Skip to content

Latest commit

 

History

History
154 lines (130 loc) · 12.6 KB

sharing-service.mdx

File metadata and controls

154 lines (130 loc) · 12.6 KB
title services.sharing — the record share API
navTitle services.sharing
description Check and manage record-level sharing with services.sharing — read filters, the tri-state checkEdit and checkDelete verdicts and their canEdit and canDelete projections, the optional set form, and granting or revoking record shares.
  • Stability: stable
  • Canonical source: packages/spec/src/contracts/sharing-service.ts
  • Registry slot: sharing — resolve with ctx.getService('sharing').

Methods

services.sharing.buildReadFilter(object: string, context: ExecutionContext): Promise<unknown | null>
services.sharing.checkEdit(object: string, recordId: string, context: ExecutionContext): Promise<SharingWriteVerdict>
services.sharing.checkDelete(object: string, recordId: string, context: ExecutionContext): Promise<SharingWriteVerdict>
services.sharing.canEdit(object: string, recordId: string, context: ExecutionContext): Promise<boolean>
services.sharing.canDelete(object: string, recordId: string, context: ExecutionContext): Promise<boolean>
services.sharing.checkEditMany?(object: string, recordIds: readonly string[], context: ExecutionContext): Promise<SharingWriteVerdict[]>
services.sharing.checkDeleteMany?(object: string, recordIds: readonly string[], context: ExecutionContext): Promise<SharingWriteVerdict[]>
services.sharing.canManageShares(object: string, recordId: string, context: ExecutionContext): Promise<boolean>
services.sharing.grant(input: GrantShareInput, context: ExecutionContext): Promise<RecordShare>
services.sharing.revoke(shareId: string, context: ExecutionContext, scope?: { object: string; recordId: string }): Promise<void>
services.sharing.listShares(object: string, recordId: string, context: ExecutionContext): Promise<RecordShare[]>

