# identity-provider-signals / workspace / t0 "Quick start"
#
# Five alerts for the moves that turn one stolen Google Workspace account
# into the domain: an admin role or domain-wide API access granted, a change
# to how people sign in, 2-Step Verification turned off, a warning Google
# raised on an account, and mail forwarded outside the domain. A sixth alert
# fires when no Workspace sign-in events have arrived for an hour.
#
# Workspace writes its Admin, Login, Groups, and OAuth audit logs into Cloud
# Logging at the organisation level once sharing is turned on. An
# organisation sink copies them into a log bucket in a security project,
# where log-based metrics count the matches.
#
# Before you start, a Workspace super admin turns sharing on, once, in the
# Admin console: Account > Account settings > Legal and compliance > Sharing
# options > Enabled. Google documents this switch only in the Admin
# console, so Terraform cannot turn it on.
#
# Change the three values below, then:
#   gcloud auth application-default login
#   terraform init && terraform apply
#
# Verify: give a test user the Help Desk Admin role in the Admin console,
# then remove it. The alert email arrives within a few minutes.

locals {
  org_id           = "123456789012"                # change me: gcloud organizations list
  security_project = "your-security-project"       # change me: where the bucket and alerts live
  alert_email      = "security-alerts@example.com" # change me

  admin = "google.admin.AdminService"
  login = "google.login.LoginService"

  # Method names as Cloud Logging records them for Workspace audit entries.
  detections = {
    # Domain-wide delegation lets an app act as any user in the domain.
    admin-granted = {
      filter = "protoPayload.methodName=(\"${local.admin}.assignRole\" OR \"${local.admin}.grantAdminPrivilege\" OR \"${local.admin}.grantDelegatedAdminPrivileges\" OR \"${local.admin}.authorizeApiClientAccess\")"
      doc    = "An admin role or admin privileges were granted, or an API client was given domain-wide access."
    }
    sign-in-changed = {
      filter = "protoPayload.methodName=(\"${local.admin}.enforceStrongAuthentication\" OR \"${local.admin}.allowStrongAuthentication\" OR \"${local.admin}.changeAllowedTwoStepVerificationMethods\" OR \"${local.admin}.toggleSsoEnabled\" OR \"${local.admin}.changeSsoSettings\")"
      doc    = "2-Step Verification enforcement, the allowed 2SV methods, or single sign-on settings changed."
    }
    two-step-off = {
      filter = "protoPayload.methodName=(\"${local.admin}.turnOff2StepVerification\" OR \"${local.login}.2svDisable\")"
      doc    = "2-Step Verification was turned off for a user, by an admin or by the user."
    }
    account-warning = {
      filter = "protoPayload.methodName=(\"${local.login}.suspiciousLogin\" OR \"${local.login}.suspiciousProgrammaticLogin\" OR \"${local.login}.govAttackWarning\" OR \"${local.login}.accountDisabledHijacked\" OR \"${local.login}.accountDisabledPasswordLeak\")"
      doc    = "Google flagged a sign-in as suspicious, warned of a government-backed attack, or disabled an account as hijacked or leaked."
    }
    mail-forwarded-out = {
      filter = "protoPayload.metadata.event.eventName=\"email_forwarding_out_of_domain\""
      doc    = "A user turned on forwarding of their mail to an address outside the domain."
    }
  }

  # Every entry from the Workspace services, so the bucket also serves
  # investigations and the silence alert.
  workspace_logs = "logName=(\"organizations/${local.org_id}/logs/cloudaudit.googleapis.com%2Factivity\" OR \"organizations/${local.org_id}/logs/cloudaudit.googleapis.com%2Fdata_access\") AND protoPayload.serviceName=(\"admin.googleapis.com\" OR \"login.googleapis.com\" OR \"cloudidentity.googleapis.com\" OR \"oauth2.googleapis.com\")"
}

terraform {
  required_version = ">= 1.6"
  required_providers {
    google = {
      source  = "hashicorp/google"
      version = "~> 8.0"
    }
  }
}

