@caelo-cms/provisioning 0.11.21 → 0.12.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 (135) hide show
  1. package/dist/adapter.d.ts +6 -1
  2. package/dist/adapter.d.ts.map +1 -1
  3. package/dist/agent-db.js +133 -8
  4. package/dist/bootstrap-token.d.ts +4 -3
  5. package/dist/bootstrap-token.d.ts.map +1 -1
  6. package/dist/bootstrap-token.js.map +1 -1
  7. package/dist/cli-routing.d.ts.map +1 -1
  8. package/dist/cli-routing.js +5 -0
  9. package/dist/cli-routing.js.map +1 -1
  10. package/dist/cli.js +4 -0
  11. package/dist/cli.js.map +1 -1
  12. package/dist/converge-job-gcp.d.ts +1 -16
  13. package/dist/converge-job-gcp.d.ts.map +1 -1
  14. package/dist/converge-job-gcp.js +10 -97
  15. package/dist/converge-job-gcp.js.map +1 -1
  16. package/dist/converge-job.d.ts +7 -46
  17. package/dist/converge-job.d.ts.map +1 -1
  18. package/dist/converge-job.js +22 -57
  19. package/dist/converge-job.js.map +1 -1
  20. package/dist/gateway-armor.d.ts.map +1 -1
  21. package/dist/gateway-armor.js +11 -3
  22. package/dist/gateway-armor.js.map +1 -1
  23. package/dist/gcp-names.d.ts +2 -0
  24. package/dist/gcp-names.d.ts.map +1 -1
  25. package/dist/gcp-names.js +4 -0
  26. package/dist/gcp-names.js.map +1 -1
  27. package/dist/index.d.ts +3 -2
  28. package/dist/index.d.ts.map +1 -1
  29. package/dist/index.js +1 -1
  30. package/dist/index.js.map +1 -1
  31. package/dist/infra-contract.d.ts +1 -1
  32. package/dist/infra-contract.d.ts.map +1 -1
  33. package/dist/infra-contract.js +14 -1
  34. package/dist/infra-contract.js.map +1 -1
  35. package/dist/job-handover-gcp.d.ts +40 -0
  36. package/dist/job-handover-gcp.d.ts.map +1 -0
  37. package/dist/job-handover-gcp.js +108 -0
  38. package/dist/job-handover-gcp.js.map +1 -0
  39. package/dist/job-handover.d.ts +141 -0
  40. package/dist/job-handover.d.ts.map +1 -0
  41. package/dist/job-handover.js +141 -0
  42. package/dist/job-handover.js.map +1 -0
  43. package/dist/owner-setup-token.d.ts +52 -0
  44. package/dist/owner-setup-token.d.ts.map +1 -0
  45. package/dist/owner-setup-token.js +111 -0
  46. package/dist/owner-setup-token.js.map +1 -0
  47. package/dist/project-status.d.ts +33 -0
  48. package/dist/project-status.d.ts.map +1 -1
  49. package/dist/project-status.js +116 -26
  50. package/dist/project-status.js.map +1 -1
  51. package/dist/stack-converge.d.ts.map +1 -1
  52. package/dist/stack-converge.js +9 -5
  53. package/dist/stack-converge.js.map +1 -1
  54. package/dist/static-security-headers.d.ts +6 -0
  55. package/dist/static-security-headers.d.ts.map +1 -1
  56. package/dist/static-security-headers.js +11 -1
  57. package/dist/static-security-headers.js.map +1 -1
  58. package/dist/upgrader-assess.d.ts +30 -3
  59. package/dist/upgrader-assess.d.ts.map +1 -1
  60. package/dist/upgrader-assess.js +77 -24
  61. package/dist/upgrader-assess.js.map +1 -1
  62. package/dist/upgrader-gcp.d.ts +4 -2
  63. package/dist/upgrader-gcp.d.ts.map +1 -1
  64. package/dist/upgrader-gcp.js +16 -3
  65. package/dist/upgrader-gcp.js.map +1 -1
  66. package/dist/upgrader-iam-preflight.d.ts +14 -3
  67. package/dist/upgrader-iam-preflight.d.ts.map +1 -1
  68. package/dist/upgrader-iam-preflight.js +40 -6
  69. package/dist/upgrader-iam-preflight.js.map +1 -1
  70. package/dist/upgrader-job.d.ts +51 -9
  71. package/dist/upgrader-job.d.ts.map +1 -1
  72. package/dist/upgrader-job.js +92 -37
  73. package/dist/upgrader-job.js.map +1 -1
  74. package/dist/upgrader-setup.d.ts +1 -1
  75. package/dist/upgrader-setup.d.ts.map +1 -1
  76. package/dist/upgrader-setup.js +5 -2
  77. package/dist/upgrader-setup.js.map +1 -1
  78. package/dist/wizards/gcp-install-job.d.ts.map +1 -1
  79. package/dist/wizards/gcp-install-job.js +11 -1
  80. package/dist/wizards/gcp-install-job.js.map +1 -1
  81. package/dist/wizards/gcp-pulumi.d.ts +0 -13
  82. package/dist/wizards/gcp-pulumi.d.ts.map +1 -1
  83. package/dist/wizards/gcp-pulumi.js +0 -12
  84. package/dist/wizards/gcp-pulumi.js.map +1 -1
  85. package/dist/wizards/gcp.d.ts.map +1 -1
  86. package/dist/wizards/gcp.js +21 -50
  87. package/dist/wizards/gcp.js.map +1 -1
  88. package/package.json +2 -2
  89. package/src/adapter.ts +6 -1
  90. package/src/bootstrap-token.ts +4 -3
  91. package/src/caddy-redirects.docker.test.ts +5 -0
  92. package/src/cli-routing.test.ts +1 -1
  93. package/src/cli-routing.ts +6 -0
  94. package/src/cli.ts +4 -0
  95. package/src/converge-job-gcp.test.ts +1 -40
  96. package/src/converge-job-gcp.ts +10 -100
  97. package/src/converge-job.test.ts +9 -3
  98. package/src/converge-job.ts +33 -115
  99. package/src/gateway-armor.ts +14 -3
  100. package/src/gateway-edge.test.ts +16 -1
  101. package/src/gcp-names.ts +4 -0
  102. package/src/gcp-url-map.test.ts +2 -0
  103. package/src/index.ts +3 -0
  104. package/src/infra-contract.test.ts +4 -3
  105. package/src/infra-contract.ts +14 -1
  106. package/src/job-handover-gcp.test.ts +129 -0
  107. package/src/job-handover-gcp.ts +135 -0
  108. package/src/job-handover.ts +259 -0
  109. package/src/owner-setup-token.test.ts +195 -0
  110. package/src/owner-setup-token.ts +138 -0
  111. package/src/project-status.test.ts +112 -3
  112. package/src/project-status.ts +141 -17
  113. package/src/stack-converge.ts +12 -5
  114. package/src/static-security-headers.test.ts +16 -0
  115. package/src/static-security-headers.ts +12 -1
  116. package/src/upgrader-assess.test.ts +75 -1
  117. package/src/upgrader-assess.ts +121 -57
  118. package/src/upgrader-gcp.ts +19 -5
  119. package/src/upgrader-iam-preflight.test.ts +28 -1
  120. package/src/upgrader-iam-preflight.ts +46 -6
  121. package/src/upgrader-job.test.ts +365 -31
  122. package/src/upgrader-job.ts +177 -53
  123. package/src/upgrader-setup.test.ts +17 -0
  124. package/src/upgrader-setup.ts +5 -2
  125. package/src/url-map-redirects-access.test.ts +1 -1
  126. package/src/wizards/gcp-install-job.ts +10 -1
  127. package/src/wizards/gcp-pulumi.ts +0 -18
  128. package/src/wizards/gcp.ts +24 -61
  129. package/stacks/aws/README.md +4 -2
  130. package/stacks/aws/index.ts +4 -8
  131. package/stacks/azure/README.md +4 -2
  132. package/stacks/azure/index.ts +4 -8
  133. package/stacks/gcp/README.md +6 -3
  134. package/stacks/gcp/index.ts +7 -8
  135. package/stacks/gcp-firebase/index.ts +4 -6
