diff --git a/.changeset/34218-platform-admin-approver.md b/.changeset/34218-platform-admin-approver.md new file mode 100644 index 00000000000..23ae1ac830a --- /dev/null +++ b/.changeset/34218-platform-admin-approver.md @@ -0,0 +1,21 @@ +--- +'@objectstack/spec': minor +'@objectstack/plugin-approvals': minor +'@objectstack/lint': minor +--- + +feat(approvals): a `platform_admin` approver type routes a step to the platform administrators, from the deployment's own packaged flows only + +Clause-②: yes (widening) +Metadata-protocol: added + +The widening: `ApproverType` accepts a new member, `platform_admin`, which takes no `value`. Nothing accepted before is refused. The narrowing that comes with it applies only to the new member: it is refused outside the running body of a `source: 'code'` package's flow. + +`{ type: 'platform_admin' }` on an approval node addresses the deployment's platform administrators: the people `hasPlatformAdminStanding` answers yes for, which covers a holder of the cross-tenant `admin_full_access` grant and a verified account whose email `OS_PLATFORM_OWNER_EMAIL` declares. + +- The step opens on ONE address slot, `platform_admin:*`, that names no person. Nobody is enumerated, nobody is notified, and the slot grants no record read. `onEmptyApprovers` does not treat the slate as empty. +- At the inbox and at every decision, the server asks whether the caller has platform-administrator standing at that moment, from the stored rows and never from the session's posture. A caller who has it decides as an ordinary approver, and the decision records the person (`actor_id`) and the slot (`acted_as`). A revoked administrator cannot decide, also on a request opened before the revocation. An organization administrator takes no slot. The #3424 tenant-admin override is withheld from a request whose slate holds `platform_admin:*`, including a mixed slate: an override decides the whole request, so the guard covers the whole request. Its ordinary approvers still decide as usual. The platform-admin override is unchanged. +- Only the `platform_admin` approver type opens the slot, on the slate as the decision, override and inbox doors read it: no other way a slate is resolved or later rewritten opens it. A request records, when it opens, that a `platform_admin` step opened its slot, and the doors honour the slot only on a request that carries that record. Moving the slot to someone else needs the platform's own standing, the platform-admin override, or the system. +- The new member is accepted only in the running body of a flow shipped by a package the deployment registers in code (registry `source: 'code'`, or a residual owner a code door recorded). The origin is answered for the body whose step is being opened, in every run state. Anywhere else the node refuses to open, fails closed and writes nothing: a flow authored in the environment, an environment override of a packaged flow, and a marketplace or authored package's flow. The runtime save door refuses an active flow naming it with `approval-approver-platform-admin-authored`. `os lint` knows the type and refuses nothing, because it cannot know which door will register a package. No designer offers the type. + +Nothing to migrate. diff --git a/content/docs/automation/approvals.mdx b/content/docs/automation/approvals.mdx index 041d5596a71..d02fdac8772 100644 --- a/content/docs/automation/approvals.mdx +++ b/content/docs/automation/approvals.mdx @@ -427,9 +427,10 @@ Only `approvers` is required on the node; everything else has a default (`behavior: 'first_response'`, `lockRecord: true`, `maxRevisions: 3`). Approver entries resolve by kind — `position`, `user`, `field`, `manager`, -`team`, `department`, `org_membership_level`, `queue`, and `expression` -(described in the [callout above](#3-the-approval-node) and in -[Dynamic approvers](#dynamic-approvers-3447)); `org_membership_level` is the +`team`, `department`, `org_membership_level`, `queue`, `expression` and +`platform_admin` (described in the [callout above](#3-the-approval-node) and in +[Dynamic approvers](#dynamic-approvers-3447), and `platform_admin` in +[Routing to the platform administrators](#platform-admin-approvers)); `org_membership_level` is the one that silently resolves to nobody when it's mistaken for a business hierarchy. A `queue` entry names an ownership queue by its machine name — one an installed app declares, or one of the organization's own — and resolves to @@ -448,6 +449,51 @@ A `position` or `queue` name is not checked when the flow is saved: positions an queues are runtime data an administrator adds and removes, so a name nobody holds yet saves, and it is resolved when the run reaches the node. +#### Routing to the platform administrators [#platform-admin-approvers] + +`{ type: 'platform_admin' }` routes the step to the deployment's **platform +administrators**: the people with platform-administrator standing, which is a +cross-tenant `admin_full_access` grant or a verified account whose email the +deployment declares in `OS_PLATFORM_OWNER_EMAIL`. It takes no `value` and no +`organization`. + +- **One slot, nobody listed.** The request opens on one slot, + `platform_admin:*`, that names no person. At every inbox read and every + decision, the server asks whether the caller has platform-administrator + standing at that moment. A caller who has it sees the request under + "My Pending" and decides it as an ordinary approver, and the decision records + that person. A caller whose standing was revoked cannot decide it, even if + the request opened before the revocation. An organization administrator + neither takes the slot nor overrides the request: the tenant admin override + below is withheld from any request whose slate holds `platform_admin:*`, + including a mixed slate that also names ordinary approvers. An override + decides the whole request, so a mixed slate is withheld whole, and its + ordinary approvers still decide it as usual. The platform admin override is + unchanged. +- **Only this type opens the slot.** The rule holds on the slate as the + decision, override and inbox doors read it: however else a slate is resolved + or later rewritten, the slot is not opened through it. A request records, + when it opens, that a `platform_admin` step opened its slot, and the doors + honour the slot only on a request that carries that record. Moving the slot + to someone else takes a platform administrator, the platform admin override, + or the system. +- **Nobody is told.** The slot names no person, so opening the request sends + no notification, and the slot grants no read of the record. The request does + not count as an empty slate, so `onEmptyApprovers` never replaces it with + the organization's administrators. +- **Only the deployment's own packaged flows may use it.** The approval node + opens on this type only when the flow body it runs ships in a package the + deployment registers in code (registry `source: 'code'`). The origin is + answered for the body whose step is being opened, in every run state. Anywhere else, the + node fails with a `FORBIDDEN:` error that says why, and writes no request. + That covers a flow authored in the deployment, an environment override of a + packaged flow, and a flow from a package installed from the marketplace or + created in the deployment. Saving an active flow that names the type, in + Studio or through `/meta`, is refused with + `approval-approver-platform-admin-authored`. `os lint` accepts the type. It + cannot know which door will register the package it reads. No designer + offers the type. + What an entry that resolves to nobody leaves on the slate depends on its kind: - **A person entry** (`manager`, `field`) adds no slot. Nor does a `queue` @@ -907,7 +953,9 @@ then — and for a `team` or `department` literal, always — no concrete user c act, and (with `lockRecord`) the record stays locked. A **platform admin** (`admin_full_access`) or **tenant admin** (`organization_admin`, org-scoped) may act on any `pending` request — **approve, reject, reassign** it to a real -approver, or **recall** it — releasing the lock. An admin decision is +approver, or **recall** it — releasing the lock. The one exception is a +request whose slate holds the platform administrators' slot: a tenant admin +cannot override it ([Routing to the platform administrators](#platform-admin-approvers)). An admin decision is authoritative: it finalizes the node even under `unanimous`/`quorum`/`per_group`, and is audited under the admin's own id. Prefer a guaranteed-staffed fallback approver so the set is never empty in the first place. diff --git a/content/docs/references/automation/approval.mdx b/content/docs/references/automation/approval.mdx index 16a2bc593b3..0e99db84477 100644 --- a/content/docs/references/automation/approval.mdx +++ b/content/docs/references/automation/approval.mdx @@ -53,7 +53,7 @@ const result = ApprovalDecision.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `Enum<'manager' \| 'position' \| 'department' \| 'team' \| 'queue' \| 'field' \| 'expression' \| 'org_membership_level' \| 'role' \| 'user'>` | ✅ | How this step finds its approvers. Prefer a role in the organization (manager, position, department, team) over one named person, who may leave or not exist in another environment. A manager step only finds someone once an administrator has recorded each user's manager in the user directory; until then it finds nobody and the request follows the node's `onEmptyApprovers` policy. `os lint` reports that at authoring time as `approval-approvers-may-resolve-empty`, and `os explain approval-approvers-may-resolve-empty` carries the ways to fill the directory in and the full remedy; the Approvals guide states the same remedy in prose. | +| **type** | `Enum<'manager' \| 'position' \| 'department' \| 'team' \| 'queue' \| 'field' \| 'expression' \| 'org_membership_level' \| 'role' \| 'user' \| 'platform_admin'>` | ✅ | How this step finds its approvers. Prefer a role in the organization (manager, position, department, team) over one named person, who may leave or not exist in another environment. A manager step only finds someone once an administrator has recorded each user's manager in the user directory; until then it finds nobody and the request follows the node's `onEmptyApprovers` policy. `os lint` reports that at authoring time as `approval-approvers-may-resolve-empty`, and `os explain approval-approvers-may-resolve-empty` carries the ways to fill the directory in and the full remedy; the Approvals guide states the same remedy in prose. The platform administrators type is for a deployment's own packaged flows only: a flow saved here cannot use it, and an approval step that names it anywhere else does not open. | | **value** | `string` | optional | Who exactly, for the chosen type: the user, membership tier, position, team, department or queue, or the record field that holds the approver. Leave it empty for a manager step. For an expression step, write the CEL expression that returns the approvers; it may read `current.*`, `trigger.*` and `vars.*`. | | **resolveAs** | `Enum<'user' \| 'department' \| 'position' \| 'team'>` | optional | Expression steps only: what the expression's results name. By default each result is a person; choose departments, positions or teams to make all their members approvers. | | **group** | `string` | optional | Group name for one-from-each-group sign-off: approvers with the same name form one group, and the step needs approval from every group (e.g. "legal", "finance"). Read only when approvers combine per group. | @@ -84,7 +84,7 @@ const result = ApprovalDecision.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `Enum<'manager' \| 'position' \| 'department' \| 'team' \| 'queue' \| 'field' \| …>` | ✅ | How this step finds its approvers. Prefer a role in the organization (manager, position, department, team) over one named person, who may leave or not exist in another environment. A manager step only finds someone once an administrator has recorded each user's manager in the user directory; until then it finds nobody and the request follows the node's `onEmptyApprovers` policy. `os lint` reports that at authoring time as `approval-approvers-may-resolve-empty`, and `os explain approval-approvers-may-resolve-empty` carries the ways to fill the directory in and the full remedy; the Approvals guide states the same remedy in prose. | +| **type** | `Enum<'manager' \| 'position' \| 'department' \| 'team' \| 'queue' \| 'field' \| …>` | ✅ | How this step finds its approvers. Prefer a role in the organization (manager, position, department, team) over one named person, who may leave or not exist in another environment. A manager step only finds someone once an administrator has recorded each user's manager in the user directory; until then it finds nobody and the request follows the node's `onEmptyApprovers` policy. `os lint` reports that at authoring time as `approval-approvers-may-resolve-empty`, and `os explain approval-approvers-may-resolve-empty` carries the ways to fill the directory in and the full remedy; the Approvals guide states the same remedy in prose. The platform administrators type is for a deployment's own packaged flows only: a flow saved here cannot use it, and an approval step that names it anywhere else does not open. | | **value** | `string` | optional | Who exactly, for the chosen type: the user, membership tier, position, team, department or queue, or the record field that holds the approver. Leave it empty for a manager step. For an expression step, write the CEL expression that returns the approvers; it may read `current.*`, `trigger.*` and `vars.*`. | | **resolveAs** | `Enum<'user' \| 'department' \| 'position' \| 'team'>` | optional | Expression steps only: what the expression's results name. By default each result is a person; choose departments, positions or teams to make all their members approvers. | | **group** | `string` | optional | Group name for one-from-each-group sign-off: approvers with the same name form one group, and the step needs approval from every group (e.g. "legal", "finance"). Read only when approvers combine per group. | @@ -94,7 +94,7 @@ const result = ApprovalDecision.parse(data); | Property | Type | Required | Description | | :--- | :--- | :--- | :--- | -| **type** | `Enum<'manager' \| 'position' \| 'department' \| 'team' \| 'queue' \| 'field' \| …>` | ✅ | How this step finds its approvers. Prefer a role in the organization (manager, position, department, team) over one named person, who may leave or not exist in another environment. A manager step only finds someone once an administrator has recorded each user's manager in the user directory; until then it finds nobody and the request follows the node's `onEmptyApprovers` policy. `os lint` reports that at authoring time as `approval-approvers-may-resolve-empty`, and `os explain approval-approvers-may-resolve-empty` carries the ways to fill the directory in and the full remedy; the Approvals guide states the same remedy in prose. | +| **type** | `Enum<'manager' \| 'position' \| 'department' \| 'team' \| 'queue' \| 'field' \| …>` | ✅ | How this step finds its approvers. Prefer a role in the organization (manager, position, department, team) over one named person, who may leave or not exist in another environment. A manager step only finds someone once an administrator has recorded each user's manager in the user directory; until then it finds nobody and the request follows the node's `onEmptyApprovers` policy. `os lint` reports that at authoring time as `approval-approvers-may-resolve-empty`, and `os explain approval-approvers-may-resolve-empty` carries the ways to fill the directory in and the full remedy; the Approvals guide states the same remedy in prose. The platform administrators type is for a deployment's own packaged flows only: a flow saved here cannot use it, and an approval step that names it anywhere else does not open. | | **value** | `string` | optional | Who exactly, for the chosen type: the user, membership tier, position, team, department or queue, or the record field that holds the approver. Leave it empty for a manager step. For an expression step, write the CEL expression that returns the approvers; it may read `current.*`, `trigger.*` and `vars.*`. | | **resolveAs** | `Enum<'user' \| 'department' \| 'position' \| 'team'>` | optional | Expression steps only: what the expression's results name. By default each result is a person; choose departments, positions or teams to make all their members approvers. | | **group** | `string` | optional | Group name for one-from-each-group sign-off: approvers with the same name form one group, and the step needs approval from every group (e.g. "legal", "finance"). Read only when approvers combine per group. | @@ -125,7 +125,7 @@ const result = ApprovalDecision.parse(data); ## ApproverType -How this step finds its approvers. Prefer a role in the organization (manager, position, department, team) over one named person, who may leave or not exist in another environment. A manager step only finds someone once an administrator has recorded each user's manager in the user directory; until then it finds nobody and the request follows the node's `onEmptyApprovers` policy. `os lint` reports that at authoring time as `approval-approvers-may-resolve-empty`, and `os explain approval-approvers-may-resolve-empty` carries the ways to fill the directory in and the full remedy; the Approvals guide states the same remedy in prose. +How this step finds its approvers. Prefer a role in the organization (manager, position, department, team) over one named person, who may leave or not exist in another environment. A manager step only finds someone once an administrator has recorded each user's manager in the user directory; until then it finds nobody and the request follows the node's `onEmptyApprovers` policy. `os lint` reports that at authoring time as `approval-approvers-may-resolve-empty`, and `os explain approval-approvers-may-resolve-empty` carries the ways to fill the directory in and the full remedy; the Approvals guide states the same remedy in prose. The platform administrators type is for a deployment's own packaged flows only: a flow saved here cannot use it, and an approval step that names it anywhere else does not open. ### Allowed Values @@ -139,6 +139,7 @@ How this step finds its approvers. Prefer a role in the organization (manager, p * `org_membership_level` * `role` * `user` +* `platform_admin` --- diff --git a/packages/lint/src/authoring-rules.ts b/packages/lint/src/authoring-rules.ts index 4fdaeb8a8ee..c6b0040569a 100644 --- a/packages/lint/src/authoring-rules.ts +++ b/packages/lint/src/authoring-rules.ts @@ -364,6 +364,12 @@ export interface AuthoringRuleContext { * authored shape the build judges (`stripInjectedSystemColumns`); and it * leaves out a label group every member of which already shared the label on * the target without the written entry, a clash the entry did not create. + * + * `validateApprovalApprovers` reads its presence only, as + * `validateEmailTemplateHoleGrammar` does: a flow written at the publish door is authored in the + * deployment, never a package's own code, so a `platform_admin` approver in + * it is refused there; the CLI commands read a package's source and cannot + * know which door will register it, so they refuse nothing. */ runtimeWriteType?: string; /** @@ -1638,7 +1644,10 @@ export const AUTHORING_RULES: readonly AuthoringRule[] = [ // `approver.value` is just a string to Zod. It is not just a string here. surfaces: CLI_AND_RUNTIME, runtimeTypes: ['flow'], - run: (stack) => validateApprovalApprovers(stack), + // At the runtime door a flow is authored in the deployment, so a + // `platform_admin` approver in it is refused there (`atSaveDoor`, read off + // `runtimeWriteType`'s presence; see that field). + run: (stack, ctx) => validateApprovalApprovers(stack, { atSaveDoor: ctx.runtimeWriteType !== undefined }), }, // ADR-0079 — `titleFormat` is retired in favour of `nameField`, and the // ruling of record on #29007 (6574393684, letter B) refuses it: an object diff --git a/packages/lint/src/index.ts b/packages/lint/src/index.ts index b2f70e67f69..adabc3c8e68 100644 --- a/packages/lint/src/index.ts +++ b/packages/lint/src/index.ts @@ -338,8 +338,9 @@ export { APPROVAL_EXPRESSION_NO_EMPTY_POLICY, APPROVAL_DECISION_OUTPUTS_RESERVED, APPROVAL_APPROVER_CROSS_ORG_UNSUPPORTED, + APPROVAL_APPROVER_PLATFORM_ADMIN_AUTHORED, } from './validate-approval-approvers.js'; -export type { ApprovalApproverFinding, ApprovalApproverSeverity } from './validate-approval-approvers.js'; +export type { ApprovalApproverFinding, ApprovalApproverSeverity, ValidateApprovalApproversOptions } from './validate-approval-approvers.js'; export { validateAssignmentRules, diff --git a/packages/lint/src/validate-approval-approvers.ts b/packages/lint/src/validate-approval-approvers.ts index 88c6e9c4dff..f5af828fb06 100644 --- a/packages/lint/src/validate-approval-approvers.ts +++ b/packages/lint/src/validate-approval-approvers.ts @@ -27,6 +27,7 @@ * | approval-expression-no-empty-policy | info | #3447 P2 empty-slate policy | * | approval-decision-outputs-reserved | error | #3447 P2 resume envelope | * | approval-approver-cross-org-unsupported | error | ADR-0105 D9 targeting | + * | approval-approver-platform-admin-authored | error | save door only (see below) | * * The first two are mutually exclusive by construction — a bad *value* wins, * because its fix (`position`) differs from the deprecation's fix @@ -65,6 +66,21 @@ export const APPROVAL_EXPRESSION_INVALID = 'approval-expression-invalid'; export const APPROVAL_EXPRESSION_NO_EMPTY_POLICY = 'approval-expression-no-empty-policy'; export const APPROVAL_DECISION_OUTPUTS_RESERVED = 'approval-decision-outputs-reserved'; export const APPROVAL_APPROVER_CROSS_ORG_UNSUPPORTED = 'approval-approver-cross-org-unsupported'; +export const APPROVAL_APPROVER_PLATFORM_ADMIN_AUTHORED = 'approval-approver-platform-admin-authored'; + +/** What {@link validateApprovalApprovers} needs to know about the door that runs it. */ +export interface ValidateApprovalApproversOptions { + /** + * True at the runtime publish gate, the save door every flow authored in a + * deployment passes (Studio, REST `/meta`, an MCP author). A flow saved there + * is never a package's own code, so a `platform_admin` approver in it is + * refused at that door ({@link APPROVAL_APPROVER_PLATFORM_ADMIN_AUTHORED}). + * Absent on the CLI commands: they read a package's source tree and cannot + * know which door will register it, so they know the type and refuse + * nothing. The approval node's refusal at entry is the gate that holds. + */ + atSaveDoor?: boolean; +} /** * The CLOSED root set an `expression` approver may reference (#3447 P2) — @@ -356,7 +372,10 @@ function stackWiresManagerChain(stack: AnyRec): boolean { * Validate the approvers of every Approval node in the stack's flows. * Returns findings (empty = clean). */ -export function validateApprovalApprovers(stack: AnyRec): ApprovalApproverFinding[] { +export function validateApprovalApprovers( + stack: AnyRec, + options: ValidateApprovalApproversOptions = {}, +): ApprovalApproverFinding[] { const findings: ApprovalApproverFinding[] = []; if (!stack || typeof stack !== 'object') return findings; @@ -408,6 +427,27 @@ export function validateApprovalApprovers(stack: AnyRec): ApprovalApproverFindin const canonical = canonicalApproverType(type); + // The platform administrators, named in a flow saved at the runtime + // door: that flow is authored in this deployment, and only a flow a + // package registered in code ships may address them. Early feedback; + // the approval node refuses to open on it whatever door it came in by. + if (options.atSaveDoor === true && canonical === 'platform_admin') { + findings.push({ + severity: 'error', + rule: APPROVAL_APPROVER_PLATFORM_ADMIN_AUTHORED, + where, + path: `${path}.type`, + message: + "approver type 'platform_admin' addresses the deployment's platform administrators, and a flow " + + 'saved here is authored in this deployment: only a flow shipped by a package the deployment ' + + 'registers in code may name them. The approval node would refuse to open on it.', + hint: + 'Route the step to people of the organization (a position, a team, a department or a person), ' + + 'or ship the flow in a package the deployment registers in code.', + }); + continue; + } + // Expression approvers (#3447 P2): the runtime REJECTS an expression // that doesn't parse or references a root outside `current`/`trigger`/ // `vars` (the CEL env would resolve an unknown root as dyn → null → a @@ -566,6 +606,30 @@ export function validateApprovalApprovers(stack: AnyRec): ApprovalApproverFindin } } + // The same save-door refusal for the node's fallback slate, which the + // approval node opens on through the same expansion. + if (options.atSaveDoor === true && Array.isArray(cfg.fallbackApprovers)) { + const fallback = cfg.fallbackApprovers as unknown[]; + for (let ai = 0; ai < fallback.length; ai++) { + const a = fallback[ai] as AnyRec | null; + if (!a || typeof a !== 'object' || typeof a.type !== 'string') continue; + if (canonicalApproverType(a.type) !== 'platform_admin') continue; + findings.push({ + severity: 'error', + rule: APPROVAL_APPROVER_PLATFORM_ADMIN_AUTHORED, + where, + path: `${nodePath}.config.fallbackApprovers[${ai}].type`, + message: + "fallback approver type 'platform_admin' addresses the deployment's platform administrators, and " + + 'a flow saved here is authored in this deployment: only a flow shipped by a package the ' + + 'deployment registers in code may name them. The approval node would refuse to open on it.', + hint: + 'Name people of the organization as the fallback, or ship the flow in a package the deployment ' + + 'registers in code.', + }); + } + } + // Empty-slate dead-end (#3424): when EVERY approver on the node routes to // a group whose membership can be empty (an unstaffed position, an empty // team/department), no person the node names can act at runtime, and diff --git a/packages/plugins/plugin-approvals/src/approval-node.ts b/packages/plugins/plugin-approvals/src/approval-node.ts index e88f750dac6..6b852081006 100644 --- a/packages/plugins/plugin-approvals/src/approval-node.ts +++ b/packages/plugins/plugin-approvals/src/approval-node.ts @@ -206,6 +206,9 @@ export function registerApprovalNode( // `vars.*` root for `expression` approvers; `record` above doubles as // their `trigger.*` snapshot root. variables: nestVariables(variables), + // The node object this run executes: a step naming the platform + // administrators opens only when it belongs to the armed body. + node, }, { ...SYSTEM_CTX, userId: context?.userId, diff --git a/packages/plugins/plugin-approvals/src/approval-service.ts b/packages/plugins/plugin-approvals/src/approval-service.ts index fb92105faf5..9c0854ceb48 100644 --- a/packages/plugins/plugin-approvals/src/approval-service.ts +++ b/packages/plugins/plugin-approvals/src/approval-service.ts @@ -75,6 +75,7 @@ import type { EnableLike, ObjectCapabilitiesParsed } from '@objectstack/spec/dat import { renderOperationMessage, type ValidationMessageTranslator } from '@objectstack/spec/system'; import { describePackageScopedHolder, + hasPlatformAdminStanding, holdsPlatformPermissionSet, isGrantActive, omitInternalFieldsFromWriteResponse, @@ -101,6 +102,13 @@ import { addressedPosition, equivalentApproverAddresses, heldSlot, + isPlatformAdminAddress, + pendingSlateAsDoorsRead, + readStoredSlate, + readsAsPlatformAdminAddress, + slateHoldsPlatformAdminAddress, + withoutPlatformAdminAddress, + PLATFORM_ADMIN_ADDRESS, positionAddresses, slateNamesAPerson, type ActingCaller, @@ -176,6 +184,19 @@ export interface ApprovalEngine { * resolver itself takes). */ getSchema?(objectName: string): unknown; + /** + * The package registry, read by the `platform_admin` approver's origin gate + * ({@link ApprovalService.platformAdminApproverRefusal}): the row the + * registering door wrote for a package, with its `source`. Optional so a + * double without it answers "origin unknown", and the gate refuses. + */ + registry?: { getPackage?(id: string): { source?: unknown } | undefined }; + /** + * `ObjectQL.residualOwnerSource`: the registering door's statement for an + * artifact residual's owner id, which has no registry row. Read by the same + * gate; absent, a residual owner's origin is unknown and the gate refuses. + */ + residualOwnerSource?(ownerId: string): 'code' | 'marketplace' | undefined; } /** @@ -1606,10 +1627,64 @@ function holdsDeclaredValues(value: unknown, declared: readonly string[]): boole return values.length > 0 && values.every((v) => v != null && declared.includes(String(v))); } -function csvSplit(raw: unknown): string[] { - if (!raw) return []; - if (Array.isArray(raw)) return raw.map(String).filter(Boolean); - return String(raw).split(',').map(s => s.trim()).filter(Boolean); +/** + * Does `body` hold `node` itself (the same object, at any depth: a top-level + * node or one inside a region)? Identity, never shape: two bodies may carry + * equal nodes. + */ +function bodyHoldsNode(body: unknown, node: object): boolean { + const seen = new Set(); + const stack: unknown[] = [body]; + while (stack.length) { + const cur = stack.pop(); + if (cur === node) return true; + if (!cur || typeof cur !== 'object' || seen.has(cur)) continue; + seen.add(cur); + for (const value of Array.isArray(cur) ? cur : Object.values(cur)) { + if (value && typeof value === 'object') stack.push(value); + } + } + return false; +} + +/** + * Split a comma-joined text (or an array) into its trimmed, non-empty parts. + * It is {@link readStoredSlate}, the one reading of a stored slate + * (`pending_approvers`) every door takes, so a rule judged on a slate's + * addresses there is judged on what these readers read. + */ +const csvSplit: (raw: unknown) => string[] = readStoredSlate; + +/** + * [#34218] The record a request's config snapshot (`node_config_json`) + * carries, `true`, when the step that opened it named the platform + * administrators (approver type `platform_admin`, admitted at node entry) and + * the slate it opened on holds their slot. Only the open path writes it, from + * that judgement alone: a key of this name handed in with the step's config is + * dropped, and `ApprovalNodeConfigSchema` declares no such key. + */ +const PLATFORM_ADMIN_SLOT_SNAPSHOT_KEY = '__platformAdminSlotOpened'; + +/** + * Does a request's config snapshot (the stored `node_config_json`, or that + * text parsed) record that a `platform_admin` approver opened its platform + * administrators' slot ({@link PLATFORM_ADMIN_SLOT_SNAPSHOT_KEY})? + */ +function platformAdminSlotOpened(snapshot: unknown): boolean { + const cfg = typeof snapshot === 'string' ? parseJson(snapshot, undefined) : snapshot; + return !!cfg && typeof cfg === 'object' && (cfg as Record)[PLATFORM_ADMIN_SLOT_SNAPSHOT_KEY] === true; +} + +/** + * [#34218] A stored request's pending slate as every door reads it: the + * decision and override admissions, the per-viewer flags, the served request + * and the approver index behind the inbox. Only the approver type that names + * the platform administrators opens their slot, so the slot stands on it + * only for a request that records a `platform_admin` step opened it + * ({@link platformAdminSlotOpened}); on any other request no door reads it. + */ +function pendingSlateOf(row: { pending_approvers?: unknown; node_config_json?: unknown } | null | undefined): string[] { + return pendingSlateAsDoorsRead(row?.pending_approvers, platformAdminSlotOpened(row?.node_config_json)); } /** @@ -1681,7 +1756,8 @@ function rowFromRequest(row: any): ApprovalRequestRow { cancel_reason: (row.cancel_reason as ApprovalCancelReason) ?? undefined, current_step: row.current_step ?? undefined, current_step_index: row.current_step_index ?? undefined, - pending_approvers: csvSplit(row.pending_approvers), + // [#34218] The slate as every door reads it ({@link pendingSlateOf}). + pending_approvers: pendingSlateAsDoorsRead(row.pending_approvers, platformAdminSlotOpened(cfg)), payload: parseJson(row.payload_json, undefined), flow_run_id: row.flow_run_id ?? undefined, flow_node_id: row.flow_node_id ?? undefined, @@ -2015,6 +2091,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega private messageTranslator?: () => ValidationMessageTranslator | undefined; /** [decision 6840464379] {@link authorizeSchemaRead}'s verdict, kept per request context. */ private readonly schemaReadVerdicts = new WeakMap>(); + /** {@link platformAdminStanding}'s answers, kept per request context and user. */ + private readonly platformAdminStandings = new WeakMap>>(); /** [#24863] Lazily-resolved `i18n` service for the reader-locale display labels. */ private i18nServiceSource?: () => ReaderLabelI18n | undefined; /** [ADR-0142 D6] Lazily-resolved `ownership-queue` service a `queue` approver expands through. */ @@ -2411,8 +2489,22 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * resolver lights this up without extra wiring. ⛔ NOT `positions` — on BOTH * rungs now: that array carries names, and a name is not an authority (see the * two blocks inside). - */ - private isOverrideActor(context: ExecutionContext, requestOrg?: string | null): boolean { + * + * [#34218] `pendingSlate` is passed by the override ADMISSIONS only (decide, + * reassign, recall and the `viewer.can_override` flag they agree with), never + * by a read grant. A slate holding the platform administrators' slot + * (`platform_admin:*`) closes the TENANT arm: such a step exists so that + * someone outside the request's organization decides it, and an override + * finalizes the whole request (it is not one vote among the slate), so an + * organization administrator overriding it would decide the platform's step + * for their own organization, on a mixed slate as on a pure one. The platform + * arm and the system context are unchanged. + */ + private isOverrideActor( + context: ExecutionContext, + requestOrg?: string | null, + pendingSlate?: readonly string[], + ): boolean { if (!context) return false; if (context.isSystem) return true; const perms = Array.isArray(context.permissions) ? context.permissions : []; @@ -2470,6 +2562,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const isTenantAdmin = posture === 'TENANT_ADMIN' || holdsTenantAdminRung(this.engine, held); if (!isTenantAdmin) return false; + if (pendingSlate !== undefined && slateHoldsPlatformAdminAddress(pendingSlate)) return false; // A tenant admin's authority stops at their own org. [ADR-0131 D1] NULL is // not a state and names no owner, so a request with no organization is no // organization administrator's to act on: under a walled posture it is the @@ -2603,6 +2696,10 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega for (const position of context.positions ?? []) { if (positionAddresses(position).includes(named)) return named; } + // The platform administrators' slot: admitted only while the server finds + // the caller in that standing, asked now (`hasPlatformAdminStanding`, the + // one per-user predicate), never read off the envelope. + if (isPlatformAdminAddress(named) && await this.platformAdminStanding(context, uid)) return named; // Email last — it costs a read, so only when nothing cheaper matched. if (named.includes('@') && await this.callerHasEmail(uid, named)) return named; @@ -2665,7 +2762,43 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const userId = context?.userId != null ? String(context.userId) : ''; if (!userId) return null; const email = await this.callerAccountEmail(userId); - return { userId, email, positions: context?.positions ?? [] }; + const platformAdmin = await this.platformAdminStanding(context, userId); + return { userId, email, positions: context?.positions ?? [], platformAdmin }; + } + + /** + * Is `userId` in platform-administrator standing right now? The answer of + * `hasPlatformAdminStanding` (`@objectstack/core`), the platform's one + * per-user predicate: the stored cross-tenant grant and the verified + * configured owner both meet there. It is read from the stored rows, never + * from the envelope's `posture`, so a revoked administrator holding a + * session opened before the revocation acts under nothing, and it decides + * whether the caller acts under {@link PLATFORM_ADMIN_ADDRESS}. + * + * Asked once per execution context (the object a transport builds per + * request) and user: the inbox read, the decision's actor check and its slot + * test share one answer. Fail-closed: the predicate answers `false` on any + * unreadable lookup, and on no user. + * + * ⚠️ The memo has no time bound. It is right only because every transport + * builds a fresh execution context per request, so an answer lives as long + * as the request that asked it. A context object kept across requests would + * carry one request's answer into the next, a revocation included, and must + * not reach this service. + */ + private async platformAdminStanding(context: ExecutionContext, userId: string): Promise { + if (!userId) return false; + const key = context && typeof context === 'object' ? (context as object) : undefined; + const memo = key ? this.platformAdminStandings.get(key) : undefined; + const known = memo?.get(userId); + if (known) return known; + const asked = hasPlatformAdminStanding(this.engine, userId); + if (key) { + const perUser = memo ?? new Map>(); + perUser.set(userId, asked); + if (!memo) this.platformAdminStandings.set(key, perUser); + } + return asked; } /** @@ -2811,8 +2944,13 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega a, record, organizationId, now, opts?.substitutions, opts?.exprCtx, onDirectoryFailure, ); if (opts?.resolvedFrom) opts.resolvedFrom[`expression#${idx}`] = resolved.raw; - for (const entry of resolved.slots) { - if (!entry.id) continue; + const kept = resolved.slots.filter((entry) => !!entry.id); + // The platform administrators' slot, judged on the slate as the doors + // read it back ({@link withoutPlatformAdminAddress}). + const opened = withoutPlatformAdminAddress(kept.map((entry) => entry.id)); + if (opened.length !== kept.length) this.warnPlatformSlotNotOpened('expression', idx); + for (const entry of kept) { + if (!opened.includes(entry.id)) continue; tag(entry.id, entry.subGroup ? `${groupKey}:${entry.subGroup}` : groupKey); if (named.has(entry.id)) continue; named.add(entry.id); @@ -2824,9 +2962,19 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (opts?.resolvedFrom && canonicalApproverType(String(a.type)) === 'field' && a.value != null) { opts.resolvedFrom[`field:${a.value}`] = (record as any)?.[a.value] ?? null; } - const ids = await this.resolveApproverSpec( + const resolvedIds = await this.resolveApproverSpec( a, record, organizationId, now, opts?.substitutions, onDirectoryFailure, opts?.callerPackageId ?? null, ); + // The platform administrators' slot is opened by the approver type that + // names them, and by nothing else: the slot is judged on the slate as + // every door reads it back once stored ({@link readStoredSlate}), not on + // the string a resolution produced. An entry that reads back as the slot + // adds nothing. Who may name the type itself is judged at node entry + // ({@link platformAdminApproverRefusal}). + const ids = canonicalApproverType(String(a.type)) === 'platform_admin' + ? resolvedIds + : withoutPlatformAdminAddress(resolvedIds); + if (ids.length !== resolvedIds.length) this.warnPlatformSlotNotOpened(canonicalApproverType(String(a.type)), idx); // per_group (#3266): tag each resolved id with this spec's group. for (const u of ids) { if (!u) continue; @@ -2839,6 +2987,16 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega return out.filter(Boolean); } + /** One warning for an approver entry whose resolution reached the platform administrators' slot. */ + private warnPlatformSlotNotOpened(type: string, index: number): void { + this.logger?.warn?.( + `[approvals] approver #${index} ('${type}') resolved to the platform administrators' slot, which only an ` + + `approver of type 'platform_admin' opens. It adds no slot to this request; a slate left naming no one is ` + + `decided by the node's onEmptyApprovers.`, + { type, index }, + ); + } + /** * Resolve ONE approver spec to concrete approver identities, applying OOO * substitution (#1322) to individually-routed types. Extracted from @@ -2888,6 +3046,12 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const directoryOrg = await this.directoryOrgFor(a, organizationId); const crossOrg = directoryOrg !== organizationId; + // The platform administrators: ONE address slot, never the people in it. + // Who may name this type is judged once, at node entry, before any slate + // is resolved ({@link platformAdminApproverRefusal}); who takes the slot + // is judged per caller, live, at the inbox and at each decision. + if (type === 'platform_admin') return [PLATFORM_ADMIN_ADDRESS]; + if (type === 'user') { // #27397: the value is the slot only when an account carries it — asked // through the ONE "does this address resolve to a person" predicate the @@ -3761,6 +3925,98 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }); } + /** + * Why an approval step may NOT name the platform administrators, or + * `undefined` when it may (or names no `platform_admin` approver at all, in + * `approvers` or `fallbackApprovers`). + * + * It may only in the running body of a flow a package ships, when that + * package came from the deployment's own code: `callerPackageId` is the + * armed body's package ({@link flowPackageOf}, the engine's + * `armedFlowPackage`), and the registry row the registering door wrote for + * it says `source: 'code'`. A residual owner, which has no row, counts only + * when the door that registered it recorded it as `code` + * (`residualOwnerSource`). The same origin reading the automation service's + * installed-package ref refusal takes (`nonHostDeclaringPackageOf`). + * + * Everything else is refused, fail closed: a flow authored in this + * environment, an environment override of a packaged flow (the engine names + * no package for the body it arms), a package installed from the + * marketplace or created here, and an origin nobody records. ⛔ Never asked + * of `packagedFlowOwner`: it names who ships the flow's NAME, so an override + * of a host flow would pass. + */ + /** Does the step's `approvers` or `fallbackApprovers` name the platform administrators? */ + private namesPlatformAdminApprover( + config: { approvers?: unknown; fallbackApprovers?: unknown } | null | undefined, + ): boolean { + const names = (list: unknown): boolean => Array.isArray(list) + && list.some((a) => canonicalApproverType(String((a as { type?: unknown } | null)?.type ?? '')) === 'platform_admin'); + return names(config?.approvers) || names(config?.fallbackApprovers); + } + + /** + * Is the step being opened a node of the body armed under the flow's key, + * the body {@link flowPackageOf} answers the origin of? The executor hands + * the node object it runs; the armed body is read under the same key the + * origin is read under (the run's slot, else the bare name), so the origin + * answered is the origin of the body whose step is being opened, in every + * run state. `false` when no node was handed, the engine cannot name the + * armed body, or the read fails: fail closed. + */ + private async stepRunsInArmedBody( + node: unknown, + flowSlot: { packageId: string | null; key: string } | undefined, + flowName: string | undefined, + ): Promise { + if (!node || typeof node !== 'object' || !flowName) return false; + const automation = this.automation; + let body: unknown = null; + try { + if (flowSlot && typeof automation?.getFlowSlot === 'function') body = automation.getFlowSlot(flowSlot.packageId, flowName); + else if (typeof automation?.getFlow === 'function') body = await automation.getFlow(flowName); + } catch { + return false; + } + return bodyHoldsNode(body, node); + } + + private platformAdminApproverRefusal( + config: { approvers?: unknown; fallbackApprovers?: unknown } | null | undefined, + callerPackageId: string | null, + ): string | undefined { + if (!this.namesPlatformAdminApprover(config)) return undefined; + if (!callerPackageId) { + return 'the body that runs is no package\'s own: a flow authored in this environment, an environment ' + + 'override of a packaged flow, or a body whose package the engine cannot name.'; + } + let row: { source?: unknown } | undefined; + try { + row = this.engine.registry?.getPackage?.(callerPackageId); + } catch { + return `the origin of package '${callerPackageId}' could not be read.`; + } + if (row !== undefined) { + if (row.source === 'code') return undefined; + const source = String(row.source); + const origin = source === 'marketplace' + ? 'was installed from the marketplace' + : source === 'authored' ? 'was created in this environment' : 'records no deployment origin'; + return `the body that runs is package '${callerPackageId}''s, which ${origin} (source '${source}').`; + } + let residual: 'code' | 'marketplace' | undefined; + try { + residual = this.engine.residualOwnerSource?.(callerPackageId); + } catch { + residual = undefined; + } + if (residual === 'code') return undefined; + return residual === 'marketplace' + ? `the body that runs is package '${callerPackageId}''s, which was installed from the marketplace.` + : `the body that runs is package '${callerPackageId}''s, which no registration in this runtime records as ` + + 'the deployment\'s own.'; + } + /** * [ADR-0150 D3] The package the approval step of flow `flowName` is * written in: the package of the body the engine runs for the flow, as the @@ -4232,6 +4488,19 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // no slot — with the "expanded to nobody" warning, and its hops leave the // collector so no substitution is audited or notified. A failed read // proves nothing, so the delegate stays. + // A delegation hands a slot to a person. The platform administrators' slot + // is opened only by the approver type that names them, so the slot stays + // with the original approver and the hops are not audited. + if (current !== start && readsAsPlatformAdminAddress(current)) { + this.logger?.warn?.( + `[approvals] out-of-office delegate of '${start}' is the platform administrators' slot, which a delegation ` + + `cannot hand a request to, so the slot stays with '${start}'. Point the delegation at a person, or ` + + `delete it.`, + { delegatorId: start, organizationId: organizationId ?? null }, + ); + if (collector) collector.length = mark; + return [start]; + } if (current !== start && !current.includes(':') && await this.namesNoAccount(current)) { this.logger?.warn?.( `[approvals] out-of-office delegate '${current}' of '${start}' expanded to nobody — the delegation ` @@ -4606,6 +4875,13 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * approvers. `input.record` doubles as their `trigger.*` root. */ variables?: Record | null; + /** + * The node object the engine is executing, as the approval executor + * receives it. Read only when the step names the platform administrators: + * such a step opens only when this node belongs to the body armed under + * the flow's key, the body whose origin {@link flowPackageOf} answers. + */ + node?: unknown; }, context: ExecutionContext, ): Promise { @@ -4672,6 +4948,24 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // No package is asked here, so no stamp can have withdrawn. const flowSlot = isWithdrawnRequestFlow(runSlot) ? undefined : runSlot; const callerPackageId = this.flowPackageOf(flowSlot?.key ?? input.flowName); + // `platform_admin` addresses the deployment's platform administrators, so + // only a flow body a `code` package ships may name it. Refused here, fail + // closed and before any slate is read or any row written. + let platformAdminRefused = this.platformAdminApproverRefusal(input.config, callerPackageId); + if (!platformAdminRefused && this.namesPlatformAdminApprover(input.config) + && !(await this.stepRunsInArmedBody(input.node, flowSlot, input.flowName))) { + platformAdminRefused = 'the body that runs is not the one armed under the flow\'s name, whose origin is the ' + + 'one this deployment records, so the origin of the running body cannot be answered.'; + } + if (platformAdminRefused) { + throw new Error( + `FORBIDDEN: approval node '${input.nodeId}'${input.flowName ? ` of flow '${input.flowName}'` : ''} names ` + + `the platform administrators (approver type 'platform_admin'), and ${platformAdminRefused} Only the ` + + `running body of a flow shipped by a package this deployment registers in code may name them. The node ` + + `does not open. Route the step to people of the request's organization, or ship the flow in a package ` + + `the deployment registers in code.`, + ); + } const submitterId = input.submitterId !== undefined ? input.submitterId : (context.userId ?? null); // [#25573] `excludeSubmitter: true` (ruling 6377888641, letter B): the // submitter is taken off every slate this request can open on. It runs on @@ -4936,6 +5230,13 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega configSnapshot.__resolvedFrom = resolvedFrom; } if (adminRescueNote) configSnapshot[ADMIN_RESCUE_NOTE_SNAPSHOT_KEY] = adminRescueNote; + // [#34218] Whether a `platform_admin` step opened the platform + // administrators' slot: the record the doors honour the slot on + // ({@link pendingSlateOf}). Written here alone, from this judgement alone. + const platformSlotOpened = this.namesPlatformAdminApprover(input.config) + && approvers.some(isPlatformAdminAddress); + delete configSnapshot[PLATFORM_ADMIN_SLOT_SNAPSHOT_KEY]; + if (platformSlotOpened) configSnapshot[PLATFORM_ADMIN_SLOT_SNAPSHOT_KEY] = true; // [#25573] The record shows when the exclusion changed the route: the // route the request took once the submitter was off its slate. const exclusionNote: SubmitterExclusionNote | undefined = excludedFrom.size @@ -4984,7 +5285,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega updated_at: now, }; await this.engine.insert('sys_approval_request', row, { context: SYSTEM_CTX }); - await this.syncApproverIndex(id, approvers, requestOrg, now); + await this.syncApproverIndex(id, approvers, requestOrg, now, platformSlotOpened); await this.engine.insert('sys_approval_action', await this.actionRow(row, { id: uid('aact'), request_id: id, organization_id: requestOrg, step_name: input.nodeId, step_index: 0, action: 'submit', @@ -5338,11 +5639,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega await this.refuseUnreadableRequest(raw, requestId, context); if (raw.status !== 'pending') throw new Error(`INVALID_STATE: request is ${raw.status}`); - const pendingApprovers = csvSplit(raw.pending_approvers); + const pendingApprovers = pendingSlateOf(raw); // A privileged admin may override a stuck request (#3424) even when they // hold no slot — the escape hatch for an approval routed to an unstaffed // position or to approvers who have all left. - const isOverride = this.isOverrideActor(context, raw.organization_id ?? null); + const isOverride = this.isOverrideActor(context, raw.organization_id ?? null, pendingApprovers); const slot = await this.takenSlot(pendingApprovers, actorId, context); const isSlotHolder = slot !== undefined; if (!isSlotHolder && !isOverride) { @@ -5543,7 +5844,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega }), } : {}), }, { context: SYSTEM_CTX }); - await this.syncApproverIndex(requestId, stillPending, org, now); + await this.syncApproverIndex(requestId, stillPending, org, now, platformAdminSlotOpened(config)); const fresh = await this.readBackRequest(requestId, context); return { request: fresh, runId, nodeId, finalized: false, decision: input.decision }; } @@ -6209,7 +6510,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // one hardcoded English sentence that Console rendered verbatim in a // toast. See {@link ApprovalService.userFacingRefusal}. const overrideAdmits = raw.status === 'pending' - && this.isOverrideActor(context, raw.organization_id ?? null); + && this.isOverrideActor(context, raw.organization_id ?? null, pendingSlateOf(raw)); // A request with no submitter is recalled only through the arm above (a // system context or the override actor, on `pending`): `actsAsSubmitter` // answers no for every actor there. @@ -6637,7 +6938,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega ): Promise { const actorId = await this.resolveActor(input?.actorId, context); const raw = await this.loadPendingRow(requestId, context); - const pending = csvSplit(raw.pending_approvers); + const pending = pendingSlateOf(raw); const slot = await this.takenSlot(pending, actorId, context); if (!context.isSystem && slot === undefined) { throw new Error(`FORBIDDEN: actor '${actorId}' is not a pending approver`); @@ -6953,11 +7254,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (!to) throw new Error('VALIDATION_FAILED: `to` (new approver) is required'); const raw = await this.loadPendingRow(requestId, context); - const pending = csvSplit(raw.pending_approvers); + const pending = pendingSlateOf(raw); if (pending.includes(to)) { throw new Error(`VALIDATION_FAILED: '${to}' is already a pending approver`); } - const isOverride = this.isOverrideActor(context, raw.organization_id ?? null); + const isOverride = this.isOverrideActor(context, raw.organization_id ?? null, pending); // The slot the actor takes (`takenSlot`) — and, when `from` is not named, // the slot being handed over. const slot = await this.takenSlot(pending, actorId, context); @@ -6974,6 +7275,16 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega if (!context.isSystem && !isOverride && slot === undefined) { throw new Error(`FORBIDDEN: actor '${actorId}' is not a pending approver`); } + // The platform's place on a request stays the platform's: it moves for + // a caller in platform-administrator standing now, the platform + // override, or the system (which `isOverrideActor` admits). + if (isPlatformAdminAddress(from) && !isOverride + && !(await this.platformAdminStanding(context, context.userId != null ? String(context.userId) : ''))) { + throw new Error( + `FORBIDDEN: actor '${actorId}' may not move the platform administrators' slot: it moves only for a ` + + `platform administrator, or the system`, + ); + } next = pending.map(a => (a === from ? to : a)); } else if (isOverride) { // Admin rescue (#3424): the caller holds no slot — the slate is an @@ -7025,7 +7336,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega id: requestId, pending_approvers: next.join(','), updated_at: now, ...configPatch, pending_approver_labels: await this.slateLabels(next), }, { context: SYSTEM_CTX }); - await this.syncApproverIndex(requestId, next, raw.organization_id ?? null, now); + await this.syncApproverIndex(requestId, next, raw.organization_id ?? null, now, platformAdminSlotOpened(raw.node_config_json)); await this.notify({ topic: 'approval.reassigned', @@ -7118,6 +7429,11 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * is that docblock's. */ private async reassignTargetRefusal(to: string, organizationId: string | null): Promise { + // Judged first, on the slate as the doors read it back once `to` is stored + // on it: a hand-off never puts the platform administrators' slot there. + if (readsAsPlatformAdminAddress(to)) { + return 'it is the platform administrators\' slot, which only an approval step that names them opens.'; + } const position = addressedPosition(to); if (position !== undefined) { if ((await this.expandPositionUsers(position, organizationId)).length) return undefined; @@ -7170,7 +7486,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega throw new Error('THROTTLED: a reminder was already sent recently'); } - const pending = csvSplit(raw.pending_approvers); + const pending = pendingSlateOf(raw); const nowIso = now.toISOString(); await this.engine.insert('sys_approval_action', await this.actionRow(raw, { id: uid('aact'), request_id: requestId, organization_id: raw.organization_id ?? null, @@ -7265,7 +7581,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega // Minted by the server for a slot it names, on behalf of no reader — read // as the system, as before. const raw = await this.loadPendingRow(requestId, SYSTEM_CTX); - const pending = csvSplit(raw.pending_approvers); + const pending = pendingSlateOf(raw); if (!pending.includes(approverId)) { throw new Error(`FORBIDDEN: '${approverId}' is not a pending approver on this request`); } @@ -7461,7 +7777,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const actorId = await this.resolveActor(input?.actorId, context); if (!input?.comment?.trim()) throw new Error('VALIDATION_FAILED: comment is required'); const raw = await this.loadPendingRow(requestId, context); - const pending = csvSplit(raw.pending_approvers); + const pending = pendingSlateOf(raw); const slot = await this.takenSlot(pending, actorId, context); if (!context.isSystem && slot === undefined) { throw new Error(`FORBIDDEN: actor '${actorId}' is not a pending approver`); @@ -7501,7 +7817,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const actorId = await this.resolveActor(input?.actorId, context); if (!input?.comment?.trim()) throw new Error('VALIDATION_FAILED: comment is required'); const raw = await this.loadPendingRow(requestId, context); - const pending = csvSplit(raw.pending_approvers); + const pending = pendingSlateOf(raw); const isSubmitter = raw.submitter_id && String(raw.submitter_id) === String(actorId); // The submitter speaks as themselves; anyone else speaks from the slot // they take (`takenSlot`). @@ -8553,7 +8869,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const escalateTo: string | undefined = typeof esc.escalateTo === 'string' && esc.escalateTo.trim() ? esc.escalateTo.trim() : undefined; const now = this.clock.now().toISOString(); - const pending = csvSplit(raw.pending_approvers); + const pending = pendingSlateOf(raw); // [#23978] Every escalation sentence names the record the way every approval notification does. const about = { object: String(raw.object_name), recordId: String(raw.record_id) }; @@ -8565,7 +8881,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega let literalTarget = false; if (escalateTo) { try { - escalatees = await this.expandPositionUsers(escalateTo, raw.organization_id ?? null); + escalatees = withoutPlatformAdminAddress(await this.expandPositionUsers(escalateTo, raw.organization_id ?? null)); } catch { escalatees = []; } if (!escalatees.length) { escalatees = [escalateTo]; literalTarget = true; } } @@ -8623,7 +8939,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega id: raw.id, pending_approvers: escalatees.join(','), updated_at: now, pending_approver_labels: await this.slateLabels(escalatees), }, { context: SYSTEM_CTX }); - await this.syncApproverIndex(raw.id, escalatees, raw.organization_id ?? null, now); + await this.syncApproverIndex(raw.id, escalatees, raw.organization_id ?? null, now, platformAdminSlotOpened(raw.node_config_json)); await this.notify({ topic: 'approval.escalated', organizationId: raw.organization_id, @@ -9390,14 +9706,21 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega * the approver set; an empty `approvers` clears the request's rows (the * request left `pending`). Diff-based so reassign/unanimous churn doesn't * rewrite untouched rows. + * + * [#34218] `platformSlotOpened` is the request's record that a + * `platform_admin` step opened the platform administrators' slot + * ({@link platformAdminSlotOpened}); without it the slot is not indexed, as + * no door reads it ({@link pendingSlateOf}). */ private async syncApproverIndex( requestId: string, approvers: string[], org: string | null, now: string, + platformSlotOpened = false, ): Promise { - const desired = new Set(approvers.map(a => String(a).trim()).filter(Boolean)); + const indexed = platformSlotOpened ? approvers : withoutPlatformAdminAddress(approvers); + const desired = new Set(indexed.map(a => String(a).trim()).filter(Boolean)); const existing = await this.engine.find('sys_approval_approver', { where: { request_id: requestId }, limit: 500, context: SYSTEM_CTX, }); @@ -9432,7 +9755,8 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega const requests = keysetWalk>( (q) => this.engine.find('sys_approval_request', { ...q, - fields: ['id', 'pending_approvers', 'organization_id'], + // [#34218] The snapshot too: the slate is read as every door reads it. + fields: ['id', 'pending_approvers', 'organization_id', 'node_config_json'], context: SYSTEM_CTX, }), { where: { status: 'pending' }, pageSize: PAGE }, @@ -9440,7 +9764,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega for await (const rows of requests.pages()) { for (const r of rows) { desired.set(String(r.id), { - approvers: new Set(csvSplit(r.pending_approvers)), + approvers: new Set(pendingSlateOf(r)), org: r.organization_id ?? null, }); } @@ -10385,7 +10709,7 @@ export class ApprovalService implements IApprovalService, ObjectSchemaReadDelega can_act: row.status === 'pending' && !!caller && heldSlot(pending, caller.userId, caller) !== undefined, is_submitter: !!uid && row.submitter_id != null && String(row.submitter_id) === uid, can_override: row.status === 'pending' - && this.isOverrideActor(context, (row as any).organization_id ?? null), + && this.isOverrideActor(context, (row as any).organization_id ?? null, pending), }; } } diff --git a/packages/plugins/plugin-approvals/src/approver-address.ts b/packages/plugins/plugin-approvals/src/approver-address.ts index 476a2ba4b3c..aee4ba4ed9e 100644 --- a/packages/plugins/plugin-approvals/src/approver-address.ts +++ b/packages/plugins/plugin-approvals/src/approver-address.ts @@ -58,6 +58,88 @@ * a slot-against-caller comparison written anywhere else. */ +/** + * The ONE slot a `platform_admin` approver opens: an address, not a person. + * It names the deployment's platform administrators as a class, so it is + * never expanded to the people in it (`hasPlatformAdminStanding` is a + * per-user predicate and forbids the population read). A caller acts under it + * exactly when the server finds them in that standing, at the moment they + * ask ({@link ActingCaller.platformAdmin}), so a revocation takes effect at + * the next read or decision, on requests opened before it too. + * + * Spelled `type:value` like every other address: the readers that + * tell a person from an address (notification fan-out, the record-read + * grant, out-of-office, labels) test for the colon, and this slot must read + * as an address to every one of them. It names no person, so it grants no + * record read and is told nothing. + */ +export const PLATFORM_ADMIN_ADDRESS = 'platform_admin:*'; + +/** Does `address` name the platform administrators' slot ({@link PLATFORM_ADMIN_ADDRESS})? */ +export function isPlatformAdminAddress(address: string): boolean { + return address === PLATFORM_ADMIN_ADDRESS; +} + +/** + * [#34218] Does the slate hold the platform administrators' slot? Read by the + * override admissions (`isOverrideActor`'s `pendingSlate`): such a slate is + * the platform's to decide, so the tenant-admin override arm is withheld from + * the whole request, a mixed slate included. + */ +export function slateHoldsPlatformAdminAddress(slate: readonly string[]): boolean { + return slate.some(isPlatformAdminAddress); +} + +/** + * A stored slate as every door reads it back. `pending_approvers` is stored + * as one text, and the decision and override admissions, the per-viewer + * flags and the approver-index rebuild all read it through this function + * (the approval service's `csvSplit` is it). An address on a slate is what + * this answers, never the string a resolution produced, so a rule about which + * addresses a slate may hold is judged on this answer. + */ +export function readStoredSlate(raw: unknown): string[] { + if (!raw) return []; + if (Array.isArray(raw)) return raw.map(String).filter(Boolean); + return String(raw).split(',').map((s) => s.trim()).filter(Boolean); +} + +/** + * Does `entry`, once stored on a slate, read back as holding the platform + * administrators' slot ({@link readStoredSlate})? The slot is judged on the + * slate the doors read, not on the value a resolution produced. Any entry is + * judged as the text it is stored as, so the answer is total: a value that is + * not text (a number, a list, an object) is judged as the text the stored + * slate holds for it. + */ +export function readsAsPlatformAdminAddress(entry: unknown): boolean { + return readStoredSlate(entry == null ? '' : String(entry)).some(isPlatformAdminAddress); +} + +/** + * `ids` without any entry that reads back as the platform administrators' + * slot ({@link readsAsPlatformAdminAddress}): the slot is judged on the slate + * as the doors read it, so such an entry adds nothing to it. Read where a + * slate is resolved from anything but the approver type that names them, + * which alone opens it. + */ +export function withoutPlatformAdminAddress(ids: readonly T[]): T[] { + return ids.filter((id) => !readsAsPlatformAdminAddress(id)); +} + +/** + * [#34218] A request's pending slate as the decision, override and inbox + * doors read it: the stored slate ({@link readStoredSlate}), on which the + * platform administrators' slot stands only when the request records that a + * `platform_admin` approver opened it (`slotOpened`). On a request without + * that record no door reads the slot, whatever its stored text holds: only + * the approver type that names the platform administrators opens their slot. + */ +export function pendingSlateAsDoorsRead(stored: unknown, slotOpened: boolean): string[] { + const slate = readStoredSlate(stored); + return slotOpened ? slate : withoutPlatformAdminAddress(slate); +} + /** * The prefixes under which a slot address names a position: `position:` alone * (ADR-0090 D3 — the retired `role:` is no alias of it). Kept a list so every @@ -118,12 +200,21 @@ export interface ActingCaller { readonly userId: string; readonly email?: string | null; readonly positions?: readonly unknown[]; + /** + * Whether the server finds the caller in platform-administrator standing + * (`hasPlatformAdminStanding`, read live for this request). `true` adds + * {@link PLATFORM_ADMIN_ADDRESS} to the addresses they act under; absent + * reads as `false`, so a caller built without asking acts under nothing + * more than before. + */ + readonly platformAdmin?: boolean; } /** * Every slot address the caller acts under WITHOUT naming one — the default - * actor — in the order a slot is taken: the user id, the account's email, then - * the address of every held position. + * actor — in the order a slot is taken: the user id, the account's email, the + * address of every held position, then the platform administrators' slot for a + * caller in that standing. * * The email is matched as the account stores it. `resolveActor` admits a * NAMED email case-insensitively, and that named spelling is judged by @@ -133,6 +224,7 @@ export function actingAddresses(caller: ActingCaller): string[] { const out = [caller.userId]; if (caller.email) out.push(caller.email); for (const position of caller.positions ?? []) out.push(...positionAddresses(position)); + if (caller.platformAdmin === true) out.push(PLATFORM_ADMIN_ADDRESS); return [...new Set(out)]; } @@ -156,6 +248,12 @@ export function actorAddresses(actorId: string, caller: ActingCaller | null): st * slate is a `type:value` literal, left by an approver target that resolved to * no holder (`position:

