@cosmicdrift/kumiko-framework 0.270.0 → 0.274.0

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 (111) hide show
  1. package/package.json +3 -3
  2. package/src/__tests__/fixtures/migrate-cross-tenant/manual-only.expected.ts +44 -0
  3. package/src/__tests__/fixtures/migrate-cross-tenant/manual-only.input.ts +44 -0
  4. package/src/__tests__/fixtures/migrate-cross-tenant/rewrite.expected.ts +41 -0
  5. package/src/__tests__/fixtures/migrate-cross-tenant/rewrite.input.ts +41 -0
  6. package/src/__tests__/migrate-cross-tenant-codemod.test.ts +106 -0
  7. package/src/__tests__/related-list-parent-filter.integration.test.ts +103 -0
  8. package/src/api/__tests__/nested-write-ownership.integration.test.ts +268 -0
  9. package/src/api/server.ts +7 -20
  10. package/src/bun-db/__tests__/query-guards.test.ts +60 -3
  11. package/src/bun-db/query.ts +24 -21
  12. package/src/changes.json +105 -0
  13. package/src/db/__tests__/build-filter-where.test.ts +8 -0
  14. package/src/db/__tests__/event-store-executor-list.integration.test.ts +69 -0
  15. package/src/db/__tests__/event-store-executor-reference-search.integration.test.ts +266 -2
  16. package/src/db/__tests__/event-store-executor-write-verbs.integration.test.ts +77 -0
  17. package/src/db/__tests__/event-store-executor.integration.test.ts +1 -1
  18. package/src/db/__tests__/replay-migration-sql.test.ts +17 -0
  19. package/src/db/__tests__/tenant-db-convention-cross-tenant.test.ts +72 -0
  20. package/src/db/__tests__/tenant-db-declared-unsafe-raw.test.ts +104 -0
  21. package/src/db/__tests__/tenant-db-global.test.ts +92 -0
  22. package/src/db/__tests__/tenant-db-no-raw.test.ts +75 -0
  23. package/src/db/__tests__/tenant-db.integration.test.ts +3 -1
  24. package/src/db/__tests__/unchecked-system-db.test.ts +76 -0
  25. package/src/db/apply-entity-event.ts +1 -1
  26. package/src/db/assert-exists-in.ts +1 -1
  27. package/src/db/entity-field-encryption.ts +18 -0
  28. package/src/db/event-store-executor-context.ts +12 -5
  29. package/src/db/event-store-executor-read.ts +125 -37
  30. package/src/db/event-store-executor-write.ts +24 -18
  31. package/src/db/queries/shadow-swap.ts +36 -0
  32. package/src/db/replay-migration-sql.ts +5 -5
  33. package/src/db/tenant-db-runner.ts +23 -0
  34. package/src/db/tenant-db.ts +97 -24
  35. package/src/derivatives/__tests__/derivatives-context.test.ts +0 -1
  36. package/src/engine/__tests__/boot-validator-nav-area.test.ts +116 -0
  37. package/src/engine/__tests__/boot-validator-projection-list.test.ts +91 -0
  38. package/src/engine/__tests__/boot-validator-query-output-schema.test.ts +143 -0
  39. package/src/engine/__tests__/boot-validator.test.ts +71 -1
  40. package/src/engine/__tests__/engine.test.ts +86 -0
  41. package/src/engine/__tests__/entity-create-caller-id.integration.test.ts +87 -0
  42. package/src/engine/__tests__/entity-handlers-escape-hatch.test.ts +91 -0
  43. package/src/engine/__tests__/entity-handlers.test.ts +28 -0
  44. package/src/engine/__tests__/entity-restore-tenant-isolation.integration.test.ts +30 -5
  45. package/src/engine/__tests__/entity-write-crosstenant.integration.test.ts +206 -47
  46. package/src/engine/__tests__/read-steps-tenant-filter.integration.test.ts +215 -0
  47. package/src/engine/__tests__/required-surface-keys.test.ts +16 -0
  48. package/src/engine/__tests__/screen-filter-ops.test.ts +1 -1
  49. package/src/engine/__tests__/screen.test.ts +150 -0
  50. package/src/engine/__tests__/soft-delete-cleanup.test.ts +0 -1
  51. package/src/engine/__tests__/steps-read.test.ts +204 -8
  52. package/src/engine/__tests__/steps-unsafe-projection-delete.test.ts +7 -4
  53. package/src/engine/__tests__/steps-unsafe-projection-upsert.test.ts +6 -3
  54. package/src/engine/boot-validator/__tests__/global-tenancy.test.ts +16 -1
  55. package/src/engine/boot-validator/__tests__/rate-limit-disabled-reason.test.ts +45 -0
  56. package/src/engine/boot-validator/entity-handler.ts +21 -0
  57. package/src/engine/boot-validator/global-tenancy.ts +13 -1
  58. package/src/engine/boot-validator/parent-ref.ts +1 -1
  59. package/src/engine/boot-validator/projection-list-screens.ts +68 -3
  60. package/src/engine/boot-validator/query-output-columns.ts +33 -0
  61. package/src/engine/boot-validator/screens.ts +154 -31
  62. package/src/engine/build-config-feature-schema.ts +7 -4
  63. package/src/engine/entity-handlers.ts +74 -22
  64. package/src/engine/feature-entity-handlers.ts +4 -4
  65. package/src/engine/index.ts +5 -0
  66. package/src/engine/registry-validate.ts +36 -6
  67. package/src/engine/schema-builder.ts +6 -0
  68. package/src/engine/screen-filter-ops.ts +10 -2
  69. package/src/engine/screen-helpers.ts +52 -0
  70. package/src/engine/steps/_read-source.ts +12 -0
  71. package/src/engine/steps/read-find-many.ts +8 -2
  72. package/src/engine/steps/read-find-one.ts +11 -8
  73. package/src/engine/steps/unsafe-projection-delete.ts +2 -1
  74. package/src/engine/steps/unsafe-projection-upsert.ts +2 -1
  75. package/src/engine/types/index.ts +8 -1
  76. package/src/errors/i18n/de.yaml +14 -0
  77. package/src/errors/i18n/en.yaml +13 -0
  78. package/src/errors/reasons.ts +4 -0
  79. package/src/i18n/required-surface-keys.ts +6 -2
  80. package/src/jobs/__tests__/job-systemdb.integration.test.ts +5 -4
  81. package/src/jobs/__tests__/jobs.integration.test.ts +41 -0
  82. package/src/jobs/job-runner.ts +35 -5
  83. package/src/pipeline/__tests__/escape-hatch-audit.integration.test.ts +254 -0
  84. package/src/pipeline/__tests__/escape-hatch-report.test.ts +149 -0
  85. package/src/pipeline/__tests__/msp-rebuild.integration.test.ts +28 -0
  86. package/src/pipeline/__tests__/projection-rebuild.integration.test.ts +94 -0
  87. package/src/pipeline/__tests__/projections-runner-systemscope.integration.test.ts +101 -0
  88. package/src/pipeline/__tests__/query-projection.integration.test.ts +169 -14
  89. package/src/pipeline/__tests__/rate-limit-default.integration.test.ts +118 -0
  90. package/src/pipeline/__tests__/rate-limit-default.test.ts +117 -0
  91. package/src/pipeline/__tests__/search-consumer-named-events.integration.test.ts +5 -2
  92. package/src/pipeline/__tests__/system-identity-switch.test.ts +240 -1
  93. package/src/pipeline/dispatch-query.ts +27 -8
  94. package/src/pipeline/dispatch-shared.ts +141 -57
  95. package/src/pipeline/dispatch-stream.ts +1 -3
  96. package/src/pipeline/dispatch-write.ts +62 -14
  97. package/src/pipeline/dispatcher.ts +20 -0
  98. package/src/pipeline/escape-hatch-report.ts +127 -0
  99. package/src/pipeline/index.ts +8 -0
  100. package/src/pipeline/member-read-only-transaction.ts +75 -0
  101. package/src/pipeline/msp-rebuild.ts +2 -0
  102. package/src/pipeline/projection-rebuild.ts +2 -0
  103. package/src/pipeline/projections-runner.ts +15 -13
  104. package/src/pipeline/system-identity-switch.ts +121 -9
  105. package/src/scripts/codemod/migrate-cross-tenant.ts +335 -0
  106. package/src/scripts/codemod/migrate-db-raw.ts +19 -6
  107. package/src/scripts/codemod/migrate-open-to-all.ts +2 -1
  108. package/src/ui-types/index.ts +3 -0
  109. package/src/utils/__tests__/ids.test.ts +29 -1
  110. package/src/utils/ids.ts +10 -1
  111. package/src/utils/index.ts +1 -1
