Skip to content

Commit db560eb

Browse files
committed
feat(plugin-security): describe a user's effective permission sets with their origins
The resolver records each permission-set name's origin when asked (withPermissionOrigins), and the security service's describeEffectiveAccess reads it behind explain's caller gate, now one shared function. Claude-Session: https://claude.ai/code/session_01FEkQ5kUXrK37qc2vkfEHQ4 Co-authored-by: Claude <noreply@anthropic.com>
1 parent f8c3ecc commit db560eb

5 files changed

Lines changed: 287 additions & 38 deletions

File tree

‎packages/core/src/security/resolve-authz-context.ts‎

Lines changed: 71 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -65,7 +65,7 @@ import { SystemObjectName } from '@objectstack/spec/system';
6565
import type { AuthzPosture, TenancyPosture } from '@objectstack/spec/security';
6666
import { postureEnforcesWall } from '@objectstack/spec/security';
6767
import { isValueDomainMember } from '@objectstack/spec/shared';
68-
import type { AuthSessionApi } from '@objectstack/spec/contracts';
68+
import type { AuthSessionApi, EffectivePermissionSetOrigin } from '@objectstack/spec/contracts';
6969

7070
import { ApiKeyLifecycleRefusalError, resolveApiKeyAdmission } from './api-key.js';
7171
import type { ApiKeyLifecyclePolicySource, ApiKeyRefusalReason } from './api-key.js';
@@ -879,6 +879,21 @@ export interface UserAuthzGrants {
879879
audience?: 'external';
880880
/** The user's unique email (`sys_user`), for `current_user.email` owner RLS. */
881881
email?: string;
882+
/**
883+
* [ADR-0090 D6] Where each name in `permissions` came from, keyed by name —
884+
* present only when the caller asked for it
885+
* ({@link ResolveUserAuthzGrantsOptions.withPermissionOrigins}). Recorded at
886+
* the derivation sites themselves, so it cannot disagree with them: `direct`
887+
* where an applying grant row of the user's own names an active set (the
888+
* `directPermissions` channel), `position` / `default` where a held
889+
* position's definition in force names it (`default` for the `everyone`
890+
* audience anchor, whose bindings are the default ones), and `derived` where
891+
* the configured platform administrators (§6b-config) or the `ai_access` flag
892+
* (§7) confer the name. Every name in `permissions` the resolution derived has
893+
* at least one origin, each origin listed once, in the order the resolution
894+
* reached it; a `seedPermissions` name the caller supplied has none.
895+
*/
896+
permissionOrigins?: Record<string, EffectivePermissionSetOrigin[]>;
882897
}
883898

