@caelo-cms/provisioning 0.11.14 → 0.11.16

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 (82) 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/adopt-existing.d.ts +0 -56
  6. package/dist/adopt-existing.d.ts.map +1 -1
  7. package/dist/adopt-existing.js +58 -2
  8. package/dist/adopt-existing.js.map +1 -1
  9. package/dist/cloudsql-tls.d.ts.map +1 -1
  10. package/dist/cloudsql-tls.js +3 -3
  11. package/dist/cloudsql-tls.js.map +1 -1
  12. package/dist/deployed-release.d.ts.map +1 -1
  13. package/dist/deployed-release.js +4 -2
  14. package/dist/deployed-release.js.map +1 -1
  15. package/dist/gateway-bootstrap.d.ts +68 -0
  16. package/dist/gateway-bootstrap.d.ts.map +1 -0
  17. package/dist/gateway-bootstrap.js +145 -0
  18. package/dist/gateway-bootstrap.js.map +1 -0
  19. package/dist/gcloud.d.ts +2 -0
  20. package/dist/gcloud.d.ts.map +1 -1
  21. package/dist/gcloud.js +14 -0
  22. package/dist/gcloud.js.map +1 -1
  23. package/dist/mcp-auth-proxy-setup.d.ts.map +1 -1
  24. package/dist/mcp-auth-proxy-setup.js +3 -6
  25. package/dist/mcp-auth-proxy-setup.js.map +1 -1
  26. package/dist/ops-backend.d.ts.map +1 -1
  27. package/dist/ops-backend.js +4 -6
  28. package/dist/ops-backend.js.map +1 -1
  29. package/dist/remote-mcp.d.ts.map +1 -1
  30. package/dist/remote-mcp.js +4 -5
  31. package/dist/remote-mcp.js.map +1 -1
  32. package/dist/runtime-secrets.d.ts.map +1 -1
  33. package/dist/runtime-secrets.js +4 -5
  34. package/dist/runtime-secrets.js.map +1 -1
  35. package/dist/stack-gateways.d.ts +31 -0
  36. package/dist/stack-gateways.d.ts.map +1 -0
  37. package/dist/stack-gateways.js +40 -0
  38. package/dist/stack-gateways.js.map +1 -0
  39. package/dist/staging-gateway-setup.d.ts.map +1 -1
  40. package/dist/staging-gateway-setup.js +7 -8
  41. package/dist/staging-gateway-setup.js.map +1 -1
  42. package/dist/state-command.d.ts.map +1 -1
  43. package/dist/state-command.js +3 -0
  44. package/dist/state-command.js.map +1 -1
  45. package/dist/state-lock-lease.d.ts +1 -1
  46. package/dist/state-lock-lease.d.ts.map +1 -1
  47. package/dist/state-lock-lease.js +2 -2
  48. package/dist/state-lock-lease.js.map +1 -1
  49. package/dist/wizards/gcp-pulumi.d.ts +7 -1
  50. package/dist/wizards/gcp-pulumi.d.ts.map +1 -1
  51. package/dist/wizards/gcp-pulumi.js +2 -0
  52. package/dist/wizards/gcp-pulumi.js.map +1 -1
  53. package/dist/wizards/gcp.d.ts.map +1 -1
  54. package/dist/wizards/gcp.js +120 -13
  55. package/dist/wizards/gcp.js.map +1 -1
  56. package/package.json +2 -2
  57. package/src/__tests__/stack-under-mocks.ts +69 -0
  58. package/src/adopt-existing.test.ts +36 -9
  59. package/src/adopt-existing.ts +2 -3
  60. package/src/cloudsql-tls.ts +3 -3
  61. package/src/deployed-release.test.ts +16 -0
  62. package/src/deployed-release.ts +4 -2
  63. package/src/gateway-bootstrap.test.ts +381 -0
  64. package/src/gateway-bootstrap.ts +195 -0
  65. package/src/gcloud.test.ts +24 -0
  66. package/src/gcloud.ts +17 -0
  67. package/src/gcp-url-map.test.ts +1 -1
  68. package/src/mcp-auth-proxy-setup.ts +3 -7
  69. package/src/ops-backend.ts +4 -7
  70. package/src/remote-mcp-stack-config.test.ts +2 -1
  71. package/src/remote-mcp.ts +4 -6
  72. package/src/runtime-secrets.ts +4 -5
  73. package/src/stack-cloud-run-names.test.ts +49 -0
  74. package/src/stack-gateways.ts +39 -0
  75. package/src/staging-gateway-setup.ts +7 -8
  76. package/src/state-command.ts +3 -0
  77. package/src/state-lock-lease.ts +2 -4
  78. package/src/wizards/gcp-pulumi.ts +9 -0
  79. package/src/wizards/gcp.ts +146 -14
  80. package/stacks/gcp/Pulumi.yaml +4 -0
  81. package/stacks/gcp/index.ts +83 -62
  82. package/stacks/gcp-firebase/index.ts +61 -42
