@caelo-cms/provisioning 0.11.20 → 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 (170) hide show
  1. package/dist/adapter.d.ts +6 -1
  2. package/dist/adapter.d.ts.map +1 -1
  3. package/dist/admin-internal-google.d.ts +13 -1
  4. package/dist/admin-internal-google.d.ts.map +1 -1
  5. package/dist/admin-internal-google.js +47 -0
  6. package/dist/admin-internal-google.js.map +1 -1
  7. package/dist/agent/command.d.ts +1 -1
  8. package/dist/agent-db.js +133 -8
  9. package/dist/bootstrap-token.d.ts +4 -3
  10. package/dist/bootstrap-token.d.ts.map +1 -1
  11. package/dist/bootstrap-token.js.map +1 -1
  12. package/dist/cli-routing.d.ts.map +1 -1
  13. package/dist/cli-routing.js +7 -2
  14. package/dist/cli-routing.js.map +1 -1
  15. package/dist/cli.js +9 -0
  16. package/dist/cli.js.map +1 -1
  17. package/dist/converge-checkpoint.d.ts +6 -0
  18. package/dist/converge-checkpoint.d.ts.map +1 -1
  19. package/dist/converge-job-gcp.d.ts +1 -16
  20. package/dist/converge-job-gcp.d.ts.map +1 -1
  21. package/dist/converge-job-gcp.js +10 -97
  22. package/dist/converge-job-gcp.js.map +1 -1
  23. package/dist/converge-job.d.ts +7 -46
  24. package/dist/converge-job.d.ts.map +1 -1
  25. package/dist/converge-job.js +22 -57
  26. package/dist/converge-job.js.map +1 -1
  27. package/dist/dns/manual.d.ts +5 -1
  28. package/dist/dns/manual.d.ts.map +1 -1
  29. package/dist/dns/manual.js +2 -1
  30. package/dist/dns/manual.js.map +1 -1
  31. package/dist/gateway-armor.d.ts.map +1 -1
  32. package/dist/gateway-armor.js +11 -3
  33. package/dist/gateway-armor.js.map +1 -1
  34. package/dist/gcp-names.d.ts +2 -0
  35. package/dist/gcp-names.d.ts.map +1 -1
  36. package/dist/gcp-names.js +4 -0
  37. package/dist/gcp-names.js.map +1 -1
  38. package/dist/index.d.ts +3 -2
  39. package/dist/index.d.ts.map +1 -1
  40. package/dist/index.js +1 -1
  41. package/dist/index.js.map +1 -1
  42. package/dist/infra-contract.d.ts +1 -1
  43. package/dist/infra-contract.d.ts.map +1 -1
  44. package/dist/infra-contract.js +14 -1
  45. package/dist/infra-contract.js.map +1 -1
  46. package/dist/install-job-runner.d.ts.map +1 -1
  47. package/dist/install-job-runner.js +4 -3
  48. package/dist/install-job-runner.js.map +1 -1
  49. package/dist/install-job.d.ts +25 -1
  50. package/dist/install-job.d.ts.map +1 -1
  51. package/dist/install-job.js +72 -3
  52. package/dist/install-job.js.map +1 -1
  53. package/dist/job-handover-gcp.d.ts +40 -0
  54. package/dist/job-handover-gcp.d.ts.map +1 -0
  55. package/dist/job-handover-gcp.js +108 -0
  56. package/dist/job-handover-gcp.js.map +1 -0
  57. package/dist/job-handover.d.ts +141 -0
  58. package/dist/job-handover.d.ts.map +1 -0
  59. package/dist/job-handover.js +141 -0
  60. package/dist/job-handover.js.map +1 -0
  61. package/dist/operator-access.d.ts +7 -2
  62. package/dist/operator-access.d.ts.map +1 -1
  63. package/dist/operator-access.js +37 -6
  64. package/dist/operator-access.js.map +1 -1
  65. package/dist/owner-setup-token.d.ts +52 -0
  66. package/dist/owner-setup-token.d.ts.map +1 -0
  67. package/dist/owner-setup-token.js +111 -0
  68. package/dist/owner-setup-token.js.map +1 -0
  69. package/dist/project-status.d.ts +128 -0
  70. package/dist/project-status.d.ts.map +1 -0
  71. package/dist/project-status.js +303 -0
  72. package/dist/project-status.js.map +1 -0
  73. package/dist/stack-converge.d.ts.map +1 -1
  74. package/dist/stack-converge.js +9 -5
  75. package/dist/stack-converge.js.map +1 -1
  76. package/dist/state-attach.d.ts +17 -0
  77. package/dist/state-attach.d.ts.map +1 -1
  78. package/dist/state-attach.js +27 -9
  79. package/dist/state-attach.js.map +1 -1
  80. package/dist/static-security-headers.d.ts +6 -0
  81. package/dist/static-security-headers.d.ts.map +1 -1
  82. package/dist/static-security-headers.js +11 -1
  83. package/dist/static-security-headers.js.map +1 -1
  84. package/dist/upgrader-assess.d.ts +30 -3
  85. package/dist/upgrader-assess.d.ts.map +1 -1
  86. package/dist/upgrader-assess.js +77 -24
  87. package/dist/upgrader-assess.js.map +1 -1
  88. package/dist/upgrader-gcp.d.ts +4 -2
  89. package/dist/upgrader-gcp.d.ts.map +1 -1
  90. package/dist/upgrader-gcp.js +16 -3
  91. package/dist/upgrader-gcp.js.map +1 -1
  92. package/dist/upgrader-iam-preflight.d.ts +14 -3
  93. package/dist/upgrader-iam-preflight.d.ts.map +1 -1
  94. package/dist/upgrader-iam-preflight.js +40 -6
  95. package/dist/upgrader-iam-preflight.js.map +1 -1
  96. package/dist/upgrader-job.d.ts +51 -9
  97. package/dist/upgrader-job.d.ts.map +1 -1
  98. package/dist/upgrader-job.js +92 -37
  99. package/dist/upgrader-job.js.map +1 -1
  100. package/dist/upgrader-setup.d.ts +1 -1
  101. package/dist/upgrader-setup.d.ts.map +1 -1
  102. package/dist/upgrader-setup.js +5 -2
  103. package/dist/upgrader-setup.js.map +1 -1
  104. package/dist/wizards/gcp-install-job.d.ts +27 -4
  105. package/dist/wizards/gcp-install-job.d.ts.map +1 -1
  106. package/dist/wizards/gcp-install-job.js +73 -33
  107. package/dist/wizards/gcp-install-job.js.map +1 -1
  108. package/dist/wizards/gcp-pulumi.d.ts +0 -13
  109. package/dist/wizards/gcp-pulumi.d.ts.map +1 -1
  110. package/dist/wizards/gcp-pulumi.js +0 -12
  111. package/dist/wizards/gcp-pulumi.js.map +1 -1
  112. package/dist/wizards/gcp.d.ts +3 -0
  113. package/dist/wizards/gcp.d.ts.map +1 -1
  114. package/dist/wizards/gcp.js +30 -53
  115. package/dist/wizards/gcp.js.map +1 -1
  116. package/package.json +2 -2
  117. package/src/adapter.ts +6 -1
  118. package/src/admin-internal-google.ts +48 -0
  119. package/src/bootstrap-token.ts +4 -3
  120. package/src/caddy-redirects.docker.test.ts +5 -0
  121. package/src/cli-routing.test.ts +1 -1
  122. package/src/cli-routing.ts +9 -2
  123. package/src/cli.ts +9 -0
  124. package/src/converge-job-gcp.test.ts +1 -40
  125. package/src/converge-job-gcp.ts +10 -100
  126. package/src/converge-job.test.ts +9 -3
  127. package/src/converge-job.ts +33 -115
  128. package/src/dns/manual.ts +4 -1
  129. package/src/gateway-armor.ts +14 -3
  130. package/src/gateway-edge.test.ts +16 -1
  131. package/src/gcp-names.ts +4 -0
  132. package/src/gcp-url-map.test.ts +2 -0
  133. package/src/index.ts +3 -0
  134. package/src/infra-contract.test.ts +4 -3
  135. package/src/infra-contract.ts +14 -1
  136. package/src/install-job-runner.ts +4 -2
  137. package/src/install-job.ts +86 -4
  138. package/src/job-handover-gcp.test.ts +129 -0
  139. package/src/job-handover-gcp.ts +135 -0
  140. package/src/job-handover.ts +259 -0
  141. package/src/operator-access.test.ts +43 -0
  142. package/src/operator-access.ts +38 -6
  143. package/src/owner-setup-token.test.ts +195 -0
  144. package/src/owner-setup-token.ts +138 -0
  145. package/src/project-status.test.ts +571 -0
  146. package/src/project-status.ts +430 -0
  147. package/src/stack-converge.ts +12 -5
  148. package/src/state-attach.ts +46 -16
  149. package/src/static-security-headers.test.ts +16 -0
  150. package/src/static-security-headers.ts +12 -1
  151. package/src/upgrader-assess.test.ts +75 -1
  152. package/src/upgrader-assess.ts +121 -57
  153. package/src/upgrader-gcp.ts +19 -5
  154. package/src/upgrader-iam-preflight.test.ts +28 -1
  155. package/src/upgrader-iam-preflight.ts +46 -6
  156. package/src/upgrader-job.test.ts +365 -31
  157. package/src/upgrader-job.ts +177 -53
  158. package/src/upgrader-setup.test.ts +17 -0
  159. package/src/upgrader-setup.ts +5 -2
  160. package/src/url-map-redirects-access.test.ts +1 -1
  161. package/src/wizards/gcp-install-job.ts +101 -47
  162. package/src/wizards/gcp-pulumi.ts +0 -18
  163. package/src/wizards/gcp.ts +37 -67
  164. package/stacks/aws/README.md +4 -2
  165. package/stacks/aws/index.ts +4 -8
  166. package/stacks/azure/README.md +4 -2
  167. package/stacks/azure/index.ts +4 -8
  168. package/stacks/gcp/README.md +6 -3
  169. package/stacks/gcp/index.ts +7 -8
  170. package/stacks/gcp-firebase/index.ts +4 -6
