# identity-provider-signals / okta / t0 "Quick start"
#
# Five alerts for the moves that turn one stolen Okta session into the whole
# organisation: an admin role granted, a new way to sign in added, a user's
# MFA removed, an Okta support session, and the System Log stream changed.
# A sixth alarm fires when no Okta events have arrived for an hour.
#
# Okta streams every System Log event to an Amazon EventBridge partner event
# source in your AWS account. This file creates the stream, accepts it as an
# event bus, keeps every event in a CloudWatch log group, and emails on the
# five patterns.
#
# Before you start:
#   Sign in to Okta as a super admin and make an API token
#   (Security > API > Tokens). Okta allows two log streams per org.
#   export OKTA_API_TOKEN=<the token>
#   AWS credentials for the account that receives the events.
#
# Change the four values below, then:
#   terraform init && terraform apply
#   Confirm the subscription in the email SNS sends.
#   In the Okta Admin Console, Reports > Log Streaming, check the stream is
#   Active. Okta deactivates a stream it cannot deliver to.
#
# Verify: grant a test user the Read-Only Administrator role, then remove it.
# The admin-granted email arrives within a few minutes.

locals {
  okta_org_name = "your-org"                    # change me: the acme in acme.okta.com
  okta_base_url = "okta.com"                    # change me if your org is on oktapreview.com or okta-emea.com
  aws_region    = "us-east-1"                   # change me: one of the 17 regions Okta streams to
  alert_email   = "security-alerts@example.com" # change me

  # Okta names the event source after the org and the name given here. It
  # cannot change after creation; a new name means a new stream and bus.
  # The Okta provider accepts letters, digits, dots, and underscores.
  stream_name = "okta_system_log"
  source      = "aws.partner/okta.com/${local.okta_org_name}/${local.stream_name}"

  # System Log event types, from Okta's event type catalog.
  detections = {
    admin-granted = {
      events = [
        "user.account.privilege.grant", "group.privilege.grant", "app.oauth2.client.privilege.grant",
        "iam.resourceset.bindings.add", "iam.role.create", "iam.role.permissions.add",
        "system.api_token.create", "system.api_token.enable",
      ]
      doc = "An admin role was granted to a user, group, or app, a custom role was made or widened, or an API token was made."
    }
    # Each of these changes who can sign in, or how. A new identity provider
    # lets its owner sign in as anyone it routes to Okta.
    sign-in-changed = {
      events = [
        "system.idp.lifecycle.create", "system.idp.lifecycle.update", "system.idp.lifecycle.activate", "system.idp.key.create",
        "policy.lifecycle.update", "policy.lifecycle.delete", "policy.lifecycle.deactivate",
        "policy.rule.update", "policy.rule.delete", "policy.rule.deactivate",
        "application.policy.sign_on.update", "application.policy.sign_on.rule.delete",
        "security.authenticator.lifecycle.update", "security.authenticator.lifecycle.deactivate",
        "system.mfa.factor.deactivate",
      ]
      doc = "An identity provider, sign-on policy, policy rule, or authenticator was added, changed, or switched off."
    }
    # The help desk call that ends with "I lost my phone".
    mfa-removed = {
      events = ["user.mfa.factor.reset_all", "user.mfa.factor.deactivate", "user.mfa.attempt_bypass"]
      doc    = "A user's MFA factors were reset or removed, or someone tried to bypass a factor."
    }
    impersonation = {
      events = ["user.session.impersonation.grant", "user.session.impersonation.initiate"]
      doc    = "Okta support was granted access to the org, or started a session as a user."
    }
    # A stream Okta switches off cannot report itself, so the silence alarm
    # below is what catches that. This catches the changes Okta can still send.
    logging-weakened = {
      events = [
        "system.log_stream.lifecycle.update", "system.log_stream.lifecycle.deactivate", "system.log_stream.lifecycle.delete",
        "event_hook.deactivated", "event_hook.deleted",
      ]
      doc = "A log stream or event hook was changed, deactivated, or deleted."
    }
  }
}

terraform {
  required_version = ">= 1.6"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 6.0"
    }
    okta = {
      source  = "okta/okta"
      version = "~> 6.0"
    }
  }
}

provider "aws" {
  region = local.aws_region
  default_tags {
    tags = {
      owner               = "security-engineering"
      environment         = "prod"
      data_classification = "confidential"
      managed_by          = "terraform"
    }
  }
}

# The API token comes from OKTA_API_TOKEN.
provider "okta" {
  org_name = local.okta_org_name
  base_url = local.okta_base_url
}

data "aws_caller_identity" "current" {}

resource "okta_log_stream" "eventbridge" {
  name   = "AWS EventBridge ${local.aws_region}"
  type   = "aws_eventbridge"
  status = "ACTIVE"
  settings {
    account_id        = data.aws_caller_identity.current.account_id
    region            = local.aws_region
    event_source_name = local.stream_name
  }
}

# Accepting the partner event source. Events Okta sends before this exists
# are dropped.
resource "aws_cloudwatch_event_bus" "okta" {
  name              = local.source
  event_source_name = local.source
  depends_on        = [okta_log_stream.eventbridge]
}

# Every event, kept for investigations and for the silence alarm.
resource "aws_cloudwatch_log_group" "okta" {
  name              = "/aws/events/okta-system-log"
  retention_in_days = 365
}

