@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
@@ -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",
@@ -46,6 +46,7 @@ import {
46
46
  recordedImageDigests,
47
47
  recordImageDigests,
48
48
  } from "../install-state.js";
49
+ import { issueOwnerSetup } from "../owner-setup-token.js";
49
50
  import { fetchVerifiedReleaseManifest } from "../release-manifest.js";
50
51
  import { selfCommand } from "../self-command.js";
51
52
  import { attachInstall } from "../state-attach.js";
@@ -248,6 +249,14 @@ async function showResult(meta: InstallMetadata): Promise<void> {
248
249
  process.exit(1);
249
250
  }
250
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
+ }
251
260
  // The records from the stack's outputs, as the pulumi-up step recorded
252
261
  // them — not from the log, which a re-run after the install no longer shows.
253
262
  // Uncached: this process may hold progress.json from before the job ran.
@@ -269,7 +278,7 @@ async function showResult(meta: InstallMetadata): Promise<void> {
269
278
  "",
270
279
  bold("Next steps:"),
271
280
  ` 1. Owner setup — open in your browser (sign in with ${meta.ownerEmail}):`,
272
- ` ${cyan(link)}`,
281
+ ` ${cyan(issued.link)} ${dim(`(valid until ${issued.expiresAt})`)}`,
273
282
  ` 2. AI provider — visit ${cyan(`${adminBase}/settings/ai`)} and paste your Anthropic API key.`,
274
283
  ` 3. Set the go-live DNS records above once your new site is published`,
275
284
  ` (the admin lists them too, at ${cyan(`${adminBase}/settings/domains`)}).`,
@@ -281,24 +281,6 @@ export function presentImageOverrides(
281
281
  return imageOverrideKeys(provider).filter((k) => config !== undefined && k in config);
282
282
  }
283
283
 
284
- /**
285
- * One output of the install's stack, secrets included (the Automation API's
286
- * `pulumi stack output --show-secrets`). Read at the moment of use, never
287
- * checkpointed (#656). Needs the `pulumi` CLI and the stack's state.
288
- *
289
- * @returns the output's value, or undefined when the stack has no such output
290
- */
291
- export async function readStackOutput(inputs: {
292
- installRoot: string;
293
- backend: ResolvedBackend;
294
- provider: "gcp" | "gcp-firebase";
295
- name: string;
296
- }): Promise<unknown> {
297
- const stack = await selectInstallStack(inputs.installRoot, inputs.backend, inputs.provider);
298
- const outputs = await stack.outputs();
299
- return outputs[inputs.name]?.value;
300
- }
301
-
302
284
  /**
303
285
  * The install's stack settings file with secrets settings that can't
304
286
  * contradict its state, or null when it is already fine (#696).
@@ -80,7 +80,7 @@ import {
80
80
  upgraderServiceAccountEmail,
81
81
  } from "../gcp-names.js";
82
82
  import { INFRA_CONTRACT_VERSION } from "../infra-contract.js";
83
- import { INSTALL_JOB_NAME, INSTALL_JOB_ROLES, storeSetupLink } from "../install-job.js";
83
+ import { INSTALL_JOB_NAME, INSTALL_JOB_ROLES } from "../install-job.js";
84
84
  import {
85
85
  adoptStateBackend,
86
86
  ensureInstallDir,
@@ -105,6 +105,7 @@ import {
105
105
  resolveOperatorAccessTarget,
106
106
  } from "../operator-access.js";
107
107
  import { ensureOpsBackend } from "../ops-backend.js";
108
+ import { issueOwnerSetup } from "../owner-setup-token.js";
108
109
  import { formatPlan, type PlannedStep, planGate, writePlanFile } from "../preview-plan.js";
109
110
  import {
110
111
  convergeKeylessProvisioner,
@@ -156,12 +157,7 @@ import { ensureUpgraderJob, resolveUpgraderTarget } from "../upgrader-setup.js";
156
157
  import { ensureUrlMapRedirectsAccess } from "../url-map-redirects-access.js";
157
158
  import { estimateGcpCost } from "./gcp-cost.js";
158
159
  import { promptProjectId } from "./gcp-prompts.js";
159
- import {
160
- GCP_STACK_KNOB_DEFAULTS,
161
- PulumiUpDeclinedError,
162
- pulumiUpGcp,
163
- readStackOutput,
164
- } from "./gcp-pulumi.js";
160
+ import { GCP_STACK_KNOB_DEFAULTS, PulumiUpDeclinedError, pulumiUpGcp } from "./gcp-pulumi.js";
165
161
 
166
162
  export interface GcpWizardOpts {
167
163
  installId: string;
@@ -2459,32 +2455,6 @@ async function stepUploadStaticPlaceholder(
2459
2455
  markStepDone(installId, stepName, { bucket: bucketName });
2460
2456
  }
2461
2457
 
2462
- /**
2463
- * The Owner setup link from the install's stack (`bootstrapUrlOut`). A
2464
- * secret: read here, at the moment it is shown, never checkpointed (#656).
2465
- * Fails loudly when the stack can't be read: the run's last step, so a
2466
- * re-run picks it up.
2467
- */
2468
- async function readBootstrapUrl(installId: string, provider: string): Promise<string> {
2469
- const meta = readMetadata(installId);
2470
- if (!meta) throw new Error(`No install.json for install '${installId}'.`);
2471
- const value = await readStackOutput({
2472
- installRoot: installRoot(installId),
2473
- backend: resolveBackend(meta, {
2474
- installRoot: installRoot(installId),
2475
- readPassphrase: () => readSecret(installId, "pulumi-passphrase"),
2476
- }),
2477
- provider: provider === "gcp-firebase" ? "gcp-firebase" : "gcp",
2478
- name: "bootstrapUrlOut",
2479
- });
2480
- if (typeof value !== "string" || value === "") {
2481
- throw new Error(
2482
- "The stack has no bootstrapUrlOut output. Re-run the installer to refresh the stack.",
2483
- );
2484
- }
2485
- return value;
2486
- }
2487
-
2488
2458
  /** The install's Pulumi outputs, as the `pulumi-up` step recorded them. */
2489
2459
  async function recordedStackOutputs(
2490
2460
  installId: string,
@@ -2573,36 +2543,30 @@ async function stepFinalize(installId: string, setupLink: "print" | "secret"): P
2573
2543
 
2574
2544
  // v0.3.15 — On gcp-firebase, the admin DomainMapping is opt-in
2575
2545
  // (`provisionAdminDomain=true` after Search Console verification);
2576
- // without it, `admin.<domain>` doesn't resolve and the bootstrap
2577
- // URL must point at the Cloud Run-generated *.run.app URL. The
2578
- // bootstrap token in Pulumi's output already includes the right
2579
- // path + query; we just swap the host.
2580
- //
2581
- // #656 — the link carries the setup token, so it is never checkpointed;
2582
- // it is read from the stack here, where it is shown.
2583
- const stackBootstrapUrl = await readBootstrapUrl(installId, provider);
2584
- const bootstrapToken = stackBootstrapUrl.match(/token=([^&]+)/)?.[1] ?? "";
2585
- const bootstrapUrl =
2586
- provider === "gcp-firebase" && adminCloudRunUrl.length > 0
2587
- ? `${adminCloudRunUrl}/setup?token=${bootstrapToken}`
2588
- : stackBootstrapUrl;
2589
- // #696 — the install job's output lands in Cloud Logging: the link goes to
2590
- // Secret Manager, where the operator's terminal reads it (install-job.ts).
2591
- if (setupLink === "secret") {
2592
- if (!meta.region) throw new Error(`install.json of ${installId} records no region.`);
2593
- const stored = await storeSetupLink(
2594
- gcloud,
2595
- { projectId: meta.projectId, region: meta.region },
2596
- bootstrapUrl,
2597
- );
2598
- if (!stored.ok) {
2599
- cancel(`Could not store the Owner setup link: ${stored.error}`);
2600
- process.exit(1);
2601
- }
2546
+ // without it, `admin.<domain>` doesn't resolve and the setup link must
2547
+ // point at the Cloud Run-generated *.run.app URL.
2548
+ const adminBase = provider === "gcp-firebase" ? adminCloudRunUrl : `https://${adminDomainOut}`;
2549
+ if (adminBase === "") {
2550
+ cancel("The stack reported no admin URL. Re-run the installer to refresh its outputs.");
2551
+ process.exit(1);
2552
+ }
2553
+ if (!meta.region) throw new Error(`install.json of ${installId} records no region.`);
2554
+ // #1476 — the token and its link: minted now so its 24 hours start with
2555
+ // this summary, stored for the admin and for `status --project`. #696 — the
2556
+ // install job's output lands in Cloud Logging, so the link is printed only
2557
+ // when this runs in the operator's terminal.
2558
+ const issued = await issueOwnerSetup(
2559
+ gcloud,
2560
+ { projectId: meta.projectId, region: meta.region },
2561
+ adminBase,
2562
+ );
2563
+ if (!issued.ok) {
2564
+ cancel(`Could not store the Owner setup link: ${issued.error}`);
2565
+ process.exit(1);
2602
2566
  }
2603
2567
  const setupLinkLine =
2604
2568
  setupLink === "print"
2605
- ? ` ${cyan(String(bootstrapUrl))}`
2569
+ ? ` ${cyan(issued.link)} ${dim(`(valid until ${issued.expiresAt})`)}`
2606
2570
  : ` ${dim(`(shown in your Cloud Shell terminal; or, from any terminal: ${selfCommand("status", "--project", meta.projectId)})`)}`;
2607
2571
 
2608
2572
  // Both providers report their records in `dnsRecordsRequiredOut`; the
@@ -2624,7 +2588,6 @@ async function stepFinalize(installId: string, setupLink: "print" | "secret"): P
2624
2588
  }
2625
2589
  }
2626
2590
 
2627
- const adminBase = provider === "gcp-firebase" ? adminCloudRunUrl : `https://${adminDomainOut}`;
2628
2591
  const adminNote: string[] =
2629
2592
  provider === "gcp-firebase"
2630
2593
  ? [
@@ -39,11 +39,13 @@ ADMIN_DATABASE_URL=$(pulumi stack output adminDatabaseUrlOut --show-secrets) \
39
39
  bunx cms-provision pulumi-output-sync --environment production
40
40
  ```
41
41
 
42
- The bootstrap-token URL surfaces as a Pulumi output:
42
+ The stack outputs the setup address without a token: nothing brings a token to
43
+ the admin on this provider yet, and `/setup` refuses until something does
44
+ (issue #1483).
43
45
 
44
46
  ```bash
45
47
  pulumi stack output bootstrapUrlOut
46
- # → https://example.com/setup?token=<64-hex>
48
+ # → https://example.com/setup
47
49
  ```
48
50
 
49
51
  Open that URL once CloudFront has issued the ACM cert (~10 minutes after DNS records propagate).
@@ -43,7 +43,6 @@ import {
43
43
  type AwsTaskService,
44
44
  secretsReadPolicy,
45
45
  } from "../../dist/aws-task-roles.js";
46
- import { generateBootstrapToken } from "../../dist/bootstrap-token.js";
47
46
  import {
48
47
  DEFAULT_ADMIN_MAX_INSTANCES,
49
48
  DEFAULT_GATEWAY_MAX_INSTANCES,
@@ -555,10 +554,7 @@ new aws.iam.RolePolicyAttachment(`${namePrefix}-exec-managed`, {
555
554
  policyArn: "arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy",
556
555
  });
557
556
 
558
- // === 9. Bootstrap token ===
559
- const tokenInfo = generateBootstrapToken();
560
-
561
- // === 10. Outputs (CloudAdapterOutputs shape) ===
557
+ // === 9. Outputs (CloudAdapterOutputs shape) ===
562
558
  const dnsRecordsRequired: DnsRecord[] = [
563
559
  {
564
560
  hostname: domain,
@@ -582,8 +578,9 @@ const out: CloudAdapterOutputs = {
582
578
  mediaStorageUrl: pulumi.interpolate`s3://${mediaBucket.bucket}` as unknown as string,
583
579
  mediaCdnBaseUrl:
584
580
  pulumi.interpolate`https://${distribution.domainName}/media` as unknown as string,
585
- bootstrapUrl:
586
- pulumi.interpolate`https://${domain}/setup?token=${tokenInfo.token}` as unknown as string,
581
+ // No token: nothing would bring it to the admin, and /setup refuses until
582
+ // something does (#1483, #1476).
583
+ bootstrapUrl: `https://${domain}/setup`,
587
584
  dnsRecordsRequired,
588
585
  edgeLogSinkUrl:
589
586
  pulumi.interpolate`cloudwatch://us-east-1/${edgeLogGroup.name}` as unknown as string,
@@ -630,7 +627,6 @@ export const poolBudgetEnvOut = poolBudget.env;
630
627
  // CSRF/cookie secrets, Anthropic key) are stored in Pulumi's encrypted
631
628
  // state via `pulumi.secret(...)`. Operators retrieve via
632
629
  // `pulumi stack output --show-secrets`.
633
- export const bootstrapTokenExpiresAtOut = tokenInfo.expiresAt;
634
630
 
635
631
  /** A KeyValueStore's id: the last segment of its ARN. */
636
632
  function kvsIdFromArn(arn: string): string {