seahaven-org-baseline/lib/terraform-substrate/terraform-substrate.template.yaml
Adam Moussa 3512214d14
fix(iam): allow s3:* on afi artifact bucket for provider reads
First HCP apply failed on s3:GetBucketAcl after CreateBucket; scope
remains the single artifact bucket ARN.
2026-08-05 12:56:24 -04:00

511 lines
26 KiB
YAML

AWSTemplateFormatVersion: "2010-09-09"
Description: >-
Per-account HCP Terraform deploy substrate for Sea Haven Industries:
the app.terraform.io OIDC identity provider and the shared boundary-gated
IAM guardrail policy that every per-workspace Terraform APPLY role attaches.
Per-workspace hcptf-* roles are NOT pre-provisioned — they are appended to
this template at each stack's migration time.
# PROVENANCE / DESIGN SOURCE
# Authored fresh 2026-07-30 (the mgmt Terraform POC's CLI-created provider and
# hcptf-* roles were rolled back the same day, so there is no deployed source
# to vendor). HcptfIamManagementPolicy DERIVES FROM the reviewed
# seahaven-cfn-exec-iam-management pattern in
# lib/deploy-substrate/deploy-substrate.template.yaml (boundary-gated
# CreateRole/AttachRolePolicy/PutRolePolicy/PutRolePermissionsBoundary +
# DenyBoundaryTampering / DenyBoundaryPolicyEdit / DenySelfMutation) but is
# DELIBERATELY STRICTER — it is NOT a byte-identical mirror. Do not "reconcile"
# the two by copying this file's statements back, or vice versa; the divergences
# below are load-bearing and were required by the 2026-07-30 security review
# (findings C1-C5, one confirmed critical + one high):
#
# 1. ROLE PATH SCOPING (review finding C2). The SAM copy's Resource
# `role/*` on the boundary-gated statements is justified there by SAM
# auto-generating execution roles at path / with no settable RolePath —
# a path condition would break every SAM deploy. THAT RATIONALE DOES NOT
# TRANSFER: Terraform's aws_iam_role supports `path` and `name_prefix`.
# So every role-WRITE statement here is scoped to the Terraform-owned path
# `role/tf-managed/*`. Terraform configs MUST set path = "/tf-managed/" on
# every role they create; a role created anywhere else is denied. The path
# is deliberately NOT `hcptf-*`, which would collide with the substrate's
# own hcptf-* apply/plan roles under DenySelfMutation's wildcard.
# 2. READ AND WRITE SPLIT (review findings C1, C3, C4). The SAM copy's
# IAMRoleReadAndDelete grants iam:UpdateAssumeRolePolicy / DeleteRole /
# DetachRolePolicy / DeleteRolePolicy / UpdateRole on Resource "*"
# unconditioned — a confirmed privilege-escalation primitive (repoint the
# AdministratorAccess CDK bootstrap role's trust policy, then assume it
# cross-account) that DenySelfMutation's three name patterns do not cover.
# Here those actions are split: reads stay on "*" (Terraform data sources
# need them), every destructive/mutating action is confined to
# `role/tf-managed/*`. This closes the escalation at the root instead of
# chasing it with a denylist.
# 3. PASSROLE SCOPING (review finding C5). The SAM copy passes any role to
# Lambda (its comment claims SAM-role scoping the Resource does not
# express). Here PassRole is confined to `role/tf-managed/*`, so one
# workspace cannot attach another workspace's execution role to a function
# it controls — that path performs no IAM write and would otherwise evade
# every boundary gate and Deny in this document.
# 4. DENYSELFMUTATION SCOPE. Extended beyond the substrate's own principals to
# cdk-hnb659fds-* (AdministratorAccess bootstrap roles),
# OrganizationAccountAccessRole, and seahaven-* (detective-control roles
# such as the Config recorder role, which no SCP on prod/nonprod protects
# from iam:DeleteRole). Defense in depth behind the path scoping above.
#
# The SAM copy retains its adjudicated accepted risks because SAM's constraints
# are real; this file has no such excuse. KNOWN OPEN ITEM (pre-existing, not
# introduced here): the org's ProtectPrivilegedRoles SCP encodes exactly the
# protection in (4) but is attached ONLY to the security OU — extending it to
# prod/nonprod is the durable org-level fix and is tracked separately.
#
# COUPLING: the boundary ARN referenced in the Conditions below is
# seahaven-lambda-execution-boundary, created by the seahaven-deploy-substrate
# stack in the same account. The reference is a literal !Sub string inside
# Condition values, so CloudFormation infers NO ordering edge from it —
# bin/app.ts carries an explicit addStackDependency on the same-account
# deploy-substrate stack instead. The coupling is by NAME: if the boundary
# policy is ever renamed or replaced, every Condition below (and the
# deploy-substrate copy) must change in the same piece of work. INFRA-186
# (boundary reduced to a fleet-wide floor; per-workload boundaries are
# INFRA-187) changed the boundary's CONTENT, not its ARN, so this file is
# textually untouched — but the Terraform path IS affected: the Conditions
# below FORCE every role a Terraform apply creates onto that boundary, and
# the floor carries zero data-plane permissions. A migrating stack that
# creates Lambda execution roles must widen the boundary per the WIDENING
# PATH in lib/deploy-substrate/deploy-substrate.template.yaml, deployed
# before its first apply (README migration checklist step 2).
#
# SIZE BUDGET: an attached managed policy document is capped at 6,144
# characters (whitespace excluded). The statement set below is ~2.5 KB.
# Measure before adding statements — len(json.dumps(doc,separators=(',',':')))
# on the synthesized PolicyDocument — the same wall the role INLINE limit
# (10,240 bytes) put the first deploy-substrate deploy into on 2026-07-27.
#
# PER-WORKSPACE ROLE ACCUMULATOR
# At each stack's migration, a PR appends to this template:
# - hcptf-<stack>-plan: read-only (ViewOnlyAccess-class), trust sub
# organization:seahaven:project:seahaven-<env>:workspace:<workspace>:run_phase:plan
# - hcptf-<stack>: apply role attaching HcptfIamManagementPolicy plus
# stack-scoped service statements, trust sub ...run_phase:apply
# All subs are exact StringEquals (never StringLike, never a wildcarded
# run_phase — a speculative PR plan must never hold write credentials);
# audience is aws.workload.identity. IAM role additions here are a mandatory
# GPT-4.1 cross-review + /sh-security-review trigger. See the README
# "Terraform substrate" section for the full migration checklist and the
# rollback runbook.
#
# This template is deployed via lib/terraform-substrate-stack.ts
# (cloudformation-include) as stack seahaven-terraform-substrate, once per
# member account that hosts Terraform-managed workloads (currently
# seahaven-prod 011934824531 and seahaven-dev 710827005802; NEVER mgmt —
# mgmt stays SAM until its stacks migrate out).
Parameters:
CreateOIDCProvider:
Type: String
Default: "true"
AllowedValues: ["true", "false"]
Description: >-
Set to false if the app.terraform.io OIDC provider already exists in this
account. An account holds exactly ONE provider per URL, so an unconditional
create collides. Because the provider is Retain, a FIRST-create rollback
(caused by any other resource in this stack failing) leaves the provider
behind as an orphan and the stack in ROLLBACK_COMPLETE — which cannot be
updated. Recovery: delete the stack, then either
`aws iam delete-open-id-connect-provider --open-id-connect-provider-arn
arn:aws:iam::<acct>:oidc-provider/app.terraform.io` before retrying, or
redeploy with this parameter false. Same idempotency affordance the sibling
deploy-substrate template carries for the GitHub provider.
Conditions:
ShouldCreateOIDCProvider: !Equals [!Ref CreateOIDCProvider, "true"]
# Per-workspace hcptf-* roles for afi-backup-monitor-prod (PLAT-56) must only
# exist in seahaven-prod. The same template deploys to seahaven-dev; creating
# prod-workspace trust there would leave dead credentials in the wrong account.
IsProdAccount: !Equals [!Ref "AWS::AccountId", "011934824531"]
Resources:
# ---------------------------------------------------------------------------
# HCP Terraform OIDC provider
#
# Created by default: Phase-0 checks (2026-07-30) confirmed neither prod nor
# dev has an app.terraform.io provider (the mgmt POC's copy was deleted in the
# same-day rollback and never existed in the member accounts). An account
# holds exactly ONE provider per URL — see the parameter above for the
# first-create rollback trap this condition exists to make recoverable.
# ---------------------------------------------------------------------------
TerraformCloudOIDCProvider:
Type: AWS::IAM::OIDCProvider
Condition: ShouldCreateOIDCProvider
Properties:
Url: https://app.terraform.io
ClientIdList:
# Default audience of HCP Terraform dynamic provider credentials
# (TFC_AWS_WORKLOAD_IDENTITY_AUDIENCE). Trust policies pin this via
# StringEquals on app.terraform.io:aud.
- aws.workload.identity
ThumbprintList:
# AWS ignores thumbprints for issuers signed by a trusted root CA
# (app.terraform.io qualifies) and secures trust via the CA bundle;
# the property is populated because CloudFormation requires a value.
# This is the thumbprint HashiCorp's own AWS setup documentation uses.
- 9e99a48a9960b14926bb7f3b02e22da2b0ab7280
# Every future hcptf-* role trusts this provider. Retain so deleting the
# stack can never delete the account's Terraform federation anchor out
# from under live workspaces.
DeletionPolicy: Retain
UpdateReplacePolicy: Retain
# ---------------------------------------------------------------------------
# Shared boundary-gated IAM guardrail policy (attached managed policy)
#
# Attached by every per-workspace Terraform APPLY role (hcptf-<stack>);
# NEVER by plan roles (hcptf-<stack>-plan are read-only and hold no IAM
# writes at all). Defined once here so all apply roles carry the identical
# reviewed escalation control instead of per-role copies that can drift.
#
# PRIMARY ESCALATION CONTROL (same design as INFRA-97 on the SAM side):
# every iam:CreateRole / AttachRolePolicy / PutRolePolicy is conditioned on
# the target role carrying seahaven-lambda-execution-boundary, so a role
# created by a Terraform apply can never exceed the boundary ceiling. The
# POC security review confirmed the unconditioned alternative is critical:
# iam:PutRolePolicy on Lambda exec roles + lambda:UpdateFunctionCode reads
# every secret in the account.
# ---------------------------------------------------------------------------
HcptfIamManagementPolicy:
Type: AWS::IAM::ManagedPolicy
Properties:
# Fixed name: future hcptf-* roles reference it by ARN, and a rename
# would detach-and-replace mid-update. Treat a rename as a coordinated
# migration, not an edit.
ManagedPolicyName: seahaven-hcptf-iam-management
Description: >-
Boundary-gated IAM role lifecycle for per-workspace Terraform apply
roles (hcptf-*), plus the explicit Deny backstops that keep the
permissions boundary from being detached or rewritten and the deploy
substrates' own principals from being mutated. Mirrors
seahaven-cfn-exec-iam-management; reconcile changes across both.
PolicyDocument:
Version: "2012-10-17"
Statement:
# Create role — MUST attach boundary AND land on the Terraform-owned
# path. Two independent gates: the boundary caps what the role can do,
# the path caps which roles this policy can touch at all. Terraform
# configs set path = "/tf-managed/" on every aws_iam_role.
- Sid: IAMCreateRoleWithBoundary
Effect: Allow
Action:
- iam:CreateRole
Resource:
- !Sub "arn:aws:iam::${AWS::AccountId}:role/tf-managed/*"
Condition:
StringEquals:
"iam:PermissionsBoundary": !Sub "arn:aws:iam::${AWS::AccountId}:policy/seahaven-lambda-execution-boundary"
# Attach managed policies — MUST have boundary already on role
- Sid: IAMAttachPolicyWithBoundary
Effect: Allow
Action:
- iam:AttachRolePolicy
Resource:
- !Sub "arn:aws:iam::${AWS::AccountId}:role/tf-managed/*"
Condition:
StringEquals:
"iam:PermissionsBoundary": !Sub "arn:aws:iam::${AWS::AccountId}:policy/seahaven-lambda-execution-boundary"
# Put inline policy — MUST have boundary already on role
- Sid: IAMPutRolePolicyWithBoundary
Effect: Allow
Action:
- iam:PutRolePolicy
Resource:
- !Sub "arn:aws:iam::${AWS::AccountId}:role/tf-managed/*"
Condition:
StringEquals:
"iam:PermissionsBoundary": !Sub "arn:aws:iam::${AWS::AccountId}:policy/seahaven-lambda-execution-boundary"
# Boundary management — SET only, never DELETE. For a delete, the
# iam:PermissionsBoundary condition key resolves to the boundary
# CURRENTLY on the target role, so a StringEquals grant would match
# exactly the roles the gate protects and self-defeat it (verified
# live against the mgmt SAM copy 2026-07-27). Terraform never needs
# the delete: it SETS the boundary on roles it creates, and destroy
# calls DeleteRole.
# Path-scoped as well as boundary-pinned: the condition constrains WHICH
# boundary may be set, not WHICH role receives it. Unscoped (as in the
# SAM copy) this is a one-way denial-of-service — applying the Lambda
# runtime boundary to the CDK bootstrap execution role collapses its
# permissions, and DenyBoundaryTampering below then blocks removal by
# this same principal (2026-07-30 review finding C3).
- Sid: IAMPutPermissionsBoundary
Effect: Allow
Action:
- iam:PutRolePermissionsBoundary
Resource:
- !Sub "arn:aws:iam::${AWS::AccountId}:role/tf-managed/*"
Condition:
StringEquals:
"iam:PermissionsBoundary": !Sub "arn:aws:iam::${AWS::AccountId}:policy/seahaven-lambda-execution-boundary"
# Explicit Deny backstop (AWS's NoBoundaryPolicyEdit/NoBoundaryDelete
# delegation pattern). A Deny is required, not merely omitting the
# Allow — any future Allow added to an apply role silently reopens
# the escalation otherwise.
- Sid: DenyBoundaryTampering
Effect: Deny
Action:
- iam:DeleteRolePermissionsBoundary
- iam:DeleteUserPermissionsBoundary
Resource:
- !Sub "arn:aws:iam::${AWS::AccountId}:role/*"
- !Sub "arn:aws:iam::${AWS::AccountId}:user/*"
# Whole seahaven-* policy family: this policy carries the Denies, so
# it is a higher-value target than the boundary it protects. Safe to
# scope broadly — no Terraform stack manages a seahaven-* managed
# policy, and apply roles hold no iam:CreatePolicy.
- Sid: DenyBoundaryPolicyEdit
Effect: Deny
Action:
- iam:CreatePolicyVersion
- iam:SetDefaultPolicyVersion
- iam:DeletePolicyVersion
- iam:DeletePolicy
Resource:
- !Sub "arn:aws:iam::${AWS::AccountId}:policy/seahaven-*"
# Self-protection for BOTH deploy substrates' principals. Without
# this the control is one API call from being undone —
# IAMRoleReadAndDelete below grants iam:DetachRolePolicy on
# Resource "*" unconditioned, so an apply role could detach this
# very policy from itself. Scope covers the Terraform substrate's
# own roles (hcptf-*) AND the GitHub Actions substrate's
# (github-cfn-execution-role, githubdeploy-*): a Terraform apply
# never legitimately manages any of them — hcptf-* roles are
# managed by THIS stack via the CDK bootstrap execution role, the
# GitHub-side roles by their own substrate/onboarding — so the Deny
# costs nothing operationally and closes the same
# UpdateAssumeRolePolicy-on-* repoint risk the SAM-side review
# flagged, for every substrate principal reachable from this path.
- Sid: DenySelfMutation
Effect: Deny
Action:
- iam:AttachRolePolicy
- iam:DeleteRole
- iam:DeleteRolePolicy
- iam:DeleteRolePermissionsBoundary
- iam:DetachRolePolicy
- iam:PutRolePolicy
- iam:PutRolePermissionsBoundary
- iam:UpdateAssumeRolePolicy
- iam:UpdateRole
- iam:UpdateRoleDescription
Resource:
- !Sub "arn:aws:iam::${AWS::AccountId}:role/hcptf-*"
- !Sub "arn:aws:iam::${AWS::AccountId}:role/github-cfn-execution-role"
- !Sub "arn:aws:iam::${AWS::AccountId}:role/githubdeploy-*"
# Extended beyond the SAM copy's three patterns (2026-07-30 review
# findings C1/C3/C4). cdk-hnb659fds-* carries AdministratorAccess
# and deploys this very stack; OrganizationAccountAccessRole is the
# org break-glass path; seahaven-* covers detective-control roles
# (e.g. the Config recorder role) that the protect-security-baseline
# SCP does NOT shield from iam:DeleteRole. Defense in depth — the
# path scoping on the write statements is the primary control.
- !Sub "arn:aws:iam::${AWS::AccountId}:role/cdk-hnb659fds-*"
- !Sub "arn:aws:iam::${AWS::AccountId}:role/OrganizationAccountAccessRole"
- !Sub "arn:aws:iam::${AWS::AccountId}:role/seahaven-*"
# READ-ONLY on every role/policy in the account. Terraform data sources
# and refresh legitimately need to read arbitrary roles; none of these
# actions can modify anything, so Resource "*" is safe here.
- Sid: IAMReadOnly
Effect: Allow
Action:
- iam:GetRole
- iam:GetRolePolicy
- iam:ListAttachedRolePolicies
- iam:ListRolePolicies
- iam:ListRoles
- iam:GetPolicy
- iam:GetPolicyVersion
- iam:ListPolicies
- iam:ListPolicyVersions
Resource: "*"
# DESTRUCTIVE / MUTATING role actions — confined to the Terraform-owned
# path. The SAM copy grants these on Resource "*" unconditioned, which
# the 2026-07-30 review confirmed as a critical escalation primitive
# (finding C1): iam:UpdateAssumeRolePolicy on "*" lets the principal
# repoint the AdministratorAccess CDK bootstrap role's trust policy to
# an external account and assume it. Path scoping closes that at the
# root rather than enumerating protected names.
- Sid: IAMRoleWriteScoped
Effect: Allow
Action:
- iam:DeleteRole
- iam:DeleteRolePolicy
- iam:DetachRolePolicy
- iam:TagRole
- iam:UntagRole
- iam:UpdateRole
- iam:UpdateRoleDescription
- iam:UpdateAssumeRolePolicy
Resource:
- !Sub "arn:aws:iam::${AWS::AccountId}:role/tf-managed/*"
# PassRole — Terraform passes the execution roles it created (which are
# on the tf-managed path, boundary-gated above) to the Lambda service.
# Path-scoped, not role/*: unscoped, one workspace's apply role could
# attach ANOTHER workspace's or a SAM stack's execution role to a
# function it controls and run arbitrary code as that identity — a path
# that performs no IAM write and so evades every boundary gate and Deny
# in this document (2026-07-30 review finding C5). Other target services
# (scheduler, apigateway, ...) are NOT granted: a stack that needs one
# adds a scoped PassRole statement to its own apply role at migration.
- Sid: IAMPassRole
Effect: Allow
Action:
- iam:PassRole
Resource:
- !Sub "arn:aws:iam::${AWS::AccountId}:role/tf-managed/*"
Condition:
StringEquals:
"iam:PassedToService": "lambda.amazonaws.com"
# ---------------------------------------------------------------------------
# Per-workspace roles: afi-backup-monitor-prod (PLAT-56)
#
# First HCP Terraform workload. Trust subs are exact StringEquals on
# organization/project/workspace/run_phase — never StringLike, never a
# wildcarded run_phase. Plan role: ViewOnlyAccess only (never ReadOnlyAccess,
# which grants secretsmanager:GetSecretValue). Apply role: attaches the
# shared guardrail plus stack-scoped Lambda / layer / EventBridge / Logs.
# Prod-only (IsProdAccount): this template also deploys to seahaven-dev.
# ---------------------------------------------------------------------------
HcptfAfiBackupMonitorPlanRole:
Type: AWS::IAM::Role
Condition: IsProdAccount
Properties:
RoleName: hcptf-afi-backup-monitor-plan
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Federated: !Sub "arn:aws:iam::${AWS::AccountId}:oidc-provider/app.terraform.io"
Action: sts:AssumeRoleWithWebIdentity
Condition:
StringEquals:
"app.terraform.io:aud": aws.workload.identity
"app.terraform.io:sub": organization:seahaven:project:seahaven-prod:workspace:afi-backup-monitor-prod:run_phase:plan
ManagedPolicyArns:
- arn:aws:iam::aws:policy/job-function/ViewOnlyAccess
HcptfAfiBackupMonitorApplyRole:
Type: AWS::IAM::Role
Condition: IsProdAccount
Properties:
RoleName: hcptf-afi-backup-monitor
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Federated: !Sub "arn:aws:iam::${AWS::AccountId}:oidc-provider/app.terraform.io"
Action: sts:AssumeRoleWithWebIdentity
Condition:
StringEquals:
"app.terraform.io:aud": aws.workload.identity
"app.terraform.io:sub": organization:seahaven:project:seahaven-prod:workspace:afi-backup-monitor-prod:run_phase:apply
ManagedPolicyArns:
- !Ref HcptfIamManagementPolicy
Policies:
- PolicyName: afi-backup-monitor-services
PolicyDocument:
Version: "2012-10-17"
Statement:
- Sid: LambdaFunctions
Effect: Allow
Action:
- lambda:CreateFunction
- lambda:DeleteFunction
- lambda:GetFunction
- lambda:GetFunctionConfiguration
- lambda:UpdateFunctionCode
- lambda:UpdateFunctionConfiguration
- lambda:ListVersionsByFunction
- lambda:PublishVersion
- lambda:TagResource
- lambda:UntagResource
- lambda:ListTags
- lambda:AddPermission
- lambda:RemovePermission
- lambda:GetPolicy
- lambda:InvokeFunction
Resource:
- !Sub "arn:aws:lambda:us-east-1:${AWS::AccountId}:function:afi-*"
- Sid: LambdaLayers
Effect: Allow
Action:
- lambda:PublishLayerVersion
- lambda:DeleteLayerVersion
- lambda:GetLayerVersion
- lambda:ListLayerVersions
Resource:
- !Sub "arn:aws:lambda:us-east-1:${AWS::AccountId}:layer:afi-shared*"
- Sid: LambdaList
Effect: Allow
Action:
- lambda:ListFunctions
- lambda:ListLayers
- lambda:GetAccountSettings
Resource: "*"
- Sid: EventBridgeRules
Effect: Allow
Action:
- events:PutRule
- events:DeleteRule
- events:DescribeRule
- events:EnableRule
- events:DisableRule
- events:PutTargets
- events:RemoveTargets
- events:ListTargetsByRule
- events:TagResource
- events:UntagResource
- events:ListTagsForResource
Resource:
- !Sub "arn:aws:events:us-east-1:${AWS::AccountId}:rule/afi-*"
- Sid: CloudWatchLogs
Effect: Allow
Action:
- logs:CreateLogGroup
- logs:DeleteLogGroup
- logs:PutRetentionPolicy
- logs:DeleteRetentionPolicy
- logs:TagResource
- logs:UntagResource
- logs:ListTagsForResource
Resource:
- !Sub "arn:aws:logs:us-east-1:${AWS::AccountId}:log-group:/aws/lambda/afi-*"
# logs:DescribeLogGroups is a collection action — AWS authorises it
# against "*" only. Scoping it to a log-group ARN is a silent no-op
# grant (same pitfall documented on LambdaExecutionBoundary).
- Sid: CloudWatchLogsDescribe
Effect: Allow
Action:
- logs:DescribeLogGroups
Resource: "*"
# Artifact bucket for HCP plan/apply split: zip bytes travel in the
# plan via aws_s3_object content_base64 (local archive_file paths
# from the plan worker are not on the apply worker). Action set is
# s3:* on this bucket only — the AWS provider reads many GetBucket*
# attributes (e.g. GetBucketAcl) after CreateBucket; enumerating
# them lags provider upgrades (PLAT-56 first-apply miss).
- Sid: LambdaArtifactsBucket
Effect: Allow
Action:
- s3:*
Resource:
- !Sub "arn:aws:s3:::afi-backup-monitor-artifacts-${AWS::AccountId}"
- !Sub "arn:aws:s3:::afi-backup-monitor-artifacts-${AWS::AccountId}/*"