@caelo-cms/provisioning 0.12.10 → 0.12.12

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 (131) hide show
  1. package/dist/agent-db.js +51 -2
  2. package/dist/cli.js +23 -2
  3. package/dist/cli.js.map +1 -1
  4. package/dist/collection-stores.d.ts +5 -0
  5. package/dist/collection-stores.d.ts.map +1 -0
  6. package/dist/collection-stores.js +21 -0
  7. package/dist/collection-stores.js.map +1 -0
  8. package/dist/collections-setup.d.ts +66 -0
  9. package/dist/collections-setup.d.ts.map +1 -0
  10. package/dist/collections-setup.js +252 -0
  11. package/dist/collections-setup.js.map +1 -0
  12. package/dist/compose.d.ts +27 -0
  13. package/dist/compose.d.ts.map +1 -1
  14. package/dist/compose.js +52 -1
  15. package/dist/compose.js.map +1 -1
  16. package/dist/gateway-edge.d.ts +13 -0
  17. package/dist/gateway-edge.d.ts.map +1 -1
  18. package/dist/gateway-edge.js +22 -0
  19. package/dist/gateway-edge.js.map +1 -1
  20. package/dist/gcp-names.d.ts +18 -48
  21. package/dist/gcp-names.d.ts.map +1 -1
  22. package/dist/gcp-names.js +11 -69
  23. package/dist/gcp-names.js.map +1 -1
  24. package/dist/infra-contract.d.ts +1 -1
  25. package/dist/infra-contract.d.ts.map +1 -1
  26. package/dist/infra-contract.js +35 -1
  27. package/dist/infra-contract.js.map +1 -1
  28. package/dist/reporting-job-catalog.d.ts +111 -0
  29. package/dist/reporting-job-catalog.d.ts.map +1 -0
  30. package/dist/reporting-job-catalog.js +306 -0
  31. package/dist/reporting-job-catalog.js.map +1 -0
  32. package/dist/reporting-job-setup.d.ts +11 -68
  33. package/dist/reporting-job-setup.d.ts.map +1 -1
  34. package/dist/reporting-job-setup.js +44 -100
  35. package/dist/reporting-job-setup.js.map +1 -1
  36. package/dist/runtime-secrets.d.ts +25 -0
  37. package/dist/runtime-secrets.d.ts.map +1 -1
  38. package/dist/runtime-secrets.js +34 -0
  39. package/dist/runtime-secrets.js.map +1 -1
  40. package/dist/self-hosted-backup.d.ts.map +1 -1
  41. package/dist/self-hosted-backup.js +18 -6
  42. package/dist/self-hosted-backup.js.map +1 -1
  43. package/dist/stack-contract.d.ts +75 -22
  44. package/dist/stack-contract.d.ts.map +1 -1
  45. package/dist/stack-contract.js +142 -51
  46. package/dist/stack-contract.js.map +1 -1
  47. package/dist/stack-converge.d.ts +20 -1
  48. package/dist/stack-converge.d.ts.map +1 -1
  49. package/dist/stack-converge.js +105 -2
  50. package/dist/stack-converge.js.map +1 -1
  51. package/dist/staging-gateway-setup.d.ts.map +1 -1
  52. package/dist/staging-gateway-setup.js +10 -5
  53. package/dist/staging-gateway-setup.js.map +1 -1
  54. package/dist/upgrade/admin-image-jobs.d.ts +4 -3
  55. package/dist/upgrade/admin-image-jobs.d.ts.map +1 -1
  56. package/dist/upgrade/admin-image-jobs.js +9 -16
  57. package/dist/upgrade/admin-image-jobs.js.map +1 -1
  58. package/dist/upgrade/app-roll.d.ts +16 -0
  59. package/dist/upgrade/app-roll.d.ts.map +1 -1
  60. package/dist/upgrade/app-roll.js +35 -23
  61. package/dist/upgrade/app-roll.js.map +1 -1
  62. package/dist/upgrade/converge.d.ts +1 -1
  63. package/dist/upgrade/converge.d.ts.map +1 -1
  64. package/dist/upgrade/converge.js +83 -87
  65. package/dist/upgrade/converge.js.map +1 -1
  66. package/dist/upgrade/upgrade.d.ts +7 -5
  67. package/dist/upgrade/upgrade.d.ts.map +1 -1
  68. package/dist/upgrade/upgrade.js +31 -14
  69. package/dist/upgrade/upgrade.js.map +1 -1
  70. package/dist/upgrader-iam-preflight.d.ts.map +1 -1
  71. package/dist/upgrader-iam-preflight.js +8 -18
  72. package/dist/upgrader-iam-preflight.js.map +1 -1
  73. package/dist/upgrader-setup.d.ts.map +1 -1
  74. package/dist/upgrader-setup.js +7 -15
  75. package/dist/upgrader-setup.js.map +1 -1
  76. package/dist/visitor-query-logs.d.ts +40 -0
  77. package/dist/visitor-query-logs.d.ts.map +1 -0
  78. package/dist/visitor-query-logs.js +41 -0
  79. package/dist/visitor-query-logs.js.map +1 -0
  80. package/dist/wizards/gcp-cost.d.ts.map +1 -1
  81. package/dist/wizards/gcp-cost.js +17 -9
  82. package/dist/wizards/gcp-cost.js.map +1 -1
  83. package/dist/wizards/gcp.d.ts.map +1 -1
  84. package/dist/wizards/gcp.js +45 -35
  85. package/dist/wizards/gcp.js.map +1 -1
  86. package/package.json +2 -2
  87. package/src/admin-memory.test.ts +57 -1
  88. package/src/cli.ts +23 -1
  89. package/src/collection-stores.ts +28 -0
  90. package/src/collections-setup.test.ts +237 -0
  91. package/src/collections-setup.ts +317 -0
  92. package/src/compose.ts +54 -1
  93. package/src/gateway-edge.test.ts +28 -0
  94. package/src/gateway-edge.ts +24 -0
  95. package/src/gateway-env-isolation.test.ts +141 -3
  96. package/src/gcp-names.ts +28 -84
  97. package/src/infra-contract.test.ts +5 -3
  98. package/src/infra-contract.ts +35 -1
  99. package/src/remote-mcp.test.ts +13 -1
  100. package/src/reporting-job-catalog.test.ts +156 -0
  101. package/src/reporting-job-catalog.ts +426 -0
  102. package/src/reporting-job-setup.test.ts +119 -6
  103. package/src/reporting-job-setup.ts +51 -158
  104. package/src/runtime-secrets.test.ts +19 -4
  105. package/src/runtime-secrets.ts +42 -0
  106. package/src/self-hosted-backup.test.ts +2 -2
  107. package/src/self-hosted-backup.ts +18 -6
  108. package/src/self-hosted-compose.test.ts +9 -3
  109. package/src/stack-contract.test.ts +62 -4
  110. package/src/stack-contract.ts +172 -59
  111. package/src/stack-converge-secrets.test.ts +4 -0
  112. package/src/stack-converge.test.ts +81 -3
  113. package/src/stack-converge.ts +124 -3
  114. package/src/staging-gateway-setup.test.ts +4 -0
  115. package/src/staging-gateway-setup.ts +16 -6
  116. package/src/upgrade/admin-image-jobs.ts +13 -25
  117. package/src/upgrade/app-roll.ts +54 -28
  118. package/src/upgrade/converge.ts +100 -122
  119. package/src/upgrade/upgrade.test.ts +159 -6
  120. package/src/upgrade/upgrade.ts +46 -32
  121. package/src/upgrader-iam-preflight.ts +7 -20
  122. package/src/upgrader-job.test.ts +3 -0
  123. package/src/upgrader-setup.test.ts +3 -0
  124. package/src/upgrader-setup.ts +6 -17
  125. package/src/visitor-query-logs.ts +46 -0
  126. package/src/wizards/gcp-cost.ts +19 -9
  127. package/src/wizards/gcp.ts +51 -45
  128. package/stacks/aws/index.ts +18 -9
  129. package/stacks/azure/index.ts +19 -8
  130. package/stacks/gcp/index.ts +54 -1
  131. package/stacks/gcp-firebase/index.ts +28 -1
