grada-run 0.41.4 → 0.42.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.
@@ -8,7 +8,7 @@ import { trackEvent, flushTelemetry, trackSuccess, trackFailure, setActiveComman
8
8
  import { failCommand, failProjectNotInitialized, isProgrammaticCall, refuseUnknownFlags } from '../utils/command.js';
9
9
  import { parseFlags, normalizeOptions, normalizeArgv } from '../utils/args.js';
10
10
  import { handleAuthErrorBranch, resolveClient } from '../utils/aws.js';
11
- import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget, readResourceSuffix } from '../utils/resolvers.js';
11
+ import { resolveRegion, resolveProjectName, resolveCwd, readTerraformComputeTarget, readResourceSuffix, resolveNamespacedProject } from '../utils/resolvers.js';
12
12
  import { runDiagnose } from './diagnose.js';
13
13
  import { fetchGoldenSignals } from '../utils/golden-signals.js';
14
14
  import { requireManagedTree } from '../utils/terraform-metadata.js';
@@ -38,7 +38,7 @@ export function parseStatusArgs(argv = []) {
38
38
  const args = normalizeArgv(argv);
39
39
  if (args[0] === 'status') args.shift();
40
40
  const { options, unknown } = parseFlags(args, {
41
- string: ['region'],
41
+ string: ['region', 'workspace'],
42
42
  boolean: ['headless'],
43
43
  bareBoolean: ['json', 'watch'],
44
44
  });
@@ -128,9 +128,10 @@ export async function runLambdaStatus(input = {}) {
128
128
  const cwd = options.cwd || process.cwd();
129
129
  const region = options.region;
130
130
  const projectName = options.projectName;
131
+ const namespacedProject = resolveNamespacedProject(projectName, options, cwd);
131
132
  const functionName = typeof options.functionName === 'string' && options.functionName.trim()
132
133
  ? options.functionName.trim()
133
- : `${projectName}${readResourceSuffix(cwd)}-fn`;
134
+ : `${namespacedProject}${readResourceSuffix(cwd)}-fn`;
134
135
  const asJson = Boolean(options.json);
135
136
  const runSync = options.spawnSyncImpl || spawnSync;
136
137
 
@@ -260,7 +261,8 @@ export async function runStaticStatus(input = {}) {
260
261
  const cwd = options.cwd || process.cwd();
261
262
  const region = options.region;
262
263
  const projectName = options.projectName;
263
- const comment = `${projectName}${readResourceSuffix(cwd)}-cdn`;
264
+ const namespacedProject = resolveNamespacedProject(projectName, options, cwd);
265
+ const comment = `${namespacedProject}${readResourceSuffix(cwd)}-cdn`;
264
266
  const asJson = Boolean(options.json);
265
267
  const cloudFrontClient = resolveClient(options.cloudFrontClient, CloudFrontClient, { region });
266
268
 
@@ -451,9 +453,13 @@ async function runStatusMain(input = {}) {
451
453
  return runStaticStatus({ ...options, cwd, region, projectName });
452
454
  }
453
455
  const resourceSuffix = readResourceSuffix(cwd);
454
- const cluster = options.cluster || process.env.ECS_CLUSTER || `${projectName}${resourceSuffix}-cluster`;
455
- const serviceName = options.service || process.env.ECS_SERVICE || `${projectName}${resourceSuffix}-service`;
456
- const logGroup = options.logGroup || process.env.ECS_LOG_GROUP || `/ecs/${projectName}${resourceSuffix}`;
456
+ // Workspace-namespaced resources (BUG-90): --workspace (or the local
457
+ // .terraform/environment) targets a preview stack like rollback and db
458
+ // do. Explicit flags/env keep winning; telemetry keeps the raw name.
459
+ const namespacedProject = resolveNamespacedProject(projectName, options, cwd);
460
+ const cluster = options.cluster || process.env.ECS_CLUSTER || `${namespacedProject}${resourceSuffix}-cluster`;
461
+ const serviceName = options.service || process.env.ECS_SERVICE || `${namespacedProject}${resourceSuffix}-service`;
462
+ const logGroup = options.logGroup || process.env.ECS_LOG_GROUP || `/ecs/${namespacedProject}${resourceSuffix}`;
457
463
 
458
464
  // --watch repaints the human dashboard; --json stays a single shot.
459
465
  if (Boolean(options.watch) && !asJson) {
@@ -213,8 +213,17 @@ export function buildDbEntries(engine, target = 'ecs') {
213
213
  };
214
214
  }
215
215
 
216
- // Adds the `random` provider to a rendered backend.tf (Lambda + database
217
- // projects only, for `random_password.db_password`). No-op when present.
216
+ // Whether a target's rendered backend.tf needs the `random` provider:
217
+ // always on ECS (the ALB origin secret), on Lambda only with a database
218
+ // (`random_password.db_password`), never on static.
219
+ export function backendNeedsRandomProvider(target, needsDatabase = false) {
220
+ if (target === 'static') return false;
221
+ if (target === 'lambda') return needsDatabase === true;
222
+ return true;
223
+ }
224
+
225
+ // Adds the `random` provider to a rendered backend.tf (see
226
+ // backendNeedsRandomProvider for which trees need it). No-op when present.
218
227
  // Resolves the compose service to merge for a render config. init
219
228
  // pre-selects through DOCKER_COMPOSE_WEB (a service name, or null when
220
229
  // init already warned and declined the merge); direct callers run the
@@ -305,6 +314,12 @@ export async function generateTemplates(targetDir, config) {
305
314
  // 3. Configure Compute Commands & Environment Variables
306
315
  let secretsArray = [];
307
316
 
317
+ // Exact container env + static-secret names for the managed_env_names
318
+ // collision-guard list (union over rendered task definitions). Each
319
+ // section below appends what IT renders, so the list tracks the
320
+ // environment by construction instead of parallel knowledge.
321
+ const managedEnvNames = ['PORT'];
322
+
308
323
  // 3.1. Format the ECS Task Command (Heroku Procfile Support)
309
324
  // If a Procfile exists and has a 'web' process, override the Docker CMD
310
325
  if (config.PROCFILE && config.PROCFILE.web) {
@@ -338,6 +353,10 @@ export async function generateTemplates(targetDir, config) {
338
353
  } else {
339
354
  config.WORKER_COMMAND = '';
340
355
  }
356
+ // Worker-only static env joins the union only when worker.tf renders —
357
+ // otherwise a pushed NODE_ENV would trip the app precondition though
358
+ // nothing would collide.
359
+ if (config.WORKER_COMMAND !== '') managedEnvNames.push('NODE_ENV');
341
360
 
342
361
  // 3.2. Inject Managed Database Variables. Static targets have no
343
362
  // compute to connect, so a database is never generated for them (init
@@ -374,6 +393,9 @@ export async function generateTemplates(targetDir, config) {
374
393
 
375
394
  secretsArray.push(`{ "name" : "DB_USER", "valueFrom" : "\${${dbRef}.master_user_secret[0].secret_arn}:username::" }`);
376
395
  secretsArray.push(`{ "name" : "DB_PASSWORD", "valueFrom" : "\${${dbRef}.master_user_secret[0].secret_arn}:password::" }`);
396
+ managedEnvNames.push('DB_HOST', 'DB_PORT', 'DB_NAME');
397
+ if (dbEngine !== 'postgres') managedEnvNames.push('DB_ENGINE');
398
+ managedEnvNames.push('DB_USER', 'DB_PASSWORD');
377
399
  }
378
400
 
379
401
  // VPC-attached functions reach RDS/ElastiCache over the VPC subnets;
@@ -412,6 +434,7 @@ export async function generateTemplates(targetDir, config) {
412
434
  composeWebEnvVars.push(` ${key} = "${String(val).replace(/"/g, '\\"')}"`);
413
435
  } else {
414
436
  composeWebEnvVars.push(`{ "name" : "${key}", "value" : "${String(val).replace(/"/g, '\\"')}" }`);
437
+ managedEnvNames.push(key);
415
438
  }
416
439
  }
417
440
 
@@ -481,6 +504,8 @@ export async function generateTemplates(targetDir, config) {
481
504
  if (config.finalFramework === 'rails') {
482
505
  secretsArray.push(`{ "name" : "RAILS_MASTER_KEY", "valueFrom" : "\${local.secret_arn}:RAILS_MASTER_KEY::" }`);
483
506
 
507
+ if (!isLambda) managedEnvNames.push('RAILS_MASTER_KEY');
508
+
484
509
  let initialMasterKey = "1234567890abcdef1234567890abcdef"; // Dummy fallback for CI/CD
485
510
  const masterKeyPath = path.join(targetDir, 'config', 'master.key');
486
511
 
@@ -501,6 +526,9 @@ export async function generateTemplates(targetDir, config) {
501
526
  console.log(color.yellow('⚠️ RAILS_MASTER_KEY is not auto-injected on Lambda targets: set it as a function environment variable after provisioning.'));
502
527
  }
503
528
  config.TASK_SECRETS = isLambda ? '' : secretsArray.join(',\n ');
529
+ // Collision-guard list for the task-definition precondition. Unused on
530
+ // Lambda/static targets (their templates carry no task definitions).
531
+ config.MANAGED_ENV_NAMES = `[${[...new Set(managedEnvNames)].map((name) => JSON.stringify(name)).join(', ')}]`;
504
532
  config.INITIAL_SECRET_MAP = initialSecretMap;
505
533
 
506
534
  config.SAFE_ALB_NAME = config.PROJECT_NAME.length > 27
@@ -565,7 +593,7 @@ resource "aws_lb_listener_rule" "vercel_redirect_${index}" {
565
593
  content = convertDatabaseTfForLambda(content);
566
594
  }
567
595
 
568
- if (isLambda && config.NEEDS_DATABASE && file.dest === 'terraform/backend.tf') {
596
+ if (file.dest === 'terraform/backend.tf' && backendNeedsRandomProvider(target, config.NEEDS_DATABASE)) {
569
597
  content = addRandomProvider(content);
570
598
  }
571
599
 
@@ -148,6 +148,77 @@ export function readTerraformOidcTrust(cwd = process.cwd()) {
148
148
  return { kind: 'string', value: raw.slice(1, -1) };
149
149
  }
150
150
 
151
+ // Index just past the `]` matching the `[` at openIdx (quoted regions
152
+ // skipped, so bracket-bearing strings can't mis-close it), or -1 when
153
+ // the block never closes.
154
+ function scanBracketBlock(content, openIdx) {
155
+ let depth = 0;
156
+ let i = openIdx;
157
+ while (i < content.length) {
158
+ const ch = content[i];
159
+ if (ch === '"') {
160
+ i += 1;
161
+ while (i < content.length && content[i] !== '"') i += content[i] === '\\' ? 2 : 1;
162
+ i += 1;
163
+ continue;
164
+ }
165
+ if (ch === '[') depth += 1;
166
+ else if (ch === ']') {
167
+ depth -= 1;
168
+ if (depth === 0) return i + 1;
169
+ }
170
+ i += 1;
171
+ }
172
+ return -1;
173
+ }
174
+
175
+ // Reads container environment + static-secret names from the rendered
176
+ // task definitions (main.tf + worker.tf). Covers every injection path —
177
+ // scaffold DB/compose entries (`{ "name" : "X" }`), addon entries
178
+ // (`{ name = "X" }`), static secrets (`valueFrom`) — because it reads
179
+ // what Terraform will actually submit, not what the maps predict. The
180
+ // dynamic `for key in local.secret_keys` loop carries an unquoted key
181
+ // reference, so it never matches; the shape filter drops resource names
182
+ // (`${...}`, hyphens, paths). Sorted, deduplicated, [] when unreadable.
183
+ //
184
+ // Scoped to secret-receiving containers (BUG-93): ECS collides secrets
185
+ // with environment per container definition, so sidecar `environment`
186
+ // arrays (whose containers get no secrets) must not contribute names —
187
+ // parsing them would falsely render same-named secrets undeployable.
188
+ // An environment block counts when a `secrets =` assignment follows it
189
+ // before the next environment block (the app/worker shape); hand-added
190
+ // entries inside those blocks stay covered.
191
+ export function readRenderedContainerEnvNames(cwd = process.cwd()) {
192
+ const base = resolveCwd({}, cwd);
193
+ const names = new Set();
194
+ const shape = /^[A-Za-z_][A-Za-z0-9_]*$/;
195
+ for (const file of ['main.tf', 'worker.tf']) {
196
+ const content = readFileSafe(path.join(base, 'terraform', file));
197
+ if (!content) continue;
198
+ const envStarts = [...content.matchAll(/environment\s*=\s*\[/g)];
199
+ for (let bi = 0; bi < envStarts.length; bi += 1) {
200
+ const match = envStarts[bi];
201
+ const openIdx = match.index + match[0].length - 1;
202
+ const closeIdx = scanBracketBlock(content, openIdx);
203
+ if (closeIdx === -1) continue;
204
+ const nextEnvIdx = bi + 1 < envStarts.length ? envStarts[bi + 1].index : content.length;
205
+ if (!/\bsecrets\s*=/.test(content.slice(closeIdx, nextEnvIdx))) continue;
206
+ const block = content.slice(openIdx, closeIdx);
207
+ for (const pattern of [/"name"\s*:\s*"([^"]+)"/g, /\bname\s*=\s*"([^"]+)"/g]) {
208
+ for (const m of block.matchAll(pattern)) {
209
+ if (shape.test(m[1])) names.add(m[1]);
210
+ }
211
+ }
212
+ }
213
+ // Static secret entries (`{ "name" : "X", "valueFrom" : ... }`):
214
+ // quoted names reached by a valueFrom within the same object.
215
+ for (const m of content.matchAll(/"name"\s*:\s*"([^"]+)"(?=[^}]{0,300}"valueFrom")/g)) {
216
+ if (shape.test(m[1])) names.add(m[1]);
217
+ }
218
+ }
219
+ return [...names].sort();
220
+ }
221
+
151
222
  // Collision-resistant naming: init mints a `-a1b2c3` suffix per project,
152
223
  // rendered into `grada_resource_suffix` in terraform/main.tf. AWS-name
153
224
  // builders append it to whatever base they assemble (bare or
@@ -250,6 +321,21 @@ export function resolveAppName(projectName, workspace, cwd = process.cwd()) {
250
321
  return `${projectName}${resolveWorkspaceSuffix({ workspace, cwd }, cwd)}`;
251
322
  }
252
323
 
324
+ // Workspace-namespaced project name for resource derivation: --workspace
325
+ // (or the local .terraform/environment) targets a preview stack. Telemetry
326
+ // keeps the raw project name; explicit --cluster/--service/--log-group
327
+ // flags still win inside the resolvers.
328
+ export function resolveNamespacedProject(projectName, options = {}, cwd = process.cwd()) {
329
+ return `${projectName}${resolveWorkspaceSuffix(options, cwd)}`;
330
+ }
331
+
332
+ // `options` with the project name workspace-namespaced, for commands that
333
+ // derive several resource names (cluster/service/log group) at once.
334
+ export function withWorkspaceNamespace(options = {}, cwd = process.cwd()) {
335
+ const opts = normalizeOptions(options);
336
+ return { ...opts, projectName: resolveNamespacedProject(resolveProjectName(opts, cwd), opts, cwd) };
337
+ }
338
+
253
339
  // Reads the local Terraform workspace (e.g. a PR-preview environment).
254
340
  // Returns '' for the default workspace so names stay un-suffixed.
255
341
  export function resolveWorkspaceSuffix(options = {}, cwd = process.cwd()) {
@@ -16,6 +16,7 @@ env:
16
16
  AWS_REGION: {{REGION}}
17
17
  ECR_REPOSITORY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-repo
18
18
  LAMBDA_FUNCTION: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-fn
19
+ CF_COMMENT: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-cdn
19
20
 
20
21
  permissions:
21
22
  id-token: write
@@ -123,3 +124,21 @@ jobs:
123
124
  aws lambda wait function-updated \
124
125
  --function-name ${{ env.LAMBDA_FUNCTION }} \
125
126
  --region ${{ env.AWS_REGION }}
127
+
128
+ # --- 6. CACHE INVALIDATION ---
129
+ # New code means new HTML: clear the CDN so deploys go live
130
+ # immediately instead of serving stale pages until TTL expiry.
131
+ - name: Invalidate CloudFront
132
+ run: |
133
+ DIST_ID=$(aws cloudfront list-distributions \
134
+ --query "DistributionList.Items[?Comment=='${{ env.CF_COMMENT }}'].Id | [0]" \
135
+ --output text \
136
+ --region ${{ env.AWS_REGION }})
137
+ if [ -z "$DIST_ID" ] || [ "$DIST_ID" = "None" ]; then
138
+ echo "CloudFront distribution '${{ env.CF_COMMENT }}' not found." >&2
139
+ exit 1
140
+ fi
141
+ aws cloudfront create-invalidation \
142
+ --distribution-id "$DIST_ID" \
143
+ --paths "/*" \
144
+ --region ${{ env.AWS_REGION }}
@@ -20,6 +20,7 @@ env:
20
20
  ECS_TASK_FAMILY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-task
21
21
  ECS_WORKER_SERVICE: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-worker-service
22
22
  ECS_WORKER_TASK_FAMILY: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-worker-task
23
+ CF_COMMENT: {{PROJECT_NAME}}{{RESOURCE_SUFFIX}}-cdn
23
24
 
24
25
  permissions:
25
26
  id-token: write
@@ -175,4 +176,22 @@ jobs:
175
176
  --service ${{ env.ECS_WORKER_SERVICE }} \
176
177
  --task-definition ${{ steps.register-worker-task-def.outputs.task-arn }} \
177
178
  --force-new-deployment \
179
+ --region ${{ env.AWS_REGION }}
180
+
181
+ # --- 6. CACHE INVALIDATION ---
182
+ # New code means new HTML: clear the CDN so deploys go live
183
+ # immediately instead of serving stale pages until TTL expiry.
184
+ - name: Invalidate CloudFront
185
+ run: |
186
+ DIST_ID=$(aws cloudfront list-distributions \
187
+ --query "DistributionList.Items[?Comment=='${{ env.CF_COMMENT }}'].Id | [0]" \
188
+ --output text \
189
+ --region ${{ env.AWS_REGION }})
190
+ if [ -z "$DIST_ID" ] || [ "$DIST_ID" = "None" ]; then
191
+ echo "CloudFront distribution '${{ env.CF_COMMENT }}' not found." >&2
192
+ exit 1
193
+ fi
194
+ aws cloudfront create-invalidation \
195
+ --distribution-id "$DIST_ID" \
196
+ --paths "/*" \
178
197
  --region ${{ env.AWS_REGION }}
@@ -7,6 +7,10 @@
7
7
  # chosen model in the AWS Bedrock console first.
8
8
 
9
9
  # --- Least-Privilege IAM Policy for the ECS Task Role ---
10
+ # Scoped to the chosen model in the deploy region (BUG-102): the
11
+ # foundation-model ARN names the model exactly, and the
12
+ # inference-profile line stays (profile-style model IDs invoke through
13
+ # profiles) but pinned to the region.
10
14
  resource "aws_iam_role_policy" "ai_bedrock_access" {
11
15
  name = "${local.app_name}-ai-bedrock-access"
12
16
  role = aws_iam_role.task_role.id
@@ -20,8 +24,8 @@ resource "aws_iam_role_policy" "ai_bedrock_access" {
20
24
  "bedrock:InvokeModelWithResponseStream"
21
25
  ]
22
26
  Resource = [
23
- "arn:aws:bedrock:*::foundation-model/*",
24
- "arn:aws:bedrock:*:*:inference-profile/*"
27
+ "arn:aws:bedrock:{{REGION}}::foundation-model/{{BEDROCK_MODEL_ID}}",
28
+ "arn:aws:bedrock:{{REGION}}:*:inference-profile/*"
25
29
  ]
26
30
  }
27
31
  ]
@@ -1,6 +1,60 @@
1
- # Fetch the AWS Managed Cache Policy (Optimized for standard web traffic)
2
- data "aws_cloudfront_cache_policy" "optimized" {
3
- name = "Managed-CachingOptimized"
1
+ # App CDN cache policies: a single path-only key (Managed-CachingOptimized)
2
+ # is wrong for an app server — one slot per path gets shared by HTML docs,
3
+ # API/RSC variants, redirects, and errors, so a cacheable variant poisons
4
+ # every other viewer of that path. Each traffic class below gets its own
5
+ # key instead (BUG-82).
6
+ data "aws_cloudfront_cache_policy" "disabled" {
7
+ name = "Managed-CachingDisabled"
8
+ }
9
+
10
+ # Default behavior key: query strings + cookies + router headers, so each
11
+ # page variant (search params, session, RSC/prefetch) caches independently
12
+ # and authenticated bytes never cross viewers. The header keys are harmless
13
+ # when absent — frameworks that never send them simply never vary on them.
14
+ resource "aws_cloudfront_cache_policy" "app_default" {
15
+ name = "${local.app_name}-app-default"
16
+ comment = "Per-variant app key: all query strings, cookies, and router headers"
17
+ default_ttl = 60
18
+ max_ttl = 86400
19
+ min_ttl = 0
20
+ parameters_in_cache_key_and_forwarded_to_origin {
21
+ cookies_config {
22
+ cookie_behavior = "all"
23
+ }
24
+ headers_config {
25
+ header_behavior = "whitelist"
26
+ headers {
27
+ items = ["RSC", "Next-Router-State-Tree", "Next-Router-Prefetch", "Next-Url"]
28
+ }
29
+ }
30
+ query_strings_config {
31
+ query_string_behavior = "all"
32
+ }
33
+ enable_accept_encoding_brotli = true
34
+ enable_accept_encoding_gzip = true
35
+ }
36
+ }
37
+
38
+ # Framework build assets are content-hashed: path-only key, immutable TTL.
39
+ resource "aws_cloudfront_cache_policy" "app_static" {
40
+ name = "${local.app_name}-app-static"
41
+ comment = "Content-hashed framework assets: immutable, long TTL"
42
+ default_ttl = 31536000
43
+ max_ttl = 31536000
44
+ min_ttl = 0
45
+ parameters_in_cache_key_and_forwarded_to_origin {
46
+ cookies_config {
47
+ cookie_behavior = "none"
48
+ }
49
+ headers_config {
50
+ header_behavior = "none"
51
+ }
52
+ query_strings_config {
53
+ query_string_behavior = "none"
54
+ }
55
+ enable_accept_encoding_brotli = true
56
+ enable_accept_encoding_gzip = true
57
+ }
4
58
  }
5
59
 
6
60
  # Fetch the AWS Managed Origin Request Policy (Passes query strings/cookies to your app)
@@ -8,10 +62,18 @@ data "aws_cloudfront_origin_request_policy" "all_viewer" {
8
62
  name = "Managed-AllViewerExceptHostHeader"
9
63
  }
10
64
 
65
+ # Managed security headers (HSTS, frame/clickjacking guards, content-type
66
+ # sniffing) on every behavior (BUG-92).
67
+ data "aws_cloudfront_response_headers_policy" "security" {
68
+ name = "Managed-SecurityHeadersPolicy"
69
+ }
70
+
11
71
  # trivy:ignore:AVD-AWS-0011 - WAF is omitted by default to prevent unexpected monthly costs for users
12
72
  resource "aws_cloudfront_distribution" "cdn" {
13
73
  enabled = true
14
74
  is_ipv6_enabled = true
75
+ comment = "${local.app_name}-cdn"
76
+ price_class = "PriceClass_100"
15
77
  wait_for_deployment = false # Prevents Terraform from hanging for 10+ minutes
16
78
 
17
79
  origin {
@@ -28,6 +90,31 @@ resource "aws_cloudfront_distribution" "cdn" {
28
90
  }
29
91
  }
30
92
 
93
+ ordered_cache_behavior {
94
+ path_pattern = "/api/*"
95
+ allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
96
+ cached_methods = ["GET", "HEAD"]
97
+ target_origin_id = "ApiGatewayOrigin"
98
+
99
+ viewer_protocol_policy = "redirect-to-https"
100
+
101
+ cache_policy_id = data.aws_cloudfront_cache_policy.disabled.id
102
+ origin_request_policy_id = data.aws_cloudfront_origin_request_policy.all_viewer.id
103
+ response_headers_policy_id = data.aws_cloudfront_response_headers_policy.security.id
104
+ }
105
+
106
+ ordered_cache_behavior {
107
+ path_pattern = "/_next/static/*"
108
+ allowed_methods = ["GET", "HEAD", "OPTIONS"]
109
+ cached_methods = ["GET", "HEAD"]
110
+ target_origin_id = "ApiGatewayOrigin"
111
+
112
+ viewer_protocol_policy = "redirect-to-https"
113
+
114
+ cache_policy_id = aws_cloudfront_cache_policy.app_static.id
115
+ response_headers_policy_id = data.aws_cloudfront_response_headers_policy.security.id
116
+ }
117
+
31
118
  default_cache_behavior {
32
119
  # Allow all HTTP methods so API POST/PUT requests still work
33
120
  allowed_methods = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"]
@@ -36,9 +123,41 @@ resource "aws_cloudfront_distribution" "cdn" {
36
123
 
37
124
  viewer_protocol_policy = "redirect-to-https"
38
125
 
39
- # Attach the Managed Policies
40
- cache_policy_id = data.aws_cloudfront_cache_policy.optimized.id
41
- origin_request_policy_id = data.aws_cloudfront_origin_request_policy.all_viewer.id
126
+ # Per-variant app key + full-variance origin forwarding
127
+ cache_policy_id = aws_cloudfront_cache_policy.app_default.id
128
+ origin_request_policy_id = data.aws_cloudfront_origin_request_policy.all_viewer.id
129
+ response_headers_policy_id = data.aws_cloudfront_response_headers_policy.security.id
130
+ }
131
+
132
+ # Error TTL caps: origin error bodies pass through untouched, but cache
133
+ # briefly so a transient 404/5xx never sticks for hours.
134
+ custom_error_response {
135
+ error_code = 400
136
+ error_caching_min_ttl = 60
137
+ }
138
+ custom_error_response {
139
+ error_code = 403
140
+ error_caching_min_ttl = 60
141
+ }
142
+ custom_error_response {
143
+ error_code = 404
144
+ error_caching_min_ttl = 60
145
+ }
146
+ custom_error_response {
147
+ error_code = 500
148
+ error_caching_min_ttl = 10
149
+ }
150
+ custom_error_response {
151
+ error_code = 502
152
+ error_caching_min_ttl = 10
153
+ }
154
+ custom_error_response {
155
+ error_code = 503
156
+ error_caching_min_ttl = 10
157
+ }
158
+ custom_error_response {
159
+ error_code = 504
160
+ error_caching_min_ttl = 10
42
161
  }
43
162
 
44
163
  restrictions {