diff --git a/.changeset/32754-member-attachment-grant.md b/.changeset/32754-member-attachment-grant.md new file mode 100644 index 00000000000..e608b9a4918 --- /dev/null +++ b/.changeset/32754-member-attachment-grant.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': patch +'@objectstack/plugin-security': patch +'@objectstack/service-storage': patch +--- + +fix(service-storage, plugin-security): every signed-in member can attach files to the records they may edit, and see those of the records they may read — the storage service contributes its own attachment set to the member baseline, beside the row gates that scope it + +Clause-②: yes (widening) +Metadata-protocol: none + +A member who could edit a record could not attach a file to it: no permission set granted the attachment object, so every attach was refused before the attachment row gates were consulted. The storage service now contributes `storage_attachment_member` — read and create on `sys_attachment`, nothing else, no edit and no delete — and every signed-in member holds it through the `everyone` anchor, beside `member_default` (ADR-0090 D5). `member_default` itself is unchanged (ADR-0090 D9). `GET /security/explain` names the set as an additive-baseline contributor. + +The set is contributed only once all four attachment gates are installed: the per-object opt-in gate (`enable.files`), the write rule (attach only to a record you may edit), the read-visibility gate (see only the attachments of records you may read) and the download door's parent-record check. All four are the storage service's own: it now enforces the `enable.files` opt-in itself, on every attachment insert and re-point, wherever it runs. A kernel whose data engine cannot carry a gate, or that composes no auth service for the download check, contributes nothing and says at warn level which gate is missing and what to add, so the object stays refused rather than ungated. A host without the storage service, a deployment that declares no member baseline (`fallbackPermissionSet: null`) and external users gain nothing. An agent principal gains nothing in its own right; an agent acting for a member is bounded by that member and by its own scope, so it can now attach where the member can, within that scope. + +**Upgrade-day changes.** + +- Attachments already stored become visible again to every member who can read the parent record, and a member can attach files to records they can edit. A member who can read a record but not edit it is now refused an attach with `ATTACHMENT_PARENT_ACCESS` instead of `PERMISSION_DENIED` (still 403). Managing other people's attachments — edit and delete — still needs an explicit set distributed by position. +- On a composition that did not mount the capability that enforced the `enable.files` opt-in before, an object that never declared the opt-in now refuses attachments for everyone, administrators and the system path included (`FILES_DISABLED`, 403), as its declaration (default off) says. Attachments already stored on such an object stay as they are: the opt-in judges only a new attachment and a re-point. An object that should take attachments declares `enable: { files: true }`. + +`ISecurityService` gains an optional member, `contributePlatformBaselineSet(contributor, set)`, the seam a platform service contributes its baseline set through. It admits only read and create, only on objects the contributing package registered itself, one set per contributor, and only during boot; a wildcard, any other permission bit, a row policy, another package's object or a late call is refused, and every admission and refusal is logged. Feature-detect it: a security service without it contributes nothing, and the contributor keeps its object refused. It is for platform services, not tenant packages. diff --git a/content/docs/permissions/attachments-access.mdx b/content/docs/permissions/attachments-access.mdx index 1f72d8bf5ba..3b806461b37 100644 --- a/content/docs/permissions/attachments-access.mdx +++ b/content/docs/permissions/attachments-access.mdx @@ -25,6 +25,39 @@ attachment to it. Enforcement is layered, and every gate is fail-closed. stored) and never create a `sys_attachment` row, so nothing on this page applies to them. +## Who holds the object grant + +The gates on this page decide the rows. The object grant on `sys_attachment` +only opens the door to them, and every member holds its **read and create** +half with no grant from the app: the storage service +(`@objectstack/service-storage`) contributes a set of its own, +`storage_attachment_member`, to the member baseline that every signed-in member +holds through the `everyone` anchor. It contributes the set beside the gates, +and only once all four are present: the write rule, the read-visibility gate, +the download door's parent-record check and the per-object opt-in gate +(`enable.files`, below). So a member attaches a file to a record they can edit, +and sees the files of a record they can read, and `security/explain` names +`storage_attachment_member` as the baseline that grants it. + +The set reaches no one else: + +- an external member (`org_external`) resolves its own baseline instead, and an + agent principal resolves no member baseline; an agent acting for a member + gets no more than that member, within its own scope; +- a deployment that declares no member baseline (`fallbackPermissionSet: null`) + hands it to no one; +- a host that registers `sys_attachment` without the storage service gets no + set, and a member's attach is refused `PERMISSION_DENIED` (403). All four + gates are the storage service's own, so wherever it runs they are present, + unless its data engine cannot carry them (no hook or middleware seam) or no + auth service is composed for the download check; then it contributes no set + either, and the boot log names the missing gate and what to add. + +The set carries **no edit and no delete** (ADR-0090 D5: a set every member holds +carries no delete bit). Editing or deleting attachments still needs an explicit +grant on `sys_attachment` (see Delete below). An app can also grant read and +create explicitly, as before; the baseline set adds nothing to such a grant. + ## The opt-in gate — `enable.files` Attachments are **opt-in per object** (spec default `false`). A `sys_attachment` @@ -33,10 +66,13 @@ Attachments panel renders only for such objects. Any other target is rejected: | Code | Status | When | | --- | --- | --- | -| `FILES_DISABLED` | 403 | Creating a `sys_attachment` whose `parent_object` is a registered object that does not declare `enable.files: true` | +| `FILES_DISABLED` | 403 | Creating a `sys_attachment` whose `parent_object` does not declare `enable.files: true` (an object that is not registered included), or re-pointing an existing one onto such an object | -This is enforced by a `beforeInsert` hook on `sys_attachment` and is -independent of the record-level checks below. +The storage service enforces it on every `sys_attachment` insert and re-point, +wherever it runs, for every caller, the system path and an administrator +included. It reads the object's current definition on each write, so an object +switched to `files: true` is attachable at once. It is independent of the +record-level checks below, and answers before them. ## Create — parent-edit access & provenance @@ -164,12 +200,14 @@ floor binds still cannot edit another user's attachment row (`PERMISSION_DENIED`), even as a parent editor. -The platform baseline permission set (`member_default`, the `everyone` -anchor) grants **no delete** on `sys_attachment` (ADR-0090 D5 — delete is not a -baseline right). Attachment management is therefore enabled by an ordinary, -position-distributed permission set that grants `sys_attachment` CRUD. Until a -member holds such a set, a delete is refused by RBAC (`PERMISSION_DENIED`) -before the attachment-level gate above is even consulted. +The member baseline (the `everyone` anchor: `member_default` and the storage +service's `storage_attachment_member`) grants **read and create** on +`sys_attachment` and **no edit or delete** (ADR-0090 D5 — delete is not a +baseline right). Managing attachments — editing or deleting them — is therefore +enabled by an ordinary, position-distributed permission set that grants edit +and delete on `sys_attachment`. Until a member holds such a set, a delete is +refused by RBAC (`PERMISSION_DENIED`) before the attachment-level gate above is +even consulted. ## Download — authenticated & parent-scoped @@ -254,13 +292,18 @@ can be shared across records). Reclamation is handled by the platform LifecycleS ## Enforcement summary +Every operation also needs its object grant on `sys_attachment`, refused +`PERMISSION_DENIED` (403) without it. Read and create come with the member +baseline (`storage_attachment_member`, where every attachment gate is +present); edit and delete need an explicit grant. + | Operation | Requirement | Deny code | | --- | --- | --- | | Attach (create) | parent object opts in (`enable.files`) | `FILES_DISABLED` (403) | | Attach on upload completion (`attachTo`) | the caller's own pending, unattached `attachments`-scope upload, then every create check | `PERMISSION_DENIED` (403) / `RESOURCE_CONFLICT` (409), then the create codes | | Attach (create), re-point | a by-id update of the parent record by the caller would be admitted | `ATTACHMENT_PARENT_ACCESS` (403); `OBJECT_NOT_FOUND` (404) when the parent object is not registered | | List / read | inherits parent read visibility | *(filtered out)* | -| Delete | uploader or parent editor (+ RBAC delete grant) | `ATTACHMENT_DELETE_DENIED` (403); `PERMISSION_DENIED` (403) when the parent is not readable or no delete grant is held | +| Delete | uploader or parent editor (+ an explicit delete grant) | `ATTACHMENT_DELETE_DENIED` (403); `PERMISSION_DENIED` (403) when the parent is not readable or no delete grant is held | | Download | session + owner-or-parent-read (attachments scope); session only for a file with no parent; none for `acl: 'public_read'` | `AUTH_REQUIRED` (401) / `ATTACHMENT_DOWNLOAD_DENIED` (403) | ## See also diff --git a/content/docs/permissions/permission-sets.mdx b/content/docs/permissions/permission-sets.mdx index 23dedd36e68..64258a43d82 100644 --- a/content/docs/permissions/permission-sets.mdx +++ b/content/docs/permissions/permission-sets.mdx @@ -185,6 +185,14 @@ the boot writes no row for them: | `member_default` | Per-org | Standard end-user CRUD; **writes owner-scoped** via `positions: ['org_member']`-domained RLS | The additive baseline — applies to every authenticated request *in addition to* explicit grants (ADR-0090 D5) | | `viewer_readonly` | Per-org | Read access only | Auditors / read-only stakeholders | +A platform service can contribute a baseline set of its own beside +`member_default`, through the security service, during boot only, and only for +read and create on objects it registers itself. The storage service contributes +`storage_attachment_member` (read and create on `sys_attachment`), which every +member holds through the `everyone` anchor wherever the storage service installs +its attachment gates; see +[Who holds the object grant](/docs/permissions/attachments-access#who-holds-the-object-grant). + **Who holds `admin_full_access` is not (only) a grant row.** `PLATFORM_ADMIN` standing is derived at a single site from **two anchors**. Which of them is sufficient depends on the deployment's 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 af3ddbad3b1..63ff6f2bb45 100644 --- a/packages/plugins/plugin-security/src/catalog-reference-report.test.ts +++ b/packages/plugins/plugin-security/src/catalog-reference-report.test.ts @@ -625,8 +625,11 @@ describe('[ADR-0131 D3/D4] SecurityPlugin runs the report at kernel:bootstrapped ]); const handlers = b.hooks.get('kernel:bootstrapped') ?? []; - // This report alone: the grant-name backfill that ran ahead of it is retired (ADR-0131 D10). - expect(handlers).toHaveLength(1); + // 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); 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/platform-baseline-sets.integration.test.ts b/packages/plugins/plugin-security/src/platform-baseline-sets.integration.test.ts new file mode 100644 index 00000000000..dec651af512 --- /dev/null +++ b/packages/plugins/plugin-security/src/platform-baseline-sets.integration.test.ts @@ -0,0 +1,324 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The platform baseline seam on a real stack: a platform service registers an + * object, contributes a read-and-create set for it from its `kernel:ready` + * handler, and the REAL `SecurityPlugin` hands that set to every member — and + * to no one else. + * + * - the REAL `SecurityPlugin` with the shipped permission sets and an app set + * that names nothing of the service's; + * - the REAL caller resolution (`resolveAuthzContext`, then + * `assembleExecutionContext`), so a member's `everyone` anchor and an + * external's lack of it are the resolver's answer; + * - the contributor registered AFTER the security plugin, so its set lands + * after the anchor's `kernel:ready` derivation and the anchor's definition + * names it only through the derivation owed at `kernel:bootstrapped`. + * + * What it pins: a member reads and creates the contributed object and nothing + * more; the explainer names the set as the baseline that grants it; the + * `everyone` definition names it; an external member and an agent principal + * gain nothing; a contribution naming another package's object is refused on + * the real registry; the window is closed once the kernel has bootstrapped; + * and a deployment declaring no member baseline hands the set to no one. + * Each refusal rule on its own: `platform-baseline-sets.test.ts`. + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { ObjectKernel, resolveAuthzContext, assembleExecutionContext, type Plugin, type PluginContext } from '@objectstack/core'; +import { ObjectQL, ObjectQLPlugin } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import type { ISecurityService, PlatformBaselineSetContribution } from '@objectstack/spec/contracts'; +import { mapDataError } from '@objectstack/types'; +import { SecurityPlugin } from './security-plugin.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; + +/** The platform service's package id, and the object it registers. */ +/** The members this suite drives, each one the plugin serves. */ +type SecurityService = Required>; + +const SERVICE = 'com.example.service.notes'; +const NOTE = 'pbs_note'; +/** An object another package registers. */ +const LEDGER = 'pbs_ledger'; +const ORG = 'org_pbs'; +const ALICE = 'usr_pbs_alice'; +const EVE = 'usr_pbs_eve'; +const SYS = { isSystem: true, tenantId: ORG } as const; + +const SERVICE_SET = { + name: 'pbs_notes_member', + label: 'Notes (every member)', + objects: { [NOTE]: { allowRead: true, allowCreate: true } }, +}; + +/** The app's member set: its own object only. */ +const APP_SET = PermissionSetSchema.parse({ + name: 'pbs_app_member', + objects: { [LEDGER]: { allowRead: true, allowCreate: false, allowEdit: false, allowDelete: false } }, +}); + +type Ctx = Record; +type Outcome = { joined: boolean } | { refused: string }; +/** What the kernel's logger was handed during boot, by level: `[message, meta]` per call. */ +type BootLogs = { info: unknown[][]; warn: unknown[][] }; + +function sqliteDriverPlugin(): Plugin { + return { + name: 'test.pbs.driver', + type: 'standard', + version: '1.0.0', + async init(ctx: PluginContext) { + ctx.registerService( + 'driver.default', + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + ); + }, + }; +} + +const textObject = (name: string) => ({ name, label: name, fields: { name: { type: 'text', label: 'Name' } } }); + +/** The identity objects and the other package's object. */ +function appPlugin(): Plugin { + return { + name: 'test.pbs.app', + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql'], + async init(ctx: PluginContext) { + ctx.getService<{ register(m: unknown): unknown }>('manifest').register({ + id: 'test.pbs.app', + version: '1.0.0', + type: 'plugin', + name: 'Platform baseline app', + objects: [SysUser, SysMember, SysOrganization, textObject(LEDGER)], + }); + }, + }; +} + +/** + * The platform service: registers its object, and contributes from its + * `kernel:ready` handler — first a set naming the app's object, which the seam + * refuses, then its own set. + */ +function servicePlugin(outcomes: Record): Plugin { + return { + name: SERVICE, + type: 'standard', + version: '1.0.0', + dependencies: ['com.objectstack.engine.objectql'], + async init(ctx: PluginContext) { + ctx.getService<{ register(m: unknown): unknown }>('manifest').register({ + id: SERVICE, + version: '1.0.0', + type: 'plugin', + name: 'Notes service', + objects: [textObject(NOTE)], + }); + }, + async start(ctx: PluginContext) { + ctx.hook('kernel:ready', async () => { + const security = ctx.getService('security'); + const attempt = (set: unknown): Outcome => { + try { + return { joined: security.contributePlatformBaselineSet(SERVICE, set as PlatformBaselineSetContribution).joined }; + } catch (e) { + return { refused: (e as Error).message }; + } + }; + outcomes.others = attempt({ name: 'pbs_ledger_member', objects: { [LEDGER]: { allowRead: true } } }); + outcomes.own = attempt(SERVICE_SET); + }); + }, + }; +} + +async function boot(fallbackPermissionSet: string | null, outcomes: Record, logs?: BootLogs): Promise { + const kernel = new ObjectKernel({ logger: { level: 'silent' } }); + // Every plugin context logs through the kernel's one logger: the calls are + // the record, whatever level the logger then prints at. + const logger = (kernel as unknown as { logger: { info: (...a: unknown[]) => void; warn: (...a: unknown[]) => void } }).logger; + if (logs) { + vi.spyOn(logger, 'info').mockImplementation((...a: unknown[]) => void logs.info.push(a)); + vi.spyOn(logger, 'warn').mockImplementation((...a: unknown[]) => void logs.warn.push(a)); + } + await kernel.use(sqliteDriverPlugin()); + await kernel.use(new ObjectQLPlugin()); + await kernel.use(appPlugin()); + await kernel.use(new SecurityPlugin({ defaultPermissionSets: [...defaultPermissionSets, APP_SET], fallbackPermissionSet })); + await kernel.use(servicePlugin(outcomes)); + await kernel.bootstrap(); + return kernel; +} + +/** The wire answer a refused engine call maps to, as the data door sends it. */ +async function refusal(run: () => Promise, object: string): Promise<{ status: number; code: string } | 'admitted'> { + try { + await run(); + } catch (e) { + const wire = mapDataError(e, object); + return { status: wire.status, code: String(wire.body.code) }; + } + return 'admitted'; +} + +async function seedPeople(ql: ObjectQL): Promise { + await ql.insert('sys_organization', { id: ORG, name: 'Notes Co', slug: 'notes-co' }, { context: SYS } as never); + for (const [userId, role] of [[ALICE, 'member'], [EVE, 'external']] as const) { + await ql.insert('sys_user', { id: userId, name: userId, email: `${userId}@notes.test`, email_verified: true }, { context: SYS } as never); + await ql.insert('sys_member', { user_id: userId, organization_id: ORG, role }, { context: SYS } as never); + } + await ql.insert(NOTE, { name: 'seeded note' }, { context: SYS } as never); +} + +async function contextOf(ql: ObjectQL, userId: string): Promise { + const authz = await resolveAuthzContext({ + ql, + headers: {}, + getSession: async () => ({ user: { id: userId }, session: { id: `ses_${userId}`, userId, activeOrganizationId: ORG } }), + } as never); + return assembleExecutionContext({ + authz, + oauth: undefined, + localization: undefined, + requestLocale: undefined, + accessToken: undefined, + } as never) as unknown as Ctx; +} + +describe('a platform service’s baseline set reaches every member, and no one else', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + let security: SecurityService; + const outcomes: Record = {}; + const logs: BootLogs = { info: [], warn: [] }; + const as: Record = {}; + + beforeAll(async () => { + kernel = await boot(APP_SET.name, outcomes, logs); + ql = kernel.getService('objectql'); + security = kernel.getService('security'); + await seedPeople(ql); + as.alice = await contextOf(ql, ALICE); + as.eve = await contextOf(ql, EVE); + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + it('the fixture is armed: the service’s own set joined, and the resolver gives a member the everyone anchor and an external none', () => { + expect(outcomes.own).toEqual({ joined: true }); + expect(as.alice.positions).toEqual(expect.arrayContaining(['org_member', 'everyone'])); + expect(as.eve.positions).toContain('org_external'); + expect(as.eve.positions).not.toContain('everyone'); + }); + + it('a member reads and creates the service’s object, and edits and deletes nothing of it', async () => { + const rows = (await ql.find(NOTE, { context: as.alice } as never)) as Array>; + expect(rows.map((r) => r.name)).toContain('seeded note'); + const created = (await ql.insert(NOTE, { name: 'alice wrote this' }, { context: as.alice } as never)) as { id: string }; + expect(created.id).toBeTruthy(); + expect(await refusal(() => ql.update(NOTE, { name: 'renamed' }, { where: { id: created.id }, context: as.alice } as never), NOTE)) + .toMatchObject({ status: 403 }); + expect(await refusal(() => ql.delete(NOTE, { where: { id: created.id }, context: as.alice } as never), NOTE)) + .toMatchObject({ status: 403 }); + }); + + it('the explainer names the service’s set as the baseline that grants it', async () => { + const decision = await security.explain({ object: NOTE, operation: 'create' }, as.alice); + expect(decision.allowed).toBe(true); + expect(decision.principal.permissionSets).toContain(SERVICE_SET.name); + const contributors = decision.layers.flatMap((l: any) => l.contributors ?? []); + expect(contributors).toEqual( + expect.arrayContaining([expect.objectContaining({ kind: 'permission_set', name: SERVICE_SET.name, via: 'additive baseline (ADR-0090 D5)' })]), + ); + }); + + it('the everyone anchor’s definition names it, though it landed after the kernel:ready derivation', () => { + const everyone = (ql as any).registry.getItem('position', 'everyone'); + expect(everyone?.permissionSets).toEqual([APP_SET.name, 'member_default', SERVICE_SET.name]); + }); + + it('the set is held in the catalog by the service’s own package', () => { + const item = (ql as any).registry.getItem('permission', SERVICE_SET.name); + expect(item?._packageId).toBe(SERVICE); + }); + + it('an external member gains nothing: the read and the create are both refused', async () => { + expect(await refusal(() => ql.find(NOTE, { context: as.eve } as never), NOTE)).toMatchObject({ status: 403 }); + expect(await refusal(() => ql.insert(NOTE, { name: 'eve' }, { context: as.eve } as never), NOTE)).toMatchObject({ status: 403 }); + const decision = await security.explain({ object: NOTE, operation: 'read' }, as.eve); + expect(decision.allowed).toBe(false); + expect(decision.principal.permissionSets).not.toContain(SERVICE_SET.name); + }); + + it('an agent principal gains nothing: it resolves no human baseline', async () => { + const agent = { userId: ALICE, tenantId: ORG, positions: [], permissions: [], principalKind: 'agent' as const }; + const sets = await security.resolvePermissionSetsForContext(agent); + expect(sets.map((s: { name: string }) => s.name)).not.toContain(SERVICE_SET.name); + expect(await refusal(() => ql.find(NOTE, { context: agent } as never), NOTE)).toMatchObject({ status: 403 }); + }); + + it('a set naming another package’s object is refused on the real registry, and grants nothing', async () => { + expect(outcomes.others).toEqual({ refused: expect.stringContaining(`'${LEDGER}' is registered by 'test.pbs.app', not by '${SERVICE}'`) }); + expect((ql as any).registry.getItem('permission', 'pbs_ledger_member')).toBeUndefined(); + }); + + it('every admission is logged: the set, its contributor, what it grants and that it joined the baseline', () => { + const admitted = logs.info.filter(([m]) => String(m).startsWith(`[security] platform baseline set '${SERVICE_SET.name}'`)); + expect(admitted).toEqual([ + [ + `[security] platform baseline set '${SERVICE_SET.name}' from '${SERVICE}': ${NOTE} (read, create) — ` + + 'joined the member baseline every signed-in member holds through the everyone anchor.', + { contributor: SERVICE, set: SERVICE_SET.name, joined: true }, + ], + ]); + }); + + it('every refusal is logged at warn, naming the contributor and the reason', () => { + const refused = logs.warn.filter(([m]) => String(m).includes(`platform baseline set from '${SERVICE}' refused`)); + expect(refused).toHaveLength(1); + expect(refused[0][0]).toContain(`'${LEDGER}' is registered by 'test.pbs.app', not by '${SERVICE}'`); + expect(refused[0][1]).toEqual({ contributor: SERVICE }); + }); + + it('the boot window is closed once the kernel has bootstrapped', () => { + expect(() => security.contributePlatformBaselineSet(SERVICE, SERVICE_SET)).toThrow(/boot window is closed/); + }); +}); + +describe('a deployment that declares no member baseline (fallbackPermissionSet: null)', () => { + let kernel: ObjectKernel; + let ql: ObjectQL; + const outcomes: Record = {}; + const logs: BootLogs = { info: [], warn: [] }; + + beforeAll(async () => { + kernel = await boot(null, outcomes, logs); + ql = kernel.getService('objectql'); + await seedPeople(ql); + }, 120_000); + + afterAll(async () => { + if (kernel) await Promise.race([kernel.shutdown(), new Promise((r) => setTimeout(r, 10_000))]); + }, 30_000); + + it('hands the set to no one: it is admitted, joins nothing, and a member is refused', async () => { + expect(outcomes.own).toEqual({ joined: false }); + const alice = await contextOf(ql, ALICE); + expect(await refusal(() => ql.find(NOTE, { context: alice } as never), NOTE)).toMatchObject({ status: 403 }); + expect(kernel.getService('security.baselinePermissionSets')).toEqual([]); + }); + + it('and the admission is logged as reaching no one', () => { + const admitted = logs.info.filter(([m]) => String(m).startsWith(`[security] platform baseline set '${SERVICE_SET.name}'`)); + expect(admitted).toHaveLength(1); + expect(admitted[0][0]).toContain('registered, and handed to no one: this deployment declares no member baseline'); + expect(admitted[0][1]).toEqual({ contributor: SERVICE, set: SERVICE_SET.name, joined: false }); + }); +}); diff --git a/packages/plugins/plugin-security/src/platform-baseline-sets.test.ts b/packages/plugins/plugin-security/src/platform-baseline-sets.test.ts new file mode 100644 index 00000000000..38d4c41940b --- /dev/null +++ b/packages/plugins/plugin-security/src/platform-baseline-sets.test.ts @@ -0,0 +1,234 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The platform baseline seam's rules, one refusal each (`platform-baseline-sets.ts`). + * + * A contribution reaches the member baseline only when it is made during boot, + * by the package that registers every object it names, with read and create + * bits alone, and no row policy or other key. Each case below changes one + * thing from an admitted contribution and expects the refusal that names it, + * with nothing registered and nothing joined. The real-kernel half (who the + * set reaches, the explainer, the anchor, the closed window on a booted + * kernel) is `platform-baseline-sets.integration.test.ts`. + */ + +import { describe, it, expect } from 'vitest'; +import { PermissionSetSchema } from '@objectstack/spec/security'; + +import { PlatformBaselineSets, type PlatformBaselineHost, type PlatformBaselineRegistry } from './platform-baseline-sets.js'; + +const CONTRIBUTOR = 'com.example.service.notes'; +const OWN = 'pbs_note'; +const OTHERS = 'pbs_ledger'; + +/** An admitted contribution: one own object, read and create. */ +const SET = Object.freeze({ + name: 'pbs_notes_member', + label: 'Notes', + objects: { [OWN]: { allowRead: true, allowCreate: true } }, +}); + +interface Rig { + host: PlatformBaselineHost; + registered: Array<{ type: string; item: Record; keyField: string; packageId?: string }>; +} + +function rig(opts: { baseline?: string[]; registerItem?: PlatformBaselineRegistry['registerItem']; registry?: null } = {}): Rig { + const registered: Rig['registered'] = []; + const owners: Record = { [OWN]: CONTRIBUTOR, pbs_draft: CONTRIBUTOR, [OTHERS]: 'com.example.other' }; + const registry: PlatformBaselineRegistry = { + getObjectOwner: (name) => (owners[name] ? { packageId: owners[name] } : undefined), + registerItem: + opts.registerItem ?? + ((type, item, keyField, packageId) => { + registered.push({ type, item, keyField, packageId }); + }), + }; + return { + registered, + host: { + baseline: opts.baseline ?? ['app_member', 'member_default'], + shipped: [PermissionSetSchema.parse({ name: 'member_default', objects: {} })], + registry: opts.registry === null ? undefined : registry, + }, + }; +} + +/** Contribute `raw` and answer the refusal's text, asserting nothing was registered or joined. */ +function refusalOf(raw: unknown, opts: Parameters[0] & { seams?: PlatformBaselineSets; contributor?: unknown } = {}): string { + const r = rig(opts); + const before = [...r.host.baseline]; + const seams = opts.seams ?? new PlatformBaselineSets(); + let message = ''; + try { + seams.contribute('contributor' in opts ? opts.contributor : CONTRIBUTOR, raw, r.host); + } catch (e) { + message = (e as Error).message; + } + expect(message, 'the contribution was refused').not.toBe(''); + expect(r.registered, 'a refused set is not registered').toEqual([]); + expect(r.host.baseline, 'a refused set joins nothing').toEqual(before); + return message; +} + +describe('an admitted contribution', () => { + it('is registered under the contributor, and its name joins the composed baseline in place', () => { + const r = rig(); + const baseline = r.host.baseline; + const admitted = new PlatformBaselineSets().contribute(CONTRIBUTOR, SET, r.host); + expect(admitted).toMatchObject({ contributor: CONTRIBUTOR, joined: true }); + expect(admitted.set.name).toBe(SET.name); + expect(admitted.set.objects[OWN]).toMatchObject({ allowRead: true, allowCreate: true, allowEdit: false, allowDelete: false }); + expect(r.registered).toHaveLength(1); + expect(r.registered[0]).toMatchObject({ type: 'permission', keyField: 'name', packageId: CONTRIBUTOR }); + expect(r.registered[0].item.name).toBe(SET.name); + // The same array every reader holds, grown in place. + expect(r.host.baseline).toBe(baseline); + expect(baseline).toEqual(['app_member', 'member_default', SET.name]); + }); + + it('joins nothing where the deployment declares no member baseline (fallbackPermissionSet: null)', () => { + const r = rig({ baseline: [] }); + const admitted = new PlatformBaselineSets().contribute(CONTRIBUTOR, SET, r.host); + expect(admitted.joined).toBe(false); + expect(r.host.baseline).toEqual([]); + expect(r.registered).toHaveLength(1); + }); + + it('the same contributor contributing the same name again replaces it and joins it once', () => { + const r = rig(); + const seams = new PlatformBaselineSets(); + seams.contribute(CONTRIBUTOR, SET, r.host); + seams.contribute(CONTRIBUTOR, { ...SET, objects: { [OWN]: { allowRead: true } } }, r.host); + expect(r.host.baseline.filter((n) => n === SET.name)).toHaveLength(1); + expect(seams.body(SET.name)?.objects[OWN]?.allowCreate).toBe(false); + }); + + it('a set that joined after the anchor was derived owes a re-derivation at close, and only then', () => { + const before = new PlatformBaselineSets(); + before.contribute(CONTRIBUTOR, SET, rig().host); + before.noteAnchorDerived(); + expect(before.close(), 'joined before the derivation: the derivation named it').toBe(false); + + const after = new PlatformBaselineSets(); + after.noteAnchorDerived(); + after.contribute(CONTRIBUTOR, SET, rig().host); + expect(after.close(), 'joined after the derivation began').toBe(true); + + const nothingJoined = new PlatformBaselineSets(); + nothingJoined.noteAnchorDerived(); + nothingJoined.contribute(CONTRIBUTOR, SET, rig({ baseline: [] }).host); + expect(nothingJoined.close(), 'a set that joined nothing owes nothing').toBe(false); + }); +}); + +describe('a refused contribution changes nothing', () => { + it('the contributor is not named', () => { + expect(refusalOf(SET, { contributor: '' })).toMatch(/contributing package is not named/); + }); + + it('the boot window has closed', () => { + const seams = new PlatformBaselineSets(); + seams.close(); + expect(refusalOf(SET, { seams })).toMatch(/boot window is closed/); + }); + + it('it is not a permission-set object', () => { + expect(refusalOf(['pbs_notes_member'])).toMatch(/not a permission-set object/); + }); + + it('it carries a row policy', () => { + const raw = { ...SET, rowLevelSecurity: [{ name: 'pbs_own', object: OWN, operation: 'select', using: 'owner_id == current_user.id' }] }; + expect(refusalOf(raw)).toMatch(/row policy \(rowLevelSecurity\)/); + }); + + it.each(['systemPermissions', 'fields', 'tabPermissions', 'isDefault', 'packageId'])('it carries the key %s', (key) => { + expect(refusalOf({ ...SET, [key]: key === 'isDefault' ? true : [] })).toMatch(new RegExp(`key '${key}' is not one`)); + }); + + it('it names no set', () => { + expect(refusalOf({ objects: SET.objects })).toMatch(/names no set/); + }); + + it('the contributor already contributed another set', () => { + const r = rig(); + const seams = new PlatformBaselineSets(); + seams.contribute(CONTRIBUTOR, SET, r.host); + expect(refusalOf({ ...SET, name: 'pbs_second' }, { seams })).toMatch(/already contributed the set 'pbs_notes_member'/); + }); + + it('another contributor already holds the name', () => { + const seams = new PlatformBaselineSets(); + seams.contribute(CONTRIBUTOR, SET, rig().host); + let message = ''; + try { + seams.contribute('com.example.other', { ...SET, objects: { [OTHERS]: { allowRead: true } } }, rig().host); + } catch (e) { + message = (e as Error).message; + } + expect(message).toMatch(/is the set 'com\.example\.service\.notes' contributed/); + }); + + it('the name is a shipped set', () => { + expect(refusalOf({ ...SET, name: 'member_default' })).toMatch(/a set this plugin ships/); + }); + + it('the engine exposes no registry', () => { + expect(refusalOf(SET, { registry: null })).toMatch(/exposes no registry/); + }); + + it('it names no object', () => { + expect(refusalOf({ ...SET, objects: {} })).toMatch(/names no object/); + }); + + it("it names '*'", () => { + expect(refusalOf({ ...SET, objects: { '*': { allowRead: true } } })).toMatch(/object '\*' is every object/); + }); + + it("it names another package's object", () => { + expect(refusalOf({ ...SET, objects: { [OTHERS]: { allowRead: true } } })).toMatch( + /'pbs_ledger' is registered by 'com\.example\.other', not by 'com\.example\.service\.notes'/, + ); + }); + + it('it names an object nobody registered', () => { + expect(refusalOf({ ...SET, objects: { pbs_ghost: { allowRead: true } } })).toMatch(/'pbs_ghost' is registered by no package/); + }); + + it.each([ + ['allowEdit', true], + ['allowDelete', true], + ['allowTransfer', true], + ['allowRestore', true], + ['allowExport', true], + ['viewAllRecords', true], + ['modifyAllRecords', true], + ['readScope', 'org'], + ['allowEdit', false], + ])('an object entry carries %s: %s', (bit, value) => { + expect(refusalOf({ ...SET, objects: { [OWN]: { allowRead: true, [bit]: value } } })).toMatch( + new RegExp(`carries '${bit}'\\. A platform baseline set grants read and create only`), + ); + }); + + it('a bit is not true or false', () => { + expect(refusalOf({ ...SET, objects: { [OWN]: { allowRead: 'yes' } } })).toMatch(/'pbs_note\.allowRead' is not true or false/); + }); + + it('an object entry grants nothing', () => { + expect(refusalOf({ ...SET, objects: { [OWN]: { allowRead: false, allowCreate: false } } })).toMatch(/grants nothing/); + }); + + it('it is not a well-formed permission set', () => { + expect(refusalOf({ ...SET, name: 'Not Snake' })).toMatch(/not a well-formed permission set/); + }); + + it('the registry refuses it (another holder of the name)', () => { + const message = refusalOf(SET, { + registerItem: () => { + throw new Error("permission 'pbs_notes_member' is held by package 'com.example.other'"); + }, + }); + expect(message).toMatch(/the registry refused the set: permission 'pbs_notes_member' is held/); + }); +}); diff --git a/packages/plugins/plugin-security/src/platform-baseline-sets.ts b/packages/plugins/plugin-security/src/platform-baseline-sets.ts new file mode 100644 index 00000000000..f2ea54b3a2f --- /dev/null +++ b/packages/plugins/plugin-security/src/platform-baseline-sets.ts @@ -0,0 +1,248 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The seam through which an always-on PLATFORM SERVICE contributes one + * permission set of its own to the member baseline (ADR-0090 D5), beside the + * row gates the service installs, and only where it installs them. + * + * ## Why a seam, and why not a line in `member_default` + * + * `member_default` is this plugin's own set, the baseline every member holds + * through the `everyone` anchor. ADR-0090 D9 (and its Alternatives 6) rules + * out the shape "a builtin permission set other packages write into", so an + * object another package registers and gates is not granted from there. And a + * static line in a shipped set would stay in force in a composition that + * registers the object WITHOUT the gates that decide its rows — there the + * object-level grant would be the last word on every row, the hazard the + * ownership-floor seam (`ownership-floor-alternates.ts`) was made for. So the + * service that registers the object and installs its gates hands over a set + * of its OWN, from the place it installs them, and this plugin decides where + * the set goes: into the deployment's composed baseline, which every reader of + * the baseline reads — the data plane's resolution, the explainer, the + * effective-access read, the describe fallback and the `everyone` anchor's + * definition. + * + * ## What a contribution is held to (each refusal is a thrown error) + * + * - **Boot only.** The window closes at `kernel:bootstrapped`, once every + * plugin's `kernel:ready` handler, where a service installs its gates, has + * run. A contribution after that is refused: the baseline is not a runtime + * write surface. + * - **A named contributor, one set each.** The contributor is the package + * that registers the objects. Its second contribution of the same name + * replaces the first; a second name is refused. + * - **Closed keys.** `name`, `label`, `description` and `objects`, nothing + * else: no row policy (`rowLevelSecurity`), no field rule, no system + * permission, no tab rule, no `isDefault`, no package key. + * - **The contributor's own objects only.** Every object the set names is one + * the engine registry holds with the contributor as its owner. ⛔ Never + * `'*'`, never another package's object, never a name nobody registered. + * - **Read and create only.** Each object entry carries `allowRead` and + * `allowCreate` and no other key — no edit, delete, transfer, restore, + * export, View All, Modify All or scope bit, not even set to `false` — and + * grants at least one of the two. The parsed set must also be anchor-safe + * by the anchor's own predicate (`describeHighPrivilegeBits`). + * - **A fresh name.** A name a shipped set or another holder already uses is + * refused (the registry's own one-holder rule answers the second). + * + * ## What an admitted contribution does + * + * The set is registered in the engine registry under the contributor's + * package — the catalog every set body is read from — and, when the deployment + * declares a member baseline at all, its name joins the composed baseline. A + * deployment that declares none (`fallbackPermissionSet: null`) hands out no + * baseline, so the set is registered and reaches no member through it. An + * external member resolves its own baseline in place of this one, and an agent + * principal's own leg resolves no human baseline (`external-baseline.ts`, + * ADR-0090 D10), so neither gains anything here in its own right. An agent + * acting for a member is bounded by that member and by its own scope, so it + * reaches what the member reaches, within that scope. Every admitted + * contribution, and every refusal, is logged by the seam that calls + * {@link PlatformBaselineSets.contribute}. + * + * This seam is for always-on platform services. A tenant-installed package + * suggests a default set and a `manage_metadata` holder accepts it + * (`suggested-audience-bindings.ts`, ADR-0090 D5); it does not contribute here. + */ + +import { describeHighPrivilegeBits, PermissionSetSchema } from '@objectstack/spec/security'; +import type { PermissionSet } from '@objectstack/spec/security'; + +/** The top-level keys a contributed set may carry. */ +const SET_KEYS: ReadonlySet = new Set(['name', 'label', 'description', 'objects']); + +/** The object-permission bits a contributed set may carry. */ +const OBJECT_BITS: ReadonlySet = new Set(['allowRead', 'allowCreate']); + +/** The registry members the seam uses: the object's owner, and the set's registration. */ +export interface PlatformBaselineRegistry { + getObjectOwner(name: string): { packageId?: string } | undefined; + registerItem(type: string, item: Record, keyField: string, packageId?: string): void; +} + +/** What the plugin hands the seam on each contribution. */ +export interface PlatformBaselineHost { + /** + * The composed baseline, joined IN PLACE: every reader of the baseline holds + * this array (`SecurityPlugin.baselinePermissionSets`), so a name pushed here + * is the one every reader sees. + */ + readonly baseline: string[]; + /** The shipped sets, whose names a contribution may not take. */ + readonly shipped: readonly PermissionSet[]; + /** The engine registry, read at the call; `undefined` when the engine exposes none. */ + readonly registry: PlatformBaselineRegistry | undefined; +} + +/** The outcome of an admitted contribution. */ +export interface PlatformBaselineContribution { + readonly contributor: string; + readonly set: PermissionSet; + /** Whether the name joined the composed baseline. */ + readonly joined: boolean; +} + +function refuse(contributor: string, detail: string): never { + throw new Error(`[security] platform baseline set from '${contributor}' refused: ${detail}`); +} + +function isPlainRecord(value: unknown): value is Record { + return !!value && typeof value === 'object' && !Array.isArray(value); +} + +/** + * The contributions in force, keyed by contributor, and the boot window they + * are admitted in. One instance per `SecurityPlugin`. + */ +export class PlatformBaselineSets { + private open = true; + private anchorDerived = false; + private joinedAfterDerivation = false; + private readonly byContributor = new Map(); + + /** + * Admit one contribution, or throw the refusal. See the module doc for the + * rules; each refusal names what was refused and why. + */ + contribute(contributor: unknown, raw: unknown, host: PlatformBaselineHost): PlatformBaselineContribution { + if (typeof contributor !== 'string' || contributor.length === 0) { + throw new Error('[security] platform baseline set refused: the contributing package is not named.'); + } + if (!this.open) { + refuse( + contributor, + 'the boot window is closed. A platform service contributes its baseline set during boot, from the ' + + 'kernel:ready handler that installs the gates the set relies on, and never after the kernel has bootstrapped.', + ); + } + if (!isPlainRecord(raw)) refuse(contributor, 'the contribution is not a permission-set object.'); + + for (const key of Object.keys(raw)) { + if (SET_KEYS.has(key)) continue; + if (key === 'rowLevelSecurity') { + refuse( + contributor, + 'it carries a row policy (rowLevelSecurity). The rows of a contributed object are decided by the gates its ' + + 'service installs; a baseline set grants the object, never a row rule.', + ); + } + refuse(contributor, `key '${key}' is not one a platform baseline set carries; it carries name, label, description and objects only.`); + } + + const name = raw.name; + if (typeof name !== 'string' || name.length === 0) refuse(contributor, 'it names no set.'); + const held = this.byContributor.get(contributor); + if (held && held.name !== name) { + refuse(contributor, `it already contributed the set '${held.name}'; a platform service contributes one set.`); + } + for (const [other, set] of this.byContributor) { + if (other !== contributor && set.name === name) refuse(contributor, `the name '${name}' is the set '${other}' contributed.`); + } + if (host.shipped.some((set) => set.name === name)) { + refuse(contributor, `the name '${name}' is a set this plugin ships.`); + } + + const registry = host.registry; + if (!registry || typeof registry.getObjectOwner !== 'function' || typeof registry.registerItem !== 'function') { + refuse(contributor, 'the engine exposes no registry that can tell who registers an object and hold the set.'); + } + + const objects = raw.objects; + if (!isPlainRecord(objects) || Object.keys(objects).length === 0) refuse(contributor, 'it names no object.'); + for (const [object, entry] of Object.entries(objects)) { + if (object === '*') { + refuse(contributor, "object '*' is every object; a platform baseline set names the objects its own service registers."); + } + const owner = registry.getObjectOwner(object)?.packageId; + if (owner !== contributor) { + refuse( + contributor, + owner === undefined + ? `object '${object}' is registered by no package; a platform baseline set names objects its contributor registers.` + : `object '${object}' is registered by '${owner}', not by '${contributor}'.`, + ); + } + if (!isPlainRecord(entry)) refuse(contributor, `the entry for '${object}' is not an object permission.`); + for (const [bit, value] of Object.entries(entry)) { + if (!OBJECT_BITS.has(bit)) { + refuse( + contributor, + `'${object}' carries '${bit}'. A platform baseline set grants read and create only (allowRead, allowCreate); ` + + 'every other bit is an elevated grant this channel does not carry, set to false included.', + ); + } + if (typeof value !== 'boolean') refuse(contributor, `'${object}.${bit}' is not true or false.`); + } + if (entry.allowRead !== true && entry.allowCreate !== true) { + refuse(contributor, `the entry for '${object}' grants nothing.`); + } + } + + const parsed = PermissionSetSchema.safeParse(raw); + if (!parsed.success) { + refuse(contributor, `it is not a well-formed permission set (${parsed.error.issues.map((i) => i.message).join('; ')}).`); + } + const set = parsed.data as PermissionSet; + const offending = describeHighPrivilegeBits(set); + if (offending) refuse(contributor, `it carries ${offending}, which the everyone anchor forbids.`); + + // The registry's own one-holder rule answers a name another package holds. + try { + registry.registerItem('permission', { ...set }, 'name', contributor); + } catch (e) { + refuse(contributor, `the registry refused the set: ${(e as Error)?.message ?? e}`); + } + this.byContributor.set(contributor, set); + + // A deployment that declares no baseline hands out none. + const joined = host.baseline.length > 0; + if (joined && !host.baseline.includes(set.name)) { + host.baseline.push(set.name); + if (this.anchorDerived) this.joinedAfterDerivation = true; + } + return { contributor, set, joined }; + } + + /** The body of the contributed set `name`, if one was admitted. */ + body(name: string): PermissionSet | undefined { + for (const set of this.byContributor.values()) if (set.name === name) return set; + return undefined; + } + + /** Said by the plugin as it starts the `everyone` derivation at `kernel:ready`. */ + noteAnchorDerived(): void { + this.anchorDerived = true; + } + + /** + * Close the boot window. Answers whether a set joined the baseline after the + * `kernel:ready` derivation of the `everyone` anchor began, so the anchor's + * definition must be derived again to name it. + */ + close(): boolean { + this.open = false; + const owed = this.joinedAfterDerivation; + this.joinedAfterDerivation = false; + return owed; + } +} diff --git a/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts b/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts index 83475e9c6cb..79da8dca56e 100644 --- a/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts +++ b/packages/plugins/plugin-security/src/registered-security-service-members.pin.test.ts @@ -49,6 +49,7 @@ import type { ISecurityService } from '@objectstack/spec/contracts'; import { SecurityPlugin } from './security-plugin.js'; import { OwnershipFloorAlternates } from './ownership-floor-alternates.js'; +import { PlatformBaselineSets } from './platform-baseline-sets.js'; /** `optional` exactly when the interface declares the member with `?`. */ type DeclaredOptionality = { @@ -82,6 +83,7 @@ const DECLARED_MEMBERS = { dismissAudienceBindingSuggestion: 'required', reopenAudienceBindingSuggestion: 'optional', contributeOwnershipFloorAlternates: 'optional', + contributePlatformBaselineSet: 'optional', organizationBoundaryFailure: 'optional', } as const satisfies DeclaredOptionality; @@ -210,5 +212,11 @@ describe('the registered `security` service serves only what ISecurityService de const contribute: NonNullable = (plugin, alternates) => new OwnershipFloorAlternates().contribute(plugin, alternates); expect(typeof contribute).toBe('function'); + + const contributeSet: NonNullable = (contributor, set) => { + const admitted = new PlatformBaselineSets().contribute(contributor, set, { baseline: [], shipped: [], registry: undefined }); + return { name: admitted.set.name, joined: admitted.joined }; + }; + expect(typeof contributeSet).toBe('function'); }); }); diff --git a/packages/plugins/plugin-security/src/security-plugin-security-service.ts b/packages/plugins/plugin-security/src/security-plugin-security-service.ts index 02ddca6bd43..0081b0ce37e 100644 --- a/packages/plugins/plugin-security/src/security-plugin-security-service.ts +++ b/packages/plugins/plugin-security/src/security-plugin-security-service.ts @@ -10,9 +10,10 @@ * grants and the explanation to the plugin's methods. It answers the write * bypass, the write scope, the delegation narrowing, the permission-set names * and the delegable scope in place, and it serves the audience-binding - * suggestions through the suggestion surface. `Object.assign` adds the two + * suggestions through the suggestion surface. `Object.assign` adds the * members the published contract does not type: the metadata-plane readable - * fields and the ownership-floor alternate seam. + * fields, the ownership-floor alternate seam, the platform baseline seam and + * the organization boundary. * * A MOVE, not a redesign. The function below is that one `try` statement of * `start()` as it stood, re-indented one level and otherwise unedited. It has @@ -62,6 +63,8 @@ import type { IMetadataService, IObjectQLEngine, ISecurityService, + PlatformBaselineSetAdmission, + PlatformBaselineSetContribution, } from '@objectstack/spec/contracts'; import type { ObjectAccessScope, PermissionSet } from '@objectstack/spec/security'; import type { SecurityPlugin } from './security-plugin.js'; @@ -73,6 +76,7 @@ import { } from './explain-engine.js'; import { organizationBoundaryFailure } from './delegated-admin-gate.js'; import type { OwnershipFloorAlternate } from './platform-ownership-policies.js'; +import type { PlatformBaselineRegistry } from './platform-baseline-sets.js'; import { listAudienceBindingSuggestions, confirmAudienceBindingSuggestion, @@ -92,9 +96,13 @@ import { */ export interface SecurityServiceHost { readonly acceptedDefaultPermissionSets: SecurityPlugin['acceptedDefaultPermissionSets']; + readonly baselinePermissionSets: SecurityPlugin['baselinePermissionSets']; + readonly bootstrapPermissionSets: SecurityPlugin['bootstrapPermissionSets']; readonly delegatedAdminGate: SecurityPlugin['delegatedAdminGate']; readonly logger: SecurityPlugin['logger']; readonly ownershipFloorAlternates: SecurityPlugin['ownershipFloorAlternates']; + readonly platformBaselineSets: SecurityPlugin['platformBaselineSets']; + readonly epoch: SecurityPlugin['epoch']; readonly permissionEvaluator: SecurityPlugin['permissionEvaluator']; readonly ql: SecurityPlugin['ql']; readonly tenancyPosture: SecurityPlugin['tenancyPosture']; @@ -119,7 +127,7 @@ export interface SecurityServiceHost { /** The `security` service registration `SecurityPlugin#start` runs; the comment above its call there is its contract. */ export function registerSecurityService( - this: Pick, + this: Pick, ctx: PluginContext, ql: IObjectQLEngine, metadata: IMetadataService, @@ -419,6 +427,38 @@ export function registerSecurityService( : alternates.map((a) => `${a.object}.${a.operation} (${a.name})`).join(', ')), ); }, + // The platform baseline seam — how an always-on platform service hands + // the member baseline a set of its own (read and create on objects it + // registers), from the place it installs the row gates those objects + // rely on, during boot only. Same extension pattern as the one above. + // Throws on a contribution the seam refuses — see + // `platform-baseline-sets.ts` for the rules. Every contribution is said, + // the refused ones included. + contributePlatformBaselineSet: (contributor: string, set: PlatformBaselineSetContribution): PlatformBaselineSetAdmission => { + let admitted; + try { + admitted = this.platformBaselineSets.contribute(contributor, set, { + baseline: this.baselinePermissionSets, + shipped: this.bootstrapPermissionSets, + registry: (this.ql as { registry?: PlatformBaselineRegistry } | undefined)?.registry, + }); + } catch (e) { + ctx.logger.warn((e as Error).message, { contributor }); + throw e; + } + const grants = Object.entries(admitted.set.objects ?? {}) + .map(([object, p]) => `${object} (${[p.allowRead ? 'read' : '', p.allowCreate ? 'create' : ''].filter(Boolean).join(', ')})`) + .join(', '); + ctx.logger.info( + `[security] platform baseline set '${admitted.set.name}' from '${admitted.contributor}': ${grants} — ` + + (admitted.joined + ? 'joined the member baseline every signed-in member holds through the everyone anchor.' + : 'registered, and handed to no one: this deployment declares no member baseline (fallbackPermissionSet: null).'), + { contributor: admitted.contributor, set: admitted.set.name, joined: admitted.joined }, + ); + if (admitted.joined) this.epoch.bump('metadata'); + return { name: admitted.set.name, joined: admitted.joined }; + }, // [ADR-0090 D12] The organization boundary, judged by the gate's own // predicate against this engine's security catalog: `null` when the set // is inside, else the reason. plugin-auth's identity-provider group diff --git a/packages/plugins/plugin-security/src/security-plugin.ts b/packages/plugins/plugin-security/src/security-plugin.ts index 6792b04ea09..4f449c4c11a 100644 --- a/packages/plugins/plugin-security/src/security-plugin.ts +++ b/packages/plugins/plugin-security/src/security-plugin.ts @@ -276,6 +276,7 @@ import { owdOpenWritesCoversOperation, } from './platform-ownership-policies.js'; import { OwnershipFloorAlternates } from './ownership-floor-alternates.js'; +import { PlatformBaselineSets } from './platform-baseline-sets.js'; import { refuseUndeclaredExternalObjectScope, registeredObjectsOf, @@ -1601,6 +1602,15 @@ export class SecurityPlugin implements Plugin { */ private readonly ownershipFloorAlternates = new OwnershipFloorAlternates(); + /** + * The permission sets always-on platform services contributed to the member + * baseline at boot, beside the row gates they install — joined into + * {@link baselinePermissionSets} in place, so every reader of the baseline + * reads them, and closed to contributions at `kernel:bootstrapped`. The + * seam and its rules: `platform-baseline-sets.ts`. + */ + private readonly platformBaselineSets = new PlatformBaselineSets(); + constructor(options: SecurityPluginOptions = {}) { this.bootstrapPermissionSets = options.defaultPermissionSets ?? securityDefaultPermissionSets; @@ -1891,7 +1901,18 @@ export class SecurityPlugin implements Plugin { // which is a database read. Derived again on every accept, revoke, // uninstall and package publish (`declareEveryone`). if (typeof (ctx as any).hook === 'function') { - (ctx as any).hook('kernel:ready', () => this.declareEveryone(ctx.logger)); + (ctx as any).hook('kernel:ready', () => { + this.platformBaselineSets.noteAnchorDerived(); + return this.declareEveryone(ctx.logger); + }); + // The platform baseline seam's boot window closes once every plugin's + // `kernel:ready` handler — where a platform service installs its gates + // and contributes its set — has run. A set that joined the baseline + // after the derivation above began is not yet named by the anchor's + // definition, so the anchor is derived again before anything serves. + (ctx as any).hook('kernel:bootstrapped', async () => { + if (this.platformBaselineSets.close()) await this.declareEveryone(ctx.logger); + }); } // [ADR-0131 D3/D4] Bind the security catalog read to this engine: every @@ -2230,8 +2251,11 @@ export class SecurityPlugin implements Plugin { const readPermissionEvaluator = () => this.permissionEvaluator; const readQl = () => this.ql; const readTenancyPosture = () => this.tenancyPosture; - const host: Pick = { + const readEpoch = () => this.epoch; + const host: Pick = { acceptedDefaultPermissionSets: this.acceptedDefaultPermissionSets, + baselinePermissionSets: this.baselinePermissionSets, + bootstrapPermissionSets: this.bootstrapPermissionSets, canExport: (...a) => this.canExport(...a), canReadObject: (...a) => this.canReadObject(...a), checkAuthoredRowWrite: (...a) => this.checkAuthoredRowWrite(...a), @@ -2240,6 +2264,7 @@ export class SecurityPlugin implements Plugin { get delegatedAdminGate() { return readDelegatedAdminGate(); }, describeEffectiveAccess: (...a) => this.describeEffectiveAccess(...a), describePositionGrants: (...a) => this.describePositionGrants(...a), + get epoch() { return readEpoch(); }, explainAccessForCaller: (...a) => this.explainAccessForCaller(...a), getEffectiveObjectPermissions: (...a) => this.getEffectiveObjectPermissions(...a), getMetadataReadableFields: (...a) => this.getMetadataReadableFields(...a), @@ -2252,6 +2277,7 @@ export class SecurityPlugin implements Plugin { get logger() { return readLogger(); }, ownershipFloorAlternates: this.ownershipFloorAlternates, get permissionEvaluator() { return readPermissionEvaluator(); }, + platformBaselineSets: this.platformBaselineSets, get ql() { return readQl(); }, resolvePermissionSetsForContext: (...a) => this.resolvePermissionSetsForContext(...a), get tenancyPosture() { return readTenancyPosture(); }, @@ -2376,7 +2402,7 @@ export class SecurityPlugin implements Plugin { onWithheld?: (set: string, offending: string) => void, ): string[] { return this.baselinePermissionSets.filter((name) => { - const boot = this.bootstrapPermissionSets.find((p) => p.name === name); + const boot = this.bootstrapPermissionSets.find((p) => p.name === name) ?? this.platformBaselineSets.body(name); const offending = boot ? describeHighPrivilegeBits(boot, context) : null; if (offending) onWithheld?.(name, offending); return !offending; diff --git a/packages/qa/dogfood/test/member-attachment-baseline.dogfood.test.ts b/packages/qa/dogfood/test/member-attachment-baseline.dogfood.test.ts new file mode 100644 index 00000000000..36139a466f1 --- /dev/null +++ b/packages/qa/dogfood/test/member-attachment-baseline.dogfood.test.ts @@ -0,0 +1,513 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// Every member attaches files to the records they can edit, and sees the files +// of the records they can read, with no `sys_attachment` grant from the app. +// +// The member here holds only what a `create-objectstack` app ships: a set that +// names the app's own objects and nothing of `sys_attachment`. The grant comes +// from the storage service's own set (`storage_attachment_member`, read and +// create), which it hands to the member baseline beside the attachment row +// gates it installs. Driven end to end through the REAL surfaces, over the +// attachments fixture's four objects: +// +// att_case — public read/write: the member edits it, so they attach; +// and another user's attachment on it is visible to them. +// att_readonly — public read: the member reads another user's record and +// cannot edit it, so the attach is refused ATTACHMENT_PARENT_ACCESS. +// att_secret — private: another user's record is unreadable, and so are +// its attachments, in the list and in its total. +// att_nofiles — no `enable.files`: still FILES_DISABLED. +// +// Both attach doors a member reaches are driven: the upload-complete door with +// `attachTo` (the record page's Attachments panel) and the single-use link the +// MCP `create_upload_link` tool mints with `attachments: true` — minted on the +// member's session and by an agent acting for the member on an OAuth token, +// which reaches what the member and its own scope both allow. The explainer +// names the storage set as the baseline that grants the object. A host that +// composes `sys_attachment` WITHOUT the storage service hands a member no +// grant: the same member is refused 403. And a composition of the storage +// service and the security plugin alone hands the grant out, with the opt-in +// (`enable.files`) still refusing: every gate the grant relies on is the +// storage service's own. + +import { createHash, randomBytes } from 'node:crypto'; +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { mkdtempSync, promises as fs } from 'node:fs'; +import { join } from 'node:path'; +import { tmpdir } from 'node:os'; +import { bootStack, type VerifyStack } from '@objectstack/verify'; +import { StorageServicePlugin } from '@objectstack/service-storage'; +import { AuditPlugin } from '@objectstack/plugin-audit'; +import { MCPServerPlugin } from '@objectstack/mcp'; +import { SecurityPlugin, securityDefaultPermissionSets } from '@objectstack/plugin-security'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { SysAttachment } from '@objectstack/platform-objects/audit'; +import { attachmentsFixtureStack } from './fixtures/attachments-fixture.js'; + +const SYS = { isSystem: true } as const; +const MEMBER_EMAIL = 'att-baseline-member@verify.test'; +const STORAGE_SET = 'storage_attachment_member'; +const MEMBER_PASSWORD = 'Member-Pass-123'; +const REDIRECT_URI = 'http://127.0.0.1:33419/callback'; +const WRITE_SCOPE = 'openid profile email offline_access data:read data:write'; +const READ_SCOPE = 'openid profile email offline_access data:read'; + +/** The app's every-member set: its own objects, and nothing of `sys_attachment` or `sys_file`. */ +const appMemberSet = PermissionSetSchema.parse({ + name: 'att_baseline_app_member', + label: 'Attachments baseline — the app set', + objects: { + att_case: { allowRead: true, allowCreate: true, allowEdit: true }, + att_readonly: { allowRead: true, allowCreate: true, allowEdit: true }, + att_secret: { allowRead: true, allowCreate: true, allowEdit: true }, + att_nofiles: { allowRead: true, allowCreate: true, allowEdit: true }, + }, +}); + +const appSecurity = () => + new SecurityPlugin({ + defaultPermissionSets: [...securityDefaultPermissionSets, appMemberSet], + fallbackPermissionSet: appMemberSet.name, + }); + +const json = { 'Content-Type': 'application/json' }; +const bearer = (token: string) => ({ Authorization: `Bearer ${token}` }); + +async function createdId(res: Response): Promise { + const j = (await res.json()) as any; + const id = j.id ?? j.record?.id ?? j.data?.id; + if (!id) throw new Error(`create response carried no id: ${JSON.stringify(j)}`); + return String(id); +} + +describe('a member attaches to the records they edit and sees the files of the records they read, with no app grant', () => { + let stack: VerifyStack; + let rootDir: string; + let ql: any; + let adminTok: string; + let memberTok: string; + let memberId: string; + let adminId: string; + let caseId: string; + let readonlyId: string; + let ownSecretId: string; + let adminSecretId: string; + let nofilesId: string; + let adminAttachmentId: string; + let adminCaseId: string; + let adminCaseAttachmentId: string; + let agentWriteTok: string; + let agentReadTok: string; + let priorOidc: string | undefined; + + /** + * An access token for an MCP client the member connects (authorization code + * with PKCE, on the member's own sign-in): the agent acts for the member, + * within `scope`. + */ + async function mintAgentToken(email: string, password: string, scope: string): Promise { + const authSvc: any = await stack.kernel.getServiceAsync('auth'); + const resource = authSvc.getMcpResourceUrl(); + const reg = await stack.api('/auth/oauth2/register', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ client_name: 'attachment agent', redirect_uris: [REDIRECT_URI], grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', application_type: 'native', scope }), + }); + const regBody: any = await reg.json(); + expect(reg.status, JSON.stringify(regBody)).toBe(201); + const signin = await stack.api('/auth/sign-in/email', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ email, password }) }); + const cookie = ((signin.headers as any).getSetCookie() as string[]).map((c) => c.split(';')[0]).join('; '); + const verifier = randomBytes(32).toString('base64url'); + const challenge = createHash('sha256').update(verifier).digest('base64url'); + const qs = new URLSearchParams({ client_id: regBody.client_id, redirect_uri: REDIRECT_URI, response_type: 'code', scope, state: 'st', code_challenge: challenge, code_challenge_method: 'S256', resource }); + const az = await stack.api(`/auth/oauth2/authorize?${qs}`, { headers: { cookie }, redirect: 'manual' }); + const loc = az.headers.get('location') ?? ''; + let code = new URL(loc, 'http://localhost:3000').searchParams.get('code'); + if (!code) { + const consent = await stack.api('/auth/oauth2/consent', { method: 'POST', headers: { 'content-type': 'application/json', cookie, origin: 'http://localhost:3000' }, body: JSON.stringify({ accept: true, oauth_query: loc.slice(loc.indexOf('?')) }) }); + const cb: any = await consent.json().catch(() => null); + code = new URL(cb?.redirect_uri ?? cb?.url).searchParams.get('code'); + } + const tok = await stack.api('/auth/oauth2/token', { + method: 'POST', + headers: { 'content-type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ grant_type: 'authorization_code', code: code!, redirect_uri: REDIRECT_URI, client_id: regBody.client_id, code_verifier: verifier, resource }).toString(), + }); + const tj: any = await tok.json(); + expect(tok.status, JSON.stringify(tj)).toBe(200); + return String(tj.access_token); + } + + /** The tool names an MCP caller is offered. */ + /** Presign in the attachments scope and PUT the bytes: the panel's first two steps. */ + async function presignAndPut(token: string, name = 'notes.txt'): Promise { + const presign = await stack.api('/storage/upload/presigned', { + method: 'POST', + headers: { ...json, ...bearer(token) }, + body: JSON.stringify({ filename: name, mimeType: 'text/plain', size: 5, scope: 'attachments' }), + }); + expect(presign.status, 'presign').toBe(200); + const { data } = (await presign.json()) as any; + const put = await stack.raw(String(data.uploadUrl).replace(/^https?:\/\/[^/]+/, ''), { + method: 'PUT', + headers: data.headers ?? { 'content-type': 'text/plain' }, + body: 'hello', + }); + expect(put.status, 'raw PUT').toBeLessThan(300); + return String(data.fileId); + } + + /** The upload-complete door with `attachTo`: the panel's third step. */ + async function completeOnto(token: string, parentObject: string, parentId: string) { + const fileId = await presignAndPut(token); + const res = await stack.api('/storage/upload/complete', { + method: 'POST', + headers: { ...json, ...bearer(token) }, + body: JSON.stringify({ fileId, attachTo: { parentObject, parentId } }), + }); + return { fileId, status: res.status, body: (await res.json()) as any }; + } + + /** One MCP tools/call as `token`. */ + async function mcpCall(token: string, name: string, args: Record) { + const res = await stack.api('/mcp', { + method: 'POST', + headers: { ...json, Accept: 'application/json, text/event-stream', ...bearer(token) }, + body: JSON.stringify({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }), + }); + expect(res.status, `tools/call ${name}`).toBe(200); + const rpc: any = await res.json(); + expect(rpc.error, `tools/call ${name} JSON-RPC error`).toBeUndefined(); + return { isError: rpc.result?.isError === true, json: JSON.parse(rpc.result?.content?.[0]?.text ?? 'null') }; + } + + const linksOn = (parentId: string) => ql.find('sys_attachment', { where: { parent_id: parentId }, context: SYS }) as Promise; + const listAs = async (token: string, query = '') => { + const res = await stack.apiAs(token, 'GET', `/data/sys_attachment${query}`); + return { status: res.status, body: (await res.json()) as any }; + }; + + beforeAll(async () => { + priorOidc = process.env.OS_OIDC_PROVIDER_ENABLED; + process.env.OS_OIDC_PROVIDER_ENABLED = 'true'; + rootDir = mkdtempSync(join(tmpdir(), 'att-member-baseline-')); + stack = await bootStack(attachmentsFixtureStack as never, { + security: appSecurity(), + extraPlugins: [ + new StorageServicePlugin({ adapter: 'local', local: { rootDir }, bindToSettings: false }), + new AuditPlugin(), + new MCPServerPlugin(), + ], + }); + ql = await stack.kernel.getServiceAsync('objectql'); + adminTok = await stack.signIn(); + memberTok = await stack.signUp(MEMBER_EMAIL, MEMBER_PASSWORD); + memberId = String((await ql.findOne('sys_user', { where: { email: MEMBER_EMAIL }, context: SYS }))?.id); + adminId = String((await ql.findOne('sys_user', { where: { email: 'admin@objectos.ai' }, context: SYS }))?.id); + + const create = async (object: string, body: Record) => { + const res = await stack.apiAs(memberTok, 'POST', `/data/${object}`, body); + expect(res.status, `member creates ${object}`).toBeLessThan(300); + return createdId(res); + }; + caseId = await create('att_case', { name: 'member case' }); + ownSecretId = await create('att_secret', { name: 'member secret', owner_id: memberId }); + nofilesId = await create('att_nofiles', { name: 'plain' }); + readonlyId = String((await ql.insert('att_readonly', { name: 'admin readonly', owner_id: adminId }, { context: SYS })).id); + adminSecretId = String((await ql.insert('att_secret', { name: 'admin secret', owner_id: adminId }, { context: SYS })).id); + + // The admin attaches a file to their own secret record: a row the member must never see. + const adminAttach = await completeOnto(adminTok, 'att_secret', adminSecretId); + expect(adminAttach.status, JSON.stringify(adminAttach.body)).toBe(200); + adminAttachmentId = String(adminAttach.body.data.attachmentId); + // And one to their own case, which every member reads: another user's + // attachment on a record the member can read. + adminCaseId = String((await ql.insert('att_case', { name: 'admin case', owner_id: adminId }, { context: SYS })).id); + const adminCaseAttach = await completeOnto(adminTok, 'att_case', adminCaseId); + expect(adminCaseAttach.status, JSON.stringify(adminCaseAttach.body)).toBe(200); + adminCaseAttachmentId = String(adminCaseAttach.body.data.attachmentId); + + agentWriteTok = await mintAgentToken(MEMBER_EMAIL, MEMBER_PASSWORD, WRITE_SCOPE); + agentReadTok = await mintAgentToken(MEMBER_EMAIL, MEMBER_PASSWORD, READ_SCOPE); + }, 240_000); + + afterAll(async () => { + await stack?.stop(); + if (rootDir) await fs.rm(rootDir, { recursive: true, force: true }); + if (priorOidc === undefined) delete process.env.OS_OIDC_PROVIDER_ENABLED; + else process.env.OS_OIDC_PROVIDER_ENABLED = priorOidc; + }); + + it('precondition: the member holds no app grant on sys_attachment — the storage set is what grants it, and explain says so', async () => { + const res = await stack.apiAs(memberTok, 'GET', '/security/explain?object=sys_attachment&operation=create'); + expect(res.status).toBe(200); + const decision = (await res.json()) as any; + expect(decision.allowed).toBe(true); + expect(decision.principal.permissionSets).toEqual(expect.arrayContaining([appMemberSet.name, 'member_default', STORAGE_SET])); + const contributors = (decision.layers ?? []).flatMap((l: any) => l.contributors ?? []); + expect(contributors).toEqual( + expect.arrayContaining([expect.objectContaining({ kind: 'permission_set', name: STORAGE_SET, via: 'additive baseline (ADR-0090 D5)' })]), + ); + expect(Object.keys(appMemberSet.objects)).not.toContain('sys_attachment'); + // The grant is read and create: no delete, no edit. + const del = await stack.apiAs(memberTok, 'GET', '/security/explain?object=sys_attachment&operation=delete'); + expect(((await del.json()) as any).allowed).toBe(false); + }); + + it('attaches through the upload-complete door (attachTo) to a record they can edit, and lists it', async () => { + const out = await completeOnto(memberTok, 'att_case', caseId); + expect(out.status, JSON.stringify(out.body)).toBe(200); + expect(out.body.data).toMatchObject({ fileId: out.fileId, attachmentId: expect.any(String) }); + expect((await linksOn(caseId)).map((r) => r.uploaded_by)).toContain(memberId); + const list = await listAs(memberTok, `?parent_id=${caseId}`); + expect(list.status).toBe(200); + expect(JSON.stringify(list.body)).toContain(out.body.data.attachmentId); + }); + + it('attaches through the MCP create_upload_link door (attachments: true) to a record they can edit', async () => { + const minted = await mcpCall(memberTok, 'create_upload_link', { objectName: 'att_secret', recordId: ownSecretId, attachments: true }); + expect(minted.isError, JSON.stringify(minted.json)).toBe(false); + expect(minted.json).toMatchObject({ singleUse: true, attachments: true, recordId: ownSecretId }); + const put = await stack.raw(String(minted.json.url).replace(/^https?:\/\/[^/]+/, ''), { + method: 'PUT', + headers: { 'content-type': 'text/plain', 'x-file-name': 'via-mcp.txt', ...bearer(memberTok) }, + body: 'hello', + }); + const body: any = await put.json(); + expect(put.status, JSON.stringify(body)).toBe(200); + expect((await linksOn(ownSecretId)).map((r) => String(r.id))).toContain(String(body.data.attachmentId)); + }); + + it('an agent acting for the member on an OAuth token attaches where the member and its scope both allow, and nowhere else', async () => { + // Both allow: the member edits the case, and the token carries data:write. + const minted = await mcpCall(agentWriteTok, 'create_upload_link', { objectName: 'att_case', recordId: caseId, attachments: true }); + expect(minted.isError, JSON.stringify(minted.json)).toBe(false); + const put = await stack.raw(String(minted.json.url).replace(/^https?:\/\/[^/]+/, ''), { + method: 'PUT', + headers: { 'content-type': 'text/plain', 'x-file-name': 'via-agent.txt', ...bearer(memberTok) }, + body: 'hello', + }); + const body: any = await put.json(); + expect(put.status, JSON.stringify(body)).toBe(200); + const row = (await linksOn(caseId)).find((r) => String(r.id) === String(body.data.attachmentId)); + expect(row?.uploaded_by, 'stored as the member').toBe(memberId); + + // The member does not allow it: a record they read but may not edit. + const onReadonly = await mcpCall(agentWriteTok, 'create_upload_link', { objectName: 'att_readonly', recordId: readonlyId, attachments: true }); + expect(onReadonly.isError).toBe(true); + expect(onReadonly.json.error?.code).toBe('ATTACHMENT_PARENT_ACCESS'); + + // The scope does not allow it: the same call on a read-only token, on the + // same record the member edits, is refused at the door and mints nothing. + const before = (await linksOn(caseId)).length; + const onReadScope = await stack.api('/mcp', { + method: 'POST', + headers: { ...json, Accept: 'application/json, text/event-stream', ...bearer(agentReadTok) }, + body: JSON.stringify({ + jsonrpc: '2.0', + id: 1, + method: 'tools/call', + params: { name: 'create_upload_link', arguments: { objectName: 'att_case', recordId: caseId, attachments: true } }, + }), + }); + expect(onReadScope.status).toBe(200); + const refused: any = await onReadScope.json(); + expect(refused.result?.isError, JSON.stringify(refused)).toBe(true); + expect(JSON.stringify(refused.result?.content ?? [])).not.toContain('"url"'); + expect((await linksOn(caseId)).length).toBe(before); + }); + + it('a record they can read but not edit refuses the attach with ATTACHMENT_PARENT_ACCESS, and keeps nothing', async () => { + expect((await stack.apiAs(memberTok, 'GET', `/data/att_readonly/${readonlyId}`)).status).toBe(200); + const out = await completeOnto(memberTok, 'att_readonly', readonlyId); + expect([out.status, out.body.error?.code]).toEqual([403, 'ATTACHMENT_PARENT_ACCESS']); + expect(await linksOn(readonlyId)).toEqual([]); + const link = await mcpCall(memberTok, 'create_upload_link', { objectName: 'att_readonly', recordId: readonlyId, attachments: true }); + expect(link.isError).toBe(true); + expect(link.json.error?.code).toBe('ATTACHMENT_PARENT_ACCESS'); + }); + + it("another user's attachment on a record they can read is visible to them: listed and readable by id", async () => { + expect((await stack.apiAs(memberTok, 'GET', `/data/att_case/${adminCaseId}`)).status).toBe(200); + const byParent = await listAs(memberTok, `?parent_id=${adminCaseId}`); + expect(byParent.status).toBe(200); + expect(JSON.stringify(byParent.body)).toContain(adminCaseAttachmentId); + expect((await stack.apiAs(memberTok, 'GET', `/data/sys_attachment/${adminCaseAttachmentId}`)).status).toBe(200); + }); + + it("the attachments of a record they cannot read stay invisible: not listed, not counted, not readable by id", async () => { + expect((await stack.apiAs(memberTok, 'GET', `/data/att_secret/${adminSecretId}`)).status).not.toBe(200); + const all = await listAs(memberTok); + expect(all.status).toBe(200); + const ids = ((all.body.records ?? all.body.data ?? []) as any[]).map((r) => String(r.id)); + expect(ids).not.toContain(adminAttachmentId); + const total = Number(all.body.total ?? ids.length); + const stored = (await ql.find('sys_attachment', { where: {}, context: SYS })).length; + expect(total, 'the total counts only the rows the member may read').toBe(stored - 1); + const byParent = await listAs(memberTok, `?parent_id=${adminSecretId}`); + expect(JSON.stringify(byParent.body)).not.toContain(adminAttachmentId); + expect((await stack.apiAs(memberTok, 'GET', `/data/sys_attachment/${adminAttachmentId}`)).status).not.toBe(200); + }); + + it('an object without enable.files still refuses the attach with FILES_DISABLED', async () => { + const out = await completeOnto(memberTok, 'att_nofiles', nofilesId); + expect([out.status, out.body.error?.code]).toEqual([403, 'FILES_DISABLED']); + expect(await linksOn(nofilesId)).toEqual([]); + }); +}); + +// A host that composes `sys_attachment` WITHOUT the storage service: the object +// is there, its row gates are not, and so no grant is handed out. A stand-in +// under the storage service's registered name keeps the always-on slate from +// mounting the real plugin; a second plugin registers the object as the +// storage service would. +const noStorageService = { + name: 'com.objectstack.service.storage', + type: 'standard' as const, + version: '0.0.0', + async init() {}, + async start() {}, +}; +const sysAttachmentWithoutStorage = { + name: 'com.dogfood.member-attachment-without-storage', + type: 'standard' as const, + version: '0.0.0', + optionalDependencies: ['com.objectstack.engine.objectql'], + async init(ctx: any) { + ctx.getService('manifest').register({ + id: 'com.dogfood.member-attachment-without-storage', + name: 'sys_attachment without service-storage', + version: '0.0.0', + type: 'plugin', + scope: 'system', + objects: [SysAttachment], + }); + }, + async start() {}, +}; + +describe('a host composing sys_attachment without the storage service hands members no attachment grant', () => { + let stack: VerifyStack; + + beforeAll(async () => { + stack = await bootStack(attachmentsFixtureStack as never, { + security: appSecurity(), + extraPlugins: [noStorageService as never, sysAttachmentWithoutStorage as never, new AuditPlugin()], + }); + }, 120_000); + + afterAll(async () => { + await stack?.stop(); + }); + + it('the same member is refused the attachment create (403 PERMISSION_DENIED), and explain names no storage set', async () => { + await stack.signIn(); + const tok = await stack.signUp('att-baseline-nostorage@verify.test'); + const caseRes = await stack.apiAs(tok, 'POST', '/data/att_case', { name: 'no storage here' }); + expect(caseRes.status).toBeLessThan(300); + const caseId = await createdId(caseRes); + const res = await stack.apiAs(tok, 'POST', '/data/sys_attachment', { + parent_object: 'att_case', + parent_id: caseId, + file_id: 'file-without-storage', + file_name: 'hello.txt', + }); + expect(res.status).toBe(403); + expect(((await res.json()) as any).code).toBe('PERMISSION_DENIED'); + const explain = (await (await stack.apiAs(tok, 'GET', '/security/explain?object=sys_attachment&operation=create')).json()) as any; + expect(explain.allowed).toBe(false); + expect(explain.principal.permissionSets).not.toContain(STORAGE_SET); + }); +}); + +// A composition of the storage service and the security plugin alone, with no +// other optional capability: every attachment gate is the storage service's +// own, so the grant is handed out here too, and an object that has not opted +// in to attachments refuses them for everyone, the administrator included. +describe('the storage service and the security plugin alone: members are granted attachments, and the opt-in still refuses', () => { + let stack: VerifyStack; + let rootDir: string; + let adminTok: string; + let memberTok: string; + let ql: any; + + beforeAll(async () => { + rootDir = mkdtempSync(join(tmpdir(), 'att-member-baseline-alone-')); + stack = await bootStack(attachmentsFixtureStack as never, { + security: appSecurity(), + extraPlugins: [new StorageServicePlugin({ adapter: 'local', local: { rootDir }, bindToSettings: false })], + }); + ql = await stack.kernel.getServiceAsync('objectql'); + adminTok = await stack.signIn(); + memberTok = await stack.signUp('att-baseline-alone@verify.test'); + }, 120_000); + + afterAll(async () => { + await stack?.stop(); + if (rootDir) await fs.rm(rootDir, { recursive: true, force: true }); + }); + + /** Presign, PUT and complete onto one record as `token`. */ + async function attachAs(token: string, parentObject: string, parentId: string) { + const presign = await stack.api('/storage/upload/presigned', { + method: 'POST', + headers: { ...json, ...bearer(token) }, + body: JSON.stringify({ filename: 'notes.txt', mimeType: 'text/plain', size: 5, scope: 'attachments' }), + }); + expect(presign.status, 'presign').toBe(200); + const { data } = (await presign.json()) as any; + const put = await stack.raw(String(data.uploadUrl).replace(/^https?:\/\/[^/]+/, ''), { + method: 'PUT', + headers: data.headers ?? { 'content-type': 'text/plain' }, + body: 'hello', + }); + expect(put.status, 'raw PUT').toBeLessThan(300); + const complete = await stack.api('/storage/upload/complete', { + method: 'POST', + headers: { ...json, ...bearer(token) }, + body: JSON.stringify({ fileId: data.fileId, attachTo: { parentObject, parentId } }), + }); + const body = (await complete.json()) as any; + return { status: complete.status, code: body.error?.code ?? body.code, body }; + } + + const linksOn = (parentId: string) => ql.find('sys_attachment', { where: { parent_id: parentId }, context: SYS }) as Promise; + + it('control: the storage service runs, and no other capability that enforces the opt-in is composed', () => { + expect(stack.kernel.getService('storage')).toBeTruthy(); + expect(() => stack.kernel.getService('audit')).toThrow(); + }); + + it('the member attaches to a record they edit, and explain names the storage set', async () => { + const caseRes = await stack.apiAs(memberTok, 'POST', '/data/att_case', { name: 'storage alone' }); + expect(caseRes.status).toBeLessThan(300); + const caseId = await createdId(caseRes); + const out = await attachAs(memberTok, 'att_case', caseId); + expect(out.status, JSON.stringify(out.body)).toBe(200); + expect(await linksOn(caseId)).toHaveLength(1); + const explain = (await (await stack.apiAs(memberTok, 'GET', '/security/explain?object=sys_attachment&operation=create')).json()) as any; + expect(explain.allowed).toBe(true); + expect(explain.principal.permissionSets).toContain(STORAGE_SET); + }); + + it('an object without enable.files refuses the attach with FILES_DISABLED, for the member and the administrator alike', async () => { + const plainRes = await stack.apiAs(memberTok, 'POST', '/data/att_nofiles', { name: 'not opted in' }); + expect(plainRes.status).toBeLessThan(300); + const plainId = await createdId(plainRes); + expect(await attachAs(memberTok, 'att_nofiles', plainId)).toMatchObject({ status: 403, code: 'FILES_DISABLED' }); + expect(await attachAs(adminTok, 'att_nofiles', plainId)).toMatchObject({ status: 403, code: 'FILES_DISABLED' }); + expect(await linksOn(plainId)).toEqual([]); + }); + + it('a re-point onto an object without enable.files is refused too, even on the system path', async () => { + const caseId = String((await ql.insert('att_case', { name: 'repoint source' }, { context: SYS })).id); + const plainId = String((await ql.insert('att_nofiles', { name: 'repoint target' }, { context: SYS })).id); + const out = await attachAs(adminTok, 'att_case', caseId); + expect(out.status, JSON.stringify(out.body)).toBe(200); + const attachmentId = String(out.body.data.attachmentId); + await expect( + ql.update('sys_attachment', { id: attachmentId, parent_object: 'att_nofiles', parent_id: plainId }, { context: SYS }), + ).rejects.toMatchObject({ code: 'FILES_DISABLED' }); + expect((await ql.findOne('sys_attachment', { where: { id: attachmentId }, context: SYS }))?.parent_object).toBe('att_case'); + }); +}); diff --git a/packages/qa/dogfood/test/print-service-archive.dogfood.test.ts b/packages/qa/dogfood/test/print-service-archive.dogfood.test.ts index 2ee736aa20c..a804fc06c4a 100644 --- a/packages/qa/dogfood/test/print-service-archive.dogfood.test.ts +++ b/packages/qa/dogfood/test/print-service-archive.dogfood.test.ts @@ -245,12 +245,12 @@ describe('print service on a real showcase boot', () => { expect(await ql.findOne('showcase_invoice', { where: { id: ownInvoice } }, { context: ctx })).not.toBeNull(); mint.mockClear(); renderPdf.mockClear(); - // The showcase grants the auditor no attachment create at all: the insert's - // own CRUD answer, asked before the render. (The attach-rule leg, - // ATTACHMENT_PARENT_ACCESS, is pinned against the real insert gate in - // service-storage's file-attachment-service.test.ts.) + // The auditor holds attachment create through the member baseline (the + // storage service's own set, `attachment-member-grant.ts`), so the + // insert passes the object grant and the attach rule answers: the + // auditor may read the invoice but not edit it. Asked before the render. expect(await refusalOf(service.printRecordToFile(request(ownInvoice), ctx))).toEqual({ - code: 'PERMISSION_DENIED', + code: 'ATTACHMENT_PARENT_ACCESS', status: 403, }); expect(mint).not.toHaveBeenCalled(); diff --git a/packages/qa/dogfood/test/security-catalog-showcase.dogfood.test.ts b/packages/qa/dogfood/test/security-catalog-showcase.dogfood.test.ts index 22c5ba13fe2..4e635e867b4 100644 --- a/packages/qa/dogfood/test/security-catalog-showcase.dogfood.test.ts +++ b/packages/qa/dogfood/test/security-catalog-showcase.dogfood.test.ts @@ -52,11 +52,31 @@ const stack = showcaseStack as unknown as { capabilities?: Named[]; }; +/** + * The permission sets platform services contribute to the member baseline at + * boot (`ISecurityService.contributePlatformBaselineSet`, #32754). An admitted + * set is registered in the catalog under the contributing package, so the read + * lists it, the door lists it, and it resolves by name: it is the set the + * `everyone` definition and explain name, and a catalog that hid it would name + * a set it cannot resolve. The storage service contributes one, + * `storage_attachment_member` (read and create on `sys_attachment`), on every + * composition that runs it, since every gate it waits for is its own; the + * showcase runs it in every posture below. Named here as its producer names it + * (`attachment-member-grant.ts`, not exported), never read off a registry. + */ +const PLATFORM_CONTRIBUTED_PERMISSION_SETS = ['storage_attachment_member']; + /** The declared catalog, read off the producers — never off a registry. */ const DECLARED: Record = { // [ADR-0131 D2] plus the six built-in positions `plugin-security` declares. position: [...new Set([...namesOf(stack.positions), ...BUILTIN_IDENTITY_NAMES, ...AUDIENCE_ANCHOR_POSITIONS])].sort(), - permission: [...new Set([...namesOf(stack.permissions), ...namesOf(securityDefaultPermissionSets)])].sort(), + permission: [ + ...new Set([ + ...namesOf(stack.permissions), + ...namesOf(securityDefaultPermissionSets), + ...PLATFORM_CONTRIBUTED_PERMISSION_SETS, + ]), + ].sort(), // [ADR-0131 D3] plus the curated platform capabilities `plugin-security` declares. capability: [...new Set([...namesOf(stack.capabilities), ...PLATFORM_CAPABILITY_NAMES])].sort(), }; diff --git a/packages/qa/dogfood/test/showcase-d7-default-profile.dogfood.test.ts b/packages/qa/dogfood/test/showcase-d7-default-profile.dogfood.test.ts index e064a386c7b..83cafdf1f80 100644 --- a/packages/qa/dogfood/test/showcase-d7-default-profile.dogfood.test.ts +++ b/packages/qa/dogfood/test/showcase-d7-default-profile.dogfood.test.ts @@ -110,9 +110,13 @@ describe('showcase: app-declared default profile, CLI-wired (ADR-0056 D7)', () = // no `sys_position` or junction row for it. const reader = createSecurityCatalogReader({ registry: ql.registry, metadata: stack.kernel.getService('metadata') }); const everyone = await reader.resolve('position', 'everyone'); + // The storage service's attachment set joins them, contributed beside the + // attachment gates, all of which are its own (`attachment-member-grant.ts`, + // service-storage). expect((everyone?.definition as any)?.permissionSets, 'everyone ← app baseline AND platform baseline').toEqual([ 'showcase_member_default', 'member_default', + 'storage_attachment_member', ]); if (ql.getObject?.('sys_position_permission_set')) { expect(await ql.find('sys_position_permission_set', { where: {}, context: SYS }), 'no junction row is written').toEqual([]); diff --git a/packages/services/service-storage/src/attachment-access-hooks.ts b/packages/services/service-storage/src/attachment-access-hooks.ts index 3bd4c3fd4de..777d1f9623f 100644 --- a/packages/services/service-storage/src/attachment-access-hooks.ts +++ b/packages/services/service-storage/src/attachment-access-hooks.ts @@ -26,11 +26,13 @@ import { findReferenceableFile, unreadableFileMessage, type FileReferenceReadAut * sys_attachment access enforcement (#2755, ADR-0049 enforce-or-remove). * * `sys_attachment` rows are written through the generic data path, and the - * default member permission sets grant wildcard CRUD with no row scoping — - * without these hooks any member can attach files to records they cannot - * see and rewrite or delete any other user's attachments. Salesforce - * semantics (ContentDocumentLink): an attachment's access is derived from - * its PARENT record. + * object grant scopes no rows: every member holds read and create on the + * object through the storage service's own baseline set (contributed beside + * these gates, `attachment-member-grant.ts`), and an app may grant more — + * without these hooks any member could attach files to records they cannot + * see, and a holder of edit or delete could rewrite or delete any other + * user's attachments. Salesforce semantics (ContentDocumentLink): an + * attachment's access is derived from its PARENT record. * * - beforeInsert: the caller must be able to EDIT the parent record (see * "Parent EDIT" below; Salesforce parity, #2970 item 3 — v1 asked read diff --git a/packages/services/service-storage/src/attachment-files-opt-in.test.ts b/packages/services/service-storage/src/attachment-files-opt-in.test.ts new file mode 100644 index 00000000000..acce3ebd169 --- /dev/null +++ b/packages/services/service-storage/src/attachment-files-opt-in.test.ts @@ -0,0 +1,121 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import { describe, expect, it } from 'vitest'; +import { installAttachmentFilesOptInGate } from './attachment-files-opt-in.js'; + +type Handler = (ctx: unknown) => unknown; + +function engineWith(definitions: Record, extra: Record = {}) { + const hooks: Array<{ event: string; fn: Handler; opts: any }> = []; + const engine = { + registerHook: (event: string, fn: Handler, opts: any) => { + hooks.push({ event, fn, opts }); + }, + getSchema: (name: string) => definitions[name], + ...extra, + }; + return { engine, hooks }; +} + +const write = (data: Record, session?: Record) => ({ input: { data }, session }); + +describe('installAttachmentFilesOptInGate: the per-object attachment opt-in, enforced by the storage service', () => { + it('installs on sys_attachment insert and update, under the storage package, and says so', () => { + const { engine, hooks } = engineWith({}); + expect(installAttachmentFilesOptInGate(engine)).toBe(true); + expect(hooks.map((h) => [h.event, h.opts])).toEqual([ + ['beforeInsert', { object: 'sys_attachment', packageId: 'com.objectstack.service.storage' }], + ['beforeUpdate', { object: 'sys_attachment', packageId: 'com.objectstack.service.storage' }], + ]); + }); + + it('an engine without the hook seam: not installed, and says so', () => { + expect(installAttachmentFilesOptInGate({} as never)).toBe(false); + }); + + it('an engine that refuses the registration: not installed, and says so', () => { + const engine = { + registerHook: () => { + throw new Error('no hooks today'); + }, + }; + expect(installAttachmentFilesOptInGate(engine)).toBe(false); + }); + + const DEFINITIONS = { + opted: { name: 'opted', enable: { files: true } }, + off: { name: 'off', enable: { files: false } }, + silent: { name: 'silent', enable: {} }, + bare: { name: 'bare' }, + }; + + it.each([ + ['declares files: false', 'off'], + ['declares an enable block without files', 'silent'], + ['declares no enable block', 'bare'], + ['is not registered', 'nowhere'], + ])('refuses an attachment onto an object that %s (403 FILES_DISABLED), on insert and on re-point alike', async (_why, parent) => { + const { engine, hooks } = engineWith(DEFINITIONS); + installAttachmentFilesOptInGate(engine); + for (const { fn } of hooks) { + await expect(fn(write({ parent_object: parent, parent_id: 'r1' }))).rejects.toMatchObject({ + code: 'FILES_DISABLED', + status: 403, + object: parent, + }); + } + }); + + it('admits an attachment onto an object that declares files: true', async () => { + const { engine, hooks } = engineWith(DEFINITIONS); + installAttachmentFilesOptInGate(engine); + for (const { fn } of hooks) { + await expect(fn(write({ parent_object: 'opted', parent_id: 'r1' }))).resolves.toBeUndefined(); + } + }); + + it('the system context is not exempt: the opt-in is a statement about the object, not the caller', async () => { + const { engine, hooks } = engineWith(DEFINITIONS); + installAttachmentFilesOptInGate(engine); + await expect(hooks[0].fn(write({ parent_object: 'bare', parent_id: 'r1' }, { isSystem: true }))).rejects.toMatchObject({ + code: 'FILES_DISABLED', + }); + }); + + it('a write naming no parent object has nothing to ask: left to validation on insert, not a re-point on update', async () => { + const { engine, hooks } = engineWith(DEFINITIONS); + installAttachmentFilesOptInGate(engine); + for (const { fn } of hooks) { + await expect(fn(write({ title: 'renamed' }))).resolves.toBeUndefined(); + await expect(fn(write({ parent_object: '' }))).resolves.toBeUndefined(); + await expect(fn({})).resolves.toBeUndefined(); + } + }); + + it('a definition that cannot be read refuses: no schema lookup, or one that throws', async () => { + const hooks: Handler[] = []; + installAttachmentFilesOptInGate({ + registerHook: (_event: string, fn: Handler) => { + hooks.push(fn); + }, + }); + await expect(hooks[0](write({ parent_object: 'opted' }))).rejects.toMatchObject({ code: 'FILES_DISABLED' }); + + const throwing = engineWith({}, { + getSchema: () => { + throw new Error('registry offline'); + }, + }); + installAttachmentFilesOptInGate(throwing.engine); + await expect(throwing.hooks[0].fn(write({ parent_object: 'opted' }))).rejects.toMatchObject({ code: 'FILES_DISABLED' }); + }); + + it('reads the live definition on every write: an object switched to files: true is attachable on the next write', async () => { + const definitions: Record = { later: { name: 'later', enable: { files: false } } }; + const { engine, hooks } = engineWith(definitions); + installAttachmentFilesOptInGate(engine); + await expect(hooks[0].fn(write({ parent_object: 'later' }))).rejects.toMatchObject({ code: 'FILES_DISABLED' }); + definitions.later = { name: 'later', enable: { files: true } }; + await expect(hooks[0].fn(write({ parent_object: 'later' }))).resolves.toBeUndefined(); + }); +}); diff --git a/packages/services/service-storage/src/attachment-files-opt-in.ts b/packages/services/service-storage/src/attachment-files-opt-in.ts new file mode 100644 index 00000000000..fd4d71365de --- /dev/null +++ b/packages/services/service-storage/src/attachment-files-opt-in.ts @@ -0,0 +1,100 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The per-object attachment opt-in (`enable.files`), enforced by the storage + * service itself on every `sys_attachment` write that makes a row target an + * object. + * + * `enable.files` is opt-IN (spec default `false`): an object must declare + * `enable: { files: true }` before an attachment may target it. Fail-closed: + * an absent enable block, an absent flag, an unknown object and a definition + * that cannot be read all refuse, `403 FILES_DISABLED`. The refusal is the + * declaration's own: a create, and an update that re-points an existing + * attachment onto another object, alike (the re-point is inside the + * declaration whether or not a row was created). An update that does not name + * a new parent object is not a re-point and has nothing to ask. + * + * Why here, beside the other attachment gates: the storage service registers + * `sys_attachment` and is always on, and it hands every member an object + * grant on it (`attachment-member-grant.ts`) only where every gate that + * judges the rows is present. So the declaration is enforced by the service + * that registers the object, and holds wherever the object does (maintainer + * ruling on #32754, route A). Another gate that enforces the same declaration + * on the same writes may also run; both read the one live definition and + * refuse with the one code, so they cannot disagree. + * + * Not gated: a file-class field (`Field.file` / `Field.image`). It stores the + * file reference in the record's own column and writes no `sys_attachment` + * row, so it is independent of this declaration. + * + * The system context is NOT exempt. The opt-in is a statement about the + * object, not about the caller: the server-side attach verb + * (`file-attachment-service.ts`) acts as the system and is refused here, as + * its contract says. + * + * ⛔ No cache of the answer. The definition is read from the engine on every + * write: the registry is its one owner and memoizes it behind its own + * invalidation points, so an object switched to `files: true` through the + * metadata door is attachable on the next write, without a restart. + */ + +/** The slice of the data engine the opt-in gate needs. */ +export interface AttachmentFilesOptInEngine { + registerHook( + event: string, + handler: (ctx: any) => void | Promise, + options?: { object?: string; packageId?: string }, + ): void; + /** The object's current definition; absent, every attachment is refused. */ + getSchema?(objectName: string): unknown; +} + +const PACKAGE_ID = 'com.objectstack.service.storage'; + +/** The refusal an attachment onto an object that has not opted in meets. */ +export function filesDisabledError(parentObject: string): Error & { code: string; status: number; object: string } { + const err = new Error( + `File attachments are not enabled for object '${parentObject}' (requires enable.files: true)`, + ) as Error & { code: string; status: number; object: string }; + err.code = 'FILES_DISABLED'; + err.status = 403; + err.object = parentObject; + return err; +} + +/** + * Install the opt-in gate on `sys_attachment` inserts and updates. Returns + * whether it is installed, which is what the member grant reads: `false` when + * the engine offers no hook seam or refuses the registration, so nothing is + * left half installed in the grant's eyes. + */ +export function installAttachmentFilesOptInGate(engine: AttachmentFilesOptInEngine): boolean { + if (!engine || typeof engine.registerHook !== 'function') return false; + + const readDefinition = (objectName: string): any => { + try { + return typeof engine.getSchema === 'function' ? engine.getSchema(objectName) : null; + } catch { + return null; // unreadable reads as undeclared: refused + } + }; + + const enforce = async (ctx: any): Promise => { + const parentObject = ctx?.input?.data?.parent_object; + // On an insert an absent `parent_object` is a schema violation, left to + // validation to report so this gate never shadows it; on an update it + // means the write is not a re-point. Either way there is no target to ask + // about. + if (typeof parentObject !== 'string' || parentObject.length === 0) return; + const definition = readDefinition(parentObject); + if (definition?.enable?.files !== true) throw filesDisabledError(parentObject); + }; + + try { + engine.registerHook('beforeInsert', enforce, { object: 'sys_attachment', packageId: PACKAGE_ID }); + engine.registerHook('beforeUpdate', enforce, { object: 'sys_attachment', packageId: PACKAGE_ID }); + } catch { + return false; + } + return true; +} diff --git a/packages/services/service-storage/src/attachment-member-grant.test.ts b/packages/services/service-storage/src/attachment-member-grant.test.ts new file mode 100644 index 00000000000..b5c599ae674 --- /dev/null +++ b/packages/services/service-storage/src/attachment-member-grant.test.ts @@ -0,0 +1,99 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * Every member's attachment grant, contributed beside the attachment row gates + * (`attachment-member-grant.ts`): the set itself, and every way it can fail to + * land. The pairing with the gates — contributed after the last of them is + * installed, and not at all on a kernel lacking one — is pinned in + * `storage-service-plugin.test.ts`; what a member can then do, on a real stack, + * in the dogfood suite `member-attachment-baseline.dogfood.test.ts`. + */ + +import { describe, it, expect, vi } from 'vitest'; + +import { + ATTACHMENT_MEMBER_GRANT_CONTRIBUTOR, + ATTACHMENT_MEMBER_PERMISSION_SET, + contributeAttachmentMemberGrant, + type AttachmentRowGates, +} from './attachment-member-grant.js'; + +const logger = () => ({ info: vi.fn(), warn: vi.fn(), debug: vi.fn() }); +const ALL_GATES: AttachmentRowGates = { writeRule: true, readVisibility: true, downloadCheck: true, filesOptIn: true }; + +describe("the members' attachment grant service-storage contributes", () => { + it('is read and create on sys_attachment, and nothing else', () => { + // Written out: the ruling is the expectation, so editing the module must + // not edit it too. No edit, no delete: a set every member holds through + // the everyone anchor carries no delete bit. + expect(ATTACHMENT_MEMBER_PERMISSION_SET.name).toBe('storage_attachment_member'); + expect(ATTACHMENT_MEMBER_PERMISSION_SET.objects).toEqual({ sys_attachment: { allowRead: true, allowCreate: true } }); + expect(Object.keys(ATTACHMENT_MEMBER_PERMISSION_SET).sort()).toEqual(['description', 'label', 'name', 'objects']); + expect(Object.isFrozen(ATTACHMENT_MEMBER_PERMISSION_SET)).toBe(true); + expect(Object.isFrozen(ATTACHMENT_MEMBER_PERMISSION_SET.objects.sys_attachment)).toBe(true); + }); + + it('lands through the seam when every gate is installed, keyed by this package', () => { + const contribute = vi.fn(() => ({ name: 'storage_attachment_member', joined: true })); + const log = logger(); + expect(contributeAttachmentMemberGrant(ALL_GATES, () => ({ contributePlatformBaselineSet: contribute }), log)).toBe('contributed'); + expect(contribute).toHaveBeenCalledTimes(1); + expect(contribute).toHaveBeenCalledWith(ATTACHMENT_MEMBER_GRANT_CONTRIBUTOR, ATTACHMENT_MEMBER_PERMISSION_SET); + expect(ATTACHMENT_MEMBER_GRANT_CONTRIBUTOR).toBe('com.objectstack.service.storage'); + expect(log.warn).not.toHaveBeenCalled(); + }); + + it.each([ + ['writeRule', 'the attachment write rule'], + ['readVisibility', 'the attachment read-visibility gate'], + ['downloadCheck', "the download door's parent-record check"], + ['filesOptIn', 'the per-object attachment opt-in gate'], + ] as const)('a kernel without %s contributes nothing, and says which gate is missing at warn', (gate, named) => { + const contribute = vi.fn(); + const log = logger(); + const gates = { ...ALL_GATES, [gate]: false }; + expect(contributeAttachmentMemberGrant(gates, () => ({ contributePlatformBaselineSet: contribute }), log)).toBe('gates-incomplete'); + expect(contribute).not.toHaveBeenCalled(); + expect(log.warn).toHaveBeenCalledTimes(1); + expect(String(log.warn.mock.calls[0][0])).toContain(named); + expect(String(log.warn.mock.calls[0][0])).toContain('members are NOT granted attachments'); + // and what an operator does about it + expect(String(log.warn.mock.calls[0][0])).toContain( + 'run the storage service on a data engine that offers hooks and middleware, beside an auth service', + ); + }); + + it('no security service: no object grant is enforced, nothing to contribute — quiet', () => { + const log = logger(); + const absent = () => { + throw new Error("service 'security' not registered"); + }; + expect(contributeAttachmentMemberGrant(ALL_GATES, absent, log)).toBe('no-security'); + expect(contributeAttachmentMemberGrant(ALL_GATES, () => undefined, log)).toBe('no-security'); + expect(log.warn).not.toHaveBeenCalled(); + }); + + it('a security service without the seam: members stay refused, said at warn', () => { + const log = logger(); + expect(contributeAttachmentMemberGrant(ALL_GATES, () => ({ contributeOwnershipFloorAlternates: vi.fn() }), log)).toBe('no-seam'); + expect(String(log.warn.mock.calls[0][0])).toContain('contributePlatformBaselineSet'); + }); + + it('a seam that refuses: members stay refused, the boot goes on, and the refusal is said at warn', () => { + const log = logger(); + const refusing = () => ({ + contributePlatformBaselineSet: () => { + throw new Error('the boot window is closed'); + }, + }); + expect(contributeAttachmentMemberGrant(ALL_GATES, refusing, log)).toBe('refused'); + expect(String(log.warn.mock.calls[0][0])).toContain('the boot window is closed'); + }); + + it('a deployment that declares no member baseline: admitted, and handed to no one', () => { + const log = logger(); + const seam = () => ({ contributePlatformBaselineSet: () => ({ name: 'storage_attachment_member', joined: false }) }); + expect(contributeAttachmentMemberGrant(ALL_GATES, seam, log)).toBe('no-baseline'); + expect(log.warn).not.toHaveBeenCalled(); + }); +}); diff --git a/packages/services/service-storage/src/attachment-member-grant.ts b/packages/services/service-storage/src/attachment-member-grant.ts new file mode 100644 index 00000000000..82b0dea8357 --- /dev/null +++ b/packages/services/service-storage/src/attachment-member-grant.ts @@ -0,0 +1,172 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +import type { AttachmentLifecycleLogger } from './attachment-lifecycle.js'; + +/** + * Every member's object-level grant on `sys_attachment`: read, and create. + * + * The rows of `sys_attachment` are decided by gates, never by the object + * grant: an insert needs edit on the parent record + * (`installAttachmentAccessHooks`), a list, count or aggregate returns only + * the rows whose parent record the caller can read + * (`installAttachmentReadVisibility`), the download door serves an + * attachments-scope file only to its uploader or a reader of a record it is + * attached to, and an insert or re-point onto an object that has not opted in + * to attachments (`enable.files`) is refused by the opt-in gate + * (`installAttachmentFilesOptInGate`). The object grant only opens the door to + * those gates. Since the + * platform baseline (`member_default`) carries no line for this object, a + * member who could edit a record still could not attach a file to it, nor see + * the files already attached to it, without an app granting the object + * explicitly. + * + * So this plugin grants it, as a set of its own handed to the member baseline, + * and only where every one of those gates is present: the set is contributed + * from the place this plugin installs its gates, after the last of them, and on + * a kernel that lacks any of the four nothing is contributed and members stay + * refused, loudly. A static line in a shipped set would stay in force in a + * composition that registers the object without these gates, where the object + * grant would decide every row; and ADR-0090 D9 rules out other packages + * writing into the platform's own baseline set. + * + * What the set is, and is not: + * - READ and CREATE on `sys_attachment`, nothing else. No edit and no delete: + * a set every member holds through the `everyone` anchor carries no delete + * bit (ADR-0090 D5). Managing attachments (detaching, re-pointing) stays an + * explicit grant. + * - It reaches the members of a deployment that declares a member baseline, + * and no one else: an external member resolves its own baseline instead, an + * agent principal's own leg resolves none, and a deployment that declares + * none (`fallbackPermissionSet: null`) hands this set to no one. An agent + * acting for a member is bounded by that member and by its own scope + * (ADR-0090 D10), so it reaches what the member reaches here, within that + * scope. + * - Wherever the set is contributed, an object that has not opted in to + * attachments (`enable.files`) refuses every attachment + * (`FILES_DISABLED`), and a parent record the caller cannot edit refuses + * the attach (`ATTACHMENT_PARENT_ACCESS`): both gates are this plugin's, + * installed before the set is contributed. + * + * The seam is `contributePlatformBaselineSet` on the `security` service, + * feature-detected because this package does not depend on plugin-security. + */ +export const ATTACHMENT_MEMBER_PERMISSION_SET = Object.freeze({ + name: 'storage_attachment_member', + label: 'Attachments: read and attach (every member)', + description: + 'Read and create on sys_attachment for every member, contributed by the storage service beside the attachment ' + + 'row gates. A member attaches a file to a record they can edit and sees the files of a record they can read.', + objects: Object.freeze({ + sys_attachment: Object.freeze({ allowRead: true, allowCreate: true }), + }), +} as const); + +/** The contributor key: the package that registers `sys_attachment` and installs its gates. */ +export const ATTACHMENT_MEMBER_GRANT_CONTRIBUTOR = 'com.objectstack.service.storage'; + +/** + * Which of the attachment gates this kernel has, each as its installation + * answered. All four must be `true` for the grant to be contributed. + */ +export interface AttachmentRowGates { + /** The write rule: the insert, update and delete gates on `sys_attachment` rows. */ + readonly writeRule: boolean; + /** The read-visibility middleware: list, count and aggregate see readable parents only. */ + readonly readVisibility: boolean; + /** The download door's parent-record check, which needs an auth service and a queryable engine. */ + readonly downloadCheck: boolean; + /** The per-object opt-in gate (`enable.files`) on the insert and re-point: `installAttachmentFilesOptInGate`'s answer. */ + readonly filesOptIn: boolean; +} + +/** The slice of plugin-security's `security` service this contribution uses. */ +interface PlatformBaselineSetSeam { + contributePlatformBaselineSet( + contributor: string, + set: typeof ATTACHMENT_MEMBER_PERMISSION_SET, + ): { name: string; joined: boolean }; +} + +export type AttachmentMemberGrantOutcome = + /** The set joined the member baseline. */ + | 'contributed' + /** The set was admitted, and the deployment declares no member baseline, so it reaches no one. */ + | 'no-baseline' + /** A gate is missing: nothing is contributed, said at `warn`. */ + | 'gates-incomplete' + /** No `security` service: no object grant is enforced, nothing to contribute. */ + | 'no-security' + /** A `security` service without the seam: members stay refused, said at `warn`. */ + | 'no-seam' + /** The seam refused the contribution: members stay refused, said at `warn`. */ + | 'refused'; + +/** The names of the gates `gates` lacks, in a fixed order. */ +function missingGates(gates: AttachmentRowGates): string[] { + const missing: string[] = []; + if (!gates.writeRule) missing.push('the attachment write rule (the engine has no hook seam)'); + if (!gates.readVisibility) missing.push('the attachment read-visibility gate (the engine has no middleware seam)'); + if (!gates.downloadCheck) { + missing.push("the download door's parent-record check (no auth service, or an engine that cannot be queried)"); + } + if (!gates.filesOptIn) missing.push('the per-object attachment opt-in gate, enable.files (the engine has no hook seam)'); + return missing; +} + +/** + * Contribute {@link ATTACHMENT_MEMBER_PERMISSION_SET} to the member baseline, + * when every attachment gate is present. ⛔ Call it only after the last + * of them is installed, from the place they are installed: that pairing is the + * maintainer's ruling, and the caller is the only place it can be kept. + * + * Every outcome other than `contributed` leaves members without the grant, + * which fails CLOSED (an attach is refused `PERMISSION_DENIED`, and the + * attachments of a record list as forbidden); the ones an operator can act on + * are logged. + */ +export function contributeAttachmentMemberGrant( + gates: AttachmentRowGates, + getSecurity: () => unknown, + logger: AttachmentLifecycleLogger, +): AttachmentMemberGrantOutcome { + const missing = missingGates(gates); + if (missing.length > 0) { + logger.warn( + '[storage] members are NOT granted attachments (read and create on sys_attachment): this kernel lacks ' + + `${missing.join('; ')}, so the rows would be judged by the object grant alone. A member's attach is refused ` + + 'until every gate is installed: run the storage service on a data engine that offers hooks and middleware, ' + + 'beside an auth service.', + ); + return 'gates-incomplete'; + } + let security: unknown; + try { + security = getSecurity(); + } catch { + security = undefined; + } + if (!security || typeof security !== 'object') { + logger.debug?.('[storage] no security service — no object grant is enforced, so there is no attachment grant to contribute'); + return 'no-security'; + } + const seam = security as Partial; + if (typeof seam.contributePlatformBaselineSet !== 'function') { + logger.warn( + '[storage] the security service offers no platform baseline seam (contributePlatformBaselineSet): members ' + + 'cannot attach files to the records they edit, nor see the files of the records they read, unless an app ' + + 'grants sys_attachment. Upgrade @objectstack/plugin-security to the version that ships the seam.', + ); + return 'no-seam'; + } + let admitted: { name: string; joined: boolean }; + try { + admitted = seam.contributePlatformBaselineSet(ATTACHMENT_MEMBER_GRANT_CONTRIBUTOR, ATTACHMENT_MEMBER_PERMISSION_SET); + } catch (err) { + logger.warn( + `[storage] the security service refused the members' attachment grant (${(err as Error)?.message ?? err}): ` + + 'members cannot attach files, nor see attachments, until this is resolved.', + ); + return 'refused'; + } + return admitted?.joined === false ? 'no-baseline' : 'contributed'; +} diff --git a/packages/services/service-storage/src/storage-service-plugin.test.ts b/packages/services/service-storage/src/storage-service-plugin.test.ts index eac549c27c2..506cbe2f364 100644 --- a/packages/services/service-storage/src/storage-service-plugin.test.ts +++ b/packages/services/service-storage/src/storage-service-plugin.test.ts @@ -486,7 +486,8 @@ describe('StorageServicePlugin: sys_file orphan lifecycle wiring (#2755)', () => // // The second `beforeInsert`/`beforeUpdate` pair is the file half of the // write gate (`installAttachmentFileReferenceGate`): the `file_id` a row - // names must be a file its caller may open. + // names must be a file its caller may open. The third is the per-object + // opt-in (`enable.files`, `attachment-files-opt-in.ts`, #32754 route A). expect(hookEvents.sort()).toEqual([ 'afterDelete', 'afterInsert', @@ -494,6 +495,8 @@ describe('StorageServicePlugin: sys_file orphan lifecycle wiring (#2755)', () => 'beforeDelete', 'beforeInsert', 'beforeInsert', + 'beforeInsert', + 'beforeUpdate', 'beforeUpdate', 'beforeUpdate', ]); @@ -577,6 +580,152 @@ describe('StorageServicePlugin: sys_file orphan lifecycle wiring (#2755)', () => expect(contribute.calls).toBe(0); }); + // Every member's attachment grant (read and create on sys_attachment) is + // contributed only once ALL FOUR attachment gates are in place — the write + // rule, the read-visibility middleware, the download door's parent-record + // check and the per-object opt-in gate — after the last of this plugin's, + // and never on a kernel that lacks one (maintainer ruling; + // `attachment-member-grant.ts`). + describe("the members' attachment grant, contributed beside the attachment gates", () => { + const MEMBER_SET = { + name: 'storage_attachment_member', + objects: { sys_attachment: { allowRead: true, allowCreate: true } }, + }; + + async function bootWith(engine: Record, opts: { auth?: boolean; auditService?: boolean } = {}) { + const dir = await fs.mkdtemp(join(tmpdir(), 'oss-member-grant-')); + const plugin = new StorageServicePlugin({ adapter: 'local', local: { rootDir: dir }, registerRoutes: false }); + const ctx = makeCtx(); + const order: string[] = []; + const contributions: unknown[][] = []; + ctx.registerService('objectql', { + find: async () => [], + findOne: async () => null, + update: async () => ({}), + getObject: () => undefined, + ...engine, + }); + if (opts.auth !== false) ctx.registerService('auth', { api: {} }); + // A service registered under the name of another capability that also + // enforces the opt-in decides nothing here: only an installed gate does. + if (opts.auditService) ctx.registerService('audit', {}); + ctx.registerService('security', { + contributeOwnershipFloorAlternates: () => {}, + contributePlatformBaselineSet: (...args: unknown[]) => { + order.push('grant'); + contributions.push(args); + return { name: 'storage_attachment_member', joined: true }; + }, + }); + await plugin.init(ctx); + await plugin.start(ctx); + await ctx._flushReady(); + return { ctx, order, contributions }; + } + + /** Objects by name: `opted` declares the attachment opt-in, `plain` does not. */ + const getSchema = (name: string) => + name === 'opted' ? { name, enable: { files: true } } : name === 'plain' ? { name, enable: {} } : undefined; + + /** A context-less insert naming `parentObject`: only the opt-in gate has anything to say to it. */ + const probe = (parentObject: string) => ({ input: { data: { parent_object: parentObject } } }); + + /** The `sys_attachment` insert gates, in installation order, each labelled by how it answers the probe. */ + async function insertGates(handlers: Array<(ctx: unknown) => unknown>): Promise { + const labels: string[] = []; + for (const fn of handlers) { + try { + await fn(probe('plain')); + labels.push('write rule'); + } catch (err) { + labels.push((err as { code?: string }).code === 'FILES_DISABLED' ? 'opt-in' : `refused ${String(err)}`); + } + } + return labels; + } + + function recordingEngine(order: string[]) { + const inserts: Array<(ctx: unknown) => unknown> = []; + const updates: Array<(ctx: unknown) => unknown> = []; + return { + inserts, + updates, + engine: { + getSchema, + registerHook: (event: string, fn: (ctx: unknown) => unknown, opts: any) => { + if (opts?.object !== 'sys_attachment') return; + if (event === 'beforeInsert') { + order.push(`insert gate ${inserts.length}`); + inserts.push(fn); + } + if (event === 'beforeUpdate') updates.push(fn); + }, + registerMiddleware: (_fn: unknown, opts: any) => { + if (opts?.object === 'sys_attachment') order.push('read visibility'); + }, + }, + }; + } + + it('contributes the set exactly once, after the opt-in gate, the write rule and the read-visibility middleware', async () => { + const order: string[] = []; + const rec = recordingEngine(order); + const booted = await bootWith(rec.engine); + expect(booted.contributions).toEqual([['com.objectstack.service.storage', expect.objectContaining(MEMBER_SET)]]); + // The grant comes last; it never exists without the gates before it. + expect([...order, ...booted.order]).toEqual(['insert gate 0', 'insert gate 1', 'insert gate 2', 'read visibility', 'grant']); + // The opt-in answers first, before any question about the caller. + expect(await insertGates(rec.inserts)).toEqual(['opt-in', 'write rule', 'write rule']); + expect(booted.ctx._logs.warn.filter((w: string) => w.includes('NOT granted attachments'))).toEqual([]); + }); + + it('a kernel without any other capability that enforces the opt-in: the gate is this service\'s own, so the grant is handed out and the opt-in still refuses', async () => { + const rec = recordingEngine([]); + const booted = await bootWith(rec.engine); + expect(() => booted.ctx.getService('audit')).toThrow(); + expect(booted.contributions).toHaveLength(1); + // insert and re-point alike + for (const gate of [rec.inserts[0], rec.updates[0]]) { + await expect(gate(probe('plain'))).rejects.toMatchObject({ code: 'FILES_DISABLED', status: 403, object: 'plain' }); + await expect(gate(probe('unknown_object'))).rejects.toMatchObject({ code: 'FILES_DISABLED', status: 403 }); + await expect(gate(probe('opted'))).resolves.toBeUndefined(); + } + }); + + it('an engine without the middleware seam: no read-visibility gate, so no grant — said at warn', async () => { + const booted = await bootWith({ registerHook: () => {} }); + expect(booted.contributions).toEqual([]); + const warned = booted.ctx._logs.warn.filter((w: string) => w.includes('NOT granted attachments')); + expect(warned).toHaveLength(1); + expect(warned[0]).toContain('read-visibility'); + }); + + it('a kernel without an auth service: no download check binds, so no grant — said at warn', async () => { + const booted = await bootWith({ registerHook: () => {}, registerMiddleware: () => {} }, { auth: false }); + expect(booted.contributions).toEqual([]); + const warned = booted.ctx._logs.warn.filter((w: string) => w.includes('NOT granted attachments')); + expect(warned).toHaveLength(1); + expect(warned[0]).toContain("download door's parent-record check"); + }); + + it('a kernel that registers a service by the name of another opt-in enforcer, on an engine without the hook seam: no opt-in gate, so no grant — the name counts for nothing', async () => { + const booted = await bootWith({ registerMiddleware: () => {} }, { auditService: true }); + expect(booted.ctx.getService('audit')).toBeDefined(); + expect(booted.contributions).toEqual([]); + const warned = booted.ctx._logs.warn.filter((w: string) => w.includes('NOT granted attachments')); + expect(warned).toHaveLength(1); + expect(warned[0]).toContain('per-object attachment opt-in gate'); + }); + + it('an engine without the hook seam: no write rule, so no grant — said at warn', async () => { + const booted = await bootWith({ registerMiddleware: () => {} }); + expect(booted.contributions).toEqual([]); + const warned = booted.ctx._logs.warn.filter((w: string) => w.includes('NOT granted attachments')); + expect(warned).toHaveLength(1); + expect(warned[0]).toContain('write rule'); + }); + }); + it('degrades silently on a bare kernel (no engine, no lifecycle service)', async () => { const dir = await fs.mkdtemp(join(tmpdir(), 'oss-bare-')); const plugin = new StorageServicePlugin({ adapter: 'local', local: { rootDir: dir }, registerRoutes: false }); diff --git a/packages/services/service-storage/src/storage-service-plugin.ts b/packages/services/service-storage/src/storage-service-plugin.ts index 56c902f9398..58520009800 100644 --- a/packages/services/service-storage/src/storage-service-plugin.ts +++ b/packages/services/service-storage/src/storage-service-plugin.ts @@ -89,6 +89,8 @@ import { installAttachmentReadVisibility, } from './attachment-access-hooks.js'; import { contributeAttachmentDeleteFloorAlternate } from './attachment-delete-floor-alternate.js'; +import { contributeAttachmentMemberGrant } from './attachment-member-grant.js'; +import { installAttachmentFilesOptInGate } from './attachment-files-opt-in.js'; import { FileAttachmentService, type FileAttachmentEngine, @@ -538,6 +540,12 @@ export class StorageServicePlugin implements Plugin { // that name a `sys_file` id — a file-class field and a // `sys_attachment` row — so a reference and the door cannot diverge. const authorizeFileReference = buildFileReferenceReadAuthorizer(toGateRegistry(ctx), engine); + // The per-object attachment opt-in (`enable.files`) on every write that + // makes a row target an object, enforced by this service itself so it + // holds wherever the object does (maintainer ruling on #32754, route + // A). Installed first, so an object that has not opted in answers with + // its own refusal before any question about the caller. + const filesOptInInstalled = installAttachmentFilesOptInGate(engine as any); // Parent-derived access on the join rows (#2755, ADR-0049) — the // sharing service resolves lazily so plugin order doesn't matter. installAttachmentAccessHooks( @@ -593,7 +601,8 @@ export class StorageServicePlugin implements Plugin { // object only when the security service answers `canReadObject`; // resolved on every read (the security plugin may start after this // one), and without it every read takes the bounded probe. - if (typeof (engine as any).registerMiddleware === 'function') { + const readVisibilityInstalled = typeof (engine as any).registerMiddleware === 'function'; + if (readVisibilityInstalled) { installAttachmentReadVisibility(engine as any, ctx.logger, () => { try { return ctx.getService('security'); @@ -602,6 +611,28 @@ export class StorageServicePlugin implements Plugin { } }); } + // Every member's object grant on sys_attachment (read and create), + // handed to the member baseline HERE, after the last of the row gates + // it relies on, and only when all four are in place: the opt-in gate + // and the write rule above, the read-visibility gate just installed, + // and the download door's parent-record check, which binds wherever an + // auth service and a queryable engine exist (`buildFileReadAuthorizer`, + // the same binding `composeStorageRoutes` makes). Each flag is the + // installation's own answer, and every gate is this service's, so no + // other plugin's order is involved. On a kernel lacking any of them the + // object grant would judge the rows alone, so nothing is contributed + // and members stay refused (maintainer ruling; the reasoning is in + // `attachment-member-grant.ts`). + contributeAttachmentMemberGrant( + { + writeRule: true, + readVisibility: readVisibilityInstalled, + downloadCheck: buildFileReadAuthorizer(toGateRegistry(ctx), engine) !== undefined, + filesOptIn: filesOptInInstalled, + }, + () => ctx.getService('security'), + ctx.logger, + ); // Field-reference ownership (ADR-0104 D3 wave 2) — keeps // sys_file.ref_object/ref_id/ref_field in step with what records hold, // and copies bytes rather than sharing a row when a second field slot @@ -694,6 +725,20 @@ export class StorageServicePlugin implements Plugin { // `PlatformObjectsPlugin` with the `sys_migration` registration it // belongs to (#4243) — the ledger and its bookkeeping are platform // infrastructure, present with or without this service. + } else if (engine) { + // An engine the attachment gates cannot be installed on: members get + // no attachment grant, and the warning says which gates are missing. + contributeAttachmentMemberGrant( + { + writeRule: false, + readVisibility: false, + downloadCheck: buildFileReadAuthorizer(toGateRegistry(ctx), engine) !== undefined, + // The installer's own answer here too: it needs the hook seam this engine lacks. + filesOptIn: installAttachmentFilesOptInGate(engine as any), + }, + () => ctx.getService('security'), + ctx.logger, + ); } // ── HTTP routes (existing behaviour) ─────────────────────────── diff --git a/packages/spec/api-surface/contracts.json b/packages/spec/api-surface/contracts.json index 41d76115e03..d337bbb0eb7 100644 --- a/packages/spec/api-surface/contracts.json +++ b/packages/spec/api-surface/contracts.json @@ -262,6 +262,8 @@ "PRINCIPAL_SESSION_MAX_TTL_SECONDS (const)", "PendingActionRow (interface)", "PendingActionStatus (type)", + "PlatformBaselineSetAdmission (interface)", + "PlatformBaselineSetContribution (interface)", "Plugin (interface)", "PluginStartupResult (type)", "PositionGrantSummary (interface)", diff --git a/packages/spec/export-origins/contracts.json b/packages/spec/export-origins/contracts.json index ed116a8d9fa..41d842b1fb3 100644 --- a/packages/spec/export-origins/contracts.json +++ b/packages/spec/export-origins/contracts.json @@ -262,6 +262,8 @@ "PRINCIPAL_SESSION_MAX_TTL_SECONDS": "src/contracts/auth-service.ts#PRINCIPAL_SESSION_MAX_TTL_SECONDS (const)", "PendingActionRow": "src/contracts/ai-service.ts#PendingActionRow (interface)", "PendingActionStatus": "src/contracts/ai-service.ts#PendingActionStatus (type)", + "PlatformBaselineSetAdmission": "src/contracts/security-service.ts#PlatformBaselineSetAdmission (interface)", + "PlatformBaselineSetContribution": "src/contracts/security-service.ts#PlatformBaselineSetContribution (interface)", "Plugin": "src/contracts/plugin-validator.ts#Plugin (interface)", "PluginStartupResult": "src/kernel/startup-orchestrator.zod.ts#PluginStartupResult (type)", "PositionGrantSummary": "src/contracts/security-service.ts#PositionGrantSummary (interface)", diff --git a/packages/spec/src/api/error-code-ledger.zod.ts b/packages/spec/src/api/error-code-ledger.zod.ts index 73f07b64eb1..d4dc14633b6 100644 --- a/packages/spec/src/api/error-code-ledger.zod.ts +++ b/packages/spec/src/api/error-code-ledger.zod.ts @@ -589,6 +589,14 @@ export const ERROR_CODE_LEDGER = { 'AUTH_REQUIRED', 'ERR_FILE_CONSTRAINT', 'ERR_FILE_REFERENCE_COPY', + // [#32754] 403 from the storage service's own per-object attachment opt-in + // gate (`attachment-files-opt-in.ts`): a `sys_attachment` insert, or an + // update that re-points one, onto an object that does not declare + // `enable.files: true`, thrown from its engine hook and answered by every + // attach door as it was thrown. Second EMITTER of the code + // `@objectstack/plugin-audit` registers for its own gate on the same + // declaration. Provenance, not identity (see above). + 'FILES_DISABLED', 'FILE_DOWNLOAD_DENIED', 'FILE_FIELD_BULK_WRITE_REFUSED', // a multi/predicate update wrote a file id into a file-class field (#7102) 'FILE_NOT_FOUND', diff --git a/packages/spec/src/contracts/security-service.test.ts b/packages/spec/src/contracts/security-service.test.ts index 832ffef7410..d42ac2c41b4 100644 --- a/packages/spec/src/contracts/security-service.test.ts +++ b/packages/spec/src/contracts/security-service.test.ts @@ -7,6 +7,7 @@ import type { AuthoredRowWriteVerdict, AuthoredRowWriteOperation, OwnershipFloorAlternate, + PlatformBaselineSetContribution, ControlledByParentWriteOutcome, ControlledByParentWriteDenialLeg, ControlledByParentWriteUnresolvedReason, @@ -668,6 +669,48 @@ describe('Security Service Contract', () => { expect(notOneLimb.operation).toBe('all'); }); + it('contributePlatformBaselineSet is OPTIONAL — absence is typed, and a contribution carries read and create only', () => { + // A security service without the seam still satisfies the contract. + // Absence leaves the baseline as it was, which is the fail-closed + // direction: members hold no grant on the contributor's objects. + const withoutIt: ISecurityService = makeService(); + expect(typeof withoutIt.contributePlatformBaselineSet).toBe('undefined'); + + const set: PlatformBaselineSetContribution = { + name: 'storage_attachment_member', + label: 'Attachments', + objects: { sys_attachment: { allowRead: true, allowCreate: true } }, + }; + + // The unguarded call does not compile. Never invoked. + const mustNotCompileWithoutAGuard = () => + // @ts-expect-error possibly undefined — a contributor must feature-detect first + withoutIt.contributePlatformBaselineSet('com.example.service', set); + expect(typeof mustNotCompileWithoutAGuard).toBe('function'); + + const contribute = (svc: ISecurityService) => { + if (typeof svc.contributePlatformBaselineSet !== 'function') return 'no-seam'; + return svc.contributePlatformBaselineSet('com.example.service', set).joined ? 'joined' : 'not-joined'; + }; + expect(contribute(withoutIt)).toBe('no-seam'); + const withIt = makeService({ contributePlatformBaselineSet: (_c, s) => ({ name: s.name, joined: true }) }); + expect(contribute(withIt)).toBe('joined'); + + // The type admits read and create only; an elevated bit and a row policy do not compile. + const withEdit: PlatformBaselineSetContribution = { + ...set, + // @ts-expect-error `allowEdit` is not a bit a platform baseline set carries + objects: { sys_attachment: { allowRead: true, allowEdit: true } }, + }; + expect(withEdit.name).toBe(set.name); + const withRowPolicy: PlatformBaselineSetContribution = { + ...set, + // @ts-expect-error a platform baseline set carries no row policy + rowLevelSecurity: [], + }; + expect(withRowPolicy.name).toBe(set.name); + }); + it('checkControlledByParentWrite is OPTIONAL — absence is typed, and it means no master check, not allow', async () => { // A security service without the member still satisfies the contract, and // a consumer cannot reach the master check without handling the absent diff --git a/packages/spec/src/contracts/security-service.ts b/packages/spec/src/contracts/security-service.ts index b6d3f4002d0..534db521ed8 100644 --- a/packages/spec/src/contracts/security-service.ts +++ b/packages/spec/src/contracts/security-service.ts @@ -407,6 +407,36 @@ export interface OwnershipFloorAlternate { readonly using: string; } +/** + * One permission set an always-on platform service contributes to the member + * baseline, through {@link ISecurityService.contributePlatformBaselineSet}. + * + * The whole shape the seam admits: a name, display text, and read and create + * bits on objects the contributor itself registers. Every other permission-set + * key and every other object bit is refused, set to `false` included. + */ +export interface PlatformBaselineSetContribution { + /** Permission set name (snake_case), unique in the security catalog; `explain` shows it. */ + readonly name: string; + /** Display label. */ + readonly label?: string; + /** Human-readable description. */ + readonly description?: string; + /** Read and create, per object the contributor registers. Never `'*'`. */ + readonly objects: Readonly>; +} + +/** What {@link ISecurityService.contributePlatformBaselineSet} answers for an admitted set. */ +export interface PlatformBaselineSetAdmission { + /** The admitted set's name. */ + readonly name: string; + /** + * Whether the set joined the member baseline. `false` when the deployment + * declares no member baseline at all, so the set reaches no member. + */ + readonly joined: boolean; +} + /** * [ADR-0055] Which leg of the master-detail write check refused, in a `deny` * from {@link ISecurityService.checkControlledByParentWrite}. @@ -1402,6 +1432,46 @@ export interface ISecurityService { plugin: string, alternates: readonly OwnershipFloorAlternate[], ): void; + /** + * Contribute a permission set of the contributor's own to the member + * baseline: the sets every signed-in member holds through the `everyone` + * anchor (ADR-0090 D5). An always-on platform service calls this from the + * place it installs the row gates of the objects it registers, and only once + * all of them are installed, so the object-level grant exists only where the + * rows are judged. It is not a channel for tenant-installed packages, which + * suggest default sets for an administrator to accept instead. + * + * The implementation registers the set under `contributor`'s package and, + * when the deployment declares a member baseline, joins its name to that + * baseline. An external member and an agent principal's own leg resolve no + * member baseline, so neither gains anything from it in its own right; an + * agent acting for a member is bounded by that member and by its own scope + * (ADR-0090 D10), so it reaches what the member reaches, within that scope. + * Synchronous; open during boot only. + * + * **Refuses by throwing a plain `Error`**, with no registered `code`: this is + * a boot-time refusal, never a wire answer. A refused call changes nothing. + * It refuses when: + * - `contributor` is empty, or the boot window has closed; + * - the set carries a key other than `name`, `label`, `description` and + * `objects` (a row policy, a field rule, a system permission among them); + * - an object is `'*'`, or is not one the engine registry holds with + * `contributor` as its owner; + * - an object entry carries a bit other than `allowRead` and `allowCreate`, + * or grants neither; + * - the name is a shipped set's, another contributor's or another holder's, + * or the contributor already contributed a set of another name. + * + * **OPTIONAL, and absence is a defined state, not a bug.** A security service + * without the seam omits it. Contributors feature-detect + * (`typeof svc.contributePlatformBaselineSet === 'function'`). Absence and a + * refusal both leave the baseline as it was, which fails CLOSED: members + * hold no grant on the contributor's objects, and nothing is widened. + */ + contributePlatformBaselineSet?( + contributor: string, + set: PlatformBaselineSetContribution, + ): PlatformBaselineSetAdmission; /** * [ADR-0090 D12] Is permission set `setName` inside the organization * boundary? Resolves `null` when it is, otherwise the reason, naming the set diff --git a/scripts/adr-anchors/packages__plugins__plugin-security__src__platform-baseline-sets.ts.json b/scripts/adr-anchors/packages__plugins__plugin-security__src__platform-baseline-sets.ts.json new file mode 100644 index 00000000000..f964272bba8 --- /dev/null +++ b/scripts/adr-anchors/packages__plugins__plugin-security__src__platform-baseline-sets.ts.json @@ -0,0 +1,7 @@ +{ + "file": "packages/plugins/plugin-security/src/platform-baseline-sets.ts", + "adrs": [ + "ADR-0090" + ], + "invariant": "A platform service's own baseline set joins the composed member baseline every signed-in member holds through the everyone anchor (ADR-0090 D5), never the body of member_default (D9). Admitted only during boot, only read and create, only on objects the contributing package registered itself, one set per contributor, no wildcard and no row policy; every admission and refusal is logged, and a refusal leaves the object refused." +} diff --git a/scripts/adr-anchors/packages__services__service-storage__src__attachment-member-grant.ts.json b/scripts/adr-anchors/packages__services__service-storage__src__attachment-member-grant.ts.json new file mode 100644 index 00000000000..8ce25361dcc --- /dev/null +++ b/scripts/adr-anchors/packages__services__service-storage__src__attachment-member-grant.ts.json @@ -0,0 +1,7 @@ +{ + "file": "packages/services/service-storage/src/attachment-member-grant.ts", + "adrs": [ + "ADR-0090" + ], + "invariant": "The members' attachment set (read and create on sys_attachment, no edit, no delete) is contributed to the additive member baseline (ADR-0090 D5) only when all four attachment gates are installed — the per-object opt-in (enable.files), the write rule, the read-visibility gate and the download door's parent-record check, each the storage service's own and each flag its installation's own answer. A kernel missing any of them grants nothing and says which gate is missing, so the object stays refused rather than ungated." +}