@open-mercato/enterprise 0.10.1-develop.8126.1.ccf499ef4c → 0.10.1-develop.8129.1.149839452c
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.
- package/.turbo/turbo-build.log +1 -1
- package/dist/lib/rls/poc/poolScope.js +57 -0
- package/dist/lib/rls/poc/poolScope.js.map +7 -0
- package/package.json +9 -9
- package/poc/rls/README.md +32 -0
- package/poc/rls/run.ts +259 -0
- package/poc/rls/tsconfig.json +5 -0
- package/src/lib/rls/poc/poolScope.ts +82 -0
package/.turbo/turbo-build.log
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
[build:enterprise] found
|
|
1
|
+
[build:enterprise] found 711 entry points
|
|
2
2
|
[build:enterprise] built successfully
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from "node:async_hooks";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
const tenantScope = new AsyncLocalStorage();
|
|
4
|
+
const tenantIdSchema = z.string().uuid();
|
|
5
|
+
const installedPools = /* @__PURE__ */ new WeakMap();
|
|
6
|
+
const setTenantSql = "select set_config('app.current_tenant_id', $1, false)";
|
|
7
|
+
function runWithRlsTenant(tenantId, fn) {
|
|
8
|
+
const parsed = tenantIdSchema.safeParse(tenantId);
|
|
9
|
+
if (!parsed.success) throw new Error("[internal] RLS tenant must be a UUID");
|
|
10
|
+
const normalizedTenantId = parsed.data.toLowerCase();
|
|
11
|
+
const current = tenantScope.getStore();
|
|
12
|
+
if (current && current.tenantId !== normalizedTenantId) {
|
|
13
|
+
throw new Error("[internal] Cannot change RLS tenant inside an active tenant scope");
|
|
14
|
+
}
|
|
15
|
+
return tenantScope.run(Object.freeze({ tenantId: normalizedTenantId }), fn);
|
|
16
|
+
}
|
|
17
|
+
function asError(error) {
|
|
18
|
+
return error instanceof Error ? error : new Error("[internal] RLS connection setup failed", { cause: error });
|
|
19
|
+
}
|
|
20
|
+
function installRlsPoolScope(pool) {
|
|
21
|
+
const existing = installedPools.get(pool);
|
|
22
|
+
if (existing) return existing;
|
|
23
|
+
const originalConnect = pool.connect;
|
|
24
|
+
async function acquireScopedClient(receiver, tenantId) {
|
|
25
|
+
const client = await originalConnect.call(receiver);
|
|
26
|
+
try {
|
|
27
|
+
await client.query(setTenantSql, [tenantId]);
|
|
28
|
+
return client;
|
|
29
|
+
} catch (error) {
|
|
30
|
+
client.release(asError(error));
|
|
31
|
+
throw error;
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
const scopedConnect = function(callback) {
|
|
35
|
+
const clientPromise = acquireScopedClient(this, tenantScope.getStore()?.tenantId ?? "");
|
|
36
|
+
if (!callback) return clientPromise;
|
|
37
|
+
void clientPromise.then(
|
|
38
|
+
(client) => callback(void 0, client, client.release.bind(client)),
|
|
39
|
+
(error) => callback(asError(error), void 0, () => void 0)
|
|
40
|
+
);
|
|
41
|
+
};
|
|
42
|
+
pool.connect = scopedConnect;
|
|
43
|
+
let disposed = false;
|
|
44
|
+
const dispose = () => {
|
|
45
|
+
if (disposed) return;
|
|
46
|
+
disposed = true;
|
|
47
|
+
if (pool.connect === scopedConnect) pool.connect = originalConnect;
|
|
48
|
+
installedPools.delete(pool);
|
|
49
|
+
};
|
|
50
|
+
installedPools.set(pool, dispose);
|
|
51
|
+
return dispose;
|
|
52
|
+
}
|
|
53
|
+
export {
|
|
54
|
+
installRlsPoolScope,
|
|
55
|
+
runWithRlsTenant
|
|
56
|
+
};
|
|
57
|
+
//# sourceMappingURL=poolScope.js.map
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
{
|
|
2
|
+
"version": 3,
|
|
3
|
+
"sources": ["../../../../src/lib/rls/poc/poolScope.ts"],
|
|
4
|
+
"sourcesContent": ["import { AsyncLocalStorage } from 'node:async_hooks'\nimport { z } from 'zod'\n\nexport type ScopeClient = {\n query(text: string, values: string[]): Promise<unknown>\n release(error?: Error | boolean): void\n}\n\nexport type ScopeConnectCallback = (\n error: Error | undefined,\n client: ScopeClient | undefined,\n release: (error?: Error | boolean) => void,\n) => void\n\nexport type ScopeConnect = {\n (): Promise<ScopeClient>\n (callback: ScopeConnectCallback): void\n}\n\nexport type ScopePool = { connect: ScopeConnect }\n\ntype TenantScope = Readonly<{ tenantId: string }>\n\nconst tenantScope = new AsyncLocalStorage<TenantScope>()\nconst tenantIdSchema = z.string().uuid()\nconst installedPools = new WeakMap<ScopePool, () => void>()\nconst setTenantSql = \"select set_config('app.current_tenant_id', $1, false)\"\n\nexport function runWithRlsTenant<Result>(tenantId: string, fn: () => Result): Result {\n const parsed = tenantIdSchema.safeParse(tenantId)\n if (!parsed.success) throw new Error('[internal] RLS tenant must be a UUID')\n const normalizedTenantId = parsed.data.toLowerCase()\n const current = tenantScope.getStore()\n if (current && current.tenantId !== normalizedTenantId) {\n throw new Error('[internal] Cannot change RLS tenant inside an active tenant scope')\n }\n return tenantScope.run(Object.freeze({ tenantId: normalizedTenantId }), fn)\n}\n\nfunction asError(error: unknown): Error {\n return error instanceof Error ? error : new Error('[internal] RLS connection setup failed', { cause: error })\n}\n\nexport function installRlsPoolScope(pool: ScopePool): () => void {\n const existing = installedPools.get(pool)\n if (existing) return existing\n const originalConnect = pool.connect\n\n async function acquireScopedClient(receiver: ScopePool, tenantId: string): Promise<ScopeClient> {\n const client = await (originalConnect as () => Promise<ScopeClient>).call(receiver)\n try {\n await client.query(setTenantSql, [tenantId])\n return client\n } catch (error) {\n client.release(asError(error))\n throw error\n }\n }\n\n const scopedConnect = function (\n this: ScopePool,\n callback?: ScopeConnectCallback,\n ): Promise<ScopeClient> | void {\n const clientPromise = acquireScopedClient(this, tenantScope.getStore()?.tenantId ?? '')\n if (!callback) return clientPromise\n void clientPromise.then(\n (client) => callback(undefined, client, client.release.bind(client)),\n (error: unknown) => callback(asError(error), undefined, () => undefined),\n )\n } as ScopeConnect\n\n pool.connect = scopedConnect\n let disposed = false\n const dispose = () => {\n if (disposed) return\n disposed = true\n if (pool.connect === scopedConnect) pool.connect = originalConnect\n installedPools.delete(pool)\n }\n installedPools.set(pool, dispose)\n return dispose\n}\n"],
|
|
5
|
+
"mappings": "AAAA,SAAS,yBAAyB;AAClC,SAAS,SAAS;AAsBlB,MAAM,cAAc,IAAI,kBAA+B;AACvD,MAAM,iBAAiB,EAAE,OAAO,EAAE,KAAK;AACvC,MAAM,iBAAiB,oBAAI,QAA+B;AAC1D,MAAM,eAAe;AAEd,SAAS,iBAAyB,UAAkB,IAA0B;AACnF,QAAM,SAAS,eAAe,UAAU,QAAQ;AAChD,MAAI,CAAC,OAAO,QAAS,OAAM,IAAI,MAAM,sCAAsC;AAC3E,QAAM,qBAAqB,OAAO,KAAK,YAAY;AACnD,QAAM,UAAU,YAAY,SAAS;AACrC,MAAI,WAAW,QAAQ,aAAa,oBAAoB;AACtD,UAAM,IAAI,MAAM,mEAAmE;AAAA,EACrF;AACA,SAAO,YAAY,IAAI,OAAO,OAAO,EAAE,UAAU,mBAAmB,CAAC,GAAG,EAAE;AAC5E;AAEA,SAAS,QAAQ,OAAuB;AACtC,SAAO,iBAAiB,QAAQ,QAAQ,IAAI,MAAM,0CAA0C,EAAE,OAAO,MAAM,CAAC;AAC9G;AAEO,SAAS,oBAAoB,MAA6B;AAC/D,QAAM,WAAW,eAAe,IAAI,IAAI;AACxC,MAAI,SAAU,QAAO;AACrB,QAAM,kBAAkB,KAAK;AAE7B,iBAAe,oBAAoB,UAAqB,UAAwC;AAC9F,UAAM,SAAS,MAAO,gBAA+C,KAAK,QAAQ;AAClF,QAAI;AACF,YAAM,OAAO,MAAM,cAAc,CAAC,QAAQ,CAAC;AAC3C,aAAO;AAAA,IACT,SAAS,OAAO;AACd,aAAO,QAAQ,QAAQ,KAAK,CAAC;AAC7B,YAAM;AAAA,IACR;AAAA,EACF;AAEA,QAAM,gBAAgB,SAEpB,UAC6B;AAC7B,UAAM,gBAAgB,oBAAoB,MAAM,YAAY,SAAS,GAAG,YAAY,EAAE;AACtF,QAAI,CAAC,SAAU,QAAO;AACtB,SAAK,cAAc;AAAA,MACjB,CAAC,WAAW,SAAS,QAAW,QAAQ,OAAO,QAAQ,KAAK,MAAM,CAAC;AAAA,MACnE,CAAC,UAAmB,SAAS,QAAQ,KAAK,GAAG,QAAW,MAAM,MAAS;AAAA,IACzE;AAAA,EACF;AAEA,OAAK,UAAU;AACf,MAAI,WAAW;AACf,QAAM,UAAU,MAAM;AACpB,QAAI,SAAU;AACd,eAAW;AACX,QAAI,KAAK,YAAY,cAAe,MAAK,UAAU;AACnD,mBAAe,OAAO,IAAI;AAAA,EAC5B;AACA,iBAAe,IAAI,MAAM,OAAO;AAChC,SAAO;AACT;",
|
|
6
|
+
"names": []
|
|
7
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@open-mercato/enterprise",
|
|
3
|
-
"version": "0.10.1-develop.
|
|
3
|
+
"version": "0.10.1-develop.8129.1.149839452c",
|
|
4
4
|
"license": "SEE LICENSE IN LICENSE.md",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -70,12 +70,12 @@
|
|
|
70
70
|
"@dnd-kit/core": "^6.3.1",
|
|
71
71
|
"@dnd-kit/sortable": "^10.0.0",
|
|
72
72
|
"@dnd-kit/utilities": "^3.2.2",
|
|
73
|
-
"@open-mercato/ai-assistant": "0.10.1-develop.
|
|
74
|
-
"@open-mercato/core": "0.10.1-develop.
|
|
75
|
-
"@open-mercato/queue": "0.10.1-develop.
|
|
76
|
-
"@open-mercato/scheduler": "0.10.1-develop.
|
|
77
|
-
"@open-mercato/ui": "0.10.1-develop.
|
|
78
|
-
"@open-mercato/web-research": "0.10.1-develop.
|
|
73
|
+
"@open-mercato/ai-assistant": "0.10.1-develop.8129.1.149839452c",
|
|
74
|
+
"@open-mercato/core": "0.10.1-develop.8129.1.149839452c",
|
|
75
|
+
"@open-mercato/queue": "0.10.1-develop.8129.1.149839452c",
|
|
76
|
+
"@open-mercato/scheduler": "0.10.1-develop.8129.1.149839452c",
|
|
77
|
+
"@open-mercato/ui": "0.10.1-develop.8129.1.149839452c",
|
|
78
|
+
"@open-mercato/web-research": "0.10.1-develop.8129.1.149839452c",
|
|
79
79
|
"@simplewebauthn/browser": "^13.3.0",
|
|
80
80
|
"@simplewebauthn/server": "^13.3.2",
|
|
81
81
|
"@simplewebauthn/types": "^12.0.0",
|
|
@@ -87,14 +87,14 @@
|
|
|
87
87
|
},
|
|
88
88
|
"peerDependencies": {
|
|
89
89
|
"@mikro-orm/core": "^7.0.14",
|
|
90
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
90
|
+
"@open-mercato/shared": "0.10.1-develop.8129.1.149839452c",
|
|
91
91
|
"react": "^19.0.0",
|
|
92
92
|
"react-dom": "^19.0.0",
|
|
93
93
|
"react-is": ">=18.0.0",
|
|
94
94
|
"zod": ">=3.23.0"
|
|
95
95
|
},
|
|
96
96
|
"devDependencies": {
|
|
97
|
-
"@open-mercato/shared": "0.10.1-develop.
|
|
97
|
+
"@open-mercato/shared": "0.10.1-develop.8129.1.149839452c",
|
|
98
98
|
"@types/jest": "^30.0.0",
|
|
99
99
|
"@types/react": "^19.2.18",
|
|
100
100
|
"@types/react-dom": "^19.2.5",
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
# Enterprise RLS connection proof
|
|
2
|
+
|
|
3
|
+
Commercial Enterprise prototype for [#244](https://github.com/open-mercato/open-mercato/issues/244). It is deliberately unregistered: importing the enterprise package does not install it or enable policies on application tables.
|
|
4
|
+
|
|
5
|
+
The adapter initializes tenant session state on the **same checked-out pg client**, before returning it to MikroORM/Kysely. It clears absent scope on every reservation and destroys the client if setup fails. Promise and callback acquisition are supported, including `pool.query` and the existing application pool instrumentation.
|
|
6
|
+
|
|
7
|
+
Run from the repository root after installing dependencies and building packages:
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
yarn workspace @open-mercato/enterprise test --runInBand --testPathPatterns=poolScope.test.ts
|
|
11
|
+
yarn tsc --project packages/enterprise/poc/rls/tsconfig.json --noEmit
|
|
12
|
+
```
|
|
13
|
+
|
|
14
|
+
Set `OM_RLS_POC_DATABASE_URL` privately to a **disposable** PostgreSQL database whose administrative role may create roles and schemas, then run:
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
yarn tsx packages/enterprise/poc/rls/run.ts
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
The proof creates a random restricted login role and schema, verifies the runtime role is neither superuser, `BYPASSRLS` nor table owner, and tears down its own fixtures in `finally`. It does not run app migrations. Never point it at a production database.
|
|
21
|
+
|
|
22
|
+
The live checks cover ORM reads/flush, raw SQL, Kysely, transaction commit/rollback, one-client A→B→absent reuse, rejected writes, setup-failure recovery with max=1, 60 concurrent reads plus 60 mixed transactions over max=3, and the old `SET LOCAL` autocommit failure. Ordinary CI runs the unit suite; this live proof is an explicit operator command and is **not automatically run by existing GitHub CI**.
|
|
23
|
+
|
|
24
|
+
This prototype requires direct PostgreSQL or session-compatible pooling. It does not support transaction-pooling proxies, escaped transaction/client reuse between tenant scopes, global maintenance, or application-wide entry-point coverage. Keep all existing tenant, organization, authorization and encryption checks. Do not install it in a production app; the [enterprise specification](../../../../.ai/specs/enterprise/2026-11-12-row-level-security.md) defines the remaining activation gates.
|
|
25
|
+
|
|
26
|
+
## Observed proof, 2026-11-12
|
|
27
|
+
|
|
28
|
+
Against a dedicated PostgreSQL 16 container, all **12 live checks passed**, including 60 overlapping tenant reads, 60 mixed transactions through a pool of 3, and recovery from setup failure over a pool of 1. The negative control confirmed that transaction-local state set outside an explicit transaction does not protect a later autocommit query. The expanded proof passed on Node 24.
|
|
29
|
+
|
|
30
|
+
The mixed-operation check uses a bounded first-wave barrier to require **three distinct PostgreSQL backend PIDs holding transactions simultaneously**, with both tenants represented. Each operation creates through ORM/flush, updates through Kysely, attempts raw update/delete against the other tenant, reads without an application tenant predicate, and rechecks the pinned PID and tenant setting. Of the 60 transactions, 40 commit and 20 deliberately roll back; committed deletes leave exactly 30 new rows. A privileged final read must exactly match those rows and both unchanged seed rows. `Promise.allSettled` drains all work before reporting errors, and only the deliberate rollback sentinel is accepted as an expected failure.
|
|
31
|
+
|
|
32
|
+
The 12 ordinary unit tests and dedicated harness no-emit typecheck also passed. Independent review found no blocking source issue. Full repository and GitHub CI results are tracked on [PR #9353](https://github.com/open-mercato/open-mercato/pull/9353); these proof results alone do not imply full-CI success or production readiness.
|
package/poc/rls/run.ts
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
1
|
+
import assert from 'node:assert/strict'
|
|
2
|
+
import { randomUUID } from 'node:crypto'
|
|
3
|
+
import { EntitySchema, MikroORM } from '@mikro-orm/core'
|
|
4
|
+
import { PostgreSqlDriver, type EntityManager } from '@mikro-orm/postgresql'
|
|
5
|
+
import { Pool, type PoolClient } from 'pg'
|
|
6
|
+
import { attachPoolErrorHandlers, instrumentPrimaryPool, resolvePoolConfig, type ObservablePool } from '@open-mercato/shared/lib/db/mikro'
|
|
7
|
+
import { installRlsPoolScope, runWithRlsTenant } from '../../src/lib/rls/poc/poolScope'
|
|
8
|
+
|
|
9
|
+
const databaseUrl = process.env.OM_RLS_POC_DATABASE_URL
|
|
10
|
+
assert.ok(databaseUrl, 'Set OM_RLS_POC_DATABASE_URL to a DISPOSABLE PostgreSQL database with role/schema creation privileges')
|
|
11
|
+
const suffix = randomUUID().replaceAll('-', '')
|
|
12
|
+
const schema = `rls_poc_${suffix}`
|
|
13
|
+
const role = `rls_poc_${suffix}`
|
|
14
|
+
const password = randomUUID()
|
|
15
|
+
const admin = new Pool({ connectionString: databaseUrl, max: 1 })
|
|
16
|
+
const runtimeUrl = new URL(databaseUrl)
|
|
17
|
+
runtimeUrl.username = role
|
|
18
|
+
runtimeUrl.password = password
|
|
19
|
+
const tenantA = randomUUID()
|
|
20
|
+
const tenantB = randomUUID()
|
|
21
|
+
const rowA = randomUUID()
|
|
22
|
+
const rowB = randomUUID()
|
|
23
|
+
type RecordRow = { id: string; tenantId: string; label: string }
|
|
24
|
+
type ProbeDatabase = { records: { id: string; tenant_id: string; label: string } }
|
|
25
|
+
const probe = new EntitySchema<RecordRow>({
|
|
26
|
+
name: 'RlsPocRecord', tableName: 'records', schema,
|
|
27
|
+
properties: {
|
|
28
|
+
id: { type: 'uuid', primary: true },
|
|
29
|
+
tenantId: { type: 'uuid', fieldName: 'tenant_id' },
|
|
30
|
+
label: { type: 'string' },
|
|
31
|
+
},
|
|
32
|
+
})
|
|
33
|
+
type TestOrm = MikroORM<PostgreSqlDriver, EntityManager<PostgreSqlDriver>>
|
|
34
|
+
const orms: TestOrm[] = []
|
|
35
|
+
const disposers: Array<() => void> = []
|
|
36
|
+
const pools: Pool[] = []
|
|
37
|
+
const table = `"${schema}"."records"`
|
|
38
|
+
let checks = 0
|
|
39
|
+
async function check(name: string, fn: () => Promise<void>) {
|
|
40
|
+
await fn()
|
|
41
|
+
checks += 1
|
|
42
|
+
process.stdout.write(`PASS ${name}\n`)
|
|
43
|
+
}
|
|
44
|
+
async function openOrm(max: number, scoped = true): Promise<TestOrm> {
|
|
45
|
+
const defaults = resolvePoolConfig({ NODE_ENV: 'test' })
|
|
46
|
+
const orm = await MikroORM.init<PostgreSqlDriver, EntityManager<PostgreSqlDriver>>({
|
|
47
|
+
driver: PostgreSqlDriver, clientUrl: runtimeUrl.toString(), entities: [probe],
|
|
48
|
+
pool: { min: 0, max, idleTimeoutMillis: defaults.poolIdleTimeout },
|
|
49
|
+
driverOptions: {
|
|
50
|
+
connectionTimeoutMillis: defaults.poolAcquireTimeout,
|
|
51
|
+
idle_in_transaction_session_timeout: defaults.idleInTransactionTimeoutMs,
|
|
52
|
+
onPoolCreated: (pool: Pool) => {
|
|
53
|
+
pools.push(pool)
|
|
54
|
+
attachPoolErrorHandlers(pool as unknown as ObservablePool)
|
|
55
|
+
disposers.push(instrumentPrimaryPool(pool as unknown as ObservablePool))
|
|
56
|
+
if (scoped) disposers.push(installRlsPoolScope(pool))
|
|
57
|
+
},
|
|
58
|
+
},
|
|
59
|
+
})
|
|
60
|
+
orms.push(orm)
|
|
61
|
+
return orm
|
|
62
|
+
}
|
|
63
|
+
async function labels(em: EntityManager): Promise<string[]> {
|
|
64
|
+
const rows = await em.execute<Array<{ label: string }>>(`select label from ${table} order by label`)
|
|
65
|
+
return rows.map((row) => row.label)
|
|
66
|
+
}
|
|
67
|
+
try {
|
|
68
|
+
await admin.query(`create role "${role}" login password '${password}' nosuperuser nobypassrls nocreatedb nocreaterole noinherit`)
|
|
69
|
+
await admin.query(`create schema "${schema}"`)
|
|
70
|
+
await admin.query(`create table ${table} (id uuid primary key, tenant_id uuid not null, label text not null)`)
|
|
71
|
+
await admin.query(`insert into ${table} values ($1, $2, 'A'), ($3, $4, 'B')`, [rowA, tenantA, rowB, tenantB])
|
|
72
|
+
await admin.query(`alter table ${table} enable row level security`)
|
|
73
|
+
await admin.query(`alter table ${table} force row level security`)
|
|
74
|
+
const predicate = "tenant_id = nullif(current_setting('app.current_tenant_id', true), '')::uuid"
|
|
75
|
+
await admin.query(`create policy tenant_boundary on ${table} using (${predicate}) with check (${predicate})`)
|
|
76
|
+
await admin.query(`grant usage on schema "${schema}" to "${role}"`)
|
|
77
|
+
await admin.query(`grant select, insert, update, delete on ${table} to "${role}"`)
|
|
78
|
+
const orm = await openOrm(1)
|
|
79
|
+
const fork = () => orm.em.fork({ clear: true, freshEventManager: true, useContext: true })
|
|
80
|
+
await check('runtime role cannot bypass RLS and does not own the table', async () => {
|
|
81
|
+
const rows = await fork().execute<Array<{ rolsuper: boolean; rolbypassrls: boolean; owns: boolean }>>(
|
|
82
|
+
`select r.rolsuper, r.rolbypassrls, c.relowner = r.oid as owns from pg_roles r, pg_class c join pg_namespace n on n.oid = c.relnamespace where r.rolname = current_user and n.nspname = ? and c.relname = 'records'`, [schema],
|
|
83
|
+
)
|
|
84
|
+
assert.deepEqual(rows, [{ rolsuper: false, rolbypassrls: false, owns: false }])
|
|
85
|
+
})
|
|
86
|
+
await check('autocommit ORM, raw connection, and Kysely reads obey tenant scope', async () => {
|
|
87
|
+
await runWithRlsTenant(tenantA, async () => {
|
|
88
|
+
assert.deepEqual((await fork().find(probe, {})).map((row) => row.label), ['A'])
|
|
89
|
+
assert.deepEqual(await fork().getConnection().execute(`select label from ${table}`), [{ label: 'A' }])
|
|
90
|
+
assert.deepEqual(await fork().getKysely<ProbeDatabase>().withSchema(schema).selectFrom('records').select('label').execute(), [{ label: 'A' }])
|
|
91
|
+
})
|
|
92
|
+
})
|
|
93
|
+
await check('same physical connection switches A to B and clears absent context', async () => {
|
|
94
|
+
const pids: number[] = []
|
|
95
|
+
for (const tenant of [tenantA, tenantB, tenantA]) {
|
|
96
|
+
await runWithRlsTenant(tenant, async () => {
|
|
97
|
+
const rows = await fork().execute<Array<{ pid: number }>>('select pg_backend_pid() as pid')
|
|
98
|
+
pids.push(rows[0].pid)
|
|
99
|
+
assert.deepEqual(await labels(fork()), tenant === tenantA ? ['A'] : ['B'])
|
|
100
|
+
})
|
|
101
|
+
}
|
|
102
|
+
assert.equal(new Set(pids).size, 1)
|
|
103
|
+
assert.deepEqual(await labels(fork()), [])
|
|
104
|
+
})
|
|
105
|
+
await check('missing context denies writes; wrong tenant insert and reassignment are rejected', async () => {
|
|
106
|
+
await assert.rejects(fork().execute(`insert into ${table} values (?, ?, 'denied')`, [randomUUID(), tenantA]), /row.level security/i)
|
|
107
|
+
await runWithRlsTenant(tenantA, async () => {
|
|
108
|
+
await assert.rejects(fork().execute(`insert into ${table} values (?, ?, 'denied')`, [randomUUID(), tenantB]), /row.level security/i)
|
|
109
|
+
await assert.rejects(fork().execute(`update ${table} set tenant_id = ? where id = ?`, [tenantB, rowA]), /row.level security/i)
|
|
110
|
+
const result = await fork().execute(`delete from ${table} where id = ? returning id`, [rowB])
|
|
111
|
+
assert.deepEqual(result, [])
|
|
112
|
+
})
|
|
113
|
+
})
|
|
114
|
+
await check('ORM flush, explicit transaction and Kysely share the pinned connection', async () => {
|
|
115
|
+
await runWithRlsTenant(tenantA, () => fork().transactional(async (tx) => {
|
|
116
|
+
const id = randomUUID()
|
|
117
|
+
tx.persist(tx.create(probe, { id, tenantId: tenantA, label: 'A-created' }))
|
|
118
|
+
await tx.flush()
|
|
119
|
+
assert.equal((await tx.getKysely<ProbeDatabase>().withSchema(schema).selectFrom('records').select('id').where('id', '=', id).execute()).length, 1)
|
|
120
|
+
assert.equal(await tx.count(probe, {}), 2)
|
|
121
|
+
await tx.nativeDelete(probe, { id })
|
|
122
|
+
}))
|
|
123
|
+
assert.deepEqual(await labels(fork()), [])
|
|
124
|
+
})
|
|
125
|
+
await check('rollback returns a reusable connection with no context on the next reservation', async () => {
|
|
126
|
+
await assert.rejects(runWithRlsTenant(tenantA, () => fork().transactional(async (tx) => {
|
|
127
|
+
await tx.execute(`insert into ${table} values (?, ?, 'rolled-back')`, [randomUUID(), tenantA])
|
|
128
|
+
throw new Error('[internal] deliberate rollback')
|
|
129
|
+
})), /deliberate rollback/)
|
|
130
|
+
assert.deepEqual(await labels(fork()), [])
|
|
131
|
+
assert.deepEqual(await runWithRlsTenant(tenantA, () => labels(fork())), ['A'])
|
|
132
|
+
})
|
|
133
|
+
await check('callback pool.query inherits scope and missing scope clears it', async () => {
|
|
134
|
+
const pool = pools[0]
|
|
135
|
+
await runWithRlsTenant(tenantB, async () => assert.deepEqual((await pool.query(`select label from ${table}`)).rows, [{ label: 'B' }]))
|
|
136
|
+
assert.deepEqual((await pool.query(`select label from ${table}`)).rows, [])
|
|
137
|
+
})
|
|
138
|
+
await check('failed setup destroys the checked-out client and max=1 recovers', async () => {
|
|
139
|
+
const pool = pools[0]
|
|
140
|
+
const client = await pool.connect()
|
|
141
|
+
const originalQuery = client.query
|
|
142
|
+
client.query = (() => Promise.reject(new Error('[internal] deliberate setup failure'))) as PoolClient['query']
|
|
143
|
+
client.release()
|
|
144
|
+
await assert.rejects(pool.connect(), /deliberate setup failure/)
|
|
145
|
+
client.query = originalQuery
|
|
146
|
+
assert.deepEqual(await runWithRlsTenant(tenantB, () => labels(fork())), ['B'])
|
|
147
|
+
})
|
|
148
|
+
await check('SET LOCAL outside a transaction reproduces the previous implementation failure', async () => {
|
|
149
|
+
const control = await openOrm(1, false)
|
|
150
|
+
const em = control.em.fork()
|
|
151
|
+
await em.execute("select set_config('app.current_tenant_id', ?, true)", [tenantA])
|
|
152
|
+
assert.deepEqual(await labels(em), [])
|
|
153
|
+
})
|
|
154
|
+
const parallelOrm = await openOrm(3)
|
|
155
|
+
await check('60 overlapping tenant requests stay isolated through a pool of 3', async () => {
|
|
156
|
+
await Promise.all(Array.from({ length: 60 }, (_, index) => {
|
|
157
|
+
const tenant = index % 2 === 0 ? tenantA : tenantB
|
|
158
|
+
return runWithRlsTenant(tenant, async () => {
|
|
159
|
+
const em = parallelOrm.em.fork({ clear: true, freshEventManager: true })
|
|
160
|
+
await em.execute('select pg_sleep(0.005)')
|
|
161
|
+
assert.deepEqual(await labels(em), tenant === tenantA ? ['A'] : ['B'])
|
|
162
|
+
})
|
|
163
|
+
}))
|
|
164
|
+
assert.deepEqual(await labels(parallelOrm.em.fork()), [])
|
|
165
|
+
})
|
|
166
|
+
await check('60 concurrent mixed transactions isolate writes, commits, rollbacks and deletes across 3 simultaneous backends', async () => {
|
|
167
|
+
const operations = Array.from({ length: 60 }, (_, index) => ({
|
|
168
|
+
id: randomUUID(),
|
|
169
|
+
tenantId: index % 2 === 0 ? tenantA : tenantB,
|
|
170
|
+
label: `concurrent-${index}-updated`,
|
|
171
|
+
rollback: index % 3 === 0,
|
|
172
|
+
remove: index % 4 === 0,
|
|
173
|
+
}))
|
|
174
|
+
const firstWaveBackends = new Set<number>()
|
|
175
|
+
const firstWaveTenants = new Set<string>()
|
|
176
|
+
let releaseFirstWave: () => void = () => undefined
|
|
177
|
+
const firstWave = new Promise<void>((resolve) => { releaseFirstWave = resolve })
|
|
178
|
+
const barrierTimeout = setTimeout(releaseFirstWave, 5_000)
|
|
179
|
+
let activeTransactions = 0
|
|
180
|
+
let peakTransactions = 0
|
|
181
|
+
try {
|
|
182
|
+
const outcomes = await Promise.allSettled(operations.map(async (operation, index) => {
|
|
183
|
+
const rollback = new Error('[internal] deliberate concurrent rollback')
|
|
184
|
+
const transaction = runWithRlsTenant(operation.tenantId, () =>
|
|
185
|
+
parallelOrm.em.fork({ clear: true, freshEventManager: true }).transactional(async (tx) => {
|
|
186
|
+
activeTransactions += 1
|
|
187
|
+
peakTransactions = Math.max(peakTransactions, activeTransactions)
|
|
188
|
+
try {
|
|
189
|
+
const [connection] = await tx.execute<Array<{ pid: number; tenant: string }>>(
|
|
190
|
+
"select pg_backend_pid() as pid, current_setting('app.current_tenant_id') as tenant",
|
|
191
|
+
)
|
|
192
|
+
assert.equal(connection.tenant, operation.tenantId)
|
|
193
|
+
if (index < 3) {
|
|
194
|
+
firstWaveBackends.add(connection.pid)
|
|
195
|
+
firstWaveTenants.add(operation.tenantId)
|
|
196
|
+
if (firstWaveBackends.size === 3) releaseFirstWave()
|
|
197
|
+
await firstWave
|
|
198
|
+
assert.equal(firstWaveBackends.size, 3, 'The first wave must hold three distinct database connections simultaneously')
|
|
199
|
+
}
|
|
200
|
+
tx.persist(tx.create(probe, { id: operation.id, tenantId: operation.tenantId, label: 'concurrent-created' }))
|
|
201
|
+
await tx.flush()
|
|
202
|
+
const updated = await tx.getKysely<ProbeDatabase>().withSchema(schema)
|
|
203
|
+
.updateTable('records').set({ label: operation.label }).where('id', '=', operation.id)
|
|
204
|
+
.returningAll().executeTakeFirstOrThrow()
|
|
205
|
+
assert.equal(updated.tenant_id, operation.tenantId)
|
|
206
|
+
assert.equal(updated.label, operation.label)
|
|
207
|
+
const foreignId = operation.tenantId === tenantA ? rowB : rowA
|
|
208
|
+
assert.deepEqual(await tx.execute(`update ${table} set label = 'cross-tenant' where id = ? returning id`, [foreignId]), [])
|
|
209
|
+
assert.deepEqual(await tx.execute(`delete from ${table} where id = ? returning id`, [foreignId]), [])
|
|
210
|
+
const visible = await tx.execute<Array<{ tenant_id: string }>>(`select tenant_id from ${table}`)
|
|
211
|
+
assert.ok(visible.length > 0)
|
|
212
|
+
assert.ok(visible.every((row) => row.tenant_id === operation.tenantId))
|
|
213
|
+
const [afterWrites] = await tx.execute<Array<{ pid: number; tenant: string }>>(
|
|
214
|
+
"select pg_backend_pid() as pid, current_setting('app.current_tenant_id') as tenant",
|
|
215
|
+
)
|
|
216
|
+
assert.deepEqual(afterWrites, connection)
|
|
217
|
+
if (operation.remove) await tx.nativeDelete(probe, { id: operation.id })
|
|
218
|
+
if (operation.rollback) throw rollback
|
|
219
|
+
} finally {
|
|
220
|
+
activeTransactions -= 1
|
|
221
|
+
}
|
|
222
|
+
}),
|
|
223
|
+
)
|
|
224
|
+
if (operation.rollback) await assert.rejects(transaction, (error) => error === rollback)
|
|
225
|
+
else await transaction
|
|
226
|
+
}))
|
|
227
|
+
for (const outcome of outcomes) {
|
|
228
|
+
if (outcome.status === 'rejected') throw outcome.reason
|
|
229
|
+
}
|
|
230
|
+
assert.equal(peakTransactions, 3)
|
|
231
|
+
assert.equal(activeTransactions, 0)
|
|
232
|
+
assert.deepEqual([...firstWaveTenants].sort(), [tenantA, tenantB].sort())
|
|
233
|
+
const expected = [
|
|
234
|
+
{ id: rowA, tenant_id: tenantA, label: 'A' },
|
|
235
|
+
{ id: rowB, tenant_id: tenantB, label: 'B' },
|
|
236
|
+
...operations.filter((operation) => !operation.rollback && !operation.remove)
|
|
237
|
+
.map((operation) => ({ id: operation.id, tenant_id: operation.tenantId, label: operation.label })),
|
|
238
|
+
].sort((left, right) => left.id.localeCompare(right.id))
|
|
239
|
+
const actual = await admin.query<{ id: string; tenant_id: string; label: string }>(`select id, tenant_id, label from ${table}`)
|
|
240
|
+
assert.deepEqual(actual.rows.sort((left, right) => left.id.localeCompare(right.id)), expected)
|
|
241
|
+
assert.deepEqual(await labels(parallelOrm.em.fork()), [])
|
|
242
|
+
} finally {
|
|
243
|
+
clearTimeout(barrierTimeout)
|
|
244
|
+
}
|
|
245
|
+
})
|
|
246
|
+
await check('nested tenant switching is rejected', async () => {
|
|
247
|
+
assert.throws(() => runWithRlsTenant(tenantA, () => runWithRlsTenant(tenantB, () => undefined)), /Cannot change RLS tenant/)
|
|
248
|
+
})
|
|
249
|
+
process.stdout.write(`Enterprise RLS PoC: ${checks} checks passed; disposable fixtures only.\n`)
|
|
250
|
+
} finally {
|
|
251
|
+
for (const dispose of disposers.reverse()) dispose()
|
|
252
|
+
await Promise.allSettled(orms.map((orm) => orm.close(true)))
|
|
253
|
+
try {
|
|
254
|
+
await admin.query(`drop schema if exists "${schema}" cascade`)
|
|
255
|
+
await admin.query(`drop role if exists "${role}"`)
|
|
256
|
+
} finally {
|
|
257
|
+
await admin.end()
|
|
258
|
+
}
|
|
259
|
+
}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { AsyncLocalStorage } from 'node:async_hooks'
|
|
2
|
+
import { z } from 'zod'
|
|
3
|
+
|
|
4
|
+
export type ScopeClient = {
|
|
5
|
+
query(text: string, values: string[]): Promise<unknown>
|
|
6
|
+
release(error?: Error | boolean): void
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
export type ScopeConnectCallback = (
|
|
10
|
+
error: Error | undefined,
|
|
11
|
+
client: ScopeClient | undefined,
|
|
12
|
+
release: (error?: Error | boolean) => void,
|
|
13
|
+
) => void
|
|
14
|
+
|
|
15
|
+
export type ScopeConnect = {
|
|
16
|
+
(): Promise<ScopeClient>
|
|
17
|
+
(callback: ScopeConnectCallback): void
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export type ScopePool = { connect: ScopeConnect }
|
|
21
|
+
|
|
22
|
+
type TenantScope = Readonly<{ tenantId: string }>
|
|
23
|
+
|
|
24
|
+
const tenantScope = new AsyncLocalStorage<TenantScope>()
|
|
25
|
+
const tenantIdSchema = z.string().uuid()
|
|
26
|
+
const installedPools = new WeakMap<ScopePool, () => void>()
|
|
27
|
+
const setTenantSql = "select set_config('app.current_tenant_id', $1, false)"
|
|
28
|
+
|
|
29
|
+
export function runWithRlsTenant<Result>(tenantId: string, fn: () => Result): Result {
|
|
30
|
+
const parsed = tenantIdSchema.safeParse(tenantId)
|
|
31
|
+
if (!parsed.success) throw new Error('[internal] RLS tenant must be a UUID')
|
|
32
|
+
const normalizedTenantId = parsed.data.toLowerCase()
|
|
33
|
+
const current = tenantScope.getStore()
|
|
34
|
+
if (current && current.tenantId !== normalizedTenantId) {
|
|
35
|
+
throw new Error('[internal] Cannot change RLS tenant inside an active tenant scope')
|
|
36
|
+
}
|
|
37
|
+
return tenantScope.run(Object.freeze({ tenantId: normalizedTenantId }), fn)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function asError(error: unknown): Error {
|
|
41
|
+
return error instanceof Error ? error : new Error('[internal] RLS connection setup failed', { cause: error })
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function installRlsPoolScope(pool: ScopePool): () => void {
|
|
45
|
+
const existing = installedPools.get(pool)
|
|
46
|
+
if (existing) return existing
|
|
47
|
+
const originalConnect = pool.connect
|
|
48
|
+
|
|
49
|
+
async function acquireScopedClient(receiver: ScopePool, tenantId: string): Promise<ScopeClient> {
|
|
50
|
+
const client = await (originalConnect as () => Promise<ScopeClient>).call(receiver)
|
|
51
|
+
try {
|
|
52
|
+
await client.query(setTenantSql, [tenantId])
|
|
53
|
+
return client
|
|
54
|
+
} catch (error) {
|
|
55
|
+
client.release(asError(error))
|
|
56
|
+
throw error
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const scopedConnect = function (
|
|
61
|
+
this: ScopePool,
|
|
62
|
+
callback?: ScopeConnectCallback,
|
|
63
|
+
): Promise<ScopeClient> | void {
|
|
64
|
+
const clientPromise = acquireScopedClient(this, tenantScope.getStore()?.tenantId ?? '')
|
|
65
|
+
if (!callback) return clientPromise
|
|
66
|
+
void clientPromise.then(
|
|
67
|
+
(client) => callback(undefined, client, client.release.bind(client)),
|
|
68
|
+
(error: unknown) => callback(asError(error), undefined, () => undefined),
|
|
69
|
+
)
|
|
70
|
+
} as ScopeConnect
|
|
71
|
+
|
|
72
|
+
pool.connect = scopedConnect
|
|
73
|
+
let disposed = false
|
|
74
|
+
const dispose = () => {
|
|
75
|
+
if (disposed) return
|
|
76
|
+
disposed = true
|
|
77
|
+
if (pool.connect === scopedConnect) pool.connect = originalConnect
|
|
78
|
+
installedPools.delete(pool)
|
|
79
|
+
}
|
|
80
|
+
installedPools.set(pool, dispose)
|
|
81
|
+
return dispose
|
|
82
|
+
}
|