@caelo-cms/provisioning 0.12.4 → 0.12.5-rc.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 (117) hide show
  1. package/dist/agent-db.js +8 -3
  2. package/dist/cli-routing.d.ts.map +1 -1
  3. package/dist/cli-routing.js +6 -5
  4. package/dist/cli-routing.js.map +1 -1
  5. package/dist/cli.js +18 -1
  6. package/dist/cli.js.map +1 -1
  7. package/dist/gcp-names.d.ts +51 -0
  8. package/dist/gcp-names.d.ts.map +1 -1
  9. package/dist/gcp-names.js +75 -0
  10. package/dist/gcp-names.js.map +1 -1
  11. package/dist/infra-contract.d.ts +1 -1
  12. package/dist/infra-contract.d.ts.map +1 -1
  13. package/dist/infra-contract.js +42 -1
  14. package/dist/infra-contract.js.map +1 -1
  15. package/dist/install-state.d.ts +8 -0
  16. package/dist/install-state.d.ts.map +1 -1
  17. package/dist/install-state.js +12 -0
  18. package/dist/install-state.js.map +1 -1
  19. package/dist/install-version.d.ts +110 -0
  20. package/dist/install-version.d.ts.map +1 -0
  21. package/dist/install-version.js +162 -0
  22. package/dist/install-version.js.map +1 -0
  23. package/dist/lifecycle.d.ts +6 -1
  24. package/dist/lifecycle.d.ts.map +1 -1
  25. package/dist/lifecycle.js +46 -1
  26. package/dist/lifecycle.js.map +1 -1
  27. package/dist/release-candidate.d.ts +67 -0
  28. package/dist/release-candidate.d.ts.map +1 -0
  29. package/dist/release-candidate.js +138 -0
  30. package/dist/release-candidate.js.map +1 -0
  31. package/dist/reporting-job-setup.d.ts +102 -0
  32. package/dist/reporting-job-setup.d.ts.map +1 -0
  33. package/dist/reporting-job-setup.js +347 -0
  34. package/dist/reporting-job-setup.js.map +1 -0
  35. package/dist/self-hosted-upgrade.d.ts.map +1 -1
  36. package/dist/self-hosted-upgrade.js +18 -3
  37. package/dist/self-hosted-upgrade.js.map +1 -1
  38. package/dist/stack-contract.d.ts +30 -5
  39. package/dist/stack-contract.d.ts.map +1 -1
  40. package/dist/stack-contract.js +74 -10
  41. package/dist/stack-contract.js.map +1 -1
  42. package/dist/upgrade/admin-image-jobs.d.ts +13 -5
  43. package/dist/upgrade/admin-image-jobs.d.ts.map +1 -1
  44. package/dist/upgrade/admin-image-jobs.js +22 -2
  45. package/dist/upgrade/admin-image-jobs.js.map +1 -1
  46. package/dist/upgrade/converge.d.ts.map +1 -1
  47. package/dist/upgrade/converge.js +99 -9
  48. package/dist/upgrade/converge.js.map +1 -1
  49. package/dist/upgrade/release-images.d.ts +6 -2
  50. package/dist/upgrade/release-images.d.ts.map +1 -1
  51. package/dist/upgrade/release-images.js +5 -5
  52. package/dist/upgrade/release-images.js.map +1 -1
  53. package/dist/upgrader-iam-preflight.d.ts.map +1 -1
  54. package/dist/upgrader-iam-preflight.js +19 -1
  55. package/dist/upgrader-iam-preflight.js.map +1 -1
  56. package/dist/upgrader-setup.d.ts.map +1 -1
  57. package/dist/upgrader-setup.js +16 -1
  58. package/dist/upgrader-setup.js.map +1 -1
  59. package/dist/wizard.d.ts +7 -0
  60. package/dist/wizard.d.ts.map +1 -1
  61. package/dist/wizard.js +20 -5
  62. package/dist/wizard.js.map +1 -1
  63. package/dist/wizards/gcp-cost.d.ts +7 -11
  64. package/dist/wizards/gcp-cost.d.ts.map +1 -1
  65. package/dist/wizards/gcp-cost.js +47 -36
  66. package/dist/wizards/gcp-cost.js.map +1 -1
  67. package/dist/wizards/gcp-firebase.d.ts +4 -0
  68. package/dist/wizards/gcp-firebase.d.ts.map +1 -1
  69. package/dist/wizards/gcp-firebase.js +2 -0
  70. package/dist/wizards/gcp-firebase.js.map +1 -1
  71. package/dist/wizards/gcp-install-job.d.ts +10 -0
  72. package/dist/wizards/gcp-install-job.d.ts.map +1 -1
  73. package/dist/wizards/gcp-install-job.js +41 -10
  74. package/dist/wizards/gcp-install-job.js.map +1 -1
  75. package/dist/wizards/gcp.d.ts +7 -0
  76. package/dist/wizards/gcp.d.ts.map +1 -1
  77. package/dist/wizards/gcp.js +191 -9
  78. package/dist/wizards/gcp.js.map +1 -1
  79. package/package.json +2 -2
  80. package/src/cli-routing.test.ts +1 -1
  81. package/src/cli-routing.ts +6 -5
  82. package/src/cli.ts +18 -1
  83. package/src/cpu-idle.test.ts +7 -2
  84. package/src/gcp-names.ts +87 -0
  85. package/src/infra-contract.test.ts +6 -3
  86. package/src/infra-contract.ts +42 -1
  87. package/src/install-state.ts +12 -0
  88. package/src/install-version.test.ts +366 -0
  89. package/src/install-version.ts +205 -0
  90. package/src/lifecycle.ts +65 -3
  91. package/src/release-candidate.test.ts +191 -0
  92. package/src/release-candidate.ts +172 -0
  93. package/src/reporting-job-setup.test.ts +392 -0
  94. package/src/reporting-job-setup.ts +431 -0
  95. package/src/self-hosted-upgrade.ts +18 -3
  96. package/src/stack-contract.test.ts +24 -0
  97. package/src/stack-contract.ts +87 -9
  98. package/src/stack-converge-secrets.test.ts +2 -0
  99. package/src/stack-converge.test.ts +3 -3
  100. package/src/upgrade/admin-image-jobs.ts +35 -6
  101. package/src/upgrade/converge.ts +137 -8
  102. package/src/upgrade/release-images.test.ts +2 -2
  103. package/src/upgrade/release-images.ts +6 -4
  104. package/src/upgrade/upgrade.test.ts +165 -4
  105. package/src/upgrader-iam-preflight.test.ts +58 -0
  106. package/src/upgrader-iam-preflight.ts +21 -0
  107. package/src/upgrader-job.test.ts +3 -0
  108. package/src/upgrader-setup.test.ts +6 -0
  109. package/src/upgrader-setup.ts +18 -0
  110. package/src/wizard.ts +30 -5
  111. package/src/wizards/gcp-cost.test.ts +11 -13
  112. package/src/wizards/gcp-cost.ts +49 -36
  113. package/src/wizards/gcp-firebase.ts +6 -0
  114. package/src/wizards/gcp-install-job.ts +46 -12
  115. package/src/wizards/gcp.ts +250 -7
  116. package/stacks/aws/index.ts +10 -0
  117. package/stacks/azure/index.ts +10 -0
