grada-run 0.42.0 → 0.43.1

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.
Files changed (63) hide show
  1. package/bin/cli.js +1 -1
  2. package/package.json +1 -1
  3. package/src/commands/add.js +93 -11
  4. package/src/commands/alerts.js +66 -30
  5. package/src/commands/apply.js +65 -10
  6. package/src/commands/db/backup.js +1 -2
  7. package/src/commands/db/connect.js +10 -4
  8. package/src/commands/db/enable-vector.js +19 -6
  9. package/src/commands/db/import.js +114 -22
  10. package/src/commands/db/migrate.js +82 -74
  11. package/src/commands/db/restore.js +38 -6
  12. package/src/commands/destroy.js +20 -3
  13. package/src/commands/diagnose.js +40 -21
  14. package/src/commands/doctor.js +27 -2
  15. package/src/commands/domain.js +20 -2
  16. package/src/commands/drift.js +2 -1
  17. package/src/commands/eject.js +13 -2
  18. package/src/commands/gc.js +100 -3
  19. package/src/commands/init.js +75 -9
  20. package/src/commands/logs.js +3 -1
  21. package/src/commands/mcp.js +2 -1
  22. package/src/commands/rollback.js +54 -5
  23. package/src/commands/secrets.js +260 -64
  24. package/src/commands/status.js +4 -1
  25. package/src/commands/sync-ai.js +4 -3
  26. package/src/commands/wake.js +45 -1
  27. package/src/data/action-pins.js +26 -0
  28. package/src/utils/addons.js +9 -6
  29. package/src/utils/ai-rules.js +3 -2
  30. package/src/utils/backup.js +16 -2
  31. package/src/utils/command.js +20 -0
  32. package/src/utils/db-tunnel.js +15 -5
  33. package/src/utils/detector.js +8 -0
  34. package/src/utils/ecs-runner.js +16 -3
  35. package/src/utils/frameworks.js +14 -2
  36. package/src/utils/generator.js +21 -13
  37. package/src/utils/prompts.js +20 -4
  38. package/src/utils/resolvers.js +9 -7
  39. package/src/utils/revision-discovery.js +19 -7
  40. package/templates/docker/django.Dockerfile +2 -2
  41. package/templates/docker/go.Dockerfile +2 -2
  42. package/templates/docker/nestjs.Dockerfile +2 -2
  43. package/templates/docker/nextjs.Dockerfile +3 -3
  44. package/templates/docker/node.Dockerfile +2 -2
  45. package/templates/docker/nuxt.Dockerfile +2 -2
  46. package/templates/docker/python.Dockerfile +2 -2
  47. package/templates/docker/rails.Dockerfile +2 -2
  48. package/templates/docker/static.Dockerfile +2 -2
  49. package/templates/docker/svelte.Dockerfile +2 -2
  50. package/templates/github/deploy-lambda.yml +55 -12
  51. package/templates/github/deploy-static.yml +24 -6
  52. package/templates/github/deploy.yml +96 -13
  53. package/templates/github/drift.yml +68 -5
  54. package/templates/github/preview-lambda.yml +137 -13
  55. package/templates/github/preview.yml +135 -13
  56. package/templates/github/teardown.yml +71 -12
  57. package/templates/terraform/addons/s3.tf +35 -0
  58. package/templates/terraform/backend.tf +7 -0
  59. package/templates/terraform/database-mysql.tf +9 -1
  60. package/templates/terraform/database.tf +9 -1
  61. package/templates/terraform/oidc.tf +3 -2
  62. package/templates/terraform/secrets.tf +6 -4
  63. package/templates/terraform/worker.tf +7 -0
@@ -1,12 +1,17 @@
1
1
  name: Ephemeral PR Preview
2
2
 
3
3
  on:
4
- pull_request:
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 admin CI role (BUG-140). The PR head is checked out explicitly by
7
+ # SHA in the guarded step instead.
8
+ pull_request_target:
5
9
  types: [opened, synchronize, reopened]
6
10
 
7
11
  # One runner per PR: rapid pushes cancel superseded previews instead of
8
- # overlapping applies on the same workspace. Shares its group with
9
- # teardown.yml, which queues (never cancels) behind an in-flight deploy.
12
+ # overlapping applies on the same workspace. Teardown runs in its own
13
+ # group (a reopen must never cancel an in-flight destroy); the state
14
+ # lock serializes the destroy/apply race instead (see -lock-timeout).
10
15
  concurrency:
11
16
  group: preview-${{ github.event.pull_request.number }}
12
17
  cancel-in-progress: true
