Skip to content

Commit cc59ef2

Browse files
committed
wip(plugin-security): collectRLSPolicies applies an object's declared default row scope on an empty collection
Claude-Session: https://claude.ai/code/session_01Nk17Z26X5DB59iQztDBADH Co-authored-by: Claude <noreply@anthropic.com>
1 parent e22defb commit cc59ef2

4 files changed

Lines changed: 226 additions & 24 deletions

File tree

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

Lines changed: 64 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,7 @@ import type { PermissionEvaluator } from './permission-evaluator.js';
5454
import { superuserBypassBitForOperation } from './permission-evaluator.js';
5555
import { rlsOperationForVerb } from './lifecycle-verb-rls-operation.js';
5656
import { ExplainObjectNotFoundError } from './errors.js';
57-
import { RLS_DENY_FILTER, compiledPolicyNameOf } from './rls-compiler.js';
57+
import { RLS_DENY_FILTER, compiledObjectDefaultRowScopeOf, compiledPolicyNameOf } from './rls-compiler.js';
5858
import { declaredComparisonColumns } from './declared-comparison-columns.js';
5959
import {
6060
declaredJsonStoredColumns,
@@ -1070,6 +1070,47 @@ function policyMembersOf(node: unknown): unknown[] {
10701070
return Array.isArray(list) ? list.flatMap(policyMembersOf) : [node];
10711071
}
10721072

1073+
/**
1074+
* [#24164 ruling E′] The object default row scopes a composed row filter
1075+
* applies: each member {@link policyMembersOf} finds whose compiled filter the
1076+
* compiler recorded as an object's declared default, once per policy name.
1077+
* Empty when every member came from a held permission set (the default only
1078+
* ever applies to an empty collection, so a filter is one or the other).
1079+
*/
1080+
function objectDefaultRowScopesOf(filters: readonly unknown[]): Array<{ name?: string; label?: string; description?: string }> {
1081+
const out = new Map<string, { name?: string; label?: string; description?: string }>();
1082+
for (const filter of filters) {
1083+
for (const member of policyMembersOf(filter)) {
1084+
const scope = compiledObjectDefaultRowScopeOf(member);
1085+
if (scope && !out.has(scope.name ?? '')) out.set(scope.name ?? '', scope);
1086+
}
1087+
}
1088+
return [...out.values()];
1089+
}
1090+
1091+
/**
1092+
* [#24164 ruling E′] The sentence explain adds where an object's default row
1093+
* scope is the row-level predicate: the source is the object's declaration,
1094+
* named with the label and description it declares, never a permission set.
1095+
*/
1096+
function objectDefaultRowScopeSource(
1097+
object: string,
1098+
scopes: ReadonlyArray<{ name?: string; label?: string; description?: string }>,
1099+
): string {
1100+
const named = scopes
1101+
.map((scope) => {
1102+
const about = [scope.label, scope.description].filter(
1103+
(text): text is string => typeof text === 'string' && text.trim() !== '',
1104+
);
1105+
return `'${scope.name ?? '(unnamed)'}'${about.length > 0 ? ` (${about.join(' — ')})` : ''}`;
1106+
})
1107+
.join(', ');
1108+
return (
1109+
` Source: the object default row scope ${named} declared on '${object}', not a permission set — ` +
1110+
'no permission set held carries a row policy for this object and operation.'
1111+
);
1112+
}
1113+
10731114
/**
10741115
* [#20431] The names of the policies in a compiled row filter whose own filter
10751116
* `refuses` — the attribution the RLS write check logs for the same refusal.
@@ -1775,16 +1816,30 @@ async function applyRecordAttribution(
17751816
const deny = isDenyAll(layer1);
17761817
const m = matches(layer1);
17771818
const excluded = deny || m === false;
1819+
// [#24164 ruling E′] An object's default row scope is named as itself,
1820+
// reached through the object's declaration rather than a held set.
1821+
const [objectDefault] = objectDefaultRowScopesOf([layer1]);
17781822
rlsLayer.record = {
17791823
outcome: excluded ? 'excluded' : 'admitted',
17801824
rowFilter: layer1,
17811825
matchesRecord: deny ? false : m,
1782-
rules: [{ kind: 'rls_policy', name: 'business_rls', predicate: layer1, effect: excluded ? 'excludes' : 'admits' }],
1783-
detail: deny
1826+
rules: [
1827+
objectDefault
1828+
? {
1829+
kind: 'rls_policy',
1830+
name: objectDefault.name ?? '(unnamed)',
1831+
via: 'object_default',
1832+
predicate: layer1,
1833+
effect: excluded ? 'excludes' : 'admits',
1834+
}
1835+
: { kind: 'rls_policy', name: 'business_rls', predicate: layer1, effect: excluded ? 'excludes' : 'admits' },
1836+
],
1837+
detail: (deny
17841838
? 'Business RLS composes to DENY ALL for this principal.'
17851839
: excluded
17861840
? 'The record does not satisfy the business row-level predicate.'
1787-
: 'The record satisfies the business row-level predicate.',
1841+
: 'The record satisfies the business row-level predicate.') +
1842+
(objectDefault ? objectDefaultRowScopeSource(object, [objectDefault]) : ''),
17881843
};
17891844
}
17901845
}
@@ -2454,14 +2509,18 @@ async function explainOnce(deps: ExplainEngineDeps, input: ExplainInput, asker:
24542509
// `__rls_deny__` denial is now reported as `denies` while `readFilter` keeps
24552510
// reporting the predicate that was ACTUALLY composed.
24562511
if (filterParts.some(isDenyAllSentinel)) readFilter = { id: DENY_ALL_SENTINEL_ID };
2512+
// [#24164 ruling E′] Where the narrowing is an object's declared default row
2513+
// scope, say so: its source is the object, not a set the principal holds.
2514+
const objectDefaults = objectDefaultRowScopesOf(filterParts);
24572515
layers.push({
24582516
layer: 'rls',
24592517
verdict: denyAll ? 'denies' : readFilter ? 'narrows' : 'not_applicable',
24602518
detail: denyAll
24612519
? 'Row-level security composes to DENY ALL for this principal.'
24622520
: readFilter
24632521
? 'Row-level security narrows the row set (see readFilter for the composed predicate)' +
2464-
(delegatorFilter ? ' — intersection of agent + delegator filters (D10).' : '.')
2522+
(delegatorFilter ? ' — intersection of agent + delegator filters (D10).' : '.') +
2523+
(objectDefaults.length > 0 ? objectDefaultRowScopeSource(object, objectDefaults) : '')
24652524
: 'No RLS policy applies.',
24662525
contributors: [],
24672526
});
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#24164 ruling E′, item 2] An object's declared default row scope
5+
* (`ObjectSchema.defaultRowScope`) as the one policy
6+
* `SecurityPlugin.collectRLSPolicies` applies when no permission set the
7+
* caller holds carries a row policy for that object and operation.
8+
*
9+
* ## What "carries a row policy" means
10+
*
11+
* Exactly what the collection already means by an EMPTY collection: the held
12+
* sets' policies for this object and operation, after the ADR-0105 D3
13+
* admission, `enabled`, the `positions` domain and `'*'` matching
14+
* (`RLSCompiler.getApplicablePolicies`). So a held `'*'` policy counts, a
15+
* policy switched off or outside the caller's positions does not, and a held
16+
* policy for another operation does not either: an object whose held sets
17+
* scope only `update` reads under its default. The default is never added to
18+
* a non-empty collection: an authored set policy is used as authored.
19+
*
20+
* The default then takes the path a held policy takes, from the same
21+
* admission onward: `getApplicablePolicies` judges its own `enabled`,
22+
* `positions` and `operation`, and the compiler compiles its `using` /
23+
* `check`. A `using` that does not lower is dropped with the same WARN and
24+
* fails closed to the same `RLS_DENY_FILTER` an authored policy's does,
25+
* because it is the same code. Superuser-bypass principals never reach the
26+
* collection, so the default cannot touch them.
27+
*
28+
* ## Why the registry, and what the read costs
29+
*
30+
* The declaration is read off `ql.getSchema(object)`, the ObjectQL registry's
31+
* resolved object: the schema the engine compiles every find against, and the
32+
* source `getObjectSecurityMeta` prefers. An object the registry does not
33+
* resolve is refused by the engine's own door before any read runs. The read
34+
* is two in-memory map lookups behind the registry's merged-object cache, and
35+
* it is made only when the held collection is empty: no I/O and no parse on
36+
* any path.
37+
*
38+
* ## Provenance
39+
*
40+
* The policy built here is recognised by IDENTITY ({@link
41+
* isObjectDefaultRowScopePolicy}), never by spelling, for the reason
42+
* `platform-ownership-policies.ts` gives for the floor's alternates: a held
43+
* policy byte-identical to an object's default is still the set's own policy,
44+
* and explain must name it as such. `RLSCompiler.compileFilter` carries the
45+
* mark onto the compiled filter, which is how explain names an applied
46+
* default by its declaration rather than by a permission set.
47+
*/
48+
49+
import type { RowLevelSecurityPolicy } from '@objectstack/spec/security';
50+
51+
/** The policies {@link objectDefaultRowScopePolicy} built — an object's default, by identity. */
52+
const OBJECT_DEFAULT_INSTANCES = new WeakSet<object>();
53+
54+
/**
55+
* The declared default row scope of `objectName` as one row-level security
56+
* policy, with `object` set to the declaring object (the key implies it, and
57+
* a stray `object` on a body that reached the registry unparsed cannot
58+
* retarget it). `null` when the schema declares none, which keeps an object
59+
* with no default exactly as it was.
60+
*
61+
* Built fresh per call: the collection hands it to filters and compilers that
62+
* never write to it, and a fresh object keeps two registered objects that
63+
* spread one shared scope literal from ever sharing a policy instance.
64+
*/
65+
export function objectDefaultRowScopePolicy(objectName: string, schema: unknown): RowLevelSecurityPolicy | null {
66+
if (schema === null || typeof schema !== 'object') return null;
67+
const scope = (schema as { defaultRowScope?: unknown }).defaultRowScope;
68+
if (scope === null || typeof scope !== 'object' || Array.isArray(scope)) return null;
69+
const policy = { ...(scope as Omit<RowLevelSecurityPolicy, 'object'>), object: objectName } as RowLevelSecurityPolicy;
70+
OBJECT_DEFAULT_INSTANCES.add(policy);
71+
return policy;
72+
}
73+
74+
/**
75+
* True iff `policy` is an object's declared default row scope, as
76+
* {@link objectDefaultRowScopePolicy} built it — never a held set's policy,
77+
* whatever it spells.
78+
*/
79+
export function isObjectDefaultRowScopePolicy(policy: object): boolean {
80+
return OBJECT_DEFAULT_INSTANCES.has(policy);
81+
}

‎packages/plugins/plugin-security/src/rls-compiler.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -54,6 +54,9 @@ import {
5454
// this plugin. This file holds no second literal: it returns the spec's object
5555
// and exports it under the name every consumer here already imports.
5656
import { RLS_DENY_FILTER as SPEC_RLS_DENY_FILTER } from '@objectstack/spec/data';
57+
// [#24164 ruling E′] An object's declared default row scope, recognised by
58+
// identity so its compiled filter can say where it came from.
59+
import { isObjectDefaultRowScopePolicy } from './object-default-row-scope.js';
5760

5861
/**
5962
* Why a policy's predicate produced no filter — the compiler's OWN answer,
@@ -712,6 +715,24 @@ export function compiledPolicyNameOf(node: unknown): string | undefined {
712715
return node !== null && typeof node === 'object' ? POLICY_OF_COMPILED_FILTER.get(node) : undefined;
713716
}
714717

718+
/**
719+
* [#24164 ruling E′] The object default row scope each compiled policy filter
720+
* came from, recorded by {@link RLSCompiler.compileFilter} beside
721+
* {@link POLICY_OF_COMPILED_FILTER}, for the same reason and in the same way:
722+
* the compiled filter is built fresh, so its identity is its policy's.
723+
*/
724+
const OBJECT_DEFAULT_OF_COMPILED_FILTER = new WeakMap<object, RowLevelSecurityPolicy>();
725+
726+
/**
727+
* [#24164 ruling E′] The object's declared default row scope whose compiled
728+
* filter `node` is, or `undefined` for any other node (a held set's policy, a
729+
* composed `$or` / `$and`, the deny sentinel). Lets explain name an applied
730+
* default as the object's declaration, never as a permission set's policy.
731+
*/
732+
export function compiledObjectDefaultRowScopeOf(node: unknown): RowLevelSecurityPolicy | undefined {
733+
return node !== null && typeof node === 'object' ? OBJECT_DEFAULT_OF_COMPILED_FILTER.get(node) : undefined;
734+
}
735+
715736
/**
716737
* Is this field constraint an emptied membership, and what CONSTANT does it
717738
* evaluate to? `{ $in: [] }` is constant FALSE on every backend ("IN ()
@@ -1017,6 +1038,7 @@ export class RLSCompiler {
10171038
if (comparands.ok) {
10181039
filters.push(comparands.filter);
10191040
POLICY_OF_COMPILED_FILTER.set(comparands.filter, (policy as { name?: string }).name ?? '(unnamed)');
1041+
if (isObjectDefaultRowScopePolicy(policy)) OBJECT_DEFAULT_OF_COMPILED_FILTER.set(comparands.filter, policy);
10201042
} else {
10211043
deniedBy.push({ policy, cause: { reason: 'refused-comparand', detail: comparands.detail } });
10221044
}

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

Lines changed: 59 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -86,6 +86,7 @@ import {
8686
} from './platform-owner-wall-bypass.js';
8787
import { isConfiguredPlatformAdminEmail, resolvePlatformAdminEmails, vetOrganizationClaim, createSecurityCatalogReader, bindSecurityCatalogReader, securityCatalogReaderOf, readDisabledCatalogNames } from '@objectstack/core';
8888
import { isPlatformTenantPolicy, isAuthoredTenantPolicy } from './platform-tenant-policies.js';
89+
import { objectDefaultRowScopePolicy } from './object-default-row-scope.js';
8990
import {
9091
isPlatformOwnershipFloorPolicy,
9192
masterGateCoversOperation,
@@ -8993,7 +8994,26 @@ export class SecurityPlugin implements Plugin {
89938994
}
89948995

89958996
/**
8996-
* Collect all RLS policies from permission sets applicable to the given object/operation.
8997+
* The row-level security policies that apply to `objectName` for
8998+
* `operation`: the one collection every reader composes from — the read
8999+
* door's Layer 1, the by-id pre-image gate, the bulk write filter, the
9000+
* post-image check, `checkAuthoredRowWrite` and explain.
9001+
*
9002+
* [#24164 ruling E′, item 2] When no held set carries a row policy for this
9003+
* object and operation, the object's declared default row scope
9004+
* (`ObjectSchema.defaultRowScope`) applies in its place:
9005+
* - "carries" is this collection's own emptiness, after the ADR-0105 D3
9006+
* admission, `enabled`, the `positions` domain and `'*'` matching, so a
9007+
* held `'*'` policy counts and a held policy for another operation does
9008+
* not (`object-default-row-scope.ts` states the reading);
9009+
* - an authored set policy is used as authored: the default is never added
9010+
* to a non-empty collection;
9011+
* - the default takes the path a held policy takes from the admission on,
9012+
* so its `using` / `check` compile, and fail closed, exactly as an
9013+
* authored policy's do;
9014+
* - a superuser-bypass principal never reaches this method (the bypass is
9015+
* decided by the caller, before the collection), and an object that
9016+
* declares no default collects exactly what it collected before.
89979017
*/
89989018
private collectRLSPolicies(
89999019
permissionSets: PermissionSet[],
@@ -9013,28 +9033,48 @@ export class SecurityPlugin implements Plugin {
90139033
// filter, the post-image check, `checkAuthoredRowWrite`, explain — sees
90149034
// the same list, because this is the one place they all collect from.
90159035
for (const policy of withOwnershipFloorAlternates(ps.rowLevelSecurity, floorAlternates)) {
9016-
// [ADR-0105 D3] When org isolation is NOT active, strip the tenant
9017-
// policies the PLATFORM itself ships — there is no meaningful active
9018-
// organization to compare against, so they would match zero rows (or
9019-
// be dropped by the field-existence safety net) for no benefit.
9020-
//
9021-
// Provenance, not pattern-matching (finding F1): the former substring
9022-
// test on `current_user.organization_id` also swallowed app-authored
9023-
// policies, silently unenforcing a declared security property. An
9024-
// authored policy now always reaches the compiler and fails closed
9025-
// there, where the operator can see it.
9026-
if (!this.orgScopingEnabled && isPlatformTenantPolicy(policy)) {
9027-
continue;
9028-
}
9029-
if (!this.orgScopingEnabled && isAuthoredTenantPolicy(policy)) {
9030-
this.warnAuthoredTenantPolicyOnce(policy, objectName);
9031-
}
9032-
allPolicies.push(policy);
9036+
if (this.admitCollectedPolicy(policy, objectName)) allPolicies.push(policy);
90339037
}
90349038
}
90359039
}
90369040

9037-
return this.rlsCompiler.getApplicablePolicies(objectName, operation, allPolicies, heldPositions);
9041+
const held = this.rlsCompiler.getApplicablePolicies(objectName, operation, allPolicies, heldPositions);
9042+
if (held.length > 0) return held;
9043+
// [#24164 ruling E′] The held sets are silent on this object and
9044+
// operation: the object's own `defaultRowScope`, if it declares one. Read
9045+
// from the registry the engine compiles every find against, only here, on
9046+
// an empty collection (two in-memory map lookups, no I/O).
9047+
const schema = typeof this.ql?.getSchema === 'function' ? this.ql.getSchema(objectName) : null;
9048+
const objectDefault = objectDefaultRowScopePolicy(objectName, schema);
9049+
if (objectDefault === null || !this.admitCollectedPolicy(objectDefault, objectName)) return held;
9050+
return this.rlsCompiler.getApplicablePolicies(objectName, operation, [objectDefault], heldPositions);
9051+
}
9052+
9053+
/**
9054+
* [ADR-0105 D3] Whether one policy enters the collection under this
9055+
* deployment's tenancy posture. When org isolation is NOT active, the tenant
9056+
* policies the PLATFORM itself ships are stripped — there is no meaningful
9057+
* active organization to compare against, so they would match zero rows (or
9058+
* be dropped by the field-existence safety net) for no benefit.
9059+
*
9060+
* Provenance, not pattern-matching (finding F1): the former substring test
9061+
* on `current_user.organization_id` also swallowed app-authored policies,
9062+
* silently unenforcing a declared security property. An authored policy now
9063+
* always reaches the compiler and fails closed there, where the operator can
9064+
* see it.
9065+
*
9066+
* An object's default row scope passes the same test, so a default that
9067+
* spells a shipped tenant policy is stripped exactly as that policy's set
9068+
* copy is (the provenance key is `(object, name, using)`).
9069+
*/
9070+
private admitCollectedPolicy(policy: RowLevelSecurityPolicy, objectName: string): boolean {
9071+
if (!this.orgScopingEnabled && isPlatformTenantPolicy(policy)) {
9072+
return false;
9073+
}
9074+
if (!this.orgScopingEnabled && isAuthoredTenantPolicy(policy)) {
9075+
this.warnAuthoredTenantPolicyOnce(policy, objectName);
9076+
}
9077+
return true;
90389078
}
90399079

90409080
/**

0 commit comments

Comments
 (0)