@caelo-cms/provisioning 0.11.14 → 0.11.15

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 (41) hide show
  1. package/dist/__tests__/stack-under-mocks.d.ts +2 -0
  2. package/dist/__tests__/stack-under-mocks.d.ts.map +1 -0
  3. package/dist/__tests__/stack-under-mocks.js +59 -0
  4. package/dist/__tests__/stack-under-mocks.js.map +1 -0
  5. package/dist/deployed-release.d.ts.map +1 -1
  6. package/dist/deployed-release.js +4 -2
  7. package/dist/deployed-release.js.map +1 -1
  8. package/dist/gateway-bootstrap.d.ts +68 -0
  9. package/dist/gateway-bootstrap.d.ts.map +1 -0
  10. package/dist/gateway-bootstrap.js +145 -0
  11. package/dist/gateway-bootstrap.js.map +1 -0
  12. package/dist/stack-gateways.d.ts +31 -0
  13. package/dist/stack-gateways.d.ts.map +1 -0
  14. package/dist/stack-gateways.js +40 -0
  15. package/dist/stack-gateways.js.map +1 -0
  16. package/dist/state-command.d.ts.map +1 -1
  17. package/dist/state-command.js +3 -0
  18. package/dist/state-command.js.map +1 -1
  19. package/dist/wizards/gcp-pulumi.d.ts +7 -1
  20. package/dist/wizards/gcp-pulumi.d.ts.map +1 -1
  21. package/dist/wizards/gcp-pulumi.js +2 -0
  22. package/dist/wizards/gcp-pulumi.js.map +1 -1
  23. package/dist/wizards/gcp.d.ts.map +1 -1
  24. package/dist/wizards/gcp.js +120 -13
  25. package/dist/wizards/gcp.js.map +1 -1
  26. package/package.json +2 -2
  27. package/src/__tests__/stack-under-mocks.ts +69 -0
  28. package/src/deployed-release.test.ts +16 -0
  29. package/src/deployed-release.ts +4 -2
  30. package/src/gateway-bootstrap.test.ts +381 -0
  31. package/src/gateway-bootstrap.ts +195 -0
  32. package/src/gcp-url-map.test.ts +1 -1
  33. package/src/remote-mcp-stack-config.test.ts +2 -1
  34. package/src/stack-cloud-run-names.test.ts +49 -0
  35. package/src/stack-gateways.ts +39 -0
  36. package/src/state-command.ts +3 -0
  37. package/src/wizards/gcp-pulumi.ts +9 -0
  38. package/src/wizards/gcp.ts +146 -14
  39. package/stacks/gcp/Pulumi.yaml +4 -0
  40. package/stacks/gcp/index.ts +83 -62
  41. package/stacks/gcp-firebase/index.ts +61 -42
