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
16 changes: 16 additions & 0 deletions .changeset/flow-start-carries-action-confirmation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
---
'@objectstack/runtime': patch
---

fix(runtime)!: the confirmation an action declares travels with the flow it starts — an AI service account does not start by name a flow that a confirmation-gated action targets

Clause-②: no (narrowing)
Metadata-protocol: none

<!-- adr-0087: not-required (no-migration-prescription) No key of any schema is added, removed, renamed or re-shaped, and no export changes shape. The moved answer is a refusal at two routes for one caller kind: no stored row changes, so there is nothing for a migration to rewrite and no tombstone. -->

**BREAKING** for an AI service account (an agent principal acting for itself, with no person it acts for) that starts a flow by name. An AI service account does not confirm an action for itself, and the action door already refuses it an action declaring `ai.requiresConfirmation: true` whatever the call sends. The same confirmation now travels with the flow such an action starts: when an action of `type: 'flow'` whose `target` is the flow declares `ai.requiresConfirmation: true`, `POST /api/v1/automation/:name/trigger` and the legacy `POST /api/v1/automation/trigger/:name` refuse the account with the action door's own refusal, `428 ACTION_CONFIRMATION_REQUIRED`, its `details` naming the action and the confirmation member, before any run exists and whatever the request carries (`confirm: true` included). Every declaration of such an action counts, whichever package holds it and whether it is embedded on an object or a standalone item. The declarations are read from the instance the request's own `/actions` door reads, in every host shape. A read of the declarations that throws on any of its sources, or a service it reads them from (the metadata protocol, the ObjectQL engine or the metadata service) that no step of that door's resolution order answers because one failed to resolve it, refuses the start `503 SERVICE_UNAVAILABLE` rather than admitting it; where a later step answers the name, the start is judged on that instance, as the `/actions` door would serve it; only a service nothing registered reads as absent. A source that answers a failed read of its own without throwing (the metadata service's plural listing, which reports a failed loader and answers the others' rows) is judged on the rows it answers. The rule reads the flow's name and the declarations, not the flow's definition. It is asked at the two trigger routes; the declared `type: 'flow'` endpoint door is not judged by it yet.

**Not moved.** A person, an OAuth-delegated agent and the system principal start the flow as before, and the action declarations are not read for them. An AI service account starts a flow no confirmation-gated action targets as before. The action door's own gate (`POST /api/v1/actions/...` and MCP `run_action`) answers as before. A declared `type: 'flow'` endpoint answers as before; on its default `authRequired` it admits a session only, so an API key is refused there before the flow.

**Who moves:** an integration that starts such a flow through the trigger routes under an AI service account's own key. The rule refuses on the safe side in three cases, each an account start only: every holder of the flow's name counts, so an account starting one package's flow is refused when another package's confirmation-gated action targets a flow of the same name; a confirmation-gated action the action door would refuse for another reason (an action switched off) still gates the flow; and on a host whose merged metadata listing is not served at all, every start by an account is refused `503`, a flow no gated action targets included. A person starts it now (through the trigger route, or through the action, confirming it), as the action door already requires; or the action's author declares `ai.requiresConfirmation: false` when the flow is safe to start unattended.
118 changes: 117 additions & 1 deletion packages/runtime/src/domains/automation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,8 @@ import { flowStartRefusal, isAiServiceAccount } from '../flow-start-admission.js
import {
apiForwardCredentialKind,
callData,
collectActionDeclarations,
readMergedItems,
refuseUnreadableFlowStartRecords,
type FlowStartRecordKeys,
} from '../action-execution.js';
Expand Down Expand Up @@ -3004,6 +3006,108 @@ async function unregisterAndDeleteFlow(
return undefined;
}