@@ -0,0 +1,431 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * #1359 (#1140 category A) — set up (and converge) a reporting job on a
5
+ * Google Cloud install (`gcp`, `gcp-firebase`): a Cloud Run job that runs
6
+ * long, bounded work (a Stage's quality audit, #1359; a site import's crawl,
7
+ * #1360) outside the admin and reports back to it by request, so the admin
8
+ * only works inside requests (CLAUDE.md §11.B Tier 5) — or, the build
9
+ * carrier (#1574), holds the request a build runs in. Run by the wizard
10
+ * after `pulumi up` and by `cms-provision upgrade`'s converge (and the
11
+ * converge job), as the operator's or the provisioner's identity. App-roll
12
+ * moves the job's image with the admin's (upgrade/admin-image-jobs.ts):
13
+ * the job runs the admin image's `reporting-jobs/job-entry.ts`.
14
+ *
15
+ * Why the CLI owns it and not the stacks: the same as audit-job-setup.ts —
16
+ * `upgrade` never runs Pulumi, so existing installs get it only from here.
17
+ *
18
+ * Trust boundary. Every reporting job runs as its own service account,
19
+ * which holds — shared by every kind ({@link ensureReportingJob}):
20
+ *
21
+ * - `roles/iam.serviceAccountTokenCreator` on ITSELF only: it signs the
22
+ * IAP credential it reports with (IAM signJwt), as the scheduler does;
23
+ * - `roles/iap.httpsResourceAccessor` on the admin's IAP resource (the
24
+ * operator-access sync job keeps it there, operator-access.ts);
25
+ * - `roles/logging.logWriter`.
26
+ *
27
+ * plus its kind's own grants (the audit runner: {@link auditRunnerJobSpec};
28
+ * the site-import crawler and the build carrier have none,
29
+ * {@link importCrawlJobSpec}, {@link buildCarrierJobSpec}).
30
+ * Nothing else: no Secret Manager, no Cloud SQL, no VPC egress. Passing IAP
31
+ * reaches nothing by itself: the admin's report endpoint takes a report of
32
+ * a kind only from that kind's account AND with the token the admin minted
33
+ * for the running attempt, and only that attempt's reports
34
+ * (admin-core reporting-jobs/dispatch.ts); every other admin route still
35
+ * needs a session, the internal token or the scheduler's identity, which
36
+ * the job has none of. IAP access goes only to jobs that run no browser
37
+ * and execute nothing they fetch; every render stays in the capture job
38
+ * and the Lighthouse tasks, which have no IAP access (capture-job-setup.ts).
39
+ *
40
+ * The admin's run SA may run the job WITH overrides (it passes each
41
+ * attempt's order: the work, the attempt, its token, the admin's URL) and
42
+ * read its executions. {@link REPORTING_JOB_FORBIDDEN_ROLES} names the line;
43
+ * the tests assert no grant crosses it.
44
+ */
45
+
46
+ import { gcloud as defaultGcloud, type GcloudResult } from "./gcloud.js";
47
+ import { type GcloudRunner, realSleep, runWithRetry, type Sleep } from "./gcloud-retry.js";
48
+ import {
49
+ auditJobName,
50
+ auditJobResource,
51
+ auditRunnerJobName,
52
+ auditRunnerServiceAccountId,
53
+ buildCarrierJobName,
54
+ buildCarrierServiceAccountId,
55
+ gcpBucketName,
56
+ importCrawlJobName,
57
+ importCrawlServiceAccountId,
58
+ runServiceAccountEmail,
59
+ } from "./gcp-names.js";
60
+ import { type IapResource, iapResourceArgs } from "./mcp-iap.js";
61
+ import type { GcpProvider } from "./stack-contract.js";
62
+
63
+ /** Where the admin image ships every reporting job's entry point. */
64
+ export const REPORTING_JOB_SCRIPT = "/app/packages/admin-core/src/reporting-jobs/job-entry.ts";
65
+
66
+ /**
67
+ * Roles a reporting job's identity must never hold anywhere. Prefix matches
68
+ * (`roles/secretmanager.` = every Secret Manager role). `roles/run.` roles
69
+ * are allowed only on a job a kind names in {@link ReportingJobSpec.runJobs}
70
+ * (the audit runner starts the Lighthouse tasks); the tests assert that.
71
+ */
72
+ export const REPORTING_JOB_FORBIDDEN_ROLES = [
73
+ "roles/owner",
74
+ "roles/editor",
75
+ "roles/viewer",
76
+ "roles/iam.serviceAccountUser",
77
+ "roles/iam.serviceAccountAdmin",
78
+ "roles/iam.securityAdmin",
79
+ "roles/iap.admin",
80
+ "roles/iap.settingsAdmin",
81
+ "roles/secretmanager.",
82
+ "roles/cloudsql.",
83
+ "roles/compute.",
84
+ "roles/resourcemanager.",
85
+ "roles/storage.admin",
86
+ "roles/storage.objectAdmin",
87
+ "roles/storage.objectUser",
88
+ "roles/storage.objectCreator",
89
+ "roles/run.admin",
90
+ "roles/run.developer",
91
+ "roles/run.invoker",
92
+ ] as const;
93
+
94
+ /** What one kind of reporting job needs beyond the shared grants. */
95
+ export interface ReportingJobSpec {
96
+ /** How the CLI names it ("quality-audit runner"). */
97
+ readonly label: string;
98
+ readonly jobName: string;
99
+ readonly serviceAccountId: string;
100
+ readonly displayName: string;
101
+ readonly description: string;
102
+ /** The job's env (`KEY=value`; never a secret). */
103
+ readonly env: readonly string[];
104
+ readonly cpu: string;
105
+ readonly memory: string;
106
+ /** One execution's ceiling (admin-core protocol.ts `JOB_TIMING.maxRunSeconds`). */
107
+ readonly taskTimeoutSeconds: number;
108
+ /** Read-only bucket access it needs, each with the reason. */
109
+ readonly readBuckets: readonly { readonly bucket: string; readonly why: string }[];
110
+ /** Jobs it starts itself, with its order as an override (and reads their executions). */
111
+ readonly runJobs: readonly { readonly job: string; readonly why: string }[];
112
+ }
113
+
114
+ /** Where one install's reporting job goes. */
115
+ export interface ReportingJobTarget {
116
+ readonly provider: GcpProvider;
117
+ readonly projectId: string;
118
+ readonly region: string;
119
+ /** Pulumi stack name (`production`). */
120
+ readonly env: string;
121
+ /** The admin image the job runs, digest-pinned (`…/admin@sha256:…`). */
122
+ readonly adminImageRef: string;
123
+ /** The admin's IAP resource (the service on gcp-firebase, the LB backend on gcp). */
124
+ readonly resource: IapResource;
125
+ }
126
+
127
+ export type ReportingJobResult =
128
+ | { readonly ok: true; readonly done: string[]; readonly serviceAccount: string }
129
+ | { readonly ok: false; readonly done: string[]; readonly error: string };
130
+
131
+ /**
132
+ * The audit runner (#1359): the whole quality audit of a Stage. It serves
133
+ * the staged build from its staging slot to its own findings checks, starts
134
+ * the Lighthouse tasks on the audit job (#875) and reads their results.
135
+ */
136
+ export function auditRunnerJobSpec(
137
+ target: Pick<ReportingJobTarget, "provider" | "projectId" | "region" | "env">,
138
+ ): ReportingJobSpec {
139
+ const { projectId, region, env, provider } = target;
140
+ const staging = gcpBucketName(projectId, env, "staging");
141
+ const results = gcpBucketName(projectId, env, "audit-results");
142
+ return {
143
+ label: "quality-audit runner",
144
+ jobName: auditRunnerJobName(env),
145
+ serviceAccountId: auditRunnerServiceAccountId(env),
146
+ displayName: "Caelo quality-audit runner",
147
+ description:
148
+ "Runs a Stage's quality audit and reports to the admin; reads the staged build and the Lighthouse results, starts the Lighthouse tasks, nothing else.",
149
+ env: [
150
+ `CAELO_PROVIDER=${provider}`,
151
+ `CAELO_STAGING_BUCKET=${staging}`,
152
+ `CAELO_AUDIT_JOB=${auditJobResource(projectId, region, env)}`,
153
+ `CAELO_AUDIT_RESULTS_BUCKET=${results}`,
154
+ ],
155
+ cpu: "1",
156
+ memory: "2Gi",
157
+ // admin-core JOB_TIMING.quality_audit.maxRunSeconds.
158
+ taskTimeoutSeconds: 3600,
159
+ readBuckets: [
160
+ { bucket: staging, why: "it serves the staged build to the findings checks" },
161
+ { bucket: results, why: "it reads the Lighthouse tasks' results" },
162
+ ],
163
+ runJobs: [{ job: auditJobName(env), why: "it starts the Lighthouse tasks" }],
164
+ };
165
+ }
166
+
167
+ /**
168
+ * The site-import crawler (#1360): one site import's crawl. It reads
169
+ * third-party pages, so it holds nothing beyond the shared grants: no
170
+ * bucket, no other job. It fetches robots.txt and sitemaps itself, through
171
+ * the SSRF guard; every page render is the admin's, which starts the
172
+ * capture job and keeps the screenshot, so the crawler never runs a
173
+ * browser and never touches the capture job or its bucket.
174
+ */
175
+ export function importCrawlJobSpec(
176
+ target: Pick<ReportingJobTarget, "provider" | "env">,
177
+ ): ReportingJobSpec {
178
+ return {
179
+ label: "site-import crawler",
180
+ jobName: importCrawlJobName(target.env),
181
+ serviceAccountId: importCrawlServiceAccountId(target.env),
182
+ displayName: "Caelo site-import crawler",
183
+ description:
184
+ "Crawls a site the Owner approved for import and reports each page to the admin; fetches robots.txt and sitemaps through the SSRF guard, nothing else.",
185
+ env: [`CAELO_PROVIDER=${target.provider}`],
186
+ cpu: "1",
187
+ // The frontier and up to four rendered pages' HTML at once.
188
+ memory: "2Gi",
189
+ // admin-core JOB_TIMING.site_import.maxRunSeconds: a longer crawl goes
190
+ // on in the next attempt, from its checkpoint.
191
+ taskTimeoutSeconds: 6 * 3600,
192
+ readBuckets: [],
193
+ runJobs: [],
194
+ };
195
+ }
196
+
197
+ /**
198
+ * The build carrier (#1574): one Stage's, Publish live's or production
199
+ * build's request. It sends one report, `run`, and the admin runs the build
200
+ * inside that request on its own database and rights, so the carrier holds
201
+ * nothing beyond the shared grants: it reads nothing, fetches nothing,
202
+ * builds nothing. Smallest machine: it only waits for the answer.
203
+ */
204
+ export function buildCarrierJobSpec(
205
+ target: Pick<ReportingJobTarget, "provider" | "env">,
206
+ ): ReportingJobSpec {
207
+ return {
208
+ label: "build carrier",
209
+ jobName: buildCarrierJobName(target.env),
210
+ serviceAccountId: buildCarrierServiceAccountId(target.env),
211
+ displayName: "Caelo build carrier",
212
+ description:
213
+ "Holds the admin request a Stage, Publish live or production build runs in, so the build ends when nobody waits for it; reports to the admin, nothing else.",
214
+ env: [`CAELO_PROVIDER=${target.provider}`],
215
+ cpu: "1",
216
+ memory: "512Mi",
217
+ // admin-core JOB_TIMING.build.maxRunSeconds: the admin's request limit
218
+ // (the build stops two minutes before it) plus room to start and end.
219
+ taskTimeoutSeconds: 3600 + 5 * 60,
220
+ readBuckets: [],
221
+ runJobs: [],
222
+ };
223
+ }
224
+
225
+ /** Ensure a reporting job and everything it needs. Never throws for a gcloud failure. */
226
+ export async function ensureReportingJob(
227
+ target: ReportingJobTarget,
228
+ spec: ReportingJobSpec,
229
+ deps: { run?: GcloudRunner; sleep?: Sleep } = {},
230
+ ): Promise<ReportingJobResult> {
231
+ const run = deps.run ?? defaultGcloud;
232
+ const sleep = deps.sleep ?? realSleep;
233
+ const retry = (args: string[]) => runWithRetry(run, sleep, args);
234
+ const { projectId, region } = target;
235
+ const project = `--project=${projectId}`;
236
+ const sa = `${spec.serviceAccountId}@${projectId}.iam.gserviceaccount.com`;
237
+ const member = `serviceAccount:${sa}`;
238
+ const runSaMember = `serviceAccount:${runServiceAccountEmail(projectId, target.env)}`;
239
+ const done: string[] = [];
240
+ const fail = (step: string, r: GcloudResult): ReportingJobResult => ({
241
+ ok: false,
242
+ done,
243
+ error: `${step}: ${r.stderr.trim()}`,
244
+ });
245
+
246
+ if (!/@sha256:[0-9a-f]{64}$/.test(target.adminImageRef)) {
247
+ return {
248
+ ok: false,
249
+ done,
250
+ error: `the ${spec.label}'s image must be pinned by digest, got ${target.adminImageRef}`,
251
+ };
252
+ }
253
+
254
+ // 1. The job's own service account.
255
+ const describe = await run([
256
+ "iam",
257
+ "service-accounts",
258
+ "describe",
259
+ sa,
260
+ project,
261
+ "--format=value(email)",
262
+ ]);
263
+ if (!describe.ok) {
264
+ const create = await run([
265
+ "iam",
266
+ "service-accounts",
267
+ "create",
268
+ spec.serviceAccountId,
269
+ `--display-name=${spec.displayName}`,
270
+ `--description=${spec.description}`,
271
+ project,
272
+ ]);
273
+ if (!create.ok && !/already exists/i.test(create.stderr)) return fail(`create ${sa}`, create);
274
+ }
275
+ done.push(`service account ${sa}`);
276
+
277
+ // 2. It signs its IAP credential as itself, and nothing else of IAM.
278
+ const self = await retry([
279
+ "iam",
280
+ "service-accounts",
281
+ "add-iam-policy-binding",
282
+ sa,
283
+ `--member=${member}`,
284
+ "--role=roles/iam.serviceAccountTokenCreator",
285
+ "--condition=None",
286
+ project,
287
+ "--quiet",
288
+ "--format=none",
289
+ ]);
290
+ if (!self.ok) return fail(`let the ${spec.label} sign its IAP credential as itself`, self);
291
+ done.push(`${spec.label}: roles/iam.serviceAccountTokenCreator on ${sa} (itself, signJwt)`);
292
+
293
+ // 3. Logs.
294
+ const logs = await retry([
295
+ "projects",
296
+ "add-iam-policy-binding",
297
+ projectId,
298
+ `--member=${member}`,
299
+ "--role=roles/logging.logWriter",
300
+ "--condition=None",
301
+ "--quiet",
302
+ "--format=none",
303
+ ]);
304
+ if (!logs.ok) return fail(`grant the ${spec.label} roles/logging.logWriter`, logs);
305
+ done.push(`${spec.label}: roles/logging.logWriter on the project`);
306
+
307
+ // 4. It passes the admin's IAP (its reports); the admin decides what a
308
+ // report may do.
309
+ const iap = await retry([
310
+ "iap",
311
+ "web",
312
+ "add-iam-policy-binding",
313
+ ...iapResourceArgs(target.resource),
314
+ `--member=${member}`,
315
+ "--role=roles/iap.httpsResourceAccessor",
316
+ "--condition=None",
317
+ project,
318
+ "--quiet",
319
+ ]);
320
+ if (!iap.ok) return fail(`let the ${spec.label} pass the admin's IAP`, iap);
321
+ done.push(
322
+ `${spec.label}: roles/iap.httpsResourceAccessor on the admin (${target.resource.service})`,
323
+ );
324
+
325
+ // 5. What its kind reads.
326
+ for (const b of spec.readBuckets) {
327
+ const r = await retry([
328
+ "storage",
329
+ "buckets",
330
+ "add-iam-policy-binding",
331
+ `gs://${b.bucket}`,
332
+ `--member=${member}`,
333
+ "--role=roles/storage.objectViewer",
334
+ // A bucket whose policy already holds a conditional binding refuses an
335
+ // unconditional grant in non-interactive mode unless it says so.
336
+ "--condition=None",
337
+ project,
338
+ "--quiet",
339
+ "--format=none",
340
+ ]);
341
+ if (!r.ok) return fail(`grant roles/storage.objectViewer on gs://${b.bucket} (${b.why})`, r);
342
+ done.push(`${spec.label}: roles/storage.objectViewer on gs://${b.bucket}`);
343
+ }
344
+
345
+ // 6. The jobs its kind starts.
346
+ for (const j of spec.runJobs) {
347
+ for (const role of ["roles/run.jobsExecutorWithOverrides", "roles/run.viewer"]) {
348
+ const r = await retry([
349
+ "run",
350
+ "jobs",
351
+ "add-iam-policy-binding",
352
+ j.job,
353
+ `--region=${region}`,
354
+ project,
355
+ `--member=${member}`,
356
+ `--role=${role}`,
357
+ "--quiet",
358
+ "--format=none",
359
+ ]);
360
+ if (!r.ok) return fail(`grant the ${spec.label} ${role} on ${j.job} (${j.why})`, r);
361
+ done.push(`${spec.label}: ${role} on ${j.job}`);
362
+ }
363
+ }
364
+
365
+ // 7. The job: the admin image, its own SA, no secrets, no VPC.
366
+ const deploy = await run([
367
+ "run",
368
+ "jobs",
369
+ "deploy",
370
+ spec.jobName,
371
+ `--image=${target.adminImageRef}`,
372
+ `--region=${region}`,
373
+ project,
374
+ `--service-account=${sa}`,
375
+ "--command=bun",
376
+ `--args=--bun,${REPORTING_JOB_SCRIPT}`,
377
+ `--set-env-vars=${spec.env.join(",")}`,
378
+ // The backstop restarts a dead attempt with a fresh token; a Cloud Run
379
+ // retry would replay the old one.
380
+ "--max-retries=0",
381
+ `--task-timeout=${spec.taskTimeoutSeconds}s`,
382
+ `--cpu=${spec.cpu}`,
383
+ `--memory=${spec.memory}`,
384
+ "--quiet",
385
+ ]);
386
+ if (!deploy.ok) return fail(`deploy job ${spec.jobName}`, deploy);
387
+ done.push(`job ${spec.jobName} (${target.adminImageRef.split("@")[1]?.slice(0, 19)}...)`);
388
+
389
+ // 8. The admin may run it with each attempt's order and read its executions.
390
+ for (const role of ["roles/run.jobsExecutorWithOverrides", "roles/run.viewer"]) {
391
+ const r = await retry([
392
+ "run",
393
+ "jobs",
394
+ "add-iam-policy-binding",
395
+ spec.jobName,
396
+ `--region=${region}`,
397
+ project,
398
+ `--member=${runSaMember}`,
399
+ `--role=${role}`,
400
+ "--quiet",
401
+ "--format=none",
402
+ ]);
403
+ if (!r.ok) return fail(`grant the admin ${role} on ${spec.jobName}`, r);
404
+ done.push(`admin: ${role} on ${spec.jobName}`);
405
+ }
406
+ return { ok: true, done, serviceAccount: sa };
407
+ }
408
+
409
+ /** Ensure the quality-audit runner (#1359). */
410
+ export function ensureAuditRunnerJob(
411
+ target: ReportingJobTarget,
412
+ deps: { run?: GcloudRunner; sleep?: Sleep } = {},
413
+ ): Promise<ReportingJobResult> {
414
+ return ensureReportingJob(target, auditRunnerJobSpec(target), deps);
415
+ }
416
+
417
+ /** Ensure the site-import crawler (#1360). */
418
+ export function ensureImportCrawlJob(
419
+ target: ReportingJobTarget,
420
+ deps: { run?: GcloudRunner; sleep?: Sleep } = {},
421
+ ): Promise<ReportingJobResult> {
422
+ return ensureReportingJob(target, importCrawlJobSpec(target), deps);
423
+ }
424
+
425
+ /** Ensure the build carrier (#1574). */
426
+ export function ensureBuildCarrierJob(
427
+ target: ReportingJobTarget,
428
+ deps: { run?: GcloudRunner; sleep?: Sleep } = {},
429
+ ): Promise<ReportingJobResult> {
430
+ return ensureReportingJob(target, buildCarrierJobSpec(target), deps);
431
+ }
@@ -68,6 +68,7 @@ import {
68
68
  type ReleaseImages,
69
69
  } from "./compose.js";
