From ab41e0b40e576f0fef90af8289fe35358094cf61 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 06:28:20 +0000 Subject: [PATCH 1/9] feat(security): an AI service account is the agent principal of its own requests, under the agent ceiling The grants resolver reads the caller's own sys_user row on every resolution and reports an account (principal_kind = agent) as principalKind 'agent': no everyone anchor, no system permission, no platform or organization administrator standing. The shared assembler stamps it as the agent principal with no onBehalfOf, so its own grants are its whole authority. The security plugin clamps every agent principal's sets at evaluation: no View All, Modify All, transfer, restore or purge, system permission or admin scope. A set assigned to an account that breaches the ceiling is refused by name at sys_user_permission_set and sys_user_position. Run, storage, mention, explain and scoped-engine envelopes carry the kind; the flow trigger and action doors forward it with the account's grants. Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- .../src/security/admin-standing-surface.ts | 7 +- .../assemble-execution-context.test.ts | 56 ++++ .../security/assemble-execution-context.ts | 32 +- packages/core/src/security/index.ts | 3 + ...esolve-authz-context.agent-account.test.ts | 150 +++++++++ ...uthz-context.batch-equivalence.golden.json | 8 + ...ve-authz-context.batch-equivalence.test.ts | 16 +- ...uthz-context.platform-admin-config.test.ts | 36 +- .../src/security/resolve-authz-context.ts | 99 ++++-- .../resolve-user-grants-cache.test.ts | 17 +- .../src/__tests__/stdio-agent-account.test.ts | 139 ++++++++ packages/mcp/src/plugin.ts | 6 +- .../objectql/src/engine-scoped-context.ts | 3 + .../plugin-audit/src/comment-access-hooks.ts | 6 +- .../src/mention-recipient-gate.ts | 2 + .../plugin-auth/src/last-admin-guard.ts | 9 + .../src/agent-account-grant-refusal.test.ts | 230 +++++++++++++ .../src/agent-account-grant-refusal.ts | 307 ++++++++++++++++++ .../src/agent-ceiling-clamp.test.ts | 172 ++++++++++ .../src/agent-ceiling-clamp.ts | 137 ++++++++ .../src/agent-ceiling-grant-refusal.ts | 12 +- .../plugin-security/src/explain-engine.ts | 3 + .../src/permission-evaluator.ts | 14 + .../src/security-plugin-effective-access.ts | 10 +- .../src/security-plugin-permission-sets.ts | 18 +- .../src/security-plugin-start-hooks.ts | 9 + .../src/rest-api-key-agent-account.test.ts | 145 +++++++++ packages/rest/src/rest-server.ts | 14 +- packages/runtime/src/action-execution.ts | 15 +- ...tomation-connector-connection-door.test.ts | 28 ++ packages/runtime/src/domains/automation.ts | 27 +- .../src/flow-run-agent-account-kind.test.ts | 71 ++++ ...ve-execution-context.agent-account.test.ts | 292 +++++++++++++++++ .../services/service-automation/src/engine.ts | 6 + .../services/service-automation/src/plugin.ts | 2 + .../src/run-agent-account-kind.test.ts | 62 ++++ .../service-automation/src/run-resume.ts | 11 +- .../src/runtime-identity.ts | 24 ++ .../src/attachment-access-hooks.ts | 6 +- .../src/storage-service-plugin.ts | 2 + 40 files changed, 2125 insertions(+), 81 deletions(-) create mode 100644 packages/core/src/security/resolve-authz-context.agent-account.test.ts create mode 100644 packages/mcp/src/__tests__/stdio-agent-account.test.ts create mode 100644 packages/plugins/plugin-security/src/agent-account-grant-refusal.test.ts create mode 100644 packages/plugins/plugin-security/src/agent-account-grant-refusal.ts create mode 100644 packages/plugins/plugin-security/src/agent-ceiling-clamp.test.ts create mode 100644 packages/plugins/plugin-security/src/agent-ceiling-clamp.ts create mode 100644 packages/rest/src/rest-api-key-agent-account.test.ts create mode 100644 packages/runtime/src/flow-run-agent-account-kind.test.ts create mode 100644 packages/runtime/src/security/resolve-execution-context.agent-account.test.ts create mode 100644 packages/services/service-automation/src/run-agent-account-kind.test.ts diff --git a/packages/core/src/security/admin-standing-surface.ts b/packages/core/src/security/admin-standing-surface.ts index b3a33352546..4503b578573 100644 --- a/packages/core/src/security/admin-standing-surface.ts +++ b/packages/core/src/security/admin-standing-surface.ts @@ -200,12 +200,17 @@ export const ADMIN_STANDING_SURFACE: Readonly + 'reachable writes, and neither touches a grant table. `banned` stays absent from the ' + 'column list because the resolver still never reads it; the guard watches the ban/delete ' + 'WRITE SHAPES on this table for its own reasons, which is a different question from what ' - + 'this resolver consumes.', + + 'this resolver consumes. [ADR-0151 D3] `principal_kind` (read in either spelling) is read ' + + 'too: a row of kind `agent` — an AI service account — confers NO standing through either ' + + 'anchor, whatever it holds. The kind is born with the row and immutable for every caller, ' + + 'so no write moves a person\'s row to `agent`.', columns: [ 'id', 'email', 'email_verified', 'ai_access', + 'principal_kind', + 'principalKind', ], }, diff --git a/packages/core/src/security/assemble-execution-context.test.ts b/packages/core/src/security/assemble-execution-context.test.ts index fc16442279e..5363b9c423e 100644 --- a/packages/core/src/security/assemble-execution-context.test.ts +++ b/packages/core/src/security/assemble-execution-context.test.ts @@ -652,3 +652,59 @@ describe('impersonatedBy — the administrator of an impersonation session, carr expect('impersonatedBy' in guest!).toBe(false); }); }); + +describe('[ADR-0151 D3] an AI service account is an agent principal of its own: no onBehalfOf, no system permission', () => { + const ACCOUNT = baseAuthz({ + userId: 'u_bot', + tenantId: 'org1', + principalKind: 'agent', + positions: ['org_member'], + permissions: ['crm_lead_reader'], + // What the resolver never hands an account; the assembler withholds it anyway. + systemPermissions: ['manage_users'], + org_user_ids: ['u_bot', 'u2'], + accessible_org_ids: ['org1'], + }); + + it('stamps principalKind agent, keeps userId the account and its own grants, and carries no onBehalfOf, performer or system permission', () => { + const ctx = assembleExecutionContext({ authz: ACCOUNT, oauth: undefined, localization: undefined, requestLocale: undefined, accessToken: undefined, authGate: undefined })!; + expect(ctx.userId).toBe('u_bot'); + expect(ctx.principalKind).toBe('agent'); + expect(ctx.permissions).toEqual(['crm_lead_reader']); + expect(ctx.systemPermissions).toEqual([]); + expect(ctx.isSystem).toBe(false); + for (const key of ['onBehalfOf', 'performedBy', 'oauthScopes']) expect(Object.keys(ctx)).not.toContain(key); + }); + + it('takes precedence over an OAuth arm: an account is never re-read as a person an OAuth client acts for', () => { + const ctx = assembleExecutionContext({ + authz: ACCOUNT, + oauth: { userId: 'u_bot', scopes: ['data:read'], clientId: 'cli1', scopePermissions: ['mcp_agent_data_read'], delegatesActions: true }, + localization: undefined, requestLocale: undefined, accessToken: undefined, authGate: undefined, + })!; + expect(ctx.principalKind).toBe('agent'); + expect(ctx.onBehalfOf).toBeUndefined(); + expect(ctx.performedBy).toBeUndefined(); + expect(ctx.permissions).toEqual(['crm_lead_reader']); + expect(ctx.systemPermissions).toEqual([]); + }); + + it('CONTROL: an OAuth-delegated agent keeps today\'s shape, and a person\'s envelope is unchanged', () => { + const delegated = assembleExecutionContext({ + authz: HUMAN_FULL, + oauth: { userId: 'u1', scopes: ['data:read', 'actions:execute'], clientId: 'cli1', scopePermissions: ['mcp_agent_data_read'], delegatesActions: true }, + localization: undefined, requestLocale: undefined, accessToken: undefined, authGate: undefined, + })!; + expect(delegated.principalKind).toBe('agent'); + expect(delegated.userId).toBe('u1'); + expect(delegated.onBehalfOf).toEqual({ userId: 'u1', principalKind: 'human' }); + expect(delegated.performedBy).toEqual({ clientId: 'cli1' }); + expect(delegated.permissions).toEqual(['mcp_agent_data_read']); + expect(delegated.systemPermissions).toEqual(HUMAN_FULL.systemPermissions); + + const person = assembleExecutionContext({ authz: HUMAN_FULL, oauth: undefined, localization: undefined, requestLocale: undefined, accessToken: undefined, authGate: undefined })!; + expect(person.principalKind).toBe('human'); + expect(person.systemPermissions).toEqual(HUMAN_FULL.systemPermissions); + expect(person.onBehalfOf).toBeUndefined(); + }); +}); diff --git a/packages/core/src/security/assemble-execution-context.ts b/packages/core/src/security/assemble-execution-context.ts index 63d4d69fce6..f6651b320f4 100644 --- a/packages/core/src/security/assemble-execution-context.ts +++ b/packages/core/src/security/assemble-execution-context.ts @@ -235,8 +235,10 @@ export interface ExecutionContextAssemblyInput { /** * OAuth access-token provenance, or `undefined` on a face that does not * accept one. Only the `/mcp` dispatch door passes a value; REST passes - * `undefined` — which is why `principalKind: 'agent'`, `onBehalfOf` and - * `oauthScopes` are not representable there. + * `undefined` — which is why an OAuth-delegated agent (`onBehalfOf`, + * `oauthScopes`) is not representable there. An AI service account's key + * makes `principalKind: 'agent'` on every face (ADR-0151 D3), with no + * `onBehalfOf`: that agent is its own subject, read from `authz`. */ oauth: OAuthTokenProvenance | undefined; /** @@ -317,7 +319,17 @@ function entryFields( // consented scope OR the user's own reach (confused-deputy prevention). // `userId` stays the human so owner-stamping and `current_user.*` RLS resolve // to them. - const agent = !anonymous && oauth?.clientId ? oauth : undefined; + // + // [ADR-0151 D3] An AI service account is an agent principal of a different + // provenance: its own subject. Its API key admits it, its row says so + // (`authz.principalKind`), and it acts for nobody — no `onBehalfOf`, so no + // intersection with anyone's grants: its own explicit grants are its whole + // authority, under the agent ceiling. It carries no system permission. It + // takes precedence over the OAuth arm: an account never consents to a client, + // so no token names it, and an `onBehalfOf` naming it as a person would be + // false. + const account = !anonymous && authz.principalKind === 'agent'; + const agent = !anonymous && !account && oauth?.clientId ? oauth : undefined; return { // [ADR-0090 D9/D10] Principal taxonomy at the HTTP entry: a session-backed @@ -334,13 +346,15 @@ function entryFields( // OBJECT access stays denied to the agent regardless of this line). The // `actions:execute` scope IS the user's consent to let this agent invoke // actions on their behalf; without it the agent holds none. - systemPermissions: agent - ? agent.delegatesActions - ? (authz.systemPermissions ?? []) - : [] - : authz.systemPermissions, + systemPermissions: account + ? [] + : agent + ? agent.delegatesActions + ? (authz.systemPermissions ?? []) + : [] + : authz.systemPermissions, isSystem: false, - principalKind: agent ? 'agent' : anonymous ? 'guest' : 'human', + principalKind: agent || account ? 'agent' : anonymous ? 'guest' : 'human', onBehalfOf: agent ? { userId: authz.userId!, principalKind: 'human' } : undefined, // [ADR-0090 D10 rule 4 — dual attribution] The same `azp` that made this // an agent principal, carried as the PERFORMER so the write is attributable diff --git a/packages/core/src/security/index.ts b/packages/core/src/security/index.ts index 61a986ffcc6..a3c28a3cb63 100644 --- a/packages/core/src/security/index.ts +++ b/packages/core/src/security/index.ts @@ -234,6 +234,9 @@ export { export { resolveAuthzContext, resolveUserAuthzGrants, + // [ADR-0151 D1] Is a `sys_user` row an AI service account? The one reading + // the resolver applies, for a gate that reads a holder's row itself. + isAgentAccountRow, // [#10348] The ONE id-shaped platform-admin predicate (ADR-0068 D2). Every // surface that only knows a user id asks this instead of re-reading // `sys_*_permission_set` — the prohibition resolve-authz-context.ts states. diff --git a/packages/core/src/security/resolve-authz-context.agent-account.test.ts b/packages/core/src/security/resolve-authz-context.agent-account.test.ts new file mode 100644 index 00000000000..7056290fa23 --- /dev/null +++ b/packages/core/src/security/resolve-authz-context.agent-account.test.ts @@ -0,0 +1,150 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0151 D3] The grants resolver reads an AI service account for what it + * is: `principalKind: 'agent'`, explicit grants only — no `everyone` anchor, + * no system permission, and no administrator standing from any anchor — while + * a person holding the very same rows resolves exactly as before (CONTROL). + * + * The account's rows are ones no registration door would write (an + * organization `owner` role, the Default Organization's `admin_full_access` + * grant, a configured administrator address) and a store can still hold: the + * resolver is the guarantee, not the doors. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; + +import { resetPlatformAdminEmailMemo } from './platform-admin.js'; +import { hasPlatformAdminStanding, isAgentAccountRow, resolveAuthzContext, resolveUserAuthzGrants } from './resolve-authz-context.js'; +import { bindCatalogFromTables } from './__tests__/security-catalog.testkit.js'; + +const ENV = 'OS_PLATFORM_OWNER_EMAIL'; +const NOW = Date.parse('2026-11-09T00:00:00.000Z'); + +/** The rows of `u_bot` (an account) and `u_mia` (a person) are the same, the kind aside. */ +function tables(): Record>> { + return { + sys_user: [ + { id: 'u_bot', email: 'owner@corp.example', email_verified: true, principal_kind: 'agent', accountable_user_id: 'u_mia' }, + { id: 'u_mia', email: 'mia@corp.example', email_verified: true, principal_kind: 'human' }, + ], + sys_member: [ + { user_id: 'u_bot', organization_id: 'org_a', role: 'owner' }, + { user_id: 'u_mia', organization_id: 'org_a', role: 'owner' }, + ], + sys_user_permission_set: [ + { user_id: 'u_bot', permission_set: 'ops_tools', organization_id: 'org_a' }, + { user_id: 'u_bot', permission_set: 'admin_full_access', organization_id: 'org_default' }, + { user_id: 'u_mia', permission_set: 'ops_tools', organization_id: 'org_a' }, + { user_id: 'u_mia', permission_set: 'admin_full_access', organization_id: 'org_default' }, + ], + sys_organization: [{ id: 'org_default', slug: 'default' }], + sys_permission_set: [ + { id: 'ps_ops', name: 'ops_tools', system_permissions: JSON.stringify(['manage_users']) }, + { id: 'ps_admin', name: 'admin_full_access' }, + { id: 'ps_everyone', name: 'everyone_reader' }, + ], + sys_position: [{ id: 'pos_everyone', name: 'everyone' }], + sys_position_permission_set: [{ position_id: 'pos_everyone', permission_set_id: 'ps_everyone' }], + }; +} + +function makeQl(t = tables()) { + const matches = (row: Record, where: any): boolean => + Object.entries(where ?? {}).every(([k, v]) => { + if (k.startsWith('$')) throw new Error(`fake driver: unsupported operator ${k}`); + if (v && typeof v === 'object' && '$in' in (v as any)) return (v as any).$in.includes(row[k]); + if (v === null) return (row[k] ?? null) === null; + return row[k] === v; + }); + return bindCatalogFromTables({ + async find(object: string, opts: any) { + const rows = (t[object] ?? []).filter((r) => matches(r, opts?.where)); + return typeof opts?.limit === 'number' ? rows.slice(0, opts.limit) : rows; + }, + }, t); +} + +let ambient: string | undefined; +beforeEach(() => { + ambient = process.env[ENV]; + delete process.env[ENV]; + resetPlatformAdminEmailMemo(); +}); +afterEach(() => { + if (ambient === undefined) delete process.env[ENV]; + else process.env[ENV] = ambient; + resetPlatformAdminEmailMemo(); +}); + +describe('[ADR-0151 D3] resolveUserAuthzGrants — an AI service account', () => { + it('is the agent kind, holds no everyone anchor, no system permission and no administrator standing', async () => { + const grants = await resolveUserAuthzGrants(makeQl(), 'u_bot', { tenantId: 'org_a', nowMs: NOW }); + expect(grants.principalKind).toBe('agent'); + expect(grants.positions).not.toContain('everyone'); + expect(grants.positions).not.toContain('platform_admin'); + expect(grants.permissions).not.toContain('everyone_reader'); + // Its explicit grants stay named: they are clamped where they are evaluated. + expect(grants.permissions).toEqual(expect.arrayContaining(['ops_tools', 'admin_full_access'])); + expect(grants.systemPermissions).toEqual([]); + expect(grants.posture).toBe('MEMBER'); + }); + + it('a configured administrator address on the account confers nothing either', async () => { + process.env[ENV] = 'owner@corp.example'; + resetPlatformAdminEmailMemo(); + const grants = await resolveUserAuthzGrants(makeQl(), 'u_bot', { tenantId: 'org_a', nowMs: NOW }); + expect(grants.posture).not.toBe('PLATFORM_ADMIN'); + expect(await hasPlatformAdminStanding(makeQl(), 'u_bot', { nowMs: NOW })).toBe(false); + }); + + it('a seeded caller cannot skip the kind: the row is read whatever is seeded', async () => { + const grants = await resolveUserAuthzGrants(makeQl(), 'u_bot', { + tenantId: 'org_a', nowMs: NOW, seedEmail: 'seeded@corp.example', seedPermissions: ['ai_seat'], + }); + expect(grants.principalKind).toBe('agent'); + expect(grants.positions).not.toContain('everyone'); + }); + + it('the request envelope carries the kind', async () => { + const ctx = await resolveAuthzContext({ + userAuthGates: undefined, + apiKeyLifecycle: undefined, + ql: makeQl(), + headers: new Headers(), + getSession: async () => ({ user: { id: 'u_bot' }, session: { activeOrganizationId: 'org_a' } }), + nowMs: NOW, + } as any); + expect(ctx.userId).toBe('u_bot'); + expect(ctx.principalKind).toBe('agent'); + expect(ctx.systemPermissions).toEqual([]); + }); + + it('reads the kind off either spelling of the column, and nothing else as an account', () => { + expect(isAgentAccountRow({ principal_kind: 'agent' })).toBe(true); + expect(isAgentAccountRow({ principalKind: 'agent' })).toBe(true); + for (const row of [{ principal_kind: 'human' }, { principal_kind: null }, {}, null, undefined, 'agent', { principal_kind: 'AGENT' }]) { + expect(isAgentAccountRow(row)).toBe(false); + } + }); +}); + +describe('CONTROL — a person holding the same rows is unchanged', () => { + it('human kind (absent), the everyone anchor, the system permission, and the anchored platform standing', async () => { + const grants = await resolveUserAuthzGrants(makeQl(), 'u_mia', { tenantId: 'org_a', nowMs: NOW }); + expect(grants.principalKind).toBeUndefined(); + expect(grants.positions).toContain('everyone'); + expect(grants.permissions).toContain('everyone_reader'); + expect(grants.systemPermissions).toContain('manage_users'); + expect(grants.posture).toBe('PLATFORM_ADMIN'); + expect(await hasPlatformAdminStanding(makeQl(), 'u_mia', { nowMs: NOW })).toBe(true); + }); + + it('a row written before the column existed reads as a person', async () => { + const t = tables(); + t.sys_user = t.sys_user.map((r) => (r.id === 'u_mia' ? { id: r.id, email: r.email, email_verified: true } : r)); + const grants = await resolveUserAuthzGrants(makeQl(t), 'u_mia', { tenantId: 'org_a', nowMs: NOW }); + expect(grants.principalKind).toBeUndefined(); + expect(grants.positions).toContain('everyone'); + }); +}); diff --git a/packages/core/src/security/resolve-authz-context.batch-equivalence.golden.json b/packages/core/src/security/resolve-authz-context.batch-equivalence.golden.json index 97a6b8221d6..df308f1acdd 100644 --- a/packages/core/src/security/resolve-authz-context.batch-equivalence.golden.json +++ b/packages/core/src/security/resolve-authz-context.batch-equivalence.golden.json @@ -703,6 +703,14 @@ "posture": "MEMBER" }, "queries": [ + { + "object": "sys_user", + "where": { + "id": "u_seed" + }, + "limit": 1, + "isSystem": true + }, { "object": "sys_member", "where": { diff --git a/packages/core/src/security/resolve-authz-context.batch-equivalence.test.ts b/packages/core/src/security/resolve-authz-context.batch-equivalence.test.ts index a101d4274a0..93c9bb753a0 100644 --- a/packages/core/src/security/resolve-authz-context.batch-equivalence.test.ts +++ b/packages/core/src/security/resolve-authz-context.batch-equivalence.test.ts @@ -99,6 +99,18 @@ * fixture resolves in three legs, the completion read being its own. The * first read itself, its bound and every other recorded read are unchanged, * and so is every other fixture: none comes back at the bound. + * + * ⚠️ A sixth recorded move ([ADR-0151] D3): the resolver reads the caller's + * own `sys_user` row on EVERY resolution, no longer only when a seed, the + * `ai_seat` synthesis or the platform-admin config asks for it, because the + * row's `principal_kind` decides whether the principal is an AI service + * account — which is withheld the `everyone` anchor and every administrator + * standing — and no caller seeds that. ONE golden moved, + * `seeded-permissions-and-email`, the only fixture whose seeds suppressed the + * read: `queries` gains `sys_user {id: 'u_seed'}`, limit 1, in wave 1 beside + * the other identity reads, so it still resolves in two legs. Its `grants` + * envelope is byte-identical, and so is every other fixture's golden: each + * already read the row. */ import { readFileSync } from 'node:fs'; @@ -183,7 +195,9 @@ describe('[#10825] batched resolveUserAuthzGrants — equivalence with the seque * * ⛔ If a future leg makes the read unconditional, the golden MOVES and the * move is written down in the PR that makes it. It is never re-captured to - * agree with new output. + * agree with new output. [ADR-0151 D3] One did: the sixth recorded move in + * this file's header. The variable is still cleared, because the config + * anchor's own derivation must not run on an ambient value. */ const ENV = 'OS_PLATFORM_OWNER_EMAIL'; let ambientOwnerEmail: string | undefined; diff --git a/packages/core/src/security/resolve-authz-context.platform-admin-config.test.ts b/packages/core/src/security/resolve-authz-context.platform-admin-config.test.ts index e1a64346745..423335e0955 100644 --- a/packages/core/src/security/resolve-authz-context.platform-admin-config.test.ts +++ b/packages/core/src/security/resolve-authz-context.platform-admin-config.test.ts @@ -437,18 +437,22 @@ describe('[#11663 L5] the legacy grant row is an anchor under `single`, and NOWH }); }); -describe('[#11663 L2] the sys_user read stays CONDITIONAL on config', () => { +describe('[#11663 L2, ADR-0151 D3] the sys_user read is ONE read, config or not', () => { const seeded = { nowMs: NOW, seedEmail: 'seeded@corp.example', seedPermissions: ['ai_seat'] }; - it('a fully-seeded principal reads NO sys_user row when nothing is declared', async () => { - // This is the property that leaves the pinned batch-equivalence query - // multiset untouched for every deployment that has not adopted the config - // anchor: pin P2's short-circuit answers "not an admin" on an empty list - // BEFORE any row is looked at. + it('a fully-seeded principal reads its sys_user row exactly ONCE when nothing is declared, and is not an admin', async () => { + // [ADR-0151 D3] Forced edit: this pin used to assert NO read here — the + // config anchor's read was conditional, and a fully seeded principal asked + // for none. The row's `principal_kind` now decides whether the principal + // is an AI service account, which no caller seeds, so the row is read on + // every resolution (the sixth recorded move in the batch-equivalence + // header). What still holds is pin P2's short-circuit: with nothing + // declared, the config branch confers nothing, whatever the row says. declare(undefined); const ql = makeQl(configOnlyTables({ id: 'usr_1', email: 'a@b.c', email_verified: true })); - await resolveUserAuthzGrants(ql, 'usr_1', seeded); - expect(ql.calls.filter((c) => c.object === 'sys_user')).toHaveLength(0); + const grants = await resolveUserAuthzGrants(ql, 'usr_1', seeded); + expect(ql.calls.filter((c) => c.object === 'sys_user')).toHaveLength(1); + expect(grants.posture).not.toBe('PLATFORM_ADMIN'); }); it('…and reads it exactly ONCE when administrators ARE declared', async () => { @@ -576,13 +580,17 @@ describe('[#11663 L5] the legacy anchor confers only on the rigs Choice 4A keeps expect(reads.single.length).toBeGreaterThan(0); // the fixture really did resolve }); - it('…and costs no sys_user read of its own — the gate never reaches for the row', async () => { - // Seed `grants.email` and the `ai_seat` capability and NOTHING in the - // resolution needs the `sys_user` row. The posture gate must still answer, - // on both sides, without issuing one: it reads the environment. #13667 owed + it('…and costs no sys_user read of its own — the one row read is the kind\'s, the same on both sides', async () => { + // Seed `grants.email` and the `ai_seat` capability, and the only thing in + // the resolution that needs the `sys_user` row is the principal's kind + // (ADR-0151 D3: an AI service account is withheld the `everyone` anchor + // and every standing). The posture gate must still answer, on both sides, + // without issuing a read of its own: it reads the environment. #13667 owed // this for the notice's `userRow?.email` lookup; L5 owes it because the gate // now decides STANDING, and a read added here would be added to every - // request on every walled rig. + // request on every walled rig. [ADR-0151 D3] Forced edit: the count was 0 + // before the kind was read; it is 1 on both postures now — the memoized + // row, never a second read. const seeded = { nowMs: NOW, seedEmail: 'seeded@corp.example', seedPermissions: ['ai_seat'] }; for (const p of ['single', 'isolated'] as const) { declare(undefined); @@ -592,7 +600,7 @@ describe('[#11663 L5] the legacy anchor confers only on the rigs Choice 4A keeps const ql = makeQl(legacyTables()); const grants = await resolveUserAuthzGrants(ql, 'usr_1', seeded); - expect(ql.calls.filter((c) => c.object === 'sys_user'), p).toHaveLength(0); + expect(ql.calls.filter((c) => c.object === 'sys_user'), p).toHaveLength(1); expect(grants.posture, p).toBe(p === 'single' ? 'PLATFORM_ADMIN' : 'MEMBER'); expect(sink.warns, p).toEqual([]); } diff --git a/packages/core/src/security/resolve-authz-context.ts b/packages/core/src/security/resolve-authz-context.ts index ee837f2a6a1..be030247d2c 100644 --- a/packages/core/src/security/resolve-authz-context.ts +++ b/packages/core/src/security/resolve-authz-context.ts @@ -148,6 +148,13 @@ export interface ResolvedAuthzContext { * `plugin-sharing`) read it off the envelope instead of re-deriving it. */ audience?: 'external'; + /** + * [ADR-0151 D3] `'agent'` when {@link userId} is an AI service account + * ({@link UserAuthzGrants.principalKind}). Only an API key admits one (an + * account never holds a session). The shared assembler stamps it as the agent + * principal of its own request, with no `onBehalfOf`. + */ + principalKind?: 'agent'; /** * [#23287, ruling C′ item 3] The credential that admitted {@link userId}: * `'api_key'` when an API key did (step 1 below), `'session'` when the @@ -825,6 +832,7 @@ async function resolveAuthzContextInScope(input: ResolveAuthzInput): Promise 0; const [, members, userPositionRows, orgMembersLeg, upsRowsAll] = await Promise.all([ - needsUserRow ? getUserRow() : Promise.resolve(undefined), + getUserRow(), tryFind(ql, 'sys_member', { user_id: userId }, 200, undefined, MEMBER_ROW_COLUMNS), tryFind(ql, 'sys_user_position', { user_id: userId }, 200), tenantId ? tryFind(ql, 'sys_member', { organization_id: tenantId }, ORG_MEMBERS_FIRST_READ_ROWS, undefined, ORG_MEMBER_PAGE_COLUMNS) : Promise.resolve([] as any[]), tryFind(ql, 'sys_user_permission_set', { user_id: userId }, 100, undefined, GRANT_ROW_COLUMNS), ]); + // [ADR-0151 D3] An AI service account is the agent principal of its own + // requests: it holds explicit grants only, under the agent ceiling. + const agentAccount = isAgentAccountRow(userRow); + if (agentAccount) grants.principalKind = 'agent'; + // Resolve the caller's unique email for `current_user.email` RLS owner // policies when the caller didn't supply it (e.g. API-key auth). if (!grants.email) { @@ -2099,7 +2137,13 @@ export async function resolveUserAuthzGrants( // platform baseline nor an app's `isDefault` set nor an accepted package // default bound to it reaches the holder. Its baseline is what its own // identity position names (§6a); everything else is an explicit grant. - if (!holdsExternalIdentity(grants.positions) && !grants.positions.includes('everyone')) grants.positions.push('everyone'); + // + // [ADR-0151 D3] …and an AI service account: its grants are the explicit + // ones an administrator assigned it, so a newly registered account can do + // nothing until it is granted something. + if (!agentAccount && !holdsExternalIdentity(grants.positions) && !grants.positions.includes('everyone')) { + grants.positions.push('everyone'); + } // [#10757 leg 4] The Default Organization read (§6) and the activation-ledger // read (§6a) are ONE wave. They used to be two serial round trips, because the @@ -2230,7 +2274,10 @@ export async function resolveUserAuthzGrants( // every posture. What a walled rig stops deriving from the grant is // PLATFORM_ADMIN STANDING — the rung, the built-in `platform_admin` position // and everything downstream of them. - if (anchorsPlatformStanding(grant) && active) { + // + // [ADR-0151 D3] An AI service account is never an administrator: no grant + // confers platform standing on it. + if (anchorsPlatformStanding(grant) && active && !agentAccount) { hasPlatformAdminGrant = true; } } @@ -2271,7 +2318,8 @@ export async function resolveUserAuthzGrants( // administrator — which is the fail-closed answer the boot-side backstop in // `plugin-security` announces at startup. const configConfersPlatformAdmin = - platformAdminConfig.emails.length > 0 + !agentAccount + && platformAdminConfig.emails.length > 0 && matchesConfiguredPlatformAdmin(await getUserRow(), platformAdminConfig); if (configConfersPlatformAdmin) { // [Choice 6A] The capability CONTENT comes from the one declaration in @@ -2299,6 +2347,12 @@ export async function resolveUserAuthzGrants( // fail-closed line (`plugin-security/src/bootstrap-platform-admin.ts`), which is // where an operator can act on it, not inside the per-request authorization path. + // [ADR-0151 D3] An AI service account carries no system permission, from + // any set it holds: an action gated by one is closed to it until a decision + // widens the agent ceiling. The sets themselves stay on `permissions` and are + // clamped where they are evaluated. + if (agentAccount) grants.systemPermissions = []; + // 6c. Project the derived platform_admin built-in role (leads the list). if (hasPlatformAdminGrant && !grants.positions.includes(BUILTIN_IDENTITY_PLATFORM_ADMIN)) { grants.positions.unshift(BUILTIN_IDENTITY_PLATFORM_ADMIN); @@ -2324,7 +2378,8 @@ export async function resolveUserAuthzGrants( isPlatformAdmin: hasPlatformAdminGrant, // [ADR-0105 D4] Either org-admin capability set resolves the rung — the // wall-less variant differs only by withholding the superuser bits. - isTenantAdmin: ORGANIZATION_ADMIN_GRANTS.some((n: string) => grants.permissions.includes(n)), + // [ADR-0151 D3] Never for an AI service account, whatever it holds. + isTenantAdmin: !agentAccount && ORGANIZATION_ADMIN_GRANTS.some((n: string) => grants.permissions.includes(n)), isExternal: external, }); if (external) grants.audience = 'external'; diff --git a/packages/core/src/security/resolve-user-grants-cache.test.ts b/packages/core/src/security/resolve-user-grants-cache.test.ts index 4e5c34febbf..744457fe830 100644 --- a/packages/core/src/security/resolve-user-grants-cache.test.ts +++ b/packages/core/src/security/resolve-user-grants-cache.test.ts @@ -432,7 +432,7 @@ describe("pin 4 — user X's envelope changes when user Y's sys_member row is wr // ── Pin 5 — seed isolation (#11633 B.2) ───────────────────────────────────── describe('pin 5 — seeds are part of the answer, so seeds are part of the key', () => { - it('different seedPermissions never see each other, ordering holds, and the suppressed sys_user read stays suppressed', async () => { + it('different seedPermissions never see each other, ordering holds, and the sys_user read is one per real resolution', async () => { cacheOn(); const ql = makeSeamQl(adminTables()); const seedsA: ResolveUserAuthzGrantsOptions = { @@ -460,12 +460,15 @@ describe('pin 5 — seeds are part of the answer, so seeds are part of the key', const a2 = await resolveExpectingZeroReads(ql, 'u1', seedsA); expect(a2).toEqual(a1); - // The seeded-API-key path's SUPPRESSED `sys_user` read is preserved in the - // query multiset: email + ai_seat are seeded and no platform admins are - // declared, so NO resolution in this test may touch `sys_user` (#11633 - // B.2's query-multiset half — the reason the seedless-envelope option was - // rejected; see the cache module's keying doc). - expect(ql.calls.every((c) => c.object !== 'sys_user')).toBe(true); + // The seeded-API-key path's `sys_user` read: [ADR-0151 D3] forced edit — + // it used to be SUPPRESSED here (email + ai_seat seeded, no platform admins + // declared, so no resolution touched `sys_user`). The row's + // `principal_kind` now decides whether the principal is an AI service + // account, which no seed carries, so each REAL resolution reads it once — + // A's and B's — and the cache hit reads nothing (asserted above). The + // query-multiset half of #11633 B.2 still holds: seeds never stand in for + // a read the resolution needs, and a hit never repeats one. + expect(ql.calls.filter((c) => c.object === 'sys_user')).toHaveLength(2); }); }); diff --git a/packages/mcp/src/__tests__/stdio-agent-account.test.ts b/packages/mcp/src/__tests__/stdio-agent-account.test.ts new file mode 100644 index 00000000000..37f3d084dfd --- /dev/null +++ b/packages/mcp/src/__tests__/stdio-agent-account.test.ts @@ -0,0 +1,139 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0151 D3] Over stdio (`OS_MCP_STDIO_API_KEY`, ADR-0101), an AI service +// account's key admits the ACCOUNT as the subject: the context the stdio +// record reader hands the data engine carries `userId` the account, +// `principalKind: 'agent'`, no `onBehalfOf` and no system permission. +// +// Unlike `plugin-execution-context.test.ts`, nothing in `@objectstack/core` is +// mocked here: the REAL `resolveAuthzContext` (key admission, then the grants +// resolver reading the account's `sys_user` row) and the REAL shared assembler +// run over a table double, so the kind is read where production reads it. +// CONTROL: a person's key through the same face is unchanged. + +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; +import { hashApiKey } from '@objectstack/core'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { MCPServerPlugin } from '../plugin.js'; +import { MCPServerRuntime } from '../mcp-server-runtime.js'; + +const FUTURE = '2999-01-01T00:00:00Z'; +const BOT_KEY = 'osk_31739_stdio_account'; +const MIA_KEY = 'osk_31739_stdio_person'; + +const TABLES: Record[]> = { + sys_api_key: [ + { id: 'k_bot', key: hashApiKey(BOT_KEY), revoked: false, user_id: 'u_bot', expires_at: FUTURE, active_organization_id: 'org_a' }, + { id: 'k_mia', key: hashApiKey(MIA_KEY), revoked: false, user_id: 'u_mia', expires_at: FUTURE, active_organization_id: 'org_a' }, + ], + sys_user: [ + { id: 'u_bot', email: 'bot@agents.invalid', principal_kind: 'agent', accountable_user_id: 'u_mia' }, + { id: 'u_mia', email: 'mia@example.com', principal_kind: 'human' }, + ], + sys_member: [ + { user_id: 'u_bot', organization_id: 'org_a', role: 'member' }, + { user_id: 'u_mia', organization_id: 'org_a', role: 'member' }, + ], +}; + +interface FindCall { + object: string; + options: { context?: ExecutionContext; where?: Record }; +} + +function createHarness() { + const finds: FindCall[] = []; + const ql = { + find: vi.fn(async (object: string, options: FindCall['options']) => { + finds.push({ object, options }); + const rows = TABLES[object]; + if (!rows) return object.startsWith('sys_') ? [] : [{ id: 'r_1', name: 'Acme' }]; + const where = options?.where ?? {}; + return rows.filter((row) => Object.entries(where).every(([k, v]) => row[k] === v)); + }), + }; + const metadata = { + listObjects: vi.fn(async () => []), + getObject: vi.fn(async () => null), + get: vi.fn(async () => null), + list: vi.fn(async () => []), + exists: vi.fn(async () => false), + getRegisteredTypes: vi.fn(async () => ['object']), + register: vi.fn(), + unregister: vi.fn(), + }; + const services: Record = { objectql: ql, metadata, settings: { get: vi.fn(async () => undefined) } }; + const ctx = { + registerService: vi.fn(), + getService: vi.fn((name: string) => { + if (!(name in services)) throw new Error(`Service "${name}" not found`); + return services[name]; + }), + replaceService: vi.fn(), + getServices: vi.fn(() => new Map(Object.entries(services))), + hook: vi.fn(), + trigger: vi.fn(async () => {}), + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + getKernel: vi.fn(() => ({})), + }; + return { ctx, finds }; +} + +/** Start the plugin on the stdio path and hand back the principal-bound record reader (transport stubbed). */ +async function startStdio(ctx: unknown) { + let getRecord: ((object: string, id: string) => Promise | null>) | undefined; + const bridgeResources = vi + .spyOn(MCPServerRuntime.prototype, 'bridgeResources') + .mockImplementation((_meta: unknown, reader?: unknown) => { + getRecord = reader as typeof getRecord; + }); + const bridgePrompts = vi.spyOn(MCPServerRuntime.prototype, 'bridgePrompts').mockImplementation(async () => {}); + const start = vi.spyOn(MCPServerRuntime.prototype, 'start').mockImplementation(async () => {}); + try { + const plugin = new MCPServerPlugin({ autoStart: true }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + } finally { + bridgeResources.mockRestore(); + bridgePrompts.mockRestore(); + start.mockRestore(); + } + if (!getRecord) throw new Error('stdio start registered no record reader'); + return getRecord; +} + +/** The context the stdio face handed the engine for one record read with `key`. */ +async function contextFor(key: string): Promise { + process.env.OS_MCP_STDIO_API_KEY = key; + const { ctx, finds } = createHarness(); + const getRecord = await startStdio(ctx); + await getRecord('crm_account', 'r_1'); + const read = finds.filter((f) => f.object === 'crm_account').at(-1); + if (!read?.options.context) throw new Error('the record read carried no context'); + return read.options.context; +} + +describe('[ADR-0151 D3] stdio: an AI service account\'s key admits the account itself', () => { + const originalEnv = { ...process.env }; + beforeEach(() => { process.env = { ...originalEnv }; }); + afterEach(() => { process.env = { ...originalEnv }; }); + + it('userId is the account, principalKind agent, no onBehalfOf, no system permission, no everyone anchor', async () => { + const context = await contextFor(BOT_KEY); + expect(context.userId).toBe('u_bot'); + expect(context.principalKind).toBe('agent'); + expect(context.onBehalfOf).toBeUndefined(); + expect(Object.keys(context)).not.toContain('onBehalfOf'); + expect(context.systemPermissions).toEqual([]); + expect(context.positions).not.toContain('everyone'); + expect(context.isSystem).toBe(false); + }); + + it('CONTROL: a person\'s key through the same face is a human principal, with the everyone anchor', async () => { + const context = await contextFor(MIA_KEY); + expect(context.userId).toBe('u_mia'); + expect(context.principalKind).toBe('human'); + expect(context.onBehalfOf).toBeUndefined(); + expect(context.positions).toContain('everyone'); + }); +}); diff --git a/packages/mcp/src/plugin.ts b/packages/mcp/src/plugin.ts index bc4a18eeacb..e56131a4c8f 100644 --- a/packages/mcp/src/plugin.ts +++ b/packages/mcp/src/plugin.ts @@ -284,8 +284,10 @@ async function resolveStdioExecutionContext( authz, // OAuth access tokens are honoured on the `/mcp` HTTP door alone // (`acceptOAuthAccessToken`); a stdio process presents an API key, never a - // bearer, so `principalKind: 'agent'`, `onBehalfOf` and `oauthScopes` are - // not representable here. + // bearer, so an OAuth-delegated agent (`onBehalfOf`, `oauthScopes`) is not + // representable here. [ADR-0151 D3] An AI service account's key is: the + // assembler stamps it `principalKind: 'agent'` from the account's row, with + // no `onBehalfOf`. oauth: undefined, localization, // No request to carry a locale preference: a long-lived stdio transport has diff --git a/packages/objectql/src/engine-scoped-context.ts b/packages/objectql/src/engine-scoped-context.ts index d016f342ac0..3b8c57a7f2f 100644 --- a/packages/objectql/src/engine-scoped-context.ts +++ b/packages/objectql/src/engine-scoped-context.ts @@ -144,6 +144,9 @@ export class ScopedContextFacet { return this.derive({ ...ctx, ...(needsGrants ? { positions: grants.positions, permissions: grants.permissions } : {}), + // [ADR-0151 D3] An AI service account is the agent principal of its own + // calls, holding no system permission. + ...(needsGrants && grants.principalKind ? { principalKind: grants.principalKind, systemPermissions: [] } : {}), ...(needsPeers ? { org_user_ids: grants.org_user_ids } : {}), ...(needsEmail && grants.email ? { email: grants.email } : {}), }); diff --git a/packages/plugins/plugin-audit/src/comment-access-hooks.ts b/packages/plugins/plugin-audit/src/comment-access-hooks.ts index e4c534f7b3c..06a7f81ea75 100644 --- a/packages/plugins/plugin-audit/src/comment-access-hooks.ts +++ b/packages/plugins/plugin-audit/src/comment-access-hooks.ts @@ -666,7 +666,11 @@ function asIdList(id: unknown): Array | null { * `principalKind === 'agent'`; stripped, the additive human baseline * (`member_default`) was appended to an agent's ceiling on this path, so * the sets the bypass probe evaluated were a SUPERSET of what the user - * consented to. + * consented to. The same key carries an AI service account (ADR-0151 + * D3: `principalKind: 'agent'`, no `onBehalfOf`), whose grants are its + * own assignments under the agent ceiling, with no member baseline: + * stripped, it would read as a person and gain the baseline and lose + * the ceiling clamp. * * `systemPermissions`, `accessible_org_ids`, `posture`, `audience` and * `rlsMembership` were dropped by the same projection; they are forwarded diff --git a/packages/plugins/plugin-audit/src/mention-recipient-gate.ts b/packages/plugins/plugin-audit/src/mention-recipient-gate.ts index fd1fb8ee6eb..38f1376e3c6 100644 --- a/packages/plugins/plugin-audit/src/mention-recipient-gate.ts +++ b/packages/plugins/plugin-audit/src/mention-recipient-gate.ts @@ -263,6 +263,8 @@ async function contextForMentionedUser( ...(grants.tabPermissions ? { tabPermissions: grants.tabPermissions } : {}), ...(grants.posture ? { posture: grants.posture } : {}), ...(grants.email ? { email: grants.email } : {}), + // [ADR-0151 D3] An AI service account is judged as the agent it is. + ...(grants.principalKind ? { principalKind: grants.principalKind } : {}), }; } diff --git a/packages/plugins/plugin-auth/src/last-admin-guard.ts b/packages/plugins/plugin-auth/src/last-admin-guard.ts index d81a913366d..5a85a85d10b 100644 --- a/packages/plugins/plugin-auth/src/last-admin-guard.ts +++ b/packages/plugins/plugin-auth/src/last-admin-guard.ts @@ -961,6 +961,15 @@ export const STANDING_KEY_EXCLUSIONS: Readonly { + vi.restoreAllMocks(); + while (engines.length) { + try { await engines.pop()?.destroy(); } catch { /* noop */ } + } +}); + +async function boot() { + const engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), true); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.agent-account-grant-refusal', + name: 'Agent account grant refusal', + version: '1.0.0', + type: 'plugin', + scope: 'system', + objects: [SysUserPermissionSet, SysUserPosition], + } as any); + await engine.syncSchemas(); + if (!engine.registry.getObject(SysUser.name)) engine.registry.registerObject(SysUser as never, 'qa.agent-account'); + await engine.syncObjectSchema('sys_user'); + // The account and two people, written as the system (no sign-in plugin is + // composed here, so no registration door judges the account row). + await engine.insert('sys_user', { id: 'u_bot', name: 'Bot', email: 'bot@agents.invalid', principal_kind: 'agent', accountable_user_id: 'u_person' }, { context: SYS }); + for (const id of ['u_person', 'u_platform']) { + await engine.insert('sys_user', { id, name: id, email: `${id}@example.test` }, { context: SYS }); + } + engines.push(engine); + + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => (type === 'position' ? null : engine.getSchema(name)) ?? null, + list: async (type: string) => (type === 'position' ? [] : [MEMBER_DEFAULT, QA_ADMIN]), + }, + }; + const ctx: any = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + hook: vi.fn(), + registerService: vi.fn(), + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); + await plugin.init(ctx); + await plugin.start(ctx); + vi.spyOn((engine as any).logger, 'warn').mockImplementation(() => undefined); + + // The security catalog (the registry): the two sets and the two positions. + engine.registry.registerItem('permission', { name: SAFE_SET, label: SAFE_SET, objects: { crm_lead: { allowRead: true, allowEdit: true } } } as any, 'name' as any, 'qa.agent-account'); + engine.registry.registerItem('permission', { + name: BREACHING_SET, + label: BREACHING_SET, + objects: { crm_lead: { allowRead: true, viewAllRecords: true, allowTransfer: true } }, + systemPermissions: ['manage_users'], + } as any, 'name' as any, 'qa.agent-account'); + engine.registry.registerItem('position', { name: SAFE_POSITION, label: SAFE_POSITION, permissionSets: [SAFE_SET] } as any, 'name' as any, 'qa.agent-account'); + engine.registry.registerItem('position', { name: BREACHING_POSITION, label: BREACHING_POSITION, permissionSets: [SAFE_SET, BREACHING_SET] } as any, 'name' as any, 'qa.agent-account'); + return { engine, plugin, ctx }; +} + +type Harness = Awaited>; + +async function refusalOf(run: () => Promise): Promise { + try { + await run(); + } catch (e) { + return e; + } + throw new Error('expected the write to be refused, but it succeeded'); +} + +function envelopeOf(e: unknown) { + const r = resolveThrownHttpError(e); + return { status: r.status, code: r.code, message: r.message, fields: (r.details?.fields ?? []) as any[] }; +} + +function expectAccountRefusal(err: unknown, field: 'permission_set' | 'position', value: string) { + const env = envelopeOf(err); + expect(env.status).toBe(400); + expect(env.code).toBe('VALIDATION_FAILED'); + expect(env.fields).toHaveLength(1); + expect(env.fields[0]).toMatchObject({ field, code: 'invalid_value', value, constraint: { principalKind: 'agent' } }); + return env; +} + +const rows = async (h: Harness, object: string, where: Record) => + ((await h.engine.find(object, { where, context: SYS })) as any[]) ?? []; + +const grant = (h: Harness, userId: string, setName: string) => + h.engine.insert('sys_user_permission_set', { user_id: userId, permission_set: setName }, { context: PLATFORM_ADMIN } as any); + +const assign = (h: Harness, userId: string, position: string) => + h.engine.insert('sys_user_position', { user_id: userId, position }, { context: PLATFORM_ADMIN } as any); + +describe('[ADR-0151 D3] a set above the agent ceiling is refused for an AI service account, by name', () => { + it('a direct grant of the breaching set to the account is refused, naming the set and what in it breaches, and nothing is stored', async () => { + const h = await boot(); + const err = await refusalOf(() => grant(h, 'u_bot', BREACHING_SET)); + const env = expectAccountRefusal(err, 'permission_set', BREACHING_SET); + expect(env.fields[0].message).toBe(agentAccountSetGrantMessage(BREACHING_SET, 'u_bot', [ + 'objects.crm_lead.viewAllRecords', 'objects.crm_lead.allowTransfer', 'systemPermissions', + ])); + expect(env.fields[0].message).toContain(`'${BREACHING_SET}'`); + expect(await rows(h, 'sys_user_permission_set', { user_id: 'u_bot' })).toHaveLength(0); + }); + + it('a position binding the breaching set is refused for the account at `position`, naming the set, and nothing is stored', async () => { + const h = await boot(); + const err = await refusalOf(() => assign(h, 'u_bot', BREACHING_POSITION)); + const env = expectAccountRefusal(err, 'position', BREACHING_POSITION); + expect(env.fields[0].message).toContain(`'${BREACHING_SET}'`); + expect(env.fields[0].message).not.toContain(`'${SAFE_SET}'`); + expect(await rows(h, 'sys_user_position', { user_id: 'u_bot' })).toHaveLength(0); + }); + + it('an update that would leave the account holding the breaching set is refused, and the stored grant is unchanged', async () => { + const h = await boot(); + const created: any = await grant(h, 'u_bot', SAFE_SET); + const err = await refusalOf(() => h.engine.update( + 'sys_user_permission_set', { id: created.id, permission_set: BREACHING_SET }, { context: PLATFORM_ADMIN } as any, + )); + expectAccountRefusal(err, 'permission_set', BREACHING_SET); + const [stored] = await rows(h, 'sys_user_permission_set', { user_id: 'u_bot' }); + expect(stored?.permission_set).toBe(SAFE_SET); + }); + + it('moving a person\'s breaching grant onto the account is refused too', async () => { + const h = await boot(); + const created: any = await grant(h, 'u_person', BREACHING_SET); + const err = await refusalOf(() => h.engine.update( + 'sys_user_permission_set', { id: created.id, user_id: 'u_bot' }, { context: PLATFORM_ADMIN } as any, + )); + expectAccountRefusal(err, 'permission_set', BREACHING_SET); + expect(await rows(h, 'sys_user_permission_set', { user_id: 'u_bot' })).toHaveLength(0); + }); + + it('positive: a set and a position within the ceiling are assigned to the account and stored', async () => { + const h = await boot(); + await grant(h, 'u_bot', SAFE_SET); + await assign(h, 'u_bot', SAFE_POSITION); + expect((await rows(h, 'sys_user_permission_set', { user_id: 'u_bot' })).map((r) => r.permission_set)).toEqual([SAFE_SET]); + expect((await rows(h, 'sys_user_position', { user_id: 'u_bot' })).map((r) => r.position)).toEqual([SAFE_POSITION]); + }); + + it('CONTROL: a person is assigned the breaching set and the breaching position, as before', async () => { + const h = await boot(); + await grant(h, 'u_person', BREACHING_SET); + await assign(h, 'u_person', BREACHING_POSITION); + expect((await rows(h, 'sys_user_permission_set', { user_id: 'u_person' })).map((r) => r.permission_set)).toEqual([BREACHING_SET]); + expect((await rows(h, 'sys_user_position', { user_id: 'u_person' })).map((r) => r.position)).toEqual([BREACHING_POSITION]); + }); + + it('a system write stands down, as on the sibling refusals', async () => { + const h = await boot(); + await h.engine.insert('sys_user_permission_set', { user_id: 'u_bot', permission_set: BREACHING_SET, organization_id: ORG }, { context: { ...SYS, tenantId: ORG } }); + expect(await rows(h, 'sys_user_permission_set', { user_id: 'u_bot' })).toHaveLength(1); + }); + + it('binds once, and says so when the engine has no hook registry', () => { + const registerHook = vi.fn(); + const unregisterHooksByPackage = vi.fn(); + expect(registerAgentAccountGrantRefusal({ registerHook, unregisterHooksByPackage })).toBe(true); + expect(unregisterHooksByPackage).toHaveBeenCalledWith(AGENT_ACCOUNT_GRANT_HOOK_PACKAGE); + expect(registerHook.mock.calls.map((c) => c[0])).toEqual(['beforeInsert', 'beforeUpdate']); + const warn = vi.fn(); + expect(registerAgentAccountGrantRefusal({}, { warn })).toBe(false); + expect(warn.mock.calls[0]?.[0]).toContain('is NOT refused'); + }); +}); diff --git a/packages/plugins/plugin-security/src/agent-account-grant-refusal.ts b/packages/plugins/plugin-security/src/agent-account-grant-refusal.ts new file mode 100644 index 00000000000..310b282786f --- /dev/null +++ b/packages/plugins/plugin-security/src/agent-account-grant-refusal.ts @@ -0,0 +1,307 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0151 D3] An AI service account is never assigned a permission set that + * breaches the agent ceiling: the write-path refusal for a + * `sys_user_permission_set` or `sys_user_position` row whose holder is an + * account and whose set — or a set its position binds — carries View All, + * Modify All, the destructive class, a system permission or an admin scope. + * + * ## Why a refusal, when the clamp already holds + * + * The guarantee is the clamp at evaluation (`agent-ceiling-clamp.ts`): every + * set an agent principal holds is read under the ceiling, so a set edited + * after it was assigned still grants nothing above it. This is the loud, + * early answer ADR-0151 D3 asks for besides: the administrator who assigns + * such a set learns, by the set's name and the bits that breach, that the + * account will never receive them — instead of an assignment that silently + * grants less than it says. + * + * ## Which rows it judges + * + * - `sys_user_permission_set`: the set the row holds AFTER the write (the + * payload's `permission_set`, else the stored one), read the way every + * by-name grant reader reads it (`grantSetNameOf`); + * - `sys_user_position`: every set the position the row holds after the + * write binds in its catalog definition. + * + * For an INSERT (one dispatch per row) and an UPDATE (one dispatch per + * matched row, with that row's stored image as `previous`). The holder is the + * row's `user_id` after the write; only a holder whose `sys_user` row reads + * `principal_kind = agent` is judged. A person's grant is never judged here, + * so no existing write is narrowed. A DELETE is never judged. + * + * It stands down on every `isSystem` write, the stand-down its sibling + * refusals on these tables take, and on a value the catalog holds no + * definition for (the catalog refusals answer that). + * + * ## Reads, and what a failed one does + * + * One `sys_user` read per judged row, by id, under the system context in the + * writer's transaction; a read that throws propagates, as the membership + * refusal's does. The set and position definitions come from the security + * catalog bound to the engine (`securityCatalogReaderOf`, the reader every + * grant refusal asks). A catalog read that throws is reported at `warn` and + * the write proceeds unjudged: the clamp still holds. + * + * ## Where it runs + * + * As `beforeInsert` / `beforeUpdate` engine hooks, inside the security + * middleware, at priority 45: after the agent ceiling set refusal (35) and + * the holder's membership (40), so a row refused for those is refused for + * them first. + * + * ## The envelope + * + * `400 VALIDATION_FAILED` (`validationFailure`) with one `fields[]` entry, + * `code: 'invalid_value'`, at `permission_set` or `position`. No new error + * code (ADR-0112). + */ + +import { isAgentAccountRow, securityCatalogReaderOf, type SecurityCatalogReader } from '@objectstack/core'; +import type { FieldErrorCode } from '@objectstack/spec/api'; +import { classifyFilterToken, isPlainRecord } from '@objectstack/spec/data'; +import { validationFailure } from '@objectstack/types'; +import { agentCeilingBreaches } from './agent-ceiling-clamp.js'; +import { GRANT_OBJECT, GRANT_SET_NAME_FIELD, grantSetNameOf } from './grant-permission-set-name.js'; +import { POSITION_ASSIGNMENT_OBJECT, POSITION_FIELD } from './position-catalog-refusal.js'; +import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; +import { SysUserPosition } from './objects/sys-user-position.object.js'; + +/** The `packageId` both hooks register under, so they bind (and re-bind) as one. */ +export const AGENT_ACCOUNT_GRANT_HOOK_PACKAGE = 'plugin-security:agent-account-grant'; + +/** See the module note, "Where it runs". */ +const HOOK_PRIORITY = 45; + +const HOLDER_FIELD = 'user_id'; +const USER_OBJECT = 'sys_user'; + +/** The grant objects judged, each with the column its refusal is at. */ +const JUDGED_OBJECTS: readonly string[] = [GRANT_OBJECT, POSITION_ASSIGNMENT_OBJECT]; + +function labelOf(schema: unknown, field: string, fallback: string): string { + const def = (schema as any)?.fields?.[field]; + return typeof def?.label === 'string' ? def.label : fallback; +} + +const SET_LABEL = labelOf(SysUserPermissionSet, GRANT_SET_NAME_FIELD, 'Permission Set'); +const POSITION_LABEL = labelOf(SysUserPosition, POSITION_FIELD, 'Position'); + +/** One set that breaches the ceiling, with what in it does. */ +export interface AgentAccountBreachingSet { + name: string; + breaches: string[]; +} + +/** One `fields[]` entry of the refusal, typed to the closed ADR-0114 catalog. */ +interface AgentAccountFieldError { + field: string; + code: FieldErrorCode; + message: string; + label: string; + value: string; + constraint: { principalKind: 'agent' }; +} + +const describe = (sets: readonly AgentAccountBreachingSet[]): string => + sets.map((s) => `'${s.name}' (${s.breaches.join(', ')})`).join('; '); + +/** The sentence an administrator reads for a direct set grant. */ +export function agentAccountSetGrantMessage(setName: string, userId: string, breaches: readonly string[]): string { + return ( + `${SET_LABEL}: '${setName}' cannot be assigned to '${userId}', an AI service account. An AI service account ` + + `never holds View All, Modify All, transfer, restore or purge, a system permission or an admin scope, ` + + `whatever its permission sets say, and '${setName}' carries ${breaches.join(', ')}. Choose a permission set ` + + `without them, or remove them from '${setName}' first.` + ); +} + +/** The sentence an administrator reads for a position assignment. */ +export function agentAccountPositionGrantMessage( + position: string, + userId: string, + sets: readonly AgentAccountBreachingSet[], +): string { + return ( + `${POSITION_LABEL}: '${position}' cannot be assigned to '${userId}', an AI service account. An AI service ` + + `account never holds View All, Modify All, transfer, restore or purge, a system permission or an admin ` + + `scope, whatever its permission sets say, and position '${position}' grants ${describe(sets)}. Choose a ` + + `position without them, or assign the account the permission sets it needs directly.` + ); +} + +/** The refusal of a direct set grant: `invalid_value` at `permission_set`. */ +export function agentAccountSetGrantError(setName: string, userId: string, breaches: readonly string[]): Error { + const message = agentAccountSetGrantMessage(setName, userId, breaches); + const entry: AgentAccountFieldError = { + field: GRANT_SET_NAME_FIELD, + code: 'invalid_value', + message, + label: SET_LABEL, + value: setName, + constraint: { principalKind: 'agent' }, + }; + return validationFailure(message, [entry]); +} + +/** The refusal of a position assignment: `invalid_value` at `position`. */ +export function agentAccountPositionGrantError( + position: string, + userId: string, + sets: readonly AgentAccountBreachingSet[], +): Error { + const message = agentAccountPositionGrantMessage(position, userId, sets); + const entry: AgentAccountFieldError = { + field: POSITION_FIELD, + code: 'invalid_value', + message, + label: POSITION_LABEL, + value: position, + constraint: { principalKind: 'agent' }, + }; + return validationFailure(message, [entry]); +} + +interface AgentAccountGrantEngine { + registerHook?: ( + event: string, + handler: (ctx: any) => void | Promise, + options?: { object?: string | string[]; priority?: number; packageId?: string }, + ) => void; + unregisterHooksByPackage?: (packageId: string) => number; + find?: (object: string, query: any) => Promise; +} + +type Logger = { warn?: (msg: string, meta?: any) => void } | undefined; + +const hasOwn = (o: object, k: string): boolean => Object.prototype.hasOwnProperty.call(o, k); + +function idOf(value: unknown): string | undefined { + let key: string | undefined; + if (typeof value === 'string') key = value; + else if (typeof value === 'number' && Number.isFinite(value)) key = String(value); + if (key === undefined || key.trim() === '') return undefined; + return key; +} + +function nameOf(value: unknown): string | undefined { + return typeof value === 'string' && value.trim() !== '' ? value.trim() : undefined; +} + +/** Is `userId` an AI service account? One `sys_user` read by id, in the writer's transaction. Throws when it fails. */ +async function isAgentAccount(engine: AgentAccountGrantEngine, userId: string, transaction: unknown): Promise { + if (typeof engine.find !== 'function') return false; + const context: Record = { isSystem: true }; + if (transaction !== undefined) context.transaction = transaction; + // A placeholder-shaped id is compared literally, as the membership refusal compares it. + const literal = classifyFilterToken(userId) === null ? userId : { $startsWith: userId.charAt(0) }; + const rows = await engine.find(USER_OBJECT, { where: { id: literal }, limit: 2, context }); + return Array.isArray(rows) && rows.some((r: any) => String(r?.id) === userId && isAgentAccountRow(r)); +} + +/** The ceiling breaches of the set `name`, per its catalog definition; `[]` when the catalog holds none. */ +async function setBreaches(catalog: SecurityCatalogReader, name: string): Promise { + const entry = await catalog.resolve('permission', name); + return entry ? agentCeilingBreaches(entry.definition) : []; +} + +/** The sets the position `name` binds that breach the ceiling, per the catalog definitions. */ +async function positionBreachingSets(catalog: SecurityCatalogReader, name: string): Promise { + const entry = await catalog.resolve('position', name); + const bound = Array.isArray(entry?.definition?.permissionSets) ? entry!.definition.permissionSets : []; + const out: AgentAccountBreachingSet[] = []; + for (const setName of new Set(bound.filter((n): n is string => typeof n === 'string' && n !== ''))) { + const breaches = await setBreaches(catalog, setName); + if (breaches.length > 0) out.push({ name: setName, breaches }); + } + return out; +} + +/** Judge one row image: the holder and the value it holds after the write. */ +async function judge( + engine: AgentAccountGrantEngine, + ctx: any, + image: Record, + logger: Logger, +): Promise { + const userId = idOf(image[HOLDER_FIELD]); + if (userId === undefined) return; + const isGrant = ctx.object === GRANT_OBJECT; + const value = isGrant ? grantSetNameOf(image) : nameOf(image[POSITION_FIELD]); + if (value === undefined) return; + const catalog = securityCatalogReaderOf(engine); + if (!catalog) return; + if (!(await isAgentAccount(engine, userId, ctx?.transaction))) return; + let breaching: AgentAccountBreachingSet[]; + try { + breaching = isGrant + ? [{ name: value, breaches: await setBreaches(catalog, value) }].filter((s) => s.breaches.length > 0) + : await positionBreachingSets(catalog, value); + } catch (e) { + logger?.warn?.( + `[security] the security catalog could not be read, so a ${ctx.object} write for an AI service account was ` + + 'NOT checked against the agent ceiling — it proceeds; the ceiling is still held when its sets are evaluated', + { object: ctx.object, error: (e as Error)?.message ?? String(e) }, + ); + return; + } + if (breaching.length === 0) return; + if (isGrant) throw agentAccountSetGrantError(value, userId, breaching[0]!.breaches); + throw agentAccountPositionGrantError(value, userId, breaching); +} + +/** `beforeInsert`: one dispatch per row, handed the caller's row as sent. */ +async function onInsert(engine: AgentAccountGrantEngine, ctx: any, logger: Logger): Promise { + if (!JUDGED_OBJECTS.includes(ctx?.object) || ctx?.session?.isSystem === true) return; + const row = ctx?.input?.data; + if (!isPlainRecord(row)) return; + await judge(engine, ctx, row as Record, logger); +} + +/** `beforeUpdate`: one dispatch per matched row, `previous` bound on both dispatch paths. */ +async function onUpdate(engine: AgentAccountGrantEngine, ctx: any, logger: Logger): Promise { + if (!JUDGED_OBJECTS.includes(ctx?.object) || ctx?.session?.isSystem === true) return; + const data = ctx?.input?.data; + if (!isPlainRecord(data)) return; + const previous = isPlainRecord(ctx?.previous) ? (ctx.previous as Record) : {}; + const valueField = ctx.object === GRANT_OBJECT ? GRANT_SET_NAME_FIELD : POSITION_FIELD; + const image: Record = { + [HOLDER_FIELD]: hasOwn(data, HOLDER_FIELD) ? (data as any)[HOLDER_FIELD] : previous[HOLDER_FIELD], + [valueField]: hasOwn(data, valueField) ? (data as any)[valueField] : previous[valueField], + }; + await judge(engine, ctx, image, logger); +} + +/** + * Bind both hooks on the engine — idempotently: a re-run of the plugin's + * `start()` on the same engine replaces the binding instead of doubling it. + * Returns `false`, after saying so at `warn`, when the engine exposes no hook + * registry (a test double): the refusal is then not in force, and the clamp + * at evaluation still is. + */ +export function registerAgentAccountGrantRefusal( + engine: AgentAccountGrantEngine | null | undefined, + logger?: Logger, +): boolean { + if (!engine || typeof engine.registerHook !== 'function') { + logger?.warn?.( + `[security] the ObjectQL engine exposes no hook registry — a ${JUDGED_OBJECTS.join(' / ')} write giving an ` + + 'AI service account a set above the agent ceiling is NOT refused (the ceiling is still held at evaluation)', + ); + return false; + } + engine.unregisterHooksByPackage?.(AGENT_ACCOUNT_GRANT_HOOK_PACKAGE); + const object = [...JUDGED_OBJECTS]; + engine.registerHook('beforeInsert', (ctx: any) => onInsert(engine, ctx, logger), { + object, + priority: HOOK_PRIORITY, + packageId: AGENT_ACCOUNT_GRANT_HOOK_PACKAGE, + }); + engine.registerHook('beforeUpdate', (ctx: any) => onUpdate(engine, ctx, logger), { + object, + priority: HOOK_PRIORITY, + packageId: AGENT_ACCOUNT_GRANT_HOOK_PACKAGE, + }); + return true; +} diff --git a/packages/plugins/plugin-security/src/agent-ceiling-clamp.test.ts b/packages/plugins/plugin-security/src/agent-ceiling-clamp.test.ts new file mode 100644 index 00000000000..43dd8041c81 --- /dev/null +++ b/packages/plugins/plugin-security/src/agent-ceiling-clamp.test.ts @@ -0,0 +1,172 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0151 D3] The agent ceiling at evaluation: what the clamp clears, what + * it leaves, that it never mutates a set it is handed, that the first-party + * OAuth ceiling sets are untouched by it (the OAuth CONTROL, measured), and + * that the security plugin applies it to every agent principal's sets and to + * no person's. + */ + +import { describe, it, expect, vi } from 'vitest'; +import type { PermissionSet } from '@objectstack/spec/security'; +import { MCP_AGENT_PERMISSION_SETS, MCP_AGENT_PERMISSION_SET_RESTRICTED } from '@objectstack/spec/ai'; + +import { + AGENT_CEILING_OBJECT_KEYS, + agentCeilingBreaches, + clampPermissionSetToAgentCeiling, + clampPermissionSetsToAgentCeiling, +} from './agent-ceiling-clamp.js'; +import { DESTRUCTIVE_CLASS_KEYS } from './permission-evaluator.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; +import { SecurityPlugin } from './security-plugin.js'; + +/** Every bit the ceiling forbids, on one object and on the wildcard, plus a system permission and an admin scope. */ +const BREACHING = { + name: 'ops_super', + label: 'Ops superuser', + objects: { + crm_lead: { + allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, allowExport: true, + viewAllRecords: true, modifyAllRecords: true, + allowTransfer: true, allowRestoreOwnDeleted: true, manageRecycleBin: true, + readScope: 'org', writeScope: 'own', + }, + '*': { allowRead: true, viewAllRecords: true, modifyAllRecords: true }, + }, + fields: { 'crm_lead.ssn': { readable: false, editable: false } }, + systemPermissions: ['manage_users'], + adminScope: { businessUnit: 'bu_root', includeSubtree: true, manageAssignments: true, assignablePermissionSets: [] }, + tabPermissions: { crm_lead: 'visible' }, +} as unknown as PermissionSet; + +const CLEAN = { + name: 'lead_reader', + label: 'Lead reader', + objects: { crm_lead: { allowRead: true, allowEdit: true, readScope: 'own' } }, +} as unknown as PermissionSet; + +describe('agentCeilingBreaches / clampPermissionSetToAgentCeiling', () => { + it('the object bits it clears are the two bypass bits and the destructive class, derived from the evaluator', () => { + expect([...AGENT_CEILING_OBJECT_KEYS]).toEqual(['viewAllRecords', 'modifyAllRecords', ...DESTRUCTIVE_CLASS_KEYS]); + expect([...DESTRUCTIVE_CLASS_KEYS].sort()).toEqual(['allowRestoreOwnDeleted', 'allowTransfer', 'manageRecycleBin']); + }); + + it('names every breach, in a stable order', () => { + expect(agentCeilingBreaches(BREACHING)).toEqual([ + 'objects.crm_lead.viewAllRecords', + 'objects.crm_lead.modifyAllRecords', + 'objects.crm_lead.allowTransfer', + 'objects.crm_lead.allowRestoreOwnDeleted', + 'objects.crm_lead.manageRecycleBin', + 'objects.*.viewAllRecords', + 'objects.*.modifyAllRecords', + 'systemPermissions', + 'adminScope', + ]); + expect(agentCeilingBreaches(CLEAN)).toEqual([]); + }); + + it('reads the row spelling too: JSON-string columns, system_permissions and admin_scope', () => { + expect(agentCeilingBreaches({ + name: 'row', + objects: JSON.stringify({ t: { viewAllRecords: true } }), + system_permissions: JSON.stringify(['manage_users']), + admin_scope: JSON.stringify({ businessUnit: 'bu' }), + })).toEqual(['objects.t.viewAllRecords', 'systemPermissions', 'adminScope']); + expect(agentCeilingBreaches({ name: 'row', system_permissions: '[]', admin_scope: null })).toEqual([]); + }); + + it('clears exactly the breaching bits and leaves every ordinary grant as authored', () => { + const clamped = clampPermissionSetToAgentCeiling(BREACHING) as any; + expect(clamped.objects.crm_lead).toEqual({ + allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true, allowExport: true, + viewAllRecords: false, modifyAllRecords: false, + allowTransfer: false, allowRestoreOwnDeleted: false, manageRecycleBin: false, + readScope: 'org', writeScope: 'own', + }); + expect(clamped.objects['*']).toEqual({ allowRead: true, viewAllRecords: false, modifyAllRecords: false }); + expect(clamped.systemPermissions).toEqual([]); + expect('adminScope' in clamped).toBe(false); + expect(clamped.fields).toEqual((BREACHING as any).fields); + expect(clamped.tabPermissions).toEqual((BREACHING as any).tabPermissions); + expect(clamped.name).toBe('ops_super'); + expect(agentCeilingBreaches(clamped)).toEqual([]); + }); + + it('never mutates the set it is handed: a clean set comes back as the same object, a breaching one as a fresh copy', () => { + const before = JSON.stringify(BREACHING); + const clamped = clampPermissionSetToAgentCeiling(BREACHING); + expect(clamped).not.toBe(BREACHING); + expect(JSON.stringify(BREACHING)).toBe(before); + expect(clampPermissionSetToAgentCeiling(CLEAN)).toBe(CLEAN); + expect(clampPermissionSetsToAgentCeiling([CLEAN, BREACHING]).map((s) => s.name)).toEqual(['lead_reader', 'ops_super']); + }); + + it('MEASURED: the first-party OAuth agent ceiling sets carry nothing the clamp clears — 0 of 3 clamped', () => { + const ceilings = defaultPermissionSets.filter((s) => (MCP_AGENT_PERMISSION_SETS as readonly string[]).includes(s.name)); + expect(ceilings.map((s) => s.name).sort()).toEqual([...MCP_AGENT_PERMISSION_SETS].sort()); + const clampedCount = ceilings.filter((s) => agentCeilingBreaches(s).length > 0).length; + expect(clampedCount).toBe(0); + for (const s of ceilings) expect(clampPermissionSetToAgentCeiling(s)).toBe(s); + }); +}); + +describe('the security plugin reads every agent principal\'s sets under the ceiling, and no person\'s', () => { + async function plugin() { + const p = new SecurityPlugin({ fallbackPermissionSet: null }); + const services: Record = { + manifest: { register: vi.fn() }, + // An engine double: the middleware is registered and never driven here. + objectql: { registerMiddleware: vi.fn(), getSchema: () => undefined, find: async () => [], findOne: async () => null }, + metadata: { get: async () => null, list: async () => [BREACHING, CLEAN] }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: vi.fn(), + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + } as any; + await p.init(ctx); + await p.start(ctx); + return p as any; + } + + it('an AI service account (agent, no onBehalfOf): the breaching set is clamped, and the restricted floor is its baseline', async () => { + const p = await plugin(); + const sets: PermissionSet[] = await p.resolvePermissionSetsForContext({ + userId: 'u_bot', principalKind: 'agent', permissions: ['ops_super', 'lead_reader'], positions: ['org_member'], + }); + expect(sets.map((s) => s.name)).toEqual(['ops_super', 'lead_reader']); + for (const s of sets) expect(agentCeilingBreaches(s), s.name).toEqual([]); + expect(sets.map((s) => s.name)).not.toContain('member_default'); + }); + + it('an OAuth-delegated agent: the same clamp holds on its own side', async () => { + const p = await plugin(); + const sets: PermissionSet[] = await p.resolvePermissionSetsForContext({ + userId: 'u_mia', principalKind: 'agent', onBehalfOf: { userId: 'u_mia', principalKind: 'human' }, permissions: ['ops_super'], + }); + expect(sets.map((s) => s.name)).toEqual(['ops_super']); + expect(agentCeilingBreaches(sets[0])).toEqual([]); + }); + + it('an agent whose sets resolve nothing falls back to the restricted set, still under the ceiling', async () => { + const p = await plugin(); + const sets: PermissionSet[] = await p.resolvePermissionSetsForContext({ userId: 'u_bot', principalKind: 'agent', permissions: ['no_such_set'] }); + expect(sets.map((s) => s.name)).toEqual([MCP_AGENT_PERMISSION_SET_RESTRICTED]); + }); + + it('CONTROL: a person holding the same set keeps every bit of it', async () => { + const p = await plugin(); + const sets: PermissionSet[] = await p.resolvePermissionSetsForContext({ + userId: 'u_mia', principalKind: 'human', permissions: ['ops_super'], + }); + const held = sets.find((s) => s.name === 'ops_super'); + expect(held).toBe(BREACHING); + expect(agentCeilingBreaches(held)).toHaveLength(9); + }); +}); diff --git a/packages/plugins/plugin-security/src/agent-ceiling-clamp.ts b/packages/plugins/plugin-security/src/agent-ceiling-clamp.ts new file mode 100644 index 00000000000..6f2e0208afa --- /dev/null +++ b/packages/plugins/plugin-security/src/agent-ceiling-clamp.ts @@ -0,0 +1,137 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0151 D3] The agent ceiling, held at evaluation: whatever its permission + * sets say, an agent principal never carries View All or Modify All, the + * destructive class, a system permission, a superuser wildcard or an admin + * scope. + * + * ## Why at evaluation + * + * An AI service account's grants are ordinary assignments + * (`sys_user_permission_set`, `sys_user_position`), and a set can be edited + * after it was assigned. The refusal at assignment + * (`agent-account-grant-refusal.ts`) is the loud, early answer; this clamp is + * the guarantee. It runs where every evaluator reads an execution context's + * sets — `resolvePermissionSetsForContextUnmemoized` + * (`security-plugin-permission-sets.ts`), the one choke point — for every + * agent principal, the account and the OAuth-delegated agent alike. The + * first-party OAuth ceiling sets (`MCP_AGENT_PERMISSION_SETS`) carry none of + * these bits, so the clamp changes nothing for them. + * + * ## What it clears + * + * On every `objects` entry, the wildcard `'*'` included: `viewAllRecords`, + * `modifyAllRecords` and the destructive class's grant keys + * ({@link DESTRUCTIVE_CLASS_KEYS}, `permission-evaluator.ts`). With the two + * bypass bits gone a `'*'` entry is no longer a superuser wildcard: the + * evaluator applies it to a private object only when it carries them + * (ADR-0066 D2), and the field merge's superuser vote reads the same two + * bits. On the set: `systemPermissions` (emptied) and `adminScope` (removed), + * in both the definition and the row spellings the delegated-administration + * gate reads. + * + * Every other key is left as authored: the CRUD bits, export, depth, field + * masks, tabs and row-level security are ordinary grants under the ceiling. + * + * ## What it never does + * + * It never mutates a set it is handed: the resolved sets are shared with the + * metadata and bootstrap catalogs. A set that needs no clamp is returned as + * the same object; one that does is a fresh copy. + */ + +import type { PermissionSet } from '@objectstack/spec/security'; +import { DESTRUCTIVE_CLASS_KEYS } from './permission-evaluator.js'; + +/** The object-entry bits the ceiling clears: the two bypass bits, then the destructive class. */ +export const AGENT_CEILING_OBJECT_KEYS: readonly string[] = Object.freeze([ + 'viewAllRecords', + 'modifyAllRecords', + ...DESTRUCTIVE_CLASS_KEYS, +]); + +/** The set-level keys the ceiling clears, each in its definition and its row spelling. */ +const SYSTEM_PERMISSION_KEYS = ['systemPermissions', 'system_permissions'] as const; +const ADMIN_SCOPE_KEYS = ['adminScope', 'admin_scope'] as const; + +const isRecord = (v: unknown): v is Record => + v !== null && typeof v === 'object' && !Array.isArray(v); + +/** A JSON-string column, read the way the delegated-administration gate reads it. */ +function parsed(v: unknown): unknown { + if (typeof v !== 'string') return v; + try { + return JSON.parse(v); + } catch { + return v; + } +} + +function nonEmptyList(v: unknown): boolean { + const list = parsed(v); + return Array.isArray(list) && list.length > 0; +} + +function present(v: unknown): boolean { + const value = parsed(v); + return value !== undefined && value !== null && value !== '' && value !== false; +} + +/** + * What in `set` breaches the agent ceiling, one phrase per bit, in a stable + * order: `objects..`, then `systemPermissions`, then + * `adminScope`. Empty when the set is within it. + */ +export function agentCeilingBreaches(set: unknown): string[] { + if (!isRecord(set)) return []; + const out: string[] = []; + const objects = parsed(set.objects); + if (isRecord(objects)) { + for (const [object, entry] of Object.entries(objects)) { + if (!isRecord(entry)) continue; + for (const key of AGENT_CEILING_OBJECT_KEYS) { + if (entry[key] === true) out.push(`objects.${object}.${key}`); + } + } + } + if (SYSTEM_PERMISSION_KEYS.some((k) => nonEmptyList(set[k]))) out.push('systemPermissions'); + if (ADMIN_SCOPE_KEYS.some((k) => present(set[k]))) out.push('adminScope'); + return out; +} + +/** + * `set` under the agent ceiling. The same object when nothing in it breaches + * the ceiling, a fresh copy with the breaching bits cleared when something + * does. + */ +export function clampPermissionSetToAgentCeiling(set: PermissionSet): PermissionSet { + if (agentCeilingBreaches(set).length === 0) return set; + const out: Record = { ...(set as unknown as Record) }; + const objects = parsed(out.objects); + if (isRecord(objects)) { + const clamped: Record = {}; + for (const [object, entry] of Object.entries(objects)) { + if (!isRecord(entry)) { + clamped[object] = entry; + continue; + } + const next: Record = { ...entry }; + for (const key of AGENT_CEILING_OBJECT_KEYS) { + if (next[key] === true) next[key] = false; + } + clamped[object] = next; + } + out.objects = clamped; + } + for (const key of SYSTEM_PERMISSION_KEYS) { + if (key in out) out[key] = []; + } + for (const key of ADMIN_SCOPE_KEYS) delete out[key]; + return out as unknown as PermissionSet; +} + +/** Every set under the agent ceiling ({@link clampPermissionSetToAgentCeiling}), in order. */ +export function clampPermissionSetsToAgentCeiling(sets: readonly PermissionSet[]): PermissionSet[] { + return sets.map(clampPermissionSetToAgentCeiling); +} diff --git a/packages/plugins/plugin-security/src/agent-ceiling-grant-refusal.ts b/packages/plugins/plugin-security/src/agent-ceiling-grant-refusal.ts index 2963cb27b68..fc11df571a7 100644 --- a/packages/plugins/plugin-security/src/agent-ceiling-grant-refusal.ts +++ b/packages/plugins/plugin-security/src/agent-ceiling-grant-refusal.ts @@ -15,11 +15,15 @@ * (`scopesToAgentPermissionSets`) and the shared assembler puts it on the * agent's context as `permissions`, with `principalKind: 'agent'` * (`assemble-execution-context.ts` in `@objectstack/core`). No assignment row - * is read for it. And no `sys_user` row is an agent principal: a user row - * signs in as a person. So every row of this table is a person's grant, and an - * agent ceiling is not a person's set — the sentence ADR-0090 D12 (as amended + * is read for it. A `sys_user` row can be an agent principal too — an AI + * service account (ADR-0151, `principal_kind = agent`) — but its grants are + * ordinary assignments under the agent ceiling, never the OAuth agent's + * scope-derived sets (ADR-0151 D3: "the agent ceiling sets stay out of the + * assignment tables"). So no row of this table, a person's or an account's, + * holds an agent ceiling set — the sentence ADR-0090 D12 (as amended * 2026-10-17) states for the organization boundary's denylist, held here for - * every writer. + * every writer. What an account may be assigned is judged on its own by + * `agent-account-grant-refusal.ts`. * * A non-system insert or update that would STORE an assignment naming one of * those sets is refused, for every caller, a platform administrator included. diff --git a/packages/plugins/plugin-security/src/explain-engine.ts b/packages/plugins/plugin-security/src/explain-engine.ts index b3833af3eb7..223cb58711d 100644 --- a/packages/plugins/plugin-security/src/explain-engine.ts +++ b/packages/plugins/plugin-security/src/explain-engine.ts @@ -800,6 +800,9 @@ export async function buildContextForUser( // [Ruling of record 6355206139] The population stamp the resolver made, so // the explained context is floored at the OWD seam as enforcement is. ...(grants.audience ? { audience: grants.audience } : {}), + // [ADR-0151 D3] An AI service account is explained as the agent it is: its + // own grants under the agent ceiling, with no one it acts for. + ...(grants.principalKind ? { principalKind: grants.principalKind } : {}), droppedGrants, delegatedPositions, // [ADR-0068 D2] Not a second derivation: `derivePosture` returns diff --git a/packages/plugins/plugin-security/src/permission-evaluator.ts b/packages/plugins/plugin-security/src/permission-evaluator.ts index 66b922107ad..42c49e82495 100644 --- a/packages/plugins/plugin-security/src/permission-evaluator.ts +++ b/packages/plugins/plugin-security/src/permission-evaluator.ts @@ -125,6 +125,20 @@ export const MODIFY_ALL_WRITE_KEYS = new Set([ }), ]); +/** + * [ADR-0151 D3] The grant keys of the destructive class, derived from the same + * two constants as {@link MODIFY_ALL_WRITE_KEYS}: `transfer`, `restore` and + * `purge` read here as the bits that grant them. The agent ceiling clears + * them on every set an agent principal holds (`agent-ceiling-clamp.ts`), so a + * destructive operation added to the map and the set is clamped as well. + */ +export const DESTRUCTIVE_CLASS_KEYS: ReadonlySet = new Set( + [...DESTRUCTIVE_OPERATIONS].flatMap((op) => { + const key = OPERATION_TO_PERMISSION[op]; + return key ? [key] : []; + }), +); + /** CRUD operation class an object-level `requiredPermissions` map keys on. */ export type CrudBucket = 'read' | 'create' | 'update' | 'delete'; diff --git a/packages/plugins/plugin-security/src/security-plugin-effective-access.ts b/packages/plugins/plugin-security/src/security-plugin-effective-access.ts index 5e18dad25d6..7f8f8f852a8 100644 --- a/packages/plugins/plugin-security/src/security-plugin-effective-access.ts +++ b/packages/plugins/plugin-security/src/security-plugin-effective-access.ts @@ -32,7 +32,9 @@ * is the human baseline the security service adds for every authenticated * member (`humanBaselineFor`, the helper the set resolution and the explainer * read): those sets join last, as `default`, and a set already listed keeps - * its place and gains the origin. + * its place and gains the origin. An AI service account (ADR-0151 D3) holds + * no member baseline: its `default` is the agent floor the set resolution + * gives every agent principal, the restricted set. * * The organization is explain's: the caller's active one, kept only while the * described user could be resolved in it (`vetOrganizationClaim`, the session @@ -40,6 +42,7 @@ */ import { resolveUserAuthzGrants, vetOrganizationClaim } from '@objectstack/core'; import type { EffectiveAccess, EffectivePermissionSet, EffectivePermissionSetOrigin } from '@objectstack/spec/contracts'; +import { MCP_AGENT_PERMISSION_SET_RESTRICTED } from '@objectstack/spec/ai'; import type { SecurityPlugin } from './security-plugin.js'; import { PermissionDeniedError } from './errors.js'; import { readSysUserRow } from './explain-engine.js'; @@ -119,7 +122,10 @@ export async function describeEffectiveAccess( } for (const origin of derivedBy) add(name, origin); } - for (const name of humanBaselineFor(grants.positions, this.baselinePermissionSets)) { + const baseline = grants.principalKind === 'agent' + ? [MCP_AGENT_PERMISSION_SET_RESTRICTED] + : humanBaselineFor(grants.positions, this.baselinePermissionSets); + for (const name of baseline) { add(name, { kind: 'default' }); } diff --git a/packages/plugins/plugin-security/src/security-plugin-permission-sets.ts b/packages/plugins/plugin-security/src/security-plugin-permission-sets.ts index 53ba6ab9beb..a99a3755fb4 100644 --- a/packages/plugins/plugin-security/src/security-plugin-permission-sets.ts +++ b/packages/plugins/plugin-security/src/security-plugin-permission-sets.ts @@ -6,8 +6,9 @@ * * - `resolvePermissionSetsForContextUnmemoized`, the resolution itself: the * permission sets the context names, the additive human baseline or the - * agent's restricted ceiling, and the post-resolution fallback for an - * authenticated caller whose sets resolved nothing. + * agent's restricted ceiling, the post-resolution fallback for an + * authenticated caller whose sets resolved nothing, and the agent ceiling + * clamp (ADR-0151 D3, `agent-ceiling-clamp.ts`) on an agent's sets. * - `reportUngrantedNamesakeSets`, the once-per-name warning for a permission * set that shares a held position's name and is NOT granted through it, * because the position's definition does not name it (#13419, #24757). @@ -84,6 +85,7 @@ import { isGuestEnvelope, POSITION_NAME_FOLD_EVENT } from './security-plugin.js' import type { PermissionSet } from '@objectstack/spec/security'; import { MCP_AGENT_PERMISSION_SET_RESTRICTED } from '@objectstack/spec/ai'; import { humanBaselineFor } from './external-baseline.js'; +import { clampPermissionSetsToAgentCeiling } from './agent-ceiling-clamp.js'; /** * The `SecurityPlugin` members the functions below read — every one of them, @@ -148,6 +150,10 @@ export async function resolvePermissionSetsForContextUnmemoized( // CLOSED (every object op denied) rather than falling open. The delegating // user's own baseline still applies on the OTHER side of the intersection // (resolved from `onBehalfOf` via a context without this flag). + // [ADR-0151 D3] An AI service account is an agent principal too: its + // `permissions` are its own assignments (no scope derivation, no + // `onBehalfOf`, so no intersection), and the same rule holds — no member + // baseline, the restricted set as its floor. const isAgent = context?.principalKind === 'agent'; // [#7555] The human side is a LIST, and the agent side deliberately is not: // the agent's ceiling is EXACTLY the restricted set, and composing the @@ -209,6 +215,14 @@ export async function resolvePermissionSetsForContextUnmemoized( { logger: this.logger }, ); } + // [ADR-0151 D3] Rule 2's ceiling, held at evaluation: an agent principal — + // an AI service account holding ordinary assignments, or an OAuth-delegated + // agent holding its scope-derived ceiling — never carries View/Modify All, + // the destructive class, a system permission, a superuser wildcard or an + // admin scope, whatever a set says. Applied here, after both resolutions, + // because every evaluator reads its sets through this one function, and a + // set can be edited after the refusal at assignment let it through. + if (isAgent) permissionSets = clampPermissionSetsToAgentCeiling(permissionSets); return permissionSets; } diff --git a/packages/plugins/plugin-security/src/security-plugin-start-hooks.ts b/packages/plugins/plugin-security/src/security-plugin-start-hooks.ts index 0b4722cf2b6..caf403f633d 100644 --- a/packages/plugins/plugin-security/src/security-plugin-start-hooks.ts +++ b/packages/plugins/plugin-security/src/security-plugin-start-hooks.ts @@ -52,6 +52,7 @@ import { POSITION_ASSIGNMENT_OBJECT, createPositionCatalogRefusal } from './posi import { registerGrantHolderMembershipRefusal } from './grant-holder-membership-refusal.js'; import { registerGrantPermissionSetNameHooks } from './grant-permission-set-name.js'; import { registerAgentCeilingGrantRefusal } from './agent-ceiling-grant-refusal.js'; +import { registerAgentAccountGrantRefusal } from './agent-account-grant-refusal.js'; import { reportCatalogReferences } from './catalog-reference-report.js'; import { reportAccessUpgrade, @@ -134,6 +135,14 @@ export function registerStartHooks( // `permission_set`), for every caller. Engine hooks; see // `agent-ceiling-grant-refusal.ts`. registerAgentCeilingGrantRefusal(ql, ctx.logger); + // [ADR-0151 D3] An AI service account is never assigned a set above the + // agent ceiling: a non-system `sys_user_permission_set` or + // `sys_user_position` write that would give an account a set carrying View + // All, Modify All, the destructive class, a system permission or an admin + // scope is refused by the set's name (`400 VALIDATION_FAILED`, + // `invalid_value`). The clamp at evaluation is the guarantee; this is the + // early answer. Engine hooks; see `agent-account-grant-refusal.ts`. + registerAgentAccountGrantRefusal(ql, ctx.logger); // [ADR-0131 D3, C3 stage 8] No data-door write-through and no walled // catalog data-door refusal is registered: the catalog objects are diff --git a/packages/rest/src/rest-api-key-agent-account.test.ts b/packages/rest/src/rest-api-key-agent-account.test.ts new file mode 100644 index 00000000000..b236dfe9184 --- /dev/null +++ b/packages/rest/src/rest-api-key-agent-account.test.ts @@ -0,0 +1,145 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// +// [ADR-0151 D3] The REST face: an AI service account's API key admits the +// ACCOUNT as the subject — `userId` the account, `principalKind: 'agent'`, no +// `onBehalfOf`, no system permission, no `everyone` anchor and no +// administrator standing — through the real `computeExecCtx` → +// `resolveAuthzContext` → `assembleExecutionContext` pipeline, captured as the +// protocol receives it (the instrumentation `rest-exec-ctx-principal-kind.test.ts` +// uses). CONTROL: a person's key over the same store is unchanged. + +import { describe, it, expect, vi } from 'vitest'; +import { hashApiKey } from '@objectstack/core'; +import { RestServer } from './rest-server'; +import { bindTestSecurityCatalog } from './__tests__/security-catalog.testkit.js'; + +const TASK = { + name: 'task', + label: 'Task', + fields: { id: { type: 'text', label: 'ID' }, title: { type: 'text', label: 'Title' } }, +}; + +const makeServer = () => ({ + get: vi.fn(), post: vi.fn(), put: vi.fn(), delete: vi.fn(), patch: vi.fn(), + use: vi.fn(), listen: vi.fn(), close: vi.fn(), +}); + +const FUTURE = '2999-01-01T00:00:00Z'; +const BOT_KEY = 'osk_31739_rest_account'; +const MIA_KEY = 'osk_31739_rest_person'; + +/** + * - `u_bot`: an AI service account, holding `ops_tools` (which carries a + * system permission) in org_a and — as a store can hold, though no door + * writes it — the Default Organization's `admin_full_access` grant, the row + * that anchors a person's platform standing. + * - `u_mia`: a person holding the same two grants. + * - The `everyone` anchor binds `everyone_reader`. + */ +const USERS: Record> = { + u_bot: { id: 'u_bot', email: 'bot@agents.invalid', principal_kind: 'agent', accountable_user_id: 'u_mia' }, + u_mia: { id: 'u_mia', email: 'mia@example.com', principal_kind: 'human' }, +}; + +const makeQl = () => bindTestSecurityCatalog({ + find: async (object: string, opts: any) => { + const where = opts?.where ?? {}; + if (object === 'sys_api_key') { + const rows = [ + { id: 'k_bot', key: hashApiKey(BOT_KEY), revoked: false, user_id: 'u_bot', expires_at: FUTURE, active_organization_id: 'org_a' }, + { id: 'k_mia', key: hashApiKey(MIA_KEY), revoked: false, user_id: 'u_mia', expires_at: FUTURE, active_organization_id: 'org_a' }, + ]; + return rows.filter((row) => Object.entries(where).every(([k, v]) => (row as any)[k] === v)); + } + if (object === 'sys_user') return USERS[where.id] ? [USERS[where.id]] : []; + if (object === 'sys_member') { + const rows = [ + { user_id: 'u_bot', organization_id: 'org_a', role: 'member' }, + { user_id: 'u_mia', organization_id: 'org_a', role: 'member' }, + ]; + return rows.filter((row) => Object.entries(where).every(([k, v]) => (row as any)[k] === v)); + } + if (object === 'sys_organization') return [{ id: 'org_default', slug: 'default' }]; + if (object === 'sys_user_permission_set') { + if (where.user_id !== 'u_bot' && where.user_id !== 'u_mia') return []; + return [ + { user_id: where.user_id, permission_set: 'ops_tools', organization_id: 'org_a' }, + { user_id: where.user_id, permission_set: 'admin_full_access', organization_id: 'org_default' }, + ]; + } + return []; + }, +}, { + permissions: [ + { name: 'admin_full_access' }, + { name: 'ops_tools', systemPermissions: ['manage_users'] }, + { name: 'everyone_reader' }, + ], + positions: [{ name: 'everyone', permissionSets: ['everyone_reader'] }], +}); + +function makeRes() { + let status = 200; + const res: any = { + write: () => true, + end: () => {}, + header: () => res, + status: (code: number) => { status = code; return res; }, + json: (body: any) => { res._json = body; return res; }, + }; + return { res, getStatus: () => status }; +} + +/** Drive the REAL `GET /api/v1/data/task` route and capture the context `findData` receives. */ +async function request(headers: Record) { + const seen: any[] = []; + const protocol: any = { + getMetaItems: vi.fn().mockResolvedValue({ items: [TASK] }), + findData: vi.fn(async (args: any) => { seen.push(args.context); return { object: 'task', records: [] }; }), + }; + const auth = { isAuthGateActive: () => true, api: { getSession: async () => undefined } }; + const rest = new RestServer( + makeServer() as any, + protocol as any, + {} as any, + undefined, + undefined, + undefined, + async () => auth, + async () => makeQl(), + ); + rest.registerRoutes(); + const route = rest.getRoutes().find((r: any) => r.method === 'GET' && r.path === '/api/v1/data/:object'); + expect(route).toBeDefined(); + const out = makeRes(); + await route!.handler({ method: 'GET', path: '/api/v1/data/task', params: { object: 'task' }, query: {}, headers } as any, out.res); + return { ctx: seen[0], status: out.getStatus() }; +} + +describe('[ADR-0151 D3] REST: an AI service account\'s key admits the account itself', () => { + it('userId is the account, principalKind agent, no onBehalfOf, no system permission, no everyone anchor, no admin standing', async () => { + const { ctx, status } = await request({ 'x-api-key': BOT_KEY }); + expect(status).toBe(200); + expect(ctx.userId).toBe('u_bot'); + expect(ctx.principalKind).toBe('agent'); + expect(ctx.onBehalfOf).toBeUndefined(); + expect(Object.keys(ctx)).not.toContain('onBehalfOf'); + expect(ctx.performedBy).toBeUndefined(); + expect(ctx.systemPermissions).toEqual([]); + expect(ctx.positions).not.toContain('everyone'); + expect(ctx.positions).not.toContain('platform_admin'); + expect(ctx.posture).not.toBe('PLATFORM_ADMIN'); + expect(ctx.isSystem).toBe(false); + }); + + it('CONTROL: a person\'s key over the same store and the same grants is unchanged', async () => { + const { ctx, status } = await request({ 'x-api-key': MIA_KEY }); + expect(status).toBe(200); + expect(ctx.userId).toBe('u_mia'); + expect(ctx.principalKind).toBe('human'); + expect(ctx.onBehalfOf).toBeUndefined(); + expect(ctx.systemPermissions).toContain('manage_users'); + expect(ctx.positions).toContain('everyone'); + expect(ctx.posture).toBe('PLATFORM_ADMIN'); + }); +}); diff --git a/packages/rest/src/rest-server.ts b/packages/rest/src/rest-server.ts index 79d8f97e23c..e2979b8c30b 100644 --- a/packages/rest/src/rest-server.ts +++ b/packages/rest/src/rest-server.ts @@ -3497,11 +3497,15 @@ export class RestServer { accessToken: 'withhold', // OAuth access tokens are honoured on the `/mcp` door alone // (`acceptOAuthAccessToken`), precisely so coarse tool-family - // scopes cannot ride onto REST. [ADR-0090 D10 rule 5] The agent - // principal (`principalKind: 'agent'`, `onBehalfOf`, - // `oauthScopes`) is represented here for one caller only: an - // agent a forward credential carried. Its ceiling is derived - // from the consented scopes exactly as the MCP door derives it. + // scopes cannot ride onto REST. [ADR-0090 D10 rule 5] The + // OAuth-delegated agent principal (`principalKind: 'agent'`, + // `onBehalfOf`, `oauthScopes`) is represented here for one + // caller only: an agent a forward credential carried. Its + // ceiling is derived from the consented scopes exactly as the + // MCP door derives it. [ADR-0151 D3] An AI service account's + // own API key is the other agent provenance on this face: the + // assembler stamps it from the account's row, with no + // `onBehalfOf` and no OAuth input. oauth: forwardAgent ? { userId: forwardAgent.userId, diff --git a/packages/runtime/src/action-execution.ts b/packages/runtime/src/action-execution.ts index ca22dfd1a25..9b41148b19e 100644 --- a/packages/runtime/src/action-execution.ts +++ b/packages/runtime/src/action-execution.ts @@ -2745,6 +2745,12 @@ export async function dispatchFlowAction(deps: ActionExecutionDeps, // door's twin (`buildAutomationContext`): never re-derived or raised, // absent when the request carries none. See `AutomationContext.posture`. ...(typeof ec?.posture === 'string' && ec.posture.length > 0 ? { posture: ec.posture } : {}), + // [ADR-0151 D3] An AI service account's kind, the trigger door's twin + // (`buildAutomationContext`): the run carries the account's grants, so + // without the kind it would be evaluated as a person's (the member + // baseline, no agent ceiling). Only the account (`agent` with no + // `onBehalfOf`); an OAuth-delegated agent is forwarded as before. + ...(ec?.principalKind === 'agent' && !ec?.onBehalfOf ? { principalKind: 'agent' as const } : {}), // [#22450] The caller's already-resolved language, the trigger door's // twin (`buildAutomationContext`): a refused run's message renders in // it. See `AutomationContext.locale`. @@ -4786,7 +4792,14 @@ async function dispatchAdmittedBusinessAction(deps: ActionExecutionDeps, console.info( `[action-audit] MCP run_action '${action.name}' on '${objectName}' — body executes TRUSTED ` + `(system-elevated context, RLS/FLS-bypassing) for user '${ec?.userId ?? 'anonymous'}'` + - (ec?.principalKind === 'agent' ? ` (AGENT on behalf of '${ec?.onBehalfOf?.userId ?? 'unknown'}')` : ''), + // [ADR-0151 D3] An agent names a person it acts for only when it is + // OAuth-delegated; an AI service account is its own subject, so the + // user above IS the agent and no one stands behind it. + (ec?.principalKind === 'agent' + ? ec?.onBehalfOf + ? ` (AGENT on behalf of '${ec.onBehalfOf.userId ?? 'unknown'}')` + : ' (AGENT: an AI service account, acting for itself)' + : ''), ); const actionContext: any = { record, diff --git a/packages/runtime/src/domains/automation-connector-connection-door.test.ts b/packages/runtime/src/domains/automation-connector-connection-door.test.ts index 45887fe2670..61fdacbaedf 100644 --- a/packages/runtime/src/domains/automation-connector-connection-door.test.ts +++ b/packages/runtime/src/domains/automation-connector-connection-door.test.ts @@ -350,6 +350,34 @@ describe('ADR-0143 D5 — connector connection door: begin and revoke refuse a d } }); + // [ADR-0151 D3] An AI service account's own key: the account is the + // subject (`principalKind: 'agent'`, no `onBehalfOf`), so it is named as + // itself, never as an agent acting for a person. + const ACCOUNT_KEY = (): HttpProtocolContext => ({ + request: {}, + admission: { credential: 'api_key', authGate: undefined }, + executionContext: assembleExecutionContext({ + authz: { ...holderAuthz, userId: 'u_agent', principalKind: 'agent' as const }, + oauth: undefined, + ...ENTRY, + }), + } as HttpProtocolContext); + + it('an AI service account is refused on begin and on revoke by its own kind, not as an agent acting for a person', async () => { + expect(ACCOUNT_KEY().executionContext).toMatchObject({ userId: 'u_agent', principalKind: 'agent', systemPermissions: [] }); + expect(ACCOUNT_KEY().executionContext.onBehalfOf).toBeUndefined(); + expect(connectorConnectionDelegatedCaller(ACCOUNT_KEY())).toBe('agent_account'); + for (const verb of ['POST', 'DELETE'] as const) { + const h = boot(); + const { response } = await connection(h, verb, ACCOUNT_KEY()); + expect(statusOf(response)).toBe(403); + expect(messageOf(response)).toBe(connectorConnectionDelegatedCallerRefusal('agent_account')); + expect(messageOf(response)).toContain('an AI service account, which acts as itself'); + expect(messageOf(response)).not.toContain('on a person\'s behalf'); + for (const m of [h.get, h.begin, h.complete, h.revoke]) expect(m).not.toHaveBeenCalled(); + } + }); + it('the same human, signed in, is admitted on begin and on revoke', async () => { const h = boot(); const begun = await connection(h, 'POST', HOLDER_SIGNED_IN()); diff --git a/packages/runtime/src/domains/automation.ts b/packages/runtime/src/domains/automation.ts index 04bfbff53a8..1cb6413534f 100644 --- a/packages/runtime/src/domains/automation.ts +++ b/packages/runtime/src/domains/automation.ts @@ -226,6 +226,13 @@ export function buildAutomationContext(body: any, context: HttpProtocolContext): // re-resolve them and this is the only way it gets one. // `AutomationContext.posture` names its readers. if (typeof ec?.posture === 'string' && ec.posture.length > 0) automationContext.posture = ec.posture; + // [ADR-0151 D3] An AI service account's kind, forwarded beside its grants + // for the same reason: the run carries those grants, so its setup does not + // re-resolve them, and without the kind the account's run would be + // evaluated as a person's (the member baseline, no agent ceiling). Only the + // account (`agent` with no `onBehalfOf`); an OAuth-delegated agent is + // forwarded as before. Read by `runPrincipalKind` (`@objectstack/service-automation`). + if (ec?.principalKind === 'agent' && !ec?.onBehalfOf) automationContext.principalKind = 'agent'; // [#22450] The caller's language, already resolved (the request's // `Accept-Language` first, then the `localization` settings) — forwarded, // never re-derived, so a refused run's message renders in the language of @@ -1043,25 +1050,29 @@ const CONNECTOR_CONNECTION_DENY_MESSAGE = `Connecting, reconnecting or revoking a connector instance, or reading its connection, requires the \`${CONNECTOR_CONNECTION_CAPABILITY}\` capability.`; /** - * ADR-0143 D5 — a caller that acts for a person instead of being that person - * signed in, by kind: `agent` (an envelope that names a delegator, - * `principalKind: 'agent'` or `onBehalfOf`), `oauth` (admitted by an OAuth - * access token) or `api_key` (admitted by an API key). The credential half is - * the forward table's own reading ({@link apiForwardCredentialKind}), so the - * two doors cannot disagree about which credential admitted a caller. + * ADR-0143 D5 — a caller that is not a person signed in, by kind: `agent` + * (an envelope that names a delegator, `onBehalfOf`), `agent_account` (an AI + * service account, ADR-0151 D3: `principalKind: 'agent'` with no + * `onBehalfOf` — its own subject, acting for nobody, admitted by its own API + * key), `oauth` (admitted by an OAuth access token) + * or `api_key` (admitted by an API key). The credential half is the forward + * table's own reading ({@link apiForwardCredentialKind}), so the two doors + * cannot disagree about which credential admitted a caller. */ -export type ConnectorConnectionDelegatedCaller = 'agent' | 'oauth' | 'api_key'; +export type ConnectorConnectionDelegatedCaller = 'agent' | 'agent_account' | 'oauth' | 'api_key'; /** The delegated kind of this request's caller, or `undefined` for a person signed in (or no recorded credential). */ export function connectorConnectionDelegatedCaller(context: HttpProtocolContext | undefined): ConnectorConnectionDelegatedCaller | undefined { const ec: any = context?.executionContext; - if (ec?.principalKind === 'agent' || ec?.onBehalfOf) return 'agent'; + if (ec?.onBehalfOf) return 'agent'; + if (ec?.principalKind === 'agent') return 'agent_account'; const credential = apiForwardCredentialKind(context); return credential === 'oauth' || credential === 'api_key' ? credential : undefined; } const CONNECTOR_CONNECTION_DELEGATED_CALLER_NAMES: Readonly> = { agent: 'an agent acting on a person\'s behalf', + agent_account: 'an AI service account, which acts as itself and never signs in', oauth: 'an OAuth access token, which a client holds to act for a person', api_key: 'an API key, which acts for its owner without them present', }; diff --git a/packages/runtime/src/flow-run-agent-account-kind.test.ts b/packages/runtime/src/flow-run-agent-account-kind.test.ts new file mode 100644 index 00000000000..98e62fbc713 --- /dev/null +++ b/packages/runtime/src/flow-run-agent-account-kind.test.ts @@ -0,0 +1,71 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0151 D3] A flow an AI service account starts runs as the agent + * principal it is. + * + * Both doors that hand the automation engine the caller's grants — the + * trigger door (`buildAutomationContext`) and the action door + * (`dispatchFlowAction`) — forward the account's kind beside them: the run + * carries those grants, so its setup does not re-resolve them, and without + * the kind the run would be evaluated as a person's (the member baseline, no + * agent ceiling). CONTROLS: a person's request forwards no kind, and an + * OAuth-delegated agent (`onBehalfOf`) is forwarded exactly as before. + */ + +import { describe, it, expect, vi } from 'vitest'; + +import { dispatchFlowAction, loadActionSubjectRecord } from './action-execution.js'; +import { buildAutomationContext } from './domains/automation.js'; + +const FLOW_NAME = 'lead_triage'; +const TRIAGE = { name: 'triage', label: 'Triage', objectName: 'crm_lead', type: 'flow', target: FLOW_NAME }; + +const ACCOUNT = { userId: 'u_bot', tenantId: 'org_1', positions: ['org_member'], permissions: ['lead_reader'], systemPermissions: [], principalKind: 'agent', posture: 'MEMBER' }; +const PERSON = { userId: 'u_mia', tenantId: 'org_1', positions: ['org_member', 'everyone'], permissions: ['lead_reader'], systemPermissions: [], principalKind: 'human', posture: 'MEMBER' }; +const DELEGATED = { ...PERSON, principalKind: 'agent', permissions: ['mcp_agent_data_read'], onBehalfOf: { userId: 'u_mia', principalKind: 'human' } }; + +function makeAutomation() { + const execute = vi.fn(async (_flow: string, _context?: any) => ({ success: true, output: {} })); + const getFlow = vi.fn(async (name: string) => (name === FLOW_NAME ? { name } : null)); + return { execute, getFlow }; +} +const flowDeps = (automation: any): any => ({ + resolveService: async (_ctx: any, name: string) => (name === 'automation' ? automation : undefined), +}); + +async function viaAction(ec: any) { + const automation = makeAutomation(); + const subject = await loadActionSubjectRecord('crm_lead', 'lead_1', async () => ({ record: { id: 'lead_1' } })); + await dispatchFlowAction(flowDeps(automation), { request: {}, environmentId: 'platform' } as any, TRIAGE as any, { + objectName: 'crm_lead', subject, params: {}, recordId: 'lead_1', ec, envId: 'platform', + }); + return automation.execute.mock.calls[0]?.[1]; +} + +const viaTrigger = (ec: any): any => + buildAutomationContext({ recordId: 'lead_1', objectName: 'crm_lead', params: {} }, { request: {}, executionContext: ec } as any); + +describe('[ADR-0151 D3] a run an AI service account starts carries its kind', () => { + it('the trigger door forwards principalKind agent beside the account\'s grants', () => { + expect(viaTrigger(ACCOUNT)).toMatchObject({ userId: 'u_bot', permissions: ['lead_reader'], principalKind: 'agent' }); + }); + + it('the action door forwards principalKind agent beside the account\'s grants', async () => { + expect(await viaAction(ACCOUNT)).toMatchObject({ userId: 'u_bot', permissions: ['lead_reader'], principalKind: 'agent' }); + }); + + it('the body cannot name a kind: a `principalKind` param stays a flow param', () => { + const ctx = buildAutomationContext({ principalKind: 'agent', params: {} }, { request: {}, executionContext: PERSON } as any) as any; + expect('principalKind' in ctx).toBe(false); + }); +}); + +describe('CONTROLS — a person and an OAuth-delegated agent forward no kind, as before', () => { + for (const [label, ec] of [['a person', PERSON], ['an OAuth-delegated agent', DELEGATED]] as const) { + it(`${label}: neither door adds the key`, async () => { + expect('principalKind' in viaTrigger(ec)).toBe(false); + expect('principalKind' in (await viaAction(ec))).toBe(false); + }); + } +}); diff --git a/packages/runtime/src/security/resolve-execution-context.agent-account.test.ts b/packages/runtime/src/security/resolve-execution-context.agent-account.test.ts new file mode 100644 index 00000000000..63894bcadc4 --- /dev/null +++ b/packages/runtime/src/security/resolve-execution-context.agent-account.test.ts @@ -0,0 +1,292 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0151 D3] An AI service account's API key admits the ACCOUNT as the + * subject: `userId` the account, `principalKind: 'agent'`, no `onBehalfOf`, + * no system permission — on the `/mcp` door and on the dispatcher's own face — + * and its sets are read under the agent ceiling. + * + * ## The rig + * + * The REAL `resolveExecutionContext` → `resolveAuthzContext` (this package's + * vitest alias resolves `@objectstack/core` to its source) over a table + * double, and the context it builds handed to the REAL `SecurityPlugin`. Only + * the OAuth token verifier is faked, for the OAuth-delegated CONTROL. + * + * - `u_bot` is an AI service account (`principal_kind: 'agent'`) owned by + * `u_mia`, a plain member of org_alpha. It holds `crm_lead_reader` and + * `crm_lead_super` in org_alpha, and — as no registration door would ever + * write, but a store can hold — `admin_full_access` owned by the Default + * Organization: the row that anchors platform standing for a person. + * - `crm_lead_super` breaches the agent ceiling: View All, Modify All, + * transfer and the recycle bin on `crm_lead`, a system permission and an + * admin scope. It is the set "assigned, then edited": the refusal at + * assignment cannot see an edit, so what the account reads is the set as it + * stands now, and the clamp is what holds. + * - `u_mia` (the CONTROL) is a person holding the SAME two sets, and her own + * key. + * - The `everyone` anchor binds `crm_contact_reader`, so a person reads + * contacts through it and the account must not. + */ + +import { describe, it, expect, vi, beforeAll, beforeEach, afterEach } from 'vitest'; +import type { PermissionSet } from '@objectstack/spec/security'; +import type { ExecutionContext } from '@objectstack/spec/kernel'; +import { SecurityPlugin } from '@objectstack/plugin-security'; +import { assertEngineFindOnePredicate } from '@objectstack/metadata-core'; + +import { resolveExecutionContext } from './resolve-execution-context.js'; +import { hashApiKey } from './api-key.js'; +import { bindCatalogFromTables } from './security-catalog.testkit.js'; + +const ALPHA = 'org_alpha'; +const DEFAULT_ORG = 'org_default'; +const LEAD = 'crm_lead'; +const CONTACT = 'crm_contact'; +const FUTURE = '2999-01-01T00:00:00Z'; +const BOT_KEY = 'osk_31739_account_key'; +const MIA_KEY = 'osk_31739_person_key'; +const CLIENT = 'agent-client-1'; + +/** One source for every set: the catalog rows core reads and the bodies the security plugin reads. */ +const SETS: PermissionSet[] = [ + { name: 'crm_lead_reader', label: 'Lead reader', objects: { [LEAD]: { allowRead: true } } }, + { + name: 'crm_lead_super', + label: 'Lead superuser', + objects: { + [LEAD]: { + allowRead: true, + allowEdit: true, + viewAllRecords: true, + modifyAllRecords: true, + allowTransfer: true, + allowRestoreOwnDeleted: true, + manageRecycleBin: true, + }, + }, + systemPermissions: ['manage_users'], + adminScope: { businessUnit: 'bu_root', includeSubtree: true, manageAssignments: true, assignablePermissionSets: [] }, + }, + { name: 'crm_contact_reader', label: 'Contact reader', objects: { [CONTACT]: { allowRead: true } } }, + // The superuser wildcard: every object, through the two bypass bits alone. + { name: 'admin_full_access', label: 'Admin', objects: { '*': { viewAllRecords: true, modifyAllRecords: true } } }, +] as PermissionSet[]; + +function tables(): Record { + return { + sys_api_key: [ + { id: 'k_bot', key: hashApiKey(BOT_KEY), revoked: false, user_id: 'u_bot', expires_at: FUTURE, active_organization_id: ALPHA }, + { id: 'k_mia', key: hashApiKey(MIA_KEY), revoked: false, user_id: 'u_mia', expires_at: FUTURE, active_organization_id: ALPHA }, + ], + sys_user: [ + { id: 'u_bot', email: 'bot-31739@agents.invalid', principal_kind: 'agent', accountable_user_id: 'u_mia' }, + { id: 'u_mia', email: 'mia@example.com', principal_kind: 'human' }, + ], + sys_member: [ + { user_id: 'u_bot', organization_id: ALPHA, role: 'member' }, + { user_id: 'u_mia', organization_id: ALPHA, role: 'member' }, + ], + sys_user_position: [], + sys_user_permission_set: [ + { user_id: 'u_bot', permission_set: 'crm_lead_reader', organization_id: ALPHA }, + { user_id: 'u_bot', permission_set: 'crm_lead_super', organization_id: ALPHA }, + { user_id: 'u_bot', permission_set: 'admin_full_access', organization_id: DEFAULT_ORG }, + { user_id: 'u_mia', permission_set: 'crm_lead_reader', organization_id: ALPHA }, + { user_id: 'u_mia', permission_set: 'crm_lead_super', organization_id: ALPHA }, + ], + sys_organization: [{ id: DEFAULT_ORG, slug: 'default' }], + sys_permission_set: SETS.map((s) => ({ + id: `ps_${s.name}`, + name: s.name, + object_permissions: JSON.stringify(s.objects ?? {}), + ...(s.systemPermissions ? { system_permissions: JSON.stringify(s.systemPermissions) } : {}), + })), + sys_position: [{ id: 'pos_everyone', name: 'everyone', organization_id: null }], + sys_position_permission_set: [{ position_id: 'pos_everyone', permission_set_id: 'ps_crm_contact_reader' }], + }; +} + +/** Equality, `$in` and a NULL column; every other shape refused loudly. */ +function matchesWhere(row: any, where: any): boolean { + return Object.entries(where ?? {}).every(([field, cond]) => { + if (field.startsWith('$')) throw new Error(`fixture where-matcher: unsupported combinator '${field}'`); + if (cond !== null && typeof cond === 'object') { + if (!Array.isArray((cond as any).$in)) throw new Error(`fixture where-matcher: unsupported operator on '${field}'`); + return (cond as any).$in.includes(row[field]); + } + if (cond === null) return (row[field] ?? null) === null; + return row[field] === cond; + }); +} + +function schemaOf(name: string) { + return { + name, + sharingModel: 'public_read_write', + fields: { id: { name: 'id' }, name: { name: 'name', type: 'text' }, organization_id: { name: 'organization_id', type: 'text' } }, + }; +} + +type Verified = { userId: string; scopes: string[]; clientId?: string; organizationId?: string }; + +function rig() { + const t = tables(); + let middleware: any; + const ql: any = bindCatalogFromTables({ + registerMiddleware: (mw: any) => { if (!middleware) middleware = mw; }, + getSchema: (name: string) => (name.startsWith('sys_') ? undefined : schemaOf(name)), + async find(object: string, q: any = {}) { + const rows = (t[object] ?? []).filter((r) => matchesWhere(r, q?.where)); + return typeof q?.limit === 'number' ? rows.slice(0, q.limit) : rows; + }, + async findOne(object: string, q: any = {}) { + assertEngineFindOnePredicate(object, q); + return (t[object] ?? []).filter((r) => matchesWhere(r, q?.where))[0] ?? null; + }, + }, t); + + const tokens = new Map(); + const services: Record = { + manifest: { register: vi.fn() }, + objectql: ql, + metadata: { + get: async (_type: string, name: string) => (name.startsWith('sys_') ? null : schemaOf(name)), + list: async () => SETS, + }, + auth: { verifyMcpAccessToken: async (bearer: string) => tokens.get(bearer) ?? null }, + }; + + /** Resolve a request carrying `headers`, on the `/mcp` door (`acceptOAuthAccessToken`) or the dispatcher's face. */ + const resolve = (headers: Record, mcp: boolean): Promise => + resolveExecutionContext({ + ...(mcp ? { acceptOAuthAccessToken: true } : {}), + getService: async (name: string) => services[name], + getQl: async () => ql, + request: { headers }, + }); + + const resolveToken = async (verified: Verified): Promise => { + const bearer = `h.${tokens.size}.s`; + tokens.set(bearer, verified); + return resolve({ authorization: `Bearer ${bearer}` }, true); + }; + + const plugin = new SecurityPlugin({ fallbackPermissionSet: null }); + const boot = async () => { + const ctx: any = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: vi.fn(), + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + await plugin.init(ctx); + await plugin.start(ctx); + }; + + /** Run one operation through the security middleware; the engine body stands in for `next()`. */ + const run = async (context: ExecutionContext, operation: 'find', object: string) => { + const opCtx: any = { object, operation, ast: { where: undefined }, context }; + await middleware(opCtx, async () => { opCtx.result = []; }); + return opCtx; + }; + + /** The effective object permission the security service reports for `context` on `object`. */ + const effective = async (context: ExecutionContext, object: string) => + ((await (plugin as any).getEffectiveObjectPermissions(context)) as Record)[object]; + + /** The sets the plugin evaluates for `context`. */ + const sets = async (context: ExecutionContext): Promise => + (plugin as any).resolvePermissionSetsForContext(context); + + return { resolve, resolveToken, boot, run, effective, sets }; +} + +let warn: ReturnType; +beforeEach(() => { warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); }); +afterEach(() => { warn.mockRestore(); }); + +describe('[ADR-0151 D3] an AI service account\'s key admits the account itself', () => { + const r = rig(); + beforeAll(async () => { await r.boot(); }); + + for (const [door, mcp] of [['/mcp', true], ['the dispatcher', false]] as const) { + it(`on ${door}: userId is the account, principalKind 'agent', no onBehalfOf, no system permission, no everyone anchor, no admin standing`, async () => { + const ctx = await r.resolve({ 'x-api-key': BOT_KEY }, mcp); + expect(ctx.userId).toBe('u_bot'); + expect(ctx.principalKind).toBe('agent'); + expect(ctx.onBehalfOf).toBeUndefined(); + expect(Object.keys(ctx)).not.toContain('onBehalfOf'); + expect(ctx.oauthScopes).toBeUndefined(); + expect(ctx.systemPermissions).toEqual([]); + expect(ctx.positions).not.toContain('everyone'); + expect(ctx.positions).not.toContain('platform_admin'); + expect(ctx.posture).not.toBe('PLATFORM_ADMIN'); + expect(ctx.isSystem).toBe(false); + // Its own grants are its whole authority: the sets it holds, by name. + expect(ctx.permissions).toEqual(expect.arrayContaining(['crm_lead_reader', 'crm_lead_super'])); + expect(ctx.permissions).not.toContain('crm_contact_reader'); + }); + } + + it('the same key presented as `Authorization: Bearer` on /mcp admits the same account', async () => { + const ctx = await r.resolve({ authorization: `Bearer ${BOT_KEY}` }, true); + expect(ctx.userId).toBe('u_bot'); + expect(ctx.principalKind).toBe('agent'); + expect(ctx.onBehalfOf).toBeUndefined(); + }); + + it('a ceiling-breaching set it holds grants nothing above the ceiling — the set as it stands now, after any edit', async () => { + const ctx = await r.resolve({ 'x-api-key': BOT_KEY }, true); + const lead = await r.effective(ctx, LEAD); + // The ordinary grants of the set still hold… + expect(lead).toMatchObject({ allowRead: true, allowEdit: true }); + // …and nothing above the ceiling does. + for (const bit of ['viewAllRecords', 'modifyAllRecords', 'allowTransfer', 'allowRestoreOwnDeleted', 'manageRecycleBin']) { + expect(lead?.[bit], bit).not.toBe(true); + } + const held = await r.sets(ctx); + expect(held.map((s) => s.name)).toEqual(expect.arrayContaining(['crm_lead_super', 'admin_full_access'])); + for (const s of held) { + expect(s.systemPermissions ?? [], s.name).toEqual([]); + expect((s as any).adminScope, s.name).toBeUndefined(); + for (const entry of Object.values(s.objects ?? {})) { + expect((entry as any).viewAllRecords, s.name).not.toBe(true); + expect((entry as any).modifyAllRecords, s.name).not.toBe(true); + } + } + }); + + it('a read reachable only through the everyone anchor or the superuser wildcard is refused for the account', async () => { + const ctx = await r.resolve({ 'x-api-key': BOT_KEY }, true); + await expect(r.run(ctx, 'find', CONTACT)).rejects.toThrow(); + await expect(r.run(ctx, 'find', LEAD)).resolves.toBeDefined(); + }); +}); + +describe('CONTROLS — a person and an OAuth-delegated agent are unchanged', () => { + const r = rig(); + beforeAll(async () => { await r.boot(); }); + + it('a person\'s key holding the SAME sets: human, everyone, the system permission and the superuser bits all stand', async () => { + const ctx = await r.resolve({ 'x-api-key': MIA_KEY }, true); + expect(ctx.userId).toBe('u_mia'); + expect(ctx.principalKind).toBe('human'); + expect(ctx.onBehalfOf).toBeUndefined(); + expect(ctx.positions).toContain('everyone'); + expect(ctx.systemPermissions).toContain('manage_users'); + const lead = await r.effective(ctx, LEAD); + expect(lead).toMatchObject({ viewAllRecords: true, modifyAllRecords: true, allowTransfer: true }); + await expect(r.run(ctx, 'find', CONTACT)).resolves.toBeDefined(); + }); + + it('an OAuth-delegated agent keeps today\'s shape: principalKind agent WITH onBehalfOf naming the person', async () => { + const ctx = await r.resolveToken({ userId: 'u_mia', scopes: ['data:read'], clientId: CLIENT, organizationId: ALPHA }); + expect(ctx.userId).toBe('u_mia'); + expect(ctx.principalKind).toBe('agent'); + expect(ctx.onBehalfOf).toEqual({ userId: 'u_mia', principalKind: 'human' }); + expect(ctx.performedBy).toEqual(expect.objectContaining({ clientId: CLIENT })); + }); +}); diff --git a/packages/services/service-automation/src/engine.ts b/packages/services/service-automation/src/engine.ts index d08f5a5ae89..a9cc086d0ce 100644 --- a/packages/services/service-automation/src/engine.ts +++ b/packages/services/service-automation/src/engine.ts @@ -828,6 +828,12 @@ export interface FlowUserGrants { * a principal below it: the run sees less, never more. */ posture?: SeededRunContext['posture']; + /** + * [ADR-0151 D3] `'agent'` when the user is an AI service account + * (`resolveUserAuthzGrants`' own field, under its own name). Run setup seeds + * it beside the grants ({@link SeededRunContext.principalKind}). + */ + principalKind?: 'agent'; } /** diff --git a/packages/services/service-automation/src/plugin.ts b/packages/services/service-automation/src/plugin.ts index 68793fa1664..041151ab704 100644 --- a/packages/services/service-automation/src/plugin.ts +++ b/packages/services/service-automation/src/plugin.ts @@ -2130,6 +2130,8 @@ export class AutomationServicePlugin implements Plugin { // (`resolveAuthzContext` copies it off this same // resolution), derived once there and never here. ...(grants.posture ? { posture: grants.posture } : {}), + // [ADR-0151 D3] An AI service account runs as an agent. + ...(grants.principalKind ? { principalKind: grants.principalKind } : {}), ...(tenantId ? { tenantId } : {}), }; }); diff --git a/packages/services/service-automation/src/run-agent-account-kind.test.ts b/packages/services/service-automation/src/run-agent-account-kind.test.ts new file mode 100644 index 00000000000..446d2552b45 --- /dev/null +++ b/packages/services/service-automation/src/run-agent-account-kind.test.ts @@ -0,0 +1,62 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0151 D3] A `runAs: 'user'` run whose acting user is an AI service + * account carries `principalKind: 'agent'` onto every data operation it makes, + * so the security plugin evaluates the run as the agent principal it is — + * the agent ceiling, no member baseline — whether run setup resolved the + * account's grants (a record-change trigger hands it only a `userId`) or a + * door forwarded them with the kind. A person's run carries no kind (CONTROL), + * and a decision that moves the run to a decider drops the trigger user's + * kind with the rest of their facts. + */ + +import { describe, it, expect, vi } from 'vitest'; + +import { seedRunGrants } from './run-resume.js'; +import { resolveRunDataContext, runPrincipalKind } from './runtime-identity.js'; + +const host = (grants: Record) => ({ + userGrantsResolver: vi.fn(async () => grants as any), + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() } as any, +}); + +const ACCOUNT_GRANTS = { positions: ['org_member'], permissions: ['lead_reader'], org_user_ids: ['u_bot'], posture: 'MEMBER', principalKind: 'agent' }; +const PERSON_GRANTS = { positions: ['org_member', 'everyone'], permissions: ['lead_reader'], org_user_ids: ['u_mia'], posture: 'MEMBER' }; + +describe('[ADR-0151 D3] an AI service account\'s run is an agent principal on every write', () => { + it('run setup seeds the kind from the resolver, and every data operation carries it', async () => { + const run: any = { userId: 'u_bot', tenantId: 'org_1', runAs: 'user' }; + await seedRunGrants.call(host(ACCOUNT_GRANTS), 'lead_triage', run, 'triggering'); + expect(run.principalKind).toBe('agent'); + expect(runPrincipalKind(run)).toBe('agent'); + expect(resolveRunDataContext(run)).toMatchObject({ userId: 'u_bot', principalKind: 'agent', permissions: ['lead_reader'] }); + }); + + it('a door-forwarded kind beside forwarded grants is kept: setup does not re-resolve them', async () => { + const run: any = { userId: 'u_bot', tenantId: 'org_1', runAs: 'user', positions: ['org_member'], permissions: ['lead_reader'], principalKind: 'agent', email: 'b@x.invalid' }; + const h = host(ACCOUNT_GRANTS); + await seedRunGrants.call(h, 'lead_triage', run, 'triggering'); + expect(resolveRunDataContext(run)).toMatchObject({ principalKind: 'agent' }); + }); + + it('a kind forwarded WITHOUT grants is not kept on its own: it is re-seeded only by the resolution', async () => { + const run: any = { userId: 'u_mia', tenantId: 'org_1', runAs: 'user', principalKind: 'agent' }; + await seedRunGrants.call(host(PERSON_GRANTS), 'lead_triage', run, 'triggering'); + expect(run.principalKind).toBeUndefined(); + expect('principalKind' in (resolveRunDataContext(run) as object)).toBe(false); + }); + + it('CONTROL: a person\'s run carries no kind', async () => { + const run: any = { userId: 'u_mia', tenantId: 'org_1', runAs: 'user' }; + await seedRunGrants.call(host(PERSON_GRANTS), 'lead_triage', run, 'triggering'); + expect(run.principalKind).toBeUndefined(); + expect('principalKind' in (resolveRunDataContext(run) as object)).toBe(false); + }); + + it('only the literal agent kind is read', () => { + for (const value of ['human', 'AGENT', '', undefined, 1]) { + expect(runPrincipalKind({ principalKind: value } as any)).toBeUndefined(); + } + }); +}); diff --git a/packages/services/service-automation/src/run-resume.ts b/packages/services/service-automation/src/run-resume.ts index a7ed5ba3538..e25173fc8c1 100644 --- a/packages/services/service-automation/src/run-resume.ts +++ b/packages/services/service-automation/src/run-resume.ts @@ -217,7 +217,10 @@ export async function seedRunGrants( // grants it was not derived from: the resolution below re-seeds the rung // with the grants, and a run whose grants stay unresolved (the resolver // throws, answers nothing, or is not wired) carries none. - if (needsGrants) delete (runContext as SeededRunContext).posture; + if (needsGrants) { + delete (runContext as SeededRunContext).posture; + delete (runContext as SeededRunContext).principalKind; + } if ( runContext.runAs !== 'system' && runContext.userId && @@ -236,6 +239,9 @@ export async function seedRunGrants( // only with them: carried grants keep the rung they came // with, so a narrowed ceiling never gains a wider rung. if (grants.posture) (runContext as SeededRunContext).posture = grants.posture; + // [ADR-0151 D3] An AI service account runs as the agent + // principal it is, under the agent ceiling. + if (grants.principalKind === 'agent') (runContext as SeededRunContext).principalKind = 'agent'; } if (needsPeers && Array.isArray(grants.org_user_ids)) { (runContext as SeededRunContext).org_user_ids = grants.org_user_ids; @@ -350,6 +356,9 @@ async function deciderSegmentContext( // platform administrator's submission would hand a member's decision // segment the deployment-level rows. Seeded for the decider below. delete switched.posture; + // [ADR-0151 D3] The trigger user's kind is theirs too: a decider is + // resolved afresh, and only an account is an agent. + delete switched.principalKind; // The impersonating administrator belonged to the write that STARTED the // run: the segment the decider owns names only the administrator, if any, // who made THIS decision while impersonating the decider. diff --git a/packages/services/service-automation/src/runtime-identity.ts b/packages/services/service-automation/src/runtime-identity.ts index 8ea2838dc4e..55fe29163b0 100644 --- a/packages/services/service-automation/src/runtime-identity.ts +++ b/packages/services/service-automation/src/runtime-identity.ts @@ -92,6 +92,13 @@ export interface RunIdentityContext { * run, whose `isSystem` short-circuit precedes every reader of it. */ posture?: AuthzPosture; + /** + * [ADR-0151 D3] `'agent'` when the acting user is an AI service account, the + * kernel `ExecutionContext.principalKind`: the security plugin then applies + * the agent ceiling and withholds the member baseline. Present on a + * `runAs:'user'` run whose setup seeded it ({@link runPrincipalKind}). + */ + principalKind?: 'agent'; /** Acting user's tenant/org id. */ tenantId?: string; /** @@ -210,6 +217,13 @@ export interface SeededRunContext extends AutomationContext { * it with the rest of the trigger user's facts. */ posture?: AuthzPosture; + /** + * [ADR-0151 D3] `'agent'` when the acting user is an AI service account, as + * the same resolver reports it (`resolveUserAuthzGrants`' `principalKind`). + * Seeded with the positions and permission sets, and removed with them by + * the decision switch: it is the acting user's fact. + */ + principalKind?: 'agent'; /** * Who TRIGGERED the run, recorded when a human decision moved the run's * acting identity (`userId`) to the decider (ruling A on `FlowSchema.runAs`; @@ -259,6 +273,15 @@ export function runPosture(context: AutomationContext | undefined): AuthzPosture return parsed.success ? parsed.data : undefined; } +/** + * [ADR-0151 D3] `'agent'` when run setup seeded the acting user as an AI + * service account ({@link SeededRunContext.principalKind}), `undefined` for a + * person. + */ +export function runPrincipalKind(context: AutomationContext | undefined): 'agent' | undefined { + return (context as SeededRunContext | undefined)?.principalKind === 'agent' ? 'agent' : undefined; +} + /** * Translate a flow run's {@link AutomationContext} into the ObjectQL `context` * its CRUD nodes must pass, honoring `runAs` (ADR-0049 / #1888): @@ -432,6 +455,7 @@ export function resolveRunDataContext(context: AutomationContext | undefined): R if (context.email) out.email = context.email; const posture = runPosture(context); if (posture) out.posture = posture; + if (runPrincipalKind(context)) out.principalKind = 'agent'; if (context.tenantId) out.tenantId = context.tenantId; if (flowRunId) out.flowRunId = flowRunId; if (locale) out.locale = locale; diff --git a/packages/services/service-storage/src/attachment-access-hooks.ts b/packages/services/service-storage/src/attachment-access-hooks.ts index bfa11fd862f..3bd4c3fd4de 100644 --- a/packages/services/service-storage/src/attachment-access-hooks.ts +++ b/packages/services/service-storage/src/attachment-access-hooks.ts @@ -344,7 +344,11 @@ function asIdList(id: unknown): Array | null { * D10 rule "an agent's grants are EXACTLY its scope-derived ceiling" on * `principalKind === 'agent'`; stripped, the additive human baseline was * appended to an agent's ceiling on this path, so the sets the bypass - * probe evaluated were a SUPERSET of what the user consented to. + * probe evaluated were a SUPERSET of what the user consented to. The + * same key carries an AI service account (ADR-0151 D3: `principalKind: + * 'agent'`, no `onBehalfOf`), whose grants are its own assignments under + * the agent ceiling, with no member baseline: stripped, it would read as + * a person and gain the baseline and lose the ceiling clamp. * * `systemPermissions`, `accessible_org_ids`, `posture`, `audience` and * `rlsMembership` were dropped by the same projection; they are forwarded diff --git a/packages/services/service-storage/src/storage-service-plugin.ts b/packages/services/service-storage/src/storage-service-plugin.ts index d90d033f021..8e87c4bc9a3 100644 --- a/packages/services/service-storage/src/storage-service-plugin.ts +++ b/packages/services/service-storage/src/storage-service-plugin.ts @@ -1340,6 +1340,8 @@ function bindRecordFileAccess( ...(grants.posture ? { posture: grants.posture } : {}), ...(grants.audience ? { audience: grants.audience } : {}), ...(grants.email ? { email: grants.email } : {}), + // [ADR-0151 D3] An AI service account reads as the agent it is. + ...(grants.principalKind ? { principalKind: grants.principalKind } : {}), }; }, getDownloadTtl: () => DEFAULT_DOWNLOAD_TTL, From 1f4c7b84342daff5636e7207b381ac6275929db9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 06:30:02 +0000 Subject: [PATCH 2/9] test(core): an organization administrator set gives an AI service account no organization standing Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- .../resolve-authz-context.agent-account.test.ts | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/packages/core/src/security/resolve-authz-context.agent-account.test.ts b/packages/core/src/security/resolve-authz-context.agent-account.test.ts index 7056290fa23..f46a01924a2 100644 --- a/packages/core/src/security/resolve-authz-context.agent-account.test.ts +++ b/packages/core/src/security/resolve-authz-context.agent-account.test.ts @@ -98,6 +98,21 @@ describe('[ADR-0151 D3] resolveUserAuthzGrants — an AI service account', () => expect(await hasPlatformAdminStanding(makeQl(), 'u_bot', { nowMs: NOW })).toBe(false); }); + it('an organization administrator set confers no organization standing on it, while a person holding it rises', async () => { + const t = tables(); + t.sys_user_permission_set = [ + { user_id: 'u_bot', permission_set: 'organization_admin', organization_id: 'org_a' }, + { user_id: 'u_mia', permission_set: 'organization_admin', organization_id: 'org_a' }, + ]; + t.sys_permission_set.push({ id: 'ps_org_admin', name: 'organization_admin' }); + const account = await resolveUserAuthzGrants(makeQl(t), 'u_bot', { tenantId: 'org_a', nowMs: NOW }); + const person = await resolveUserAuthzGrants(makeQl(t), 'u_mia', { tenantId: 'org_a', nowMs: NOW }); + expect(account.permissions).toContain('organization_admin'); + expect(account.posture).toBe('MEMBER'); + expect(person.posture).not.toBe('MEMBER'); + expect(person.posture).not.toBe('PLATFORM_ADMIN'); + }); + it('a seeded caller cannot skip the kind: the row is read whatever is seeded', async () => { const grants = await resolveUserAuthzGrants(makeQl(), 'u_bot', { tenantId: 'org_a', nowMs: NOW, seedEmail: 'seeded@corp.example', seedPermissions: ['ai_seat'], From 44a5cd01e1d9b98b2c294fb00b7862751a9a09f8 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 06:32:49 +0000 Subject: [PATCH 3/9] test(plugin-security): an AI service account's effective access lists the agent floor as its default Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- .../src/effective-access.test.ts | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/packages/plugins/plugin-security/src/effective-access.test.ts b/packages/plugins/plugin-security/src/effective-access.test.ts index 478ea7e189d..6c362fabf13 100644 --- a/packages/plugins/plugin-security/src/effective-access.test.ts +++ b/packages/plugins/plugin-security/src/effective-access.test.ts @@ -251,3 +251,34 @@ describe('[ADR-0090 D6/D12] refusals: an unknown user is indistinguishable from expect(await refusalOf(describeAs(host(ql, baseline), '', ADMIN))).toEqual(forbidden); }); }); + +describe('[ADR-0151 D3] an AI service account\'s effective access: its own grants, the agent floor as its default', () => { + it('lists its direct set and the restricted set as `default` — never the everyone anchor\'s sets or the member baseline', async () => { + const { ql, baseline } = defaultsDeployment({ + sys_user: [ + { id: 'u_bot', email: 'bot@agents.invalid', principal_kind: 'agent', accountable_user_id: 'u_member' }, + { id: 'u_admin', email: 'admin@example.test' }, + ], + sys_member: [ + { user_id: 'u_bot', organization_id: ORG, role: 'member' }, + { user_id: 'u_admin', organization_id: ORG, role: 'member' }, + ], + sys_user_position: [], + sys_user_permission_set: [{ user_id: 'u_bot', permission_set: 'forecasting', organization_id: ORG }], + }); + const answer = await describeAs(host(ql, baseline), 'u_bot', ADMIN); + expect(answer.positions).not.toContain('everyone'); + expect(originsOf(answer)).toEqual({ + forecasting: [{ kind: 'direct' }], + mcp_agent_restricted: [{ kind: 'default' }], + }); + }); + + it('CONTROL: a person in the same deployment keeps the everyone anchor and the member baseline', async () => { + const { ql, baseline } = defaultsDeployment(); + const answer = await describeAs(host(ql, baseline), 'u_member', ADMIN); + expect(answer.positions).toContain('everyone'); + expect(originsOf(answer)).toMatchObject({ member_default: expect.arrayContaining([{ kind: 'default' }]) }); + expect(Object.keys(originsOf(answer))).not.toContain('mcp_agent_restricted'); + }); +}); From 95eae55f90555fd289345d49827fef2fe41b978a Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 06:36:19 +0000 Subject: [PATCH 4/9] chore: changeset for the AI service account ceiling Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- .../31739-ai-service-account-ceiling.md | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 .changeset/31739-ai-service-account-ceiling.md diff --git a/.changeset/31739-ai-service-account-ceiling.md b/.changeset/31739-ai-service-account-ceiling.md new file mode 100644 index 00000000000..fbdca3ca074 --- /dev/null +++ b/.changeset/31739-ai-service-account-ceiling.md @@ -0,0 +1,28 @@ +--- +'@objectstack/core': patch +'@objectstack/mcp': patch +'@objectstack/objectql': patch +'@objectstack/plugin-audit': patch +'@objectstack/plugin-auth': patch +'@objectstack/plugin-security': patch +'@objectstack/rest': patch +'@objectstack/runtime': patch +'@objectstack/service-automation': patch +'@objectstack/service-storage': patch +--- + +feat(security): an AI service account is the agent principal of its own requests, under the agent ceiling (ADR-0151 D3) + +Clause-②: no (narrowing) +Metadata-protocol: none + +An AI service account (a `sys_user` row whose `principal_kind` is `agent`) now acts as itself. Its API key, on REST, on `/mcp` and over stdio, admits a context whose `userId` is the account, with `principalKind: 'agent'` and no `onBehalfOf`. Its own grants are its whole authority: + +- It does not receive the `everyone` anchor's permission sets or the member baseline. Its floor is the restricted agent set, so a new account can do nothing until it is granted something. +- It carries no system permission and is never a platform or organization administrator, whatever it holds. +- Every agent principal's permission sets are read under the agent ceiling: no View All, no Modify All, no transfer, restore or purge, no system permission and no admin scope. A set edited after it was assigned still grants nothing above the ceiling. The permission sets an OAuth-connected assistant receives carry none of these bits, so it is unchanged. +- Assigning an account a permission set, or a position whose sets, carry any of those bits is refused `400 VALIDATION_FAILED` (`invalid_value`), naming the set and what in it is above the ceiling. + +Flow runs, attachment and comment access checks, mention checks and the access explainer read the account as the agent it is. A person's sign-in, keys and grants are unchanged. + +Nothing registers an AI service account yet; the registration, key and lifecycle doors follow in a later change. From 211f6ce3e29dcb3cbae5e9c94ca7cf8e8312c39d Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 06:41:16 +0000 Subject: [PATCH 5/9] chore: changeset declares the agent ceiling narrowing and its ADR-0087 disposition Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- .changeset/31739-ai-service-account-ceiling.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/.changeset/31739-ai-service-account-ceiling.md b/.changeset/31739-ai-service-account-ceiling.md index fbdca3ca074..2397a859b1c 100644 --- a/.changeset/31739-ai-service-account-ceiling.md +++ b/.changeset/31739-ai-service-account-ceiling.md @@ -11,11 +11,19 @@ '@objectstack/service-storage': patch --- -feat(security): an AI service account is the agent principal of its own requests, under the agent ceiling (ADR-0151 D3) +feat(security)!: an AI service account is the agent principal of its own requests, under the agent ceiling (ADR-0151 D3) -Clause-②: no (narrowing) +Clause-②: no (narrowing) — every agent principal's permission sets are now read under the agent ceiling (no View All, no Modify All, no transfer, restore or purge, no system permission, no admin scope). The OAuth-connected assistant's first-party sets carry none of these bits, so only a deployment that edited its own agent set to carry one sees a narrower answer. No door, request or response shape, error code or status changes. Metadata-protocol: none + + +**BREAKING** for an agent principal whose permission sets carry View All, Modify All, a destructive grant (transfer, restore, purge), a system permission or an admin scope. Measured first-party: 0 (none of the 3 OAuth agent ceiling sets carries any of these bits, and no AI service account row can exist until registration lands). + +- **Before.** An agent principal's sets were applied as written. +- **Now.** Those bits are cleared when the sets are read, and assigning such a set (or a position binding one) to an AI service account is refused by name. +- **The remedy.** Grant the agent the CRUD bits it needs on the objects it reads; a bypass bit or an administrative grant is a person's to hold. + An AI service account (a `sys_user` row whose `principal_kind` is `agent`) now acts as itself. Its API key, on REST, on `/mcp` and over stdio, admits a context whose `userId` is the account, with `principalKind: 'agent'` and no `onBehalfOf`. Its own grants are its whole authority: - It does not receive the `everyone` anchor's permission sets or the member baseline. Its floor is the restricted agent set, so a new account can do nothing until it is granted something. From 0c2ef4252b3ed241d7091c490127d9ecae2f0d3f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 07:29:10 +0000 Subject: [PATCH 6/9] fix(plugin-security): the AI service account grant refusal reads only a holder the caller can read A grant naming a holder the caller's own door does not return is left to the engine's reference check, as the membership refusal leaves it; the account refusal no longer reads that holder as the system, so its answer cannot name the kind of a user the caller cannot read. A composition with no sys_user object has no account to judge. The caller's read is shared with the membership refusal through one per-write memo. Registers the bypass on the system-context page, and pins the new test doubles the way the double gates require. Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- content/docs/permissions/system-context.mdx | 3 + .../src/__tests__/stdio-agent-account.test.ts | 15 ++++- .../src/agent-account-grant-refusal.test.ts | 41 +++++++++++++ .../src/agent-account-grant-refusal.ts | 26 ++++++-- .../src/agent-ceiling-clamp.test.ts | 2 +- .../src/grant-holder-membership-refusal.ts | 15 ++++- .../src/rest-api-key-agent-account.test.ts | 59 +++++++++++-------- ...tomation-connector-connection-door.test.ts | 2 + scripts/engine-double-contract.pinned.json | 5 ++ 9 files changed, 134 insertions(+), 34 deletions(-) diff --git a/content/docs/permissions/system-context.mdx b/content/docs/permissions/system-context.mdx index 500d638440f..fa136b5c8dc 100644 --- a/content/docs/permissions/system-context.mdx +++ b/content/docs/permissions/system-context.mdx @@ -140,6 +140,7 @@ bugs — it is the protection or the side effect that silently does not happen. | 23d | **Grant-holder membership check skipped** — a `sys_user_position` or `sys_user_permission_set` write naming a user with no `sys_member` row in the row's organization is not refused | plugin-security | Get: a system writer can store such a grant — invitation acceptance writes the membership and its placement together, and seed replay, the organization-admin reconcile and the platform bootstraps write grants as the system. Lose: such a row takes effect once its user is admitted to the organization. A non-system insert, or a non-system update that moves `user_id` or `organization_id`, is refused `400 VALIDATION_FAILED` / `reference_not_found` at `user_id` instead, for every caller, a platform administrator included; the membership is read as `{ isSystem: true, tenantId }` with `tenantId` the row's own organization, never another one. A row stored with no organization is not judged. Under `single`, 18.0 stamps a new grant with the Default Organization, so such a row is one an earlier release wrote | `packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts#onInsert`, `packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts#onUpdate` | | 23e | **A `secret` field takes a stored reference as given** — a value already spelled `secret:` is stored unchanged | objectql | Get: a system writer may copy a `secret:` reference onto a record as it stands (seed replay, a migration). Every other caller may only seal a new value or keep its own record's ref, and its own is the value it reads in that column: on a create any such value is refused, and on an update it would be kept only where every record the write lands on serves exactly that reference to this caller's own read door. The read path serves a `secret` column masked to every caller, so every reference such a caller sends is refused `400 VALIDATION_ERROR` before anything is written, with one answer whatever it names and whatever the column holds; an echoed read mask still leaves the column as it is. Lose: the check that the reference is the record's own — a system writer that copies one is trusted to mean it. Inbound HTTP never carries the flag | `encryptSecretFields` | | 23f | **Agent ceiling grant check skipped** — a `sys_user_permission_set` write naming an MCP agent ceiling set is not refused | plugin-security | Get: a system writer is not judged. The platform-admin promotion and the organization-admin reconcile name their sets in code, and neither is a ceiling; the self-registration grant writes the configured `audience.selfRegistrationPermissionSet`, which the audience validation (`assertAudienceConfig`, plugin-auth) refuses when it names an agent ceiling set. Lose: seed replay and the development-only demo-staff seed write the sets their stack declares, unjudged, so a seed that names an agent ceiling set stores it. A non-system insert, or a non-system update whose resulting row names one, is refused `400 VALIDATION_FAILED` / `invalid_value` at `permission_set`, for every caller, a platform administrator included; a delete is not judged (ADR-0090 D10) | `packages/plugins/plugin-security/src/agent-ceiling-grant-refusal.ts#onInsert`, `packages/plugins/plugin-security/src/agent-ceiling-grant-refusal.ts#onUpdate` | +| 23g | **AI service account grant check skipped** — a `sys_user_permission_set` or `sys_user_position` write giving an AI service account a set above the agent ceiling is not refused | plugin-security | Get: a system writer is not judged. The organization-admin reconcile binds nothing for an account, and the platform bootstraps grant only people. Lose: seed replay writes the grants its stack declares, unjudged, so a seed that gives an account a set carrying View All, Modify All, transfer, restore, purge, a system permission or an admin scope stores it; those bits are still cleared when the account's sets are evaluated (`packages/plugins/plugin-security/src/agent-ceiling-clamp.ts`). A non-system insert, or a non-system update whose resulting row gives an account such a set (directly, or through a position binding one), is refused `400 VALIDATION_FAILED` / `invalid_value` at `permission_set` or `position`, for every caller, a platform administrator included; the holder's `sys_user` row is read as the system only when the caller's own door reads it; a delete is not judged | `packages/plugins/plugin-security/src/agent-account-grant-refusal.ts#onInsert`, `packages/plugins/plugin-security/src/agent-account-grant-refusal.ts#onUpdate` | | 24 | Tenant-audit warning silenced; `bypassTenantAudit` threaded to the driver | objectql | Get: unscoped system writes stop warning. Lose: the signal that would flag a genuine user-path scoping bug | `buildDriverOptions` | | 25 | Engine-owned / append-only write guard bypassed | plugin-security | Get: generic writes to `managedBy` engine-owned objects | `packages/plugins/plugin-security/src/system-write-guard.ts#isUserContextWrite`, `packages/plugins/plugin-security/src/system-write-guard.ts#assertEngineOwnedWriteAllowed` | | 26 | Identity write guard bypassed (ADR-0092) | plugin-auth | Get: direct writes to identity tables through the generic data path | `packages/plugins/plugin-auth/src/identity-write-guard.ts#isUserContextWrite` | @@ -590,6 +591,8 @@ and CI refuses one that differs from what the tree produces. | `packages/plugins/plugin-auth/src/owner-fixed-rule.ts#isOwnerChange` | 1 | 26c | | `packages/plugins/plugin-auth/src/principal-session-mint.ts#refuseUpFront` | 1 | 61b | | `packages/plugins/plugin-email/src/email-template-door.ts#isOrganizationWrite` | 1 | 59 | +| `packages/plugins/plugin-security/src/agent-account-grant-refusal.ts#onInsert` | 1 | 23g | +| `packages/plugins/plugin-security/src/agent-account-grant-refusal.ts#onUpdate` | 1 | 23g | | `packages/plugins/plugin-security/src/agent-ceiling-grant-refusal.ts#onInsert` | 1 | 23f | | `packages/plugins/plugin-security/src/agent-ceiling-grant-refusal.ts#onUpdate` | 1 | 23f | | `packages/plugins/plugin-security/src/flow-system-identity-write-refusal.ts#elevationSource` | 1 | 1b | diff --git a/packages/mcp/src/__tests__/stdio-agent-account.test.ts b/packages/mcp/src/__tests__/stdio-agent-account.test.ts index 37f3d084dfd..55a6d1246e7 100644 --- a/packages/mcp/src/__tests__/stdio-agent-account.test.ts +++ b/packages/mcp/src/__tests__/stdio-agent-account.test.ts @@ -41,6 +41,19 @@ interface FindCall { options: { context?: ExecutionContext; where?: Record }; } +/** + * Scalar equality only. A combinator or an operator is not implemented here, so + * it is refused rather than read as a field name. + */ +function matchesWhere(row: Record, where: Record): boolean { + return Object.entries(where).every(([k, v]) => { + if (k.startsWith('$') || (v !== null && typeof v === 'object')) { + throw new Error(`stdio-agent-account double: unsupported where ${JSON.stringify(where)}`); + } + return row[k] === v; + }); +} + function createHarness() { const finds: FindCall[] = []; const ql = { @@ -49,7 +62,7 @@ function createHarness() { const rows = TABLES[object]; if (!rows) return object.startsWith('sys_') ? [] : [{ id: 'r_1', name: 'Acme' }]; const where = options?.where ?? {}; - return rows.filter((row) => Object.entries(where).every(([k, v]) => row[k] === v)); + return rows.filter((row) => matchesWhere(row, where)); }), }; const metadata = { diff --git a/packages/plugins/plugin-security/src/agent-account-grant-refusal.test.ts b/packages/plugins/plugin-security/src/agent-account-grant-refusal.test.ts index 76e9f5444c8..4689b12e458 100644 --- a/packages/plugins/plugin-security/src/agent-account-grant-refusal.test.ts +++ b/packages/plugins/plugin-security/src/agent-account-grant-refusal.test.ts @@ -24,6 +24,7 @@ import { SqlDriver } from '@objectstack/driver-sql'; import { resolveThrownHttpError } from '@objectstack/types'; import type { PermissionSet } from '@objectstack/spec/security'; import { SysUser } from '@objectstack/platform-objects/identity'; +import { bindSecurityCatalogReader } from '@objectstack/core'; import { SecurityPlugin } from './security-plugin.js'; import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; @@ -217,6 +218,46 @@ describe('[ADR-0151 D3] a set above the agent ceiling is refused for an AI servi expect(await rows(h, 'sys_user_permission_set', { user_id: 'u_bot' })).toHaveLength(1); }); + /** The bound `beforeInsert` handler over a double engine whose user row is an account. */ + function boundInsertHandler(opts: { hasUserObject: boolean }) { + const handlers: Record Promise> = {}; + const find = vi.fn(async () => [{ id: 'u_bot', principal_kind: 'agent' }]); + const engine = { + registerHook: (event: string, handler: any) => { handlers[event] = handler; }, + find, + getSchema: (name: string) => (name === 'sys_user' && !opts.hasUserObject ? undefined : { name }), + }; + bindSecurityCatalogReader(engine, { + resolve: async (kind: string, name: string) => (kind === 'permission' && name === BREACHING_SET + ? { definition: { name, objects: { crm_lead: { allowRead: true, viewAllRecords: true } } } } + : undefined), + } as any); + expect(registerAgentAccountGrantRefusal(engine)).toBe(true); + return { handler: handlers.beforeInsert!, find }; + } + + const insertCtx = (callerReads: boolean) => ({ + object: 'sys_user_permission_set', + session: { userId: 'u_caller' }, + input: { data: { user_id: 'u_bot', permission_set: BREACHING_SET } }, + api: { object: () => ({ find: async () => (callerReads ? [{ id: 'u_bot' }] : []) }) }, + }); + + it('a holder the caller\'s own door does not read is never read as the system, and is not judged here', async () => { + const { handler, find } = boundInsertHandler({ hasUserObject: true }); + await expect(handler(insertCtx(false))).resolves.toBeUndefined(); + expect(find).not.toHaveBeenCalled(); + // CONTROL: the same row, with a holder the caller reads, is read and refused. + expectAccountRefusal(await refusalOf(() => handler(insertCtx(true))), 'permission_set', BREACHING_SET); + expect(find).toHaveBeenCalledTimes(1); + }); + + it('a composition with no sys_user object has no account to judge, and reads none', async () => { + const { handler, find } = boundInsertHandler({ hasUserObject: false }); + await expect(handler(insertCtx(true))).resolves.toBeUndefined(); + expect(find).not.toHaveBeenCalled(); + }); + it('binds once, and says so when the engine has no hook registry', () => { const registerHook = vi.fn(); const unregisterHooksByPackage = vi.fn(); diff --git a/packages/plugins/plugin-security/src/agent-account-grant-refusal.ts b/packages/plugins/plugin-security/src/agent-account-grant-refusal.ts index 310b282786f..351cf8c3a65 100644 --- a/packages/plugins/plugin-security/src/agent-account-grant-refusal.ts +++ b/packages/plugins/plugin-security/src/agent-account-grant-refusal.ts @@ -32,14 +32,22 @@ * so no existing write is narrowed. A DELETE is never judged. * * It stands down on every `isSystem` write, the stand-down its sibling - * refusals on these tables take, and on a value the catalog holds no - * definition for (the catalog refusals answer that). + * refusals on these tables take; on a value the catalog holds no definition + * for (the catalog refusals answer that); in a composition with no `sys_user` + * object; and on a holder the caller's own read door does not return. That + * last one is the membership refusal's discipline: the engine's reference + * check answers an unreadable holder as one that does not exist, and a + * refusal naming its kind would tell the caller what it cannot read. The + * clamp at evaluation still holds for such a row. * * ## Reads, and what a failed one does * - * One `sys_user` read per judged row, by id, under the system context in the - * writer's transaction; a read that throws propagates, as the membership - * refusal's does. The set and position definitions come from the security + * First the caller's own read of the holder, projected to its id — the read + * the membership refusal asks, memoised per write, so a row both judge pays + * it once (`callerReadsGrantHolder`). Then, for a holder the caller reads, + * one `sys_user` read by id under the system context in the writer's + * transaction; a read that throws propagates, as the membership refusal's + * does. The set and position definitions come from the security * catalog bound to the engine (`securityCatalogReaderOf`, the reader every * grant refusal asks). A catalog read that throws is reported at `warn` and * the write proceeds unjudged: the clamp still holds. @@ -63,6 +71,7 @@ import type { FieldErrorCode } from '@objectstack/spec/api'; import { classifyFilterToken, isPlainRecord } from '@objectstack/spec/data'; import { validationFailure } from '@objectstack/types'; import { agentCeilingBreaches } from './agent-ceiling-clamp.js'; +import { callerReadsGrantHolder } from './grant-holder-membership-refusal.js'; import { GRANT_OBJECT, GRANT_SET_NAME_FIELD, grantSetNameOf } from './grant-permission-set-name.js'; import { POSITION_ASSIGNMENT_OBJECT, POSITION_FIELD } from './position-catalog-refusal.js'; import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; @@ -171,6 +180,7 @@ interface AgentAccountGrantEngine { ) => void; unregisterHooksByPackage?: (packageId: string) => number; find?: (object: string, query: any) => Promise; + getSchema?: (object: string) => unknown; } type Logger = { warn?: (msg: string, meta?: any) => void } | undefined; @@ -192,6 +202,8 @@ function nameOf(value: unknown): string | undefined { /** Is `userId` an AI service account? One `sys_user` read by id, in the writer's transaction. Throws when it fails. */ async function isAgentAccount(engine: AgentAccountGrantEngine, userId: string, transaction: unknown): Promise { if (typeof engine.find !== 'function') return false; + // A composition with no user object holds no account to judge. + if (typeof engine.getSchema === 'function' && !engine.getSchema(USER_OBJECT)) return false; const context: Record = { isSystem: true }; if (transaction !== undefined) context.transaction = transaction; // A placeholder-shaped id is compared literally, as the membership refusal compares it. @@ -232,6 +244,10 @@ async function judge( if (value === undefined) return; const catalog = securityCatalogReaderOf(engine); if (!catalog) return; + // A holder the caller's own door does not read is never read here: the + // engine's reference check (or the stored row) answers it, and an answer + // naming the holder's kind would tell the caller what it cannot read. + if ((await callerReadsGrantHolder(ctx, image[HOLDER_FIELD], userId)) === false) return; if (!(await isAgentAccount(engine, userId, ctx?.transaction))) return; let breaching: AgentAccountBreachingSet[]; try { diff --git a/packages/plugins/plugin-security/src/agent-ceiling-clamp.test.ts b/packages/plugins/plugin-security/src/agent-ceiling-clamp.test.ts index 43dd8041c81..23d6f8ae48f 100644 --- a/packages/plugins/plugin-security/src/agent-ceiling-clamp.test.ts +++ b/packages/plugins/plugin-security/src/agent-ceiling-clamp.test.ts @@ -119,7 +119,7 @@ describe('the security plugin reads every agent principal\'s sets under the ceil const services: Record = { manifest: { register: vi.fn() }, // An engine double: the middleware is registered and never driven here. - objectql: { registerMiddleware: vi.fn(), getSchema: () => undefined, find: async () => [], findOne: async () => null }, + objectql: { registerMiddleware: vi.fn(), getSchema: () => undefined, find: async () => [] }, metadata: { get: async () => null, list: async () => [BREACHING, CLEAN] }, }; const ctx = { diff --git a/packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts b/packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts index 8fde22781e6..7353ee5aaaa 100644 --- a/packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts +++ b/packages/plugins/plugin-security/src/grant-holder-membership-refusal.ts @@ -370,14 +370,25 @@ async function holderLeftToReferenceCheck( userId: string, ): Promise { if (!referenceCheckAsksCaller(engine, ctx.object)) return false; + const reads = await callerReadsGrantHolder(ctx, holder, userId); + return reads === false; +} + +/** + * Does the caller's own read door return the grant holder `userId`? The same + * projected-to-id read this refusal asks, memoised per write, so a sibling + * hook judging the same row (`agent-account-grant-refusal.ts`) pays no read + * of its own. `undefined` when the dispatch carries no caller api to ask. + */ +export async function callerReadsGrantHolder(ctx: any, holder: unknown, userId: string): Promise { const memo = memoOf(readsByWrite, ctx); let reads = memo?.get(userId); if (reads === undefined) { reads = await callerReadsHolder(ctx, holder, userId); - if (reads === undefined) return false; + if (reads === undefined) return undefined; memo?.set(userId, reads); } - return !reads; + return reads; } /** diff --git a/packages/rest/src/rest-api-key-agent-account.test.ts b/packages/rest/src/rest-api-key-agent-account.test.ts index b236dfe9184..5953209f56f 100644 --- a/packages/rest/src/rest-api-key-agent-account.test.ts +++ b/packages/rest/src/rest-api-key-agent-account.test.ts @@ -9,6 +9,8 @@ // uses). CONTROL: a person's key over the same store is unchanged. import { describe, it, expect, vi } from 'vitest'; +// The route modules load ObjectQL lazily; pay that load at collection, never in a clocked case. +import '@objectstack/objectql'; import { hashApiKey } from '@objectstack/core'; import { RestServer } from './rest-server'; import { bindTestSecurityCatalog } from './__tests__/security-catalog.testkit.js'; @@ -41,33 +43,40 @@ const USERS: Record> = { u_mia: { id: 'u_mia', email: 'mia@example.com', principal_kind: 'human' }, }; +/** The rows the store holds for `object` under the `where` of `opts`, before any bound. */ +function rowsOf(object: string, opts: any): Record[] { + const where = opts?.where ?? {}; + if (object === 'sys_api_key') { + const rows = [ + { id: 'k_bot', key: hashApiKey(BOT_KEY), revoked: false, user_id: 'u_bot', expires_at: FUTURE, active_organization_id: 'org_a' }, + { id: 'k_mia', key: hashApiKey(MIA_KEY), revoked: false, user_id: 'u_mia', expires_at: FUTURE, active_organization_id: 'org_a' }, + ]; + return rows.filter((row) => Object.entries(where).every(([k, v]) => (row as any)[k] === v)); + } + if (object === 'sys_user') return USERS[where.id] ? [USERS[where.id]] : []; + if (object === 'sys_member') { + const rows = [ + { user_id: 'u_bot', organization_id: 'org_a', role: 'member' }, + { user_id: 'u_mia', organization_id: 'org_a', role: 'member' }, + ]; + return rows.filter((row) => Object.entries(where).every(([k, v]) => (row as any)[k] === v)); + } + if (object === 'sys_organization') return [{ id: 'org_default', slug: 'default' }]; + if (object === 'sys_user_permission_set') { + if (where.user_id !== 'u_bot' && where.user_id !== 'u_mia') return []; + return [ + { user_id: where.user_id, permission_set: 'ops_tools', organization_id: 'org_a' }, + { user_id: where.user_id, permission_set: 'admin_full_access', organization_id: 'org_default' }, + ]; + } + return []; +} + const makeQl = () => bindTestSecurityCatalog({ + // The caller's bound applies after the filter, by presence, as ObjectQL applies it. find: async (object: string, opts: any) => { - const where = opts?.where ?? {}; - if (object === 'sys_api_key') { - const rows = [ - { id: 'k_bot', key: hashApiKey(BOT_KEY), revoked: false, user_id: 'u_bot', expires_at: FUTURE, active_organization_id: 'org_a' }, - { id: 'k_mia', key: hashApiKey(MIA_KEY), revoked: false, user_id: 'u_mia', expires_at: FUTURE, active_organization_id: 'org_a' }, - ]; - return rows.filter((row) => Object.entries(where).every(([k, v]) => (row as any)[k] === v)); - } - if (object === 'sys_user') return USERS[where.id] ? [USERS[where.id]] : []; - if (object === 'sys_member') { - const rows = [ - { user_id: 'u_bot', organization_id: 'org_a', role: 'member' }, - { user_id: 'u_mia', organization_id: 'org_a', role: 'member' }, - ]; - return rows.filter((row) => Object.entries(where).every(([k, v]) => (row as any)[k] === v)); - } - if (object === 'sys_organization') return [{ id: 'org_default', slug: 'default' }]; - if (object === 'sys_user_permission_set') { - if (where.user_id !== 'u_bot' && where.user_id !== 'u_mia') return []; - return [ - { user_id: where.user_id, permission_set: 'ops_tools', organization_id: 'org_a' }, - { user_id: where.user_id, permission_set: 'admin_full_access', organization_id: 'org_default' }, - ]; - } - return []; + const rows = rowsOf(object, opts); + return typeof opts?.limit === 'number' ? rows.slice(0, opts.limit) : rows; }, }, { permissions: [ diff --git a/packages/runtime/src/domains/automation-connector-connection-door.test.ts b/packages/runtime/src/domains/automation-connector-connection-door.test.ts index 61fdacbaedf..07c63067461 100644 --- a/packages/runtime/src/domains/automation-connector-connection-door.test.ts +++ b/packages/runtime/src/domains/automation-connector-connection-door.test.ts @@ -14,6 +14,8 @@ // (`connector-connection-door.test.ts`). import { describe, it, expect, vi } from 'vitest'; +// The stack loads the metadata service lazily; pay that load at collection, never in a clocked case. +import '@objectstack/metadata'; import { PLATFORM_CAPABILITIES } from '@objectstack/spec/security'; import { assembleExecutionContext } from '@objectstack/core'; diff --git a/scripts/engine-double-contract.pinned.json b/scripts/engine-double-contract.pinned.json index 25c8b2440aa..620b5a22981 100644 --- a/scripts/engine-double-contract.pinned.json +++ b/scripts/engine-double-contract.pinned.json @@ -5191,6 +5191,11 @@ "verb": "update", "pinned": 1 }, + { + "file": "packages/runtime/src/security/resolve-execution-context.agent-account.test.ts", + "verb": "findOne", + "pinned": 1 + }, { "file": "packages/runtime/src/security/resolve-execution-context.forward-credential.test.ts", "verb": "findOne", From a415adccafa6b221270dfee7ca73b75217c91710 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 08:38:00 +0000 Subject: [PATCH 7/9] test(runtime): the account connector-door pin reads onBehalfOf through an optional context Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- .../src/domains/automation-connector-connection-door.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/runtime/src/domains/automation-connector-connection-door.test.ts b/packages/runtime/src/domains/automation-connector-connection-door.test.ts index 07c63067461..15ff4b29dde 100644 --- a/packages/runtime/src/domains/automation-connector-connection-door.test.ts +++ b/packages/runtime/src/domains/automation-connector-connection-door.test.ts @@ -367,7 +367,7 @@ describe('ADR-0143 D5 — connector connection door: begin and revoke refuse a d it('an AI service account is refused on begin and on revoke by its own kind, not as an agent acting for a person', async () => { expect(ACCOUNT_KEY().executionContext).toMatchObject({ userId: 'u_agent', principalKind: 'agent', systemPermissions: [] }); - expect(ACCOUNT_KEY().executionContext.onBehalfOf).toBeUndefined(); + expect(ACCOUNT_KEY().executionContext?.onBehalfOf).toBeUndefined(); expect(connectorConnectionDelegatedCaller(ACCOUNT_KEY())).toBe('agent_account'); for (const verb of ['POST', 'DELETE'] as const) { const h = boot(); From e26e44a53b25d818ca39c25ed62c74cbfae30d9c Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 08:43:33 +0000 Subject: [PATCH 8/9] fix(core): an AI service account never carries an administrative permission set by name Standing is still read by name off an envelope's permissions in places: the approvals override arms, the admin_rescue administrators' slate and the access explainer's tenant-admin read. The agent ceiling clears a set's bits, not its name, so the resolver now withholds admin_full_access and every organization administrator set from an account's permissions, beside its system permissions. A person's grants are unchanged. Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- .../31739-ai-service-account-ceiling.md | 2 +- ...esolve-authz-context.agent-account.test.ts | 26 +- .../src/security/resolve-authz-context.ts | 14 +- ...t-not-an-administrator.integration.test.ts | 225 ++++++++++++++++++ ...ve-execution-context.agent-account.test.ts | 8 +- 5 files changed, 267 insertions(+), 8 deletions(-) create mode 100644 packages/plugins/plugin-approvals/src/agent-account-not-an-administrator.integration.test.ts diff --git a/.changeset/31739-ai-service-account-ceiling.md b/.changeset/31739-ai-service-account-ceiling.md index 2397a859b1c..8c4034f1a4a 100644 --- a/.changeset/31739-ai-service-account-ceiling.md +++ b/.changeset/31739-ai-service-account-ceiling.md @@ -27,7 +27,7 @@ Metadata-protocol: none An AI service account (a `sys_user` row whose `principal_kind` is `agent`) now acts as itself. Its API key, on REST, on `/mcp` and over stdio, admits a context whose `userId` is the account, with `principalKind: 'agent'` and no `onBehalfOf`. Its own grants are its whole authority: - It does not receive the `everyone` anchor's permission sets or the member baseline. Its floor is the restricted agent set, so a new account can do nothing until it is granted something. -- It carries no system permission and is never a platform or organization administrator, whatever it holds. +- It carries no system permission and is never a platform or organization administrator, whatever it holds: it never carries `admin_full_access` or an organization administrator set at all, so no reader that judges standing by a set's name (the approvals override and the `admin_rescue` slate among them) counts it. - Every agent principal's permission sets are read under the agent ceiling: no View All, no Modify All, no transfer, restore or purge, no system permission and no admin scope. A set edited after it was assigned still grants nothing above the ceiling. The permission sets an OAuth-connected assistant receives carry none of these bits, so it is unchanged. - Assigning an account a permission set, or a position whose sets, carry any of those bits is refused `400 VALIDATION_FAILED` (`invalid_value`), naming the set and what in it is above the ceiling. diff --git a/packages/core/src/security/resolve-authz-context.agent-account.test.ts b/packages/core/src/security/resolve-authz-context.agent-account.test.ts index f46a01924a2..41557b21165 100644 --- a/packages/core/src/security/resolve-authz-context.agent-account.test.ts +++ b/packages/core/src/security/resolve-authz-context.agent-account.test.ts @@ -14,6 +14,7 @@ import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ORGANIZATION_ADMIN_GRANTS } from '@objectstack/spec/identity'; import { resetPlatformAdminEmailMemo } from './platform-admin.js'; import { hasPlatformAdminStanding, isAgentAccountRow, resolveAuthzContext, resolveUserAuthzGrants } from './resolve-authz-context.js'; import { bindCatalogFromTables } from './__tests__/security-catalog.testkit.js'; @@ -84,8 +85,11 @@ describe('[ADR-0151 D3] resolveUserAuthzGrants — an AI service account', () => expect(grants.positions).not.toContain('everyone'); expect(grants.positions).not.toContain('platform_admin'); expect(grants.permissions).not.toContain('everyone_reader'); - // Its explicit grants stay named: they are clamped where they are evaluated. - expect(grants.permissions).toEqual(expect.arrayContaining(['ops_tools', 'admin_full_access'])); + // Its ordinary grants stay named (they are clamped where they are + // evaluated); an administrative set never does, since standing is also + // read by name. + expect(grants.permissions).toContain('ops_tools'); + expect(grants.permissions).not.toContain('admin_full_access'); expect(grants.systemPermissions).toEqual([]); expect(grants.posture).toBe('MEMBER'); }); @@ -107,12 +111,28 @@ describe('[ADR-0151 D3] resolveUserAuthzGrants — an AI service account', () => t.sys_permission_set.push({ id: 'ps_org_admin', name: 'organization_admin' }); const account = await resolveUserAuthzGrants(makeQl(t), 'u_bot', { tenantId: 'org_a', nowMs: NOW }); const person = await resolveUserAuthzGrants(makeQl(t), 'u_mia', { tenantId: 'org_a', nowMs: NOW }); - expect(account.permissions).toContain('organization_admin'); + expect(account.permissions).not.toContain('organization_admin'); + expect(person.permissions).toContain('organization_admin'); expect(account.posture).toBe('MEMBER'); expect(person.posture).not.toBe('MEMBER'); expect(person.posture).not.toBe('PLATFORM_ADMIN'); }); + it('never carries an administrative set by name, on any spelling of the organization-administrator rung, while a person keeps it', async () => { + for (const name of ORGANIZATION_ADMIN_GRANTS) { + const t = tables(); + t.sys_user_permission_set = [ + { user_id: 'u_bot', permission_set: name, organization_id: 'org_a' }, + { user_id: 'u_mia', permission_set: name, organization_id: 'org_a' }, + ]; + t.sys_permission_set.push({ id: `ps_${name}`, name }); + const account = await resolveUserAuthzGrants(makeQl(t), 'u_bot', { tenantId: 'org_a', nowMs: NOW }); + const person = await resolveUserAuthzGrants(makeQl(t), 'u_mia', { tenantId: 'org_a', nowMs: NOW }); + expect(account.permissions, name).not.toContain(name); + expect(person.permissions, name).toContain(name); + } + }); + it('a seeded caller cannot skip the kind: the row is read whatever is seeded', async () => { const grants = await resolveUserAuthzGrants(makeQl(), 'u_bot', { tenantId: 'org_a', nowMs: NOW, seedEmail: 'seeded@corp.example', seedPermissions: ['ai_seat'], diff --git a/packages/core/src/security/resolve-authz-context.ts b/packages/core/src/security/resolve-authz-context.ts index be030247d2c..72bf553cc1d 100644 --- a/packages/core/src/security/resolve-authz-context.ts +++ b/packages/core/src/security/resolve-authz-context.ts @@ -2350,8 +2350,18 @@ export async function resolveUserAuthzGrants( // [ADR-0151 D3] An AI service account carries no system permission, from // any set it holds: an action gated by one is closed to it until a decision // widens the agent ceiling. The sets themselves stay on `permissions` and are - // clamped where they are evaluated. - if (agentAccount) grants.systemPermissions = []; + // clamped where they are evaluated — except the administrative ones. Standing + // is still read by NAME in places (the approvals override arms and the + // `admin_rescue` slate, the access explainer's tenant-admin read), and the + // clamp clears bits, not names, so an account never carries + // `admin_full_access` or an organization-administrator set at all: an + // administrative grant is a person's to hold. + if (agentAccount) { + grants.systemPermissions = []; + grants.permissions = grants.permissions.filter( + (n) => n !== ADMIN_FULL_ACCESS && !ORGANIZATION_ADMIN_GRANTS.includes(n), + ); + } // 6c. Project the derived platform_admin built-in role (leads the list). if (hasPlatformAdminGrant && !grants.positions.includes(BUILTIN_IDENTITY_PLATFORM_ADMIN)) { diff --git a/packages/plugins/plugin-approvals/src/agent-account-not-an-administrator.integration.test.ts b/packages/plugins/plugin-approvals/src/agent-account-not-an-administrator.integration.test.ts new file mode 100644 index 00000000000..2745035ce51 --- /dev/null +++ b/packages/plugins/plugin-approvals/src/agent-account-not-an-administrator.integration.test.ts @@ -0,0 +1,225 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0151 D3] An AI service account is never an approvals administrator, + * whatever it holds. + * + * ## Why this file exists + * + * `ApprovalService.isOverrideActor` and the `admin_rescue` administrators' + * slate read standing partly by NAME off the envelope's `permissions` + * (`admin_full_access` for the platform arm, `ORGANIZATION_ADMIN_GRANTS` for + * the tenant arm and the slate). The agent ceiling clears bits on a set's + * body, not names, so the resolver withholds those names from an account's + * `permissions` instead (`resolveUserAuthzGrants`, core). An account can only + * hold such a grant row through a system or seed writer (a non-system write is + * refused at assignment), which is the row this file stores. + * + * ## What this pins + * + * Driven through the real `ApprovalService` on a real `ObjectQL` over + * `SqlDriver` (better-sqlite3, in-memory), with each actor's envelope built + * from the real `resolveUserAuthzGrants`: + * + * - an account holding `organization_admin` in the organization is not on the + * `admin_rescue` slate, while a person holding the same grant is; + * - an account holding `admin_full_access`, or `organization_admin`, cannot + * decide a staffed request it is not on — answered as for a missing id, the + * request left pending — while a person holding the same grant overrides it; + * - the premise: the account's envelope carries neither name, the person's + * carries it. + */ + +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { + bindSecurityCatalogReader, resolveUserAuthzGrants, type SecurityCatalogEntry, type SecurityCatalogReader, +} from '@objectstack/core'; +import type { ApprovalRequestRow } from '@objectstack/spec/contracts'; +import { ApprovalService, type ApprovalNodeAutoOutcome } from './approval-service.js'; +import { ApprovalsServicePlugin } from './approvals-plugin.js'; +import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js'; + +const SYSTEM = { isSystem: true, positions: [], permissions: [] } as any; +const ORG = 'org_a'; + +/** People and accounts. An account is a `sys_user` row of kind `agent`. */ +const USERS = [ + { id: 'u_sub', principal_kind: 'human' }, + { id: 'u_alice', principal_kind: 'human' }, + { id: 'u_owner', principal_kind: 'human' }, + { id: 'u_root', principal_kind: 'human' }, + { id: 'u_bot_org', principal_kind: 'agent' }, + { id: 'u_bot_root', principal_kind: 'agent' }, +].map((u) => ({ ...u, name: u.id, email: `${u.id}@example.com` })); + +/** + * `sys_user_permission_set`, written as the system: the account rows are the + * ones only a system or seed writer can store. + */ +const GRANTS: Array<[string, string, string | null]> = [ + ['u_owner', 'organization_admin', ORG], + ['u_bot_org', 'organization_admin', ORG], + ['u_root', 'admin_full_access', ORG], + ['u_bot_root', 'admin_full_access', ORG], +]; + +const text = (name: string) => ({ name, label: name, type: 'text' as const }); +const objectDef = (name: string, fields: string[]) => ({ + name, + label: name, + fields: Object.fromEntries([ + ['id', { ...text('id'), primaryKey: true }], + ...fields.map((f) => [f, text(f)]), + ]), +}); + +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; +} + +function opened(result: ApprovalRequestRow | ApprovalNodeAutoOutcome): ApprovalRequestRow { + if ('autoApproved' in result) throw new Error('expected an OPENED approval request, got an auto-approval outcome'); + return result; +} + +describe('[ADR-0151 D3] an AI service account is never an approvals administrator, whatever it holds', () => { + let engine: ObjectQL; + let svc: ApprovalService; + let now = Date.parse('2026-11-09T09:00:00.000Z'); + let seq = 0; + + /** The envelope a transport builds for `userId`, from the real resolver. */ + const actor = async (userId: string) => { + const grants = await resolveUserAuthzGrants(engine as any, userId, { tenantId: ORG }); + return { + userId, + tenantId: ORG, + positions: grants.positions, + permissions: grants.permissions, + systemPermissions: grants.systemPermissions, + ...(grants.posture ? { posture: grants.posture } : {}), + ...(grants.principalKind ? { principalKind: grants.principalKind } : {}), + } as any; + }; + + const open = async (approvers: any[]): Promise => { + const i = ++seq; + await engine.insert('crm_deal', { id: `D_${i}`, title: `d${i}` }, { context: SYSTEM } as any); + return opened(await svc.openNodeRequest({ + object: 'crm_deal', recordId: `D_${i}`, runId: `run_${i}`, nodeId: 'review', flowName: 'deal_review', + config: { approvers, behavior: 'first_response' } as any, + submitterId: 'u_sub', record: { id: `D_${i}`, title: `d${i}` }, organizationId: ORG, + } as any, { userId: 'u_sub', tenantId: ORG, positions: [], permissions: [] } as any)); + }; + + /** What a decision attempt DID: the throw's code, the request's status, and whether a decision was recorded. */ + const attemptDecide = async (userId: string, id: string) => { + let threw: string | null = null; + try { + await svc.decideNode(id, { decision: 'approve', actorId: userId } as any, await actor(userId)); + } catch (e) { + threw = String((e as any)?.message ?? e).split(':')[0]; + } + const [row]: any[] = await engine.find('sys_approval_request', { where: { id }, context: SYSTEM }); + const actions: any[] = await engine.find('sys_approval_action', { where: { request_id: id }, context: SYSTEM }); + const decision = actions.find((a) => a.actor_id === userId && a.action === 'approve'); + return { threw, status: row?.status, decided: Boolean(decision), viaOverride: Boolean(decision?.via_override) }; + }; + + beforeAll(async () => { + engine = new ObjectQL(); + engine.registerDriver(new SqlDriver({ + client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true, + }), true); + await engine.init(); + const defs = [ + objectDef('sys_user', ['name', 'email', 'principal_kind']), + 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']), + ...(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 u of USERS) await engine.insert('sys_user', u, { context: SYSTEM } as any); + for (const [i, u] of USERS.entries()) { + await engine.insert('sys_member', { id: `m_${i}`, user_id: u.id, organization_id: ORG, role: 'member' }, + { context: SYSTEM } as any); + } + for (const [i, [user_id, permission_set, organization_id]] of GRANTS.entries()) { + await engine.insert('sys_user_permission_set', { id: `ups_${i}`, user_id, permission_set, organization_id }, + { context: SYSTEM } as any); + } + svc = new ApprovalService({ + engine: engine as any, + clock: { now: () => new Date(now += 1000) }, + logger: { warn: () => {}, info: () => {}, error: () => {}, debug: () => {} } as any, + }); + }); + + afterAll(async () => { + try { await engine?.destroy(); } catch { /* noop */ } + }); + + it('the premise: an account\'s envelope carries no administrative set name, a person\'s carries it', async () => { + expect((await actor('u_bot_org')).permissions).not.toContain('organization_admin'); + expect((await actor('u_bot_root')).permissions).not.toContain('admin_full_access'); + expect((await actor('u_bot_root')).principalKind).toBe('agent'); + expect((await actor('u_owner')).permissions).toContain('organization_admin'); + expect((await actor('u_root')).permissions).toContain('admin_full_access'); + }); + + it('an account holding organization_admin is not on the admin_rescue slate; a person holding it is', async () => { + const row = await open([{ type: 'position', value: 'sales_manager' }]); + expect(row.status).toBe('pending'); + expect([...row.pending_approvers].sort()).toEqual(['u_owner']); + }); + + it.each(['u_bot_root', 'u_bot_org'])( + '%s cannot decide a staffed request it is not on: answered as for a missing id, left pending', + async (account) => { + const row = await open([{ type: 'user', value: 'u_alice' }]); + expect(await attemptDecide(account, row.id)).toEqual({ + threw: 'REQUEST_NOT_FOUND', status: 'pending', decided: false, viaOverride: false, + }); + }, + ); + + it.each(['u_root', 'u_owner'])( + 'CONTROL: %s, a person holding the same grant, overrides the same staffed request', + async (person) => { + const row = await open([{ type: 'user', value: 'u_alice' }]); + expect(await attemptDecide(person, row.id)).toEqual({ + threw: null, status: 'approved', decided: true, viaOverride: true, + }); + }, + ); +}); diff --git a/packages/runtime/src/security/resolve-execution-context.agent-account.test.ts b/packages/runtime/src/security/resolve-execution-context.agent-account.test.ts index 63894bcadc4..15ade7ac3e1 100644 --- a/packages/runtime/src/security/resolve-execution-context.agent-account.test.ts +++ b/packages/runtime/src/security/resolve-execution-context.agent-account.test.ts @@ -17,7 +17,8 @@ * `u_mia`, a plain member of org_alpha. It holds `crm_lead_reader` and * `crm_lead_super` in org_alpha, and — as no registration door would ever * write, but a store can hold — `admin_full_access` owned by the Default - * Organization: the row that anchors platform standing for a person. + * Organization: the row that anchors platform standing for a person. The + * account never carries that name, so it is never held. * - `crm_lead_super` breaches the agent ceiling: View All, Modify All, * transfer and the recycle bin on `crm_lead`, a system permission and an * admin scope. It is the set "assigned, then edited": the refusal at @@ -248,7 +249,10 @@ describe('[ADR-0151 D3] an AI service account\'s key admits the account itself', expect(lead?.[bit], bit).not.toBe(true); } const held = await r.sets(ctx); - expect(held.map((s) => s.name)).toEqual(expect.arrayContaining(['crm_lead_super', 'admin_full_access'])); + // The breaching set is held (and clamped); the administrative set the + // store also holds for it is never held at all: standing is read by name too. + expect(held.map((s) => s.name)).toContain('crm_lead_super'); + expect(held.map((s) => s.name)).not.toContain('admin_full_access'); for (const s of held) { expect(s.systemPermissions ?? [], s.name).toEqual([]); expect((s as any).adminScope, s.name).toBeUndefined(); From 1166ca5fe95d6a8d65901dc56e6b84bf3dc5777b Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 09:36:15 +0000 Subject: [PATCH 9/9] test(plugin-approvals): the account slate pin reads pending_approvers as optional Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- .../src/agent-account-not-an-administrator.integration.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/plugins/plugin-approvals/src/agent-account-not-an-administrator.integration.test.ts b/packages/plugins/plugin-approvals/src/agent-account-not-an-administrator.integration.test.ts index 2745035ce51..9cfaffed8f3 100644 --- a/packages/plugins/plugin-approvals/src/agent-account-not-an-administrator.integration.test.ts +++ b/packages/plugins/plugin-approvals/src/agent-account-not-an-administrator.integration.test.ts @@ -200,7 +200,7 @@ describe('[ADR-0151 D3] an AI service account is never an approvals administrato it('an account holding organization_admin is not on the admin_rescue slate; a person holding it is', async () => { const row = await open([{ type: 'position', value: 'sales_manager' }]); expect(row.status).toBe('pending'); - expect([...row.pending_approvers].sort()).toEqual(['u_owner']); + expect([...(row.pending_approvers ?? [])].sort()).toEqual(['u_owner']); }); it.each(['u_bot_root', 'u_bot_org'])(