@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
@@ -644,6 +644,8 @@ describe("gcp load balancer (remote-mcp-edge)", () => {
644
644
 
645
645
  it("covers exactly the broker's paths; a traversal never borrows the MCP rule", async () => {
646
646
  // RE2 and JS agree on this pattern (anchors, alternation, classes only).
647
+ // Cloud Armor refuses capture groups (scratch install of v0.11.17).
648
+ expect(MCP_ARMOR_PATH_PATTERN).not.toMatch(/\((?!\?:)/);
647
649
  const re = new RegExp(MCP_ARMOR_PATH_PATTERN);
648
650
  for (const p of [
649
651
  "/api/mcp/chat",
@@ -791,7 +793,8 @@ describe("gcp load balancer (remote-mcp-edge)", () => {
791
793
  expect(planUrlMapPaths([], "acme.com", PROXY_BACKEND).ok).toBe(false);
792
794
  });
793
795
 
794
- const policyJson = (rules: object[]) => ok(JSON.stringify({ rules }));
796
+ // As real gcloud prints it: a one-element list.
797
+ const policyJson = (rules: object[]) => ok(JSON.stringify([{ rules }]));
795
798
  const PROXY_POLICY = "caelo-production-mcp-auth-proxy-armor";
796
799
 
797
800
  it("#1328 — creates the proxy's own policy and its rule when missing", async () => {
@@ -870,6 +873,7 @@ describe("gcp load balancer (remote-mcp-edge)", () => {
870
873
  "compute network-endpoint-groups create": ok(),
871
874
  "compute backend-services describe": fail("NOT_FOUND: was not found"),
872
875
  "compute backend-services create": ok(JSON.stringify([{ selfLink: PROXY_BACKEND }])),
876
+ "compute backend-services update": ok(),
873
877
  "compute backend-services add-backend": ok(),
874
878
  });
875
879
  const r = await ensureMcpAuthProxyBackend(target, missing);
@@ -877,7 +881,12 @@ describe("gcp load balancer (remote-mcp-edge)", () => {
877
881
  expect(missing.calls).toContain(
878
882
  "compute network-endpoint-groups create caelo-production-mcp-auth-proxy-neg --region=europe-west1 --project=acme --network-endpoint-type=serverless --cloud-run-service=caelo-production-mcp-auth-proxy --quiet",
879
883
  );
880
- expect(missing.calls.find((c) => c.startsWith("compute backend-services create"))).toContain(
884
+ // `backend-services create` has no --security-policy flag (scratch
885
+ // install of v0.11.17, 2026-11-05): `update` attaches the policy.
886
+ expect(
887
+ missing.calls.find((c) => c.startsWith("compute backend-services create")),
888
+ ).not.toContain("--security-policy");
889
+ expect(missing.calls.find((c) => c.startsWith("compute backend-services update"))).toContain(
881
890
  `--security-policy=${PROXY_POLICY}`,
882
891
  );
883
892
  expect(
@@ -901,6 +910,58 @@ describe("gcp load balancer (remote-mcp-edge)", () => {
901
910
  });
902
911
  const again = await ensureMcpAuthProxyBackend(target, present);
903
912
  expect(again).toEqual({ ok: true, backend: PROXY_BACKEND, done: [] });
913
+
914
+ // A backend an earlier run left without its policy gets it attached.
915
+ const bare = fakeGcloud({
916
+ "compute network-endpoint-groups describe": ok("caelo-production-mcp-auth-proxy-neg\n"),
917
+ "compute backend-services describe": ok(
918
+ JSON.stringify({
919
+ selfLink: PROXY_BACKEND,
920
+ backends: [{ group: "x/networkEndpointGroups/caelo-production-mcp-auth-proxy-neg" }],
921
+ }),
922
+ ),
923
+ "compute backend-services update": ok(),
924
+ });
925
+ expect((await ensureMcpAuthProxyBackend(target, bare)).ok).toBe(true);
926
+ expect(bare.calls.find((c) => c.startsWith("compute backend-services update"))).toContain(
927
+ `--security-policy=${PROXY_POLICY}`,
928
+ );
929
+ });
930
+
931
+ it("creates the backend with the http port name a serverless NEG needs", async () => {
932
+ const missing = fakeGcloud({
933
+ "compute network-endpoint-groups describe": ok("caelo-production-mcp-auth-proxy-neg\n"),
934
+ "compute backend-services describe": fail("NOT_FOUND: was not found"),
935
+ "compute backend-services create": ok(JSON.stringify([{ selfLink: PROXY_BACKEND }])),
936
+ });
937
+ await ensureMcpAuthProxyBackend(
938
+ { projectId: "acme", region: "europe-west1", env: "production" },
939
+ missing,
940
+ );
941
+ expect(missing.calls.find((c) => c.startsWith("compute backend-services create"))).toContain(
942
+ "--protocol=HTTPS --port-name=http",
943
+ );
944
+ });
945
+
946
+ it("repairs a backend an earlier run left with the https port name, before add-backend", async () => {
947
+ const left = fakeGcloud({
948
+ "compute network-endpoint-groups describe": ok("caelo-production-mcp-auth-proxy-neg\n"),
949
+ "compute backend-services describe": ok(
950
+ JSON.stringify({ selfLink: PROXY_BACKEND, portName: "https", backends: [] }),
951
+ ),
952
+ "compute backend-services update": ok(),
953
+ "compute backend-services add-backend": ok(),
954
+ });
955
+ const r = await ensureMcpAuthProxyBackend(
956
+ { projectId: "acme", region: "europe-west1", env: "production" },
957
+ left,
958
+ );
959
+ expect(r.ok).toBe(true);
960
+ const writes = left.calls.filter((c) =>
961
+ /^compute backend-services (update|add-backend)/.test(c),
962
+ );
963
+ expect(writes[0]).toContain("--port-name=http");
964
+ expect(writes.at(-1)).toContain("add-backend");
904
965
  });
905
966
 
906
967
  it("#1328 — ensureRemoteMcpEdge: service, policy, backend, URL map, then the gateway rule; no-op on gcp-firebase", async () => {
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,32 +754,40 @@ export async function ensureMcpAuthProxyBackend(
739
754
  "--global",
740
755
  project,
741
756
  "--load-balancing-scheme=EXTERNAL_MANAGED",
742
- "--protocol=HTTPS",
743
- `--security-policy=${names.policy}`,
757
+ ...SERVERLESS_BACKEND_CREATE_FLAGS,
744
758
  "--format=json",
745
759
  "--quiet",
746
760
  ]);
747
761
  if (!created.ok)
748
762
  return { ok: false, error: `create ${names.backend}: ${created.stderr.trim()}` };
749
- done.push(`created backend service ${names.backend} (Cloud Armor ${names.policy})`);
763
+ done.push(`created backend service ${names.backend}`);
750
764
  const parsed = parseJson(created.stdout);
751
765
  backendJson = (Array.isArray(parsed) ? parsed[0] : parsed) ?? {};
752
766
  } else {
753
767
  backendJson = (parseJson(backend.stdout) ?? {}) as typeof backendJson;
754
- if (!backendJson.securityPolicy?.endsWith(`/securityPolicies/${names.policy}`)) {
755
- const set = await run([
756
- "compute",
757
- "backend-services",
758
- "update",
759
- names.backend,
760
- "--global",
761
- project,
762
- `--security-policy=${names.policy}`,
763
- "--quiet",
764
- ]);
765
- if (!set.ok) return { ok: false, error: `attach ${names.policy}: ${set.stderr.trim()}` };
766
- done.push(`attached Cloud Armor ${names.policy} to ${names.backend}`);
767
- }
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`);
776
+ // `backend-services create` has no --security-policy: `update` attaches it,
777
+ // here and on a backend an earlier run left without one.
778
+ if (!backendJson.securityPolicy?.endsWith(`/securityPolicies/${names.policy}`)) {
779
+ const set = await run([
780
+ "compute",
781
+ "backend-services",
782
+ "update",
783
+ names.backend,
784
+ "--global",
785
+ project,
786
+ `--security-policy=${names.policy}`,
787
+ "--quiet",
788
+ ]);
789
+ if (!set.ok) return { ok: false, error: `attach ${names.policy}: ${set.stderr.trim()}` };
790
+ done.push(`attached Cloud Armor ${names.policy} to ${names.backend}`);
768
791
  }
769
792
  if (
770
793
  !(backendJson.backends ?? []).some((b) =>
@@ -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),
@@ -340,6 +389,88 @@ describe("the gcp edge: the staging host's own rule on the load balancer", () =>
340
389
  ]);
341
390
  });
342
391
 
392
+ it("creates the backend, attaches Cloud Armor by update, and names the one external address", async () => {
393
+ const proxy = "caelo-production-https-proxy-1";
394
+ const { run, calls } = fakeGcloud({
395
+ "compute network-endpoint-groups describe": fail("NOT_FOUND: was not found"),
396
+ "compute network-endpoint-groups create": ok(),
397
+ "compute security-policies list": ok("caelo-production-waf-1\n"),
398
+ "compute backend-services describe": fail("NOT_FOUND: was not found"),
399
+ "compute backend-services create": ok(JSON.stringify([{ selfLink: BACKEND }])),
400
+ "compute backend-services update": ok(),
401
+ "compute backend-services add-backend": ok(),
402
+ "compute ssl-certificates describe": ok("{}"),
403
+ // Routed already: the REST update of the map has its own tests.
404
+ "compute url-maps list": ok(JSON.stringify([planStagingHostRule(map, t, BACKEND)])),
405
+ "compute target-https-proxies list": ok(
406
+ JSON.stringify([{ name: proxy, sslCertificates: [] }]),
407
+ ),
408
+ "compute target-https-proxies update": ok(),
409
+ "compute url-maps import": ok(),
410
+ "compute addresses list": ok("136.81.196.111\n"),
411
+ });
412
+ const r = await ensureStagingGatewayEdge(
413
+ {
414
+ provider: "gcp",
415
+ projectId: "acme",
416
+ region: "europe-west1",
417
+ env: "production",
418
+ domain: "acme.com",
419
+ stagingHost: "staging.acme.com",
420
+ },
421
+ { run },
422
+ );
423
+ if (!r.ok) throw new Error(r.error);
424
+ expect(r.dnsRecords).toEqual([
425
+ { name: "staging.acme.com", type: "A", value: "136.81.196.111" },
426
+ ]);
427
+ expect(calls.find((c) => c.startsWith("compute backend-services create"))).toContain(
428
+ "--protocol=HTTPS --port-name=http",
429
+ );
430
+ expect(calls.find((c) => c.startsWith("compute backend-services create"))).not.toContain(
431
+ "--security-policy",
432
+ );
433
+ expect(calls.find((c) => c.startsWith("compute backend-services update"))).toContain(
434
+ "--security-policy=",
435
+ );
436
+ expect(calls.find((c) => c.startsWith("compute addresses list"))).toContain(
437
+ "addressType=EXTERNAL",
438
+ );
439
+ });
440
+
441
+ it("attaches Cloud Armor to a backend an earlier run left without one", async () => {
442
+ const edge = (backendJson: unknown) =>
443
+ fakeGcloud({
444
+ "compute security-policies list": ok("caelo-production-waf-1\n"),
445
+ "compute backend-services describe": ok(JSON.stringify(backendJson)),
446
+ "compute ssl-certificates describe": ok("{}"),
447
+ "compute url-maps list": ok(JSON.stringify([planStagingHostRule(map, t, BACKEND)])),
448
+ "compute target-https-proxies list": ok(JSON.stringify([{ name: "proxy" }])),
449
+ "compute addresses list": ok("136.81.196.111\n"),
450
+ });
451
+ const target = {
452
+ provider: "gcp" as const,
453
+ projectId: "acme",
454
+ region: "europe-west1",
455
+ env: "production",
456
+ domain: "acme.com",
457
+ stagingHost: "staging.acme.com",
458
+ };
459
+ const bare = edge({ selfLink: BACKEND });
460
+ expect((await ensureStagingGatewayEdge(target, { run: bare.run })).ok).toBe(true);
461
+ expect(bare.calls.find((c) => c.startsWith("compute backend-services update"))).toContain(
462
+ "--security-policy=caelo-production-waf-1",
463
+ );
464
+
465
+ const guarded = edge({
466
+ selfLink: BACKEND,
467
+ securityPolicy:
468
+ "https://compute/projects/acme/global/securityPolicies/caelo-production-waf-1",
469
+ });
470
+ expect((await ensureStagingGatewayEdge(target, { run: guarded.run })).ok).toBe(true);
471
+ expect(guarded.calls.some((c) => c.startsWith("compute backend-services update"))).toBe(false);
472
+ });
473
+
343
474
  it("is a no-op when the map already routes it, and moves a changed staging host", () => {
344
475
  const routed = planStagingHostRule(map, t, BACKEND);
345
476
  if (!routed) throw new Error("expected a plan");