70
70
  import { MIGRATION_TARGETS } from "./migration-targets.js";
71
+ import { resolveChannelVersion } from "./release-candidate.js";
71
72
  import { selfCommand } from "./self-command.js";
72
73
  import {
73
74
  type HostRunner,
@@ -516,15 +517,29 @@ function fail(
516
517
  return { ok: false, stage, error, previousRunning };
517
518
  }
518
519
 
519
- /** The tag to resolve and the version to record: explicit, channel, or newest stable. */
520
+ /**
521
+ * The tag to resolve and the version to record: explicit, the channel's
522
+ * newest release (#1558: there is no moving channel tag to resolve), or the
523
+ * newest stable release.
524
+ */
520
525
  async function targetVersion(
521
526
  opts: SelfHostedUpgradeOpts,
522
527
  fetchImpl?: typeof fetch,
523
528
  ): Promise<{ ok: true; tag: string; version: string } | { ok: false; error: string }> {
524
- if (opts.version || opts.channel === "rc" || opts.channel === "beta") {
525
- const tag = releaseTag(opts);
529
+ if (opts.version) {
530
+ const tag = releaseTag({ version: opts.version });
526
531
  return { ok: true, tag, version: tag };
527
532
  }
533
+ if (opts.channel === "rc" || opts.channel === "beta") {
534
+ const newest = await resolveChannelVersion(opts.channel, fetchImpl);
535
+ if (!newest.ok) {
536
+ return {
537
+ ok: false,
538
+ error: `Could not look up the newest ${opts.channel} release (${newest.reason}). Pass --version x.y.z.`,
539
+ };
540
+ }
541
+ return { ok: true, tag: newest.version, version: newest.version };
542
+ }
528
543
  const latest = await fetchLatestReleaseTag(fetchImpl);
529
544
  if (!latest.ok) {
530
545
  return {
@@ -108,6 +108,16 @@ describe("adminEnvContract", () => {
108
108
  CAELO_AUDIT_RESULTS_BUCKET: "acme-caelo-production-audit-results",
109
109
  CAELO_CAPTURE_BUCKET: "acme-caelo-production-capture",
110
110
  CAELO_CAPTURE_JOB: "projects/acme/locations/europe-west1/jobs/caelo-production-capture",
111
+ // #1359 — the job a Stage's audit runs in, and whose reports the admin takes.
112
+ CAELO_AUDIT_RUNNER_JOB:
113
+ "projects/acme/locations/europe-west1/jobs/caelo-production-audit-run",
114
+ CAELO_AUDIT_RUNNER_SERVICE_ACCOUNT: "caelo-production-audit-run@acme.iam.gserviceaccount.com",
115
+ // #1360 — the same pair for the site-import crawler.
116
+ CAELO_IMPORT_CRAWL_JOB: "projects/acme/locations/europe-west1/jobs/caelo-production-import",
117
+ CAELO_IMPORT_CRAWL_SERVICE_ACCOUNT: "caelo-production-import@acme.iam.gserviceaccount.com",
118
+ // #1574 — and for the build carrier.
119
+ CAELO_BUILD_CARRIER_JOB: "projects/acme/locations/europe-west1/jobs/caelo-production-build",
120
+ CAELO_BUILD_CARRIER_SERVICE_ACCOUNT: "caelo-production-build@acme.iam.gserviceaccount.com",
111
121
  CAELO_STATIC_BUCKET: "acme-caelo-production-static",
112
122
  CAELO_STAGING_BUCKET: "acme-caelo-production-staging",
113
123
  // #1330 — every provider serves staging at its own host now.
@@ -156,6 +166,16 @@ describe("adminEnvContract", () => {
156
166
  CAELO_AUDIT_RESULTS_BUCKET: "acme-caelo-production-audit-results",
157
167
  CAELO_CAPTURE_BUCKET: "acme-caelo-production-capture",
158
168
  CAELO_CAPTURE_JOB: "projects/acme/locations/europe-west1/jobs/caelo-production-capture",
169
+ // #1359 — the job a Stage's audit runs in, and whose reports the admin takes.
170
+ CAELO_AUDIT_RUNNER_JOB:
171
+ "projects/acme/locations/europe-west1/jobs/caelo-production-audit-run",
172
+ CAELO_AUDIT_RUNNER_SERVICE_ACCOUNT: "caelo-production-audit-run@acme.iam.gserviceaccount.com",
173
+ // #1360 — the same pair for the site-import crawler.
174
+ CAELO_IMPORT_CRAWL_JOB: "projects/acme/locations/europe-west1/jobs/caelo-production-import",
175
+ CAELO_IMPORT_CRAWL_SERVICE_ACCOUNT: "caelo-production-import@acme.iam.gserviceaccount.com",
176
+ // #1574 — and for the build carrier.
177
+ CAELO_BUILD_CARRIER_JOB: "projects/acme/locations/europe-west1/jobs/caelo-production-build",
178
+ CAELO_BUILD_CARRIER_SERVICE_ACCOUNT: "caelo-production-build@acme.iam.gserviceaccount.com",
159
179
  CAELO_FIREBASE_SITE: "caelo-production-site-abc123",
160
180
  CAELO_GATEWAY_SERVICE: "caelo-production-gateway-1a2b3c4",
161
181
  CAELO_GATEWAY_REGION: "europe-west1",
@@ -216,6 +236,9 @@ describe("gatewayEnvContract", () => {
216
236
  CAELO_TRUSTED_PROXY_HOPS: "2",
217
237
  PUBLIC_DATABASE_URL:
218
238
  "postgresql://public_role@db1.p-label.europe-west1.sql-psa.goog:5432/cms_public?sslmode=verify-full&sslrootcert=/etc/caelo/db-ca/cloudsql-global.pem",
239
+ // The only account whose refresh pings it takes: the admin's runtime
240
+ // account. An identity, nothing secret.
241
+ CAELO_GATEWAY_REFRESH_ACCOUNT: "caelo-production-run-sa@acme.iam.gserviceaccount.com",
219
242
  PUBLIC_DATABASE_PASSWORD: "secret:caelo-production-public-role-password:latest",
220
243
  // No remote-MCP env: the broker is the MCP-Auth-Proxy's (#1328); no
221
244
  // staging gate key: the staging gateway's, through its projection (#1330).
@@ -246,6 +269,7 @@ describe("gatewayEnvContract", () => {
246
269
  PUBLIC_DATABASE_URL:
247
270
  "postgresql://public_staging_role@db1.p-label.europe-west1.sql-psa.goog:5432/cms_public_staging?sslmode=verify-full&sslrootcert=/etc/caelo/db-ca/cloudsql-global.pem",
248
271
  CAELO_STAGING_STORAGE: "gs://acme-caelo-production-staging",
272
+ CAELO_GATEWAY_REFRESH_ACCOUNT: "caelo-production-run-sa@acme.iam.gserviceaccount.com",
249
273
  PUBLIC_DATABASE_PASSWORD: "secret:caelo-production-public-staging-role-password:latest",
250
274
  });
251
275
  }
@@ -34,17 +34,28 @@
34
34
  * Pure module — the stacks import it from `dist/`.
35
35
  */
36
36
 
37
- import { CLOUD_SQL_CA_BUNDLE, isIpLiteral, verifyFullQuery } from "@caelo-cms/shared";
37
+ import {
38
+ CLOUD_SQL_CA_BUNDLE,
39
+ GATEWAY_REFRESH_ACCOUNT_ENV,
40
+ isIpLiteral,
41
+ verifyFullQuery,
42
+ } from "@caelo-cms/shared";
38
43
  import { z } from "zod";
39
44
  import type { SupportedProvider } from "./adapter.js";
40
45
  import {
41
46
  auditJobResource,
47
+ auditRunnerJobResource,
48
+ auditRunnerServiceAccountEmail,
49
+ buildCarrierJobResource,
50
+ buildCarrierServiceAccountEmail,
42
51
  captureJobResource,
43
52
  convergeJobResource,
44
53
  gatewayServiceAccountEmail,
45
54
  gcpBucketName,
46
55
  gcpNamePrefix,
47
56
  gcpSecretId,
57
+ importCrawlJobResource,
58
+ importCrawlServiceAccountEmail,
48
59
  mcpAuthProxyServiceAccountEmail,
49
60
  mcpIapServiceAccountEmail,
50
61
  operatorAccessJobResource,
@@ -388,6 +399,30 @@ export const CAPTURE_JOB_ENV_VAR = "CAELO_CAPTURE_JOB";
388
399
  export const CAPTURE_BUCKET_ENV_VAR = "CAELO_CAPTURE_BUCKET";
389
400
  export const MEDIA_BUCKET_ENV_VAR = "CAELO_MEDIA_BUCKET";
390
401
 
402
+ /**
403
+ * #1359 — the admin env vars naming the quality-audit runner job (the
404
+ * whole audit of a Stage, a reporting job: reporting-job-setup.ts) and the
405
+ * one service account whose reports the admin takes for it (admin-core
406
+ * quality/audit-job-kind.ts). `upgrade` leaves them untouched when it could
407
+ * not set the job up.
408
+ */
409
+ export const AUDIT_RUNNER_JOB_ENV_VAR = "CAELO_AUDIT_RUNNER_JOB";
410
+ export const AUDIT_RUNNER_SERVICE_ACCOUNT_ENV_VAR = "CAELO_AUDIT_RUNNER_SERVICE_ACCOUNT";
411
+
412
+ /**
413
+ * #1360 — the same pair for the site-import crawler (a site import's crawl,
414
+ * a reporting job; admin-core site-import/import-job-kind.ts).
415
+ */
416
+ export const IMPORT_CRAWL_JOB_ENV_VAR = "CAELO_IMPORT_CRAWL_JOB";
417
+ export const IMPORT_CRAWL_SERVICE_ACCOUNT_ENV_VAR = "CAELO_IMPORT_CRAWL_SERVICE_ACCOUNT";
418
+
419
+ /**
420
+ * #1574 — the same pair for the build carrier (the job that holds the
421
+ * request a build runs in; admin-core build-carrier/kind.ts).
422
+ */
423
+ export const BUILD_CARRIER_JOB_ENV_VAR = "CAELO_BUILD_CARRIER_JOB";
424
+ export const BUILD_CARRIER_SERVICE_ACCOUNT_ENV_VAR = "CAELO_BUILD_CARRIER_SERVICE_ACCOUNT";
425
+
391
426
  /**
392
427
  * #1140 — the admin env var naming the service account of the scheduler
393
428
  * tick (scheduler-setup.ts): the one IAP identity the admin's
@@ -1005,6 +1040,12 @@ export function gatewayEnvContract<V>(inputs: RuntimeEnvInputs<V>): CloudRunEnvV
1005
1040
  { name: GATEWAY_ENVIRONMENT_ENV, value: "live" },
1006
1041
  { name: TRUSTED_PROXY_HOPS_ENV, value: String(GATEWAY_TRUSTED_PROXY_HOPS[inputs.provider]) },
1007
1042
  { name: "PUBLIC_DATABASE_URL", value: inputs.databaseUrls.public },
1043
+ // The only account whose refresh pings the gateway takes: the admin's
1044
+ // (@caelo-cms/shared gateway-refresh.ts). An identity, not a secret.
1045
+ {
1046
+ name: GATEWAY_REFRESH_ACCOUNT_ENV,
1047
+ value: runServiceAccountEmail(inputs.projectId, inputs.env),
1048
+ },
1008
1049
  ...secretEnv("gateway", inputs.env),
1009
1050
  ];
1010
1051
  }
@@ -1029,6 +1070,11 @@ export function stagingGatewayEnvContract<V>(
1029
1070
  },
1030
1071
  { name: "PUBLIC_DATABASE_URL", value: inputs.databaseUrls.publicStaging },
1031
1072
  { name: STAGING_STORAGE_ENV, value: gcpStagingStorage(inputs.projectId, inputs.env) },
1073
+ // As the live gateway's: whose refresh pings it takes.
1074
+ {
1075
+ name: GATEWAY_REFRESH_ACCOUNT_ENV,
1076
+ value: runServiceAccountEmail(inputs.projectId, inputs.env),
1077
+ },
1032
1078
  ...secretEnv("staging-gateway", inputs.env),
1033
1079
  ];
1034
1080
  }
@@ -1127,16 +1173,18 @@ export const DEFAULT_MCP_AUTH_PROXY_MAX_INSTANCES = 10;
1127
1173
  * `resources`, which is how both services ran with always-on CPU without
1128
1174
  * anyone choosing it — billed for every idle minute an instance stayed up.
1129
1175
  *
1130
- * The gateway and the MCP-Auth-Proxy only do work inside requests. The
1131
- * admin's periodic work and plugin workers run on the scheduler tick
1132
- * (#1140), but the quality audit and the site-import crawl still run on
1133
- * in-process timers that need CPU between requests (#1359, #1360), and the
1134
- * plugin runtime heartbeat would read an idling instance as down.
1176
+ * Every service only does work inside requests (CLAUDE.md §11.B Tier 5,
1177
+ * #1140, #1361): the admin's periodic work and plugin workers run on the
1178
+ * scheduler tick, the quality audit and the site-import crawl in container
1179
+ * jobs that report back by request, the plugin runtime heartbeat at
1180
+ * request start. So every one of them is billed only while a request is
1181
+ * open — the admin idles at about nothing, which is the point: always-on
1182
+ * CPU kept one admin instance billed around the clock on every install.
1183
+ * An upgrade moves a service still on always-on CPU here (`planCpuIdle`,
1184
+ * one way only).
1135
1185
  */
1136
1186
  export const SERVICE_CPU_IDLE: Readonly<Record<CloudRunSlug, boolean>> = {
1137
- // FIXME(issue #1361): true once nothing in the admin depends on CPU
1138
- // between requests (the category-A jobs, the heartbeat at request start).
1139
- admin: false,
1187
+ admin: true,
1140
1188
  gateway: true,
1141
1189
  "staging-gateway": true,
1142
1190
  "mcp-auth-proxy": true,
@@ -1450,6 +1498,36 @@ export function adminEnvContract<V>(inputs: AdminEnvInputs<V>): CloudRunEnvVar<V
1450
1498
  { name: CAPTURE_JOB_ENV_VAR, value: captureJobResource(projectId, inputs.region, env) },
1451
1499
  { name: CAPTURE_BUCKET_ENV_VAR, value: gcpBucketName(projectId, env, "capture") },
1452
1500
  { name: MEDIA_BUCKET_ENV_VAR, value: gcpBucketName(projectId, env, "media") },
1501
+ // #1359 — the job a Stage's quality audit runs in, and the only IAP
1502
+ // identity whose reports the admin takes for it (reporting-job-setup.ts).
1503
+ {
1504
+ name: AUDIT_RUNNER_JOB_ENV_VAR,
1505
+ value: auditRunnerJobResource(projectId, inputs.region, env),
1506
+ },
1507
+ {
1508
+ name: AUDIT_RUNNER_SERVICE_ACCOUNT_ENV_VAR,
1509
+ value: auditRunnerServiceAccountEmail(projectId, env),
1510
+ },
1511
+ // #1360 — the job a site import's crawl runs in, and the only IAP
1512
+ // identity whose reports the admin takes for it.
1513
+ {
1514
+ name: IMPORT_CRAWL_JOB_ENV_VAR,
1515
+ value: importCrawlJobResource(projectId, inputs.region, env),
1516
+ },
1517
+ {
1518
+ name: IMPORT_CRAWL_SERVICE_ACCOUNT_ENV_VAR,
1519
+ value: importCrawlServiceAccountEmail(projectId, env),
1520
+ },
1521
+ // #1574 — the job that holds the request a build nobody else waits for
1522
+ // runs in, and the only IAP identity whose reports the admin takes for it.
1523
+ {
1524
+ name: BUILD_CARRIER_JOB_ENV_VAR,
1525
+ value: buildCarrierJobResource(projectId, inputs.region, env),
1526
+ },
1527
+ {
1528
+ name: BUILD_CARRIER_SERVICE_ACCOUNT_ENV_VAR,
1529
+ value: buildCarrierServiceAccountEmail(projectId, env),
1530
+ },
1453
1531
  // #1140 — the only IAP identity the admin's scheduler tick endpoint
1454
1532
  // accepts (scheduler-setup.ts).
1455
1533
  {
@@ -367,6 +367,8 @@ describe("upgrading a v0.10.35 install: the gateway leaves admin_role (#613)", (
367
367
  "ADMIN_DATABASE_URL",
368
368
  // #1329 — the gateway says it is the live site's.
369
369
  "CAELO_GATEWAY_ENVIRONMENT",
370
+ // Whose refresh pings it takes: the admin's account.
371
+ "CAELO_GATEWAY_REFRESH_ACCOUNT",
370
372
  // No remote-MCP env: the broker is the MCP-Auth-Proxy's (#1328).
371
373
  // No staging gate key: it reaches the staging gateway through the
372
374
  // staging projection (#1330), never the live gateway.