@@ -33,7 +33,6 @@ import {
33
33
  operatorAccessJobName,
34
34
  } from "./gcp-names.js";
35
35
  import { INFRA_CONTRACT_VERSION } from "./infra-contract.js";
36
- import { describeExecution } from "./install-job.js";
37
36
  import {
38
37
  type InstallMetadata,
39
38
  installRoot,
@@ -41,6 +40,7 @@ import {
41
40
  readMetadata,
42
41
  recordInfraContractVersion,
43
42
  } from "./install-state.js";
43
+ import { jobExecutionNameError, selfHandoverDeps } from "./job-handover-gcp.js";
44
44
  import { runMigrationsViaCloudRunJob } from "./migration-runner.js";
45
45
  import { installIapAllowlist } from "./operator-access.js";
46
46
  import { provisionerServiceAccountEmail } from "./provisioner-identity.js";
@@ -56,31 +56,6 @@ import { upgradeGcpInstallOutcome } from "./upgrade/upgrade.js";
56
56
  import { gcloudIamTester, healthProbeFor, type UpgraderPlacement } from "./upgrader-gcp.js";
57
57
  import type { JobLog } from "./upgrader-reporter.js";
58
58
 
59
- const DIGEST = /@(sha256:[0-9a-f]{64})/;
60
-
61
- /**
62
- * The image digest an execution of the converge job runs, from its Cloud
63
- * Run description (the execution's task template names the image it was
64
- * started with). Null when it cannot be read or names no digest.
65
- */
66
- export function executionImageDigest(describeJson: string): string | null {
67
- let parsed: unknown;
68
- try {
69
- parsed = JSON.parse(describeJson);
70
- } catch {
71
- return null;
72
- }
73
- // gcloud prints the v1 resource (spec.template.spec.containers); the v2
74
- // shape (template.containers) is accepted too. The first container is it.
75
- const p = parsed as {
76
- spec?: { template?: { spec?: { containers?: { image?: string }[] } } };
77
- template?: { containers?: { image?: string }[] };
78
- };
79
- const image =
80
- p.spec?.template?.spec?.containers?.[0]?.image ?? p.template?.containers?.[0]?.image ?? "";
81
- return DIGEST.exec(image)?.[1] ?? null;
82
- }
83
-
84
59
  /** The operator-access job's env var listing the install's fixed IAP members. */
85
60
  const STATIC_MEMBERS_ENV = "CAELO_OPERATOR_ACCESS_STATIC_MEMBERS";
86
61
 
@@ -182,27 +157,9 @@ export function deployedSiteMismatch(
182
157
  return null;
183
158
  }
184
159
 
185
- /**
186
- * Why `CLOUD_RUN_EXECUTION` cannot name a run of the converge job, or null
187
- * when it can. The name keys the state lock's holder and the hand-over
188
- * between the job's two stages, so a value that names another job's run
189
- * (or is not a Cloud Run name at all) stops the job before it acts
190
- * (#883 review). Cloud Run sets it and rejects user values for it; this is
191
- * the second line.
192
- */
160
+ /** Why `CLOUD_RUN_EXECUTION` cannot name a run of the converge job, or null when it can. */
193
161
  export function convergeExecutionNameError(execution: string | null): string | null {
194
- if (execution === null) return null;
195
- const prefix = `${convergeJobName(GCP_STACK_ENV)}-`;
196
- if (!/^[a-z0-9-]{1,63}$/.test(execution) || !execution.startsWith(prefix)) {
197
- return `CLOUD_RUN_EXECUTION is "${execution.slice(0, 80)}", not a run of ${convergeJobName(GCP_STACK_ENV)}`;
198
- }
199
- return null;
200
- }
201
-
202
- /** The new execution's name from `gcloud run jobs execute --async`. */
203
- export function startedExecutionName(stdout: string, stderr: string): string | null {
204
- const name = stdout.trim().split(/\s+/)[0] || /Execution \[([^\]]+)\]/.exec(stderr)?.[1] || "";
205
- return /^[a-z0-9-]+$/.test(name) ? name : null;
162
+ return jobExecutionNameError(convergeJobName(GCP_STACK_ENV), execution);
206
163
  }