Every method above adjudicates access, so each takes the complete resolveAuthzContext envelope (ExecutionContext) — not a per-site subset (#6523, applying the #6206 ruling). The six-field SharingExecutionContext these signatures used to name was retired in #7218; pass the whole context you were handed, unchanged.

The write verdicts: tri-state, two-state and set form

Each write gate has a primary tri-state form, checkEdit (update) and checkDelete (delete), which answers a SharingWriteVerdict:

  • allow — a positive basis to permit: ownership (widened by write DEPTH), the modifyAllRecords super-user bypass or a system context, and, for checkEdit only, an edit-level share or a record sitting in a queue the caller belongs to.
  • abstain — record sharing does not enforce on this row at all: a public object, an object with no owner field, a bypass-listed platform internal, or an object with no resolvable schema. The decision belongs to whatever else guards the row. checkDelete abstains on the rows checkEdit abstains on except one class: on an object that declares public_read_write and has an owner field, delete follows the record's owner, so checkDelete answers allow or deny there as it does under public_read.
  • deny — refused: a sharing-enforced row where the caller has none of the bases above, a principal-less context, or a lookup that failed. A failure is always deny, never abstain.

canEdit / canDelete are the two-state projection of those verdicts: true for anything that is not deny, so abstain and allow both read as true. That is right for a caller that only adds this gate to what already guards the row, and wrong for one that would let the answer override another authority's floor: such a caller must read checkEdit / checkDelete, so that "sharing has no opinion" is never taken as permission.

checkEditMany / checkDeleteMany are the optional set form of the tri-state verdicts: answer[i] is the verdict checkEdit / checkDelete answers for recordIds[i] under the same context, with the same bases and the same verb boundary, and the answer is exactly as long as recordIds. Only the cost differs: the number of store reads grows with the number of chunks, not the number of records. The bundled SharingService (@objectstack/plugin-sharing) implements both, reading 1,000 ids per chunk. They are optional: a caller feature-detects them (typeof sharing.checkEditMany === 'function') and, where a service does not implement them, asks checkEdit / checkDelete once per record, with the same answers. The platform's predicate update and delete do exactly that. A chunk whose lookup fails answers deny for each of its records. A custom ISharingService that does not add the set form keeps working.

Management authority (ADR-0111)

grant / revoke / listShares are management operations, enforced in the service for every non-system caller: the caller must hold canManageShares on the record — its owner, a holder of Modify All Data, a hierarchy manager whose effective write DEPTH (unit / unit_and_below / own_and_reports) covers the record's owner (via the enterprise hierarchy-scope-resolver), or system context. A deployment without @objectstack/plugin-security fails closed to owner-only; without the enterprise resolver the DEPTH path is inert and authority stays owner + Modify-All. Pass { isSystem: true } only from platform-internal machinery. A share a non-system caller grants is always a manual share: grant refuses a source other than 'manual', and any sourceId, with VALIDATION_FAILED (400), because only the platform's own sharing-rule, team and system paths write a share of another source.

The verb boundary (ADR-0111 D3)

A share widens which rows a principal reaches, never which verbs they may use. canEdit (the update gate) accepts an edit-level share; canDelete (the delete gate) does not — delete is ownership (widened by write DEPTH) or the modifyAllRecords super-user bypass only. Delete is not a share level and never will be; a future per-record delete grant would be a capability mask AND-ed with object CRUD, not a fourth access_level.

Returns

  • buildReadFilter: null means unrestricted read; otherwise returns an engine filter
  • checkEdit / checkDelete: a SharingWriteVerdict ('allow' | 'abstain' | 'deny'); a failed lookup answers deny rather than throwing
  • checkEditMany / checkDeleteMany (optional): one SharingWriteVerdict per id, in the order of recordIds
  • canEdit / canDelete / canManageShares: boolean decisions (they return false rather than throwing); canEdit / canDelete are true for every verdict that is not deny
  • grant/listShares: normalized RecordShare rows

Typical Errors

  • FORBIDDEN (403) — a write denied by the canEdit gate. Thrown by the sharing engine middleware; canEdit itself returns false rather than throwing.
  • VALIDATION_FAILED (400) — grant/revoke called without a required field (object, recordId, recipientId, or shareId), or grant with a non-user recipientType (only user rows are enforced by the gates). The refusal names the sharing-rule recipient that delivers each declared value: group → team (a rule spells it team since the ADR-0090 D3 rename), position → position, unit_and_subordinates → unit_and_subordinates. A non-system grant is also refused when its user recipient names no user the gates could ever match: on a deployment walled by organization (isolated / group) with the record's organization known, the recipient must be a member of that organization, and a user of another organization gets the same answer as an id that does not exist, so the door tells no caller who exists in another tenant; on single it must be an existing sys_user. Under a wall where the grant's organization does not resolve, the recipient is not judged: the engine refuses that insert for every recipient alike (ERR_SYSTEM_WRITE_ORGANIZATION_REQUIRED, 500). defineRule refuses a non-system user recipient the same way, in the rule's organization, when the rule is new or its recipient changes. The rule's organization is the caller's or, for a platform operator with no active organization updating a stored rule, the stored rule's own (the engine's organization rule refuses only inserts, so that update is judged here); a new rule written with no organization under a wall is not judged, and the engine refuses its insert. A sys_sharing_rule write through the /data door (Setup's form) gets the same refusal and sentence, judged in the organization the write leaves the rule in: an organization_id the write supplies, else the stored rule's, else the caller's active organization; a write that keeps the stored recipient is not judged.
  • PERMISSION_DENIED (403) — the caller does not hold canManageShares on the record (ADR-0111 D1). On the sharing-rule surface (ISharingRuleService, declared in the same canonical source — listRules / getRule / defineRule / deleteRule / evaluateRule) the same code carries a second condition: the caller holds manage_sharing but their session resolves no active organization, and an org-scoped capability with no organization has no tenant whose rules it authorizes. System contexts and platform operators (manage_platform_settings, or the platform_admin position) are unaffected — see Rule administration.
  • NOT_FOUND (404) — the record is missing or not visible to the caller (indistinguishable by design), or a revoke share id does not exist / does not belong to the scope record.
  • CONFLICT (409) — revoke on a rule-materialised share (source != 'manual'); the next rule reconciliation would silently re-grant it. Deactivate or edit the sharing rule instead.
  • SHARING_NOT_ENABLED (422) — grant on an object the sharing gates never consult for the recipient (a public sharing model, unless the recipient is an external member of the record's organization, whose owner-only floor does consult it; no owner_id field; a bypass object, controlled_by_parent, or a federated object whose owner_id is the platform's injected anchor rather than a real remote column — the platform provisions no storage for a federated object, so the gates read that column off a table that has not got it and can never admit; or an object whose share grants cannot count where it is stored — it sits on another datasource than sys_record_share, even a SQL one, or on a driver that does not evaluate the share-grant subquery, today MongoDB, in-memory and OData (ADR-0155 R2); to share its records, store it on the datasource of sys_record_share, on a driver that evaluates share grants, as the SQL drivers do). On the sharing-rule surface, defineRule (and a sys_sharing_rule write through the /data door) answers the same code when the rule's object is one no gate consults for any recipient: the rule is refused at save instead of saved to share nothing.

Enforcement is automatic — do not re-check it in a hook

With @objectstack/plugin-sharing installed, the gates run inside the engine: its middleware picks the gate by verb — canEdit before a by-id update, canDelete before a delete — and throws FORBIDDEN before the hook chain could ask anything. A hook that re-checks adds nothing, and it cannot ask this service at all: a hook context is built key by key by the engine (object / event / input / session / provenance / user / api / transaction / ql) and carries no services key, so ctx.services?.sharing?.canEdit(…) is undefined there and if (!ok) throw … rejects every write (#5720). A hook's own channel is ctx.api — use it for business rules (examples).

Example

Call canEdit only from code that holds the service — a plugin that resolved it from the kernel service registry, or a managed runtime's services.sharing binding — for example to pre-flight an affordance before offering it:

{/* os:check */}

import type { ISharingService } from '@objectstack/spec/contracts';

export async function mayEditContract(
  sharing: ISharingService,
  recordId: string,
  session: { userId?: string; organizationId?: string; positions?: string[] },
): Promise<boolean> {
  return sharing.canEdit('contract', recordId, {
    userId: session.userId,
    // The execution context names the org `tenantId`; a session exposes the
    // same value as `organizationId` (the `session.tenantId` alias was removed in
    // v16, #3290).
    tenantId: session.organizationId,
    positions: session.positions,
  });
}

canEdit returns false rather than throwing, so a caller decides what a denial means — hiding a button, or raising its own error.