@rehearsal-db/core 0.1.0-beta.13 → 0.1.0-beta.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 (169) hide show
  1. package/CHANGELOG.md +93 -0
  2. package/README.md +4 -1
  3. package/dist/package.json +100 -0
  4. package/dist/scripts/install/create_root_config.d.mts +3 -0
  5. package/dist/scripts/install/create_root_config.mjs +13 -0
  6. package/dist/scripts/runtime/manage_database.d.mts +6 -0
  7. package/{scripts → dist/scripts}/runtime/manage_database.mjs +6 -8
  8. package/dist/src/application/session.d.mts +96 -0
  9. package/dist/src/application/session.mjs +380 -0
  10. package/dist/src/baseline/artifact.d.mts +119 -0
  11. package/dist/src/baseline/artifact.mjs +522 -0
  12. package/dist/src/baseline/builder.d.mts +19 -0
  13. package/dist/src/baseline/builder.mjs +142 -0
  14. package/dist/src/baseline/input_discovery.d.mts +13 -0
  15. package/dist/src/baseline/input_discovery.mjs +149 -0
  16. package/dist/src/baseline/policy_review.d.mts +56 -0
  17. package/dist/src/baseline/policy_review.mjs +73 -0
  18. package/dist/src/baseline/preparation.d.mts +63 -0
  19. package/dist/src/baseline/preparation.mjs +295 -0
  20. package/dist/src/baseline/privacy_engine.d.mts +162 -0
  21. package/dist/src/baseline/privacy_engine.mjs +1162 -0
  22. package/dist/src/baseline/privacy_structured_json.d.mts +66 -0
  23. package/dist/src/baseline/privacy_structured_json.mjs +464 -0
  24. package/dist/src/baseline/sanitization_policy.d.mts +69 -0
  25. package/dist/src/baseline/sanitization_policy.mjs +227 -0
  26. package/dist/src/baseline/schema_snapshot.d.mts +19 -0
  27. package/dist/src/baseline/schema_snapshot.mjs +79 -0
  28. package/dist/src/cli/arguments.d.mts +43 -0
  29. package/dist/src/cli/arguments.mjs +135 -0
  30. package/dist/src/cli/guided.d.mts +51 -0
  31. package/dist/src/cli/guided.mjs +713 -0
  32. package/dist/src/cli/init_command.d.mts +21 -0
  33. package/dist/src/cli/init_command.mjs +90 -0
  34. package/dist/src/cli/project_commands.d.mts +157 -0
  35. package/dist/src/cli/project_commands.mjs +183 -0
  36. package/dist/src/cli/rehearsal.d.mts +7 -0
  37. package/dist/src/cli/rehearsal.mjs +706 -0
  38. package/dist/src/cli/renderers.d.mts +299 -0
  39. package/dist/src/cli/renderers.mjs +554 -0
  40. package/dist/src/cli/runtime_commands.d.mts +265 -0
  41. package/dist/src/cli/runtime_commands.mjs +599 -0
  42. package/dist/src/cli/source_commands.d.mts +432 -0
  43. package/dist/src/cli/source_commands.mjs +299 -0
  44. package/dist/src/cli/terminal.d.mts +59 -0
  45. package/dist/src/cli/terminal.mjs +230 -0
  46. package/dist/src/identity/claim.d.mts +144 -0
  47. package/dist/src/identity/claim.mjs +947 -0
  48. package/dist/src/identity/provider_configuration.d.mts +37 -0
  49. package/dist/src/identity/provider_configuration.mjs +132 -0
  50. package/dist/src/identity/storage.d.mts +21 -0
  51. package/dist/src/identity/storage.mjs +122 -0
  52. package/dist/src/index.d.mts +4 -0
  53. package/dist/src/index.mjs +3 -0
  54. package/dist/src/project/configuration.d.mts +181 -0
  55. package/dist/src/project/configuration.mjs +958 -0
  56. package/dist/src/project/install_scaffold.d.mts +42 -0
  57. package/dist/src/project/install_scaffold.mjs +263 -0
  58. package/dist/src/project/setup.d.mts +87 -0
  59. package/dist/src/project/setup.mjs +414 -0
  60. package/dist/src/project/support_report.d.mts +88 -0
  61. package/dist/src/project/support_report.mjs +83 -0
  62. package/dist/src/runtime/cleanup.d.mts +85 -0
  63. package/dist/src/runtime/cleanup.mjs +311 -0
  64. package/dist/src/runtime/migration_history.d.mts +51 -0
  65. package/dist/src/runtime/migration_history.mjs +170 -0
  66. package/dist/src/runtime/plan.d.mts +134 -0
  67. package/dist/src/runtime/plan.mjs +636 -0
  68. package/dist/src/runtime/policy.d.mts +66 -0
  69. package/dist/src/runtime/policy.mjs +369 -0
  70. package/dist/src/runtime/restore.d.mts +22 -0
  71. package/dist/src/runtime/restore.mjs +276 -0
  72. package/dist/src/runtime/service_environment.d.mts +11 -0
  73. package/dist/src/runtime/service_environment.mjs +58 -0
  74. package/dist/src/runtime/topology.d.mts +51 -0
  75. package/dist/src/runtime/topology.mjs +128 -0
  76. package/dist/src/shared/diagnostics.d.mts +97 -0
  77. package/dist/src/shared/diagnostics.mjs +170 -0
  78. package/dist/src/shared/human_output.d.mts +2 -0
  79. package/{src → dist/src}/shared/human_output.mjs +1 -3
  80. package/dist/src/shared/node_runtime.d.mts +14 -0
  81. package/dist/src/shared/node_runtime.mjs +25 -0
  82. package/dist/src/shared/operation_guard.d.mts +22 -0
  83. package/dist/src/shared/operation_guard.mjs +150 -0
  84. package/dist/src/shared/process_environment.d.mts +15 -0
  85. package/dist/src/shared/process_environment.mjs +50 -0
  86. package/dist/src/source/access.d.mts +165 -0
  87. package/dist/src/source/access.mjs +602 -0
  88. package/dist/src/source/asset_transfer.d.mts +27 -0
  89. package/dist/src/source/asset_transfer.mjs +202 -0
  90. package/dist/src/source/baseline.d.mts +66 -0
  91. package/dist/src/source/baseline.mjs +372 -0
  92. package/dist/src/source/external_reader.d.mts +42 -0
  93. package/dist/src/source/external_reader.mjs +278 -0
  94. package/dist/src/source/postgresql_access.d.mts +86 -0
  95. package/dist/src/source/postgresql_access.mjs +454 -0
  96. package/dist/src/source/privacy_paths.d.mts +10 -0
  97. package/dist/src/source/privacy_paths.mjs +27 -0
  98. package/dist/src/targets/driver.d.mts +2 -0
  99. package/dist/src/targets/driver.mjs +13 -0
  100. package/dist/src/targets/postgresql.d.mts +5 -0
  101. package/dist/src/targets/postgresql.mjs +641 -0
  102. package/dist/src/targets/supabase.d.mts +8 -0
  103. package/dist/src/targets/supabase.mjs +659 -0
  104. package/dist/src/targets/supabase_environment.d.mts +49 -0
  105. package/dist/src/targets/supabase_environment.mjs +162 -0
  106. package/dist/src/targets/target.d.mts +33 -0
  107. package/dist/src/targets/target.mjs +39 -0
  108. package/docs/README.md +1 -0
  109. package/docs/architecture.md +17 -9
  110. package/docs/configuration.md +49 -8
  111. package/docs/getting-started.md +28 -0
  112. package/docs/index.md +1 -0
  113. package/docs/production-source.md +43 -7
  114. package/docs/releasing.md +5 -3
  115. package/docs/roadmap.md +3 -2
  116. package/docs/sanitization.md +415 -14
  117. package/docs/standalone-workflow.md +12 -6
  118. package/docs/troubleshooting.md +5 -1
  119. package/docs/tutorial.md +5 -0
  120. package/docs/typescript.md +87 -0
  121. package/package.json +35 -29
  122. package/scripts/install/create_root_config.mjs +0 -36
  123. package/src/README.md +0 -17
  124. package/src/application/session.mjs +0 -435
  125. package/src/baseline/artifact.mjs +0 -684
  126. package/src/baseline/builder.mjs +0 -164
  127. package/src/baseline/input_discovery.mjs +0 -155
  128. package/src/baseline/policy_review.mjs +0 -92
  129. package/src/baseline/preparation.mjs +0 -323
  130. package/src/baseline/privacy_engine.mjs +0 -952
  131. package/src/baseline/sanitization_policy.mjs +0 -299
  132. package/src/baseline/schema_snapshot.mjs +0 -113
  133. package/src/cli/arguments.mjs +0 -126
  134. package/src/cli/guided.mjs +0 -814
  135. package/src/cli/init_command.mjs +0 -94
  136. package/src/cli/rehearsal.mjs +0 -970
  137. package/src/cli/renderers.mjs +0 -626
  138. package/src/cli/runtime_commands.mjs +0 -707
  139. package/src/cli/source_commands.mjs +0 -347
  140. package/src/cli/terminal.mjs +0 -275
  141. package/src/identity/claim.mjs +0 -1163
  142. package/src/identity/provider_configuration.mjs +0 -177
  143. package/src/identity/storage.mjs +0 -165
  144. package/src/project/configuration.mjs +0 -1337
  145. package/src/project/install_scaffold.mjs +0 -291
  146. package/src/project/setup.mjs +0 -466
  147. package/src/project/support_report.mjs +0 -105
  148. package/src/runtime/cleanup.mjs +0 -381
  149. package/src/runtime/migration_history.mjs +0 -220
  150. package/src/runtime/plan.mjs +0 -722
  151. package/src/runtime/policy.mjs +0 -438
  152. package/src/runtime/restore.mjs +0 -337
  153. package/src/runtime/service_environment.mjs +0 -82
  154. package/src/runtime/topology.mjs +0 -177
  155. package/src/shared/diagnostics.mjs +0 -207
  156. package/src/shared/node_runtime.mjs +0 -31
  157. package/src/shared/operation_guard.mjs +0 -162
  158. package/src/shared/process_environment.mjs +0 -68
  159. package/src/source/access.mjs +0 -753
  160. package/src/source/asset_transfer.mjs +0 -207
  161. package/src/source/baseline.mjs +0 -482
  162. package/src/source/external_reader.mjs +0 -255
  163. package/src/source/postgresql_access.mjs +0 -581
  164. package/src/source/privacy_paths.mjs +0 -38
  165. package/src/targets/postgresql.mjs +0 -808
  166. package/src/targets/supabase.mjs +0 -840
  167. package/src/targets/supabase_environment.mjs +0 -229
  168. package/src/targets/target.mjs +0 -66
  169. /package/{src/project → types}/configuration.d.mts +0 -0
