Skip to content

Commit 243bd1a

Browse files
committed
wip(spec,plugin-security,rest,client): record-scoped field projection over the write gate's own verdict
Claude-Session: https://claude.ai/code/session_01WGufzfXsZBPnnuWWQGXm48 Co-authored-by: Claude <noreply@anthropic.com>
1 parent c2ad84e commit 243bd1a

11 files changed

Lines changed: 336 additions & 7 deletions

‎packages/client/src/index.ts‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import { QueryAST, SortNode, AggregationNode, isFilterAST, type DroppedFieldsEve
44
import {
55
BatchUpdateRequest,
66
BatchUpdateResponse,
7+
GetRecordFieldAccessResponse,
78
UpdateManyRequest,
89
DeleteManyRequest,
910
BatchOptions,
@@ -7400,6 +7401,25 @@ export class ObjectStackClient {
74007401
return this.unwrapResponse<CloneDataResult<T>>(res);
74017402
},
74027403

7404+
/**
7405+
* [#26594] The field projection of ONE record —
7406+
* `GET /data/:object/:id/field-access`, declared by
7407+
* `GetRecordFieldAccessResponseSchema` (`@objectstack/spec/api`): the
7408+
* fields the caller may read on `object`, and the fields the write gate
7409+
* admits on an update of THIS stored row. A record's edit form reads it, so
7410+
* a field permission whose `when` names only some rows disables the field
7411+
* only on those rows; the row-less `/auth/me/permissions` read keeps
7412+
* reporting such an entry as its lock. A row that is absent or that the
7413+
* caller cannot read rejects with the record read's 404.
7414+
*/
7415+
fieldAccess: async (object: string, id: string): Promise<GetRecordFieldAccessResponse> => {
7416+
const route = this.getRoute('data');
7417+
const res = await this.fetch(
7418+
`${this.baseUrl}${route}/${encodeURIComponent(object)}/${encodeURIComponent(id)}/field-access`,
7419+
);
7420+
return this.unwrapResponse<GetRecordFieldAccessResponse>(res);
7421+
},
7422+
74037423
/**
74047424
* Streaming export (M10.9): CSV / JSON / XLSX file download. Returns the
74057425
* raw `Response` — the body is a file stream (`Content-Disposition`
@@ -8338,6 +8358,7 @@ export type {
83388358
CheckPermissionResponse,
83398359
GetObjectPermissionsResponse,
83408360
GetEffectivePermissionsResponse,
8361+
GetRecordFieldAccessResponse,
83418362
RealtimeConnectRequest,
83428363
RealtimeConnectResponse,
83438364
RealtimeSubscribeRequest,

‎packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,7 @@ const DECLARED_MEMBERS = {
6262
getMetadataReadableFields: 'optional',
6363
getQueryableFields: 'optional',
6464
getWritableFields: 'optional',
65+
getRecordFieldAccess: 'optional',
6566
resolvePermissionSetNames: 'required',
6667
resolvePermissionSetsForContext: 'optional',
6768
getEffectiveObjectPermissions: 'optional',

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

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ export interface FieldReadersHost {
8282
readonly permissionEvaluator: SecurityPlugin['permissionEvaluator'];
8383
readonly ql: SecurityPlugin['ql'];
8484
readonly tenancyPosture: SecurityPlugin['tenancyPosture'];
85+
computeForbiddenFieldWrites: SecurityPlugin['computeForbiddenFieldWrites'];
8586
computeQueryGuardFieldPerms: SecurityPlugin['computeQueryGuardFieldPerms'];
8687
computeReadPartialMaskRules: SecurityPlugin['computeReadPartialMaskRules'];
8788
foldFieldRequiredPermissions: SecurityPlugin['foldFieldRequiredPermissions'];
@@ -133,7 +134,7 @@ export async function computeReadableFields(
133134

134135
/** The body of `SecurityPlugin#resolveProjectionFieldMask`; the method's docblock there is its contract. */
135136
export async function resolveProjectionFieldMask(
136-
this: Pick<FieldReadersHost, 'computeQueryGuardFieldPerms' | 'computeReadPartialMaskRules' | 'foldFieldRequiredPermissions' | 'getObjectFieldNames' | 'metadata' | 'permissionEvaluator' | 'ql' | 'resolveCallerPosture' | 'resolveFallbackPermissionSets' | 'resolvePermissionSetsForContext' | 'tenancyPosture'>,
137+
this: Pick<FieldReadersHost, 'computeForbiddenFieldWrites' | 'computeQueryGuardFieldPerms' | 'computeReadPartialMaskRules' | 'foldFieldRequiredPermissions' | 'getObjectFieldNames' | 'metadata' | 'permissionEvaluator' | 'ql' | 'resolveCallerPosture' | 'resolveFallbackPermissionSets' | 'resolvePermissionSetsForContext' | 'tenancyPosture'>,
137138
object: string,
138139
context: any,
139140
options: { fallbackOnEmptySets: boolean },
@@ -146,6 +147,11 @@ export async function resolveProjectionFieldMask(
146147
readPartialMaskRules: () => Record<string, FieldMaskingRule>;
147148
/** [#20935] The middleware's query-guard map for these sets (computeQueryGuardFieldPerms). */
148149
readQueryGuardPerms: () => Record<string, { readable: boolean; editable: boolean }>;
150+
/**
151+
* [#26594] The write gate's verdict (computeForbiddenFieldWrites) on an
152+
* update of `row` naming every field: the fields it refuses there.
153+
*/
154+
readRowForbiddenWrites: (row: Record<string, unknown>) => Promise<string[]>;
149155
}
150156
> {
151157
const objectName = String(object ?? '');
@@ -225,6 +231,21 @@ export async function resolveProjectionFieldMask(
225231
readQueryGuardPerms: () => this.computeQueryGuardFieldPerms(
226232
objectName, secMeta, permissionSets, delegatorSets,
227233
),
234+
// [#26594 / ruling of record 6457467702] The record-scoped projection's
235+
// edit half is the step 2.5 gate ITSELF, asked over these sets, this
236+
// posture and this delegator's sets, as an update by id of `row` (the
237+
// pre-image, read as the caller reads it) naming every field. The gate
238+
// refuses per field, so the fields it names are exactly the ones a write
239+
// of that row may not touch — a row-conditioned entry judged on `row`,
240+
// the rest as `fieldPerms` above reads them.
241+
readRowForbiddenWrites: (row) => this.computeForbiddenFieldWrites(
242+
objectName,
243+
Object.fromEntries(allFields.map((f) => [f, null])),
244+
secMeta,
245+
permissionSets,
246+
delegatorSets,
247+
{ operation: 'update', context, preImage: async () => row },
248+
),
228249
};
229250
}
230251

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

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -109,13 +109,14 @@ export interface SecurityServiceHost {
109109
getQueryableFields: SecurityPlugin['getQueryableFields'];
110110
getReadFilter: SecurityPlugin['getReadFilter'];
111111
getReadableFields: SecurityPlugin['getReadableFields'];
112+
getRecordFieldAccess: SecurityPlugin['getRecordFieldAccess'];
112113
getWritableFields: SecurityPlugin['getWritableFields'];
113114
resolvePermissionSetsForContext: SecurityPlugin['resolvePermissionSetsForContext'];
114115
}
115116

116117
/** The `security` service registration `SecurityPlugin#start` runs; the comment above its call there is its contract. */
117118
export function registerSecurityService(
118-
this: Pick<SecurityServiceHost, 'acceptedDefaultPermissionSets' | 'canExport' | 'canReadObject' | 'checkAuthoredRowWrite' | 'checkControlledByParentWrite' | 'declareEveryone' | 'delegatedAdminGate' | 'describePositionGrants' | 'explainAccessForCaller' | 'getEffectiveObjectPermissions' | 'getMetadataReadableFields' | 'getObjectSecurityMeta' | 'getQueryableFields' | 'getReadFilter' | 'getReadableFields' | 'getWritableFields' | 'logger' | 'ownershipFloorAlternates' | 'permissionEvaluator' | 'ql' | 'resolvePermissionSetsForContext' | 'tenancyPosture'>,
119+
this: Pick<SecurityServiceHost, 'acceptedDefaultPermissionSets' | 'canExport' | 'canReadObject' | 'checkAuthoredRowWrite' | 'checkControlledByParentWrite' | 'declareEveryone' | 'delegatedAdminGate' | 'describePositionGrants' | 'explainAccessForCaller' | 'getEffectiveObjectPermissions' | 'getMetadataReadableFields' | 'getObjectSecurityMeta' | 'getQueryableFields' | 'getReadFilter' | 'getReadableFields' | 'getRecordFieldAccess' | 'getWritableFields' | 'logger' | 'ownershipFloorAlternates' | 'permissionEvaluator' | 'ql' | 'resolvePermissionSetsForContext' | 'tenancyPosture'>,
119120
ctx: PluginContext,
120121
ql: IObjectQLEngine,
121122
metadata: IMetadataService,
@@ -154,6 +155,12 @@ export function registerSecurityService(
154155
// [#18386] Its write-side twin: the fields step 2.5 would not refuse.
155156
// The import template narrows its columns by it. See getWritableFields.
156157
getWritableFields: (object: string, context?: any) => this.getWritableFields(object, context),
158+
// [#26594] The field projection of ONE record: its edit half is step
159+
// 2.5's own verdict on the stored row, so a row-conditioned lock (`when`)
160+
// disables a field only on the rows it names. A record's edit form reads
161+
// it. See getRecordFieldAccess.
162+
getRecordFieldAccess: (object: string, recordId: string, context?: any) =>
163+
this.getRecordFieldAccess(object, recordId, context),
157164
// [#20935] Its query-side twin: the fields steps 2.5b and 2.9 would not
158165
// refuse as a group key, an aggregate input, a filter or a sort key. A
159166
// field served MASKED is readable and NOT queryable, so a door that

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

Lines changed: 71 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2119,6 +2119,77 @@ describe('SecurityPlugin', () => {
21192119
await expect(plugin.canWriteObject('task', 'update', whenCtx, { name: 'renamed' })).resolves.toBe(true);
21202120
});
21212121

2122+
// [#26594 / ruling of record 6457467702] The record-scoped field projection:
2123+
// its edit half is the step 2.5 gate's own verdict on the stored row, so it
2124+
// must agree with a by-id update of that row, both ways, field by field.
2125+
describe('[#26594] getRecordFieldAccess — the field projection of one record', () => {
2126+
const rowOf = (status: string) => ({ id: 'r1', owner_id: 'u1', name: 'A', amount: 1, status, assigned_to: null });
2127+
const gateAdmits = async (harness: any, data: Record<string, unknown>) => {
2128+
const opCtx: any = { object: 'task', operation: 'update', context: whenCtx, data, options: { where: { id: 'r1' } } };
2129+
return harness.run(opCtx).then(() => true, (e: any) => {
2130+
if (e?.details?.forbiddenFields) return false;
2131+
throw e;
2132+
});
2133+
};
2134+
2135+
it('a row the condition does not name: the conditioned field is editable, and the gate admits its write', async () => {
2136+
const { plugin, harness } = await bootWhen(APPROVED_LOCK, { findOneImpl: () => rowOf('draft') });
2137+
const access = await plugin.getRecordFieldAccess('task', 'r1', whenCtx);
2138+
expect(access).toEqual({ object: 'task', recordId: 'r1', readable: whenFields, editable: whenFields });
2139+
await expect(gateAdmits(harness, { amount: 2 })).resolves.toBe(true);
2140+
// Read as the CALLER, by id — the gate's own pre-image reader.
2141+
expect(harness.findOne).toHaveBeenCalledWith('task', expect.objectContaining({ where: { id: 'r1' }, context: whenCtx }));
2142+
});
2143+
2144+
it('a row the condition names: the field is locked, and the gate refuses its write', async () => {
2145+
const { plugin, harness } = await bootWhen(APPROVED_LOCK, { findOneImpl: () => rowOf('approved') });
2146+
const access = await plugin.getRecordFieldAccess('task', 'r1', whenCtx);
2147+
expect(access?.editable).toEqual(whenFields.filter((f) => f !== 'amount'));
2148+
expect(access?.readable).toEqual(whenFields);
2149+
await expect(gateAdmits(harness, { amount: 2 })).resolves.toBe(false);
2150+
});
2151+
2152+
it('equals the gate verdict for every field, on a row each side of the condition', async () => {
2153+
for (const status of ['draft', 'approved']) {
2154+
const { plugin, harness } = await bootWhen(APPROVED_LOCK, { findOneImpl: () => rowOf(status) });
2155+
const access = await plugin.getRecordFieldAccess('task', 'r1', whenCtx);
2156+
for (const field of whenFields) {
2157+
const admitted = await gateAdmits(harness, { [field]: 'x' });
2158+
expect(access!.editable.includes(field), `${status}.${field}`).toBe(admitted);
2159+
}
2160+
}
2161+
});
2162+
2163+
it('a row that is absent or that the caller cannot read answers null — no projection is served for it', async () => {
2164+
const { plugin } = await bootWhen(APPROVED_LOCK, { findOneImpl: () => null });
2165+
await expect(plugin.getRecordFieldAccess('task', 'r1', whenCtx)).resolves.toBeNull();
2166+
});
2167+
2168+
it('the row-less projection is unchanged: it still reports the conditioned entry as its lock', async () => {
2169+
const { plugin, harness } = await bootWhen(APPROVED_LOCK, { findOneImpl: () => rowOf('draft') });
2170+
await expect(plugin.getWritableFields('task', whenCtx)).resolves.toEqual(whenFields.filter((f) => f !== 'amount'));
2171+
// …and it reads no row to say so.
2172+
expect(harness.findOne).not.toHaveBeenCalled();
2173+
});
2174+
2175+
it('an unresolvable schema is "no answer", and a system context reads every field', async () => {
2176+
const { plugin } = await bootWhen(APPROVED_LOCK, { findOneImpl: () => rowOf('approved') });
2177+
await expect(plugin.getRecordFieldAccess('', 'r1', whenCtx)).resolves.toBeUndefined();
2178+
await expect(plugin.getRecordFieldAccess('task', 'r1', { isSystem: true })).resolves.toEqual({
2179+
object: 'task', recordId: 'r1', readable: whenFields, editable: whenFields,
2180+
});
2181+
});
2182+
2183+
it('is the method the registered security service answers from', async () => {
2184+
const { plugin, harness } = await bootWhen(APPROVED_LOCK, { findOneImpl: () => rowOf('approved') });
2185+
const svc = harness.ctx.registerService.mock.calls.find((c: any[]) => c[0] === 'security')?.[1];
2186+
expect(typeof svc?.getRecordFieldAccess).toBe('function');
2187+
await expect(svc.getRecordFieldAccess('task', 'r1', whenCtx)).resolves.toEqual(
2188+
await plugin.getRecordFieldAccess('task', 'r1', whenCtx),
2189+
);
2190+
});
2191+
});
2192+
21222193
it('[#2982 follow-up] bulk-write predicate guard inspects the CALLER predicate, not injected owner/RLS filters', async () => {
21232194
// The anti-oracle guard (2.9) must reject a caller filtering on an
21242195
// FLS-hidden field, but must NOT reject an owner_id predicate a sibling

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

Lines changed: 62 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2095,7 +2095,7 @@ export class SecurityPlugin implements Plugin {
20952095
const readPermissionEvaluator = () => this.permissionEvaluator;
20962096
const readQl = () => this.ql;
20972097
const readTenancyPosture = () => this.tenancyPosture;
2098-
const host: Pick<SecurityServiceHost, 'acceptedDefaultPermissionSets' | 'canExport' | 'canReadObject' | 'checkAuthoredRowWrite' | 'checkControlledByParentWrite' | 'declareEveryone' | 'delegatedAdminGate' | 'describePositionGrants' | 'explainAccessForCaller' | 'getEffectiveObjectPermissions' | 'getMetadataReadableFields' | 'getObjectSecurityMeta' | 'getQueryableFields' | 'getReadFilter' | 'getReadableFields' | 'getWritableFields' | 'logger' | 'ownershipFloorAlternates' | 'permissionEvaluator' | 'ql' | 'resolvePermissionSetsForContext' | 'tenancyPosture'> = {
2098+
const host: Pick<SecurityServiceHost, 'acceptedDefaultPermissionSets' | 'canExport' | 'canReadObject' | 'checkAuthoredRowWrite' | 'checkControlledByParentWrite' | 'declareEveryone' | 'delegatedAdminGate' | 'describePositionGrants' | 'explainAccessForCaller' | 'getEffectiveObjectPermissions' | 'getMetadataReadableFields' | 'getObjectSecurityMeta' | 'getQueryableFields' | 'getReadFilter' | 'getReadableFields' | 'getRecordFieldAccess' | 'getWritableFields' | 'logger' | 'ownershipFloorAlternates' | 'permissionEvaluator' | 'ql' | 'resolvePermissionSetsForContext' | 'tenancyPosture'> = {
20992099
acceptedDefaultPermissionSets: this.acceptedDefaultPermissionSets,
21002100
canExport: (...a) => this.canExport(...a),
21012101
canReadObject: (...a) => this.canReadObject(...a),
@@ -2111,6 +2111,7 @@ export class SecurityPlugin implements Plugin {
21112111
getQueryableFields: (...a) => this.getQueryableFields(...a),
21122112
getReadFilter: (...a) => this.getReadFilter(...a),
21132113
getReadableFields: (...a) => this.getReadableFields(...a),
2114+
getRecordFieldAccess: (...a) => this.getRecordFieldAccess(...a),
21142115
getWritableFields: (...a) => this.getWritableFields(...a),
21152116
get logger() { return readLogger(); },
21162117
ownershipFloorAlternates: this.ownershipFloorAlternates,
@@ -2969,6 +2970,62 @@ export class SecurityPlugin implements Plugin {
29692970
return mask.allFields.filter((f) => !nonEditable.has(f));
29702971
}
29712972

2973+
/**
2974+
* [#26594 / ruling of record 6457467702] Query surface: the field projection
2975+
* of ONE record — which fields the caller may read on `object`, and which it
2976+
* may write on the stored row `recordId`. The record-scoped twin of
2977+
* {@link getReadableFields} and {@link getWritableFields}, for the one reader
2978+
* that holds a row: a record's edit form.
2979+
*
2980+
* One judge. `editable` is the step 2.5 write gate's own verdict
2981+
* ({@link computeForbiddenFieldWrites}) on an update by id of that row
2982+
* naming every field, over the same sets, posture and delegator
2983+
* intersection the gate takes ({@link resolveProjectionFieldMask}), with the
2984+
* row read as the CALLER reads it — the reader the gate's own pre-image is
2985+
* read by ({@link getCallerPreImage} → {@link readRowById}). So a
2986+
* row-conditioned entry (`FieldPermissionSchema.when`) locks a field only on
2987+
* the rows its condition names, and a field is in `editable` iff a by-id
2988+
* update of that row naming it passes step 2.5. No second evaluator of
2989+
* `when` exists for this answer to drift from.
2990+
*
2991+
* `readable` is {@link getReadableFields}' answer from the same mask: reads
2992+
* are judged row-blind.
2993+
*
2994+
* Never wider than the read path: `null` for a row that is absent or that the
2995+
* caller cannot read — the same no-row read, deliberately indistinguishable
2996+
* — and a read the middleware refuses outright (no read grant) rejects as it
2997+
* does there. `undefined` when the schema cannot be resolved, as on the
2998+
* object-wide projections. A system context reads every field.
2999+
*/
3000+
async getRecordFieldAccess(
3001+
object: string,
3002+
recordId: string,
3003+
context?: any,
3004+
): Promise<{ object: string; recordId: string; readable: string[]; editable: string[] } | null | undefined> {
3005+
const objectName = String(object ?? '');
3006+
const id = String(recordId ?? '');
3007+
const mask = await this.resolveProjectionFieldMask(objectName, context, { fallbackOnEmptySets: false });
3008+
if (mask.kind === 'answer' && mask.fields === undefined) return undefined;
3009+
if (!id) return null;
3010+
const row = await this.readRowById(objectName, id, context);
3011+
if (!row) return null;
3012+
// The read half from the SAME mask, through the read projection's own body.
3013+
const readable = await computeReadableFields.call(
3014+
{ resolveProjectionFieldMask: async () => mask },
3015+
objectName, context, { fallbackOnEmptySets: false },
3016+
);
3017+
if (mask.kind === 'answer') {
3018+
return { object: objectName, recordId: id, readable: readable ?? [], editable: mask.fields ?? [] };
3019+
}
3020+
const forbidden = new Set(await mask.readRowForbiddenWrites(row));
3021+
return {
3022+
object: objectName,
3023+
recordId: id,
3024+
readable: readable ?? [],
3025+
editable: mask.allFields.filter((f) => !forbidden.has(f)),
3026+
};
3027+
}
3028+
29723029
/**
29733030
* [#20935] Query surface: the field names the caller may QUERY ON in
29743031
* `object` — filter, sort, group or aggregate by — the query-side twin of
@@ -3023,14 +3080,17 @@ export class SecurityPlugin implements Plugin {
30233080
readPartialMaskRules: () => Record<string, FieldMaskingRule>;
30243081
/** [#20935] The middleware's query-guard map for these sets (computeQueryGuardFieldPerms). */
30253082
readQueryGuardPerms: () => Record<string, { readable: boolean; editable: boolean }>;
3083+
/** [#26594] The write gate's verdict on an update of `row` naming every field (computeForbiddenFieldWrites). */
3084+
readRowForbiddenWrites: (row: Record<string, unknown>) => Promise<string[]>;
30263085
}
30273086
> {
30283087
// [#25223 cut 9] The body moved to `security-plugin-field-readers.ts` (see `FieldReadersHost`).
30293088
const readMetadata = () => this.metadata;
30303089
const readPermissionEvaluator = () => this.permissionEvaluator;
30313090
const readQl = () => this.ql;
30323091
const readTenancyPosture = () => this.tenancyPosture;
3033-
const host: Pick<FieldReadersHost, 'computeQueryGuardFieldPerms' | 'computeReadPartialMaskRules' | 'foldFieldRequiredPermissions' | 'getObjectFieldNames' | 'metadata' | 'permissionEvaluator' | 'ql' | 'resolveCallerPosture' | 'resolveFallbackPermissionSets' | 'resolvePermissionSetsForContext' | 'tenancyPosture'> = {
3092+
const host: Pick<FieldReadersHost, 'computeForbiddenFieldWrites' | 'computeQueryGuardFieldPerms' | 'computeReadPartialMaskRules' | 'foldFieldRequiredPermissions' | 'getObjectFieldNames' | 'metadata' | 'permissionEvaluator' | 'ql' | 'resolveCallerPosture' | 'resolveFallbackPermissionSets' | 'resolvePermissionSetsForContext' | 'tenancyPosture'> = {
3093+
computeForbiddenFieldWrites: (...a) => this.computeForbiddenFieldWrites(...a),
30343094
computeQueryGuardFieldPerms: (...a) => this.computeQueryGuardFieldPerms(...a),
30353095
computeReadPartialMaskRules: (...a) => this.computeReadPartialMaskRules(...a),
30363096
foldFieldRequiredPermissions: (...a) => this.foldFieldRequiredPermissions(...a),

0 commit comments

Comments
 (0)