@@ -15,6 +20,7 @@ env:
15
20
  AWS_REGION: {{REGION}}
16
21
  ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo
17
22
  WORKSPACE: pr-${{ github.event.pull_request.number }}
23
+ CF_COMMENT: {{PROJECT_NAME}}-pr-${{ github.event.pull_request.number }}{{RESOURCE_SUFFIX}}-cdn
18
24
 
19
25
  permissions:
20
26
  id-token: write
@@ -24,23 +30,48 @@ permissions:
24
30
  jobs:
25
31
  deploy-preview:
26
32
  name: Provision Preview Environment
33
+ # Same-repo PRs only: fork code must never execute with the admin CI
34
+ # role or production secrets. Trustworthy because this file comes from
35
+ # base (see trigger above). Public repos needing fork previews should
36
+ # gate this job behind an environment with required reviewers instead
37
+ # of deleting the guard.
38
+ if: github.event.pull_request.head.repo.full_name == github.repository
27
39
  runs-on: ubuntu-latest
40
+ timeout-minutes: 45
28
41
 
29
42
  steps:
30
- - name: Checkout Code
31
- uses: actions/checkout@v4
43
+ - name: Checkout PR head
44
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
45
+ with:
46
+ # Pinned SHA (not a ref name): the exact head this event fired
47
+ # for, immune to ref moves between event and checkout.
48
+ ref: ${{ github.event.pull_request.head.sha }}
32
49
 
33
50
  - name: Configure AWS credentials
34
- uses: aws-actions/configure-aws-credentials@v4
51
+ id: aws-creds
52
+ uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
53
+ continue-on-error: true
35
54
  with:
36
55
  role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
37
56
  aws-region: ${{ env.AWS_REGION }}
38
57
 
58
+ # STS denies a missing role and a trust mismatch with the same
59
+ # message, so the API won't support distinguishing them: every
60
+ # assume failure skips loud (green) with both cases + pointers
61
+ # named (BUG-199).
62
+ - name: Interpret credential failure
63
+ if: steps.aws-creds.outcome == 'failure'
64
+ run: |
65
+ ROLE_ARN="arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role"
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
+
39
68
  - name: Login to Amazon ECR
69
+ if: steps.aws-creds.outcome == 'success'
40
70
  id: login-ecr
41
- uses: aws-actions/amazon-ecr-login@v2
71
+ uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2
42
72
 
43
73
  - name: Build and Push Docker image
74
+ if: steps.aws-creds.outcome == 'success'
44
75
  env:
45
76
  ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
46
77
  run: |
@@ -49,18 +80,22 @@ jobs:
49
80
  docker push $ECR_REGISTRY/$ECR_REPOSITORY:${{ env.WORKSPACE }}
50
81
 
51
82
  - name: Setup Terraform
52
- uses: hashicorp/setup-terraform@v3
83
+ uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3
53
84
 
54
85
  - name: Terraform Init & Apply
55
86
  id: tf-apply
87
+ if: steps.aws-creds.outcome == 'success'
56
88
  working-directory: ./terraform
57
89
  run: |
58
90
  terraform init -input=false
59
91
  # Create or select the workspace specific to this PR
60
92
  terraform workspace select -or-create ${{ env.WORKSPACE }}
61
- terraform apply -auto-approve
93
+ # Teardown runs in its own group (see teardown.yml): a reopen
94
+ # during teardown waits on the state lock instead of racing it.
95
+ terraform apply -auto-approve -input=false -lock-timeout=10m
62
96
 
63
97
  - name: Deploy PR image to the preview function
98
+ if: steps.aws-creds.outcome == 'success'
64
99
  env:
65
100
  ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
66
101
  run: |
@@ -76,18 +111,107 @@ jobs:
76
111
  --region ${{ env.AWS_REGION }}
77
112
 
78
113
  - name: Read preview URL
114
+ if: steps.aws-creds.outcome == 'success'
79
115
  working-directory: ./terraform
80
116
  run: |
81
117
  API_URL=$(terraform output -raw api_gateway_url)
82
118
  echo "PREVIEW_URL=$API_URL" >> $GITHUB_ENV
83
119
 
