Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions .changeset/33661-automation-dry-run.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
'@objectstack/spec': patch
'@objectstack/core': patch
'@objectstack/runtime': patch
'@objectstack/plugin-security': patch
'@objectstack/service-automation': patch
---

feat(automation): `IAutomationService.dryRun` runs an unpublished flow definition once, unarmed, as a named user

Clause-②: yes (widening) — `AutomationEngine.dryRun` admits a `runAs: 'system'` self-triggered draft for the named user (ruling B); `@objectstack/core` exports the shared flow-start rules (`aiAccountElevatedStartRefusal`, `requiredPermissionsStartRefusal`, `requiredPermissionsRefusal`, `missingCapabilities`, `isAiServiceAccount`, `AI_ACCOUNT_ELEVATED_START_REFUSAL`, `FlowStartPermissionRefusal`); plugin-security's registered `security` service serves `canWriteObject`
Metadata-protocol: none

The automation service now implements `dryRun(definition, { userId, record, … })`, the method the `IAutomationService` contract declares. A dry run admits the definition by the checks `registerFlow` asks, then by the rules that admit a start by name, and then runs it once against the supplied record as the named user. It registers nothing and arms no trigger, and it writes, sends and pauses nothing:

- Record writes (`create_record`, `update_record`, `delete_record`) are simulated. The step shows the values the run would write and a placeholder id for a new record. The named user's object-level write permission is judged as allowed, refused or not judged. A later read by id in the same run sees the simulated row.
- Routing and computing nodes (`assignment`, `decision`, gateways, loops, parallel branches, try/catch) run on the engine's own executors. A decision step shows the branch taken and the expressions it evaluated.
- Outbound nodes (`http`, email and the like) are never executed. The step shows the payload they would send.
- The run stops at a node that pauses (`approval`, `wait`, `screen`, a subflow) and names why. A node type the dry run cannot simulate stops it as `not_simulated`.

Under maintainer ruling B (record 6917953931), a draft declaring `runAs: 'system'` whose type starts on its own trigger is admitted to a dry run for the named user, and the run is never elevated. The contract's admission text says so. A by-name start of a published flow keeps refusing such a flow.

The AI service account rule and the flow's own `requiredPermissions` rule now live in `@objectstack/core`. The by-name start doors and the dry run both ask that one copy. `@objectstack/runtime` re-exports every symbol under the name it had. The registered `security` service now also exposes `canWriteObject`, so a dry run can judge a write without performing it.
153 changes: 153 additions & 0 deletions packages/core/src/security/flow-start-rules.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license.

/**
* The flow start rules two different askers share — ONE spelling, asked by
* both:
*
* - every door that starts a published flow by name
* (`flowStartRefusal`, `@objectstack/runtime`'s `flow-start-admission.ts`,
* whose header is the authority on the rules and their order there);
* - a dry run of an unpublished definition
* (`IAutomationService.dryRun`, `@objectstack/service-automation`), which
* the contract admits by "the rules that admit a start by name".
*
* They live here, below both, because `@objectstack/service-automation` does
* not depend on `@objectstack/runtime`, and a rule each asker spelled for
* itself is a rule that drifts: the account reading, the capability
* arithmetic, the refusals' code and status, and their words are written here
* once. `flow-start-admission.ts` re-exports every one of them under the name
* it always had.
*
* Two rules are here, and only two:
*
* - **The AI service account rule** ({@link aiAccountElevatedStartRefusal};
* ADR-0151 D3 and Non-goals, ruling record 6812617393, letter C): an AI
* service account starts a flow declared `runAs: 'system'` only through
* an action its author opted into AI.
* - **The flow's own `requiredPermissions`**
* ({@link requiredPermissionsStartRefusal}; ruling record 6377848497,
* letter A): a caller must hold every capability the flow names.
*
* The elevated self-triggered rule stays in `flow-start-admission.ts`: only
* the by-name doors ask it. A dry run admits such a draft for the named user,
* never elevated (ruling record 6917953931, letter B), so it is not shared.
*
* The system principal is NOT decided here: each asker reads
* `isSystem` itself, before it asks (a dry run never runs as it).
*/

/** The ADR-0112 `403` a start the rules here do not admit answers. */
export interface FlowStartPermissionRefusal {
code: 'PERMISSION_DENIED';
status: 403;
message: string;
}

