grada-run 0.46.0 → 0.48.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/README.md +3 -2
- package/package.json +1 -1
- package/src/commands/drift.js +8 -12
- package/src/commands/init.js +78 -2
- package/src/core/parser.js +1 -0
- package/src/utils/backup.js +3 -3
- package/src/utils/ci-workflows.js +38 -0
- package/src/utils/reconcile.js +5 -3
- package/src/utils/resolvers.js +21 -9
- package/templates/github/deploy-lambda.yml +2 -2
- package/templates/github/deploy-static.yml +2 -2
- package/templates/github/deploy.yml +2 -2
- package/templates/github/plan.yml +153 -0
- package/templates/github/preview-lambda.yml +3 -3
- package/templates/github/preview.yml +3 -3
- package/templates/github/teardown.yml +2 -2
- package/templates/terraform/addons/redis.tf +22 -0
- package/templates/terraform/addons/s3.tf +22 -2
- package/templates/terraform/oidc.tf +204 -18
- package/templates/terraform/static/main.tf +0 -2
package/README.md
CHANGED
|
@@ -116,7 +116,7 @@ The interactive wizard will analyze your codebase, detect your framework, estima
|
|
|
116
116
|
| [`domain`](./apps/docs/src/content/docs/cli/domain.md) | Attaches a custom domain with automated ACM TLS (Route 53 or external DNS). |
|
|
117
117
|
| [`destroy`](./apps/docs/src/content/docs/cli/destroy.md) | Tears down AWS resources to stop billing (state bucket optionally retained). |
|
|
118
118
|
| [`eject`](./apps/docs/src/content/docs/cli/eject.md) | Strips `grada` metadata, leaving pure Terraform and Actions files. |
|
|
119
|
-
| [`--headless`](./apps/docs/src/content/docs/guides/headless.md) | Fully programmatic runs for CI/CD (`--target`, `--with`, `--db-engine`, `--setup-ci-migrate`, `--setup-ci-drift`, `--offline`). |
|
|
119
|
+
| [`--headless`](./apps/docs/src/content/docs/guides/headless.md) | Fully programmatic runs for CI/CD (`--target`, `--with`, `--db-engine`, `--setup-ci-migrate`, `--setup-ci-drift`, `--setup-ci-plan`, `--offline`). |
|
|
120
120
|
| [`sync-ai`](./apps/docs/src/content/docs/cli/sync-ai.md) | Generates IDE assistant rules for your stack (Cursor, Copilot, Windsurf, Claude). |
|
|
121
121
|
| [`mcp`](./apps/docs/src/content/docs/cli/mcp.md) | Serves the MCP server for AI agents (STDIO/HTTP) or installs editor config (`--install`). |
|
|
122
122
|
|
|
@@ -134,7 +134,8 @@ your-project/
|
|
|
134
134
|
├── .github/
|
|
135
135
|
│ └── workflows/
|
|
136
136
|
│ ├── deploy.yml # Keyless OIDC CI/CD deployment pipeline
|
|
137
|
-
│
|
|
137
|
+
│ ├── drift.yml # Scheduled IaC drift detection (opt-in via `--setup-ci-drift` or `drift --setup`)
|
|
138
|
+
│ └── plan.yml # Terraform plan comments on PRs (via `--setup-ci-plan`, on by default interactively)
|
|
138
139
|
└── terraform/
|
|
139
140
|
├── main.tf # ECR repository + compute (ECS Cluster/Fargate Task, Lambda + API Gateway with `--target lambda`, or S3 + CloudFront with `--target static`)
|
|
140
141
|
├── network.tf # VPC, Public Subnets, ALB, and Security Groups
|
package/package.json
CHANGED
package/src/commands/drift.js
CHANGED
|
@@ -8,7 +8,7 @@ import { trackSuccess, setActiveCommandName, resetActiveCommandName } from '../c
|
|
|
8
8
|
import { failCommand, failAwsError, failProjectNotInitialized, isProgrammaticCall, refuseUnknownFlags } from '../utils/command.js';
|
|
9
9
|
import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
|
|
10
10
|
import { resolveRegion, resolveProjectName, resolveCwd, readFileSafe } from '../utils/resolvers.js';
|
|
11
|
-
import {
|
|
11
|
+
import { renderCiWorkflow } from '../utils/ci-workflows.js';
|
|
12
12
|
|
|
13
13
|
const __filename = fileURLToPath(import.meta.url);
|
|
14
14
|
const __dirname = path.dirname(__filename);
|
|
@@ -44,17 +44,13 @@ export function extractRoleArn(deployYmlContent) {
|
|
|
44
44
|
// Renders `templates/github/drift.yml` into the project. Shared by
|
|
45
45
|
// `drift --setup` and `--setup-ci-drift`; never exits, never tracks.
|
|
46
46
|
export function scaffoldDriftWorkflow(cwd = process.cwd(), { region, roleArn, force = false } = {}) {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
}
|
|
55
|
-
fsSync.mkdirSync(path.dirname(targetPath), { recursive: true });
|
|
56
|
-
atomicWriteFileSync(targetPath, rendered, 'utf8');
|
|
57
|
-
return { ok: true, path: targetPath };
|
|
47
|
+
return renderCiWorkflow({
|
|
48
|
+
templatePath: DRIFT_TEMPLATE_PATH,
|
|
49
|
+
region,
|
|
50
|
+
roleArn,
|
|
51
|
+
targetPath: path.join(cwd, DRIFT_WORKFLOW_FILE),
|
|
52
|
+
force,
|
|
53
|
+
});
|
|
58
54
|
}
|
|
59
55
|
|
|
60
56
|
// Condenses `terraform plan` output to the resource-change lines plus the
|
package/src/commands/init.js
CHANGED
|
@@ -27,6 +27,7 @@ import { ADDON_REGISTRY, addonTargetDisposition, addonSupportedTargets } from '.
|
|
|
27
27
|
import { validateAddonFlags, resolveAddonOptions, scaffoldAddon, DEFAULT_BEDROCK_MODEL } from './add.js';
|
|
28
28
|
import { injectMigrationGate, injectPreviewMigrationGate } from './db/migrate.js';
|
|
29
29
|
import { scaffoldDriftWorkflow } from './drift.js';
|
|
30
|
+
import { scaffoldPlanWorkflow } from '../utils/ci-workflows.js';
|
|
30
31
|
import { trackEvent, flushTelemetry, getCliVersion, setActiveCommandName, resetActiveCommandName } from '../core/telemetry.js';
|
|
31
32
|
import { failCommand } from '../utils/command.js';
|
|
32
33
|
import { getFrameworkWarning } from '../utils/warnings.js';
|
|
@@ -113,6 +114,47 @@ export function renderOidcSubClaim(sub) {
|
|
|
113
114
|
return `["${sub}", "${companion}"]`;
|
|
114
115
|
}
|
|
115
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
|
+
|
|
116
158
|
// Classifies an existing tree's OIDC claim for re-init: a bare string (or
|
|
117
159
|
// single-entry list, IAM-identical) renders verbatim; our own canonical
|
|
118
160
|
// dual-format pair resolves back to its classic entry so re-init stays
|
|
@@ -609,6 +651,21 @@ async function mainStackMain(input = {}) {
|
|
|
609
651
|
driftEnabled = driftAnswer === true;
|
|
610
652
|
}
|
|
611
653
|
|
|
654
|
+
// Plan-on-PR: explicit flag wins, else offer. Defaults ON —
|
|
655
|
+
// reviewing infra changes before merge is the safe default.
|
|
656
|
+
const setupCiPlanFlag = initOptions.setupCiPlan === true;
|
|
657
|
+
let planEnabled = false;
|
|
658
|
+
if (setupCiPlanFlag) {
|
|
659
|
+
planEnabled = true;
|
|
660
|
+
} else if (isInteractive) {
|
|
661
|
+
const planAnswer = await confirm({
|
|
662
|
+
message: 'Post Terraform plans as PR comments (review infra changes before merge)?',
|
|
663
|
+
initialValue: true,
|
|
664
|
+
});
|
|
665
|
+
if (typeof planAnswer === 'symbol') process.exit(0);
|
|
666
|
+
planEnabled = planAnswer === true;
|
|
667
|
+
}
|
|
668
|
+
|
|
612
669
|
// Addon selection: interactive multiselect, or explicit --with.
|
|
613
670
|
let selectedAddons;
|
|
614
671
|
if (isInteractive && !isStaticSite) {
|
|
@@ -852,6 +909,7 @@ async function mainStackMain(input = {}) {
|
|
|
852
909
|
|
|
853
910
|
// 7. Synthesize Templates
|
|
854
911
|
s.message('Synthesizing Terraform templates...');
|
|
912
|
+
const { deploySub, previewSub } = renderOidcRoleSubs(oidcTrustSub, config.branch);
|
|
855
913
|
const renderConfig = {
|
|
856
914
|
PROJECT_NAME: dirConfig.actualProjectName,
|
|
857
915
|
RESOURCE_SUFFIX: resourceSuffix,
|
|
@@ -866,7 +924,10 @@ async function mainStackMain(input = {}) {
|
|
|
866
924
|
HEALTH_CHECK_PATH: config.healthCheckPath,
|
|
867
925
|
DESIRED_COUNT: config.desiredCount,
|
|
868
926
|
DEPLOY_BRANCH: config.branch,
|
|
869
|
-
|
|
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,
|
|
870
931
|
BUILD_DIR: buildDir,
|
|
871
932
|
finalFramework: config.framework,
|
|
872
933
|
NEEDS_DATABASE: config.needsDatabase,
|
|
@@ -929,7 +990,7 @@ async function mainStackMain(input = {}) {
|
|
|
929
990
|
// Hand edits trip refuse-dirty before this point; --force regenerates.
|
|
930
991
|
const drifted = scaffoldDriftWorkflow(dirConfig.targetDir, {
|
|
931
992
|
region: config.region,
|
|
932
|
-
roleArn:
|
|
993
|
+
roleArn: buildRoleArn(awsAccountId, buildDeployRoleName(dirConfig.actualProjectName, resourceSuffix)),
|
|
933
994
|
force: initOptions.force,
|
|
934
995
|
});
|
|
935
996
|
if (drifted.ok) {
|
|
@@ -937,6 +998,20 @@ async function mainStackMain(input = {}) {
|
|
|
937
998
|
}
|
|
938
999
|
}
|
|
939
1000
|
|
|
1001
|
+
if (planEnabled) {
|
|
1002
|
+
// plan.yml rides the manifest + backup like drift.yml (R1):
|
|
1003
|
+
// re-init backs the old file up and regenerates fresh (current
|
|
1004
|
+
// role ARN) instead of silently keeping a stale copy.
|
|
1005
|
+
const planned = scaffoldPlanWorkflow(dirConfig.targetDir, {
|
|
1006
|
+
region: config.region,
|
|
1007
|
+
roleArn: buildRoleArn(awsAccountId, buildPreviewRoleName(dirConfig.actualProjectName, resourceSuffix)),
|
|
1008
|
+
force: initOptions.force,
|
|
1009
|
+
});
|
|
1010
|
+
if (planned.ok) {
|
|
1011
|
+
console.log(color.green('✅ Scaffolded .github/workflows/plan.yml (Terraform plan on PR)'));
|
|
1012
|
+
}
|
|
1013
|
+
}
|
|
1014
|
+
|
|
940
1015
|
// 7b2. Restore preserved files over the fresh output, then record
|
|
941
1016
|
// content hashes of everything generated above so a later re-run can
|
|
942
1017
|
// distinguish pristine output from hand edits (F3), plus the intended
|
|
@@ -989,6 +1064,7 @@ async function mainStackMain(input = {}) {
|
|
|
989
1064
|
detected_addons: Object.keys(ADDON_REGISTRY).filter((cap) => capabilities.addons[cap]?.detected === true),
|
|
990
1065
|
migration_gate_enabled: migrationGateEnabled,
|
|
991
1066
|
drift_detection_enabled: driftEnabled,
|
|
1067
|
+
plan_on_pr_enabled: planEnabled,
|
|
992
1068
|
});
|
|
993
1069
|
|
|
994
1070
|
s.stop('Infrastructure provisioned successfully!');
|
package/src/core/parser.js
CHANGED
|
@@ -141,6 +141,7 @@ export function parseCliArgs(processArgs) {
|
|
|
141
141
|
githubRepo: getValueFlag('github-repo'),
|
|
142
142
|
setupCiMigrate: getBoolOrValueFlag('setup-ci-migrate'),
|
|
143
143
|
setupCiDrift: getBoolFlag('setup-ci-drift') === true,
|
|
144
|
+
setupCiPlan: getBoolFlag('setup-ci-plan') === true,
|
|
144
145
|
};
|
|
145
146
|
|
|
146
147
|
// 5. Isolate positional commands (non-string elements are positionals;
|
package/src/utils/backup.js
CHANGED
|
@@ -33,7 +33,7 @@ function collectManifestFiles(targetDir) {
|
|
|
33
33
|
// hand edits like deploy.yml — manifest them so re-init refuses
|
|
34
34
|
// dirty trees and backs them up instead of silently overwriting or
|
|
35
35
|
// leaving them stale (BUG-158).
|
|
36
|
-
for (const rel of ['Dockerfile', 'preview.yml', 'teardown.yml', 'drift.yml'].map((name) => (
|
|
36
|
+
for (const rel of ['Dockerfile', 'preview.yml', 'teardown.yml', 'drift.yml', 'plan.yml'].map((name) => (
|
|
37
37
|
name === 'Dockerfile' ? name : path.join('.github', 'workflows', name)
|
|
38
38
|
))) {
|
|
39
39
|
if (fs.existsSync(path.join(targetDir, rel))) relPaths.push(rel);
|
|
@@ -226,7 +226,7 @@ export async function planExistingFiles(targetDir, { isHeadless = false, force =
|
|
|
226
226
|
const tfPath = path.join(targetDir, 'terraform');
|
|
227
227
|
const dockerfilePath = path.join(targetDir, 'Dockerfile');
|
|
228
228
|
const wfPath = path.join(targetDir, '.github', 'workflows', 'deploy.yml');
|
|
229
|
-
const extraWorkflows = ['preview.yml', 'teardown.yml', 'drift.yml']
|
|
229
|
+
const extraWorkflows = ['preview.yml', 'teardown.yml', 'drift.yml', 'plan.yml']
|
|
230
230
|
.map((workflow) => path.join('.github', 'workflows', workflow))
|
|
231
231
|
.filter((rel) => fs.existsSync(path.join(targetDir, rel)));
|
|
232
232
|
|
|
@@ -303,7 +303,7 @@ export async function executeBackup(targetDir, plan = {}) {
|
|
|
303
303
|
['terraform/', path.join(targetDir, 'terraform')],
|
|
304
304
|
['Dockerfile', path.join(targetDir, 'Dockerfile')],
|
|
305
305
|
['.github/workflows/deploy.yml', path.join(targetDir, '.github', 'workflows', 'deploy.yml')],
|
|
306
|
-
...['preview.yml', 'teardown.yml', 'drift.yml'].map((workflow) => {
|
|
306
|
+
...['preview.yml', 'teardown.yml', 'drift.yml', 'plan.yml'].map((workflow) => {
|
|
307
307
|
const rel = path.join('.github', 'workflows', workflow);
|
|
308
308
|
return [rel, path.join(targetDir, rel)];
|
|
309
309
|
}),
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import fsSync from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { fileURLToPath } from 'url';
|
|
4
|
+
import { atomicWriteFileSync } from './atomic-write.js';
|
|
5
|
+
|
|
6
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
7
|
+
const __dirname = path.dirname(__filename);
|
|
8
|
+
|
|
9
|
+
export const PLAN_TEMPLATE_PATH = path.join(__dirname, '../../templates/github/plan.yml');
|
|
10
|
+
export const PLAN_WORKFLOW_FILE = path.join('.github', 'workflows', 'plan.yml');
|
|
11
|
+
|
|
12
|
+
// Shared render-and-write core for generated CI workflows: substitutes
|
|
13
|
+
// the region + role ARN placeholders, refuses to overwrite without
|
|
14
|
+
// force, and writes atomically. Never exits, never tracks.
|
|
15
|
+
export function renderCiWorkflow({ templatePath, region, roleArn, targetPath, force = false } = {}) {
|
|
16
|
+
const template = fsSync.readFileSync(templatePath, 'utf8');
|
|
17
|
+
const rendered = template
|
|
18
|
+
.replaceAll('{{REGION}}', region)
|
|
19
|
+
.replaceAll('{{ROLE_ARN}}', roleArn);
|
|
20
|
+
if (fsSync.existsSync(targetPath) && force !== true && force !== 'true') {
|
|
21
|
+
return { ok: false, reason: 'exists', path: targetPath };
|
|
22
|
+
}
|
|
23
|
+
fsSync.mkdirSync(path.dirname(targetPath), { recursive: true });
|
|
24
|
+
atomicWriteFileSync(targetPath, rendered, 'utf8');
|
|
25
|
+
return { ok: true, path: targetPath };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Renders `templates/github/plan.yml` into the project. Used by init's
|
|
29
|
+
// `--setup-ci-plan`; never exits, never tracks.
|
|
30
|
+
export function scaffoldPlanWorkflow(cwd = process.cwd(), { region, roleArn, force = false } = {}) {
|
|
31
|
+
return renderCiWorkflow({
|
|
32
|
+
templatePath: PLAN_TEMPLATE_PATH,
|
|
33
|
+
region,
|
|
34
|
+
roleArn,
|
|
35
|
+
targetPath: path.join(cwd, PLAN_WORKFLOW_FILE),
|
|
36
|
+
force,
|
|
37
|
+
});
|
|
38
|
+
}
|
package/src/utils/reconcile.js
CHANGED
|
@@ -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
|
|
6
|
-
// role-to-assume ARN in
|
|
7
|
-
// rewriting lives in apply's
|
|
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'));
|
package/src/utils/resolvers.js
CHANGED
|
@@ -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
|
-
|
|
141
|
-
if
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
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
|
-
|
|
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
|
|
@@ -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/{{
|
|
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/{{
|
|
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/{{
|
|
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/{{
|
|
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/{{
|
|
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/{{
|
|
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 ---
|
|
@@ -0,0 +1,153 @@
|
|
|
1
|
+
name: Terraform Plan on PR
|
|
2
|
+
|
|
3
|
+
on:
|
|
4
|
+
# pull_request_target (not pull_request): this file comes from the base
|
|
5
|
+
# branch, so a fork PR cannot delete the same-repo guard below to reach
|
|
6
|
+
# the privileged CI roles (BUG-140). The PR head is checked out explicitly by
|
|
7
|
+
# SHA in the guarded step instead.
|
|
8
|
+
pull_request_target:
|
|
9
|
+
types: [opened, synchronize, reopened]
|
|
10
|
+
paths:
|
|
11
|
+
- 'terraform/**'
|
|
12
|
+
|
|
13
|
+
# One runner per PR: rapid pushes cancel superseded plans instead of
|
|
14
|
+
# overlapping runs on the same state.
|
|
15
|
+
concurrency:
|
|
16
|
+
group: plan-${{ github.event.pull_request.number }}
|
|
17
|
+
cancel-in-progress: true
|
|
18
|
+
|
|
19
|
+
env:
|
|
20
|
+
AWS_REGION: {{REGION}}
|
|
21
|
+
|
|
22
|
+
permissions:
|
|
23
|
+
id-token: write
|
|
24
|
+
contents: read
|
|
25
|
+
pull-requests: write # Required to post the plan comment
|
|
26
|
+
|
|
27
|
+
jobs:
|
|
28
|
+
terraform-plan:
|
|
29
|
+
name: Terraform Plan
|
|
30
|
+
# Same-repo PRs only: fork code must never execute with the admin CI
|
|
31
|
+
# role. Trustworthy because this file comes from base (see trigger
|
|
32
|
+
# above). Public repos needing fork plans should gate this job
|
|
33
|
+
# behind an environment with required reviewers instead of deleting
|
|
34
|
+
# the guard.
|
|
35
|
+
if: github.event.pull_request.head.repo.full_name == github.repository
|
|
36
|
+
runs-on: ubuntu-latest
|
|
37
|
+
timeout-minutes: 30
|
|
38
|
+
|
|
39
|
+
steps:
|
|
40
|
+
- name: Checkout PR head
|
|
41
|
+
uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
|
|
42
|
+
with:
|
|
43
|
+
# Pinned SHA (not a ref name): the exact head this event fired
|
|
44
|
+
# for, immune to ref moves between event and checkout.
|
|
45
|
+
ref: ${{ github.event.pull_request.head.sha }}
|
|
46
|
+
|
|
47
|
+
- name: Configure AWS credentials
|
|
48
|
+
id: aws-creds
|
|
49
|
+
uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
|
|
50
|
+
continue-on-error: true
|
|
51
|
+
with:
|
|
52
|
+
role-to-assume: {{ROLE_ARN}}
|
|
53
|
+
aws-region: ${{ env.AWS_REGION }}
|
|
54
|
+
|
|
55
|
+
# Plan-on-PR is a merge signal: a failed assume fails the run with
|
|
56
|
+
# the bootstrap pointer (deploy shape, BUG-138) — never green-silent.
|
|
57
|
+
- name: Interpret credential failure
|
|
58
|
+
if: steps.aws-creds.outcome == 'failure'
|
|
59
|
+
run: |
|
|
60
|
+
echo "::error::AWS credential assumption failed — if the stack was never provisioned, bootstrap it first (npx grada-run apply); otherwise check terraform/oidc.tf trust."
|
|
61
|
+
exit 1
|
|
62
|
+
|
|
63
|
+
- name: Setup Terraform
|
|
64
|
+
uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3
|
|
65
|
+
with:
|
|
66
|
+
# The wrapper mangles -detailed-exitcode; raw codes (0/1/2) are the signal.
|
|
67
|
+
terraform_wrapper: false
|
|
68
|
+
|
|
69
|
+
- name: Terraform Init
|
|
70
|
+
working-directory: ./terraform
|
|
71
|
+
run: terraform init -input=false
|
|
72
|
+
|
|
73
|
+
# -detailed-exitcode: 0 = no changes, 1 = error, 2 = changes present.
|
|
74
|
+
# Exit 2 posts the plan and stays green — the comment is the signal.
|
|
75
|
+
# Exit 1 (plan ERROR) fails the job after the comment posts below.
|
|
76
|
+
- name: Terraform Plan
|
|
77
|
+
id: plan
|
|
78
|
+
working-directory: ./terraform
|
|
79
|
+
run: |
|
|
80
|
+
set +e
|
|
81
|
+
terraform plan -input=false -lock-timeout=5m -detailed-exitcode -no-color -out=tfplan > plan-full.txt 2>&1
|
|
82
|
+
EXITCODE=$?
|
|
83
|
+
echo "exitcode=$EXITCODE" >> "$GITHUB_OUTPUT"
|
|
84
|
+
if [ "$EXITCODE" != "1" ]; then
|
|
85
|
+
terraform show -no-color tfplan > plan.txt
|
|
86
|
+
else
|
|
87
|
+
cp plan-full.txt plan.txt
|
|
88
|
+
fi
|
|
89
|
+
# Exit 1 fails the job; the comment step still posts via its
|
|
90
|
+
# always() gate so the error lands on the PR, not just the log.
|
|
91
|
+
if [ "$EXITCODE" = "1" ]; then exit 1; fi
|
|
92
|
+
|
|
93
|
+
- name: Comment plan on PR
|
|
94
|
+
if: always() && steps.plan.outputs.exitcode != ''
|
|
95
|
+
uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
|
|
96
|
+
with:
|
|
97
|
+
script: |
|
|
98
|
+
const fs = require('fs');
|
|
99
|
+
const { owner, repo } = context.repo;
|
|
100
|
+
const marker = '<!-- grada-plan -->';
|
|
101
|
+
const exitcode = '${{ steps.plan.outputs.exitcode }}';
|
|
102
|
+
const runUrl = `https://github.com/${owner}/${repo}/actions/runs/${context.runId}`;
|
|
103
|
+
let plan = '';
|
|
104
|
+
try {
|
|
105
|
+
plan = fs.readFileSync('terraform/plan.txt', 'utf8');
|
|
106
|
+
} catch (error) {
|
|
107
|
+
plan = '(plan output unavailable)';
|
|
108
|
+
}
|
|
109
|
+
if (plan.length > 30000) {
|
|
110
|
+
plan = `${plan.slice(0, 30000)}\n... (truncated, see ${runUrl})`;
|
|
111
|
+
}
|
|
112
|
+
let summary = '';
|
|
113
|
+
if (exitcode === '2') {
|
|
114
|
+
const match = /^Plan:.*$/m.exec(plan);
|
|
115
|
+
summary = match ? match[0] : 'Plan: changes present';
|
|
116
|
+
} else if (exitcode === '1') {
|
|
117
|
+
summary = 'Plan: errored';
|
|
118
|
+
} else {
|
|
119
|
+
summary = 'No changes';
|
|
120
|
+
}
|
|
121
|
+
const heading = exitcode === '1' ? '## ❌ Terraform Plan Failed' : '## Terraform Plan';
|
|
122
|
+
const body = `${marker}\n${heading}\n\n**${summary}** ([workflow run](${runUrl})).\n\n<details><summary>Show Plan</summary>\n\n\`\`\`diff\n${plan}\n\`\`\`\n\n</details>`;
|
|
123
|
+
const { data: comments } = await github.rest.issues.listComments({
|
|
124
|
+
issue_number: context.issue.number,
|
|
125
|
+
owner: context.repo.owner,
|
|
126
|
+
repo: context.repo.repo,
|
|
127
|
+
});
|
|
128
|
+
const existing = comments.find((comment) => comment.body?.includes(marker));
|
|
129
|
+
if (existing) {
|
|
130
|
+
await github.rest.issues.updateComment({
|
|
131
|
+
owner: context.repo.owner,
|
|
132
|
+
repo: context.repo.repo,
|
|
133
|
+
comment_id: existing.id,
|
|
134
|
+
body,
|
|
135
|
+
});
|
|
136
|
+
} else {
|
|
137
|
+
await github.rest.issues.createComment({
|
|
138
|
+
issue_number: context.issue.number,
|
|
139
|
+
owner: context.repo.owner,
|
|
140
|
+
repo: context.repo.repo,
|
|
141
|
+
body,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
# Fork PRs skip the privileged job above loudly instead of silently:
|
|
146
|
+
# no credentials are issued and no plan is posted.
|
|
147
|
+
fork-notice:
|
|
148
|
+
name: Fork PR notice
|
|
149
|
+
if: github.event.pull_request.head.repo.full_name != github.repository
|
|
150
|
+
runs-on: ubuntu-latest
|
|
151
|
+
timeout-minutes: 5
|
|
152
|
+
steps:
|
|
153
|
+
- run: echo "Terraform plan runs for same-repo pull requests only — fork PR #${{ github.event.pull_request.number }} skipped (no AWS credentials issued)."
|
|
@@ -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
|
|
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/{{
|
|
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/{{
|
|
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
|
|
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/{{
|
|
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/{{
|
|
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/{{
|
|
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/{{
|
|
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
|
+
}
|
|
@@ -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
|
-
#
|
|
32
|
-
|
|
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 = "{{
|
|
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
|
|
49
|
-
# Actions can assume this role —
|
|
50
|
-
# Scoped trusts render both
|
|
51
|
-
# `repo:<owner>/<name
|
|
52
|
-
#
|
|
53
|
-
# (repos created after 2026-07-15).
|
|
54
|
-
"token.actions.githubusercontent.com: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
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
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.
|
|
71
|
-
policy_arn = "arn:aws:iam::aws:policy/
|
|
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}}.
|