@caelo-cms/provisioning 0.12.9 → 0.12.11

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 (123) hide show
  1. package/dist/agent-db.js +76 -3
  2. package/dist/cli.js +23 -2
  3. package/dist/cli.js.map +1 -1
  4. package/dist/collection-stores.d.ts +5 -0
  5. package/dist/collection-stores.d.ts.map +1 -0
  6. package/dist/collection-stores.js +21 -0
  7. package/dist/collection-stores.js.map +1 -0
  8. package/dist/collections-setup.d.ts +66 -0
  9. package/dist/collections-setup.d.ts.map +1 -0
  10. package/dist/collections-setup.js +252 -0
  11. package/dist/collections-setup.js.map +1 -0
  12. package/dist/compose.d.ts +27 -0
  13. package/dist/compose.d.ts.map +1 -1
  14. package/dist/compose.js +52 -1
  15. package/dist/compose.js.map +1 -1
  16. package/dist/gateway-edge.d.ts +13 -0
  17. package/dist/gateway-edge.d.ts.map +1 -1
  18. package/dist/gateway-edge.js +22 -0
  19. package/dist/gateway-edge.js.map +1 -1
  20. package/dist/gcp-names.d.ts +18 -48
  21. package/dist/gcp-names.d.ts.map +1 -1
  22. package/dist/gcp-names.js +11 -69
  23. package/dist/gcp-names.js.map +1 -1
  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 +35 -1
  27. package/dist/infra-contract.js.map +1 -1
  28. package/dist/reporting-job-catalog.d.ts +111 -0
  29. package/dist/reporting-job-catalog.d.ts.map +1 -0
  30. package/dist/reporting-job-catalog.js +306 -0
  31. package/dist/reporting-job-catalog.js.map +1 -0
  32. package/dist/reporting-job-setup.d.ts +11 -68
  33. package/dist/reporting-job-setup.d.ts.map +1 -1
  34. package/dist/reporting-job-setup.js +44 -100
  35. package/dist/reporting-job-setup.js.map +1 -1
  36. package/dist/runtime-secrets.d.ts.map +1 -1
  37. package/dist/runtime-secrets.js +3 -0
  38. package/dist/runtime-secrets.js.map +1 -1
  39. package/dist/self-hosted-backup.d.ts.map +1 -1
  40. package/dist/self-hosted-backup.js +18 -6
  41. package/dist/self-hosted-backup.js.map +1 -1
  42. package/dist/stack-contract.d.ts +75 -22
  43. package/dist/stack-contract.d.ts.map +1 -1
  44. package/dist/stack-contract.js +142 -51
  45. package/dist/stack-contract.js.map +1 -1
  46. package/dist/stack-converge.d.ts +20 -1
  47. package/dist/stack-converge.d.ts.map +1 -1
  48. package/dist/stack-converge.js +105 -2
  49. package/dist/stack-converge.js.map +1 -1
  50. package/dist/staging-gateway-setup.d.ts.map +1 -1
  51. package/dist/staging-gateway-setup.js +10 -5
  52. package/dist/staging-gateway-setup.js.map +1 -1
  53. package/dist/upgrade/admin-image-jobs.d.ts +4 -3
  54. package/dist/upgrade/admin-image-jobs.d.ts.map +1 -1
  55. package/dist/upgrade/admin-image-jobs.js +9 -16
  56. package/dist/upgrade/admin-image-jobs.js.map +1 -1
  57. package/dist/upgrade/app-roll.d.ts.map +1 -1
  58. package/dist/upgrade/app-roll.js +8 -7
  59. package/dist/upgrade/app-roll.js.map +1 -1
  60. package/dist/upgrade/converge.d.ts.map +1 -1
  61. package/dist/upgrade/converge.js +78 -50
  62. package/dist/upgrade/converge.js.map +1 -1
  63. package/dist/upgrader-iam-preflight.d.ts.map +1 -1
  64. package/dist/upgrader-iam-preflight.js +8 -18
  65. package/dist/upgrader-iam-preflight.js.map +1 -1
  66. package/dist/upgrader-setup.d.ts.map +1 -1
  67. package/dist/upgrader-setup.js +7 -15
  68. package/dist/upgrader-setup.js.map +1 -1
  69. package/dist/visitor-query-logs.d.ts +40 -0
  70. package/dist/visitor-query-logs.d.ts.map +1 -0
  71. package/dist/visitor-query-logs.js +41 -0
  72. package/dist/visitor-query-logs.js.map +1 -0
  73. package/dist/wizards/gcp-cost.d.ts.map +1 -1
  74. package/dist/wizards/gcp-cost.js +17 -9
  75. package/dist/wizards/gcp-cost.js.map +1 -1
  76. package/dist/wizards/gcp.d.ts.map +1 -1
  77. package/dist/wizards/gcp.js +45 -35
  78. package/dist/wizards/gcp.js.map +1 -1
  79. package/package.json +2 -2
  80. package/src/admin-memory.test.ts +57 -1
  81. package/src/cli.ts +23 -1
  82. package/src/collection-stores.ts +28 -0
  83. package/src/collections-setup.test.ts +237 -0
  84. package/src/collections-setup.ts +317 -0
  85. package/src/compose.ts +54 -1
  86. package/src/gateway-edge.test.ts +28 -0
  87. package/src/gateway-edge.ts +24 -0
  88. package/src/gateway-env-isolation.test.ts +141 -3
  89. package/src/gcp-names.ts +28 -84
  90. package/src/infra-contract.test.ts +5 -3
  91. package/src/infra-contract.ts +35 -1
  92. package/src/remote-mcp.test.ts +13 -1
  93. package/src/reporting-job-catalog.test.ts +156 -0
  94. package/src/reporting-job-catalog.ts +426 -0
  95. package/src/reporting-job-setup.test.ts +119 -6
  96. package/src/reporting-job-setup.ts +51 -158
  97. package/src/runtime-secrets.test.ts +19 -4
  98. package/src/runtime-secrets.ts +3 -0
  99. package/src/self-hosted-backup.test.ts +2 -2
  100. package/src/self-hosted-backup.ts +18 -6
  101. package/src/self-hosted-compose.test.ts +9 -3
  102. package/src/stack-contract.test.ts +62 -4
  103. package/src/stack-contract.ts +172 -59
  104. package/src/stack-converge-secrets.test.ts +4 -0
  105. package/src/stack-converge.test.ts +81 -3
  106. package/src/stack-converge.ts +124 -3
  107. package/src/staging-gateway-setup.test.ts +4 -0
  108. package/src/staging-gateway-setup.ts +16 -6
  109. package/src/upgrade/admin-image-jobs.ts +13 -25
  110. package/src/upgrade/app-roll.ts +7 -6
  111. package/src/upgrade/converge.ts +94 -77
  112. package/src/upgrade/upgrade.test.ts +97 -2
  113. package/src/upgrader-iam-preflight.ts +7 -20
  114. package/src/upgrader-job.test.ts +3 -0
  115. package/src/upgrader-setup.test.ts +3 -0
  116. package/src/upgrader-setup.ts +6 -17
  117. package/src/visitor-query-logs.ts +46 -0
  118. package/src/wizards/gcp-cost.ts +19 -9
  119. package/src/wizards/gcp.ts +51 -45
  120. package/stacks/aws/index.ts +18 -9
  121. package/stacks/azure/index.ts +19 -8
  122. package/stacks/gcp/index.ts +54 -1
  123. package/stacks/gcp-firebase/index.ts +28 -1