/**
* [ADR-0066 D4] The capabilities in `required` the caller does not hold, in
* declaration order — the arithmetic behind every declared
* `requiredPermissions` gate that admits a caller to an execution surface,
* asked by the action gate (`actionPermissionError`, `action-execution.ts`),
* the flow start gate and a dry run's admission. A declaration is a list of
* capability names; the caller holds the capabilities its permission sets
* grant (`ExecutionContext.systemPermissions`). Empty when nothing is declared
* (an ungated surface) or when the caller holds all of them. A value that is
* not an array declares nothing.
*/
export function missingCapabilities(
required: unknown,
executionContext: { systemPermissions?: readonly string[] } | null | undefined,
): string[] {
if (!Array.isArray(required) || required.length === 0) return [];
const held = new Set<string>(executionContext?.systemPermissions ?? []);
return (required as string[]).filter((perm) => !held.has(perm));
}

/**
* The refusal answered when the caller lacks a capability the flow's
* `requiredPermissions` names — the same code and status as the action
* gate's 403 (ADR-0112). ⛔ No new code is minted here.
*
* The message names the declared and the missing capabilities, as the action
* gate's does — the remedy is a grant, and a caller cannot ask for one it
* cannot name — and nothing else about the flow: not its name, its type or its
* run-as declaration.
*/
export function requiredPermissionsRefusal(required: readonly string[], missing: readonly string[]): FlowStartPermissionRefusal {
return {
code: 'PERMISSION_DENIED',
status: 403,
message:
`Starting this flow requires capability [${required.join(', ')}] — `
+ `caller is missing [${missing.join(', ')}]`,
};
}

/**
* The refusal answered when an AI service account starts a flow declared
* `runAs: 'system'` and what starts the flow carries no AI opt-in — the same
* code and status as the refusal beside it (ADR-0112). ⛔ No new code is
* minted here.
*
* The message names the rule and the opt-in the author adds, and nothing else
* about THIS flow: not its name, its type or its definition, and not the
* door, so it reads the same wherever it is answered. It names the action
* route and the MCP tool because those are the doors where the opt-in can
* stand.
*/
export const AI_ACCOUNT_ELEVATED_START_REFUSAL = Object.freeze({
code: 'PERMISSION_DENIED',
status: 403,
message:
'An AI service account starts a flow that runs as the system only through an action its author opted '
+ "into AI. Declare `ai: { exposed: true, description: … }` on an action of type 'flow' that targets the "
+ 'flow, and have the account run that action (the REST actions route or the MCP `run_action` tool).',
} as const);

/**
* Whether `executionContext` is an AI service account's (ADR-0151 D3): the
* agent principal that is its own subject, `principalKind: 'agent'` with no
* `onBehalfOf`. An OAuth-delegated agent names the person it acts for and is
* not one; neither is a person, the guest or the system principal.
*
* ONE reading, asked by the AI service account rule and by the builders that
* forward the account's kind onto the run it starts, so the caller judged as
* an account is the caller whose run carries the kind.
*/
export function isAiServiceAccount(
executionContext: { principalKind?: unknown; onBehalfOf?: unknown } | null | undefined,
): boolean {
return executionContext?.principalKind === 'agent' && !executionContext?.onBehalfOf;
}

/**
* The AI service account rule: {@link AI_ACCOUNT_ELEVATED_START_REFUSAL} when
* `executionContext` is an AI service account, the flow declares
* `runAs: 'system'`, and what starts it carries no `ai.exposed: true` opt-in
* (`aiExposed`); else `null`. A dry run starts with no action in hand, so it
* asks with `aiExposed: false`.
*/
export function aiAccountElevatedStartRefusal(
flow: { runAs?: unknown },
executionContext: { principalKind?: unknown; onBehalfOf?: unknown } | null | undefined,
aiExposed: boolean,
): FlowStartPermissionRefusal | null {
if (flow.runAs === 'system' && isAiServiceAccount(executionContext) && aiExposed !== true) {
return AI_ACCOUNT_ELEVATED_START_REFUSAL;
}
return null;
}

