Skip to content

Commit f875455

Browse files
committed
test: pin the external write gate in the effective permission map and its two builders
Claude-Session: https://claude.ai/code/session_01Utp6CXSTW6WZn81ULyBVdb Co-authored-by: Claude <noreply@anthropic.com>
1 parent a14c198 commit f875455

5 files changed

Lines changed: 201 additions & 2 deletions

File tree

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
---
2+
'@objectstack/core': patch
3+
'@objectstack/objectql': patch
4+
'@objectstack/plugin-security': patch
5+
'@objectstack/plugin-hono-server': patch
6+
---
7+
8+
fix(core,objectql): effective object permissions read the external write gate, so a read-only external object is no longer offered New, Import, Edit or Delete
9+
10+
Clause-②: yes (widening)
11+
Metadata-protocol: none
12+
13+
- **Behaviour.** On an object whose external write gate is closed (ADR-0015 §5.3 Gate 3: a federated datasource, and not both `datasource.external.allowWrites` and `object.external.writable`), every insert, update and delete is refused `403 EXTERNAL_WRITE_FORBIDDEN` for every caller. The effective object-permission map now says so: the entry grants no `allowCreate`, `allowEdit`, `allowDelete` or `allowTransfer`, a `modifyAllRecords` on it is lowered to the `viewAllRecords` read it implies, and `apiOperations` carries no write operation (`create`, `update`, `delete`, `upsert`, `bulk`, `import`, `restore`, `purge`). Read and export are unchanged. Both consumers move together: `/auth/me/permissions` (the console hides those doors with no client change) and `ISecurityService.getEffectiveObjectPermissions`, so `current_user.can(object, 'create' | 'edit' | 'delete' | 'transfer')` now answers `false` on such an object, as the write itself always did.
14+
- **`@objectstack/objectql`: `ObjectQL.isExternalWriteForbidden(objectName)`**, the gate's verdict as a read-only question. The write gate (`assertWriteAllowed`) reads the same verdict, so the two cannot disagree.
15+
- **`@objectstack/core`: `engineExternalWriteForbidden(engine)`** (the accessor over an engine, asked when the member is present) and the optional `isExternalWriteForbidden` accessor on `EffectiveObjectPermissionsSchemaSource`; `annotateEffectiveApiOperations` takes the same predicate as an optional third argument. A caller that hands over neither gets the map it got before.

‎packages/core/src/security/effective-object-permissions.test.ts‎

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { objectPermissionGrants } from '@objectstack/spec/security';
1818
import {
1919
buildEffectiveFieldPermissions,
2020
buildEffectiveObjectPermissions,
21+
engineExternalWriteForbidden,
2122
fieldPermissionVote,
2223
holdsSuperuserBypass,
2324
registryObjectPackageDisabled,
@@ -474,6 +475,86 @@ describe('[#20135] apiOperations says what the REST door serves', () => {
474475
});
475476
});
476477

