From ac9c2e52e6167721e0ec1128f5a9ba059bc065de Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 01:26:32 +0000 Subject: [PATCH 01/10] wip: a kernel serving private objects boots only with an enforcing sharing service Claude-Session: https://claude.ai/code/session_01ASNY8XNef4ywkQio6S9ju4 Co-authored-by: Claude --- packages/plugins/plugin-dev/package.json | 1 + packages/plugins/plugin-dev/src/dev-plugin.ts | 15 + packages/plugins/plugin-security/src/index.ts | 2 + .../src/private-object-sharing-floor.test.ts | 279 ++++++++++++ .../src/private-object-sharing-floor.ts | 130 ++++++ .../src/record-row-write-probe.ts | 4 +- .../plugin-security/src/security-plugin.ts | 7 +- .../src/share-link-tenant-wall.test.ts | 2 +- .../src/in-process-session-read.pin.test.ts | 2 +- .../plugin-sharing/src/share-arm-boot.test.ts | 2 +- .../share-link-enforcement-context.test.ts | 9 +- ...routes.api-key-account-posture.pin.test.ts | 2 +- .../share-link-routes.auth-gate.pin.test.ts | 2 +- ...are-link-tenancy-posture-admission.test.ts | 9 +- .../src/shareable-objects-routes.ts | 4 +- .../plugin-sharing/src/shareable-objects.ts | 4 +- .../plugin-sharing/src/sharing-plugin.ts | 398 +++++++++--------- .../plugin-sharing/src/sharing-service.ts | 8 +- .../share-links-enforcement-context.test.ts | 2 +- pnpm-lock.yaml | 3 + 20 files changed, 652 insertions(+), 233 deletions(-) create mode 100644 packages/plugins/plugin-security/src/private-object-sharing-floor.test.ts create mode 100644 packages/plugins/plugin-security/src/private-object-sharing-floor.ts diff --git a/packages/plugins/plugin-dev/package.json b/packages/plugins/plugin-dev/package.json index 64bb1afb846..a3cb8c6971f 100644 --- a/packages/plugins/plugin-dev/package.json +++ b/packages/plugins/plugin-dev/package.json @@ -33,6 +33,7 @@ "@objectstack/plugin-auth": "workspace:*", "@objectstack/plugin-hono-server": "workspace:*", "@objectstack/plugin-security": "workspace:*", + "@objectstack/plugin-sharing": "workspace:*", "@objectstack/rest": "workspace:*", "@objectstack/runtime": "workspace:*", "@objectstack/service-i18n": "workspace:*", diff --git a/packages/plugins/plugin-dev/src/dev-plugin.ts b/packages/plugins/plugin-dev/src/dev-plugin.ts index a756e4f7864..e0a9c867872 100644 --- a/packages/plugins/plugin-dev/src/dev-plugin.ts +++ b/packages/plugins/plugin-dev/src/dev-plugin.ts @@ -895,6 +895,21 @@ export class DevPlugin implements Plugin { outcome: 'skipping security', }); } + // The record-sharing service, beside the plugin that admits members: a + // kernel serving a private object boots only with it (plugin-security's + // sharing floor refuses the boot otherwise). + try { + const { SharingServicePlugin } = await import('@objectstack/plugin-sharing') as any; + this.childPlugins.push(new SharingServicePlugin()); + ctx.logger.info(' ✔ Sharing plugin enabled (record sharing for private objects)'); + } catch (err) { + reportOptionalLoadFailure(ctx, err, { + packages: ['@objectstack/plugin-sharing'], + absent: ' ℹ @objectstack/plugin-sharing not installed — skipping record sharing', + absentLevel: 'warn', + outcome: 'skipping record sharing', + }); + } } // 6. Hono HTTP Server diff --git a/packages/plugins/plugin-security/src/index.ts b/packages/plugins/plugin-security/src/index.ts index 9765d8d3a26..a8330478fb0 100644 --- a/packages/plugins/plugin-security/src/index.ts +++ b/packages/plugins/plugin-security/src/index.ts @@ -8,6 +8,8 @@ */ export { SecurityPlugin } from './security-plugin.js'; +// The boot refusal for a kernel that serves a private object without an enforcing record-sharing service. +export { PrivateObjectsWithoutSharingError } from './private-object-sharing-floor.js'; // [#33132] The shape of `SecurityPluginOptions.platformBaselineOverrides`, for a host that declares one. export type { PlatformBaselineOverride, PlatformBaselineOverrides } from './platform-baseline-sets.js'; export { PermissionEvaluator } from './permission-evaluator.js'; diff --git a/packages/plugins/plugin-security/src/private-object-sharing-floor.test.ts b/packages/plugins/plugin-security/src/private-object-sharing-floor.test.ts new file mode 100644 index 00000000000..5a15b15b537 --- /dev/null +++ b/packages/plugins/plugin-security/src/private-object-sharing-floor.test.ts @@ -0,0 +1,279 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * A kernel that serves an object with a private sharing model boots only with + * an enforcing record-sharing service (`private-object-sharing-floor.ts`). + * + * Real kernels, real ObjectQL, a real in-memory SQLite driver, the real + * SecurityPlugin and, where mounted, the real SharingServicePlugin. Each boot + * differs from its control in the one input under test: + * + * - a private object with no sharing service is refused, naming the object; + * the same kernel with the sharing service mounted boots; + * - the served-capability rule under `--preset minimal` mounts no `sharing` + * unless `requires` lists it: a private object there is refused, and listing + * `sharing` boots it; the default preset mounts it unlisted; + * - the judgement is per kernel: a host kernel with no sharing service and no + * private object of its own boots beside environment kernels that carry + * both, and an environment kernel without one is refused even while another + * kernel in the same process has it; + * - objects whose effective model is not private, or that carry no owner + * column, do not require the service. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { + CAPABILITY_PROVIDERS, + ObjectKernel, + resolveServedCapabilities, + type Plugin, + type PluginContext, +} from '@objectstack/core'; +import { ObjectQLPlugin } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SharingServicePlugin } from '@objectstack/plugin-sharing'; +import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; +import { SecurityPlugin } from './security-plugin.js'; +import { PrivateObjectsWithoutSharingError } from './index.js'; +import { + isEnforcingSharingService, + isSharingScopedPrivateObject, +} from './private-object-sharing-floor.js'; + +const OWNER = { type: 'lookup', reference: 'sys_user', label: 'Owner' } as const; + +/** A custom object that declares a private sharing model over its owner column. */ +const PRIVATE_OBJECT = { + name: 'floor_deal', + label: 'Deal', + sharingModel: 'private', + fields: { title: { type: 'text', label: 'Title' }, owner_id: OWNER }, +}; + +/** The same shape with an org-wide readable model. */ +const PUBLIC_OBJECT = { + name: 'floor_note', + label: 'Note', + sharingModel: 'public_read_write', + fields: { title: { type: 'text', label: 'Title' }, owner_id: OWNER }, +}; + +/** Publishes an in-memory SQLite driver the way a datasource plugin does. */ +function sqliteDriverPlugin(): Plugin { + return { + name: 'test.driver.sqlite', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService( + 'driver.default', + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + ); + }, + }; +} + +/** Registers the identity objects SecurityPlugin reads, plus `objects`, under a test package id. */ +function objectsPlugin(objects: unknown[]): Plugin { + return { + name: 'test.sharing-floor.objects', + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql'], + async init(ctx: PluginContext) { + const manifest = ctx.getService<{ register(m: unknown): unknown }>('manifest'); + manifest.register({ + id: 'test.sharing-floor.identity', + namespace: 'sys', + version: '1.0.0', + type: 'plugin', + name: 'Identity stand-in', + objects: [SysUser, SysMember, SysOrganization], + }); + if (objects.length > 0) { + manifest.register({ + id: 'test.sharing-floor.app', + namespace: 'floor', + version: '1.0.0', + type: 'app', + name: 'Floor app', + objects, + }); + } + }, + }; +} + +/** Stands in for a multi-environment host's kernel resolver: a service, nothing more. */ +function kernelResolverPlugin(): Plugin { + return { + name: 'test.sharing-floor.kernel-resolver', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService('kernel-resolver', { resolve: async () => null }); + }, + }; +} + +const kernels: ObjectKernel[] = []; + +afterEach(async () => { + for (const k of kernels.splice(0)) { + try { + await k.shutdown(); + } catch { + /* a refused boot leaves the kernel stopped */ + } + } +}); + +/** Boots one kernel; resolves to the boot's error, or `undefined` when it booted. */ +async function boot(opts: { objects: unknown[]; extra?: Plugin[] }): Promise<{ kernel: ObjectKernel; err: unknown }> { + const kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false } as never); + kernels.push(kernel); + await kernel.use(sqliteDriverPlugin()); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(objectsPlugin(opts.objects)); + for (const p of opts.extra ?? []) await kernel.use(p); + await kernel.use(new SecurityPlugin()); + try { + await kernel.bootstrap(); + return { kernel, err: undefined }; + } catch (err) { + return { kernel, err }; + } +} + +/** + * The providers a served boot mounts for `requires` under `preset`, through the + * same two answers `os serve` reads: which tokens (`resolveServedCapabilities`) + * and which provider each names (`CAPABILITY_PROVIDERS`). Only the `sharing` + * row is constructed: it is the one under test, and the rest of the slate is + * not composed on this kernel. + */ +async function servedSharingProviders(requires: string[], preset: string): Promise { + const { tokens } = resolveServedCapabilities(requires, { preset }); + if (!tokens.includes('sharing')) return []; + const row = CAPABILITY_PROVIDERS.sharing!; + const mod = (await import(/* @vite-ignore */ row.pkg)) as Record Plugin>; + return [new mod[row.export]!({ registerShareLinkRoutes: false })]; +} + +describe('a kernel serving a private object boots only with an enforcing sharing service', () => { + it('refuses a kernel with a private object and no sharing service, naming the object', async () => { + const { kernel, err } = await boot({ objects: [PRIVATE_OBJECT] }); + + expect(err).toBeInstanceOf(PrivateObjectsWithoutSharingError); + expect((err as PrivateObjectsWithoutSharingError).privateObjects).toEqual(['floor_deal']); + expect((err as Error).message).toContain('floor_deal'); + expect((err as Error).message).toContain('@objectstack/plugin-sharing'); + expect(kernel.getState()).toBe('stopped'); + }); + + it('control: the same kernel with the sharing service mounted boots', async () => { + const { kernel, err } = await boot({ + objects: [PRIVATE_OBJECT], + extra: [new SharingServicePlugin({ registerShareLinkRoutes: false })], + }); + + expect(err).toBeUndefined(); + expect(kernel.getState()).toBe('running'); + expect(isEnforcingSharingService(kernel.getService('sharing'))).toBe(true); + }); + + it('control: a kernel whose objects are not private boots without it', async () => { + const { kernel, err } = await boot({ objects: [PUBLIC_OBJECT] }); + + expect(err).toBeUndefined(); + expect(kernel.getState()).toBe('running'); + }); +}); + +describe('--preset minimal: a private object needs `sharing` in requires', () => { + it('refuses under minimal when requires does not list sharing', async () => { + const extra = await servedSharingProviders(['auth'], 'minimal'); + expect(extra).toEqual([]); + const { err } = await boot({ objects: [PRIVATE_OBJECT], extra }); + + expect(err).toBeInstanceOf(PrivateObjectsWithoutSharingError); + expect((err as PrivateObjectsWithoutSharingError).privateObjects).toEqual(['floor_deal']); + }); + + it('control: under minimal, listing sharing in requires boots', async () => { + const extra = await servedSharingProviders(['auth', 'sharing'], 'minimal'); + expect(extra).toHaveLength(1); + const { kernel, err } = await boot({ objects: [PRIVATE_OBJECT], extra }); + + expect(err).toBeUndefined(); + expect(kernel.getState()).toBe('running'); + }); + + it('control: the default preset mounts sharing unlisted and boots', async () => { + const extra = await servedSharingProviders(['auth'], 'default'); + expect(extra).toHaveLength(1); + const { err } = await boot({ objects: [PRIVATE_OBJECT], extra }); + + expect(err).toBeUndefined(); + }); +}); + +describe('the judgement is per serving kernel', () => { + it('a host kernel without sharing boots beside environment kernels that carry it', async () => { + const host = await boot({ objects: [], extra: [kernelResolverPlugin()] }); + const envA = await boot({ + objects: [PRIVATE_OBJECT], + extra: [new SharingServicePlugin({ registerShareLinkRoutes: false })], + }); + const envB = await boot({ + objects: [PRIVATE_OBJECT], + extra: [new SharingServicePlugin({ registerShareLinkRoutes: false })], + }); + + expect(host.err).toBeUndefined(); + expect(host.kernel.getState()).toBe('running'); + expect(() => host.kernel.getService('sharing')).toThrow(); + expect(envA.err).toBeUndefined(); + expect(envB.err).toBeUndefined(); + }); + + it('an environment kernel without sharing is refused while another kernel in the process has it', async () => { + const withSharing = await boot({ + objects: [PRIVATE_OBJECT], + extra: [new SharingServicePlugin({ registerShareLinkRoutes: false })], + }); + const without = await boot({ objects: [PRIVATE_OBJECT] }); + + expect(withSharing.err).toBeUndefined(); + expect(without.err).toBeInstanceOf(PrivateObjectsWithoutSharingError); + }); +}); + +describe('which objects require the sharing service', () => { + const owner = { owner_id: OWNER }; + + it('private by declaration, by an unrecognised value, or by the custom-object default', () => { + expect(isSharingScopedPrivateObject({ name: 'a', sharingModel: 'private', fields: owner })).toBe(true); + expect(isSharingScopedPrivateObject({ name: 'a', security: { sharingModel: 'private' }, fields: owner })).toBe(true); + expect(isSharingScopedPrivateObject({ name: 'a', sharingModel: 'legacy_value', fields: owner })).toBe(true); + expect(isSharingScopedPrivateObject({ name: 'a', fields: owner })).toBe(true); + expect(isSharingScopedPrivateObject({ name: 'sys_task', sharingModel: 'private', fields: owner })).toBe(true); + }); + + it('not when the effective model is open, or the object has no owner column', () => { + for (const sharingModel of ['public_read', 'public_read_write', 'controlled_by_parent']) { + expect(isSharingScopedPrivateObject({ name: 'a', sharingModel, fields: owner }), sharingModel).toBe(false); + } + expect(isSharingScopedPrivateObject({ name: 'sys_thing', fields: owner })).toBe(false); + expect(isSharingScopedPrivateObject({ name: 'a', isSystem: true, fields: owner })).toBe(false); + expect(isSharingScopedPrivateObject({ name: 'a', sharingModel: 'private', fields: { title: {} } })).toBe(false); + expect(isSharingScopedPrivateObject(undefined)).toBe(false); + }); + + it('a sharing service counts only when its middleware is installed', () => { + expect(isEnforcingSharingService({ byIdWriteGateInstalled: true })).toBe(true); + expect(isEnforcingSharingService({ byIdWriteGateInstalled: false })).toBe(false); + expect(isEnforcingSharingService({})).toBe(false); + expect(isEnforcingSharingService(undefined)).toBe(false); + }); +}); diff --git a/packages/plugins/plugin-security/src/private-object-sharing-floor.ts b/packages/plugins/plugin-security/src/private-object-sharing-floor.ts new file mode 100644 index 00000000000..032572c40ad --- /dev/null +++ b/packages/plugins/plugin-security/src/private-object-sharing-floor.ts @@ -0,0 +1,130 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The sharing floor: a kernel that serves an object whose org-wide default is + * `private` boots only with an enforcing record-sharing service. + * + * A `private` sharing model is enforced by the record-sharing service + * (`@objectstack/plugin-sharing`) and the engine middleware it installs. So a + * kernel that admits members through this plugin and registers a private + * object boots only with that middleware installed; otherwise the boot is + * refused, naming the objects and the fix. + * + * ## What it judges, and where + * + * - **Per kernel.** The question is asked of the kernel this plugin is mounted + * on, about the objects that kernel's engine registers and the `sharing` + * service that kernel registers. A host that runs several kernels (one per + * environment) has each one judged on its own composition; a kernel that + * serves no private object is never refused for another kernel's objects. + * - **At `kernel:bootstrapped`.** The sharing service and its middleware are + * installed from a `kernel:ready` handler, whose order against this plugin's + * is not declared; by `kernel:bootstrapped` every `kernel:ready` handler has + * settled, so "not installed" is final (AGENTS.md, startup registry reads). + * A throw there fails `bootstrap()` on both kernels, before + * `kernel:listening` opens any socket. + * - **Only on a kernel that starts this plugin.** A boot that composes it for + * its declarations alone (`os migrate`, which suppresses `start()`) serves no + * member and is not judged. + * + * ## Which objects count + * + * The objects whose rows record sharing scopes for a member: an effective + * org-wide default of `private` (declared `private`, an unrecognised value, or + * no declaration on a non-platform object, ADR-0090 D1) on an object that + * carries the `owner_id` column the scope is written over. The reading is + * plugin-sharing's `effectiveSharingModel`, mirrored here as + * `explain-engine.ts` mirrors it, because this package does not depend on + * plugin-sharing. + * + * ## What "enforcing" means + * + * A `sharing` service whose engine middleware is installed: plugin-sharing + * sets `byIdWriteGateInstalled` on its service in the same step that registers + * the middleware (one middleware serves the read filter and the by-id write + * gate). A service registered without it — an engine with no middleware API — + * does not count. There is no switch that turns this check off. + */ + +import type { PluginContext } from '@objectstack/core'; +import type { IObjectQLEngine } from '@objectstack/spec/contracts'; + +/** The column a private object's read scope is written over. */ +const OWNER_COLUMN = 'owner_id'; + +/** + * Does record sharing scope this object's rows for a member? The effective + * org-wide default is `private` and the object carries the owner column. + */ +export function isSharingScopedPrivateObject(schema: unknown): boolean { + if (!schema || typeof schema !== 'object') return false; + const s = schema as { name?: unknown; isSystem?: unknown; sharingModel?: unknown; security?: { sharingModel?: unknown }; fields?: unknown }; + const fields = s.fields && typeof s.fields === 'object' ? (s.fields as Record) : undefined; + if (!fields || !(OWNER_COLUMN in fields)) return false; + const model = s.sharingModel ?? s.security?.sharingModel; + if (model === 'private') return true; + if (model === 'public_read' || model === 'public_read_write' || model === 'controlled_by_parent') return false; + if (model == null) return !(s.isSystem === true || String(s.name ?? '').startsWith('sys_')); + // An unrecognised stored value fails closed to private (ADR-0090 D4). + return true; +} + +/** Is `service` a record-sharing service whose engine middleware is installed? */ +export function isEnforcingSharingService(service: unknown): boolean { + return Boolean(service) && (service as { byIdWriteGateInstalled?: unknown }).byIdWriteGateInstalled === true; +} + +/** + * The boot refusal for a kernel that serves a private object without an + * enforcing record-sharing service. `privateObjects` names every such object + * the kernel registers. + */ +export class PrivateObjectsWithoutSharingError extends Error { + readonly privateObjects: readonly string[]; + + constructor(privateObjects: readonly string[]) { + super( + 'SecurityPlugin cannot boot: a kernel that serves objects with a private sharing model boots only with ' + + 'an enforcing record-sharing service, and this kernel registers ' + + `${privateObjects.join(', ')} with none. Mount @objectstack/plugin-sharing on this kernel ` + + "(SharingServicePlugin; under `os serve --preset minimal`, list 'sharing' in `requires`). " + + 'On a host that runs one kernel per environment, mount it on each kernel that serves such objects.', + ); + this.name = 'PrivateObjectsWithoutSharingError'; + this.privateObjects = [...privateObjects]; + } +} + +/** + * Run from a `kernel:bootstrapped` handler (see the module header): throws + * {@link PrivateObjectsWithoutSharingError} when this kernel's engine registers + * a private object and this kernel has no enforcing `sharing` service. + */ +export function refusePrivateObjectsWithoutSharing(ctx: PluginContext): void { + let ql: IObjectQLEngine | undefined; + try { + ql = ctx.getService('objectql'); + } catch { + // No engine on this kernel: it serves no object. The security middleware + // reports its own absence at start(). + return; + } + const schemas = ql?.registry?.getAllObjects?.() ?? []; + const privateObjects = [ + ...new Set( + schemas + .filter(isSharingScopedPrivateObject) + .map((schema) => String((schema as { name?: unknown }).name ?? '')) + .filter((name) => name !== ''), + ), + ].sort(); + if (privateObjects.length === 0) return; + let sharing: unknown; + try { + sharing = ctx.getService('sharing'); + } catch { + sharing = undefined; + } + if (isEnforcingSharingService(sharing)) return; + throw new PrivateObjectsWithoutSharingError(privateObjects); +} diff --git a/packages/plugins/plugin-security/src/record-row-write-probe.ts b/packages/plugins/plugin-security/src/record-row-write-probe.ts index ede9832ab66..407d786c82b 100644 --- a/packages/plugins/plugin-security/src/record-row-write-probe.ts +++ b/packages/plugins/plugin-security/src/record-row-write-probe.ts @@ -25,8 +25,8 @@ * through `SharingService.admitsByIdWrite` — the method its middleware * refuses on — with the context exactly as this middleware stamped it for * the next one (the write depth, an external principal's grant). Skipped - * when the deployment runs without that middleware (`enforce: false`), as - * the write skips it. + * when the kernel has no installed sharing middleware, as the write skips + * it. * * ## Why an empty payload * diff --git a/packages/plugins/plugin-security/src/security-plugin.ts b/packages/plugins/plugin-security/src/security-plugin.ts index e16b1e4a2d6..afc4e62af5d 100644 --- a/packages/plugins/plugin-security/src/security-plugin.ts +++ b/packages/plugins/plugin-security/src/security-plugin.ts @@ -43,6 +43,7 @@ import { type DeploymentAcceptance, } from './suggested-audience-bindings.js'; import { refuseAgentCeilingInBaselineOptions } from './agent-ceiling-grant-refusal.js'; +import { refusePrivateObjectsWithoutSharing } from './private-object-sharing-floor.js'; import { RLSCompiler, RLS_DENY_FILTER, policyDeclaresClause } from './rls-compiler.js'; import { andComposeLayers, @@ -1952,6 +1953,10 @@ export class SecurityPlugin implements Plugin { // suppresses `start()`) arms nothing that reads the store, and is not refused. if (typeof (ctx as any).hook === 'function') { (ctx as any).hook('kernel:ready', () => refuseMissingAuthzIdentityObjects(ctx)); + // A kernel serving a private object boots only with an enforcing + // record-sharing service — judged once every `kernel:ready` handler has + // installed what it installs (`private-object-sharing-floor.ts`). + (ctx as any).hook('kernel:bootstrapped', () => refusePrivateObjectsWithoutSharing(ctx)); } // [#10706] Bind the report sink FIRST — above the two bail-outs below. @@ -3445,7 +3450,7 @@ export class SecurityPlugin implements Plugin { * covers and why it writes nothing: `record-row-write-probe.ts`. * * The sharing leg answers as the chain does: no sharing service, or one - * whose middleware is not installed (`enforce: false`), imposes nothing; a + * whose middleware is not installed, imposes nothing; a * service without the method, or a throw, refuses (fail closed). */ private isRecordRowWritable(object: string, recordId: string, context: any): Promise { diff --git a/packages/plugins/plugin-security/src/share-link-tenant-wall.test.ts b/packages/plugins/plugin-security/src/share-link-tenant-wall.test.ts index ffd1dbcf9fb..605da5f2801 100644 --- a/packages/plugins/plugin-security/src/share-link-tenant-wall.test.ts +++ b/packages/plugins/plugin-security/src/share-link-tenant-wall.test.ts @@ -221,7 +221,7 @@ async function groupPostureMint( registerService: vi.fn(), }; - const plugin = new SharingServicePlugin({ enforce: false }); + const plugin = new SharingServicePlugin(); await plugin.start(ctx); for (const handler of hooks['kernel:ready'] ?? []) await handler(); diff --git a/packages/plugins/plugin-sharing/src/in-process-session-read.pin.test.ts b/packages/plugins/plugin-sharing/src/in-process-session-read.pin.test.ts index 0658cfb2199..cd599f79f3f 100644 --- a/packages/plugins/plugin-sharing/src/in-process-session-read.pin.test.ts +++ b/packages/plugins/plugin-sharing/src/in-process-session-read.pin.test.ts @@ -81,7 +81,7 @@ async function listLinks(headers: Record) { registerService: vi.fn(), getKernel: () => kernel, }; - const plugin = new SharingServicePlugin({ enforce: false }); + const plugin = new SharingServicePlugin(); await plugin.start(ctx as unknown as PluginContext); for (const handler of hooks['kernel:ready'] ?? []) await handler(); diff --git a/packages/plugins/plugin-sharing/src/share-arm-boot.test.ts b/packages/plugins/plugin-sharing/src/share-arm-boot.test.ts index e557aaba1d4..ed5cbcc7bce 100644 --- a/packages/plugins/plugin-sharing/src/share-arm-boot.test.ts +++ b/packages/plugins/plugin-sharing/src/share-arm-boot.test.ts @@ -293,7 +293,7 @@ describe('[ADR-0155 ② ruled R1 at boot] the plugin refuses the boot at kernel: registerService: vi.fn(), getKernel: () => kernel, }; - const plugin = new SharingServicePlugin({ enforce: false }); + const plugin = new SharingServicePlugin(); await plugin.start(ctx as unknown as PluginContext); return refusalOf((async () => { for (const event of ['kernel:ready', 'kernel:bootstrapped']) for (const handler of hooks[event] ?? []) await handler(); diff --git a/packages/plugins/plugin-sharing/src/share-link-enforcement-context.test.ts b/packages/plugins/plugin-sharing/src/share-link-enforcement-context.test.ts index 4ea2b59b942..c4ecb07fd0b 100644 --- a/packages/plugins/plugin-sharing/src/share-link-enforcement-context.test.ts +++ b/packages/plugins/plugin-sharing/src/share-link-enforcement-context.test.ts @@ -144,10 +144,9 @@ function makeEngine(tables: Record) { /** * Boot the REAL plugin: the assembly under test is a closure inside its * `kernel:ready` handler, so nothing short of starting the plugin exercises the - * production wiring. `enforce: false` keeps this to the share-link surface — - * the sharing middleware and the rule subsystem are a different card's code and - * would only add noise here (the share-link service is registered in that - * posture too, by design). + * production wiring. The sharing middleware and the rule subsystem start too + * (there is no posture without them); this file asserts the share-link + * surface only. */ async function bootPlugin(opts: { session: () => any; tables: Record }) { const engine = makeEngine(opts.tables); @@ -167,7 +166,7 @@ async function bootPlugin(opts: { session: () => any; tables: Record kernel, }; - const plugin = new SharingServicePlugin({ enforce: false }); + const plugin = new SharingServicePlugin(); await plugin.start(ctx as unknown as PluginContext); for (const handler of hooks['kernel:ready'] ?? []) await handler(); return http; diff --git a/packages/plugins/plugin-sharing/src/share-link-routes.auth-gate.pin.test.ts b/packages/plugins/plugin-sharing/src/share-link-routes.auth-gate.pin.test.ts index 0bad6ae7ee9..087166d53c4 100644 --- a/packages/plugins/plugin-sharing/src/share-link-routes.auth-gate.pin.test.ts +++ b/packages/plugins/plugin-sharing/src/share-link-routes.auth-gate.pin.test.ts @@ -232,7 +232,7 @@ async function bootPlugin(session: () => Session | undefined) { registerService: vi.fn(), getKernel: () => kernel, }; - const plugin = new SharingServicePlugin({ enforce: false }); + const plugin = new SharingServicePlugin(); await plugin.start(ctx as unknown as PluginContext); for (const handler of hooks['kernel:ready'] ?? []) await handler(); return http; diff --git a/packages/plugins/plugin-sharing/src/share-link-tenancy-posture-admission.test.ts b/packages/plugins/plugin-sharing/src/share-link-tenancy-posture-admission.test.ts index 79befb33990..79693dd5f29 100644 --- a/packages/plugins/plugin-sharing/src/share-link-tenancy-posture-admission.test.ts +++ b/packages/plugins/plugin-sharing/src/share-link-tenancy-posture-admission.test.ts @@ -257,10 +257,9 @@ interface Harness { /** * Boot the REAL plugin. The assembly under test is a closure inside its * `kernel:ready` handler, so nothing short of starting the plugin exercises the - * production wiring. `enforce: false` keeps this to the share-link surface — - * the RLS middleware and the rule subsystem are other cards' code and would - * only add noise (the share-link service is registered in that posture too, by - * design). + * production wiring. The sharing middleware and the rule subsystem start too + * (there is no posture without them); this file asserts the share-link + * surface only. */ async function boot(opts: { tenancy: TenancyArm; session?: () => Session | undefined }): Promise { const tables = fixtureTables(); @@ -297,7 +296,7 @@ async function boot(opts: { tenancy: TenancyArm; session?: () => Session | undef getKernel: () => kernel, }; - const plugin = new SharingServicePlugin({ enforce: false }); + const plugin = new SharingServicePlugin(); await plugin.start(ctx as unknown as PluginContext); for (const handler of hooks['kernel:ready'] ?? []) await handler(); diff --git a/packages/plugins/plugin-sharing/src/shareable-objects-routes.ts b/packages/plugins/plugin-sharing/src/shareable-objects-routes.ts index b4f31d4eb49..ca61e257d1a 100644 --- a/packages/plugins/plugin-sharing/src/shareable-objects-routes.ts +++ b/packages/plugins/plugin-sharing/src/shareable-objects-routes.ts @@ -60,8 +60,8 @@ import { SharingRulesNotRunningError, type ShareableObject } from './shareable-o * * - **Success:** `200` with `{ objects }` (`ShareableObject[]`), business * objects first. - * - **Sharing rules not running on this kernel** (`enforce: false`, or the - * rule subsystem did not start): `501` / `NOT_IMPLEMENTED`, the answer the + * - **Sharing rules not running on this kernel** (the rule subsystem did + * not start): `501` / `NOT_IMPLEMENTED`, the answer the * REST sharing-rule routes give for the same state. * - **An engine that cannot enumerate its objects** is a fault: `500` / * `INTERNAL_ERROR` with this door's sentence and the error in the fault log. diff --git a/packages/plugins/plugin-sharing/src/shareable-objects.ts b/packages/plugins/plugin-sharing/src/shareable-objects.ts index 33c1f051f7d..43d5b6a17b4 100644 --- a/packages/plugins/plugin-sharing/src/shareable-objects.ts +++ b/packages/plugins/plugin-sharing/src/shareable-objects.ts @@ -56,8 +56,8 @@ export class ShareableObjectsUnavailableError extends Error { } /** - * Raised when the sharing-rule subsystem is not running on this kernel (record - * sharing configured with `enforce: false`, or the subsystem failed to start). + * Raised when the sharing-rule subsystem is not running on this kernel (the + * subsystem failed to start). * No object can take a rule there, and the door says so rather than answering * an empty list or an unmounted path. */ diff --git a/packages/plugins/plugin-sharing/src/sharing-plugin.ts b/packages/plugins/plugin-sharing/src/sharing-plugin.ts index 3e748ba8d08..00d34811a60 100644 --- a/packages/plugins/plugin-sharing/src/sharing-plugin.ts +++ b/packages/plugins/plugin-sharing/src/sharing-plugin.ts @@ -195,12 +195,6 @@ function createdOrganizationId(opCtx: any): string | undefined { export interface SharingPluginOptions { /** Extra object names that bypass sharing entirely. */ bypassObjects?: string[]; - /** - * Disable enforcement (read filter + canEdit) while still registering - * the schema + service. Useful in development to flip enforcement on - * via env var without rebuilding. - */ - enforce?: boolean; /** * Disable the public share-link REST routes. The `IShareLinkService` * is always registered (other services may depend on it); only the @@ -864,8 +858,8 @@ export class SharingServicePlugin implements Plugin { ctx.registerService('sharing', this.service); // [ADR-0142 D1] The authored queue tables' name guards — data hygiene on - // tables this plugin owns, bound regardless of `enforce` — and the boot - // report of an authored queue a later declaration shadows. + // tables this plugin owns — and the boot report of an authored queue a + // later declaration shadows. try { if (this.queues && typeof engine.registerHook === 'function') { bindQueueGuards(engine as any, this.queues); @@ -878,8 +872,8 @@ export class SharingServicePlugin implements Plugin { // [ADR-0142 D5, ruling A on organization-authored routing] An // organization's own assignment rules: the save guard on the table this // plugin owns (name namespace, object, entry shape, CEL compile, user - // target membership), bound regardless of `enforce`, and the boot report - // of an authored rule a later declaration shadows. + // target membership), and the boot report of an authored rule a later + // declaration shadows. try { if (typeof engine.registerHook === 'function') { bindAssignmentRuleGuards(engine as any); @@ -891,8 +885,8 @@ export class SharingServicePlugin implements Plugin { // [ADR-0057 D12] Maintain sys_user.primary_business_unit_id as a // denormalised projection of sys_business_unit_member.is_primary so a - // user-lookup can filter candidates by business unit. Bound regardless of - // `enforce` — it is a data projection, not an access-control surface. + // user-lookup can filter candidates by business unit. A data projection, + // not an access-control surface. try { if (typeof engine.registerHook === 'function' && typeof engine.unregisterHooksByPackage === 'function') { bindPrimaryBuHooks(engine, ctx.logger as any); @@ -903,13 +897,9 @@ export class SharingServicePlugin implements Plugin { } // [#5103] Record delete ⇒ every share on that record is revoked, whatever - // its source. Bound REGARDLESS of `enforce`, and deliberately: with - // enforcement off the rows are not consulted, but they are still written - // (by rules, by the share REST surface in a host that mounts it) and - // still accumulate — and a deployment that flips `enforce` back on must - // not inherit a table of dangling grants. Same reasoning as the primary-BU - // projection above: this is data hygiene on a table this plugin owns, not - // an access-control surface. + // its source, so no table of dangling grants accumulates. Same reasoning + // as the primary-BU projection above: this is data hygiene on a table + // this plugin owns. // // Not bound per object: the posture is judged per delete from live // metadata, so an object that gains `sharingModel` after boot is covered @@ -935,189 +925,185 @@ export class SharingServicePlugin implements Plugin { ctx.logger.warn('SharingServicePlugin: record-share delete cascade not bound', { error: err?.message }); } - // Enforcement (read-filter middleware + sharing-rule hooks) is opt-out - // via `enforce: false`. The share-link service below is registered - // REGARDLESS — capability-token sharing does not depend on principal- - // based RLS enforcement, and multi-tenant hosts mount this plugin purely - // for the `shareLinks` service (per-env enforcement is applied elsewhere). - if (this.options.enforce === false) { - ctx.logger.info('SharingServicePlugin: enforcement disabled (enforce=false) — share-link service still registered'); + // Enforcement: the read-filter middleware and the sharing-rule hooks. + // There is no switch that leaves them off — a kernel serving a private + // object boots only with this middleware installed (plugin-security's + // sharing floor refuses it otherwise). The share-link service below is + // registered beside it. + const mw = buildSharingMiddleware(this.service, ctx.logger as any, pluginMessageTranslator(ctx)); + if (typeof engine.registerMiddleware === 'function') { + engine.registerMiddleware(mw, { object: '*' }); + // [#27175] The by-id write gate now meets every by-id write, so a + // reader asking `admitsByIdWrite` is asking a gate that is enforced. + this.service.byIdWriteGateInstalled = true; + ctx.logger.info('SharingServicePlugin: enforcement middleware installed'); } else { - const mw = buildSharingMiddleware(this.service, ctx.logger as any, pluginMessageTranslator(ctx)); - if (typeof engine.registerMiddleware === 'function') { - engine.registerMiddleware(mw, { object: '*' }); - // [#27175] The by-id write gate now meets every by-id write, so a - // reader asking `admitsByIdWrite` is asking a gate that is enforced. - this.service.byIdWriteGateInstalled = true; - ctx.logger.info('SharingServicePlugin: enforcement middleware installed'); - } else { - ctx.logger.warn('SharingServicePlugin: engine has no registerMiddleware — enforcement not applied'); - } + ctx.logger.warn('SharingServicePlugin: engine has no registerMiddleware — enforcement not applied'); + } - // Rule evaluator + hot-rebindable lifecycle hooks. - try { - // [ADR-0131 D2] Declared `sharingRules` are READ from the registry - // on every read of the rule set, never copied into `sys_sharing_rule` - // — the seeder that copied them (`bootstrapDeclaredSharingRules`) is - // retired. The metadata service is resolved at read time: it is the - // registry-less host's reader and may register after this plugin. - this.ruleService = new SharingRuleService({ - engine: engine as SharingEngine, - sharing: this.service, + // Rule evaluator + hot-rebindable lifecycle hooks. + try { + // [ADR-0131 D2] Declared `sharingRules` are READ from the registry + // on every read of the rule set, never copied into `sys_sharing_rule` + // — the seeder that copied them (`bootstrapDeclaredSharingRules`) is + // retired. The metadata service is resolved at read time: it is the + // registry-less host's reader and may register after this plugin. + this.ruleService = new SharingRuleService({ + engine: engine as SharingEngine, + sharing: this.service, + logger: ctx.logger as any, + // [ADR-0142 D7] A `queue` recipient expands through the queue service. + ownershipQueues: () => this.queues ?? null, + declaredRules: createDeclaredSharingRuleSource({ + engine, + metadata: () => { + try { return ctx.getService('metadata'); } catch { return null; } + }, logger: ctx.logger as any, - // [ADR-0142 D7] A `queue` recipient expands through the queue service. - ownershipQueues: () => this.queues ?? null, - declaredRules: createDeclaredSharingRuleSource({ - engine, - metadata: () => { - try { return ctx.getService('metadata'); } catch { return null; } - }, - logger: ctx.logger as any, - }), + }), + }); + ctx.registerService('sharingRules', this.ruleService); + + // [#10103] Declared rules are served ONCE PER ORGANIZATION under a + // walled posture and organization-less under `single` — the passes + // the retired seeder made. A rule served organization-less on a + // walled deployment would sweep every tenant's records; under + // `single` the organization-less rule is the platform-global class + // `deleteRule` guards (#7795). + // The posture, read EXACTLY the way this plugin already reads it for + // the hierarchy org gate (the `tenancy` service, ADR-0105 D1 / #5859), + // so the two layers can never disagree about whether a wall is in + // force. An unresolvable posture is NOT evidence of `single`: it is + // treated as walled, because serving organization-less on a walled + // deployment is the failure #10103 removed, while an unnecessary + // per-organization scope on a `single` deployment costs one read. + const sharingPosture = (): TenancyPosture => { + try { + const probe = ctx.getService('tenancy'); + const normalized = normalizeTenancyPosture(probe?.posture); + if (normalized) return normalized; + if (probe?.isolationActive === false) return 'single'; + } catch { /* absent — fall through to the walled default */ } + return 'isolated'; + }; + const declaredScopes = await resolveDeclaredRuleScopes(engine, sharingPosture(), ctx.logger as any); + if (declaredScopes) this.ruleService.setDeclaredRuleScopes(declaredScopes); + else this.ruleService.setDeclaredRuleScopesUnknown(); + + // Serve a NEWLY CREATED organization's declared rules too, not only + // the ones present at boot. Without it a tenant created after + // startup reads no declared rule until the next restart. + if (typeof engine.registerMiddleware === 'function') { + engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { + await next(); + if (opCtx?.object !== 'sys_organization') return; + const op = opCtx?.operation; + if (op !== 'insert' && op !== 'create') return; + if (!postureEnforcesWall(sharingPosture())) return; + const organizationId = createdOrganizationId(opCtx); + if (!organizationId) { + // Never fall back to an organization-less scope on a walled + // deployment: that is the `single`-posture shape. + ctx.logger.warn('SharingServicePlugin: an organization was created but its id was ' + + 'unreadable — its declared sharing rules are NOT served until the next boot'); + return; + } + this.ruleService?.addDeclaredRuleScope(organizationId); }); - ctx.registerService('sharingRules', this.ruleService); - - // [#10103] Declared rules are served ONCE PER ORGANIZATION under a - // walled posture and organization-less under `single` — the passes - // the retired seeder made. A rule served organization-less on a - // walled deployment would sweep every tenant's records; under - // `single` the organization-less rule is the platform-global class - // `deleteRule` guards (#7795). - // The posture, read EXACTLY the way this plugin already reads it for - // the hierarchy org gate (the `tenancy` service, ADR-0105 D1 / #5859), - // so the two layers can never disagree about whether a wall is in - // force. An unresolvable posture is NOT evidence of `single`: it is - // treated as walled, because serving organization-less on a walled - // deployment is the failure #10103 removed, while an unnecessary - // per-organization scope on a `single` deployment costs one read. - const sharingPosture = (): TenancyPosture => { - try { - const probe = ctx.getService('tenancy'); - const normalized = normalizeTenancyPosture(probe?.posture); - if (normalized) return normalized; - if (probe?.isolationActive === false) return 'single'; - } catch { /* absent — fall through to the walled default */ } - return 'isolated'; - }; - const declaredScopes = await resolveDeclaredRuleScopes(engine, sharingPosture(), ctx.logger as any); - if (declaredScopes) this.ruleService.setDeclaredRuleScopes(declaredScopes); - else this.ruleService.setDeclaredRuleScopesUnknown(); - - // Serve a NEWLY CREATED organization's declared rules too, not only - // the ones present at boot. Without it a tenant created after - // startup reads no declared rule until the next restart. - if (typeof engine.registerMiddleware === 'function') { - engine.registerMiddleware(async (opCtx: any, next: () => Promise) => { - await next(); - if (opCtx?.object !== 'sys_organization') return; - const op = opCtx?.operation; - if (op !== 'insert' && op !== 'create') return; - if (!postureEnforcesWall(sharingPosture())) return; - const organizationId = createdOrganizationId(opCtx); - if (!organizationId) { - // Never fall back to an organization-less scope on a walled - // deployment: that is the `single`-posture shape. - ctx.logger.warn('SharingServicePlugin: an organization was created but its id was ' + - 'unreadable — its declared sharing rules are NOT served until the next boot'); - return; - } - this.ruleService?.addDeclaredRuleScope(organizationId); - }); - } + } - if (typeof engine.registerHook === 'function' && typeof engine.unregisterHooksByPackage === 'function') { - // Bound per OBJECT, never per organization: an organization the - // middleware above serves later needs no rebind (`bindRuleHooks`). - await this.bindRuleHooks(engine, ctx); - this.bindRuleRebindTriggers(engine, ctx); - // A recycle-bin restore runs no hook (ADR-0148 D2): re-evaluate each - // restored row's rules before the restore returns, on the objects - // the hooks above are bound on. - bindRuleRestoreRecompute(engine, this.ruleService, ctx.logger as any); - - // [#7729] A rule whose recipient resolves through the BUSINESS-UNIT - // graph changes audience when the graph moves, not when the shared - // record is written — and `bindRuleHooks` above binds only on each - // rule's own object, so a re-parent or a membership edit reached - // nothing. Left unbound, a business unit moved OUT of a shared - // subtree kept its members' read access until somebody happened to - // write the shared record: a revocation with no bound in time. - // - // Bound OUTSIDE the rebind seam on purpose. It carries no rule - // snapshot — the handler reads `listRules()` live on each BU write — - // so a runtime-authored rule is picked up without a rebind, and - // `unbindAllRuleHooks` (which every rebind calls) cannot tear it - // down. Inside `enforce`, unlike the primary-BU projection next to - // it: this one IS an access-control surface. - bindBusinessUnitTreeRecompute(engine, this.ruleService, ctx.logger as any, async (rule) => { - // [ADR-0142 D2] A queue recipient reads the BU tree exactly when - // its queue has a business-unit member — the queue the rule's - // grants are read from, so a declared rule's from its package - // (ADR-0150 D3). - const callerPackageId = await this.ruleService?.queueRecipientPackageOf(rule); - const queue = await this.queues?.resolveQueue( - rule.recipient_id, - rule.organization_id ?? null, - callerPackageId ? { callerPackageId } : undefined, - ); - return queue ? specsReadBusinessUnits(queue.members) : false; - }); + if (typeof engine.registerHook === 'function' && typeof engine.unregisterHooksByPackage === 'function') { + // Bound per OBJECT, never per organization: an organization the + // middleware above serves later needs no rebind (`bindRuleHooks`). + await this.bindRuleHooks(engine, ctx); + this.bindRuleRebindTriggers(engine, ctx); + // A recycle-bin restore runs no hook (ADR-0148 D2): re-evaluate each + // restored row's rules before the restore returns, on the objects + // the hooks above are bound on. + bindRuleRestoreRecompute(engine, this.ruleService, ctx.logger as any); + + // [#7729] A rule whose recipient resolves through the BUSINESS-UNIT + // graph changes audience when the graph moves, not when the shared + // record is written — and `bindRuleHooks` above binds only on each + // rule's own object, so a re-parent or a membership edit reached + // nothing. Left unbound, a business unit moved OUT of a shared + // subtree kept its members' read access until somebody happened to + // write the shared record: a revocation with no bound in time. + // + // Bound OUTSIDE the rebind seam on purpose. It carries no rule + // snapshot — the handler reads `listRules()` live on each BU write — + // so a runtime-authored rule is picked up without a rebind, and + // `unbindAllRuleHooks` (which every rebind calls) cannot tear it + // down. Unlike the primary-BU projection, this one IS an + // access-control surface. + bindBusinessUnitTreeRecompute(engine, this.ruleService, ctx.logger as any, async (rule) => { + // [ADR-0142 D2] A queue recipient reads the BU tree exactly when + // its queue has a business-unit member — the queue the rule's + // grants are read from, so a declared rule's from its package + // (ADR-0150 D3). + const callerPackageId = await this.ruleService?.queueRecipientPackageOf(rule); + const queue = await this.queues?.resolveQueue( + rule.recipient_id, + rule.organization_id ?? null, + callerPackageId ? { callerPackageId } : undefined, + ); + return queue ? specsReadBusinessUnits(queue.members) : false; + }); - // …and a rule whose recipient is a POSITION or a TEAM changes - // audience when a membership row (`sys_user_position`, - // `sys_team_member`) is written. Each such write re-evaluates the rules naming that - // recipient for the one user the row names, so a new holder gains - // the rule's grants and a former holder loses them before the write - // returns. Bound outside the rebind seam for the same reason as the - // BU recompute above: it reads `listRules()` live on every write. - bindRecipientMembershipRecompute(engine, this.ruleService, ctx.logger as any, this.queues); - - // [ADR-0142 D7] …and a rule whose recipient is a QUEUE changes - // audience when the queue's own rows move: a member specification - // added or removed, the queue deleted. Same placement and reasoning. - bindQueueRecipientRecompute(engine, this.ruleService, ctx.logger as any); - - // [#3896] Authoring a rule in Setup is a plain INSERT on - // sys_sharing_rule — it bypasses defineRule's validation, so the - // match-all criteria gate has to sit on the table itself too. - bindRuleCriteriaGuard(engine, ctx.logger as any); - - // [#30621] …and so must the refusal of a rule whose object is not - // under record-sharing enforcement: it would save and share nothing. - if (this.service) bindRuleObjectEnforcementGuard(engine, this.service); - - // [#38254] …and so must the refusal of a `user` recipient that - // names no user the rule could share with (`defineRule`'s own - // verdict, #33912): it would save and grant no one access. - if (this.service) bindRuleRecipientGuard(engine, this.service); - - // [ADR-0131 D6 regime C] …and so must the refusal of a row, new or - // renamed, that takes a declared rule's name: `defineRule` makes it - // for its own callers. A declared rule is customised by a clone - // under another name plus the declared rule switched off in the - // activation ledger, whose writes reconcile its grants at once. - bindDeclaredRuleNameGuard(engine, this.ruleService); - bindSharingRuleActivationReconcile(engine, this.ruleService); - - // [#2909 T1] Stamp `customized` on admin edits of seeded rules so - // a customized copy keeps answering for its name — the declared - // rule is not served beside it (ADR-0131 D2), and the ownership - // ceremony deletes only uncustomized copies. - unbindRuleProvenanceStamp(engine); - bindRuleProvenanceStamp(engine, ctx.logger as any); - - // [#2926 ③] Reconciling existing rows against every rule is - // deferred to `kernel:bootstrapped` (below): seed data is loaded on - // `kernel:ready` (raced against a budget, and the AppPlugin's seed - // hook is a *different* kernel:ready handler), so a backfill here - // would race the very records it must materialize. `kernel:bootstrapped` - // fires only after every kernel:ready handler has settled. - } else { - ctx.logger.warn('SharingServicePlugin: engine has no hook API — sharing rule auto-evaluation disabled'); - } - } catch (err: any) { - ctx.logger.warn('SharingServicePlugin: sharing-rule subsystem not started', { error: err?.message }); + // …and a rule whose recipient is a POSITION or a TEAM changes + // audience when a membership row (`sys_user_position`, + // `sys_team_member`) is written. Each such write re-evaluates the rules naming that + // recipient for the one user the row names, so a new holder gains + // the rule's grants and a former holder loses them before the write + // returns. Bound outside the rebind seam for the same reason as the + // BU recompute above: it reads `listRules()` live on every write. + bindRecipientMembershipRecompute(engine, this.ruleService, ctx.logger as any, this.queues); + + // [ADR-0142 D7] …and a rule whose recipient is a QUEUE changes + // audience when the queue's own rows move: a member specification + // added or removed, the queue deleted. Same placement and reasoning. + bindQueueRecipientRecompute(engine, this.ruleService, ctx.logger as any); + + // [#3896] Authoring a rule in Setup is a plain INSERT on + // sys_sharing_rule — it bypasses defineRule's validation, so the + // match-all criteria gate has to sit on the table itself too. + bindRuleCriteriaGuard(engine, ctx.logger as any); + + // [#30621] …and so must the refusal of a rule whose object is not + // under record-sharing enforcement: it would save and share nothing. + if (this.service) bindRuleObjectEnforcementGuard(engine, this.service); + + // [#38254] …and so must the refusal of a `user` recipient that + // names no user the rule could share with (`defineRule`'s own + // verdict, #33912): it would save and grant no one access. + if (this.service) bindRuleRecipientGuard(engine, this.service); + + // [ADR-0131 D6 regime C] …and so must the refusal of a row, new or + // renamed, that takes a declared rule's name: `defineRule` makes it + // for its own callers. A declared rule is customised by a clone + // under another name plus the declared rule switched off in the + // activation ledger, whose writes reconcile its grants at once. + bindDeclaredRuleNameGuard(engine, this.ruleService); + bindSharingRuleActivationReconcile(engine, this.ruleService); + + // [#2909 T1] Stamp `customized` on admin edits of seeded rules so + // a customized copy keeps answering for its name — the declared + // rule is not served beside it (ADR-0131 D2), and the ownership + // ceremony deletes only uncustomized copies. + unbindRuleProvenanceStamp(engine); + bindRuleProvenanceStamp(engine, ctx.logger as any); + + // [#2926 ③] Reconciling existing rows against every rule is + // deferred to `kernel:bootstrapped` (below): seed data is loaded on + // `kernel:ready` (raced against a budget, and the AppPlugin's seed + // hook is a *different* kernel:ready handler), so a backfill here + // would race the very records it must materialize. `kernel:bootstrapped` + // fires only after every kernel:ready handler has settled. + } else { + ctx.logger.warn('SharingServicePlugin: engine has no hook API — sharing rule auto-evaluation disabled'); } + } catch (err: any) { + ctx.logger.warn('SharingServicePlugin: sharing-rule subsystem not started', { error: err?.message }); } // ── Share-Link service (capability tokens) ──────────────── @@ -1134,9 +1120,8 @@ export class SharingServicePlugin implements Plugin { logger: ctx.logger as any, // [ADR-0111 D8] Let a record's share-manager (owner / Modify All) // revoke a link someone else minted on their record. `this.service` - // is always constructed above — even under `enforce: false` (the - // multi-tenant share-link-only config), where only the RLS middleware - // is skipped — so the probe is available in every posture. + // is constructed above, so the probe is available whenever the + // engine is. canManageShares: this.service ? (o, r, c) => this.service!.canManageShares(o, r, c as any) : undefined, @@ -1318,9 +1303,9 @@ export class SharingServicePlugin implements Plugin { // socket). Judged here, not at `kernel:ready`: other plugins register // their read middlewares and find hooks in their own `kernel:ready` // handlers, so only now is every registration final. Only where a - // producer writes the leaf: the sharing service is registered, whatever - // `enforce` says, because plugin-security's read paths ask that service - // for its read filter too. See `share-arm-boot.ts`. + // producer writes the leaf: the sharing service is registered, and + // plugin-security's read paths ask that service for its read filter too. + // See `share-arm-boot.ts`. ctx.hook('kernel:bootstrapped', async () => { if (!this.service) return; const refusal = shareGrantRegistrationRefusal(this.engine as any, ctx.logger as any); @@ -1367,8 +1352,8 @@ export class SharingServicePlugin implements Plugin { // delete and the revoke, and deletes on the one posture the cascade // deliberately skips (an unmarked system object). Runs BEFORE the // rule-grant passes and outside the `ruleService` guard: this sweep is - // source-agnostic and must also run in the `enforce: false` posture, - // where there is no rule service at all. + // source-agnostic and must also run when the rule service failed to + // start. // // Bounded per boot (keyset pages + a scan cap that reports itself) so a // table that only grows cannot make startup cost grow with it. @@ -1392,8 +1377,7 @@ export class SharingServicePlugin implements Plugin { // must not also skip the capability tokens, which are the leftovers that // do not need a named recipient to be exercised. Same bounded shape // (keyset pages, a self-reporting scan cap), and — like the share sweep — - // it runs in every posture, including `enforce: false`, where a host - // mounts this plugin purely for the share-link surface. + // it runs whether or not the rule service started. try { if (this.linkService) { const swept = await this.linkService.sweepOrphanedShareLinks(); @@ -1437,8 +1421,8 @@ export class SharingServicePlugin implements Plugin { // [ADR-0155 ② ruled R2, ADR-0111 D10] The visible trail of the storage // rows' tightening: the objects whose share grants stopped counting at the // switch and that hold share rows, named once per boot at `warn`. After - // the passes above, in a handler of its own, so it runs in every posture - // (`enforce: false` and no rule service included) and never fails the boot. + // the passes above, in a handler of its own, so it runs whether or not the + // rule service started and never fails the boot. ctx.hook('kernel:bootstrapped', async () => { if (!this.service) return; try { diff --git a/packages/plugins/plugin-sharing/src/sharing-service.ts b/packages/plugins/plugin-sharing/src/sharing-service.ts index c7623967af1..d8a82a148be 100644 --- a/packages/plugins/plugin-sharing/src/sharing-service.ts +++ b/packages/plugins/plugin-sharing/src/sharing-service.ts @@ -1765,10 +1765,12 @@ export class SharingService implements ISharingService { } /** - * Whether this service's engine middleware is installed and so enforces + * Whether this service's engine middleware — the read filter and the by-id + * write gate, one middleware — is installed, and so enforces * {@link admitsByIdWrite} on every by-id write. Set by the plugin when it - * registers the middleware; `false` when the deployment runs with - * enforcement off (`enforce: false`), where no by-id write meets the gate. + * registers the middleware; `false` on an engine with no middleware API. + * plugin-security's sharing floor reads it: a kernel serving a private + * object boots only when it is `true`. */ byIdWriteGateInstalled = false; diff --git a/packages/runtime/src/domains/share-links-enforcement-context.test.ts b/packages/runtime/src/domains/share-links-enforcement-context.test.ts index 1a1831cc03e..41350337257 100644 --- a/packages/runtime/src/domains/share-links-enforcement-context.test.ts +++ b/packages/runtime/src/domains/share-links-enforcement-context.test.ts @@ -1271,7 +1271,7 @@ describe('[#21329] mint authority on an owner-private object, at both doors (rul registerService, getService, }; - const plugin = new SharingServicePlugin({ enforce: false, registerShareLinkRoutes: false }); + const plugin = new SharingServicePlugin({ registerShareLinkRoutes: false }); await plugin.init(sharingCtx); await plugin.start(sharingCtx); for (const handler of hooks['kernel:ready'] ?? []) await handler(); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index f00d6234a39..81face88e65 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -2167,6 +2167,9 @@ importers: '@objectstack/plugin-security': specifier: workspace:* version: link:../plugin-security + '@objectstack/plugin-sharing': + specifier: workspace:* + version: link:../plugin-sharing '@objectstack/rest': specifier: workspace:* version: link:../../rest From 5f14455d300ad8e9dd7d41837c7f647e6bc75007 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 01:36:44 +0000 Subject: [PATCH 02/10] wip: pin the sharing plugin's always-on enforcement Claude-Session: https://claude.ai/code/session_01ASNY8XNef4ywkQio6S9ju4 Co-authored-by: Claude --- ...g-plugin-enforcement-always-on.pin.test.ts | 77 +++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 packages/plugins/plugin-sharing/src/sharing-plugin-enforcement-always-on.pin.test.ts diff --git a/packages/plugins/plugin-sharing/src/sharing-plugin-enforcement-always-on.pin.test.ts b/packages/plugins/plugin-sharing/src/sharing-plugin-enforcement-always-on.pin.test.ts new file mode 100644 index 00000000000..2d4bc1148cf --- /dev/null +++ b/packages/plugins/plugin-sharing/src/sharing-plugin-enforcement-always-on.pin.test.ts @@ -0,0 +1,77 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The record-sharing plugin has no switch that leaves its enforcement off: + * every boot of `SharingServicePlugin` installs its engine middleware, and its + * options carry no key that says otherwise. + * + * Two halves. At the type level, `SharingPluginOptions` has no `enforce` key, + * so a literal naming it does not compile. At runtime, a plugin handed that + * key anyway (an untyped caller) still installs the middleware: the service it + * registers reports `byIdWriteGateInstalled`, the flag plugin-security's + * sharing floor reads. + */ + +import { afterEach, describe, expect, it } from 'vitest'; +import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQLPlugin } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SharingServicePlugin, type SharingPluginOptions } from './index.js'; +import type { SharingService } from './sharing-service.js'; + +/** Compile error unless `T` is exactly `false`. */ +type Refute = T; +/** `SharingPluginOptions` declares no `enforce` key. */ +export type _NoEnforceOption = Refute<'enforce' extends keyof SharingPluginOptions ? true : false>; + +/** Never called: the excess-property check on a fresh literal is the assertion. */ +export function __pinNoEnforceOption(): void { + // @ts-expect-error — `enforce` is not an option of SharingServicePlugin. + void new SharingServicePlugin({ enforce: false }); +} + +function sqliteDriverPlugin(): Plugin { + return { + name: 'test.driver.sqlite', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService( + 'driver.default', + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + ); + }, + }; +} + +let kernel: ObjectKernel | undefined; + +afterEach(async () => { + try { + await kernel?.shutdown(); + } catch { + /* already stopped */ + } + kernel = undefined; +}); + +async function bootWith(options: unknown): Promise { + kernel = new ObjectKernel({ logger: { level: 'silent' }, gracefulShutdown: false } as never); + await kernel.use(sqliteDriverPlugin()); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(new SharingServicePlugin(options as SharingPluginOptions)); + await kernel.bootstrap(); + return kernel.getService('sharing'); +} + +describe('SharingServicePlugin always installs its enforcement middleware', () => { + it('installs it on a default boot', async () => { + const sharing = await bootWith({ registerShareLinkRoutes: false }); + expect(sharing.byIdWriteGateInstalled).toBe(true); + }); + + it('installs it when an untyped caller passes a retired enforce key', async () => { + const sharing = await bootWith({ enforce: false, registerShareLinkRoutes: false }); + expect(sharing.byIdWriteGateInstalled).toBe(true); + }); +}); From f03df9c617ebb070eac7b4a6c67fd8450f144db9 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 01:52:03 +0000 Subject: [PATCH 03/10] wip: skill, docs and changeset for the sharing floor Claude-Session: https://claude.ai/code/session_01ASNY8XNef4ywkQio6S9ju4 Co-authored-by: Claude --- .changeset/sharing-floor-private-objects.md | 27 +++++++++++++++++++ content/docs/deployment/cli.mdx | 6 ++++- scripts/check-skills-token-ratchet.mjs | 2 +- skills/objectstack-platform/SKILL.md | 7 +++-- .../evals/config-plugins-ops.json | 16 +++++++++++ 5 files changed, 52 insertions(+), 6 deletions(-) create mode 100644 .changeset/sharing-floor-private-objects.md diff --git a/.changeset/sharing-floor-private-objects.md b/.changeset/sharing-floor-private-objects.md new file mode 100644 index 00000000000..0f976676278 --- /dev/null +++ b/.changeset/sharing-floor-private-objects.md @@ -0,0 +1,27 @@ +--- +'@objectstack/plugin-security': patch +'@objectstack/plugin-sharing': patch +'@objectstack/plugin-dev': patch +--- + +fix(plugin-security)!: a kernel that serves an object with a private sharing model boots only with an enforcing record-sharing service + +Clause-②: no (narrowing) +Metadata-protocol: none +Skills-docs: skills/objectstack-platform/SKILL.md (the `queues` / `assignmentRules` note now names private objects on a boot with `auth`) and its `config-plugins-ops` eval + + + +**BREAKING — upgrade note.** Two rules now hold on every kernel: + +- **A kernel that composes the security plugin and registers an object whose effective sharing model is `private` (declared `private`, or undeclared on a custom object) boots only with an enforcing record-sharing service.** Otherwise `bootstrap()` is refused with `PrivateObjectsWithoutSharingError` (exported by `@objectstack/plugin-security`), naming every such object. It is judged per kernel at `kernel:bootstrapped`, before any socket opens; there is no switch that turns it off. The built-in tasks and notes (`sys_task`, `sys_note`) are private objects. +- **`SharingServicePlugin` has no `enforce` option.** Its enforcement middleware and sharing-rule hooks are always installed; the share-link service is registered as before. + +What to do: + +- `os serve` with the default preset: nothing. `sharing` is on the always-on slate. +- `os serve --preset minimal` with `auth`: list `sharing` in `requires` (`requires: ['auth', 'sharing']`). +- A hand-composed kernel: mount `SharingServicePlugin` from `@objectstack/plugin-sharing` on every kernel that composes `SecurityPlugin` and serves a private object. On a host that runs one kernel per environment, mount it on each environment kernel that serves such objects; a kernel that registers none is not affected. +- `new SharingServicePlugin({ enforce: false })` → `new SharingServicePlugin()`. Remove the key: it no longer compiles. + +`DevPlugin` (`@objectstack/plugin-dev`) now composes `SharingServicePlugin` beside `SecurityPlugin`, so a dev stack serving a private object boots as before. diff --git a/content/docs/deployment/cli.mdx b/content/docs/deployment/cli.mdx index 03df7b15e9a..608b04c9306 100644 --- a/content/docs/deployment/cli.mdx +++ b/content/docs/deployment/cli.mdx @@ -386,7 +386,11 @@ os serve --preset minimal # Skip auto-loaded auth/i18n/ui plugins (production: - `--preset minimal | default | full` — Override the auto-registration tier (see below). `minimal` composes no `auth` tier, so a production boot (no `--dev`) with it is refused, with or without `--server`, unless the - stack mounts `AuthPlugin` in its own `plugins`. + stack mounts `AuthPlugin` in its own `plugins`. `minimal` also drops the + always-on capabilities, `sharing` among them, and a kernel that composes the + security plugin and serves an object with a private sharing model (the + built-in tasks and notes are) boots only with the record-sharing service: + list `sharing` in `requires`, or the boot is refused, naming those objects. **Probes.** A served process exposes `GET /api/v1/health` (liveness — process only, and deliberately blind to configuration and credentials, so a diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 3b6e0988ae0..5ff46fa7d5f 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -1383,7 +1383,7 @@ export const CEILINGS = new Map([ // condition, both paid inside the entry: 9027 -> 9025 bytes (9000 -> 8998 priced), 25 over // the 9 KB target, the same 2250 tokens, still AT the measurement. // ceil(($(wc -c < skills/objectstack-platform/SKILL.md) - 27) / 4) == ceil(8998 / 4) - ['skills/objectstack-platform/SKILL.md', 2250], + ['skills/objectstack-platform/SKILL.md', 2246], // `skills/objectstack-pm-dispatch/SKILL.md` (9708) and its // `rules/dev-template.md` (1838) left this table on 2026-09-10 with the files: // the maintainer deleted the published PM skill whole (verbatim: diff --git a/skills/objectstack-platform/SKILL.md b/skills/objectstack-platform/SKILL.md index f19c0c90005..9cd40e2dec2 100644 --- a/skills/objectstack-platform/SKILL.md +++ b/skills/objectstack-platform/SKILL.md @@ -61,11 +61,10 @@ Each `objects[]` entry and field refuses an undeclared key too (`TS2353`). A sur closed yet (`connectors` is one) only warns that the key's `value is dropped at load`. -`queues` (`defineQueue`, `@objectstack/spec/security`; objectstack-data) and +`queues` (`defineQueue`, `@objectstack/spec/security`; objectstack-data), `assignmentRules` (`defineAssignmentRule`, `@objectstack/spec/automation`; -objectstack-automation) need the ownership-queue service -`@objectstack/plugin-sharing` registers: a stack declaring either without it is -refused at boot. +objectstack-automation) and, with `auth`, any private object (built-in tasks and +notes are) need `sharing`: without it the boot is refused. ### `requires:` — which service plugins boot diff --git a/skills/objectstack-platform/evals/config-plugins-ops.json b/skills/objectstack-platform/evals/config-plugins-ops.json index 474124aaffb..0a44d6cffd0 100644 --- a/skills/objectstack-platform/evals/config-plugins-ops.json +++ b/skills/objectstack-platform/evals/config-plugins-ops.json @@ -402,6 +402,22 @@ "recordId, confirm: true" ] } + }, + { + "id": 24, + "prompt": "We run `os serve --preset minimal` in production with `requires: ['auth']`, and our `crm_deal` object declares `sharingModel: 'private'`. What must `requires` list?", + "expected_output": "`requires: ['auth', 'sharing']`. `sharing` is always-on, so a default boot mounts it unlisted, but `--preset minimal` drops the always-on slate. A kernel that admits members (`auth` composes the security plugin) and serves a private object boots only with the record-sharing service (`@objectstack/plugin-sharing`); without `sharing` the boot is refused, naming the private objects (the built-in tasks and notes are private too). There is no switch that turns the check off.", + "files": [], + "assertions": { + "must_contain": [ + "sharing", + "--preset minimal", + "refused" + ], + "must_not_contain": [ + "enforce: false" + ] + } } ] } From 922eedd1fe36ee62ef682f9c20ba422f306f1848 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 02:31:23 +0000 Subject: [PATCH 04/10] test(plugin-security): fixtures that serve org-wide objects declare it Kernel fixtures whose subject is permission-set grants declare their objects public_read; the mocked kernels stand in for one carrying a sharing service. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01ASNY8XNef4ywkQio6S9ju4 --- .../src/catalog-reference-report.test.ts | 11 ++++++----- .../src/comment-doors.integration.test.ts | 3 +++ .../comment-reaction-unreact-door.integration.test.ts | 3 +++ .../comment-read-scope-semi-join.integration.test.ts | 5 ++++- ...ermission-sets.unit-of-measure.integration.test.ts | 3 +++ .../member-default-feed-grants.integration.test.ts | 3 +++ .../src/platform-baseline-sets.integration.test.ts | 4 +++- .../src/upgrade-impact-report.wiring.test.ts | 3 +++ 8 files changed, 28 insertions(+), 7 deletions(-) diff --git a/packages/plugins/plugin-security/src/catalog-reference-report.test.ts b/packages/plugins/plugin-security/src/catalog-reference-report.test.ts index 769751df7c9..5ecfabc996f 100644 --- a/packages/plugins/plugin-security/src/catalog-reference-report.test.ts +++ b/packages/plugins/plugin-security/src/catalog-reference-report.test.ts @@ -631,11 +631,12 @@ describe('[ADR-0131 D3/D4] SecurityPlugin runs the report at kernel:bootstrapped ]); const handlers = b.hooks.get('kernel:bootstrapped') ?? []; - // The platform baseline seam's window close (it re-derives the everyone - // anchor only when a set joined after the derivation began — none here), - // then this report, last. The grant-name backfill that ran ahead of it is - // retired (ADR-0131 D10). - expect(handlers).toHaveLength(2); + // The sharing floor (a kernel serving a private object boots only with an + // enforcing sharing service), the platform baseline seam's window close (it + // re-derives the everyone anchor only when a set joined after the + // derivation began — none here), then this report, last. The grant-name + // backfill that ran ahead of it is retired (ADR-0131 D10). + expect(handlers).toHaveLength(3); for (const handler of handlers.slice(0, -1)) await handler(); const writes = [ vi.spyOn(b.engine, 'insert'), vi.spyOn(b.engine, 'update'), vi.spyOn(b.engine, 'delete'), diff --git a/packages/plugins/plugin-security/src/comment-doors.integration.test.ts b/packages/plugins/plugin-security/src/comment-doors.integration.test.ts index a1366e7d0b3..334308ffb1b 100644 --- a/packages/plugins/plugin-security/src/comment-doors.integration.test.ts +++ b/packages/plugins/plugin-security/src/comment-doors.integration.test.ts @@ -153,6 +153,9 @@ function objectsPlugin(): Plugin { const parent = (name: string, label: string) => ({ name, label, + // Org-wide readable: this fixture's subject is the permission-set grants, not + // row sharing, and a private object boots only with a sharing service. + sharingModel: 'public_read', fields: { name: { type: 'text', label: 'Name' } }, }); return { diff --git a/packages/plugins/plugin-security/src/comment-reaction-unreact-door.integration.test.ts b/packages/plugins/plugin-security/src/comment-reaction-unreact-door.integration.test.ts index 0c40abc9c29..90aeb587f1e 100644 --- a/packages/plugins/plugin-security/src/comment-reaction-unreact-door.integration.test.ts +++ b/packages/plugins/plugin-security/src/comment-reaction-unreact-door.integration.test.ts @@ -133,6 +133,9 @@ function objectsPlugin(): Plugin { const parent = (name: string, label: string) => ({ name, label, + // Org-wide readable: this fixture's subject is the permission-set grants, not + // row sharing, and a private object boots only with a sharing service. + sharingModel: 'public_read', fields: { name: { type: 'text', label: 'Name' } }, }); return { diff --git a/packages/plugins/plugin-security/src/comment-read-scope-semi-join.integration.test.ts b/packages/plugins/plugin-security/src/comment-read-scope-semi-join.integration.test.ts index 127b53ec742..43c6a9b24fa 100644 --- a/packages/plugins/plugin-security/src/comment-read-scope-semi-join.integration.test.ts +++ b/packages/plugins/plugin-security/src/comment-read-scope-semi-join.integration.test.ts @@ -146,6 +146,9 @@ function objectsPlugin(): Plugin { { name: ACCOUNT, label: 'Account', + // Org-wide readable: this fixture's subject is the permission-set grants, not + // row sharing, and a private object boots only with a sharing service. + sharingModel: 'public_read', fields: { name: { type: 'text', label: 'Name' }, region: { type: 'text', label: 'Region' }, @@ -153,7 +156,7 @@ function objectsPlugin(): Plugin { secret: { type: 'text', label: 'Secret' }, }, }, - { name: BOARD, label: 'Board', fields: { name: { type: 'text', label: 'Name' } } }, + { name: BOARD, label: 'Board', sharingModel: 'public_read', fields: { name: { type: 'text', label: 'Name' } } }, ], }); }, diff --git a/packages/plugins/plugin-security/src/default-permission-sets.unit-of-measure.integration.test.ts b/packages/plugins/plugin-security/src/default-permission-sets.unit-of-measure.integration.test.ts index f6c6848d958..fea85c3b936 100644 --- a/packages/plugins/plugin-security/src/default-permission-sets.unit-of-measure.integration.test.ts +++ b/packages/plugins/plugin-security/src/default-permission-sets.unit-of-measure.integration.test.ts @@ -103,6 +103,9 @@ function objectsPlugin(): Plugin { { name: MATERIAL, label: 'Material', + // Org-wide readable: this fixture's subject is the permission-set grants, not + // row sharing, and a private object boots only with a sharing service. + sharingModel: 'public_read', fields: { title: { type: 'text', label: 'Title' }, uom: { type: 'text', label: 'Unit' }, diff --git a/packages/plugins/plugin-security/src/member-default-feed-grants.integration.test.ts b/packages/plugins/plugin-security/src/member-default-feed-grants.integration.test.ts index ac307a2cad8..5b0bd03ae42 100644 --- a/packages/plugins/plugin-security/src/member-default-feed-grants.integration.test.ts +++ b/packages/plugins/plugin-security/src/member-default-feed-grants.integration.test.ts @@ -125,6 +125,9 @@ function objectsPlugin(): Plugin { const appObject = (name: string, label: string, extra: Record = {}) => ({ name, label, + // Org-wide readable: this fixture's subject is the permission-set grants, not + // row sharing, and a private object boots only with a sharing service. + sharingModel: 'public_read', fields: { name: { type: 'text', label: 'Name' }, requester_id: { type: 'text', label: 'Requester' }, diff --git a/packages/plugins/plugin-security/src/platform-baseline-sets.integration.test.ts b/packages/plugins/plugin-security/src/platform-baseline-sets.integration.test.ts index 02feba4a785..fc8c187a2a0 100644 --- a/packages/plugins/plugin-security/src/platform-baseline-sets.integration.test.ts +++ b/packages/plugins/plugin-security/src/platform-baseline-sets.integration.test.ts @@ -82,7 +82,9 @@ function sqliteDriverPlugin(): Plugin { }; } -const textObject = (name: string) => ({ name, label: name, fields: { name: { type: 'text', label: 'Name' } } }); +// Org-wide readable: this fixture's subject is the baseline sets, not row +// sharing, and a private object boots only with a sharing service. +const textObject = (name: string) => ({ name, label: name, sharingModel: 'public_read', fields: { name: { type: 'text', label: 'Name' } } }); /** The identity objects and the other package's object. */ function appPlugin(): Plugin { diff --git a/packages/plugins/plugin-security/src/upgrade-impact-report.wiring.test.ts b/packages/plugins/plugin-security/src/upgrade-impact-report.wiring.test.ts index 62ea494f94b..aaaba5d2f82 100644 --- a/packages/plugins/plugin-security/src/upgrade-impact-report.wiring.test.ts +++ b/packages/plugins/plugin-security/src/upgrade-impact-report.wiring.test.ts @@ -131,6 +131,9 @@ async function boot(posture: 'single' | 'isolated', upgraded: boolean) { for (const ps of m.permissions ?? []) (engine as any).registry.registerItem('permission', structuredClone(ps), 'name', m.id); }) }, objectql: engine, + // The fixture's objects are private: the kernel this stands in for carries + // an enforcing sharing service (the sharing floor reads only this flag). + sharing: { byIdWriteGateInstalled: true }, metadata, protocol, messaging: { emit }, From bfa4ebb51021ea1af120630c583c7856971bc9e5 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 02:54:52 +0000 Subject: [PATCH 05/10] fix(plugin-security): the sharing floor reads the explain OWD mirror; fixtures follow the floor The floor's private-object test reuses the one OWD mirror plugin-security already carries. Fixtures whose subject is not row sharing declare their objects org-wide readable; plugin-dev's tests alias the sharing plugin to source. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01ASNY8XNef4ywkQio6S9ju4 --- .../src/identity-objects-plugin.test.ts | 6 +++++- packages/plugins/plugin-dev/vitest.config.ts | 4 ++++ .../plugin-security/src/explain-engine.ts | 7 +++++-- .../src/private-object-sharing-floor.ts | 18 +++++++----------- .../share-links-enforcement-context.test.ts | 2 ++ 5 files changed, 23 insertions(+), 14 deletions(-) diff --git a/packages/plugins/plugin-auth/src/identity-objects-plugin.test.ts b/packages/plugins/plugin-auth/src/identity-objects-plugin.test.ts index 5c306b27177..91ab5ecf8c3 100644 --- a/packages/plugins/plugin-auth/src/identity-objects-plugin.test.ts +++ b/packages/plugins/plugin-auth/src/identity-objects-plugin.test.ts @@ -29,6 +29,8 @@ */ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +// The auth plugin's reach loads this dynamically inside a case; pay it at collection. +import '@objectstack/core/egress'; import { ObjectKernel, resolvePluginOrder, @@ -79,7 +81,9 @@ function appPlugin(): Plugin { version: '1.0.0', type: 'app', name: 'Kit App', - objects: [{ name: 'kit_account', label: 'Account', fields: { name: Field.text({ label: 'Name' }) } }], + // Org-wide readable: these cases are about identity and boot, not row + // sharing, and a private object boots only with a sharing service. + objects: [{ name: 'kit_account', label: 'Account', sharingModel: 'public_read', fields: { name: Field.text({ label: 'Name' }) } }], }); }, }; diff --git a/packages/plugins/plugin-dev/vitest.config.ts b/packages/plugins/plugin-dev/vitest.config.ts index 756155ccf14..d81d85c1e97 100644 --- a/packages/plugins/plugin-dev/vitest.config.ts +++ b/packages/plugins/plugin-dev/vitest.config.ts @@ -62,6 +62,10 @@ export default defineConfig({ }, { find: /^@objectstack\/platform-objects$/, replacement: path.resolve(__dirname, '../../platform-objects/src/index.ts') }, { find: /^@objectstack\/plugin-security$/, replacement: path.resolve(__dirname, '../plugin-security/src/index.ts') }, + // `dev-plugin.ts` composes the record-sharing plugin beside the security + // plugin through a literal `import('@objectstack/plugin-sharing')`: same + // reason as the entry above. + { find: /^@objectstack\/plugin-sharing$/, replacement: path.resolve(__dirname, '../plugin-sharing/src/index.ts') }, // [#20376] The setup / account app packages. `dev-plugin.ts` names them with // literal `import('…')` specifiers now, so `check:test-source-alias` sees // both and, unaliased, both resolve through `exports` to `dist/`. Every diff --git a/packages/plugins/plugin-security/src/explain-engine.ts b/packages/plugins/plugin-security/src/explain-engine.ts index 61927d1c9da..29d6c5d1352 100644 --- a/packages/plugins/plugin-security/src/explain-engine.ts +++ b/packages/plugins/plugin-security/src/explain-engine.ts @@ -1343,8 +1343,11 @@ function owdForPrincipal( }; } -/** D1-equivalent OWD reading (mirrors plugin-sharing's effectiveSharingModel). */ -function describeOwd(schema: any): { model: string; declared: boolean; effect: 'private' | 'read' | 'public' } { +/** + * D1-equivalent OWD reading (mirrors plugin-sharing's effectiveSharingModel). + * Also read by the sharing floor (`private-object-sharing-floor.ts`). + */ +export function describeOwd(schema: any): { model: string; declared: boolean; effect: 'private' | 'read' | 'public' } { const m = schema?.sharingModel ?? schema?.security?.sharingModel; if (m === 'private') return { model: 'private', declared: true, effect: 'private' }; if (m === 'public_read') return { model: 'public_read', declared: true, effect: 'read' }; diff --git a/packages/plugins/plugin-security/src/private-object-sharing-floor.ts b/packages/plugins/plugin-security/src/private-object-sharing-floor.ts index 032572c40ad..38fa5356076 100644 --- a/packages/plugins/plugin-security/src/private-object-sharing-floor.ts +++ b/packages/plugins/plugin-security/src/private-object-sharing-floor.ts @@ -33,9 +33,9 @@ * org-wide default of `private` (declared `private`, an unrecognised value, or * no declaration on a non-platform object, ADR-0090 D1) on an object that * carries the `owner_id` column the scope is written over. The reading is - * plugin-sharing's `effectiveSharingModel`, mirrored here as - * `explain-engine.ts` mirrors it, because this package does not depend on - * plugin-sharing. + * plugin-sharing's `effectiveSharingModel`, through the mirror `explain()` + * already reads (`describeOwd`, `explain-engine.ts`), because this package does + * not depend on plugin-sharing. * * ## What "enforcing" means * @@ -48,6 +48,7 @@ import type { PluginContext } from '@objectstack/core'; import type { IObjectQLEngine } from '@objectstack/spec/contracts'; +import { describeOwd } from './explain-engine.js'; /** The column a private object's read scope is written over. */ const OWNER_COLUMN = 'owner_id'; @@ -58,15 +59,10 @@ const OWNER_COLUMN = 'owner_id'; */ export function isSharingScopedPrivateObject(schema: unknown): boolean { if (!schema || typeof schema !== 'object') return false; - const s = schema as { name?: unknown; isSystem?: unknown; sharingModel?: unknown; security?: { sharingModel?: unknown }; fields?: unknown }; - const fields = s.fields && typeof s.fields === 'object' ? (s.fields as Record) : undefined; - if (!fields || !(OWNER_COLUMN in fields)) return false; - const model = s.sharingModel ?? s.security?.sharingModel; - if (model === 'private') return true; - if (model === 'public_read' || model === 'public_read_write' || model === 'controlled_by_parent') return false; - if (model == null) return !(s.isSystem === true || String(s.name ?? '').startsWith('sys_')); + const fields = (schema as { fields?: unknown }).fields; + if (!fields || typeof fields !== 'object' || !(OWNER_COLUMN in fields)) return false; // An unrecognised stored value fails closed to private (ADR-0090 D4). - return true; + return describeOwd(schema).effect === 'private'; } /** Is `service` a record-sharing service whose engine middleware is installed? */ diff --git a/packages/runtime/src/domains/share-links-enforcement-context.test.ts b/packages/runtime/src/domains/share-links-enforcement-context.test.ts index 41350337257..f72c609423c 100644 --- a/packages/runtime/src/domains/share-links-enforcement-context.test.ts +++ b/packages/runtime/src/domains/share-links-enforcement-context.test.ts @@ -47,6 +47,8 @@ */ import { describe, it, expect, vi } from 'vitest'; +// The dispatcher's reach loads this dynamically inside a case; pay it at collection. +import '@objectstack/metadata'; import { assertEngineDeleteDispatch, assertEngineUpdateDispatch } from '@objectstack/metadata-core'; import { PermissionSetSchema } from '@objectstack/spec/security'; import type { PermissionSet } from '@objectstack/spec/security'; From 69bd621234676f86777dfdb337c73ab6eaf9ab84 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 03:01:53 +0000 Subject: [PATCH 06/10] test: kernels that serve the platform's private objects mount the sharing service Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01ASNY8XNef4ywkQio6S9ju4 --- .../cli/test/permission-set-zero-row.integration.test.ts | 4 ++++ .../security-catalog-echo-env-kernel.integration.test.ts | 4 ++++ .../http-conformance/src/hono-print-door.conformance.test.ts | 4 ++++ .../src/duplicate-record-user-message-doors-33790.test.ts | 4 ++++ .../src/identity-objects-default-organization.pin.test.ts | 5 ++++- packages/runtime/src/in-process-session-renewal.pin.test.ts | 4 ++++ 6 files changed, 24 insertions(+), 1 deletion(-) diff --git a/packages/cli/test/permission-set-zero-row.integration.test.ts b/packages/cli/test/permission-set-zero-row.integration.test.ts index a1fb2b31a90..7027865cc5b 100644 --- a/packages/cli/test/permission-set-zero-row.integration.test.ts +++ b/packages/cli/test/permission-set-zero-row.integration.test.ts @@ -40,6 +40,7 @@ import { MetadataPlugin } from '@objectstack/metadata'; import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; import { AuthPlugin } from '@objectstack/plugin-auth'; import { SecurityPlugin, appSecurityPluginOptions } from '@objectstack/plugin-security'; +import { SharingServicePlugin } from '@objectstack/plugin-sharing'; const ENV = 'env_zero_row'; const TABLE = 'sys_permission_set'; @@ -66,6 +67,9 @@ async function boot(kind: Kind, dbFile: string, rootDir: string): Promise { await kernel.use(new PlatformObjectsPlugin() as any); await kernel.use(new AuthPlugin({ secret: 'zero-row-secret-zero-row-secret-zero' }) as any); await kernel.use(new SecurityPlugin(appSecurityPluginOptions(stack)) as any); + // A kernel serving private objects (the platform's tasks and notes) boots only + // with an enforcing sharing service, as `os serve` composes it. + await kernel.use(new SharingServicePlugin({ registerShareLinkRoutes: false }) as any); await kernel.bootstrap(); return kernel; } diff --git a/packages/cli/test/security-catalog-echo-env-kernel.integration.test.ts b/packages/cli/test/security-catalog-echo-env-kernel.integration.test.ts index 121fb4aff94..259327ad60d 100644 --- a/packages/cli/test/security-catalog-echo-env-kernel.integration.test.ts +++ b/packages/cli/test/security-catalog-echo-env-kernel.integration.test.ts @@ -46,6 +46,7 @@ import { MetadataPlugin } from '@objectstack/metadata'; import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; import { AuthPlugin } from '@objectstack/plugin-auth'; import { SecurityPlugin, appSecurityPluginOptions } from '@objectstack/plugin-security'; +import { SharingServicePlugin } from '@objectstack/plugin-sharing'; import { securityCatalogReaderOf, resolveAuthzContext, assembleExecutionContext } from '@objectstack/core'; const ENV = 'env_catalog_echo'; @@ -91,6 +92,9 @@ async function boot(kind: Kind, dbFile: string, rootDir: string, app: any): Prom await kernel.use(new PlatformObjectsPlugin() as any); await kernel.use(new AuthPlugin({ secret: 'catalog-echo-secret-catalog-echo-secret' }) as any); await kernel.use(new SecurityPlugin(appSecurityPluginOptions(app)) as any); + // A kernel serving private objects (the platform's tasks and notes) boots only + // with an enforcing sharing service, as `os serve` composes it. + await kernel.use(new SharingServicePlugin({ registerShareLinkRoutes: false }) as any); await kernel.bootstrap(); return kernel; } diff --git a/packages/qa/http-conformance/src/hono-print-door.conformance.test.ts b/packages/qa/http-conformance/src/hono-print-door.conformance.test.ts index 7c57b456351..1aecea496b7 100644 --- a/packages/qa/http-conformance/src/hono-print-door.conformance.test.ts +++ b/packages/qa/http-conformance/src/hono-print-door.conformance.test.ts @@ -31,6 +31,7 @@ import { ObjectQLPlugin } from '@objectstack/objectql'; import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; import { AuthManager, AuthPlugin } from '@objectstack/plugin-auth'; import { SecurityPlugin, appSecurityPluginOptions } from '@objectstack/plugin-security'; +import { SharingServicePlugin } from '@objectstack/plugin-sharing'; import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; import { PrintServicePlugin } from '@objectstack/service-print'; import { AppPlugin, DefaultDatasourcePlugin } from '@objectstack/runtime'; @@ -66,6 +67,9 @@ async function boot(opts: { hosted: boolean; print?: boolean }): Promise { await kernel.use(new PlatformObjectsPlugin()); await kernel.use(new AuthPlugin({ secret: SECRET, ...(opts.hosted ? { registerRoutes: false } : {}) } as never)); await kernel.use(new SecurityPlugin(appSecurityPluginOptions(APP))); + // A kernel serving private objects (the platform's tasks and notes) boots only + // with an enforcing sharing service, as `os serve` composes it. + await kernel.use(new SharingServicePlugin({ registerShareLinkRoutes: false })); if (opts.print !== false) await kernel.use(new PrintServicePlugin()); await kernel.bootstrap(); diff --git a/packages/runtime/src/duplicate-record-user-message-doors-33790.test.ts b/packages/runtime/src/duplicate-record-user-message-doors-33790.test.ts index b0bdcf3f080..3e1dd10a955 100644 --- a/packages/runtime/src/duplicate-record-user-message-doors-33790.test.ts +++ b/packages/runtime/src/duplicate-record-user-message-doors-33790.test.ts @@ -41,6 +41,7 @@ import { actionsDoorAnswerOf } from '@objectstack/types'; import { createRestApiPlugin } from '@objectstack/rest'; import { AuthPlugin } from '@objectstack/plugin-auth'; import { SecurityPlugin, appSecurityPluginOptions } from '@objectstack/plugin-security'; +import { SharingServicePlugin } from '@objectstack/plugin-sharing'; import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; import { AppPlugin } from './app-plugin.js'; import { DefaultDatasourcePlugin } from './default-datasource-plugin.js'; @@ -172,6 +173,9 @@ beforeAll(async () => { await kernel.use(new PlatformObjectsPlugin()); await kernel.use(new AuthPlugin({ secret: 'duplicate-user-message-doors-secret' })); await kernel.use(new SecurityPlugin(appSecurityPluginOptions(APP))); + // A kernel serving private objects (the platform's tasks and notes) boots only + // with an enforcing sharing service, as `os serve` composes it. + await kernel.use(new SharingServicePlugin({ registerShareLinkRoutes: false })); await kernel.use(createRestApiPlugin({})); await kernel.use(createDispatcherPlugin({})); await kernel.bootstrap(); diff --git a/packages/runtime/src/identity-objects-default-organization.pin.test.ts b/packages/runtime/src/identity-objects-default-organization.pin.test.ts index c921f402c0b..17441b2614e 100644 --- a/packages/runtime/src/identity-objects-default-organization.pin.test.ts +++ b/packages/runtime/src/identity-objects-default-organization.pin.test.ts @@ -37,11 +37,14 @@ const SYS = { isSystem: true }; const PIN_APP: any = { manifest: { id: 'com.pin.identityobjectsdefaultorg', name: 'Identity objects default organization pins', version: '1.0.0' }, objects: [ - { name: 'pin_kit_ledger', label: 'Pin kit ledger', fields: { title: { type: 'text', label: 'Title' } } }, + // Org-wide readable: these pins are about the Default Organization, not row + // sharing, and a private object boots only with a sharing service. + { name: 'pin_kit_ledger', label: 'Pin kit ledger', sharingModel: 'public_read', fields: { title: { type: 'text', label: 'Title' } } }, { // ADR-0066: the declared way to hold rows that belong to no organization. name: 'pin_kit_licence', label: 'Pin kit licence', + sharingModel: 'public_read', tenancy: { enabled: false }, fields: { title: { type: 'text', label: 'Title' } }, }, diff --git a/packages/runtime/src/in-process-session-renewal.pin.test.ts b/packages/runtime/src/in-process-session-renewal.pin.test.ts index 89d3c6cea55..428d17a9104 100644 --- a/packages/runtime/src/in-process-session-renewal.pin.test.ts +++ b/packages/runtime/src/in-process-session-renewal.pin.test.ts @@ -53,6 +53,7 @@ import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; import { createRestApiPlugin } from '@objectstack/rest'; import { AuthPlugin } from '@objectstack/plugin-auth'; import { SecurityPlugin, appSecurityPluginOptions } from '@objectstack/plugin-security'; +import { SharingServicePlugin } from '@objectstack/plugin-sharing'; import { PlatformObjectsPlugin } from '@objectstack/platform-objects/plugin'; import { AppPlugin } from './app-plugin.js'; import { DefaultDatasourcePlugin } from './default-datasource-plugin.js'; @@ -146,6 +147,9 @@ beforeAll(async () => { await kernel.use(new PlatformObjectsPlugin()); await kernel.use(new AuthPlugin({ secret: 'session-renewal-22258-secret', autoDefaultOrganization: false })); await kernel.use(new SecurityPlugin(appSecurityPluginOptions(PIN_APP))); + // A kernel serving private objects (the platform's tasks and notes) boots only + // with an enforcing sharing service, as `os serve` composes it. + await kernel.use(new SharingServicePlugin({ registerShareLinkRoutes: false })); await kernel.use(createRestApiPlugin({})); await kernel.use(createDispatcherPlugin({})); await kernel.bootstrap(); From 0d6213c001c1d01693d7fd22bc391871ce708136 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 03:08:57 +0000 Subject: [PATCH 07/10] test(runtime): pay the metadata load at collection in the edited pins Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01ASNY8XNef4ywkQio6S9ju4 --- .../src/identity-objects-default-organization.pin.test.ts | 2 ++ packages/runtime/src/in-process-session-renewal.pin.test.ts | 2 ++ 2 files changed, 4 insertions(+) diff --git a/packages/runtime/src/identity-objects-default-organization.pin.test.ts b/packages/runtime/src/identity-objects-default-organization.pin.test.ts index 17441b2614e..887c987e3c4 100644 --- a/packages/runtime/src/identity-objects-default-organization.pin.test.ts +++ b/packages/runtime/src/identity-objects-default-organization.pin.test.ts @@ -24,6 +24,8 @@ */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +// The runtime's reach loads this dynamically inside a case; pay it at collection. +import '@objectstack/metadata'; import { ObjectKernel, type Plugin, type PluginContext } from '@objectstack/core'; import { ObjectQLPlugin, type ObjectQL } from '@objectstack/objectql'; import { createIdentityObjectsPlugin } from '@objectstack/plugin-auth'; diff --git a/packages/runtime/src/in-process-session-renewal.pin.test.ts b/packages/runtime/src/in-process-session-renewal.pin.test.ts index 428d17a9104..cc6a88fc44d 100644 --- a/packages/runtime/src/in-process-session-renewal.pin.test.ts +++ b/packages/runtime/src/in-process-session-renewal.pin.test.ts @@ -47,6 +47,8 @@ */ import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +// The runtime's reach loads this dynamically inside a case; pay it at collection. +import '@objectstack/metadata'; import { ObjectKernel } from '@objectstack/core'; import { ObjectQLPlugin } from '@objectstack/objectql'; import { HonoServerPlugin } from '@objectstack/plugin-hono-server'; From 8575f34fa6418a1b6e64fdd0acc8e951fe0a8997 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 03:27:03 +0000 Subject: [PATCH 08/10] =?UTF-8?q?chore(changeset):=20carry=20the=20dispatc?= =?UTF-8?q?h's=20Clause-=E2=91=A1=20line=20verbatim?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01ASNY8XNef4ywkQio6S9ju4 --- .changeset/sharing-floor-private-objects.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.changeset/sharing-floor-private-objects.md b/.changeset/sharing-floor-private-objects.md index 0f976676278..64af6890814 100644 --- a/.changeset/sharing-floor-private-objects.md +++ b/.changeset/sharing-floor-private-objects.md @@ -6,7 +6,7 @@ fix(plugin-security)!: a kernel that serves an object with a private sharing model boots only with an enforcing record-sharing service -Clause-②: no (narrowing) +Clause-②: no (narrowing — refuses a composition that was accepted) Metadata-protocol: none Skills-docs: skills/objectstack-platform/SKILL.md (the `queues` / `assignmentRules` note now names private objects on a boot with `auth`) and its `config-plugins-ops` eval From 4253f1c37abee7490ab3d62bc9a548cbb04beea6 Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 04:20:53 +0000 Subject: [PATCH 09/10] fix(plugin-security): the sharing floor refuses a boot whose object registry it cannot read A kernel whose engine exposes no readable registry is not read as serving no private object. Pins: the unreadable-registry refusal, the refusal on a LiteKernel, and the floor's private-object reading against plugin-sharing's. The env-kernel catalog fixture declares its object org-wide readable. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01ASNY8XNef4ywkQio6S9ju4 --- .changeset/sharing-floor-private-objects.md | 2 +- ...atalog-echo-env-kernel.integration.test.ts | 4 +- packages/plugins/plugin-security/src/index.ts | 2 +- .../src/private-object-sharing-floor.test.ts | 106 +++++++++++++++++- .../src/private-object-sharing-floor.ts | 44 +++++++- scripts/check-skills-token-ratchet.mjs | 5 + 6 files changed, 151 insertions(+), 12 deletions(-) diff --git a/.changeset/sharing-floor-private-objects.md b/.changeset/sharing-floor-private-objects.md index 64af6890814..8ca87ef776f 100644 --- a/.changeset/sharing-floor-private-objects.md +++ b/.changeset/sharing-floor-private-objects.md @@ -24,4 +24,4 @@ What to do: - A hand-composed kernel: mount `SharingServicePlugin` from `@objectstack/plugin-sharing` on every kernel that composes `SecurityPlugin` and serves a private object. On a host that runs one kernel per environment, mount it on each environment kernel that serves such objects; a kernel that registers none is not affected. - `new SharingServicePlugin({ enforce: false })` → `new SharingServicePlugin()`. Remove the key: it no longer compiles. -`DevPlugin` (`@objectstack/plugin-dev`) now composes `SharingServicePlugin` beside `SecurityPlugin`, so a dev stack serving a private object boots as before. +`DevPlugin` (`@objectstack/plugin-dev`) now composes `SharingServicePlugin` beside `SecurityPlugin`: a dev stack serving a private object boots as before, and record sharing is now enforced in that stack. diff --git a/packages/cli/test/security-catalog-echo-env-kernel.integration.test.ts b/packages/cli/test/security-catalog-echo-env-kernel.integration.test.ts index 259327ad60d..fc30a484807 100644 --- a/packages/cli/test/security-catalog-echo-env-kernel.integration.test.ts +++ b/packages/cli/test/security-catalog-echo-env-kernel.integration.test.ts @@ -66,7 +66,9 @@ const STACK_POSITION = 'echo_stack_position'; const stack: any = { manifest: { id: 'com.example.catalog_echo', name: 'catalog_echo', version: '0.0.1', type: 'app' }, - objects: [{ name: 'echo_doc', label: 'Echo Doc', fields: { title: { type: 'text', label: 'Title' } } }], + // Org-wide readable: this fixture's subject is the security catalog, not row + // sharing, and its seeded row carries no owner. + objects: [{ name: 'echo_doc', label: 'Echo Doc', sharingModel: 'public_read', fields: { title: { type: 'text', label: 'Title' } } }], permissions: [{ name: DECLARED_SET, label: 'Declared reader', objects: { echo_doc: { allowRead: true } } }], positions: [{ name: STACK_POSITION, label: 'Stack position', permissionSets: [DECLARED_SET] }], }; diff --git a/packages/plugins/plugin-security/src/index.ts b/packages/plugins/plugin-security/src/index.ts index a8330478fb0..0bfe58ad889 100644 --- a/packages/plugins/plugin-security/src/index.ts +++ b/packages/plugins/plugin-security/src/index.ts @@ -9,7 +9,7 @@ export { SecurityPlugin } from './security-plugin.js'; // The boot refusal for a kernel that serves a private object without an enforcing record-sharing service. -export { PrivateObjectsWithoutSharingError } from './private-object-sharing-floor.js'; +export { PrivateObjectsWithoutSharingError, SharingFloorRegistryUnreadableError } from './private-object-sharing-floor.js'; // [#33132] The shape of `SecurityPluginOptions.platformBaselineOverrides`, for a host that declares one. export type { PlatformBaselineOverride, PlatformBaselineOverrides } from './platform-baseline-sets.js'; export { PermissionEvaluator } from './permission-evaluator.js'; diff --git a/packages/plugins/plugin-security/src/private-object-sharing-floor.test.ts b/packages/plugins/plugin-security/src/private-object-sharing-floor.test.ts index 5a15b15b537..9fbcdfe4ad3 100644 --- a/packages/plugins/plugin-security/src/private-object-sharing-floor.test.ts +++ b/packages/plugins/plugin-security/src/private-object-sharing-floor.test.ts @@ -18,12 +18,17 @@ * both, and an environment kernel without one is refused even while another * kernel in the same process has it; * - objects whose effective model is not private, or that carry no owner - * column, do not require the service. + * column, do not require the service, and that reading agrees with + * plugin-sharing's own (`effectiveSharingModel` over the owner column); + * - the refusal holds on a LiteKernel as on an ObjectKernel; + * - a registry the floor cannot read refuses the boot rather than reading as + * "no private objects". */ import { afterEach, describe, expect, it } from 'vitest'; import { CAPABILITY_PROVIDERS, + LiteKernel, ObjectKernel, resolveServedCapabilities, type Plugin, @@ -31,13 +36,14 @@ import { } from '@objectstack/core'; import { ObjectQLPlugin } from '@objectstack/objectql'; import { SqlDriver } from '@objectstack/driver-sql'; -import { SharingServicePlugin } from '@objectstack/plugin-sharing'; +import { SharingServicePlugin, effectiveSharingModel } from '@objectstack/plugin-sharing'; import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; import { SecurityPlugin } from './security-plugin.js'; -import { PrivateObjectsWithoutSharingError } from './index.js'; +import { PrivateObjectsWithoutSharingError, SharingFloorRegistryUnreadableError } from './index.js'; import { isEnforcingSharingService, isSharingScopedPrivateObject, + refusePrivateObjectsWithoutSharing, } from './private-object-sharing-floor.js'; const OWNER = { type: 'lookup', reference: 'sys_user', label: 'Owner' } as const; @@ -116,7 +122,7 @@ function kernelResolverPlugin(): Plugin { }; } -const kernels: ObjectKernel[] = []; +const kernels: Array = []; afterEach(async () => { for (const k of kernels.splice(0)) { @@ -277,3 +283,95 @@ describe('which objects require the sharing service', () => { expect(isEnforcingSharingService(undefined)).toBe(false); }); }); + +describe('the refusal holds on a LiteKernel', () => { + async function bootLite(extra: Plugin[]): Promise<{ kernel: LiteKernel; err: unknown }> { + const kernel = new LiteKernel({ logger: { level: 'silent' } } as never); + kernels.push(kernel); + kernel.use(sqliteDriverPlugin()); + kernel.use(new ObjectQLPlugin()); + kernel.use(objectsPlugin([PRIVATE_OBJECT])); + for (const p of extra) kernel.use(p); + kernel.use(new SecurityPlugin()); + try { + await kernel.bootstrap(); + return { kernel, err: undefined }; + } catch (err) { + return { kernel, err }; + } + } + + it('refuses a LiteKernel with a private object and no sharing service', async () => { + const { err } = await bootLite([]); + + expect(err).toBeInstanceOf(PrivateObjectsWithoutSharingError); + expect((err as PrivateObjectsWithoutSharingError).privateObjects).toEqual(['floor_deal']); + }); + + it('control: the same LiteKernel with the sharing service mounted boots', async () => { + const { kernel, err } = await bootLite([new SharingServicePlugin({ registerShareLinkRoutes: false })]); + + expect(err).toBeUndefined(); + expect(kernel.getState()).toBe('running'); + }); +}); + +describe('a registry the floor cannot read refuses the boot', () => { + /** A plugin context whose `objectql` service is `engine`, and no `sharing`. */ + const ctxWith = (engine: unknown) => ({ + getService: (name: string) => { + if (name === 'objectql') return engine; + throw new Error(`service not registered: ${name}`); + }, + }) as never; + + it('an engine with no registry', () => { + expect(() => refusePrivateObjectsWithoutSharing(ctxWith({}))).toThrow(SharingFloorRegistryUnreadableError); + }); + + it('a registry with no getAllObjects', () => { + expect(() => refusePrivateObjectsWithoutSharing(ctxWith({ registry: {} }))).toThrow(SharingFloorRegistryUnreadableError); + }); + + it('a getAllObjects that answers no list', () => { + expect(() => refusePrivateObjectsWithoutSharing(ctxWith({ registry: { getAllObjects: () => undefined } }))) + .toThrow(SharingFloorRegistryUnreadableError); + }); + + it('a registry that throws propagates its own error', () => { + const own = new Error('registry read failed'); + expect(() => refusePrivateObjectsWithoutSharing(ctxWith({ registry: { getAllObjects: () => { throw own; } } }))) + .toThrow(own); + }); + + it('control: a registry that answers an empty list boots', () => { + expect(() => refusePrivateObjectsWithoutSharing(ctxWith({ registry: { getAllObjects: () => [] } }))).not.toThrow(); + }); +}); + +describe('the floor reads a private object as plugin-sharing does', () => { + /** plugin-sharing's reading: the effective model is private and the object carries the owner column. */ + const sharingReads = (schema: any) => + effectiveSharingModel(schema) === 'private' && Boolean(schema?.fields && 'owner_id' in schema.fields); + + const owner = { owner_id: OWNER }; + const plain = { title: { type: 'text' } }; + const cases: unknown[] = []; + for (const sharingModel of [undefined, 'private', 'public_read', 'public_read_write', 'controlled_by_parent', 'legacy_value']) { + for (const name of ['crm_deal', 'sys_thing']) { + for (const isSystem of [undefined, true]) { + for (const fields of [owner, plain]) { + cases.push({ name, ...(isSystem ? { isSystem } : {}), ...(sharingModel ? { sharingModel } : {}), fields }); + if (sharingModel) cases.push({ name, ...(isSystem ? { isSystem } : {}), security: { sharingModel }, fields }); + } + } + } + } + + it(`agrees on every one of ${cases.length} schemas`, () => { + const disagreements = cases.filter((schema) => isSharingScopedPrivateObject(schema) !== sharingReads(schema)); + expect(disagreements).toEqual([]); + expect(cases.some((schema) => sharingReads(schema))).toBe(true); + expect(cases.some((schema) => !sharingReads(schema))).toBe(true); + }); +}); diff --git a/packages/plugins/plugin-security/src/private-object-sharing-floor.ts b/packages/plugins/plugin-security/src/private-object-sharing-floor.ts index 38fa5356076..0a75282d16b 100644 --- a/packages/plugins/plugin-security/src/private-object-sharing-floor.ts +++ b/packages/plugins/plugin-security/src/private-object-sharing-floor.ts @@ -23,9 +23,16 @@ * settled, so "not installed" is final (AGENTS.md, startup registry reads). * A throw there fails `bootstrap()` on both kernels, before * `kernel:listening` opens any socket. - * - **Only on a kernel that starts this plugin.** A boot that composes it for - * its declarations alone (`os migrate`, which suppresses `start()`) serves no - * member and is not judged. + * - **Only on a kernel that starts this plugin and runs its boot-phase hooks.** + * A boot that composes it for its declarations alone (`os migrate`, which + * suppresses `start()`) serves no member and is not judged; nor is a kernel + * built with `bootPhaseHooks: false`, which never fires `kernel:bootstrapped` + * (`ObjectKernelConfig.bootPhaseHooks` states what such a kernel withholds). + * - **Or it refuses.** An engine whose registry cannot be read (no `registry`, + * or no `getAllObjects` on it) is not read as "no private objects": the boot + * is refused with {@link SharingFloorRegistryUnreadableError}, and a registry + * that throws propagates its own error (discriminate or propagate, #8895 / + * #9285, as `@objectstack/objectql`'s plugin reads the same registry). * * ## Which objects count * @@ -91,10 +98,28 @@ export class PrivateObjectsWithoutSharingError extends Error { } } +/** + * The boot refusal for a kernel whose object registry the sharing floor cannot + * read: it cannot tell whether the kernel serves a private object, so it does + * not boot as though it served none. + */ +export class SharingFloorRegistryUnreadableError extends Error { + constructor(reason: string) { + super( + 'SecurityPlugin cannot boot: the sharing floor cannot read this kernel\'s object registry ' + + `(${reason}), ` + + 'so it cannot tell whether the kernel serves an object with a private sharing model. ' + + 'A kernel boots only when that answer can be read.', + ); + this.name = 'SharingFloorRegistryUnreadableError'; + } +} + /** * Run from a `kernel:bootstrapped` handler (see the module header): throws * {@link PrivateObjectsWithoutSharingError} when this kernel's engine registers - * a private object and this kernel has no enforcing `sharing` service. + * a private object and this kernel has no enforcing `sharing` service, and + * {@link SharingFloorRegistryUnreadableError} when it cannot read the registry. */ export function refusePrivateObjectsWithoutSharing(ctx: PluginContext): void { let ql: IObjectQLEngine | undefined; @@ -105,7 +130,16 @@ export function refusePrivateObjectsWithoutSharing(ctx: PluginContext): void { // reports its own absence at start(). return; } - const schemas = ql?.registry?.getAllObjects?.() ?? []; + const registry = (ql as { registry?: { getAllObjects?: () => unknown[] } } | undefined)?.registry; + if (!registry) throw new SharingFloorRegistryUnreadableError('the objectql engine exposes no `registry`'); + if (typeof registry.getAllObjects !== 'function') { + throw new SharingFloorRegistryUnreadableError('the registry exposes no `getAllObjects()`'); + } + // A registry that throws propagates its own error: no catch here. + const schemas: unknown = registry.getAllObjects(); + if (!Array.isArray(schemas)) { + throw new SharingFloorRegistryUnreadableError('`getAllObjects()` answered something other than a list'); + } const privateObjects = [ ...new Set( schemas diff --git a/scripts/check-skills-token-ratchet.mjs b/scripts/check-skills-token-ratchet.mjs index 5ff46fa7d5f..7deb9838004 100644 --- a/scripts/check-skills-token-ratchet.mjs +++ b/scripts/check-skills-token-ratchet.mjs @@ -1383,6 +1383,11 @@ export const CEILINGS = new Map([ // condition, both paid inside the entry: 9027 -> 9025 bytes (9000 -> 8998 priced), 25 over // the 9 KB target, the same 2250 tokens, still AT the measurement. // ceil(($(wc -c < skills/objectstack-platform/SKILL.md) - 27) / 4) == ceil(8998 / 4) + // 2250 -> 2246 (#39789, the sharing floor): the `queues` / `assignmentRules` note also names + // private objects on a boot with `auth` (the built-in tasks and notes are private) as needing + // `sharing`, rewritten in place: 9025 -> 9008 bytes (8998 -> 8981 priced), 8 over the 9 KB + // target, -> 2246 tokens, pinned AT the measurement. + // ceil(($(wc -c < skills/objectstack-platform/SKILL.md) - 27) / 4) == ceil(8981 / 4) ['skills/objectstack-platform/SKILL.md', 2246], // `skills/objectstack-pm-dispatch/SKILL.md` (9708) and its // `rules/dev-template.md` (1838) left this table on 2026-09-10 with the files: From 80b53b236d4994aa07d832390681c93da227a08b Mon Sep 17 00:00:00 2001 From: Claude Date: Sat, 5 Dec 2026 05:11:22 +0000 Subject: [PATCH 10/10] test(dogfood): the comment-thread engine cell declares its account object org-wide readable Its subject is permission-set grants (full vs row-scoped reads), not row sharing, and a kernel serving a private object boots only with a sharing service. Co-Authored-By: Claude Claude-Session: https://claude.ai/code/session_01ASNY8XNef4ywkQio6S9ju4 --- .../qa/dogfood/test/comment-threads-query.dogfood.test.ts | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts b/packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts index d93604d3662..0286a3b6d16 100644 --- a/packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts +++ b/packages/qa/dogfood/test/comment-threads-query.dogfood.test.ts @@ -627,6 +627,10 @@ function objectsPlugin(): Plugin { { name: ACCOUNT, label: 'Account', + // Org-wide readable: this cell's subject is the permission-set grants + // (full vs row-scoped), not row sharing, and a private object boots + // only with a sharing service. + sharingModel: 'public_read', fields: { name: { type: 'text', label: 'Name' }, region: { type: 'text', label: 'Region' },