/**
* The flow's own `requiredPermissions` rule: {@link requiredPermissionsRefusal}
* naming what the caller is missing, or `null` when it holds every capability
* the flow names (or the flow names none).
*/
export function requiredPermissionsStartRefusal(
flow: { requiredPermissions?: unknown },
executionContext: { systemPermissions?: readonly string[] } | null | undefined,
): FlowStartPermissionRefusal | null {
const missing = missingCapabilities(flow.requiredPermissions, executionContext);
if (missing.length === 0) return null;
return requiredPermissionsRefusal(flow.requiredPermissions as string[], missing);
}
13 changes: 13 additions & 0 deletions packages/core/src/security/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -717,3 +717,16 @@ export {
type CallerMailSenderSource,
type CallerMailBoundsResult,
} from './caller-mail-bounds.js';

// The flow start rules a by-name start of a published flow
// (`flowStartRefusal`, runtime) and a dry run of an unpublished definition
// (`IAutomationService.dryRun`, service-automation) both ask — one spelling.
export {
missingCapabilities,
requiredPermissionsRefusal,
AI_ACCOUNT_ELEVATED_START_REFUSAL,
isAiServiceAccount,
aiAccountElevatedStartRefusal,
requiredPermissionsStartRefusal,
type FlowStartPermissionRefusal,
} from './flow-start-rules.js';
Original file line number Diff line number Diff line change
Expand Up @@ -90,11 +90,21 @@ const DECLARED_MEMBERS = {
/**
* Members the registered service serves that are deliberately NOT part of the
* contract — plugin-internal, no caller outside this package — each with the
* reason. Empty: every served member is declared. An entry here is a decision
* that a member stays off the contract; a member another package calls is a
* contract, and belongs on `ISecurityService` instead.
* reason. An entry here is a decision that a member stays off the contract; a
* member another package calls is a contract, and belongs on
* `ISecurityService` instead — except where a published contract places it
* off `ISecurityService`, and the entry cites that contract. One such entry:
* `canWriteObject`, which the `IAutomationService.dryRun` contract's
* `FlowDryRunWritePermission` text names a method of this plugin's service
* and not of `ISecurityService`.
*/
const SERVED_NOT_DECLARED: Readonly<Record<string, string>> = {};
const SERVED_NOT_DECLARED: Readonly<Record<string, string>> = {
canWriteObject:
'the object-level write check a flow dry run asks (`@objectstack/service-automation`). The ' +
'`IAutomationService.dryRun` contract (`FlowDryRunWritePermission`, packages/spec/src/contracts/' +
'automation-service.ts) names it a method of this plugin\'s service and NOT of ISecurityService, so a ' +
'kernel without this plugin has none and every write step answers `not_judged`',
};

/**
* OPTIONAL members this plugin must SERVE, each with the reason its absence is
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,7 @@ export interface SecurityServiceHost {
readonly tenancyPosture: SecurityPlugin['tenancyPosture'];
canExport: SecurityPlugin['canExport'];
canReadObject: SecurityPlugin['canReadObject'];
canWriteObject: SecurityPlugin['canWriteObject'];
checkAuthoredRowWrite: SecurityPlugin['checkAuthoredRowWrite'];
checkControlledByParentWrite: SecurityPlugin['checkControlledByParentWrite'];
declareEveryone: SecurityPlugin['declareEveryone'];
Expand All @@ -127,7 +128,7 @@ export interface SecurityServiceHost {

/** The `security` service registration `SecurityPlugin#start` runs; the comment above its call there is its contract. */
export function registerSecurityService(
this: Pick<SecurityServiceHost, 'acceptedDefaultPermissionSets' | 'baselinePermissionSets' | 'bootstrapPermissionSets' | 'canExport' | 'canReadObject' | 'checkAuthoredRowWrite' | 'checkControlledByParentWrite' | 'declareEveryone' | 'delegatedAdminGate' | 'describeEffectiveAccess' | 'describePositionGrants' | 'epoch' | 'explainAccessForCaller' | 'getEffectiveObjectPermissions' | 'getMetadataReadableFields' | 'getObjectSecurityMeta' | 'getQueryableFields' | 'getReadFilter' | 'getReadableFields' | 'getRecordFieldAccess' | 'getWritableFields' | 'logger' | 'ownershipFloorAlternates' | 'permissionEvaluator' | 'platformBaselineSets' | 'ql' | 'resolvePermissionSetsForContext' | 'tenancyPosture'>,
this: Pick<SecurityServiceHost, 'acceptedDefaultPermissionSets' | 'baselinePermissionSets' | 'bootstrapPermissionSets' | 'canExport' | 'canReadObject' | 'canWriteObject' | 'checkAuthoredRowWrite' | 'checkControlledByParentWrite' | 'declareEveryone' | 'delegatedAdminGate' | 'describeEffectiveAccess' | 'describePositionGrants' | 'epoch' | 'explainAccessForCaller' | 'getEffectiveObjectPermissions' | 'getMetadataReadableFields' | 'getObjectSecurityMeta' | 'getQueryableFields' | 'getReadFilter' | 'getReadableFields' | 'getRecordFieldAccess' | 'getWritableFields' | 'logger' | 'ownershipFloorAlternates' | 'permissionEvaluator' | 'platformBaselineSets' | 'ql' | 'resolvePermissionSetsForContext' | 'tenancyPosture'>,
ctx: PluginContext,
ql: IObjectQLEngine,
metadata: IMetadataService,
Expand Down Expand Up @@ -407,6 +408,12 @@ export function registerSecurityService(
const registeredSecurityService = Object.assign(securityService, {
getMetadataReadableFields: (object: string, context?: any) =>
this.getMetadataReadableFields(object, context),
// [#33661] The object-level write check (insert or update) a flow dry
// run asks for each simulated write (`IAutomationService.dryRun`,
// "canWriteObject is a method of plugin-security's service"). The same
// method the engine's write-gate probe calls; ⛔ not a second decision.
canWriteObject: (object: string, operation: 'insert' | 'update', context?: any, data?: unknown) =>
this.canWriteObject(object, operation, context, data),
// [#21729] The ownership-floor alternate seam — how a plugin that
// installs a tighter row gate stops the platform's `created_by` floor
// pre-empting it, registered beside that gate and nowhere else. Same
Expand Down
3 changes: 2 additions & 1 deletion packages/plugins/plugin-security/src/security-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2328,12 +2328,13 @@ export class SecurityPlugin implements Plugin {
const readQl = () => this.ql;
const readTenancyPosture = () => this.tenancyPosture;
const readEpoch = () => this.epoch;
const host: Pick<SecurityServiceHost, 'acceptedDefaultPermissionSets' | 'baselinePermissionSets' | 'bootstrapPermissionSets' | 'canExport' | 'canReadObject' | 'checkAuthoredRowWrite' | 'checkControlledByParentWrite' | 'declareEveryone' | 'delegatedAdminGate' | 'describeEffectiveAccess' | 'describePositionGrants' | 'epoch' | 'explainAccessForCaller' | 'getEffectiveObjectPermissions' | 'getMetadataReadableFields' | 'getObjectSecurityMeta' | 'getQueryableFields' | 'getReadFilter' | 'getReadableFields' | 'getRecordFieldAccess' | 'getWritableFields' | 'logger' | 'ownershipFloorAlternates' | 'permissionEvaluator' | 'platformBaselineSets' | 'ql' | 'resolvePermissionSetsForContext' | 'tenancyPosture'> = {
const host: Pick<SecurityServiceHost, 'acceptedDefaultPermissionSets' | 'baselinePermissionSets' | 'bootstrapPermissionSets' | 'canExport' | 'canReadObject' | 'canWriteObject' | 'checkAuthoredRowWrite' | 'checkControlledByParentWrite' | 'declareEveryone' | 'delegatedAdminGate' | 'describeEffectiveAccess' | 'describePositionGrants' | 'epoch' | 'explainAccessForCaller' | 'getEffectiveObjectPermissions' | 'getMetadataReadableFields' | 'getObjectSecurityMeta' | 'getQueryableFields' | 'getReadFilter' | 'getReadableFields' | 'getRecordFieldAccess' | 'getWritableFields' | 'logger' | 'ownershipFloorAlternates' | 'permissionEvaluator' | 'platformBaselineSets' | 'ql' | 'resolvePermissionSetsForContext' | 'tenancyPosture'> = {
acceptedDefaultPermissionSets: this.acceptedDefaultPermissionSets,
baselinePermissionSets: this.baselinePermissionSets,
bootstrapPermissionSets: this.bootstrapPermissionSets,
canExport: (...a) => this.canExport(...a),
canReadObject: (...a) => this.canReadObject(...a),
canWriteObject: (...a) => this.canWriteObject(...a),
checkAuthoredRowWrite: (...a) => this.checkAuthoredRowWrite(...a),
checkControlledByParentWrite: (...a) => this.checkControlledByParentWrite(...a),
declareEveryone: (...a) => this.declareEveryone(...a),
Expand Down
Loading
Loading