@@ -0,0 +1,237 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * Epic #1644 — the collection stores of a Google Cloud install and the log
5
+ * exclusion for visitors' search queries (collections-setup.ts,
6
+ * visitor-query-logs.ts), against a fake gcloud. The load-bearing
7
+ * assertions: both buckets private, the admin the only writer, each gateway
8
+ * a reader of its own environment's store only, and the exclusion filter
9
+ * dropping exactly the GETs that carry a visitor's query.
10
+ */
11
+
12
+ import { describe, expect, it } from "bun:test";
13
+ import {
14
+ COLLECTION_STORE_GRANTS,
15
+ edgeLogSinkName,
16
+ ensureCollectionStores,
17
+ ensureVisitorQueryLogExclusion,
18
+ visitorQueryExclusionFlag,
19
+ } from "./collections-setup.js";
20
+ import type { GcloudResult } from "./gcloud.js";
21
+ import { VISITOR_QUERY_LOG_FILTER } from "./visitor-query-logs.js";
22
+
23
+ const ok = (stdout = ""): GcloudResult => ({ ok: true, stdout, stderr: "", exitCode: 0 });
24
+ const fail = (stderr: string): GcloudResult => ({ ok: false, stdout: "", stderr, exitCode: 1 });
25
+
26
+ const TARGET = {
27
+ provider: "gcp-firebase",
28
+ projectId: "acme",
29
+ region: "europe-west1",
30
+ env: "production",
31
+ } as const;
32
+
33
+ const STAGING = "gs://acme-caelo-production-coll-staging";
34
+ const LIVE = "gs://acme-caelo-production-coll-live";
35
+ const ADMIN = "serviceAccount:caelo-production-run-sa@acme.iam.gserviceaccount.com";
36
+ const GATEWAY = "serviceAccount:caelo-production-gateway-sa@acme.iam.gserviceaccount.com";
37
+ const STG_GATEWAY = "serviceAccount:caelo-production-stg-gw-sa@acme.iam.gserviceaccount.com";
38
+
39
+ function fakeGcloud(rules: [RegExp, GcloudResult][] = []) {
40
+ const calls: string[][] = [];
41
+ const all: [RegExp, GcloudResult][] = [
42
+ ...rules,
43
+ [/^storage buckets describe/, fail("ERROR: (gcloud.storage.buckets.describe) NOT_FOUND: 404")],
44
+ [/^logging sinks describe _Default/, ok(JSON.stringify({ name: "_Default" }))],
45
+ ];
46
+ const run = async (args: string[]) => {
47
+ calls.push(args);
48
+ const line = args.join(" ");
49
+ return all.find(([re]) => re.test(line))?.[1] ?? ok("");
50
+ };
51
+ return { run, calls };
52
+ }
53
+
54
+ const flag = (args: string[], name: string) =>
55
+ args.find((a) => a.startsWith(`--${name}=`))?.slice(name.length + 3);
56
+
57
+ function bucketGrants(calls: string[][]) {
58
+ return calls
59
+ .filter((c) => c[0] === "storage" && c[2] === "add-iam-policy-binding")
60
+ .map((c) => [c[3], flag(c, "member"), flag(c, "role")]);
61
+ }
62
+
63
+ describe("ensureCollectionStores", () => {
64
+ it("creates both stores private, in the install's region, without soft delete", async () => {
65
+ const { run, calls } = fakeGcloud();
66
+ const r = await ensureCollectionStores(TARGET, { run, sleep: async () => {} });
67
+ expect(r.ok).toBe(true);
68
+ const created = calls.filter((c) => c[0] === "storage" && c[2] === "create");
69
+ expect(created.map((c) => c[3])).toEqual([STAGING, LIVE]);
70
+ for (const c of created) {
71
+ expect(c).toContain("--location=europe-west1");
72
+ expect(c).toContain("--uniform-bucket-level-access");
73
+ expect(c).toContain("--public-access-prevention");
74
+ expect(c).toContain("--soft-delete-duration=0");
75
+ }
76
+ });
77
+
78
+ it("lets the admin write both and each gateway read only its own store", async () => {
79
+ const { run, calls } = fakeGcloud();
80
+ await ensureCollectionStores(TARGET, { run, sleep: async () => {} });
81
+ expect(bucketGrants(calls)).toEqual([
82
+ [STAGING, ADMIN, "roles/storage.objectAdmin"],
83
+ [LIVE, ADMIN, "roles/storage.objectAdmin"],
84
+ [LIVE, GATEWAY, "roles/storage.objectViewer"],
85
+ [STAGING, STG_GATEWAY, "roles/storage.objectViewer"],
86
+ ]);
87
+ // No public principal anywhere, and no gateway ever writes.
88
+ for (const g of COLLECTION_STORE_GRANTS) {
89
+ if (g.member !== "admin") expect(g.role).toBe("roles/storage.objectViewer");
90
+ }
91
+ expect(calls.some((c) => c.join(" ").includes("allUsers"))).toBe(false);
92
+ });
93
+
94
+ it("keeps existing buckets and creates nothing twice", async () => {
95
+ const { run, calls } = fakeGcloud([
96
+ [/^storage buckets describe/, ok("acme-caelo-production-coll-x")],
97
+ ]);
98
+ const r = await ensureCollectionStores(TARGET, { run, sleep: async () => {} });
99
+ expect(r.ok).toBe(true);
100
+ expect(calls.some((c) => c[0] === "storage" && c[2] === "create")).toBe(false);
101
+ });
102
+
103
+ it("names a bucket another project holds instead of failing obscurely", async () => {
104
+ const { run } = fakeGcloud([
105
+ [
106
+ /^storage buckets create/,
107
+ fail("ERROR: HTTPError 409: The requested bucket name is not available."),
108
+ ],
109
+ ]);
110
+ const r = await ensureCollectionStores(TARGET, { run, sleep: async () => {} });
111
+ expect(r.ok).toBe(false);
112
+ if (!r.ok) expect(r.error).toContain("exists but does not belong to project acme");
113
+ });
114
+
115
+ it("waits for the staging gateway's account instead of failing, and says when it comes", async () => {
116
+ const { run, calls } = fakeGcloud([
117
+ [/^iam service-accounts describe caelo-production-stg-gw-sa/, fail("NOT_FOUND: 404")],
118
+ ]);
119
+ const r = await ensureCollectionStores(TARGET, { run, sleep: async () => {} });
120
+ expect(r.ok).toBe(true);
121
+ if (r.ok) {
122
+ expect(r.pending).toHaveLength(1);
123
+ expect(r.pending[0]).toContain("staging gateway");
124
+ }
125
+ expect(bucketGrants(calls).some((g) => g[1] === STG_GATEWAY)).toBe(false);
126
+ });
127
+
128
+ it("stops at a failed grant and says which", async () => {
129
+ const { run } = fakeGcloud([
130
+ [
131
+ /add-iam-policy-binding gs:\/\/acme-caelo-production-coll-live --member=serviceAccount:caelo-production-gateway-sa/,
132
+ fail("PERMISSION_DENIED"),
133
+ ],
134
+ ]);
135
+ const r = await ensureCollectionStores(TARGET, { run, sleep: async () => {} });
136
+ expect(r.ok).toBe(false);
137
+ if (!r.ok) expect(r.error).toContain(`roles/storage.objectViewer on ${LIVE}`);
138
+ });
139
+
140
+ it("puts the search-query exclusion on the project's logs as its last step", async () => {
141
+ const { run, calls } = fakeGcloud();
142
+ await ensureCollectionStores(TARGET, { run, sleep: async () => {} });
143
+ const update = calls.find((c) => c.slice(0, 3).join(" ") === "logging sinks update");
144
+ expect(update?.[3]).toBe("_Default");
145
+ });
146
+ });
147
+
148
+ describe("the visitor-query log exclusion", () => {
149
+ /** Cloud Logging's `=~` is RE2, matched anywhere; JS's RegExp agrees on this pattern. */
150
+ const urlPattern = new RegExp(
151
+ (/requestUrl=~"([^"]+)"/.exec(VISITOR_QUERY_LOG_FILTER) as RegExpExecArray)[1] as string,
152
+ );
153
+
154
+ it("matches only GETs whose URL is a collection operation with a query string", () => {
155
+ expect(VISITOR_QUERY_LOG_FILTER.startsWith('httpRequest.requestMethod="GET" AND ')).toBe(true);
156
+ for (const url of [
157
+ "https://acme.com/api/plugin/site-search/search?q=preise&lang=de&release=release-0123456789abcdef01234567.json",
158
+ "https://acme.com/api/plugin/site-search/suggest?q=pr&lang=de",
159
+ "https://caelo-production-data-gateway-abc.a.run.app/api/plugin/site-search/read?value=%2Fpreise%2F",
160
+ ]) {
161
+ expect(urlPattern.test(url)).toBe(true);
162
+ }
163
+ for (const url of [
164
+ "https://acme.com/api/plugin/site-search/search/release",
165
+ "https://acme.com/api/captcha/challenge",
166
+ "https://acme.com/api/_caelo/mail-link/newsletter/confirm?t=x",
167
+ "https://acme.com/preise/?q=x",
168
+ ]) {
169
+ expect(urlPattern.test(url)).toBe(false);
170
+ }
171
+ });
172
+
173
+ it("passes the filter through gcloud's dict flag without a comma split", () => {
174
+ const flagValue = visitorQueryExclusionFlag("production");
175
+ expect(flagValue.startsWith("^;^name=caelo-production-visitor-queries;filter=")).toBe(true);
176
+ expect(flagValue.split(";").length).toBe(4);
177
+ expect(VISITOR_QUERY_LOG_FILTER).not.toContain(";");
178
+ });
179
+
180
+ it("adds it to _Default and, on gcp, to the edge log sink", async () => {
181
+ const { run, calls } = fakeGcloud([
182
+ [
183
+ /^logging sinks describe caelo-production-edge-log-sink/,
184
+ ok(JSON.stringify({ exclusions: [] })),
185
+ ],
186
+ ]);
187
+ const r = await ensureVisitorQueryLogExclusion({ ...TARGET, provider: "gcp" }, { run });
188
+ expect(r.ok).toBe(true);
189
+ const updates = calls.filter((c) => c.slice(0, 3).join(" ") === "logging sinks update");
190
+ expect(updates.map((c) => c[3])).toEqual(["_Default", edgeLogSinkName("production")]);
191
+ for (const u of updates) {
192
+ expect(u).toContain(`--add-exclusion=${visitorQueryExclusionFlag("production")}`);
193
+ expect(u.some((a) => a.startsWith("--remove-exclusions"))).toBe(false);
194
+ }
195
+ });
196
+
197
+ it("leaves an exclusion in place alone, and replaces a changed or disabled one", async () => {
198
+ const same = { name: "caelo-production-visitor-queries", filter: VISITOR_QUERY_LOG_FILTER };
199
+ const a = fakeGcloud([
200
+ [/^logging sinks describe _Default/, ok(JSON.stringify({ exclusions: [same] }))],
201
+ ]);
202
+ await ensureVisitorQueryLogExclusion(TARGET, { run: a.run });
203
+ expect(a.calls.some((c) => c[2] === "update")).toBe(false);
204
+ for (const live of [
205
+ { ...same, filter: 'httpRequest.requestUrl=~"/api/"' },
206
+ { ...same, disabled: true },
207
+ ]) {
208
+ const b = fakeGcloud([
209
+ [/^logging sinks describe _Default/, ok(JSON.stringify({ exclusions: [live] }))],
210
+ ]);
211
+ await ensureVisitorQueryLogExclusion(TARGET, { run: b.run });
212
+ const update = b.calls.find((c) => c[2] === "update") ?? [];
213
+ expect(update).toContain("--remove-exclusions=caelo-production-visitor-queries");
214
+ expect(update).toContain(`--add-exclusion=${visitorQueryExclusionFlag("production")}`);
215
+ }
216
+ });
217
+
218
+ it("skips an edge sink a gcp install does not have, but never a missing _Default", async () => {
219
+ const a = fakeGcloud([
220
+ [/^logging sinks describe caelo-production-edge-log-sink/, fail("NOT_FOUND: 404")],
221
+ ]);
222
+ expect(
223
+ (await ensureVisitorQueryLogExclusion({ ...TARGET, provider: "gcp" }, { run: a.run })).ok,
224
+ ).toBe(true);
225
+ const b = fakeGcloud([[/^logging sinks describe _Default/, fail("PERMISSION_DENIED")]]);
226
+ const r = await ensureVisitorQueryLogExclusion(TARGET, { run: b.run });
227
+ expect(r.ok).toBe(false);
228
+ });
229
+
230
+ it("is what the gcp stack declares on its edge log sink", async () => {
231
+ const { readFileSync } = await import("node:fs");
232
+ const { resolve } = await import("node:path");
233
+ const src = readFileSync(resolve(import.meta.dir, "../stacks/gcp/index.ts"), "utf8");
234
+ expect(src).toContain("name: visitorQueryLogExclusionName(env),");
235
+ expect(src).toContain("filter: VISITOR_QUERY_LOG_FILTER,");
236
+ });
237
+ });
@@ -0,0 +1,317 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ /**
4
+ * Epic #1644 (R2 #1648, R3 #1649) — the collection stores of a Google Cloud
5
+ * install (`gcp`, `gcp-firebase`) and who may use them, plus the log
6
+ * exclusion that keeps visitors' search queries out of the logs
7
+ * (visitor-query-logs.ts).
8
+ *
9
+ * Plugin collections (a site search's pages, say) are built per Stage and
10
+ * served by the gateways from object storage: never from a database, never
11
+ * from the admin.
12
+ *
13
+ * gs://<project>-caelo-<env>-coll-staging change files the plugins
14
+ * write during a Stage (through the admin), the releases the
15
+ * collection index job builds from them; the staging gateway answers
16
+ * from here.
17
+ * gs://<project>-caelo-<env>-coll-live what Publish live copied from
18
+ * staging before it moved the live pointer; the live gateway answers
19
+ * from here.
20
+ *
21
+ * Both private: uniform access, public access prevention enforced, no soft
22
+ * delete (the admin deletes what no release keeps; a soft-deleted copy
23
+ * would only be billed). Every file is content-named and written once.
24
+ *
25
+ * Grants ({@link COLLECTION_STORE_GRANTS}), each the least that works:
26
+ *
27
+ * - the admin's run SA: objectAdmin on both — it writes change files,
28
+ * reads a plugin's document back for `ctx.collections.get`, copies a
29
+ * Stage's release files to live at Publish live, and deletes files no
30
+ * release keeps;
31
+ * - the live gateway's SA: objectViewer on the live store only;
32
+ * - the staging gateway's SA: objectViewer on the staging store only.
33
+ * Neither gateway can read the other environment's index (CLAUDE.md
34
+ * §2: staging content never reaches the live side), nor write any.
35
+ *
36
+ * The collection index job's own grants (read + create on the staging
37
+ * store, nothing on live) are its reporting-job spec's
38
+ * (reporting-job-setup.ts `collectionIndexJobSpec`).
39
+ *
40
+ * CLI-owned like the audit and capture buckets: `upgrade` never runs
41
+ * Pulumi, so the wizard (after the first `pulumi up`) and every converge
42
+ * run this, idempotently. Infrastructure contract 29.
43
+ */
44
+
45
+ import { gcloud as defaultGcloud, isGcloudNotFound } from "./gcloud.js";
46
+ import { type GcloudRunner, realSleep, runWithRetry, type Sleep } from "./gcloud-retry.js";
47
+ import {
48
+ gatewayServiceAccountEmail,
49
+ gcpBucketName,
50
+ gcpNamePrefix,
51
+ runServiceAccountEmail,
52
+ stagingGatewayServiceAccountEmail,
53
+ visitorQueryLogExclusionName,
54
+ } from "./gcp-names.js";
55
+ import type { GcpProvider } from "./stack-contract.js";
56
+ import {
57
+ DEFAULT_LOG_SINK,
58
+ VISITOR_QUERY_LOG_DESCRIPTION,
59
+ VISITOR_QUERY_LOG_FILTER,
60
+ } from "./visitor-query-logs.js";
61
+
62
+ /** Where the stores go. */
63
+ export interface CollectionStoresTarget {
64
+ readonly provider: GcpProvider;
65
+ readonly projectId: string;
66
+ readonly region: string;
67
+ /** Pulumi stack name (`production`). */
68
+ readonly env: string;
69
+ }
70
+
71
+ /** What {@link ensureCollectionStores} did. */
72
+ export type CollectionStoresResult =
73
+ | {
74
+ readonly ok: true;
75
+ readonly done: readonly string[];
76
+ /** What it could not do yet, and when it will (never a failure of the install). */
77
+ readonly pending: readonly string[];
78
+ }
79
+ | { readonly ok: false; readonly done: readonly string[]; readonly error: string };
80
+
81
+ /** Who a collection store grant is for. */
82
+ export type CollectionStoreReader = "admin" | "gateway" | "staging-gateway";
83
+
84
+ /** One bucket grant of the collection stores. */
85
+ export interface CollectionStoreGrant {
86
+ readonly bucket: "coll-staging" | "coll-live";
87
+ readonly member: CollectionStoreReader;
88
+ readonly role: "roles/storage.objectAdmin" | "roles/storage.objectViewer";
89
+ readonly why: string;
90
+ }
91
+
92
+ /** Every grant on the collection stores, but the index job's (see the file comment). */
93
+ export const COLLECTION_STORE_GRANTS: readonly CollectionStoreGrant[] = [
94
+ {
95
+ bucket: "coll-staging",
96
+ member: "admin",
97
+ role: "roles/storage.objectAdmin",
98
+ why: "the admin writes the plugins' change files, reads documents back and deletes what no release keeps",
99
+ },
100
+ {
101
+ bucket: "coll-live",
102
+ member: "admin",
103
+ role: "roles/storage.objectAdmin",
104
+ why: "Publish live copies a Stage's releases from staging, and the admin deletes what no live release keeps",
105
+ },
106
+ {
107
+ bucket: "coll-live",
108
+ member: "gateway",
109
+ role: "roles/storage.objectViewer",
110
+ why: "the live gateway answers search, suggest and read from the live releases",
111
+ },
112
+ {
113
+ bucket: "coll-staging",
114
+ member: "staging-gateway",
115
+ role: "roles/storage.objectViewer",
116
+ why: "the staging gateway answers search, suggest and read from the Stage's releases",
117
+ },
118
+ ];
119
+
120
+ function memberEmail(t: CollectionStoresTarget, who: CollectionStoreReader): string {
121
+ switch (who) {
122
+ case "admin":
123
+ return runServiceAccountEmail(t.projectId, t.env);
124
+ case "gateway":
125
+ return gatewayServiceAccountEmail(t.projectId, t.env);
126
+ case "staging-gateway":
127
+ return stagingGatewayServiceAccountEmail(t.projectId, t.env);
128
+ }
129
+ }
130
+
131
+ const ALREADY_EXISTS = /ALREADY_EXISTS|already exists|409/i;
132
+
133
+ /**
134
+ * Create both collection stores when missing and grant each reader its
135
+ * access. Never throws for a gcloud failure. The staging gateway's grant
136
+ * waits for its account when the install has none yet (its setup failed or
137
+ * has not run): `pending` says so, and the next converge grants it.
138
+ */
139
+ export async function ensureCollectionStores(
140
+ target: CollectionStoresTarget,
141
+ deps: { run?: GcloudRunner; sleep?: Sleep } = {},
142
+ ): Promise<CollectionStoresResult> {
143
+ const run = deps.run ?? defaultGcloud;
144
+ const sleep = deps.sleep ?? realSleep;
145
+ const project = `--project=${target.projectId}`;
146
+ const done: string[] = [];
147
+ const pending: string[] = [];
148
+
149
+ for (const kind of ["coll-staging", "coll-live"] as const) {
150
+ const url = `gs://${gcpBucketName(target.projectId, target.env, kind)}`;
151
+ const described = await run([
152
+ "storage",
153
+ "buckets",
154
+ "describe",
155
+ url,
156
+ project,
157
+ "--format=value(name)",
158
+ ]);
159
+ if (described.ok) {
160
+ done.push(`bucket ${url}`);
161
+ continue;
162
+ }
163
+ if (!isGcloudNotFound(described.stderr)) {
164
+ return { ok: false, done, error: `look up ${url}: ${described.stderr.trim()}` };
165
+ }
166
+ const created = await run([
167
+ "storage",
168
+ "buckets",
169
+ "create",
170
+ url,
171
+ project,
172
+ `--location=${target.region}`,
173
+ "--default-storage-class=STANDARD",
174
+ "--uniform-bucket-level-access",
175
+ "--public-access-prevention",
176
+ "--soft-delete-duration=0",
177
+ "--quiet",
178
+ ]);
179
+ if (!created.ok) {
180
+ return {
181
+ ok: false,
182
+ done,
183
+ error: ALREADY_EXISTS.test(created.stderr)
184
+ ? `${url} exists but does not belong to project ${target.projectId}; delete or rename that bucket, this install needs the name`
185
+ : `create ${url}: ${created.stderr.trim()}`,
186
+ };
187
+ }
188
+ done.push(`bucket ${url} (created: private, uniform access, no soft delete)`);
189
+ }
190
+
191
+ for (const g of COLLECTION_STORE_GRANTS) {
192
+ const url = `gs://${gcpBucketName(target.projectId, target.env, g.bucket)}`;
193
+ const email = memberEmail(target, g.member);
194
+ if (g.member === "staging-gateway") {
195
+ const exists = await run([
196
+ "iam",
197
+ "service-accounts",
198
+ "describe",
199
+ email,
200
+ project,
201
+ "--format=value(email)",
202
+ ]);
203
+ if (!exists.ok) {
204
+ if (!isGcloudNotFound(exists.stderr)) {
205
+ return { ok: false, done, error: `look up ${email}: ${exists.stderr.trim()}` };
206
+ }
207
+ pending.push(
208
+ `${g.role} on ${url} for the staging gateway: its account does not exist yet, so staging's search answers 503 until upgrade sets the staging gateway up and grants it`,
209
+ );
210
+ continue;
211
+ }
212
+ }
213
+ // The gateway's account may have been created a moment ago; IAM answers
214
+ // "does not exist" until it has propagated, so this is retried.
215
+ const r = await runWithRetry(run, sleep, [
216
+ "storage",
217
+ "buckets",
218
+ "add-iam-policy-binding",
219
+ url,
220
+ `--member=serviceAccount:${email}`,
221
+ `--role=${g.role}`,
222
+ // A bucket whose policy holds a conditional binding refuses an
223
+ // unconditional grant in non-interactive mode unless it says so.
224
+ "--condition=None",
225
+ project,
226
+ "--quiet",
227
+ "--format=none",
228
+ ]);
229
+ if (!r.ok)
230
+ return { ok: false, done, error: `grant ${g.role} on ${url} (${g.why}): ${r.stderr.trim()}` };
231
+ done.push(`${g.member}: ${g.role} on ${url}`);
232
+ }
233
+
234
+ const logs = await ensureVisitorQueryLogExclusion(target, { run });
235
+ done.push(...logs.done);
236
+ if (!logs.ok) return { ok: false, done, error: logs.error };
237
+ return { ok: true, done, pending };
238
+ }
239
+
240
+ /** The `gcp` stack's edge log sink to BigQuery (stacks/gcp/index.ts). */
241
+ export function edgeLogSinkName(env: string): string {
242
+ return `${gcpNamePrefix(env)}-edge-log-sink`;
243
+ }
244
+
245
+ /** One exclusion as `gcloud logging sinks describe --format=json` shows it. */
246
+ interface LiveExclusion {
247
+ readonly name?: string;
248
+ readonly filter?: string;
249
+ readonly disabled?: boolean;
250
+ }
251
+
252
+ /**
253
+ * The dict-flag value of the exclusion. `^;^` makes `;` the delimiter: the
254
+ * filter and the description carry commas (`gcloud topic escaping`).
255
+ */
256
+ export function visitorQueryExclusionFlag(env: string): string {
257
+ return `^;^name=${visitorQueryLogExclusionName(env)};filter=${VISITOR_QUERY_LOG_FILTER};description=${VISITOR_QUERY_LOG_DESCRIPTION}`;
258
+ }
259
+
260
+ /**
261
+ * Put {@link VISITOR_QUERY_LOG_FILTER} on `_Default` and, where it exists,
262
+ * the `gcp` edge log sink. An exclusion that is there with another filter
263
+ * or disabled is replaced in one update (remove, then add). Sinks the
264
+ * Owner created themselves are theirs; Caelo routes nothing through them.
265
+ */
266
+ export async function ensureVisitorQueryLogExclusion(
267
+ target: Pick<CollectionStoresTarget, "provider" | "projectId" | "env">,
268
+ deps: { run?: GcloudRunner } = {},
269
+ ): Promise<{ ok: true; done: string[] } | { ok: false; done: string[]; error: string }> {
270
+ const run = deps.run ?? defaultGcloud;
271
+ const project = `--project=${target.projectId}`;
272
+ const name = visitorQueryLogExclusionName(target.env);
273
+ const done: string[] = [];
274
+ const sinks = [
275
+ DEFAULT_LOG_SINK,
276
+ ...(target.provider === "gcp" ? [edgeLogSinkName(target.env)] : []),
277
+ ];
278
+ for (const sink of sinks) {
279
+ const described = await run(["logging", "sinks", "describe", sink, project, "--format=json"]);
280
+ if (!described.ok) {
281
+ // The edge sink exists from the gcp stack's first `pulumi up` on; an
282
+ // install without it has nothing to exclude there.
283
+ if (sink !== DEFAULT_LOG_SINK && isGcloudNotFound(described.stderr)) continue;
284
+ return { ok: false, done, error: `look up log sink ${sink}: ${described.stderr.trim()}` };
285
+ }
286
+ let live: LiveExclusion | undefined;
287
+ try {
288
+ const parsed = JSON.parse(described.stdout) as { exclusions?: LiveExclusion[] };
289
+ live = (parsed.exclusions ?? []).find((e) => e.name === name);
290
+ } catch {
291
+ return { ok: false, done, error: `log sink ${sink}: gcloud printed no JSON` };
292
+ }
293
+ if (live && live.filter === VISITOR_QUERY_LOG_FILTER && live.disabled !== true) {
294
+ done.push(`log sink ${sink}: exclusion ${name}`);
295
+ continue;
296
+ }
297
+ const update = await run([
298
+ "logging",
299
+ "sinks",
300
+ "update",
301
+ sink,
302
+ project,
303
+ ...(live ? [`--remove-exclusions=${name}`] : []),
304
+ `--add-exclusion=${visitorQueryExclusionFlag(target.env)}`,
305
+ "--quiet",
306
+ ]);
307
+ if (!update.ok) {
308
+ return {
309
+ ok: false,
310
+ done,
311
+ error: `exclude visitors' search queries from log sink ${sink}: ${update.stderr.trim()}`,
312
+ };
313
+ }
314
+ done.push(`log sink ${sink}: exclusion ${name} (${live ? "replaced" : "added"})`);
315
+ }
316
+ return { ok: true, done };
317
+ }
package/src/compose.ts CHANGED
@@ -29,6 +29,7 @@
29
29
 
