Skip to content

Commit e8f2903

Browse files
committed
wip: rest route test, client test, docs, changesets
Claude-Session: https://claude.ai/code/session_01WGufzfXsZBPnnuWWQGXm48 Co-authored-by: Claude <noreply@anthropic.com>
1 parent 243bd1a commit e8f2903

11 files changed

Lines changed: 291 additions & 8 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/client': minor
3+
---
4+
5+
feat(client): `data.fieldAccess(object, id)` reads the field projection of one record
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: added
9+
10+
`client.data.fieldAccess(object, id)` calls `GET /data/:object/:id/field-access` and resolves to `GetRecordFieldAccessResponse`: the fields the caller may read, and the fields the write gate admits on an update of that stored row. A field permission whose `when` names only some rows is unlocked on the rows it does not name. A row that is absent or unreadable rejects with the record read's 404.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/rest': minor
3+
---
4+
5+
feat(rest): `GET /data/:object/:id/field-access` serves the field projection of one record
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: added
9+
10+
A record's edit form can ask which fields it may write on THAT record: the route answers `{ success: true, data: { object, recordId, readable, editable } }` (`GetRecordFieldAccessResponseSchema`), with `editable` judged on the stored row by the write gate through the security service's `getRecordFieldAccess`. The record is read first exactly as `GET /data/:object/:id` reads it, so an absent row or one the caller cannot read answers that route's 404 and the projection discloses nothing more. The route takes no query parameter (a located 400 names any). Without a security service that offers the method it answers 501, and `/auth/me/permissions` remains the row-less reader.
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@objectstack/plugin-security': minor
3+
---
4+
5+
feat(plugin-security): `getRecordFieldAccess` — a record's field projection from the write gate's own verdict
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: added
9+
10+
The `security` service answers `getRecordFieldAccess(object, recordId, context)`. It reads the row as the caller reads it (the reader the write gate's pre-image comes from) and asks the field-level write gate itself, `computeForbiddenFieldWrites`, for an update of that row naming every field, over the same permission sets, posture and delegator intersection the gate takes. A field permission whose `when` names only some rows therefore locks the field only on those rows, and the answer cannot disagree with a write of that row. A row that is absent or unreadable answers `null`. `getWritableFields` and every other row-less reader are unchanged and still apply each row-conditioned entry as its lock.
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
---
2+
'@objectstack/spec': minor
3+
---
4+
5+
feat(spec): a record-scoped field projection, judged on the stored row by the write gate
6+
7+
Clause-②: yes (widening)
8+
Metadata-protocol: added
9+
10+
`GetRecordFieldAccessResponseSchema` (`@objectstack/spec/api`) declares the answer of `GET /api/v1/data/{object}/{id}/field-access`: `{ object, recordId, readable, editable }`, the field projection of ONE record. `ISecurityService` declares its source as the optional `getRecordFieldAccess(object, recordId, context)`: `editable` is the write gate's own verdict on an update of the stored row, so a field permission whose `when` names only some rows locks the field only on those rows, and `readable` is the row-blind read projection. `null` means the caller has no row there (absent or unreadable, deliberately the same answer); `undefined` means no answer.
11+
12+
The `FieldPermissionSchema.when` description now names that reader: the row-less readers (`/auth/me/permissions`, the object-wide field projections, the write preview on an update) keep reporting a row-conditioned entry as its lock, and the record-scoped projection judges it on the row. Nothing an author writes changes meaning.

‎content/docs/permissions/field-level-security.mdx‎

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -52,10 +52,19 @@ fields: {
5252
address, a stored row the caller cannot read, a condition that does not
5353
resolve for the request — the entry is applied as its **lock**: no edit
5454
grant on that write, and a WARN line says why.
55-
- **Readers that hold no row** (`/auth/me/permissions`, the writable-field
56-
projections, `os explain`) report a row-conditioned entry as its lock, so
57-
a client never advertises an edit the gate refuses. `os explain` names
58-
each such entry as a row-conditioned lock in its `fls` layer.
55+
- **Readers that hold no row** (`/auth/me/permissions`, the object-wide
56+
writable-field projections, `os explain`) report a row-conditioned entry
57+
as its lock, so a client never advertises an edit the gate refuses.
58+
`os explain` names each such entry as a row-conditioned lock in its `fls`
59+
layer.
60+
- **The record-scoped projection holds the row.**
61+
`GET /api/v1/data/{object}/{id}/field-access` (`client.data.fieldAccess`)
62+
answers the fields the caller may read and the fields it may write on
63+
**that** record, and its `editable` list is the write gate's own verdict on
64+
an update of the stored row. So a lock that applies from a stage onward
65+
disables the field only on the rows its condition names — this is the
66+
answer a record's edit form reads. A row that is absent or that the caller
67+
cannot read answers the record read's `404`.
5968
- **Union without deny is unchanged.** A matched conditioned lock is still
6069
out-voted by another set's unconditioned `editable: true`; an entry
6170
without `when` votes on every row, as before (ADR-0066 ⑧, note of

‎packages/client/src/client.test.ts‎

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -542,6 +542,15 @@ describe('Data actions, email, dataset query, external datasources (#3587 gap cl
542542
expect(JSON.parse(init.body)).toEqual({ overrides: { name: 'Copy of Acme' } });
543543
});
544544

545+
it('[#26594] data.fieldAccess pins GET /data/:object/:id/field-access and unwraps the envelope', async () => {
546+
const access = { object: 'lead', recordId: 'rec 1', readable: ['name'], editable: [] };
547+
const { client, fetchMock } = createMockClient({ success: true, data: access });
548+
await expect(client.data.fieldAccess('lead', 'rec 1')).resolves.toEqual(access);
549+
const [url, init] = fetchMock.mock.calls[0];
550+
expect(String(url)).toBe('http://localhost:3000/api/v1/data/lead/rec%201/field-access');
551+
expect(init?.method ?? 'GET').toBe('GET');
552+
});
553+
545554
it('data.export pins GET /data/:object/export and returns the raw Response', async () => {
546555
const { client, fetchMock } = createMockClient({});
547556
const res = await client.data.export('lead', { format: 'xlsx', limit: 100, filter: { status: 'open' }, orderby: 'name:asc', header: false });

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2154,7 +2154,9 @@ describe('SecurityPlugin', () => {
21542154
const { plugin, harness } = await bootWhen(APPROVED_LOCK, { findOneImpl: () => rowOf(status) });
21552155
const access = await plugin.getRecordFieldAccess('task', 'r1', whenCtx);
21562156
for (const field of whenFields) {
2157-
const admitted = await gateAdmits(harness, { [field]: 'x' });
2157+
// The stored value written back, so no other gate (an ownership
2158+
// change, a move across the condition) answers instead of 2.5.
2159+
const admitted = await gateAdmits(harness, { [field]: (rowOf(status) as any)[field] ?? 'x' });
21582160
expect(access!.editable.includes(field), `${status}.${field}`).toBe(admitted);
21592161
}
21602162
}

‎packages/qa/dogfood/test/record-field-access-when.dogfood.test.ts‎

Lines changed: 80 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,20 @@
11
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
22
//
3-
// A row-conditioned field lock (`FieldPermissionSchema.when`), end to end
4-
// through the real HTTP + security stack: what the console is told about a
5-
// field on ONE record, against what the write gate does with a write of it.
3+
// [#26594 / ruling of record 6457467702] A row-conditioned field lock
4+
// (`FieldPermissionSchema.when`), end to end through the real HTTP + security
5+
// stack: what the console is told about a field on ONE record, against what the
6+
// write gate does with a write of it.
7+
//
8+
// The two `measure` legs are the card's symptom and stay as its record: the
9+
// row-less reader (`/auth/me/permissions`) reports the conditioned entry as its
10+
// lock on every row, while the write gate admits the field on a draft. The rest
11+
// pin the record-scoped projection (`GET /data/:object/:id/field-access`): it
12+
// answers what the gate does, row by row and field by field, and never more
13+
// than the record read discloses.
614

715
import { describe, it, expect, beforeAll, afterAll } from 'vitest';
816
import { bootStack, type VerifyStack } from '@objectstack/verify';
17+
import { GetRecordFieldAccessResponseSchema } from '@objectstack/spec/api';
918
import {
1019
recordFieldAccessFixtureStack,
1120
recordFieldAccessFixtureSecurity,
@@ -21,6 +30,7 @@ describe('a row-conditioned field lock, on the record the form edits', () => {
2130
let memberId: string;
2231
let draftId: string;
2332
let approvedId: string;
33+
let hiddenMemoId: string;
2434

2535
beforeAll(async () => {
2636
stack = await bootStack(recordFieldAccessFixtureStack, { security: recordFieldAccessFixtureSecurity() });
@@ -31,6 +41,8 @@ describe('a row-conditioned field lock, on the record the form edits', () => {
3141
expect(memberId, 'member provisioned').toBeTruthy();
3242
draftId = (await ql.insert('rfa_contract', { title: 'D', status: 'draft' }, { context: SYS })).id;
3343
approvedId = (await ql.insert('rfa_contract', { title: 'A', status: 'approved' }, { context: SYS })).id;
44+
// A private row the member does not own, so cannot read.
45+
hiddenMemoId = (await ql.insert('rfa_memo', { title: 'approved' }, { context: SYS })).id;
3446
}, 180_000);
3547

3648
afterAll(async () => {
@@ -50,4 +62,69 @@ describe('a row-conditioned field lock, on the record the form edits', () => {
5062
const onApproved = await stack.apiAs(memberTok, 'PATCH', `/data/rfa_contract/${approvedId}`, { summary: 'filled' });
5163
expect(onApproved.status).toBe(403);
5264
}, 60_000);
65+
66+
const fieldAccess = async (object: string, id: string, query = '') => {
67+
const res = await stack.apiAs(memberTok, 'GET', `/data/${object}/${id}/field-access${query}`);
68+
return { status: res.status, body: (await res.json().catch(() => undefined)) as any };
69+
};
70+
const stored = async (id: string) => ql.findOne('rfa_contract', { where: { id }, context: SYS });
71+
const FIELDS = ['title', 'status', 'summary', 'ref_no'] as const;
72+
73+
it('the record-scoped projection unlocks the conditioned field on a row the condition does not name', async () => {
74+
const { status, body } = await fieldAccess('rfa_contract', draftId);
75+
expect(status).toBe(200);
76+
expect(body.success).toBe(true);
77+
const access = GetRecordFieldAccessResponseSchema.parse(body.data);
78+
expect(access.object).toBe('rfa_contract');
79+
expect(access.recordId).toBe(draftId);
80+
expect(access.editable).toEqual(expect.arrayContaining(['title', 'status', 'summary']));
81+
// The unconditioned lock stays a lock on every row.
82+
expect(access.editable).not.toContain('ref_no');
83+
expect(access.readable).toEqual(expect.arrayContaining([...FIELDS]));
84+
}, 60_000);
85+
86+
it('and locks it on a row the condition names', async () => {
87+
const { status, body } = await fieldAccess('rfa_contract', approvedId);
88+
expect(status).toBe(200);
89+
const access = GetRecordFieldAccessResponseSchema.parse(body.data);
90+
expect(access.editable).not.toContain('summary');
91+
expect(access.editable).not.toContain('ref_no');
92+
expect(access.editable).toEqual(expect.arrayContaining(['title', 'status']));
93+
}, 60_000);
94+
95+
it('equals the write gate, field by field, on a row each side of the condition (allowed and refused)', async () => {
96+
for (const id of [draftId, approvedId]) {
97+
const access = GetRecordFieldAccessResponseSchema.parse((await fieldAccess('rfa_contract', id)).body.data);
98+
const row: any = await stored(id);
99+
for (const field of FIELDS) {
100+
// Write the stored value back (a placeholder where none is stored), so
101+
// no write moves the row across its own condition.
102+
const value = row[field] ?? 'x';
103+
const res = await stack.apiAs(memberTok, 'PATCH', `/data/rfa_contract/${id}`, { [field]: value });
104+
const admitted = res.status === 200;
105+
if (!admitted) expect(res.status, `${row.status}.${field}: ${await res.clone().text()}`).toBe(403);
106+
expect(access.editable.includes(field), `${row.status}.${field}`).toBe(admitted);
107+
}
108+
}
109+
}, 120_000);
110+
111+
it('a record the caller cannot read answers exactly as the record read does — no projection leaks it', async () => {
112+
for (const id of [hiddenMemoId, 'rfa_no_such_row']) {
113+
const read = await stack.apiAs(memberTok, 'GET', `/data/rfa_memo/${id}`);
114+
const projected = await fieldAccess('rfa_memo', id);
115+
expect(read.status).toBe(404);
116+
expect(projected.status).toBe(read.status);
117+
expect(projected.body).toEqual(await read.json());
118+
}
119+
}, 60_000);
120+
121+
it('the row-less reader still answers as before, and the route takes no query parameter', async () => {
122+
const res = await stack.apiAs(memberTok, 'GET', '/auth/me/permissions');
123+
const body: any = await res.json();
124+
expect(body.fields['rfa_contract.summary']).toEqual({ readable: true, editable: false });
125+
expect(body.fields['rfa_contract.ref_no']).toEqual({ readable: true, editable: false });
126+
const refused = await fieldAccess('rfa_contract', draftId, '?fields=summary');
127+
expect(refused.status).toBe(400);
128+
expect(refused.body?.error?.code).toBe('VALIDATION_ERROR');
129+
}, 60_000);
53130
});
Lines changed: 139 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,139 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* [#26594 / ruling of record 6457467702] `GET /data/:object/:id/field-access`
5+
* — the field projection of ONE record, the answer a record's edit form reads.
6+
*
7+
* What the route owes, each pinned below:
8+
*
9+
* - the record is read FIRST, exactly as `GET /data/:object/:id` reads it, so
10+
* a refusal of that read (404 for an absent or unreadable row, 403) is this
11+
* route's answer too and the projection is never asked;
12+
* - the answer is the security service's `getRecordFieldAccess`, relayed in
13+
* the shared envelope, asked with the caller's object, record and context;
14+
* - a row that leaves the caller's sight between the two reads answers the
15+
* read path's own 404, never an empty projection;
16+
* - no service with the method → a loud 501, never an invented projection;
17+
* - a CLOSED, empty query-parameter set: any name is a located 400 and the
18+
* service is never called.
19+
*
20+
* The end-to-end half — the real security stack judging a `when` on a row each
21+
* side of its condition — is `record-field-access-when.dogfood.test.ts`.
22+
*/
23+
24+
import { describe, it, expect, vi } from 'vitest';
25+
import { RestServer } from './rest-server.js';
26+
import { RECORD_FIELD_ACCESS_PARAMS } from './data-action-routes.js';
27+
import { unknownQueryParamMessage } from './query-allowlist.js';
28+
29+
const TASK = {
30+
name: 'task',
31+
label: 'Task',
32+
fields: {
33+
id: { name: 'id', type: 'text', label: 'ID' },
34+
title: { name: 'title', type: 'text', label: 'Title' },
35+
amount: { name: 'amount', type: 'number', label: 'Amount' },
36+
},
37+
};
38+
const CTX = { userId: 'u1', permissions: ['member_default'] };
39+
const ACCESS = { object: 'task', recordId: 'r1', readable: ['id', 'title', 'amount'], editable: ['title', 'amount'] };
40+
41+
function mockServer() {
42+
const noop = () => { /* routes are driven directly, never through the adapter */ };
43+
return {
44+
get: noop, post: noop, put: noop, delete: noop, patch: noop, use: noop,
45+
listen: async () => { /* never started */ },
46+
close: async () => { /* never started */ },
47+
};
48+
}
49+
50+
function mockRes() {
51+
const res: any = {
52+
statusCode: 200,
53+
header: vi.fn(function (this: any) { return this; }),
54+
setHeader: vi.fn(function (this: any) { return this; }),
55+
json: vi.fn(function (this: any, body: any) { this._body = body; return this; }),
56+
status: vi.fn(function (this: any, code: number) { this.statusCode = code; return this; }),
57+
};
58+
return res;
59+
}
60+
61+
function boot(opts: { getData?: () => Promise<unknown>; security?: unknown } = {}) {
62+
const getData = vi.fn(opts.getData ?? (async () => ({ object: 'task', id: 'r1', record: { id: 'r1' } })));
63+
const protocol: any = {
64+
getDiscovery: vi.fn().mockResolvedValue({
65+
version: 'v0', routes: { data: '', metadata: '', ui: '', auth: '/auth' },
66+
}),
67+
getMetaTypes: vi.fn().mockResolvedValue([]),
68+
getMetaItems: vi.fn().mockResolvedValue({ items: [TASK] }),
69+
getMetaItem: vi.fn().mockResolvedValue({ type: 'object', name: 'task', item: TASK }),
70+
getData,
71+
};
72+
const rest = new RestServer(mockServer() as any, protocol as any, { api: { requireAuth: false } } as any);
73+
(rest as any).resolveExecCtx = async () => CTX;
74+
(rest as any).resolveSecurityService = async () => opts.security;
75+
rest.registerRoutes();
76+
const route = (rest as any).getRoutes().find(
77+
(r: any) => r.method === 'GET' && r.path === '/api/v1/data/:object/:id/field-access',
78+
);
79+
const call = async (query: Record<string, unknown> = {}, params = { object: 'task', id: 'r1' }) => {
80+
if (!route) throw new Error('route not registered: GET /api/v1/data/:object/:id/field-access');
81+
const res = mockRes();
82+
await route.handler({ method: 'GET', params, query, headers: {}, body: {} } as any, res);
83+
return { status: res.statusCode, body: res.json.mock.calls.at(-1)?.[0] };
84+
};
85+
return { getData, call };
86+
}
87+
88+
const recordNotFound = () => Object.assign(new Error('Record r1 not found in task'), {
89+
code: 'RECORD_NOT_FOUND', status: 404, object: 'task',
90+
});
91+
92+
describe('[#26594] GET /data/:object/:id/field-access', () => {
93+
it("relays the service's projection of this record, asked with the caller's object, record and context", async () => {
94+
const getRecordFieldAccess = vi.fn().mockResolvedValue(ACCESS);
95+
const { call, getData } = boot({ security: { getRecordFieldAccess } });
96+
const answer = await call();
97+
expect(answer).toEqual({ status: 200, body: { success: true, data: ACCESS } });
98+
expect(getRecordFieldAccess).toHaveBeenCalledWith('task', 'r1', CTX);
99+
// The record read the GET record route makes, as that route makes it.
100+
expect(getData).toHaveBeenCalledWith({ object: 'task', id: 'r1', context: CTX });
101+
});
102+
103+
it('a record the read path refuses answers that refusal, and the projection is never asked', async () => {
104+
const getRecordFieldAccess = vi.fn().mockResolvedValue(ACCESS);
105+
const { call } = boot({ getData: async () => { throw recordNotFound(); }, security: { getRecordFieldAccess } });
106+
const answer = await call();
107+
expect(answer.status).toBe(404);
108+
expect(answer.body?.error?.code ?? answer.body?.code).toBe('RECORD_NOT_FOUND');
109+
expect(getRecordFieldAccess).not.toHaveBeenCalled();
110+
});
111+
112+
it("a row the service cannot see after the read answers the read path's own 404, not an empty projection", async () => {
113+
const viaService = await boot({ security: { getRecordFieldAccess: vi.fn().mockResolvedValue(null) } }).call();
114+
const viaRead = await boot({ getData: async () => { throw recordNotFound(); }, security: {} }).call();
115+
expect(viaService.status).toBe(404);
116+
expect(viaService).toEqual(viaRead);
117+
});
118+
119+
it('no security service with the method answers a loud 501, never an invented projection', async () => {
120+
for (const security of [undefined, {}]) {
121+
const answer = await boot({ security }).call();
122+
expect(answer.status).toBe(501);
123+
expect(answer.body?.success).toBe(false);
124+
expect(answer.body?.error?.code).toBe('NOT_IMPLEMENTED');
125+
}
126+
});
127+
128+
it('takes no query parameter: a name is a located 400 and the service is never called', async () => {
129+
expect(RECORD_FIELD_ACCESS_PARAMS).toEqual([]);
130+
const getRecordFieldAccess = vi.fn().mockResolvedValue(ACCESS);
131+
const { call, getData } = boot({ security: { getRecordFieldAccess } });
132+
const answer = await call({ fields: 'amount' });
133+
expect(answer.status).toBe(400);
134+
expect(answer.body?.error?.code).toBe('VALIDATION_ERROR');
135+
expect(answer.body?.error?.message).toBe(unknownQueryParamMessage(['fields'], []));
136+
expect(getData).not.toHaveBeenCalled();
137+
expect(getRecordFieldAccess).not.toHaveBeenCalled();
138+
});
139+
});

0 commit comments

Comments
 (0)