478+
describe('[#30370] an object whose external write gate is closed grants no write', () => {
479+
const SCHEMAS: Record<string, any> = {
480+
customer: { name: 'customer', datasource: 'showcase_external' },
481+
order: { name: 'order', datasource: 'showcase_external', enable: { apiMethods: ['get', 'list', 'create', 'update'] } },
482+
lead: { name: 'lead' },
483+
};
484+
const source = (forbidden: (name: string) => boolean = (name) => name === 'customer' || name === 'order') => ({
485+
allSchemas: () => Object.values(SCHEMAS),
486+
schemaOf: (name: string) => SCHEMAS[name],
487+
isExternalWriteForbidden: forbidden,
488+
});
489+
const WRITE_OPERATIONS = ['create', 'update', 'delete', 'upsert', 'bulk', 'import', 'restore', 'purge'];
490+
const VERBS = ['allowCreate', 'allowEdit', 'allowDelete', 'allowTransfer'] as const;
491+
492+
it('an explicit grant, a plain wildcard and a super-user wildcard all lose every write verb, and keep read and export', () => {
493+
for (const sets of [
494+
[{ objects: { customer: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, allowTransfer: true, allowExport: true }, lead: { allowRead: true, allowCreate: true } } }],
495+
[{ objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, allowExport: true } } }],
496+
[{ objects: { '*': { allowRead: true, allowExport: true, viewAllRecords: true, modifyAllRecords: true } } }],
497+
]) {
498+
const map: any = buildEffectiveObjectPermissions(sets, source());
499+
const label = JSON.stringify(sets);
500+
for (const verb of VERBS) expect(objectPermissionGrants(map.customer, verb), `${label} ${verb}`).toBe(false);
501+
expect(objectPermissionGrants(map.customer, 'allowRead'), label).toBe(true);
502+
expect(objectPermissionGrants(map.customer, 'allowExport'), label).toBe(true);
503+
// The read operations stay served, export included; no write operation is.
504+
expect(map.customer.apiOperations, label).toEqual(['get', 'list', 'aggregate', 'search', 'export']);
505+
// An object on a managed datasource keeps exactly what it was granted.
506+
const { isExternalWriteForbidden: _drop, ...without } = source();
507+
expect(map.lead, label).toEqual((buildEffectiveObjectPermissions(sets, without) as any).lead);
508+
expect(objectPermissionGrants(map.lead, 'allowCreate') || objectPermissionGrants(map.lead, 'allowEdit'), label).toBe(true);
509+
}
510+
});
511+
512+
it('modifyAllRecords on the object is lowered to the read it implies, so can() answers no write and the same read', () => {
513+
const map: any = buildEffectiveObjectPermissions(
514+
[{ objects: { customer: { modifyAllRecords: true } } }],
515+
source(),
516+
);
517+
expect(map.customer.modifyAllRecords).toBe(false);
518+
expect(map.customer.viewAllRecords).toBe(true);
519+
expect(objectPermissionGrants(map.customer, 'allowRead')).toBe(true);
520+
for (const verb of VERBS) expect(objectPermissionGrants(map.customer, verb), verb).toBe(false);
521+
});
522+
523+
it('an object that already narrows its operations is served its narrowed reads only', () => {
524+
const map: any = buildEffectiveObjectPermissions([{ objects: { order: { allowRead: true, allowCreate: true } } }], source());
525+
expect(map.order.apiOperations).toEqual(['get', 'list', 'aggregate', 'search']);
526+
for (const op of WRITE_OPERATIONS) expect(map.order.apiOperations).not.toContain(op);
527+
});
528+
529+
it('an open gate, or no accessor, leaves the map exactly as before', () => {
530+
const sets = [{ objects: { '*': { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, allowExport: true } } }];
531+
const { isExternalWriteForbidden: _drop, ...without } = source();
532+
const before = JSON.stringify(buildEffectiveObjectPermissions(sets, without));
533+
expect(JSON.stringify(buildEffectiveObjectPermissions(sets, source(() => false)))).toBe(before);
534+
expect((JSON.parse(before) as any).customer).toMatchObject({ allowCreate: true, allowEdit: true, allowDelete: true });
535+
});
536+
537+
it('a predicate that throws is reported and clamps nothing — never half the map', () => {
538+
const sets = [{ objects: { customer: { allowRead: true, allowEdit: true }, order: { allowRead: true, allowEdit: true } } }];
539+
const warnings: string[] = [];
540+
const map: any = buildEffectiveObjectPermissions(sets, {
541+
...source((name) => { if (name === 'order') throw new Error('registry offline'); return true; }),
542+
logger: { warn: (message) => warnings.push(message) },
543+
});
544+
expect(map.customer.allowEdit).toBe(true);
545+
expect(map.order.allowEdit).toBe(true);
546+
expect(warnings).toEqual(['[effective-permissions] external write gate read failed']);
547+
});
548+
549+
it('engineExternalWriteForbidden asks the engine\'s own verdict, and an engine without it forbids nothing', () => {
550+
const engine = { isExternalWriteForbidden(name: string) { return this === engine && name === 'customer'; } };
551+
expect(engineExternalWriteForbidden(engine)('customer')).toBe(true);
552+
expect(engineExternalWriteForbidden(engine)('lead')).toBe(false);
553+
expect(engineExternalWriteForbidden({})('customer')).toBe(false);
554+
expect(engineExternalWriteForbidden(undefined)('customer')).toBe(false);
555+
});
556+
});
557+
477558
// ── [#25866 / ruling of record 6408558941] A field permission entry's row
478559
// condition (`when`): the ONE vote per verdict, and the row-blind merge behind
479560
// `/auth/me/permissions`' `fields` slot.

