@caelo-cms/provisioning 0.11.19 → 0.11.20

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (121) hide show
  1. package/dist/agent-db.js +32 -0
  2. package/dist/aws-task-roles.d.ts +11 -0
  3. package/dist/aws-task-roles.d.ts.map +1 -1
  4. package/dist/aws-task-roles.js +19 -0
  5. package/dist/aws-task-roles.js.map +1 -1
  6. package/dist/azure-secrets.d.ts +22 -0
  7. package/dist/azure-secrets.d.ts.map +1 -0
  8. package/dist/azure-secrets.js +14 -0
  9. package/dist/azure-secrets.js.map +1 -0
  10. package/dist/caddy.d.ts +7 -0
  11. package/dist/caddy.d.ts.map +1 -1
  12. package/dist/caddy.js +22 -1
  13. package/dist/caddy.js.map +1 -1
  14. package/dist/cli.js +3 -0
  15. package/dist/cli.js.map +1 -1
  16. package/dist/gateway-armor.d.ts +24 -0
  17. package/dist/gateway-armor.d.ts.map +1 -0
  18. package/dist/gateway-armor.js +118 -0
  19. package/dist/gateway-armor.js.map +1 -0
  20. package/dist/gateway-edge.d.ts +128 -0
  21. package/dist/gateway-edge.d.ts.map +1 -0
  22. package/dist/gateway-edge.js +211 -0
  23. package/dist/gateway-edge.js.map +1 -0
  24. package/dist/infra-contract.d.ts +1 -1
  25. package/dist/infra-contract.d.ts.map +1 -1
  26. package/dist/infra-contract.js +21 -1
  27. package/dist/infra-contract.js.map +1 -1
  28. package/dist/lifecycle.d.ts.map +1 -1
  29. package/dist/lifecycle.js +8 -1
  30. package/dist/lifecycle.js.map +1 -1
  31. package/dist/pool-budget-stack.d.ts +22 -0
  32. package/dist/pool-budget-stack.d.ts.map +1 -1
  33. package/dist/pool-budget-stack.js +22 -1
  34. package/dist/pool-budget-stack.js.map +1 -1
  35. package/dist/public-service-shape.d.ts +45 -0
  36. package/dist/public-service-shape.d.ts.map +1 -0
  37. package/dist/public-service-shape.js +90 -0
  38. package/dist/public-service-shape.js.map +1 -0
  39. package/dist/remote-mcp-edge.d.ts +1 -1
  40. package/dist/remote-mcp-edge.js +1 -1
  41. package/dist/remote-mcp.d.ts.map +1 -1
  42. package/dist/remote-mcp.js +12 -2
  43. package/dist/remote-mcp.js.map +1 -1
  44. package/dist/serverless-backend.d.ts +27 -0
  45. package/dist/serverless-backend.d.ts.map +1 -0
  46. package/dist/serverless-backend.js +30 -0
  47. package/dist/serverless-backend.js.map +1 -0
  48. package/dist/stack-contract.d.ts +6 -0
  49. package/dist/stack-contract.d.ts.map +1 -1
  50. package/dist/stack-contract.js +24 -0
  51. package/dist/stack-contract.js.map +1 -1
  52. package/dist/stack-converge.d.ts +13 -0
  53. package/dist/stack-converge.d.ts.map +1 -1
  54. package/dist/stack-converge.js +27 -0
  55. package/dist/stack-converge.js.map +1 -1
  56. package/dist/staging-gateway-setup.d.ts +5 -0
  57. package/dist/staging-gateway-setup.d.ts.map +1 -1
  58. package/dist/staging-gateway-setup.js +60 -19
  59. package/dist/staging-gateway-setup.js.map +1 -1
  60. package/dist/upgrade/app-roll.d.ts +5 -1
  61. package/dist/upgrade/app-roll.d.ts.map +1 -1
  62. package/dist/upgrade/app-roll.js +20 -3
  63. package/dist/upgrade/app-roll.js.map +1 -1
  64. package/dist/upgrade/converge.d.ts.map +1 -1
  65. package/dist/upgrade/converge.js +27 -4
  66. package/dist/upgrade/converge.js.map +1 -1
  67. package/dist/upgrade/health.d.ts +13 -3
  68. package/dist/upgrade/health.d.ts.map +1 -1
  69. package/dist/upgrade/health.js +24 -7
  70. package/dist/upgrade/health.js.map +1 -1
  71. package/dist/upgrade/load-balancer-get.d.ts +17 -0
  72. package/dist/upgrade/load-balancer-get.d.ts.map +1 -0
  73. package/dist/upgrade/load-balancer-get.js +38 -0
  74. package/dist/upgrade/load-balancer-get.js.map +1 -0
  75. package/dist/upgrader-gcp.d.ts.map +1 -1
  76. package/dist/upgrader-gcp.js +8 -1
  77. package/dist/upgrader-gcp.js.map +1 -1
  78. package/dist/wizards/gcp-cost.d.ts +9 -0
  79. package/dist/wizards/gcp-cost.d.ts.map +1 -1
  80. package/dist/wizards/gcp-cost.js +69 -34
  81. package/dist/wizards/gcp-cost.js.map +1 -1
  82. package/package.json +2 -2
  83. package/src/aws-task-roles.ts +22 -0
  84. package/src/azure-secrets.ts +38 -0
  85. package/src/caddy.test.ts +19 -2
  86. package/src/caddy.ts +23 -0
  87. package/src/cli.ts +5 -0
  88. package/src/gateway-armor.ts +135 -0
  89. package/src/gateway-bootstrap.test.ts +1 -0
  90. package/src/gateway-edge.test.ts +262 -0
  91. package/src/gateway-edge.ts +256 -0
  92. package/src/gateway-env-isolation.test.ts +45 -6
  93. package/src/infra-contract.test.ts +5 -3
  94. package/src/infra-contract.ts +21 -1
  95. package/src/lifecycle.ts +8 -1
  96. package/src/pool-budget-stack.ts +25 -0
  97. package/src/pool-budget-stacks.test.ts +31 -0
  98. package/src/public-service-shape.test.ts +166 -0
  99. package/src/public-service-shape.ts +131 -0
  100. package/src/remote-mcp-edge.ts +1 -1
  101. package/src/remote-mcp.test.ts +38 -1
  102. package/src/remote-mcp.ts +25 -3
  103. package/src/serverless-backend.ts +47 -0
  104. package/src/stack-contract.test.ts +13 -0
  105. package/src/stack-contract.ts +25 -0
  106. package/src/stack-converge.test.ts +28 -1
  107. package/src/stack-converge.ts +30 -0
  108. package/src/staging-gateway-setup.test.ts +55 -3
  109. package/src/staging-gateway-setup.ts +79 -27
  110. package/src/upgrade/app-roll.ts +27 -3
  111. package/src/upgrade/converge.ts +33 -4
  112. package/src/upgrade/health.test.ts +88 -13
  113. package/src/upgrade/health.ts +32 -7
  114. package/src/upgrade/load-balancer-get.ts +64 -0
  115. package/src/upgrade/upgrade.test.ts +96 -3
  116. package/src/upgrader-gcp.ts +8 -1
  117. package/src/wizards/gcp-cost.ts +78 -35
  118. package/stacks/aws/index.ts +24 -22
  119. package/stacks/azure/index.ts +152 -64
  120. package/stacks/gcp/index.ts +35 -47
  121. package/stacks/gcp-firebase/index.ts +25 -13