120
+ # Every push redeploys the preview: clear its CDN so new HTML shows
121
+ # immediately instead of serving stale pages until TTL expiry.
122
+ - name: Invalidate CloudFront
123
+ if: steps.aws-creds.outcome == 'success'
124
+ run: |
125
+ DIST_ID=$(aws cloudfront list-distributions \
126
+ --query "DistributionList.Items[?Comment=='${{ env.CF_COMMENT }}'].Id | [0]" \
127
+ --output text \
128
+ --region ${{ env.AWS_REGION }})
129
+ if [ -z "$DIST_ID" ] || [ "$DIST_ID" = "None" ]; then
130
+ echo "CloudFront distribution '${{ env.CF_COMMENT }}' not found." >&2
131
+ exit 1
132
+ fi
133
+ aws cloudfront create-invalidation \
134
+ --distribution-id "$DIST_ID" \
135
+ --paths "/*" \
136
+ --region ${{ env.AWS_REGION }}
137
+
138
+ # One sticky comment per PR (updated in place), never a new
139
+ # comment per push — and a failed run overwrites the green URL
140
+ # instead of leaving it standing as truth (BUG-190).
84
141
  - name: Comment PR
85
- uses: actions/github-script@v7
142
+ if: steps.aws-creds.outcome == 'success'
143
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
86
144
  with:
87
145
  script: |
88
- github.rest.issues.createComment({
146
+ const marker = '<!-- grada-preview -->';
147
+ const body = `${marker}\n🚀 **Preview Environment Deployed!**\n\nYour ephemeral AWS Lambda environment is live at:\n[${process.env.PREVIEW_URL}](${process.env.PREVIEW_URL})\n\n_This environment will be automatically destroyed when the PR is merged or closed._\n\n---\n<div align="right"><sup>☁️ Generated by <a href="https://github.com/grada-run/grada">Grada</a></sup></div>`;
148
+ const { data: comments } = await github.rest.issues.listComments({
89
149
  issue_number: context.issue.number,
90
150
  owner: context.repo.owner,
91
151
  repo: context.repo.repo,
92
- body: `🚀 **Preview Environment Deployed!**\n\nYour ephemeral AWS Lambda environment is live at:\n[${process.env.PREVIEW_URL}](${process.env.PREVIEW_URL})\n\n_This environment will be automatically destroyed when the PR is merged or closed._\n\n---\n<div align="right"><sup>☁️ Generated by <a href="https://github.com/grada-run/grada">Grada</a></sup></div>`
93
- })
152
+ });
153
+ const existing = comments.find((comment) => comment.body?.includes(marker));
154
+ if (existing) {
155
+ await github.rest.issues.updateComment({
156
+ owner: context.repo.owner,
157
+ repo: context.repo.repo,
158
+ comment_id: existing.id,
159
+ body,
160
+ });
161
+ } else {
162
+ await github.rest.issues.createComment({
163
+ issue_number: context.issue.number,
164
+ owner: context.repo.owner,
165
+ repo: context.repo.repo,
166
+ body,
167
+ });
168
+ }
169
+
170
+ - name: Report preview failure on PR
171
+ if: failure()
172
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
173
+ with:
174
+ script: |
175
+ const marker = '<!-- grada-preview -->';
176
+ const runUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
177
+ const body = `${marker}\n❌ **Preview Environment Failed**\n\nThe preview deployment for this PR failed — the URL below (if any) is stale. See the [workflow run](${runUrl}) for details.`;
178
+ const { data: comments } = await github.rest.issues.listComments({
179
+ issue_number: context.issue.number,
180
+ owner: context.repo.owner,
181
+ repo: context.repo.repo,
182
+ });
183
+ const existing = comments.find((comment) => comment.body?.includes(marker));
184
+ if (existing) {
185
+ await github.rest.issues.updateComment({
186
+ owner: context.repo.owner,
187
+ repo: context.repo.repo,
188
+ comment_id: existing.id,
189
+ body,
190
+ });
191
+ } else {
192
+ await github.rest.issues.createComment({
193
+ issue_number: context.issue.number,
194
+ owner: context.repo.owner,
195
+ repo: context.repo.repo,
196
+ body,
197
+ });
198
+ }
199
+
200
+ # A cancelled apply can strand the S3 state lockfile: point at
201
+ # recovery instead of leaving the next run to fail obscurely
202
+ # (BUG-194). Generic by necessity — the lock ID only exists in the
203
+ # follow-up run's own error.
204
+ - name: Cancellation recovery note
205
+ if: cancelled()
206
+ run: |
207
+ echo "::warning::This run was cancelled while Terraform may have held the state lock. If the next run fails with 'Error acquiring the state lock', run terraform force-unlock <LOCK_ID> (the ID is printed in that error) inside ./terraform — or delete the .tflock object beside the state file in S3 — then re-run."
208
+
209
+ # Fork PRs skip the privileged job above loudly instead of silently:
210
+ # no credentials are issued and no preview is provisioned.
211
+ fork-notice:
212
+ name: Fork PR notice
213
+ if: github.event.pull_request.head.repo.full_name != github.repository
214
+ runs-on: ubuntu-latest
215
+ timeout-minutes: 5
216
+ steps:
217
+ - run: echo "PR previews run for same-repo pull requests only — fork PR #${{ github.event.pull_request.number }} skipped (no AWS credentials issued)."
@@ -1,12 +1,17 @@
1
1
  name: Ephemeral PR Preview