@@ -1,581 +0,0 @@
1
- /**
2
- * Apply and retire an exact PostgreSQL source-access plan. This module is used
3
- * only by explicit source commands; ordinary runtime commands must not import it.
4
- */
5
-
6
- import { createHash, randomBytes } from "node:crypto";
7
- import {
8
- chmod,
9
- link,
10
- mkdir,
11
- open,
12
- readFile,
13
- rm,
14
- writeFile,
15
- } from "node:fs/promises";
16
- import { dirname, isAbsolute, relative, resolve } from "node:path";
17
- import pg from "pg";
18
- import {
19
- assertSourceAccessConfirmation,
20
- createSourceRetirementPlan,
21
- sourceAccessPolicyFingerprint,
22
- sourceTargetFingerprint,
23
- } from "./access.mjs";
24
- import { verifyExternalPostgresqlReader } from "./external_reader.mjs";
25
-
26
- const { Client } = pg;
27
- const IDENTIFIER = /^[a-z][a-z0-9_]{0,62}$/u;
28
-
29
- const quoteIdentifier = (value) => {
30
- if (!IDENTIFIER.test(value ?? ""))
31
- throw new Error("Unsafe source-access identifier.");
32
- return `"${value}"`;
33
- };
34
-
35
- const quoteLiteral = (value) => `'${String(value).replaceAll("'", "''")}'`;
36
-
37
- const ensureOwnedPath = (projectRoot, relativePath) => {
38
- const root = resolve(projectRoot);
39
- const path = resolve(root, relativePath);
40
- const child = relative(root, path);
41
- if (!child || child.startsWith("..") || isAbsolute(child))
42
- throw new Error("Source-access file escaped the project root.");
43
- return path;
44
- };
45
-
46
- const readerConnectionString = (
47
- administratorConnectionString,
48
- role,
49
- password,
50
- ) => {
51
- const target = new URL(administratorConnectionString);
52
- target.username = role;
53
- target.password = password;
54
- return target.toString();
55
- };
56
-
57
- const writeExclusiveSecret = async (path, content) => {
58
- await mkdir(dirname(path), { recursive: true, mode: 0o700 });
59
- const handle = await open(path, "wx", 0o600);
60
- try {
61
- await handle.writeFile(content);
62
- await handle.sync();
63
- } finally {
64
- await handle.close();
65
- }
66
- await chmod(path, 0o600);
67
- };
68
-
69
- const connection = async (connectionString, clientFactory) => {
70
- const client = clientFactory
71
- ? await clientFactory(connectionString)
72
- : new Client({
73
- connectionString,
74
- application_name: "rehearsal-source-access",
75
- });
76
- if (typeof client.connect === "function") await client.connect();
77
- return client;
78
- };
79
-
80
- const sourceRelation = (relation) =>
81
- `${quoteIdentifier(relation.source.schema)}.${quoteIdentifier(relation.source.table)}`;
82
-
83
- const viewRelation = (plan, relation) =>
84
- `${quoteIdentifier(plan.policy.exportSchema)}.${quoteIdentifier(relation.view)}`;
85
-
86
- const assertTarget = (plan, administratorConnectionString) => {
87
- if (
88
- sourceTargetFingerprint(administratorConnectionString) !==
89
- plan.policy.targetFingerprint
90
- ) {
91
- throw new Error(
92
- "Source administrator credential changed to a different target.",
93
- );
94
- }
95
- };
96
-
97
- const assertUnusedObjects = async (client, plan) => {
98
- const result = await client.query(
99
- `select
100
- exists(select 1 from pg_namespace where nspname = $1) as schema_exists,
101
- exists(select 1 from pg_roles where rolname = $2) as reader_exists,
102
- exists(select 1 from pg_roles where rolname = $3) as owner_exists`,
103
- [
104
- plan.policy.exportSchema,
105
- plan.policy.reader.role,
106
- plan.policy.reader.ownerRole,
107
- ],
108
- );
109
- const state = result.rows[0];
110
- if (state.schema_exists || state.reader_exists || state.owner_exists) {
111
- throw new Error(
112
- "Source-access targets already exist. Rehearsal will not overwrite or adopt them.",
113
- );
114
- }
115
- };
116
-
117
- const assertSourceColumns = async (client, relation) => {
118
- const result = await client.query(
119
- `select column_name
120
- from information_schema.columns
121
- where table_schema = $1 and table_name = $2
122
- order by ordinal_position`,
123
- [relation.source.schema, relation.source.table],
124
- );
125
- if (result.rows.length === 0) {
126
- throw new Error(
127
- `Declared source relation ${relation.source.schema}.${relation.source.table} does not exist.`,
128
- );
129
- }
130
- const actual = new Set(result.rows.map((row) => row.column_name));
131
- const missing = relation.columns.filter((column) => !actual.has(column));
132
- if (missing.length) {
133
- throw new Error(
134
- `Declared source relation is missing ${missing.length} reviewed column(s).`,
135
- );
136
- }
137
- };
138
-
139
- const runDenyChecks = async (client, plan) => {
140
- const role = plan.policy.reader.role;
141
- for (const relation of plan.policy.relations) {
142
- const raw = `${relation.source.schema}.${relation.source.table}`;
143
- const permissions = await client.query(
144
- `select
145
- has_table_privilege($1, $2, 'SELECT') as can_select,
146
- has_table_privilege($1, $2, 'INSERT') as can_insert,
147
- has_table_privilege($1, $2, 'UPDATE') as can_update,
148
- has_table_privilege($1, $2, 'DELETE') as can_delete`,
149
- [role, raw],
150
- );
151
- if (Object.values(permissions.rows[0]).some(Boolean)) {
152
- throw new Error(
153
- "Source reader unexpectedly has raw-table or write privileges.",
154
- );
155
- }
156
- }
157
- const escalation = await client.query(
158
- `select
159
- pg_has_role($1, $2, 'MEMBER') as owner_member,
160
- (select rolsuper or rolcreaterole or rolcreatedb or rolreplication or rolbypassrls
161
- from pg_roles where rolname = $1) as privileged`,
162
- [role, plan.policy.reader.ownerRole],
163
- );
164
- if (escalation.rows[0].owner_member || escalation.rows[0].privileged) {
165
- throw new Error(
166
- "Source reader unexpectedly has role-escalation privileges.",
167
- );
168
- }
169
- const network = await client.query(
170
- `select count(*)::integer as exposed
171
- from pg_proc p
172
- join pg_namespace n on n.oid = p.pronamespace
173
- where has_function_privilege($1, p.oid, 'EXECUTE')
174
- and (n.nspname in ('net', 'http') or p.proname ~* '^(dblink|http|net_)')
175
- and p.prosecdef`,
176
- [role],
177
- );
178
- if (network.rows[0].exposed > 0) {
179
- throw new Error(
180
- "Source reader can execute a security-definer network function.",
181
- );
182
- }
183
- };
184
-
185
- const assertApprovedOwnerScopes = (plan, environment) => {
186
- for (const relation of plan.policy.relations) {
187
- if (relation.rowScope.kind !== "approved-owner") continue;
188
- const value = environment[relation.rowScope.valueEnvironmentVariable];
189
- if (
190
- !value ||
191
- createHash("sha256").update(value).digest("hex") !==
192
- plan.review.relations.find((entry) => entry.view === relation.view)
193
- ?.rowScope.valueSha256
194
- ) {
195
- throw new Error(
196
- "Approved owner scope changed after the reviewed source-access preview.",
197
- );
198
- }
199
- }
200
- };
201
-
202
- const buildSourceAccessReceipt = ({ plan, expiresAt }) => ({
203
- receiptVersion: 1,
204
- accessMode: plan.policy.reader.mode,
205
- policyFingerprint: sourceAccessPolicyFingerprint(plan.policy),
206
- targetFingerprint: plan.policy.targetFingerprint,
207
- planDigest: plan.digest,
208
- exportSchema: plan.policy.exportSchema,
209
- views: plan.policy.relations.map((relation) => relation.view).sort(),
210
- relations: plan.policy.relations.map((relation) => ({
211
- ...relation.source,
212
- columns: relation.columns,
213
- })),
214
- migrationLedger: plan.policy.migrationLedger,
215
- readerRole: plan.policy.reader.role,
216
- ...(plan.policy.reader.mode === "managed"
217
- ? { ownerRole: plan.policy.reader.ownerRole }
218
- : {}),
219
- expiresAt,
220
- });
221
-
222
- const activateExternalPostgresqlSourceAccess = async ({
223
- plan,
224
- projectRoot,
225
- environment,
226
- clientFactory,
227
- now,
228
- }) => {
229
- const connectionString =
230
- environment[plan.policy.reader.connectionEnvironmentVariable];
231
- if (!connectionString) {
232
- throw new Error(
233
- `Missing ${plan.policy.reader.connectionEnvironmentVariable}.`,
234
- );
235
- }
236
- assertTarget(plan, connectionString);
237
- assertApprovedOwnerScopes(plan, environment);
238
- const verified = await verifyExternalPostgresqlReader({
239
- plan,
240
- connectionString,
241
- clientFactory,
242
- now,
243
- });
244
- const credentialPath = ensureOwnedPath(
245
- projectRoot,
246
- plan.policy.reader.credentialFile,
247
- );
248
- const receiptPath = ensureOwnedPath(
249
- projectRoot,
250
- ".rehearsal/source-access-receipt.json",
251
- );
252
- const temporaryCredentialPath = `${credentialPath}.building-${process.pid}`;
253
- const receipt = buildSourceAccessReceipt({
254
- plan,
255
- expiresAt: verified.expiresAt,
256
- });
257
- let receiptWritten = false;
258
- try {
259
- await writeExclusiveSecret(
260
- temporaryCredentialPath,
261
- `REHEARSAL_SOURCE_DATABASE_URL=${connectionString}\n`,
262
- );
263
- await writeFile(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`, {
264
- flag: "wx",
265
- mode: 0o600,
266
- });
267
- receiptWritten = true;
268
- await chmod(receiptPath, 0o600);
269
- await link(temporaryCredentialPath, credentialPath);
270
- await rm(temporaryCredentialPath, { force: true });
271
- } catch (error) {
272
- await rm(temporaryCredentialPath, { force: true });
273
- if (receiptWritten) await rm(receiptPath, { force: true });
274
- throw error;
275
- }
276
- return { receipt, credentialPath, receiptPath };
277
- };
278
-
279
- export const applyPostgresqlSourceAccess = async ({
280
- plan,
281
- confirmation,
282
- projectRoot = process.cwd(),
283
- environment = process.env,
284
- clientFactory,
285
- now = new Date(),
286
- }) => {
287
- assertSourceAccessConfirmation(plan, confirmation);
288
- if (plan.policy.reader.mode === "external") {
289
- return activateExternalPostgresqlSourceAccess({
290
- plan,
291
- projectRoot,
292
- environment,
293
- clientFactory,
294
- now,
295
- });
296
- }
297
- const administratorConnectionString =
298
- environment[plan.policy.administratorEnvironmentVariable];
299
- if (!administratorConnectionString) {
300
- throw new Error(`Missing ${plan.policy.administratorEnvironmentVariable}.`);
301
- }
302
- assertTarget(plan, administratorConnectionString);
303
- assertApprovedOwnerScopes(plan, environment);
304
- const password = randomBytes(32).toString("base64url");
305
- const expiresAt = new Date(
306
- now.valueOf() + plan.policy.reader.validForMinutes * 60_000,
307
- ).toISOString();
308
- const credentialPath = ensureOwnedPath(
309
- projectRoot,
310
- plan.policy.reader.credentialFile,
311
- );
312
- const receiptPath = ensureOwnedPath(
313
- projectRoot,
314
- ".rehearsal/source-access-receipt.json",
315
- );
316
- const temporaryCredentialPath = `${credentialPath}.building-${process.pid}`;
317
- const readerUrl = readerConnectionString(
318
- administratorConnectionString,
319
- plan.policy.reader.role,
320
- password,
321
- );
322
- let receiptReserved = false;
323
- let credentialLinked = false;
324
- try {
325
- await writeExclusiveSecret(
326
- temporaryCredentialPath,
327
- `REHEARSAL_SOURCE_DATABASE_URL=${readerUrl}\n`,
328
- );
329
- const receiptReservation = await open(receiptPath, "wx", 0o600);
330
- receiptReserved = true;
331
- await receiptReservation.close();
332
- await link(temporaryCredentialPath, credentialPath);
333
- credentialLinked = true;
334
- await rm(temporaryCredentialPath, { force: true });
335
- } catch (error) {
336
- await rm(temporaryCredentialPath, { force: true });
337
- if (credentialLinked) await rm(credentialPath, { force: true });
338
- if (receiptReserved) await rm(receiptPath, { force: true });
339
- throw error;
340
- }
341
- let client;
342
- try {
343
- client = await connection(administratorConnectionString, clientFactory);
344
- await client.query("begin");
345
- await client.query(
346
- "select pg_advisory_xact_lock(hashtext('rehearsal-source-access'))",
347
- );
348
- await assertUnusedObjects(client, plan);
349
- for (const relation of plan.policy.relations)
350
- await assertSourceColumns(client, relation);
351
- await client.query(
352
- `create role ${quoteIdentifier(plan.policy.reader.ownerRole)}
353
- nologin noinherit nosuperuser nocreatedb nocreaterole noreplication nobypassrls`,
354
- );
355
- await client.query(
356
- `create role ${quoteIdentifier(plan.policy.reader.role)}
357
- login password ${quoteLiteral(password)} valid until ${quoteLiteral(expiresAt)}
358
- noinherit nosuperuser nocreatedb nocreaterole noreplication nobypassrls`,
359
- );
360
- await client.query(
361
- `create schema ${quoteIdentifier(plan.policy.exportSchema)}
362
- authorization ${quoteIdentifier(plan.policy.reader.ownerRole)}`,
363
- );
364
- await client.query(
365
- `revoke all on schema ${quoteIdentifier(plan.policy.exportSchema)} from public`,
366
- );
367
- for (const schema of new Set(
368
- plan.policy.relations.map((relation) => relation.source.schema),
369
- )) {
370
- await client.query(
371
- `grant usage on schema ${quoteIdentifier(schema)}
372
- to ${quoteIdentifier(plan.policy.reader.ownerRole)}`,
373
- );
374
- }
375
- for (const relation of plan.policy.relations) {
376
- const columns = relation.columns.map(quoteIdentifier).join(", ");
377
- await client.query(
378
- `grant select (${columns}) on ${sourceRelation(relation)}
379
- to ${quoteIdentifier(plan.policy.reader.ownerRole)}`,
380
- );
381
- const filter =
382
- relation.rowScope.kind === "approved-owner"
383
- ? ` where ${quoteIdentifier(relation.rowScope.column)} = ${quoteLiteral(environment[relation.rowScope.valueEnvironmentVariable])}`
384
- : "";
385
- await client.query(
386
- `set local role ${quoteIdentifier(plan.policy.reader.ownerRole)}`,
387
- );
388
- await client.query(
389
- `create view ${viewRelation(plan, relation)} with (security_barrier = true) as
390
- select ${columns} from ${sourceRelation(relation)}${filter}`,
391
- );
392
- await client.query("reset role");
393
- await client.query(
394
- `revoke all on ${viewRelation(plan, relation)} from public`,
395
- );
396
- await client.query(
397
- `grant select on ${viewRelation(plan, relation)} to ${quoteIdentifier(plan.policy.reader.role)}`,
398
- );
399
- }
400
- await client.query(
401
- `grant usage on schema ${quoteIdentifier(plan.policy.exportSchema)}
402
- to ${quoteIdentifier(plan.policy.reader.role)}`,
403
- );
404
- const ledger = plan.policy.migrationLedger;
405
- await client.query(
406
- `grant usage on schema ${quoteIdentifier(ledger.schema)}
407
- to ${quoteIdentifier(plan.policy.reader.role)}`,
408
- );
409
- await client.query(
410
- `grant select (${[
411
- ledger.versionColumn,
412
- ledger.nameColumn,
413
- ledger.statementsColumn,
414
- ]
415
- .map(quoteIdentifier)
416
- .join(
417
- ", ",
418
- )}) on ${quoteIdentifier(ledger.schema)}.${quoteIdentifier(ledger.table)}
419
- to ${quoteIdentifier(plan.policy.reader.role)}`,
420
- );
421
- await client.query(
422
- `comment on schema ${quoteIdentifier(plan.policy.exportSchema)} is ${quoteLiteral(
423
- `rehearsal-source-access:${plan.digest}`,
424
- )}`,
425
- );
426
- await runDenyChecks(client, plan);
427
- await client.query("commit");
428
- } catch (error) {
429
- await client?.query("rollback").catch(() => undefined);
430
- await Promise.all([
431
- rm(credentialPath, { force: true }),
432
- rm(receiptPath, { force: true }),
433
- ]);
434
- throw error;
435
- } finally {
436
- await client?.end?.();
437
- }
438
- const receipt = buildSourceAccessReceipt({ plan, expiresAt });
439
- await writeFile(receiptPath, `${JSON.stringify(receipt, null, 2)}\n`, {
440
- flag: "w",
441
- mode: 0o600,
442
- });
443
- await chmod(receiptPath, 0o600);
444
- return { receipt, credentialPath, receiptPath };
445
- };
446
-
447
- export const planPostgresqlSourceAccessRetirement = async ({
448
- projectRoot = process.cwd(),
449
- targetFingerprint,
450
- }) => {
451
- const receiptPath = ensureOwnedPath(
452
- projectRoot,
453
- ".rehearsal/source-access-receipt.json",
454
- );
455
- const receipt = JSON.parse(await readFile(receiptPath, "utf8"));
456
- return {
457
- ...createSourceRetirementPlan({ receipt, targetFingerprint }),
458
- receipt,
459
- receiptPath,
460
- };
461
- };
462
-
463
- export const retirePostgresqlSourceAccess = async ({
464
- plan,
465
- confirmation,
466
- administratorEnvironmentVariable,
467
- projectRoot = process.cwd(),
468
- environment = process.env,
469
- credentialFile,
470
- clientFactory,
471
- }) => {
472
- if (confirmation !== plan.digest) {
473
- throw new Error(
474
- `Source retirement confirmation does not match. Expected ${plan.digest}.`,
475
- );
476
- }
477
- if (plan.review.accessMode === "external") {
478
- await Promise.all([
479
- rm(ensureOwnedPath(projectRoot, credentialFile), { force: true }),
480
- rm(plan.receiptPath, { force: true }),
481
- ]);
482
- return { retired: true, providerResourcesPreserved: true };
483
- }
484
- const administratorConnectionString =
485
- environment[administratorEnvironmentVariable];
486
- if (!administratorConnectionString)
487
- throw new Error(`Missing ${administratorEnvironmentVariable}.`);
488
- assertTarget(
489
- { policy: { targetFingerprint: plan.review.targetFingerprint } },
490
- administratorConnectionString,
491
- );
492
- const client = await connection(administratorConnectionString, clientFactory);
493
- try {
494
- await client.query("begin");
495
- await client.query(
496
- "select pg_advisory_xact_lock(hashtext('rehearsal-source-access'))",
497
- );
498
- const inventory = await client.query(
499
- `select c.relname,
500
- obj_description(n.oid, 'pg_namespace') as schema_comment
501
- from pg_class c join pg_namespace n on n.oid = c.relnamespace
502
- where n.nspname = $1 and c.relkind in ('v', 'm')
503
- order by c.relname`,
504
- [plan.review.exportSchema],
505
- );
506
- if (
507
- inventory.rows.map((row) => row.relname).join("\0") !==
508
- plan.review.views.join("\0")
509
- ) {
510
- throw new Error(
511
- "Source export schema changed after preparation; retirement stopped.",
512
- );
513
- }
514
- if (
515
- inventory.rows.some(
516
- (row) =>
517
- row.schema_comment !==
518
- `rehearsal-source-access:${plan.review.preparationDigest}`,
519
- )
520
- ) {
521
- throw new Error("Source export schema ownership receipt does not match.");
522
- }
523
- for (const view of plan.review.views) {
524
- await client.query(
525
- `drop view ${quoteIdentifier(plan.review.exportSchema)}.${quoteIdentifier(view)}`,
526
- );
527
- }
528
- await client.query(
529
- `drop schema ${quoteIdentifier(plan.review.exportSchema)} restrict`,
530
- );
531
- for (const relation of plan.receipt.relations) {
532
- await client.query(
533
- `revoke select (${relation.columns.map(quoteIdentifier).join(", ")})
534
- on table ${quoteIdentifier(relation.schema)}.${quoteIdentifier(relation.table)}
535
- from ${quoteIdentifier(plan.review.ownerRole)}`,
536
- );
537
- }
538
- for (const schema of new Set(
539
- plan.receipt.relations.map((relation) => relation.schema),
540
- )) {
541
- await client.query(
542
- `revoke usage on schema ${quoteIdentifier(schema)}
543
- from ${quoteIdentifier(plan.review.ownerRole)}`,
544
- );
545
- }
546
- const ledger = plan.receipt.migrationLedger;
547
- await client.query(
548
- `revoke all privileges on table ${quoteIdentifier(ledger.schema)}.${quoteIdentifier(ledger.table)}
549
- from ${quoteIdentifier(plan.review.readerRole)}`,
550
- );
551
- await client.query(
552
- `revoke usage on schema ${quoteIdentifier(ledger.schema)}
553
- from ${quoteIdentifier(plan.review.readerRole)}`,
554
- );
555
- await client.query(`drop role ${quoteIdentifier(plan.review.readerRole)}`);
556
- await client.query(`drop role ${quoteIdentifier(plan.review.ownerRole)}`);
557
- await client.query("commit");
558
- const remaining = await client.query(
559
- `select
560
- exists(select 1 from pg_namespace where nspname = $1) as schema_exists,
561
- exists(select 1 from pg_roles where rolname = $2) as reader_exists,
562
- exists(select 1 from pg_roles where rolname = $3) as owner_exists`,
563
- [plan.review.exportSchema, plan.review.readerRole, plan.review.ownerRole],
564
- );
565
- if (Object.values(remaining.rows[0]).some(Boolean)) {
566
- throw new Error(
567
- "Source access retirement could not be independently verified.",
568
- );
569
- }
570
- } catch (error) {
571
- await client.query("rollback").catch(() => undefined);
572
- throw error;
573
- } finally {
574
- await client.end?.();
575
- }
576
- await Promise.all([
577
- rm(ensureOwnedPath(projectRoot, credentialFile), { force: true }),
578
- rm(plan.receiptPath, { force: true }),
579
- ]);
580
- return { retired: true };
581
- };
@@ -1,38 +0,0 @@
1
- /** Coordinate private source prefixes with reviewed privacy path mappings. */
2
-
3
- import { validateExecutablePrivacyPolicy } from "../baseline/privacy_engine.mjs";
4
- import { validateSourceAccessPolicy } from "./access.mjs";
5
-
6
- export const resolvePrivacyMappedAssets = ({
7
- sourcePolicy,
8
- privacyPolicy,
9
- environment = process.env,
10
- }) => {
11
- const source = validateSourceAccessPolicy(sourcePolicy);
12
- const privacy = validateExecutablePrivacyPolicy(privacyPolicy);
13
-
14
- return Object.freeze(
15
- source.assets.map((asset) => {
16
- if (!asset.pathMapping) return asset;
17
- const mapping = privacy.pathMappings[asset.pathMapping];
18
- if (!mapping) {
19
- throw new Error(
20
- `Storage asset references unknown privacy path mapping ${asset.pathMapping}.`,
21
- );
22
- }
23
- const binding = privacy.bindings[mapping.binding];
24
- if (binding.environmentVariable !== asset.prefixEnvironmentVariable) {
25
- throw new Error(
26
- `Storage asset ${asset.bucket} must use the environment variable reviewed by privacy path mapping ${asset.pathMapping}.`,
27
- );
28
- }
29
- const prefix = environment[asset.prefixEnvironmentVariable];
30
- if (typeof prefix !== "string" || !prefix) {
31
- throw new Error(
32
- `Storage asset ${asset.bucket} requires ${asset.prefixEnvironmentVariable}.`,
33
- );
34
- }
35
- return Object.freeze({ ...asset, prefix });
36
- }),
37
- );
38
- };