@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
@@ -9,16 +9,43 @@
9
9
  * `runWithOverrides` — so it cannot pass arguments, env or another image
10
10
  * (upgrader-setup.ts). The job runs as its own service account, which may
11
11
  * deploy Cloud Run revisions, run the migration job and back up Cloud SQL,
12
- * but cannot change IAM, service accounts or secrets. One run:
12
+ * but cannot change IAM, service accounts or secrets.
13
13
  *
14
- * 1. claim the oldest pending request (ending a run that died mid-way);
14
+ * One job, two stages (#1029, the converge job's shape, job-handover.ts),
15
+ * told apart by the release this code belongs to:
16
+ *
17
+ * Stage 1 — the job still runs the ops image of an earlier release:
18
+ *
19
+ * a. claim the request (adopting one whose run ended, or that a stage 1
20
+ * released and no run took);
21
+ * b. read install.json, fetch the target's manifest from the FIXED
22
+ * registry, verify its signature, and refuse an older release
23
+ * (upgrader-assess.ts `assessHandover`);
24
+ * c. ask IAM for the job's rights on itself, verify the target's ops image
25
+ * with cosign, point this job at it BY DIGEST under the state lock,
26
+ * release the request and start a new execution.
27
+ *
28
+ * It decides nothing else on purpose. Every step below runs in the
29
+ * TARGET's code, so a bug in the assessment or the roll reaches only
30
+ * installs that do not have the fix yet, and the release with the fix
31
+ * repairs them by being installed (#1025 could not; #1470 had to raise
32
+ * the infrastructure contract only to get its code to run).
33
+ *
34
+ * A stage 2 that refuses or fails leaves the job on the target's image.
35
+ * That is safe: it is signed, stage 1 only ever moves onto a release not
36
+ * older than install.json's, and the next update moves the job again.
37
+ *
38
+ * Stage 2 — the job runs the target release's own image; one run:
39
+ *
40
+ * 1. claim or adopt the request, with the policy as it stands now;
15
41
  * 2. read what the install runs from install.json in its ops bucket; when
16
42
  * it names other images than the ones serving, judge against the
17
43
  * serving release if a signed release manifest names both its images,
18
44
  * else stop (upgrader-records.ts, #860);
19
45
  * 3. fetch the release manifest from the FIXED registry and verify its
20
46
  * signature (release-manifest.ts) — no registry, identity or digest
21
- * ever comes from the request, the env or argv;
47
+ * ever comes from the request, the env or argv — and check that the
48
+ * image this run executes is the one that manifest signs;
22
49
  * 4. decide (upgrader-assess.ts): refuse a bad signature, a downgrade, a
23
50
  * release below its minFromVersion, an automatic run the policy does
24
51
  * not allow; hand an infrastructure change back (the admin routes
@@ -39,8 +66,13 @@
39
66
  * with the new admin image, admin then gateway, deep health check,
40
67
  * traffic back onto the previous revisions on any failure;
41
68
  * 7. record the new digests + version in install.json (a failed write
42
- * ends the run as failed, never as succeeded);
43
- * 8. move this job onto the release's own ops image, last.
69
+ * ends the run as failed, never as succeeded).
70
+ *
71
+ * A run that dies leaves its request `running`. Starting the job again (the
72
+ * page's "Continue") adopts it once Cloud Run says that run has ended; the
73
+ * new run starts over from step 1, which is safe because each step reads
74
+ * what the last one left. There is no checkpoint: a roll killed half-way
75
+ * rolls nothing back by itself, and step 2 then reports the mixed install.
44
76
  *
45
77
  * Every step is narrated into `platform_update_events` (upgrader-reporter.ts).
46
78
  * All side effects come in through {@link UpgraderJobDeps}, so the whole
@@ -56,8 +88,17 @@ import type {
56
88
  StoredUpdatePolicy,
57
89
  } from "@caelo-cms/shared";
58
90
  import type { GcloudRunner, Sleep } from "./gcloud-retry.js";
59
- import { upgraderJobName } from "./gcp-names.js";
60
91
  import type { InstallMetadata } from "./install-state.js";
92
+ import {
93
+ adoptClaim,
94
+ type HandoverBlocked,
95
+ type HandoverQueue,
96
+ handOverToRelease,
97
+ isStageOne,
98
+ type JobClaim,
99
+ ownImageProblem,
100
+ type SelfHandoverDeps,
101
+ } from "./job-handover.js";
61
102
  import {
62
103
  manifestServiceImages,
63
104
  type ReleaseManifest,
@@ -86,8 +127,7 @@ import {
86
127
  } from "./upgrade/gcp-lookup.js";
87
128
  import type { HealthProbe } from "./upgrade/health.js";
88
129
  import { platformDigestsOf, type ReleaseImageForms } from "./upgrade/image-forms.js";
89
- import { releaseImageRef } from "./upgrade/release-images.js";
90
- import { assessUpgradeRequest, type RefusalCode } from "./upgrader-assess.js";
130
+ import { assessHandover, assessUpgradeRequest, type RefusalCode } from "./upgrader-assess.js";
91
131
  import {
92
132
  type IamTester,
93
133
  preflightErrorReason,
@@ -95,6 +135,7 @@ import {
95
135
  runIamPreflight,
96
136
  UPGRADER_PREFLIGHT_VOICE,
97
137
  upgraderAccessChecks,
138
+ upgraderHandoverChecks,
98
139
  } from "./upgrader-iam-preflight.js";
99
140
  import {
100
141
  findServingRelease,
@@ -159,8 +200,20 @@ export interface UpdateQueue {
159
200
  finish(requestId: string, end: UpdateEnd): Promise<boolean>;
160
201
  }
161
202
 
162
- export interface UpgraderJobDeps {
163
- readonly queue: UpdateQueue;
203
+ /**
204
+ * The upgrader job's view of the database: {@link UpdateQueue} (which the
205
+ * self-hosted agent drives as it is), plus what the two stages need.
206
+ */
207
+ export interface UpgraderQueue extends Omit<UpdateQueue, "claim">, HandoverQueue {
208
+ /**
209
+ * End runs that died long ago, then return the running `app_roll`
210
+ * request, or claim the oldest pending one, with the policy as it stands.
211
+ */
212
+ claimUpgrade(execution: string | null): Promise<JobClaim | null>;
213
+ }
214
+
215
+ export interface UpgraderJobDeps extends SelfHandoverDeps {
216
+ readonly queue: UpgraderQueue;
164
217
  readonly run: GcloudRunner;
165
218
  readonly sleep?: Sleep;
166
219
  /** From the metadata server — never from env or argv. */
@@ -168,8 +221,6 @@ export interface UpgraderJobDeps {
168
221
  readonly region: string;
169
222
  /** Pulumi stack name (`production`). */
170
223
  readonly env: string;
171
- /** This Cloud Run execution, for the log link; null outside Cloud Run. */
172
- readonly execution: string | null;
173
224
  /**
174
225
  * Asks IAM which permissions the job's own account holds (#818), for the
175
226
  * self-check right after the decision. Never the action itself.
@@ -217,11 +268,7 @@ export interface UpgraderRunResult {
217
268
  }
218
269
 
219
270
  /** Why the run cannot go on: how its request ends. */
220
- interface Blocked {
221
- readonly status: UpdateEndStatus;
222
- readonly codes: readonly string[];
223
- readonly reason: string;
224
- }
271
+ type Blocked = HandoverBlocked;
225
272
 
226
273
  type LockOutcome = { readonly ok: true } | ({ readonly ok: false } & Blocked);
227
274
 
@@ -242,37 +289,44 @@ const defaultSleep: Sleep = (ms) => new Promise((resolve) => setTimeout(resolve,
242
289
  /** Run the job once. Never throws; see the file comment for the sequence. */
243
290
  export async function runUpgraderJob(deps: UpgraderJobDeps): Promise<UpgraderRunResult> {
244
291
  const { queue, log } = deps;
245
- let claimed: ClaimedUpdate | null;
292
+ let claim: JobClaim | null;
246
293
  try {
247
- claimed = await queue.claim(deps.execution);
294
+ claim = await queue.claimUpgrade(deps.execution);
248
295
  } catch (e) {
249
296
  log({ severity: "ERROR", message: `could not read update requests: ${errorText(e)}` });
250
297
  return { exitCode: 1, requestId: null, status: null };
251
298
  }
252
- if (!claimed) {
299
+ if (!claim) {
253
300
  log({ severity: "INFO", message: "no pending update request; nothing to do" });
254
301
  return { exitCode: 0, requestId: null, status: null };
255
302
  }
256
- const request = claimed;
303
+ const { request } = claim;
257
304
  const r = eventReporter(
258
305
  (phase, level, message) => queue.event(request.id, phase, level, message),
259
306
  log,
260
307
  request.id,
261
308
  );
309
+ /** This run leaves the request to another (live) run: no end, no events. */
310
+ const leave = (message: string, failed = false): UpgraderRunResult => {
311
+ log({ severity: failed ? "ERROR" : "INFO", message, requestId: request.id });
312
+ return { exitCode: failed ? 1 : 0, requestId: request.id, status: null };
313
+ };
262
314
  let releaseLock: (() => void) | null = null;
315
+ const unlock = () => {
316
+ if (!releaseLock) return;
317
+ try {
318
+ releaseLock();
319
+ } catch (e) {
320
+ r.warn(errorText(e));
321
+ }
322
+ releaseLock = null;
323
+ };
263
324
  const finish = async (end: UpdateEnd): Promise<UpgraderRunResult> => {
264
325
  r.phase("finish");
265
326
  if (end.status === "succeeded") r.success(`Caelo ${request.targetVersion} is installed.`);
266
327
  else r.error(end.reason ?? end.status);
267
328
  await r.flush();
268
- if (releaseLock) {
269
- try {
270
- releaseLock();
271
- } catch (e) {
272
- r.warn(errorText(e));
273
- }
274
- releaseLock = null;
275
- }
329
+ unlock();
276
330
  const recorded = await recordUpdateEnd(queue, request.id, end, log, deps.sleep);
277
331
  const failed = end.status === "failed" || end.status === "rolled_back" || !recorded;
278
332
  return { exitCode: failed ? 1 : 0, requestId: request.id, status: end.status };
@@ -291,10 +345,20 @@ export async function runUpgraderJob(deps: UpgraderJobDeps): Promise<UpgraderRun
291
345
  });
292
346
 
293
347
  try {
348
+ const adoption = await adoptClaim(claim, { ...deps, queue });
349
+ if (adoption.kind === "leave") return leave(adoption.message, adoption.failed);
294
350
  r.phase("start");
295
- r.info(
296
- `Upgrader started${deps.execution ? ` (run ${deps.execution})` : ""}: installing Caelo ${request.targetVersion}.`,
297
- );
351
+ if (!adoption.adopted) {
352
+ r.info(
353
+ `Upgrader started${deps.execution ? ` (run ${deps.execution})` : ""}: installing Caelo ${request.targetVersion}.`,
354
+ );
355
+ } else if (claim.execution === null) {
356
+ r.info(`Caelo ${deps.ownVersion}'s own upgrader took over (run ${deps.execution}).`);
357
+ } else {
358
+ r.info(
359
+ `Continuing the update to ${request.targetVersion} (run ${deps.execution}; the previous run ${claim.execution} stopped before it finished).`,
360
+ );
361
+ }
298
362
 
299
363
  // #815 — the state lock is taken only right before the first write
300
364
  // (lockBeforeWrite below), never before the decision: any lock problem
@@ -347,6 +411,13 @@ export async function runUpgraderJob(deps: UpgraderJobDeps): Promise<UpgraderRun
347
411
  ...read,
348
412
  provider: read.provider,
349
413
  };
414
+
415
+ // #1029 — this image is an earlier release's: the target's own does the
416
+ // rest. Nothing below this line runs in the code being replaced.
417
+ if (isStageOne(deps.ownVersion, request.targetVersion)) {
418
+ return await handOverToTarget(meta, lockBeforeWrite);
419
+ }
420
+
350
421
  /** The corrected records (#860), when install.json is stale; written under the lock. */
351
422
  let heal: InstallMetadata | null = null;
352
423
 
@@ -446,6 +517,14 @@ export async function runUpgraderJob(deps: UpgraderJobDeps): Promise<UpgraderRun
446
517
 
447
518
  // 3 + 4. The signed manifest decides.
448
519
  const manifest = await deps.fetchManifest(request.targetVersion);
520
+ if (manifest.ok) {
521
+ const wrongImage = ownImageProblem(
522
+ manifest.manifest,
523
+ await deps.ownImageDigest(),
524
+ "upgrader",
525
+ );
526
+ if (wrongImage) return stopWith(wrongImage.status, wrongImage.codes, wrongImage.reason);
527
+ }
449
528
  const decision = assessUpgradeRequest({
450
529
  request,
451
530
  manifest,
@@ -538,7 +617,7 @@ export async function runUpgraderJob(deps: UpgraderJobDeps): Promise<UpgraderRun
538
617
  for (const w of planned.plan.warnings) r.warn(w);
539
618
 
540
619
  // Decided, planned: the backup (or the records correction) is the first
541
- // write. Held through the roll, install.json and the self-update.
620
+ // write. Held through the roll and install.json.
542
621
  const blocked = lockAndHeal();
543
622
  if (blocked) return stopWith(blocked.status, blocked.codes, blocked.reason);
544
623
 
@@ -644,25 +723,6 @@ export async function runUpgraderJob(deps: UpgraderJobDeps): Promise<UpgraderRun
644
723
  );
645
724
  }
646
725
 
647
- // 8. Self-update, last: the next run uses this release's upgrader.
648
- r.phase("self-update");
649
- const job = upgraderJobName(deps.env);
650
- const self = await deps.run([
651
- "run",
652
- "jobs",
653
- "update",
654
- job,
655
- `--image=${releaseImageRef("ops", m.digests.ops)}`,
656
- `--region=${deps.region}`,
657
- `--project=${deps.projectId}`,
658
- "--quiet",
659
- ]);
660
- if (self.ok) r.info(`The upgrader itself now runs ${m.version}.`);
661
- else {
662
- r.warn(
663
- `The upgrader could not update itself (${self.stderr.trim().slice(0, 300)}); the next update still works, with this run's upgrader.`,
664
- );
665
- }
666
726
  return finish({ status: "succeeded", reason: null, codes: [], pauseAutoUpdates: false });
667
727
  } catch (e) {
668
728
  return stopWith(
@@ -671,6 +731,70 @@ export async function runUpgraderJob(deps: UpgraderJobDeps): Promise<UpgraderRun
671
731
  `The upgrader stopped unexpectedly: ${errorText(e)}. If the site misbehaves, check Settings → Updates and the job's log.`,
672
732
  );
673
733
  }
734
+
735
+ /** Stage 1: hand the request to the target release's own signed upgrader. */
736
+ async function handOverToTarget(
737
+ meta: InstallMetadata,
738
+ lock: () => LockOutcome,
739
+ ): Promise<UpgraderRunResult> {
740
+ const manifest = await deps.fetchManifest(request.targetVersion);
741
+ const decision = assessHandover({
742
+ request,
743
+ manifest,
744
+ installed: {
745
+ version: meta.releaseVersion ?? null,
746
+ infraContractVersion: meta.infraContractVersion ?? 0,
747
+ },
748
+ policy: request.policy,
749
+ now: deps.now(),
750
+ });
751
+ if (decision.manifest) {
752
+ r.success(
753
+ `Release information of ${decision.manifest.version} verified: signed by Caelo's release workflow.`,
754
+ );
755
+ await recordFacts(queue, request.id, decision.manifest, meta);
756
+ }
757
+ r.phase("assess");
758
+ if (decision.kind === "stop") {
759
+ return stopWith(decision.status, decision.codes, decision.reason);
760
+ }
761
+ const access = await runIamPreflight(
762
+ upgraderHandoverChecks({ projectId: deps.projectId, region: deps.region, env: deps.env }),
763
+ deps.iam,
764
+ );
765
+ if (access.kind === "missing") {
766
+ return stopWith(
767
+ "needs_cloud_shell",
768
+ ["iam-preflight"],
769
+ preflightMissingReason(access.missing, UPGRADER_PREFLIGHT_VOICE),
770
+ );
771
+ }
772
+ if (access.kind === "error") {
773
+ return stopWith(
774
+ "failed",
775
+ ["iam-preflight"],
776
+ preflightErrorReason(access.errors, UPGRADER_PREFLIGHT_VOICE),
777
+ );
778
+ }
779
+ r.info(
780
+ `This upgrader belongs to Caelo ${deps.ownVersion}; handing over to the upgrader of ${decision.manifest.version} itself, so the update is checked and installed by the release that carries it.`,
781
+ );
782
+ return handOverToRelease(decision.manifest, {
783
+ deps,
784
+ queue,
785
+ requestId: request.id,
786
+ noun: "upgrader",
787
+ reporter: r,
788
+ log,
789
+ lock: () => {
790
+ const locked = lock();
791
+ return locked.ok ? null : locked;
792
+ },
793
+ unlock,
794
+ stop: (b) => stopWith(b.status, b.codes, b.reason),
795
+ leave,
796
+ });
797
+ }
674
798
  }
675
799
 
676
800
  /**
@@ -794,7 +918,7 @@ async function templateDigests(
794
918
  }
795
919
 
796
920
  async function recordFacts(
797
- queue: UpdateQueue,
921
+ queue: Pick<UpdateQueue, "record">,
798
922
  requestId: string,
799
923
  m: ReleaseManifest,
800
924
  meta: InstallMetadata,
@@ -14,6 +14,7 @@ import {
14
14
  ensureUpgraderJob,
15
15
  UPGRADER_FORBIDDEN_ROLES,
16
16
  UPGRADER_OPS_LIST_ROLE,
17
+ UPGRADER_RUN_ROLE,
17
18
  UPGRADER_SQL_BACKUP_ROLE,
18
19
  type UpgraderSetupTarget,
19
20
  } from "./upgrader-setup.js";
@@ -126,6 +127,22 @@ describe("ensureUpgraderJob", () => {
126
127
  expect(writes).toEqual(["cloudsql.backupRuns.create"]);
127
128
  });
128
129
 
130
+ it("#1029: the upgrader's job can move and start itself, and only ever as itself", async () => {
131
+ // What the hand-over uses, no more: no overrides anywhere, and actAs on
132
+ // no account of a privileged job, so the upgrader cannot put its job,
133
+ // or any other, under another identity.
134
+ expect(UPGRADER_RUN_ROLE.permissions).toContain("run.jobs.update");
135
+ expect(UPGRADER_RUN_ROLE.permissions).toContain("run.jobs.run");
136
+ expect(UPGRADER_RUN_ROLE.permissions).not.toContain("run.jobs.runWithOverrides");
137
+ expect(UPGRADER_RUN_ROLE.permissions.some((p) => p.endsWith(".setIamPolicy"))).toBe(false);
138
+ const { run, calls } = fakeGcloud();
139
+ expect((await ensureUpgraderJob(TARGET, { run, sleep: async () => {} })).ok).toBe(true);
140
+ const actAs = grants(calls).filter((g) => g.role === "roles/iam.serviceAccountUser");
141
+ expect(actAs.length).toBeGreaterThan(0);
142
+ expect(actAs.some((g) => g.where.includes("caelo-production-upgrader@"))).toBe(true);
143
+ for (const g of actAs) expect(g.where).not.toContain("caelo-provisioner");
144
+ });
145
+
129
146
  it("the admin may start the job without overrides and read it — nothing else", async () => {
130
147
  const { run, calls } = fakeGcloud();
131
148
  await ensureUpgraderJob(TARGET, { run, sleep: async () => {} });
@@ -19,7 +19,10 @@
19
19
  *
20
20
  * - the custom role `caeloUpgraderRun` on the project
21
21
  * ({@link UPGRADER_RUN_ROLE}): deploy admin/gateway revisions, move
22
- * traffic, recreate and run the migration job, update its own job image.
22
+ * traffic, recreate and run the migration job, and move its own job onto
23
+ * the ops image of the release it installs and start it (#1029; stage 1
24
+ * of upgrader-job.ts, without overrides: the target's image runs the
25
+ * command and args this setup deployed).
23
26
  * NOT `roles/run.developer`: that role holds `run.jobs.runWithOverrides`
24
27
  * on every job of the project, including the converge job and the
25
28
  * install job, which run as `caelo-provisioner` — the upgrader could run
@@ -119,7 +122,7 @@ export const UPGRADER_OPS_LIST_ROLE: CustomRoleSpec = {
119
122
 
120
123
  /**
121
124
  * What an app-roll does on Cloud Run (upgrade/app-roll.ts, migration-runner.ts,
122
- * the self-update, the #815 lock lease) — `roles/run.developer` minus
125
+ * the hand-over to the target's image, the #815 lock lease) — `roles/run.developer` minus
123
126
  * everything else, above all `run.jobs.runWithOverrides` (see the file
124
127
  * header). Keep in step with upgrader-iam-preflight.ts.
125
128
  */
@@ -28,7 +28,7 @@ function runner(answer: (args: string[]) => GcloudResult) {
28
28
  }
29
29
 
30
30
  const PERMS =
31
- "--permissions=compute.urlMaps.list,compute.urlMaps.get,compute.urlMaps.update,compute.backendBuckets.use,compute.backendServices.use,compute.globalOperations.get";
31
+ "--permissions=compute.urlMaps.list,compute.urlMaps.get,compute.urlMaps.update,compute.backendBuckets.get,compute.backendBuckets.update,compute.backendBuckets.use,compute.backendServices.use,compute.globalOperations.get";
32
32
  const BIND = [
33
33
  "projects",
34
34
  "add-iam-policy-binding",
@@ -13,7 +13,7 @@
13
13
  import { CAELO_VERSION } from "@caelo-cms/shared";
14
14
  import { cancel, confirm, isCancel, log, note } from "@clack/prompts";
15
15
  import { bold, cyan, dim, green, red, yellow } from "kleur/colors";
16
- import { formatDnsRecordGroups, groupDnsRecords, type InstallDnsRecord } from "../dns/groups.js";
16
+ import { formatDnsRecordGroups, groupDnsRecords } from "../dns/groups.js";
17
17
  import { activeAccount, gcloud } from "../gcloud.js";
18
18
  import type { GcloudRunner, Sleep } from "../gcloud-retry.js";
19
19
  import { realSleep } from "../gcloud-retry.js";
@@ -30,7 +30,9 @@ import {
30
30
  opsImageRef,
31
31
  readExecutionLogs,
32
32
  readInstallJobStatus,
33
+ readRecordedStackOutputs,
33
34
  readSetupLink,
35
+ recordedDnsRecords,
34
36
  startInstallJob,
35
37
  storeInstallSecretValue,
36
38
  } from "../install-job.js";
@@ -44,6 +46,7 @@ import {
44
46
  recordedImageDigests,
45
47
  recordImageDigests,
46
48
  } from "../install-state.js";
49
+ import { issueOwnerSetup } from "../owner-setup-token.js";
47
50
  import { fetchVerifiedReleaseManifest } from "../release-manifest.js";
48
51
  import { selfCommand } from "../self-command.js";
49
52
  import { attachInstall } from "../state-attach.js";
@@ -178,20 +181,35 @@ function logsHint(projectId: string, region: string): string {
178
181
  return `gcloud run jobs executions list --job=${INSTALL_JOB_NAME} --region=${region} --project=${projectId}`;
179
182
  }
180
183
 
181
- /** Print that closing the tab is fine; exit 130 on Ctrl-C with the re-attach hint. */
182
- function announceDetachable(projectId: string, execution: string): void {
184
+ /**
185
+ * What the terminal says before it hands the install to the job (#822): the
186
+ * tab may close, and the one command that shows where the install stands
187
+ * from any terminal.
188
+ */
189
+ export function handoffLines(projectId: string): string[] {
190
+ return [
191
+ bold(yellow("You may close this tab now.")),
192
+ "The install keeps running in your Google Cloud project. To see where it stands",
193
+ "(phase, DNS records, admin URL, Owner setup link), run this in any terminal",
194
+ "signed in to gcloud:",
195
+ "",
196
+ ` ${bold(cyan(selfCommand("status", "--project", projectId)))}`,
197
+ ];
198
+ }
199
+
200
+ /** Print {@link handoffLines}, highlighted. */
201
+ function announceHandoff(projectId: string): void {
202
+ note(handoffLines(projectId).join("\n"), "The install runs on its own from here");
203
+ }
204
+
205
+ /** Name the job being followed; exit 130 on Ctrl-C with the way back. */
206
+ function announceFollowing(projectId: string, execution: string): void {
183
207
  log.info(
184
- [
185
- `The install runs in your project as Cloud Run job ${bold(INSTALL_JOB_NAME)} (execution ${dim(execution)}).`,
186
- dim(
187
- "Closing this tab, Ctrl-C or Cloud Shell's idle timeout does not stop it. To follow it again, re-open the",
188
- ),
189
- dim(`"Open in Cloud Shell" link (or re-run the same command) and pick project ${projectId}.`),
190
- ].join("\n"),
208
+ `The install runs in your project as Cloud Run job ${bold(INSTALL_JOB_NAME)} (execution ${dim(execution)}).`,
191
209
  );
192
210
  process.once("SIGINT", () => {
193
211
  process.stdout.write(
194
- `\nStopped following. The install keeps running in ${projectId}; re-run to attach again.\n`,
212
+ `\nStopped following. The install keeps running in ${projectId}; to see where it stands: ${selfCommand("status", "--project", projectId)}\n`,
195
213
  );
196
214
  process.exit(130);
197
215
  });
@@ -201,7 +219,7 @@ function announceDetachable(projectId: string, execution: string): void {
201
219
  async function followToTheEnd(meta: InstallMetadata, execution: string): Promise<void> {
202
220
  const projectId = meta.projectId ?? "";
203
221
  const region = meta.region ?? "";
204
- announceDetachable(projectId, execution);
222
+ announceFollowing(projectId, execution);
205
223
  const outcome = await tailInstallJob({ projectId, region, execution });
206
224
  if (outcome.kind === "succeeded") {
207
225
  await showResult(meta);
@@ -231,24 +249,18 @@ async function showResult(meta: InstallMetadata): Promise<void> {
231
249
  process.exit(1);
232
250
  }
233
251
  const adminBase = new URL(link).origin;
252
+ // #1476 — this run may come days after the install: a link past its 24 hours
253
+ // is replaced here instead of being shown again.
254
+ if (!meta.region) throw new Error(`install.json of ${meta.installId} records no region.`);
255
+ const issued = await issueOwnerSetup(gcloud, { projectId, region: meta.region }, adminBase);
256
+ if (!issued.ok) {
257
+ cancel(`Could not store the Owner setup link: ${issued.error}`);
258
+ process.exit(1);
259
+ }
234
260
  // The records from the stack's outputs, as the pulumi-up step recorded
235
261
  // them — not from the log, which a re-run after the install no longer shows.
236
262
  // Uncached: this process may hold progress.json from before the job ran.
237
- const progressText = new GcsStateStore(
238
- opsBucketName(projectId),
239
- installRoot(meta.installId),
240
- realSyncGcloud,
241
- ).peek("progress.json");
242
- const progress = progressText
243
- ? (JSON.parse(progressText) as { steps?: Record<string, unknown> })
244
- : {};
245
- const pulumiUp = progress.steps?.[`pulumi-up-${projectId}`] as
246
- | { outputs?: Record<string, unknown> }
247
- | undefined;
248
- const outputs = pulumiUp?.outputs ?? {};
249
- const records = Array.isArray(outputs.dnsRecordsRequiredOut)
250
- ? (outputs.dnsRecordsRequiredOut as InstallDnsRecord[])
251
- : [];
263
+ const records = recordedDnsRecords(readRecordedStackOutputs(projectId, realSyncGcloud));
252
264
  const dnsLines =
253
265
  records.length > 0
254
266
  ? [
@@ -266,7 +278,7 @@ async function showResult(meta: InstallMetadata): Promise<void> {
266
278
  "",
267
279
  bold("Next steps:"),
268
280
  ` 1. Owner setup — open in your browser (sign in with ${meta.ownerEmail}):`,
269
- ` ${cyan(link)}`,
281
+ ` ${cyan(issued.link)} ${dim(`(valid until ${issued.expiresAt})`)}`,
270
282
  ` 2. AI provider — visit ${cyan(`${adminBase}/settings/ai`)} and paste your Anthropic API key.`,
271
283
  ` 3. Set the go-live DNS records above once your new site is published`,
272
284
  ` (the admin lists them too, at ${cyan(`${adminBase}/settings/domains`)}).`,
@@ -295,6 +307,7 @@ export async function launchInstallJob(opts: {
295
307
  if (!meta) throw new Error(`No install.json for install '${installId}'.`);
296
308
  const decision = await decide(gcloud, realSyncGcloud, { projectId, region });
297
309
  if (decision.kind === "attach") {
310
+ announceHandoff(projectId);
298
311
  await followToTheEnd(meta, decision.status.execution);
299
312
  return;
300
313
  }
@@ -345,8 +358,10 @@ export async function launchInstallJob(opts: {
345
358
  const now = await decide(gcloud, realSyncGcloud, { projectId, region });
346
359
  if (now.kind !== "start") {
347
360
  release();
348
- if (now.kind === "attach") await followToTheEnd(meta, now.status.execution);
349
- else await showResult(meta);
361
+ if (now.kind === "attach") {
362
+ announceHandoff(projectId);
363
+ await followToTheEnd(meta, now.status.execution);
364
+ } else await showResult(meta);
350
365
  return;
351
366
  }
352
367
  // Automatic DNS in the job (dns/cloudflare.ts) when this shell has a
@@ -369,6 +384,7 @@ export async function launchInstallJob(opts: {
369
384
  `DNS: the job sets the records through Cloudflare (token stored in Secret Manager as ${INSTALL_CLOUDFLARE_TOKEN_SECRET}).`,
370
385
  );
371
386
  }
387
+ announceHandoff(projectId);
372
388
  const started = await startInstallJob(gcloud, {
373
389
  projectId,
374
390
  region,
@@ -460,6 +476,7 @@ export async function prepareJobModeInstall(opts: {
460
476
  if (!meta.region) return { kind: "existing", meta };
461
477
  const decision = await decide(gcloud, realSyncGcloud, { projectId, region: meta.region });
462
478
  if (decision.kind === "attach") {
479
+ announceHandoff(projectId);
463
480
  await followToTheEnd(meta, decision.status.execution);
464
481
  return { kind: "handled" };
465
482
  }
@@ -470,37 +487,74 @@ export async function prepareJobModeInstall(opts: {
470
487
  return { kind: "existing", meta };
471
488
  }
472
489
 
490
+ /** The command that follows or resumes the install in `meta`'s project, on any machine. */
491
+ export function installerCommand(meta: Pick<InstallMetadata, "provider" | "projectId">): string {
492
+ return selfCommand(
493
+ "--provider",
494
+ meta.provider,
495
+ "--install-job",
496
+ "--project-id",
497
+ meta.projectId ?? "<gcp-project-id>",
498
+ );
499
+ }
500
+
501
+ /** How the install job stands: what the bucket records and what that means. */
502
+ export interface InstallJobView {
503
+ readonly status: InstallJobStatus;
504
+ readonly decision: InstallJobDecision;
505
+ }
506
+
473
507
  /**
474
- * `status`'s view of the install job: what the bucket records and, for a
475
- * run that claims to be running, whether its execution still is. Empty
476
- * when the install never used the job.
508
+ * What the bucket records about the install job and, for a run that claims
509
+ * to be running, whether its execution still is. Null when the install
510
+ * never used the job.
477
511
  */
478
- export async function installJobStatusLines(
479
- meta: InstallMetadata,
480
- deps: { run: GcloudRunner; syncRun: SyncGcloud } = { run: gcloud, syncRun: realSyncGcloud },
481
- ): Promise<string[]> {
482
- if (!meta.projectId || !meta.region) return [];
512
+ export async function readInstallJobView(
513
+ meta: Pick<InstallMetadata, "projectId" | "region">,
514
+ deps: { run: GcloudRunner; syncRun: SyncGcloud },
515
+ ): Promise<InstallJobView | null> {
516
+ if (!meta.projectId || !meta.region) return null;
483
517
  const status = readInstallJobStatus(opsBucketName(meta.projectId), deps.syncRun);
484
- if (!status) return [];
485
- const decision = decideInstallJob(
486
- status,
518
+ if (!status) return null;
519
+ const live =
487
520
  status.state === "running"
488
521
  ? await describeExecution(deps.run, {
489
522
  projectId: meta.projectId,
490
523
  region: meta.region,
491
524
  execution: status.execution,
492
525
  })
493
- : null,
494
- );
495
- const head = `Install job: ${status.state} — ${status.phase} ${dim(`(v${status.caeloVersion}, execution ${status.execution}, updated ${status.updatedAt})`)}`;
496
- const lines = [head];
526
+ : null;
527
+ return { status, decision: decideInstallJob(status, live) };
528
+ }
529
+
530
+ /** {@link InstallJobView} as `status` prints it, with the command that goes on from there. */
531
+ export function installJobViewLines(
532
+ view: InstallJobView,
533
+ meta: Pick<InstallMetadata, "provider" | "projectId">,
534
+ ): string[] {
535
+ const { status, decision } = view;
536
+ const lines = [
537
+ `Install job: ${status.state} — ${status.phase} ${dim(`(v${status.caeloVersion}, execution ${status.execution}, updated ${status.updatedAt})`)}`,
538
+ ];
497
539
  if (status.detail) lines.push(` ${status.detail}`);
498
540
  if (decision.kind === "attach") {
499
- lines.push(` Follow it: re-run the installer for project ${meta.projectId} (it attaches).`);
541
+ lines.push(` Follow it live: ${installerCommand(meta)}`);
500
542
  } else if (decision.kind === "start") {
501
543
  lines.push(
502
- ` Not finished (${decision.why}). Re-run the installer for project ${meta.projectId}; it resumes where this run stopped.`,
544
+ ` Not finished (${decision.why}). Resume it where this run stopped: ${installerCommand(meta)}`,
503
545
  );
504
546
  }
505
547
  return lines;
506
548
  }
549
+
550
+ /**
551
+ * `status`'s view of the install job as text. Empty when the install never
552
+ * used the job.
553
+ */
554
+ export async function installJobStatusLines(
555
+ meta: InstallMetadata,
556
+ deps: { run: GcloudRunner; syncRun: SyncGcloud } = { run: gcloud, syncRun: realSyncGcloud },
557
+ ): Promise<string[]> {
558
+ const view = await readInstallJobView(meta, deps);
559
+ return view ? installJobViewLines(view, meta) : [];
560
+ }