2
2
 
3
3
  on:
4
- pull_request:
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 admin CI role (BUG-140). The PR head is checked out explicitly by
7
+ # SHA in the guarded step instead.
8
+ pull_request_target:
5
9
  types: [opened, synchronize, reopened]
6
10
 
7
11
  # One runner per PR: rapid pushes cancel superseded previews instead of
8
- # overlapping applies on the same workspace. Shares its group with
9
- # teardown.yml, which queues (never cancels) behind an in-flight deploy.
12
+ # overlapping applies on the same workspace. Teardown runs in its own
13
+ # group (a reopen must never cancel an in-flight destroy); the state
14
+ # lock serializes the destroy/apply race instead (see -lock-timeout).
10
15
  concurrency:
11
16
  group: preview-${{ github.event.pull_request.number }}
12
17
  cancel-in-progress: true
@@ -15,6 +20,7 @@ env:
15
20
  AWS_REGION: {{REGION}}
16
21
  ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo
17
22
  WORKSPACE: pr-${{ github.event.pull_request.number }}
23
+ CF_COMMENT: {{PROJECT_NAME}}-pr-${{ github.event.pull_request.number }}{{RESOURCE_SUFFIX}}-cdn
18
24
 
19
25
  permissions:
20
26
  id-token: write
@@ -24,23 +30,48 @@ permissions:
24
30
  jobs:
25
31
  deploy-preview:
26
32
  name: Provision Preview Environment
33
+ # Same-repo PRs only: fork code must never execute with the admin CI
34
+ # role or production secrets. Trustworthy because this file comes from
35
+ # base (see trigger above). Public repos needing fork previews should
36
+ # gate this job behind an environment with required reviewers instead
37
+ # of deleting the guard.
38
+ if: github.event.pull_request.head.repo.full_name == github.repository
27
39
  runs-on: ubuntu-latest
40
+ timeout-minutes: 45
28
41
 
29
42
  steps:
30
- - name: Checkout Code
31
- uses: actions/checkout@v4
43
+ - name: Checkout PR head
44
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
45
+ with:
46
+ # Pinned SHA (not a ref name): the exact head this event fired
47
+ # for, immune to ref moves between event and checkout.
48
+ ref: ${{ github.event.pull_request.head.sha }}
32
49
 
33
50
  - name: Configure AWS credentials
34
- uses: aws-actions/configure-aws-credentials@v4
51
+ id: aws-creds
52
+ uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
53
+ continue-on-error: true
35
54
  with:
36
55
  role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
37
56
  aws-region: ${{ env.AWS_REGION }}
38
57
 
58
+ # STS denies a missing role and a trust mismatch with the same
59
+ # message, so the API won't support distinguishing them: every
60
+ # assume failure skips loud (green) with both cases + pointers
61
+ # named (BUG-199).
62
+ - name: Interpret credential failure
63
+ if: steps.aws-creds.outcome == 'failure'
64
+ run: |
65
+ ROLE_ARN="arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role"
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
+
39
68
  - name: Login to Amazon ECR
69
+ if: steps.aws-creds.outcome == 'success'
40
70
  id: login-ecr
41
- uses: aws-actions/amazon-ecr-login@v2
71
+ uses: aws-actions/amazon-ecr-login@03f1aad4c6c7ffd436567f42f9384779290529bd # v2
42
72
 
43
73
  - name: Build and Push Docker image
74
+ if: steps.aws-creds.outcome == 'success'
44
75
  env:
45
76
  ECR_REGISTRY: ${{ steps.login-ecr.outputs.registry }}
46
77
  run: |
@@ -49,29 +80,120 @@ jobs:
49
80
  docker push $ECR_REGISTRY/$ECR_REPOSITORY:${{ env.WORKSPACE }}
50
81
 
51
82
  - name: Setup Terraform
52
- uses: hashicorp/setup-terraform@v3
83
+ uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3
53
84
 
54
85
  - name: Terraform Init & Apply
55
86
  id: tf-apply
87
+ if: steps.aws-creds.outcome == 'success'
56
88
  working-directory: ./terraform
57
89
  run: |
58
90
  terraform init -input=false
59
91
  # Create or select the workspace specific to this PR
