@caelo-cms/provisioning 0.11.18 → 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 (126) 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 +4 -4
  40. package/dist/remote-mcp-edge.d.ts.map +1 -1
  41. package/dist/remote-mcp-edge.js +2 -2
  42. package/dist/remote-mcp-edge.js.map +1 -1
  43. package/dist/remote-mcp.d.ts.map +1 -1
  44. package/dist/remote-mcp.js +30 -19
  45. package/dist/remote-mcp.js.map +1 -1
  46. package/dist/serverless-backend.d.ts +27 -0
  47. package/dist/serverless-backend.d.ts.map +1 -0
  48. package/dist/serverless-backend.js +30 -0
  49. package/dist/serverless-backend.js.map +1 -0
  50. package/dist/stack-contract.d.ts +6 -0
  51. package/dist/stack-contract.d.ts.map +1 -1
  52. package/dist/stack-contract.js +24 -0
  53. package/dist/stack-contract.js.map +1 -1
  54. package/dist/stack-converge.d.ts +13 -0
  55. package/dist/stack-converge.d.ts.map +1 -1
  56. package/dist/stack-converge.js +27 -0
  57. package/dist/stack-converge.js.map +1 -1
  58. package/dist/staging-gateway-setup.d.ts +5 -0
  59. package/dist/staging-gateway-setup.d.ts.map +1 -1
  60. package/dist/staging-gateway-setup.js +88 -28
  61. package/dist/staging-gateway-setup.js.map +1 -1
  62. package/dist/upgrade/app-roll.d.ts +5 -1
  63. package/dist/upgrade/app-roll.d.ts.map +1 -1
  64. package/dist/upgrade/app-roll.js +20 -3
  65. package/dist/upgrade/app-roll.js.map +1 -1
  66. package/dist/upgrade/converge.d.ts.map +1 -1
  67. package/dist/upgrade/converge.js +27 -4
  68. package/dist/upgrade/converge.js.map +1 -1
  69. package/dist/upgrade/health.d.ts +13 -3
  70. package/dist/upgrade/health.d.ts.map +1 -1
  71. package/dist/upgrade/health.js +24 -7
  72. package/dist/upgrade/health.js.map +1 -1
  73. package/dist/upgrade/load-balancer-get.d.ts +17 -0
  74. package/dist/upgrade/load-balancer-get.d.ts.map +1 -0
  75. package/dist/upgrade/load-balancer-get.js +38 -0
  76. package/dist/upgrade/load-balancer-get.js.map +1 -0
  77. package/dist/upgrader-gcp.d.ts.map +1 -1
  78. package/dist/upgrader-gcp.js +8 -1
  79. package/dist/upgrader-gcp.js.map +1 -1
  80. package/dist/wizards/gcp-cost.d.ts +9 -0
  81. package/dist/wizards/gcp-cost.d.ts.map +1 -1
  82. package/dist/wizards/gcp-cost.js +69 -34
  83. package/dist/wizards/gcp-cost.js.map +1 -1
  84. package/dist/wizards/gcp.js +1 -1
  85. package/dist/wizards/gcp.js.map +1 -1
  86. package/package.json +2 -2
  87. package/src/aws-task-roles.ts +22 -0
  88. package/src/azure-secrets.ts +38 -0
  89. package/src/caddy.test.ts +19 -2
  90. package/src/caddy.ts +23 -0
  91. package/src/cli.ts +5 -0
  92. package/src/gateway-armor.ts +135 -0
  93. package/src/gateway-bootstrap.test.ts +1 -0
  94. package/src/gateway-edge.test.ts +262 -0
  95. package/src/gateway-edge.ts +256 -0
  96. package/src/gateway-env-isolation.test.ts +45 -6
  97. package/src/infra-contract.test.ts +5 -3
  98. package/src/infra-contract.ts +21 -1
  99. package/src/lifecycle.ts +8 -1
  100. package/src/pool-budget-stack.ts +25 -0
  101. package/src/pool-budget-stacks.test.ts +31 -0
  102. package/src/public-service-shape.test.ts +166 -0
  103. package/src/public-service-shape.ts +131 -0
  104. package/src/remote-mcp-edge.ts +2 -2
  105. package/src/remote-mcp.test.ts +63 -2
  106. package/src/remote-mcp.ts +42 -19
  107. package/src/serverless-backend.ts +47 -0
  108. package/src/stack-contract.test.ts +13 -0
  109. package/src/stack-contract.ts +25 -0
  110. package/src/stack-converge.test.ts +28 -1
  111. package/src/stack-converge.ts +30 -0
  112. package/src/staging-gateway-setup.test.ts +134 -3
  113. package/src/staging-gateway-setup.ts +107 -36
  114. package/src/upgrade/app-roll.ts +27 -3
  115. package/src/upgrade/converge.ts +33 -4
  116. package/src/upgrade/health.test.ts +88 -13
  117. package/src/upgrade/health.ts +32 -7
  118. package/src/upgrade/load-balancer-get.ts +64 -0
  119. package/src/upgrade/upgrade.test.ts +97 -4
  120. package/src/upgrader-gcp.ts +8 -1
  121. package/src/wizards/gcp-cost.ts +78 -35
  122. package/src/wizards/gcp.ts +2 -1
  123. package/stacks/aws/index.ts +24 -22
  124. package/stacks/azure/index.ts +152 -64
  125. package/stacks/gcp/index.ts +35 -47
  126. package/stacks/gcp-firebase/index.ts +25 -13
