@caelo-cms/provisioning 0.11.13 → 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 (186) 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/admin-domain.d.ts +4 -46
  6. package/dist/admin-domain.d.ts.map +1 -1
  7. package/dist/admin-domain.js +4 -101
  8. package/dist/admin-domain.js.map +1 -1
  9. package/dist/agent-db.js +29 -5
  10. package/dist/audit-job-setup.d.ts.map +1 -1
  11. package/dist/audit-job-setup.js +14 -19
  12. package/dist/audit-job-setup.js.map +1 -1
  13. package/dist/caddy.d.ts +2 -1
  14. package/dist/caddy.d.ts.map +1 -1
  15. package/dist/caddy.js +21 -3
  16. package/dist/caddy.js.map +1 -1
  17. package/dist/cli.js +111 -62
  18. package/dist/cli.js.map +1 -1
  19. package/dist/compose.d.ts +22 -2
  20. package/dist/compose.d.ts.map +1 -1
  21. package/dist/compose.js +53 -3
  22. package/dist/compose.js.map +1 -1
  23. package/dist/converge-checkpoint.d.ts +1 -0
  24. package/dist/converge-checkpoint.d.ts.map +1 -1
  25. package/dist/converge-checkpoint.js +1 -0
  26. package/dist/converge-checkpoint.js.map +1 -1
  27. package/dist/deployed-release.d.ts.map +1 -1
  28. package/dist/deployed-release.js +42 -8
  29. package/dist/deployed-release.js.map +1 -1
  30. package/dist/gateway-bootstrap.d.ts +68 -0
  31. package/dist/gateway-bootstrap.d.ts.map +1 -0
  32. package/dist/gateway-bootstrap.js +145 -0
  33. package/dist/gateway-bootstrap.js.map +1 -0
  34. package/dist/gcp-names.d.ts +33 -14
  35. package/dist/gcp-names.d.ts.map +1 -1
  36. package/dist/gcp-names.js +43 -0
  37. package/dist/gcp-names.js.map +1 -1
  38. package/dist/gcp-url-map.d.ts +19 -4
  39. package/dist/gcp-url-map.d.ts.map +1 -1
  40. package/dist/gcp-url-map.js +33 -5
  41. package/dist/gcp-url-map.js.map +1 -1
  42. package/dist/infra-contract.d.ts +1 -1
  43. package/dist/infra-contract.d.ts.map +1 -1
  44. package/dist/infra-contract.js +18 -1
  45. package/dist/infra-contract.js.map +1 -1
  46. package/dist/lifecycle.d.ts.map +1 -1
  47. package/dist/lifecycle.js +5 -39
  48. package/dist/lifecycle.js.map +1 -1
  49. package/dist/mcp-auth-proxy-setup.d.ts +8 -2
  50. package/dist/mcp-auth-proxy-setup.d.ts.map +1 -1
  51. package/dist/mcp-auth-proxy-setup.js +4 -0
  52. package/dist/mcp-auth-proxy-setup.js.map +1 -1
  53. package/dist/release-manifest.d.ts +1 -1
  54. package/dist/release-manifest.d.ts.map +1 -1
  55. package/dist/release-manifest.js +2 -0
  56. package/dist/release-manifest.js.map +1 -1
  57. package/dist/remote-mcp.d.ts.map +1 -1
  58. package/dist/remote-mcp.js +11 -1
  59. package/dist/remote-mcp.js.map +1 -1
  60. package/dist/runtime-secrets.d.ts +10 -0
  61. package/dist/runtime-secrets.d.ts.map +1 -1
  62. package/dist/runtime-secrets.js +10 -1
  63. package/dist/runtime-secrets.js.map +1 -1
  64. package/dist/stack-contract.d.ts +61 -20
  65. package/dist/stack-contract.d.ts.map +1 -1
  66. package/dist/stack-contract.js +173 -35
  67. package/dist/stack-contract.js.map +1 -1
  68. package/dist/stack-converge.d.ts.map +1 -1
  69. package/dist/stack-converge.js +4 -2
  70. package/dist/stack-converge.js.map +1 -1
  71. package/dist/stack-gateways.d.ts +31 -0
  72. package/dist/stack-gateways.d.ts.map +1 -0
  73. package/dist/stack-gateways.js +40 -0
  74. package/dist/stack-gateways.js.map +1 -0
  75. package/dist/staging-admin.d.ts +2 -2
  76. package/dist/staging-admin.d.ts.map +1 -1
  77. package/dist/staging-gateway-setup.d.ts +140 -0
  78. package/dist/staging-gateway-setup.d.ts.map +1 -0
  79. package/dist/staging-gateway-setup.js +848 -0
  80. package/dist/staging-gateway-setup.js.map +1 -0
  81. package/dist/state-command.d.ts.map +1 -1
  82. package/dist/state-command.js +3 -0
  83. package/dist/state-command.js.map +1 -1
  84. package/dist/upgrade/app-roll.d.ts +4 -4
  85. package/dist/upgrade/app-roll.d.ts.map +1 -1
  86. package/dist/upgrade/app-roll.js +7 -5
  87. package/dist/upgrade/app-roll.js.map +1 -1
  88. package/dist/upgrade/converge.d.ts.map +1 -1
  89. package/dist/upgrade/converge.js +36 -27
  90. package/dist/upgrade/converge.js.map +1 -1
  91. package/dist/upgrade/image-forms.d.ts +3 -3
  92. package/dist/upgrade/image-forms.d.ts.map +1 -1
  93. package/dist/upgrade/image-forms.js +2 -2
  94. package/dist/upgrade/image-forms.js.map +1 -1
  95. package/dist/upgrade/release-images.d.ts +20 -0
  96. package/dist/upgrade/release-images.d.ts.map +1 -1
  97. package/dist/upgrade/release-images.js +28 -0
  98. package/dist/upgrade/release-images.js.map +1 -1
  99. package/dist/upgrade/upgrade.d.ts +3 -1
  100. package/dist/upgrade/upgrade.d.ts.map +1 -1
  101. package/dist/upgrade/upgrade.js +22 -1
  102. package/dist/upgrade/upgrade.js.map +1 -1
  103. package/dist/upgrader-job.d.ts.map +1 -1
  104. package/dist/upgrader-job.js +30 -5
  105. package/dist/upgrader-job.js.map +1 -1
  106. package/dist/upgrader-records.d.ts +2 -2
  107. package/dist/upgrader-records.d.ts.map +1 -1
  108. package/dist/upgrader-records.js +2 -2
  109. package/dist/upgrader-records.js.map +1 -1
  110. package/dist/wizard.d.ts.map +1 -1
  111. package/dist/wizard.js +3 -3
  112. package/dist/wizard.js.map +1 -1
  113. package/dist/wizards/gcp-pulumi.d.ts +7 -1
  114. package/dist/wizards/gcp-pulumi.d.ts.map +1 -1
  115. package/dist/wizards/gcp-pulumi.js +2 -0
  116. package/dist/wizards/gcp-pulumi.js.map +1 -1
  117. package/dist/wizards/gcp.d.ts.map +1 -1
  118. package/dist/wizards/gcp.js +168 -22
  119. package/dist/wizards/gcp.js.map +1 -1
  120. package/package.json +2 -2
  121. package/src/__tests__/stack-under-mocks.ts +69 -0
  122. package/src/admin-domain.test.ts +0 -156
  123. package/src/admin-domain.ts +4 -117
  124. package/src/admin-memory.test.ts +2 -0
  125. package/src/audit-job-setup.test.ts +11 -11
  126. package/src/audit-job-setup.ts +14 -19
  127. package/src/caddy-redirects.docker.test.ts +10 -5
  128. package/src/caddy-redirects.test.ts +7 -5
  129. package/src/caddy-validate.test.ts +1 -1
  130. package/src/caddy.test.ts +12 -6
  131. package/src/caddy.ts +23 -4
  132. package/src/cli.ts +138 -77
  133. package/src/compose.ts +67 -2
  134. package/src/converge-checkpoint.ts +1 -0
  135. package/src/database-tls-builders.test.ts +3 -1
  136. package/src/deployed-release.test.ts +37 -0
  137. package/src/deployed-release.ts +44 -7
  138. package/src/gateway-bootstrap.test.ts +381 -0
  139. package/src/gateway-bootstrap.ts +195 -0
  140. package/src/gateway-env-isolation.test.ts +2 -0
  141. package/src/gcp-names.ts +53 -0
  142. package/src/gcp-url-map.test.ts +27 -3
  143. package/src/gcp-url-map.ts +36 -5
  144. package/src/index.test.ts +9 -3
  145. package/src/infra-contract.test.ts +4 -3
  146. package/src/infra-contract.ts +18 -1
  147. package/src/lifecycle.ts +8 -52
  148. package/src/mcp-auth-proxy-setup.test.ts +15 -6
  149. package/src/mcp-auth-proxy-setup.ts +14 -2
  150. package/src/release-manifest.ts +3 -1
  151. package/src/remote-mcp-stack-config.test.ts +3 -1
  152. package/src/remote-mcp.test.ts +5 -1
  153. package/src/remote-mcp.ts +10 -1
  154. package/src/runtime-secrets.test.ts +10 -1
  155. package/src/runtime-secrets.ts +21 -0
  156. package/src/self-hosted-backup.test.ts +6 -4
  157. package/src/self-hosted-compose.test.ts +2 -0
  158. package/src/stack-cloud-run-names.test.ts +49 -0
  159. package/src/stack-contract-parity.test.ts +7 -3
  160. package/src/stack-contract.test.ts +73 -13
  161. package/src/stack-contract.ts +195 -42
  162. package/src/stack-converge-secrets.test.ts +7 -2
  163. package/src/stack-converge.test.ts +37 -9
  164. package/src/stack-converge.ts +4 -1
  165. package/src/stack-gateways.ts +39 -0
  166. package/src/staging-admin.ts +2 -2
  167. package/src/staging-gateway-setup.test.ts +361 -0
  168. package/src/staging-gateway-setup.ts +1083 -0
  169. package/src/state-command.ts +3 -0
  170. package/src/upgrade/app-roll.ts +7 -4
  171. package/src/upgrade/converge.ts +40 -26
  172. package/src/upgrade/image-forms.ts +7 -7
  173. package/src/upgrade/release-images.test.ts +28 -0
  174. package/src/upgrade/release-images.ts +44 -0
  175. package/src/upgrade/upgrade.test.ts +63 -11
  176. package/src/upgrade/upgrade.ts +29 -2
  177. package/src/upgrader-job.test.ts +23 -0
  178. package/src/upgrader-job.ts +45 -11
  179. package/src/upgrader-records.ts +7 -7
  180. package/src/wizard.ts +2 -3
  181. package/src/wizards/gcp-pulumi.ts +9 -0
  182. package/src/wizards/gcp.ts +219 -23
  183. package/stacks/gcp/Pulumi.yaml +4 -0
  184. package/stacks/gcp/index.ts +128 -66
  185. package/stacks/gcp-firebase/index.ts +101 -50
  186. package/stacks/self-hosted/index.ts +9 -2