207
164
 
208
165
  /**
@@ -238,9 +195,8 @@ export function gcpConvergeDeps(
238
195
  const run: GcloudRunner = gcloud;
239
196
  const http = fetch as unknown as HttpFetch;
240
197
  const { projectId, region } = placement;
241
- const bucket = opsBucketName(projectId);
242
- const job = convergeJobName(GCP_STACK_ENV);
243
198
  const location = [`--region=${region}`, `--project=${projectId}`];
199
+ const bucket = opsBucketName(projectId);
244
200
  // Peeks only (uncached); the upgrade writes through install-state.ts.
245
201
  const store = new GcsStateStore(bucket, mkdtempSync(join(tmpdir(), "caelo-converge-")));
246
202
 
@@ -398,7 +354,12 @@ export function gcpConvergeDeps(
398
354
  : { ok: false, error: r.stderr.trim() || `gcloud exited ${r.exitCode}` };
399
355
  },
400
356
  sleep: realSleep,
401
- execution: placement.execution,
357
+ ...selfHandoverDeps(run, {
358
+ job: convergeJobName(GCP_STACK_ENV),
359
+ projectId,
360
+ region,
361
+ execution: placement.execution,
362
+ }),
402
363
  ownVersion: CAELO_VERSION,
403
364
  // The default deps: the fixed registry and signer, never overridden.
404
365
  fetchManifest: (version) => fetchVerifiedReleaseManifest(version),
@@ -406,57 +367,6 @@ export function gcpConvergeDeps(
406
367
  const text = store.peek("install.json");
407
368
  return text === null ? null : (JSON.parse(text) as InstallMetadata);
408
369
  },
409
- verifyImage: (slug, digest) => verifyCosignAll([{ slug, digest }]),
410
- ownImageDigest: async () => {
411
- if (!placement.execution) return null;
412
- const r = await run([
413
- "run",
414
- "jobs",
415
- "executions",
416
- "describe",
417
- placement.execution,
418
- ...location,
419
- "--format=json",
420
- ]);
421
- return r.ok ? executionImageDigest(r.stdout) : null;
422
- },
423
- pointJobAt: async (digest) => {
424
- // Only the image changes: the identity, command and args stay what
425
- // converge-job-setup.ts deployed.
426
- const update = await run([
427
- "run",
428
- "jobs",
429
- "update",
430
- job,
431
- `--image=${releaseImageRef("ops", digest)}`,
432
- ...location,
433
- "--quiet",
434
- ]);
435
- return update.ok
436
- ? { ok: true }
437
- : { ok: false, error: `update ${job}: ${update.stderr.trim()}` };
438
- },
439
- startJob: async () => {
440
- const exec = await run([
441
- "run",
442
- "jobs",
443
- "execute",
444
- job,
445
- ...location,
446
- "--async",
447
- "--format=value(metadata.name)",
448
- ]);
449
- if (!exec.ok) return { ok: false, error: `start ${job}: ${exec.stderr.trim()}` };
450
- const execution = startedExecutionName(exec.stdout, exec.stderr);
451
- if (!execution) {
452
- return {
453
- ok: false,
454
- error: `${job} started but gcloud did not name the execution (${exec.stderr.trim()})`,
455
- };
456
- }
457
- return { ok: true, execution };
458
- },
459
- executionState: (execution) => describeExecution(run, { projectId, region, execution }),
460
370
  // #815 — the lock names this execution; a later run breaks it once
461
371
  // Cloud Run says this one has ended (killed at its task timeout).
462
372
  lockState: (onBreak) =>
@@ -192,7 +192,13 @@ function harness(
192
192
  calls.push(`verify ${slug} ${digest}`);
193
193
  return opts.imageSigned ?? true;
194
194
  },
195
- ownImageDigest: async () => (opts.ownDigest === undefined ? D("c") : opts.ownDigest),
195
+ // Stage 1 runs an earlier release's image, stage 2 the manifest's.
196
+ ownImageDigest: async () =>
197
+ opts.ownDigest !== undefined
198
+ ? opts.ownDigest
199
+ : (opts.ownVersion ?? "0.11.0") === "0.11.0"
200
+ ? D("c")
201
+ : D("e"),
196
202
  pointJobAt: async (digest) => {
197
203
  calls.push(`point ${digest}`);
198
204
  return { ok: true };
@@ -665,7 +671,7 @@ describe("runConvergeJob — resume after a killed run", () => {
665
671
  expect(h.q.handovers).toEqual([{ from: null, to: "caelo-production-converge-run1" }]);
666
672
  });
667
673
 
668
- it("a stage-1 hand-over whose new run cannot start ends the request with nothing changed", async () => {
674
+ it("a stage-1 hand-over whose new run cannot start ends the request with the site unchanged", async () => {
669
675
  const h = harness({ ownVersion: "0.10.53" });
670
676
  const deps = {
671
677
  ...h.deps,
@@ -674,7 +680,7 @@ describe("runConvergeJob — resume after a killed run", () => {
674
680
  const r = await runConvergeJob(deps);
675
681
  expect(r.status).toBe("failed");
676
682
  expect(h.q.ends[0]?.codes).toEqual(["handover"]);
677
- expect(h.q.ends[0]?.reason).toStartWith("Nothing was changed");
683
+ expect(h.q.ends[0]?.reason).toStartWith("Nothing on the site was changed");
678
684
  });
679
685
 
680
686
  it("a finished converge whose end was never recorded is finished, not repeated", async () => {
@@ -57,14 +57,19 @@ import {
57
57
  selfGrantPlan,
58
58
  } from "./converge-job-preflight.js";
59
59
  import { GCP_STACK_ENV } from "./gcp-names.js";
60
- import { decideInstallJob, type ExecutionState, type InstallJobRole } from "./install-job.js";
60
+ import { decideInstallJob, type InstallJobRole } from "./install-job.js";
61
61
  import type { InstallMetadata } from "./install-state.js";
62
- import { provisionerServiceAccountEmail } from "./provisioner-identity.js";
63
62
  import {
64
- compareSemver,
65
- type ReleaseManifest,
66
- type ReleaseManifestResult,
67
- } from "./release-manifest.js";
63
+ adoptClaim,
64
+ type HandoverQueue,
65
+ handOverToRelease,
66
+ isStageOne,
67
+ type JobClaim,
68
+ ownImageProblem,
69
+ type SelfHandoverDeps,
70
+ } from "./job-handover.js";
71
+ import { provisionerServiceAccountEmail } from "./provisioner-identity.js";
72
+ import type { ReleaseManifest, ReleaseManifestResult } from "./release-manifest.js";
68
73
  import { StateLockHeldError } from "./state-store.js";
69
74
  import type { UpgradeCheckpoint } from "./upgrade/upgrade.js";
70
75
  import { assessUpgradeRequest } from "./upgrader-assess.js";
@@ -76,7 +81,6 @@ import {
76
81
  runIamPreflight,
77
82
  } from "./upgrader-iam-preflight.js";
78
83
  import {
79
- type ClaimedUpdate,
80
84
  recordUpdateEnd,
81
85
  type UpdateEnd,
82
86
  type UpdateEndStatus,
@@ -86,30 +90,15 @@ import {
86
90
  import { type EventReporter, eventReporter, type JobLog } from "./upgrader-reporter.js";
87
91
 
88
92
  /** What the converge claim found. */