@@ -11,8 +11,9 @@
11
11
  * - `gcp-firebase` (E13 a): a second Firebase Hosting site with one `**`
12
12
  * rewrite to the staging gateway, the staging host as that site's
13
13
  * custom domain. The Cloud Run domain mapping that sent the staging
14
- * host to the old gateway service (#650) is deleted: nothing may lead
15
- * to the staged files but the gate.
14
+ * host to the old gateway service (#650) is deleted once the host's DNS
15
+ * points at the new site (#1455): nothing may lead to the staged files
16
+ * but the gate.
16
17
  * - `gcp`: the staging host gets its own host rule on the site's load
17
18
  * balancer, routed in full to the staging gateway's serverless NEG and
18
19
  * backend (the gateway's Cloud Armor policy as an extra layer, E3), and
@@ -33,12 +34,7 @@
33
34
  */
34
35
 
35
36
  import { createHash } from "node:crypto";
36
- import {
37
- DB_PUBLIC_POOL_MAX_ENV,
38
- DEFAULT_STAGING_GATEWAY_MAX_INSTANCES,
39
- GATEWAY_POOL_MAX,
40
- isIpLiteral,
41
- } from "@caelo-cms/shared";
37
+ import { DEFAULT_STAGING_GATEWAY_MAX_INSTANCES, isIpLiteral } from "@caelo-cms/shared";
42
38
  import { gcloud as defaultGcloud, isGcloudNotFound } from "./gcloud.js";
43
39
  import { type GcloudRunner, realSleep, runWithRetry, type Sleep } from "./gcloud-retry.js";
44
40
  import {
@@ -50,11 +46,16 @@ import {
50
46
  stagingGatewayEdgeNames,
51
47
  stagingGatewayServiceAccountEmail,
52
48
  } from "./gcp-names.js";
49
+ import { GATEWAY_POOL_ENV } from "./pool-budget-stack.js";
53
50
  import {
54
51
  type EnsureOutcome,
55
52
  ensureStagingGatewayServiceAccount,
56
53
  type HttpFetch,
57
54
  } from "./runtime-secrets.js";
55
+ import {
56
+ repairServerlessBackendPort,
57
+ SERVERLESS_BACKEND_CREATE_FLAGS,
58
+ } from "./serverless-backend.js";
58
59
  import {
59
60
  type CloudRunEnvVar,
60
61
  cloudRunServicePrefix,
@@ -141,7 +142,7 @@ export function stagingGatewayDeployArgs(inputs: StagingGatewayServiceInputs): s
141
142
  ...env.flatMap((e) => ("value" in e ? [`${e.name}=${e.value}`] : [])),
142
143
  // The connection budget's share of one instance (pool-budget.ts): the
143
144
  // stacks set the same on the live gateway.
144
- `${DB_PUBLIC_POOL_MAX_ENV}=${GATEWAY_POOL_MAX}`,
145
+ ...GATEWAY_POOL_ENV.map((e) => `${e.name}=${e.value}`),
145
146
  ];
146
147
  const secrets = env.flatMap((e) =>
147
148
  "valueSource" in e
@@ -471,6 +472,11 @@ export type StagingEdgeResult =
471
472
  readonly done: string[];
472
473
  /** The records the staging host needs at the registrar (Settings → Updates shows them too). */
473
474
  readonly dnsRecords: StagingDnsRecord[];
475
+ /**
476
+ * #1455 — the host's DNS still points at its Cloud Run domain mapping,
477
+ * so the mapping stayed: see {@link settleStagingDomainMapping}.
478
+ */
479
+ readonly domainMappingKept: boolean;
474
480
  }
475
481
  | { readonly ok: false; readonly error: string; readonly done: string[] };
476
482
 
@@ -530,6 +536,18 @@ export function isFirebaseStagingConfig(
530
536
  );
531
537
  }
532
538
 
539
+ /**
540
+ * Whether Hosting serves the host, in its own words: the check #1455 turns
541
+ * on, the same one Settings → Updates uses (`readStagingHostDns`). The DNS
542
+ * pointing at Hosting (`HOST_ACTIVE`, also for a CNAME to the site's `web.app`
543
+ * name: searchviu-website, 2026-11-05) is not enough while ownership is
544
+ * pending.
545
+ */
546
+ function firebaseHostActive(customDomain: unknown): boolean {
547
+ const domain = customDomain as { hostState?: string; ownershipState?: string } | null;
548
+ return domain?.hostState === "HOST_ACTIVE" && domain.ownershipState === "OWNERSHIP_ACTIVE";
549
+ }
550
+
533
551
  /** The DNS records a Firebase custom domain asks for (`requiredDnsUpdates.desired`). */
534
552
  export function firebaseDesiredRecords(customDomain: unknown): StagingDnsRecord[] {
535
553
  const desired = (
@@ -668,7 +686,8 @@ async function ensureFirebaseStagingSite(
668
686
  // v0.11.16, 2026-11-04).
669
687
  const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
670
688
  let dnsRecords = firebaseDesiredRecords(domain.json);
671
- for (let i = 0; createdDomain && dnsRecords.length === 0 && i < FIREBASE_DNS_POLLS; i++) {
689
+ let hostActive = firebaseHostActive(domain.json);
690
+ for (let i = 0; !hostActive && dnsRecords.length === 0 && i < FIREBASE_DNS_POLLS; i++) {
672
691
  await sleep(FIREBASE_DNS_POLL_MS);
673
692
  const again = await call(domainPath);
674
693
  if (!again.ok) {
@@ -677,32 +696,48 @@ async function ensureFirebaseStagingSite(
677
696
  );
678
697
  }
679
698
  dnsRecords = firebaseDesiredRecords(again.json);
699
+ hostActive = firebaseHostActive(again.json);
680
700
  }
681
- if (createdDomain && dnsRecords.length === 0) {
701
+ if (!hostActive && dnsRecords.length === 0) {
682
702
  return fail(
683
703
  `Firebase Hosting has not said which DNS records ${t.stagingHost} needs after ${(FIREBASE_DNS_POLLS * FIREBASE_DNS_POLL_MS) / 1000} s. Nothing is wrong with what was set up; re-run the installer to print them.`,
684
704
  );
685
705
  }
686
706
 
687
707
  // 4. The old route: the Cloud Run domain mapping (#650) to the service
688
- // that is now the MCP-Auth-Proxy. Nothing but the gate may lead to the
689
- // staged files, and the proxy no longer forwards (#1331).
690
- const mapping = await deleteStagingDomainMapping(t, run);
708
+ // that is now the MCP-Auth-Proxy.
709
+ const mapping = await settleStagingDomainMapping(t, hostActive, run);
691
710
  if (!mapping.ok) return fail(mapping.error);
692
- if (mapping.deleted) done.push(`deleted the Cloud Run domain mapping of ${t.stagingHost}`);
711
+ if (mapping.outcome === "deleted") {
712
+ done.push(`deleted the Cloud Run domain mapping of ${t.stagingHost}`);
713
+ }
693
714
 
694
- return { ok: true, done, dnsRecords };
715
+ return { ok: true, done, dnsRecords, domainMappingKept: mapping.outcome === "kept" };
695
716
  }
696
717
 
697
718
  /**
698
- * Delete the staging host's Cloud Run domain mapping (#650), if there is
699
- * one. Needs the gcloud `beta` component; without it the mapping is reported
700
- * as unknown rather than guessed away.
719
+ * The staging host's Cloud Run domain mapping (#650), if there is one: gone
720
+ * once the host's DNS points at Hosting, kept until then (#1455).
721
+ *
722
+ * While the host is still a CNAME to `ghs.googlehosted.com` the mapping holds
723
+ * its certificate, and Hosting can issue none, so deleting it turns the host
724
+ * into a TLS error (0.11.17 on searchviu-website). The mapping leads to the
725
+ * MCP-Auth-Proxy, which forwards nothing (#1331) and answers its fixed 404,
726
+ * so keeping it opens no way around the staging gate. It cannot be pointed at
727
+ * the staging gateway instead: Cloud Run refuses a second mapping of a host
728
+ * in the same region even with `--force-override`, delete + create drops the
729
+ * certificate, and create needs a verified owner of the domain, which the
730
+ * converge job's account is not (all tried on caelo-p0-tmp-1104, 2026-11-05).
731
+ * The next converge after the DNS change deletes it.
732
+ *
733
+ * Needs the gcloud `beta` component; without it the mapping is reported as
734
+ * unknown rather than guessed away.
701
735
  */
702
- async function deleteStagingDomainMapping(
736
+ async function settleStagingDomainMapping(
703
737
  t: StagingGatewayTarget,
738
+ hostActive: boolean,
704
739
  run: GcloudRunner,
705
- ): Promise<{ ok: true; deleted: boolean } | { ok: false; error: string }> {
740
+ ): Promise<{ ok: true; outcome: "none" | "kept" | "deleted" } | { ok: false; error: string }> {
706
741
  const scope = [`--domain=${t.stagingHost}`, `--region=${t.region}`, `--project=${t.projectId}`];
707
742
  const described = await run([
708
743
  "beta",
@@ -714,16 +749,17 @@ async function deleteStagingDomainMapping(
714
749
  ]);
715
750
  if (!described.ok) {
716
751
  if (isGcloudNotFound(described.stderr)) {
717
- return { ok: true, deleted: false };
752
+ return { ok: true, outcome: "none" };
718
753
  }
719
754
  return {
720
755
  ok: false,
721
756
  error: `read the Cloud Run domain mapping of ${t.stagingHost}: ${described.stderr.trim()}`,
722
757
  };
723
758
  }
759
+ if (!hostActive) return { ok: true, outcome: "kept" };
724
760
  const deleted = await run(["beta", "run", "domain-mappings", "delete", ...scope, "--quiet"]);
725
761
  return deleted.ok
726
- ? { ok: true, deleted: true }
762
+ ? { ok: true, outcome: "deleted" }
727
763
  : {
728
764
  ok: false,
729
765
  error: `delete the Cloud Run domain mapping of ${t.stagingHost}: ${deleted.stderr.trim()}`,
@@ -884,7 +920,12 @@ async function ensureGcpEdge(
884
920
  project,
885
921
  "--format=json",
886
922
  ]);
887
- let backendJson: { selfLink?: string; backends?: { group?: string }[] } = {};
923
+ let backendJson: {
924
+ selfLink?: string;
925
+ securityPolicy?: string;
926
+ portName?: string;
927
+ backends?: { group?: string }[];
928
+ } = {};
888
929
  if (!backend.ok) {
889
930
  if (!isGcloudNotFound(backend.stderr)) {
890
931
  return fail(`describe ${names.backend}: ${backend.stderr.trim()}`);
@@ -897,18 +938,41 @@ async function ensureGcpEdge(
897
938
  "--global",
898
939
  project,
899
940
  "--load-balancing-scheme=EXTERNAL_MANAGED",
900
- "--protocol=HTTPS",
901
- `--security-policy=${policy}`,
941
+ ...SERVERLESS_BACKEND_CREATE_FLAGS,
902
942
  "--format=json",
903
943
  "--quiet",
904
944
  ]);
905
945
  if (!created.ok) return fail(`create ${names.backend}: ${created.stderr.trim()}`);
906
- done.push(`created backend service ${names.backend} (Cloud Armor ${policy})`);
946
+ done.push(`created backend service ${names.backend}`);
907
947
  const parsed = safeJson(created.stdout);
908
948
  backendJson = ((Array.isArray(parsed) ? parsed[0] : parsed) ?? {}) as typeof backendJson;
909
949
  } else {
910
950
  backendJson = (safeJson(backend.stdout) ?? {}) as typeof backendJson;
911
951
  }
952
+ const port = await repairServerlessBackendPort(
953
+ run,
954
+ { name: names.backend, portName: backendJson.portName },
955
+ project,
956
+ );
957
+ if (port.error) return fail(port.error);
958
+ if (port.repaired) done.push(`set ${names.backend}'s port name to http`);
959
+ // `backend-services create` has no --security-policy: `update` attaches it,
960
+ // here and on a backend an earlier run left without one. The URL map is
961
+ // only pointed at this backend afterwards, so it is never served unguarded.
962
+ if (!backendJson.securityPolicy?.endsWith(`/securityPolicies/${policy}`)) {
963
+ const set = await run([
964
+ "compute",
965
+ "backend-services",
966
+ "update",
967
+ names.backend,
968
+ "--global",
969
+ project,
970
+ `--security-policy=${policy}`,
971
+ "--quiet",
972
+ ]);
973
+ if (!set.ok) return fail(`attach ${policy} to ${names.backend}: ${set.stderr.trim()}`);
974
+ done.push(`attached Cloud Armor ${policy} to ${names.backend}`);
975
+ }
912
976
  if (
913
977
  !(backendJson.backends ?? []).some((b) =>
914
978
  b.group?.endsWith(`/networkEndpointGroups/${names.neg}`),
@@ -1056,20 +1120,27 @@ async function ensureGcpEdge(
1056
1120
  "list",
1057
1121
  "--global",
1058
1122
  project,
1059
- `--filter=name~^${gcpNamePrefix(t.env)}`,
1123
+ // EXTERNAL: the stack's other global address is the database's private
1124
+ // range, and with two matches the install printed no record at all.
1125
+ `--filter=name~^${gcpNamePrefix(t.env)} AND addressType=EXTERNAL`,
1060
1126
  "--format=value(address)",
1061
1127
  ]);
1062
- const ips = address.ok
1063
- ? address.stdout
1064
- .split("\n")
1065
- .map((s) => s.trim())
1066
- .filter(Boolean)
1067
- : [];
1128
+ if (!address.ok) return fail(`list the load balancer's address: ${address.stderr.trim()}`);
1129
+ const ips = address.stdout
1130
+ .split("\n")
1131
+ .map((s) => s.trim())
1132
+ .filter(Boolean);
1133
+ const [ip, ...others] = ips;
1134
+ if (!ip || others.length > 0) {
1135
+ return fail(
1136
+ `expected one external address for ${t.stagingHost}, found ${ips.join(", ") || "none"}`,
1137
+ );
1138
+ }
1068
1139
  return {
1069
1140
  ok: true,
1070
1141
  done,
1071
- dnsRecords:
1072
- ips.length === 1 ? [{ name: t.stagingHost, type: "A", value: ips[0] as string }] : [],
1142
+ dnsRecords: [{ name: t.stagingHost, type: "A", value: ip }],
1143
+ domainMappingKept: false,
1073
1144
  };
1074
1145
  }
1075
1146
 
@@ -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 () => {},