grada-run 0.47.0 → 0.49.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "grada-run",
3
- "version": "0.47.0",
3
+ "version": "0.49.0",
4
4
  "description": "Provision production-ready AWS infrastructure and CI/CD pipelines in seconds.",
5
5
  "engines": {
6
6
  "node": ">=18.0.0"
@@ -27,6 +27,7 @@
27
27
  "test:iac": "node ./scripts/test-iac.js",
28
28
  "test:e2e:tier0": "vitest run -c vitest.e2e.tier0.config.js",
29
29
  "test:e2e:tier1": "vitest run -c vitest.e2e.tier1.config.js",
30
+ "test:e2e:tier2": "vitest run -c vitest.e2e.tier2.config.js",
30
31
  "sync:bedrock-models": "node scripts/sync-bedrock-models.js",
31
32
  "docs:dev": "npm run dev --workspace=apps/docs",
32
33
  "docs:build": "npm run build --workspace=apps/docs"
@@ -108,10 +109,13 @@
108
109
  "@aws-sdk/client-ecr": "3.1119.0",
109
110
  "@aws-sdk/client-ecs": "3.1119.0",
110
111
  "@aws-sdk/client-elastic-load-balancing-v2": "3.1119.0",
112
+ "@aws-sdk/client-iam": "3.1119.0",
111
113
  "@aws-sdk/client-rds": "3.1119.0",
112
114
  "@aws-sdk/client-s3": "3.1115.0",
113
115
  "@aws-sdk/client-secrets-manager": "3.1112.0",
116
+ "@aws-sdk/client-sqs": "3.1119.0",
114
117
  "@aws-sdk/client-sts": "3.1115.0",
118
+ "@aws-sdk/s3-request-presigner": "3.1119.0",
115
119
  "@clack/prompts": "1.7.0",
116
120
  "@modelcontextprotocol/sdk": "^1.32.0",
117
121
  "dotenv": "17.4.2",
@@ -114,6 +114,47 @@ export function renderOidcSubClaim(sub) {
114
114
  return `["${sub}", "${companion}"]`;
115
115
  }
116
116
 
117
+ // Renders both CI roles' trust claims as HCL fragments from the resolved
118
+ // repo trust: the deploy role binds to the effective deploy branch (the
119
+ // same value rendered into the deploy trigger, so the two stay in sync),
120
+ // the preview role binds to pull request events. The open trust and
121
+ // hand-customized claims render verbatim — never silently widened.
122
+ export function renderOidcRoleSubs(resolvedSub, deployBranch) {
123
+ const match = typeof resolvedSub === 'string' && resolvedSub.match(/^repo:([^:]+\/[^:]+)(?::(.*))?$/);
124
+ if (!match) return { deploySub: renderOidcSubClaim(resolvedSub), previewSub: renderOidcSubClaim(resolvedSub) };
125
+ const [, slug, rest] = match;
126
+ const preview = `repo:${slug}:pull_request`;
127
+ const deploy = rest === undefined || rest === '*' || rest.startsWith('ref:refs/heads/')
128
+ ? `repo:${slug}:ref:refs/heads/${deployBranch}`
129
+ : resolvedSub;
130
+ return { deploySub: renderOidcSubClaim(deploy), previewSub: renderOidcSubClaim(preview) };
131
+ }
132
+
133
+ // Centralized CI role-name construction (R1): the deploy/preview role
134
+ // names rendered into oidc.tf, the workflow templates, and the drift/plan
135
+ // scaffold calls all come from these builders. IAM caps role names at 64
136
+ // chars, so long projects truncate from the project part — the entropy
137
+ // suffix (uniqueness) and the role-kind suffix always survive intact.
138
+ export const MAX_IAM_ROLE_NAME_LENGTH = 64;
139
+
140
+ function buildCiRoleName(projectName, suffix, kind) {
141
+ const tail = `${suffix}-github-actions-${kind}-role`;
142
+ const head = String(projectName ?? '').slice(0, Math.max(MAX_IAM_ROLE_NAME_LENGTH - tail.length, 0)).replace(/-+$/, '');
143
+ return `${head}${tail}`;
144
+ }
145
+
146
+ export function buildDeployRoleName(projectName, suffix) {
147
+ return buildCiRoleName(projectName, suffix, 'deploy');
148
+ }
149
+
150
+ export function buildPreviewRoleName(projectName, suffix) {
151
+ return buildCiRoleName(projectName, suffix, 'preview');
152
+ }
153
+
154
+ export function buildRoleArn(accountId, roleName) {
155
+ return `arn:aws:iam::${accountId}:role/${roleName}`;
156
+ }
157
+
117
158
  // Classifies an existing tree's OIDC claim for re-init: a bare string (or
118
159
  // single-entry list, IAM-identical) renders verbatim; our own canonical
119
160
  // dual-format pair resolves back to its classic entry so re-init stays
@@ -868,6 +909,7 @@ async function mainStackMain(input = {}) {
868
909
 
869
910
  // 7. Synthesize Templates
870
911
  s.message('Synthesizing Terraform templates...');
912
+ const { deploySub, previewSub } = renderOidcRoleSubs(oidcTrustSub, config.branch);
871
913
  const renderConfig = {
872
914
  PROJECT_NAME: dirConfig.actualProjectName,
873
915
  RESOURCE_SUFFIX: resourceSuffix,
@@ -882,7 +924,10 @@ async function mainStackMain(input = {}) {
882
924
  HEALTH_CHECK_PATH: config.healthCheckPath,
883
925
  DESIRED_COUNT: config.desiredCount,
884
926
  DEPLOY_BRANCH: config.branch,
885
- GITHUB_REPO_SUB: renderOidcSubClaim(oidcTrustSub),
927
+ DEPLOY_ROLE_NAME: buildDeployRoleName(dirConfig.actualProjectName, resourceSuffix),
928
+ PREVIEW_ROLE_NAME: buildPreviewRoleName(dirConfig.actualProjectName, resourceSuffix),
929
+ GITHUB_DEPLOY_SUB: deploySub,
930
+ GITHUB_PREVIEW_SUB: previewSub,
886
931
  BUILD_DIR: buildDir,
887
932
  finalFramework: config.framework,
888
933
  NEEDS_DATABASE: config.needsDatabase,
@@ -945,7 +990,7 @@ async function mainStackMain(input = {}) {
945
990
  // Hand edits trip refuse-dirty before this point; --force regenerates.
946
991
  const drifted = scaffoldDriftWorkflow(dirConfig.targetDir, {
947
992
  region: config.region,
948
- roleArn: `arn:aws:iam::${awsAccountId}:role/${dirConfig.actualProjectName}${resourceSuffix}-github-actions-role`,
993
+ roleArn: buildRoleArn(awsAccountId, buildDeployRoleName(dirConfig.actualProjectName, resourceSuffix)),
949
994
  force: initOptions.force,
950
995
  });
951
996
  if (drifted.ok) {
@@ -959,7 +1004,7 @@ async function mainStackMain(input = {}) {
959
1004
  // role ARN) instead of silently keeping a stale copy.
960
1005
  const planned = scaffoldPlanWorkflow(dirConfig.targetDir, {
961
1006
  region: config.region,
962
- roleArn: `arn:aws:iam::${awsAccountId}:role/${dirConfig.actualProjectName}${resourceSuffix}-github-actions-role`,
1007
+ roleArn: buildRoleArn(awsAccountId, buildPreviewRoleName(dirConfig.actualProjectName, resourceSuffix)),
963
1008
  force: initOptions.force,
964
1009
  });
965
1010
  if (planned.ok) {
@@ -2,9 +2,10 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
 
4
4
  // Token offline scaffolds (`init --offline`) leave where the AWS account
5
- // ID belongs: the bucket name in terraform/backend.tf plus every
6
- // role-to-assume ARN in .github/workflows/*.yml. Detection only —
7
- // rewriting lives in apply's reconcile pre-step.
5
+ // ID belongs: the bucket name in terraform/backend.tf, the state-bucket
6
+ // deny ARNs in terraform/oidc.tf, plus every role-to-assume ARN in
7
+ // .github/workflows/*.yml. Detection only — rewriting lives in apply's
8
+ // reconcile pre-step.
8
9
  export const PLACEHOLDER_ACCOUNT_ID = 'YOUR_AWS_ACCOUNT_ID';
9
10
 
10
11
  // Repo-relative paths still containing the placeholder (`[]` when the
@@ -23,6 +24,7 @@ export function findUnreconciledFiles(targetDir) {
23
24
  if (content.includes(PLACEHOLDER_ACCOUNT_ID)) found.push(repoPath);
24
25
  };
25
26
  check(path.join('terraform', 'backend.tf'));
27
+ check(path.join('terraform', 'oidc.tf'));
26
28
  let entries = [];
27
29
  try {
28
30
  entries = fs.readdirSync(path.join(targetDir, '.github', 'workflows'));
@@ -137,17 +137,29 @@ export function readTerraformOidcTrust(cwd = process.cwd()) {
137
137
  const base = resolveCwd({}, cwd);
138
138
  const oidcTf = readFileSafe(path.join(base, 'terraform', 'oidc.tf'));
139
139
  if (!oidcTf) return null;
140
- const claimMatch = oidcTf.match(/"token\.actions\.githubusercontent\.com:sub"\s*:\s*(\[[\s\S]*?\]|"[^"]*")/);
141
- if (!claimMatch) {
142
- const hasClaim = /"token\.actions\.githubusercontent\.com:sub"\s*:/.test(oidcTf);
143
- return hasClaim ? { kind: 'unparseable' } : null;
144
- }
145
- const raw = claimMatch[1];
146
- if (raw.startsWith('[')) {
147
- const entries = [...raw.matchAll(/"([^"]+)"/g)].map((m) => m[1]);
140
+ // Dual-role files carry two claims: anchor on the deploy role block so
141
+ // re-init resolves trust from the deploy claim even if the file is
142
+ // reordered. Legacy single-role files fall back to the first claim.
143
+ // The value is classified in place (never skipped past): a non-literal
144
+ // deploy claim must read unparseable, not silently resolve to the
145
+ // preview claim further down.
146
+ const deployScope = oidcTf.match(/resource\s+"aws_iam_role"\s+"github_actions_deploy"[\s\S]*/);
147
+ const scope = deployScope ? deployScope[0] : oidcTf;
148
+ const keyMatch = scope.match(/"token\.actions\.githubusercontent\.com:sub"\s*:\s*/);
149
+ if (!keyMatch) return null;
150
+ const after = scope.slice(keyMatch.index + keyMatch[0].length);
151
+ if (after.startsWith('[')) {
152
+ const listMatch = after.match(/^\[[\s\S]*?\]/);
153
+ if (!listMatch) return { kind: 'unparseable' };
154
+ const entries = [...listMatch[0].matchAll(/"([^"]+)"/g)].map((m) => m[1]);
148
155
  return { kind: 'list', entries };
149
156
  }
150
- return { kind: 'string', value: raw.slice(1, -1) };
157
+ if (after.startsWith('"')) {
158
+ const strMatch = after.match(/^"[^"]*"/);
159
+ if (!strMatch) return { kind: 'unparseable' };
160
+ return { kind: 'string', value: strMatch[0].slice(1, -1) };
161
+ }
162
+ return { kind: 'unparseable' };
151
163
  }
152
164
 
153
165
  // Index just past the `]` matching the `[` at openIdx (quoted regions
@@ -338,7 +338,7 @@ export async function getTerraformStateBuckets(cwd) {
338
338
  // state), missing keys warn (conservative start to avoid false
339
339
  // positives on customized trees).
340
340
  export const EXPECTED_OUTPUT_KEYS = {
341
- ecs: ['alb_direct_url', 'ecr_repository_url'],
341
+ ecs: ['alb_direct_url', 'ecr_repository_url', 'ecs_task_role_arn'],
342
342
  lambda: ['api_gateway_url', 'ecr_repository_url'],
343
343
  static: ['site_url'],
344
344
  };
@@ -60,7 +60,7 @@ jobs:
60
60
  uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
61
61
  continue-on-error: true
62
62
  with:
63
- role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
63
+ role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{DEPLOY_ROLE_NAME}}
64
64
  aws-region: ${{ env.AWS_REGION }}
65
65
 
66
66
  # Deploy never skips: a failed assume fails the run with the
@@ -141,7 +141,7 @@ jobs:
141
141
  uses: grada-run/grada-action@12227808ae4caafaec1041319645586a1132fc57 # v1
142
142
  with:
143
143
  aws-region: ${{ env.AWS_REGION }}
144
- role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
144
+ role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{DEPLOY_ROLE_NAME}}
145
145
  terraform-dir: 'terraform'
146
146
 
147
147
  # --- 8. DEPLOY ---
@@ -60,7 +60,7 @@ jobs:
60
60
  uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
61
61
  continue-on-error: true
62
62
  with:
63
- role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
63
+ role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{DEPLOY_ROLE_NAME}}
64
64
  aws-region: ${{ env.AWS_REGION }}
65
65
 
66
66
  # Deploy never skips: a failed assume fails the run with the
@@ -76,7 +76,7 @@ jobs:
76
76
  uses: grada-run/grada-action@12227808ae4caafaec1041319645586a1132fc57 # v1
77
77
  with:
78
78
  aws-region: ${{ env.AWS_REGION }}
79
- role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
79
+ role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{DEPLOY_ROLE_NAME}}
80
80
  terraform-dir: 'terraform'
81
81
 
82
82
  # --- 4. BUILD ---
@@ -64,7 +64,7 @@ jobs:
64
64
  uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
65
65
  continue-on-error: true
66
66
  with:
67
- role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
67
+ role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{DEPLOY_ROLE_NAME}}
68
68
  aws-region: ${{ env.AWS_REGION }}
69
69
 
70
70
  # Deploy never skips: a failed assume fails the run with the
@@ -144,7 +144,7 @@ jobs:
144
144
  uses: grada-run/grada-action@12227808ae4caafaec1041319645586a1132fc57 # v1
145
145
  with:
146
146
  aws-region: ${{ env.AWS_REGION }}
147
- role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
147
+ role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{DEPLOY_ROLE_NAME}}
148
148
  terraform-dir: 'terraform'
149
149
 
150
150
  # --- 8. DEPLOY ---
@@ -3,7 +3,7 @@ name: Terraform Plan on PR
3
3
  on:
4
4
  # pull_request_target (not pull_request): this file comes from the base
5
5
  # branch, so a fork PR cannot delete the same-repo guard below to reach
6
- # the admin CI role (BUG-140). The PR head is checked out explicitly by
6
+ # the privileged CI roles (BUG-140). The PR head is checked out explicitly by
7
7
  # SHA in the guarded step instead.
8
8
  pull_request_target:
9
9
  types: [opened, synchronize, reopened]
@@ -3,7 +3,7 @@ name: Ephemeral PR Preview
3
3
  on:
4
4
  # pull_request_target (not pull_request): this file comes from the base
5
5
  # branch, so a fork PR cannot delete the same-repo guard below to reach
6
- # the admin CI role (BUG-140). The PR head is checked out explicitly by
6
+ # the privileged CI roles (BUG-140). The PR head is checked out explicitly by
7
7
  # SHA in the guarded step instead.
8
8
  pull_request_target:
9
9
  types: [opened, synchronize, reopened]
@@ -52,7 +52,7 @@ jobs:
52
52
  uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
53
53
  continue-on-error: true
54
54
  with:
55
- role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
55
+ role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PREVIEW_ROLE_NAME}}
56
56
  aws-region: ${{ env.AWS_REGION }}
57
57
 
58
58
  # STS denies a missing role and a trust mismatch with the same
@@ -62,7 +62,7 @@ jobs:
62
62
  - name: Interpret credential failure
63
63
  if: steps.aws-creds.outcome == 'failure'
64
64
  run: |
65
- ROLE_ARN="arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role"
65
+ ROLE_ARN="arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PREVIEW_ROLE_NAME}}"
66
66
  echo "::notice::AWS credential assumption failed for $ROLE_ARN — skipping this run. Either the stack is absent (never provisioned or destroyed — re-bootstrap with: npx grada-run apply) or the OIDC trust does not cover this run (check terraform/oidc.tf)."
67
67
 
68
68
  - name: Login to Amazon ECR
@@ -3,7 +3,7 @@ name: Ephemeral PR Preview
3
3
  on:
4
4
  # pull_request_target (not pull_request): this file comes from the base
5
5
  # branch, so a fork PR cannot delete the same-repo guard below to reach
6
- # the admin CI role (BUG-140). The PR head is checked out explicitly by
6
+ # the privileged CI roles (BUG-140). The PR head is checked out explicitly by
7
7
  # SHA in the guarded step instead.
8
8
  pull_request_target:
9
9
  types: [opened, synchronize, reopened]
@@ -52,7 +52,7 @@ jobs:
52
52
  uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
53
53
  continue-on-error: true
54
54
  with:
55
- role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
55
+ role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PREVIEW_ROLE_NAME}}
56
56
  aws-region: ${{ env.AWS_REGION }}
57
57
 
58
58
  # STS denies a missing role and a trust mismatch with the same
@@ -62,7 +62,7 @@ jobs:
62
62
  - name: Interpret credential failure
63
63
  if: steps.aws-creds.outcome == 'failure'
64
64
  run: |
65
- ROLE_ARN="arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role"
65
+ ROLE_ARN="arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PREVIEW_ROLE_NAME}}"
66
66
  echo "::notice::AWS credential assumption failed for $ROLE_ARN — skipping this run. Either the stack is absent (never provisioned or destroyed — re-bootstrap with: npx grada-run apply) or the OIDC trust does not cover this run (check terraform/oidc.tf)."
67
67
 
68
68
  - name: Login to Amazon ECR
@@ -46,7 +46,7 @@ jobs:
46
46
  uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
47
47
  continue-on-error: true
48
48
  with:
49
- role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
49
+ role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PREVIEW_ROLE_NAME}}
50
50
  aws-region: ${{ env.AWS_REGION }}