provider "google" {
  project = local.security_project
}

resource "google_logging_project_bucket_config" "workspace" {
  project        = local.security_project
  location       = "global"
  bucket_id      = "workspace-signals"
  retention_days = 400
}

# Workspace entries belong to the organisation itself, so the sink does not
# need its children's logs.
resource "google_logging_organization_sink" "workspace" {
  org_id           = local.org_id
  name             = "workspace-signals"
  destination      = "logging.googleapis.com/${google_logging_project_bucket_config.workspace.id}"
  filter           = local.workspace_logs
  include_children = false
}

resource "google_project_iam_member" "sink_writes" {
  project = local.security_project
  role    = "roles/logging.bucketWriter"
  member  = google_logging_organization_sink.workspace.writer_identity
}

resource "google_logging_metric" "detection" {
  for_each    = local.detections
  project     = local.security_project
  name        = "workspace-${each.key}"
  bucket_name = google_logging_project_bucket_config.workspace.id
  filter      = each.value.filter
  metric_descriptor {
    metric_kind = "DELTA"
    value_type  = "INT64"
  }
}

resource "google_logging_metric" "sign_ins" {
  project     = local.security_project
  name        = "workspace-sign-in-events"
  bucket_name = google_logging_project_bucket_config.workspace.id
  filter      = "protoPayload.serviceName=\"login.googleapis.com\""
  metric_descriptor {
    metric_kind = "DELTA"
    value_type  = "INT64"
  }
}

resource "google_monitoring_notification_channel" "email" {
  project      = local.security_project
  display_name = "Workspace signals"
  type         = "email"
  labels = {
    email_address = local.alert_email
  }
}

resource "google_monitoring_alert_policy" "detection" {
  for_each              = local.detections
  project               = local.security_project
  display_name          = "Workspace: ${each.key}"
  combiner              = "OR"
  notification_channels = [google_monitoring_notification_channel.email.id]
  conditions {
    display_name = each.value.doc
    condition_threshold {
      filter          = "metric.type=\"logging.googleapis.com/user/${google_logging_metric.detection[each.key].name}\""
      comparison      = "COMPARISON_GT"
      threshold_value = 0
      duration        = "0s"
      aggregations {
        alignment_period     = "60s"
        per_series_aligner   = "ALIGN_SUM"
        cross_series_reducer = "REDUCE_SUM"
      }
    }
  }
  documentation {
    content = "${each.value.doc} In Logs Explorer in ${local.security_project}, scope by storage to the workspace-signals bucket and search ${each.value.filter} to see who, from where, and on whom."
  }
}

# Workspace records every sign-in, so an hour with none means sharing was
# turned off or the sink stopped.
resource "google_monitoring_alert_policy" "silence" {
  project               = local.security_project
  display_name          = "Workspace: signals silent"
  combiner              = "OR"
  notification_channels = [google_monitoring_notification_channel.email.id]
  conditions {
    display_name = "No Workspace sign-in events for an hour"
    condition_absent {
      filter   = "metric.type=\"logging.googleapis.com/user/${google_logging_metric.sign_ins.name}\""
      duration = "3600s"
      aggregations {
        alignment_period     = "300s"
        per_series_aligner   = "ALIGN_SUM"
        cross_series_reducer = "REDUCE_SUM"
      }
    }
  }
  documentation {
    content = "No Workspace sign-in events reached the workspace-signals bucket for an hour. Check that sharing with Google Cloud is still on in the Admin console, and that the workspace-signals organisation sink exists."
  }
}

output "verify" {
  description = "The drill."
  value       = <<-EOT
    Give a test user the Help Desk Admin role in the Admin console, then remove it.
    The Workspace: admin-granted email arrives within a few minutes.
    Entries are arriving when this lists some:
      gcloud logging read 'protoPayload.serviceName="login.googleapis.com"' --bucket=workspace-signals --location=global --view=_AllLogs --project=${local.security_project} --freshness=1h --limit=5
  EOT
}