30
30
  import { CADDY_REDIRECTS_FILE, SELF_HOSTED_CA_FILE, verifyFullQuery } from "@caelo-cms/shared";
31
31
  import { caddyRedirectReloadCommand } from "./caddy-redirects.js";
32
+ import { COLLECTIONS_LIVE_STORE_ENV, COLLECTIONS_STAGING_STORE_ENV } from "./collection-stores.js";
32
33
  import { DEFAULT_MAX_CONNECTIONS, stackPoolBudget } from "./pool-budget-stack.js";
33
34
  import {
34
35
  SELF_HOSTED_DB_HOST,
@@ -119,6 +120,35 @@ export const MEDIA_DIR = "media";
119
120
  /** Where {@link MEDIA_DIR} appears in the admin container (its `MEDIA_ROOT_DIR`). */
120
121
  export const MEDIA_ROOT = "/data/media";
121
122
 
123
+ /**
124
+ * Epic #1644 — `.caelo/<this>/` holds the plugin collection stores:
125
+ * `staging/` (change files and the releases each Stage builds; the index
126
+ * job runs inside the admin here) and `live/` (what Publish live copied).
127
+ * On the host, so a recreated container keeps them, like the media.
128
+ */
129
+ export const COLLECTIONS_DIR = "collections";
130
+ /** Where {@link COLLECTIONS_DIR} appears in the admin container (read-write). */
131
+ export const COLLECTIONS_ROOT = "/data/collections";
132
+ /**
133
+ * Where a gateway sees its own environment's store, read-only: the live
134
+ * gateway `live/`, the staging gateway `staging/`, never the other one.
135
+ */
136
+ export const GATEWAY_COLLECTIONS_ROOT = "/srv/collections";
137
+
138
+ /**
139
+ * #1654 — the visitor AI's key per environment: `live/key.json` and
140
+ * `staging/key.json` on the host. The admin replaces a file when the Owner
141
+ * stores or removes a key and reads none (no admin code path opens it); each
142
+ * gateway mounts its own environment's directory read-only, never the other.
143
+ * A directory, not the file: the admin replaces the file atomically (a new
144
+ * inode), which a single-file bind mount would never see.
145
+ */
146
+ export const VISITOR_AI_DIR = "visitor-ai";
147
+ /** Where {@link VISITOR_AI_DIR} appears in the admin container (read-write). */
148
+ export const VISITOR_AI_ROOT = "/data/visitor-ai";
149
+ /** Where a gateway sees its own environment's key directory. */
150
+ export const GATEWAY_VISITOR_AI_DIR = "/secrets/visitor-ai";
151
+
122
152
  /** The gateway's HTTP port inside the Compose network. */
123
153
  export const COMPOSE_GATEWAY_PORT = 8090;
124
154
 
@@ -492,6 +522,11 @@ ${serviceRuntime(
492
522
  `./${BOOTSTRAP_DIR}:/app/.caelo`,
493
523
  `./output:${SITE_OUTPUT_ROOT}`,
494
524
  `./${MEDIA_DIR}:${MEDIA_ROOT}`,
525
+ // Epic #1644 — both collection stores: the admin writes change files,
526
+ // builds a Stage's releases in-process and copies them to live.
527
+ `./${COLLECTIONS_DIR}:${COLLECTIONS_ROOT}`,
528
+ // #1654 — where the Owner's visitor-AI keys are stored, one per environment.
529
+ `./${VISITOR_AI_DIR}:${VISITOR_AI_ROOT}`,
495
530
  DATABASE_CA_MOUNT,
496
531
  ],
497
532
  )}
