# guardrail-baseline / aws / t0 "Quick start"
#
# One service control policy with three rules that should never need breaking:
# no account leaves the organisation, nobody switches off audit logging or threat
# detection, and nobody uses an account's root user.
#
# Run it in the organisation's management account. Attach it to a test OU
# first: a policy on the whole organisation applies to every member account at
# once.
#
# Change the target below, then:
#   terraform init && terraform apply
#
# Verify, from a member account under that target:
#   aws cloudtrail stop-logging --name <any trail>
#   Expect: AccessDenied ... with an explicit deny in a service control policy.

locals {
  target_id = "ou-xxxx-xxxxxxxx" # change me: an OU ID, or a 12-digit account ID
}

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

provider "aws" {}

# A service control policy grants nothing. It sets the most any principal in
# the account may do, and a deny here wins over any allow in the account.
data "aws_iam_policy_document" "guardrails" {
  statement {
    sid       = "DenyLeavingOrganization"
    effect    = "Deny"
    actions   = ["organizations:LeaveOrganization"]
    resources = ["*"]
  }

  statement {
    sid    = "DenyAuditTampering"
    effect = "Deny"
    actions = [
      "cloudtrail:StopLogging", "cloudtrail:DeleteTrail", "cloudtrail:UpdateTrail", "cloudtrail:PutEventSelectors",
      "config:StopConfigurationRecorder", "config:DeleteConfigurationRecorder", "config:DeleteDeliveryChannel",
      "guardduty:DeleteDetector", "guardduty:DisassociateFromAdministratorAccount",
    ]
    resources = ["*"]
  }

  statement {
    sid       = "DenyRootUser"
    effect    = "Deny"
    actions   = ["*"]
    resources = ["*"]
    condition {
      test     = "StringLike"
      variable = "aws:PrincipalArn"
      values   = ["arn:aws:iam::*:root"]
    }
  }
}

resource "aws_organizations_policy" "guardrails" {
  name        = "guardrail-baseline"
  description = "No leaving the organisation, no audit tampering, no root user."
  type        = "SERVICE_CONTROL_POLICY"
  content     = data.aws_iam_policy_document.guardrails.json
}

resource "aws_organizations_policy_attachment" "guardrails" {
  policy_id = aws_organizations_policy.guardrails.id
  target_id = local.target_id
}

output "policy_id" {
  description = "The policy, for attaching to more targets later."
  value       = aws_organizations_policy.guardrails.id
}
