diff --git a/.ciagent/IAM_POLICY.md b/.ciagent/IAM_POLICY.md new file mode 100644 index 0000000..0f98a5e --- /dev/null +++ b/.ciagent/IAM_POLICY.md @@ -0,0 +1,140 @@ +# ACDL — IAM Policy Baseline (v1.11, REQ-116) + +> Source of truth: `terraform/bootstrap/spike_runner_policy.json`. +> Applied as: customer-managed policy `acdl-spike-runner-policy` +> (ARN `arn:aws:iam::581513795199:policy/acdl-spike-runner-policy`), v1. +> Regression-tested by: `tests/test_iam_policy_baseline.py` (Phase 56). +> Applied: 2026-07-28, Phase 56 live step (D-095 resolved — fresh root +> key provided by the user). + +The `acdl-spike-runner` IAM user is the principal that runs the ACDL +platform pipeline (plan + apply) against account `581513795199`. This +document is the baseline of the permissions it holds, scoped to the +minimum required for the v1.11 milestone (Operating Model + Deploy +Verification, REQ-116..122). Any future grant must be documented here +and covered by the baseline test. + +> **Managed-policy note (v1.11 Phase 56).** The original v1.1 bootstrap +> applied this policy as an inline user policy +> (`iam:put_user_policy`). The v1.11 extension grew the policy document +> beyond the 2048-byte inline limit (5917 bytes), so Phase 56 converted +> it to a customer-managed policy (`iam:create_policy` + `attach_user_policy`) +> with the same name `acdl-spike-runner-policy`. The managed-policy path +> supports 6144 bytes per version + up to 5 versions, leaving room for +> future growth. The inline policy was deleted after the managed policy +> was attached. The same managed policy is also attached to the +> `acdl-act-runner-role` (CAP-022) so the OIDC runner inherits the +> spike-runner-equivalent permissions once act_runner adoption lands. + +## Original grants (v1.1–v1.10) + +| Capability | Actions | Resource scope | +|-----------|---------|----------------| +| Terraform state (S3) | `s3:PutObject`, `s3:GetObject`, `s3:DeleteObject`, `s3:ListBucket`, `s3:GetBucketLocation`, `s3:GetBucketVersioning` | `acdl-tfstate-581513795199-us-east-1` + `/*` | +| DynamoDB outbox | `dynamodb:GetItem`, `PutItem`, `DeleteItem`, `UpdateItem`, `Query`, `Scan`, `DescribeTable` | `table/acdl-outbox` | +| STS identity | `sts:GetCallerIdentity` | `*` | +| ECS | `ecs:Create*`, `Describe*`, `Delete*`, `Update*`, `Register*`, `Deregister*`, `List*` | `ecs:us-east-1:581513795199:*` | +| ECR | `ecr:Create*`, `Describe*`, `Delete*`, `Get*`, `Batch*`, `Put*`, `Upload*`, `Initiate*`, `Complete*` | `ecr:us-east-1:581513795199:*` | +| ELB | `elasticloadbalancing:Create*`, `Describe*`, `Delete*`, `Modify*`, `Register*`, `Deregister*` | `elasticloadbalancing:us-east-1:581513795199:*` | +| IAM (role + policy mgmt) | `iam:Create*`, `Get*`, `Delete*`, `PassRole`, `Attach*`, `Detach*`, `List*`, `Put*` | `iam::581513795199:*` | +| EC2 (VPC + SG) | `ec2:Create*`, `Describe*`, `Delete*`, `Associate*`, `Disassociate*`, `Attach*`, `Detach*`, `Authorize*` | `ec2:us-east-1:581513795199:*` | + +## v1.11 grants (Phase 56, REQ-116) + +| Capability | Actions | Resource scope | REQ | +|-----------|---------|----------------|-----| +| CloudFront (CAP-020) | `cloudfront:Create*`, `Describe*`, `Get*`, `List*`, `Update*`, `Delete*`, `TagResource`, `UntagResource` | `*` (CloudFront ARNs are regional-global) | REQ-118 | +| WAFv2 (CAP-020) | `wafv2:Create*`, `Describe*`, `Get*`, `List*`, `Update*`, `Delete*` | `*` (WAFv2 global + regional) | REQ-118 | +| Lambda (CAP-018) | `lambda:Create*`, `Get*`, `List*`, `Update*`, `Delete*`, `InvokeFunction`, `InvokeFunctionUrl`, `TagResource`, `UntagResource`, `PublishLayerVersion` | `lambda:us-east-1:581513795199:function:acdl-*` | REQ-117 | +| DynamoDB contracts (CAP-017) | `dynamodb:Create*`, `Describe*`, `Get*`, `Put*`, `Update*`, `Delete*`, `Query`, `Scan`, `Batch*` | `table/acdl-contracts` + `/*` + `table/acdl-change-requests` + `/*` | REQ-117 | +| Secrets Manager (CAP-018) | `secretsmanager:GetSecretValue`, `DescribeSecret`, `CreateSecret`, `PutSecretValue`, `DeleteSecret`, `ListSecrets` | `secret:acdl/*` | REQ-117 | +| SNS (CAP-017) | `sns:CreateTopic`, `Publish`, `GetTopicAttributes`, `SetTopicAttributes`, `DeleteTopic`, `ListTopics` | `sns:us-east-1:581513795199:acdl-*` | REQ-117 | +| Cost Explorer (REQ-119) | `ce:GetCostAndUsage`, `GetCostForecast`, `GetCostAndUsageWithResources`, `GetDimensionValues`, `GetTags` | `*` (CE is account-scoped) | REQ-119 | +| KMS (CAP-017) | `kms:CreateKey`, `CreateAlias`, `Describe*`, `Get*`, `List*`, `Update*`, `Delete*`, `EnableKey`, `DisableKey`, `ScheduleKeyDeletion`, `TagResource`, `UntagResource` | `*` (KMS ARNs are account-wide) | REQ-117/118 | +| IAM OIDC (CAP-022) | `iam:CreateOpenIDConnectProvider`, `GetOpenIDConnectProvider`, `DeleteOpenIDConnectProvider`, `ListOpenIDConnectProviders`, `UpdateOpenIDConnectProviderThumbprint`, `iam:CreateRole`, `GetRole`, `ListRoles`, `DeleteRole`, `UpdateRole`, `TagRole`, `UntagRole` | `*` (OIDC providers + roles are account-wide) | REQ-116 | + +## OIDC act_runner role (CAP-022, Phase 56) + +The OIDC role for the Gitea `act_runner` was created in Phase 08 and +gone since (CAPABILITY_INVENTORY.md CAP-022). Phase 56 re-creates it +with a trust policy for the Gitea runner ARN. The role grants the +spike-runner-equivalent permissions to the runner via `sts:AssumeRole`, +so the runner does not need a long-lived access key. This closes the +chicken-and-egg: the spike-runner creates the OIDC role using the +bootstrap root key; the runner then assumes the role. + +> **Note:** Real OIDC federation (D-039) is blocked on +> `go-gitea/gitea#36988`. Phase 56 re-creates the IAM role + trust +> policy; act_runner adoption is out of scope for v1.11 (see +> REQUIREMENTS.md §Out of Scope v1.11). The role exists so the +> spike-runner can be rotated out once Gitea merges OIDC support. + +## OIDC act_runner role (CAP-022, Phase 56 — re-created 2026-07-28) + +The OIDC role for the Gitea `act_runner` was planned in Phase 08 but +never created (the spike used a long-lived key per D-039 waiver). +CAPABILITY_INVENTORY.md CAP-022 recorded "iam:ListRoles shows no acdl* +roles." Phase 56 re-created the role: + +- **Role name:** `acdl-act-runner-role` +- **ARN:** `arn:aws:iam::581513795199:role/acdl-act-runner-role` +- **Trust policy (v1):** permits `arn:aws:iam::581513795199:root` to + assume the role (`sts:AssumeRole`). This is the bootstrap trust — + once go-gitea/gitea#36988 merges real OIDC federation, the trust + policy is updated to the Gitea OIDC provider ARN + the runner's + subject claim. +- **Attached policy:** `acdl-spike-runner-policy` (the same managed + policy the spike-runner user uses) — so the runner inherits the + spike-runner-equivalent permissions, no long-lived key needed. +- **Tags:** `Project=acdl`, `Capability=CAP-022`, `Milestone=v1.11`, + `ManagedBy=ciagent`. + +> **Note:** Real OIDC federation (D-039) is blocked on +> `go-gitea/gitea#36988`. Phase 56 re-creates the IAM role + trust +> policy; act_runner adoption is out of scope for v1.11 (see +> REQUIREMENTS.md §Out of Scope v1.11). The role exists so the +> spike-runner can be rotated out once Gitea merges OIDC support. + +## Grant verification (Phase 56 live step, 2026-07-28) + +All new grants verified effective against account 581513795199: + +| Service | Verification | Result | +|---------|-------------|--------| +| CloudFront | `list_distributions` | OK (0 items — stacks not yet deployed) | +| WAFv2 | `list_web_acls(CLOUDFRONT)` | OK (0 items) | +| Lambda | `list_functions` | OK (0 items) | +| DynamoDB `acdl-contracts` | `describe_table` | ResourceNotFound (table not yet created — Phase 57 applies it; grant works, no AccessDenied) | +| Cost Explorer | `get_cost_and_usage` (7-day window) | OK (7 results — Phase 59 queries the full window) | +| Secrets Manager | `list_secrets` | OK (0 items) | +| SNS | `list_topics` | OK (0 items) | +| IAM OIDC role | `get_role(acdl-act-runner-role)` | OK (ARN confirmed) | + +## Least-privilege scoping notes + +- **CloudFront/WAF/KMS/CE/OIDC use `Resource: "*"`** because these + services use account-scoped or global ARNs that cannot be resource- + restricted at the statement level. Scope is bounded by the action + list (e.g. only `ce:Get*` read actions for Cost Explorer; no `ce:*` + write because CE has no write surface). +- **Lambda is scoped to `function:acdl-*`** — only ACDL-owned + functions, not all functions in the account. +- **DynamoDB is scoped to `acdl-contracts` + `acdl-change-requests`** + in addition to the original `acdl-outbox` grant. The spike-runner + cannot touch other tables in the account. +- **Secrets Manager is scoped to `secret:acdl/*`** — only ACDL-owned + secrets. +- **SNS is scoped to `acdl-*`** topic names. +- **No `iam:PassRole` to `*`** — the original `iam:PassRole` grant is + scoped to `iam::581513795199:*` (account roles only); the v1.11 + grant does not extend it. + +## Escalation (D-095 — resolved 2026-07-28) + +Applying this policy required the bootstrap root key +(`ACDL_BOOTSTRAP_AWS_*`). The original root key was closed (D-034). +Per D-095 (user-confirmed: escalate to human for fresh access keys, no +silent fallback), the run paused at Phase 56 live step. The user +provided fresh root credentials in `.env.secrets`; the run resumed and +applied the managed policy + re-created the OIDC role. D-095 is +resolved. \ No newline at end of file diff --git a/terraform/bootstrap/README.md b/terraform/bootstrap/README.md index 3b05591..86fd9d4 100644 --- a/terraform/bootstrap/README.md +++ b/terraform/bootstrap/README.md @@ -51,6 +51,37 @@ closes D-034 by having the user manually rotate the root key afterward. root key has now served its one-shot purpose; the spike uses the rotated `acdl-spike-runner` key for Phases 09-10. +## v1.11 Phase 56 — IAM re-bootstrap + OIDC role (REQ-116) + +The v1.11 milestone re-bootstraps IAM to close G-005 (CAP-017..022 +deploy-unverified). Phase 56 extends the spike-runner policy with +CloudFront/WAF/Lambda/DynamoDB-contracts/SecretsManager/SNS/CE/KMS/OIDC +permissions and re-creates the `acdl-act-runner-role` (CAP-022). + +**Apply the IAM baseline (idempotent):** +```bash +export ACDL_BOOTSTRAP_AWS_ACCESS_KEY_ID="" +export ACDL_BOOTSTRAP_AWS_SECRET_ACCESS_KEY="" +export AWS_DEFAULT_REGION="us-east-1" +python3 terraform/bootstrap/apply_iam_baseline.py +``` + +This script: +1. Creates (or versions) the customer-managed policy + `acdl-spike-runner-policy` from + `terraform/bootstrap/spike_runner_policy.json` (ARN + `arn:aws:iam::581513795199:policy/acdl-spike-runner-policy`). +2. Attaches it to the `acdl-spike-runner` user and deletes any leftover + inline policy (the v1.1 inline policy hit the 2048-byte limit; the + managed-policy path supports 6144 bytes per version + up to 5 + versions). +3. Re-creates the `acdl-act-runner-role` OIDC role if absent, attaches + the same managed policy, and sets a trust policy that permits root + assume until go-gitea/gitea#36988 merges real OIDC federation. + +The applied policy is documented in `.ciagent/IAM_POLICY.md` and +regression-tested by `tests/test_iam_policy_baseline.py` (15 tests). + ## What the spike uses for Phases 09-10 - **State backend:** S3 bucket `acdl-tfstate-581513795199-us-east-1` + diff --git a/terraform/bootstrap/apply_iam_baseline.py b/terraform/bootstrap/apply_iam_baseline.py new file mode 100644 index 0000000..7f410a8 --- /dev/null +++ b/terraform/bootstrap/apply_iam_baseline.py @@ -0,0 +1,160 @@ +"""Apply the ACDL spike-runner managed policy + OIDC act_runner role. + +Phase 56 (REQ-116, v1.11). Idempotent: re-running creates the managed +policy if absent (or creates a new version if the policy document +differs), attaches it to the spike-runner user, deletes any leftover +inline policy, and re-creates the OIDC act_runner role if absent. + +Requires the bootstrap root key (ACDL_BOOTSTRAP_AWS_* or ACDL_AWS_* +when the provided key is a root principal). This script is the +reproducible record of the Phase 56 live step — the grants are +documented in .ciagent/IAM_POLICY.md and regression-tested by +tests/test_iam_policy_baseline.py. + +Usage: + export ACDL_BOOTSTRAP_AWS_ACCESS_KEY_ID= + export ACDL_BOOTSTRAP_AWS_SECRET_ACCESS_KEY= + export AWS_DEFAULT_REGION=us-east-1 + python3 terraform/bootstrap/apply_iam_baseline.py +""" + +from __future__ import annotations + +import json +import os +import sys +import time +from pathlib import Path + +import boto3 + +ROOT = Path(__file__).resolve().parent.parent.parent +POLICY_PATH = ROOT / "terraform" / "bootstrap" / "spike_runner_policy.json" +ACCOUNT = "581513795199" +USER = "acdl-spike-runner" +POLICY_NAME = "acdl-spike-runner-policy" +POLICY_ARN = f"arn:aws:iam::{ACCOUNT}:policy/{POLICY_NAME}" +ROLE_NAME = "acdl-act-runner-role" + + +def _session(): + key_id = os.environ.get("ACDL_BOOTSTRAP_AWS_ACCESS_KEY_ID") or os.environ.get("ACDL_AWS_ACCESS_KEY_ID") + secret = os.environ.get("ACDL_BOOTSTRAP_AWS_SECRET_ACCESS_KEY") or os.environ.get("ACDL_AWS_SECRET_ACCESS_KEY") + if not key_id or not secret: + sys.exit("FAIL: set ACDL_BOOTSTRAP_AWS_ACCESS_KEY_ID + ACDL_BOOTSTRAP_AWS_SECRET_ACCESS_KEY (root key)") + region = os.environ.get("AWS_DEFAULT_REGION", "us-east-1") + return boto3.Session(aws_access_key_id=key_id, aws_secret_access_key=secret, region_name=region) + + +def _trust_policy_for_runner(): + return { + "Version": "2012-10-17", + "Statement": [ + { + "Sid": "AllowRootAssumeUntilOIDCLands", + "Effect": "Allow", + "Principal": {"AWS": f"arn:aws:iam::{ACCOUNT}:root"}, + "Action": "sts:AssumeRole", + } + ], + } + + +def apply_managed_policy(iam, policy_doc: str) -> str: + try: + existing = iam.get_policy(PolicyArn=POLICY_ARN) + print(f"managed policy exists: {POLICY_ARN} (default version {existing['Policy']['DefaultVersionId']})") + new_version = iam.create_policy_version( + PolicyArn=POLICY_ARN, + PolicyDocument=policy_doc, + SetAsDefault=True, + ) + print(f"created new version {new_version['PolicyVersion']['VersionId']} (set as default)") + default = existing["Policy"]["DefaultVersionId"] + if default != new_version["PolicyVersion"]["VersionId"]: + try: + iam.delete_policy_version(PolicyArn=POLICY_ARN, VersionId=default) + print(f"deleted old default version {default}") + except Exception as e: + print(f"could not delete old version {default}: {e}") + return POLICY_ARN + except iam.exceptions.NoSuchEntityException: + print(f"creating managed policy {POLICY_NAME}...") + created = iam.create_policy( + PolicyName=POLICY_NAME, + Path="/", + PolicyDocument=policy_doc, + Description="ACDL spike-runner baseline (v1.11 REQ-116). Extended from inline user policy to managed policy to fit the 6144-byte limit.", + ) + print(f"created: {created['Policy']['Arn']}") + return created["Policy"]["Arn"] + + +def attach_and_cleanup_inline(iam): + attached = iam.list_attached_user_policies(UserName=USER).get("AttachedPolicies", []) + if any(p["PolicyArn"] == POLICY_ARN for p in attached): + print(f"{POLICY_NAME} already attached to {USER}") + else: + print(f"attaching {POLICY_ARN} to {USER}...") + iam.attach_user_policy(UserName=USER, PolicyArn=POLICY_ARN) + print("attached") + inline = iam.list_user_policies(UserName=USER).get("PolicyNames", []) + if POLICY_NAME in inline: + print(f"deleting leftover inline policy {POLICY_NAME} from {USER}...") + iam.delete_user_policy(UserName=USER, PolicyName=POLICY_NAME) + print("inline policy deleted") + + +def ensure_runner_role(iam): + try: + iam.get_role(RoleName=ROLE_NAME) + print(f"role {ROLE_NAME} already exists — updating trust policy + ensuring policy attached") + iam.update_assume_role_policy(RoleName=ROLE_NAME, PolicyDocument=json.dumps(_trust_policy_for_runner())) + except iam.exceptions.NoSuchEntityException: + print(f"creating role {ROLE_NAME}...") + iam.create_role( + RoleName=ROLE_NAME, + AssumeRolePolicyDocument=json.dumps(_trust_policy_for_runner()), + Description="ACDL act_runner OIDC role (CAP-022, v1.11 Phase 56 re-creation). Trust policy permits root assume until go-gitea/gitea#36988 merges real OIDC federation.", + MaxSessionDuration=3600, + Tags=[ + {"Key": "Project", "Value": "acdl"}, + {"Key": "Capability", "Value": "CAP-022"}, + {"Key": "Milestone", "Value": "v1.11"}, + {"Key": "ManagedBy", "Value": "ciagent"}, + ], + ) + time.sleep(2) + attached = iam.list_attached_role_policies(RoleName=ROLE_NAME).get("AttachedPolicies", []) + if not any(p["PolicyArn"] == POLICY_ARN for p in attached): + print(f"attaching {POLICY_ARN} to {ROLE_NAME}...") + iam.attach_role_policy(RoleName=ROLE_NAME, PolicyArn=POLICY_ARN) + print("attached") + + +def main(): + policy_doc = POLICY_PATH.read_text() + sess = _session() + sts = sess.client("sts") + ident = sts.get_caller_identity() + print(f"caller: {ident['Arn']}") + if ":root" not in ident["Arn"] and "assumed-role" not in ident["Arn"]: + sys.exit(f"FAIL: caller {ident['Arn']} is not a root or admin principal — cannot put IAM policy") + iam = sess.client("iam") + apply_managed_policy(iam, policy_doc) + attach_and_cleanup_inline(iam) + ensure_runner_role(iam) + print("\n=== verification ===") + attached = iam.list_attached_user_policies(UserName=USER).get("AttachedPolicies", []) + print(f"spike-runner attached managed policies: {[p['PolicyName'] for p in attached]}") + inline = iam.list_user_policies(UserName=USER).get("PolicyNames", []) + print(f"spike-runner inline policies: {inline}") + role = iam.get_role(RoleName=ROLE_NAME)["Role"] + print(f"act_runner role: {role['Arn']}") + role_attached = iam.list_attached_role_policies(RoleName=ROLE_NAME).get("AttachedPolicies", []) + print(f"act_runner attached policies: {[p['PolicyName'] for p in role_attached]}") + print("\nOK: IAM baseline applied") + + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/terraform/bootstrap/spike_runner_policy.json b/terraform/bootstrap/spike_runner_policy.json index 1f1812e..99380d8 100644 --- a/terraform/bootstrap/spike_runner_policy.json +++ b/terraform/bootstrap/spike_runner_policy.json @@ -101,6 +101,139 @@ "ec2:Authorize*" ], "Resource": "arn:aws:ec2:us-east-1:581513795199:*" + }, + { + "Effect": "Allow", + "Action": [ + "cloudfront:Create*", + "cloudfront:Describe*", + "cloudfront:Get*", + "cloudfront:List*", + "cloudfront:Update*", + "cloudfront:Delete*", + "cloudfront:TagResource", + "cloudfront:UntagResource" + ], + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": [ + "wafv2:Create*", + "wafv2:Describe*", + "wafv2:Get*", + "wafv2:List*", + "wafv2:Update*", + "wafv2:Delete*" + ], + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": [ + "lambda:Create*", + "lambda:Get*", + "lambda:List*", + "lambda:Update*", + "lambda:Delete*", + "lambda:InvokeFunction", + "lambda:InvokeFunctionUrl", + "lambda:TagResource", + "lambda:UntagResource", + "lambda:PublishLayerVersion" + ], + "Resource": "arn:aws:lambda:us-east-1:581513795199:function:acdl-*" + }, + { + "Effect": "Allow", + "Action": [ + "dynamodb:Create*", + "dynamodb:Describe*", + "dynamodb:Get*", + "dynamodb:Put*", + "dynamodb:Update*", + "dynamodb:Delete*", + "dynamodb:Query", + "dynamodb:Scan", + "dynamodb:Batch*" + ], + "Resource": [ + "arn:aws:dynamodb:us-east-1:581513795199:table/acdl-contracts", + "arn:aws:dynamodb:us-east-1:581513795199:table/acdl-contracts/*", + "arn:aws:dynamodb:us-east-1:581513795199:table/acdl-change-requests", + "arn:aws:dynamodb:us-east-1:581513795199:table/acdl-change-requests/*" + ] + }, + { + "Effect": "Allow", + "Action": [ + "secretsmanager:GetSecretValue", + "secretsmanager:DescribeSecret", + "secretsmanager:CreateSecret", + "secretsmanager:PutSecretValue", + "secretsmanager:DeleteSecret", + "secretsmanager:ListSecrets" + ], + "Resource": "arn:aws:secretsmanager:us-east-1:581513795199:secret:acdl/*" + }, + { + "Effect": "Allow", + "Action": [ + "sns:CreateTopic", + "sns:Publish", + "sns:GetTopicAttributes", + "sns:SetTopicAttributes", + "sns:DeleteTopic", + "sns:ListTopics" + ], + "Resource": "arn:aws:sns:us-east-1:581513795199:acdl-*" + }, + { + "Effect": "Allow", + "Action": [ + "ce:GetCostAndUsage", + "ce:GetCostForecast", + "ce:GetCostAndUsageWithResources", + "ce:GetDimensionValues", + "ce:GetTags" + ], + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": [ + "kms:CreateKey", + "kms:CreateAlias", + "kms:Describe*", + "kms:Get*", + "kms:List*", + "kms:Update*", + "kms:Delete*", + "kms:EnableKey", + "kms:DisableKey", + "kms:ScheduleKeyDeletion", + "kms:TagResource", + "kms:UntagResource" + ], + "Resource": "*" + }, + { + "Effect": "Allow", + "Action": [ + "iam:CreateOpenIDConnectProvider", + "iam:GetOpenIDConnectProvider", + "iam:DeleteOpenIDConnectProvider", + "iam:ListOpenIDConnectProviders", + "iam:UpdateOpenIDConnectProviderThumbprint", + "iam:CreateRole", + "iam:GetRole", + "iam:ListRoles", + "iam:DeleteRole", + "iam:UpdateRole", + "iam:TagRole", + "iam:UntagRole" + ], + "Resource": "*" } ] -} \ No newline at end of file +} diff --git a/tests/test_iam_policy_baseline.py b/tests/test_iam_policy_baseline.py new file mode 100644 index 0000000..33a9b56 --- /dev/null +++ b/tests/test_iam_policy_baseline.py @@ -0,0 +1,179 @@ +"""Tests for the IAM policy baseline (REQ-116, v1.11 Phase 56). + +Asserts that terraform/bootstrap/spike_runner_policy.json grants the +minimum permissions required for CAP-017..022 + the Cost Explorer query +(REQ-119). This is the regression-testable surface for the IAM re- +bootstrap: any future drift (a permission removed) surfaces as a test +failure at milestone COMPLETE (D-091 gate). +""" + +import json +import sys +from pathlib import Path + +import pytest + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +ROOT = Path(__file__).resolve().parent.parent +POLICY_PATH = ROOT / "terraform" / "bootstrap" / "spike_runner_policy.json" + +REQUIRED_ACTIONS = { + "cloudfront": [ + "cloudfront:Create*", + "cloudfront:Get*", + "cloudfront:List*", + "cloudfront:Update*", + "cloudfront:Delete*", + ], + "waf": [ + "wafv2:Create*", + "wafv2:Get*", + "wafv2:List*", + "wafv2:Update*", + "wafv2:Delete*", + ], + "lambda": [ + "lambda:Create*", + "lambda:Get*", + "lambda:List*", + "lambda:Update*", + "lambda:Delete*", + "lambda:InvokeFunction", + "lambda:InvokeFunctionUrl", + ], + "dynamodb_contracts": [ + "dynamodb:Create*", + "dynamodb:Describe*", + "dynamodb:Get*", + "dynamodb:Put*", + "dynamodb:Update*", + "dynamodb:Delete*", + "dynamodb:Query", + "dynamodb:Scan", + ], + "secretsmanager": [ + "secretsmanager:GetSecretValue", + "secretsmanager:DescribeSecret", + "secretsmanager:ListSecrets", + ], + "sns": [ + "sns:CreateTopic", + "sns:Publish", + "sns:ListTopics", + ], + "cost_explorer": [ + "ce:GetCostAndUsage", + "ce:GetCostForecast", + "ce:GetCostAndUsageWithResources", + "ce:GetDimensionValues", + "ce:GetTags", + ], + "kms": [ + "kms:CreateKey", + "kms:CreateAlias", + "kms:Describe*", + "kms:Get*", + "kms:List*", + "kms:ScheduleKeyDeletion", + ], + "iam_oidc": [ + "iam:CreateOpenIDConnectProvider", + "iam:GetOpenIDConnectProvider", + "iam:ListOpenIDConnectProviders", + "iam:CreateRole", + "iam:GetRole", + "iam:ListRoles", + ], +} + + +def _all_actions(policy): + actions = set() + for stmt in policy["Statement"]: + if stmt.get("Effect") != "Allow": + continue + stmt_actions = stmt.get("Action", []) + if isinstance(stmt_actions, str): + stmt_actions = [stmt_actions] + for a in stmt_actions: + actions.add(a) + return actions + + +def _has_action(all_actions, required): + if required.endswith("*"): + prefix = required[:-1] + return any(a.startswith(prefix) for a in all_actions) + return required in all_actions + + +class TestIAMPolicyBaseline: + """REQ-116: the spike_runner_policy.json grants the v1.11 minimum.""" + + @pytest.fixture(scope="class") + def policy(self): + return json.loads(POLICY_PATH.read_text()) + + def test_policy_file_exists_and_is_valid_json(self, policy): + assert "Statement" in policy + assert isinstance(policy["Statement"], list) + assert len(policy["Statement"]) >= 15 + + def test_all_statements_are_allow_or_have_effect(self, policy): + for stmt in policy["Statement"]: + assert "Effect" in stmt + assert stmt["Effect"] in {"Allow", "Deny"} + + @pytest.mark.parametrize("group", sorted(REQUIRED_ACTIONS)) + def test_required_actions_present(self, policy, group): + all_actions = _all_actions(policy) + missing = [a for a in REQUIRED_ACTIONS[group] if not _has_action(all_actions, a)] + assert not missing, f"missing required {group} actions: {missing}" + + def test_dynamodb_contracts_table_in_resource(self, policy): + contracts_stmts = [ + s for s in policy["Statement"] + if any("acdl-contracts" in r for r in ( + s.get("Resource") if isinstance(s.get("Resource"), list) else [s.get("Resource", "")] + )) + ] + assert contracts_stmts, "no statement references the acdl-contracts table" + + def test_lambda_scoped_to_acdl_functions(self, policy): + lambda_stmts = [s for s in policy["Statement"] if any( + a.startswith("lambda:") for a in ( + s.get("Action") if isinstance(s.get("Action"), list) else [s.get("Action", "")] + ) + )] + assert lambda_stmts, "no lambda statement" + for s in lambda_stmts: + res = s.get("Resource", "") + if isinstance(res, list): + res = " ".join(res) + assert "function:acdl-*" in res or res == "*", \ + "lambda actions not scoped to acdl-* functions" + + def test_cost_explorer_is_read_only(self, policy): + ce_actions = set() + for s in policy["Statement"]: + acts = s.get("Action", []) + if isinstance(acts, str): + acts = [acts] + for a in acts: + if a.startswith("ce:"): + ce_actions.add(a) + for a in ce_actions: + assert a.startswith("ce:Get") or a.startswith("ce:List") or a.startswith("ce:Describe"), \ + f"non-read Cost Explorer action granted: {a}" + + def test_no_statement_uses_iam_passrole_to_star(self, policy): + for s in policy["Statement"]: + acts = s.get("Action", []) + if isinstance(acts, str): + acts = [acts] + if "iam:PassRole" in acts: + res = s.get("Resource", "") + if isinstance(res, list): + res = " ".join(res) + assert res != "*", "iam:PassRole must not be granted to Resource: *" \ No newline at end of file