@@ -0,0 +1,381 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * A fresh Google Cloud install deploys the public gateway only onto a
5
+ * migrated database (gateway-bootstrap.ts). Regression: from #767 on, the
6
+ * gateway refuses to boot while its login can CONNECT to cms_admin, the
7
+ * REVOKEs are migrations, and the wizard ran them after the `pulumi up` that
8
+ * created the gateway — so every fresh install failed in that `up` with
9
+ * "the API gateway's database login is not isolated from cms_admin".
10
+ */
11
+
12
+ import { describe, expect, it } from "bun:test";
13
+ import { readFileSync } from "node:fs";
14
+ import { resolve } from "node:path";
15
+ import type * as automation from "@pulumi/pulumi/automation";
16
+ import {
17
+ deleteNeverStartedGateways,
18
+ deployOntoMigratedDatabase,
19
+ readGatewayStart,
20
+ } from "./gateway-bootstrap.js";
21
+ import type { GcloudResult } from "./gcloud.js";
22
+ import { fixedCloudRunServiceName } from "./stack-contract.js";
23
+ import { DEPLOY_GATEWAYS_CONFIG, parseDeployGateways } from "./stack-gateways.js";
24
+ import { applyStackConfig, type StackConfigInputs } from "./wizards/gcp-pulumi.js";
25
+
26
+ const ok = (stdout: string): GcloudResult => ({ ok: true, stdout, stderr: "", exitCode: 0 });
27
+ const failed = (stderr: string): GcloudResult => ({ ok: false, stdout: "", stderr, exitCode: 1 });
28
+
29
+ /** A gcloud fake: the first matching rule answers; every call is recorded. */
30
+ function fakeGcloud(rules: ReadonlyArray<[RegExp, GcloudResult]>) {
31
+ const calls: string[] = [];
32
+ const run = async (args: readonly string[]) => {
33
+ const line = args.join(" ");
34
+ calls.push(line);
35
+ for (const [re, result] of rules) if (re.test(line)) return result;
36
+ throw new Error(`unexpected gcloud call: ${line}`);
37
+ };
38
+ return { run, calls };
39
+ }
40
+
41
+ const TARGET = { provider: "gcp", projectId: "p-1", region: "europe-west1" } as const;
42
+
43
+ describe("parseDeployGateways", () => {
44
+ it("reads the installer's explicit value", () => {
45
+ expect(parseDeployGateways("true")).toBe(true);
46
+ expect(parseDeployGateways("false")).toBe(false);
47
+ });
48
+
49
+ it("declares the gateway on a stack configured before the key existed (every such install is migrated)", () => {
50
+ expect(parseDeployGateways(undefined)).toBe(true);
51
+ });
52
+
53
+ it("refuses anything else instead of guessing", () => {
54
+ expect(() => parseDeployGateways("no")).toThrow(DEPLOY_GATEWAYS_CONFIG);
55
+ expect(() => parseDeployGateways("")).toThrow(DEPLOY_GATEWAYS_CONFIG);
56
+ });
57
+ });
58
+
59
+ describe("readGatewayStart", () => {
60
+ it("a project without a gateway service has a gateway that never started", async () => {
61
+ const g = fakeGcloud([[/services list/, ok("")]]);
62
+ expect(await readGatewayStart(TARGET, g.run)).toEqual({
63
+ ok: true,
64
+ start: "never-started",
65
+ neverStarted: [],
66
+ });
67
+ expect(g.calls[0]).toContain("--filter=metadata.name~^caelo-production-gateway");
68
+ });
69
+
70
+ it("a gateway whose create failed at its boot check (no ready revision) never started", async () => {
71
+ // The scratch install of 2026-11-04: the service exists, no revision became ready.
72
+ const g = fakeGcloud([
73
+ [/services list/, ok("caelo-production-gateway-1a2b3c4\n")],
74
+ [/describe caelo-production-gateway-1a2b3c4 .*latestReadyRevisionName/, ok("\n")],
75
+ ]);
76
+ expect(await readGatewayStart(TARGET, g.run)).toEqual({
77
+ ok: true,
78
+ start: "never-started",
79
+ neverStarted: ["caelo-production-gateway-1a2b3c4"],
80
+ });
81
+ });
82
+
83
+ it("a gateway with a ready revision has started, even if its latest revision failed", async () => {
84
+ const g = fakeGcloud([
85
+ [/services list/, ok("caelo-production-gateway-1a2b3c4\n")],
86
+ [/describe/, ok("caelo-production-gateway-1a2b3c4-00007-xyz\n")],
87
+ ]);
88
+ expect(await readGatewayStart(TARGET, g.run)).toEqual({ ok: true, start: "started" });
89
+ });
90
+
91
+ it("looks for the data gateway on gcp-firebase, not the MCP-Auth-Proxy that kept the gateway's name", async () => {
92
+ const g = fakeGcloud([[/services list/, ok("")]]);
93
+ await readGatewayStart({ ...TARGET, provider: "gcp-firebase" }, g.run);
94
+ expect(g.calls[0]).toContain("--filter=metadata.name~^caelo-production-data-gateway");
95
+ });
96
+
97
+ it("fails loudly when the services cannot be read — no guess either way", async () => {
98
+ const list = fakeGcloud([[/services list/, failed("PERMISSION_DENIED: run.services.list")]]);
99
+ const r = await readGatewayStart(TARGET, list.run);
100
+ expect(r.ok).toBe(false);
101
+ if (!r.ok) expect(r.error).toContain("PERMISSION_DENIED");
102
+
103
+ const describe = fakeGcloud([
104
+ [/services list/, ok("caelo-production-gateway-1a2b3c4\n")],
105
+ [/describe/, failed("boom")],
106
+ ]);
107
+ const d = await readGatewayStart(TARGET, describe.run);
108
+ expect(d.ok).toBe(false);
109
+ });
110
+ });
111
+
112
+ describe("deleteNeverStartedGateways", () => {
113
+ it("deletes a gateway that never started (Pulumi cannot when deletionProtection is on)", async () => {
114
+ const g = fakeGcloud([
115
+ [/describe/, ok("")],
116
+ [/services delete caelo-production-gateway-1a2b3c4 /, ok("")],
117
+ ]);
118
+ expect(
119
+ await deleteNeverStartedGateways(TARGET, ["caelo-production-gateway-1a2b3c4"], g.run),
120
+ ).toEqual({ ok: true, deleted: ["caelo-production-gateway-1a2b3c4"] });
121
+ expect(g.calls.at(-1)).toContain("--quiet");
122
+ });
123
+
124
+ it("never deletes one that has started meanwhile (another run deployed it)", async () => {
125
+ const g = fakeGcloud([[/describe/, ok("caelo-production-gateway-1a2b3c4-00001-abc\n")]]);
126
+ const r = await deleteNeverStartedGateways(TARGET, ["caelo-production-gateway-1a2b3c4"], g.run);
127
+ expect(r.ok).toBe(false);
128
+ expect(g.calls.some((c) => c.includes("services delete"))).toBe(false);
129
+ });
130
+
131
+ it("treats an already-gone service as deleted, and fails loudly on any other error", async () => {
132
+ const gone = fakeGcloud([
133
+ [/describe/, ok("")],
134
+ [/services delete/, failed("NOT_FOUND: service not found")],
135
+ ]);
136
+ expect((await deleteNeverStartedGateways(TARGET, ["s"], gone.run)).ok).toBe(true);
137
+ const denied = fakeGcloud([
138
+ [/describe/, ok("")],
139
+ [/services delete/, failed("PERMISSION_DENIED")],
140
+ ]);
141
+ const r = await deleteNeverStartedGateways(TARGET, ["s"], denied.run);
142
+ expect(r.ok).toBe(false);
143
+ if (!r.ok) expect(r.error).toContain("PERMISSION_DENIED");
144
+ });
145
+ });
146
+
147
+ describe("deployOntoMigratedDatabase — the install order", () => {
148
+ function recorder() {
149
+ const steps: string[] = [];
150
+ return {
151
+ steps,
152
+ deps: {
153
+ up: async (deployGateways: boolean) => {
154
+ steps.push(`up(deployGateways=${deployGateways})`);
155
+ },
156
+ prepareDatabase: async () => {
157
+ steps.push("isolate + migrate");
158
+ },
159
+ },
160
+ };
161
+ }
162
+
163
+ it("a gateway that never started: up without it, migrate, then up with it", async () => {
164
+ const r = recorder();
165
+ expect(await deployOntoMigratedDatabase("never-started", r.deps)).toEqual({
166
+ databasePrepared: true,
167
+ });
168
+ expect(r.steps).toEqual([
169
+ "up(deployGateways=false)",
170
+ "isolate + migrate",
171
+ "up(deployGateways=true)",
172
+ ]);
173
+ });
174
+
175
+ it("a gateway that has started keeps the order every existing install had", async () => {
176
+ const r = recorder();
177
+ expect(await deployOntoMigratedDatabase("started", r.deps)).toEqual({
178
+ databasePrepared: false,
179
+ });
180
+ expect(r.steps).toEqual(["up(deployGateways=true)"]);
181
+ });
182
+
183
+ it("never deploys the gateway when the migrations fail", async () => {
184
+ const steps: boolean[] = [];
185
+ await expect(
186
+ deployOntoMigratedDatabase("never-started", {
187
+ up: async (d) => {
188
+ steps.push(d);
189
+ },
190
+ prepareDatabase: async () => {
191
+ throw new Error("migrate-admin-exec failed");
192
+ },
193
+ }),
194
+ ).rejects.toThrow("migrate-admin-exec");
195
+ expect(steps).toEqual([false]);
196
+ });
197
+ });
198
+
199
+ describe("applyStackConfig — deployGateways", () => {
200
+ const inputs: StackConfigInputs = {
201
+ provider: "gcp",
202
+ projectId: "p-1",
203
+ domain: "example.com",
204
+ stagingDomain: "staging.example.com",
205
+ ownerEmail: "o@example.com",
206
+ region: "europe-west1",
207
+ cloudSqlTier: "db-f1-micro",
208
+ cloudSqlHa: false,
209
+ adminMinInstances: 0,
210
+ adminMemory: "2Gi",
211
+ gatewayMinInstances: 0,
212
+ wafAdaptiveProtection: false,
213
+ iapAllowlist: ["user:o@example.com"],
214
+ imageDigests: { admin: "sha256:a", gateway: "sha256:g", "mcp-auth-proxy": "sha256:m" },
215
+ deployGateways: false,
216
+ };
217
+
218
+ it.each([false, true])("writes %p as the stack's config before every up", async (value) => {
219
+ const config: Record<string, string> = {};
220
+ const stack = {
221
+ setAllConfig: async (c: automation.ConfigMap) => {
222
+ for (const [k, v] of Object.entries(c)) config[k] = v.value;
223
+ },
224
+ setConfig: async (k: string, v: automation.ConfigValue) => {
225
+ config[k] = v.value;
226
+ },
227
+ getConfig: async (k: string) => {
228
+ if (!(k in config)) throw new Error(`configuration key '${k}' not found`);
229
+ return { value: config[k] as string };
230
+ },
231
+ } as unknown as automation.Stack;
232
+ await applyStackConfig(stack, { ...inputs, deployGateways: value }, []);
233
+ expect(config[`caelo-gcp:${DEPLOY_GATEWAYS_CONFIG}`]).toBe(String(value));
234
+ });
235
+ });
236
+
237
+ /** The resources a stack program declares under Pulumi mocks (src/__tests__/stack-under-mocks.ts). */
238
+ function declaredBy(
239
+ provider: "gcp" | "gcp-firebase",
240
+ deployGateways: "true" | "false",
241
+ ): { type: string; name: string; cloudName?: string }[] {
242
+ const config = {
243
+ domain: "example.com",
244
+ ownerEmail: "o@example.com",
245
+ project: "p-1",
246
+ region: "europe-west1",
247
+ secretReplication: "regional",
248
+ [DEPLOY_GATEWAYS_CONFIG]: deployGateways,
249
+ };
250
+ const r = Bun.spawnSync(
251
+ [
252
+ process.execPath,
253
+ resolve(import.meta.dir, "__tests__", "stack-under-mocks.ts"),
254
+ provider,
255
+ JSON.stringify(config),
256
+ ],
257
+ { stdout: "pipe", stderr: "pipe" },
258
+ );
259
+ if (r.exitCode !== 0) throw new Error(`stack-under-mocks ${provider}: ${r.stderr.toString()}`);
260
+ return r.stdout
261
+ .toString()
262
+ .split("\n")
263
+ .filter(Boolean)
264
+ .map((l) => JSON.parse(l) as { type: string; name: string; cloudName?: string });
265
+ }
266
+
267
+ const SERVICE = "gcp:cloudrunv2/service:Service";
268
+
269
+ describe.each(["gcp", "gcp-firebase"] as const)("%s stack — one URN per resource", (provider) => {
270
+ it.each(["false", "true"] as const)("with deployGateways=%s", (deployGateways) => {
271
+ // Pulumi fails the whole program on a duplicate URN (#1434).
272
+ const urns = declaredBy(provider, deployGateways).map((r) => `${r.type}::${r.name}`);
273
+ expect(new Set(urns).size).toBe(urns.length);
274
+ });
275
+ });
276
+
277
+ describe("gcp stack — the first up declares no gateway (Pulumi mocks)", () => {
278
+ // Everything that serves or routes visitor traffic to the gateway: the URL
279
+ // map goes with it, because the stack ignores its path rules after creation.
280
+ const GATEWAY_CHAIN = [
281
+ `${SERVICE}::caelo-production-gateway`,
282
+ "gcp:compute/regionNetworkEndpointGroup:RegionNetworkEndpointGroup::caelo-production-gateway-neg",
283
+ "gcp:compute/backendService:BackendService::caelo-production-gateway-backend",
284
+ "gcp:compute/uRLMap:URLMap::caelo-production-url-map",
285
+ "gcp:compute/targetHttpsProxy:TargetHttpsProxy::caelo-production-https-proxy",
286
+ "gcp:compute/globalForwardingRule:GlobalForwardingRule::caelo-production-https-fwd",
287
+ ];
288
+ const keys = (d: ReturnType<typeof declaredBy>) => d.map((r) => `${r.type}::${r.name}`);
289
+
290
+ it("withholds the gateway and its route, but declares what the migrations need", () => {
291
+ const first = keys(declaredBy("gcp", "false"));
292
+ for (const k of GATEWAY_CHAIN) expect(first).not.toContain(k);
293
+ for (const k of [
294
+ `${SERVICE}::caelo-production-admin`,
295
+ "gcp:sql/databaseInstance:DatabaseInstance::caelo-production-pg",
296
+ "gcp:sql/database:Database::caelo-production-cms-admin-db",
297
+ "gcp:sql/database:Database::caelo-production-cms-public-db",
298
+ "gcp:sql/database:Database::caelo-production-cms-public-staging-db",
299
+ "gcp:sql/user:User::caelo-production-pg-public",
300
+ "gcp:sql/user:User::caelo-production-pg-public-staging",
301
+ ]) {
302
+ expect(first).toContain(k);
303
+ }
304
+ });
305
+
306
+ it("declares all of it once the database is migrated — and adds nothing else", () => {
307
+ const first = keys(declaredBy("gcp", "false"));
308
+ const full = keys(declaredBy("gcp", "true"));
309
+ for (const k of GATEWAY_CHAIN) expect(full).toContain(k);
310
+ expect(full.filter((k) => !first.includes(k)).sort()).toEqual([...GATEWAY_CHAIN].sort());
311
+ });
312
+ });
313
+
314
+ describe("gcp-firebase stack — the first up declares no data gateway (Pulumi mocks)", () => {
315
+ const dataGateway = fixedCloudRunServiceName("gcp-firebase", "production", "gateway");
316
+ const isDataGateway = (r: { type: string; cloudName?: string }) =>
317
+ r.type === SERVICE && r.cloudName === dataGateway;
318
+
319
+ it("withholds the data gateway and its bindings, keeps the admin and the MCP-Auth-Proxy", () => {
320
+ const first = declaredBy("gcp-firebase", "false");
321
+ expect(first.filter(isDataGateway)).toEqual([]);
322
+ expect(first.map((r) => r.name)).not.toContain("caelo-production-data-gateway-public-invoker");
323
+ expect(first.map((r) => r.name)).not.toContain(
324
+ "caelo-production-data-gateway-viewer-for-admin-sa",
325
+ );
326
+ expect(first.filter((r) => r.type === SERVICE).length).toBe(2);
327
+ });
328
+
329
+ it("declares it once the database is migrated", () => {
330
+ const full = declaredBy("gcp-firebase", "true");
331
+ expect(full.filter(isDataGateway).length).toBe(1);
332
+ expect(full.map((r) => r.name)).toContain("caelo-production-data-gateway-public-invoker");
333
+ });
334
+ });
335
+
336
+ describe("the installer wires the order (wizards/gcp.ts)", () => {
337
+ const src = readFileSync(resolve(import.meta.dir, "wizards", "gcp.ts"), "utf8");
338
+ const converge = src.slice(src.indexOf("export async function runGcpConverge("));
339
+ const body = converge.slice(0, converge.indexOf("\nasync function ") + 1 || undefined);
340
+
341
+ it("runs the first pulumi up through deployOntoMigratedDatabase, with the gateway decided by the live read", () => {
342
+ const firstUp = body.indexOf("stepPulumiUp(");
343
+ expect(body.indexOf("stepReadGatewayStart(")).toBeGreaterThan(-1);
344
+ expect(body.indexOf("deployOntoMigratedDatabase(gatewayStart")).toBeGreaterThan(-1);
345
+ expect(firstUp).toBeGreaterThan(body.indexOf("deployOntoMigratedDatabase(gatewayStart"));
346
+ expect(body.indexOf("stepReadGatewayStart(")).toBeLessThan(firstUp);
347
+ });
348
+
349
+ it("every other up keeps the gateway declared", () => {
350
+ const calls = body.split("stepPulumiUp(").slice(1);
351
+ expect(calls.length).toBe(2);
352
+ expect(calls[0]).toMatch(/^installId, \{\s*\.\.\.upOpts,\s*deployGateways,/);
353
+ expect(calls[1]).toMatch(/^installId, \{\s*\.\.\.upOpts,\s*deployGateways: true,/);
354
+ });
355
+
356
+ it("isolates the logins and migrates inside prepareDatabase, before the gateway's up", () => {
357
+ const prepare = body.slice(body.indexOf("prepareDatabase: async () => {"));
358
+ const prepareBody = prepare.slice(0, prepare.indexOf("\n },\n"));
359
+ expect(prepareBody.indexOf("stepPublicRoleIsolation(projectId)")).toBeGreaterThan(-1);
360
+ expect(prepareBody.indexOf("stepMigrations(projectId, region)")).toBeGreaterThan(
361
+ prepareBody.indexOf("stepPublicRoleIsolation(projectId)"),
362
+ );
363
+ });
364
+
365
+ it("looks at the gateway again under the state lock before an up that withholds it", () => {
366
+ const up = src.slice(src.indexOf("async function stepPulumiUp("));
367
+ const lock = up.indexOf("acquireStateLock(");
368
+ const recheck = up.indexOf("withholdGatewayUnderLock(");
369
+ const pulumi = up.indexOf("pulumiUpGcp(");
370
+ expect(lock).toBeGreaterThan(-1);
371
+ expect(recheck).toBeGreaterThan(lock);
372
+ expect(pulumi).toBeGreaterThan(recheck);
373
+ expect(up.slice(pulumi, pulumi + 400)).toContain("deployGateways,");
374
+ });
375
+
376
+ it("migrates after the up only when it did not before", () => {
377
+ expect(body).toMatch(
378
+ /if \(!databasePrepared\) \{\s*phase\("Applying database migrations"\);\s*await stepMigrations\(projectId, region\);/,
379
+ );
380
+ });
381
+ });
@@ -0,0 +1,195 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * The installer's order on Google Cloud: no public gateway is deployed onto
5
+ * a database whose migrations have not run (CLAUDE.md §2, §11.C).
6
+ *
7
+ * The data gateway checks at boot that its login cannot reach cms_admin or
8
+ * the other environment's public database, and exits when it can
9
+ * (apps/api-gateway `databaseIsolationProblems`). Cloud SQL leaves CONNECT
10
+ * on every database granted to PUBLIC; the REVOKEs are migrations (0278,
11
+ * 0530), so migrations stay their single source. Cloud Run finishes creating
12
+ * a service only once its container listens, so a `pulumi up` that creates
13
+ * the gateway before the migrations ran fails on every fresh install — and
14
+ * the migration job needs the database, the network and the admin service
15
+ * that very `up` creates.
16
+ *
17
+ * So an install whose gateway has never started runs:
18
+ *
19
+ * 1. `pulumi up` without the gateway (stack-gateways.ts) — the database,
20
+ * the network, the secrets and the admin;
21
+ * 2. the gateway logins out of cloudsqlsuperuser, then the migrations;
22
+ * 3. `pulumi up` with the gateway, which now starts.
23
+ *
24
+ * An install whose gateway has started at least once has been migrated, and
25
+ * keeps the order it always had: `up` first (which may roll the admin onto
26
+ * the images the run deploys), migrations after. "Has started" is the live
27
+ * service's latest READY revision, not the Pulumi checkpoint: a first run
28
+ * that failed exactly here left a gateway that never started, and the next
29
+ * run must take the three steps, not repeat the failure. The staging gateway
30
+ * is the CLI's and is created after the migrations anyway
31
+ * (staging-gateway-setup.ts); `upgrade` never runs Pulumi and migrates
32
+ * before it rolls any gateway (upgrade/app-roll.ts).
33
+ */
34
+
35
+ import { isGcloudAuthError } from "./gcloud.js";
36
+ import type { GcloudRunner } from "./gcloud-retry.js";
37
+ import { GCP_STACK_ENV } from "./gcp-names.js";
38
+ import { cloudRunServicePrefix, type GcpProvider } from "./stack-contract.js";
39
+ import { lookupFailure } from "./upgrade/gcp-lookup.js";
40
+
41
+ /** Whether the install's data gateway has ever started. */
42
+ export type GatewayStart = "started" | "never-started";
43
+
44
+ /** What {@link readGatewayStart} found. */
45
+ export type GatewayStartRead =
46
+ | { readonly ok: true; readonly start: "started" }
47
+ | {
48
+ readonly ok: true;
49
+ readonly start: "never-started";
50
+ /** Gateway services that exist but never had a ready revision (a failed first run). */
51
+ readonly neverStarted: readonly string[];
52
+ }
53
+ | { readonly ok: false; readonly error: string };
54
+
55
+ /** The install the gateway is looked up on. */
56
+ export interface GatewayStartTarget {
57
+ readonly provider: GcpProvider;
58
+ readonly projectId: string;
59
+ readonly region: string;
60
+ }
61
+
62
+ /**
63
+ * Whether the live data gateway has a READY revision (Cloud Run's
64
+ * `status.latestReadyRevisionName`): only a gateway that passed its boot
65
+ * check has one. No gateway service at all is "never-started". Read-only.
66
+ *
67
+ * @returns an error (never a guess) when the services cannot be read
68
+ */
69
+ export async function readGatewayStart(
70
+ target: GatewayStartTarget,
71
+ run: GcloudRunner,
72
+ ): Promise<GatewayStartRead> {
73
+ const prefix = cloudRunServicePrefix(target.provider, GCP_STACK_ENV, "gateway");
74
+ const list = await run([
75
+ "run",
76
+ "services",
77
+ "list",
78
+ `--region=${target.region}`,
79
+ `--project=${target.projectId}`,
80
+ `--filter=metadata.name~^${prefix}`,
81
+ "--format=value(metadata.name)",
82
+ ]);
83
+ if (!list.ok) {
84
+ return {
85
+ ok: false,
86
+ error: lookupFailure(
87
+ { status: "error", stderr: list.stderr, authExpired: isGcloudAuthError(list.stderr) },
88
+ `${prefix}* Cloud Run service`,
89
+ "operator",
90
+ ),
91
+ };
92
+ }
93
+ const names = list.stdout
94
+ .split("\n")
95
+ .map((s) => s.trim())
96
+ .filter(Boolean);
97
+ for (const name of names) {
98
+ const ready = await latestReadyRevision(target, name, run);
99
+ if (!ready.ok) return ready;
100
+ if (ready.revision) return { ok: true, start: "started" };
101
+ }
102
+ return { ok: true, start: "never-started", neverStarted: names };
103
+ }
104
+
105
+ async function latestReadyRevision(
106
+ target: GatewayStartTarget,
107
+ name: string,
108
+ run: GcloudRunner,
109
+ ): Promise<{ ok: true; revision: string } | { ok: false; error: string }> {
110
+ const r = await run([
111
+ "run",
112
+ "services",
113
+ "describe",
114
+ name,
115
+ `--region=${target.region}`,
116
+ `--project=${target.projectId}`,
117
+ "--format=value(status.latestReadyRevisionName)",
118
+ ]);
119
+ return r.ok
120
+ ? { ok: true, revision: r.stdout.trim() }
121
+ : { ok: false, error: `describe ${name}: ${r.stderr.trim()}` };
122
+ }
123
+
124
+ /**
125
+ * Delete gateway services a failed first run left behind, which never had a
126
+ * ready revision — so never served a request. Run under the install's state
127
+ * lock, right before the `up` that withholds the gateway: Pulumi would
128
+ * delete them in that `up` anyway, but cannot when the operator enabled
129
+ * `deletionProtection`, and a fixed-name one outside the state would block
130
+ * the later create. The `up`'s refresh then drops them from the state.
131
+ * Each is described again first; one that has become ready meanwhile is
132
+ * kept and reported, never deleted.
133
+ *
134
+ * @returns the services deleted, or an error naming the one that stopped it
135
+ */
136
+ export async function deleteNeverStartedGateways(
137
+ target: GatewayStartTarget,
138
+ names: readonly string[],
139
+ run: GcloudRunner,
140
+ ): Promise<{ ok: true; deleted: string[] } | { ok: false; error: string }> {
141
+ const deleted: string[] = [];
142
+ for (const name of names) {
143
+ const ready = await latestReadyRevision(target, name, run);
144
+ if (!ready.ok) return ready;
145
+ if (ready.revision) {
146
+ return {
147
+ ok: false,
148
+ error: `${name} has started meanwhile (revision ${ready.revision}), so another run has deployed the gateway; re-run the installer`,
149
+ };
150
+ }
151
+ const r = await run([
152
+ "run",
153
+ "services",
154
+ "delete",
155
+ name,
156
+ `--region=${target.region}`,
157
+ `--project=${target.projectId}`,
158
+ "--quiet",
159
+ ]);
160
+ if (!r.ok && !/NOT_FOUND|not found|could not be found/i.test(r.stderr)) {
161
+ return { ok: false, error: `delete ${name}: ${r.stderr.trim()}` };
162
+ }
163
+ deleted.push(name);
164
+ }
165
+ return { ok: true, deleted };
166
+ }
167
+
168
+ /** The steps {@link deployOntoMigratedDatabase} orders. */
169
+ export interface GatewayBootstrapSteps {
170
+ /** `pulumi up` with the stack's `deployGateways` set to the argument. */
171
+ readonly up: (deployGateways: boolean) => Promise<void>;
172
+ /** The gateway logins out of cloudsqlsuperuser, then the migrations. */
173
+ readonly prepareDatabase: () => Promise<void>;
174
+ }
175
+
176
+ /**
177
+ * Run the installer's `pulumi up` so that the gateway is deployed only onto
178
+ * a migrated database (see the module comment).
179
+ *
180
+ * @returns whether the database was prepared here; when not, the caller
181
+ * runs the migrations after this `up`, as before
182
+ */
183
+ export async function deployOntoMigratedDatabase(
184
+ start: GatewayStart,
185
+ steps: GatewayBootstrapSteps,
186
+ ): Promise<{ readonly databasePrepared: boolean }> {
187
+ if (start === "started") {
188
+ await steps.up(true);
189
+ return { databasePrepared: false };
190
+ }
191
+ await steps.up(false);
192
+ await steps.prepareDatabase();
193
+ await steps.up(true);
194
+ return { databasePrepared: true };
195
+ }
@@ -162,6 +162,8 @@ describe("self-hosted: the generated compose gateway service (#635)", () => {
162
162
  caeloSecretKek: "0".repeat(64),
163
163
  dbTlsServerCertSha256: "abababababababababababababababababababababababababababababababab",
164
164
  internalSecret: "i".repeat(48),
165
+ stagingHost: "staging.example.com",
166
+ stagingGateSecret: "g".repeat(64),
165
167
  diskSize: "20Gi",
166
168
  images: {
167
169
  mode: "release" as const,
package/src/gcp-names.ts CHANGED
@@ -15,6 +15,8 @@
15
15
  * the CLI's dependencies.
16
16
  */
17
17
 
18
+ import { createHash } from "node:crypto";
19
+
18
20
  /** The Pulumi stack name the wizard provisions and `upgrade` operates on. */
19
21
  export const GCP_STACK_ENV = "production";
20
22
 
@@ -87,6 +89,57 @@ export function mcpAuthProxyServiceAccountEmail(projectId: string, env: string):
87
89
  return `${mcpAuthProxyServiceAccountId(env)}@${projectId}.iam.gserviceaccount.com`;
88
90
  }
89
91
 
92
+ /**
93
+ * #1330 — account id of the service account the staging gateway runs as. It
94
+ * may read the staging database's login password and the staging bucket,
95
+ * and nothing else: no live data, no media, no gate key (the gate key
96
+ * reaches it through the staging projection). Shortened: account ids max
97
+ * out at 30 characters (`caelo-production-stg-gateway-sa` would be 31).
98
+ */
99
+ export function stagingGatewayServiceAccountId(env: string): string {
100
+ return `${gcpNamePrefix(env)}-stg-gw-sa`;
101
+ }
102
+
103
+ /** Email of the service account the staging gateway runs as. */
104
+ export function stagingGatewayServiceAccountEmail(projectId: string, env: string): string {
105
+ return `${stagingGatewayServiceAccountId(env)}@${projectId}.iam.gserviceaccount.com`;
106
+ }
107
+
108
+ /**
109
+ * #1330 — the `gcp` staging gateway's load-balancer resources, CLI-owned
110
+ * (staging-gateway-setup.ts): its serverless NEG, its backend service and
111
+ * the managed certificate for the staging host. None matches a prefix the
112
+ * other lookups use (`…-waf`, `…-admin-backend`, `…-gateway-backend`,
113
+ * `…-mcp-auth-proxy-*`).
114
+ */
115
+ export function stagingGatewayEdgeNames(env: string): {
116
+ readonly neg: string;
117
+ readonly backend: string;
118
+ readonly cert: string;
119
+ readonly pathMatcher: string;
120
+ } {
121
+ const prefix = `${gcpNamePrefix(env)}-staging-gateway`;
122
+ return {
123
+ neg: `${prefix}-neg`,
124
+ backend: `${prefix}-backend`,
125
+ cert: `${gcpNamePrefix(env)}-staging-cert`,
126
+ pathMatcher: "staging",
127
+ };
128
+ }
129
+
130
+ /**
131
+ * #1330 — the second Firebase Hosting site of a `gcp-firebase` install,
132
+ * which serves the staging host through a `**` rewrite to the staging
133
+ * gateway (E13 a of #763). Derived from the live site's id (Hosting site ids
134
+ * are global, and the live one carries a random suffix): `caelo-<env>-stg-`
135
+ * plus six hex characters of its SHA-256, so the admin and the converge,
136
+ * which both know the live site id (`CAELO_FIREBASE_SITE`), name the same
137
+ * site without storing it anywhere.
138
+ */
139
+ export function firebaseStagingSiteId(env: string, liveSiteId: string): string {
140
+ return `${gcpNamePrefix(env)}-stg-${createHash("sha256").update(liveSiteId).digest("hex").slice(0, 6)}`;
141
+ }
142
+
90
143
  /**
91
144
  * Account id of the `gcp` stack's static-publisher service account. Account
92
145
  * ids max out at 30 chars, so the env is shortened.