51
51
 
52
52
  # STS denies a missing role and a trust mismatch with the same
@@ -56,7 +56,7 @@ jobs:
56
56
  - name: Interpret credential failure
57
57
  if: steps.aws-creds.outcome == 'failure'
58
58
  run: |
59
- ROLE_ARN="arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role"
59
+ ROLE_ARN="arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PREVIEW_ROLE_NAME}}"
60
60
  echo "::notice::AWS credential assumption failed for $ROLE_ARN — skipping this run. Either the stack is absent (never provisioned or destroyed — re-bootstrap with: npx grada-run apply) or the OIDC trust does not cover this run (check terraform/oidc.tf)."
61
61
 
62
62
  - name: Setup Terraform
@@ -64,3 +64,25 @@ output "redis_endpoint" {
64
64
  output "redis_port" {
65
65
  value = aws_elasticache_replication_group.redis.port
66
66
  }
67
+
68
+ # Preview guardrail fragment: the replication group ID is content-hashed,
69
+ # so its ARN cannot be rebuilt by name in oidc.tf — deny by live reference
70
+ # instead. Only rendered with the addon; count-matched to the preview role
71
+ # so preview-workspace plans never evaluate it.
72
+ resource "aws_iam_role_policy" "preview_deny_redis" {
73
+ count = terraform.workspace == "default" ? 1 : 0
74
+ name = "${local.app_name}-preview-deny-redis"
75
+ role = aws_iam_role.github_actions_preview[0].id
76
+
77
+ policy = jsonencode({
78
+ Version = "2012-10-17"
79
+ Statement = [
80
+ {
81
+ Sid = "DenyProdRedisDestruction"
82
+ Effect = "Deny"
83
+ Action = ["elasticache:DeleteReplicationGroup", "elasticache:ModifyReplicationGroup"]
84
+ Resource = [aws_elasticache_replication_group.redis.arn]
85
+ },
86
+ ]
87
+ })
88
+ }
@@ -6,8 +6,6 @@
6
6
  # ($0.023/GB-mo), S3 PUT/GET requests, and CloudFront data transfer out
7
7
  # are billed by usage on top of the stack's fixed baseline.
8
8
 
9
- data "aws_caller_identity" "current" {}
10
-
11
9
  # --- Private S3 Bucket ---
12
10
  resource "aws_s3_bucket" "storage" {
13
11
  # Truncate and sanitize the prefix so the full account ID suffix always fits
@@ -178,3 +176,25 @@ output "s3_bucket_name" {
178
176
  output "s3_cdn_domain" {
179
177
  value = aws_cloudfront_distribution.storage_cdn.domain_name
180
178
  }
179
+
180
+ # Preview guardrail fragment: the bucket name transform cannot be rebuilt
181
+ # by name in oidc.tf — deny by live reference instead. Only rendered with
182
+ # the addon; count-matched to the preview role so preview-workspace plans
183
+ # never evaluate it.
184
+ resource "aws_iam_role_policy" "preview_deny_storage" {
185
+ count = terraform.workspace == "default" ? 1 : 0
186
+ name = "${local.app_name}-preview-deny-storage"
187
+ role = aws_iam_role.github_actions_preview[0].id
188
+
189
+ policy = jsonencode({
190
+ Version = "2012-10-17"
191
+ Statement = [
192
+ {
193
+ Sid = "DenyProdStorageDestruction"
194
+ Effect = "Deny"
195
+ Action = ["s3:DeleteBucket", "s3:DeleteObjectVersion"]
196
+ Resource = [aws_s3_bucket.storage.arn, "${aws_s3_bucket.storage.arn}/*"]
197
+ },
198
+ ]
199
+ })
200
+ }
@@ -337,6 +337,11 @@ output "ecr_repository_url" {
337
337
  value = local.ecr_url
338
338
  }
339
339
 
340
+ output "ecs_task_role_arn" {
341
+ description = "ARN of the ECS task IAM role (used by Tier 2 live-service assertions)"
342
+ value = aws_iam_role.task_role.arn
343
+ }
344
+
340
345
  # --- CloudWatch Alarms ---
341
346
  # State-only alarm: visible in the console, notifies nobody. There is no
342
347
  # notification destination at scaffold time; `grada alerts` provisions
@@ -4,7 +4,7 @@ data "tls_certificate" "github" {
4
4
  }
5
5
 
6
6
  variable "create_oidc_provider" {
7
- description = "Set to false if you already have OIDC provider in your AWS account"
7
+ description = "Set to false if you already have an OIDC provider in your AWS account"
8
8
  type = bool
9
9
  default = true
10
10
  }
@@ -23,15 +23,26 @@ data "aws_iam_openid_connect_provider" "github_existing" {
23
23
  url = "https://token.actions.githubusercontent.com"
24
24
  }
25
25
 
26
+ # Canonical home for the account/region data sources: every generated tree
27
+ # includes this file, so conditional templates must reference (never
28
+ # redeclare) these blocks.
29
+ data "aws_caller_identity" "current" {}
30
+ data "aws_region" "current" {}
31
+
26
32
  # Dynamically pick the ARN of the provider based on the variable
27
33
  locals {
28
34
  github_provider_arn = (var.create_oidc_provider && terraform.workspace == "default") ? aws_iam_openid_connect_provider.github[0].arn : data.aws_iam_openid_connect_provider.github_existing[0].arn
35
+ # Production resource prefix for the guardrail policies below. Rendered
36
+ # (not local.app_name): app_name carries the workspace suffix in preview
37
+ # workspaces, while these denies must always name production.
38
+ prod_prefix = "{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}"
29
39
  }
30
40
 
31
- # Create the IAM Role that GitHub Actions will assume
32
- resource "aws_iam_role" "github_actions" {
41
+ # Deploy role FIRST: readTerraformOidcTrust anchors on this block so re-init
42
+ # resolves trust from the deploy claim even if the file is reordered.
43
+ resource "aws_iam_role" "github_actions_deploy" {
33
44
  count = terraform.workspace == "default" ? 1 : 0
34
- name = "{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role"
45
+ name = "{{DEPLOY_ROLE_NAME}}"
35
46
 
36
47
  assume_role_policy = jsonencode({
37
48
  Version = "2012-10-17"
@@ -45,28 +56,203 @@ resource "aws_iam_role" "github_actions" {
45
56
  Condition = {
46
57
  StringLike = {
47
58
  # CI trust, scoped at scaffold time from --github-repo, the git
48
- # remote, or the setup prompt. "repo:*" means any GitHub repo's
49
- # Actions can assume this role — re-scope before going live.
50
- # Scoped trusts render both subject-claim formats: the classic
51
- # `repo:<owner>/<name>:<suffix>` plus the immutable-claim
52
- # companion `repo:<owner>@*/<name>@*:<same suffix>`
53
- # (repos created after 2026-07-15).
54
- "token.actions.githubusercontent.com:sub" : {{GITHUB_REPO_SUB}}
59
+ # remote, or the setup prompt, then bound to the deploy branch.
60
+ # "repo:*" means any GitHub repo's Actions can assume this role —
61
+ # re-scope before going live. Scoped trusts render both
62
+ # subject-claim formats: the classic `repo:<owner>/<name>:...`
63
+ # plus the immutable-claim companion
64
+ # `repo:<owner>@*/<name>@*:...` (repos created after 2026-07-15).
65
+ "token.actions.githubusercontent.com:sub" : {{GITHUB_DEPLOY_SUB}}
55
66
  }
56
67
  StringEquals = {
57
68
  "token.actions.githubusercontent.com:aud" : "sts.amazonaws.com"
58
69
  }
59
70
  }
60
- }
71
+ },
61
72
  ]
62
73
  })
63
74
  }
64
75
 
65
- # Grant the CI/CD pipeline permissions to provision infrastructure.
66
- # Intentionally broad: this role runs full Terraform applies from CI.
67
- # Narrow only with a reviewed least-privilege policy.
68
- resource "aws_iam_role_policy_attachment" "github_actions_admin" {
76
+ resource "aws_iam_role" "github_actions_preview" {
77
+ count = terraform.workspace == "default" ? 1 : 0
78
+ name = "{{PREVIEW_ROLE_NAME}}"
79
+
80
+ assume_role_policy = jsonencode({
81
+ Version = "2012-10-17"
82
+ Statement = [
83
+ {
84
+ Action = "sts:AssumeRoleWithWebIdentity"
85
+ Effect = "Allow"
86
+ Principal = {
87
+ Federated = local.github_provider_arn
88
+ }
89
+ Condition = {
90
+ StringLike = {
91
+ # Same scoping as the deploy role, bound to pull request events
92
+ # instead of the deploy branch.
93
+ "token.actions.githubusercontent.com:sub" : {{GITHUB_PREVIEW_SUB}}
94
+ }
95
+ StringEquals = {
96
+ "token.actions.githubusercontent.com:aud" : "sts.amazonaws.com"
97
+ }
98
+ }
99
+ },
100
+ ]
101
+ })
102
+ }
103
+
104
+ # Least-privilege baselines for the CI/CD pipeline: full service power
105
+ # without standing AdministratorAccess. Guardrail policies below carve out
106
+ # the audit planes (deploy) and production data + compute (preview).
107
+ resource "aws_iam_role_policy_attachment" "deploy_poweruser" {
69
108
  count = terraform.workspace == "default" ? 1 : 0
70
- role = aws_iam_role.github_actions[0].name
71
- policy_arn = "arn:aws:iam::aws:policy/AdministratorAccess"
109
+ role = aws_iam_role.github_actions_deploy[0].name
110
+ policy_arn = "arn:aws:iam::aws:policy/PowerUserAccess"
111
+ }
112
+
113
+ resource "aws_iam_role_policy_attachment" "deploy_iam_full" {
114
+ count = terraform.workspace == "default" ? 1 : 0
115
+ role = aws_iam_role.github_actions_deploy[0].name
116
+ policy_arn = "arn:aws:iam::aws:policy/IAMFullAccess"
117
+ }
118
+
119
+ resource "aws_iam_role_policy_attachment" "preview_poweruser" {
120
+ count = terraform.workspace == "default" ? 1 : 0
121
+ role = aws_iam_role.github_actions_preview[0].name
122
+ policy_arn = "arn:aws:iam::aws:policy/PowerUserAccess"
123
+ }
124
+
125
+ resource "aws_iam_role_policy_attachment" "preview_iam_full" {
126
+ count = terraform.workspace == "default" ? 1 : 0
127
+ role = aws_iam_role.github_actions_preview[0].name
128
+ policy_arn = "arn:aws:iam::aws:policy/IAMFullAccess"
129
+ }
130
+
131
+ # Deploy boundary: even the deploy role cannot touch the audit and billing
132
+ # planes or delete the state bucket backing every workspace.
133
+ resource "aws_iam_role_policy" "deploy_boundary" {
134
+ count = terraform.workspace == "default" ? 1 : 0
135
+ name = "${local.prod_prefix}-deploy-boundary"
136
+ role = aws_iam_role.github_actions_deploy[0].id
137
+
138
+ policy = jsonencode({
139
+ Version = "2012-10-17"
140
+ Statement = [
141
+ {
142
+ Sid = "DenyAuditBillingPlanes"
143
+ Effect = "Deny"
144
+ Action = ["cloudtrail:*", "organizations:*", "aws-portal:*", "billing:*"]
145
+ Resource = "*"
146
+ },
147
+ {
148
+ Sid = "DenyStateBucketDeletion"
149
+ Effect = "Deny"
150
+ Action = ["s3:DeleteBucket"]
151
+ Resource = ["arn:aws:s3:::{{STATE_BUCKET}}"]
152
+ },
153
+ ]
154
+ })
155
+ }
156
+
157
+ # Preview guardrails: PR-triggered runs (preview/teardown/plan) keep full
158
+ # build power but cannot destroy production data, mint compute, or open
159
+ # IAM backdoors. Every Resource below names an exact production ARN —
160
+ # never a wildcard — so pr-suffixed preview resources keep working.
161
+ resource "aws_iam_role_policy" "preview_guardrails" {
162
+ count = terraform.workspace == "default" ? 1 : 0
163
+ name = "${local.prod_prefix}-preview-guardrails"
164
+ role = aws_iam_role.github_actions_preview[0].id
165
+
166
+ policy = jsonencode({
167
+ Version = "2012-10-17"
168
+ Statement = [
169
+ {
170
+ Sid = "DenyComputeAbuse"
171
+ Effect = "Deny"
172
+ Action = ["ec2:RunInstances"]
173
+ Resource = "*"
174
+ },
175
+ {
176
+ Sid = "DenyIAMBackdoors"
177
+ Effect = "Deny"
178
+ Action = ["iam:CreateUser", "iam:CreateAccessKey"]
179
+ Resource = "*"
180
+ },
181
+ {
182
+ Sid = "DenySnapshotSharing"
183
+ Effect = "Deny"
184
+ Action = ["rds:ModifyDBSnapshotAttribute"]
185
+ Resource = "*"
186
+ },
187
+ {
188
+ Sid = "DenyProdStateDestruction"
189
+ Effect = "Deny"
190
+ Action = ["s3:DeleteBucket", "s3:DeleteObjectVersion"]
191
+ Resource = [
192
+ "arn:aws:s3:::{{STATE_BUCKET}}",
193
+ "arn:aws:s3:::{{STATE_BUCKET}}/*",
194
+ ]
195
+ },
196
+ {
197
+ Sid = "DenyProdECSShutdown"
198
+ Effect = "Deny"
199
+ Action = ["ecs:UpdateService", "ecs:DeleteService", "ecs:DeleteCluster"]
200
+ Resource = [
201
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster/${local.prod_prefix}-cluster",
202
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:service/${local.prod_prefix}-cluster/${local.prod_prefix}-service",
203
+ "arn:aws:ecs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:service/${local.prod_prefix}-service",
204
+ ]
205
+ },
206
+ {
207
+ Sid = "DenyProdImageDeletion"
208
+ Effect = "Deny"
209
+ Action = ["ecr:BatchDeleteImage"]
210
+ Resource = [
211
+ "arn:aws:ecr:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:repository/${local.prod_prefix}-repo",
212
+ ]
213
+ },
214
+ {
215
+ Sid = "DenyProdLambdaRewrite"
216
+ Effect = "Deny"
217
+ Action = ["lambda:UpdateFunctionCode", "lambda:DeleteFunction"]
218
+ Resource = [
219
+ "arn:aws:lambda:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:function:${local.prod_prefix}-fn",
220
+ ]
221
+ },
222
+ {
223
+ Sid = "DenyProdQueueDestruction"
224
+ Effect = "Deny"
225
+ Action = ["sqs:PurgeQueue", "sqs:DeleteQueue"]
226
+ Resource = [
227
+ "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${local.prod_prefix}-queue",
228
+ "arn:aws:sqs:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:${local.prod_prefix}-dlq",
229
+ ]
230
+ },
231
+ {
232
+ Sid = "DenyProdDatabaseDestruction"
233
+ Effect = "Deny"
234
+ Action = ["rds:DeleteDBInstance", "rds:ModifyDBInstance"]
235
+ Resource = [
236
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:db:${local.prod_prefix}-db",
237
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:db:${local.prod_prefix}-db-instance-1",
238
+ ]
239
+ },
240
+ {
241
+ Sid = "DenyProdAuroraDestruction"
242
+ Effect = "Deny"
243
+ Action = ["rds:DeleteDBCluster", "rds:ModifyDBCluster"]
244
+ Resource = [
245
+ "arn:aws:rds:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:cluster:${local.prod_prefix}-db-cluster",
246
+ ]
247
+ },
248
+ {
249
+ Sid = "DenyProdTableDeletion"
250
+ Effect = "Deny"
251
+ Action = ["dynamodb:DeleteTable"]
252
+ Resource = [
253
+ "arn:aws:dynamodb:${data.aws_region.current.name}:${data.aws_caller_identity.current.account_id}:table/${local.prod_prefix}-table",
254
+ ]
255
+ },
256
+ ]
257
+ })
72
258
  }
@@ -23,8 +23,6 @@ locals {
23
23
  app_name = "{{PROJECT_NAME}}${local.env_suffix}${local.grada_resource_suffix}"
24
24
  }
25
25
 
26
- data "aws_caller_identity" "current" {}
27
-
28
26
  # --- Static site bucket (private; CloudFront reads via OAC) ---
29
27
  # NOTE: the bucket name embeds the AWS account ID so CI can reconstruct it
30
28
  # without terraform outputs: {{PROJECT_NAME}}-site-{{AWS_ACCOUNT_ID}}.