@@ -0,0 +1,262 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * #1339 — the gateway's Cloud Armor rules (gateway-edge.ts): their order,
5
+ * the stack and the converge applying the same rules, and the converge
6
+ * bringing an install with the old single rate rule up to them.
7
+ */
8
+
9
+ import { describe, expect, it } from "bun:test";
10
+ import { readFileSync } from "node:fs";
11
+ import { resolve } from "node:path";
12
+ import { ensureGatewayArmorRules } from "./gateway-armor.js";
13
+ import {
14
+ CREDENTIAL_PATH_PATTERN,
15
+ DEFAULT_RULE_PRIORITY,
16
+ GATEWAY_ARMOR_BILLED_RULES,
17
+ GATEWAY_ARMOR_RULES,
18
+ gatewayArmorRuleArgs,
19
+ isGatewayArmorRule,
20
+ isLegacyGeneralBan,
21
+ type LiveGatewayArmorRule,
22
+ } from "./gateway-edge.js";
23
+ import type { GcloudResult } from "./gcloud.js";
24
+ import { MCP_ARMOR_RULE } from "./remote-mcp-edge.js";
25
+
26
+ const ok = (stdout = ""): GcloudResult => ({ ok: true, stdout, stderr: "", exitCode: 0 });
27
+
28
+ /** A rule as `gcloud compute security-policies describe --format=json` returns it. */
29
+ function live(args: ReturnType<typeof gatewayArmorRuleArgs>[number]): LiveGatewayArmorRule {
30
+ return JSON.parse(JSON.stringify(args)) as LiveGatewayArmorRule;
31
+ }
32
+
33
+ /** A fake gcloud holding one policy with `rules`, recording every call. */
34
+ function fakeGcloud(rules: LiveGatewayArmorRule[], policies = ["caelo-production-waf-1a2b3c"]) {
35
+ const calls: string[][] = [];
36
+ const run = async (args: string[]): Promise<GcloudResult> => {
37
+ calls.push(args);
38
+ if (args.includes("list")) return ok(`${policies.join("\n")}\n`);
39
+ if (args.includes("describe")) return ok(JSON.stringify({ rules }));
40
+ return ok();
41
+ };
42
+ return { run, calls };
43
+ }
44
+
45
+ describe("the gateway's Cloud Armor rules (#1339)", () => {
46
+ it("run in a fixed order: credential ban, captcha throttle, the API ban, then the OWASP packs", () => {
47
+ const priorities = GATEWAY_ARMOR_RULES.map((r) => r.priority);
48
+ expect(priorities).toEqual([...priorities].sort((a, b) => a - b));
49
+ expect(new Set(priorities).size).toBe(priorities.length);
50
+ // The MCP throttle's priority stays free: the converge of #1328 retires
51
+ // a rule there by its exact shape.
52
+ expect(priorities).not.toContain(MCP_ARMOR_RULE.priority);
53
+ expect(priorities).not.toContain(DEFAULT_RULE_PRIORITY);
54
+ expect(GATEWAY_ARMOR_BILLED_RULES).toBe(GATEWAY_ARMOR_RULES.length + 1);
55
+ });
56
+
57
+ it("bans a credential-op flood harder than the plugin's own limits, and only those paths", () => {
58
+ // Cloud Armor refuses capture groups (scratch install of v0.11.17).
59
+ expect(CREDENTIAL_PATH_PATTERN).not.toMatch(/\((?!\?:)/);
60
+ const re = new RegExp(CREDENTIAL_PATH_PATTERN);
61
+ for (const op of ["signup", "login", "request_password_reset", "reset_password"]) {
62
+ expect(re.test(`/api/plugin/auth/${op}`)).toBe(true);
63
+ }
64
+ for (const p of [
65
+ "/api/plugin/auth/me",
66
+ "/api/plugin/auth/logout",
67
+ "/api/plugin/auth/../auth/login",
68
+ "/api/plugin/auth/%6cogin",
69
+ "/api/plugin/auth/login/x",
70
+ ]) {
71
+ expect(re.test(p)).toBe(false);
72
+ }
73
+ const credential = GATEWAY_ARMOR_RULES[0];
74
+ expect(credential?.kind === "rate" && credential.count).toBe(30);
75
+ });
76
+
77
+ it("keeps staged pages out of the general ban: it matches /api/ paths only", () => {
78
+ const general = GATEWAY_ARMOR_RULES.find((r) => r.priority === 1001);
79
+ expect(general?.expression).toBe("request.path.contains('/api/')");
80
+ for (const r of GATEWAY_ARMOR_RULES) expect(r.expression).not.toContain("srcIpRanges");
81
+ });
82
+
83
+ it("are what the gcp stack declares", () => {
84
+ const src = readFileSync(resolve(import.meta.dir, "../stacks/gcp/index.ts"), "utf8");
85
+ expect(src).toContain("rules: gatewayArmorRuleArgs(),");
86
+ expect(src).not.toContain("evaluatePreconfiguredWaf(");
87
+ const args = gatewayArmorRuleArgs();
88
+ expect(args.at(-1)?.priority).toBe(DEFAULT_RULE_PRIORITY);
89
+ expect(args.at(-1)?.action).toBe("allow");
90
+ });
91
+
92
+ it("recognises a live rule only when it is exactly the spec", () => {
93
+ const args = gatewayArmorRuleArgs();
94
+ GATEWAY_ARMOR_RULES.forEach((spec, i) => {
95
+ const rule = live(args[i] as (typeof args)[number]);
96
+ expect(isGatewayArmorRule(rule, spec)).toBe(true);
97
+ expect(isGatewayArmorRule({ ...rule, action: "allow" }, spec)).toBe(false);
98
+ expect(isGatewayArmorRule({ ...rule, match: { expr: { expression: "true" } } }, spec)).toBe(
99
+ false,
100
+ );
101
+ });
102
+ });
103
+ });
104
+
105
+ describe("ensureGatewayArmorRules (the converge, contract 22)", () => {
106
+ const target = { projectId: "acme", env: "production" };
107
+
108
+ it("changes nothing when every rule is in place", async () => {
109
+ const { run, calls } = fakeGcloud(gatewayArmorRuleArgs().map(live));
110
+ const r = await ensureGatewayArmorRules(target, { run });
111
+ expect(r).toEqual({ ok: true, policy: "caelo-production-waf-1a2b3c", done: [] });
112
+ expect(calls.some((c) => c.includes("create") || c.includes("delete"))).toBe(false);
113
+ });
114
+
115
+ it("brings the old policy (one source-IP ban, untuned OWASP packs) up to the rules", async () => {
116
+ const old: LiveGatewayArmorRule[] = [
117
+ {
118
+ priority: 1000,
119
+ action: "rate_based_ban",
120
+ match: { versionedExpr: "SRC_IPS_V1", config: { srcIpRanges: ["*"] } },
121
+ rateLimitOptions: {
122
+ rateLimitThreshold: { count: 100, intervalSec: 60 },
123
+ conformAction: "allow",
124
+ exceedAction: "deny(429)",
125
+ enforceOnKey: "IP",
126
+ banDurationSec: 600,
127
+ },
128
+ },
129
+ {
130
+ priority: 2000,
131
+ action: "deny(403)",
132
+ match: { expr: { expression: "evaluatePreconfiguredWaf('sqli-v33-stable')" } },
133
+ },
134
+ {
135
+ priority: 2001,
136
+ action: "deny(403)",
137
+ match: { expr: { expression: "evaluatePreconfiguredWaf('xss-v33-stable')" } },
138
+ },
139
+ // An Owner's own rule stays.
140
+ {
141
+ priority: 5000,
142
+ action: "deny(403)",
143
+ match: { expr: { expression: "origin.region_code == 'XX'" } },
144
+ },
145
+ ];
146
+ const { run, calls } = fakeGcloud(old);
147
+ const r = await ensureGatewayArmorRules(target, { run });
148
+ expect(r.ok).toBe(true);
149
+ const writes = calls.filter((c) => c.includes("rules")).map((c) => `${c[3]} ${c[4]}`);
150
+ // Updated in place (never a moment without the rule); the old catch-all
151
+ // goes only after every new rule is in.
152
+ expect(writes).toEqual([
153
+ "create 800",
154
+ "create 810",
155
+ "create 1001",
156
+ "update 2000",
157
+ "update 2001",
158
+ "delete 1000",
159
+ ]);
160
+ const general = calls.find((c) => c[3] === "create" && c[4] === "1001") ?? [];
161
+ expect(general).toContain("--expression=request.path.contains('/api/')");
162
+ expect(general).toContain("--action=rate-based-ban");
163
+ expect(general).toContain("--ban-duration-sec=600");
164
+ expect(general).toContain("--security-policy=caelo-production-waf-1a2b3c");
165
+ const captcha = calls.find((c) => c[3] === "create" && c[4] === "810") ?? [];
166
+ expect(captcha).toContain("--action=throttle");
167
+ expect(captcha.some((a) => a.startsWith("--ban-duration-sec"))).toBe(false);
168
+ expect(calls.some((c) => c.includes("5000"))).toBe(false);
169
+ });
170
+
171
+ it("refuses when it cannot tell which policy is the gateway's", async () => {
172
+ for (const policies of [[], ["caelo-production-waf-a", "caelo-production-waf-b"]]) {
173
+ const { run, calls } = fakeGcloud([], policies);
174
+ const r = await ensureGatewayArmorRules(target, { run });
175
+ expect(r.ok).toBe(false);
176
+ expect(calls.some((c) => c.includes("create"))).toBe(false);
177
+ }
178
+ });
179
+
180
+ it("keeps the old catch-all ban when a new rule could not be written", async () => {
181
+ const calls: string[][] = [];
182
+ const old = {
183
+ priority: 1000,
184
+ action: "rate_based_ban",
185
+ match: { versionedExpr: "SRC_IPS_V1", config: { srcIpRanges: ["*"] } },
186
+ rateLimitOptions: {
187
+ rateLimitThreshold: { count: 100, intervalSec: 60 },
188
+ conformAction: "allow",
189
+ exceedAction: "deny(429)",
190
+ enforceOnKey: "IP",
191
+ banDurationSec: 600,
192
+ },
193
+ };
194
+ const run = async (args: string[]): Promise<GcloudResult> => {
195
+ calls.push(args);
196
+ if (args.includes("list")) return ok("caelo-production-waf-x\n");
197
+ if (args.includes("describe")) return ok(JSON.stringify({ rules: [old] }));
198
+ if (args[4] === "1001") return { ok: false, stdout: "", stderr: "QUOTA", exitCode: 1 };
199
+ return ok();
200
+ };
201
+ const r = await ensureGatewayArmorRules(target, { run });
202
+ expect(r.ok).toBe(false);
203
+ expect(calls.some((c) => c.includes("delete"))).toBe(false);
204
+ });
205
+
206
+ it("leaves an Owner's own rule at the old priority alone", async () => {
207
+ const own = {
208
+ priority: 1000,
209
+ action: "rate_based_ban",
210
+ match: { versionedExpr: "SRC_IPS_V1", config: { srcIpRanges: ["203.0.113.0/24"] } },
211
+ rateLimitOptions: {
212
+ rateLimitThreshold: { count: 100, intervalSec: 60 },
213
+ banDurationSec: 600,
214
+ },
215
+ };
216
+ const { run, calls } = fakeGcloud([...gatewayArmorRuleArgs().map(live), own]);
217
+ const r = await ensureGatewayArmorRules(target, { run });
218
+ expect(r).toEqual({ ok: true, policy: "caelo-production-waf-1a2b3c", done: [] });
219
+ expect(calls.some((c) => c.includes("delete"))).toBe(false);
220
+ });
221
+
222
+ it("deletes the old catch-all only when every option is the old stack's (#1429 review)", () => {
223
+ const old: LiveGatewayArmorRule = {
224
+ priority: 1000,
225
+ action: "rate_based_ban",
226
+ match: { versionedExpr: "SRC_IPS_V1", config: { srcIpRanges: ["*"] } } as never,
227
+ rateLimitOptions: {
228
+ rateLimitThreshold: { count: 100, intervalSec: 60 },
229
+ conformAction: "allow",
230
+ exceedAction: "deny(429)",
231
+ enforceOnKey: "IP",
232
+ banDurationSec: 600,
233
+ },
234
+ };
235
+ expect(isLegacyGeneralBan(old)).toBe(true);
236
+ const o = old.rateLimitOptions ?? {};
237
+ for (const customised of [
238
+ { ...old, rateLimitOptions: { ...o, enforceOnKey: "ALL" } },
239
+ { ...old, rateLimitOptions: { ...o, exceedAction: "deny(403)" } },
240
+ { ...old, rateLimitOptions: { ...o, banThreshold: { count: 500, intervalSec: 600 } } },
241
+ { ...old, rateLimitOptions: { ...o, banDurationSec: 3600 } },
242
+ ]) {
243
+ expect(isLegacyGeneralBan(customised as LiveGatewayArmorRule)).toBe(false);
244
+ }
245
+ });
246
+
247
+ it("stops at the first failed write and says which rule", async () => {
248
+ const calls: string[][] = [];
249
+ const run = async (args: string[]): Promise<GcloudResult> => {
250
+ calls.push(args);
251
+ if (args.includes("list")) return ok("caelo-production-waf-x\n");
252
+ if (args.includes("describe")) return ok(JSON.stringify({ rules: [] }));
253
+ return { ok: false, stdout: "", stderr: "PERMISSION_DENIED", exitCode: 1 };
254
+ };
255
+ const r = await ensureGatewayArmorRules(target, { run });
256
+ expect(r).toEqual({
257
+ ok: false,
258
+ error: "create rule 800 on caelo-production-waf-x: PERMISSION_DENIED",
259
+ done: [],
260
+ });
261
+ });
262
+ });
@@ -0,0 +1,256 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * #1339 (epic #763 P9, L5) — the Cloud Armor rules of the visitor gateway's
5
+ * policy on `gcp` (`<prefix>-waf`), declared once for the stack (new
6
+ * installs, imported from `dist/`) and for `cms-provision upgrade`
7
+ * ({@link ensureGatewayArmorRules} in gateway-armor.ts, existing installs).
8
+ * Pure module: no CLI or Pulumi imports.
9
+ *
10
+ * Cloud Armor is an extra layer here, never the only one (E3): the gateway
11
+ * sheds junk and rate-limits every route itself (docs/dev/gateway-hardening.md),
12
+ * and the cheap setup (gcp-firebase) has no WAF at all. What the edge adds
13
+ * is a per-IP ban before a request costs a Cloud Run instance.
14
+ *
15
+ * The policy also fronts the staging gateway's backend (staging-gateway-setup.ts),
16
+ * which serves whole staged pages. So the rules are per path:
17
+ *
18
+ * - Credential operations of the auth plugin (signup, login, password
19
+ * reset) — the brute-force targets — get the tightest ban, 30 a minute
20
+ * per IP: above every per-operation limit the plugin declares, so a
21
+ * visitor behind a shared NAT is stopped by the gateway's own limit
22
+ * first, and only a flood earns the ban. The pattern is anchored (as in
23
+ * remote-mcp-edge.ts): a traversal or encoded variant cannot match it and
24
+ * falls through to the general rule below.
25
+ * - The captcha challenge is throttled (429, no ban) at 60 a minute, the
26
+ * gateway's own per-client budget (`CAPTCHA_CHALLENGE_RATE_LIMIT`).
27
+ * - Every other path containing `/api/` keeps the original ban of 100 a
28
+ * minute. It used to match every request, so a reviewer who browsed a
29
+ * few staged pages (each with its styles, scripts, fonts and images)
30
+ * was banned from staging for ten minutes; staged pages are not `/api/`
31
+ * and are throttled by the staging gate itself.
32
+ * - The OWASP sqli/xss packs at sensitivity 1, Google's recommended
33
+ * starting level: the default (all signatures) flags ordinary comment
34
+ * and form text as an attack.
35
+ *
36
+ * Priorities: lower runs first, the first matching rule decides; the MCP
37
+ * throttle moved to the MCP-Auth-Proxy's own policy (#1328).
38
+ */
39
+
40
+ import { GENERAL_RATE_LIMIT_PRIORITY, type LiveArmorRule } from "./remote-mcp-edge.js";
41
+
42
+ /**
43
+ * Priority of the `/api/` ban. Not the old catch-all's (1000): the converge
44
+ * creates this one first and deletes the old one only afterwards, so an
45
+ * install is never without a ban (gateway-armor.ts).
46
+ */
47
+ export const API_BAN_PRIORITY = GENERAL_RATE_LIMIT_PRIORITY + 1;
48
+
49
+ /**
50
+ * The catch-all ban every policy carried before #1339 (`srcIpRanges: *`,
51
+ * 100 a minute, 10-minute ban), retired by the converge once the rules
52
+ * below are in place.
53
+ */
54
+ export const LEGACY_GENERAL_BAN = {
55
+ priority: GENERAL_RATE_LIMIT_PRIORITY,
56
+ count: 100,
57
+ intervalSec: 60,
58
+ banDurationSec: 600,
59
+ } as const;
60
+
61
+ /** A per-IP rate rule of the gateway's policy. */
62
+ interface ArmorRateRule {
63
+ readonly kind: "rate";
64
+ readonly priority: number;
65
+ readonly description: string;
66
+ readonly expression: string;
67
+ readonly action: "rate_based_ban" | "throttle";
68
+ /** Requests per {@link intervalSec} per source IP. */
69
+ readonly count: number;
70
+ readonly intervalSec: number;
71
+ /** Seconds an IP stays banned after it went over (rate_based_ban only). */
72
+ readonly banDurationSec?: number;
73
+ }
74
+
75
+ /** A deny rule of the gateway's policy. */
76
+ interface ArmorDenyRule {
77
+ readonly kind: "deny";
78
+ readonly priority: number;
79
+ readonly description: string;
80
+ readonly expression: string;
81
+ readonly action: "deny(403)";
82
+ }
83
+
84
+ export type GatewayArmorRule = ArmorRateRule | ArmorDenyRule;
85
+
86
+ /**
87
+ * The auth plugin's credential operations, as an anchored RE2 pattern
88
+ * (Cloud Armor's `matches`).
89
+ */
90
+ export const CREDENTIAL_PATH_PATTERN =
91
+ "^/api/plugin/auth/(?:signup|login|request_password_reset|reset_password)$";
92
+
93
+ /** Priority of Cloud Armor's default rule (it allows; every policy has one). */
94
+ export const DEFAULT_RULE_PRIORITY = 2147483647;
95
+
96
+ /** The gateway policy's rules, in evaluation order (the default allow excluded). */
97
+ export const GATEWAY_ARMOR_RULES: readonly GatewayArmorRule[] = [
98
+ {
99
+ kind: "rate",
100
+ priority: 800,
101
+ description: "Caelo gateway: per-IP ban on the auth plugin's credential operations",
102
+ expression: `request.path.matches('${CREDENTIAL_PATH_PATTERN}')`,
103
+ action: "rate_based_ban",
104
+ count: 30,
105
+ intervalSec: 60,
106
+ banDurationSec: 600,
107
+ },
108
+ {
109
+ kind: "rate",
110
+ priority: 810,
111
+ description: "Caelo gateway: per-IP throttle on captcha challenges",
112
+ expression: "request.path == '/api/captcha/challenge'",
113
+ action: "throttle",
114
+ count: 60,
115
+ intervalSec: 60,
116
+ },
117
+ {
118
+ kind: "rate",
119
+ priority: API_BAN_PRIORITY,
120
+ description: "Caelo gateway: per-IP ban on the visitor API",
121
+ expression: "request.path.contains('/api/')",
122
+ action: "rate_based_ban",
123
+ count: 100,
124
+ intervalSec: 60,
125
+ banDurationSec: 600,
126
+ },
127
+ {
128
+ kind: "deny",
129
+ priority: 2000,
130
+ description: "Caelo gateway: OWASP SQL injection signatures (sensitivity 1)",
131
+ expression: "evaluatePreconfiguredWaf('sqli-v33-stable', {'sensitivity': 1})",
132
+ action: "deny(403)",
133
+ },
134
+ {
135
+ kind: "deny",
136
+ priority: 2001,
137
+ description: "Caelo gateway: OWASP cross-site scripting signatures (sensitivity 1)",
138
+ expression: "evaluatePreconfiguredWaf('xss-v33-stable', {'sensitivity': 1})",
139
+ action: "deny(403)",
140
+ },
141
+ ];
142
+
143
+ /**
144
+ * Rules the gateway policy bills for, the default rule included (Cloud
145
+ * Armor Standard prices every rule of a policy, cloud.google.com/armor/pricing).
146
+ */
147
+ export const GATEWAY_ARMOR_BILLED_RULES = GATEWAY_ARMOR_RULES.length + 1;
148
+
149
+ /** One rule in the shape `gcp.compute.SecurityPolicy` `rules` take. */
150
+ function ruleArgs(r: GatewayArmorRule) {
151
+ const base = {
152
+ action: r.action,
153
+ priority: r.priority,
154
+ description: r.description,
155
+ match: { expr: { expression: r.expression } },
156
+ };
157
+ if (r.kind === "deny") return base;
158
+ return {
159
+ ...base,
160
+ rateLimitOptions: {
161
+ rateLimitThreshold: { count: r.count, intervalSec: r.intervalSec },
162
+ conformAction: "allow",
163
+ exceedAction: "deny(429)",
164
+ enforceOnKey: "IP",
165
+ ...(r.banDurationSec !== undefined ? { banDurationSec: r.banDurationSec } : {}),
166
+ },
167
+ };
168
+ }
169
+
170
+ /** The gateway policy's rules for the `gcp` stack, the default allow last. */
171
+ export function gatewayArmorRuleArgs() {
172
+ return [
173
+ ...GATEWAY_ARMOR_RULES.map(ruleArgs),
174
+ {
175
+ action: "allow",
176
+ priority: DEFAULT_RULE_PRIORITY,
177
+ description: "default rule",
178
+ match: { versionedExpr: "SRC_IPS_V1", config: { srcIpRanges: ["*"] } },
179
+ },
180
+ ];
181
+ }
182
+
183
+ /**
184
+ * The `gcloud compute security-policies rules create` flags for `r`
185
+ * (without the verb, priority and policy).
186
+ */
187
+ export function gatewayArmorRuleFlags(r: GatewayArmorRule): string[] {
188
+ const flags = [`--description=${r.description}`, `--expression=${r.expression}`];
189
+ if (r.kind === "deny") return [...flags, "--action=deny-403"];
190
+ return [
191
+ ...flags,
192
+ `--action=${r.action === "rate_based_ban" ? "rate-based-ban" : "throttle"}`,
193
+ `--rate-limit-threshold-count=${r.count}`,
194
+ `--rate-limit-threshold-interval-sec=${r.intervalSec}`,
195
+ "--conform-action=allow",
196
+ // gcloud spells deny(429) as deny-429.
197
+ "--exceed-action=deny-429",
198
+ "--enforce-on-key=IP",
199
+ ...(r.banDurationSec !== undefined ? [`--ban-duration-sec=${r.banDurationSec}`] : []),
200
+ ];
201
+ }
202
+
203
+ /** A live rule as `describe` lists it, with the ban duration a rate rule carries. */
204
+ export interface LiveGatewayArmorRule extends LiveArmorRule {
205
+ readonly rateLimitOptions?: LiveArmorRule["rateLimitOptions"] & {
206
+ readonly banDurationSec?: number;
207
+ };
208
+ }
209
+
210
+ /** Whether a live rule is exactly `spec`. */
211
+ export function isGatewayArmorRule(live: LiveGatewayArmorRule, spec: GatewayArmorRule): boolean {
212
+ if (live.priority !== spec.priority || live.action !== spec.action) return false;
213
+ if (live.match?.expr?.expression !== spec.expression) return false;
214
+ const o = live.rateLimitOptions;
215
+ if (spec.kind === "deny") return o === undefined;
216
+ return (
217
+ o?.rateLimitThreshold?.count === spec.count &&
218
+ o?.rateLimitThreshold?.intervalSec === spec.intervalSec &&
219
+ o?.conformAction === "allow" &&
220
+ o?.exceedAction === "deny(429)" &&
221
+ (o?.enforceOnKey ?? "ALL") === "IP" &&
222
+ o?.banDurationSec === spec.banDurationSec
223
+ );
224
+ }
225
+
226
+ /** The rate-limit options the pre-#1339 stack set on the catch-all ban. */
227
+ const LEGACY_RATE_OPTION_KEYS = new Set([
228
+ "rateLimitThreshold",
229
+ "conformAction",
230
+ "exceedAction",
231
+ "enforceOnKey",
232
+ "banDurationSec",
233
+ ]);
234
+
235
+ /** Whether a live rule is exactly {@link LEGACY_GENERAL_BAN}; any other rule at its priority is the Owner's. */
236
+ export function isLegacyGeneralBan(live: LiveGatewayArmorRule): boolean {
237
+ const l = LEGACY_GENERAL_BAN;
238
+ const o = live.rateLimitOptions;
239
+ const config = (live.match as { config?: { srcIpRanges?: readonly string[] } } | undefined)
240
+ ?.config;
241
+ return (
242
+ live.priority === l.priority &&
243
+ live.action === "rate_based_ban" &&
244
+ live.match?.expr === undefined &&
245
+ JSON.stringify(config?.srcIpRanges ?? null) === JSON.stringify(["*"]) &&
246
+ o?.rateLimitThreshold?.count === l.count &&
247
+ o?.rateLimitThreshold?.intervalSec === l.intervalSec &&
248
+ o?.banDurationSec === l.banDurationSec &&
249
+ o?.conformAction === "allow" &&
250
+ o?.exceedAction === "deny(429)" &&
251
+ o?.enforceOnKey === "IP" &&
252
+ // Every other option the old stack never set (a ban threshold, an
253
+ // enforce-on-key config, a redirect, …) makes it an Owner's rule.
254
+ Object.keys(o ?? {}).every((k) => LEGACY_RATE_OPTION_KEYS.has(k))
255
+ );
256
+ }
@@ -30,7 +30,12 @@
30
30
  import { describe, expect, it } from "bun:test";
31
31
  import { readFileSync } from "node:fs";
32
32
  import { resolve } from "node:path";
33
- import { AWS_SERVICE_SECRETS, secretsReadPolicy } from "./aws-task-roles.js";
33
+ import {
34
+ AWS_SERVICE_DATABASE_PASSWORDS,
35
+ AWS_SERVICE_SECRETS,
36
+ secretsReadPolicy,
37
+ } from "./aws-task-roles.js";
38
+ import { AZURE_SERVICE_DATABASE_SECRETS } from "./azure-secrets.js";
34
39
  import { generateDockerCompose } from "./compose.js";
35
40
  import {
36
41
  databaseUrls,
@@ -220,13 +225,35 @@ describe("azure: the gateway container app (#635)", () => {
220
225
  expect(stack("azure")).not.toMatch(/gateway_role:\$\{/);
221
226
  });
222
227
 
223
- it("gives no container app an identity or Key Vault access (review finding)", () => {
224
- // The vault uses RBAC authorisation: without a role assignment or a
225
- // managed identity no container app can read any vault secret, so the
226
- // gateway's only credential is the public_role URL in its env.
228
+ it("the gateway's identity reads public_role's password and no other secret (#1339, review finding)", () => {
229
+ // #1339 — the passwords left the URLs for Key Vault references. The vault
230
+ // uses RBAC authorisation, so an identity reads only the secrets it holds
231
+ // a role assignment on: one assignment per (reader, secret) from
232
+ // AZURE_SERVICE_DATABASE_SECRETS, scoped to the secret, never the vault.
227
233
  const src = stack("azure");
228
234
  expect(src).toContain("enableRbacAuthorization: true");
229
- expect(src).not.toMatch(/RoleAssignment|accessPolicies|identity\s*:|keyVaultUrl|secretRef/);
235
+ expect(src).not.toMatch(/accessPolicies/);
236
+ expect(src.match(/new azure\.authorization\.RoleAssignment\(/g)).toHaveLength(1);
237
+ expect(src).toContain("scope: keyVaultSecrets[name].id,");
238
+ // An app resolves its Key Vault references at creation: grants first (#1429 review).
239
+ expect(src).toContain("{ dependsOn: [...(args.secrets?.grants ?? [])] }");
240
+ expect(src).toContain(
241
+ "for (const name of new Set(Object.values(AZURE_SERVICE_DATABASE_SECRETS[reader]))) {",
242
+ );
243
+ expect(AZURE_SERVICE_DATABASE_SECRETS.gateway).toEqual({
244
+ PUBLIC_DATABASE_PASSWORD: "public-role-password",
245
+ });
246
+ const start = src.indexOf('serviceName: "gateway"');
247
+ const block = src.slice(start, src.indexOf("});", start));
248
+ expect(block).toContain("secrets: gatewaySecretReader,");
249
+ // The proxy reads nothing (#1328).
250
+ const proxy = src.slice(src.indexOf('serviceName: "mcp-auth-proxy"'));
251
+ expect(proxy.slice(0, proxy.indexOf("});"))).not.toContain("secrets:");
252
+ });
253
+
254
+ it("puts no password into a database URL (#1339)", () => {
255
+ const src = stack("azure");
256
+ expect(src).not.toMatch(/postgresql:\/\/[a-z_]+:\$\{/);
230
257
  });
231
258
  });
232
259
 
@@ -264,4 +291,16 @@ describe("aws: the stack (#635)", () => {
264
291
  });
265
292
  expect(() => secretsReadPolicy([])).toThrow();
266
293
  });
294
+
295
+ it("database passwords come from Secrets Manager, never inside a URL (#1339)", () => {
296
+ expect(stack("aws")).not.toMatch(/postgresql:\/\/[a-z_]+:\$\{/);
297
+ expect(AWS_SERVICE_DATABASE_PASSWORDS.gateway).toEqual({
298
+ PUBLIC_DATABASE_PASSWORD: "public-role-password",
299
+ });
300
+ for (const [service, vars] of Object.entries(AWS_SERVICE_DATABASE_PASSWORDS)) {
301
+ for (const secret of Object.values(vars)) {
302
+ expect(AWS_SERVICE_SECRETS[service as keyof typeof AWS_SERVICE_SECRETS]).toContain(secret);
303
+ }
304
+ }
305
+ });
267
306
  });
@@ -20,8 +20,8 @@ describe("infrastructure contract steps", () => {
20
20
  );
21
21
  });
22
22
 
23
- it("is at 20: public_role revoke (3), URL-map redirects role (4), no gateway cms_admin login (5), ops-bucket list (6), gateway proxy hops (7), quality-audit job (8), converge job (9), remote MCP (10), Google sign-in (11), project-level sign-in client (12), edge security headers (13), capture job (14), database verify-full TLS (15), MCP-Auth-Proxy (16), staging database (17), scheduler tick (18), scheduler tick as JSON (19), staging gateway (20)", () => {
24
- expect(INFRA_CONTRACT_VERSION).toBe(20);
23
+ it("is at 22: public_role revoke (3), URL-map redirects role (4), no gateway cms_admin login (5), ops-bucket list (6), gateway proxy hops (7), quality-audit job (8), converge job (9), remote MCP (10), Google sign-in (11), project-level sign-in client (12), edge security headers (13), capture job (14), database verify-full TLS (15), MCP-Auth-Proxy (16), staging database (17), scheduler tick (18), scheduler tick as JSON (19), staging gateway (20), gateway budget and plain-gcp repairs (21), per-path Cloud Armor rules (22)", () => {
24
+ expect(INFRA_CONTRACT_VERSION).toBe(22);
25
25
  expect(INFRA_CONTRACT_STEPS[3]).toContain("#633");
26
26
  expect(INFRA_CONTRACT_STEPS[4]).toContain("#587");
27
27
  expect(INFRA_CONTRACT_STEPS[5]).toContain("#635");
@@ -40,6 +40,8 @@ describe("infrastructure contract steps", () => {
40
40
  expect(INFRA_CONTRACT_STEPS[18]).toContain("#1140");
41
41
  expect(INFRA_CONTRACT_STEPS[19]).toContain("JSON");
42
42
  expect(INFRA_CONTRACT_STEPS[20]).toContain("#1330");
43
+ expect(INFRA_CONTRACT_STEPS[21]).toContain("#1463");
44
+ expect(INFRA_CONTRACT_STEPS[22]).toContain("#1339");
43
45
  });
44
46
 
45
47
  it("lists the pending steps oldest first", () => {
@@ -50,6 +52,6 @@ describe("infrastructure contract steps", () => {
50
52
  });
51
53
 
52
54
  it("names a version a newer release added by number", () => {
53
- expect(infraStepsText(20, 21)).toBe("infrastructure step 21 (see that release's notes)");
55
+ expect(infraStepsText(22, 23)).toBe("infrastructure step 23 (see that release's notes)");
54
56
  });
55
57
  });
@@ -22,7 +22,7 @@
22
22
  * whose app-roll references infrastructure an install does not have yet fails
23
23
  * at roll time, after migrations ran.
24
24
  */
25
- export const INFRA_CONTRACT_VERSION = 20;
25
+ export const INFRA_CONTRACT_VERSION = 22;
26
26
 
27
27
  // History (why each bump happened — an install below a number needs the
28
28
  // converge that introduced it):
@@ -169,6 +169,24 @@ export const INFRA_CONTRACT_VERSION = 20;
169
169
  // forwarder. New service, account, bucket, IAM and edge resources the
170
170
  // in-cloud upgrader may not create, and the app-roll rolls four
171
171
  // services from now on.
172
+ // 21 — #1463 and the plain-gcp repairs. The app-roll now brings the gateways
173
+ // to the connection budget (max instances, CAELO_DB_PUBLIC_POOL_MAX),
174
+ // but an in-cloud upgrader rolls with the code of the release it runs
175
+ // from, so without this bump an install would keep 100 gateway
176
+ // instances until the update after next; the converge job runs the
177
+ // target release's code. On `gcp` the gateway also gets its allUsers
178
+ // run.invoker (the stack never declared it, so every /api/ call
179
+ // answered Cloud Run's 403) and the CLI-owned backends created with
180
+ // the `https` port name get `http` and their NEG: IAM and
181
+ // load-balancer writes the in-cloud upgrader may not make.
182
+ // 22 — #1339: on `gcp` the gateway's Cloud Armor policy gets per-path
183
+ // rules (gateway-edge.ts): a tighter ban on the auth plugin's
184
+ // credential operations, a captcha throttle, the general ban limited
185
+ // to /api/ paths (it banned staging reviewers, whose pages share the
186
+ // policy since #1330) and the OWASP packs at sensitivity 1. Policy
187
+ // writes the in-cloud upgrader holds no compute rights for, so the
188
+ // converge applies them (gateway-armor.ts). Other providers have
189
+ // nothing to converge for it.
172
190
 
173
191
  /**
174
192
  * What each contract version adds, in operator terms — the upgrader's
@@ -196,6 +214,8 @@ export const INFRA_CONTRACT_STEPS: Readonly<Record<number, string>> = {
196
214
  18: "the scheduler tick that runs the admin's periodic work and plugin workers every few minutes: its service account, workflow and Cloud Scheduler job, and its IAP access (#1140)",
197
215
  19: "the scheduler tick sent as a JSON request, because the admin refused every tick before (#1140)",
198
216
  20: "the staging gateway that serves the staged site behind the staging gate on every address: its service, service account and grants, the private staging bucket, and the staging host's own route (a second Firebase Hosting site, or a host rule and certificate on the load balancer); the live gateway no longer holds the staging gate key (#1330, #1331)",
217
+ 21: "the gateways' scale-out and connection pool kept inside the database connection budget, and on Google Cloud load-balancer installs the gateway open to visitors and the sign-in and staging routes repaired (#1463)",
218
+ 22: "per-path Cloud Armor rules for the visitor and staging gateways on Google Cloud load-balancer installs: a tighter ban on sign-up, login and password reset, a captcha throttle, the general ban only on the visitor API, and fewer false positives from the OWASP rules (#1339)",
199
219
  };
200
220
 
201
221
  /**