‎packages/objectql/src/external-write-gate.test.ts‎

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,52 @@ describe('write gate (ADR-0015 Gate 3)', () => {
140140
});
141141
});
142142

143+
/**
144+
* [#30370] `isExternalWriteForbidden` is the gate's own verdict: the
145+
* effective-permission map reads it to withhold the writes the gate refuses,
146+
* so over every case of the double opt-in it must answer exactly what the
147+
* write itself meets.
148+
*/
149+
describe('[#30370] isExternalWriteForbidden agrees with the write gate', () => {
150+
/** What an insert, an update and a delete each meet: the refusal envelope, or none. */
151+
async function refusals(engine: ObjectQL, object: string) {
152+
const meet = (p: Promise<unknown>) =>
153+
p.then(() => null, (err: any) => (err?.code === 'EXTERNAL_WRITE_FORBIDDEN' ? { code: err.code, status: err.status } : null));
154+
return [
155+
await meet(engine.insert(object, { order_id: 'o1' })),
156+
await meet(engine.update(object, { id: 'x', amount: 1 })),
157+
await meet(engine.delete(object, { where: { id: 'x' } } as any)),
158+
];
159+
}
160+
161+
const CASES: Array<{ label: string; opts: Parameters<typeof makeEngine>[0]; forbidden: boolean }> = [
162+
{ label: 'external, neither opts in', opts: { dsAllowWrites: false, objWritable: false }, forbidden: true },
163+
{ label: 'external, only the datasource opts in', opts: { dsAllowWrites: true, objWritable: false }, forbidden: true },
164+
{ label: 'external, only the object opts in', opts: { dsAllowWrites: false, objWritable: true }, forbidden: true },
165+
{ label: 'validate-only, neither opts in', opts: { dsSchemaMode: 'validate-only' }, forbidden: true },
166+
{ label: 'external, the full double opt-in', opts: { dsAllowWrites: true, objWritable: true }, forbidden: false },
167+
{ label: 'managed datasource', opts: { dsSchemaMode: 'managed' }, forbidden: false },
168+
];
169+
170+
for (const { label, opts, forbidden } of CASES) {
171+
it(`${label}: verdict ${forbidden}, and every write meets it`, async () => {
172+
const engine = makeEngine(opts);
173+
expect(engine.isExternalWriteForbidden('wh_order')).toBe(forbidden);
174+
const met = await refusals(engine, 'wh_order');
175+
for (const refusal of met) {
176+
expect(refusal).toEqual(forbidden ? { code: 'EXTERNAL_WRITE_FORBIDDEN', status: 403 } : null);
177+
}
178+
});
179+
}
180+
181+
it('an object on the default datasource, and an unknown object, are not forbidden', () => {
182+
const engine = makeEngine({});
183+
engine.registerApp({ id: 'local_pkg', name: 'Local', objects: [{ name: 'task', fields: { title: { type: 'text' } } }] } as any);
184+
expect(engine.isExternalWriteForbidden('task')).toBe(false);
185+
expect(engine.isExternalWriteForbidden('no_such_object')).toBe(false);
186+
});
187+
});
188+
143189
describe('engine.introspectDatasource (ADR-0015)', () => {
144190
it('delegates to the named driver introspectSchema()', async () => {
145191
const engine = new ObjectQL();

‎packages/plugins/plugin-hono-server/src/current-user-endpoints-effective-objects.test.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@
1717

1818
import { describe, it, expect } from 'vitest';
1919
import { Hono } from 'hono';
20-
import { buildEffectiveObjectPermissions, registryObjectPackageDisabled } from '@objectstack/core';
20+
import { buildEffectiveObjectPermissions, engineExternalWriteForbidden, registryObjectPackageDisabled } from '@objectstack/core';
2121
import { registerCurrentUserEndpoints } from './current-user-endpoints';
2222

2323
const ME_PERMISSIONS = '/api/v1/auth/me/permissions';
@@ -53,6 +53,9 @@ const SCHEMAS: Record<string, any> = {
5353
/** [#28877] Objects whose owning package the registry reports disabled — empty but in one case. */
5454
const DISABLED = new Set<string>();
5555

56+
/** [#30370] Objects whose external write gate the engine reports closed — empty but in one case. */
57+
const READ_ONLY_EXTERNAL = new Set<string>();
58+
5659
const ql = {
5760
find: async () => [],
5861
registry: {
@@ -61,6 +64,7 @@ const ql = {
6164
isObjectPackageDisabled: (name: string) => DISABLED.has(name),
6265
},
6366
getSchema: (name: string) => SCHEMAS[name],
67+
isExternalWriteForbidden: (name: string) => READ_ONLY_EXTERNAL.has(name),
6468
};
6569

6670
function mount(resolved: unknown[] = RESOLVED) {
@@ -197,6 +201,32 @@ describe('[#18783] /auth/me/permissions `objects` is the one effective-map funct
197201
expect(again.objects.deal).toMatchObject({ allowEdit: true });
198202
});
199203

204+
it('[#30370] serves a read-only external object no write grant and no write operation — the same bytes', async () => {
205+
READ_ONLY_EXTERNAL.add('deal');
206+
try {
207+
const body: any = await (await mount().request(`http://localhost${ME_PERMISSIONS}`)).json();
208+
const expected = buildEffectiveObjectPermissions(RESOLVED, {
209+
allSchemas: () => ql.registry.getAllObjects(),
210+
schemaOf: (name) => ql.getSchema(name),
211+
isObjectPackageDisabled: registryObjectPackageDisabled(ql.registry),
212+
isExternalWriteForbidden: engineExternalWriteForbidden(ql),
213+
});
214+
expect(JSON.stringify(body.objects)).toBe(JSON.stringify(expected));
215+
// The super-user's wildcard would grant every write on `deal`; the gate refuses each one.
216+
expect(body.objects.deal).toMatchObject({ allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false, allowTransfer: false });
217+
for (const op of ['create', 'update', 'delete', 'upsert', 'bulk', 'import']) {
218+
expect(body.objects.deal.apiOperations, op).not.toContain(op);
219+
}
220+
expect(body.objects.deal.apiOperations).toEqual(expect.arrayContaining(['get', 'list']));
221+
} finally {
222+
READ_ONLY_EXTERNAL.clear();
223+
}
224+
// Gate open again: the write is back on the next request.
225+
const again: any = await (await mount().request(`http://localhost${ME_PERMISSIONS}`)).json();
226+
expect(again.objects.deal).toMatchObject({ allowCreate: true, allowEdit: true });
227+
expect(again.objects.deal.apiOperations).toEqual(expect.arrayContaining(['create', 'update', 'delete', 'import']));
228+
});
229+
200230
it('keeps the rest of the envelope on its own merges', async () => {
201231
const body: any = await (await mount().request(`http://localhost${ME_PERMISSIONS}`)).json();
202232
expect(body.permissionSets).toEqual(['ops_admin', 'sales']);

‎packages/plugins/plugin-security/src/get-effective-object-permissions.test.ts‎

Lines changed: 28 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
*/
3030

3131
import { describe, it, expect, vi } from 'vitest';
32-
import { buildEffectiveObjectPermissions, registryObjectPackageDisabled } from '@objectstack/core';
32+
import { buildEffectiveObjectPermissions, engineExternalWriteForbidden, registryObjectPackageDisabled } from '@objectstack/core';
3333
import { ExpressionEngine, toEvalPermissions } from '@objectstack/formula';
3434
import { SysAttachment, SysMember, SysSecret, SysUser, SysUserPreference } from '@objectstack/platform-objects';
3535
import type { ISecurityService } from '@objectstack/spec/contracts';
@@ -108,6 +108,8 @@ function bootPlugin(
108108
dbRows?: Array<Record<string, unknown>>; engineSeam?: boolean; schemas?: Record<string, any>;
109109
/** [#28877] Objects whose owning package the registry reports disabled. */
110110
disabledObjects?: string[];
111+
/** [#30370] Objects whose external write gate the engine reports closed. */
112+
readOnlyExternal?: string[];
111113
} = {},
112114
) {
113115
const dbRows = opts.dbRows ?? [];
@@ -140,6 +142,7 @@ function bootPlugin(
140142
isObjectPackageDisabled: (name: string) => (opts.disabledObjects ?? []).includes(name),
141143
},
142144
getSchema: (name: string) => schemas[name] ?? null,
145+
isExternalWriteForbidden: (name: string) => (opts.readOnlyExternal ?? []).includes(name),
143146
// No table answers here: every set is the catalog's (above).
144147
find: async () => [],
145148
};
@@ -177,6 +180,7 @@ function endpointObjects(sets: unknown, ql: any) {
177180
allSchemas: () => ql.registry.getAllObjects(),
178181
schemaOf: (name) => ql.getSchema(name),
179182
isObjectPackageDisabled: registryObjectPackageDisabled(ql.registry),
183+
isExternalWriteForbidden: engineExternalWriteForbidden(ql),
180184
});
181185
}
182186

@@ -238,6 +242,29 @@ describe('[#18783] getEffectiveObjectPermissions — reachable, and the endpoint
238242
expect(admin.sys_member).toMatchObject({ allowRead: true });
239243
});
240244

245+
it('[#30370] a read-only external object grants no write — the same bytes as the endpoint, and can() answers false', async () => {
246+
const { svc, ql } = await locate({ dbRows: [OPS_ADMIN_ROW, SALES_ROW], readOnlyExternal: ['deal'] });
247+
for (const context of [ADMIN, REP]) {
248+
const sets = await svc.resolvePermissionSetsForContext!(context);
249+
const map: any = await svc.getEffectiveObjectPermissions!(context);
250+
expect(JSON.stringify(map), context.userId).toBe(JSON.stringify(endpointObjects(sets, ql)));
251+
for (const verb of ['create', 'edit', 'delete', 'transfer']) {
252+
const answer = ExpressionEngine.evaluate<boolean>(
253+
{ dialect: 'cel', source: `current_user.can('deal', '${verb}')` },
254+
{ user: { id: context.userId }, permissions: toEvalPermissions(map) } as any,
255+
);
256+
expect(answer, `${context.userId} ${verb}`).toMatchObject({ ok: true, value: false });
257+
}
258+
for (const op of ['create', 'update', 'delete', 'upsert', 'bulk', 'import']) {
259+
expect(map.deal.apiOperations, `${context.userId} ${op}`).not.toContain(op);
260+
}
261+
}
262+
// Read stays; and an object on a managed datasource keeps its writes.
263+
const admin: any = await svc.getEffectiveObjectPermissions!(ADMIN);
264+
expect(admin.deal).toMatchObject({ allowRead: true });
265+
expect(admin.report).toMatchObject({ allowEdit: true });
266+
});
267+
241268
it('is frozen at the top level and aliases no permission set', async () => {
242269
const { svc } = await locate({ dbRows: [SALES_ROW] });
243270
const sets: any[] = await svc.resolvePermissionSetsForContext!(REP);

0 commit comments

Comments
 (0)