`, `team:`, a stored `role:

`). * + * One address counts as naming someone: {@link PLATFORM_ADMIN_ADDRESS}. It is + * not an approver target that found nobody; it is the address the platform + * administrators decide under, and it is never expanded. Read as empty, the + * default `admin_rescue` would replace it with the request organization's + * administrators, the very people the type exists to keep off the slate. + * * `false` is the slate the open path hands to the node's `onEmptyApprovers` * policy, and the one it re-tests after a `fallback` before the default * `admin_rescue` opens on the organization's administrators (#22824). One @@ -165,7 +263,7 @@ export function actorAddresses(actorId: string, caller: ActingCaller | null): st * is not a reader of the equivalence above. */ export function slateNamesAPerson(slate: readonly string[]): boolean { - return slate.some((address) => !!address && !address.includes(':')); + return slate.some((address) => !!address && (!address.includes(':') || isPlatformAdminAddress(address))); } /** diff --git a/packages/plugins/plugin-approvals/src/platform-admin-approver-34218.test.ts b/packages/plugins/plugin-approvals/src/platform-admin-approver-34218.test.ts new file mode 100644 index 00000000000..63c6fc89de7 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/platform-admin-approver-34218.test.ts @@ -0,0 +1,862 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * The `platform_admin` approver type: one address slot the platform + * administrators decide under, named only by the deployment's own packaged + * flows. + * + * ## What this pins + * + * Driven through the real `ApprovalService` on a real `ObjectQL` over + * `SqlDriver` (better-sqlite3, in-memory, real DDL), with the real + * `hasPlatformAdminStanding` reading the stored grant rows and the configured + * owner list, and a real package registry stating each package's origin: + * + * - the step opens on ONE slot, `platform_admin:*`, that names no person: no + * one is told, and the default `admin_rescue` does not replace it; + * - a holder of the cross-tenant `admin_full_access` grant, and the verified + * configured owner who has no grant row, each find it in their inbox and + * decide it as an ordinary approver; the decision records the person and the + * slot (`actor_id`, `acted_as`), not an override; + * - a member of the request's organization takes no slot and cannot decide; + * an administrator of that organization takes no slot either (the #3424 + * override stays what it was, and is recorded as one), and an administrator + * of another organization cannot decide at all; + * - a revoked administrator cannot decide a request opened before the + * revocation; + * - the node refuses to open, writing nothing, unless the running body is a + * `code` package's own: a flow authored in the environment, an environment + * override of a host flow (whose NAME a host package ships), a marketplace + * or authored package's flow, an unrecorded package, and a fallback slate + * naming the type are all refused; a residual owner a `code` door recorded + * is admitted; + * - the save door refuses the type as early feedback; `os lint` does not; + * - CONTROL: an existing approver type opens and is decided as before, and + * the platform administrator takes no slot on it. + */ + +import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { AutomationEngine } from '@objectstack/service-automation'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { bindSecurityCatalogReader, type SecurityCatalogEntry, type SecurityCatalogReader } from '@objectstack/core'; +import { normalizeStackInput } from '@objectstack/spec'; +import { ApprovalNodeConfigSchema } from '@objectstack/spec/automation'; +import { runAuthoringRules, runRuntimeAuthoringRules, APPROVAL_APPROVER_PLATFORM_ADMIN_AUTHORED } from '@objectstack/lint'; +import { ApprovalService } from './approval-service.js'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; +import { registerApprovalNode } from './approval-node.js'; +import { readStoredSlate, readsAsPlatformAdminAddress } from './approver-address.js'; +import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js'; + +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as any; +const SLOT = 'platform_admin:*'; +const ORG = 'org_a'; +const OTHER_ORG = 'org_b'; +const OWNER_EMAIL = 'owner@platform.test'; + +/** + * A fresh acting envelope per call, as a transport builds one per request, + * carrying NO posture and no permissions: every admission below comes from + * the stored rows the predicate reads, never from the envelope. + */ +const as = (userId: string, org = ORG, permissions: string[] = []) => + ({ userId, tenantId: org, positions: [], permissions }) as any; + +const USERS = [ + { id: 'u_sub', email: 'u_sub@example.com' }, + { id: 'u_root', email: 'u_root@example.com' }, + { id: 'u_owner_cfg', email: OWNER_EMAIL, email_verified: true }, + { id: 'u_member', email: 'u_member@example.com' }, + { id: 'u_org_admin', email: 'u_org_admin@example.com' }, + { id: 'u_other_admin', email: 'u_other_admin@example.com' }, + { id: 'u_revoked', email: 'u_revoked@example.com' }, + { id: 'u_alice', email: 'u_alice@example.com' }, +]; + +const MEMBERS: Array<[string, string, string]> = [ + ['u_sub', ORG, 'member'], + ['u_root', ORG, 'member'], + ['u_owner_cfg', ORG, 'member'], + ['u_member', ORG, 'member'], + ['u_org_admin', ORG, 'admin'], + ['u_other_admin', OTHER_ORG, 'admin'], + ['u_revoked', ORG, 'member'], + ['u_alice', ORG, 'member'], +]; + +/** The Default Organization: an `admin_full_access` grant anchors platform standing only there (ADR-0131 D5). */ +const DEFAULT_ORG = 'org_default'; + +/** `sys_user_permission_set`: the platform grant lives in the Default Organization. */ +const GRANTS: Array<[string, string, string, string | null]> = [ + ['ups_root', 'u_root', 'admin_full_access', DEFAULT_ORG], + ['ups_revoked', 'u_revoked', 'admin_full_access', DEFAULT_ORG], + ['ups_org_admin', 'u_org_admin', 'organization_admin', ORG], + ['ups_other_admin', 'u_other_admin', 'organization_admin', OTHER_ORG], +]; + +/** Which package's body the engine arms for each flow name (`armedFlowPackage`). */ +const ARMED: Record = { + host_review: 'com.host.review', + residual_review: 'com.host.residual', + marketplace_review: 'com.vendor.app', + authored_review: 'com.tenant.authored', + unrecorded_review: 'com.nobody.recorded', + installed_residual_review: 'com.vendor.residual', + // A flow authored in the environment, and an environment override of the + // host's `host_review_overridden`: the engine names no package for either. + tenant_review: undefined, + host_review_overridden: undefined, +}; +/** Who ships each flow's NAME (`packagedFlowOwner`): the override's name is the host's. */ +/** + * The body the engine holds armed under every flow name here: one approval + * node, the object the executor hands when the run executes that body. + */ +const ARMED_NODE = { id: 'review', type: 'approval', label: 'Review', config: { approvers: [{ type: 'platform_admin' }] } }; +const ARMED_BODY = { nodes: [{ id: 'start', type: 'start' }, ARMED_NODE] }; +const NAME_OWNER: Record = { + host_review: 'com.host.review', + host_review_overridden: 'com.host.review', +}; +/** A stand-in for the flow engine's reads, answering from the tables above. */ +const STAND_IN_AUTOMATION = { + armedFlowPackage: (name: string) => ARMED[name], + packagedFlowOwner: (name: string) => NAME_OWNER[name], + getFlow: async () => ARMED_BODY, +} as any; + +const text = (name: string) => ({ name, label: name, type: 'text' as const }); +const objectDef = (name: string, fields: string[], extra: Record = {}) => ({ + name, + label: name, + fields: Object.fromEntries([ + ['id', { ...text('id'), primaryKey: true }], + ...fields.map((f) => [f, text(f)]), + ...Object.entries(extra), + ]), +}); + +function catalogServing(names: string[]): SecurityCatalogReader { + const entry = (name: string): SecurityCatalogEntry => ({ + type: 'permission', name, definition: { name }, source: 'registry', + }); + return { + async resolve(type, name) { + return type === 'permission' && names.includes(name) ? entry(name) : undefined; + }, + async list(type) { + return type === 'permission' ? names.map(entry) : []; + }, + }; +} + +async function packageObjects(): Promise { + let manifest: any; + const ctx: any = { + getService: (name: string) => { + if (name === 'manifest') return { register: (m: any) => { manifest = m; } }; + throw new Error(`no service '${name}'`); + }, + logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} }, + }; + await new ApprovalsServicePlugin().init(ctx); + return manifest.objects; +} + +const pkg = (id: string) => ({ id, name: id, version: '1.0.0', type: 'app' }); + +/** The members each queue's expander answers, as the queue service would. */ +const QUEUES: Record = {}; + +/** The record a request's snapshot carries when a `platform_admin` step opened its slot. */ +const SLOT_RECORD_KEY = '__platformAdminSlotOpened'; + +describe('platform_admin approver: one slot the platform administrators decide under', () => { + let engine: ObjectQL; + let svc: ApprovalService; + let now = Date.parse('2026-11-16T09:00:00.000Z'); + const told: string[][] = []; + const prevOwnerEnv = process.env.OS_PLATFORM_OWNER_EMAIL; + + const open = async ( + key: string, flowName: string, approvers: any[], extra: Record = {}, + scene: { fields?: Record; node?: unknown } = {}, + ) => { + const fields = { title: key, ...scene.fields }; + await engine.insert('crm_deal', { id: `D_${key}`, ...fields, organization_id: ORG }, { context: SYSTEM } as any); + const opened = await svc.openNodeRequest({ + object: 'crm_deal', recordId: `D_${key}`, runId: `run_${key}`, nodeId: 'review', flowName, + config: { approvers, behavior: 'first_response', ...extra } as any, + submitterId: 'u_sub', record: { id: `D_${key}`, ...fields }, organizationId: ORG, + node: 'node' in scene ? scene.node : ARMED_NODE, + }, as('u_sub')); + // A slate that reads as empty auto-approves instead of opening; no pin here + // expects that, so it is a failure of the scene, not a branch to handle. + if ('autoApproved' in opened) throw new Error(`node ${key} auto-approved instead of opening`); + return opened; + }; + const PLATFORM = [{ type: 'platform_admin' }]; + const requestRows = async (key: string): Promise => engine.find('sys_approval_request', { + where: { record_id: `D_${key}` }, context: SYSTEM, + }); + const actionsOf = async (requestId: string): Promise => engine.find('sys_approval_action', { + where: { request_id: requestId }, context: SYSTEM, + }); + /** The inbox asked for the platform slot, as the caller. */ + const inbox = async (ctx: any): Promise => + (await svc.listRequests({ status: 'pending', approverId: [SLOT] }, ctx)).map((r) => r.id).sort(); + + beforeAll(async () => { + process.env.OS_PLATFORM_OWNER_EMAIL = OWNER_EMAIL; + engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true, + }), true); + await engine.init(); + const defs = [ + // Accounts belong to no organization: membership says which they are in. + { + ...objectDef('sys_user', ['name', 'email', 'manager_id'], { email_verified: { name: 'email_verified', label: 'v', type: 'boolean' } }), + systemFields: { tenant: false }, + }, + // Organizations belong to no organization (ADR-0131). + { ...objectDef('sys_organization', ['name', 'slug']), systemFields: { tenant: false } }, + objectDef('sys_member', ['user_id', 'organization_id', 'role']), + objectDef('sys_user_position', ['user_id', 'position', 'organization_id']), + objectDef('sys_user_permission_set', ['user_id', 'permission_set', 'organization_id']), + objectDef('crm_deal', ['title', 'reviewer', 'subject', 'organization_id'], { + reviewers: { name: 'reviewers', label: 'reviewers', type: 'lookup', reference: 'sys_user', multiple: true }, + }), + ...(await packageObjects()), + ]; + for (const def of defs) engine.registry.registerObject(def as any, 'approvals-test', 'approvals-test'); + await engine.syncSchemas(); + await relaxTenantColumns(engine, ['sys_user', 'sys_user_permission_set', 'crm_deal']); + bindSecurityCatalogReader(engine, catalogServing(['organization_admin', 'admin_full_access'])); + for (const [id, slug] of [[DEFAULT_ORG, 'default'], [ORG, 'org-a'], [OTHER_ORG, 'org-b']]) { + await engine.insert('sys_organization', { id, slug, name: slug }, { context: SYSTEM } as any); + } + for (const u of USERS) await engine.insert('sys_user', { name: u.id, ...u }, { context: SYSTEM } as any); + for (const [i, [user_id, organization_id, role]] of MEMBERS.entries()) { + await engine.insert('sys_member', { id: `m_${i}`, user_id, organization_id, role }, { context: SYSTEM } as any); + } + for (const [id, user_id, permission_set, organization_id] of GRANTS) { + await engine.insert('sys_user_permission_set', { id, user_id, permission_set, organization_id }, + { context: SYSTEM } as any); + } + // The registering doors' statements: the host's own code, a marketplace + // install, a package created in this environment, and two residual owners. + engine.registry.installPackage(pkg('com.host.review') as never, 'code'); + engine.registry.installPackage(pkg('com.vendor.app') as never, 'marketplace'); + engine.registry.installPackage(pkg('com.tenant.authored') as never, 'authored'); + engine.recordResidualOwner('com.host.residual', 'code'); + engine.recordResidualOwner('com.vendor.residual', 'marketplace'); + + svc = new ApprovalService({ + engine: engine as any, + clock: { now: () => new Date(now += 1000) }, + logger: { warn: () => {}, info: () => {}, error: () => {}, debug: () => {} } as any, + ownershipQueues: () => ({ expandMembers: async (name: string) => QUEUES[name] ?? [] }), + }); + svc.attachMessaging({ + emit: (async (input: { topic: string; audience: string[] }) => { + if (input.topic === 'approval.requested') told.push(input.audience); + }) as any, + }); + svc.attachAutomation(STAND_IN_AUTOMATION); + }); + + afterAll(async () => { + if (prevOwnerEnv === undefined) delete process.env.OS_PLATFORM_OWNER_EMAIL; + else process.env.OS_PLATFORM_OWNER_EMAIL = prevOwnerEnv; + try { await engine?.destroy(); } catch { /* noop */ } + }); + + it('a host flow opens on the one slot, tells no one, and admin_rescue does not replace it', async () => { + const before = told.length; + const row = await open('slot', 'host_review', PLATFORM); + expect(row.status).toBe('pending'); + expect(row.pending_approvers).toEqual([SLOT]); + expect(told.slice(before).flat()).toEqual([]); + }); + + it('a holder of the cross-tenant grant finds it and decides it as an ordinary approver', async () => { + const row = await open('grant', 'host_review', PLATFORM); + expect(await inbox(as('u_root'))).toContain(row.id); + expect((await svc.getRequest(row.id, as('u_root')) as any)?.viewer?.can_act).toBe(true); + const out = await svc.decide(row.id, { decision: 'approve' } as any, as('u_root')); + expect([out.finalized, out.request.status]).toEqual([true, 'approved']); + const decision = (await actionsOf(row.id)).find((a) => a.action === 'approve'); + expect(decision).toMatchObject({ actor_id: 'u_root', acted_as: SLOT }); + expect(Boolean(decision?.via_override)).toBe(false); + }); + + it('the verified configured owner, who has no grant row, decides it too', async () => { + const row = await open('owner', 'host_review', PLATFORM); + expect(await inbox(as('u_owner_cfg'))).toContain(row.id); + // Naming the slot is admitted for the owner as well as the default actor. + const out = await svc.decide(row.id, { decision: 'reject', actorId: SLOT } as any, as('u_owner_cfg')); + expect(out.request.status).toBe('rejected'); + const decision = (await actionsOf(row.id)).find((a) => a.action === 'reject'); + expect(decision).toMatchObject({ actor_id: 'u_owner_cfg', acted_as: SLOT }); + expect(Boolean(decision?.via_override)).toBe(false); + }); + + it('a member of the request\'s organization takes no slot and cannot decide', async () => { + const row = await open('member', 'host_review', PLATFORM); + expect(await inbox(as('u_member'))).toEqual([]); + // Not a participant, so the request is not theirs to read: it answers as an id that names none. + await expect(svc.decide(row.id, { decision: 'approve' } as any, as('u_member'))) + .rejects.toThrow(/^REQUEST_NOT_FOUND: /); + await expect(svc.decide(row.id, { decision: 'approve', actorId: SLOT } as any, as('u_member'))) + .rejects.toThrow(/^FORBIDDEN: cannot act as 'platform_admin:\*'/); + expect((await requestRows('member'))[0].status).toBe('pending'); + }); + + it('an organization administrator takes no slot and no override: decide, reassign and recall are refused; another organization\'s cannot decide', async () => { + const row = await open('org_admin', 'host_review', PLATFORM); + const orgAdmin = () => as('u_org_admin', ORG, ['organization_admin']); + expect((await svc.getRequest(row.id, orgAdmin()) as any)?.viewer).toMatchObject({ can_act: false, can_override: false }); + await expect(svc.decide(row.id, { decision: 'approve', actorId: SLOT } as any, orgAdmin())) + .rejects.toThrow(/^FORBIDDEN: cannot act as 'platform_admin:\*'/); + await expect(svc.decide(row.id, { decision: 'approve' } as any, orgAdmin())) + .rejects.toThrow(/^FORBIDDEN: actor 'u_org_admin' is not a pending approver/); + await expect(svc.reassign(row.id, { actorId: 'u_org_admin', to: 'u_alice' }, orgAdmin())) + .rejects.toThrow(/^FORBIDDEN: /); + await expect(svc.recall(row.id, {} as any, orgAdmin())) + .rejects.toThrow(/^FORBIDDEN: /); + await expect(svc.decide(row.id, { decision: 'approve' } as any, as('u_other_admin', OTHER_ORG, ['organization_admin']))) + .rejects.toThrow(/^REQUEST_NOT_FOUND: /); + expect(await requestRows('org_admin')).toMatchObject([{ status: 'pending', pending_approvers: SLOT }]); + expect(await actionsOf(row.id)).not.toContainEqual(expect.objectContaining({ actor_id: 'u_org_admin' })); + }); + + it('an override finalizes the whole request, so a mixed slate is withheld from the organization administrator whole; its ordinary slot holder decides as before', async () => { + const orgAdmin = () => as('u_org_admin', ORG, ['organization_admin']); + const mixed = await open('mixed', 'host_review', [...PLATFORM, { type: 'user', value: 'u_alice' }]); + expect(mixed.pending_approvers).toEqual([SLOT, 'u_alice']); + expect((await svc.getRequest(mixed.id, orgAdmin()) as any)?.viewer).toMatchObject({ can_act: false, can_override: false }); + await expect(svc.decide(mixed.id, { decision: 'approve' } as any, orgAdmin())) + .rejects.toThrow(/^FORBIDDEN: actor 'u_org_admin' is not a pending approver/); + await svc.decide(mixed.id, { decision: 'approve' } as any, as('u_alice')); + expect((await actionsOf(mixed.id)).find((a) => a.action === 'approve')) + .toMatchObject({ actor_id: 'u_alice', acted_as: 'u_alice' }); + expect(Boolean((await actionsOf(mixed.id)).find((a) => a.action === 'approve')?.via_override)).toBe(false); + // CONTROL: on a slate without the platform slot the tenant arm is unchanged. + const ordinary = await open('ordinary', 'tenant_review', [{ type: 'user', value: 'u_alice' }]); + expect((await svc.getRequest(ordinary.id, orgAdmin()) as any)?.viewer).toMatchObject({ can_act: false, can_override: true }); + }); + + it('CONTROL: the platform administrator\'s override arm is unchanged on the platform slot', async () => { + const row = await open('platform_override', 'host_review', PLATFORM); + const root = () => as('u_root', ORG, ['admin_full_access']); + expect((await svc.getRequest(row.id, root()) as any)?.viewer).toMatchObject({ can_act: true, can_override: true }); + // Recall holds no slot: the override arm alone admits a caller who is not + // the submitter. + await svc.recall(row.id, {} as any, root()); + expect((await requestRows('platform_override'))[0].status).not.toBe('pending'); + }); + + it('a revoked administrator cannot decide a request opened before the revocation', async () => { + const row = await open('revoked', 'host_review', PLATFORM); + expect((await svc.getRequest(row.id, as('u_revoked')) as any)?.viewer?.can_act).toBe(true); + await engine.delete('sys_user_permission_set', { where: { id: 'ups_revoked' }, context: SYSTEM } as any); + expect(await inbox(as('u_revoked'))).toEqual([]); + await expect(svc.decide(row.id, { decision: 'approve' } as any, as('u_revoked'))) + .rejects.toThrow(/^REQUEST_NOT_FOUND: /); + await expect(svc.decide(row.id, { decision: 'approve', actorId: SLOT } as any, as('u_revoked'))) + .rejects.toThrow(/^FORBIDDEN: cannot act as 'platform_admin:\*'/); + expect((await requestRows('revoked'))[0].status).toBe('pending'); + }); + + describe('only the running body of a code package\'s flow may name it; the node refuses, writing nothing', () => { + const refused = async (key: string, flowName: string, approvers: any[] = PLATFORM, extra = {}) => { + await expect(open(key, flowName, approvers, extra)).rejects.toThrow( + /^FORBIDDEN: approval node 'review' of flow '[a-z_]+' names the platform administrators/, + ); + expect(await requestRows(key)).toEqual([]); + }; + + it('a flow authored in the environment is refused', async () => { + await refused('tenant', 'tenant_review'); + }); + + it('an environment override of a host flow is refused, though the host ships its name', async () => { + await refused('override', 'host_review_overridden'); + }); + + it('a marketplace package\'s flow is refused', async () => { + await refused('marketplace', 'marketplace_review'); + }); + + it('an authored package\'s flow, an unrecorded package\'s and a marketplace residual\'s are refused', async () => { + await refused('authored', 'authored_review'); + await refused('unrecorded', 'unrecorded_review'); + await refused('installed_residual', 'installed_residual_review'); + }); + + it('a fallback slate naming it is refused the same way', async () => { + await refused('fallback', 'tenant_review', [{ type: 'position', value: 'nobody_holds_this' }], { + onEmptyApprovers: 'fallback', fallbackApprovers: PLATFORM, + }); + }); + + it('a residual owner a code door recorded is admitted', async () => { + const row = await open('residual', 'residual_review', PLATFORM); + expect(row.pending_approvers).toEqual([SLOT]); + }); + }); + + describe('the slot is opened only by the approver type that names it: every other way a slate is resolved opens no slot', () => { + it('case 1: the resolved slate holds no slot the typed approver did not open', async () => { + const row = await open('case_1', 'tenant_review', [{ type: 'user', value: SLOT }, { type: 'user', value: 'u_alice' }]); + expect(row.pending_approvers).toEqual(['u_alice']); + }); + + it('case 2: the resolved slate holds no slot the typed approver did not open', async () => { + const row = await open('case_2', 'tenant_review', [{ type: 'field', value: 'reviewer' }], {}, + { fields: { reviewer: `${SLOT},u_alice` } }); + expect(row.pending_approvers).toEqual(['u_alice']); + }); + + it('case 3: the resolved slate holds no slot the typed approver did not open', async () => { + const row = await open('case_3', 'tenant_review', + [{ type: 'expression', value: 'trigger.reviewer', resolveAs: 'user' }, { type: 'user', value: 'u_alice' }], {}, + { fields: { reviewer: SLOT } }); + expect(row.pending_approvers).toEqual(['u_alice']); + }); + + it('case 4: the resolved slate holds no slot the typed approver did not open', async () => { + await engine.insert('sys_user_position', { + id: 'pos_case_4', user_id: SLOT, position: 'deal_desk', organization_id: ORG, + }, { context: SYSTEM } as any); + try { + const row = await open('case_4', 'tenant_review', + [{ type: 'position', value: 'deal_desk' }, { type: 'user', value: 'u_alice' }]); + expect(row.pending_approvers).toEqual(['u_alice']); + } finally { + await engine.delete('sys_user_position', { where: { id: 'pos_case_4' }, context: SYSTEM } as any); + } + }); + + it('case 5: a later slate holds no slot the typed approver did not open', async () => { + await engine.insert('sys_user_position', { + id: 'pos_case_5', user_id: SLOT, position: 'escalation_desk', organization_id: ORG, + }, { context: SYSTEM } as any); + try { + await open('case_5', 'tenant_review', [{ type: 'user', value: 'u_alice' }], + { escalation: { timeoutHours: 1, action: 'reassign', escalateTo: 'escalation_desk', notifySubmitter: false } }); + now += 2 * 3600_000; + await svc.runEscalations(); + expect((await requestRows('case_5'))[0].pending_approvers).not.toContain(SLOT); + } finally { + await engine.delete('sys_user_position', { where: { id: 'pos_case_5' }, context: SYSTEM } as any); + } + }); + + it('case 6: the resolved slate keeps its people and holds no slot the typed approver did not open', async () => { + await engine.insert('sys_approval_delegation', { + id: 'dlg_case_6', delegator_id: 'u_alice', delegate_id: SLOT, organization_id: ORG, + }, { context: SYSTEM } as any); + try { + const row = await open('case_6', 'tenant_review', [{ type: 'user', value: 'u_alice' }]); + expect(row.pending_approvers).toEqual(['u_alice']); + } finally { + await engine.delete('sys_approval_delegation', { where: { id: 'dlg_case_6' }, context: SYSTEM } as any); + } + }); + }); + + describe('the slot is judged on the slate the decision, override and inbox doors read: no route opens it but the typed approver', () => { + const person = { type: 'user', value: 'u_member' }; + const joined = `u_alice,${SLOT}`; + const orgAdmin = () => as('u_org_admin', ORG, ['organization_admin']); + /** + * The doors, each as it reads the stored slate: the request as the + * service serves it, the approver index as plugin start rebuilds it from + * the stored slate (the inbox), the decision admission for a caller in + * platform standing naming the slot, and the override admission (a slate + * holding the slot would withhold the tenant arm). + */ + const expectNoDoorReadsTheSlot = async (id: string) => { + expect((await svc.getRequest(id, SYSTEM))?.pending_approvers).not.toContain(SLOT); + await svc.rebuildApproverIndex(); + expect(await inbox(as('u_root'))).not.toContain(id); + await expect(svc.decide(id, { decision: 'approve', actorId: SLOT } as any, as('u_root'))) + .rejects.toThrow(/^(REQUEST_NOT_FOUND|FORBIDDEN): /); + expect((await svc.getRequest(id, orgAdmin()) as any)?.viewer?.can_override).toBe(true); + }; + const withRows = async (object: string, rows: Array>, body: () => Promise) => { + for (const row of rows) await engine.insert(object, row, { context: SYSTEM } as any); + try { + await body(); + } finally { + for (const row of rows) await engine.delete(object, { where: { id: row.id }, context: SYSTEM } as any); + } + }; + const opensOn = async (key: string, approvers: any[], expected: string[], extra = {}, fields = {}) => { + const row = await open(key, 'tenant_review', approvers, extra, { fields }); + expect(row.pending_approvers).toEqual(expected); + await expectNoDoorReadsTheSlot(row.id); + return row; + }; + + it('case 7: an approver entry opens no slot the doors read', async () => { + await opensOn('case_7', [person, { type: 'user', value: joined }], ['u_member']); + }); + + it('case 8: an approver entry opens no slot the doors read', async () => { + await opensOn('case_8', [person, { type: 'user', value: `u_alice, ${SLOT}` }], ['u_member']); + }); + + it('case 9: an approver entry opens no slot the doors read', async () => { + await opensOn('case_9', [person, { type: 'team', value: `no_team,${SLOT}` }], ['u_member']); + }); + + it('case 10: an approver entry opens no slot the doors read', async () => { + await opensOn('case_10', [person, { type: 'position', value: `nobody,${SLOT}` }], ['u_member']); + }); + + it('case 11: an approver entry opens no slot the doors read', async () => { + await opensOn('case_11', [person, { type: 'org_membership_level', value: `nobody,${SLOT}` }], ['u_member']); + }); + + it('case 12: an approver entry opens no slot the doors read', async () => { + await opensOn('case_12', [person, { type: 'department', value: `no_unit,${SLOT}` }], ['u_member']); + }); + + it('case 13: a record value opens no slot the doors read', async () => { + await opensOn('case_13', [person, { type: 'field', value: 'reviewers' }], ['u_member'], {}, { reviewers: [joined] }); + }); + + it('case 14: a directory value opens no slot the doors read', async () => { + await withRows('sys_user', [{ id: 'u_case_14', name: 'u_case_14', manager_id: joined }], async () => { + await opensOn('case_14', [person, { type: 'manager', value: 'subject' }], ['u_member'], {}, { subject: 'u_case_14' }); + }); + }); + + it('case 15: a directory value opens no slot the doors read', async () => { + await withRows('sys_user_position', [{ id: 'pos_case_15', user_id: joined, position: 'desk_15', organization_id: ORG }], async () => { + await opensOn('case_15', [person, { type: 'position', value: 'desk_15' }], ['u_member']); + await opensOn('case_15b', [person, { type: 'expression', value: "'desk_15'", resolveAs: 'position' }], ['u_member']); + }); + }); + + it('case 16: a delegation opens no slot the doors read, and the slot stays with its approver', async () => { + await withRows('sys_approval_delegation', [{ + id: 'dlg_case_16', delegator_id: 'u_alice', delegate_id: `u_member,${SLOT}`, organization_id: ORG, + }], async () => { + await opensOn('case_16', [person, { type: 'user', value: 'u_alice' }], ['u_member', 'u_alice']); + }); + }); + + it('case 17: a fallback slate opens no slot the doors read', async () => { + await opensOn('case_17', [{ type: 'position', value: 'nobody_holds_this' }], ['u_member'], { + onEmptyApprovers: 'fallback', fallbackApprovers: [person, { type: 'team', value: `no_team,${SLOT}` }], + }); + }); + + it('case 18: the administrators\' slate opens no slot the doors read', async () => { + await withRows('sys_member', [{ id: 'm_case_18', user_id: joined, organization_id: ORG, role: 'admin' }], async () => { + await withRows('sys_user_permission_set', [{ + id: 'ups_case_18', user_id: joined, permission_set: 'organization_admin', organization_id: ORG, + }], async () => { + await opensOn('case_18', [{ type: 'position', value: 'nobody_holds_this' }], ['u_org_admin']); + }); + }); + }); + + it('case 19: a slate rewritten by a vote holds no slot the doors read', async () => { + const row = await opensOn('case_19', + [person, { type: 'user', value: 'u_alice' }, { type: 'team', value: `no_team,${SLOT}` }], + ['u_member', 'u_alice'], { behavior: 'unanimous' }); + const out = await svc.decide(row.id, { decision: 'approve' } as any, as('u_member')); + expect(out.request.pending_approvers).toEqual(['u_alice']); + await expectNoDoorReadsTheSlot(row.id); + }); + + it('case 20: a slate the SLA hands over holds no slot the doors read', async () => { + await withRows('sys_user_position', [ + { id: 'pos_case_20', user_id: joined, position: 'desk_20', organization_id: ORG }, + { id: 'pos_case_20b', user_id: 'u_member', position: `desk_20b,${SLOT}`, organization_id: ORG }, + ], async () => { + for (const [key, escalateTo] of [['case_20', 'desk_20'], ['case_20b', `position:desk_20b,${SLOT}`]]) { + const row = await open(key, 'tenant_review', [{ type: 'user', value: 'u_alice' }], + { escalation: { timeoutHours: 1, action: 'reassign', escalateTo, notifySubmitter: false } }); + now += 2 * 3600_000; + await svc.runEscalations(); + expect((await svc.getRequest(row.id, SYSTEM))?.pending_approvers).toEqual(['u_alice']); + await expectNoDoorReadsTheSlot(row.id); + } + }); + }); + + it('case 21: a hand-off target puts no slot on the slate the doors read', async () => { + await withRows('sys_user_position', [{ id: 'pos_case_21', user_id: 'u_member', position: `desk_21,${SLOT}`, organization_id: ORG }], async () => { + const row = await open('case_21', 'tenant_review', [{ type: 'user', value: 'u_alice' }]); + await expect(svc.reassign(row.id, { actorId: 'u_alice', to: `position:desk_21,${SLOT}` }, as('u_alice'))) + .rejects.toThrow(/^VALIDATION_FAILED: cannot reassign to /); + expect((await svc.getRequest(row.id, SYSTEM))?.pending_approvers).toEqual(['u_alice']); + await expectNoDoorReadsTheSlot(row.id); + }); + }); + + it('case 22: a queue\'s members open no slot the doors read', async () => { + QUEUES.queue_22 = ['u_member', SLOT, joined]; + await opensOn('case_22', [{ type: 'queue', value: 'queue_22' }], ['u_member']); + }); + + it('case 23: an expression yielding a list of people opens no slot the doors read', async () => { + await opensOn('case_23', [{ type: 'expression', value: 'trigger.reviewers', resolveAs: 'user' }], ['u_member'], {}, + { reviewers: ['u_member', SLOT, joined] }); + }); + + it('the slot test is total: an entry that is not text is judged as the text the stored slate holds for it', () => { + const entries: unknown[] = [ + 42, true, null, undefined, { toString: () => SLOT }, [SLOT], ['u_alice', SLOT], [['u_alice', SLOT]], + [`u_alice, ${SLOT}`], ['u_alice', 'u_member'], + ]; + const asStored = entries.map((entry) => readStoredSlate([entry].join(',')).includes(SLOT)); + expect(entries.map((entry) => readsAsPlatformAdminAddress(entry))).toEqual(asStored); + expect(asStored.filter(Boolean)).toHaveLength(5); + }); + }); + + describe('the doors honour the slot only on a request that records a platform_admin step opened it', () => { + const orgAdmin = () => as('u_org_admin', ORG, ['organization_admin']); + const snapshotOf = async (key: string): Promise> => + JSON.parse(String((await requestRows(key))[0].node_config_json)); + /** The request as a row that holds no such record: its stored slate and the rest of its snapshot as they are. */ + const withoutTheRecord = async (key: string): Promise => { + const [row] = await requestRows(key); + const snapshot = await snapshotOf(key); + delete snapshot[SLOT_RECORD_KEY]; + await engine.update('sys_approval_request', { id: row.id, node_config_json: JSON.stringify(snapshot) }, + { context: SYSTEM } as any); + }; + const doorsRead = async (id: string) => { + await svc.rebuildApproverIndex(); + return { + served: (await svc.getRequest(id, SYSTEM))?.pending_approvers, + listed: (await inbox(as('u_root'))).includes(id), + orgAdminOverrides: (await svc.getRequest(id, orgAdmin()) as any)?.viewer?.can_override, + }; + }; + + it('CONTROL: a request a platform_admin step opened records it, and every door reads the slot', async () => { + const row = await open('recorded', 'host_review', [...PLATFORM, { type: 'user', value: 'u_alice' }]); + expect((await snapshotOf('recorded'))[SLOT_RECORD_KEY]).toBe(true); + expect(await doorsRead(row.id)).toEqual({ served: [SLOT, 'u_alice'], listed: true, orgAdminOverrides: false }); + const out = await svc.decide(row.id, { decision: 'approve', actorId: SLOT } as any, as('u_root')); + expect(out.request.status).toBe('approved'); + expect((await actionsOf(row.id)).find((a) => a.action === 'approve')).toMatchObject({ actor_id: 'u_root', acted_as: SLOT }); + }); + + it('a request without the record: no door reads the slot its stored slate holds, and its people decide as before', async () => { + const row = await open('no_record', 'host_review', [...PLATFORM, { type: 'user', value: 'u_alice' }]); + await withoutTheRecord('no_record'); + expect((await requestRows('no_record'))[0].pending_approvers).toBe(`${SLOT},u_alice`); + expect(await doorsRead(row.id)).toEqual({ served: ['u_alice'], listed: false, orgAdminOverrides: true }); + await expect(svc.decide(row.id, { decision: 'approve', actorId: SLOT } as any, as('u_root'))) + .rejects.toThrow(/^(REQUEST_NOT_FOUND|FORBIDDEN): /); + await expect(svc.decide(row.id, { decision: 'approve' } as any, as('u_root'))) + .rejects.toThrow(/^(REQUEST_NOT_FOUND|FORBIDDEN): /); + const out = await svc.decide(row.id, { decision: 'approve' } as any, as('u_alice')); + expect(out.request.status).toBe('approved'); + }); + + it('a request without the record: a vote that rewrites its slate indexes no slot for the inbox', async () => { + const row = await open('no_record_vote', 'host_review', [...PLATFORM, { type: 'user', value: 'u_alice' }], + { behavior: 'unanimous' }); + await withoutTheRecord('no_record_vote'); + await svc.rebuildApproverIndex(); + await svc.decide(row.id, { decision: 'approve' } as any, as('u_alice')); + expect((await requestRows('no_record_vote'))[0]).toMatchObject({ status: 'pending', pending_approvers: SLOT }); + expect(await inbox(as('u_root'))).not.toContain(row.id); + expect(await doorsRead(row.id)).toEqual({ served: [], listed: false, orgAdminOverrides: true }); + }); + + it('only the open path writes the record: a step\'s config cannot carry it', async () => { + const declared = ApprovalNodeConfigSchema.safeParse({ approvers: PLATFORM, [SLOT_RECORD_KEY]: true }); + expect(declared.success).toBe(false); + expect(declared.error?.issues.map((issue) => issue.code)).toContain('unrecognized_keys'); + await open('handed', 'tenant_review', [{ type: 'user', value: 'u_alice' }], { [SLOT_RECORD_KEY]: true }); + expect(await snapshotOf('handed')).not.toHaveProperty(SLOT_RECORD_KEY); + }); + }); + + describe('the origin is answered for the body whose step is being opened, on the real flow engine', () => { + const HOST_FLOW = 'host_review_real'; + const flowDef = { + name: HOST_FLOW, label: 'Host review', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'review', type: 'approval', label: 'Review', config: { approvers: [{ type: 'platform_admin' }] } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'review' }, + { id: 'e2', source: 'review', target: 'end', label: 'approve' }, + { id: 'e3', source: 'review', target: 'end', label: 'reject' }, + ], + }; + const quiet = { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} } as any; + let automation: AutomationEngine; + let armedNode: any; + + beforeAll(async () => { + automation = new AutomationEngine(quiet); + registerApprovalNode(automation as any, svc, quiet); + automation.setPackagedFlowSource((name) => (name === HOST_FLOW ? 'com.host.review' : undefined)); + automation.registerFlow(HOST_FLOW, flowDef, { source: 'package', packageId: 'com.host.review' }); + svc.attachAutomation(automation as any); + armedNode = (await automation.getFlow(HOST_FLOW))?.nodes.find((n: any) => n.id === 'review'); + }); + + afterAll(() => { + svc.attachAutomation(STAND_IN_AUTOMATION); + vi.restoreAllMocks(); + }); + + const deal = async (key: string) => { + await engine.insert('crm_deal', { id: `D_${key}`, title: key, organization_id: ORG }, { context: SYSTEM } as any); + return { id: `D_${key}`, title: key }; + }; + const openDirect = async (key: string, node: unknown, flowKey?: string) => svc.openNodeRequest({ + object: 'crm_deal', recordId: `D_${key}`, runId: `run_${key}`, nodeId: 'review', flowName: HOST_FLOW, flowKey, + config: { approvers: [{ type: 'platform_admin' }], behavior: 'first_response' } as any, + submitterId: 'u_sub', record: await deal(key), organizationId: ORG, node, + }, as('u_sub')); + + it('a real run of a code package\'s flow opens on the slot, the origin read for the body it runs', async () => { + expect(automation.armedFlowPackage(HOST_FLOW)).toBe('com.host.review'); + const slotRead = vi.spyOn(automation, 'getFlowSlot'); + const record = await deal('real_run'); + const result = await automation.execute(HOST_FLOW, { + object: 'crm_deal', record, userId: 'u_sub', organizationId: ORG, tenantId: ORG, + } as any); + expect(result).toMatchObject({ status: 'paused' }); + expect(slotRead).toHaveBeenCalledWith('com.host.review', HOST_FLOW); + expect(await requestRows('real_run')).toMatchObject([{ status: 'pending', pending_approvers: SLOT }]); + slotRead.mockRestore(); + }); + + it('the slot read: the armed body\'s own step opens, and a step it does not hold is refused', async () => { + const slotRead = vi.spyOn(automation, 'getFlowSlot'); + const opened = await openDirect('real_slot', armedNode, HOST_FLOW); + expect(opened).toMatchObject({ status: 'pending', pending_approvers: [SLOT] }); + expect(slotRead).toHaveBeenCalledWith('com.host.review', HOST_FLOW); + await expect(openDirect('real_slot_copy', { ...armedNode }, HOST_FLOW)) + .rejects.toThrow(/^FORBIDDEN: approval node 'review' of flow 'host_review_real' names the platform administrators/); + expect(await requestRows('real_slot_copy')).toEqual([]); + slotRead.mockRestore(); + }); + + it('the bare read: the armed body\'s own step opens, and a step it does not hold is refused', async () => { + const slotRead = vi.spyOn(automation, 'getFlowSlot'); + const bareRead = vi.spyOn(automation, 'getFlow'); + const opened = await openDirect('real_bare', armedNode); + expect(opened).toMatchObject({ status: 'pending', pending_approvers: [SLOT] }); + expect(bareRead).toHaveBeenCalledWith(HOST_FLOW); + expect(slotRead).not.toHaveBeenCalled(); + await expect(openDirect('real_bare_copy', { ...armedNode })) + .rejects.toThrow(/^FORBIDDEN: approval node 'review' of flow 'host_review_real' names the platform administrators/); + expect(await requestRows('real_bare_copy')).toEqual([]); + slotRead.mockRestore(); + bareRead.mockRestore(); + }); + }); + + describe('the platform\'s place on a mixed slate moves only for the platform or the system', () => { + const mixed = (key: string) => open(key, 'host_review', [...PLATFORM, { type: 'user', value: 'u_alice' }]); + + it('a caller without platform standing cannot move it', async () => { + const row = await mixed('move_1'); + await expect(svc.reassign(row.id, { actorId: 'u_alice', from: SLOT, to: 'u_member' }, as('u_alice'))) + .rejects.toThrow(/^FORBIDDEN: actor 'u_alice' may not move the platform administrators' slot/); + expect((await requestRows('move_1'))[0].pending_approvers).toBe(`${SLOT},u_alice`); + }); + + it('a platform administrator can', async () => { + const row = await mixed('move_2'); + await svc.reassign(row.id, { actorId: SLOT, from: SLOT, to: 'u_member' }, as('u_root')); + expect((await requestRows('move_2'))[0].pending_approvers).toBe('u_member,u_alice'); + }); + + it('the system can', async () => { + const row = await mixed('move_3'); + await svc.reassign(row.id, { actorId: 'system', from: SLOT, to: 'u_member' }, SYSTEM); + expect((await requestRows('move_3'))[0].pending_approvers).toBe('u_member,u_alice'); + }); + }); + + describe('the origin is answered for the body whose step is being opened', () => { + it('a step the answered origin does not describe is refused', async () => { + await expect(open('origin_1', 'host_review', PLATFORM, {}, { node: { ...ARMED_NODE } })) + .rejects.toThrow(/^FORBIDDEN: approval node 'review' of flow 'host_review' names the platform administrators/); + await expect(open('origin_2', 'host_review', PLATFORM, {}, { node: undefined })) + .rejects.toThrow(/^FORBIDDEN: /); + expect(await requestRows('origin_1')).toEqual([]); + }); + + it('the approval executor hands the step it runs, and the origin is answered for that step', async () => { + const executors: any[] = []; + registerApprovalNode({ registerNodeExecutor: (e: any) => { executors.push(e); } } as any, svc); + const executor = executors.find((e) => e.type === 'approval'); + const run = async (key: string, node: unknown) => { + await engine.insert('crm_deal', { id: `D_${key}`, title: key, organization_id: ORG }, { context: SYSTEM } as any); + const variables = new Map([ + ['$runId', `run_${key}`], ['$record', { id: `D_${key}`, title: key }], ['$flowName', 'host_review'], + ]); + return executor.execute(node, variables, { object: 'crm_deal', userId: 'u_sub', organizationId: ORG, tenantId: ORG }); + }; + expect(await run('origin_3', ARMED_NODE)).toMatchObject({ success: true, suspend: true }); + const other = await run('origin_4', { ...ARMED_NODE }); + expect(other.success).toBe(false); + expect(other.error).toMatch(/FORBIDDEN: approval node 'review'/); + expect(await requestRows('origin_4')).toEqual([]); + }); + }); + + it('the save door refuses it as early feedback; os lint knows the type and refuses nothing', () => { + const flow = { + name: 'tenant_review', label: 'Tenant review', type: 'autolaunched', + nodes: [ + { id: 'start', type: 'start', label: 'Start' }, + { id: 'review', type: 'approval', label: 'Review', config: { approvers: PLATFORM } }, + { id: 'end', type: 'end', label: 'End' }, + ], + edges: [ + { id: 'e1', source: 'start', target: 'review' }, + { id: 'e2', source: 'review', target: 'end', label: 'approve' }, + ], + }; + const judged = runRuntimeAuthoringRules({ type: 'flow', item: flow }); + const door = judged.errors.filter((f) => f.rule === APPROVAL_APPROVER_PLATFORM_ADMIN_AUTHORED); + expect(door.map((f) => f.path)).toEqual(['flows[0].nodes[1].config.approvers[0].type']); + const normalized = normalizeStackInput({ + manifest: { id: 'com.acme.lint', name: 'lint_probe', version: '1.0.0', type: 'app' }, flows: [flow], + } as any) as any; + const cli = runAuthoringRules('lint', { normalized }); + expect(cli.filter((f) => f.rule === APPROVAL_APPROVER_PLATFORM_ADMIN_AUTHORED)).toEqual([]); + expect(cli.filter((f) => f.rule === 'approval-approver-type-unknown')).toEqual([]); + }); + + it('CONTROL: an existing approver type opens and is decided as before; the platform administrator takes no slot on it', async () => { + const row = await open('control', 'tenant_review', [{ type: 'user', value: 'u_alice' }]); + expect(row.pending_approvers).toEqual(['u_alice']); + // The scene: u_root DOES hold platform standing (the grant pin above), so + // the absence here is the slot's, not a caller with no standing. + expect(await inbox(as('u_root'))).not.toContain(row.id); + expect(await svc.getRequest(row.id, as('u_root'))).toBeNull(); + await expect(svc.decide(row.id, { decision: 'approve' } as any, as('u_root'))) + .rejects.toThrow(/^REQUEST_NOT_FOUND: /); + const out = await svc.decide(row.id, { decision: 'approve' } as any, as('u_alice')); + expect(out.request.status).toBe('approved'); + expect((await actionsOf(row.id)).find((a) => a.action === 'approve')).toMatchObject({ + actor_id: 'u_alice', acted_as: 'u_alice', + }); + }); +}); diff --git a/packages/spec/src/automation/approval.zod.ts b/packages/spec/src/automation/approval.zod.ts index e5919db27cd..3f2ceeb11ec 100644 --- a/packages/spec/src/automation/approval.zod.ts +++ b/packages/spec/src/automation/approval.zod.ts @@ -70,6 +70,18 @@ export const ApproverType = z.enum([ // where it sits. 'role', 'user', // A specific user id — least portable; see the note above + // The deployment's platform administrators: the people + // `hasPlatformAdminStanding` (`@objectstack/core`) answers yes for, asked + // per caller at the inbox and at each decision, never enumerated. Takes no + // `value` and no `organization`. Opens ONE address slot that names no + // person, so it reads no record, tells no one, and a revocation takes effect + // at the next decision, on requests already open too. Accepted only in the + // running body of a flow shipped by a package the deployment registers in + // code (registry `source: 'code'`): the approval node refuses to open + // anywhere else, and the tenant save door refuses it as early feedback. + // Never offered by a designer (NON_AUTHORABLE_APPROVER_TYPES), since every + // flow saved through one is authored in the deployment and refused. + 'platform_admin', ]) // The generated reference page renders THIS string under `## ApproverType`; // the JSDoc above the enum renders nowhere (`renderSchemaSection` prints @@ -112,7 +124,9 @@ export const ApproverType = z.enum([ "user directory; until then it finds nobody and the request follows the node's `onEmptyApprovers` " + 'policy. `os lint` reports that at authoring time as `approval-approvers-may-resolve-empty`, and ' + '`os explain approval-approvers-may-resolve-empty` carries the ways to fill the directory in and ' + - 'the full remedy; the Approvals guide states the same remedy in prose.', + 'the full remedy; the Approvals guide states the same remedy in prose. ' + + "The platform administrators type is for a deployment's own packaged flows only: a flow saved here " + + 'cannot use it, and an approval step that names it anywhere else does not open.', ); export type ApproverType = z.input; @@ -134,8 +148,16 @@ export function canonicalApproverType(type: string): string { * Approver types that still PARSE but must not be offered for new authoring. * Published to designers as `xEnumDeprecated` on the approver `type` (see * {@link ApprovalNodeApproverSchema}): a stored value keeps rendering, the - * dropdown just stops handing authors the entry. One source: the deprecated - * spellings in {@link DEPRECATED_APPROVER_TYPES} (ADR-0090 D3). + * dropdown just stops handing authors the entry. Two sources: the deprecated + * spellings in {@link DEPRECATED_APPROVER_TYPES} (ADR-0090 D3), and + * `platform_admin`, which is NOT deprecated: it is accepted only in a code + * package's flow body, which no designer saves. + * + * The published label is `xEnumDeprecated` because that is the one key every + * designer reads to keep an entry out of its picker. For `platform_admin` it + * means "not offered for authoring", never "deprecated": no replacement exists + * and no removal is planned. A `value` on a `platform_admin` approver is + * ignored, not refused. * * `queue` was the second source while the runtime had no queue branch * (offering it would have advertised a capability the engine did not deliver, @@ -144,6 +166,10 @@ export function canonicalApproverType(type: string): string { */ export const NON_AUTHORABLE_APPROVER_TYPES: readonly string[] = [ ...Object.keys(DEPRECATED_APPROVER_TYPES), + // Not deprecated: accepted only in the running body of a flow a `code` + // package ships (see the enum). Every flow a designer saves is authored in + // the deployment and is refused for naming it, so no picker offers it. + 'platform_admin', ]; /** @@ -202,9 +228,11 @@ export type ApproverValueBinding = /** Closed value set — render a strict select, never free text. */ | { source: 'enum'; values: readonly string[] } /** - * Resolved by the engine at runtime (submitter's manager via - * `sys_user.manager_id`); `value` is optional (an advanced override naming - * the record field that holds the subject user) and normally stays empty. + * Resolved by the engine at runtime, with nothing to pick. `manager`: the + * submitter's manager via `sys_user.manager_id`; `value` is optional (an + * advanced override naming the record field that holds the subject user) + * and normally stays empty. `platform_admin`: the platform administrators, + * asked per caller; it takes no `value` at all. */ | { source: 'auto' } /** `value` names a field on the flow's trigger object. */ @@ -260,6 +288,8 @@ export const APPROVER_VALUE_BINDINGS = { // `registry-and-record` member of ApproverValueBinding. queue: { source: 'registry-and-record', type: 'queue', object: 'sys_queue', valueField: 'name' }, expression: { source: 'expression', roots: APPROVER_EXPRESSION_ROOTS }, + // Nothing to pick: the engine asks each caller's standing. + platform_admin: { source: 'auto' }, } as const satisfies Record, ApproverValueBinding>; /** @@ -385,6 +415,8 @@ export const APPROVER_ORG_SCOPED = { // expand, in the request's organization or the one `organization` targets. queue: true, expression: true, + // No directory and no organization: platform standing is deployment-wide. + platform_admin: false, } as const satisfies Record, boolean>; /** Does `organization` (ADR-0105 D9) apply to this approver type? */ @@ -515,6 +547,8 @@ export const ApprovalNodeApproverSchema = lazySchema(() => strictObject( // approver-type dropdown straight from this enum and keeps offering `role` // — the exact trap ADR-0090 D3 is retiring — one click away from `position`. // (`queue` was listed too until the runtime resolved it, ADR-0142 D6.) + // `platform_admin` is listed without being deprecated: it is not offered + // for authoring (see NON_AUTHORABLE_APPROVER_TYPES). // Renderers omit these from pickers while still rendering a stored value. type: ApproverType.meta({ xEnumDeprecated: [...NON_AUTHORABLE_APPROVER_TYPES], @@ -524,7 +558,8 @@ export const ApprovalNodeApproverSchema = lazySchema(() => strictObject( * membership tier — owner/admin/member (`org_membership_level`), a position * machine name (`position`), team/department id (`team`/`department`), field * name holding a user id (`field`), or queue machine name (`queue`). Omitted for - * `manager` (resolved from the submitter's `manager_id`). + * `manager` (resolved from the submitter's `manager_id`) and for + * `platform_admin`, which takes none. */ // `xRef` marks this string as a *polymorphic* typed reference (ADR-0018 // §configSchema): the concrete picker follows the sibling `type` column.