89
- export interface ConvergeClaim {
90
- readonly request: ClaimedUpdate;
91
- /**
92
- * The request was already running: stage 1 handed it to this run, or a
93
- * run that died left it. Fresh claims (pending → running) are false.
94
- */
95
- readonly resume: boolean;
96
- /** The execution the request names now (after a fresh claim: this one). */
97
- readonly execution: string | null;
98
- }
93
+ export type ConvergeClaim = JobClaim;
99
94
 
100
95
  /** The converge job's view of the database (the platform_updater role). */
101
- export interface ConvergeQueue extends Omit<UpdateQueue, "claim"> {
96
+ export interface ConvergeQueue extends Omit<UpdateQueue, "claim">, HandoverQueue {
102
97
  /**
103
98
  * End runs that died long ago (stale), then return the running converge
104
99
  * request, or claim the oldest pending one.
105
100
  */
106
101
  claimConverge(execution: string | null): Promise<ConvergeClaim | null>;
107
- /**
108
- * Point running request `requestId` at execution `to` — or at none
109
- * (`null`: released for the next run to adopt) — only while it still
110
- * names `from`. Resolves false when another run got there first.
111
- */
112
- handover(requestId: string, from: string | null, to: string | null): Promise<boolean>;
113
102
  }
114
103
 
115
104
  /** How stage 2's upgrade ended (upgrade/upgrade.ts, seen from the job). */
@@ -140,7 +129,7 @@ export type SecureDatabaseResult =
140
129
  | { readonly ok: true; readonly host: string }
141
130
  | { readonly ok: false; readonly error: string };
142
131
 
143
- export interface ConvergeJobDeps {
132
+ export interface ConvergeJobDeps extends SelfHandoverDeps {
144
133
  readonly queue: ConvergeQueue;
145
134
  /**
146
135
  * #1373 — the install's database TLS step (#1338, cloudsql-tls.ts), and
@@ -167,29 +156,10 @@ export interface ConvergeJobDeps {
167
156
  ) => Promise<{ readonly ok: true } | { readonly ok: false; readonly error: string }>;
168
157
  /** Waits between the IAM re-checks after a self-grant. */
169
158
  readonly sleep: (ms: number) => Promise<void>;
170
- /** This Cloud Run execution; null outside Cloud Run. */
171
- readonly execution: string | null;
172
- /** The Caelo release this code belongs to (CAELO_VERSION of the image). */
173
- readonly ownVersion: string;
174
159
  /** fetchVerifiedReleaseManifest against the fixed registry. */
175
160
  readonly fetchManifest: (version: string) => Promise<ReleaseManifestResult>;
176
161
  /** install.json as the ops bucket holds it NOW (null when absent) — never cached. */
177
162
  readonly readInstall: () => InstallMetadata | null;
178
- /** Verify the cosign signature of the release image `slug@digest`. */
179
- readonly verifyImage: (slug: "ops", digest: string) => Promise<boolean>;
180
- /** The digest of the image this execution runs (from Cloud Run); null when unreadable. */
181
- readonly ownImageDigest: () => Promise<string | null>;
182
- /** Point this job at the ops image with `digest` (its identity, command and args stay). */
183
- readonly pointJobAt: (
184
- digest: string,
185
- ) => Promise<{ readonly ok: true } | { readonly ok: false; readonly error: string }>;
186
- /** Start a new execution of this job; returns its name. */
187
- readonly startJob: () => Promise<
188
- | { readonly ok: true; readonly execution: string }
189
- | { readonly ok: false; readonly error: string }
190
- >;
191
- /** Where an execution of this job stands (Cloud Run). */
192
- readonly executionState: (execution: string) => Promise<ExecutionState>;
193
163
  /**
194
164
  * Take the install's state lock (#815); returns its release. Throws
195
165
  * StateLockHeldError when a live run holds it, any other error when it
@@ -230,9 +200,9 @@ export async function runConvergeJob(deps: ConvergeJobDeps): Promise<UpgraderRun
230
200
  request.id,
231
201
  );
232
202
  /** This run leaves the request to another (live) run: no end, no events. */
233
- const leave = (message: string): UpgraderRunResult => {
234
- log({ severity: "INFO", message, requestId: request.id });
235
- return { exitCode: 0, requestId: request.id, status: null };
203
+ const leave = (message: string, failed = false): UpgraderRunResult => {
204
+ log({ severity: failed ? "ERROR" : "INFO", message, requestId: request.id });
205
+ return { exitCode: failed ? 1 : 0, requestId: request.id, status: null };
236
206
  };
237
207
  let releaseLock: (() => void) | null = null;
238
208
  const unlock = () => {
@@ -264,21 +234,9 @@ export async function runConvergeJob(deps: ConvergeJobDeps): Promise<UpgraderRun
264
234
  });
265
235
 
266
236
  try {
267
- // A request another execution started: adopt it only once that one
268
- // has ended — two converges at once must never happen.
269
- if (claim.resume && claim.execution !== deps.execution) {
270
- if (!deps.execution) {
271
- return leave("a converge request is running; only a Cloud Run execution may adopt it");
272
- }
273
- if (claim.execution) {
274
- const live = await deps.executionState(claim.execution);
275
- if (live === "running") {
276
- return leave(`execution ${claim.execution} is still installing; this run does nothing`);
277
- }
278
- }
279
- if (!(await queue.handover(request.id, claim.execution, deps.execution))) {
280
- return leave("another run adopted the request first; this run does nothing");
281
- }
237
+ const adoption = await adoptClaim(claim, { ...deps, queue });
238
+ if (adoption.kind === "leave") return leave(adoption.message, adoption.failed);
239
+ if (adoption.adopted) {
282
240
  r.phase("start");
283
241
  r.info(
284
242
  `Continuing the update to ${request.targetVersion} (run ${deps.execution}; the previous run${claim.execution ? ` ${claim.execution}` : ""} stopped before it finished).`,
@@ -358,7 +316,7 @@ export async function runConvergeJob(deps: ConvergeJobDeps): Promise<UpgraderRun
358
316
  // stages ask; stage 2's list is the target release's own. A missing
359
317
  // role of the self-grant allowlist does not stop the run: stage 2
360
318
  // grants it once it has verified its own image and holds the lock.
361
- const stage1 = compareSemver(deps.ownVersion, m.version) !== 0;
319
+ const stage1 = isStageOne(deps.ownVersion, m.version);
362
320
  const access = await askIam();
363
321
  if (access.kind === "error") {
364
322
  return stopWith(
@@ -410,48 +368,18 @@ export async function runConvergeJob(deps: ConvergeJobDeps): Promise<UpgraderRun
410
368
  r.info(
411
369
  `This installer belongs to Caelo ${deps.ownVersion}; handing over to the installer of ${m.version} itself, so the cloud setup is changed by the release that needs it.`,
412
370
  );
413
- if (!(await deps.verifyImage("ops", m.digests.ops))) {
414
- return stopWith(
415
- "refused",
416
- ["signature"],
417
- `The installer image of ${m.version} is not signed by Caelo's release workflow, so nothing was changed.`,
418
- );
419
- }
420
- // Under the lock (the terminal `upgrade` redeploys this job too), and
421
- // released before the new run starts: it takes the lock itself.
422
- const locked = lockOrBlock(false);
423
- if (locked) return stopWith(locked.status, locked.codes, locked.reason);
424
- const pointed = await deps.pointJobAt(m.digests.ops);
425
- unlock();
426
- if (!pointed.ok) {
427
- return stopWith(
428
- "failed",
429
- ["handover"],
430
- `Nothing was changed: the installer of ${m.version} could not be prepared (${pointed.error}). Try again in a moment.`,
431
- );
432
- }
433
- // Release the request BEFORE the new run exists: it adopts a request
434
- // that names no run at once, while a run still named (this one, alive
435
- // for a moment longer) would make it step back.
436
- if (!(await queue.handover(request.id, deps.execution, null))) {
437
- return leave("the request moved on before the hand-over; this run does nothing");
438
- }
439
- const started = await deps.startJob();
440
- if (!started.ok) {
441
- return stopWith(
442
- "failed",
443
- ["handover"],
444
- `Nothing was changed: the installer of ${m.version} could not be started (${started.error}). Try again in a moment.`,
445
- );
446
- }
447
- r.info(`The installer of ${m.version} runs now (run ${started.execution}).`);
448
- await r.flush();
449
- log({
450
- severity: "INFO",
451
- message: `handed over to ${started.execution}`,
371
+ return handOverToRelease(m, {
372
+ deps,
373
+ queue,
452
374
  requestId: request.id,
375
+ noun: "installer",
376
+ reporter: r,
377
+ log,
378
+ lock: () => lockOrBlock(false),
379
+ unlock,
380
+ stop: (b) => stopWith(b.status, b.codes, b.reason),
381
+ leave,
453
382
  });
454
- return { exitCode: 0, requestId: request.id, status: null };
455
383
  }
456
384
 
457
385
  /** Stage 2: this image is the release's own installer; converge + roll. */
@@ -463,18 +391,8 @@ export async function runConvergeJob(deps: ConvergeJobDeps): Promise<UpgraderRun
463
391
  toGrant: readonly InstallJobRole[],
464
392
  ): Promise<UpgraderRunResult> {
465
393
  const installId = judged.installId;
466
- const own = await deps.ownImageDigest();
467
- // Cloud Run records the linux/amd64 platform manifest it resolved, not
468
- // the index the hand-over pinned (#1025), so an execution of the right
469
- // image reads back as the platform form the manifest also signs.
470
- const signedForms = [m.digests.ops, ...(m.platformDigests ? [m.platformDigests.ops] : [])];
471
- if (own === null || !signedForms.includes(own)) {
472
- return stopWith(
473
- "refused",
474
- ["ops-image"],
475
- `Nothing was changed: this run's installer image (${own ?? "unknown"}) is not the one Caelo's release workflow signed for ${m.version} (${signedForms.join(" or ")}). Start the update again from Settings → Updates.`,
476
- );
477
- }
394
+ const wrongImage = ownImageProblem(m, await deps.ownImageDigest(), "installer");
395
+ if (wrongImage) return stopWith(wrongImage.status, wrongImage.codes, wrongImage.reason);
478
396
  // The checkpoint's run, if it is not this one, must have ended.
479
397
  const live =
480
398
  checkpoint && checkpoint.execution !== deps.execution
@@ -3,7 +3,7 @@
3
3
  /**
4
4
  * #1339 — bring the visitor gateway's Cloud Armor policy on an existing
5
5
  * `gcp` install to the rules of gateway-edge.ts (infrastructure contract
6
- * 21). The stack declares the same rules for new installs; the converge
6
+ * 22). The stack declares the same rules for new installs; the converge
7
7
  * runs this, because the in-cloud upgrader holds no compute rights.
8
8
  *
9
9
  * No step leaves the policy with less protection than before:
@@ -82,8 +82,19 @@ export async function ensureGatewayArmorRules(
82
82
  }
83
83
  let live: LiveGatewayArmorRule[];
84
84
  try {
85
- live = ((JSON.parse(describe.stdout) as { rules?: LiveGatewayArmorRule[] }).rules ??
86
- []) as LiveGatewayArmorRule[];
85
+ // `describe --format=json` prints a one-element list. Read as an object it
86
+ // has no rules, so every existing rule looked missing and `create` failed.
87
+ const parsed = JSON.parse(describe.stdout) as unknown;
88
+ const policyJson = (Array.isArray(parsed) ? parsed[0] : parsed) as
89
+ | { rules?: LiveGatewayArmorRule[] }
90
+ | null
91
+ | undefined;
92
+ // Every policy has at least its default rule, so a reply without rules is
93
+ // not an empty policy: read as one, every rule would be created again.
94
+ if (!Array.isArray(policyJson?.rules)) {
95
+ return { ok: false, error: `describe ${policy}: the reply names no rules`, done };
96
+ }
97
+ live = policyJson.rules;
87
98
  } catch {
88
99
  return { ok: false, error: `describe ${policy}: output is not JSON`, done };
89
100
  }
@@ -36,7 +36,8 @@ function fakeGcloud(rules: LiveGatewayArmorRule[], policies = ["caelo-production
36
36
  const run = async (args: string[]): Promise<GcloudResult> => {
37
37
  calls.push(args);
38
38
  if (args.includes("list")) return ok(`${policies.join("\n")}\n`);
39
- if (args.includes("describe")) return ok(JSON.stringify({ rules }));
39
+ // As real gcloud prints it: `describe --format=json` is a one-element list.
40
+ if (args.includes("describe")) return ok(JSON.stringify([{ rules }]));
40
41
  return ok();
41
42
  };
42
43
  return { run, calls };
@@ -105,6 +106,20 @@ describe("the gateway's Cloud Armor rules (#1339)", () => {
105
106
  describe("ensureGatewayArmorRules (the converge, contract 22)", () => {
106
107
  const target = { projectId: "acme", env: "production" };
107
108
 
109
+ it("stops on a describe reply without rules instead of creating every rule again", async () => {
110
+ for (const reply of ["[]", "[null]", "{}"]) {
111
+ const calls: string[][] = [];
112
+ const run = async (args: string[]): Promise<GcloudResult> => {
113
+ calls.push(args);
114
+ if (args.includes("list")) return ok("caelo-production-waf-1a2b3c\n");
115
+ return ok(reply);
116
+ };
117
+ const r = await ensureGatewayArmorRules(target, { run });
118
+ expect(r.ok).toBe(false);
119
+ expect(calls.some((c) => c.includes("create"))).toBe(false);
120
+ }
121
+ });
122
+
108
123
  it("changes nothing when every rule is in place", async () => {
109
124
  const { run, calls } = fakeGcloud(gatewayArmorRuleArgs().map(live));
110
125
  const r = await ensureGatewayArmorRules(target, { run });
package/src/gcp-names.ts CHANGED
@@ -326,11 +326,15 @@ export function urlMapRedirectsRoleId(env: string): string {
326
326
  * #587 — permissions of {@link urlMapRedirectsRoleId}: read-modify-write of
327
327
  * the URL map and waiting for the operation. A URL-map update must be
328
328
  * allowed to "use" every backend the map references, hence the `.use` pair.
329
+ * #1454 — get and update of the static backend bucket: a build's page headers
330
+ * are its custom response headers (admin-core gcp-site-headers.ts).
329
331
  */
330
332
  export const URL_MAP_REDIRECTS_PERMISSIONS: readonly string[] = [
331
333
  "compute.urlMaps.list",
332
334
  "compute.urlMaps.get",
333
335
  "compute.urlMaps.update",
336
+ "compute.backendBuckets.get",
337
+ "compute.backendBuckets.update",
334
338
  "compute.backendBuckets.use",
335
339
  "compute.backendServices.use",
336
340
  "compute.globalOperations.get",
@@ -169,6 +169,8 @@ describe("gcp stack wiring (source)", () => {
169
169
  expect(urlMapRedirectsRoleId("production")).toBe("caelo_production_urlMapRedirects");
170
170
  expect(urlMapRedirectsRoleId("production")).toMatch(/^[A-Za-z0-9_.]{3,64}$/);
171
171
  expect([...URL_MAP_REDIRECTS_PERMISSIONS].sort()).toEqual([
172
+ "compute.backendBuckets.get",
173
+ "compute.backendBuckets.update",
172
174
  "compute.backendBuckets.use",
173
175
  "compute.backendServices.use",
174
176
  "compute.globalOperations.get",
package/src/index.ts CHANGED
@@ -61,6 +61,7 @@ export {
61
61
  } from "./converge-job.js";
62
62
  export { convergeExecutionNameError, gcpConvergeDeps } from "./converge-job-gcp.js";
63
63
  export { INFRA_CONTRACT_VERSION } from "./infra-contract.js";
64
+ export type { HandoverQueue, JobClaim } from "./job-handover.js";
64
65
  export {
65
66
  INFRA_CONTRACT_PATHS,
66
67
  isInfraContractPath,
@@ -106,6 +107,7 @@ export {
106
107
  gcpUpgraderDeps,
107
108
  type UpgraderPlacement,
108
109
  upgraderDatabaseHost,
110
+ upgraderExecutionNameError,
109
111
  } from "./upgrader-gcp.js";
110
112
  export {
111
113
  type ClaimedUpdate,
@@ -115,6 +117,7 @@ export {
115
117
  type UpdateFacts,
116
118
  type UpdateQueue,
117
119
  type UpgraderJobDeps,
120
+ type UpgraderQueue,
118
121
  type UpgraderRunResult,
119
122
  } from "./upgrader-job.js";
120
123
  export type { JobLog } from "./upgrader-reporter.js";
@@ -20,8 +20,9 @@ describe("infrastructure contract steps", () => {
20
20
  );
21
21
  });
22
22
 
23
- it("is at 22: public_role revoke (3), URL-map redirects role (4), no gateway cms_admin login (5), ops-bucket list (6), gateway proxy hops (7), quality-audit job (8), converge job (9), remote MCP (10), Google sign-in (11), project-level sign-in client (12), edge security headers (13), capture job (14), database verify-full TLS (15), MCP-Auth-Proxy (16), staging database (17), scheduler tick (18), scheduler tick as JSON (19), staging gateway (20), gateway budget and plain-gcp repairs (21), per-path Cloud Armor rules (22)", () => {
24
- expect(INFRA_CONTRACT_VERSION).toBe(22);
23
+ it("is at 23: public_role revoke (3), URL-map redirects role (4), no gateway cms_admin login (5), ops-bucket list (6), gateway proxy hops (7), quality-audit job (8), converge job (9), remote MCP (10), Google sign-in (11), project-level sign-in client (12), edge security headers (13), capture job (14), database verify-full TLS (15), MCP-Auth-Proxy (16), staging database (17), scheduler tick (18), scheduler tick as JSON (19), staging gateway (20), gateway budget and plain-gcp repairs (21), per-path Cloud Armor rules (22), site security headers on the backend bucket (23)", () => {
24
+ expect(INFRA_CONTRACT_VERSION).toBe(23);
25
+ expect(INFRA_CONTRACT_STEPS[23]).toContain("#1454");
25
26
  expect(INFRA_CONTRACT_STEPS[3]).toContain("#633");
26
27
  expect(INFRA_CONTRACT_STEPS[4]).toContain("#587");
27
28
  expect(INFRA_CONTRACT_STEPS[5]).toContain("#635");
@@ -52,6 +53,6 @@ describe("infrastructure contract steps", () => {
52
53
  });
53
54
 
54
55
  it("names a version a newer release added by number", () => {
55
- expect(infraStepsText(22, 23)).toBe("infrastructure step 23 (see that release's notes)");
56
+ expect(infraStepsText(23, 24)).toBe("infrastructure step 24 (see that release's notes)");
56
57
  });
57
58
  });
@@ -22,7 +22,7 @@
22
22
  * whose app-roll references infrastructure an install does not have yet fails
23
23
  * at roll time, after migrations ran.
24
24
  */
25
- export const INFRA_CONTRACT_VERSION = 22;
25
+ export const INFRA_CONTRACT_VERSION = 23;
26
26
 
27
27
  // History (why each bump happened — an install below a number needs the
28
28
  // converge that introduced it):
@@ -187,6 +187,18 @@ export const INFRA_CONTRACT_VERSION = 22;
187
187
  // writes the in-cloud upgrader holds no compute rights for, so the
188
188
  // converge applies them (gateway-armor.ts). Other providers have
189
189
  // nothing to converge for it.
190
+ // 23 — #1454: on `gcp` the admin writes a build's page headers (CSP and the
191
+ // rest) to the static backend bucket at Publish live, so its
192
+ // `caeloUrlMapRedirects` role gains `compute.backendBuckets.get` and
193
+ // `.update`, a custom-role change the in-cloud upgrader may not make.
194
+ // Other providers have nothing to converge for it.
195
+ //
196
+ // #1029 is deliberately NOT a bump. The upgrader job's stage 1 moves the job
197
+ // onto the target's ops image with rights it has held on itself since
198
+ // contract 9 (`run.jobs.update`, `run.jobs.run`, `actAs` on its own account),
199
+ // so no install needs a converge for it. It also ends the first reason of
200
+ // bump 21: once an install's job carries #1029, an app-roll runs the target
201
+ // release's code, and "the upgrader rolls with old code" is no reason to bump.
190
202
 
191
203
  /**
192
204
  * What each contract version adds, in operator terms — the upgrader's
@@ -216,6 +228,7 @@ export const INFRA_CONTRACT_STEPS: Readonly<Record<number, string>> = {
216
228
  20: "the staging gateway that serves the staged site behind the staging gate on every address: its service, service account and grants, the private staging bucket, and the staging host's own route (a second Firebase Hosting site, or a host rule and certificate on the load balancer); the live gateway no longer holds the staging gate key (#1330, #1331)",
217
229
  21: "the gateways' scale-out and connection pool kept inside the database connection budget, and on Google Cloud load-balancer installs the gateway open to visitors and the sign-in and staging routes repaired (#1463)",
218
230
  22: "per-path Cloud Armor rules for the visitor and staging gateways on Google Cloud load-balancer installs: a tighter ban on sign-up, login and password reset, a captcha throttle, the general ban only on the visitor API, and fewer false positives from the OWASP rules (#1339)",
231
+ 23: "the admin's permission on Google Cloud load-balancer installs to set the site's security headers on the static backend bucket at Publish live (#1454)",
219
232
  };
220
233
 
221
234
  /**