@@ -9,19 +9,25 @@ import {
9
9
  normalizeAccessEntry,
10
10
  shiftParams,
11
11
  } from "../engine/ownership";
12
- import type { EntityDefinition, EntityId } from "../engine/types";
12
+ import type { EntityDefinition, EntityId, SessionUser } from "../engine/types";
13
13
  import { SYSTEM_TENANT_ID } from "../engine/types/identifiers";
14
14
  import { UnprocessableError } from "../errors";
15
15
  import { getStreamVersion } from "../event-store";
16
+ import type { SearchAdapter } from "../search/types";
16
17
  import { LIST_ROW_META_REFERENCES } from "../ui-types/list-row-meta";
17
18
  import { rehydrateCompoundTypes } from "./compound-types";
18
19
  import { decodeKeysetCursor, encodeCursor, encodeKeysetCursor } from "./cursor";
19
- import { collectEncryptedFieldNames } from "./entity-field-encryption";
20
+ import {
21
+ collectEncryptedFieldNames,
22
+ hasSearchablePlaintext,
23
+ isSensitiveLabelField,
24
+ } from "./entity-field-encryption";
20
25
  import type { EventStoreExecutor } from "./event-store-executor";
21
26
  import { buildFilterWhere, type ExecutorContext, type Table } from "./event-store-executor-context";
22
27
  import { buildParentRefClause } from "./parent-ref-clause";
23
28
  import { buildEntityTable, physicalColumnName } from "./table-builder";
24
29
  import type { TenantDb, TenantDbMode } from "./tenant-db";