data "aws_iam_policy_document" "events_write_logs" {
  statement {
    actions   = ["logs:CreateLogStream", "logs:PutLogEvents"]
    resources = ["${aws_cloudwatch_log_group.okta.arn}:*"]
    principals {
      type        = "Service"
      identifiers = ["events.amazonaws.com", "delivery.logs.amazonaws.com"]
    }
  }
}

resource "aws_cloudwatch_log_resource_policy" "events_write_logs" {
  policy_name     = "okta-system-log-from-eventbridge"
  policy_document = data.aws_iam_policy_document.events_write_logs.json
}

resource "aws_cloudwatch_event_rule" "archive" {
  name           = "okta-archive"
  description    = "Every Okta System Log event, into the log group."
  event_bus_name = aws_cloudwatch_event_bus.okta.name
  state          = "ENABLED"
  event_pattern  = jsonencode({ source = [local.source] })
}

resource "aws_cloudwatch_event_target" "archive" {
  rule           = aws_cloudwatch_event_rule.archive.name
  event_bus_name = aws_cloudwatch_event_bus.okta.name
  arn            = aws_cloudwatch_log_group.okta.arn
  depends_on     = [aws_cloudwatch_log_resource_policy.events_write_logs]
}

resource "aws_sns_topic" "alerts" {
  name = "okta-signals"
}

data "aws_iam_policy_document" "events_publish" {
  statement {
    actions   = ["sns:Publish"]
    resources = [aws_sns_topic.alerts.arn]
    principals {
      type        = "Service"
      identifiers = ["events.amazonaws.com"]
    }
    condition {
      test     = "ArnLike"
      variable = "aws:SourceArn"
      values   = [for r in aws_cloudwatch_event_rule.detection : r.arn]
    }
  }
  # The silence alarm publishes as CloudWatch.
  statement {
    actions   = ["sns:Publish"]
    resources = [aws_sns_topic.alerts.arn]
    principals {
      type        = "Service"
      identifiers = ["cloudwatch.amazonaws.com"]
    }
    condition {
      test     = "StringEquals"
      variable = "aws:SourceAccount"
      values   = [data.aws_caller_identity.current.account_id]
    }
  }
}

resource "aws_sns_topic_policy" "alerts" {
  arn    = aws_sns_topic.alerts.arn
  policy = data.aws_iam_policy_document.events_publish.json
}

resource "aws_sns_topic_subscription" "email" {
  topic_arn = aws_sns_topic.alerts.arn
  protocol  = "email"
  endpoint  = local.alert_email
}

resource "aws_cloudwatch_event_rule" "detection" {
  for_each       = local.detections
  name           = "okta-${each.key}"
  description    = each.value.doc
  event_bus_name = aws_cloudwatch_event_bus.okta.name
  state          = "ENABLED"
  event_pattern = jsonencode({
    source = [local.source]
    detail = { eventType = each.value.events }
  })
}

# The email names the event, who did it, from where, and to whom.
resource "aws_cloudwatch_event_target" "detection" {
  for_each       = local.detections
  rule           = aws_cloudwatch_event_rule.detection[each.key].name
  event_bus_name = aws_cloudwatch_event_bus.okta.name
  arn            = aws_sns_topic.alerts.arn
  input_transformer {
    input_paths = {
      type    = "$.detail.eventType"
      message = "$.detail.displayMessage"
      actor   = "$.detail.actor.alternateId"
      ip      = "$.detail.client.ipAddress"
      target  = "$.detail.target[0].alternateId"
      result  = "$.detail.outcome.result"
      time    = "$.detail.published"
    }
    input_template = "\"Okta ${each.key}: <message> (<type>, <result>) by <actor> from <ip>, on <target>, at <time>. ${each.value.doc}\""
  }
}

# Okta writes sign-ins all day, so an hour with nothing means the stream or
# the bus has stopped.
resource "aws_cloudwatch_metric_alarm" "silence" {
  alarm_name          = "okta-signals-silent"
  alarm_description   = "No Okta System Log events reached ${aws_cloudwatch_log_group.okta.name} for an hour. Check the stream's status in the Okta Admin Console, Reports > Log Streaming, and reactivate it."
  namespace           = "AWS/Logs"
  metric_name         = "IncomingLogEvents"
  dimensions          = { LogGroupName = aws_cloudwatch_log_group.okta.name }
  statistic           = "Sum"
  period              = 3600
  evaluation_periods  = 1
  threshold           = 1
  comparison_operator = "LessThanThreshold"
  treat_missing_data  = "breaching"
  alarm_actions       = [aws_sns_topic.alerts.arn]
}

output "verify" {
  description = "The drill."
  value       = <<-EOT
    In Okta, grant a test user the Read-Only Administrator role, then remove it.
    The okta-admin-granted email arrives within a few minutes.
    Every event is also in the log group:
      aws logs tail ${aws_cloudwatch_log_group.okta.name} --since 15m --region ${local.aws_region}
    The silence alarm should read OK once events flow:
      aws cloudwatch describe-alarms --alarm-names okta-signals-silent --query 'MetricAlarms[].StateValue' --region ${local.aws_region}
  EOT
}
