@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
package/src/remote-mcp.ts CHANGED
@@ -43,6 +43,10 @@ import {
43
43
  mcpArmorRuleFlags,
44
44
  } from "./remote-mcp-edge.js";
45
45
  import type { HttpFetch } from "./runtime-secrets.js";
46
+ import {
47
+ repairServerlessBackendPort,
48
+ SERVERLESS_BACKEND_CREATE_FLAGS,
49
+ } from "./serverless-backend.js";
46
50
  import {
47
51
  CLOUD_RUN_SLUGS,
48
52
  type CloudRunSlug,
@@ -565,7 +569,13 @@ async function describePolicyRules(
565
569
  if (!describe.ok) {
566
570
  return { ok: false, missing: isGcloudNotFound(describe.stderr), error: describe.stderr.trim() };
567
571
  }
568
- const described = parseJson(describe.stdout) as { rules?: LiveArmorRule[] } | null;
572
+ // gcloud prints this one `describe` as a one-element list. Read as an
573
+ // object it has no rules, so a second run tried to create a rule that
574
+ // exists ("Cannot have rules with the same priorities").
575
+ const parsed = parseJson(describe.stdout);
576
+ const described = (Array.isArray(parsed) ? parsed[0] : parsed) as {
577
+ rules?: LiveArmorRule[];
578
+ } | null;
569
579
  if (!described)
570
580
  return { ok: false, missing: false, error: `describe ${policy}: output is not JSON` };
571
581
  return { ok: true, rules: described.rules ?? [] };
@@ -726,7 +736,12 @@ export async function ensureMcpAuthProxyBackend(
726
736
  project,
727
737
  "--format=json",
728
738
  ]);
729
- let backendJson: { selfLink?: string; securityPolicy?: string; backends?: { group?: string }[] };
739
+ let backendJson: {
740
+ selfLink?: string;
741
+ securityPolicy?: string;
742
+ portName?: string;
743
+ backends?: { group?: string }[];
744
+ };
730
745
  if (!backend.ok) {
731
746
  if (!isGcloudNotFound(backend.stderr)) {
732
747
  return { ok: false, error: `describe ${names.backend}: ${backend.stderr.trim()}` };
@@ -739,7 +754,7 @@ export async function ensureMcpAuthProxyBackend(
739
754
  "--global",
740
755
  project,
741
756
  "--load-balancing-scheme=EXTERNAL_MANAGED",
742
- "--protocol=HTTPS",
757
+ ...SERVERLESS_BACKEND_CREATE_FLAGS,
743
758
  "--format=json",
744
759
  "--quiet",
745
760
  ]);
@@ -751,6 +766,13 @@ export async function ensureMcpAuthProxyBackend(
751
766
  } else {
752
767
  backendJson = (parseJson(backend.stdout) ?? {}) as typeof backendJson;
753
768
  }
769
+ const port = await repairServerlessBackendPort(
770
+ run,
771
+ { name: names.backend, portName: backendJson.portName },
772
+ project,
773
+ );
774
+ if (port.error) return { ok: false, error: port.error };
775
+ if (port.repaired) done.push(`set ${names.backend}'s port name to http`);
754
776
  // `backend-services create` has no --security-policy: `update` attaches it,
755
777
  // here and on a backend an earlier run left without one.
756
778
  if (!backendJson.securityPolicy?.endsWith(`/securityPolicies/${names.policy}`)) {
@@ -0,0 +1,47 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * What the CLI-owned backend services on `gcp` (the MCP-Auth-Proxy's and the
5
+ * staging gateway's) need so a serverless NEG can be added to them.
6
+ *
7
+ * `gcloud compute backend-services create --protocol=HTTPS` sets the port
8
+ * name to `https`, and `add-backend` then refuses the NEG: "Port name is not
9
+ * supported for a backend service with Serverless network endpoint groups".
10
+ * The stack's backends carry `protocol: HTTPS` with the port name `http`,
11
+ * which Google accepts; the flags below give these two the same shape.
12
+ */
13
+
14
+ import type { GcloudRunner } from "./gcloud-retry.js";
15
+
16
+ /** The `backend-services create` flags of a backend that will hold a serverless NEG. */
17
+ export const SERVERLESS_BACKEND_CREATE_FLAGS: readonly string[] = [
18
+ "--protocol=HTTPS",
19
+ "--port-name=http",
20
+ ];
21
+
22
+ /**
23
+ * Repair a backend an earlier run created with the `https` port name, so
24
+ * `add-backend` can succeed. No call for any other backend.
25
+ *
26
+ * @returns whether it repaired the backend; `error` says what gcloud answered
27
+ */
28
+ export async function repairServerlessBackendPort(
29
+ run: GcloudRunner,
30
+ backend: { readonly name: string; readonly portName: string | undefined },
31
+ project: string,
32
+ ): Promise<{ readonly repaired: boolean; readonly error?: string }> {
33
+ if (backend.portName !== "https") return { repaired: false };
34
+ const set = await run([
35
+ "compute",
36
+ "backend-services",
37
+ "update",
38
+ backend.name,
39
+ "--global",
40
+ project,
41
+ "--port-name=http",
42
+ "--quiet",
43
+ ]);
44
+ return set.ok
45
+ ? { repaired: true }
46
+ : { repaired: false, error: `set ${backend.name}'s port name: ${set.stderr.trim()}` };
47
+ }
@@ -617,6 +617,19 @@ describe("MCP-Auth-Proxy contract (#1328)", () => {
617
617
  }
618
618
  });
619
619
 
620
+ it("gcp: visitors reach the gateway without a Google identity", () => {
621
+ expect(
622
+ stackIamInvariants("gcp").find(
623
+ (i) => i.target.kind === "run-service" && i.target.service === "gateway",
624
+ ),
625
+ ).toMatchObject({
626
+ stackResource: "data-gateway-public-invoker",
627
+ role: "roles/run.invoker",
628
+ member: "allUsers",
629
+ onFailure: "abort",
630
+ });
631
+ });
632
+
620
633
  it("gcp-firebase: the data gateway is the rewrite target, the proxy public", () => {
621
634
  const inv = stackIamInvariants("gcp-firebase");
622
635
  const on = (service: string) =>
@@ -526,6 +526,23 @@ export type RuntimeSecret =
526
526
  */
527
527
  | "mcp-oauth-seal-key";
528
528
 
529
+ /**
530
+ * Every {@link RuntimeSecret} as a value (the record makes the compiler
531
+ * check the list against the union): the cost table prices one active
532
+ * version of each.
533
+ */
534
+ export const RUNTIME_SECRETS = Object.keys({
535
+ "postgres-password": true,
536
+ "public-role-password": true,
537
+ "public-staging-role-password": true,
538
+ "secret-kek": true,
539
+ "internal-secret": true,
540
+ "tool-approval-secret": true,
541
+ "staging-gate-secret": true,
542
+ "operator-oauth-client": true,
543
+ "mcp-oauth-seal-key": true,
544
+ } satisfies Record<RuntimeSecret, true>) as readonly RuntimeSecret[];
545
+
529
546
  /** The Postgres roles Caelo's services log in as, with their passwords. */
530
547
  export type DatabaseRole = "admin_role" | "public_role" | "public_staging_role";
531
548
 
@@ -1703,6 +1720,14 @@ const GCP_ONLY: readonly IamInvariant[] = [
1703
1720
  onFailure: "abort",
1704
1721
  why: "IAP forwards admin traffic to Cloud Run as its service agent",
1705
1722
  },
1723
+ {
1724
+ stackResource: "data-gateway-public-invoker",
1725
+ role: "roles/run.invoker",
1726
+ member: "allUsers",
1727
+ target: { kind: "run-service", service: "gateway" },
1728
+ onFailure: "abort",
1729
+ why: "visitors reach the gateway through the load balancer without a Google identity; its load-balancer-only ingress is what closes the run.app URL",
1730
+ },
1706
1731
  ];
1707
1732
 
1708
1733
  const GCP_FIREBASE_ONLY: readonly IamInvariant[] = [
@@ -14,9 +14,11 @@ import {
14
14
  liveContainerEnv,
15
15
  liveDatabaseHost,
16
16
  liveDirectVpc,
17
+ liveMaxInstances,
17
18
  liveServiceAccount,
18
19
  planContractEnv,
19
20
  planEnvUpdate,
21
+ planMaxInstances,
20
22
  planNoVpc,
21
23
  policyGrants,
22
24
  removeRetiredIamBindings,
@@ -849,7 +851,7 @@ describe("ensureStackInvariants", () => {
849
851
  ]),
850
852
  ],
851
853
  "run services get-iam-policy": [
852
- policy([{ role: "roles/run.invoker", members: [IAP_AGENT] }]),
854
+ policy([{ role: "roles/run.invoker", members: [IAP_AGENT, "allUsers"] }]),
853
855
  ],
854
856
  "compute backend-buckets list": [ok("caelo-production-static-backend-9f8e7d6\n")],
855
857
  "compute firewall-rules list": [ok("[]")],
@@ -1145,3 +1147,28 @@ describe("liveDirectVpc / planNoVpc (#1328)", () => {
1145
1147
  expect(planNoVpc(false)).toEqual({ ok: true, flags: [], changes: [] });
1146
1148
  });
1147
1149
  });
1150
+
1151
+ describe("planMaxInstances (#1463)", () => {
1152
+ const described = (annotations: Record<string, string>) =>
1153
+ JSON.stringify({ spec: { template: { metadata: { annotations } } } });
1154
+
1155
+ it("reads the revision template's scale-out, null when unset", () => {
1156
+ expect(liveMaxInstances(described({ "autoscaling.knative.dev/maxScale": "100" }))).toBe(100);
1157
+ expect(liveMaxInstances(described({}))).toBeNull();
1158
+ });
1159
+
1160
+ it("lowers a value above the budget, an unset one included", () => {
1161
+ expect(planMaxInstances(100, 10)).toEqual({
1162
+ ok: true,
1163
+ flags: ["--max-instances=10"],
1164
+ changes: ["max instances: 100 → 10"],
1165
+ });
1166
+ expect(planMaxInstances(null, 10).flags).toEqual(["--max-instances=10"]);
1167
+ expect(planMaxInstances(Number.NaN, 10).flags).toEqual(["--max-instances=10"]);
1168
+ });
1169
+
1170
+ it("never raises what an operator lowered", () => {
1171
+ expect(planMaxInstances(3, 10).flags).toEqual([]);
1172
+ expect(planMaxInstances(10, 10).flags).toEqual([]);
1173
+ });
1174
+ });
@@ -27,6 +27,8 @@
27
27
  * timeout, in the same `services update`.
28
28
  * - {@link planCpuIdle}: request-based CPU where the contract wants it
29
29
  * (`SERVICE_CPU_IDLE`), in the same `services update`.
30
+ * - {@link planMaxInstances} (#1463): a gateway's scale-out down to what
31
+ * the connection budget allows, in the same `services update`.
30
32
  */
31
33
 
32
34
  import { isIpLiteral } from "@caelo-cms/shared";
@@ -1219,6 +1221,34 @@ export function planCpuIdle(live: boolean, desired: boolean): RollAdditionsPlan
1219
1221
  };
1220
1222
  }
1221
1223
 
1224
+ /**
1225
+ * The most instances a described service may start: the revision template's
1226
+ * `autoscaling.knative.dev/maxScale` annotation. Null without one, which is
1227
+ * Cloud Run's default of 100.
1228
+ */
1229
+ export function liveMaxInstances(serviceJson: string): number | null {
1230
+ const svc = JSON.parse(serviceJson) as {
1231
+ spec?: { template?: { metadata?: { annotations?: Record<string, string> } } };
1232
+ };
1233
+ const raw = svc.spec?.template?.metadata?.annotations?.["autoscaling.knative.dev/maxScale"];
1234
+ return raw === undefined ? null : Number(raw);
1235
+ }
1236
+
1237
+ /**
1238
+ * `--max-instances=<ceiling>` when the service may start more instances than
1239
+ * the connection budget has room for (#1463). Never raises the value: a roll
1240
+ * cannot see the stack's `gatewayMaxInstances`, and a lower live value is the
1241
+ * operator's. An unset or unreadable value counts as above the ceiling.
1242
+ */
1243
+ export function planMaxInstances(live: number | null, ceiling: number): RollAdditionsPlan {
1244
+ if (live !== null && live <= ceiling) return { ok: true, flags: [], changes: [] };
1245
+ return {
1246
+ ok: true,
1247
+ flags: [`--max-instances=${ceiling}`],
1248
+ changes: [`max instances: ${live ?? "(default 100)"} → ${ceiling}`],
1249
+ };
1250
+ }
1251
+
1222
1252
  /**
1223
1253
  * Whether the service's revision template egresses into a VPC (Direct VPC
1224
1254
  * egress, the stacks' `vpcAccess.networkInterfaces`).
@@ -150,7 +150,7 @@ describe("the gcp-firebase edge: a second Hosting site", () => {
150
150
  expect(SITE.length).toBeLessThanOrEqual(30);
151
151
  });
152
152
 
153
- it("creates the site, one `**` rewrite to the staging gateway, the custom domain; deletes the old mapping", async () => {
153
+ it("creates the site, one `**` rewrite to the staging gateway, the custom domain; keeps the old mapping while the DNS has not moved", async () => {
154
154
  const { run, calls } = fakeGcloud({
155
155
  ...adminWith(LIVE_SITE),
156
156
  "auth print-access-token": ok("tok\n"),
@@ -204,6 +204,7 @@ describe("the gcp-firebase edge: a second Hosting site", () => {
204
204
  expect(r.dnsRecords).toEqual([
205
205
  { name: "staging.acme.com", type: "A", value: "199.36.158.100" },
206
206
  ]);
207
+ expect(r.domainMappingKept).toBe(true);
207
208
  const version = requests.find((q) => q.method === "POST" && q.url.endsWith("/versions"));
208
209
  expect(JSON.parse(version?.body ?? "{}")).toEqual({
209
210
  config: {
@@ -224,10 +225,58 @@ describe("the gcp-firebase edge: a second Hosting site", () => {
224
225
  q.method === "POST" && q.url.includes("customDomains?customDomainId=staging.acme.com"),
225
226
  ),
226
227
  ).toBe(true);
227
- // No second path to the staged files: the old mapping goes.
228
- expect(calls).toContainEqual(expect.stringMatching(/^beta run domain-mappings delete /));
228
+ // #1455 — the mapping holds the host's certificate until the DNS moved.
229
+ expect(calls.some((c) => c.startsWith("beta run domain-mappings delete"))).toBe(false);
229
230
  });
230
231
 
232
+ it.each([
233
+ ["OWNERSHIP_ACTIVE", true],
234
+ // DNS moved, but Hosting does not serve the host yet.
235
+ ["OWNERSHIP_PENDING", false],
236
+ ])(
237
+ "#1455 — old mapping with DNS on the staging site, ownership %s",
238
+ async (ownershipState, gone) => {
239
+ const { run, calls } = fakeGcloud({
240
+ ...adminWith(LIVE_SITE),
241
+ "auth print-access-token": ok("tok\n"),
242
+ "beta run domain-mappings describe": ok("staging.acme.com\n"),
243
+ "beta run domain-mappings delete": ok(),
244
+ });
245
+ const http: HttpFetch = async (url) => ({
246
+ ok: true,
247
+ status: 200,
248
+ text: async () =>
249
+ JSON.stringify({
250
+ ...(url.includes("/customDomains/") && !gone
251
+ ? {
252
+ requiredDnsUpdates: {
253
+ desired: [
254
+ { records: [{ domainName: "staging.acme.com.", type: "TXT", rdata: "tok" }] },
255
+ ],
256
+ },
257
+ }
258
+ : {}),
259
+ name: `sites/${SITE}/versions/v1`,
260
+ hostState: "HOST_ACTIVE",
261
+ ownershipState,
262
+ }),
263
+ });
264
+ const r = await ensureStagingGatewayEdge(
265
+ {
266
+ provider: "gcp-firebase",
267
+ projectId: "acme",
268
+ region: "europe-west1",
269
+ env: "production",
270
+ domain: "acme.com",
271
+ stagingHost: "staging.acme.com",
272
+ },
273
+ { run, http },
274
+ );
275
+ expect(r.ok && r.domainMappingKept).toBe(!gone);
276
+ expect(calls.some((c) => c.startsWith("beta run domain-mappings delete"))).toBe(gone);
277
+ },
278
+ );
279
+
231
280
  it("waits for the records Firebase works out after the custom domain is created", async () => {
232
281
  const { run } = fakeGcloud({
233
282
  ...adminWith(LIVE_SITE),
@@ -375,6 +424,9 @@ describe("the gcp edge: the staging host's own rule on the load balancer", () =>
375
424
  expect(r.dnsRecords).toEqual([
376
425
  { name: "staging.acme.com", type: "A", value: "136.81.196.111" },
377
426
  ]);
427
+ expect(calls.find((c) => c.startsWith("compute backend-services create"))).toContain(
428
+ "--protocol=HTTPS --port-name=http",
429
+ );
378
430
  expect(calls.find((c) => c.startsWith("compute backend-services create"))).not.toContain(
379
431
  "--security-policy",
380
432
  );
@@ -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,8 +920,12 @@ async function ensureGcpEdge(
884
920
  project,
885
921
  "--format=json",
886
922
  ]);
887
- let backendJson: { selfLink?: string; securityPolicy?: string; backends?: { group?: string }[] } =
888
- {};
923
+ let backendJson: {
924
+ selfLink?: string;
925
+ securityPolicy?: string;
926
+ portName?: string;
927
+ backends?: { group?: string }[];
928
+ } = {};
889
929
  if (!backend.ok) {
890
930
  if (!isGcloudNotFound(backend.stderr)) {
891
931
  return fail(`describe ${names.backend}: ${backend.stderr.trim()}`);
@@ -898,7 +938,7 @@ async function ensureGcpEdge(
898
938
  "--global",
899
939
  project,
900
940
  "--load-balancing-scheme=EXTERNAL_MANAGED",
901
- "--protocol=HTTPS",
941
+ ...SERVERLESS_BACKEND_CREATE_FLAGS,
902
942
  "--format=json",
903
943
  "--quiet",
904
944
  ]);
@@ -909,6 +949,13 @@ async function ensureGcpEdge(
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`);
912
959
  // `backend-services create` has no --security-policy: `update` attaches it,
913
960
  // here and on a backend an earlier run left without one. The URL map is
914
961
  // only pointed at this backend afterwards, so it is never served unguarded.
@@ -1089,7 +1136,12 @@ async function ensureGcpEdge(
1089
1136
  `expected one external address for ${t.stagingHost}, found ${ips.join(", ") || "none"}`,
1090
1137
  );
1091
1138
  }
1092
- return { ok: true, done, dnsRecords: [{ name: t.stagingHost, type: "A", value: ip }] };
1139
+ return {
1140
+ ok: true,
1141
+ done,
1142
+ dnsRecords: [{ name: t.stagingHost, type: "A", value: ip }],
1143
+ domainMappingKept: false,
1144
+ };
1093
1145
  }
1094
1146
 
1095
1147
  /** An OAuth access token as gcloud prints one: base64url-ish characters only. */
@@ -29,33 +29,35 @@ export type AttachResult =
29
29
  /** Install ids are `<provider>-<slug>` (install-state.ts deriveInstallId). */
30
30
  const INSTALL_ID = /^[a-z0-9][a-z0-9-]{0,80}$/;
31
31
 
32
+ /** The install record in a project's ops bucket, checked. */
33
+ export type ProjectInstallRecord =
34
+ | {
35
+ readonly ok: true;
36
+ readonly installId: string;
37
+ readonly domain: string;
38
+ /** install.json exactly as the bucket held it. */
39
+ readonly text: string;
40
+ }
41
+ | { readonly ok: false; readonly error: string };
42
+
32
43
  /**
33
- * Attach the install in `projectId` to this machine.
34
- *
35
- * @param deps.run gcloud runner (tests pass a fake bucket)
36
- * @param deps.rootFor `~/.caelo-<id>` for an install id
37
- * @param deps.hasLocalState whether a dir holds a local Pulumi stack
44
+ * Read and check `gs://<project>-caelo-ops/install/install.json`, touching
45
+ * nothing on this machine: shared by `attach` and `status --project`, which
46
+ * has to work with no local install directory at all (#822).
38
47
  */
39
- export function attachInstall(
40
- projectId: string,
41
- deps: {
42
- run: SyncGcloud;
43
- rootFor: (installId: string) => string;
44
- hasLocalState: (root: string) => boolean;
45
- },
46
- ): AttachResult {
48
+ export function readProjectInstall(projectId: string, run: SyncGcloud): ProjectInstallRecord {
47
49
  const bucket = opsBucketName(projectId);
48
50
  let text: string | null;
49
51
  try {
50
52
  // Peek: the directory to mirror into isn't known (or checked) yet.
51
- text = new GcsStateStore(bucket, "/nonexistent", deps.run).peek("install.json");
53
+ text = new GcsStateStore(bucket, "/nonexistent", run).peek("install.json");
52
54
  } catch (e) {
53
55
  return { ok: false, error: e instanceof Error ? e.message : String(e) };
54
56
  }
55
57
  if (text === null) {
56
58
  return {
57
59
  ok: false,
58
- error: `gs://${bucket} holds no install.json. If this install's state is still on the machine that installed it, run \`${selfCommand("state", "migrate")}\` there first.`,
60
+ error: `gs://${bucket} holds no install.json. Check the project id. If this install's state is still on the machine that installed it, run \`${selfCommand("state", "migrate")}\` there first.`,
59
61
  };
60
62
  }
61
63
  let remote: {
@@ -95,6 +97,34 @@ export function attachInstall(
95
97
  };
96
98
  }
97
99
 
100
+ return {
101
+ ok: true,
102
+ installId,
103
+ domain: typeof remote.domain === "string" ? remote.domain : installId,
104
+ text,
105
+ };
106
+ }
107
+
108
+ /**
109
+ * Attach the install in `projectId` to this machine.
110
+ *
111
+ * @param deps.run gcloud runner (tests pass a fake bucket)
112
+ * @param deps.rootFor `~/.caelo-<id>` for an install id
113
+ * @param deps.hasLocalState whether a dir holds a local Pulumi stack
114
+ */
115
+ export function attachInstall(
116
+ projectId: string,
117
+ deps: {
118
+ run: SyncGcloud;
119
+ rootFor: (installId: string) => string;
120
+ hasLocalState: (root: string) => boolean;
121
+ },
122
+ ): AttachResult {
123
+ const bucket = opsBucketName(projectId);
124
+ const record = readProjectInstall(projectId, deps.run);
125
+ if (!record.ok) return record;
126
+ const { installId, domain, text } = record;
127
+
98
128
  const root = deps.rootFor(installId);
99
129
  const localText = new LocalStateStore(root).read("install.json");
100
130
  // Local Pulumi state blocks the attach whether or not an install.json
@@ -126,7 +156,7 @@ export function attachInstall(
126
156
  return {
127
157
  ok: true,
128
158
  installId,
129
- domain: typeof remote.domain === "string" ? remote.domain : installId,
159
+ domain,
130
160
  status,
131
161
  };
132
162
  }