30
+ import { tenantDbRunner } from "./tenant-db-runner";
25
31
 
26
32
  // The two read verbs (list/detail) of the event-store-executor. Split out
27
33
  // of event-store-executor.ts (#1005, Welle 2) — behavior-preserving
@@ -103,26 +109,27 @@ function keysetBoundarySql(
103
109
 
104
110
  type ListFilter = {
105
111
  readonly field: string;
106
- readonly op: "eq" | "ne" | "lt" | "gt" | "in";
112
+ readonly op: "eq" | "ne" | "lt" | "gt" | "lte" | "gte" | "in";
107
113
  readonly value: unknown;
108
114
  };
109
115
 
110
116
  // multiSelect stores its options as a jsonb array — a filter value is one
111
117
  // option, not the whole array, so eq/ne/in must check array containment
112
118
  // (`@>`) instead of scalar `=`/`<>`/`IN` against the jsonb column (fw#2490).
113
- // lt/gt have no containment analogue; the boot-validator already blocks them
114
- // for screen-declared filters (screen-filter-ops.ts EQUALITY_ONLY), but a
115
- // client-supplied facet filter reaches here unvalidated, so treat it as
116
- // unsatisfiable rather than emitting SQL Postgres would reject.
119
+ // lt/gt/lte/gte have no containment analogue; the boot-validator already
120
+ // blocks them for screen-declared filters (screen-filter-ops.ts
121
+ // EQUALITY_ONLY), but a client-supplied facet filter reaches here
122
+ // unvalidated, so treat it as unsatisfiable rather than emitting SQL
123
+ // Postgres would reject.
117
124
  function applyMultiSelectFilter(
118
125
  colSql: (field: string) => string,
119
126
  whereSql: string[],
120
127
  params: unknown[],
121
128
  f: ListFilter,
122
129
  ): void {
123
- if (f.op === "lt" || f.op === "gt") {
130
+ if (f.op === "lt" || f.op === "gt" || f.op === "lte" || f.op === "gte") {
124
131
  whereSql.push("FALSE");
125
- // skip: lt/gt is unsatisfiable on a multiSelect column
132
+ // skip: lt/gt/lte/gte is unsatisfiable on a multiSelect column
126
133
  return;
127
134
  }
128
135
  if (f.op === "in") {
@@ -289,11 +296,86 @@ function collectReferenceSearchDescriptors(
289
296
  // unscoped SQL, a match in a foreign tenant must never surface a row here
290
297
  // (fw#2660's hard constraint). Mirrors the main table's own tenant filter
291
298
  // (see the `table["tenantId"]` check further down in list()).
299
+ async function resolveReferenceMatchesViaIlike(
300
+ descriptor: ReferenceSearchDescriptor,
301
+ searchTerm: string,
302
+ targetTable: Table,
303
+ targetTableName: string,
304
+ db: TenantDb,
305
+ ): Promise<{ readonly ownColumn: string; readonly ids: readonly string[] } | undefined> {
306
+ const labelCol = physicalColumnName(targetTable, descriptor.labelField);
307
+ const subParams: unknown[] = [`%${escapeLikePattern(searchTerm)}%`];
308
+ let tenantClause = "";
309
+ if (targetTable["tenantId"] !== undefined && db.mode === "tenant") {
310
+ subParams.push(db.tenantId, SYSTEM_TENANT_ID);
311
+ tenantClause = ` AND "${physicalColumnName(targetTable, "tenantId")}" IN ($2, $3)`;
312
+ }
313
+ // ::text cast covers a non-text labelField (e.g. a number/select column
314
+ // used as label) — Postgres has no ILIKE for those types otherwise.
315
+ const sql =
316
+ `SELECT "id" FROM "${targetTableName}" WHERE ("${labelCol}")::text ILIKE $1${tenantClause} ` +
317
+ `LIMIT ${MAX_REFERENCE_SEARCH_IDS + 1}`;
318
+ const rows = await executeRawQueryRead<{ id: string }>(tenantDbRunner(db), sql, subParams);
319
+ if (rows.length === 0 || rows.length > MAX_REFERENCE_SEARCH_IDS) {
320
+ // skip: no match, or over the cap — drop the clause rather than
321
+ // truncate to an arbitrary slice of matching targets
322
+ return undefined;
323
+ }
324
+ return { ownColumn: descriptor.ownColumn, ids: rows.map((r) => r.id) };
325
+ }
326
+
327
+ // Same lookup, but the target's index is tenant-wide, not per-viewer, so
328
+ // candidate ids get re-checked against the target entity's own read access.
329
+ async function resolveReferenceMatchesViaSearchIndex(
330
+ descriptor: ReferenceSearchDescriptor,
331
+ searchTerm: string,
332
+ targetEntity: EntityDefinition,
333
+ targetTable: Table,
334
+ targetTableName: string,
335
+ user: SessionUser,
336
+ db: TenantDb,
337
+ searchAdapter: SearchAdapter,
338
+ ): Promise<{ readonly ownColumn: string; readonly ids: readonly string[] } | undefined> {
339
+ const searchTenantId = targetEntity.systemStream ? SYSTEM_TENANT_ID : user.tenantId;
340
+ const results = await searchAdapter.search(searchTenantId, searchTerm, {
341
+ filterType: descriptor.targetEntityName,
342
+ limit: MAX_REFERENCE_SEARCH_IDS + 1,
343
+ });
344
+ if (results.length === 0 || results.length > MAX_REFERENCE_SEARCH_IDS) {
345
+ // skip: no match, or over the cap — same drop-the-clause policy as the ILIKE path
346
+ return undefined;
347
+ }
348
+
349
+ const ownership = buildOwnershipClause(user, targetEntity.access?.read, targetTable);
350
+ if (ownership.kind === "empty") return undefined;
351
+
352
+ const candidateIds = results.map((r) => String(r.entityId));
353
+ if (ownership.kind === "pass") {
354
+ return { ownColumn: descriptor.ownColumn, ids: candidateIds };
355
+ }
356
+
357
+ const params: unknown[] = [...candidateIds];
358
+ const idPlaceholders = candidateIds.map((_, i) => `$${i + 1}`);
359
+ const shifted = shiftParams(
360
+ { sqlText: ownership.sqlText, params: ownership.params },
361
+ params.length,
362
+ );
363
+ const sql =
364
+ `SELECT "id" FROM "${targetTableName}" WHERE "id" IN (${idPlaceholders.join(", ")}) ` +
365
+ `AND ${shifted.sqlText}`;
366
+ for (const p of shifted.params) params.push(p);
367
+ const rows = await executeRawQueryRead<{ id: string }>(tenantDbRunner(db), sql, params);
368
+ if (rows.length === 0) return undefined;
369
+ return { ownColumn: descriptor.ownColumn, ids: rows.map((r) => r.id) };
370
+ }
371
+
292
372
  async function resolveReferenceMatches(
293
373
  descriptor: ReferenceSearchDescriptor,
294
374
  searchTerm: string,
295
375
  resolveEntity: (entityName: string) => EntityDefinition | undefined,
296
376
  db: TenantDb,
377
+ user: SessionUser,
378
+ searchAdapter: SearchAdapter,
297
379
  ): Promise<{ readonly ownColumn: string; readonly ids: readonly string[] } | undefined> {
298
380
  const targetEntity = resolveEntity(descriptor.targetEntityName);
299
381
  if (targetEntity === undefined) {
@@ -307,38 +389,36 @@ async function resolveReferenceMatches(
307
389
  // `name` is a declared field on the tenant entity, not an id/row-meta column
308
390
  return undefined;
309
391
  }
310
- if (
311
- collectEncryptedFieldNames(targetEntity).has(descriptor.labelField) ||
312
- collectPiiSubjectFields(targetEntity).includes(descriptor.labelField)
313
- ) {
314
- // skip: encrypted/PII labelField — ILIKE can never match ciphertext,
315
- // emitting the query would just be a silent, permanent non-match
316
- return undefined;
317
- }
318
392
 
319
393
  const targetTable = buildEntityTable(descriptor.targetEntityName, targetEntity);
320
394
  const targetTableName = String(
321
395
  (targetTable as unknown as Record<symbol, unknown>)[KUMIKO_NAME_SYMBOL],
322
396
  );
323
- const labelCol = physicalColumnName(targetTable, descriptor.labelField);
324
- const subParams: unknown[] = [`%${escapeLikePattern(searchTerm)}%`];
325
- let tenantClause = "";
326
- if (targetTable["tenantId"] !== undefined && db.mode === "tenant") {
327
- subParams.push(db.tenantId, SYSTEM_TENANT_ID);
328
- tenantClause = ` AND "${physicalColumnName(targetTable, "tenantId")}" IN ($2, $3)`;
397
+
398
+ if (!isSensitiveLabelField(targetEntity, descriptor.labelField)) {
399
+ return resolveReferenceMatchesViaIlike(
400
+ descriptor,
401
+ searchTerm,
402
+ targetTable,
403
+ targetTableName,
404
+ db,
405
+ );
329
406
  }
330
- // ::text cast covers a non-text labelField (e.g. a number/select column
331
- // used as label) — Postgres has no ILIKE for those types otherwise.
332
- const sql =
333
- `SELECT "id" FROM "${targetTableName}" WHERE ("${labelCol}")::text ILIKE $1${tenantClause} ` +
334
- `LIMIT ${MAX_REFERENCE_SEARCH_IDS + 1}`;
335
- const rows = await executeRawQueryRead<{ id: string }>(db.raw, sql, subParams);
336
- if (rows.length === 0 || rows.length > MAX_REFERENCE_SEARCH_IDS) {
337
- // skip: no match, or over the cap — drop the clause rather than
338
- // truncate to an arbitrary slice of matching targets
407
+ if (!hasSearchablePlaintext(targetEntity, descriptor.labelField)) {
408
+ // skip: no plaintext anywhere to match — boot rejects this normally,
409
+ // this is defense-in-depth for a target entity resolved only at runtime.
339
410
  return undefined;
340
411
  }
341
- return { ownColumn: descriptor.ownColumn, ids: rows.map((r) => r.id) };
412
+ return resolveReferenceMatchesViaSearchIndex(
413
+ descriptor,
414
+ searchTerm,
415
+ targetEntity,
416
+ targetTable,
417
+ targetTableName,
418
+ user,
419
+ db,
420
+ searchAdapter,
421
+ );
342
422
  }
343
423
 
344
424
  // Projected alongside the row when a reference sort is active, so the keyset
@@ -423,6 +503,7 @@ export function createReadVerbs(ctx: ExecutorContext): Pick<EventStoreExecutor,
423
503
  // list + detail are unchanged from crud-executor — projections are the
424
504
  // read-model and serve these queries directly.
425
505
  async list(payload, user, db, runtimeOptions) {
506
+ const runner = tenantDbRunner(db);
426
507
  const { limit, offset } = resolveListPagination(payload);
427
508
  const totalCount = payload.totalCount === true;
428
509
  const tableName = String((table as unknown as Record<symbol, unknown>)[KUMIKO_NAME_SYMBOL]);
@@ -515,7 +596,14 @@ export function createReadVerbs(ctx: ExecutorContext): Pick<EventStoreExecutor,
515
596
  ? (
516
597
  await Promise.all(
517
598
  descriptors.map((d) =>
518
- resolveReferenceMatches(d, searchTerm, referenceSearch.resolveEntity, db),
599
+ resolveReferenceMatches(
600
+ d,
601
+ searchTerm,
602
+ referenceSearch.resolveEntity,
603
+ db,
604
+ user,
605
+ effectiveSearchAdapter,
606
+ ),
519
607
  ),
520
608
  )
521
609
  ).filter(
@@ -674,7 +762,7 @@ export function createReadVerbs(ctx: ExecutorContext): Pick<EventStoreExecutor,
674
762
  : "*";
675
763
  const listSql = `SELECT ${selectList} FROM "${tableName}"${whereClauseSqlText}${orderByClause} LIMIT ${limit}${offsetClause}`;
676
764
 
677
- const rawRows = await executeRawQueryRead<Record<string, unknown>>(db.raw, listSql, params);
765
+ const rawRows = await executeRawQueryRead<Record<string, unknown>>(runner, listSql, params);
678
766
  const lastSortLabel = rawRows[rawRows.length - 1]?.[SORT_LABEL_ALIAS];
679
767
  if (referenceSortExpr !== undefined) {
680
768
  // The alias is a sort artifact, not a column of this entity — strip it
@@ -735,7 +823,7 @@ export function createReadVerbs(ctx: ExecutorContext): Pick<EventStoreExecutor,
735
823
  } else {
736
824
  const countSql = `SELECT COUNT(*)::int AS count FROM "${tableName}"${whereClauseSqlText}`;
737
825
  const countRows = await executeRawQueryRead<{ count: number }>(
738
- db.raw,
826
+ runner,
739
827
  countSql,
740
828
  whereParams,
741
829
  );
@@ -779,7 +867,7 @@ export function createReadVerbs(ctx: ExecutorContext): Pick<EventStoreExecutor,
779
867
  row: Record<string, unknown>,
780
868
  ): Promise<Record<string, unknown>> => {
781
869
  const streamVersion = await getStreamVersion(
782
- db.raw,
870
+ tenantDbRunner(db),
783
871
  String(payload.id),
784
872
  streamTenantFor(user),
785
873
  );
@@ -30,6 +30,7 @@ import {
30
30
  tryMapUniqueViolation,
31
31
  } from "./event-store-executor-context";
32
32
  import { runInSavepointIfSupported } from "./query";
33
+ import { tenantDbRunner } from "./tenant-db-runner";
33
34
 
34
35
  // Art. 17 erasure runs as the framework operator, not as a row owner; a
35
36
  // per-role ownership map can never cover it, and a silent deny means the
@@ -117,6 +118,7 @@ export function createWriteVerbs(
117
118
 
118
119
  return {
119
120
  async create(payload, user, db, options) {
121
+ const runner = tenantDbRunner(db);
120
122
  if (isForeignTenantOnGlobalEntity(entity, payload["tenantId"])) {
121
123
  throw new AccessDeniedError({
122
124
  message:
@@ -215,9 +217,9 @@ export function createWriteVerbs(
215
217
  // of the version_conflict this catch classifies. runInSavepointIfSupported
216
218
  // confines the failed INSERT to a nested scope that rolls back on
217
219
  // its own (same pattern as ctx.tryAppendEvent), and falls back to a
218
- // plain call when db.raw is a bare pool connection with no active
220
+ // plain call when the runner is a bare pool connection with no active
219
221
  // transaction to poison (seeds/tests calling the executor directly).
220
- event = await runInSavepointIfSupported(db.raw, async (sp) =>
222
+ event = await runInSavepointIfSupported(runner, async (sp) =>
221
223
  append(sp, {
222
224
  aggregateId,
223
225
  aggregateType: entityName,
@@ -232,7 +234,7 @@ export function createWriteVerbs(
232
234
  if (e instanceof EventStoreVersionConflict) {
233
235
  let currentVersion = -1;
234
236
  try {
235
- currentVersion = await getStreamVersion(db.raw, aggregateId, streamTenantFor(user));
237
+ currentVersion = await getStreamVersion(runner, aggregateId, streamTenantFor(user));
236
238
  } catch {
237
239
  // Lookup failure — keep the sentinel.
238
240
  }
@@ -268,7 +270,7 @@ export function createWriteVerbs(
268
270
  // failed INSERT back; the error still propagates and stays catchable.
269
271
  let result: Awaited<ReturnType<typeof applyEntityEvent>>;
270
272
  try {
271
- result = await runInSavepointIfSupported(db.raw, async (sp) =>
273
+ result = await runInSavepointIfSupported(runner, async (sp) =>
272
274
  applyEntityEvent(event, table, entity, sp),
273
275
  );
274
276
  } catch (e) {
@@ -308,6 +310,7 @@ export function createWriteVerbs(
308
310
  },
309
311
 
310
312
  async update(payload, user, db, updateOptions) {
313
+ const runner = tenantDbRunner(db);
311
314
  if (isForeignTenantOnGlobalEntity(entity, payload.changes["tenantId"])) {
312
315
  throw new AccessDeniedError({
313
316
  message:
@@ -397,7 +400,7 @@ export function createWriteVerbs(
397
400
  // trip `events_aggregate_version_uq` (tenant_id, aggregate_id, version)
398
401
  // with version_conflict.
399
402
  const currentVersion = await getStreamVersion(
400
- db.raw,
403
+ runner,
401
404
  String(payload.id),
402
405
  streamTenantFor(user),
403
406
  );
@@ -452,7 +455,7 @@ export function createWriteVerbs(
452
455
  // Savepoint-scoped — see the create() append() above for why:
453
456
  // confines a losing writer's unique-violation to a nested scope
454
457
  // instead of poisoning the whole outer transaction.
455
- const event = await runInSavepointIfSupported(db.raw, (sp) =>
458
+ const event = await runInSavepointIfSupported(runner, (sp) =>
456
459
  append(sp, {
457
460
  aggregateId: String(payload.id),
458
461
  aggregateType: entityName,
@@ -480,7 +483,7 @@ export function createWriteVerbs(
480
483
  // failed nested one throws 500 instead of failing cleanly.
481
484
  let result: Awaited<ReturnType<typeof applyEntityEvent>>;
482
485
  try {
483
- result = await runInSavepointIfSupported(db.raw, async (sp) =>
486
+ result = await runInSavepointIfSupported(runner, async (sp) =>
484
487
  applyEntityEvent(event, table, entity, sp),
485
488
  );
486
489
  } catch (e) {
@@ -539,6 +542,7 @@ export function createWriteVerbs(
539
542
  },
540
543
 
541
544
  async delete(payload, user, db) {
545
+ const runner = tenantDbRunner(db);
542
546
  const existing = await loadById(payload.id, db);
543
547
  if (!existing) return writeFailure(new NotFoundError(entityName, payload.id));
544
548
 
@@ -565,7 +569,7 @@ export function createWriteVerbs(
565
569
 
566
570
  // Stream-version authoritative (see update() for rationale).
567
571
  const currentVersion = await getStreamVersion(
568
- db.raw,
572
+ runner,
569
573
  String(payload.id),
570
574
  streamTenantFor(user),
571
575
  );
@@ -578,7 +582,7 @@ export function createWriteVerbs(
578
582
  // land in the immutable log.
579
583
  let event: Awaited<ReturnType<typeof append>>;
580
584
  try {
581
- event = await runInSavepointIfSupported(db.raw, async (sp) =>
585
+ event = await runInSavepointIfSupported(runner, async (sp) =>
582
586
  append(sp, {
583
587
  aggregateId: String(payload.id),
584
588
  aggregateType: entityName,
@@ -606,7 +610,7 @@ export function createWriteVerbs(
606
610
  }
607
611
 
608
612
  // Live==Rebuild via applyEntityEvent. Savepoint like create/update.
609
- const deleteResult = await runInSavepointIfSupported(db.raw, async (sp) =>
613
+ const deleteResult = await runInSavepointIfSupported(runner, async (sp) =>
610
614
  applyEntityEvent(event, table, entity, sp),
611
615
  );
612
616
  if (deleteResult.kind !== "applied") {
@@ -636,6 +640,7 @@ export function createWriteVerbs(
636
640
  // the erasure replays on rebuild (created → forgotten → row gone). Loads
637
641
  // without the isDeleted filter so trashed (soft-deleted) rows are erased too.
638
642
  async forget(payload, user, db) {
643
+ const runner = tenantDbRunner(db);
639
644
  const raw = await db.fetchOne<Record<string, unknown>>(table, { id: payload.id });
640
645
  if (!raw) return writeFailure(new NotFoundError(entityName, payload.id));
641
646
  const existing = await decryptForRead(rehydrateCompoundTypes(raw as DbRow, entity) as DbRow);
@@ -660,14 +665,14 @@ export function createWriteVerbs(
660
665
 
661
666
  await assertStreamWritable(db, payload.id, streamTenantFor(user));
662
667
  const currentVersion = await getStreamVersion(
663
- db.raw,
668
+ runner,
664
669
  String(payload.id),
665
670
  streamTenantFor(user),
666
671
  );
667
672
 
668
673
  let event: Awaited<ReturnType<typeof append>>;
669
674
  try {
670
- event = await runInSavepointIfSupported(db.raw, async (sp) =>
675
+ event = await runInSavepointIfSupported(runner, async (sp) =>
671
676
  append(sp, {
672
677
  aggregateId: String(payload.id),
673
678
  aggregateType: entityName,
@@ -696,7 +701,7 @@ export function createWriteVerbs(
696
701
  throw e;
697
702
  }
698
703
 
699
- const forgetResult = await runInSavepointIfSupported(db.raw, async (sp) =>
704
+ const forgetResult = await runInSavepointIfSupported(runner, async (sp) =>
700
705
  applyEntityEvent(event, table, entity, sp),
701
706
  );
702
707
  if (forgetResult.kind !== "applied") {
@@ -722,6 +727,7 @@ export function createWriteVerbs(
722
727
  },
723
728
 
724
729
  async restore(payload, user, db) {
730
+ const runner = tenantDbRunner(db);
725
731
  if (!softDelete) {
726
732
  return writeFailure(
727
733
  new UnprocessableError("soft_delete_not_enabled", {
@@ -731,8 +737,8 @@ export function createWriteVerbs(
731
737
  }
732
738
 
733
739
  // Tenant boundary: db.fetchOne applies TenantDb's tenant predicate,
734
- // selectMany(db.raw, ...) did not — any caller could un-delete a foreign
735
- // tenant's row by id. "system"-mode dbs (r.systemScope() / crossTenant
740
+ // selectMany(runner, ...) did not — any caller could un-delete a foreign
741
+ // tenant's row by id. "system"-mode dbs (r.systemScope() / escapeHatch
736
742
  // handlers) still read unfiltered. No isDeleted filter here: restore
737
743
  // targets exactly the soft-deleted row.
738
744
  const row = await db.fetchOne(table, { id: payload.id });
@@ -766,7 +772,7 @@ export function createWriteVerbs(
766
772
 
767
773
  // Stream-version authoritative (see update() for rationale).
768
774
  const currentVersion = await getStreamVersion(
769
- db.raw,
775
+ runner,
770
776
  String(payload.id),
771
777
  streamTenantFor(user),
772
778
  );
@@ -777,7 +783,7 @@ export function createWriteVerbs(
777
783
  // already ciphertext, no re-encrypt needed.
778
784
  let event: Awaited<ReturnType<typeof append>>;
779
785
  try {
780
- event = await runInSavepointIfSupported(db.raw, (sp) =>
786
+ event = await runInSavepointIfSupported(runner, (sp) =>
781
787
  append(sp, {
782
788
  aggregateId: String(payload.id),
783
789
  aggregateType: entityName,
@@ -807,7 +813,7 @@ export function createWriteVerbs(
807
813
  // Live==Rebuild via applyEntityEvent. Restore only writes isDeleted=false
808
814
  // plus the version bump, so there is no sensitive-field drift and no
809
815
  // payload override is needed.
810
- const restoreResult = await runInSavepointIfSupported(db.raw, async (sp) =>
816
+ const restoreResult = await runInSavepointIfSupported(runner, async (sp) =>
811
817
  applyEntityEvent(event, table, entity, sp),
812
818
  );
813
819
  if (restoreResult.kind !== "applied" || restoreResult.row === null) {
@@ -105,6 +105,40 @@ export async function assertLiveColumnsMatchMeta(
105
105
  );
106
106
  }
107
107
 
108
+ // EntityTableMeta carries no RLS/policies, so the swap would silently drop them (#2907).
109
+ export async function assertLiveTableHasNoRowLevelSecurity(
110
+ tx: AnyDb,
111
+ tableName: string,
112
+ projectionName?: string,
113
+ ): Promise<void> {
114
+ const rows = await asRawClient(tx).unsafe<{
115
+ rls_enabled: boolean;
116
+ rls_forced: boolean;
117
+ policy_count: number;
118
+ }>(
119
+ `SELECT c.relrowsecurity AS rls_enabled, c.relforcerowsecurity AS rls_forced,
120
+ (SELECT count(*)::int FROM pg_policy p WHERE p.polrelid = c.oid) AS policy_count
121
+ FROM pg_class c
122
+ JOIN pg_namespace n ON n.oid = c.relnamespace
123
+ WHERE n.nspname = 'public' AND c.relname = $1`,
124
+ [tableName],
125
+ );
126
+ const row = rows[0];
127
+ // skip: no live table yet — nothing to have RLS on
128
+ if (!row) return;
129
+ // skip: no RLS flags and no policies — nothing the swap could drop
130
+ if (!row.rls_enabled && !row.rls_forced && row.policy_count === 0) return;
131
+ const context =
132
+ projectionName !== undefined ? `projection-rebuild "${projectionName}"` : "shadow swap";
133
+ throw new Error(
134
+ `${context}: live table "${tableName}" has row level security (enabled: ${row.rls_enabled}, ` +
135
+ `forced: ${row.rls_forced}, policies: ${row.policy_count}). The shadow swap rebuilds the table ` +
136
+ "from EntityTableMeta and would silently drop RLS and every policy. Kumiko does not support RLS " +
137
+ "on rebuildable tables — see kumiko-platform docs/plans/rls-evaluation.md. Rebuild aborted; live " +
138
+ "table untouched.",
139
+ );
140
+ }
141
+
108
142
  // Runs INSIDE the rebuild tx, AFTER the state/consumer row lock is taken.
109
143
  // Points search_path at the shadow schema (SET LOCAL → auto-reset on commit or
110
144
  // rollback), drops any leftover shadow from a crashed run, then builds the
@@ -300,6 +334,8 @@ export async function countColumnDrift(
300
334
  // object depends on the live table the swap fails loud and the whole rebuild
301
335
  // rolls back, leaving the old table untouched.
302
336
  export async function swapShadowIntoLive(tx: AnyDb, tableName: string): Promise<void> {
337
+ // Re-checked right before DROP: RLS could have been enabled after the early check.
338
+ await assertLiveTableHasNoRowLevelSecurity(tx, tableName);
303
339
  const raw = asRawClient(tx);
304
340
  const ident = quoteTableIdent(tableName);
305
341
  await raw.unsafe(`DROP TABLE public.${ident}`);
@@ -84,7 +84,7 @@ const SHAPE_NEUTRAL_ALTER_CLAUSE_RE = new RegExp(
84
84
  `ALTER COLUMN\\s+${IDENT}\\s+(SET|DROP)\\s+NOT NULL\\b`,
85
85
  `ALTER COLUMN\\s+${IDENT}\\s+(SET DEFAULT\\b|DROP DEFAULT\\b)`,
86
86
  `(ADD|DROP)\\s+CONSTRAINT\\s+${IDENT}`,
87
- `\\b(ENABLE|DISABLE)\\s+ROW LEVEL SECURITY\\b`,
87
+ `\\b(ENABLE|DISABLE|(NO\\s+)?FORCE)\\s+ROW LEVEL SECURITY\\b`,
88
88
  `^OWNER TO\\b`,
89
89
  ].join("|"),
90
90
  "gi",
@@ -149,9 +149,9 @@ function applyStatement(
149
149
  else table.columns.delete(name);
150
150
  }
151
151
  // Shape-neutral clauses (ALTER COLUMN TYPE, SET/DROP NOT NULL, SET/DROP
152
- // DEFAULT, ADD/DROP CONSTRAINT, ENABLE/DISABLE ROW LEVEL SECURITY, OWNER
153
- // TO) — none add/remove/rename a column, so this replay (which only
154
- // tracks column presence) correctly has nothing to do for them.
152
+ // DEFAULT, ADD/DROP CONSTRAINT, ENABLE/DISABLE/[NO] FORCE ROW LEVEL
153
+ // SECURITY, OWNER TO) — none add/remove/rename a column, so this replay
154
+ // (which only tracks column presence) correctly has nothing to do for them.
155
155
  if (alterBody.match(SHAPE_NEUTRAL_ALTER_CLAUSE_RE)) matchedAClause = true;
156
156
  // An ALTER TABLE that matched the outer "ALTER TABLE <name> <body>" shape
157
157
  // but whose body contains no recognized clause (e.g. RENAME TO/RENAME
@@ -177,7 +177,7 @@ function applyStatement(
177
177
  `starts with CREATE/ALTER/DROP TABLE but matched none of the replay's ` +
178
178
  `recognized patterns (CREATE TABLE, DROP TABLE, ALTER TABLE ADD/DROP ` +
179
179
  `COLUMN, ALTER COLUMN ... TYPE, SET/DROP NOT NULL, SET/DROP DEFAULT, ` +
180
- `ADD/DROP CONSTRAINT, ENABLE/DISABLE ROW LEVEL SECURITY, OWNER TO — ` +
180
+ `ADD/DROP CONSTRAINT, ENABLE/DISABLE/[NO] FORCE ROW LEVEL SECURITY, OWNER TO — ` +
181
181
  `optionally-quoted identifiers). Likely RENAME TO/RENAME COLUMN (real ` +
182
182
  `identity change, not trackable here) or genuinely unparsed hand-written ` +
183
183
  `DDL. Statement: ${prefix}${statement.length > 200 ? "…" : ""}`,
@@ -0,0 +1,23 @@
1
+ import type { TenantDb } from "@cosmicdrift/kumiko-types/tenant-db-types";
2
+ import { InternalError } from "../errors";
3
+ import type { DbRunner } from "./connection";
4
+
5
+ const tenantDbRunners = new WeakMap<TenantDb, DbRunner>();
6
+
7
+ export function bindTenantDbRunner(tenantDb: TenantDb, runner: DbRunner): void {
8
+ tenantDbRunners.set(tenantDb, runner);
9
+ }
10
+
11
+ // WeakMap.get never reads a property off tenantDb — safe even when tenantDb is a
12
+ // throwing systemScope guard Proxy that rejects every property access.
13
+ export function tenantDbRunner(tenantDb: TenantDb): DbRunner {
14
+ const runner = tenantDbRunners.get(tenantDb);
15
+ if (!runner) {
16
+ throw new InternalError({
17
+ message:
18
+ "framework infrastructure received a TenantDb not built by createTenantDb (or a " +
19
+ "fail-closed systemScope guard) — no connection bound.",
20
+ });
21
+ }
22
+ return runner;
23
+ }