@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
@@ -0,0 +1,259 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * How an update job hands its request to the ops image of the release it
5
+ * installs (#819 for the converge job, #1029 for the upgrader). Both jobs
6
+ * have the same two stages, told apart by comparing the release their code
7
+ * belongs to with the request's:
8
+ *
9
+ * Stage 1 — the job runs the INSTALLED release's image. After its own
10
+ * gate it verifies the target's ops image, points itself at it BY
11
+ * DIGEST (only the image changes: identity, command and args stay) and
12
+ * starts a new execution, which takes the request over.
13
+ * Stage 2 — the job runs the TARGET's image and does the work.
14
+ *
15
+ * The point of the split: a fix to the logic that decides and installs
16
+ * reaches every install with the release that carries it. Without stage 1
17
+ * that logic always comes from the release being replaced.
18
+ *
19
+ * This file holds that sequence once, for both jobs, because its order is
20
+ * what keeps it safe: the signature before the image moves, the image moved
21
+ * under the state lock, the request released before the next run exists.
22
+ */
23
+
24
+ import type { ExecutionState } from "./install-job.js";
25
+ import { compareSemver, type ReleaseManifest } from "./release-manifest.js";
26
+ import type { ClaimedUpdate, UpdateEndStatus, UpgraderRunResult } from "./upgrader-job.js";
27
+ import type { EventReporter, JobLog } from "./upgrader-reporter.js";
28
+
29
+ /** What a job's claim found. */
30
+ export interface JobClaim {
31
+ readonly request: ClaimedUpdate;
32
+ /**
33
+ * The request was already running: stage 1 handed it to this run, or a
34
+ * run that died left it. Fresh claims (pending → running) are false.
35
+ */
36
+ readonly resume: boolean;
37
+ /** The execution the request names now (after a fresh claim: this one). */
38
+ readonly execution: string | null;
39
+ }
40
+
41
+ /** The part of a job's queue that moves a running request between runs. */
42
+ export interface HandoverQueue {
43
+ /**
44
+ * Point running request `requestId` at execution `to` — or at none
45
+ * (`null`: released for the next run to adopt) — only while it still
46
+ * names `from`. Resolves false when another run got there first.
47
+ */
48
+ handover(requestId: string, from: string | null, to: string | null): Promise<boolean>;
49
+ }
50
+
51
+ /** What a job does to itself and asks about itself to hand over. */
52
+ export interface SelfHandoverDeps {
53
+ /** This Cloud Run execution; null outside Cloud Run. */
54
+ readonly execution: string | null;
55
+ /** The Caelo release this code belongs to (CAELO_VERSION of the image). */
56
+ readonly ownVersion: string;
57
+ /** Verify the cosign signature of the release image `slug@digest`. */
58
+ readonly verifyImage: (slug: "ops", digest: string) => Promise<boolean>;
59
+ /** The digest of the image this execution runs (from Cloud Run); null when unreadable. */
60
+ readonly ownImageDigest: () => Promise<string | null>;
61
+ /** Point this job at the ops image with `digest` (its identity, command and args stay). */
62
+ readonly pointJobAt: (
63
+ digest: string,
64
+ ) => Promise<{ readonly ok: true } | { readonly ok: false; readonly error: string }>;
65
+ /** Start a new execution of this job; returns its name. */
66
+ readonly startJob: () => Promise<
67
+ | { readonly ok: true; readonly execution: string }
68
+ | { readonly ok: false; readonly error: string }
69
+ >;
70
+ /** Where an execution of this job stands (Cloud Run). */
71
+ readonly executionState: (execution: string) => Promise<ExecutionState>;
72
+ }
73
+
74
+ /** How a request ends because the run cannot go on. */
75
+ export interface HandoverBlocked {
76
+ readonly status: UpdateEndStatus;
77
+ readonly codes: readonly string[];
78
+ readonly reason: string;
79
+ }
80
+
81
+ /** Whether this run is the one to work on the request. */
82
+ export type Adoption =
83
+ | {
84
+ readonly kind: "work";
85
+ /** This run took a request another run started, or one no run names. */
86
+ readonly adopted: boolean;
87
+ }
88
+ /**
89
+ * This run ends without touching the request. `failed`: it could not tell
90
+ * whether another run has it, so the job's run reports an error.
91
+ */
92
+ | { readonly kind: "leave"; readonly message: string; readonly failed?: boolean };
93
+
94
+ /**
95
+ * Decide whether this run may work on `claim`, adopting the request when
96
+ * another run started it: only once that run has ended, because two runs
97
+ * at once must never happen. An error here never ends the request: nothing
98
+ * yet says this run owns it, and the run that does may be alive.
99
+ */
100
+ export async function adoptClaim(
101
+ claim: JobClaim,
102
+ deps: Pick<SelfHandoverDeps, "execution" | "executionState"> & {
103
+ readonly queue: HandoverQueue;
104
+ },
105
+ ): Promise<Adoption> {
106
+ if (!claim.resume || (deps.execution !== null && claim.execution === deps.execution)) {
107
+ return { kind: "work", adopted: false };
108
+ }
109
+ if (!deps.execution) {
110
+ return {
111
+ kind: "leave",
112
+ message: "an update request is running; only a Cloud Run execution may adopt it",
113
+ };
114
+ }
115
+ try {
116
+ if (claim.execution) {
117
+ const live = await deps.executionState(claim.execution);
118
+ if (live === "running") {
119
+ return {
120
+ kind: "leave",
121
+ message: `execution ${claim.execution} is still installing; this run does nothing`,
122
+ };
123
+ }
124
+ }
125
+ if (!(await deps.queue.handover(claim.request.id, claim.execution, deps.execution))) {
126
+ return {
127
+ kind: "leave",
128
+ message: "another run adopted the request first; this run does nothing",
129
+ };
130
+ }
131
+ } catch (e) {
132
+ return {
133
+ kind: "leave",
134
+ failed: true,
135
+ message: `could not tell whether run ${claim.execution ?? "(none)"} still has the request, so this run leaves it alone: ${e instanceof Error ? e.message : String(e)}`,
136
+ };
137
+ }
138
+ return { kind: "work", adopted: true };
139
+ }
140
+
141
+ /** Whether this code belongs to another release than the request's: stage 1. */
142
+ export function isStageOne(ownVersion: string, targetVersion: string): boolean {
143
+ return compareSemver(ownVersion, targetVersion) !== 0;
144
+ }
145
+
146
+ /**
147
+ * Every digest the ops image the manifest signs is known by. Cloud Run
148
+ * records the linux/amd64 platform manifest it resolved, not the index the
149
+ * hand-over pinned (#1025), so an execution of the right image reads back
150
+ * as the platform form the manifest also signs.
151
+ */
152
+ export function signedOpsDigests(m: ReleaseManifest): readonly string[] {
153
+ return [m.digests.ops, ...(m.platformDigests ? [m.platformDigests.ops] : [])];
154
+ }
155
+
156
+ /**
157
+ * Stage 2's check that the image this run executes is the one the manifest
158
+ * signs. Null when it is; how the request ends otherwise.
159
+ *
160
+ * @param own the digest Cloud Run names for this execution, null when unreadable
161
+ * @param noun what the timeline calls this job's image
162
+ */
163
+ export function ownImageProblem(
164
+ m: ReleaseManifest,
165
+ own: string | null,
166
+ noun: string,
167
+ ): HandoverBlocked | null {
168
+ const signed = signedOpsDigests(m);
169
+ if (own !== null && signed.includes(own)) return null;
170
+ return {
171
+ status: "refused",
172
+ codes: ["ops-image"],
173
+ reason: `Nothing was changed: this run's ${noun} image (${own ?? "unknown"}) is not the one Caelo's release workflow signed for ${m.version} (${signed.join(" or ")}). Start the update again from Settings → Updates.`,
174
+ };
175
+ }
176
+
177
+ /** What {@link handOverToRelease} works with: the job's closures over its run. */
178
+ export interface HandoverContext {
179
+ readonly deps: SelfHandoverDeps;
180
+ readonly queue: HandoverQueue;
181
+ readonly requestId: string;
182
+ /** What the timeline calls this job's image: `installer`, `upgrader`. */
183
+ readonly noun: string;
184
+ readonly reporter: EventReporter;
185
+ readonly log: JobLog;
186
+ /** Take the install's state lock; how the request ends when it cannot be had. */
187
+ readonly lock: () => HandoverBlocked | null;
188
+ readonly unlock: () => void;
189
+ readonly stop: (blocked: HandoverBlocked) => Promise<UpgraderRunResult>;
190
+ readonly leave: (message: string) => UpgraderRunResult;
191
+ }
192
+
193
+ /**
194
+ * Stage 1: hand the request to the target release's own signed ops image.
195
+ * `m` is a manifest whose signature verified and that the job's gate let
196
+ * through; nothing else about the install changes here.
197
+ */
198
+ export async function handOverToRelease(
199
+ m: ReleaseManifest,
200
+ c: HandoverContext,
201
+ ): Promise<UpgraderRunResult> {
202
+ const { deps, noun, reporter: r } = c;
203
+ if (!(await deps.verifyImage("ops", m.digests.ops))) {
204
+ return c.stop({
205
+ status: "refused",
206
+ codes: ["signature"],
207
+ reason: `The ${noun} image of ${m.version} is not signed by Caelo's release workflow, so nothing was changed.`,
208
+ });
209
+ }
210
+ // The target's image naming another version would hand over to itself
211
+ // for ever: each run would start the next. Only a broken build gets here.
212
+ const own = await deps.ownImageDigest();
213
+ if (own !== null && signedOpsDigests(m).includes(own)) {
214
+ return c.stop({
215
+ status: "refused",
216
+ codes: ["ops-image"],
217
+ reason: `Nothing was changed: this run already is the ${noun} image Caelo's release workflow signed for ${m.version}, but it reports version ${deps.ownVersion}. That release's image is broken; a newer release installs normally.`,
218
+ });
219
+ }
220
+ // Under the lock (the terminal `upgrade` redeploys this job too), and
221
+ // released before the new run starts: it takes the lock itself.
222
+ const locked = c.lock();
223
+ if (locked) return c.stop(locked);
224
+ let pointed: Awaited<ReturnType<SelfHandoverDeps["pointJobAt"]>>;
225
+ try {
226
+ pointed = await deps.pointJobAt(m.digests.ops);
227
+ } finally {
228
+ c.unlock();
229
+ }
230
+ if (!pointed.ok) {
231
+ return c.stop({
232
+ status: "failed",
233
+ codes: ["handover"],
234
+ reason: `Nothing was changed: the ${noun} of ${m.version} could not be prepared (${pointed.error}). Try again in a moment.`,
235
+ });
236
+ }
237
+ // Release the request BEFORE the new run exists: it adopts a request
238
+ // that names no run at once, while a run still named (this one, alive
239
+ // for a moment longer) would make it step back.
240
+ if (!(await c.queue.handover(c.requestId, deps.execution, null))) {
241
+ return c.leave("the request moved on before the hand-over; this run does nothing");
242
+ }
243
+ const started = await deps.startJob();
244
+ if (!started.ok) {
245
+ return c.stop({
246
+ status: "failed",
247
+ codes: ["handover"],
248
+ reason: `Nothing on the site was changed: the ${noun} of ${m.version} is ready but could not be started (${started.error}). Try again in a moment.`,
249
+ });
250
+ }
251
+ r.info(`The ${noun} of ${m.version} runs now (run ${started.execution}).`);
252
+ await r.flush();
253
+ c.log({
254
+ severity: "INFO",
255
+ message: `handed over to ${started.execution}`,
256
+ requestId: c.requestId,
257
+ });
258
+ return { exitCode: 0, requestId: c.requestId, status: null };
259
+ }
@@ -15,6 +15,7 @@ import { withIamAuthFlag } from "./cloudsql-iam-user.js";
15
15
  import type { GcloudResult } from "./gcloud.js";
16
16
  import {
17
17
  ensureOperatorAccessSync,
18
+ iapWebPath,
18
19
  installIapAllowlist,
19
20
  OPERATOR_ACCESS_PROJECT_IAP_ROLE,
20
21
  OPERATOR_ACCESS_ROLE,
@@ -205,6 +206,48 @@ describe("ensureOperatorAccessSync", () => {
205
206
  );
206
207
  });
207
208
 
209
+ it("#1120 — on plain gcp the job addresses the backend by its numeric id", async () => {
210
+ const { run, calls } = freshInstall();
211
+ const withId: typeof run = async (args) =>
212
+ args.slice(0, 3).join(" ") === "compute backend-services describe"
213
+ ? ok("6948347336569833444\n")
214
+ : run(args);
215
+ const r = await ensureOperatorAccessSync(
216
+ {
217
+ ...target,
218
+ resource: { kind: "backend-services", service: "caelo-production-admin-backend-1a2b" },
219
+ },
220
+ { run: withId, sleep: async () => {} },
221
+ );
222
+ expect(r.ok).toBe(true);
223
+ const deploy = calls.find((c) => c.slice(0, 3).join(" ") === "run jobs deploy") ?? [];
224
+ expect(deploy.find((a) => a.startsWith("--set-env-vars="))).toContain(
225
+ "CAELO_OPERATOR_ACCESS_IAP_WEB=compute/services/6948347336569833444|",
226
+ );
227
+ });
228
+
229
+ it("#1120 — iapWebPath refuses a backend without its numeric id", () => {
230
+ expect(() => iapWebPath({ kind: "backend-services", service: "b" })).toThrow("numeric id");
231
+ });
232
+
233
+ it("#1120 — refuses a backend whose id cannot be read instead of deploying by name", async () => {
234
+ const { run, calls } = freshInstall();
235
+ const noId: typeof run = async (args) =>
236
+ args.slice(0, 3).join(" ") === "compute backend-services describe"
237
+ ? fail("PERMISSION_DENIED")
238
+ : run(args);
239
+ const r = await ensureOperatorAccessSync(
240
+ {
241
+ ...target,
242
+ resource: { kind: "backend-services", service: "caelo-production-admin-backend-1a2b" },
243
+ },
244
+ { run: noId, sleep: async () => {} },
245
+ );
246
+ expect(r.ok).toBe(false);
247
+ // It stops before anything is written, the revoke of the old path included.
248
+ expect(calls).toEqual([]);
249
+ });
250
+
208
251
  it("#1140 — tells the job which service accounts keep IAP access (the scheduler tick)", async () => {
209
252
  const { run, calls } = freshInstall();
210
253
  await ensureOperatorAccessSync(
@@ -136,11 +136,20 @@ export const OPERATOR_ACCESS_DB_ROLE = "operator_access_reader";
136
136
  /** Where the admin image ships the job's entry point. */
137
137
  const SYNC_JOB_SCRIPT = "/app/packages/admin-core/src/security/operator-access/sync-job.ts";
138
138
 
139
- /** The `iap_web` path of an IAP resource, as the IAP REST API names it. */
140
- export function iapWebPath(resource: IapResource): string {
141
- return resource.kind === "cloud-run"
142
- ? `cloud_run-${resource.region}/services/${resource.service}`
143
- : `compute/services/${resource.service}`;
139
+ /**
140
+ * The `iap_web` path of an IAP resource, as the IAP REST API names it. A
141
+ * backend service goes by its numeric id: IAM on the job's account is
142
+ * evaluated there, and addressed by name `:iapSettings` answers 403 even with
143
+ * the role bound, so the sync failed every hour on plain gcp (#1120).
144
+ */
145
+ export function iapWebPath(resource: IapResource, backendServiceId?: string): string {
146
+ if (resource.kind === "cloud-run") {
147
+ return `cloud_run-${resource.region}/services/${resource.service}`;
148
+ }
149
+ if (!backendServiceId) {
150
+ throw new Error(`${resource.service}: an IAP backend is addressed by its numeric id`);
151
+ }
152
+ return `compute/services/${backendServiceId}`;
144
153
  }
145
154
 
146
155
  /** Create the custom role, or bring an existing / soft-deleted one to spec. */
@@ -261,6 +270,29 @@ export async function ensureOperatorAccessSync(
261
270
  const customRole = customRoleName(projectId, OPERATOR_ACCESS_ROLE.roleId);
262
271
  const jobName = operatorAccessJobName(env);
263
272
  const done: string[] = [];
273
+
274
+ // Before any write: the steps below revoke the old access path, so an
275
+ // unreadable id must not leave the install without a replacement job.
276
+ let backendServiceId: string | undefined;
277
+ if (target.resource.kind === "backend-services") {
278
+ const described = await run([
279
+ "compute",
280
+ "backend-services",
281
+ "describe",
282
+ target.resource.service,
283
+ "--global",
284
+ project,
285
+ "--format=value(id)",
286
+ ]);
287
+ backendServiceId = described.stdout.trim();
288
+ if (!described.ok || !/^\d+$/.test(backendServiceId)) {
289
+ return {
290
+ ok: false,
291
+ done,
292
+ error: `read the id of ${target.resource.service}: ${described.stderr.trim() || "no numeric id"}`,
293
+ };
294
+ }
295
+ }
264
296
  const fail = (step: string, r: GcloudResult): OperatorAccessSyncResult => ({
265
297
  ok: false,
266
298
  done,
@@ -427,7 +459,7 @@ export async function ensureOperatorAccessSync(
427
459
  // 6. The job: the admin image with another entry point, the job's own SA,
428
460
  // and its whole input as env the admin cannot override.
429
461
  const envVars = [
430
- `CAELO_OPERATOR_ACCESS_IAP_WEB=${iapWebPath(target.resource)}`,
462
+ `CAELO_OPERATOR_ACCESS_IAP_WEB=${iapWebPath(target.resource, backendServiceId)}`,
431
463
  `CAELO_MCP_IAP_SERVICE_ACCOUNT=${mcpSa}`,
432
464
  `CAELO_OPERATOR_ACCESS_STATIC_MEMBERS=${installIapAllowlist(target.ownerEmail).join(",")}`,
433
465
  `CAELO_OPERATOR_ACCESS_DB_HOST=${target.databaseHost}`,
@@ -0,0 +1,195 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * #1476 — the Owner setup token: stored for the admin, with its read access,
5
+ * minted once, and replaced only when it stopped being useful. The admin's
6
+ * half is packages/admin-core/src/__tests__/owner-bootstrap-secret.integration.test.ts.
7
+ */
8
+
9
+ import { describe, expect, it } from "bun:test";
10
+ import { readFileSync } from "node:fs";
11
+ import { join } from "node:path";
12
+ import { OWNER_BOOTSTRAP_TOKEN_SECRET, parseOwnerBootstrapToken } from "@caelo-cms/shared";
13
+ import type { GcloudResult } from "./gcloud.js";
14
+ import type { GcloudRunner } from "./gcloud-retry.js";
15
+ import { GCP_STACK_ENV, gcpSecretId } from "./gcp-names.js";
16
+ import { INFRA_CONTRACT_STEPS } from "./infra-contract.js";
17
+ import { INSTALL_SETUP_LINK_SECRET } from "./install-job.js";
18
+ import { issueOwnerSetup, readOwnerBootstrapToken } from "./owner-setup-token.js";
19
+
20
+ const PROJECT = "acme-site";
21
+ const TARGET = { projectId: PROJECT, region: "europe-west1" };
22
+ const ADMIN = "https://admin.acme.test";
23
+ const NOW = Date.parse("2026-11-05T12:00:00.000Z");
24
+ const HOUR = 60 * 60 * 1000;
25
+
26
+ const ok = (stdout = ""): GcloudResult => ({ ok: true, stdout, stderr: "", exitCode: 0 });
27
+ const fail = (stderr: string): GcloudResult => ({ ok: false, stdout: "", stderr, exitCode: 1 });
28
+
29
+ /** A project's secrets as gcloud sees them; the calls it got. */
30
+ function secretManager(
31
+ initial: Record<string, string> = {},
32
+ refuse?: { readonly match: string; readonly stderr: string },
33
+ ) {
34
+ const secrets = new Map(Object.entries(initial));
35
+ const calls: { args: string[]; stdin?: string }[] = [];
36
+ const run: GcloudRunner = async (args, opts) => {
37
+ calls.push({ args, ...(opts?.stdin === undefined ? {} : { stdin: opts.stdin }) });
38
+ const line = args.join(" ");
39
+ if (refuse && line.includes(refuse.match)) return fail(refuse.stderr);
40
+ if (line.startsWith("secrets versions access")) {
41
+ const id = args.find((a) => a.startsWith("--secret="))?.slice("--secret=".length) ?? "";
42
+ const value = secrets.get(id);
43
+ return value === undefined ? fail("NOT_FOUND: Secret not found") : ok(value);
44
+ }
45
+ if (line.startsWith("secrets describe")) {
46
+ const id = args[2] ?? "";
47
+ if (id.endsWith("postgres-password")) return ok('{"replication":{"automatic":{}}}');
48
+ return secrets.has(id) ? ok(id) : fail("NOT_FOUND: Secret not found");
49
+ }
50
+ if (line.startsWith("secrets versions add")) {
51
+ secrets.set(args[3] ?? "", opts?.stdin ?? "");
52
+ return ok(`projects/1/secrets/${args[3]}/versions/2`);
53
+ }
54
+ if (line.startsWith("secrets versions list")) return ok("");
55
+ if (line.startsWith("secrets create")) {
56
+ secrets.set(args[2] ?? "", "");
57
+ return ok();
58
+ }
59
+ if (line.startsWith("secrets add-iam-policy-binding")) return ok();
60
+ throw new Error(`unexpected gcloud call: ${line}`);
61
+ };
62
+ return { run, secrets, calls };
63
+ }
64
+
65
+ const stored = (expiresAt: number) =>
66
+ JSON.stringify({ token: "a".repeat(64), expiresAt: new Date(expiresAt).toISOString() });
67
+
68
+ describe("issueOwnerSetup", () => {
69
+ it("mints a token, stores it for the admin, and stores the link that carries it", async () => {
70
+ const gcp = secretManager({ "caelo-production-postgres-password": "x" });
71
+ const r = await issueOwnerSetup(gcp.run, TARGET, ADMIN, NOW);
72
+ if (!r.ok) throw new Error(r.error);
73
+ expect(r.minted).toBe(true);
74
+ const token = parseOwnerBootstrapToken(gcp.secrets.get(OWNER_BOOTSTRAP_TOKEN_SECRET) ?? "");
75
+ expect(token?.token).toMatch(/^[0-9a-f]{64}$/);
76
+ expect(r.link).toBe(`${ADMIN}/setup?token=${token?.token}`);
77
+ expect(gcp.secrets.get(INSTALL_SETUP_LINK_SECRET)).toBe(r.link);
78
+ });
79
+
80
+ it("gives the admin's service account read access, on this secret only", async () => {
81
+ const gcp = secretManager({ "caelo-production-postgres-password": "x" });
82
+ await issueOwnerSetup(gcp.run, TARGET, ADMIN, NOW);
83
+ const grants = gcp.calls.filter((c) => c.args[1] === "add-iam-policy-binding");
84
+ expect(grants).toHaveLength(1);
85
+ expect(grants[0]?.args[2]).toBe(OWNER_BOOTSTRAP_TOKEN_SECRET);
86
+ expect(grants[0]?.args).toContain(
87
+ `--member=serviceAccount:caelo-production-run-sa@${PROJECT}.iam.gserviceaccount.com`,
88
+ );
89
+ expect(grants[0]?.args).toContain("--role=roles/secretmanager.secretAccessor");
90
+ });
91
+
92
+ it("never puts the token on a command line", async () => {
93
+ const gcp = secretManager({ "caelo-production-postgres-password": "x" });
94
+ const r = await issueOwnerSetup(gcp.run, TARGET, ADMIN, NOW);
95
+ if (!r.ok) throw new Error(r.error);
96
+ const token = new URL(r.link).searchParams.get("token") ?? "";
97
+ expect(gcp.calls.some((c) => c.args.join(" ").includes(token))).toBe(false);
98
+ });
99
+
100
+ it("keeps a token with time left, so a link already handed out stays good", async () => {
101
+ const gcp = secretManager({
102
+ [OWNER_BOOTSTRAP_TOKEN_SECRET]: stored(NOW + 5 * HOUR),
103
+ });
104
+ const r = await issueOwnerSetup(gcp.run, TARGET, ADMIN, NOW);
105
+ if (!r.ok) throw new Error(r.error);
106
+ expect(r.minted).toBe(false);
107
+ expect(r.link).toBe(`${ADMIN}/setup?token=${"a".repeat(64)}`);
108
+ expect(gcp.secrets.get(OWNER_BOOTSTRAP_TOKEN_SECRET)).toBe(stored(NOW + 5 * HOUR));
109
+ // An interrupted run may have stopped before the grant.
110
+ expect(gcp.calls.some((c) => c.args[1] === "add-iam-policy-binding")).toBe(true);
111
+ });
112
+
113
+ it.each([
114
+ ["expired", stored(NOW - HOUR)],
115
+ ["about to expire", stored(NOW + HOUR / 2)],
116
+ ["not a token", "garbage"],
117
+ ])("replaces a stored token that is %s", async (_case, value) => {
118
+ const gcp = secretManager({
119
+ "caelo-production-postgres-password": "x",
120
+ [OWNER_BOOTSTRAP_TOKEN_SECRET]: value,
121
+ });
122
+ const r = await issueOwnerSetup(gcp.run, TARGET, ADMIN, NOW);
123
+ if (!r.ok) throw new Error(r.error);
124
+ expect(r.minted).toBe(true);
125
+ expect(r.link).not.toContain("a".repeat(64));
126
+ });
127
+
128
+ it("says so when a run at the same time changed the token, instead of printing a dead link", async () => {
129
+ const gcp = secretManager({ "caelo-production-postgres-password": "x" });
130
+ const racing: GcloudRunner = async (args, opts) => {
131
+ const r = await gcp.run(args, opts);
132
+ if (args.includes("add") && args.includes(INSTALL_SETUP_LINK_SECRET)) {
133
+ gcp.secrets.set(OWNER_BOOTSTRAP_TOKEN_SECRET, stored(NOW + 20 * HOUR));
134
+ }
135
+ return r;
136
+ };
137
+ const r = await issueOwnerSetup(racing, TARGET, ADMIN, NOW);
138
+ expect(r.ok).toBe(false);
139
+ if (!r.ok) expect(r.error).toContain("Run this command again");
140
+ });
141
+
142
+ it("fails loudly when the admin cannot be given access, with no link stored", async () => {
143
+ const gcp = secretManager(
144
+ { "caelo-production-postgres-password": "x" },
145
+ { match: "add-iam-policy-binding", stderr: "PERMISSION_DENIED: setIamPolicy" },
146
+ );
147
+ const r = await issueOwnerSetup(gcp.run, TARGET, ADMIN, NOW);
148
+ expect(r).toEqual({
149
+ ok: false,
150
+ error: `let the admin read ${OWNER_BOOTSTRAP_TOKEN_SECRET}: PERMISSION_DENIED: setIamPolicy`,
151
+ });
152
+ expect(gcp.secrets.has(INSTALL_SETUP_LINK_SECRET)).toBe(false);
153
+ });
154
+ });
155
+
156
+ describe("readOwnerBootstrapToken", () => {
157
+ it("is null without a token", async () => {
158
+ expect(await readOwnerBootstrapToken(secretManager().run, PROJECT)).toBeNull();
159
+ });
160
+
161
+ it("names what the account needs when the read is refused", async () => {
162
+ const gcp = secretManager({}, { match: "versions access", stderr: "PERMISSION_DENIED: no" });
163
+ await expect(readOwnerBootstrapToken(gcp.run, PROJECT)).rejects.toThrow(
164
+ "secretmanager.versions.access",
165
+ );
166
+ });
167
+ });
168
+
169
+ describe("where the token lives", () => {
170
+ const stack = (provider: string) =>
171
+ readFileSync(join(import.meta.dir, `../stacks/${provider}/index.ts`), "utf8");
172
+
173
+ it("the admin and the CLI name the same secret", () => {
174
+ expect(OWNER_BOOTSTRAP_TOKEN_SECRET).toBe(gcpSecretId(GCP_STACK_ENV, "owner-bootstrap-token"));
175
+ });
176
+
177
+ it.each(["gcp", "gcp-firebase", "aws", "azure"])(
178
+ "%s mints no token in the Pulumi program: it would change on every up and sit in its state",
179
+ (provider) => {
180
+ const source = stack(provider);
181
+ expect(source).not.toContain("generateBootstrapToken");
182
+ expect(source).not.toContain("setup?token=");
183
+ },
184
+ );
185
+
186
+ it.each(["gcp", "gcp-firebase"])(
187
+ "%s neither mounts the secret nor binds it: existing installs get no converge step",
188
+ (provider) => {
189
+ expect(stack(provider)).not.toContain("owner-bootstrap-token");
190
+ // No contract step was added for the token (#1476): a later bump is
191
+ // another change, so check the steps, not the current number.
192
+ expect(Object.values(INFRA_CONTRACT_STEPS).join("\n")).not.toContain("#1476");
193
+ },
194
+ );
195
+ });