terraform {
  required_version = ">= 1.7.0, < 2.0.0"
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "6.20.0"
    }
  }
}

provider "aws" {
  region              = "ca-central-1"
  allowed_account_ids = [var.account_id]
}

variable "account_id" {
  type        = string
  description = "Disposable account; never a production account. No default."
  validation {
    condition     = can(regex("^[0-9]{12}$", var.account_id))
    error_message = "Supply the dedicated twelve-digit lab account ID."
  }
}

variable "artifact_bucket" {
  type        = string
  description = "Existing isolated artifact bucket; public access blocked, versioned, centrally audited."
  validation {
    condition     = can(regex("^[a-z0-9][a-z0-9-]{1,61}[a-z0-9]$", var.artifact_bucket))
    error_message = "Supply a plain bucket name without ARN, wildcards, or path."
  }
}

variable "subjects" {
  type        = map(string)
  description = "Exact observed GitHub subjects, including immutable IDs if applicable."
  validation {
    condition = (toset(keys(var.subjects)) == toset(["staging", "production"]) &&
      alltrue([for env, subject in var.subjects :
    can(regex("^repo:[^*?<> ]+/[^*?<> ]+:environment:${env}$", subject))]))
    error_message = "Use two exact subjects ending in environment:staging and environment:production."
  }
}

locals {
  provider_arn = "arn:aws:iam::${var.account_id}:oidc-provider/token.actions.githubusercontent.com"
  permissions = { for env in keys(var.subjects) : env => {
    Version = "2012-10-17"
    Statement = [{
      Sid      = "OnlyEnvironmentArtifacts"
      Effect   = "Allow"
      Action   = ["s3:GetObject", "s3:PutObject"]
      Resource = "arn:aws:s3:::${var.artifact_bucket}/${env}/*"
    }]
  } }
  boundaries = { for env in keys(var.subjects) : env => {
    Version = "2012-10-17"
    Statement = concat(local.permissions[env].Statement, [
      {
        Sid       = "DenyEveryOtherAPI"
        Effect    = "Deny"
        NotAction = ["s3:GetObject", "s3:PutObject"]
        Resource  = "*"
      },
      {
        Sid         = "DenyOtherResources"
        Effect      = "Deny"
        Action      = "s3:*"
        NotResource = "arn:aws:s3:::${var.artifact_bucket}/${env}/*"
      }
    ])
  } }
  trusts = { for env, subject in var.subjects : env => {
    Version = "2012-10-17"
    Statement = [{
      Effect    = "Allow"
      Principal = { Federated = local.provider_arn }
      Action    = "sts:AssumeRoleWithWebIdentity"
      Condition = { StringEquals = {
        "token.actions.githubusercontent.com:aud" = "sts.amazonaws.com"
        "token.actions.githubusercontent.com:sub" = subject
      } }
    }]
  } }
}

# Bootstrap administrator owns these policies; the resulting runtime roles cannot
# modify IAM, federation, their boundary, CloudTrail, KMS, or workflow repositories.
resource "aws_iam_policy" "boundary" {
  for_each = var.subjects
  name     = "research-${each.key}-boundary"
  policy   = jsonencode(local.boundaries[each.key])
}

resource "aws_iam_role" "deploy" {
  for_each             = var.subjects
  name                 = "research-${each.key}-deploy"
  max_session_duration = 3600
  assume_role_policy   = jsonencode(local.trusts[each.key])
  permissions_boundary = aws_iam_policy.boundary[each.key].arn
}

resource "aws_iam_role_policy" "artifacts" {
  for_each = var.subjects
  name     = "environment-artifacts"
  role     = aws_iam_role.deploy[each.key].id
  policy   = jsonencode(local.permissions[each.key])
}

output "policy_contract" {
  description = "Pure policy documents consumed by offline behavioral tests. Not an STS result."
  value = { for env in keys(var.subjects) : env => {
    trust = local.trusts[env], identity = local.permissions[env], boundary = local.boundaries[env]
  } }
}

output "audit_assumptions" {
  value = [
    "An independently administered organization trail records management events including global IAM/STS.",
    "S3 object data events for the artifact prefixes must be selected separately.",
    "Archive and alert routing are outside both deployment roles; test delivery and freshness.",
    "The existing GitHub provider, bucket, KMS policy, SCPs, and resource policies require separate review."
  ]
}