@@ -88,8 +88,9 @@ export const CLI_COMMANDS: readonly CliCommandDoc[] = [
88
88
  },
89
89
  {
90
90
  name: "status",
91
- args: "[--install <id|domain|all>]",
92
- summary: "Show the install's health and its estimated monthly cost.",
91
+ args: "[--install <id|domain|all>] [--project <gcp-project-id>]",
92
+ summary:
93
+ "Show the install's health and its estimated monthly cost. With --project, show from any terminal signed in to gcloud where an install in that project stands: phase, DNS records still to set, admin URL and Owner setup link.",
93
94
  },
94
95
  {
95
96
  name: "upgrade",
@@ -148,6 +149,12 @@ export const CLI_COMMANDS: readonly CliCommandDoc[] = [
148
149
  summary:
149
150
  "Print a one-time password-reset link for a locked-out Owner on installs whose admin cannot send email.",
150
151
  },
152
+ {
153
+ name: "setup-link",
154
+ args: "--project <gcp-project-id>",
155
+ summary:
156
+ "Print a working Owner setup link for an install that has no Owner yet, from any terminal signed in to gcloud. A link lasts 24 hours; this replaces an expired one.",
157
+ },
151
158
  {
152
159
  name: "state migrate",
153
160
  args: "[--install <id|domain>] [--to remote|local] [--dry-run] [--yes]",
package/src/cli.ts CHANGED
@@ -32,6 +32,8 @@
32
32
  * a backup, restarts, health-checks.
33
33
  * status — prints container health + cert
34
34
  * expiry per domain.
35
+ * setup-link --project <id> — Google Cloud: a working Owner setup
36
+ * link, from any signed-in terminal.
35
37
  *
36
38
  * Pulumi-driven cloud variants (GCP / AWS / Azure) land in P15 and
37
39
  * plug into the same CLI via `--provider <name>`.
@@ -1265,6 +1267,8 @@ const handlers: Record<string, () => Promise<void>> = {
1265
1267
  "admin-domain": adminDomain,
1266
1268
  "staging-domain": stagingDomain,
1267
1269
  "owner-reset": ownerReset,
1270
+ // #1476 — a late Owner's new link.
1271
+ "setup-link": async () => (await import("./project-status.js")).setupLinkCommand(process.argv),
1268
1272
  // #696 — Pulumi state in the install's own project.
1269
1273
  state: async () => (await import("./state-command.js")).stateCommand(process.argv),
1270
1274
  attach: async () => (await import("./state-command.js")).attachCommand(process.argv),
@@ -1284,6 +1288,11 @@ const handlers: Record<string, () => Promise<void>> = {
1284
1288
  };
1285
1289
 
1286
1290
  async function lifecycleStatus(): Promise<void> {
1291
+ if (process.argv.includes("--project")) {
1292
+ const { projectStatusCommand } = await import("./project-status.js");
1293
+ await projectStatusCommand(process.argv);
1294
+ return;
1295
+ }
1287
1296
  const { statusCommand } = await import("./lifecycle.js");
1288
1297
  await statusCommand();
1289
1298
  }
@@ -2,8 +2,7 @@
2
2
 
3
3
  /**
4
4
  * The parts of the converge job's Google Cloud wiring (#819) that parse
5
- * what gcloud says — which image an execution runs, which execution a
6
- * hand-over started — and its checkpoint document in the ops bucket.
5
+ * what gcloud says, and its checkpoint document in the ops bucket.
7
6
  */
8
7
 
9
8
  import { describe, expect, it } from "bun:test";
@@ -17,49 +16,11 @@ import {
17
16
  convergeExecutionNameError,
18
17
  deployedOwnerMismatch,
19
18
  deployedSiteMismatch,
20
- executionImageDigest,
21
- startedExecutionName,
22
19
  } from "./converge-job-gcp.js";
23
20
  import type { GcloudResult } from "./gcloud.js";
24
21
  import type { SyncGcloud } from "./state-store.js";
25
22
  import { installStateCondition } from "./upgrader-setup.js";
26
23
 
27
- const D = `sha256:${"c".repeat(64)}`;
28
- const OPS = `europe-west1-docker.pkg.dev/caelo-website/caelo-cms-images/ops@${D}`;
29
-
30
- describe("executionImageDigest", () => {
31
- it("reads the digest from gcloud's v1 execution (and the v2 shape)", () => {
32
- const v1 = { spec: { template: { spec: { containers: [{ image: OPS }] } } } };
33
- expect(executionImageDigest(JSON.stringify(v1))).toBe(D);
34
- expect(
35
- executionImageDigest(JSON.stringify({ template: { containers: [{ image: OPS }] } })),
36
- ).toBe(D);
37
- });
38
-
39
- it("is null for a tag, no container or unreadable output — never a guess", () => {
40
- const tag = { spec: { template: { spec: { containers: [{ image: "x/ops:0.11.0" }] } } } };
41
- expect(executionImageDigest(JSON.stringify(tag))).toBeNull();
42
- expect(executionImageDigest("{}")).toBeNull();
43
- expect(executionImageDigest("not json")).toBeNull();
44
- });
45
- });
46
-
47
- describe("startedExecutionName", () => {
48
- it("takes the name gcloud prints, or the one it announces on stderr", () => {
49
- expect(startedExecutionName("caelo-production-converge-x7k2p\n", "")).toBe(
50
- "caelo-production-converge-x7k2p",
51
- );
52
- expect(
53
- startedExecutionName(
54
- "",
55
- "Execution [caelo-production-converge-q1w2e] has successfully started",
56
- ),
57
- ).toBe("caelo-production-converge-q1w2e");
58
- expect(startedExecutionName("", "")).toBeNull();
59
- expect(startedExecutionName("Bad Name; rm -rf", "")).toBeNull();
60
- });
61
- });
62
-
63
24
  describe("the converge checkpoint", () => {
64
25
  const BUCKET = "acme-caelo-ops";
65
26
  const fakeBucket = () => {
@@ -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
package/src/dns/manual.ts CHANGED
@@ -101,7 +101,10 @@ function recordKey(r: DnsRecord): string {
101
101
  return `${r.type}:${r.hostname}`;
102
102
  }
103
103
 
104
- async function checkRecord(record: DnsRecord): Promise<boolean> {
104
+ /** Whether public DNS answers `record` with its value right now. */
105
+ export async function checkRecord(
106
+ record: Pick<DnsRecord, "hostname" | "value"> & { readonly type: string },
107
+ ): Promise<boolean> {
105
108
  try {
106
109
  if (record.type === "A") {
107
110
  const result = await dns.resolve4(record.hostname);
@@ -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";