884899
export interface ResolveUserAuthzGrantsOptions {
@@ -920,6 +935,16 @@ export interface ResolveUserAuthzGrantsOptions {
920935
* would then trust.
921936
*/
922937
bypassGrantsCache?: boolean;
938+
/**
939+
* [ADR-0090 D6] Record where each permission-set name came from, in
940+
* {@link UserAuthzGrants.permissionOrigins}. For a surface that DESCRIBES a
941+
* user's access (`ISecurityService.describeEffectiveAccess`), never for
942+
* enforcement: the envelope is otherwise byte-identical to a resolution
943+
* without it. It implies {@link bypassGrantsCache}, for the explainer's ruled
944+
* reason: a description is what an administrator reads to verify a change
945+
* took effect, and an origin map is recorded only by a resolution that ran.
946+
*/
947+
withPermissionOrigins?: boolean;
923948
}
924949

925950
/**
@@ -1839,12 +1864,29 @@ export async function resolveUserAuthzGrants(
18391864
// read HERE, before any read of this resolution is issued. Outside that
18401865
// scope (every direct caller of this function) it is `undefined` and nothing
18411866
// changes.
1842-
const requestMemo = openRequestGrantsMemo(ql, userId, opts, readWriteEpoch(ql));
1867+
// [ADR-0090 D6] An origin map is recorded only by a resolution that runs, so
1868+
// asking for one is a fresh resolution (see `withPermissionOrigins`).
1869+
const cacheOpts = opts.withPermissionOrigins ? { ...opts, bypassGrantsCache: true } : opts;
1870+
const requestMemo = openRequestGrantsMemo(ql, userId, cacheOpts, readWriteEpoch(ql));
18431871
if (requestMemo?.hit) return requestMemo.hit;
18441872

1845-
const grantsCache = openUserGrantsCache(ql, userId, opts);
1873+
const grantsCache = openUserGrantsCache(ql, userId, cacheOpts);
18461874
if (grantsCache?.hit) return grantsCache.hit;
18471875

1876+
// [ADR-0090 D6] The origin record, when asked for: each origin once per name,
1877+
// in the order the derivation below reaches it.
1878+
const origins = opts.withPermissionOrigins ? new Map<string, EffectivePermissionSetOrigin[]>() : undefined;
1879+
const recordOrigin = (name: string, origin: EffectivePermissionSetOrigin): void => {
1880+
if (!origins) return;
1881+
const list = origins.get(name) ?? [];
1882+
const same = (o: EffectivePermissionSetOrigin): boolean =>
1883+
o.kind === origin.kind
1884+
&& (o.kind !== 'position' || (origin.kind === 'position' && o.position === origin.position))
1885+
&& (o.kind !== 'derived' || (origin.kind === 'derived' && o.source === origin.source));
1886+
if (!list.some(same)) list.push(origin);
1887+
origins.set(name, list);
1888+
};
1889+
18481890
const { tenantId } = opts;
18491891
const grants: UserAuthzGrants = {
18501892
positions: [],
@@ -2138,9 +2180,13 @@ export async function resolveUserAuthzGrants(
21382180
if (disabled.positions.size > 0) {
21392181
grants.positions = grants.positions.filter((n) => !disabled.positions.has(n));
21402182
}
2141-
for (const setNames of setsInForceByPosition(grants.positions, namedByPosition, disabled).values()) {
2183+
for (const [positionName, setNames] of setsInForceByPosition(grants.positions, namedByPosition, disabled)) {
21422184
for (const setName of setNames) {
21432185
if (!boundSetNames.includes(setName)) boundSetNames.push(setName);
2186+
// [ADR-0090 D5] The `everyone` anchor's bindings are the default ones.
2187+
recordOrigin(setName, positionName === 'everyone'
2188+
? { kind: 'default' }
2189+
: { kind: 'position', position: positionName });
21442190
}
21452191
}
21462192

@@ -2168,6 +2214,7 @@ export async function resolveUserAuthzGrants(
21682214
// [#25799] The direct channel, as the explainer reads it: a name this
21692215
// resolution confers through the user's own grant row.
21702216
if (active && !grants.directPermissions.includes(name)) grants.directPermissions.push(name);
2217+
if (active) recordOrigin(name, { kind: 'direct' });
21712218
// platform_admin (ADR-0068 D2) is DERIVED from the anchoring admin_full_access
21722219
// USER grant — the single source of truth (no trusted stored boolean). The
21732220
// set is the catalog's one `admin_full_access` (ADR-0131 D4); a grant the
@@ -2235,6 +2282,7 @@ export async function resolveUserAuthzGrants(
22352282
// envelope a grant-derived one carries.
22362283
hasPlatformAdminGrant = true;
22372284
if (!grants.permissions.includes(ADMIN_FULL_ACCESS)) grants.permissions.push(ADMIN_FULL_ACCESS);
2285+
recordOrigin(ADMIN_FULL_ACCESS, { kind: 'derived', source: 'platform_admin_config' });
22382286
for (const p of ADMIN_FULL_ACCESS_CAPABILITIES.systemPermissions ?? []) {
22392287
if (!grants.systemPermissions.includes(p)) grants.systemPermissions.push(p);
22402288
}
@@ -2282,9 +2330,26 @@ export async function resolveUserAuthzGrants(
22822330

22832331
// 7. [cloud ADR-0024 §7] Env-side AI seat: synthesize the `ai_seat` capability from the
22842332
// boolean sys_user.ai_access (sqlite returns 1/0; memory returns boolean).
2285-
if (!grants.permissions.includes('ai_seat')) {
2333+
// An origin record reads the flag even when another channel already named
2334+
// `ai_seat`, so a name reached both ways carries both origins; the row is
2335+
// the memoised one, and the envelope is unchanged.
2336+
if (!grants.permissions.includes('ai_seat') || origins) {
22862337
const aiAccess = ((await getUserRow()) as { ai_access?: unknown } | undefined)?.ai_access;
2287-
if (aiAccess === true || aiAccess === 1 || aiAccess === '1') grants.permissions.push('ai_seat');
2338+
if (aiAccess === true || aiAccess === 1 || aiAccess === '1') {
2339+
if (!grants.permissions.includes('ai_seat')) grants.permissions.push('ai_seat');
2340+
recordOrigin('ai_seat', { kind: 'derived', source: 'ai_access' });
2341+
}
2342+
}
2343+
2344+
// [ADR-0090 D6] Only names the envelope holds keep an origin: a bound name
2345+
// the catalog holds no set for, or a switched-off set, confers nothing.
2346+
if (origins) {
2347+
const permissionOrigins: Record<string, EffectivePermissionSetOrigin[]> = {};
2348+
for (const name of grants.permissions) {
2349+
const list = origins.get(name);
2350+
if (list) permissionOrigins[name] = list;
2351+
}
2352+
grants.permissionOrigins = permissionOrigins;
22882353
}
22892354

22902355
// [#11971] Store the fresh envelope (miss path only; the argument list is
Lines changed: 130 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,130 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [ADR-0090 D6/D12] `SecurityPlugin#describeEffectiveAccess`: one user's
5+
* effective permission sets, each with where it comes from — a default
6+
* binding, a held position, a direct grant, or a name the resolver derives
7+
* from the user's standing. The contract is the spec's
8+
* `ISecurityService.describeEffectiveAccess` docblock; this module implements
9+
* exactly that.
10+
*
11+
* ## One gate, and the one place it departs from explain
12+
*
13+
* Who may read whom is explain's caller gate itself
14+
* ({@link mayDescribeAnotherUser}, `security-plugin-explain-access.ts`), asked
15+
* the same way for any id that is not the caller's own. Then the user must
16+
* exist (`readSysUserRow`, the explainer's one existence read). An id no user
17+
* row has is refused with the SAME `PermissionDeniedError` — same message,
18+
* same details — as one the caller may not manage, for every caller,
19+
* `manage_users` included, so the answer says nothing about which ids exist.
20+
* That is the departure the contract names: explain answers an admitted caller
21+
* `404` there, and this read must not.
22+
*
23+
* ## One reading of the origins
24+
*
25+
* The positions and permission-set names are the resolver's own
26+
* (`resolveUserAuthzGrants`, `@objectstack/core`), and so are the origins: the
27+
* resolution records them at its derivation sites when asked
28+
* (`withPermissionOrigins`), so a set here can never carry an origin the
29+
* resolution did not derive it by. The one channel the resolver does not own
30+
* is the human baseline the security service adds for every authenticated
31+
* member (`humanBaselineFor`, the helper the set resolution and the explainer
32+
* read): those sets join last, as `default`, and a set already listed keeps
33+
* its place and gains the origin.
34+
*
35+
* The organization is explain's: the caller's active one, kept only while the
36+
* described user could be resolved in it (`vetOrganizationClaim`, the session
37+
* arm of `resolveAuthzContext`), else none.
38+
*/
39+
import { resolveUserAuthzGrants, vetOrganizationClaim } from '@objectstack/core';
40+
import type { EffectiveAccess, EffectivePermissionSet, EffectivePermissionSetOrigin } from '@objectstack/spec/contracts';
41+
import type { SecurityPlugin } from './security-plugin.js';
42+
import { PermissionDeniedError } from './errors.js';
43+
import { readSysUserRow } from './explain-engine.js';
44+
import { humanBaselineFor } from './external-baseline.js';
45+
import { mayDescribeAnotherUser } from './security-plugin-explain-access.js';
46+
47+
/**
48+
* The `SecurityPlugin` members {@link describeEffectiveAccess} reads — every
49+
* one of them, and no other. Each is typed AS the class member, so a change to
50+
* a member's signature on the class is a change here too.
51+
*/
52+
export interface EffectiveAccessHost {
53+
readonly baselinePermissionSets: SecurityPlugin['baselinePermissionSets'];
54+
readonly delegatedAdminGate: SecurityPlugin['delegatedAdminGate'];
55+
readonly permissionEvaluator: SecurityPlugin['permissionEvaluator'];
56+
readonly ql: SecurityPlugin['ql'];
57+
readonly tenancyPosture: SecurityPlugin['tenancyPosture'];
58+
resolvePermissionSetsForContext: SecurityPlugin['resolvePermissionSetsForContext'];
59+
}
60+
61+
/**
62+
* The refusal for a user the caller may not describe AND for an id no user
63+
* has: one constructor, so the two cannot drift apart. It names no id.
64+
*/
65+
function effectiveAccessRefusal(): PermissionDeniedError {
66+
return new PermissionDeniedError(
67+
`[Security] Access denied: reading another user's effective access requires the 'manage_users' ` +
68+
`capability, organization administration of an organization that user is a member of, ` +
69+
`or a delegated adminScope covering that user (ADR-0090 D6/D12).`,
70+
);
71+
}
72+
73+
/** The body of `SecurityPlugin#describeEffectiveAccess`; the spec member's docblock is its contract. */
74+
export async function describeEffectiveAccess(
75+
this: EffectiveAccessHost,
76+
userId: string,
77+
callerContext?: any,
78+
): Promise<EffectiveAccess> {
79+
const target = typeof userId === 'string' ? userId : '';
80+
// An empty id names nobody: refused as an unknown one, never read as the caller.
81+
if (target === '') throw effectiveAccessRefusal();
82+
if (target !== callerContext?.userId && !(await mayDescribeAnotherUser.call(this, target, callerContext))) {
83+
throw effectiveAccessRefusal();
84+
}
85+
// Asked only after the gate, so a caller it refuses learns nothing about ids.
86+
// A read that throws propagates as a fault; it is not "no such user".
87+
if (!(await readSysUserRow(this.ql, target))) throw effectiveAccessRefusal();
88+
89+
const callerTenantId = typeof callerContext?.tenantId === 'string' && callerContext.tenantId !== ''
90+
? callerContext.tenantId
91+
: undefined;
92+
const nowMs = Date.now();
93+
const resolveIn = (tenantId: string | undefined) =>
94+
resolveUserAuthzGrants(this.ql, target, { tenantId, nowMs, withPermissionOrigins: true });
95+
let grants = await resolveIn(callerTenantId);
96+
const organizationId = vetOrganizationClaim(callerTenantId, grants.accessible_org_ids ?? [], this.tenancyPosture);
97+
if (organizationId !== callerTenantId) grants = await resolveIn(organizationId);
98+
99+
const origins = grants.permissionOrigins ?? {};
100+
const permissionSets: EffectivePermissionSet[] = [];
101+
const byName = new Map<string, EffectivePermissionSet>();
102+
const add = (name: string, origin: EffectivePermissionSetOrigin): void => {
103+
let entry = byName.get(name);
104+
if (!entry) {
105+
entry = { name, origins: [] };
106+
byName.set(name, entry);
107+
permissionSets.push(entry);
108+
}
109+
if (!entry.origins.some((o) => JSON.stringify(o) === JSON.stringify(origin))) entry.origins.push(origin);
110+
};
111+
for (const name of grants.permissions) {
112+
const derivedBy = origins[name];
113+
// Every name this resolution derived carries an origin; one without is a
114+
// resolver defect, said as one rather than listed with an invented origin.
115+
if (!derivedBy || derivedBy.length === 0) {
116+
throw new Error(`[Security] describeEffectiveAccess: the resolution named permission set '${name}' without an origin.`);
117+
}
118+
for (const origin of derivedBy) add(name, origin);
119+
}
120+
for (const name of humanBaselineFor(grants.positions, this.baselinePermissionSets)) {
121+
add(name, { kind: 'default' });
122+
}
123+
124+
return {
125+
userId: target,
126+
organizationId: organizationId ?? null,
127+
positions: [...grants.positions],
128+
permissionSets,
129+
};
130+
}

‎packages/plugins/plugin-security/src/security-plugin-explain-access.ts‎

Lines changed: 43 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,42 @@ export interface ExplainAccessHost {
123123
*/
124124
type RlsFilterOptions = NonNullable<Parameters<SecurityPlugin['computeLayeredRlsFilter']>[4]>;
125125

126+
/**
127+
* [ADR-0090 D6/D12] Whether `callerContext` may describe ANOTHER user's access:
128+
* the one caller gate of the explain family, asked by `explain` and by
129+
* `describeEffectiveAccess` (`security-plugin-effective-access.ts`) alike, so
130+
* the two cannot disagree about who may read whom.
131+
*
132+
* A system caller may. Otherwise the caller holds `manage_users`, or — [ADR-0090
133+
* D12, amended 2026-10-17] — is the organization administrator of an
134+
* organization `userId` is a member of (the members whose assignments it
135+
* creates and removes), or [D12] holds a delegated `adminScope` covering
136+
* `userId`. Each check fails closed on any error, and each reads the
137+
* organization the caller's sets were resolved in, never another. It answers
138+
* `false` for an id no user has, as for one the caller may not manage: what
139+
* each caller does about a user that does not exist is decided after it.
140+
*/
141+
export async function mayDescribeAnotherUser(
142+
this: Pick<ExplainAccessHost, 'delegatedAdminGate' | 'permissionEvaluator' | 'resolvePermissionSetsForContext'>,
143+
userId: string,
144+
callerContext?: any,
145+
): Promise<boolean> {
146+
if (callerContext?.isSystem === true) return true;
147+
const callerSets = await this.resolvePermissionSetsForContext(callerContext).catch(() => []);
148+
const held = this.permissionEvaluator.getSystemPermissions(callerSets);
149+
if (held.has('manage_users')) return true;
150+
const organizationLevel = this.delegatedAdminGate
151+
? await this.delegatedAdminGate
152+
.organizationAdminCoversUser(callerSets, userId, callerContext)
153+
.catch(() => false)
154+
: false;
155+
return organizationLevel || (this.delegatedAdminGate
156+
? await this.delegatedAdminGate
157+
.scopesCoverUser(callerSets, userId, callerContext)
158+
.catch(() => false)
159+
: false);
160+
}
161+
126162
/** The body of `SecurityPlugin#explainAccessForCaller`; the method's docblock there is its contract. */
127163
export async function explainAccessForCaller(
128164
this: Pick<ExplainAccessHost, 'baselinePermissionSets' | 'checkControlledByParentWrite' | 'collectRLSPolicies' | 'computeLayeredRlsFilter' | 'computeReadPartialMaskRules' | 'computeRlsFilter' | 'delegatedAdminGate' | 'foldFieldRequiredPermissions' | 'getObjectSecurityMeta' | 'permissionEvaluator' | 'ql' | 'readRowById' | 'resolveKernelService' | 'resolvePermissionSetsForContext' | 'resolvePreImageFloorDrop' | 'resolveSharingReadFilter' | 'resolveSharingWriteVerdict' | 'resolveWriteScopeForSharing' | 'tenancyPosture'>,
@@ -150,36 +186,13 @@ export async function explainAccessForCaller(
150186
// through the other-user arm: an empty id names nobody, so it is refused
151187
// there like an unknown one, never folded into explaining the caller.
152188
if (request.userId !== undefined && request.userId !== callerContext?.userId) {
153-
const callerIsSystem = callerContext?.isSystem === true;
154-
if (!callerIsSystem) {
155-
const callerSets = await this.resolvePermissionSetsForContext(callerContext).catch(() => []);
156-
const held = this.permissionEvaluator.getSystemPermissions(callerSets);
157-
if (!held.has('manage_users')) {
158-
// [ADR-0090 D12, amended 2026-10-17] An organization administrator
159-
// may explain a member of the organization it administers — the
160-
// members whose assignments it creates and removes. Then [D12]
161-
// delegated administrators may explain principals inside their
162-
// delegation boundary. Both fail closed on any error, and both read
163-
// the organization the caller's sets were resolved in, never another.
164-
const organizationLevel = this.delegatedAdminGate
165-
? await this.delegatedAdminGate
166-
.organizationAdminCoversUser(callerSets, request.userId, callerContext)
167-
.catch(() => false)
168-
: false;
169-
const delegated = organizationLevel || (this.delegatedAdminGate
170-
? await this.delegatedAdminGate
171-
.scopesCoverUser(callerSets, request.userId, callerContext)
172-
.catch(() => false)
173-
: false);
174-
if (!delegated) {
175-
throw new PermissionDeniedError(
176-
`[Security] Access denied: explaining another user's access requires the 'manage_users' ` +
177-
`capability, organization administration of an organization that user is a member of, ` +
178-
`or a delegated adminScope covering that user (ADR-0090 D6/D12).`,
179-
{ object, operation, targetUserId: request.userId },
180-
);
181-
}
182-
}
189+
if (!(await mayDescribeAnotherUser.call(this, request.userId, callerContext))) {
190+
throw new PermissionDeniedError(
191+
`[Security] Access denied: explaining another user's access requires the 'manage_users' ` +
192+
`capability, organization administration of an organization that user is a member of, ` +
193+
`or a delegated adminScope covering that user (ADR-0090 D6/D12).`,
194+
{ object, operation, targetUserId: request.userId },
195+
);
183196
}
184197
// [#26641] ...and only a user who exists is explained. The resolver
185198
// synthesises the baseline anchor and sets for ANY id, so an id no

0 commit comments

Comments
 (0)