@@ -3,13 +3,15 @@
3
3
  /**
4
4
  * The converge half of an upgrade (epic #696): everything that changes IAM,
5
5
  * service accounts, secrets or other cloud resources so the install matches
6
- * what the release's stacks declare — the gateway's run SA and the
7
- * CLI-generated runtime secrets, the stack's IAM/CDN/firewall invariants,
6
+ * what the release's stacks declare — the stack's IAM/CDN/firewall invariants,
8
7
  * MCP access through IAP, the staging database and its gateway login
9
8
  * (#1329), the gateway logins' Cloud SQL role memberships (#633),
10
9
  * the gateway's and public_role's database logins, the operator-access sync
11
- * job, the quality-audit job (#875), the remote-MCP load-balancer rules and
12
- * identity env (#806), and dropping bindings nothing reads any more.
10
+ * job, the quality-audit job (#875), the reporting jobs (#1359, #1360,
11
+ * #1574, epic #1644's collection index job), the collection stores and the
12
+ * search-query log exclusion (epic #1644), the remote-MCP load-balancer
13
+ * rules and identity env (#806), and dropping bindings nothing reads any
14
+ * more.
13
15
  *
14
16
  * It needs the rights of whoever provisioned the install: `cms-provision
15
17
  * upgrade` runs it as the operator's own identity, and the converge job
@@ -27,6 +29,10 @@
27
29
  * gets its password after migrations, before the gateway rolls onto it), so
28
30
  * a converge is a {@link ConvergeSession}: a part before the app-roll, the
29
31
  * {@link AppRollHooks} the app-roll calls in between, and a part after it.
32
+ *
33
+ * The gateway's run SA and the CLI-generated runtime secrets come before all
34
+ * of it, in the upgrade's pre-flight (`ensureRuntimeIdentities`, #1682):
35
+ * the services that pre-flight sets up are granted those secrets.
30
36
  */
31
37
 
32
38
  import { ensureAuditJob, resolveAdminImage } from "../audit-job-setup.js";
@@ -37,50 +43,35 @@ import {
37
43
  liveDatabaseUrls,
38
44
  moveServicesToDnsHost,
39
45
  } from "../cloudsql-tls.js";
46
+ import { COLLECTIONS_LIVE_STORE_ENV, COLLECTIONS_STAGING_STORE_ENV } from "../collection-stores.js";
47
+ import { ensureCollectionStores } from "../collections-setup.js";
40
48
  import { ensureConvergeJob } from "../converge-job-setup.js";
41
49
  import { ensureGatewayArmorRules } from "../gateway-armor.js";
42
50
  import { findSqlInstance, planPublicRoleSwitch } from "../gateway-credentials.js";
43
51
  import type { GcloudRunner, Sleep } from "../gcloud-retry.js";
