Skip to content

Commit a14c198

Browse files
committed
fix(core): effective object permissions read the external write gate
A read-only external object (ADR-0015 Gate 3 closed) is served no write grant and no write operation, so the console stops offering New, Import, Edit and Delete the data plane refuses. objectql gains the public isExternalWriteForbidden verdict that assertWriteAllowed itself reads; both map builders hand it over. Claude-Session: https://claude.ai/code/session_01Utp6CXSTW6WZn81ULyBVdb Co-authored-by: Claude <noreply@anthropic.com>
1 parent 0e4dfbe commit a14c198

6 files changed

Lines changed: 190 additions & 25 deletions

File tree

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

Lines changed: 116 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ import {
3636
resolveEffectiveApiMethods,
3737
effectiveOperationsArray,
3838
canServeApiOperation,
39+
type ApiOperation,
3940
type EnableLike,
4041
} from '@objectstack/spec/data';
4142
import { objectPermissionGrants, type EffectiveObjectPermission } from '@objectstack/spec/security';
@@ -478,10 +479,18 @@ export function seedSuperUserRestrictedObjects(
478479
* Which entries carry the annotation is unchanged in rule: only an
479480
* unrestricted object that keeps its whole closure — every operation served,
480481
* `export` included — gets none.
482+
*
483+
* [#30370] With `isExternalWriteForbidden`, an object whose external write
484+
* gate is closed (ADR-0015 §5.3 Gate 3) is served without every write
485+
* operation ({@link EXTERNAL_WRITE_GATED_OPERATIONS}): the data plane refuses
486+
* each one `403 EXTERNAL_WRITE_FORBIDDEN` whatever the permission sets say,
487+
* and such an object is always annotated, since the client's default-allow
488+
* path would offer every write. Without it, the answer is what it was.
481489
*/
482490
export function annotateEffectiveApiOperations(
483491
objects: Record<string, any>,
484492
schemaOf: (objectName: string) => ApiExposureSchemaLike | undefined,
493+
isExternalWriteForbidden?: (objectName: string) => boolean,
485494
): void {
486495
for (const [obj, acc] of Object.entries(objects) as Array<[string, any]>) {
487496
if (obj === '*' || !acc) continue;
@@ -497,18 +506,86 @@ export function annotateEffectiveApiOperations(
497506
const closure = effectiveOperationsArray(eff);
498507
// [#20135] Only what the door itself admits: `apiEnabled: false` empties
499508
// the set; any other `enable` leaves the closure as it is.
500-
const served = closure.filter((operation) => canServeApiOperation(enable, operation));
509+
// [#30370] And only what the external write gate admits: a closed gate
510+
// refuses every write operation on the data plane.
511+
const writeForbidden = isExternalWriteForbidden?.(obj) === true;
512+
const served = closure.filter((operation) =>
513+
canServeApiOperation(enable, operation)
514+
&& !(writeForbidden && EXTERNAL_WRITE_GATED_OPERATIONS.has(operation)));
501515
// Annotate when the object tightens via `apiMethods`, when the export
502516
// axis removes `export` from an otherwise-open object (so the client
503517
// hides the Export button), OR when the door serves less than the closure
504-
// (an API-disabled object). An unrestricted object with every operation
505-
// still served needs no annotation — the client keeps its default-allow
506-
// path.
518+
// (an API-disabled object, or [#30370] a closed external write gate). An
519+
// unrestricted object with every operation still served needs no
520+
// annotation — the client keeps its default-allow path.
507521
if (eff.mode === 'unrestricted' && userExportAllowed && served.length === closure.length) continue;
508522
acc.apiOperations = served;
509523
}
510524
}
511525

526+
/**
527+
* [#30370] The effective API operations that WRITE a row — every one the
528+
* external write gate (ADR-0015 §5.3 Gate 3, objectql `assertWriteAllowed`)
529+
* refuses on an object whose gate is closed: the three primitives it judges
530+
* (`insert` is `create`), and every derived operation built on them —
531+
* `upsert` (create ∧ update), `bulk` (batched create / update / delete),
532+
* `import` (create ∨ update), and `restore` / `purge`, which never derive
533+
* today but write when they do. The read operations (`get`, `list`,
534+
* `aggregate`, `history`, `search`, `export`) are untouched: the gate judges
535+
* writes only.
536+
*/
537+
const EXTERNAL_WRITE_GATED_OPERATIONS: ReadonlySet<ApiOperation> = new Set<ApiOperation>([
538+
'create', 'update', 'delete', 'upsert', 'bulk', 'import', 'restore', 'purge',
539+
]);
540+
541+
/**
542+
* [#30370] Re-clamp the map by the THIRD server-side enforcement layer
543+
* permission sets do not model: the external write gate (ADR-0015 §5.3
544+
* Gate 3). On an object whose gate is closed, objectql refuses every insert,
545+
* update and delete `403 EXTERNAL_WRITE_FORBIDDEN` for every caller — no
546+
* permission set, super-user bypass included, opens it — so the entry grants
547+
* no write: `allowCreate`, `allowEdit`, `allowDelete` and `allowTransfer`
548+
* (an owner change is an update) are `false`.
549+
*
550+
* `modifyAllRecords` is a write grant too: the spec's `objectPermissionGrants`
551+
* answers edit, delete and transfer `true` on it alone, so an entry keeping it
552+
* would still answer `current_user.can(object, 'edit')` `true`. It is lowered
553+
* to `viewAllRecords`, the read half it implies, so the entry keeps exactly
554+
* the read it had.
555+
*
556+
* An object the map does not mention already grants nothing, and is left out.
557+
*/
558+
function clampExternalReadOnlyWrites(objects: Record<string, any>, forbidden: ReadonlySet<string>): void {
559+
if (forbidden.size === 0) return;
560+
for (const [obj, acc] of Object.entries(objects) as Array<[string, any]>) {
561+
if (obj === '*' || !acc || !forbidden.has(obj)) continue;
562+
acc.allowCreate = false;
563+
acc.allowEdit = false;
564+
acc.allowDelete = false;
565+
acc.allowTransfer = false;
566+
if (acc.modifyAllRecords === true) {
567+
acc.modifyAllRecords = false;
568+
acc.viewAllRecords = true;
569+
}
570+
}
571+
}
572+
573+
/**
574+
* [#30370] The {@link EffectiveObjectPermissionsSchemaSource.isExternalWriteForbidden}
575+
* accessor over an engine: its `isExternalWriteForbidden`, the verdict objectql's
576+
* own write gate (`assertWriteAllowed`) reads before it refuses a write
577+
* `403 EXTERNAL_WRITE_FORBIDDEN`. That member is not on the contract's engine
578+
* view, so it is asked when present; an engine without it forbids nothing.
579+
* Both builders of the map (`/auth/me/permissions` and
580+
* `ISecurityService.getEffectiveObjectPermissions`) hand over this one reading.
581+
*/
582+
export function engineExternalWriteForbidden(engine: unknown): (objectName: string) => boolean {
583+
return (objectName) => {
584+
const predicate = (engine as { isExternalWriteForbidden?: unknown } | null | undefined)?.isExternalWriteForbidden;
585+
return typeof predicate === 'function' && predicate.call(engine, objectName) === true;
586+
};
587+
}
588+
512589
/**
513590
* The schema reads {@link buildEffectiveObjectPermissions} needs, as accessors
514591
* over whatever engine the caller holds. Every accessor is optional and every
@@ -534,6 +611,15 @@ export interface EffectiveObjectPermissionsSchemaSource {
534611
* the map must leave out exactly the objects the data plane refuses.
535612
*/
536613
isObjectPackageDisabled?: (objectName: string) => boolean;
614+
/**
615+
* [#30370] Whether the external write gate (ADR-0015 §5.3 Gate 3) is closed
616+
* on `objectName` — the engine's `isExternalWriteForbidden`, the verdict its
617+
* own `assertWriteAllowed` refuses a write on. Hand over that predicate
618+
* itself ({@link engineExternalWriteForbidden}), never a second reading of
619+
* the datasource definitions: the map must withhold exactly the writes the
620+
* data plane refuses.
621+
*/
622+
isExternalWriteForbidden?: (objectName: string) => boolean;
537623
/** Where a failed seed / annotation pass is reported. */
538624
logger?: { warn?: (message: string, meta?: Record<string, unknown>) => void };
539625
}
@@ -604,8 +690,15 @@ export interface EffectiveObjectPermissionsInputSet {
604690
* not a step, so an entry a super-user set names itself keeps that set's
605691
* explicit answer, and `modifyAllRecords` alone grants no create;
606692
* 5. {@link clampManagedObjectWrites};
607-
* 6. {@link annotateEffectiveApiOperations} — guarded like (2);
608-
* 7. {@link omitDisabledPackageObjects} — [#28877] an object whose owning
693+
* 6. {@link clampExternalReadOnlyWrites} — [#30370] an object whose external
694+
* write gate is closed grants no write, as the data plane refuses every
695+
* one; the verdict is judged for every entry before anything is clamped,
696+
* and a predicate that throws is reported and clamps nothing (guarded
697+
* like (2));
698+
* 7. {@link annotateEffectiveApiOperations} — guarded like (2); [#30370] it
699+
* reads the same verdicts, so a closed gate's object is served no write
700+
* operation;
701+
* 8. {@link omitDisabledPackageObjects} — [#28877] an object whose owning
609702
* package is disabled is left out, as the data plane refuses it; guarded
610703
* like (2).
611704
*
@@ -659,19 +752,33 @@ export function buildEffectiveObjectPermissions(
659752
}
660753
// Make the per-object map reflect the server's ACTUAL effective enforcement
661754
// = permission-set grant ∩ identity write guard (ADR-0057 D10, cited as an
662-
// attribution, #9628): (1) fold each set's `'*'` super-user grant into every
755+
// attribution, #9628) ∩ [#30370] external write gate (ADR-0015 §5.3): (1) fold each set's `'*'` super-user grant into every
663756
// entry that set does not name, so an admin's wildcard is not shadowed by
664757
// another set's explicit deny — [#20134] every bit it grants, `transfer` and
665758
// its own plain bits included; [#20136] per set only, never the merged
666759
// bypass, which would also override the super-user set's OWN narrower entry;
667-
// (2) re-clamp guarded managed objects by their write affordance.
760+
// (2) re-clamp guarded managed objects by their write affordance; (3)
761+
// [#30370] re-clamp objects whose external write gate is closed.
668762
foldSuperUserWildcardGrants(objects, sets);
669763
clampManagedObjectWrites(objects, schemaOf);
764+
// [#30370] Judged in full before anything is clamped, so a predicate that
765+
// throws midway clamps nothing rather than half the map — and the
766+
// annotation below reads these same verdicts, never a second asking.
767+
let externalWriteForbidden: ReadonlySet<string> = new Set();
768+
const isForbidden = source.isExternalWriteForbidden;
769+
if (typeof isForbidden === 'function') {
770+
try {
771+
externalWriteForbidden = new Set(Object.keys(objects).filter((name) => name !== '*' && isForbidden(name) === true));
772+
} catch (e: any) {
773+
source.logger?.warn?.('[effective-permissions] external write gate read failed', { err: e?.message });
774+
}
775+
}
776+
clampExternalReadOnlyWrites(objects, externalWriteForbidden);
670777
// [#3391] Annotate the per-object effective API operation set. Guarded: on
671778
// failure `apiOperations` is simply omitted and a client falls back to its
672779
// default-allow behaviour.
673780
try {
674-
annotateEffectiveApiOperations(objects, schemaOf);
781+
annotateEffectiveApiOperations(objects, schemaOf, (name) => externalWriteForbidden.has(name));
675782
} catch (e: any) {
676783
source.logger?.warn?.('[effective-permissions] apiOperations annotate failed', { err: e?.message });
677784
}

‎packages/core/src/security/index.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -324,6 +324,8 @@ export {
324324
buildEffectiveObjectPermissions,
325325
// [#28877] The map's disabled-package accessor over an engine registry.
326326
registryObjectPackageDisabled,
327+
// [#30370] The map's external-write-gate accessor over an engine.
328+
engineExternalWriteForbidden,
327329
foldWildcardSuperUser,
328330
clampManagedObjectWrites,
329331
seedSuperUserRestrictedObjects,

‎packages/objectql/src/engine-registration.ts‎

Lines changed: 44 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,8 @@
99
* `listDatasourceDefs`, `markDatasourceUnavailable`,
1010
* `clearDatasourceUnavailable`, `getDefaultDriverName`,
1111
* `listUnavailableDatasources`, `assertWriteAllowed` moved out of `engine.ts`
12-
* whole by `scripts/codemod-split-engine.mjs`.
12+
* whole by `scripts/codemod-split-engine.mjs`. `isExternalWriteForbidden`
13+
* (#30370) was written here, beside the gate whose verdict it answers.
1314
*
1415
* A MOVE, not a redesign. {@link RegistrationFacet} is a stateless facet of `ObjectQL`
1516
* (ruling 6624345766): each static method of it is the body of the `ObjectQL`
@@ -493,22 +494,50 @@ export class RegistrationFacet {
493494
* definition) are unaffected.
494495
*/
495496
static assertWriteAllowed(this: Pick<RegistrationHost, '_registry' | 'datasourceDefs'>, objectName: string, operation: 'insert' | 'update' | 'delete'): void {
496-
const object = this._registry.getObject(objectName) as any;
497-
const dsName = object?.datasource;
498-
if (!dsName || dsName === 'default') return;
499-
500-
const ds = this.datasourceDefs.get(dsName);
501-
// No recorded definition, or an explicitly managed one ⇒ allow.
502-
if (!ds || !ds.schemaMode || ds.schemaMode === 'managed') return;
503-
504-
const dsAllows = ds.external?.allowWrites ?? false;
505-
const objAllows = object?.external?.writable ?? false;
506-
if (!(dsAllows && objAllows)) {
497+
const closed = externalWriteGateClosure(this, objectName);
498+
if (closed) {
507499
throw new ExternalWriteForbiddenError(
508-
`Write '${operation}' blocked on object '${objectName}': datasource '${dsName}' is external ` +
509-
`(schemaMode=${ds.schemaMode}). Requires datasource.external.allowWrites=true (got ${dsAllows}) ` +
510-
`AND object.external.writable=true (got ${objAllows}).`,
500+
`Write '${operation}' blocked on object '${objectName}': datasource '${closed.dsName}' is external ` +
501+
`(schemaMode=${closed.schemaMode}). Requires datasource.external.allowWrites=true (got ${closed.dsAllows}) ` +
502+
`AND object.external.writable=true (got ${closed.objAllows}).`,
511503
);
512504
}
513505
}
506+
507+
/** The body of `ObjectQL#isExternalWriteForbidden`; the method's docblock there is its contract. */
508+
static isExternalWriteForbidden(this: Pick<RegistrationHost, '_registry' | 'datasourceDefs'>, objectName: string): boolean {
509+
return externalWriteGateClosure(this, objectName) !== null;
510+
}
511+
}
512+
513+
/**
514+
* [#30370] Gate 3 of ADR-0015 §5.3, judged ONCE: why the external write gate
515+
* is closed on `objectName`, or `null` when it is open. Both
516+
* {@link RegistrationFacet.assertWriteAllowed} (the refusal) and
517+
* {@link RegistrationFacet.isExternalWriteForbidden} (the verdict the
518+
* effective-permission map reads) ask this one function, so the map can never
519+
* offer a write the gate refuses, nor hide one it admits.
520+
*
521+
* Closed exactly when the object sits on a recorded, federated datasource
522+
* (`schemaMode !== 'managed'`) and NOT both the datasource opts in
523+
* (`external.allowWrites`) and the object opts in (`external.writable`).
524+
* Managed datasources (the common case, including the absence of any
525+
* definition) are open.
526+
*/
527+
function externalWriteGateClosure(
528+
host: Pick<RegistrationHost, '_registry' | 'datasourceDefs'>,
529+
objectName: string,
530+
): { dsName: string; schemaMode: string; dsAllows: boolean; objAllows: boolean } | null {
531+
const object = host._registry.getObject(objectName) as any;
532+
const dsName = object?.datasource;
533+
if (!dsName || dsName === 'default') return null;
534+
535+
const ds = host.datasourceDefs.get(dsName);
536+
// No recorded definition, or an explicitly managed one ⇒ allow.
537+
if (!ds || !ds.schemaMode || ds.schemaMode === 'managed') return null;
538+
539+
const dsAllows = ds.external?.allowWrites ?? false;
540+
const objAllows = object?.external?.writable ?? false;
541+
if (dsAllows && objAllows) return null;
542+
return { dsName, schemaMode: ds.schemaMode, dsAllows, objAllows };
514543
}

‎packages/objectql/src/engine.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3162,6 +3162,25 @@ export class ObjectQL implements IObjectQLEngine {
31623162
return RegistrationFacet.assertWriteAllowed.call(registrationHost.of(this), objectName, operation);
31633163
}
31643164

3165+
/**
3166+
* [#30370] Is the external write gate (ADR-0015 §5.3 Gate 3) CLOSED on
3167+
* `objectName`? `true` exactly when every insert / update / delete on it is
3168+
* refused `403 EXTERNAL_WRITE_FORBIDDEN`: the object sits on a federated
3169+
* datasource (`schemaMode !== 'managed'`) and not both
3170+
* `datasource.external.allowWrites` and `object.external.writable` opt in.
3171+
* `false` for a managed datasource, an object with no datasource, and an
3172+
* unknown object (the gate judges none of them).
3173+
*
3174+
* The write gate itself reads this same verdict, so the two can never
3175+
* disagree. A read-only question for the effective-permission map
3176+
* (`buildEffectiveObjectPermissions` in `@objectstack/core`), which must not
3177+
* offer a write the data plane refuses. Holds for every caller alike: no
3178+
* permission set, super-user bypass included, opens a closed gate.
3179+
*/
3180+
isExternalWriteForbidden(objectName: string): boolean {
3181+
return RegistrationFacet.isExternalWriteForbidden.call(registrationHost.of(this), objectName);
3182+
}
3183+
31653184
/**
31663185
* Set the realtime service for publishing data change events.
31673186
* Should be called after kernel resolves the realtime service.

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

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,7 @@ import {
4242
buildEffectiveFieldPermissions,
4343
buildEffectiveObjectPermissions,
4444
registryObjectPackageDisabled,
45+
engineExternalWriteForbidden,
4546
IDataEngine,
4647
resolveLocalizationContext,
4748
resolveRequestExecutionContext,
@@ -1037,6 +1038,10 @@ export function registerCurrentUserEndpoints(
10371038
// [#28877] The data plane's own predicate: a disabled package's
10381039
// objects leave the map, as the data plane refuses them.
10391040
isObjectPackageDisabled: registryObjectPackageDisabled(ql?.registry),
1041+
// [#30370] The external write gate's own verdict: a read-only
1042+
// external object is served no write, as the data plane
1043+
// refuses every one.
1044+
isExternalWriteForbidden: engineExternalWriteForbidden(ql),
10401045
logger: ctx.logger,
10411046
});
10421047
// Spread into a literal ON PURPOSE, here and in the `catch`: the

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
import { AsyncLocalStorage } from 'node:async_hooks';
44
import { declaredHttpStatus } from '@objectstack/types';
5-
import { Plugin, PluginContext, POSTURE_LADDER, buildEffectiveObjectPermissions, registryObjectPackageDisabled } from '@objectstack/core';
5+
import { Plugin, PluginContext, POSTURE_LADDER, buildEffectiveObjectPermissions, engineExternalWriteForbidden, registryObjectPackageDisabled } from '@objectstack/core';
66
import type { EffectiveObjectPermission, PermissionSet, RowLevelSecurityPolicy, TenantLayer0Verdict } from '@objectstack/spec/security';
77
import { describeHighPrivilegeBits } from '@objectstack/spec/security';
88
import type { AnchorBindingContext } from '@objectstack/spec/security';
@@ -3647,6 +3647,9 @@ export class SecurityPlugin implements Plugin {
36473647
// [#28877] The data plane's own predicate, as `/auth/me/permissions` hands
36483648
// it: a disabled package's objects leave the map `can()` reads.
36493649
isObjectPackageDisabled: registryObjectPackageDisabled(ql?.registry),
3650+
// [#30370] The write gate's own verdict, as `/auth/me/permissions` hands
3651+
// it: a read-only external object grants no write `can()` reads.
3652+
isExternalWriteForbidden: engineExternalWriteForbidden(ql),
36503653
logger: this.logger,
36513654
}));
36523655
}

0 commit comments

Comments
 (0)