/**
* [ADR-0151 D3 rule 3] One service slot rule 2b reads its declarations from,
* resolved to the instance the same request's `/actions` door reads, in every
* host shape. The rule, as this function holds it: a read failure refuses the
* start when no leg of that door's order answers the name; where a later leg
* answers, the start is judged on that instance, as the `/actions` door would
* serve it. The smallest composition of the two resolvers that exist:
*
* 1. `resolveService`, the order every `/actions` read uses (`getObjectQL`
* included): the request's own kernel first on a host that routes a
* request to a kernel of its own, then the host kernel's scoped factory,
* then its singletons. An instance it answers is the door's instance,
* whichever leg answers it, a leg that did not resolve before it included.
* 2. Only on a miss, `resolveServiceOrLoud` classifies it: a name nothing
* registered (or a scoped registration with no instance in this scope) is
* absent, `undefined`; any other rejection is re-raised. The quiet probe
* absorbs every rejection, so a miss there is absence or a failure it
* swallowed, and this step is what tells the two apart. Its own order
* (the host's scoped leg first) never decides WHICH instance is read: it
* is asked only when step 1 found none.
*
* Scoped by the request's environment, as the door's reads are: unscoped, a
* scoped registration is a fault to the classifier.
*
* Per-leg loud resolution (a wired slot that fails on an earlier step refuses
* even when a later step answers) is a shared resolver change for every
* dispatcher door, tracked by the security lane; it is not in this function.
*/
async function resolveSlotAsActionsDoorReads(
deps: DomainHandlerDeps,
context: HttpProtocolContext,
name: 'protocol' | 'objectql' | 'metadata',
): Promise<any> {
const served = await deps.resolveService(context, name, context?.environmentId);
if (served != null) return served;
return deps.resolveServiceOrLoud(context, name, context?.environmentId);
}

/**
* [ADR-0151 D3 rule 3] The action declarations the request's environment
* serves: what flow start admission's rule 2b reads, for an AI service
* account only, to find an action that targets the flow and declares
* `ai.requiresConfirmation: true` (`../flow-start-admission.ts`). Every row is
* a `collectActionDeclarations` row, from these sources:
*
* - where the `protocol` slot serves the merged listings (`getMetaItems`), its
* merged object and action listings alone — the reading the addressed
* `/actions` door, the bare door's holder rule and the MCP bridge make;
* - otherwise every source the bare `/actions` door resolves a declaration
* from on such a host: the ObjectQL registry's objects (their embedded
* actions) and standalone `action` items, and the metadata service's
* object and action listings.
*
* Each of the three slots (`protocol`, `objectql`, `metadata`) is the
* instance the same request's `/actions` door reads, in every host shape
* ({@link resolveSlotAsActionsDoorReads}: the request's own kernel first). A
* slot nothing registered is absent and contributes nothing; a slot that no
* leg of that door's order answers, because a leg failed to resolve it,
* throws; and where a later leg answers the name, that instance is read, as
* the `/actions` door would serve it. Each listing (the two merged ones, the
* registry's two, the metadata service's objects and its standalone `action`
* items) is read where its throw travels. Any such throw makes the predicate
* refuse the start `503`. So a host that serves no declaration from any of
* these sources finds none, and a read failure that reaches this function as
* a throw admits nothing. A source that answers a failed read of its own
* without throwing is not told apart here: the metadata service's plural
* listing reports a loader that failed and answers the other loaders' rows,
* and those rows are what is judged.
*/
async function servedActionDeclarations(
deps: DomainHandlerDeps,
context: HttpProtocolContext,
): Promise<Array<{ action: unknown; objectName: string }>> {
const protocol = await resolveSlotAsActionsDoorReads(deps, context, 'protocol');
if (typeof protocol?.getMetaItems === 'function') {
const objects = await readMergedItems(protocol, 'object');
const actions = await readMergedItems(protocol, 'action');
return collectActionDeclarations(deps, undefined, objects, actions);
}
const rows: Array<{ action: unknown; objectName: string }> = [];
// The engine the `/actions` door's `getObjectQL` reads. A slot that no step
// of that door's order answers, because a step failed to resolve it, throws,
// which that probe does not; where a later step answers, that engine is read.
const engine = (await resolveSlotAsActionsDoorReads(deps, context, 'objectql')) as
| { registry?: { listItems?: (type: string) => unknown[] } }
| undefined;
const registry = engine?.registry;
if (typeof registry?.listItems === 'function') {
rows.push(...await collectActionDeclarations(deps, undefined, registry.listItems('object'), registry.listItems('action')));
}
const metadata = await resolveSlotAsActionsDoorReads(deps, context, 'metadata');
if (typeof metadata?.listObjects === 'function' || typeof metadata?.loadMany === 'function') {
// Both listings read HERE and handed over, so a throw of either one
// travels: `collectActionDeclarations` reads a throwing standalone
// listing it is left to read as no standalone item, by design.
const objects: unknown[] = typeof metadata.listObjects === 'function' ? (await metadata.listObjects()) ?? [] : [];
const actions: unknown[] = typeof metadata.loadMany === 'function' ? (await metadata.loadMany('action')) ?? [] : [];
rows.push(...await collectActionDeclarations(deps, undefined, objects, actions));
}
return rows;
}

