@caelo-cms/provisioning 0.11.19 → 0.11.20

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 (121) hide show
  1. package/dist/agent-db.js +32 -0
  2. package/dist/aws-task-roles.d.ts +11 -0
  3. package/dist/aws-task-roles.d.ts.map +1 -1
  4. package/dist/aws-task-roles.js +19 -0
  5. package/dist/aws-task-roles.js.map +1 -1
  6. package/dist/azure-secrets.d.ts +22 -0
  7. package/dist/azure-secrets.d.ts.map +1 -0
  8. package/dist/azure-secrets.js +14 -0
  9. package/dist/azure-secrets.js.map +1 -0
  10. package/dist/caddy.d.ts +7 -0
  11. package/dist/caddy.d.ts.map +1 -1
  12. package/dist/caddy.js +22 -1
  13. package/dist/caddy.js.map +1 -1
  14. package/dist/cli.js +3 -0
  15. package/dist/cli.js.map +1 -1
  16. package/dist/gateway-armor.d.ts +24 -0
  17. package/dist/gateway-armor.d.ts.map +1 -0
  18. package/dist/gateway-armor.js +118 -0
  19. package/dist/gateway-armor.js.map +1 -0
  20. package/dist/gateway-edge.d.ts +128 -0
  21. package/dist/gateway-edge.d.ts.map +1 -0
  22. package/dist/gateway-edge.js +211 -0
  23. package/dist/gateway-edge.js.map +1 -0
  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 +21 -1
  27. package/dist/infra-contract.js.map +1 -1
  28. package/dist/lifecycle.d.ts.map +1 -1
  29. package/dist/lifecycle.js +8 -1
  30. package/dist/lifecycle.js.map +1 -1
  31. package/dist/pool-budget-stack.d.ts +22 -0
  32. package/dist/pool-budget-stack.d.ts.map +1 -1
  33. package/dist/pool-budget-stack.js +22 -1
  34. package/dist/pool-budget-stack.js.map +1 -1
  35. package/dist/public-service-shape.d.ts +45 -0
  36. package/dist/public-service-shape.d.ts.map +1 -0
  37. package/dist/public-service-shape.js +90 -0
  38. package/dist/public-service-shape.js.map +1 -0
  39. package/dist/remote-mcp-edge.d.ts +1 -1
  40. package/dist/remote-mcp-edge.js +1 -1
  41. package/dist/remote-mcp.d.ts.map +1 -1
  42. package/dist/remote-mcp.js +12 -2
  43. package/dist/remote-mcp.js.map +1 -1
  44. package/dist/serverless-backend.d.ts +27 -0
  45. package/dist/serverless-backend.d.ts.map +1 -0
  46. package/dist/serverless-backend.js +30 -0
  47. package/dist/serverless-backend.js.map +1 -0
  48. package/dist/stack-contract.d.ts +6 -0
  49. package/dist/stack-contract.d.ts.map +1 -1
  50. package/dist/stack-contract.js +24 -0
  51. package/dist/stack-contract.js.map +1 -1
  52. package/dist/stack-converge.d.ts +13 -0
  53. package/dist/stack-converge.d.ts.map +1 -1
  54. package/dist/stack-converge.js +27 -0
  55. package/dist/stack-converge.js.map +1 -1
  56. package/dist/staging-gateway-setup.d.ts +5 -0
  57. package/dist/staging-gateway-setup.d.ts.map +1 -1
  58. package/dist/staging-gateway-setup.js +60 -19
  59. package/dist/staging-gateway-setup.js.map +1 -1
  60. package/dist/upgrade/app-roll.d.ts +5 -1
  61. package/dist/upgrade/app-roll.d.ts.map +1 -1
  62. package/dist/upgrade/app-roll.js +20 -3
  63. package/dist/upgrade/app-roll.js.map +1 -1
  64. package/dist/upgrade/converge.d.ts.map +1 -1
  65. package/dist/upgrade/converge.js +27 -4
  66. package/dist/upgrade/converge.js.map +1 -1
  67. package/dist/upgrade/health.d.ts +13 -3
  68. package/dist/upgrade/health.d.ts.map +1 -1
  69. package/dist/upgrade/health.js +24 -7
  70. package/dist/upgrade/health.js.map +1 -1
  71. package/dist/upgrade/load-balancer-get.d.ts +17 -0
  72. package/dist/upgrade/load-balancer-get.d.ts.map +1 -0
  73. package/dist/upgrade/load-balancer-get.js +38 -0
  74. package/dist/upgrade/load-balancer-get.js.map +1 -0
  75. package/dist/upgrader-gcp.d.ts.map +1 -1
  76. package/dist/upgrader-gcp.js +8 -1
  77. package/dist/upgrader-gcp.js.map +1 -1
  78. package/dist/wizards/gcp-cost.d.ts +9 -0
  79. package/dist/wizards/gcp-cost.d.ts.map +1 -1
  80. package/dist/wizards/gcp-cost.js +69 -34
  81. package/dist/wizards/gcp-cost.js.map +1 -1
  82. package/package.json +2 -2
  83. package/src/aws-task-roles.ts +22 -0
  84. package/src/azure-secrets.ts +38 -0
  85. package/src/caddy.test.ts +19 -2
  86. package/src/caddy.ts +23 -0
  87. package/src/cli.ts +5 -0
  88. package/src/gateway-armor.ts +135 -0
  89. package/src/gateway-bootstrap.test.ts +1 -0
  90. package/src/gateway-edge.test.ts +262 -0
  91. package/src/gateway-edge.ts +256 -0
  92. package/src/gateway-env-isolation.test.ts +45 -6
  93. package/src/infra-contract.test.ts +5 -3
  94. package/src/infra-contract.ts +21 -1
  95. package/src/lifecycle.ts +8 -1
  96. package/src/pool-budget-stack.ts +25 -0
  97. package/src/pool-budget-stacks.test.ts +31 -0
  98. package/src/public-service-shape.test.ts +166 -0
  99. package/src/public-service-shape.ts +131 -0
  100. package/src/remote-mcp-edge.ts +1 -1
  101. package/src/remote-mcp.test.ts +38 -1
  102. package/src/remote-mcp.ts +25 -3
  103. package/src/serverless-backend.ts +47 -0
  104. package/src/stack-contract.test.ts +13 -0
  105. package/src/stack-contract.ts +25 -0
  106. package/src/stack-converge.test.ts +28 -1
  107. package/src/stack-converge.ts +30 -0
  108. package/src/staging-gateway-setup.test.ts +55 -3
  109. package/src/staging-gateway-setup.ts +79 -27
  110. package/src/upgrade/app-roll.ts +27 -3
  111. package/src/upgrade/converge.ts +33 -4
  112. package/src/upgrade/health.test.ts +88 -13
  113. package/src/upgrade/health.ts +32 -7
  114. package/src/upgrade/load-balancer-get.ts +64 -0
  115. package/src/upgrade/upgrade.test.ts +96 -3
  116. package/src/upgrader-gcp.ts +8 -1
  117. package/src/wizards/gcp-cost.ts +78 -35
  118. package/stacks/aws/index.ts +24 -22
  119. package/stacks/azure/index.ts +152 -64
  120. package/stacks/gcp/index.ts +35 -47
  121. package/stacks/gcp-firebase/index.ts +25 -13
@@ -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
  }),
@@ -42,6 +42,7 @@ import {
42
42
  } from "./upgrade/gcp-lookup.js";
43
43
  import { createIapHealthProbe } from "./upgrade/health.js";
44
44
  import { createReleaseImageForms } from "./upgrade/image-forms.js";
45
+ import { httpsLoadBalancerGet } from "./upgrade/load-balancer-get.js";
45
46
  import { type IamTester, restIamTester } from "./upgrader-iam-preflight.js";
46
47
  import type { UpdateQueue, UpgraderJobDeps } from "./upgrader-job.js";
47
48
  import type { JobLog } from "./upgrader-reporter.js";
@@ -152,7 +153,13 @@ export async function healthProbeFor(
152
153
  gatewayServiceUrl: urls.gateway as string,
153
154
  mcpAuthProxyServiceUrl: urls["mcp-auth-proxy"] as string,
154
155
  },
155
- { run, http, sleep: realSleep, accessJustChanged: context.accessJustChanged },
156
+ {
157
+ run,
158
+ http,
159
+ loadBalancerGet: httpsLoadBalancerGet,
160
+ sleep: realSleep,
161
+ accessJustChanged: context.accessJustChanged,
162
+ },
156
163
  ),
157
164
  };
158
165
  }