From 4ace9167c3dacd3b9ffd2cbc9a3a22ad55e2c1c6 Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 18 Aug 2026 10:42:24 +0000 Subject: [PATCH] tests(access-security): pin the FLS read side and the persona x CRUD cell matrix (#9481) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit QA run #9401 scored `access-security.fls-mask-and-strip` and `access-security.crud-permission-matrix` green on pins that reach only a subset of each item's acceptance clauses. Two new dogfood pins close the named gaps, and both items' `automated.ref` are re-scoped so the next Tier-1 run scores them honestly — including what stays manual. FLS read side. A permission-set `readable: false` STRIPS the field: the key is deleted, not nulled and not replaced by a placeholder. The pin asserts key-absence on the by-id record, on every listed row and on an explicit `select` that names the field, always against the entitled caller's contrast on the same row and request; it also pins the filter and sort oracle refusals (403 PERMISSION_DENIED naming the field) and the read deny's write complement. The scratch `readable: false` set is authored at runtime, exactly as the item's own steps prescribe — stock showcase metadata is untouched. Persona x CRUD cells. All 25 `showcase_*` rows of the showcase's access-matrix.json are driven over all four verbs by one fresh member per permission set: 100 cells, 50 effective-allow and 50 effective-deny, each judged against the BASELINE-UNIONED expectation (ADR-0090 D5), whose 9 baseline-only grants are asserted as load-bearing in their own right. An admin payload control runs first, so a persona 403 cannot be a 400 in disguise. Both refs now state what they do NOT reach: the #8993 maskingRule path has no fixture anywhere in this repo, the UI halves have no pin, the 6 sys_* delegate rows are not plain cells, and the guest-anchor intake asymmetry is not observable on a member persona at all. Co-Authored-By: Claude --- .../areas/access-security.json | 28 +- ...owcase-crud-persona-matrix.dogfood.test.ts | 479 ++++++++++++++++++ ...owcase-fls-read-mask-strip.dogfood.test.ts | 292 +++++++++++ 3 files changed, 792 insertions(+), 7 deletions(-) create mode 100644 packages/qa/dogfood/test/showcase-crud-persona-matrix.dogfood.test.ts create mode 100644 packages/qa/dogfood/test/showcase-fls-read-mask-strip.dogfood.test.ts diff --git a/docs/qa/platform-checklist/areas/access-security.json b/docs/qa/platform-checklist/areas/access-security.json index 0594ac064f0..aa9dd9774d2 100644 --- a/docs/qa/platform-checklist/areas/access-security.json +++ b/docs/qa/platform-checklist/areas/access-security.json @@ -385,7 +385,7 @@ "title": "CRUD × permission-set matrix: every access-matrix.json row holds — allowed verbs succeed, withheld verbs 403, VAMA bounded", "since": "v15", "status": "active", - "revision": 2, + "revision": 3, "priority": "P0", "surface": "api", "personas": [ @@ -400,7 +400,8 @@ "seeded permission sets showcase_contributor/manager/executive/auditor/ops/member_default/guest_portal/field_ops_delegate (security bootstrap)" ], "knownGaps": [ - "every authenticated member ALSO holds the everyone baseline showcase_member_default additively (ADR-0090 D5) — the effective expectation per cell is the UNION of the tested set's row and the baseline's row for that object; compute the union before judging a cell, or a baseline-granted read will look like a matrix violation" + "every authenticated member ALSO holds the everyone baseline showcase_member_default additively (ADR-0090 D5) — the effective expectation per cell is the UNION of the tested set's row and the baseline's row for that object; compute the union before judging a cell, or a baseline-granted read will look like a matrix violation. Measured on the committed table: 9 of the 100 showcase_* cells are granted ONLY by the baseline (showcase_auditor and showcase_executive can CREATE an inquiry and create+edit a private note; guest_portal can READ an inquiry; showcase_manager and showcase_ops can CREATE an inquiry). showcase-crud-persona-matrix.dogfood.test.ts computes the union and asserts those 9 as allowed.", + "access-matrix.json is the APP's declared matrix; the platform's own baseline permission sets are additionally in force and grant some sys_* surface the app matrix never mentions (measured: a plain member reads /data/sys_user 200, self-scoped). So the absence of a row is NOT a prediction of denial on sys_* objects, and the automated sweep judges the showcase_* rows only — see automated.ref." ] }, "steps": [ @@ -472,7 +473,7 @@ ], "automated": { "kind": "verify", - "ref": "packages/verify/src/verify.ts (runCrudVerification) + packages/verify/src/rls.ts (runRlsProofs) — `objectstack verify --rls` for the RLS half (the flag is load-bearing: bare verify prints no RLS section); persona-grained cells remain manual" + "ref": "packages/verify/src/verify.ts (runCrudVerification) + packages/verify/src/rls.ts (runRlsProofs) — `objectstack verify --rls` for the OBJECT-level CRUD and cross-owner RLS half (the flag is load-bearing: bare verify prints no RLS section) + packages/qa/dogfood/test/showcase-crud-persona-matrix.dogfood.test.ts for the PERSONA-grained cells: all 25 showcase_* rows of access-matrix.json driven over all four verbs by one fresh member per permission set — 100 cells, 50 effective-allow and 50 effective-deny, each judged against the BASELINE-UNIONED expectation (row OR showcase_member_default row, ADR-0090 D5), which is also asserted as load-bearing on the 9 cells whose only grant is the baseline. Reaches clauses 0, 1, 2, 3, 4 and 6 for those rows; every denial is checked to be 403 PERMISSION_DENIED specifically, every allow to persist, and an admin payload control runs first so a persona 403 cannot be a 400 in disguise. STILL MANUAL: (a) the 6 showcase_field_ops_delegate x sys_* rows — the platform's OWN baseline sets grant part of that surface independently of the app matrix (measured: a member holding nothing but the app baseline reads /data/sys_user 200, self-scoped, though the matrix lists sys_user read only for the delegate), and the delegate's sys_user_position writes are decided by the ADR-0090 D12 adminScope subtree gate that showcase-permission-zoo.dogfood.test.ts already pins on both sides — a raw cell verdict there would be false in one direction or the other; (b) clause 5's guest-anchor intake asymmetry (guest_portal create-without-read) — NOT observable on a member persona at all, because the everyone baseline grants read on showcase_inquiry and capability is a union, so the member-persona expectation is READ ALLOWED; the asymmetry lives on the unauthenticated guest anchor, a different admission lane." }, "traps": [ "wrong-persona", @@ -491,7 +492,13 @@ "change": "new — CRUD × permission matrix grounded in access-matrix.json, per the deep-test contract", "ref": "claude/platform-test-checklist-ocwugl" }, - { "revision": 2, "date": "2026-08-18", "change": "named the --rls flag in automated.ref. The ref pointed at runRlsProofs while spelling the invocation as bare `objectstack verify`, which never runs the proofs (#9334)", "ref": "#9386" } + { "revision": 2, "date": "2026-08-18", "change": "named the --rls flag in automated.ref. The ref pointed at runRlsProofs while spelling the invocation as bare `objectstack verify`, which never runs the proofs (#9334)", "ref": "#9386" }, + { + "revision": 3, + "date": "2026-08-18", + "change": "persona-grained cells pinned (QA run #9401 scored this item partial: verify proves object-level CRUD + cross-owner RLS, never the persona x cell matrix). automated.ref now names the dogfood sweep over the 25 showcase_* rows and states precisely what stays manual — the 6 sys_* delegate rows, whose verdicts are not plain cells, and clause 5's guest-anchor asymmetry, which a member persona structurally cannot observe. knownGaps records the measured baseline-union flip count and the fact that a missing row is not a prediction of denial on sys_* objects", + "ref": "#9481" + } ] }, { @@ -614,7 +621,7 @@ "title": "Field-level security: editable:false strips/denies writes API-side and renders read-only in the UI; masked-read half needs an authored readable:false grant", "since": "v15", "status": "active", - "revision": 1, + "revision": 2, "priority": "P1", "surface": "mixed", "personas": [ @@ -628,7 +635,8 @@ "a seeded showcase_project row with a non-null budget" ], "knownGaps": [ - "stock showcase authors NO readable:false FLS grant, so the read-MASKING half (field absent/nulled on GET, plugin-security/src/field-masker.ts) has no stock fixture; to run it, author a scratch permission set carrying readable:false on a showcase_project field and grant it to a fresh member — if the run cannot author one through a supported surface, record that half blocked(fixture) rather than ticking on the write half alone" + "[API half CLOSED by #9481; the seed gap itself stays open] stock showcase authors NO readable:false FLS grant, so the read-MASKING half (field absent/nulled on GET, plugin-security/src/field-masker.ts) has no stock fixture; to run it, author a scratch permission set carrying readable:false on a showcase_project field and grant it to a fresh member — if the run cannot author one through a supported surface, record that half blocked(fixture) rather than ticking on the write half alone. What changed: showcase-fls-read-mask-strip.dogfood.test.ts does exactly that at runtime, so the SERVER half no longer waits on the seed. The UI half still does — a console render cannot be driven off a permission set that exists only inside a test's stack — and #9308 fixture 4 is the card that would land the stock grant.", + "MASKED and STRIPPED are two different mechanisms with two different wire shapes, and this item's clause 4 (\"absent or nulled\") predates the measurement. Measured answer: a permission-set readable:false DELETES the key (strip); the #8993 `maskingRule` path REPLACES the value and leaves the key present (mask). A test that only checks \"I did not get the real value\" passes for both and pins neither, so the pin asserts key-absence. The masked half has no fixture at all — do not tick it off the strip pin." ] }, "steps": [ @@ -682,7 +690,7 @@ ], "automated": { "kind": "dogfood", - "ref": "packages/qa/dogfood/test/showcase-permission-zoo.dogfood.test.ts (FLS budget case — write half only)" + "ref": "packages/qa/dogfood/test/showcase-permission-zoo.dogfood.test.ts (FLS budget case — WRITE half: the showcase's own readable:true/editable:false grant) + packages/qa/dogfood/test/showcase-fls-read-mask-strip.dogfood.test.ts (READ half, asserted server-side: a readable:false field is STRIPPED — the KEY is absent from the by-id record, from every listed row and from an explicit `select` that names it, and it is neither nulled nor replaced by a placeholder — while the entitled caller still receives it on the same row and request; filtering or sorting on the stripped field is refused 403 PERMISSION_DENIED naming the field, and the entitled caller can still do both; the read-deny's write complement is refused and the stored value is unchanged. The scratch readable:false set is authored at runtime, per this item's own steps). STILL MANUAL: (a) clause 3 and the UI half of clause 4 — the console render of the FLS state — have no pin; (b) the partial-MASKING path (#8993 `maskingRule`: key PRESENT, value replaced by a mask image) is unpinned and has no fixture anywhere in this repo — NO object declares a maskingRule, so the masked-value wire shape cannot be asserted on the stock showcase. The read pin covers the STRIP mechanism only; do not read it as covering the masked one." }, "source": [ "examples/app-showcase/src/security/permission-sets.ts (contributor FLS)", @@ -695,6 +703,12 @@ "date": "2026-08-07", "change": "new — FLS item per the deep-test contract; read-mask half carries an explicit fixture gap instead of an ungrounded step", "ref": "claude/platform-test-checklist-ocwugl" + }, + { + "revision": 2, + "date": "2026-08-18", + "change": "READ half pinned (QA run #9401 scored this item partial on a write-only pin). automated.ref now names the read pin and states what it does NOT reach: the UI render, and the #8993 maskingRule path, which has no fixture in this repo. knownGaps records the measured mask-vs-strip distinction — readable:false DELETES the key, it does not null it — so the next runner does not tick the masked half off the strip pin", + "ref": "#9481" } ] }, diff --git a/packages/qa/dogfood/test/showcase-crud-persona-matrix.dogfood.test.ts b/packages/qa/dogfood/test/showcase-crud-persona-matrix.dogfood.test.ts new file mode 100644 index 00000000000..722c5fb5a37 --- /dev/null +++ b/packages/qa/dogfood/test/showcase-crud-persona-matrix.dogfood.test.ts @@ -0,0 +1,479 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// `access-security.crud-permission-matrix` — the PERSONA × CRUD-CELL half (#9481). +// +// `objectstack verify` proves object-level CRUD and cross-owner RLS, and the +// item's `automated.ref` says outright that the persona-grained cells remain +// manual. This file drives them: for every `showcase_*` row of the showcase's +// own `access-matrix.json`, one fresh member holding exactly that permission set +// runs all four verbs over the real HTTP surface, and each cell is judged +// against the table. +// +// ── The union, which is the whole trap ─────────────────────────────────────── +// +// `access-matrix.json` lists what each set grants ON ITS OWN. Every authenticated +// member ALSO holds the app's everyone-baseline `showcase_member_default` +// additively (ADR-0090 D5), and capability is a UNION — there are no subtraction +// sets. So the expectation for a cell is +// +// effective(set, object, verb) = row(set)[verb] OR row(member_default)[verb] +// +// and judging a cell against the raw row is simply wrong: it turns 9 correctly +// ALLOWED cells into fabricated violations. `showcase_auditor` is a read-only +// compliance set that nonetheless CAN create an inquiry, because the baseline +// can. The union is computed below and the flipped cells are asserted as +// allowed, which is what pins D5's additivity end-to-end. +// +// ── Why the allow half is not decoration ───────────────────────────────────── +// +// A permission matrix that only asserts denials stays green when everything +// denies — an over-tightening regression is invisible to it. This table is +// deliberately balanced and the balance is CHECKED: `records the verdict of +// every cell` asserts the exact allow/deny split, so narrowing the sweep (or +// letting a persona silently fail to be provisioned) breaks the build instead of +// quietly shrinking what is proven. +// +// ── Why a denial here is a PERMISSION verdict and not a bad payload ────────── +// +// A 403 proves nothing if the request would have failed anyway. Before any +// persona runs, the admin creates every object FROM THE SAME PAYLOAD BUILDER +// (`the admin control`). If a required field moves in the showcase, that control +// goes red naming the object, instead of every persona's denial staying green +// for the wrong reason. +// +// ── What this file deliberately does NOT cover ─────────────────────────────── +// +// • The 6 `showcase_field_ops_delegate` × `sys_*` rows. Their verdicts are not +// plain cells: the platform's OWN baseline sets grant some of that surface +// independently of the app's matrix (measured: a member holding no app set +// beyond the baseline reads `/data/sys_user` 200 — self-scoped — while the +// matrix lists `sys_user` read only for the delegate), and the delegate's +// `sys_user_position` writes are decided by the ADR-0090 D12 adminScope +// subtree gate, which `showcase-permission-zoo.dogfood.test.ts` already pins +// on both sides. A raw cell verdict for those rows would be a false negative +// or a false positive depending on the row. They stay manual. +// • The guest-anchor intake asymmetry (`guest_portal`: create without read). +// It is NOT observable on a member persona: the everyone baseline grants read +// on `showcase_inquiry`, so the union says read — and this file asserts the +// union, because that IS what a member holding the set may do. The asymmetry +// lives on the unauthenticated guest anchor, a different admission lane. +// +// @proof: showcase-crud-persona-matrix + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { readFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import showcaseStack from '@objectstack/example-showcase'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { showcaseAppDefaultSecurity } from './showcase-security.js'; + +const SYS = { isSystem: true } as const; +const HERE = dirname(fileURLToPath(import.meta.url)); +// packages/qa/dogfood/test → repo root. +const REPO_ROOT = join(HERE, '../../../..'); +const MATRIX_PATH = join(REPO_ROOT, 'examples/app-showcase/access-matrix.json'); + +type Verb = 'create' | 'read' | 'edit' | 'delete'; +const VERBS: Verb[] = ['create', 'read', 'edit', 'delete']; + +interface MatrixRow { + permissionSet: string; + object: string; + create: boolean; + read: boolean; + edit: boolean; + delete: boolean; + viewAllRecords: boolean; + modifyAllRecords: boolean; +} + +const matrix = JSON.parse(readFileSync(MATRIX_PATH, 'utf8')) as { version: number; entries: MatrixRow[] }; +/** The app's everyone-baseline rows, keyed by object — the union's other half. */ +const BASELINE_SET = 'showcase_member_default'; +const baselineByObject = new Map( + matrix.entries.filter((e) => e.permissionSet === BASELINE_SET).map((e) => [e.object, e]), +); +/** Business-object rows only — see the header for why the `sys_*` rows are out. */ +const ROWS = matrix.entries.filter((e) => e.object.startsWith('showcase_')); + +const effective = (row: MatrixRow, verb: Verb): boolean => + Boolean(row[verb]) || Boolean(baselineByObject.get(row.object)?.[verb]); + +/** The `sys_*` rows this file does not judge — named so the exclusion is visible. */ +const UNJUDGED_ROWS = matrix.entries.filter((e) => !e.object.startsWith('showcase_')); + +/** Marker field per object: what a created row is findable by afterwards. */ +const MARKER: Record = { + showcase_account: 'name', + showcase_announcement: 'title', + showcase_contact: 'name', + showcase_inquiry: 'name', + showcase_invoice: 'name', + showcase_invoice_line: 'description', + showcase_private_note: 'title', + showcase_product: 'name', + showcase_project: 'name', + showcase_task: 'title', +}; + +interface PayloadCtx { + mark: string; + email: string; + accountId: string; + productId: string; + projectId: string; + /** The invoice a line should hang off — the caller's OWN where they have one. */ + invoiceId: string; +} + +/** + * Minimal VALID create payloads. Required fields are named explicitly rather + * than derived, so a showcase change that adds one fails the admin control with + * the object's name instead of degrading a persona's cell into a silent 400. + * + * `owner` is set to the acting persona on the two objects that carry an owner + * TEXT column, because `showcase_contributor`'s RLS selects invoices by + * `owner == current_user.email`: a row created without it would be invisible to + * its own creator, and the contributor's EDIT cell would fail for a record-level + * reason while looking like a CRUD denial. + */ +const PAYLOAD: Record Record> = { + showcase_account: (c) => ({ name: c.mark, status: 'prospect' }), + showcase_announcement: (c) => ({ title: c.mark }), + showcase_contact: (c) => ({ name: c.mark, email: `contact-${Date.now()}@probe.test` }), + showcase_inquiry: (c) => ({ name: c.mark, email: `inq-${Date.now()}@probe.test`, message: 'matrix probe' }), + showcase_invoice: (c) => ({ name: c.mark, account: c.accountId, status: 'draft', owner: c.email }), + showcase_invoice_line: (c) => ({ invoice: c.invoiceId, product: c.productId, quantity: 1, description: c.mark }), + showcase_private_note: (c) => ({ title: c.mark }), + showcase_product: (c) => ({ name: c.mark, sku: `SKU-${Date.now()}` }), + showcase_project: (c) => ({ name: c.mark, account: c.accountId, status: 'planned', owner: c.email }), + showcase_task: (c) => ({ title: c.mark, project: c.projectId, status: 'todo' }), +}; + +/** Field patched on the EDIT probe — always an unrestricted one. */ +const EDIT_FIELD: Record = { ...MARKER }; + +const OBJECTS = [...new Set(ROWS.map((r) => r.object))].sort(); +const SETS = [...new Set(ROWS.map((r) => r.permissionSet))].sort(); + +const idOf = (b: any) => b?.id ?? b?.record?.id ?? b?.data?.id; +const rowsOf = (b: any) => b?.records ?? b?.data ?? (Array.isArray(b) ? b : []); + +interface Cell { + set: string; + object: string; + verb: Verb; + expected: 'allow' | 'deny'; + /** true when the raw row says false and only the baseline union allows it. */ + baselineFlip: boolean; + status: number; + code?: string; +} +const VERDICTS: Cell[] = []; + +describe('showcase: persona × CRUD-cell matrix (#9481)', () => { + let stack: VerifyStack; + let ql: any; + let adminTok: string; + /** persona token / email / own-row ids, keyed by permission set name. */ + const persona = new Map }>(); + /** Admin-created foreign probe row per object. */ + const foreign = new Map(); + const seed = { accountId: '', productId: '', projectId: '', invoiceId: '' }; + + const ctxFor = (email: string, mark: string, invoiceId?: string): PayloadCtx => ({ + mark, + email, + accountId: seed.accountId, + productId: seed.productId, + projectId: seed.projectId, + invoiceId: invoiceId || seed.invoiceId, + }); + + const bodyOf = async (r: Response) => { + try { + return (await r.json()) as any; + } catch { + return undefined; + } + }; + + beforeAll(async () => { + stack = await bootStack(showcaseStack, { security: showcaseAppDefaultSecurity() }); + adminTok = await stack.signIn(); + ql = await stack.kernel.getServiceAsync('objectql'); + + const firstId = async (object: string) => + String((await ql.find(object, { limit: 1, context: SYS }))?.[0]?.id ?? ''); + seed.accountId = await firstId('showcase_account'); + seed.productId = await firstId('showcase_product'); + seed.projectId = await firstId('showcase_project'); + seed.invoiceId = await firstId('showcase_invoice'); + expect( + seed.accountId && seed.productId && seed.projectId && seed.invoiceId, + 'the showcase seed provides the lookup parents every payload needs', + ).toBeTruthy(); + + // Personas. `showcase_member_default` is the baseline itself — that persona + // is a plain sign-up holding no extra grant, which is exactly the shape the + // matrix row describes. + for (const set of SETS) { + const email = `crudmx-${set.replace(/^showcase_/, '')}@verify.test`; + const token = await stack.signUp(email); + if (set !== BASELINE_SET) { + const ps = await ql.findOne('sys_permission_set', { where: { name: set }, context: SYS }); + expect(ps?.id, `permission set ${set} seeded by the security bootstrap`).toBeTruthy(); + const uid = (await ql.findOne('sys_user', { where: { email }, context: SYS }))?.id; + expect(uid, `persona ${email} provisioned`).toBeTruthy(); + await ql.insert( + 'sys_user_permission_set', + { user_id: uid, permission_set_id: ps.id }, + { context: SYS }, + ); + } + persona.set(set, { token, email, own: new Map() }); + } + + // Admin FOREIGN probe rows — the edit/delete target for personas that may + // not create, and simultaneously the payload control (see header). + for (const object of OBJECTS) { + const mark = `MX-admin-${object}`; + const r = await stack.apiAs(adminTok, 'POST', `/data/${object}`, PAYLOAD[object](ctxFor('admin@objectos.ai', mark))); + const body = await bodyOf(r); + expect( + r.status, + `admin control: the ${object} payload is VALID (a persona 403 must be a permission verdict, not a 400 in disguise) — got ${JSON.stringify(body)}`, + ).toBeLessThan(300); + foreign.set(object, String(idOf(body))); + expect(foreign.get(object), `admin probe row id for ${object}`).toBeTruthy(); + } + }, 300_000); + + afterAll(async () => { + await stack?.stop?.(); + }); + + // ── The sweep ──────────────────────────────────────────────────────────── + for (const row of ROWS) { + const label = `${row.permissionSet} × ${row.object}`; + it(`${label}: all four verbs answer the matrix (baseline-unioned)`, async () => { + const p = persona.get(row.permissionSet)!; + const record = (verb: Verb, status: number, code?: string) => { + VERDICTS.push({ + set: row.permissionSet, + object: row.object, + verb, + expected: effective(row, verb) ? 'allow' : 'deny', + baselineFlip: !row[verb] && effective(row, verb), + status, + code, + }); + }; + const why = (verb: Verb) => + `${label} ${verb}: row=${row[verb]} baseline=${Boolean(baselineByObject.get(row.object)?.[verb])} ⇒ effective=${effective(row, verb)}`; + + // ── CREATE ────────────────────────────────────────────────────────── + const mark = `MX-${row.permissionSet}-${row.object}`; + const createBody = PAYLOAD[row.object](ctxFor(p.email, mark, p.own.get('showcase_invoice'))); + const created = await stack.apiAs(p.token, 'POST', `/data/${row.object}`, createBody); + const createdJson = await bodyOf(created); + record('create', created.status, createdJson?.code); + if (effective(row, 'create')) { + expect(created.status, `${why('create')} — got ${JSON.stringify(createdJson)}`).toBeLessThan(300); + const newId = String(idOf(createdJson)); + expect(newId, `${label}: the allowed create returns an id`).toBeTruthy(); + p.own.set(row.object, newId); + // The effect persists (clause 0's value oracle, not the status alone). + const stored = await ql.findOne(row.object, { where: { id: newId }, context: SYS }); + expect(stored, `${label}: the created row is really there`).toBeTruthy(); + } else { + expect(created.status, why('create')).toBe(403); + expect(createdJson?.code, `${label}: the ledgered denial code`).toBe('PERMISSION_DENIED'); + // Clause 2 — a denied CREATE leaves NO row behind. + const left = await ql.find(row.object, { + where: { [MARKER[row.object]]: mark }, + context: SYS, + }); + expect(left?.length ?? 0, `${label}: the denied create persisted nothing`).toBe(0); + } + + // ── READ (list) ───────────────────────────────────────────────────── + const listed = await stack.apiAs(p.token, 'GET', `/data/${row.object}`); + const listedJson = await bodyOf(listed); + record('read', listed.status, listedJson?.code); + if (effective(row, 'read')) { + expect(listed.status, `${why('read')} — got ${JSON.stringify(listedJson)}`).toBe(200); + expect(Array.isArray(rowsOf(listedJson)), `${label}: a readable list answers with rows`).toBe(true); + } else { + expect(listed.status, why('read')).toBe(403); + expect(listedJson?.code).toBe('PERMISSION_DENIED'); + } + + // ── EDIT ──────────────────────────────────────────────────────────── + // Own row where the persona could make one; the admin's foreign row + // otherwise. Either way the target EXISTS, so a refusal cannot be a + // 404 in disguise. + const editTarget = p.own.get(row.object) ?? foreign.get(row.object)!; + const editField = EDIT_FIELD[row.object]; + const editValue = `${mark}-edited`; + const edited = await stack.apiAs(p.token, 'PATCH', `/data/${row.object}/${editTarget}`, { + [editField]: editValue, + }); + const editedJson = await bodyOf(edited); + record('edit', edited.status, editedJson?.code); + if (effective(row, 'edit')) { + expect(edited.status, `${why('edit')} — got ${JSON.stringify(editedJson)}`).toBeLessThan(300); + const after = await ql.findOne(row.object, { where: { id: editTarget }, context: SYS }); + expect(after?.[editField], `${label}: the allowed edit persisted`).toBe(editValue); + } else { + expect(edited.status, why('edit')).toBe(403); + expect(editedJson?.code).toBe('PERMISSION_DENIED'); + const after = await ql.findOne(row.object, { where: { id: editTarget }, context: SYS }); + expect(after?.[editField], `${label}: the denied edit changed nothing`).not.toBe(editValue); + } + + // ── DELETE ────────────────────────────────────────────────────────── + // An allowed delete gets a throwaway row of its own so the sweep does not + // destroy a target a later assertion still needs. + let deleteTarget = p.own.get(row.object) ?? foreign.get(row.object)!; + if (effective(row, 'delete') && effective(row, 'create')) { + const throwaway = await stack.apiAs( + p.token, + 'POST', + `/data/${row.object}`, + PAYLOAD[row.object](ctxFor(p.email, `${mark}-del`, p.own.get('showcase_invoice'))), + ); + const tid = idOf(await bodyOf(throwaway)); + if (tid) deleteTarget = String(tid); + } + const deleted = await stack.apiAs(p.token, 'DELETE', `/data/${row.object}/${deleteTarget}`); + const deletedJson = await bodyOf(deleted); + record('delete', deleted.status, deletedJson?.code); + if (effective(row, 'delete')) { + expect(deleted.status, `${why('delete')} — got ${JSON.stringify(deletedJson)}`).toBeLessThan(300); + const gone = await ql.findOne(row.object, { where: { id: deleteTarget }, context: SYS }); + expect(gone ?? null, `${label}: the deleted row is gone`).toBeNull(); + } else { + expect(deleted.status, why('delete')).toBe(403); + expect(deletedJson?.code).toBe('PERMISSION_DENIED'); + const still = await ql.findOne(row.object, { where: { id: deleteTarget }, context: SYS }); + expect(still, `${label}: the denied delete left the row standing`).toBeTruthy(); + } + }, 180_000); + } + + // ── VAMA, both sides (clause 3) ────────────────────────────────────────── + it('viewAllRecords: the auditor reads a FOREIGN private note by id AND in lists; a plain member gets it neither way', async () => { + const auditor = persona.get('showcase_auditor')!; + const plain = persona.get(BASELINE_SET)!; + // The plain member's OWN note is foreign to the auditor and vice versa. + const mark = `MX-vama-${Date.now()}`; + const mine = await stack.apiAs(plain.token, 'POST', '/data/showcase_private_note', { title: mark }); + const noteId = String(idOf(await bodyOf(mine))); + expect(noteId, 'the plain member owns a note').toBeTruthy(); + + const byId = await stack.apiAs(auditor.token, 'GET', `/data/showcase_private_note/${noteId}`); + expect(byId.status, 'viewAllRecords reaches the foreign row by id').toBe(200); + + const listed = await stack.apiAs(auditor.token, 'GET', '/data/showcase_private_note'); + const titles = rowsOf(await bodyOf(listed)).map((r: any) => r.title); + expect(titles, 'and in the LIST — the bypass is not by-id only').toContain(mark); + + // The negative persona: same row, no bit. + const other = persona.get('showcase_contributor')!; + const otherById = await stack.apiAs(other.token, 'GET', `/data/showcase_private_note/${noteId}`); + expect(otherById.status, 'a persona without the bit cannot read it by id').not.toBe(200); + const otherList = await stack.apiAs(other.token, 'GET', '/data/showcase_private_note'); + const otherTitles = rowsOf(await bodyOf(otherList)).map((r: any) => r.title); + expect(otherTitles, 'nor see it in a list').not.toContain(mark); + }, 120_000); + + // ── MAMA, both sides (clause 4) ────────────────────────────────────────── + it('modifyAllRecords: ops PATCHes a FOREIGN announcement; the same PATCH by a plain member is denied and the row is unchanged', async () => { + const ops = persona.get('showcase_ops')!; + const plain = persona.get(BASELINE_SET)!; + const target = foreign.get('showcase_announcement')!; // admin-owned + + const opsValue = `MX-mama-ops-${Date.now()}`; + const opsPatch = await stack.apiAs(ops.token, 'PATCH', `/data/showcase_announcement/${target}`, { + title: opsValue, + }); + expect(opsPatch.status, 'modifyAllRecords grants the foreign write').toBeLessThan(300); + const afterOps = await ql.findOne('showcase_announcement', { where: { id: target }, context: SYS }); + expect(afterOps?.title, 'and it persisted').toBe(opsValue); + + const plainValue = `MX-mama-plain-${Date.now()}`; + const plainPatch = await stack.apiAs(plain.token, 'PATCH', `/data/showcase_announcement/${target}`, { + title: plainValue, + }); + expect(plainPatch.status, 'the same write without the bit is refused').toBe(403); + expect((await bodyOf(plainPatch))?.code).toBe('PERMISSION_DENIED'); + const afterPlain = await ql.findOne('showcase_announcement', { where: { id: target }, context: SYS }); + expect(afterPlain?.title, 'and the row is untouched').toBe(opsValue); + }, 120_000); + + // ── The verdict table itself (clause 6) ────────────────────────────────── + // + // This is the anti-vacuity check. Without it the sweep could shrink — a + // persona failing to be provisioned, a row quietly filtered out — and every + // remaining assertion would still pass. + it('records the verdict of every cell, with both halves non-trivially populated', () => { + expect(VERDICTS.length, 'one verdict per (set × object × verb)').toBe(ROWS.length * VERBS.length); + + const allow = VERDICTS.filter((c) => c.expected === 'allow'); + const deny = VERDICTS.filter((c) => c.expected === 'deny'); + // A matrix in which everything denies proves nothing about over-tightening, + // and one in which everything allows proves nothing about enforcement. + expect(allow.length, 'the ALLOW half is what catches an over-tightening regression').toBe(50); + expect(deny.length, 'the DENY half is what catches a widening regression').toBe(50); + + // Every set and every object of the business-object matrix was really driven. + expect([...new Set(VERDICTS.map((c) => c.set))].sort()).toEqual(SETS); + expect([...new Set(VERDICTS.map((c) => c.object))].sort()).toEqual(OBJECTS); + + // Denials are the ledgered code, never an incidental 404/400. + for (const cell of deny) { + expect(cell.status, `${cell.set} × ${cell.object} ${cell.verb}`).toBe(403); + expect(cell.code, `${cell.set} × ${cell.object} ${cell.verb}`).toBe('PERMISSION_DENIED'); + } + for (const cell of allow) { + expect(cell.status, `${cell.set} × ${cell.object} ${cell.verb}`).toBeLessThan(300); + } + }); + + // ── ADR-0090 D5: the additive baseline, pinned as such ─────────────────── + it('the everyone-baseline union is load-bearing: cells the tested set denies are ALLOWED through it', () => { + const flips = VERDICTS.filter((c) => c.baselineFlip); + expect( + flips.length, + 'the showcase really does contain cells whose only grant is the baseline — if this hits 0 the union has stopped mattering and the sweep silently stopped testing it', + ).toBe(9); + for (const cell of flips) { + expect(cell.expected, `${cell.set} × ${cell.object} ${cell.verb} is a baseline flip`).toBe('allow'); + expect( + cell.status, + `${cell.set} × ${cell.object} ${cell.verb}: the baseline grant really answers 2xx`, + ).toBeLessThan(300); + } + }); + + // ── The exclusion is declared, not silent ──────────────────────────────── + it('names the matrix rows this file does not judge (the sys_* delegate surface)', () => { + expect(UNJUDGED_ROWS.map((r) => r.object).sort()).toEqual([ + 'sys_business_unit', + 'sys_business_unit_member', + 'sys_permission_set', + 'sys_position', + 'sys_user', + 'sys_user_position', + ]); + expect( + [...new Set(UNJUDGED_ROWS.map((r) => r.permissionSet))], + 'they are all one set — if an app set starts granting sys_* surface, this list moves and the exclusion must be re-argued', + ).toEqual(['showcase_field_ops_delegate']); + expect(ROWS.length + UNJUDGED_ROWS.length, 'the two partitions cover the whole matrix').toBe( + matrix.entries.length, + ); + }); +}); diff --git a/packages/qa/dogfood/test/showcase-fls-read-mask-strip.dogfood.test.ts b/packages/qa/dogfood/test/showcase-fls-read-mask-strip.dogfood.test.ts new file mode 100644 index 00000000000..9ce0ac04149 --- /dev/null +++ b/packages/qa/dogfood/test/showcase-fls-read-mask-strip.dogfood.test.ts @@ -0,0 +1,292 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// FLS — the READ side of `access-security.fls-mask-and-strip` (#9481). +// +// The item's existing pin (`showcase-permission-zoo.dogfood.test.ts`, FLS budget +// case) covers the WRITE half only, and its `automated.ref` says so. This file +// is the read half: what an UNENTITLED persona actually receives on the wire. +// +// ── MASKED vs STRIPPED: two different mechanisms, two different wire shapes ── +// +// The platform has TWO ways a field can fail to reach a caller, and they are not +// interchangeable. `plugin-security/src/field-masker.ts` implements both: +// +// STRIPPED — a permission set marks the field `readable: false`. `maskRecord` +// DELETES the key. The field is ABSENT from the response object: not null, +// not empty string, not a placeholder. This is the mechanism this checklist +// item is about, and the one asserted below. +// +// MASKED — the FIELD declares a `maskingRule` (#8993) the caller has not +// unmasked. `maskRecord` REPLACES the value (`138****5678`). The key is +// PRESENT and its value is a mask image. +// +// A test that only asserts "I did not get the real value" passes for BOTH and +// pins NEITHER. So the assertions below are about the KEY, not just the value: +// `'budget' in record` must be false. If the strip ever degrades into a null — +// or into a masking-rule placeholder — the shape changes and this goes red, +// which a `toBeUndefined()`-style assertion would not catch (`in` distinguishes +// an absent key from a present-but-undefined one; `record.budget === undefined` +// does not). +// +// ⚠️ Scope, stated so nobody reads more into this file than it proves: the +// MASKED half is NOT pinned here and cannot be, on the stock showcase. No object +// anywhere in this repo declares a `maskingRule` — the showcase declares none, +// so there is no fixture whose masked value could be asserted, and inventing one +// would change what the stock showcase means. The masked half stays manual; see +// the item's re-scoped `automated.ref`. +// +// ── The fixture, and why it is authored at runtime ─────────────────────────── +// +// Stock showcase authors NO `readable: false` FLS grant — its only `fields` +// block is `showcase_contributor`'s three `readable: true, editable: false` +// entries. That is the item's own recorded `knownGaps`, and #9308 is the open +// card that would land such a grant in the SEED. Until it does, the item's own +// steps prescribe exactly what this file does: author a SCRATCH permission set +// carrying `readable: false` and grant it to a fresh member. The scratch set +// lives only inside this test's stack — the showcase's committed metadata is +// untouched, so what the stock app declares is unchanged. +// +// Why a private boot rather than the worker-shared showcase: this file inserts a +// `sys_permission_set` row, which the shared harness's eligibility rules exclude +// outright (no permission-set metadata edits — see `shared-showcase.ts`). +// +// ── One thing measured here and deliberately NOT asserted ──────────────────── +// +// `showcase_project.budget_remaining` is a FORMULA over `budget` and `spent`, +// and it is served to the denied member alongside `spent` — so the stripped +// value is recoverable exactly (`budget = budget_remaining + spent`, confirmed +// against the system-context row). That is filed as #9562, out of this card's +// scope, with the three readings. It is recorded here and asserted NOWHERE: an +// assertion pinning today's behaviour would turn a future fix into a red, and an +// assertion pinning the fix would be red today. The strip assertions below are +// scoped to the field the scratch set actually enumerates. +// +// ── Both sides, always ─────────────────────────────────────────────────────── +// +// Every deny below is paired with the entitled contrast on the SAME field, row +// and request. A read-side FLS suite that only asserted absence would stay green +// if the field vanished for everyone, which is an over-tightening regression, +// not a fix. +// +// @proof: showcase-fls-read-mask-strip + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import showcaseStack from '@objectstack/example-showcase'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { showcaseAppDefaultSecurity } from './showcase-security.js'; + +const SYS = { isSystem: true } as const; + +/** The field the scratch set denies READ on. */ +const DENIED = 'budget'; +/** + * A sibling currency field on the SAME object that the scratch set does NOT + * enumerate. It is the per-field discrimination control: without it, "budget is + * gone" is equally consistent with "the whole row is gone" and with "every + * currency field is gone". + */ +const KEPT = 'spent'; +const SCRATCH_SET = 'showcase_scratch_fls_read_deny'; +const MEMBER = 'fls-read-side@verify.test'; + +const recordOf = (b: any) => b?.record ?? b?.data ?? b; +const rowsOf = (b: any) => b?.records ?? b?.data ?? (Array.isArray(b) ? b : []); + +describe('showcase FLS read side: a readable:false field is STRIPPED, not masked (#9481)', () => { + let stack: VerifyStack; + let ql: any; + let adminTok: string; + let memberTok: string; + let projectId: string; + let storedBudget: number; + let storedSpent: number; + + beforeAll(async () => { + stack = await bootStack(showcaseStack, { security: showcaseAppDefaultSecurity() }); + adminTok = await stack.signIn(); + memberTok = await stack.signUp(MEMBER); + ql = await stack.kernel.getServiceAsync('objectql'); + + // The scratch grant. `object_permissions` is deliberately EMPTY: the app's + // own everyone-baseline (`showcase_member_default`) already grants read on + // `showcase_project`, so this set contributes nothing but the field deny — + // which is what makes the assertions below attributable to FLS alone. + // + // `active: true` is load-bearing: the security plugin's DB loader filters + // deactivated rows out (`isRowActive`), and an inactive set grants nothing, + // including nothing to deny — the field would come back readable and every + // assertion here would fail as if the strip were broken. + await ql.insert( + 'sys_permission_set', + { + name: SCRATCH_SET, + label: 'Scratch: FLS read deny on showcase_project.budget', + description: + 'Test-authored (#9481). Stock showcase authors no readable:false grant — see #9308.', + object_permissions: JSON.stringify({}), + // Object-QUALIFIED key. A bare `budget` key silently enforces nothing: + // the evaluator matches `.` prefixes, which is the exact + // defect the permission-zoo audit found on the write half. + field_permissions: JSON.stringify({ + [`showcase_project.${DENIED}`]: { readable: false, editable: false }, + }), + system_permissions: JSON.stringify([]), + active: true, + }, + { context: SYS }, + ); + const ps = await ql.findOne('sys_permission_set', { where: { name: SCRATCH_SET }, context: SYS }); + expect(ps?.id, 'scratch permission set authored').toBeTruthy(); + const memberId = (await ql.findOne('sys_user', { where: { email: MEMBER }, context: SYS }))?.id; + expect(memberId, 'member provisioned').toBeTruthy(); + await ql.insert( + 'sys_user_permission_set', + { user_id: memberId, permission_set_id: ps.id }, + { context: SYS }, + ); + + const projects = await ql.find('showcase_project', { where: {}, context: SYS }); + const target = (projects ?? []).find( + (p: any) => p[DENIED] != null && Number(p[DENIED]) > 0 && p[KEPT] != null, + ); + expect(target, `a seeded showcase_project with a non-null ${DENIED} and ${KEPT}`).toBeTruthy(); + projectId = target.id; + storedBudget = Number(target[DENIED]); + storedSpent = Number(target[KEPT]); + }, 180_000); + + afterAll(async () => { + await stack?.stop?.(); + }); + + // ── The strip, on the single-record read ───────────────────────────────── + it('by-id GET: the denied field is ABSENT from the record — the key is gone, not nulled', async () => { + const r = await stack.apiAs(memberTok, 'GET', `/data/showcase_project/${projectId}`); + expect(r.status, 'the ROW is still served — FLS is a field gate, not a row gate').toBe(200); + const record = recordOf(await r.json()); + + // The distinction, asserted three ways so no single weaker reading passes: + expect( + Object.prototype.hasOwnProperty.call(record, DENIED), + `${DENIED} must be absent from the response shape (stripped), not present-and-nulled`, + ).toBe(false); + expect(Object.keys(record), 'the key does not appear in the served projection').not.toContain(DENIED); + // And it is not smuggled back as a masking-rule placeholder under its own name. + expect(record[DENIED], 'no placeholder value is served in its place').toBeUndefined(); + }); + + it('the same record still carries its other fields — the strip is per-FIELD, not per-row', async () => { + const r = await stack.apiAs(memberTok, 'GET', `/data/showcase_project/${projectId}`); + const record = recordOf(await r.json()); + expect(record.name, 'an unrestricted text field is served').toBeTruthy(); + expect( + Object.prototype.hasOwnProperty.call(record, KEPT), + `${KEPT} is not enumerated by the scratch set and must survive`, + ).toBe(true); + expect(Number(record[KEPT]), 'and it carries its REAL value, not a masked one').toBe(storedSpent); + }); + + // ── The entitled contrast — the allow half ─────────────────────────────── + it('admin reads the SAME row and the field is present with its real value (both sides)', async () => { + const r = await stack.apiAs(adminTok, 'GET', `/data/showcase_project/${projectId}`); + expect(r.status).toBe(200); + const record = recordOf(await r.json()); + expect( + Object.prototype.hasOwnProperty.call(record, DENIED), + 'the entitled caller still receives the field — the lock keys on the CALLER, not the field', + ).toBe(true); + expect(Number(record[DENIED])).toBe(storedBudget); + }); + + // ── The strip on the LIST path ─────────────────────────────────────────── + it('list GET: every row is stripped for the member and intact for admin', async () => { + const m = await stack.apiAs(memberTok, 'GET', '/data/showcase_project'); + expect(m.status).toBe(200); + const memberRows = rowsOf(await m.json()); + expect(memberRows.length, 'the member sees rows at all (baseline read on a public object)').toBeGreaterThan(0); + for (const row of memberRows) { + expect( + Object.prototype.hasOwnProperty.call(row, DENIED), + `${DENIED} stripped from every listed row (id ${row.id})`, + ).toBe(false); + } + + const a = await stack.apiAs(adminTok, 'GET', '/data/showcase_project'); + const adminRows = rowsOf(await a.json()); + expect(adminRows.length, 'admin sees rows too').toBeGreaterThan(0); + expect( + adminRows.some((row: any) => Object.prototype.hasOwnProperty.call(row, DENIED)), + 'admin still receives the field in lists — the list strip is caller-keyed', + ).toBe(true); + }); + + // ── Explicitly ASKING for the field does not get it back ───────────────── + it('an explicit `select` of the denied field returns the record WITHOUT it (no error, no value)', async () => { + const m = await stack.apiAs( + memberTok, + 'GET', + `/data/showcase_project/${projectId}?select=name,${DENIED}`, + ); + expect(m.status, 'naming a stripped field in a projection is not itself an error').toBe(200); + const record = recordOf(await m.json()); + expect(record.name, 'the readable half of the projection is served').toBeTruthy(); + expect( + Object.prototype.hasOwnProperty.call(record, DENIED), + 'the projection cannot re-open the strip', + ).toBe(false); + + const a = await stack.apiAs( + adminTok, + 'GET', + `/data/showcase_project/${projectId}?select=name,${DENIED}`, + ); + const adminRecord = recordOf(await a.json()); + expect(Number(adminRecord[DENIED]), 'the same projection serves admin the value').toBe(storedBudget); + }); + + // ── The filter/sort oracle — absence is not enough on its own ──────────── + // + // A stripped field that can still be FILTERED or SORTED on is only cosmetically + // hidden: `budget gt N` answered honestly is a binary search for the value. + // The security plugin refuses those queries by name; these two cases pin the + // refusal AND the entitled caller's continued ability to run them. + it('filtering on the stripped field is refused 403 PERMISSION_DENIED, naming the field', async () => { + const filter = encodeURIComponent(JSON.stringify({ [DENIED]: { $gt: 0 } })); + const m = await stack.apiAs(memberTok, 'GET', `/data/showcase_project?$filter=${filter}`); + expect(m.status, 'the filter oracle is closed').toBe(403); + const body: any = await m.json(); + expect(body?.code).toBe('PERMISSION_DENIED'); + expect(String(body?.error), 'the refusal names the offending field').toContain(DENIED); + + const a = await stack.apiAs(adminTok, 'GET', `/data/showcase_project?$filter=${filter}`); + expect(a.status, 'the entitled caller can still filter on it').toBe(200); + expect(rowsOf(await a.json()).length).toBeGreaterThan(0); + }); + + it('sorting on the stripped field is refused 403 PERMISSION_DENIED (ordering leaks it too)', async () => { + const m = await stack.apiAs(memberTok, 'GET', `/data/showcase_project?sort=${DENIED}`); + expect(m.status).toBe(403); + const body: any = await m.json(); + expect(body?.code).toBe('PERMISSION_DENIED'); + expect(String(body?.error)).toContain(DENIED); + + const a = await stack.apiAs(adminTok, 'GET', `/data/showcase_project?$orderby=${DENIED} desc`); + expect(a.status, 'the entitled caller can still sort on it').toBe(200); + }); + + // ── The write complement of a READ deny ────────────────────────────────── + // + // Distinct from the permission-zoo write pin, which exercises the showcase's + // `readable: true, editable: false` grant. This is the OTHER shape: a field the + // caller cannot even read must not be writable either, and the value oracle — + // not the status — is what decides. + it('a field the caller cannot READ cannot be written either, and the stored value is unchanged', async () => { + const r = await stack.apiAs(memberTok, 'PATCH', `/data/showcase_project/${projectId}`, { + [DENIED]: 1, + }); + expect(r.status, 'write to an unreadable field is refused').toBe(403); + expect((await r.json())?.code).toBe('PERMISSION_DENIED'); + const after = await ql.findOne('showcase_project', { where: { id: projectId }, context: SYS }); + expect(Number(after[DENIED]), 'the stored value is untouched').toBe(storedBudget); + }); +});