@@ -156,7 +156,7 @@ describe("gcp stack wiring (source)", () => {
156
156
  const src = readFileSync(resolve(import.meta.dir, "../stacks/gcp/index.ts"), "utf8");
157
157
 
158
158
  it("builds the URL map through createSiteUrlMap", () => {
159
- expect(src).toMatch(/const urlMap = createSiteUrlMap\(\s*`\$\{namePrefix\}-url-map`/);
159
+ expect(src).toMatch(/return createSiteUrlMap\(\s*`\$\{namePrefix\}-url-map`/);
160
160
  expect(src).not.toMatch(/new gcp\.compute\.URLMap\(\s*`\$\{namePrefix\}-url-map`/);
161
161
  });
162
162
 
@@ -187,7 +187,8 @@ describe("applyStackConfig writes the identity (#1082)", () => {
187
187
  gatewayMinInstances: 0,
188
188
  wafAdaptiveProtection: false,
189
189
  iapAllowlist: ["owner@viu.one"],
190
- imageDigests: { admin: "sha256:a", gateway: "sha256:g" },
190
+ imageDigests: { admin: "sha256:a", gateway: "sha256:g", "mcp-auth-proxy": "sha256:m" },
191
+ deployGateways: true,
191
192
  };
192
193
  const key = `caelo-gcp-firebase:${REMOTE_MCP_IDENTITY_CONFIG}`;
193
194
 
@@ -0,0 +1,49 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * Every Cloud Run service a GCP stack declares has its own Pulumi logical
5
+ * name. Two resources with one URN fail the whole program, so every
6
+ * `pulumi up` of that stack fails. That broke every fresh gcp-firebase
7
+ * install from #1347 on: the data gateway took the default
8
+ * `${namePrefix}-gateway`, which the MCP-Auth-Proxy keeps on purpose (E13 a
9
+ * of #763). A fresh install of v0.11.14 on a scratch project showed it on
10
+ * 2026-11-04.
11
+ */
12
+
13
+ import { describe, expect, it } from "bun:test";
14
+ import { readFileSync } from "node:fs";
15
+ import { resolve } from "node:path";
16
+
17
+ const stackSource = (provider: string): string =>
18
+ readFileSync(resolve(import.meta.dir, "..", "stacks", provider, "index.ts"), "utf8");
19
+
20
+ /** The logical name of each `cloudRunService({ … })` call, as the stack's helper derives it. */
21
+ function cloudRunLogicalNames(source: string): string[] {
22
+ const names: string[] = [];
23
+ // Up to the first closing `})` at a line start, indented or not (a
24
+ // conditional call is indented, stack-gateways.ts): the names come first.
25
+ for (const call of source.matchAll(/cloudRunService\(\{([\s\S]*?)\n\s*\}\)/g)) {
26
+ const body = call[1] ?? "";
27
+ const explicit = body.match(/resourceName:\s*`\$\{namePrefix\}-([a-z-]+)`/);
28
+ const slug = body.match(/serviceName:\s*"([a-z-]+)"/);
29
+ names.push(explicit ? (explicit[1] ?? "") : (slug?.[1] ?? ""));
30
+ }
31
+ return names;
32
+ }
33
+
34
+ describe("GCP stacks: one logical name per Cloud Run service", () => {
35
+ for (const provider of ["gcp", "gcp-firebase"]) {
36
+ it(`${provider} declares no two services under one name`, () => {
37
+ const names = cloudRunLogicalNames(stackSource(provider));
38
+ expect(names.length).toBeGreaterThan(1);
39
+ expect(names.every((n) => n !== "")).toBe(true);
40
+ expect(new Set(names).size).toBe(names.length);
41
+ });
42
+ }
43
+
44
+ it("gcp-firebase: the MCP-Auth-Proxy keeps the gateway's old name, the data gateway has its own", () => {
45
+ const names = cloudRunLogicalNames(stackSource("gcp-firebase"));
46
+ expect(names).toContain("gateway");
47
+ expect(names).toContain("data-gateway");
48
+ });
49
+ });
@@ -0,0 +1,39 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * Whether a `gcp` / `gcp-firebase` stack declares the public data gateway
5
+ * (CLAUDE.md §2, §11.C).
6
+ *
7
+ * The gateway refuses to start while its database login can reach cms_admin
8
+ * or the other environment's public database (apps/api-gateway
9
+ * `databaseIsolationProblems`, #635/#1329), and Cloud Run only finishes
10
+ * creating a service once its container listens. The REVOKEs that isolate
11
+ * the login are migrations (0278, 0530), and the migration job needs the
12
+ * database, the network and the admin service the same stack creates. So a
13
+ * fresh install cannot create everything in one `up`: the first one
14
+ * withholds the gateway, the migrations run, and the next `up` declares it
15
+ * (gateway-bootstrap.ts).
16
+ *
17
+ * Imported by the stacks from `dist/`; keep it free of CLI dependencies.
18
+ */
19
+
20
+ /** Stack config key (`caelo-<provider>:deployGateways`): `"true"` or `"false"`. */
21
+ export const DEPLOY_GATEWAYS_CONFIG = "deployGateways";
22
+
23
+ /**
24
+ * The stack's reading of {@link DEPLOY_GATEWAYS_CONFIG}. The installer sets
25
+ * it before every `up`. Absent means a stack last configured by an installer
26
+ * from before the key: every such install has run its migrations, so its
27
+ * gateway is declared as it always was — reading "absent" as "withhold"
28
+ * would delete a live gateway on a `state migrate` preview or a manual
29
+ * `pulumi up`.
30
+ *
31
+ * @throws on anything but `"true"`, `"false"` or absent — a typo must not
32
+ * silently remove the gateway
33
+ */
34
+ export function parseDeployGateways(value: string | undefined): boolean {
35
+ if (value === undefined) return true;
36
+ if (value === "true") return true;
37
+ if (value === "false") return false;
38
+ throw new Error(`${DEPLOY_GATEWAYS_CONFIG} must be "true" or "false", got "${value}"`);
39
+ }
@@ -200,6 +200,9 @@ export async function stateCommand(argv: readonly string[]): Promise<void> {
200
200
  region,
201
201
  iapAllowlist: installIapAllowlist(meta.ownerEmail),
202
202
  imageDigests,
203
+ // Only a deployed install's state is migrated: its gateway is
204
+ // declared (stack-gateways.ts).
205
+ deployGateways: true,
203
206
  },
204
207
  resolveRemoteMcpIdentity: () =>
205
208
  resolveRemoteMcpIdentityForPreview({
@@ -36,6 +36,7 @@ import {
36
36
  type RemoteMcpIdentity,
37
37
  serializeRemoteMcpIdentity,
38
38
  } from "../stack-contract.js";
39
+ import { DEPLOY_GATEWAYS_CONFIG } from "../stack-gateways.js";
39
40
  import type { ResolvedBackend } from "../state-backend.js";
40
41
 
41
42
  /**
@@ -108,6 +109,12 @@ export interface PulumiUpInputs {
108
109
  * first `up`): the config keeps what an earlier run wrote.
109
110
  */
110
111
  remoteMcpIdentity?: RemoteMcpIdentity | null;
112
+ /**
113
+ * Whether the stack declares the public data gateway (stack-gateways.ts).
114
+ * False only for the first `up` of an install whose gateway has never
115
+ * started (gateway-bootstrap.ts): its migrations have not run yet.
116
+ */
117
+ deployGateways: boolean;
111
118
  }
112
119
 
113
120
  export interface PulumiUpResult {
@@ -469,6 +476,7 @@ export type StackConfigInputs = Pick<
469
476
  | "iapAllowlist"
470
477
  | "imageDigests"
471
478
  | "remoteMcpIdentity"
479
+ | "deployGateways"
472
480
  > & { provider: "gcp" | "gcp-firebase" };
473
481
 
474
482
  /**
@@ -504,6 +512,7 @@ export async function applyStackConfig(
504
512
  ? { [`${ns}:wafAdaptiveProtection`]: { value: String(inputs.wafAdaptiveProtection) } }
505
513
  : {}),
506
514
  [`${ns}:iapAllowlist`]: { value: inputs.iapAllowlist.join(",") },
515
+ [`${ns}:${DEPLOY_GATEWAYS_CONFIG}`]: { value: String(inputs.deployGateways) },
507
516
  // v0.3.2 — anthropicApiKey config dropped. Runtime path is
508
517
  // /settings/ai → ai_providers (KEK-encrypted).
509
518
  ...imageDigestConfig(provider, inputs.imageDigests),
@@ -50,6 +50,12 @@ import {
50
50
  import { formatDnsRecordGroups, groupDnsRecords, type InstallDnsRecord } from "../dns/groups.js";
51
51
  import { pickDnsAdapter } from "../dns/index.js";
52
52
  import type { DnsRecord } from "../dns/types.js";
53
+ import {
54
+ deleteNeverStartedGateways,
55
+ deployOntoMigratedDatabase,
56
+ type GatewayStart,
57
+ readGatewayStart,
58
+ } from "../gateway-bootstrap.js";
53
59
  import {
54
60
  activeAccount,
55
61
  type BillingAccount,
@@ -417,7 +423,7 @@ export async function runGcpConverge(opts: GcpConvergeOpts): Promise<void> {
417
423
  // the live services, so this `up` keeps what they carry. A fresh install
418
424
  // has no services yet: the identity is resolved after the first `up` and
419
425
  // applied by a second one below.
420
- const identityBefore = deployed
426
+ let identityBefore = deployed
421
427
  ? await stepResolveRemoteMcpIdentity(projectId, region, provider, domain, "before")
422
428
  : null;
423
429
 
@@ -426,7 +432,7 @@ export async function runGcpConverge(opts: GcpConvergeOpts): Promise<void> {
426
432
  // (caelo-website/caelo-cms-images by default). Cloud Run reads them
427
433
  // directly with no operator-side IAM binding — anonymous public pull.
428
434
  phase("Provisioning the infrastructure (pulumi up, 8-15 min)");
429
- const upOpts: PulumiUpOpts = {
435
+ const upOpts: Omit<PulumiUpOpts, "deployGateways"> = {
430
436
  projectId,
431
437
  domain,
432
438
  // #650 — the wizard recorded it (or the install predates the setting).
@@ -449,8 +455,43 @@ export async function runGcpConverge(opts: GcpConvergeOpts): Promise<void> {
449
455
  provider,
450
456
  nonInteractive: opts.nonInteractive,
451
457
  };
452
- await stepPulumiUp(installId, { ...upOpts, remoteMcpIdentity: identityBefore?.identity ?? null });
453
- recordImageDigests(installId, imageDigests);
458
+ // An install whose gateway has never started (a fresh one, or one whose
459
+ // first run failed right here) is migrated between an `up` without the
460
+ // gateway and one with it: the gateway refuses to boot until the
461
+ // migrations isolated its database login (gateway-bootstrap.ts).
462
+ const gatewayStart = await stepReadGatewayStart(projectId, region, provider);
463
+ const { databasePrepared } = await deployOntoMigratedDatabase(gatewayStart, {
464
+ up: async (deployGateways) => {
465
+ if (!deployGateways) {
466
+ log.info(
467
+ "First pass without the public gateway: it can only start once the database migrations have run.",
468
+ );
469
+ }
470
+ await stepPulumiUp(installId, {
471
+ ...upOpts,
472
+ deployGateways,
473
+ remoteMcpIdentity: identityBefore?.identity ?? null,
474
+ });
475
+ // Recorded after every pass: a run stopped between them keeps this
476
+ // release on the next run, which then finds no gateway to read it from.
477
+ recordImageDigests(installId, imageDigests);
478
+ },
479
+ prepareDatabase: async () => {
480
+ await stepPublicRoleIsolation(projectId);
481
+ phase("Applying database migrations");
482
+ await stepMigrations(projectId, region);
483
+ // gcp-firebase: the admin and the MCP-Auth-Proxy exist now, so the
484
+ // gateway's `up` declares their identity instead of a third `up`. On
485
+ // gcp the identity lookup needs the gateway service itself; the read
486
+ // after that `up` (10.05) covers it.
487
+ if (provider === "gcp-firebase") {
488
+ identityBefore =
489
+ (await stepResolveRemoteMcpIdentity(projectId, region, provider, domain, "before")) ??
490
+ identityBefore;
491
+ }
492
+ phase("Provisioning the public gateway (pulumi up)");
493
+ },
494
+ });
454
495
 
455
496
  // === 10.05. The identity once the services exist (#1082) ===
456
497
  // Read again after every `up`: on a fresh install (or one whose identity
@@ -463,7 +504,11 @@ export async function runGcpConverge(opts: GcpConvergeOpts): Promise<void> {
463
504
  log.info(
464
505
  "Applying the remote-MCP URLs and IAP audience through the stack (second pulumi up)...",
465
506
  );
466
- await stepPulumiUp(installId, { ...upOpts, remoteMcpIdentity: identity.identity });
507
+ await stepPulumiUp(installId, {
508
+ ...upOpts,
509
+ deployGateways: true,
510
+ remoteMcpIdentity: identity.identity,
511
+ });
467
512
  }
468
513
 
469
514
  // === 10.1. Remove the default network's pre-populated firewall rules ===
@@ -506,21 +551,19 @@ export async function runGcpConverge(opts: GcpConvergeOpts): Promise<void> {
506
551
  // The stack creates public_role through the Cloud SQL Admin API, which
507
552
  // makes it a member of cloudsqlsuperuser. Revoked before migrations: the
508
553
  // migration job's role audit verifies it and fails the install otherwise.
509
- await stepPublicRoleIsolation(projectId);
554
+ // Already done before the gateway's `up` when it had never started.
555
+ if (!databasePrepared) await stepPublicRoleIsolation(projectId);
510
556
 
511
557
  // === 10.95. The admin may write redirects into the URL map (#587) ===
512
558
  // Confirm-publish writes the redirects table into the load balancer's URL
513
559
  // map; the custom role is the CLI's, not the stack's (url-map-redirects-access.ts).
514
560
  if (provider === "gcp") await stepUrlMapRedirectsAccess(projectId);
515
561
 
516
- phase("Applying database migrations");
517
- {
518
- const { runMigrationsViaCloudRunJob } = await import("../migration-runner.js");
519
- const r = await runMigrationsViaCloudRunJob({ projectId, region });
520
- if (!r.ok) {
521
- cancel(`Migrations failed: ${r.error}. Inspect the Cloud Run Job logs and re-run.`);
522
- process.exit(1);
523
- }
562
+ // A gateway that had never started got the migrations before its `up`,
563
+ // with the admin image this run deploys; the `up` since rolled nothing.
564
+ if (!databasePrepared) {
565
+ phase("Applying database migrations");
566
+ await stepMigrations(projectId, region);
524
567
  }
525
568
 
526
569
  phase("Finishing: operator access, welcome page");
@@ -1040,6 +1083,77 @@ async function stepGrantBaseRoles(
1040
1083
  * (cloudsqlsuperuser, #633). Idempotent, so it runs on every wizard pass;
1041
1084
  * the migration job's role audit verifies the result.
1042
1085
  */
1086
+ /**
1087
+ * Both migration targets through the one-shot Cloud Run job, with the admin
1088
+ * service's image (migration-runner.ts). Idempotent; aborts the run on a
1089
+ * failure rather than continuing on a half-migrated database.
1090
+ */
1091
+ async function stepMigrations(projectId: string, region: string): Promise<void> {
1092
+ const { runMigrationsViaCloudRunJob } = await import("../migration-runner.js");
1093
+ const r = await runMigrationsViaCloudRunJob({ projectId, region });
1094
+ if (!r.ok) {
1095
+ cancel(`Migrations failed: ${r.error}. Inspect the Cloud Run Job logs and re-run.`);
1096
+ process.exit(1);
1097
+ }
1098
+ }
1099
+
1100
+ /**
1101
+ * Whether the install's data gateway has ever started (gateway-bootstrap.ts),
1102
+ * which decides whether the migrations run before its `pulumi up`. Aborts on
1103
+ * a failed read: guessing "started" would repeat the failed deploy, guessing
1104
+ * "never started" would withhold a gateway that serves visitors.
1105
+ */
1106
+ async function stepReadGatewayStart(
1107
+ projectId: string,
1108
+ region: string,
1109
+ provider: "gcp" | "gcp-firebase",
1110
+ ): Promise<GatewayStart> {
1111
+ const r = await readGatewayStart({ provider, projectId, region }, gcloud);
1112
+ if (!r.ok) {
1113
+ cancel(
1114
+ `Could not tell whether the public gateway is deployed: ${r.error}. Re-run the installer.`,
1115
+ );
1116
+ process.exit(1);
1117
+ }
1118
+ return r.start;
1119
+ }
1120
+
1121
+ /**
1122
+ * Under the install's state lock, before an `up` that withholds the
1123
+ * gateway: read its state again — another run may have deployed it since
1124
+ * this run decided, and withholding it now would delete a serving gateway —
1125
+ * and delete the services a failed first run left, which never started
1126
+ * (deleteNeverStartedGateways: Pulumi cannot when `deletionProtection` is
1127
+ * on).
1128
+ *
1129
+ * @returns whether this `up` declares the gateway after all
1130
+ */
1131
+ async function withholdGatewayUnderLock(
1132
+ projectId: string,
1133
+ region: string,
1134
+ provider: "gcp" | "gcp-firebase",
1135
+ ): Promise<{ ok: true; deployGateways: boolean } | { ok: false; error: string }> {
1136
+ const target = { provider, projectId, region };
1137
+ const now = await readGatewayStart(target, gcloud);
1138
+ if (!now.ok) {
1139
+ return {
1140
+ ok: false,
1141
+ error: `Could not tell whether the public gateway is deployed: ${now.error}. Re-run the installer.`,
1142
+ };
1143
+ }
1144
+ if (now.start === "started") {
1145
+ log.info("Another run has deployed the public gateway meanwhile; this pass keeps it.");
1146
+ return { ok: true, deployGateways: true };
1147
+ }
1148
+ if (now.neverStarted.length === 0) return { ok: true, deployGateways: false };
1149
+ const removed = await deleteNeverStartedGateways(target, now.neverStarted, gcloud);
1150
+ if (!removed.ok) return { ok: false, error: `${removed.error}.` };
1151
+ log.info(
1152
+ `Removed the gateway service a failed run left behind, which never started: ${removed.deleted.join(", ")}.`,
1153
+ );
1154
+ return { ok: true, deployGateways: false };
1155
+ }
1156
+
1043
1157
  async function stepPublicRoleIsolation(projectId: string): Promise<void> {
1044
1158
  const s = spinner();
1045
1159
  s.start("Removing the gateway logins from the Cloud SQL superuser group...");
@@ -1780,6 +1894,8 @@ interface PulumiUpOpts {
1780
1894
  nonInteractive: boolean;
1781
1895
  /** #1082 — the remote-MCP identity the stack declares (gcp-pulumi.ts PulumiUpInputs). */
1782
1896
  remoteMcpIdentity?: RemoteMcpIdentity | null;
1897
+ /** Whether the stack declares the public gateway (gateway-bootstrap.ts). */
1898
+ deployGateways: boolean;
1783
1899
  }
1784
1900
 
1785
1901
  /**
@@ -1876,6 +1992,21 @@ async function stepPulumiUp(installId: string, opts: PulumiUpOpts): Promise<void
1876
1992
  );
1877
1993
  process.exit(1);
1878
1994
  }
1995
+ // Decided before the lock: under it, look again (gateway-bootstrap.ts).
1996
+ let deployGateways = opts.deployGateways;
1997
+ if (!deployGateways) {
1998
+ const withheld = await withholdGatewayUnderLock(
1999
+ opts.projectId,
2000
+ opts.region,
2001
+ opts.provider ?? "gcp",
2002
+ );
2003
+ if (!withheld.ok) {
2004
+ releaseLock();
2005
+ cancel(withheld.error);
2006
+ process.exit(1);
2007
+ }
2008
+ deployGateways = withheld.deployGateways;
2009
+ }
1879
2010
  log.info(`Pulumi up — wall-clock 8–15 min (Cloud SQL is the long pole). Streaming progress...`);
1880
2011
 
1881
2012
  let resourceCount = 0;
@@ -1888,6 +2019,7 @@ async function stepPulumiUp(installId: string, opts: PulumiUpOpts): Promise<void
1888
2019
  installRoot: root,
1889
2020
  secretsDir,
1890
2021
  ...opts,
2022
+ deployGateways,
1891
2023
  // A deployed install's stack must exist: a missing one means the
1892
2024
  // state is elsewhere, and a fresh stack would try to recreate it all.
1893
2025
  stackMustExist: deployed,
@@ -100,3 +100,7 @@ config:
100
100
  # Optional config NOT declared above:
101
101
  # caelo-gcp:image-admin / image-gateway — image tags for Cloud Run services.
102
102
  # Default `<region>-docker.pkg.dev/<project>/caelo/<service>:latest`.
103
+ # caelo-gcp:deployGateways — "false" only on the installer's first `up` of an
104
+ # install whose gateway has never started: the stack then declares no
105
+ # gateway, URL map or HTTPS proxy until the migrations have isolated the
106
+ # gateway's database login (src/gateway-bootstrap.ts). Absent = "true".
@@ -64,6 +64,7 @@ import {
64
64
  STATIC_CDN_POLICY,
65
65
  secretFileVolumesTemplate,
66
66
  } from "../../dist/stack-contract.js";
67
+ import { DEPLOY_GATEWAYS_CONFIG, parseDeployGateways } from "../../dist/stack-gateways.js";
67
68
  import { GCP_STATIC_RESPONSE_HEADERS } from "../../dist/static-security-headers.js";
68
69
 
69
70
  const cfg = new pulumi.Config();
@@ -947,18 +948,26 @@ const adminSvc = cloudRunService({
947
948
  ],
948
949
  mediaVolume: adminMediaVolumeTemplate(adminMediaVolume(project, env)),
949
950
  });
950
- const gatewaySvc = cloudRunService({
951
- serviceName: "gateway",
952
- minInstances: gatewayMinInstances,
953
- maxInstances: gatewayMaxInstances,
954
- memory: "512Mi",
955
- // Visitor requests only (#1328 moved remote MCP's long streams to the
956
- // MCP-Auth-Proxy): Cloud Run's default.
957
- timeout: "300s",
958
- // public_role on cms_public only: no cms_admin login of any role
959
- // (#613, #635, CLAUDE.md §2).
960
- contractEnv: [...gatewayEnvContract(envContractInputs), ...poolBudget.env.gateway],
961
- });
951
+ // The first `up` of a fresh install withholds the gateway and everything
952
+ // that routes to it (stack-gateways.ts): it refuses to start until the
953
+ // migrations, which run after that `up`, have isolated its database login.
954
+ // The URL map goes with it because its `/api/*` rule must exist at creation
955
+ // (the stack ignores `pathRules` after that, gcp-url-map.ts).
956
+ const deployGateways = parseDeployGateways(cfg.get(DEPLOY_GATEWAYS_CONFIG));
957
+ const gatewaySvc = deployGateways
958
+ ? cloudRunService({
959
+ serviceName: "gateway",
960
+ minInstances: gatewayMinInstances,
961
+ maxInstances: gatewayMaxInstances,
962
+ memory: "512Mi",
963
+ // Visitor requests only (#1328 moved remote MCP's long streams to the
964
+ // MCP-Auth-Proxy): Cloud Run's default.
965
+ timeout: "300s",
966
+ // public_role on cms_public only: no cms_admin login of any role
967
+ // (#613, #635, CLAUDE.md §2).
968
+ contractEnv: [...gatewayEnvContract(envContractInputs), ...poolBudget.env.gateway],
969
+ })
970
+ : null;
962
971
 
963
972
  // =========================================================================
964
973
  // Tier 1 + Tier 2 + Tier 3 LB — single HTTPS LB serves three backends
@@ -1059,26 +1068,28 @@ const staticBackendBucket = new gcp.compute.BackendBucket(
1059
1068
  );
1060
1069
 
1061
1070
  // Tier 3 backend — gateway Cloud Run via serverless NEG
1062
- const gatewayNeg = new gcp.compute.RegionNetworkEndpointGroup(
1063
- `${namePrefix}-gateway-neg`,
1064
- {
1065
- region,
1066
- networkEndpointType: "SERVERLESS",
1067
- cloudRun: { service: gatewaySvc.name },
1068
- },
1069
- opts,
1070
- );
1071
-
1072
- const gatewayBackendService = new gcp.compute.BackendService(
1073
- `${namePrefix}-gateway-backend`,
1074
- {
1075
- protocol: "HTTPS",
1076
- backends: [{ group: gatewayNeg.id }],
1077
- loadBalancingScheme: "EXTERNAL_MANAGED",
1078
- securityPolicy: wafPolicy.id,
1079
- },
1080
- opts,
1081
- );
1071
+ function gatewayBackend(service: gcp.cloudrunv2.Service): gcp.compute.BackendService {
1072
+ const gatewayNeg = new gcp.compute.RegionNetworkEndpointGroup(
1073
+ `${namePrefix}-gateway-neg`,
1074
+ {
1075
+ region,
1076
+ networkEndpointType: "SERVERLESS",
1077
+ cloudRun: { service: service.name },
1078
+ },
1079
+ opts,
1080
+ );
1081
+ return new gcp.compute.BackendService(
1082
+ `${namePrefix}-gateway-backend`,
1083
+ {
1084
+ protocol: "HTTPS",
1085
+ backends: [{ group: gatewayNeg.id }],
1086
+ loadBalancingScheme: "EXTERNAL_MANAGED",
1087
+ securityPolicy: wafPolicy.id,
1088
+ },
1089
+ opts,
1090
+ );
1091
+ }
1092
+ const gatewayBackendService = gatewaySvc ? gatewayBackend(gatewaySvc) : null;
1082
1093
 
1083
1094
  // Tier 2 backend — admin Cloud Run via serverless NEG, IAP-gated.
1084
1095
  const adminNeg = new gcp.compute.RegionNetworkEndpointGroup(
@@ -1258,18 +1269,22 @@ new gcp.iap.WebBackendServiceIamMember(
1258
1269
  // #587 — the public path matcher also carries the redirects table as
1259
1270
  // `urlRedirect` rules, written by the admin on every Confirm-publish; the
1260
1271
  // stack ignores that field after creation (src/gcp-url-map.ts).
1261
- const urlMap = createSiteUrlMap(
1262
- `${namePrefix}-url-map`,
1263
- {
1264
- domain,
1265
- adminDomain,
1266
- stagingHost,
1267
- staticBackend: staticBackendBucket.id,
1268
- gatewayBackend: gatewayBackendService.id,
1269
- adminBackend: adminBackendService.id,
1270
- },
1271
- opts,
1272
- );
1272
+ // Withheld with the gateway (see `deployGateways`), and the HTTPS proxy and
1273
+ // forwarding rule below with it.
1274
+ function siteUrlMap(gatewayBackendId: pulumi.Input<string>): gcp.compute.URLMap {
1275
+ return createSiteUrlMap(
1276
+ `${namePrefix}-url-map`,
1277
+ {
1278
+ domain,
1279
+ adminDomain,
1280
+ stagingHost,
1281
+ staticBackend: staticBackendBucket.id,
1282
+ gatewayBackend: gatewayBackendId,
1283
+ adminBackend: adminBackendService.id,
1284
+ },
1285
+ opts,
1286
+ );
1287
+ }
1273
1288
 
1274
1289
  // #587 — the admin's run SA may rewrite the URL map's redirect rules through
1275
1290
  // a project custom role. The CLI owns that role, not this stack: the
@@ -1302,22 +1317,25 @@ const adminCert = new gcp.compute.ManagedSslCertificate(
1302
1317
  // (staging-gateway-setup.ts, `caelo-<env>-staging-cert`), attached next to
1303
1318
  // these two after the first `up` and by every converge, so the proxy's
1304
1319
  // certificate list is left to it after creation.
1305
- const httpsProxy = new gcp.compute.TargetHttpsProxy(
1306
- `${namePrefix}-https-proxy`,
1307
- { urlMap: urlMap.id, sslCertificates: [adminCert.id, managedCert.id] },
1308
- { ...opts, ignoreChanges: ["sslCertificates"] },
1309
- );
1320
+ if (gatewayBackendService) {
1321
+ const urlMap = siteUrlMap(gatewayBackendService.id);
1322
+ const httpsProxy = new gcp.compute.TargetHttpsProxy(
1323
+ `${namePrefix}-https-proxy`,
1324
+ { urlMap: urlMap.id, sslCertificates: [adminCert.id, managedCert.id] },
1325
+ { ...opts, ignoreChanges: ["sslCertificates"] },
1326
+ );
1310
1327
 
1311
- new gcp.compute.GlobalForwardingRule(
1312
- `${namePrefix}-https-fwd`,
1313
- {
1314
- target: httpsProxy.id,
1315
- portRange: "443",
1316
- ipAddress: lbIp.address,
1317
- loadBalancingScheme: "EXTERNAL_MANAGED",
1318
- },
1319
- opts,
1320
- );
1328
+ new gcp.compute.GlobalForwardingRule(
1329
+ `${namePrefix}-https-fwd`,
1330
+ {
1331
+ target: httpsProxy.id,
1332
+ portRange: "443",
1333
+ ipAddress: lbIp.address,
1334
+ loadBalancingScheme: "EXTERNAL_MANAGED",
1335
+ },
1336
+ opts,
1337
+ );
1338
+ }
1321
1339
 
1322
1340
  // HTTP → HTTPS redirect: a tiny URLMap with no backend, just a 301
1323
1341
  // redirect rule. Same LB IP, port 80, returns to the request's host
@@ -1371,8 +1389,11 @@ const loggingSink = new gcp.logging.ProjectSink(
1371
1389
  {
1372
1390
  name: `${namePrefix}-edge-log-sink`,
1373
1391
  destination: pulumi.interpolate`bigquery.googleapis.com/projects/${project}/datasets/${edgeLogDataset.datasetId}`,
1374
- // Capture all gateway request logs + admin warnings/errors.
1375
- filter: pulumi.interpolate`(resource.type="cloud_run_revision" AND resource.labels.service_name="${gatewaySvc.name}") OR (resource.type="cloud_run_revision" AND resource.labels.service_name="${adminSvc.name}" AND severity>=WARNING)`,
1392
+ // Capture all gateway request logs + admin warnings/errors (the
1393
+ // gateway's once it is declared).
1394
+ filter: gatewaySvc
1395
+ ? pulumi.interpolate`(resource.type="cloud_run_revision" AND resource.labels.service_name="${gatewaySvc.name}") OR (resource.type="cloud_run_revision" AND resource.labels.service_name="${adminSvc.name}" AND severity>=WARNING)`
1396
+ : pulumi.interpolate`resource.type="cloud_run_revision" AND resource.labels.service_name="${adminSvc.name}" AND severity>=WARNING`,
1376
1397
  uniqueWriterIdentity: true,
1377
1398
  },
1378
1399
  opts,
@@ -1438,7 +1459,7 @@ export const environmentOut = out.environment;
1438
1459
  export const cloudSqlConnectionNameOut = sqlInstance.connectionName;
1439
1460
  export const cloudSqlPrivateIpOut = sqlInstance.privateIpAddress;
1440
1461
  export const adminCloudRunUrlOut = adminSvc.uri;
1441
- export const gatewayCloudRunUrlOut = gatewaySvc.uri;
1462
+ export const gatewayCloudRunUrlOut = gatewaySvc?.uri;
1442
1463
  export const lbIpOut = lbIp.address;
1443
1464
  export const adminDomainOut = adminDomain;
1444
1465
  export const bootstrapTokenExpiresAtOut = tokenInfo.expiresAt;