@caelo-cms/provisioning 0.11.19 → 0.11.21

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 (174) hide show
  1. package/dist/admin-internal-google.d.ts +13 -1
  2. package/dist/admin-internal-google.d.ts.map +1 -1
  3. package/dist/admin-internal-google.js +47 -0
  4. package/dist/admin-internal-google.js.map +1 -1
  5. package/dist/agent/command.d.ts +1 -1
  6. package/dist/agent-db.js +32 -0
  7. package/dist/aws-task-roles.d.ts +11 -0
  8. package/dist/aws-task-roles.d.ts.map +1 -1
  9. package/dist/aws-task-roles.js +19 -0
  10. package/dist/aws-task-roles.js.map +1 -1
  11. package/dist/azure-secrets.d.ts +22 -0
  12. package/dist/azure-secrets.d.ts.map +1 -0
  13. package/dist/azure-secrets.js +14 -0
  14. package/dist/azure-secrets.js.map +1 -0
  15. package/dist/caddy.d.ts +7 -0
  16. package/dist/caddy.d.ts.map +1 -1
  17. package/dist/caddy.js +22 -1
  18. package/dist/caddy.js.map +1 -1
  19. package/dist/cli-routing.d.ts.map +1 -1
  20. package/dist/cli-routing.js +2 -2
  21. package/dist/cli-routing.js.map +1 -1
  22. package/dist/cli.js +8 -0
  23. package/dist/cli.js.map +1 -1
  24. package/dist/converge-checkpoint.d.ts +6 -0
  25. package/dist/converge-checkpoint.d.ts.map +1 -1
  26. package/dist/dns/manual.d.ts +5 -1
  27. package/dist/dns/manual.d.ts.map +1 -1
  28. package/dist/dns/manual.js +2 -1
  29. package/dist/dns/manual.js.map +1 -1
  30. package/dist/gateway-armor.d.ts +24 -0
  31. package/dist/gateway-armor.d.ts.map +1 -0
  32. package/dist/gateway-armor.js +118 -0
  33. package/dist/gateway-armor.js.map +1 -0
  34. package/dist/gateway-edge.d.ts +128 -0
  35. package/dist/gateway-edge.d.ts.map +1 -0
  36. package/dist/gateway-edge.js +211 -0
  37. package/dist/gateway-edge.js.map +1 -0
  38. package/dist/infra-contract.d.ts +1 -1
  39. package/dist/infra-contract.d.ts.map +1 -1
  40. package/dist/infra-contract.js +21 -1
  41. package/dist/infra-contract.js.map +1 -1
  42. package/dist/install-job-runner.d.ts.map +1 -1
  43. package/dist/install-job-runner.js +4 -3
  44. package/dist/install-job-runner.js.map +1 -1
  45. package/dist/install-job.d.ts +25 -1
  46. package/dist/install-job.d.ts.map +1 -1
  47. package/dist/install-job.js +72 -3
  48. package/dist/install-job.js.map +1 -1
  49. package/dist/lifecycle.d.ts.map +1 -1
  50. package/dist/lifecycle.js +8 -1
  51. package/dist/lifecycle.js.map +1 -1
  52. package/dist/operator-access.d.ts +7 -2
  53. package/dist/operator-access.d.ts.map +1 -1
  54. package/dist/operator-access.js +37 -6
  55. package/dist/operator-access.js.map +1 -1
  56. package/dist/pool-budget-stack.d.ts +22 -0
  57. package/dist/pool-budget-stack.d.ts.map +1 -1
  58. package/dist/pool-budget-stack.js +22 -1
  59. package/dist/pool-budget-stack.js.map +1 -1
  60. package/dist/project-status.d.ts +95 -0
  61. package/dist/project-status.d.ts.map +1 -0
  62. package/dist/project-status.js +213 -0
  63. package/dist/project-status.js.map +1 -0
  64. package/dist/public-service-shape.d.ts +45 -0
  65. package/dist/public-service-shape.d.ts.map +1 -0
  66. package/dist/public-service-shape.js +90 -0
  67. package/dist/public-service-shape.js.map +1 -0
  68. package/dist/remote-mcp-edge.d.ts +1 -1
  69. package/dist/remote-mcp-edge.js +1 -1
  70. package/dist/remote-mcp.d.ts.map +1 -1
  71. package/dist/remote-mcp.js +12 -2
  72. package/dist/remote-mcp.js.map +1 -1
  73. package/dist/serverless-backend.d.ts +27 -0
  74. package/dist/serverless-backend.d.ts.map +1 -0
  75. package/dist/serverless-backend.js +30 -0
  76. package/dist/serverless-backend.js.map +1 -0
  77. package/dist/stack-contract.d.ts +6 -0
  78. package/dist/stack-contract.d.ts.map +1 -1
  79. package/dist/stack-contract.js +24 -0
  80. package/dist/stack-contract.js.map +1 -1
  81. package/dist/stack-converge.d.ts +13 -0
  82. package/dist/stack-converge.d.ts.map +1 -1
  83. package/dist/stack-converge.js +27 -0
  84. package/dist/stack-converge.js.map +1 -1
  85. package/dist/staging-gateway-setup.d.ts +5 -0
  86. package/dist/staging-gateway-setup.d.ts.map +1 -1
  87. package/dist/staging-gateway-setup.js +60 -19
  88. package/dist/staging-gateway-setup.js.map +1 -1
  89. package/dist/state-attach.d.ts +17 -0
  90. package/dist/state-attach.d.ts.map +1 -1
  91. package/dist/state-attach.js +27 -9
  92. package/dist/state-attach.js.map +1 -1
  93. package/dist/upgrade/app-roll.d.ts +5 -1
  94. package/dist/upgrade/app-roll.d.ts.map +1 -1
  95. package/dist/upgrade/app-roll.js +20 -3
  96. package/dist/upgrade/app-roll.js.map +1 -1
  97. package/dist/upgrade/converge.d.ts.map +1 -1
  98. package/dist/upgrade/converge.js +27 -4
  99. package/dist/upgrade/converge.js.map +1 -1
  100. package/dist/upgrade/health.d.ts +13 -3
  101. package/dist/upgrade/health.d.ts.map +1 -1
  102. package/dist/upgrade/health.js +24 -7
  103. package/dist/upgrade/health.js.map +1 -1
  104. package/dist/upgrade/load-balancer-get.d.ts +17 -0
  105. package/dist/upgrade/load-balancer-get.d.ts.map +1 -0
  106. package/dist/upgrade/load-balancer-get.js +38 -0
  107. package/dist/upgrade/load-balancer-get.js.map +1 -0
  108. package/dist/upgrader-gcp.d.ts.map +1 -1
  109. package/dist/upgrader-gcp.js +8 -1
  110. package/dist/upgrader-gcp.js.map +1 -1
  111. package/dist/wizards/gcp-cost.d.ts +9 -0
  112. package/dist/wizards/gcp-cost.d.ts.map +1 -1
  113. package/dist/wizards/gcp-cost.js +69 -34
  114. package/dist/wizards/gcp-cost.js.map +1 -1
  115. package/dist/wizards/gcp-install-job.d.ts +27 -4
  116. package/dist/wizards/gcp-install-job.d.ts.map +1 -1
  117. package/dist/wizards/gcp-install-job.js +62 -32
  118. package/dist/wizards/gcp-install-job.js.map +1 -1
  119. package/dist/wizards/gcp.d.ts +3 -0
  120. package/dist/wizards/gcp.d.ts.map +1 -1
  121. package/dist/wizards/gcp.js +10 -4
  122. package/dist/wizards/gcp.js.map +1 -1
  123. package/package.json +2 -2
  124. package/src/admin-internal-google.ts +48 -0
  125. package/src/aws-task-roles.ts +22 -0
  126. package/src/azure-secrets.ts +38 -0
  127. package/src/caddy.test.ts +19 -2
  128. package/src/caddy.ts +23 -0
  129. package/src/cli-routing.ts +3 -2
  130. package/src/cli.ts +10 -0
  131. package/src/dns/manual.ts +4 -1
  132. package/src/gateway-armor.ts +135 -0
  133. package/src/gateway-bootstrap.test.ts +1 -0
  134. package/src/gateway-edge.test.ts +262 -0
  135. package/src/gateway-edge.ts +256 -0
  136. package/src/gateway-env-isolation.test.ts +45 -6
  137. package/src/infra-contract.test.ts +5 -3
  138. package/src/infra-contract.ts +21 -1
  139. package/src/install-job-runner.ts +4 -2
  140. package/src/install-job.ts +86 -4
  141. package/src/lifecycle.ts +8 -1
  142. package/src/operator-access.test.ts +43 -0
  143. package/src/operator-access.ts +38 -6
  144. package/src/pool-budget-stack.ts +25 -0
  145. package/src/pool-budget-stacks.test.ts +31 -0
  146. package/src/project-status.test.ts +462 -0
  147. package/src/project-status.ts +306 -0
  148. package/src/public-service-shape.test.ts +166 -0
  149. package/src/public-service-shape.ts +131 -0
  150. package/src/remote-mcp-edge.ts +1 -1
  151. package/src/remote-mcp.test.ts +38 -1
  152. package/src/remote-mcp.ts +25 -3
  153. package/src/serverless-backend.ts +47 -0
  154. package/src/stack-contract.test.ts +13 -0
  155. package/src/stack-contract.ts +25 -0
  156. package/src/stack-converge.test.ts +28 -1
  157. package/src/stack-converge.ts +30 -0
  158. package/src/staging-gateway-setup.test.ts +55 -3
  159. package/src/staging-gateway-setup.ts +79 -27
  160. package/src/state-attach.ts +46 -16
  161. package/src/upgrade/app-roll.ts +27 -3
  162. package/src/upgrade/converge.ts +33 -4
  163. package/src/upgrade/health.test.ts +88 -13
  164. package/src/upgrade/health.ts +32 -7
  165. package/src/upgrade/load-balancer-get.ts +64 -0
  166. package/src/upgrade/upgrade.test.ts +96 -3
  167. package/src/upgrader-gcp.ts +8 -1
  168. package/src/wizards/gcp-cost.ts +78 -35
  169. package/src/wizards/gcp-install-job.ts +91 -46
  170. package/src/wizards/gcp.ts +14 -7
  171. package/stacks/aws/index.ts +24 -22
  172. package/stacks/azure/index.ts +152 -64
  173. package/stacks/gcp/index.ts +35 -47
  174. package/stacks/gcp-firebase/index.ts +25 -13
