Skip to content

Commit 24e3a48

Browse files
committed
test(plugin-security): pin the delegated answer about a user the caller cannot read on the fake engine
Every write shape that judges a target user, and the explain doors' coverage, answer a user the caller cannot read exactly as an id naming no user. Claude-Session: https://claude.ai/code/session_017xRBcT1w3zpekijraHJE4f Co-authored-by: Claude <noreply@anthropic.com>
1 parent e43264a commit 24e3a48

1 file changed

Lines changed: 182 additions & 98 deletions

File tree

‎packages/plugins/plugin-security/src/delegated-admin-gate.test.ts‎

Lines changed: 182 additions & 98 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ function makeHarness() {
113113

114114
const ctxOf = (principal: string, userId = `u_${principal}`) =>
115115
({ principal, userId, positions: [principal], organizationId: HARNESS_ORG });
116-
return { gate, ql, tables, ctxOf };
116+
return { gate, ql, tables, ctxOf, SETS };
117117
}
118118

119119
let h: ReturnType<typeof makeHarness>;
@@ -1941,116 +1941,200 @@ describe('[#26189] DelegatedAdminGate — a scope violation answers DELEGATION_S
19411941
// target outside it is refused with ONE reason, whether or not the user
19421942
// exists or holds a business-unit membership: the same class, code, status,
19431943
// sentence and details, on the thrown value and on the REST door's
1944-
// classification (`mapDataError`). A target user the write NAMES is first
1945-
// asked of the caller's own read door, as the engine's reference check asks
1946-
// it: one the caller cannot read is answered as one that does not exist, so
1947-
// it is outside the subtree too. One target id, its stored states, and every
1948-
// write shape that judges a target user.
1949-
1950-
describe('[ADR-0090 D12] a delegated refusal names one reason for a target user outside the subtree, whether or not the user exists or holds a business-unit membership', () => {
1951-
const TARGET = 'u_target';
1952-
const STATES = [
1953-
'an id naming no user',
1954-
'a user with no business-unit membership',
1955-
'a user whose business unit is outside the subtree',
1956-
] as const;
1957-
/** A state only a write that NAMES the target meets: the caller's read door is asked about it. */
1958-
const UNREADABLE_INSIDE = 'a user with a business unit inside the subtree whom the caller cannot read';
1959-
const READABLE_INSIDE = 'a user with a business unit inside the subtree whom the caller reads';
1960-
type TargetState = (typeof STATES)[number] | typeof UNREADABLE_INSIDE | typeof READABLE_INSIDE;
1944+
// classification (`mapDataError`). Every target user the gate judges — one
1945+
// the write names and one a stored grant keeps alike — is first asked of the
1946+
// caller's own read door: one the caller cannot read is answered as one that
1947+
// does not exist, so it is outside the subtree too, and a delegated scope
1948+
// covers it for the explain doors no more than it covers an id naming no
1949+
// user. One target id, its states, every write shape that judges a target
1950+
// user, and the explain doors' coverage.
1951+
1952+
const TARGET = 'u_target';
1953+
/** The four states of `TARGET` a delegated answer does not tell apart. */
1954+
const TARGET_STATES = [
1955+
'an id naming no user',
1956+
'a user with no business-unit membership',
1957+
'a user whose business unit is outside the subtree',
1958+
'a user with a business unit inside the subtree whom the caller cannot read',
1959+
] as const;
1960+
const UNREADABLE_INSIDE = TARGET_STATES[3];
1961+
/** The CONTROL: inside the subtree, and read by the caller. */
1962+
const READABLE_INSIDE = 'a user with a business unit inside the subtree whom the caller reads';
1963+
type TargetState = (typeof TARGET_STATES)[number] | typeof READABLE_INSIDE;
19611964

1962-
/**
1963-
* A fresh harness with `TARGET` in `state`, over the engine the gate meets in
1964-
* a real composition: `sys_user` registered and the grant's `user_id` a
1965-
* lookup to it (the conditions under which the engine's reference check asks
1966-
* the caller's read door), and a caller read of `sys_user` that returns no
1967-
* row for a user the caller cannot read. A system read returns every row.
1968-
*/
1969-
function harnessWith(state: TargetState): ReturnType<typeof makeHarness> {
1970-
const harness = makeHarness();
1971-
const unreadable = new Set<string>();
1972-
const { find, findOne } = harness.ql;
1973-
const served = (object: string, opts: any, row: any) =>
1974-
!(object === 'sys_user' && !opts?.context?.isSystem && unreadable.has(row?.id));
1975-
harness.ql.find = async (object: string, opts: any) =>
1976-
(await find.call(harness.ql, object, opts)).filter((row: any) => served(object, opts, row));
1977-
harness.ql.findOne = async (object: string, opts: any) => {
1978-
const row = await findOne.call(harness.ql, object, opts);
1979-
return row && served(object, opts, row) ? row : null;
1980-
};
1981-
const SCHEMAS: Record<string, unknown> = {
1982-
sys_user: { name: 'sys_user', fields: {} },
1983-
sys_user_permission_set: { name: 'sys_user_permission_set', fields: { user_id: { type: 'lookup', reference: 'sys_user' } } },
1984-
};
1985-
harness.ql.getSchema = (name: string) => SCHEMAS[name];
1986-
if (state === 'an id naming no user') return harness;
1987-
harness.tables.sys_user.push({ id: TARGET });
1988-
if (state === 'a user whose business unit is outside the subtree') {
1989-
harness.tables.sys_business_unit_member.push({ id: 'm_target', business_unit_id: 'bu_west', user_id: TARGET });
1990-
}
1991-
if (state === UNREADABLE_INSIDE || state === READABLE_INSIDE) {
1992-
harness.tables.sys_business_unit_member.push({ id: 'm_target', business_unit_id: 'bu_es', user_id: TARGET });
1993-
}
1994-
if (state === UNREADABLE_INSIDE) unreadable.add(TARGET);
1995-
return harness;
1965+
/**
1966+
* A fresh harness with `TARGET` in `state`, over the engine the gate meets in
1967+
* a real composition: `sys_user` registered, and a caller read of `sys_user`
1968+
* that returns no row for a user the caller cannot read. A system read returns
1969+
* every row. `holderColumn` is the live schema of the grant's `user_id` (a
1970+
* writable lookup to `sys_user` unless a pin says otherwise; `null` declares
1971+
* none). Every non-system `sys_user` read is recorded in `callerUserReads`,
1972+
* as the context it ran under.
1973+
*/
1974+
function harnessWith(state: TargetState, holderColumn: unknown = { type: 'lookup', reference: 'sys_user' }) {
1975+
const harness = makeHarness();
1976+
const unreadable = new Set<string>();
1977+
const callerUserReads: any[] = [];
1978+
const { find, findOne } = harness.ql;
1979+
const served = (object: string, opts: any, row: any) =>
1980+
!(object === 'sys_user' && !opts?.context?.isSystem && unreadable.has(row?.id));
1981+
harness.ql.find = async (object: string, opts: any) => {
1982+
if (object === 'sys_user' && !opts?.context?.isSystem) callerUserReads.push(opts?.context);
1983+
return (await find.call(harness.ql, object, opts)).filter((row: any) => served(object, opts, row));
1984+
};
1985+
harness.ql.findOne = async (object: string, opts: any) => {
1986+
const row = await findOne.call(harness.ql, object, opts);
1987+
return row && served(object, opts, row) ? row : null;
1988+
};
1989+
const SCHEMAS: Record<string, unknown> = {
1990+
sys_user: { name: 'sys_user', fields: {} },
1991+
sys_user_permission_set: { name: 'sys_user_permission_set', fields: holderColumn ? { user_id: holderColumn } : {} },
1992+
};
1993+
harness.ql.getSchema = (name: string) => SCHEMAS[name];
1994+
const out = { ...harness, callerUserReads };
1995+
if (state === 'an id naming no user') return out;
1996+
harness.tables.sys_user.push({ id: TARGET });
1997+
if (state === 'a user whose business unit is outside the subtree') {
1998+
harness.tables.sys_business_unit_member.push({ id: 'm_target', business_unit_id: 'bu_west', user_id: TARGET });
19961999
}
2000+
if (state === UNREADABLE_INSIDE || state === READABLE_INSIDE) {
2001+
harness.tables.sys_business_unit_member.push({ id: 'm_target', business_unit_id: 'bu_es', user_id: TARGET });
2002+
}
2003+
if (state === UNREADABLE_INSIDE) unreadable.add(TARGET);
2004+
return out;
2005+
}
2006+
type TargetHarness = ReturnType<typeof harnessWith>;
19972007

1998-
/**
1999-
* Every write shape that judges a target user, as `[operation, write, names]`:
2000-
* a new grant and a stored grant pointed at the target NAME it; a stored
2001-
* grant of the target removed holds it as stored. Each write is the gate's
2002-
* own `assert`, never an engine double.
2003-
*/
2004-
const WRITES: ReadonlyArray<readonly [string, (harness: ReturnType<typeof makeHarness>) => Promise<void>, boolean]> = [
2005-
['insert', (harness) => harness.gate.assert({
2006-
object: 'sys_user_permission_set', operation: 'insert',
2007-
data: { user_id: TARGET, permission_set: 'sales_user' }, context: harness.ctxOf('delegate'),
2008-
}), true],
2009-
['update', (harness) => {
2010-
harness.tables.sys_user_permission_set = [{ id: 'g_east', user_id: 'u_east_1', permission_set: 'sales_user' }];
2011-
return harness.gate.assert({
2012-
object: 'sys_user_permission_set', operation: 'update',
2013-
data: { id: 'g_east', user_id: TARGET }, context: harness.ctxOf('delegate'),
2014-
});
2015-
}, true],
2016-
['delete', (harness) => {
2017-
harness.tables.sys_user_permission_set = [{ id: 'g_target', user_id: TARGET, permission_set: 'sales_user' }];
2018-
return harness.gate.assert({
2019-
object: 'sys_user_permission_set', operation: 'delete',
2020-
options: { where: { id: 'g_target' } }, context: harness.ctxOf('delegate'),
2021-
});
2022-
}, false],
2023-
];
2024-
2025-
/** Everything a caller is told by a refusal: the thrown value and the REST door's envelope. */
2026-
const answerOf = (err: any) => ({
2027-
class: err?.constructor?.name,
2028-
name: err?.name,
2029-
code: err?.code,
2030-
status: err?.status,
2031-
statusCode: err?.statusCode,
2032-
message: err?.message,
2033-
details: err?.details,
2034-
wire: mapDataError(err, 'sys_user_permission_set'),
2035-
});
2036-
2037-
for (const [shape, write, names] of WRITES) {
2038-
const states: TargetState[] = names ? [...STATES, UNREADABLE_INSIDE] : [...STATES];
2039-
it(`${shape}: the ${states.length} target states answer the same scope-violation refusal`, async () => {
2008+
/**
2009+
* Every write shape that judges a target user, as `[shape, operation, write]`:
2010+
* a new grant and a stored grant pointed at the target NAME it; a stored grant
2011+
* of the target edited with its `user_id` left as stored, and one removed, KEEP
2012+
* it. Each write is the gate's own `assert`, never an engine double.
2013+
*/
2014+
const TARGET_WRITES: ReadonlyArray<readonly [string, string, (harness: TargetHarness) => Promise<void>]> = [
2015+
['insert', 'insert', (harness) => harness.gate.assert({
2016+
object: 'sys_user_permission_set', operation: 'insert',
2017+
data: { user_id: TARGET, permission_set: 'sales_user' }, context: harness.ctxOf('delegate'),
2018+
})],
2019+
['update pointing a stored grant at the target', 'update', (harness) => {
2020+
harness.tables.sys_user_permission_set = [{ id: 'g_east', user_id: 'u_east_1', permission_set: 'sales_user' }];
2021+
return harness.gate.assert({
2022+
object: 'sys_user_permission_set', operation: 'update',
2023+
data: { id: 'g_east', user_id: TARGET }, context: harness.ctxOf('delegate'),
2024+
});
2025+
}],
2026+
["update of the target's stored grant, its user_id left as stored", 'update', (harness) => {
2027+
harness.tables.sys_user_permission_set = [{ id: 'g_target', user_id: TARGET, permission_set: 'sales_user' }];
2028+
return harness.gate.assert({
2029+
object: 'sys_user_permission_set', operation: 'update',
2030+
data: { id: 'g_target', reason: 'renewed' }, context: harness.ctxOf('delegate'),
2031+
});
2032+
}],
2033+
["delete of the target's stored grant", 'delete', (harness) => {
2034+
harness.tables.sys_user_permission_set = [{ id: 'g_target', user_id: TARGET, permission_set: 'sales_user' }];
2035+
return harness.gate.assert({
2036+
object: 'sys_user_permission_set', operation: 'delete',
2037+
options: { where: { id: 'g_target' } }, context: harness.ctxOf('delegate'),
2038+
});
2039+
}],
2040+
];
2041+
2042+
/** Everything a caller is told by a refusal: the thrown value and the REST door's envelope. */
2043+
const answerOf = (err: any) => ({
2044+
class: err?.constructor?.name,
2045+
name: err?.name,
2046+
code: err?.code,
2047+
status: err?.status,
2048+
statusCode: err?.statusCode,
2049+
message: err?.message,
2050+
details: err?.details,
2051+
wire: mapDataError(err, 'sys_user_permission_set'),
2052+
});
2053+
2054+
describe('[ADR-0090 D12] a delegated refusal names one reason for a target user outside the subtree, whether or not the user exists, holds a business-unit membership, or is one the caller can read', () => {
2055+
for (const [shape, operation, write] of TARGET_WRITES) {
2056+
it(`${shape}: the ${TARGET_STATES.length} target states answer the same scope-violation refusal`, async () => {
20402057
const answers: Array<ReturnType<typeof answerOf>> = [];
2041-
for (const state of states) answers.push(answerOf(await refusalOf(() => write(harnessWith(state)))));
2042-
for (const [i, answer] of answers.entries()) expect(answer, states[i]).toEqual(answers[0]);
2058+
for (const state of TARGET_STATES) answers.push(answerOf(await refusalOf(() => write(harnessWith(state)))));
2059+
for (const [i, answer] of answers.entries()) expect(answer, TARGET_STATES[i]).toEqual(answers[0]);
20432060
// The one answer is the caller's own scope: the target outside the subtree.
20442061
const err = await refusalOf(() => write(harnessWith('an id naming no user')));
20452062
expectScopeViolation(err, 'sys_user_permission_set',
20462063
/^\[Security\] Outside your delegated scope: delegated '\w+' on sys_user_permission_set rejected — target user 'u_target' is outside the delegated subtree \(scope from 'sub_admin'\)\.$/);
2047-
expect(err.details).toEqual({ operation: shape, object: 'sys_user_permission_set', permissionSet: 'sales_user' });
2064+
expect(err.details).toEqual({ operation, object: 'sys_user_permission_set', permissionSet: 'sales_user' });
20482065
});
20492066
}
20502067

20512068
it('CONTROL: the same target with a business unit inside the subtree, read by the caller, is admitted on every write shape', async () => {
2052-
for (const [shape, write] of WRITES) {
2069+
for (const [shape, , write] of TARGET_WRITES) {
20532070
await expect(write(harnessWith(READABLE_INSIDE)), shape).resolves.toBeUndefined();
20542071
}
20552072
});
2073+
2074+
it("the answer does not change with the grant's user_id column: a read-only lookup, a plain text column, or none at all", async () => {
2075+
for (const holderColumn of [{ type: 'lookup', reference: 'sys_user', readonly: true }, { type: 'text' }, null]) {
2076+
for (const [shape, , write] of TARGET_WRITES) {
2077+
const label = `${shape} · ${JSON.stringify(holderColumn)}`;
2078+
expect(answerOf(await refusalOf(() => write(harnessWith(UNREADABLE_INSIDE, holderColumn)))), label)
2079+
.toEqual(answerOf(await refusalOf(() => write(harnessWith('an id naming no user', holderColumn)))));
2080+
await expect(write(harnessWith(READABLE_INSIDE, holderColumn)), `CONTROL · ${label}`).resolves.toBeUndefined();
2081+
}
2082+
}
2083+
});
2084+
2085+
it("the caller's read of the target runs under the write's own context, never the system's", async () => {
2086+
for (const [shape, , write] of TARGET_WRITES) {
2087+
const harness = harnessWith(READABLE_INSIDE);
2088+
const context = harness.ctxOf('delegate');
2089+
const assert = harness.gate.assert.bind(harness.gate);
2090+
harness.gate.assert = (opCtx: any) => assert({ ...opCtx, context });
2091+
await write(harness);
2092+
expect(harness.callerUserReads.length, shape).toBeGreaterThan(0);
2093+
for (const read of harness.callerUserReads) expect(read, shape).toBe(context);
2094+
}
2095+
});
2096+
2097+
it("CONTROL: a tenant-level administrator's removal of the stored grant of a target the caller cannot read is admitted, and asks the read nothing", async () => {
2098+
const harness = harnessWith(UNREADABLE_INSIDE);
2099+
harness.tables.sys_user_permission_set = [{ id: 'g_target', user_id: TARGET, permission_set: 'sales_user' }];
2100+
await expect(harness.gate.assert({
2101+
object: 'sys_user_permission_set', operation: 'delete',
2102+
options: { where: { id: 'g_target' } }, context: harness.ctxOf('tenant_admin'),
2103+
})).resolves.toBeUndefined();
2104+
expect(harness.callerUserReads).toEqual([]);
2105+
});
2106+
});
2107+
2108+
describe('[ADR-0090 D12] a delegated scope covers a user for the explain doors only as the write gate would, so the answer about a user the caller cannot read does not depend on its existence or memberships', () => {
2109+
const covers = (harness: TargetHarness, context: any) =>
2110+
harness.gate.scopesCoverUser(harness.SETS.delegate as any, TARGET, context);
2111+
2112+
it(`the ${TARGET_STATES.length} target states are covered by no scope, as an id naming no user is not`, async () => {
2113+
for (const state of TARGET_STATES) {
2114+
const harness = harnessWith(state);
2115+
expect(await covers(harness, harness.ctxOf('delegate')), state).toBe(false);
2116+
}
2117+
});
2118+
2119+
it('CONTROL: the same target with a business unit inside the subtree, read by the caller, is covered', async () => {
2120+
const harness = harnessWith(READABLE_INSIDE);
2121+
expect(await covers(harness, harness.ctxOf('delegate'))).toBe(true);
2122+
});
2123+
2124+
it("the caller's read of the target runs under the caller's own context, never the system's", async () => {
2125+
const harness = harnessWith(READABLE_INSIDE);
2126+
const context = harness.ctxOf('delegate');
2127+
expect(await covers(harness, context)).toBe(true);
2128+
expect(harness.callerUserReads).toEqual([context]);
2129+
expect(harness.callerUserReads[0]).toBe(context);
2130+
});
2131+
2132+
it('a context that names no organization covers nobody, and asks the read door nothing', async () => {
2133+
for (const state of [...TARGET_STATES, READABLE_INSIDE]) {
2134+
const harness = harnessWith(state);
2135+
const noOrganization = { principal: 'delegate', userId: 'u_delegate', positions: ['delegate'] };
2136+
expect(await covers(harness, noOrganization), state).toBe(false);
2137+
expect(harness.callerUserReads, state).toEqual([]);
2138+
}
2139+
});
20562140
});

0 commit comments

Comments
 (0)