Skip to content

Commit acd6367

Browse files
committed
feat(plugin-sharing): list the objects a sharing rule can take effect on
GET /api/v1/sharing/shareable-objects answers the objects the save doors admit a sharing rule on (SharingService.sharingRuleObjectRefusal), business objects first, for Setup's sharing-rule object picker. Admitted as the sharing-rule surface admits (manage_sharing, ADR-0111 D6). Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017ihL2f62c1GYk6XzbdtCa4
1 parent 8ef4d30 commit acd6367

5 files changed

Lines changed: 437 additions & 0 deletions

File tree

Lines changed: 199 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,199 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
import {
4+
ANONYMOUS_DENY_CODE,
5+
ANONYMOUS_DENY_MESSAGE,
6+
ANONYMOUS_DENY_STATUS,
7+
evaluateAuthGate,
8+
isApiKeyLifecycleRefusalError,
9+
isAuthzStoreUnavailableError,
10+
resolveRequestExecutionContext,
11+
shouldDenyAnonymous,
12+
type RequestAuthService,
13+
type TenancyServiceResolver,
14+
} from '@objectstack/core';
15+
import type { ErrorCode } from '@objectstack/spec/api';
16+
import type { IHttpRequest, IHttpResponse, IHttpServer } from '@objectstack/spec/contracts';
17+
import type { ExecutionContext } from '@objectstack/spec/kernel';
18+
import { sendError, sendOk, sendServerFault } from '@objectstack/types';
19+
import { SharingRulesNotRunningError, type ShareableObject } from './shareable-objects.js';
20+
21+
/**
22+
* The shareable-objects door: `GET /api/v1/sharing/shareable-objects`. It
23+
* answers the objects a sharing rule can take effect on, for Setup's
24+
* sharing-rule object picker (`shareable-objects.ts` says which objects and in
25+
* what order). It reads and never writes.
26+
*
27+
* ## Why plugin-sharing mounts it
28+
*
29+
* The sharing-rule administration routes (`/api/v1/sharing/rules*`) are
30+
* `@objectstack/rest`'s, served over the `sharingRules` service through a spec
31+
* contract. A list there would need a new member on that contract; this door
32+
* is the plugin's own, read straight off the `SharingRuleService` the plugin
33+
* constructs, at a path no other package serves. It reaches for the
34+
* `http.server` service and registers on `IHttpServer`, as the share-link
35+
* family does; `sharing-route-ledger.ts` records it.
36+
*
37+
* ## Who may ask — the sharing-rule administrators
38+
*
39+
* In order, before anything is read:
40+
*
41+
* 1. **The caller**, resolved by the platform's one request-to-context
42+
* composition (`resolveRequestExecutionContext`) from the request's session
43+
* or API key. A permission store that cannot be read answers its own
44+
* `SERVICE_UNAVAILABLE` / `503`, and an API key its lifecycle refuses its
45+
* own `403` and code: both relayed as declared, never folded into a denial.
46+
* 2. **A held sign-in** (ADR-0069: an expired password, enforced MFA not yet
47+
* enrolled): `403` with the authentication policy's own code.
48+
* 3. **Anonymous** — the platform's one anonymous floor (ADR-0056 D2):
49+
* `UNAUTHENTICATED` / `401`.
50+
* 4. **The request**: the route takes no query parameter, and a request that
51+
* carries one is refused `VALIDATION_ERROR` / `400` naming it (AGENTS.md,
52+
* route rule 5: the closed set here is empty), never ignored.
53+
* 5. **The administrator**: the sharing-rule surface's own admission
54+
* (`SharingRuleService.listShareableObjects` asks the check every verb of
55+
* that surface asks, ADR-0111 D6). A caller it refuses is answered
56+
* `PERMISSION_DENIED` / `403` with its sentence, so the list names nothing
57+
* the caller could not author a rule on.
58+
*
59+
* ## What the door answers
60+
*
61+
* - **Success:** `200` with `{ objects }` (`ShareableObject[]`), business
62+
* objects first.
63+
* - **Sharing rules not running on this kernel** (`enforce: false`, or the
64+
* rule subsystem did not start): `501` / `NOT_IMPLEMENTED`, the answer the
65+
* REST sharing-rule routes give for the same state.
66+
* - **An engine that cannot enumerate its objects** is a fault: `500` /
67+
* `INTERNAL_ERROR` with this door's sentence and the error in the fault log.
68+
* An empty list would read as "no object can take a rule", so it is never
69+
* served in place of the answer.
70+
*/
71+
72+
/** The route the door is mounted at. */
73+
export const SHAREABLE_OBJECTS_ROUTE = '/api/v1/sharing/shareable-objects';
74+
75+
/** What the door is composed over — every service read when a request arrives. */
76+
export interface ShareableObjectsRoutesDeps {
77+
/** The data engine the caller's grants are read through; `undefined` when none is registered. */
78+
getEngine(): unknown;
79+
/** The auth service the caller's session is read through; `undefined` when none is registered. */
80+
getAuth(): RequestAuthService | undefined;
81+
/** How this door reaches the `tenancy` service; `undefined` on a host with no async service accessor. */
82+
tenancy: TenancyServiceResolver | undefined;
83+
/**
84+
* The list, admitted for `context` — `SharingRuleService.listShareableObjects`.
85+
* Throws `PERMISSION_DENIED: …` for a caller the sharing-rule surface refuses,
86+
* and {@link SharingRulesNotRunningError} when no rule service runs.
87+
*/
88+
listShareableObjects(context: ExecutionContext): ShareableObject[];
89+
}
90+
91+
/** Mount the door on `http`. Nothing on `deps` is called until a request arrives. */
92+
export function registerShareableObjectsRoutes(http: IHttpServer, deps: ShareableObjectsRoutesDeps): void {
93+
http.get(SHAREABLE_OBJECTS_ROUTE, (req, res) => handleShareableObjects(req, res, deps));
94+
}
95+
96+
/** The sharing-rule surface's refusal idiom (`PERMISSION_DENIED: <sentence>`), read once. */
97+
const PERMISSION_DENIED_PREFIX = /^PERMISSION_DENIED:\s*/;
98+
99+
async function handleShareableObjects(
100+
req: IHttpRequest,
101+
res: IHttpResponse,
102+
deps: ShareableObjectsRoutesDeps,
103+
): Promise<void> {
104+
// ① The caller.
105+
let context: ExecutionContext | undefined;
106+
try {
107+
context = await resolveCaller(req, deps);
108+
} catch (err) {
109+
if (isAuthzStoreUnavailableError(err) || isApiKeyLifecycleRefusalError(err)) {
110+
sendError(res, err.status, err.code, err.message);
111+
return;
112+
}
113+
sendServerFault(res, 500, 'INTERNAL_ERROR', 'The caller of this request could not be resolved.', err, {
114+
method: 'GET',
115+
path: SHAREABLE_OBJECTS_ROUTE,
116+
});
117+
return;
118+
}
119+
120+
// ② A held sign-in.
121+
const gate = evaluateAuthGate(context, '');
122+
if (gate) {
123+
sendError(res, 403, gate.code as ErrorCode, gate.message);
124+
return;
125+
}
126+
127+
// ③ Anonymous.
128+
if (!context || shouldDenyAnonymous({ userId: context.userId, method: req.method })) {
129+
sendError(res, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE);
130+
return;
131+
}
132+
133+
// ④ The request: the closed query set is empty.
134+
const query = Object.keys(req.query ?? {});
135+
if (query.length > 0) {
136+
sendError(
137+
res,
138+
400,
139+
'VALIDATION_ERROR',
140+
`The shareable objects list takes no query parameter, and this request carries ${query.map((q) => `'${q}'`).join(', ')}. ` +
141+
'Ask for the list with no parameters: it always answers every object a sharing rule can take effect on.',
142+
);
143+
return;
144+
}
145+
146+
// ⑤ The administrator, then the list.
147+
let objects: ShareableObject[];
148+
try {
149+
objects = deps.listShareableObjects(context);
150+
} catch (err) {
151+
const message = err instanceof Error ? err.message : String(err);
152+
if (err instanceof SharingRulesNotRunningError) {
153+
sendError(res, 501, 'NOT_IMPLEMENTED', message);
154+
return;
155+
}
156+
if (PERMISSION_DENIED_PREFIX.test(message)) {
157+
sendError(res, 403, 'PERMISSION_DENIED', message.replace(PERMISSION_DENIED_PREFIX, ''));
158+
return;
159+
}
160+
sendServerFault(res, 500, 'INTERNAL_ERROR', 'The objects a sharing rule can take effect on could not be listed.', err, {
161+
method: 'GET',
162+
path: SHAREABLE_OBJECTS_ROUTE,
163+
});
164+
return;
165+
}
166+
sendOk(res, { objects });
167+
}
168+
169+
/**
170+
* Resolve the caller through the one composition. This door's differences, as
171+
* its named parameters: anonymous fails closed (the door answers its floor);
172+
* the held-sign-in posture is the one the resolver decided for the credential
173+
* that admitted the caller; an API key admits its owner with no session read;
174+
* no locale, bearer or OAuth token is carried — the list is the same in every
175+
* language, and nothing downstream acts as the caller.
176+
*/
177+
async function resolveCaller(req: IHttpRequest, deps: ShareableObjectsRoutesDeps): Promise<ExecutionContext | undefined> {
178+
const headers = new Headers();
179+
for (const [name, value] of Object.entries(req.headers ?? {})) {
180+
if (value == null) continue;
181+
headers.set(name, Array.isArray(value) ? value.join(',') : String(value));
182+
}
183+
return await resolveRequestExecutionContext({
184+
headers,
185+
ql: deps.getEngine(),
186+
authService: deps.getAuth(),
187+
tenancy: deps.tenancy,
188+
anonymous: 'fail-closed',
189+
authGate: 'resolved',
190+
credentials: 'api-key-and-session',
191+
sessionApi: 'optional',
192+
session: 'request',
193+
localization: 'withhold',
194+
requestLocale: undefined,
195+
accessToken: 'withhold',
196+
oauth: undefined,
197+
onAdmission: undefined,
198+
});
199+
}
Lines changed: 111 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,111 @@
1+
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.
2+
3+
/**
4+
* The objects a sharing rule can take effect on — the list behind Setup's
5+
* sharing-rule object picker (the read half of the row-5 ruling on #30209:
6+
* a read-only "objects under record sharing" list, and a picker that offers
7+
* only those).
8+
*
9+
* ## One verdict, never a second copy
10+
*
11+
* An object is listed exactly when the save doors would ACCEPT a rule on it:
12+
* `SharingService.sharingRuleObjectRefusal(object)` answers `null`. That is the
13+
* predicate both save doors already ask (the `sys_sharing_rule` hook guard on
14+
* the `/data` door, and `SharingRuleService.defineRule`), and it reads the
15+
* reconcile's own ADR-0111 D7 inert-grant verdict. So the picker, the save
16+
* doors and the reconcile cannot disagree about which objects a rule works on:
17+
* an object this list leaves out is one a save would refuse with
18+
* `SHARING_NOT_ENABLED`, and an object it lists is one a save admits. The
19+
* predicate is handed in, never re-derived here.
20+
*
21+
* ## Order
22+
*
23+
* Business objects first, then platform (system) objects; inside each group
24+
* by label, then by machine name. A platform object is one the registry marks
25+
* `isSystem`, or one named with the platform's `sys_` prefix (AGENTS.md Prime
26+
* Directive 6: a module prefix is part of the name).
27+
*/
28+
29+
/** One object a sharing rule can take effect on. */
30+
export interface ShareableObject {
31+
/** The object's machine name — the value `sys_sharing_rule.object_name` stores. */
32+
name: string;
33+
/** The object's declared label, or its name when it declares none. */
34+
label: string;
35+
/** `true` for a platform object (`isSystem`, or a `sys_` name); business objects are `false`. */
36+
system: boolean;
37+
}
38+
39+
/** The slice of the data engine this list reads: the registry's object configs. */
40+
export interface ShareableObjectsEngine {
41+
getConfigs?(): Record<string, unknown> | undefined;
42+
}
43+
44+
/**
45+
* Raised when the engine cannot enumerate its objects. An empty list would
46+
* read as "no object can take a sharing rule", which is a different and wrong
47+
* answer, so the caller is told the list could not be read.
48+
*/
49+
export class ShareableObjectsUnavailableError extends Error {
50+
constructor() {
51+
super('The data engine cannot enumerate its objects, so the objects a sharing rule can take effect on cannot be listed.');
52+
this.name = 'ShareableObjectsUnavailableError';
53+
}
54+
}
55+
56+
/**
57+
* Raised when the sharing-rule subsystem is not running on this kernel (record
58+
* sharing configured with `enforce: false`, or the subsystem failed to start).
59+
* No object can take a rule there, and the door says so rather than answering
60+
* an empty list or an unmounted path.
61+
*/
62+
export class SharingRulesNotRunningError extends Error {
63+
constructor() {
64+
super('Sharing rules are not running on this deployment (record-sharing enforcement is off or did not start), so no object can take one.');
65+
this.name = 'SharingRulesNotRunningError';
66+
}
67+
}
68+
69+
interface ObjectConfigShape {
70+
name?: unknown;
71+
label?: unknown;
72+
isSystem?: unknown;
73+
}
74+
75+
function labelOf(name: string, config: ObjectConfigShape): string {
76+
return typeof config.label === 'string' && config.label.trim().length > 0 ? config.label : name;
77+
}
78+
79+
function isPlatformObject(name: string, config: ObjectConfigShape): boolean {
80+
return config.isSystem === true || name.startsWith('sys_');
81+
}
82+
83+
function byGroupThenLabel(a: ShareableObject, b: ShareableObject): number {
84+
if (a.system !== b.system) return a.system ? 1 : -1;
85+
const byLabel = a.label.localeCompare(b.label, 'en', { sensitivity: 'base' });
86+
if (byLabel !== 0) return byLabel;
87+
return a.name < b.name ? -1 : a.name > b.name ? 1 : 0;
88+
}
89+
90+
/**
91+
* Every registered object a sharing rule can take effect on, ordered business
92+
* first. `refusal` is the save doors' own verdict
93+
* (`SharingService.sharingRuleObjectRefusal`): an object is listed when it
94+
* answers `null`.
95+
*/
96+
export function listShareableObjects(
97+
engine: ShareableObjectsEngine,
98+
refusal: (object: string) => string | null,
99+
): ShareableObject[] {
100+
if (typeof engine.getConfigs !== 'function') throw new ShareableObjectsUnavailableError();
101+
const configs = engine.getConfigs();
102+
if (!configs || typeof configs !== 'object') throw new ShareableObjectsUnavailableError();
103+
const listed: ShareableObject[] = [];
104+
for (const [key, raw] of Object.entries(configs)) {
105+
const config: ObjectConfigShape = raw && typeof raw === 'object' ? (raw as ObjectConfigShape) : {};
106+
const name = typeof config.name === 'string' && config.name.length > 0 ? config.name : key;
107+
if (refusal(name) !== null) continue;
108+
listed.push({ name, label: labelOf(name, config), system: isPlatformObject(name, config) });
109+
}
110+
return listed.sort(byGroupThenLabel);
111+
}

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

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import {
2121
// [#23367] The API-key lifecycle policy source, and its branded refusal.
2222
apiKeyLifecyclePolicySourceOf,
2323
isApiKeyLifecycleRefusalError,
24+
type RequestAuthService,
2425
} from '@objectstack/core';
2526
import type { EngineMiddleware, OperationContext } from '@objectstack/objectql';
2627
import type {
@@ -73,6 +74,8 @@ import {
7374
import { SharingRuleService, bindDeclaredRuleNameGuard, bindSharingRuleActivationReconcile } from './sharing-rule-service.js';
7475
import { ShareLinkService } from './share-link-service.js';
7576
import { registerShareLinkRoutes } from './share-link-routes.js';
77+
import { SHAREABLE_OBJECTS_ROUTE, registerShareableObjectsRoutes } from './shareable-objects-routes.js';
78+
import { SharingRulesNotRunningError } from './shareable-objects.js';
7679
import {
7780
bindRuleHooks,
7881
unbindAllRuleHooks,
@@ -639,6 +642,47 @@ export class SharingServicePlugin implements Plugin {
639642
);
640643
};
641644

645+
/**
646+
* [#30209 row 5 B] Mount `GET /api/v1/sharing/shareable-objects`
647+
* (`shareable-objects-routes.ts`, ledger `sharing-route-ledger.ts`). The
648+
* list is `SharingRuleService.listShareableObjects`, read at request time,
649+
* so a rule service that never started answers 501 there instead of the
650+
* path going unmounted. Canonical `http.server` first, the deprecated
651+
* `http-server` alias second, as the share-link mount reads them.
652+
*/
653+
private mountShareableObjectsRoute(ctx: PluginContext): void {
654+
const readServer = (name: string): IHttpServer | null => {
655+
try { return ctx.getService<IHttpServer>(name); } catch { return null; }
656+
};
657+
const http: IHttpServer | null = readServer('http.server') ?? readServer('http-server');
658+
if (!http) {
659+
ctx.logger.warn(
660+
'SharingServicePlugin: no HTTP server — GET ' + SHAREABLE_OBJECTS_ROUTE + ' (the sharing-rule object '
661+
+ 'picker list) not registered. SharingRuleService.listShareableObjects is still reachable via '
662+
+ 'kernel.getService("sharingRules").',
663+
);
664+
return;
665+
}
666+
const optional = <T>(name: string): T | undefined => {
667+
try { return ctx.getService<T>(name); } catch { return undefined; }
668+
};
669+
const kernel = ctx.getKernel?.() as
670+
| { getServiceAsync?: <T>(name: string) => Promise<T> }
671+
| undefined;
672+
registerShareableObjectsRoutes(http, {
673+
getEngine: () => optional<unknown>('objectql'),
674+
getAuth: () => optional<RequestAuthService>('auth'),
675+
tenancy: kernel && typeof kernel.getServiceAsync === 'function'
676+
? () => kernel.getServiceAsync!<TenancyPostureSource>('tenancy')
677+
: undefined,
678+
listShareableObjects: (context) => {
679+
if (!this.ruleService) throw new SharingRulesNotRunningError();
680+
return this.ruleService.listShareableObjects(context);
681+
},
682+
});
683+
ctx.logger.info(`SharingServicePlugin: shareable objects list mounted at GET ${SHAREABLE_OBJECTS_ROUTE}`);
684+
}
685+
642686
async init(ctx: PluginContext): Promise<void> {
643687
// Register sys_record_share via the manifest service.
644688
ctx.getService<{ register(m: any): void }>('manifest').register({
@@ -1182,6 +1226,12 @@ export class SharingServicePlugin implements Plugin {
11821226
} catch (err: any) {
11831227
ctx.logger.warn('SharingServicePlugin: share-link subsystem not started', { error: err?.message });
11841228
}
1229+
1230+
// [#30209 row 5 B] The objects a sharing rule can take effect on, for
1231+
// Setup's sharing-rule object picker. Mounted whenever an HTTP server is
1232+
// present; with no rule service running it answers 501 rather than an
1233+
// unmounted path (see `shareable-objects-routes.ts`).
1234+
this.mountShareableObjectsRoute(ctx);
11851235
});
11861236

11871237
// [#2926 ③] Materialize sharing grants for rows already present at boot.

0 commit comments

Comments
 (0)