@@ -32,6 +32,7 @@ import {
32
32
  stagingGatewayServiceAccountEmail,
33
33
  } from "../gcp-names.js";
34
34
  import type { ImageDigests } from "../install-state.js";
35
+ import { GATEWAY_MAX_INSTANCES_CEILING, GATEWAY_POOL_ENV } from "../pool-budget-stack.js";
35
36
  import {
36
37
  adminMediaVolume,
37
38
  CLOUD_RUN_SLUGS,
@@ -54,11 +55,13 @@ import {
54
55
  liveContainerMemory,
55
56
  liveCpuIdle,
56
57
  liveDirectVpc,
58
+ liveMaxInstances,
57
59
  liveTimeoutSeconds,
58
60
  liveVolumes,
59
61
  planAdminMemory,
60
62
  planContractEnv,
61
63
  planCpuIdle,
64
+ planMaxInstances,
62
65
  planMediaVolume,
63
66
  planNoVpc,
64
67
  planRequestTimeout,
@@ -142,6 +145,8 @@ export interface ServicePlan {
142
145
  readonly liveCpuIdle: boolean;
143
146
  /** Whether the service egresses into the install's VPC now. */
144
147
  readonly liveDirectVpc: boolean;
148
+ /** Most instances the service may start now (null = Cloud Run's default). */
149
+ readonly liveMaxInstances: number | null;
145
150
  }
146
151
 
147
152
  /** A service plan plus the changes its roll applies. */
@@ -151,7 +156,9 @@ export interface RollPlan extends ServicePlan {
151
156
  /**
152
157
  * #553 — e.g. `--memory=2Gi` when the admin runs below the stack default;
153
158
  * #806 — `--timeout=3600` when the gateway runs below its contract timeout;
154
- * `--cpu-throttling` when the contract wants request-based CPU.
159
+ * `--cpu-throttling` when the contract wants request-based CPU;
160
+ * #1463 — `--max-instances=10` when a gateway may start more instances than
161
+ * the connection budget has room for.
155
162
  */
156
163
  readonly resourceFlags: readonly string[];
157
164
  readonly resourceChanges: readonly string[];
@@ -250,6 +257,7 @@ export async function planAppRoll(
250
257
  liveTimeout: liveTimeoutSeconds(json),
251
258
  liveCpuIdle: liveCpuIdle(json),
252
259
  liveDirectVpc: liveDirectVpc(json),
260
+ liveMaxInstances: liveMaxInstances(json),
253
261
  });
254
262
  }
255
263
  const env = planEnv(install, services, {});
@@ -320,16 +328,24 @@ export async function planAppRoll(
320
328
  // leaves the VPC in the same revision that drops its database env.
321
329
  const vpc = SERVICE_VPC_EGRESS[s.slug] ? null : planNoVpc(s.liveDirectVpc);
322
330
  const vpcFlags = vpc?.ok ? vpc.flags : [];
331
+ // #1463 — every gateway instance holds three of its login's connections,
332
+ // so the scale-out rides the roll with the pool env (planEnv below).
333
+ const scale =
334
+ s.slug === "gateway" || s.slug === "staging-gateway"
335
+ ? planMaxInstances(s.liveMaxInstances, GATEWAY_MAX_INSTANCES_CEILING[s.slug])
336
+ : null;
337
+ const scaleFlags = scale?.ok ? scale.flags : [];
323
338
  return {
324
339
  ...s,
325
340
  envFlags: env.services[s.slug].flags,
326
341
  envChanges: env.services[s.slug].changes,
327
- resourceFlags: [...memoryFlags, ...timeoutFlags, ...cpuFlags, ...vpcFlags],
342
+ resourceFlags: [...memoryFlags, ...timeoutFlags, ...cpuFlags, ...vpcFlags, ...scaleFlags],
328
343
  resourceChanges: [
329
344
  ...memoryFlags.map((f) => `${s.liveMemory ?? "(default)"} → ${f}`),
330
345
  ...(timeout?.ok ? timeout.changes : []),
331
346
  ...(cpu.ok ? cpu.changes : []),
332
347
  ...(vpc?.ok ? vpc.changes : []),
348
+ ...(scale?.ok ? scale.changes : []),
333
349
  ],
334
350
  volumeFlags: [...(s.slug === "admin" ? media.flags : []), ...secretFiles[s.slug].flags],
335
351
  volumeChanges: [...(s.slug === "admin" ? media.changes : []), ...secretFiles[s.slug].changes],
@@ -370,6 +386,14 @@ function planEnv(
370
386
  const deployed = Object.fromEntries(
371
387
  services.map((s) => [s.slug, { serviceName: s.serviceName, liveEnv: s.liveEnv }]),
372
388
  ) as Record<RollSlug, DeployedService>;
389
+ // #1463 — the gateways' pool env is the stacks', outside the contract: it
390
+ // used to reach an install only through `pulumi up`, so an install from
391
+ // before the budget never got it.
392
+ const extraEnv = {
393
+ ...adjust.extraEnv,
394
+ gateway: [...(adjust.extraEnv?.gateway ?? []), ...GATEWAY_POOL_ENV],
395
+ "staging-gateway": [...(adjust.extraEnv?.["staging-gateway"] ?? []), ...GATEWAY_POOL_ENV],
396
+ };
373
397
  return planContractEnv(
374
398
  {
375
399
  provider: install.provider,
@@ -382,7 +406,7 @@ function planEnv(
382
406
  deployed,
383
407
  {
384
408
  leaveUntouched: adjust.leaveUntouched ?? [],
385
- ...(adjust.extraEnv ? { extraEnv: adjust.extraEnv } : {}),
409
+ extraEnv,
386
410
  ...(adjust.databaseHost ? { databaseHost: adjust.databaseHost } : {}),
387
411
  },
388
412
  );
@@ -38,6 +38,7 @@ import {
38
38
  moveServicesToDnsHost,
39
39
  } from "../cloudsql-tls.js";
40
40
  import { ensureConvergeJob } from "../converge-job-setup.js";
41
+ import { ensureGatewayArmorRules } from "../gateway-armor.js";
41
42
  import { findSqlInstance, planPublicRoleSwitch } from "../gateway-credentials.js";
42
43
  import type { GcloudRunner, Sleep } from "../gcloud-retry.js";
43
44
  import { schedulerServiceAccountEmail, upgraderServiceAccountEmail } from "../gcp-names.js";
@@ -451,13 +452,35 @@ export function startConverge(
451
452
  incomplete = true;
452
453
  }
453
454
 
455
+ async function gatewayArmor(): Promise<void> {
456
+ // #1339 — on `gcp` the gateway's Cloud Armor policy gets its per-path
457
+ // rules (gateway-edge.ts). An extra layer over the gateway's own limits
458
+ // (E3 of #763), so a failure warns; the old rules stay in force.
459
+ if (install.provider !== "gcp") return;
460
+ const s = r.step("Bringing the gateway's Cloud Armor rules up to date...");
461
+ const armor = await ensureGatewayArmorRules(
462
+ { projectId: install.projectId, env: install.env },
463
+ runDeps,
464
+ );
465
+ for (const line of armor.done) r.info(` ${line}`);
466
+ if (armor.ok) {
467
+ s.done(`Cloud Armor rules of ${armor.policy} in place`);
468
+ return;
469
+ }
470
+ s.warned(`Cloud Armor rules not updated: ${armor.error}`);
471
+ r.warn(
472
+ "The upgrade continues; the gateway keeps its own rate limits, and the edge keeps the old catch-all ban until every new rule is in (each rule is replaced in place, never removed first). Re-run upgrade once the cause is fixed.",
473
+ );
474
+ incomplete = true;
475
+ }
476
+
454
477
  async function stagingEdge(): Promise<void> {
455
478
  // #1330 — route the staging host to the staging gateway and nowhere
456
479
  // else: gcp-firebase's second Hosting site (and the old Cloud Run domain
457
- // mapping deleted), gcp's host rule, backend and certificate
458
- // (staging-gateway-setup.ts). Only staging depends on it, so a failure
459
- // warns; the records the staging host needs are printed (Settings →
460
- // Updates shows them too).
480
+ // mapping deleted once the DNS moved, #1455), gcp's host rule, backend
481
+ // and certificate (staging-gateway-setup.ts). Only staging depends on
482
+ // it, so a failure warns; the records the staging host needs are printed
483
+ // (Settings → Updates shows them too, verify_dns_records checks them).
461
484
  const s = r.step(`Routing the staging host ${install.stagingHost} to the staging gateway...`);
462
485
  const edge = await ensureStagingGatewayEdge(
463
486
  {
@@ -479,6 +502,11 @@ export function startConverge(
479
502
  );
480
503
  for (const d of edge.dnsRecords) r.info(` ${d.name} ${d.type} ${d.value}`);
481
504
  }
505
+ if (edge.domainMappingKept) {
506
+ r.warn(
507
+ `${install.stagingHost} still points at its old Cloud Run route, so this update keeps that route and the address keeps its certificate. Once the services have rolled it answers 404 until the records above are set; then the staging site is back. The next update that changes the cloud setup removes the old route.`,
508
+ );
509
+ }
482
510
  return;
483
511
  }
484
512
  s.warned(`The staging host is not routed yet: ${edge.error}`);
@@ -872,6 +900,7 @@ export function startConverge(
872
900
  await auditJob();
873
901
  await captureJob();
874
902
  await remoteMcpEdge();
903
+ await gatewayArmor();
875
904
  await stagingEdge();
876
905
  return true;
877
906
  },
@@ -7,10 +7,12 @@ import {
7
7
  createIapHealthProbe,
8
8
  evaluateAdminDeepHealth,
9
9
  evaluatePublicServiceDeepHealth,
10
+ type HealthProbeDeps,
10
11
  type HealthTarget,
11
12
  healthOrigins,
12
13
  IAM_PROPAGATION_WINDOW_MS,
13
14
  } from "./health.js";
15
+ import type { LoadBalancerGet, LoadBalancerRequest } from "./load-balancer-get.js";
14
16
 
15
17
  const migrations = (adminPending = 0, publicPending = 0) => ({
16
18
  admin: { head: "0262_tool_approval_branch.sql", pending: adminPending },
@@ -109,6 +111,15 @@ const FIREBASE: HealthTarget = {
109
111
  mcpAuthProxyServiceUrl: "https://caelo-production-gateway-bbb-xyz.a.run.app",
110
112
  };
111
113
 
114
+ /** A gcp-firebase probe: its public services need no load balancer path. */
115
+ const firebaseProbe = (deps: Omit<HealthProbeDeps, "loadBalancerGet">) =>
116
+ createIapHealthProbe(FIREBASE, {
117
+ ...deps,
118
+ loadBalancerGet: async () => {
119
+ throw new Error("gcp-firebase never uses the load balancer path");
120
+ },
121
+ });
122
+
112
123
  describe("healthOrigins", () => {
113
124
  it("uses the load balancer hosts on gcp", () => {
114
125
  expect(healthOrigins({ ...FIREBASE, provider: "gcp" })).toEqual({
@@ -161,7 +172,7 @@ describe("createIapHealthProbe", () => {
161
172
  admin: () => [200, adminBody()],
162
173
  gateway: () => [200, JSON.stringify({ ok: true })],
163
174
  });
164
- const probe = createIapHealthProbe(FIREBASE, {
175
+ const probe = firebaseProbe({
165
176
  run: gcloudOk,
166
177
  http: net.http,
167
178
  sleep: async () => {},
@@ -202,7 +213,7 @@ describe("createIapHealthProbe", () => {
202
213
 
203
214
  it("#1328 — fails the deep check while the MCP-Auth-Proxy is unhealthy or does not answer", async () => {
204
215
  const deepWith = (proxy: () => [number, string]) =>
205
- createIapHealthProbe(FIREBASE, {
216
+ firebaseProbe({
206
217
  run: gcloudOk,
207
218
  http: network({
208
219
  admin: () => [200, adminBody()],
@@ -234,7 +245,7 @@ describe("createIapHealthProbe", () => {
234
245
  },
235
246
  gateway: () => [200, JSON.stringify({ ok: true })],
236
247
  });
237
- const probe = createIapHealthProbe(FIREBASE, {
248
+ const probe = firebaseProbe({
238
249
  run: gcloudOk,
239
250
  http: net.http,
240
251
  sleep: async () => {},
@@ -248,7 +259,7 @@ describe("createIapHealthProbe", () => {
248
259
  admin: () => [503, adminBody({ ok: false, migrations: migrations(1) })],
249
260
  gateway: () => [200, "{}"],
250
261
  });
251
- const failing = createIapHealthProbe(FIREBASE, {
262
+ const failing = firebaseProbe({
252
263
  run: gcloudOk,
253
264
  http: stuck.http,
254
265
  sleep: async () => {},
@@ -265,7 +276,7 @@ describe("createIapHealthProbe", () => {
265
276
  admin: () => [200, "<html>Sign in with Google</html>"],
266
277
  gateway: () => [404, "{}"],
267
278
  });
268
- const probe = createIapHealthProbe(FIREBASE, {
279
+ const probe = firebaseProbe({
269
280
  run: gcloudOk,
270
281
  http: net.http,
271
282
  sleep: async () => {},
@@ -282,7 +293,7 @@ describe("createIapHealthProbe", () => {
282
293
  admin: () => [200, JSON.stringify({ ok: true, version: "0.10.43" })],
283
294
  gateway: () => [404, '{"ok":false}'],
284
295
  });
285
- const probe = createIapHealthProbe(FIREBASE, {
296
+ const probe = firebaseProbe({
286
297
  run: gcloudOk,
287
298
  http: net.http,
288
299
  sleep: async () => {},
@@ -299,7 +310,7 @@ describe("createIapHealthProbe", () => {
299
310
  admin: () => [200, JSON.stringify({ ok: true, version: "0.10.20" })],
300
311
  gateway: () => [404, "<!DOCTYPE html><html><title>Error 404 (Not Found)!!1</title>"],
301
312
  });
302
- const probe = createIapHealthProbe(FIREBASE, {
313
+ const probe = firebaseProbe({
303
314
  run: gcloudOk,
304
315
  http: net.http,
305
316
  sleep: async () => {},
@@ -313,13 +324,77 @@ describe("createIapHealthProbe", () => {
313
324
  }
314
325
  const lb = createIapHealthProbe(
315
326
  { ...FIREBASE, provider: "gcp" },
316
- { run: gcloudOk, http: net.http, sleep: async () => {}, accessJustChanged: false },
327
+ {
328
+ run: gcloudOk,
329
+ http: net.http,
330
+ loadBalancerGet: async () => ({ status: 404, text: "<!DOCTYPE html>" }),
331
+ sleep: async () => {},
332
+ accessJustChanged: false,
333
+ },
317
334
  );
318
335
  const viaLb = await lb.baseline();
319
336
  if (!viaLb.ok) expect(viaLb.error).toContain("route /api/* to the gateway backend");
320
337
  expect(viaLb.ok).toBe(false);
321
338
  });
322
339
 
340
+ describe("#1459 — gcp reaches the public services through the load balancer", () => {
341
+ const GCP: HealthTarget = { ...FIREBASE, provider: "gcp" };
342
+ const healthyGcp = (loadBalancerGet: LoadBalancerGet) => {
343
+ const net = network({
344
+ admin: () => [200, adminBody()],
345
+ // Nothing resolves the site's domain before go-live.
346
+ gateway: () => {
347
+ throw new Error("getaddrinfo ENOTFOUND acme.com");
348
+ },
349
+ });
350
+ return createIapHealthProbe(GCP, {
351
+ run: gcloudOk,
352
+ http: net.http,
353
+ loadBalancerGet,
354
+ sleep: async () => {},
355
+ accessJustChanged: false,
356
+ attempts: 1,
357
+ });
358
+ };
359
+
360
+ it("passes with no record on the main domain, connecting through the admin's name", async () => {
361
+ const asked: LoadBalancerRequest[] = [];
362
+ const probe = healthyGcp(async (req) => {
363
+ asked.push(req);
364
+ return { status: 200, text: JSON.stringify({ ok: true }) };
365
+ });
366
+ expect((await probe.baseline()).ok).toBe(true);
367
+ expect((await probe.deep({ version: "0.11.0" })).ok).toBe(true);
368
+ expect(asked).toEqual([
369
+ { connectHost: "admin.acme.com", hostHeader: "acme.com", path: "/api/_caelo/health" },
370
+ {
371
+ connectHost: "admin.acme.com",
372
+ hostHeader: "acme.com",
373
+ path: "/api/_caelo/health?deep=1",
374
+ },
375
+ { connectHost: "admin.acme.com", hostHeader: "acme.com", path: "/api/mcp/health" },
376
+ ]);
377
+ });
378
+
379
+ it("still stops on a gateway that does not answer", async () => {
380
+ const probe = healthyGcp(async () => {
381
+ throw new Error("socket hang up");
382
+ });
383
+ expect(await probe.baseline()).toEqual({
384
+ ok: false,
385
+ error: "gateway unreachable at https://acme.com: socket hang up",
386
+ });
387
+ expect((await probe.deep({ version: "0.11.0" })).ok).toBe(false);
388
+ });
389
+
390
+ it("names the missing invoker when Cloud Run answers its own 403", async () => {
391
+ const probe = healthyGcp(async () => ({ status: 403, text: "<html>403 Forbidden</html>" }));
392
+ const r = await probe.baseline();
393
+ expect(r.ok).toBe(false);
394
+ if (!r.ok) expect(r.error).toContain("roles/run.invoker");
395
+ });
396
+ });
397
+
323
398
  describe("#734 — a refused signJwt right after converge granted it", () => {
324
399
  /** signJwt answers 403 `denials` times, then signs. */
325
400
  function propagating(denials: number) {
@@ -346,7 +421,7 @@ describe("createIapHealthProbe", () => {
346
421
  const net = propagating(4);
347
422
  const slept: number[] = [];
348
423
  const waits: string[] = [];
349
- const probe = createIapHealthProbe(FIREBASE, {
424
+ const probe = firebaseProbe({
350
425
  run: gcloudOk,
351
426
  http: net.http,
352
427
  sleep: async (ms) => {
@@ -367,7 +442,7 @@ describe("createIapHealthProbe", () => {
367
442
  it("gives up after the propagation window: the grant exists, re-run in a few minutes", async () => {
368
443
  const net = propagating(Number.POSITIVE_INFINITY);
369
444
  let slept = 0;
370
- const probe = createIapHealthProbe(FIREBASE, {
445
+ const probe = firebaseProbe({
371
446
  run: gcloudOk,
372
447
  http: net.http,
373
448
  sleep: async (ms) => {
@@ -387,7 +462,7 @@ describe("createIapHealthProbe", () => {
387
462
  it("fails at once when nothing was just granted: the grant is missing", async () => {
388
463
  const net = propagating(Number.POSITIVE_INFINITY);
389
464
  let slept = 0;
390
- const probe = createIapHealthProbe(FIREBASE, {
465
+ const probe = firebaseProbe({
391
466
  run: gcloudOk,
392
467
  http: net.http,
393
468
  sleep: async (ms) => {
@@ -410,7 +485,7 @@ describe("createIapHealthProbe", () => {
410
485
  throw new Error("ENOTFOUND");
411
486
  };
412
487
  let slept = 0;
413
- const probe = createIapHealthProbe(FIREBASE, {
488
+ const probe = firebaseProbe({
414
489
  run: gcloudOk,
415
490
  http,
416
491
  sleep: async (ms) => {
@@ -427,7 +502,7 @@ describe("createIapHealthProbe", () => {
427
502
  const http: HttpFetch = async () => {
428
503
  throw new Error("ECONNRESET");
429
504
  };
430
- const probe = createIapHealthProbe(FIREBASE, {
505
+ const probe = firebaseProbe({
431
506
  run: gcloudOk,
432
507
  http,
433
508
  sleep: async () => {},
@@ -18,6 +18,12 @@
18
18
  * either): it has no database, so it answers once it runs; under
19
19
  * `/api/mcp/`, the prefix the gcp load balancer routes to it.
20
20
  *
21
+ * On `gcp` the public two are asked through the load balancer with the
22
+ * site's Host header on a connection to `admin.<domain>`
23
+ * (load-balancer-get.ts), so an install whose main domain has no record yet
24
+ * (the weeks before go-live, #1459) takes updates like any other. Their
25
+ * `run.app` URLs are no way in: ingress is load-balancer-only.
26
+ *
21
27
  * Both answer with no secrets and no raw database errors. The admin sits
22
28
  * behind IAP, so the probe signs an IAP credential as the install's MCP
23
29
  * service account (`caelo-mcp@`, mcp-iap.ts) exactly like the MCP shim does
@@ -44,6 +50,7 @@
44
50
  import type { GcloudRunner, Sleep } from "../gcloud-retry.js";
45
51
  import { mcpIapServiceAccountEmail } from "../gcp-names.js";
46
52
  import type { HttpFetch } from "../runtime-secrets.js";
53
+ import type { LoadBalancerGet } from "./load-balancer-get.js";
47
54
 
48
55
  export type HealthOutcome =
49
56
  | { readonly ok: true; readonly detail: string }
@@ -186,10 +193,11 @@ export interface HealthTarget {
186
193
  }
187
194
 
188
195
  /**
189
- * The origins the probe calls. On gcp the admin's IAP lives on the load
196
+ * The origins the probe asks. On gcp the admin's IAP lives on the load
190
197
  * balancer (`admin.<domain>`), and the gateway's and the proxy's ingress is
191
- * load-balancer-only (`<domain>/api/*`, `<domain>/api/mcp/*`); on
192
- * gcp-firebase every `run.app` URL is reachable — the admin's through Cloud
198
+ * load-balancer-only (`<domain>/api/*`, `<domain>/api/mcp/*`, connected
199
+ * through the admin's name, see the module comment); on gcp-firebase every
200
+ * `run.app` URL is reachable — the admin's through Cloud
193
201
  * Run's own IAP, the others publicly.
194
202
  */
195
203
  export function healthOrigins(target: HealthTarget): {
@@ -219,6 +227,8 @@ export const IAM_PROPAGATION_WINDOW_MS = 7 * 60_000;
219
227
  export interface HealthProbeDeps {
220
228
  readonly run: GcloudRunner;
221
229
  readonly http: HttpFetch;
230
+ /** How `gcp` reaches the site's host through the load balancer (#1459). */
231
+ readonly loadBalancerGet: LoadBalancerGet;
222
232
  readonly sleep: Sleep;
223
233
  /**
224
234
  * Whether the converge step that ran just before changed the access the
@@ -347,7 +357,7 @@ export function createIapHealthProbe(target: HealthTarget, deps: HealthProbeDeps
347
357
  function gatewayRoutingHelp(): string {
348
358
  return target.provider === "gcp-firebase"
349
359
  ? `Requests to its run.app URL do not reach the Caelo gateway: its Cloud Run ingress likely refuses them. The gcp-firebase stack declares ingress "all"; upgrade's converge step sets it. Check it with: gcloud run services describe <gateway service> --region=<region> --project=${target.projectId} --format='value(metadata.annotations."run.googleapis.com/ingress")'`
350
- : `Requests to ${origins.gateway}/api/ do not reach the Caelo gateway: the load balancer's URL map must route /api/* to the gateway backend. Check the install's load balancer, then re-run upgrade.`;
360
+ : `Requests to ${origins.gateway}/api/ through the load balancer do not reach the Caelo gateway: its URL map must route /api/* to the gateway backend, and the gateway service must admit allUsers as roles/run.invoker (upgrade's converge step grants it; Cloud Run answers 403 without it). Check them, then re-run upgrade.`;
351
361
  }
352
362
 
353
363
  async function get(url: string, headers: Record<string, string>) {
@@ -359,6 +369,21 @@ export function createIapHealthProbe(target: HealthTarget, deps: HealthProbeDeps
359
369
  }
360
370
  }
361
371
 
372
+ /** A GET to a public service: on gcp through the load balancer (#1459). */
373
+ async function getPublic(origin: string, path: string) {
374
+ if (target.provider !== "gcp") return get(`${origin}${path}`, {});
375
+ try {
376
+ const res = await deps.loadBalancerGet({
377
+ connectHost: new URL(origins.admin).hostname,
378
+ hostHeader: new URL(origin).hostname,
379
+ path,
380
+ });
381
+ return { reached: true as const, status: res.status, text: res.text };
382
+ } catch (e) {
383
+ return { reached: false as const, error: e instanceof Error ? e.message : String(e) };
384
+ }
385
+ }
386
+
362
387
  async function baselineOnce(): Promise<BaselineOutcome> {
363
388
  const token = await iapToken();
364
389
  if (!token.ok) {
@@ -385,7 +410,7 @@ export function createIapHealthProbe(target: HealthTarget, deps: HealthProbeDeps
385
410
  refusal: admin.status === 401 || admin.status === 403 ? "iap-refused" : "other",
386
411
  };
387
412
  }
388
- const gateway = await get(`${origins.gateway}/api/_caelo/health`, {});
413
+ const gateway = await getPublic(origins.gateway, "/api/_caelo/health");
389
414
  if (!gateway.reached) {
390
415
  return {
391
416
  ok: false,
@@ -462,12 +487,12 @@ export function createIapHealthProbe(target: HealthTarget, deps: HealthProbeDeps
462
487
  if (!admin.reached) return { ok: false, error: `admin unreachable: ${admin.error}` };
463
488
  const a = evaluateAdminDeepHealth(admin.status, admin.text, expectedVersion);
464
489
  if (!a.ok) return a;
465
- const gateway = await get(`${origins.gateway}/api/_caelo/health?deep=1`, {});
490
+ const gateway = await getPublic(origins.gateway, "/api/_caelo/health?deep=1");
466
491
  if (!gateway.reached) return { ok: false, error: `gateway unreachable: ${gateway.error}` };
467
492
  const g = evaluatePublicServiceDeepHealth("gateway", gateway.status, gateway.text);
468
493
  if (!g.ok) return g;
469
494
  // #1328 — the proxy holds no database login: healthy once it answers.
470
- const proxy = await get(`${origins.mcpAuthProxy}${MCP_AUTH_PROXY_HEALTH_PATH}`, {});
495
+ const proxy = await getPublic(origins.mcpAuthProxy, MCP_AUTH_PROXY_HEALTH_PATH);
471
496
  if (!proxy.reached) return { ok: false, error: `MCP-Auth-Proxy unreachable: ${proxy.error}` };
472
497
  const p = evaluatePublicServiceDeepHealth("MCP-Auth-Proxy", proxy.status, proxy.text);
473
498
  return p.ok ? { ok: true, detail: `${a.detail}; ${g.detail}; ${p.detail}` } : p;
@@ -0,0 +1,64 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * A GET to one of the `gcp` load balancer's hosts, connected through another
5
+ * of its names (#1459).
6
+ *
7
+ * The load balancer routes by Host header, not by the name the connection
8
+ * was opened to, and every host of an install shares its address. So the
9
+ * health check reaches the site's `/api/*` before the site's domain has any
10
+ * record: it connects to `admin.<domain>`, whose record and certificate the
11
+ * install needs anyway, verifies that certificate as usual, and asks for the
12
+ * site's host. The site's own certificate cannot serve here: Google issues it
13
+ * only once the domain points at the load balancer.
14
+ *
15
+ * `node:https` because `fetch` may not set the Host header (undici), and this
16
+ * runs under Bun in the ops image and under either runtime from a terminal.
17
+ */
18
+
19
+ import { request } from "node:https";
20
+
21
+ /** One GET through the load balancer. */
22
+ export interface LoadBalancerRequest {
23
+ /** The name to connect to and verify the certificate against. */
24
+ readonly connectHost: string;
25
+ /** The host the URL map routes on. */
26
+ readonly hostHeader: string;
27
+ /** Path and query. */
28
+ readonly path: string;
29
+ }
30
+
31
+ /** Sends a {@link LoadBalancerRequest}; rejects when no HTTP answer came. */
32
+ export type LoadBalancerGet = (
33
+ req: LoadBalancerRequest,
34
+ ) => Promise<{ readonly status: number; readonly text: string }>;
35
+
36
+ const TIMEOUT_MS = 30_000;
37
+
38
+ /** {@link LoadBalancerGet} over HTTPS, with the default certificate checks. */
39
+ export const httpsLoadBalancerGet: LoadBalancerGet = (req) =>
40
+ new Promise((resolve, reject) => {
41
+ const outgoing = request(
42
+ {
43
+ host: req.connectHost,
44
+ servername: req.connectHost,
45
+ path: req.path,
46
+ method: "GET",
47
+ headers: { Host: req.hostHeader },
48
+ timeout: TIMEOUT_MS,
49
+ },
50
+ (res) => {
51
+ const chunks: Buffer[] = [];
52
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
53
+ res.on("error", reject);
54
+ res.on("end", () =>
55
+ resolve({ status: res.statusCode ?? 0, text: Buffer.concat(chunks).toString("utf8") }),
56
+ );
57
+ },
58
+ );
59
+ outgoing.on("timeout", () =>
60
+ outgoing.destroy(new Error(`no answer from ${req.connectHost} in ${TIMEOUT_MS / 1000} s`)),
61
+ );
62
+ outgoing.on("error", reject);
63
+ outgoing.end();
64
+ });
@@ -221,11 +221,20 @@ function fakeInstall(events: string[], overrides: [RegExp, Answer][] = []) {
221
221
  return { run, calls };
222
222
  }
223
223
 
224
- /** Cloud SQL Admin API: every operation is done at once. */
224
+ /**
225
+ * Cloud SQL Admin API: every operation is done at once. Firebase Hosting: the
226
+ * staging host's DNS already points at the staging site.
227
+ */
225
228
  const http: HttpFetch = async () => ({
226
229
  ok: true,
227
230
  status: 200,
228
- text: async () => JSON.stringify({ name: "op-1", status: "DONE" }),
231
+ text: async () =>
232
+ JSON.stringify({
233
+ name: "op-1",
234
+ status: "DONE",
235
+ hostState: "HOST_ACTIVE",
236
+ ownershipState: "OWNERSHIP_ACTIVE",
237
+ }),
229
238
  });
230
239
 
231
240
  function recordingReporter() {
@@ -732,6 +741,71 @@ describe("upgradeGcpInstall — converge, then app-roll", () => {
732
741
  ).toBe(false);
733
742
  });
734
743
 
744
+ it("#1463 — an existing install's gateways reach the budget in the revision that rolls their image", async () => {
745
+ const before = (json: string) => {
746
+ const svc = JSON.parse(json);
747
+ svc.spec.template.metadata.annotations["autoscaling.knative.dev/maxScale"] = "100";
748
+ return ok(JSON.stringify(svc));
749
+ };
750
+ const events: string[] = [];
751
+ const { deps } = upgradeDeps(events, {
752
+ overrides: [
753
+ [new RegExp(`describe ${GATEWAY} .*--format=json`), before(GATEWAY_JSON)],
754
+ [new RegExp(`describe ${STAGING} .*--format=json`), before(STAGING_JSON)],
755
+ ],
756
+ });
757
+ expect(await upgradeGcpInstall(TARGET, deps)).toBe(true);
758
+ const roll = (service: string) =>
759
+ events.find((e) => e.startsWith(`gcloud run services update ${service} `)) ?? "";
760
+ expect(roll(GATEWAY)).toContain("--image registry/gateway@");
761
+ expect(roll(GATEWAY)).toContain("--max-instances=10");
762
+ expect(roll(GATEWAY)).toContain("CAELO_DB_PUBLIC_POOL_MAX=2");
763
+ expect(roll(STAGING)).toContain("--image registry/gateway@");
764
+ expect(roll(STAGING)).toContain("--max-instances=1");
765
+ expect(roll(STAGING)).toContain("CAELO_DB_PUBLIC_POOL_MAX=2");
766
+ // Neither reaches the services the budget does not size this way.
767
+ expect(roll(ADMIN)).not.toContain("--max-instances");
768
+ expect(roll(PROXY)).not.toContain("CAELO_DB_PUBLIC_POOL_MAX");
769
+ });
770
+
771
+ it("#1455 — names the records and keeps the old route while the staging host's DNS has not moved", async () => {
772
+ const events: string[] = [];
773
+ const { deps, lines, recorded } = upgradeDeps(events, {
774
+ overrides: [
775
+ [/^beta run domain-mappings describe/, ok("staging.acme.com\n")],
776
+ // Nothing else keeps this converge incomplete.
777
+ [/^compute firewall-rules list/, ok("[]")],
778
+ ],
779
+ });
780
+ const notMoved: HttpFetch = async (url) => ({
781
+ ok: true,
782
+ status: 200,
783
+ text: async () =>
784
+ JSON.stringify(
785
+ url.includes("/customDomains/")
786
+ ? {
787
+ hostState: "HOST_UNHOSTED",
788
+ requiredDnsUpdates: {
789
+ desired: [
790
+ {
791
+ records: [
792
+ { domainName: "staging.acme.com.", type: "A", rdata: "199.36.158.100" },
793
+ ],
794
+ },
795
+ ],
796
+ },
797
+ }
798
+ : { name: "op-1", status: "DONE" },
799
+ ),
800
+ });
801
+ expect(await upgradeGcpInstall(TARGET, { ...deps, http: notMoved })).toBe(true);
802
+ expect(events.some((e) => e.includes("domain-mappings delete"))).toBe(false);
803
+ expect(lines.some((l) => l.includes("staging.acme.com A 199.36.158.100"))).toBe(true);
804
+ expect(lines.some((l) => l.includes("keeps that route"))).toBe(true);
805
+ // The Owner's DNS change must not hold every later update back.
806
+ expect(recorded.contract).toEqual([TARGET.infraContractVersion]);
807
+ });
808
+
735
809
  it("#883 review: an install without caelo-provisioner still records the contract; its admin keeps the terminal path", async () => {
736
810
  const events: string[] = [];
737
811
  const { deps, recorded, lines } = upgradeDeps(events, {
@@ -1196,6 +1270,17 @@ describe("upgradeGcpInstall — converge, then app-roll", () => {
1196
1270
  expect(neg).toBeLessThan(backend);
1197
1271
  expect(backend).toBeLessThan(retire);
1198
1272
  expect(retire).toBeLessThan(indexOf(events, /^migrate /));
1273
+ // #1339 (contract 22) — the gateway policy's per-path rules, before the
1274
+ // migrations; the general ban is limited to /api/ paths.
1275
+ const general = indexOf(
1276
+ events,
1277
+ /^gcloud compute security-policies rules create 1001 --security-policy=caelo-production-waf-1 .*--expression=request\.path\.contains\('\/api\/'\)/,
1278
+ );
1279
+ expect(
1280
+ indexOf(events, /rules create 800 --security-policy=caelo-production-waf-1 /),
1281
+ ).toBeLessThan(general);
1282
+ expect(general).toBeLessThan(indexOf(events, /^migrate /));
1283
+ expect(lines).toContain("done: Cloud Armor rules of caelo-production-waf-1 in place");
1199
1284
  });
1200
1285
 
1201
1286
  it("on gcp-firebase there is no URL map: no redirects role", async () => {
@@ -1336,7 +1421,15 @@ describe("upgradeGcpInstall — converge, then app-roll", () => {
1336
1421
  gatewayServiceUrl: `https://${GATEWAY}-xyz.a.run.app`,
1337
1422
  mcpAuthProxyServiceUrl: `https://${PROXY}-xyz.a.run.app`,
1338
1423
  },
1339
- { run: deps.run, http: htmlGateway, sleep: noSleep, accessJustChanged: false },
1424
+ {
1425
+ run: deps.run,
1426
+ http: htmlGateway,
1427
+ loadBalancerGet: async () => {
1428
+ throw new Error("gcp-firebase never uses the load balancer path");
1429
+ },
1430
+ sleep: noSleep,
1431
+ accessJustChanged: false,
1432
+ },
1340
1433
  ),
1341
1434
  }),
1342
1435
  }),