From cf04c7b52840f23e392a211de4093644b5635c9d Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 20:46:39 +0000 Subject: [PATCH 1/3] test(plugin-security): probe that no shipped non-admin set reads a private credential row Drives the real SecurityPlugin + ObjectQL over SqlDriver with the shipped permission sets, across three deployment shapes, and asserts that every non-admin persona reads no row of sys_verification or sys_jwks (list, count and by-id), while the platform admin and the system context keep every row. Committed before the fix: on this tree the persona cases are red. Claude-Session: https://claude.ai/code/session_01Evb5jFDZGKQE9KG4jbMfMF Co-authored-by: Claude --- .../src/private-credential-row-scope.test.ts | 282 ++++++++++++++++++ 1 file changed, 282 insertions(+) create mode 100644 packages/plugins/plugin-security/src/private-credential-row-scope.test.ts diff --git a/packages/plugins/plugin-security/src/private-credential-row-scope.test.ts b/packages/plugins/plugin-security/src/private-credential-row-scope.test.ts new file mode 100644 index 00000000000..ffaf00c10b7 --- /dev/null +++ b/packages/plugins/plugin-security/src/private-credential-row-scope.test.ts @@ -0,0 +1,282 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * `sys_verification` and `sys_jwks` hold credentials: one-time verification and + * password-reset tokens, and the environment's JWT signing keys. Both objects + * declare `access: { default: 'private' }`, and `default-permission-sets.ts` + * says they "stay DENY for non-admins by design". This file holds that + * contract: no shipped permission set below platform admin reads a row of + * either object. + * + * The class is the one the header of `objects/default-permission-sets.ts` + * describes. Every object on `BETTER_AUTH_MANAGED_OBJECTS` gets an EXPLICIT + * per-object read entry from `denyWritesOnManagedObjects()`. An explicit entry + * is not the `'*'` wildcard, so the `private` posture (which only keeps a plain + * wildcard off an object) never applies to it. What narrows the read is the row + * policy the holder's set declares, and neither object had one. + * + * The fix is the header's own instrument, the per-object row scope: a `_none` + * policy (`id == null`, no row) on each object, in every shipped set that holds + * the blanket and carries row-level security. The two readers that must keep + * every row are controls here: + * - the platform admin (`admin_full_access`), through its superuser bypass; + * - better-auth itself, which reads these tables through its adapter under + * system context (`withSystemContext` in plugin-auth injects exactly the + * `{ isSystem: true }` context used below). + * + * Driven on the real `SecurityPlugin` + `ObjectQL` over a real `SqlDriver`, + * with the SHIPPED permission sets (no copy). Rows are written straight into + * the tables, past every scope. Three deployment shapes, as in + * `scim-projection-row-scope.test.ts`: + * - `isolated` with the platform baseline composed (the stock walled shape); + * - `isolated` with NO baseline, where each persona resolves only the set it + * names, so a set that carried no scope of its own reads every row even + * while the stock shape stays green through `member_default`; + * - `single`, where the policies carry no tenant token and so must survive + * the posture's strip of the platform's tenant policies (ADR-0105 D3). + */ + +import { describe, it, expect, afterAll, beforeAll, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysJwks, SysMember, SysUser, SysVerification } from '@objectstack/platform-objects/identity'; +import { SecurityPlugin } from './security-plugin.js'; + +const CREDENTIAL_OBJECTS = ['sys_verification', 'sys_jwks'] as const; +type CredentialObject = (typeof CREDENTIAL_OBJECTS)[number]; + +const SCHEMAS = [SysUser, SysMember, SysVerification, SysJwks]; + +/** + * The people in the fixture. `u_x`, `v_x` and `a_x` belong to organization X; + * `u_y` belongs to organization Y. Each person has one verification row keyed + * on their own address, so "a principal's own row" exists for every persona. + */ +const PEOPLE = { member: 'u_x', viewer: 'v_x', admin: 'a_x', otherOrg: 'u_y' } as const; +const ORG_OF: Record = { u_x: 'org_x', v_x: 'org_x', a_x: 'org_x', u_y: 'org_y' }; +const emailOf = (user: string) => `${user}@example.test`; + +const verificationId = (user: string) => `sys_verification:${user}`; +const JWKS_IDS = ['sys_jwks:k1', 'sys_jwks:k2'] as const; + +function fixtureRows(): Record>> { + return { + sys_verification: Object.values(PEOPLE).map((user) => ({ + id: verificationId(user), + identifier: emailOf(user), + value: `token-${user}`, + expires_at: '2099-01-01T00:00:00.000Z', + })), + sys_jwks: JWKS_IDS.map((id) => ({ + id, + public_key: `{"kid":"${id}"}`, + private_key: `{"kid":"${id}","d":"material-${id}"}`, + created_at: '2026-01-01T00:00:00.000Z', + })), + }; +} + +/** The driver's own query builder, reached past its `protected` modifier. */ +type Table = (name: string) => { insert(rows: Array>): Promise }; + +interface Shape { + label: string; + posture: 'isolated' | 'single'; + composedBaseline: boolean; +} + +const SHAPES: Shape[] = [ + { label: 'isolated posture, platform baseline composed (the stock shape)', posture: 'isolated', composedBaseline: true }, + { label: 'isolated posture, no platform baseline (each set on its own)', posture: 'isolated', composedBaseline: false }, + { label: 'single posture, platform baseline composed', posture: 'single', composedBaseline: true }, +]; + +async function boot(shape: Shape): Promise { + const driver = new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }); + const engine = new ObjectQL(); + engine.registerDriver(driver as never, true); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.private-credential-row-scope', + name: 'Private credential row scope', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: SCHEMAS, + } as never); + await engine.syncSchemas(); + + const services: Record = { + ...(shape.posture === 'isolated' ? { 'org-scoping': { name: 'com.objectstack.org-scoping' } } : {}), + tenancy: { posture: shape.posture }, + manifest: { register: vi.fn() }, + objectql: engine, + // `list` answers nothing, so every set name resolves from the plugin's + // bootstrap list: the SHIPPED `defaultPermissionSets`, not a copy. + metadata: { get: async (_t: string, name: string) => engine.getSchema(name) ?? null, list: async () => [] }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: vi.fn(), + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin(shape.composedBaseline ? {} : { fallbackPermissionSet: null }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + vi.spyOn((engine as unknown as { logger: { warn: () => void } }).logger, 'warn').mockImplementation(() => undefined); + + // Straight into the tables, past every scope: the fixture is not the subject. + const table = (driver as unknown as { knex: Table }).knex; + for (const [object, rows] of Object.entries(fixtureRows())) await table(object).insert(rows); + await table('sys_user').insert(Object.values(PEOPLE).map((id) => ({ id, name: id, email: emailOf(id) }))); + await table('sys_member').insert( + Object.values(PEOPLE).map((id) => ({ + id: `sys_member:${id}`, + user_id: id, + organization_id: ORG_OF[id], + role: id === PEOPLE.admin ? 'admin' : 'member', + })), + ); + return engine; +} + +/** Organization X's co-members, as the authz resolver pre-resolves them. */ +const ORG_X_USERS = Object.values(PEOPLE).filter((id) => ORG_OF[id] === 'org_x'); + +/** + * Each shipped set that holds the managed-object read grant, carried by a + * principal of organization X exactly as the authz resolver shapes it — each + * naming its set explicitly, so it resolves even where no baseline is composed. + */ +const PERSONAS = { + member_default: { + userId: PEOPLE.member, tenantId: 'org_x', positions: ['org_member'], permissions: ['member_default'], + posture: 'MEMBER', org_user_ids: ORG_X_USERS, email: emailOf(PEOPLE.member), + }, + viewer_readonly: { + userId: PEOPLE.viewer, tenantId: 'org_x', positions: ['org_member'], permissions: ['viewer_readonly'], + posture: 'MEMBER', org_user_ids: ORG_X_USERS, email: emailOf(PEOPLE.viewer), + }, + organization_admin: { + userId: PEOPLE.admin, tenantId: 'org_x', positions: ['org_admin'], permissions: ['organization_admin'], + posture: 'TENANT_ADMIN', org_user_ids: ORG_X_USERS, email: emailOf(PEOPLE.admin), + }, + organization_admin_no_bypass: { + userId: PEOPLE.admin, tenantId: 'org_x', positions: ['org_admin'], permissions: ['organization_admin_no_bypass'], + posture: 'TENANT_ADMIN', org_user_ids: ORG_X_USERS, email: emailOf(PEOPLE.admin), + }, + // The MCP write ceiling holds the grant too; it carries no row policy of its + // own by design (ADR-0090 D10), so its bound is the delegating member's sets. + // Those resolve from the baseline, so this persona runs where one is composed. + mcp_agent_data_write: { + userId: 'agent_x', tenantId: 'org_x', positions: [], permissions: ['mcp_agent_data_write'], + principalKind: 'agent', onBehalfOf: { userId: PEOPLE.member }, org_user_ids: ORG_X_USERS, + }, +} as const; +type Persona = keyof typeof PERSONAS; + +/** Whose own verification row each persona has (the delegator's, for the agent). */ +const SELF_OF: Record = { + member_default: PEOPLE.member, + viewer_readonly: PEOPLE.viewer, + organization_admin: PEOPLE.admin, + organization_admin_no_bypass: PEOPLE.admin, + mcp_agent_data_write: PEOPLE.member, +}; + +const PLATFORM_ADMIN = { + userId: 'p_admin', tenantId: 'org_x', positions: [], permissions: ['admin_full_access'], posture: 'PLATFORM_ADMIN', +}; + +/** The context better-auth's adapter reads with (`withSystemContext`, plugin-auth). */ +const BETTER_AUTH_ADAPTER = { isSystem: true }; + +async function idsRead(engine: ObjectQL, object: string, context: object): Promise { + const rows = (await engine.find(object, { context } as never)) as Array<{ id: string }>; + return rows.map((r) => r.id).sort(); +} + +/** Everything `context` reads of the two credential tables, one sorted id list per table. */ +async function credentialTables(engine: ObjectQL, context: object): Promise> { + const out = {} as Record; + for (const object of CREDENTIAL_OBJECTS) out[object] = await idsRead(engine, object, context); + return out; +} + +const EVERY_ROW = (): Record => { + const rows = fixtureRows(); + return { + sys_verification: rows.sys_verification.map((r) => String(r.id)).sort(), + sys_jwks: rows.sys_jwks.map((r) => String(r.id)).sort(), + }; +}; + +describe.each(SHAPES)('private credential tables — $label', (shape) => { + let engine: ObjectQL; + beforeAll(async () => { + engine = await boot(shape); + }); + afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + }); + + const personas = (Object.keys(PERSONAS) as Persona[]).filter( + (p) => shape.composedBaseline || p !== 'mcp_agent_data_write', + ); + + for (const persona of personas) { + it(`${persona}: reads no row of either credential table`, async () => { + const context = PERSONAS[persona]; + expect(await credentialTables(engine, context)).toEqual({ sys_verification: [], sys_jwks: [] }); + for (const object of CREDENTIAL_OBJECTS) { + expect(await engine.count(object, { context } as never), object).toBe(0); + } + }); + + it(`${persona}: a by-id read of a credential row finds nothing — its own verification row, another user's, or a signing key`, async () => { + const context = PERSONAS[persona]; + const ids: Array<[CredentialObject, string]> = [ + ['sys_verification', verificationId(SELF_OF[persona])], + ['sys_verification', verificationId(PEOPLE.otherOrg)], + ['sys_verification', verificationId(persona === 'member_default' ? PEOPLE.viewer : PEOPLE.member)], + ['sys_jwks', JWKS_IDS[0]], + ]; + for (const [object, id] of ids) { + const row = await engine.findOne(object, { where: { id }, context } as never); + expect(row, `${object} ${id}`).toBeNull(); + } + }); + } + + it('CONTROL: the persona contexts are live — each still reads its own `sys_user` row through the same engine', async () => { + for (const persona of personas) { + if (persona === 'mcp_agent_data_write') continue; + expect(await idsRead(engine, 'sys_user', PERSONAS[persona]), persona).toContain(SELF_OF[persona]); + } + }); + + it('CONTROL: the platform admin reads every row of both tables, list and by-id', async () => { + expect(await credentialTables(engine, PLATFORM_ADMIN)).toEqual(EVERY_ROW()); + const row = await engine.findOne('sys_verification', { + where: { id: verificationId(PEOPLE.otherOrg) }, + context: PLATFORM_ADMIN, + } as never); + expect((row as { value?: string } | null)?.value).toBe(`token-${PEOPLE.otherOrg}`); + }); + + it('CONTROL: better-auth’s adapter context (system) reads every row, by identifier and by id', async () => { + expect(await credentialTables(engine, BETTER_AUTH_ADAPTER)).toEqual(EVERY_ROW()); + // The adapter keys verification lookups on `identifier` (better-auth's + // `findByIdentifier`); a signing-key read is by `id`. + const byIdentifier = (await engine.find('sys_verification', { + where: { identifier: emailOf(PEOPLE.member) }, + context: BETTER_AUTH_ADAPTER, + } as never)) as Array<{ value: string }>; + expect(byIdentifier.map((r) => r.value)).toEqual([`token-${PEOPLE.member}`]); + const key = await engine.findOne('sys_jwks', { where: { id: JWKS_IDS[1] }, context: BETTER_AUTH_ADAPTER } as never); + expect((key as { id?: string } | null)?.id).toBe(JWKS_IDS[1]); + }); +}); From 6ccbc9c0ab25424c0bd3e46dbaa967a70cf0b5d4 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 20:52:13 +0000 Subject: [PATCH 2/3] fix(plugin-security)!: no shipped non-admin set reads a row of the private credential tables sys_verification and sys_jwks declare access: private and "DENY for non-admins by design", but the managed-object blanket gives them an explicit per-object read entry, which the private posture does not reach, and neither carried a row policy. Add a no-row select policy for each (privateCredentialRowScope) to every shipped set that holds the blanket and carries row-level security: organization_admin (and so its no-bypass variant), member_default and viewer_readonly. The blanket is not edited. The platform admin keeps every row through the superuser bypass; better-auth keeps its system-context adapter reads. The member_default policy-name pin in rbac-objects.test.ts is re-judged with the two new names. Claude-Session: https://claude.ai/code/session_01Evb5jFDZGKQE9KG4jbMfMF Co-authored-by: Claude --- .../src/objects/default-permission-sets.ts | 64 +++++++++++++++++++ .../src/objects/rbac-objects.test.ts | 8 +++ 2 files changed, 72 insertions(+) diff --git a/packages/plugins/plugin-security/src/objects/default-permission-sets.ts b/packages/plugins/plugin-security/src/objects/default-permission-sets.ts index 2ae6cfa3ab1..37920bbfa76 100644 --- a/packages/plugins/plugin-security/src/objects/default-permission-sets.ts +++ b/packages/plugins/plugin-security/src/objects/default-permission-sets.ts @@ -192,6 +192,58 @@ const scimProjectionRowScope = () => [ }, ]; +/** + * [#20027] The row scope of the two better-auth tables whose rows ARE + * credentials: `sys_verification` (one-time verification and password-reset + * tokens) and `sys_jwks` (the environment's JWT signing keys). Both declare + * `access: { default: 'private' }`, and the contract this file has always + * stated for them is "DENY for non-admins by design" — see the note above the + * `_self` carve-outs in `member_default`. + * + * Why the declaration alone did not hold: `private` keeps a plain `'*'` + * wildcard off an object (`resolveObjectPermission`), but the blanket above + * gives these objects an EXPLICIT per-object read entry, and an explicit entry + * is not the wildcard. The object-level read therefore resolved `true` for + * every set holding the blanket, and neither object had a row policy. The + * retired wildcard `tenant_isolation` policy was what used to deny their rows; + * ADR-0095 D1 moved the tenant wall to Layer 0, which is inert on an object + * with no tenant column. One more instance of the class this file's header + * describes, closed with the instrument the header names: the per-object row + * scope, ⛔ never an edit of the blanket. + * + * `_none` (`id == null`, i.e. no row), the shape `scimProjectionRowScope` + * uses. There is no `_self` form: neither table names a user + * (`sys_verification` keys on an address, `sys_jwks` on nothing), and no + * principal needs to read even their OWN live token — better-auth reads it. + * + * Who keeps every row, and why this does not reach them: + * - the platform admin (`admin_full_access`): its wildcard carries the + * superuser read bypass, which skips Layer 1, and it names neither object + * explicitly; + * - better-auth itself: it reads through its adapter under system context + * (`withSystemContext`, plugin-auth), which no row policy reaches. + * + * Why a policy, and not `private` taking precedence over explicit entries in + * the evaluator: three OTHER `private` objects on the blanket — + * `sys_device_code`, `sys_oauth_access_token`, `sys_oauth_refresh_token` — are + * deliberately readable by their owner through that same explicit entry plus + * a `_self` policy. An evaluator rule would retire those reads too; this scope + * touches only the two objects the contract names. + * + * `select` (not `all`): every write on these tables is already denied at the + * object layer by the blanket. Spread into EVERY shipped set that spreads the + * blanket and carries row-level security (`organization_admin`, and so its + * derived no-bypass variant, `member_default`, `viewer_readonly`), for the + * reason `scimProjectionRowScope` gives: where no platform baseline is + * composed, a set with no policy for an object leaves it unfiltered. The MCP + * write ceiling holds the blanket too; its bound is the delegating user's own + * sets (ADR-0090 D10), which carry this scope. A fresh array per set. + */ +const privateCredentialRowScope = () => [ + { name: 'sys_verification_none', object: 'sys_verification', operation: 'select', using: 'id == null' }, + { name: 'sys_jwks_none', object: 'sys_jwks', operation: 'select', using: 'id == null' }, +]; + /** * Default permission sets seeded by the platform. * @@ -480,6 +532,10 @@ const baseDefaultPermissionSets: PermissionSet[] = [ // admission shaped like `sys_invitation_org_admin` would read every // organization's rows. See `scimProjectionRowScope` above. ...scimProjectionRowScope(), + // [#20027] The credential tables: no row. The org admin's `viewAllRecords` + // does not reach them — the blanket's explicit entry, not the wildcard, + // is what resolves for them. See `privateCredentialRowScope` above. + ...privateCredentialRowScope(), ], }), PermissionSetSchema.parse({ @@ -704,6 +760,10 @@ const baseDefaultPermissionSets: PermissionSet[] = [ // `user_id` (`sys_verification`, `sys_jwks`, empty `sys_passkey`) // stay DENY for non-admins by design — only platform admins (via // `admin_full_access`, which has no RLS) should inspect them. + // [#20027] ⚠️ Since the wildcard policy retired, nothing above denies + // them: the blanket's explicit read entry opens the object, so the + // deny is held by `privateCredentialRowScope` (spread at the end of this + // list and of the two sibling sets). Keep the two together. { name: 'sys_organization_self', object: 'sys_organization', @@ -1024,6 +1084,8 @@ const baseDefaultPermissionSets: PermissionSet[] = [ // [#20001] The SCIM projection tables: a member reads the rows about // themselves and no other — see `scimProjectionRowScope` above. ...scimProjectionRowScope(), + // [#20027] The credential tables: no row — see `privateCredentialRowScope`. + ...privateCredentialRowScope(), ], }), PermissionSetSchema.parse({ @@ -1148,6 +1210,8 @@ const baseDefaultPermissionSets: PermissionSet[] = [ // the platform baseline is not composed a set with no policy for them // leaves them unfiltered. See `scimProjectionRowScope` above. ...scimProjectionRowScope(), + // [#20027] Repeated here for the same reason: the credential tables, no row. + ...privateCredentialRowScope(), ], }), diff --git a/packages/plugins/plugin-security/src/objects/rbac-objects.test.ts b/packages/plugins/plugin-security/src/objects/rbac-objects.test.ts index 74e78e24395..39d230d5df2 100644 --- a/packages/plugins/plugin-security/src/objects/rbac-objects.test.ts +++ b/packages/plugins/plugin-security/src/objects/rbac-objects.test.ts @@ -129,6 +129,13 @@ describe('default permission sets', () => { // deliberate, not a duplicate to be collapsed. 'sys_invitation_issuer', 'sys_invitation_self', + // [#20027] The credential tables' row scope (`id == null`, no row) — + // re-judged here, not a drift. `sys_jwks` and `sys_verification` declare + // `access: private` and "DENY for non-admins", but the managed-object + // blanket's EXPLICIT read entry opened them to every set holding it. + // Behaviour is pinned end to end in `private-credential-row-scope.test.ts`; + // this list only records presence (its twin is last in the list). + 'sys_jwks_none', 'sys_notification_receipt_self', 'sys_oauth_access_token_self', 'sys_oauth_application_self', @@ -154,6 +161,7 @@ describe('default permission sets', () => { 'sys_user_org_members', 'sys_user_preference_self', 'sys_user_self', + 'sys_verification_none', ]); expect(policyNames).not.toContain('tenant_isolation'); const orgSelf = (member.rowLevelSecurity ?? []).find((p) => p.name === 'sys_organization_self')!; From 4c82dfa32f7d6dba4a5182d70b8e2c23647d9a88 Mon Sep 17 00:00:00 2001 From: Claude Date: Thu, 24 Sep 2026 20:54:41 +0000 Subject: [PATCH 3/3] chore(changeset): plugin-security minor, breaking narrowing on the private credential tables Claude-Session: https://claude.ai/code/session_01Evb5jFDZGKQE9KG4jbMfMF Co-authored-by: Claude --- .../20027-private-credential-objects.md | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 .changeset/20027-private-credential-objects.md diff --git a/.changeset/20027-private-credential-objects.md b/.changeset/20027-private-credential-objects.md new file mode 100644 index 00000000000..1acd0ba9171 --- /dev/null +++ b/.changeset/20027-private-credential-objects.md @@ -0,0 +1,40 @@ +--- +'@objectstack/plugin-security': minor +--- + +fix(plugin-security)!: no shipped permission set below platform admin reads a row of `sys_verification` or `sys_jwks` — the credential rows those objects declare private (#20027) + +Clause-②: no (narrowing) + +**BREAKING** — shipped as `minor` under the launch-window convention +(`check-changeset-no-major` refuses `major` until GA; breaking-ness is carried by +this banner and the ADR-0087 disposition below, never by the level). + +`sys_verification` (one-time verification and password-reset tokens) and +`sys_jwks` (JWT signing keys) declare `access: { default: 'private' }`, and the +shipped permission sets documented them as denied to every principal below +platform admin. The sets did not hold that: the read they grant on every +better-auth-managed object is an explicit per-object entry, which the `private` +posture does not govern, and neither object had a row policy behind it. + +**What a principal can no longer read.** Every shipped set that grants that read +and carries row-level security — `member_default`, `viewer_readonly`, +`organization_admin` and its wall-less variant `organization_admin_no_bypass` — +now declares a row policy that admits no row on each of the two objects +(`sys_verification_none`, `sys_jwks_none`). That covers the rows the objects +declare private, including a caller's own verification row. An MCP agent acting +for a user is bounded by that user's sets and reads the same. `admin_full_access` +is unchanged and still reads every row. + +**Remedy.** None is expected to be needed: no shipped product surface reads these +tables under a user context. A deployment that genuinely needs a principal below +platform admin to inspect them grants that in a permission set of its own, with +a row-level-security policy that names the rows it may see. + +Unchanged: better-auth's own verification, password-reset and token-signing flows +(they read and write through its adapter under system context, which no row +policy reaches), the owner-scoped reads of the other `private` identity objects +(`sys_device_code`, `sys_oauth_access_token`, `sys_oauth_refresh_token`), and +every other managed object. + +