@@ -516,6 +551,10 @@ ${serviceRuntime(
516
551
  PORT: "${COMPOSE_ADMIN_PORT}"
517
552
  CAELO_OUTPUT_ROOT: "${SITE_OUTPUT_ROOT}"
518
553
  MEDIA_ROOT_DIR: "${MEDIA_ROOT}"
554
+ ${COLLECTIONS_STAGING_STORE_ENV}: "file://${COLLECTIONS_ROOT}/staging"
555
+ ${COLLECTIONS_LIVE_STORE_ENV}: "file://${COLLECTIONS_ROOT}/live"
556
+ CAELO_VISITOR_AI_KEY_FILE: "${VISITOR_AI_ROOT}/live/key.json"
557
+ CAELO_VISITOR_AI_STAGING_KEY_FILE: "${VISITOR_AI_ROOT}/staging/key.json"
519
558
  CAELO_PROVIDER: "self-hosted"
520
559
  ${poolEnvLines("admin")}
521
560
  NODE_ENV: production
@@ -525,7 +564,13 @@ ${env("RESEND_API_KEY", spec.resendApiKey)}`;
525
564
 
526
565
  function gatewayService(spec: ComposeSpec): string {
527
566
  return ` caelo-gateway:
528
- ${serviceRuntime(spec.images, "gateway", "bun run apps/api-gateway/src/server.ts", [DATABASE_CA_MOUNT])}
567
+ ${serviceRuntime(spec.images, "gateway", "bun run apps/api-gateway/src/server.ts", [
568
+ DATABASE_CA_MOUNT,
569
+ // Epic #1644 — the live collection store only, read-only.
570
+ `./${COLLECTIONS_DIR}/live:${GATEWAY_COLLECTIONS_ROOT}/live:ro`,
571
+ // #1654 — the live site's visitor-AI key only, read-only.
572
+ `./${VISITOR_AI_DIR}/live:${GATEWAY_VISITOR_AI_DIR}:ro`,
573
+ ])}
529
574
  restart: unless-stopped
530
575
  depends_on:
531
576
  postgres: { condition: service_healthy }
@@ -536,6 +581,8 @@ ${serviceRuntime(spec.images, "gateway", "bun run apps/api-gateway/src/server.ts
536
581
  # #1329 — the live site's gateway: it refuses anything of the staging data.
537
582
  ${GATEWAY_ENVIRONMENT_ENV}: "live"
538
583
  GATEWAY_PORT: "${COMPOSE_GATEWAY_PORT}"
584
+ ${COLLECTIONS_LIVE_STORE_ENV}: "file://${GATEWAY_COLLECTIONS_ROOT}/live"
585
+ CAELO_VISITOR_AI_KEY_FILE: "${GATEWAY_VISITOR_AI_DIR}/key.json"
539
586
  # Caddy is the one proxy in front (client-ip.ts in the gateway).
540
587
  ${TRUSTED_PROXY_HOPS_ENV}: "${GATEWAY_TRUSTED_PROXY_HOPS["self-hosted"]}"
541
588
  ${poolEnvLines("gateway")}
@@ -555,6 +602,10 @@ function stagingGatewayService(spec: ComposeSpec): string {
555
602
  ${serviceRuntime(spec.images, "gateway", "bun run apps/api-gateway/src/server.ts", [
556
603
  DATABASE_CA_MOUNT,
557
604
  `./output/output/staging:${STAGING_GATEWAY_STORAGE_DIR}:ro`,
605
+ // Epic #1644 — the staging collection store only, read-only.
606
+ `./${COLLECTIONS_DIR}/staging:${GATEWAY_COLLECTIONS_ROOT}/staging:ro`,
607
+ // #1654 — staging's own visitor-AI key, never the live one's directory.
608
+ `./${VISITOR_AI_DIR}/staging:${GATEWAY_VISITOR_AI_DIR}:ro`,
558
609
  ])}
559
610
  restart: unless-stopped
560
611
  depends_on:
@@ -564,6 +615,8 @@ ${serviceRuntime(spec.images, "gateway", "bun run apps/api-gateway/src/server.ts
564
615
  ${GATEWAY_ENVIRONMENT_ENV}: "staging"
565
616
  GATEWAY_PORT: "${COMPOSE_STAGING_GATEWAY_PORT}"
566
617
  ${STAGING_STORAGE_ENV}: "file://${STAGING_GATEWAY_STORAGE_DIR}"
618
+ ${COLLECTIONS_STAGING_STORE_ENV}: "file://${GATEWAY_COLLECTIONS_ROOT}/staging"
619
+ CAELO_VISITOR_AI_KEY_FILE: "${GATEWAY_VISITOR_AI_DIR}/key.json"
567
620
  # Caddy is the one proxy in front (client-ip.ts in the gateway).
568
621
  ${TRUSTED_PROXY_HOPS_ENV}: "${STAGING_GATEWAY_TRUSTED_PROXY_HOPS["self-hosted"]}"
569
622
  ${poolEnvLines("gateway")}