@@ -30,7 +30,7 @@
30
30
  import { mkdtempSync, rmSync, writeFileSync } from "node:fs";
31
31
  import { tmpdir } from "node:os";
32
32
  import { join } from "node:path";
33
- import { gcloud as defaultGcloud } from "./gcloud.js";
33
+ import { gcloud as defaultGcloud, isGcloudNotFound } from "./gcloud.js";
34
34
  import {
35
35
  type GcloudRunner,
36
36
  realSleep,
@@ -63,9 +63,6 @@ const OPS_APIS = ["storage.googleapis.com", "cloudkms.googleapis.com"] as const;
63
63
  /** Principals that must never appear on the ops bucket. */
64
64
  const PUBLIC_MEMBERS = new Set(["allUsers", "allAuthenticatedUsers"]);
65
65
 
66
- /** gcloud's wording for a resource that does not exist (yet). */
67
- const NOT_FOUND = /NOT_FOUND|NotFound|not found|404|does not exist/i;
68
-
69
66
  /** Everything {@link ensureOpsBackend} needs to know about the install. */
70
67
  export interface OpsBackendTarget {
71
68
  readonly projectId: string;
@@ -211,7 +208,7 @@ export async function ensureOpsBackend(
211
208
  "--format=json",
212
209
  ]);
213
210
  let bucketExists = described.ok;
214
- if (!described.ok && !NOT_FOUND.test(described.stderr)) {
211
+ if (!described.ok && !isGcloudNotFound(described.stderr)) {
215
212
  return {
216
213
  ok: false,
217
214
  error: `Could not read ${bucketUrl}: ${reason(described.stderr, described.exitCode)}. If the name is taken by a bucket outside project ${projectId}, the install can't use it — tell the maintainers (the name is <project>-caelo-ops).`,
@@ -367,7 +364,7 @@ export async function ensureOpsBackend(
367
364
  "--format=value(name)",
368
365
  ]);
369
366
  // In a dry run the KMS API may still be disabled; that reads as "not there yet".
370
- const ringMissing = !ring.ok && (NOT_FOUND.test(ring.stderr) || dryRun);
367
+ const ringMissing = !ring.ok && (isGcloudNotFound(ring.stderr) || dryRun);
371
368
  if (!ring.ok && !ringMissing) return fail(`Reading key ring ${OPS_KEY_RING}`, ring);
372
369
  if (ringMissing) {
373
370
  act(`create KMS key ring ${OPS_KEY_RING} in ${region}`);
@@ -380,7 +377,7 @@ export async function ensureOpsBackend(
380
377
  const key = ringMissing
381
378
  ? { ok: false, stderr: "NOT_FOUND", stdout: "", exitCode: 1 }
382
379
  : await run(["kms", "keys", "describe", OPS_STATE_KEY, ...keyWhere, "--format=value(name)"]);
383
- const keyMissing = !key.ok && NOT_FOUND.test(key.stderr);
380
+ const keyMissing = !key.ok && isGcloudNotFound(key.stderr);
384
381
  if (!key.ok && !keyMissing) return fail(`Reading key ${OPS_STATE_KEY}`, key);
385
382
  if (keyMissing) {
386
383
  act(`create KMS key ${OPS_KEY_RING}/${OPS_STATE_KEY}`);
@@ -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
 
package/src/remote-mcp.ts CHANGED
@@ -32,7 +32,7 @@
32
32
  */
33
33
 
34
34
  import { GCP_MCP_AUTH_PROXY_PATHS } from "@caelo-cms/shared";
35
- import { gcloud as defaultGcloud } from "./gcloud.js";
35
+ import { gcloud as defaultGcloud, isGcloudNotFound } from "./gcloud.js";
36
36
  import type { GcloudRunner } from "./gcloud-retry.js";
37
37
  import { gcpNamePrefix, mcpAuthProxyEdgeNames } from "./gcp-names.js";
38
38
  import { ensureMcpAuthProxyServiceGcp } from "./mcp-auth-proxy-setup.js";
@@ -563,7 +563,7 @@ async function describePolicyRules(
563
563
  "--format=json",
564
564
  ]);
565
565
  if (!describe.ok) {
566
- return { ok: false, missing: NOT_FOUND.test(describe.stderr), error: describe.stderr.trim() };
566
+ return { ok: false, missing: isGcloudNotFound(describe.stderr), error: describe.stderr.trim() };
567
567
  }
568
568
  const described = parseJson(describe.stdout) as { rules?: LiveArmorRule[] } | null;
569
569
  if (!described)
@@ -571,8 +571,6 @@ async function describePolicyRules(
571
571
  return { ok: true, rules: described.rules ?? [] };
572
572
  }
573
573
 
574
- const NOT_FOUND = /NOT_FOUND|not found|was not found|does not exist/i;
575
-
576
574
  /**
577
575
  * #1328 — the MCP-Auth-Proxy's own Cloud Armor policy with the `/api/mcp/*`
578
576
  * rule ({@link MCP_ARMOR_RULE}; remote-mcp-edge.ts says why): created when
@@ -703,7 +701,7 @@ export async function ensureMcpAuthProxyBackend(
703
701
  "--format=value(name)",
704
702
  ]);
705
703
  if (!neg.ok) {
706
- if (!NOT_FOUND.test(neg.stderr))
704
+ if (!isGcloudNotFound(neg.stderr))
707
705
  return { ok: false, error: `describe ${names.neg}: ${neg.stderr.trim()}` };
708
706
  const created = await run([
709
707
  "compute",
@@ -730,7 +728,7 @@ export async function ensureMcpAuthProxyBackend(
730
728
  ]);
731
729
  let backendJson: { selfLink?: string; securityPolicy?: string; backends?: { group?: string }[] };
732
730
  if (!backend.ok) {
733
- if (!NOT_FOUND.test(backend.stderr)) {
731
+ if (!isGcloudNotFound(backend.stderr)) {
734
732
  return { ok: false, error: `describe ${names.backend}: ${backend.stderr.trim()}` };
735
733
  }
736
734
  const created = await run([
@@ -22,7 +22,7 @@
22
22
  */
23
23
 
24
24
  import { randomBytes } from "node:crypto";
25
- import { gcloud as defaultGcloud } from "./gcloud.js";
25
+ import { gcloud as defaultGcloud, isGcloudNotFound } from "./gcloud.js";
26
26
  import { type GcloudRunner, realSleep, runWithRetry, type Sleep } from "./gcloud-retry.js";
27
27
  import {
28
28
  gatewayServiceAccountEmail,
@@ -86,7 +86,6 @@ export interface EnsureOutcome {
86
86
  readonly detail?: string;
87
87
  }
88
88
 
89
- const NOT_FOUND = /NOT_FOUND|not found|does not exist/i;
90
89
  const ALREADY_EXISTS = /ALREADY_EXISTS|already exists/i;
91
90
 
92
91
  // ===========================================================================
@@ -163,7 +162,7 @@ async function ensureServiceAccount(
163
162
  "--format=value(email)",
164
163
  ]);
165
164
  if (describe.ok) return { id, status: "present" };
166
- if (!NOT_FOUND.test(describe.stderr)) {
165
+ if (!isGcloudNotFound(describe.stderr)) {
167
166
  return { id, status: "failed", error: describe.stderr.trim() };
168
167
  }
169
168
  const create = await run([
@@ -292,7 +291,7 @@ export async function createInstallSecret(
292
291
  "--format=value(name)",
293
292
  ]);
294
293
  const read: { ok: true; replication: SecretReplication } | { ok: false; error: string } =
295
- !pg.ok && NOT_FOUND.test(pg.stderr)
294
+ !pg.ok && isGcloudNotFound(pg.stderr)
296
295
  ? { ok: true, replication: { kind: "user-managed", locations: [install.region] } }
297
296
  : await readSecretReplication(install, { run });
298
297
  if (!read.ok) return read;
@@ -360,7 +359,7 @@ export async function ensureGeneratedSecrets(
360
359
  const secretId = gcpSecretId(install.env, name);
361
360
  const id = `secret ${secretId}`;
362
361
  const describe = await run(["secrets", "describe", secretId, project, "--format=value(name)"]);
363
- if (!describe.ok && !NOT_FOUND.test(describe.stderr)) {
362
+ if (!describe.ok && !isGcloudNotFound(describe.stderr)) {
364
363
  outcomes.push({ id, status: "failed", error: describe.stderr.trim() });
365
364
  continue;
366
365
  }
@@ -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
+ }
@@ -39,7 +39,7 @@ import {
39
39
  GATEWAY_POOL_MAX,
40
40
  isIpLiteral,
41
41
  } from "@caelo-cms/shared";
42
- import { gcloud as defaultGcloud } from "./gcloud.js";
42
+ import { gcloud as defaultGcloud, isGcloudNotFound } from "./gcloud.js";
43
43
  import { type GcloudRunner, realSleep, runWithRetry, type Sleep } from "./gcloud-retry.js";
44
44
  import {
45
45
  firebaseStagingSiteId,
@@ -87,7 +87,6 @@ export interface StagingDnsRecord {
87
87
  readonly value: string;
88
88
  }
89
89
 
90
- const NOT_FOUND = /NOT_FOUND|not found|cannot find|does not exist|could not be found|404/i;
91
90
  const ALREADY_EXISTS = /ALREADY_EXISTS|already exists|409/i;
92
91
 
93
92
  /** The `gcp` staging host's managed certificate: the edge's prefix plus six hex of the host's SHA-256. */
@@ -269,7 +268,7 @@ async function ensureStagingBucket(
269
268
  "--format=value(name)",
270
269
  ]);
271
270
  if (described.ok) outcomes.push({ id, status: "present" });
272
- else if (!NOT_FOUND.test(described.stderr)) {
271
+ else if (!isGcloudNotFound(described.stderr)) {
273
272
  return [{ id, status: "failed", error: described.stderr.trim() }];
274
273
  } else {
275
274
  const created = await run([
@@ -352,7 +351,7 @@ async function ensureService(
352
351
  `--project=${inputs.projectId}`,
353
352
  "--format=value(metadata.name)",
354
353
  ]);
355
- if (!existing.ok && !NOT_FOUND.test(existing.stderr)) {
354
+ if (!existing.ok && !isGcloudNotFound(existing.stderr)) {
356
355
  return { id, status: "failed", error: existing.stderr.trim() };
357
356
  }
358
357
  if (!existing.ok) {
@@ -689,7 +688,7 @@ async function deleteStagingDomainMapping(
689
688
  "--format=value(metadata.name)",
690
689
  ]);
691
690
  if (!described.ok) {
692
- if (/\bNOT_FOUND\b|not found|could not be found/i.test(described.stderr)) {
691
+ if (isGcloudNotFound(described.stderr)) {
693
692
  return { ok: true, deleted: false };
694
693
  }
695
694
  return {
@@ -814,7 +813,7 @@ async function ensureGcpEdge(
814
813
  "--format=value(name)",
815
814
  ]);
816
815
  if (!neg.ok) {
817
- if (!NOT_FOUND.test(neg.stderr)) return fail(`describe ${names.neg}: ${neg.stderr.trim()}`);
816
+ if (!isGcloudNotFound(neg.stderr)) return fail(`describe ${names.neg}: ${neg.stderr.trim()}`);
818
817
  const created = await run([
819
818
  "compute",
820
819
  "network-endpoint-groups",
@@ -862,7 +861,7 @@ async function ensureGcpEdge(
862
861
  ]);
863
862
  let backendJson: { selfLink?: string; backends?: { group?: string }[] } = {};
864
863
  if (!backend.ok) {
865
- if (!NOT_FOUND.test(backend.stderr)) {
864
+ if (!isGcloudNotFound(backend.stderr)) {
866
865
  return fail(`describe ${names.backend}: ${backend.stderr.trim()}`);
867
866
  }
868
867
  const created = await run([
@@ -922,7 +921,7 @@ async function ensureGcpEdge(
922
921
  "--format=value(name)",
923
922
  ]);
924
923
  if (!cert.ok) {
925
- if (!NOT_FOUND.test(cert.stderr)) return fail(`describe ${certName}: ${cert.stderr.trim()}`);
924
+ if (!isGcloudNotFound(cert.stderr)) return fail(`describe ${certName}: ${cert.stderr.trim()}`);
926
925
  const created = await run([
927
926
  "compute",
928
927
  "ssl-certificates",
@@ -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({
@@ -47,7 +47,7 @@ import { createHash, randomUUID } from "node:crypto";
47
47
  import { readlinkSync } from "node:fs";
48
48
  import { hostname, networkInterfaces } from "node:os";
49
49
  import { z } from "zod";
50
- import type { GcloudResult } from "./gcloud.js";
50
+ import { type GcloudResult, isGcloudNotFound } from "./gcloud.js";
51
51
 
52
52
  /** A Cloud Run job execution, fully addressed. */
53
53
  export interface CloudRunExecutionRef {
@@ -229,8 +229,6 @@ export type ExecutionState =
229
229
  /** Cloud Run could not be asked; `error` says why. */
230
230
  | { readonly kind: "unknown"; readonly error: string };
231
231
 
232
- const NOT_FOUND = /NOT_FOUND|not found|could not be found|does not exist/i;
233
-
234
232
  const executionStatusSchema = z.object({
235
233
  status: z
236
234
  .object({
@@ -257,7 +255,7 @@ const executionStatusSchema = z.object({
257
255
  */
258
256
  export function parseExecutionState(result: GcloudResult): ExecutionState {
259
257
  if (!result.ok) {
260
- if (NOT_FOUND.test(result.stderr)) return { kind: "not-found" };
258
+ if (isGcloudNotFound(result.stderr)) return { kind: "not-found" };
261
259
  return {
262
260
  kind: "unknown",
263
261
  error: result.stderr.trim() || `gcloud exited ${result.exitCode}`,
@@ -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".