60
92
  terraform workspace select -or-create ${{ env.WORKSPACE }}
61
- terraform apply -auto-approve
93
+ # Teardown runs in its own group (see teardown.yml): a reopen
94
+ # during teardown waits on the state lock instead of racing it.
95
+ terraform apply -auto-approve -input=false -lock-timeout=10m
62
96
 
63
97
  # Extract the CloudFront URL to post to GitHub (the ALB origin
64
98
  # accepts CloudFront edges only — its direct URL is not browsable)
65
99
  PREVIEW_URL=$(terraform output -raw cloudfront_url)
66
100
  echo "PREVIEW_URL=$PREVIEW_URL" >> $GITHUB_ENV
67
101
 
102
+ # Every push redeploys the preview: clear its CDN so new HTML shows
103
+ # immediately instead of serving stale pages until TTL expiry.
104
+ - name: Invalidate CloudFront
105
+ if: steps.aws-creds.outcome == 'success'
106
+ run: |
107
+ DIST_ID=$(aws cloudfront list-distributions \
108
+ --query "DistributionList.Items[?Comment=='${{ env.CF_COMMENT }}'].Id | [0]" \
109
+ --output text \
110
+ --region ${{ env.AWS_REGION }})
111
+ if [ -z "$DIST_ID" ] || [ "$DIST_ID" = "None" ]; then
112
+ echo "CloudFront distribution '${{ env.CF_COMMENT }}' not found." >&2
113
+ exit 1
114
+ fi
115
+ aws cloudfront create-invalidation \
116
+ --distribution-id "$DIST_ID" \
117
+ --paths "/*" \
118
+ --region ${{ env.AWS_REGION }}
119
+
120
+ # One sticky comment per PR (updated in place), never a new
121
+ # comment per push — and a failed run overwrites the green URL
122
+ # instead of leaving it standing as truth (BUG-190).
68
123
  - name: Comment PR
69
- uses: actions/github-script@v7
124
+ if: steps.aws-creds.outcome == 'success'
125
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
126
+ with:
127
+ script: |
128
+ const marker = '<!-- grada-preview -->';
129
+ const body = `${marker}\n🚀 **Preview Environment Deployed!**\n\nYour ephemeral AWS Fargate environment is live at:\n[${process.env.PREVIEW_URL}](${process.env.PREVIEW_URL})\n\n_This environment will be automatically destroyed when the PR is merged or closed._\n\n---\n<div align="right"><sup>☁️ Generated by <a href="https://github.com/grada-run/grada">Grada</a></sup></div>`;
130
+ const { data: comments } = await github.rest.issues.listComments({
131
+ issue_number: context.issue.number,
132
+ owner: context.repo.owner,
133
+ repo: context.repo.repo,
134
+ });
135
+ const existing = comments.find((comment) => comment.body?.includes(marker));
136
+ if (existing) {
137
+ await github.rest.issues.updateComment({
138
+ owner: context.repo.owner,
139
+ repo: context.repo.repo,
140
+ comment_id: existing.id,
141
+ body,
142
+ });
143
+ } else {
144
+ await github.rest.issues.createComment({
145
+ issue_number: context.issue.number,
146
+ owner: context.repo.owner,
147
+ repo: context.repo.repo,
148
+ body,
149
+ });
150
+ }
151
+
152
+ - name: Report preview failure on PR
153
+ if: failure()
154
+ uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
70
155
  with:
71
156
  script: |