44
- import {
45
- auditRunnerServiceAccountEmail,
46
- buildCarrierServiceAccountEmail,
47
- importCrawlServiceAccountEmail,
48
- schedulerServiceAccountEmail,
49
- upgraderServiceAccountEmail,
50
- } from "../gcp-names.js";
52
+ import { schedulerServiceAccountEmail, upgraderServiceAccountEmail } from "../gcp-names.js";
51
53
  import type { InstallMetadata } from "../install-state.js";
52
54
  import { ensureMcpIapAccess, type IapResource } from "../mcp-iap.js";
53
55
  import { ensureOperatorAccessSync, resolveOperatorAccessTarget } from "../operator-access.js";
54
56
  import { revokePublicRoleMemberships } from "../public-role-isolation.js";
55
57
  import { ensureRemoteMcpEdge, resolveRemoteMcpIdentity } from "../remote-mcp.js";
56
58
  import {
57
- ensureAuditRunnerJob,
58
- ensureBuildCarrierJob,
59
- ensureImportCrawlJob,
60
- } from "../reporting-job-setup.js";
61
- import {
62
- ensureGatewayServiceAccount,
63
- ensureGeneratedSecrets,
64
- type HttpFetch,
65
- plainGeneratedSecretSeed,
66
- readSecretReplication,
67
- } from "../runtime-secrets.js";
59
+ REPORTING_JOB_CATALOG,
60
+ type ReportingJobKindEntry,
61
+ reportingJobServiceAccountEmail,
62
+ } from "../reporting-job-catalog.js";
63
+ import { ensureReportingJobKind } from "../reporting-job-setup.js";
64
+ import type { HttpFetch } from "../runtime-secrets.js";
68
65
  import { ensureSchedulerTick } from "../scheduler-setup.js";
69
66
  import { selfCommand } from "../self-command.js";
