@caelo-cms/provisioning 0.11.17 → 0.11.19

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.
@@ -228,6 +228,66 @@ describe("the gcp-firebase edge: a second Hosting site", () => {
228
228
  expect(calls).toContainEqual(expect.stringMatching(/^beta run domain-mappings delete /));
229
229
  });
230
230
 
231
+ it("waits for the records Firebase works out after the custom domain is created", async () => {
232
+ const { run } = fakeGcloud({
233
+ ...adminWith(LIVE_SITE),
234
+ "auth print-access-token": ok("tok\n"),
235
+ "beta run domain-mappings describe": fail("ERROR: Cannot find mapping [staging.acme.com]"),
236
+ });
237
+ let domainReads = 0;
238
+ const sleeps: number[] = [];
239
+ const http: HttpFetch = async (url, init) => {
240
+ const json = (status: number, body: unknown) => ({
241
+ ok: status < 400,
242
+ status,
243
+ text: async () => JSON.stringify(body),
244
+ });
245
+ if (init.method === "GET" && url.includes("/customDomains/staging.acme.com")) {
246
+ domainReads++;
247
+ // Not there yet, then created by this run: the first reads carry no records.
248
+ if (domainReads === 1) return json(404, {});
249
+ return json(
250
+ 200,
251
+ domainReads < 4
252
+ ? {}
253
+ : {
254
+ requiredDnsUpdates: {
255
+ desired: [
256
+ {
257
+ records: [
258
+ { domainName: "staging.acme.com.", type: "CNAME", rdata: "stg.web.app." },
259
+ ],
260
+ },
261
+ ],
262
+ },
263
+ },
264
+ );
265
+ }
266
+ if (url.includes("/channels/live/releases")) return json(404, {});
267
+ if (init.method === "POST" && url.includes("/versions")) {
268
+ return json(200, { name: `sites/${SITE}/versions/v1` });
269
+ }
270
+ return json(200, {});
271
+ };
272
+ const r = await ensureStagingGatewayEdge(
273
+ {
274
+ provider: "gcp-firebase",
275
+ projectId: "acme",
276
+ region: "europe-west1",
277
+ env: "production",
278
+ domain: "acme.com",
279
+ stagingHost: "staging.acme.com",
280
+ },
281
+ { run, http, sleep: async (ms) => void sleeps.push(ms) },
282
+ );
283
+ expect(r.ok).toBe(true);
284
+ if (!r.ok) return;
285
+ expect(r.dnsRecords).toEqual([
286
+ { name: "staging.acme.com", type: "CNAME", value: "stg.web.app." },
287
+ ]);
288
+ expect(sleeps).toHaveLength(2);
289
+ });
290
+
231
291
  it("a site already serving the rewrite is not released again", () => {
232
292
  const t = { env: "production", region: "europe-west1" };
233
293
  expect(isFirebaseStagingConfig(firebaseStagingSiteConfig(t), t)).toBe(true);
@@ -280,6 +340,85 @@ describe("the gcp edge: the staging host's own rule on the load balancer", () =>
280
340
  ]);
281
341
  });
282
342
 