72
- github.rest.issues.createComment({
157
+ const marker = '<!-- grada-preview -->';
158
+ const runUrl = `https://github.com/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
159
+ const body = `${marker}\n❌ **Preview Environment Failed**\n\nThe preview deployment for this PR failed — the URL below (if any) is stale. See the [workflow run](${runUrl}) for details.`;
160
+ const { data: comments } = await github.rest.issues.listComments({
73
161
  issue_number: context.issue.number,
74
162
  owner: context.repo.owner,
75
163
  repo: context.repo.repo,
76
- body: `🚀 **Preview Environment Deployed!**\n\nYour ephemeral AWS Fargate environment is live at:\n[${process.env.PREVIEW_URL}](${process.env.PREVIEW_URL})\n\n_This environment will be automatically destroyed when the PR is merged or closed._\n\n---\n<div align="right"><sup>☁️ Generated by <a href="https://github.com/grada-run/grada">Grada</a></sup></div>`
77
- })
164
+ });
165
+ const existing = comments.find((comment) => comment.body?.includes(marker));
166
+ if (existing) {
167
+ await github.rest.issues.updateComment({
168
+ owner: context.repo.owner,
169
+ repo: context.repo.repo,
170
+ comment_id: existing.id,
171
+ body,
172
+ });
173
+ } else {
174
+ await github.rest.issues.createComment({
175
+ issue_number: context.issue.number,
176
+ owner: context.repo.owner,
177
+ repo: context.repo.repo,
178
+ body,
179
+ });
180
+ }
181
+
182
+ # A cancelled apply can strand the S3 state lockfile: point at
183
+ # recovery instead of leaving the next run to fail obscurely
184
+ # (BUG-194). Generic by necessity — the lock ID only exists in the
185
+ # follow-up run's own error.
186
+ - name: Cancellation recovery note
187
+ if: cancelled()
188
+ run: |
189
+ echo "::warning::This run was cancelled while Terraform may have held the state lock. If the next run fails with 'Error acquiring the state lock', run terraform force-unlock <LOCK_ID> (the ID is printed in that error) inside ./terraform — or delete the .tflock object beside the state file in S3 — then re-run."
190
+
191
+ # Fork PRs skip the privileged job above loudly instead of silently:
192
+ # no credentials are issued and no preview is provisioned.
193
+ fork-notice:
194
+ name: Fork PR notice
195
+ if: github.event.pull_request.head.repo.full_name != github.repository
196
+ runs-on: ubuntu-latest
197
+ timeout-minutes: 5
198
+ steps:
199
+ - run: echo "PR previews run for same-repo pull requests only — fork PR #${{ github.event.pull_request.number }} skipped (no AWS credentials issued)."
@@ -1,14 +1,19 @@
1
1
  name: Destroy PR Preview
2
2
 
3
3
  on:
4
- pull_request:
4
+ # pull_request_target (not pull_request): this file comes from the base
5
+ # branch, so a fork PR cannot smuggle privileged steps into its own
6
+ # teardown run (BUG-140). The PR head is checked out explicitly by SHA
7
+ # in the guarded step instead.
8
+ pull_request_target:
5
9
  types: [closed]
6
10
 
7
- # Shared with the preview workflow: teardown queues behind an in-flight
8
- # deploy instead of racing it on the state lock. No cancel-in-progress —
9
- # a teardown must run to completion, never be skipped.
11
+ # Own group (never preview's): a reopen must never cancel an in-flight
12
+ # destroy. No cancel-in-progress — a teardown must run to completion,
13
+ # never be skipped. The state lock serializes the destroy/apply race
14
+ # instead (see -lock-timeout below).
10
15
  concurrency:
11
- group: preview-${{ github.event.pull_request.number }}
16
+ group: teardown-${{ github.event.pull_request.number }}
12
17
 
13
18
  env:
14
19
  AWS_REGION: {{REGION}}
@@ -21,22 +26,65 @@ permissions:
21
26
  jobs:
22
27
  destroy-preview:
23
28
  name: Teardown Preview Environment
29
+ # Same-repo PRs only: fork previews are never provisioned (see the
30
+ # preview workflow guard), so fork teardowns have nothing to destroy.
31
+ # Trustworthy because this file comes from base (see trigger above).
32
+ if: github.event.pull_request.head.repo.full_name == github.repository
24
33
  runs-on: ubuntu-latest
34
+ timeout-minutes: 30
25
35
 
26
36
  steps:
27
- - name: Checkout Code
28
- uses: actions/checkout@v4
37
+ - name: Checkout PR head
38
+ uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
39
+ with:
40
+ # Pinned SHA: destroy exactly the tree the preview applied, so
41
+ # PR-only resources are torn down instead of leaked.
42
+ ref: ${{ github.event.pull_request.head.sha }}
29
43
 
30
44
  - name: Configure AWS credentials
31
- uses: aws-actions/configure-aws-credentials@v4
45
+ id: aws-creds
46
+ uses: aws-actions/configure-aws-credentials@7474bc4690e29a8392af63c5b98e7449536d5c3a # v4
47
+ continue-on-error: true
32
48
  with:
33
49
  role-to-assume: arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role
34
50
  aws-region: ${{ env.AWS_REGION }}
35
51
 
52
+ # STS denies a missing role and a trust mismatch with the same
53
+ # message, so the API won't support distinguishing them: every
54
+ # assume failure skips loud (green) with both cases + pointers
55
+ # named (BUG-199).
56
+ - name: Interpret credential failure
57
+ if: steps.aws-creds.outcome == 'failure'
58
+ run: |
59
+ ROLE_ARN="arn:aws:iam::{{AWS_ACCOUNT_ID}}:role/{{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-github-actions-role"
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
+
36
62
  - name: Setup Terraform
37
- uses: hashicorp/setup-terraform@v3
63
+ uses: hashicorp/setup-terraform@b9cd54a3c349d3f38e8881555d616ced269862dd # v3
64
+
65
+ # Preview databases carry deletion protection (database.tf) and
66
+ # `terraform destroy` never applies var updates, so protection is
67
+ # lifted out-of-band first — instance and Aurora-cluster forms.
68
+ # DB-less previews skip quietly (describes find nothing).
69
+ - name: Lift preview deletion protection
70
+ if: steps.aws-creds.outcome == 'success'
71
+ run: |
72
+ APP_NAME="{{PROJECT_NAME}}-${{ env.WORKSPACE }}{{RESOURCE_SUFFIX}}"
73
+ DB_ID="$APP_NAME-db"
74
+ if aws rds describe-db-instances --db-instance-identifier "$DB_ID" --region ${{ env.AWS_REGION }} >/dev/null 2>&1; then
75
+ echo "Lifting deletion protection on $DB_ID..."
76
+ aws rds modify-db-instance --db-instance-identifier "$DB_ID" --no-deletion-protection --apply-immediately --region ${{ env.AWS_REGION }}
77
+ aws rds wait db-instance-available --db-instance-identifier "$DB_ID" --region ${{ env.AWS_REGION }}
78
+ fi
79
+ CLUSTER_ID="$APP_NAME-db-cluster"
80
+ if aws rds describe-db-clusters --db-cluster-identifier "$CLUSTER_ID" --region ${{ env.AWS_REGION }} >/dev/null 2>&1; then
81
+ echo "Lifting deletion protection on $CLUSTER_ID..."
82
+ aws rds modify-db-cluster --db-cluster-identifier "$CLUSTER_ID" --no-deletion-protection --apply-immediately --region ${{ env.AWS_REGION }}
83
+ aws rds wait db-cluster-available --db-cluster-identifier "$CLUSTER_ID" --region ${{ env.AWS_REGION }}
84
+ fi
38
85
 
39
86
  - name: Terraform Init & Destroy
87
+ if: steps.aws-creds.outcome == 'success'
40
88
  working-directory: ./terraform
41
89
  run: |
42
90
  terraform init -input=false
@@ -51,8 +99,19 @@ jobs:
51
99
  fi
52
100
  # Select the PR workspace
53
101
  terraform workspace select ${{ env.WORKSPACE }}
54
- # Destroy all resources in this workspace safely
55
- terraform destroy -auto-approve
102
+ # Destroy all resources in this workspace safely. A close during
103
+ # an in-flight preview waits on the state lock instead of
104
+ # racing it (teardown has its own concurrency group now).
105
+ terraform destroy -auto-approve -input=false -lock-timeout=10m
56
106
  # Switch back to default and delete the PR workspace
57
107
  terraform workspace select default
58
- terraform workspace delete ${{ env.WORKSPACE }}
108
+ terraform workspace delete ${{ env.WORKSPACE }}
109
+
110
+ # A cancelled destroy can strand the S3 state lockfile: point at
111
+ # recovery instead of leaving the next run to fail obscurely
112
+ # (BUG-194). Generic by necessity — the lock ID only exists in the
113
+ # follow-up run's own error.
114
+ - name: Cancellation recovery note
115
+ if: cancelled()
116
+ run: |
117
+ echo "::warning::This run was cancelled while Terraform may have held the state lock. If the next run fails with 'Error acquiring the state lock', run terraform force-unlock <LOCK_ID> (the ID is printed in that error) inside ./terraform — or delete the .tflock object beside the state file in S3 — then re-run."
@@ -35,6 +35,34 @@ resource "aws_s3_bucket_server_side_encryption_configuration" "storage" {
35
35
  }
36
36
  }
37
37
 
38
+ # Versioning: an overwrite or bad deploy never destroys the previous
39
+ # object. Old versions expire via the lifecycle rule below so storage
40
+ # does not grow without bound.
41
+ resource "aws_s3_bucket_versioning" "storage" {
42
+ bucket = aws_s3_bucket.storage.id
43
+
44
+ versioning_configuration {
45
+ status = "Enabled"
46
+ }
47
+ }
48
+
49
+ resource "aws_s3_bucket_lifecycle_configuration" "storage" {
50
+ bucket = aws_s3_bucket.storage.id
51
+
52
+ rule {
53
+ id = "expire-old-versions"
54
+ status = "Enabled"
55
+
56
+ # Empty filter = the whole bucket (required: a filterless rule is a
57
+ # provider warning today and an error in future versions).
58
+ filter {}
59
+
60
+ noncurrent_version_expiration {
61
+ noncurrent_days = 30
62
+ }
63
+ }
64
+ }
65
+
38
66
  resource "aws_s3_bucket_cors_configuration" "storage" {
39
67
  bucket = aws_s3_bucket.storage.id
40
68
 
@@ -58,10 +86,17 @@ resource "aws_cloudfront_origin_access_control" "storage_oac" {
58
86
  }
59
87
 
60
88
  # trivy:ignore:AVD-AWS-0011 - WAF is omitted by default to prevent unexpected monthly costs for users
89
+ # Access logging is intentionally disabled: at starter scale these logs go
90
+ # unread (CloudWatch metrics cover ops), while a log bucket adds a delivery
91
+ # policy + lifecycle + review surface. Enable logging_config to a dedicated
92
+ # bucket if compliance needs it. Restrict price_class to PriceClass_100/200
93
+ # as well if most traffic is US/EU — edge coverage shrinks but so does the
94
+ # transfer bill.
61
95
  resource "aws_cloudfront_distribution" "storage_cdn" {
62
96
  enabled = true
63
97
  is_ipv6_enabled = true
64
98
  wait_for_deployment = false
99
+ price_class = "PriceClass_All"
65
100
 
66
101
  origin {
67
102
  domain_name = aws_s3_bucket.storage.bucket_regional_domain_name
@@ -10,6 +10,13 @@ terraform {
10
10
  source = "hashicorp/tls"
11
11
  version = "~> 4.0"
12
12
  }
13
+ # Declared unconditionally (BUG-137): the conditional injection left
14
+ # pre-existing trees without the pin when the DB arrived via
15
+ # `add database`. Unused on DB-less trees; init installs it anyway.
16
+ random = {
17
+ source = "hashicorp/random"
18
+ version = "~> 3.0"
19
+ }
13
20
  }
14
21
 
15
22
  backend "s3" {
@@ -26,7 +26,15 @@ resource "aws_db_instance" "postgres" {
26
26
  engine_version = "8.0"
27
27
  instance_class = "db.t4g.micro"
28
28
  allocated_storage = 20
29
- storage_encrypted = true
29
+ # Cap storage autoscaling: without a ceiling a runaway workload can
30
+ # grow the volume (and the bill) without bound.
31
+ max_allocated_storage = 200
32
+ backup_retention_period = 7
33
+ # Explicit off-peak UTC windows: without them AWS assigns windows
34
+ # that can land in peak hours (and drift between stacks).
35
+ backup_window = "03:00-04:00"
36
+ maintenance_window = "sun:04:00-sun:05:00"
37
+ storage_encrypted = true
30
38
 
31
39
  # Strip dashes for the database name: RDS MySQL db_name must begin with a
32
40
  # letter and contain only alphanumeric characters (e.g. my-project -> myproject)
@@ -26,7 +26,15 @@ resource "aws_db_instance" "postgres" {
26
26
  engine_version = "16"
27
27
  instance_class = "db.t4g.micro"
28
28
  allocated_storage = 20
29
- storage_encrypted = true
29
+ # Cap storage autoscaling: without a ceiling a runaway workload can
30
+ # grow the volume (and the bill) without bound.
31
+ max_allocated_storage = 200
32
+ backup_retention_period = 7
33
+ # Explicit off-peak UTC windows: without them AWS assigns windows
34
+ # that can land in peak hours (and drift between stacks).
35
+ backup_window = "03:00-04:00"
36
+ maintenance_window = "sun:04:00-sun:05:00"
37
+ storage_encrypted = true
30
38
 
31
39
  # Clean up dashes for the database name (e.g. my-project -> my_project)
32
40
  db_name = replace(local.app_name, "-", "_")
@@ -48,8 +48,9 @@ resource "aws_iam_role" "github_actions" {
48
48
  # remote, or the setup prompt. "repo:*" means any GitHub repo's
49
49
  # Actions can assume this role — re-scope before going live.
50
50
  # Scoped trusts render both subject-claim formats: the classic
51
- # `repo:<owner>/<name>:*` plus the immutable-claim companion
52
- # `repo:<owner>@*/<name>@*:*` (repos created after 2026-07-15).
51
+ # `repo:<owner>/<name>:<suffix>` plus the immutable-claim
52
+ # companion `repo:<owner>@*/<name>@*:<same suffix>`
53
+ # (repos created after 2026-07-15).
53
54
  "token.actions.githubusercontent.com:sub" : {{GITHUB_REPO_SUB}}
54
55
  }
55
56
  StringEquals = {