/**
* [#9378] The ONE mapper both trigger doors answer through — `POST
* /:name/trigger` and the legacy `POST /trigger/:name`, which
Expand Down Expand Up @@ -3136,12 +3240,24 @@ async function respondToFlowTrigger(
// account is therefore refused an elevated (`runAs: 'system'`) flow at
// this route, and told where the opt-in stands: an `ai.exposed` action
// that targets the flow, run through `/actions` or MCP `run_action`.
const startRefusal = await flowStartRefusal(automationService, flowName, context?.executionContext, { aiExposed: false });
//
// [ADR-0151 D3 rule 3] And the confirmation an action declares travels
// with what it starts: this door states the environment's action
// declarations (`servedActionDeclarations`), so an account's start of a
// flow that a confirmation-gated action targets is refused with the action
// door's own `428`, whatever the request carries. A declaration read that
// fails is refused by the predicate itself, a flat `503`, and nothing runs.
const startRefusal = await flowStartRefusal(automationService, flowName, context?.executionContext, {
aiExposed: false,
actionDeclarations: () => servedActionDeclarations(deps, context),
});
if (startRefusal) {
const details = 'details' in startRefusal ? startRefusal.details : undefined;
return {
handled: true,
response: deps.error(startRefusal.message, startRefusal.status, {
code: startRefusal.code,
...(details ?? {}),
}),
};
}
Expand Down
17 changes: 17 additions & 0 deletions packages/runtime/src/endpoint-policy.auth-gate.pin.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,10 @@
*/

import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
// The dispatcher's reach loads `@objectstack/metadata` inside a function body
// (`standalone-stack.ts`); paid here, during collection, so no case's clocked
// window pays that first load (`check:test-source-alias`).
import '@objectstack/metadata';
import { LiteKernel, Plugin, PluginContext, isAuthGateAllowlisted, hashApiKey } from '@objectstack/core';
import { HonoServerPlugin } from '@objectstack/plugin-hono-server';
import { ApiEndpointSchema, type ApiEndpoint } from '@objectstack/spec/api';
Expand Down Expand Up @@ -332,6 +336,19 @@ describe('ADR-0069 at the declared-endpoint fallback (real boot, real socket)',
expect(observed.taskReads).toBe(1);
});

// [ADR-0151 D3 rule 3] The declared `type: 'flow'` endpoint is a door that
// starts a flow by name, and an AI service account authenticates by key:
// on the default `authRequired`, a key alone is refused before the
// executor, so no key starts the endpoint's flow there (the trigger routes
// judge the account instead, `flow-start-confirmation-gated-target.test.ts`).
it('API KEY alone: a flow endpoint on the default authRequired answers 401 UNAUTHENTICATED, and its flow never runs', async () => {
const res = await request(WRITE, undefined, { 'x-api-key': API_KEY });
const text = await res.text();
expect(res.status, text).toBe(401);
expect((JSON.parse(text) as { error?: { code?: string } }).error?.code).toBe('UNAUTHENTICATED');
expect(observed.flowRuns, 'the endpoint ran its flow').toBe(0);
});

it('API KEY beside a held session: the key answers, the session is not asked', async () => {
const res = await request(READ, 'u_held_mfa', { 'x-api-key': API_KEY });
expect(res.status, await res.text()).toBe(200);
Expand Down
Loading
Loading