343
+ it("creates the backend, attaches Cloud Armor by update, and names the one external address", async () => {
344
+ const proxy = "caelo-production-https-proxy-1";
345
+ const { run, calls } = fakeGcloud({
346
+ "compute network-endpoint-groups describe": fail("NOT_FOUND: was not found"),
347
+ "compute network-endpoint-groups create": ok(),
348
+ "compute security-policies list": ok("caelo-production-waf-1\n"),
349
+ "compute backend-services describe": fail("NOT_FOUND: was not found"),
350
+ "compute backend-services create": ok(JSON.stringify([{ selfLink: BACKEND }])),
351
+ "compute backend-services update": ok(),
352
+ "compute backend-services add-backend": ok(),
353
+ "compute ssl-certificates describe": ok("{}"),
354
+ // Routed already: the REST update of the map has its own tests.
355
+ "compute url-maps list": ok(JSON.stringify([planStagingHostRule(map, t, BACKEND)])),
356
+ "compute target-https-proxies list": ok(
357
+ JSON.stringify([{ name: proxy, sslCertificates: [] }]),
358
+ ),
359
+ "compute target-https-proxies update": ok(),
360
+ "compute url-maps import": ok(),
361
+ "compute addresses list": ok("136.81.196.111\n"),
362
+ });
363
+ const r = await ensureStagingGatewayEdge(
364
+ {
365
+ provider: "gcp",
366
+ projectId: "acme",
367
+ region: "europe-west1",
368
+ env: "production",
369
+ domain: "acme.com",
370
+ stagingHost: "staging.acme.com",
371
+ },
372
+ { run },
373
+ );
374
+ if (!r.ok) throw new Error(r.error);
375
+ expect(r.dnsRecords).toEqual([
376
+ { name: "staging.acme.com", type: "A", value: "136.81.196.111" },
377
+ ]);
378
+ expect(calls.find((c) => c.startsWith("compute backend-services create"))).not.toContain(
379
+ "--security-policy",
380
+ );
381
+ expect(calls.find((c) => c.startsWith("compute backend-services update"))).toContain(
382
+ "--security-policy=",
383
+ );
384
+ expect(calls.find((c) => c.startsWith("compute addresses list"))).toContain(
385
+ "addressType=EXTERNAL",
386
+ );
387
+ });
388
+
389
+ it("attaches Cloud Armor to a backend an earlier run left without one", async () => {
390
+ const edge = (backendJson: unknown) =>
391
+ fakeGcloud({
392
+ "compute security-policies list": ok("caelo-production-waf-1\n"),
393
+ "compute backend-services describe": ok(JSON.stringify(backendJson)),
394
+ "compute ssl-certificates describe": ok("{}"),
395
+ "compute url-maps list": ok(JSON.stringify([planStagingHostRule(map, t, BACKEND)])),
396
+ "compute target-https-proxies list": ok(JSON.stringify([{ name: "proxy" }])),
397
+ "compute addresses list": ok("136.81.196.111\n"),
398
+ });
399
+ const target = {
400
+ provider: "gcp" as const,
401
+ projectId: "acme",
402
+ region: "europe-west1",
403
+ env: "production",
404
+ domain: "acme.com",
405
+ stagingHost: "staging.acme.com",
406
+ };
407
+ const bare = edge({ selfLink: BACKEND });
408
+ expect((await ensureStagingGatewayEdge(target, { run: bare.run })).ok).toBe(true);
409
+ expect(bare.calls.find((c) => c.startsWith("compute backend-services update"))).toContain(
410
+ "--security-policy=caelo-production-waf-1",
411
+ );
412
+
413
+ const guarded = edge({
414
+ selfLink: BACKEND,
415
+ securityPolicy:
416
+ "https://compute/projects/acme/global/securityPolicies/caelo-production-waf-1",
417
+ });
418
+ expect((await ensureStagingGatewayEdge(target, { run: guarded.run })).ok).toBe(true);
419
+ expect(guarded.calls.some((c) => c.startsWith("compute backend-services update"))).toBe(false);
420
+ });
421
+
283
422
  it("is a no-op when the map already routes it, and moves a changed staging host", () => {
284
423
  const routed = planStagingHostRule(map, t, BACKEND);
285
424
  if (!routed) throw new Error("expected a plan");
@@ -497,6 +497,9 @@ export async function ensureStagingGatewayEdge(
497
497
  // --- gcp-firebase ----------------------------------------------------------
498
498
 
499
499
  const FIREBASE_HOSTING_API = "https://firebasehosting.googleapis.com/v1beta1";
500
+ /** How often, and how far apart, a new custom domain is re-read for its records. */
501
+ const FIREBASE_DNS_POLLS = 12;
502
+ const FIREBASE_DNS_POLL_MS = 5_000;
500
503
 
501
504
  /** The config of the staging site's only version: every path to the staging gateway. */
502
505
  export function firebaseStagingSiteConfig(t: Pick<StagingGatewayTarget, "env" | "region">): {
@@ -639,7 +642,8 @@ async function ensureFirebaseStagingSite(
639
642
  // 3. The staging host as its custom domain.
640
643
  const domainPath = `projects/${project}/sites/${site}/customDomains/${encodeURIComponent(t.stagingHost)}`;
641
644
  let domain = await call(domainPath);
642
- if (domain.status === 404) {
645
+ const createdDomain = domain.status === 404;
646
+ if (createdDomain) {
643
647
  const created = await call(
644
648
  `projects/${project}/sites/${site}/customDomains?customDomainId=${encodeURIComponent(t.stagingHost)}`,
645
649
  "POST",
@@ -658,6 +662,27 @@ async function ensureFirebaseStagingSite(
658
662
  `read ${t.stagingHost} on ${site}: HTTP ${domain.status} ${domain.text.slice(0, 300)}`,
659
663
  );
660
664
  }
665
+ // Firebase works out the records a new custom domain needs a few seconds
666
+ // after it is created; read straight away, the list is empty and the
667
+ // install printed no record for the staging host (scratch install of
668
+ // v0.11.16, 2026-11-04).
669
+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
670
+ let dnsRecords = firebaseDesiredRecords(domain.json);
671
+ for (let i = 0; createdDomain && dnsRecords.length === 0 && i < FIREBASE_DNS_POLLS; i++) {
672
+ await sleep(FIREBASE_DNS_POLL_MS);
673
+ const again = await call(domainPath);
674
+ if (!again.ok) {
675
+ return fail(
676
+ `read ${t.stagingHost} on ${site}: HTTP ${again.status} ${again.text.slice(0, 300)}`,
677
+ );
678
+ }
679
+ dnsRecords = firebaseDesiredRecords(again.json);
680
+ }
681
+ if (createdDomain && dnsRecords.length === 0) {
682
+ return fail(
683
+ `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
+ );
685
+ }
661
686
 
662
687
  // 4. The old route: the Cloud Run domain mapping (#650) to the service
663
688
  // that is now the MCP-Auth-Proxy. Nothing but the gate may lead to the
@@ -666,7 +691,7 @@ async function ensureFirebaseStagingSite(
666
691
  if (!mapping.ok) return fail(mapping.error);
667
692
  if (mapping.deleted) done.push(`deleted the Cloud Run domain mapping of ${t.stagingHost}`);
668
693
 
669
- return { ok: true, done, dnsRecords: firebaseDesiredRecords(domain.json) };
694
+ return { ok: true, done, dnsRecords };
670
695
  }
671
696
 
672
697
  /**
@@ -859,7 +884,8 @@ async function ensureGcpEdge(
859
884
  project,
860
885
  "--format=json",
861
886
  ]);
862
- let backendJson: { selfLink?: string; backends?: { group?: string }[] } = {};
887
+ let backendJson: { selfLink?: string; securityPolicy?: string; backends?: { group?: string }[] } =
888
+ {};
863
889
  if (!backend.ok) {
864
890
  if (!isGcloudNotFound(backend.stderr)) {
865
891
  return fail(`describe ${names.backend}: ${backend.stderr.trim()}`);
@@ -873,17 +899,33 @@ async function ensureGcpEdge(
873
899
  project,
874
900
  "--load-balancing-scheme=EXTERNAL_MANAGED",
875
901
  "--protocol=HTTPS",
876
- `--security-policy=${policy}`,
877
902
  "--format=json",
878
903
  "--quiet",
879
904
  ]);
880
905
  if (!created.ok) return fail(`create ${names.backend}: ${created.stderr.trim()}`);
881
- done.push(`created backend service ${names.backend} (Cloud Armor ${policy})`);
906
+ done.push(`created backend service ${names.backend}`);
882
907
  const parsed = safeJson(created.stdout);
883
908
  backendJson = ((Array.isArray(parsed) ? parsed[0] : parsed) ?? {}) as typeof backendJson;
884
909
  } else {
885
910
  backendJson = (safeJson(backend.stdout) ?? {}) as typeof backendJson;
886
911
  }
912
+ // `backend-services create` has no --security-policy: `update` attaches it,
913
+ // here and on a backend an earlier run left without one. The URL map is
914
+ // only pointed at this backend afterwards, so it is never served unguarded.
915
+ if (!backendJson.securityPolicy?.endsWith(`/securityPolicies/${policy}`)) {
916
+ const set = await run([
917
+ "compute",
918
+ "backend-services",
919
+ "update",
920
+ names.backend,
921
+ "--global",
922
+ project,
923
+ `--security-policy=${policy}`,
924
+ "--quiet",
925
+ ]);
926
+ if (!set.ok) return fail(`attach ${policy} to ${names.backend}: ${set.stderr.trim()}`);
927
+ done.push(`attached Cloud Armor ${policy} to ${names.backend}`);
928
+ }
887
929
  if (
888
930
  !(backendJson.backends ?? []).some((b) =>
889
931
  b.group?.endsWith(`/networkEndpointGroups/${names.neg}`),
@@ -1031,21 +1073,23 @@ async function ensureGcpEdge(
1031
1073
  "list",
1032
1074
  "--global",
1033
1075
  project,
1034
- `--filter=name~^${gcpNamePrefix(t.env)}`,
1076
+ // EXTERNAL: the stack's other global address is the database's private
1077
+ // range, and with two matches the install printed no record at all.
1078
+ `--filter=name~^${gcpNamePrefix(t.env)} AND addressType=EXTERNAL`,
1035
1079
  "--format=value(address)",
1036
1080
  ]);
1037
- const ips = address.ok
1038
- ? address.stdout
1039
- .split("\n")
1040
- .map((s) => s.trim())
1041
- .filter(Boolean)
1042
- : [];
1043
- return {
1044
- ok: true,
1045
- done,
1046
- dnsRecords:
1047
- ips.length === 1 ? [{ name: t.stagingHost, type: "A", value: ips[0] as string }] : [],
1048
- };
1081
+ if (!address.ok) return fail(`list the load balancer's address: ${address.stderr.trim()}`);
1082
+ const ips = address.stdout
1083
+ .split("\n")
1084
+ .map((s) => s.trim())
1085
+ .filter(Boolean);
1086
+ const [ip, ...others] = ips;
1087
+ if (!ip || others.length > 0) {
1088
+ return fail(
1089
+ `expected one external address for ${t.stagingHost}, found ${ips.join(", ") || "none"}`,
1090
+ );
1091
+ }
1092
+ return { ok: true, done, dnsRecords: [{ name: t.stagingHost, type: "A", value: ip }] };
1049
1093
  }
1050
1094
 
1051
1095
  /** An OAuth access token as gcloud prints one: base64url-ish characters only. */
@@ -468,7 +468,7 @@ export function startConverge(
468
468
  domain: install.domain,
469
469
  stagingHost: install.stagingHost,
470
470
  },
471
- { run, ...(deps.http ? { http: deps.http } : {}) },
471
+ { ...runDeps, ...(deps.http ? { http: deps.http } : {}) },
472
472
  );
473
473
  for (const line of edge.done) r.info(` ${line}`);
474
474
  if (edge.ok) {
@@ -1162,7 +1162,7 @@ describe("upgradeGcpInstall — converge, then app-roll", () => {
1162
1162
  );
1163
1163
  const backend = indexOf(
1164
1164
  events,
1165
- /^gcloud compute backend-services create caelo-production-mcp-auth-proxy-backend .*--security-policy=caelo-production-mcp-auth-proxy-armor/,
1165
+ /^gcloud compute backend-services update caelo-production-mcp-auth-proxy-backend .*--security-policy=caelo-production-mcp-auth-proxy-armor/,
1166
1166
  );
1167
1167
  const retire = indexOf(
1168
1168
  events,
@@ -2635,7 +2635,8 @@ async function stepFinalize(installId: string, setupLink: "print" | "secret"): P
2635
2635
  "",
2636
2636
  bold("Protected staging site:"),
2637
2637
  ` ${cyan(installStagingHost(meta))} is served by the staging gateway behind the staging gate,`,
2638
- " once the DNS records printed above (also under Settings → Updates) point at it.",
2638
+ " once the staging gateway step above reported ready and the DNS record it printed",
2639
+ " (also under Settings → Updates) points at it.",
2639
2640
  ` To turn on password protection and print the staging login once, run`,
2640
2641
  ` ${dim(selfCommand("staging-domain", "enable"))}`,
2641
2642
  " The host serves pages after the first Stage.",