70
67
  import {
71
68
  AUDIT_JOB_ENV_VAR,
72
69
  AUDIT_RESULTS_BUCKET_ENV_VAR,
73
- AUDIT_RUNNER_JOB_ENV_VAR,
74
- AUDIT_RUNNER_SERVICE_ACCOUNT_ENV_VAR,
75
- BUILD_CARRIER_JOB_ENV_VAR,
76
- BUILD_CARRIER_SERVICE_ACCOUNT_ENV_VAR,
77
70
  CAPTURE_BUCKET_ENV_VAR,
78
71
  CAPTURE_JOB_ENV_VAR,
79
72
  type CloudRunEnvVar,
80
73
  CONVERGE_JOB_ENV_VAR,
81
74
  DATABASE_URL_VARS,
82
- IMPORT_CRAWL_JOB_ENV_VAR,
83
- IMPORT_CRAWL_SERVICE_ACCOUNT_ENV_VAR,
84
75
  MCP_ENV_VAR,
85
76
  OPERATOR_ACCESS_JOB_ENV_VAR,
86
77
  parseSchedulerIntervalMinutes,
@@ -195,41 +186,6 @@ export function startConverge(
195
186
  const leaveUntouched: string[] = [];
196
187
  let publicRole: ReturnType<typeof planPublicRoleSwitch> | null = null;
197
188
 
198
- async function runtimeIdentities(): Promise<boolean> {
199
- // The gateway's own run SA and the CLI-generated secrets the env
200
- // contract references. Created once, never overwritten; must exist
201
- // before the invariants bind them and the rolls reference them.
202
- const s = r.step("Ensuring the gateway service account + generated runtime secrets...");
203
- const secretsTarget = { projectId: install.projectId, env: install.env };
204
- const replication = await readSecretReplication(secretsTarget, runDeps);
205
- const outcomes = [
206
- await ensureGatewayServiceAccount(secretsTarget, runDeps),
207
- ...(replication.ok
208
- ? await ensureGeneratedSecrets(
209
- {
210
- ...secretsTarget,
211
- region: install.region,
212
- replication: replication.replication,
213
- seed: plainGeneratedSecretSeed(service("admin").liveEnv),
214
- },
215
- runDeps,
216
- )
217
- : [{ id: "secret replication", status: "failed" as const, error: replication.error }]),
218
- ];
219
- const failed = outcomes.filter((o) => o.status === "failed");
220
- if (failed.length > 0) {
221
- s.failed("Runtime identities/secrets could not be ensured. Aborting upgrade.");
222
- for (const o of failed) r.error(` FAILED: ${o.id}\n ${o.error ?? ""}`);
223
- r.warn("No traffic was shifted and no migrations ran. Fix the above and re-run.");
224
- return false;
225
- }
226
- s.done("Gateway service account + runtime secrets ok");
227
- for (const o of outcomes.filter((o) => o.status === "applied")) {
228
- r.info(` created: ${o.id}${o.detail ? ` (${o.detail})` : ""}`);
229
- }
230
- return true;
231
- }
232
-
233
189
  async function stackInvariants(): Promise<boolean> {
234
190
  // IAM bindings + CDN policy added to the stacks after this install was
235
191
  // provisioned (stack-contract.ts), a gcp-firebase gateway's ingress
@@ -402,24 +358,23 @@ export function startConverge(
402
358
  }
403
359
 
404
360
  /**
405
- * Reporting jobs (#1359, #1360) set up this run, or whose account exists
406
- * from an earlier one: the operator-access sync keeps them on IAP.
361
+ * Reporting jobs (reporting-job-catalog.ts) set up this run, or whose
362
+ * account exists from an earlier one: the operator-access sync keeps them
363
+ * on IAP.
407
364
  */
408
365
  const reportingJobsOnIap: string[] = [];
409
366
 
410
- async function reportingJob(job: {
411
- readonly step: string;
412
- readonly ready: string;
413
- readonly label: string;
414
- readonly consequence: string;
415
- readonly ensure: typeof ensureAuditRunnerJob;
416
- readonly serviceAccount: string;
417
- readonly envVars: readonly string[];
418
- }): Promise<void> {
367
+ async function reportingJob(entry: ReportingJobKindEntry): Promise<void> {
419
368
  // A job that reports back to the admin through IAP
420
369
  // (reporting-job-setup.ts), deployed with the admin's CURRENT image like
421
370
  // the audit job: the app-roll moves them onto the new one. A failure
422
371
  // costs the work it runs, so it warns and the admin keeps its env.
372
+ const job = {
373
+ ...entry.converge,
374
+ label: `${entry.label.charAt(0).toUpperCase()}${entry.label.slice(1)}`,
375
+ serviceAccount: reportingJobServiceAccountEmail(entry, install.projectId, install.env),
376
+ envVars: [entry.jobEnvVar, entry.serviceAccountEnvVar],
377
+ };
423
378
  const s = r.step(job.step);
424
379
  const image = await resolveAdminImage(
425
380
  { projectId: install.projectId, region: install.region, env: install.env },
@@ -430,7 +385,8 @@ export function startConverge(
430
385
  ? { ok: false as const, done: [], error: image.error }
431
386
  : !resource
432
387
  ? { ok: false as const, done: [], error: "the admin's IAP resource was not found" }
433
- : await job.ensure(
388
+ : await ensureReportingJobKind(
389
+ entry,
434
390
  {
435
391
  provider: install.provider,
436
392
  projectId: install.projectId,
@@ -451,63 +407,87 @@ export function startConverge(
451
407
  r.warn(
452
408
  `The upgrade continues; ${job.consequence} until this succeeds. Re-run upgrade once the cause is fixed.`,
453
409
  );
454
- // An account set up by an earlier run keeps its IAP access, or the next
455
- // operator-access sync would cut off a job that still works.
410
+ await keepOnIapIfExists(job.serviceAccount);
411
+ incomplete = true;
412
+ leaveUntouched.push(...job.envVars);
413
+ }
414
+
415
+ /**
416
+ * An account set up by an earlier run keeps its IAP access, or the next
417
+ * operator-access sync would cut off a job that still works.
418
+ */
419
+ async function keepOnIapIfExists(serviceAccount: string): Promise<void> {
456
420
  const exists = await run([
457
421
  "iam",
458
422
  "service-accounts",
459
423
  "describe",
460
- job.serviceAccount,
424
+ serviceAccount,
461
425
  `--project=${install.projectId}`,
462
426
  "--format=value(email)",
463
427
  ]);
464
- if (exists.ok) reportingJobsOnIap.push(job.serviceAccount);
465
- incomplete = true;
466
- leaveUntouched.push(...job.envVars);
428
+ if (exists.ok) reportingJobsOnIap.push(serviceAccount);
467
429
  }
468
430
 
469
431
  /**
470
- * #1359 — the job a Stage's whole quality audit runs in. After the audit
471
- * job, on whose Lighthouse tasks it gets its run grant.
432
+ * Epic #1644 — the collection stores (collections-setup.ts) and the log
433
+ * exclusion for visitors' search queries. A failure costs plugin
434
+ * collections (a site search) only: it warns, and the admin and the
435
+ * gateways keep their env without the stores.
472
436
  */
473
- const auditRunnerJob = () =>
474
- reportingJob({
475
- step: "Ensuring the quality-audit runner (audits outside the admin)...",
476
- ready: "Quality-audit runner ready (Stage audits run in their own job)",
477
- label: "Quality-audit runner",
478
- consequence: "Stage audits fail after their last attempt",
479
- ensure: ensureAuditRunnerJob,
480
- serviceAccount: auditRunnerServiceAccountEmail(install.projectId, install.env),
481
- envVars: [AUDIT_RUNNER_JOB_ENV_VAR, AUDIT_RUNNER_SERVICE_ACCOUNT_ENV_VAR],
482
- });
483
-
484
- /** #1360 — the job a site import's crawl runs in. */
485
- const importCrawlJob = () =>
486
- reportingJob({
487
- step: "Ensuring the site-import crawler (crawls outside the admin)...",
488
- ready: "Site-import crawler ready (site imports crawl in their own job)",
489
- label: "Site-import crawler",
490
- consequence: "site imports fail after their last attempt",
491
- ensure: ensureImportCrawlJob,
492
- serviceAccount: importCrawlServiceAccountEmail(install.projectId, install.env),
493
- envVars: [IMPORT_CRAWL_JOB_ENV_VAR, IMPORT_CRAWL_SERVICE_ACCOUNT_ENV_VAR],
494
- });
437
+ let collectionStoresReady = false;
438
+ async function collectionStores(): Promise<void> {
439
+ const s = r.step(
440
+ "Ensuring the collection stores (plugin indexes such as site search) and the search-query log exclusion...",
441
+ );
442
+ const cs = await ensureCollectionStores(
443
+ {
444
+ provider: install.provider,
445
+ projectId: install.projectId,
446
+ region: install.region,
447
+ env: install.env,
448
+ },
449
+ runDeps,
450
+ );
451
+ for (const step of cs.done) r.info(` ${step}`);
452
+ if (cs.ok) {
453
+ collectionStoresReady = true;
454
+ for (const p of cs.pending) r.warn(` not yet: ${p}`);
455
+ if (cs.pending.length > 0) incomplete = true;
456
+ s.done("Collection stores ready (each gateway reads only its own index)");
457
+ return;
458
+ }
459
+ s.warned(`Collection stores not set up: ${cs.error}`);
460
+ r.warn(
461
+ "The upgrade continues; plugin collections (a site search) fail at every Stage until this succeeds. Re-run upgrade once the cause is fixed.",
462
+ );
463
+ incomplete = true;
464
+ // And the env of every job that works on the stores, which is not set up.
465
+ leaveUntouched.push(
466
+ COLLECTIONS_STAGING_STORE_ENV,
467
+ COLLECTIONS_LIVE_STORE_ENV,
468
+ ...REPORTING_JOB_CATALOG.filter((e) => e.prerequisite === "collection-stores").flatMap(
469
+ (e) => [e.jobEnvVar, e.serviceAccountEnvVar],
470
+ ),
471
+ );
472
+ }
495
473
 
496
474
  /**
497
- * #1574 — the job that holds the request a Stage, Publish live or
498
- * production build nobody else waits for runs in.
475
+ * Every reporting job of the catalog, in its order: each after what it
476
+ * needs (the audit runner after the audit job whose Lighthouse tasks it
477
+ * starts; the collection index job after the stores it writes, and not
478
+ * at all without them: its env stays untouched, collectionStores said so).
499
479
  */
500
- const buildCarrierJob = () =>
501
- reportingJob({
502
- step: "Ensuring the build carrier (builds that outlast their request)...",
503
- ready: "Build carrier ready (a build nobody waits for still ends)",
504
- label: "Build carrier",
505
- consequence:
506
- "an agent's Stage and every Stage or Publish live button fail at once with this reason",
507
- ensure: ensureBuildCarrierJob,
508
- serviceAccount: buildCarrierServiceAccountEmail(install.projectId, install.env),
509
- envVars: [BUILD_CARRIER_JOB_ENV_VAR, BUILD_CARRIER_SERVICE_ACCOUNT_ENV_VAR],
510
- });
480
+ async function reportingJobs(): Promise<void> {
481
+ for (const entry of REPORTING_JOB_CATALOG) {
482
+ if (entry.prerequisite === "collection-stores" && !collectionStoresReady) {
483
+ await keepOnIapIfExists(
484
+ reportingJobServiceAccountEmail(entry, install.projectId, install.env),
485
+ );
486
+ continue;
487
+ }
488
+ await reportingJob(entry);
489
+ }
490
+ }
511
491
 
512
492
  async function captureJob(): Promise<void> {
513
493
  // #1217 — the job every server-side browser render runs in, so no
@@ -1016,7 +996,6 @@ export function startConverge(
1016
996
  return {
1017
997
  async beforeAppRoll() {
1018
998
  if (deps.provisionerIdentity && !(await deps.provisionerIdentity())) return false;
1019
- if (!(await runtimeIdentities())) return false;
1020
999
  if (!(await stackInvariants())) return false;
1021
1000
  if (!(await stagingDatabase())) return false;
1022
1001
  if (!(await publicRoleIsolation())) return false;
@@ -1024,9 +1003,8 @@ export function startConverge(
1024
1003
  await mcpAccess();
1025
1004
  await urlMapRedirectsAccess();
1026
1005
  await auditJob();
1027
- await auditRunnerJob();
1028
- await importCrawlJob();
1029
- await buildCarrierJob();
1006
+ await collectionStores();
1007
+ await reportingJobs();
1030
1008
  await captureJob();
1031
1009
  await remoteMcpEdge();
1032
1010
  await gatewayArmor();
@@ -338,12 +338,15 @@ const ANY_WRITE =
338
338
  /\b(create|update|update-traffic|delete|add-iam-policy-binding|remove-iam-policy-binding|set-iam-policy|execute|enable|add|restore)\b/;
339
339
 
340
340
  /**
341
- * #1328 — the only writes allowed before the backup: the MCP-Auth-Proxy's
342
- * account, its secretAccessor on its two secrets, and the services an older
343
- * install lacks (mcp-auth-proxy-setup.ts). Additive; nothing serves on them.
341
+ * #1328 — the only writes allowed before the backup: the gateway's account
342
+ * and the CLI-generated secrets an older install lacks (#1682), the
343
+ * MCP-Auth-Proxy's account, its secretAccessor on its two secrets, and the
344
+ * services an older install lacks (mcp-auth-proxy-setup.ts), with (#1654)
345
+ * the staging gateway's read of its own visitor-AI key. Additive; nothing
346
+ * serves on them.
344
347
  */
345
348
  const PRE_PLAN_WRITE =
346
- /^(iam service-accounts create caelo-production-(mcp-proxy-sa|stg-gw-sa) |secrets add-iam-policy-binding caelo-production-(mcp-oauth-seal-key|operator-oauth-client) .*--member=serviceAccount:caelo-production-mcp-proxy-sa@|secrets add-iam-policy-binding caelo-production-public-staging-role-password .*--member=serviceAccount:caelo-production-stg-gw-sa@|storage buckets (create|add-iam-policy-binding) gs:\/\/acme-caelo-production-staging |run services replace |run deploy caelo-production-(mcp-auth-proxy|staging-gateway) |run services add-iam-policy-binding caelo-production-staging-gateway .*--member=allUsers )/;
349
+ /^(iam service-accounts create caelo-production-(gateway-sa|mcp-proxy-sa|stg-gw-sa) |secrets (create|versions add) caelo-production-\S+ |secrets add-iam-policy-binding caelo-production-(mcp-oauth-seal-key|operator-oauth-client) .*--member=serviceAccount:caelo-production-mcp-proxy-sa@|secrets add-iam-policy-binding caelo-production-(public-staging-role-password|visitor-ai-staging-key) .*--member=serviceAccount:caelo-production-stg-gw-sa@|storage buckets (create|add-iam-policy-binding) gs:\/\/acme-caelo-production-staging |run services replace |run deploy caelo-production-(mcp-auth-proxy|staging-gateway) |run services add-iam-policy-binding caelo-production-staging-gateway .*--member=allUsers )/;
347
350
 
348
351
  const indexOf = (events: string[], pattern: RegExp): number => {
349
352
  const i = events.findIndex((e) => pattern.test(e));
@@ -351,6 +354,38 @@ const indexOf = (events: string[], pattern: RegExp): number => {
351
354
  return i;
352
355
  };
353
356
 
357
+ /**
358
+ * #1682 — Secret Manager as on an install that predates the secrets `names`:
359
+ * each is missing until `secrets create` makes it, and a grant on a missing
360
+ * one answers 404, as gcloud does.
361
+ */
362
+ function secretsMissing(names: readonly string[]): [RegExp, Answer][] {
363
+ const ids = names.map((n) => `caelo-production-${n}`).join("|");
364
+ const created = new Set<string>();
365
+ const secretOf = (line: string) => line.split(" ")[line.startsWith("secrets versions") ? 3 : 2];
366
+ const known = (line: string, answer: GcloudResult): GcloudResult =>
367
+ created.has(secretOf(line) as string)
368
+ ? answer
369
+ : fail(
370
+ `ERROR: (gcloud.secrets) Status code: 404. Secret [projects/42/secrets/${secretOf(line)}] not found.`,
371
+ );
372
+ return [
373
+ [
374
+ new RegExp(`^secrets create (${ids}) `),
375
+ (l) => {
376
+ created.add(secretOf(l) as string);
377
+ return ok("");
378
+ },
379
+ ],
380
+ [new RegExp(`^secrets describe (${ids}) `), (l) => known(l, ok("name\n"))],
381
+ [
382
+ new RegExp(`^secrets versions list (${ids}) `),
383
+ (l) => known(l, ok(`projects/42/secrets/${secretOf(l)}/versions/1\n`)),
384
+ ],
385
+ [new RegExp(`^secrets add-iam-policy-binding (${ids}) `), (l) => known(l, ok("{}"))],
386
+ ];
387
+ }
388
+
354
389
  describe("upgradeGcpInstall — converge, then app-roll", () => {
355
390
  it("takes the backup first, migrates before rolling, checks health, records the digests", async () => {
356
391
  const events: string[] = [];
@@ -368,8 +403,7 @@ describe("upgradeGcpInstall — converge, then app-roll", () => {
368
403
  const deep = indexOf(events, /^health deep 0\.11\.0/);
369
404
  const digests = indexOf(events, /^record digests/);
370
405
 
371
- // Before the backup only the additive pre-plan step writes (#1328): the
372
- // MCP-Auth-Proxy's account and its two secret grants.
406
+ // Before the backup only the additive pre-plan step writes (#1328, #1682).
373
407
  for (const e of events.slice(0, backup)) expect(e).not.toMatch(/^(migrate|record)/);
374
408
  for (const e of events.slice(0, backup).filter((e) => e.startsWith("gcloud "))) {
375
409
  const call = e.slice("gcloud ".length);
@@ -388,6 +422,31 @@ describe("upgradeGcpInstall — converge, then app-roll", () => {
388
422
  expect(lines).toContain(`done: Pre-upgrade backup ${BACKUP_ID} of ${SQL} taken`);
389
423
  });
390
424
 
425
+ it("an install without the secrets a release adds gets them before anything is granted on them (#1682)", async () => {
426
+ // caelo-cms.com updating 0.12.6 → 0.12.11: the staging gateway's grant
427
+ // on its visitor-AI key ran in the pre-flight, the key was created after
428
+ // the backup, and every update stopped on a 404.
429
+ const added = ["visitor-ai-key", "visitor-ai-staging-key"];
430
+ for (const target of [TARGET, GCP_TARGET]) {
431
+ const events: string[] = [];
432
+ const { deps } = upgradeDeps(events, { overrides: secretsMissing(added) });
433
+ expect(await upgradeGcpInstall(target, deps)).toBe(true);
434
+ const backup = indexOf(events, /^gcloud sql backups create/);
435
+ for (const name of added) {
436
+ const created = indexOf(
437
+ events,
438
+ new RegExp(`^gcloud secrets create caelo-production-${name} `),
439
+ );
440
+ const granted = indexOf(
441
+ events,
442
+ new RegExp(`^gcloud secrets add-iam-policy-binding caelo-production-${name} `),
443
+ );
444
+ expect(created).toBeLessThan(granted);
445
+ expect(created).toBeLessThan(backup);
446
+ }
447
+ }
448
+ });
449
+
391
450
  it("sets up the upgrader job after migrations, before operator access keeps its caelo-mcp grant (#696)", async () => {
392
451
  const events: string[] = [];
393
452
  const { deps, lines } = upgradeDeps(events);
@@ -595,6 +654,100 @@ describe("upgradeGcpInstall — converge, then app-roll", () => {
595
654
  ).toBe(false);
596
655
  });
597
656
 
657
+ it("epic #1644 — creates the collection stores, then the index job that writes the staging one, keeps it on IAP, tells the admin and both gateways", async () => {
658
+ const events: string[] = [];
659
+ const { deps, lines } = upgradeDeps(events, {
660
+ overrides: [
661
+ [/^storage buckets describe gs:\/\/acme-caelo-production-coll-/, fail("NOT_FOUND: 404")],
662
+ ],
663
+ });
664
+ expect(await upgradeGcpInstall(TARGET, deps)).toBe(true);
665
+ const index = "caelo-production-index@acme.iam.gserviceaccount.com";
666
+ const created = indexOf(
667
+ events,
668
+ /^gcloud storage buckets create gs:\/\/acme-caelo-production-coll-staging /,
669
+ );
670
+ const exclusion = indexOf(
671
+ events,
672
+ /^gcloud logging sinks update _Default .*--add-exclusion=\^;\^name=caelo-production-visitor-queries;/,
673
+ );
674
+ const write = indexOf(
675
+ events,
676
+ new RegExp(
677
+ `^gcloud storage buckets add-iam-policy-binding gs://acme-caelo-production-coll-staging --member=serviceAccount:${index} --role=roles/storage\\.objectCreator`,
678
+ ),
679
+ );
680
+ const deploy = indexOf(events, /^gcloud run jobs deploy caelo-production-index /);
681
+ const opAccess = indexOf(
682
+ events,
683
+ /^gcloud run jobs deploy caelo-production-operator-access-sync /,
684
+ );
685
+ const adminRoll = indexOf(events, new RegExp(`^gcloud run services update ${ADMIN} `));
686
+ const gatewayRoll = indexOf(events, new RegExp(`^gcloud run services update ${GATEWAY} `));
687
+ const move = indexOf(events, /^gcloud run jobs update caelo-production-index /);
688
+ expect(created < exclusion && exclusion < write && write < deploy).toBe(true);
689
+ expect(deploy < opAccess && opAccess < adminRoll && adminRoll < move).toBe(true);
690
+ expect(events[opAccess]).toContain(index);
691
+ expect(events[adminRoll]).toContain(
692
+ "CAELO_COLLECTION_INDEX_JOB=projects/acme/locations/europe-west1/jobs/caelo-production-index",
693
+ );
694
+ expect(events[adminRoll]).toContain(
695
+ "CAELO_COLLECTIONS_STAGING_STORE=gs://acme-caelo-production-coll-staging",
696
+ );
697
+ expect(events[adminRoll]).toContain(
698
+ "CAELO_COLLECTIONS_LIVE_STORE=gs://acme-caelo-production-coll-live",
699
+ );
700
+ // The live gateway learns the live store and nothing of staging.
701
+ expect(events[gatewayRoll]).toContain(
702
+ "CAELO_COLLECTIONS_LIVE_STORE=gs://acme-caelo-production-coll-live",
703
+ );
704
+ expect(events[gatewayRoll]).not.toContain("coll-staging");
705
+ // #1646 — and the plugin batch job, which holds the shared line only.
706
+ const batch = "caelo-production-plugin-batch@acme.iam.gserviceaccount.com";
707
+ expect(
708
+ indexOf(events, /^gcloud run jobs deploy caelo-production-plugin-batch /),
709
+ ).toBeGreaterThan(-1);
710
+ expect(
711
+ events.some(
712
+ (e) =>
713
+ e.includes(`--member=serviceAccount:${batch}`) &&
714
+ /(run jobs|storage buckets) add-iam-policy-binding/.test(e),
715
+ ),
716
+ ).toBe(false);
717
+ expect(events[opAccess]).toContain(batch);
718
+ expect(events[adminRoll]).toContain(`CAELO_PLUGIN_BATCH_SERVICE_ACCOUNT=${batch}`);
719
+ expect(lines).toContain(
720
+ "done: Collection stores ready (each gateway reads only its own index)",
721
+ );
722
+ expect(lines).toContain(
723
+ "done: Collection index job ready (a Stage's plugin indexes build in their own job)",
724
+ );
725
+ });
726
+
727
+ it("epic #1644 — failed collection stores skip the index job and leave every collection env untouched", async () => {
728
+ const events: string[] = [];
729
+ const { deps, recorded, lines } = upgradeDeps(events, {
730
+ overrides: [
731
+ [/^storage buckets describe gs:\/\/acme-caelo-production-coll-/, fail("NOT_FOUND: 404")],
732
+ [
733
+ /^storage buckets create gs:\/\/acme-caelo-production-coll-staging/,
734
+ fail("PERMISSION_DENIED"),
735
+ ],
736
+ ],
737
+ });
738
+ expect(await upgradeGcpInstall(TARGET, deps)).toBe(true);
739
+ expect(recorded.contract).toEqual([]);
740
+ expect(lines.some((l) => l.includes("Collection stores not set up"))).toBe(true);
741
+ expect(events.some((e) => e.startsWith("gcloud run jobs deploy caelo-production-index "))).toBe(
742
+ false,
743
+ );
744
+ expect(events.some((e) => /services update .*CAELO_COLLECTION/.test(e))).toBe(false);
745
+ // The other reporting jobs are untouched by it.
746
+ expect(
747
+ events.some((e) => e.startsWith("gcloud run jobs deploy caelo-production-plugin-batch ")),
748
+ ).toBe(true);
749
+ });
750
+
598
751
  it("sets up the capture job on the CURRENT admin image before the roll, then moves it with the admin (#1217)", async () => {
599
752
  const events: string[] = [];
600
753
  const { deps, lines } = upgradeDeps(events);
@@ -5,13 +5,15 @@
5
5
  * app-roll (epic #696). The order, and why:
6
6
  *
7
7
  * 1. plan: release digests, the services, the env contract — read-only
8
- * but for the services an older install lacks (#1328, additive and
9
- * serving nothing yet: mcp-auth-proxy-setup.ts)
8
+ * but for what an older install lacks, all additive and serving
9
+ * nothing yet: the gateway's account and the CLI-generated secrets
10
+ * first (#1682, runtime-secrets.ts), then the services (#1328,
11
+ * mcp-auth-proxy-setup.ts), which are granted those secrets
10
12
  * 2. verify the images' signatures
11
13
  * 3. pre-upgrade Cloud SQL backup — the first change; if it fails, the
12
14
  * install is exactly as it was
13
- * 4. converge, the part before the roll (keyless provisioner, IAM, secrets,
14
- * MCP access)
15
+ * 4. converge, the part before the roll (keyless provisioner, IAM, MCP
16
+ * access)
15
17
  * 5. app-roll: health baseline, migrations, the converge steps that must
16
18
  * follow migrations, admin, gateway and MCP-Auth-Proxy rolls, deep
17
19
  * health check, rollback
@@ -33,10 +35,12 @@
33
35
  import type { GcloudRunner, Sleep } from "../gcloud-retry.js";
34
36
  import type { ImageDigests } from "../install-state.js";
35
37
  import { ensureReleaseServices } from "../mcp-auth-proxy-setup.js";
36
- import type { HttpFetch } from "../runtime-secrets.js";
38
+ import { ensureRuntimeIdentities, type HttpFetch } from "../runtime-secrets.js";
37
39
  import { SERVICE_IMAGE } from "../stack-contract.js";
40
+ import { liveContainerEnv } from "../stack-converge.js";
38
41
  import {
39
42
  type AppRollPlan,
43
+ describeLiveService,
40
44
  executeAppRoll,
41
45
  planAppRoll,
42
46
  type ReleaseImage,
@@ -213,19 +217,42 @@ export async function upgradeGcpInstallOutcome(
213
217
  sPre.failed("The gateway image's signature did not verify");
214
218
  return failed;
215
219
  }
216
- const ensured = await ensureReleaseServices(
217
- {
218
- provider: target.provider,
219
- projectId,
220
- region: target.region,
221
- env: target.env,
222
- domain: target.domain,
223
- stagingHost: target.stagingHost,
224
- mcpAuthProxyImageRef: proxyImage.imageRef,
225
- gatewayImageRef: gatewayImage.imageRef,
226
- },
227
- { run },
228
- );
220
+ // #1682 — the gateway's account and every CLI-generated secret first:
221
+ // the services set up next are granted the secrets they read, a secret
222
+ // this release adds included (#1654's visitor-AI keys). A secret the
223
+ // admin still runs as a plain env var keeps that value.
224
+ const install = {
225
+ provider: target.provider,
226
+ projectId,
227
+ region: target.region,
228
+ env: target.env,
229
+ domain: target.domain,
230
+ stagingHost: target.stagingHost,
231
+ credentials: target.credentials,
232
+ };
233
+ const admin = await describeLiveService(install, "admin", run);
234
+ if (!admin.ok) {
235
+ sPre.failed("Pre-flight failed");
236
+ r.error(admin.error);
237
+ return failed;
238
+ }
239
+ const identities = await ensureRuntimeIdentities(install, liveContainerEnv(admin.json), {
240
+ run,
241
+ ...(deps.sleep ? { sleep: deps.sleep } : {}),
242
+ });
243
+ const ensured = identities.some((o) => o.status === "failed")
244
+ ? identities
245
+ : [
246
+ ...identities,
247
+ ...(await ensureReleaseServices(
248
+ {
249
+ ...install,
250
+ mcpAuthProxyImageRef: proxyImage.imageRef,
251
+ gatewayImageRef: gatewayImage.imageRef,
252
+ },
253
+ { run, ...(deps.sleep ? { sleep: deps.sleep } : {}) },
254
+ )),
255
+ ];
229
256
  const ensureFailed = ensured.filter((o) => o.status === "failed");
230
257
  if (ensureFailed.length > 0) {
231
258
  sPre.failed("The services this release runs could not be set up. Nothing was changed.");
@@ -235,20 +262,7 @@ export async function upgradeGcpInstallOutcome(
235
262
  for (const o of ensured.filter((o) => o.status === "applied")) {
236
263
  r.info(` created: ${o.id}${o.detail ? ` (${o.detail})` : ""}`);
237
264
  }
238
- const planned = await planAppRoll(
239
- {
240
- provider: target.provider,
241
- projectId,
242
- region: target.region,
243
- env: target.env,
244
- domain: target.domain,
245
- stagingHost: target.stagingHost,
246
- credentials: target.credentials,
247
- },
248
- images.images,
249
- run,
250
- { secretVolumes: true },
251
- );
265
+ const planned = await planAppRoll(install, images.images, run, { secretVolumes: true });
252
266
  if (!planned.ok) {
253
267
  sPre.failed("Pre-flight failed");
254
268
  r.error(planned.error);