From 9f7c8d1e56d1104f1d3fddaa1b32d27bb7fc8ed4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:32:13 +0000 Subject: [PATCH 1/6] feat(plugin-auth): register an AI service account and mint its keys; neither administrator count includes one Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- packages/core/src/security/api-key.ts | 86 ++++ packages/core/src/security/index.ts | 5 + .../plugins/plugin-auth/src/auth-plugin.ts | 83 ++++ .../last-admin-guard.agent-account.test.ts | 188 ++++++++ .../plugin-auth/src/last-admin-guard.ts | 19 + .../plugin-auth/src/service-account-doors.ts | 424 ++++++++++++++++++ .../src/upgrade-report-delivery.test.ts | 61 ++- .../src/upgrade-report-delivery.ts | 37 +- packages/runtime/src/domains/keys.ts | 63 +-- 9 files changed, 915 insertions(+), 51 deletions(-) create mode 100644 packages/plugins/plugin-auth/src/last-admin-guard.agent-account.test.ts create mode 100644 packages/plugins/plugin-auth/src/service-account-doors.ts diff --git a/packages/core/src/security/api-key.ts b/packages/core/src/security/api-key.ts index 5aaf0978a91..69776e63ad8 100644 --- a/packages/core/src/security/api-key.ts +++ b/packages/core/src/security/api-key.ts @@ -207,6 +207,92 @@ export function apiKeyLifecyclePolicySourceOf( return () => service.resolveApiKeyLifecyclePolicy!(); } +// ── [#23367, ADR-0151 D4] The life a key is signed with ────────────────────── +// +// The one rule every door that mints a key applies — `POST /keys` for the +// caller's own key, and the AI service account key door — so a person's key +// and an account's key are bound by the same default life and the same +// ceiling. Two steps, because the doors read the request before they read the +// policy (a body that does not parse is refused without asking the auth +// service, whose outage answers 503). + +/** + * [#23367] The clock skew the ceiling forgives. A client that computes "one + * year from now" on its own clock and sends it is asking for exactly the + * ceiling; a client clock a few seconds ahead of the server's must not turn + * that into a refusal. + */ +const API_KEY_EXPIRY_CEILING_SKEW_MS = 60_000; + +/** [#23367] The ceiling refusal's code (ADR-0112 ledger). */ +export const API_KEY_EXPIRY_TOO_LONG_CODE = 'API_KEY_EXPIRY_TOO_LONG'; + +/** A refused signing: always `400`, with the code and the located message. */ +export interface ApiKeyExpiryRefusal { + ok: false; + status: 400; + code: 'VALIDATION_ERROR' | typeof API_KEY_EXPIRY_TOO_LONG_CODE; + message: string; +} + +/** + * Step 1, the request: the `expires_at` a caller asked for, as epoch + * milliseconds, or `undefined` when it asked for none (absent or empty). A + * number below 1e12 is read as seconds, a larger one as milliseconds. A value + * that does not parse as a date, or is not in the future, is refused `400 + * VALIDATION_ERROR`. + */ +export function readRequestedApiKeyExpiry( + requested: unknown, + nowMs: number, +): { ok: true; requestedMs?: number } | ApiKeyExpiryRefusal { + if (requested == null || requested === '') return { ok: true }; + const ms = typeof requested === 'number' + ? (requested < 1e12 ? requested * 1000 : requested) + : Date.parse(String(requested)); + if (Number.isNaN(ms)) { + return { ok: false, status: 400, code: 'VALIDATION_ERROR', message: 'Invalid expires_at: must be a parseable date' }; + } + if (ms <= nowMs) { + return { ok: false, status: 400, code: 'VALIDATION_ERROR', message: 'Invalid expires_at: must be in the future' }; + } + return { ok: true, requestedMs: ms }; +} + +/** + * Step 2, the policy: the `expires_at` the key is signed with. No date asked + * for gets the policy's default life (never a permanent key), or no expiry + * when no policy is configured (a kernel with no `auth` service has no auth + * configuration). A date further away than the policy's ceiling is refused + * `400 API_KEY_EXPIRY_TOO_LONG`, naming the latest date that would be + * accepted; exactly the ceiling is accepted. + */ +export function signApiKeyExpiry( + policy: ApiKeyLifecyclePolicy | undefined, + requestedMs: number | undefined, + nowMs: number, +): { ok: true; expiresAt?: string } | ApiKeyExpiryRefusal { + if (requestedMs === undefined) { + return policy + ? { ok: true, expiresAt: new Date(nowMs + policy.defaultExpiryDays * DAY_MS).toISOString() } + : { ok: true }; + } + if (policy && requestedMs > nowMs + policy.maxExpiryDays * DAY_MS + API_KEY_EXPIRY_CEILING_SKEW_MS) { + const latest = new Date(nowMs + policy.maxExpiryDays * DAY_MS).toISOString(); + return { + ok: false, + status: 400, + code: API_KEY_EXPIRY_TOO_LONG_CODE, + message: + `expires_at ${new Date(requestedMs).toISOString()} is further away than this deployment allows: the ` + + `Authentication API key policy's Maximum key lifetime is ${policy.maxExpiryDays} days, so the ` + + `latest expiry a key signed now may have is ${latest}. Ask for that date or an earlier one, and ` + + 'rotate the key before it expires.', + }; + } + return { ok: true, expiresAt: new Date(requestedMs).toISOString() }; +} + /** * [#23367] The three lifecycle refusals, each declared as its wire pair — the * ADR-0112 code (registered under `@objectstack/core`) beside the status it diff --git a/packages/core/src/security/index.ts b/packages/core/src/security/index.ts index d91d120680d..c2a9194aeb5 100644 --- a/packages/core/src/security/index.ts +++ b/packages/core/src/security/index.ts @@ -165,6 +165,11 @@ export { API_KEY_REVOKED_CODE, API_KEY_LIFECYCLE_REFUSAL_STATUS, apiKeyLifecyclePolicySourceOf, + // [ADR-0151 D4] The one signing-expiry rule both mint doors apply. + readRequestedApiKeyExpiry, + signApiKeyExpiry, + API_KEY_EXPIRY_TOO_LONG_CODE, + type ApiKeyExpiryRefusal, ApiKeyLifecycleRefusalError, isApiKeyLifecycleRefusalError, type ApiKeyLifecyclePolicySource, diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 5ebd5d952ce..5febba3dddf 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -4104,6 +4104,89 @@ export class AuthPlugin implements Plugin { } }); + // ──────────────────────────────────────────────────────────────────── + // ADR-0151 D1/D4 — register an AI service account, and mint its keys. + // + // A person signed in, read from the better-auth session, so an API key + // never reaches these routes and an AI service account (which never holds + // a session) never calls them. Anonymous is 401, a held session is refused + // with its posture; who may act (an organization or platform + // administrator; for a key, also the account's owner) is the handler's + // to judge, against `sys_member` (service-account-doors.ts). Writes run + // as the system, attributed to the person. + const serviceAccountCaller = async ( + c: any, + ): Promise => { + const authApi = await this.authManager!.getApi(); + const session: SessionRead | null = await authApi.getSession(inProcessSessionReadInput(c.req.raw.headers)); + const user = session?.user; + if (!user?.id) { + return c.json({ success: false, error: { code: 'UNAUTHENTICATED', message: 'Sign in first' } }, 401); + } + const held = judgeHeldSession(user); + if (held) return c.json(held.body, held.status); + const activeOrganizationId = (session?.session as { activeOrganizationId?: unknown } | undefined)?.activeOrganizationId; + const impersonatedBy = session?.session?.impersonatedBy; + return { + id: user.id, + isPlatformAdmin: isPlatformAdminUser(user), + activeOrganizationId: typeof activeOrganizationId === 'string' && activeOrganizationId !== '' ? activeOrganizationId : null, + ...(typeof impersonatedBy === 'string' && impersonatedBy.trim() !== '' ? { impersonatedBy: impersonatedBy.trim() } : {}), + }; + }; + const serviceAccountDeps = (): import('./service-account-doors.js').ServiceAccountDoorDeps => ({ + getDataEngine: () => this.authManager!.getDataEngine() as any, + addMember: async ({ userId, organizationId }) => { + const authApi: any = await this.authManager!.getApi(); + await authApi.addMember({ body: { userId, role: 'member', organizationId } }); + }, + runAtomically: async (work: () => Promise): Promise => { + const engine = this.authManager!.getDataEngine() as + | { transaction?: (callback: (trxCtx: any, info: any) => Promise) => Promise } + | undefined; + if (typeof engine?.transaction !== 'function') return work(); + return engine.transaction(async () => work()); + }, + resolveApiKeyLifecyclePolicy: () => this.authManager!.resolveApiKeyLifecyclePolicy(), + }); + const serviceAccountRoute = ( + path: string, + run: ( + deps: import('./service-account-doors.js').ServiceAccountDoorDeps, + caller: import('./service-account-doors.js').ServiceAccountCaller, + request: Request, + ) => Promise, + ): void => { + rawApp.post(`${basePath}/service-account/${path}`, async (c: any) => { + try { + const caller = await serviceAccountCaller(c); + if (caller instanceof Response) return caller; + const { status, body } = await runAttributedToUser(caller, () => run(serviceAccountDeps(), caller, c.req.raw)); + return c.json(body, status as any); + } catch (error) { + // An unreadable membership or policy is an outage, never a caller + // without standing: answered 503 in the shared seam's words. + if (isAuthzStoreUnavailableError(error)) { + return c.json( + { success: false, error: { code: AUTHZ_STORE_UNAVAILABLE_CODE, message: AUTHZ_STORE_UNAVAILABLE_MESSAGE } }, + AUTHZ_STORE_UNAVAILABLE_STATUS, + ); + } + const err = error instanceof Error ? error : new Error(String(error)); + ctx.logger.error(`[AuthPlugin] service-account/${path} failed`, err); + return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: 'The request could not be completed.' } }, 500); + } + }); + }; + serviceAccountRoute('register', async (deps, caller, request) => { + const { runRegisterServiceAccount } = await import('./service-account-doors.js'); + return runRegisterServiceAccount(deps, caller, request); + }); + serviceAccountRoute('create-key', async (deps, caller, request) => { + const { runCreateServiceAccountKey } = await import('./service-account-doors.js'); + return runCreateServiceAccountKey(deps, caller, request); + }); + // ──────────────────────────────────────────────────────────────────── // [#30398] ADR-0069 D5 — admin: the caller's own address as the // `auth.allowed_ip_ranges` save check and the sign-in gate judge it, so diff --git a/packages/plugins/plugin-auth/src/last-admin-guard.agent-account.test.ts b/packages/plugins/plugin-auth/src/last-admin-guard.agent-account.test.ts new file mode 100644 index 00000000000..2e57296e942 --- /dev/null +++ b/packages/plugins/plugin-auth/src/last-admin-guard.agent-account.test.ts @@ -0,0 +1,188 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0151 D2/D3] An AI service account is never counted as an + * administrator by the break-glass guard, whatever its grade or its grants + * say. + * + * An account (a `sys_user` row of kind `agent`) holds no administrator + * standing — the resolver withholds every administrator set from it — and it + * can never sign in, so it is no escape hatch. A guard that counted it would + * wave through the write that ends the last person's standing. Only a system + * or seed writer can store an administrator grant on an account (a non-system + * write is refused at assignment), and an organization administrator can + * raise its membership grade; these rows are those writes. + * + * Same method as `last-admin-guard.default-organization.test.ts`: a REAL + * ObjectQL engine over better-sqlite3 `:memory:`, so the engine dispatches the + * hooks. Each pin sits beside a CONTROL where a person holds the same thing. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { ADMIN_FULL_ACCESS } from '@objectstack/spec/identity'; +import { resetPlatformAdminEmailMemo } from '@objectstack/core'; + +import { + registerLastAdminGuard, resolveAdminUserIds, type LastAdminGuardEngine, +} from './last-admin-guard.js'; +import { bindTestSecurityCatalog } from './__tests__/security-catalog.testkit.js'; + +const POSTURE_ENV = 'OS_TENANCY_POSTURE'; +const MULTI_ORG_ENV = 'OS_MULTI_ORG_ENABLED'; +const OWNER_ENV = 'OS_PLATFORM_OWNER_EMAIL'; +const SYSTEM = { context: { isSystem: true } } as const; + +const text = (name: string) => ({ name, type: 'text' as const }); +const OBJECTS = [ + { + name: 'sys_user', + label: 'User', + managedBy: 'better-auth', + fields: { + id: { ...text('id'), primaryKey: true }, + name: text('name'), + email: text('email'), + email_verified: { name: 'email_verified', type: 'boolean' as const }, + banned: { name: 'banned', type: 'boolean' as const, readonly: true }, + principal_kind: text('principal_kind'), + accountable_user_id: text('accountable_user_id'), + }, + }, + { + name: 'sys_member', + label: 'Member', + managedBy: 'better-auth', + fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') }, + }, + { + name: 'sys_organization', + label: 'Organization', + managedBy: 'better-auth', + fields: { id: { ...text('id'), primaryKey: true }, name: text('name'), slug: text('slug') }, + }, + { + name: 'sys_user_permission_set', + label: 'User Permission Set', + fields: { + id: { ...text('id'), primaryKey: true }, + user_id: text('user_id'), + permission_set: text('permission_set'), + organization_id: text('organization_id'), + valid_from: { name: 'valid_from', type: 'datetime' as const }, + valid_until: { name: 'valid_until', type: 'datetime' as const }, + }, + }, +]; + +let engines: ObjectQL[] = []; +const ambient: Record = {}; + +beforeEach(() => { + for (const name of [POSTURE_ENV, MULTI_ORG_ENV, OWNER_ENV]) { + ambient[name] = process.env[name]; + delete process.env[name]; + } + resetPlatformAdminEmailMemo(); +}); + +afterEach(async () => { + for (const [name, value] of Object.entries(ambient)) { + if (value === undefined) delete process.env[name]; + else process.env[name] = value; + } + resetPlatformAdminEmailMemo(); + const open = engines; + engines = []; + for (const e of open) { + try { await e.destroy(); } catch { /* noop */ } + } +}); + +/** + * A `single` environment whose one person administrator, `usr_admin`, holds + * the Default Organization's `admin_full_access` grant, beside an AI service + * account, `usr_bot`, that holds the same grant AND an owner membership of + * that organization. With `person`, a second person holds `as` too. + */ +async function environment(opts: { person?: 'grant' | 'owner' } = {}): Promise { + const engine = new ObjectQL(); + engines.push(engine); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + true, + ); + await engine.init(); + for (const o of OBJECTS) engine.registry.registerObject(o as never); + await engine.syncSchemas(); + bindTestSecurityCatalog(engine, { permissions: [{ name: ADMIN_FULL_ACCESS }] }); + registerLastAdminGuard(engine as unknown as LastAdminGuardEngine, { packageId: 'test.last-admin-guard.agent-account' }); + + await engine.insert('sys_organization', { id: 'org_default', name: 'Default Organization', slug: 'default' }, SYSTEM); + for (const id of ['usr_admin', 'usr_person']) { + await engine.insert('sys_user', { + id, name: id, email: `${id}@d.example`, email_verified: true, banned: false, principal_kind: 'human', + }, SYSTEM); + } + await engine.insert('sys_user', { + id: 'usr_bot', name: 'Bot', email: 'bot@placeholder.invalid', email_verified: false, banned: false, + principal_kind: 'agent', accountable_user_id: 'usr_admin', + }, SYSTEM); + + await engine.insert('sys_user_permission_set', { + id: 'ups_admin', user_id: 'usr_admin', permission_set: ADMIN_FULL_ACCESS, organization_id: 'org_default', + }, SYSTEM); + await engine.insert('sys_user_permission_set', { + id: 'ups_bot', user_id: 'usr_bot', permission_set: ADMIN_FULL_ACCESS, organization_id: 'org_default', + }, SYSTEM); + await engine.insert('sys_member', { id: 'm_bot', user_id: 'usr_bot', organization_id: 'org_default', role: 'owner' }, SYSTEM); + + if (opts.person === 'grant') { + await engine.insert('sys_user_permission_set', { + id: 'ups_person', user_id: 'usr_person', permission_set: ADMIN_FULL_ACCESS, organization_id: 'org_default', + }, SYSTEM); + } + if (opts.person === 'owner') { + await engine.insert('sys_member', { id: 'm_person', user_id: 'usr_person', organization_id: 'org_default', role: 'owner' }, SYSTEM); + } + return engine; +} + +const ban = (engine: ObjectQL, id: string) => engine.update('sys_user', { id, banned: true }, SYSTEM); +const refusal = { code: 'PERMISSION_DENIED', status: 403 }; + +describe('[ADR-0151 D2/D3] the break-glass guard never counts an AI service account as an administrator', () => { + it('the enumeration names the person and never the account, for either population', async () => { + const engine = await environment(); + const readable = engine as unknown as LastAdminGuardEngine; + expect([...(await resolveAdminUserIds(readable))]).toEqual(['usr_admin']); + expect([...(await resolveAdminUserIds(readable, { standing: 'platform-admins' }))]).toEqual(['usr_admin']); + }); + + it('banning the last person administrator is refused, although an account holds the same grant and an owner grade', async () => { + const engine = await environment(); + await expect(ban(engine, 'usr_admin')).rejects.toMatchObject(refusal); + }); + + it('revoking the last person administrator\'s grant is refused, although an account holds the same grant', async () => { + const engine = await environment(); + await expect(engine.delete('sys_user_permission_set', { where: { id: 'ups_admin' }, ...SYSTEM } as any)) + .rejects.toMatchObject(refusal); + }); + + it('CONTROL: a person holding the same grant is counted, so the ban is admitted', async () => { + const engine = await environment({ person: 'grant' }); + await expect(ban(engine, 'usr_admin')).resolves.toBeDefined(); + }); + + it('CONTROL: a person holding the same owner grade is counted, so the ban is admitted', async () => { + const engine = await environment({ person: 'owner' }); + await expect(ban(engine, 'usr_admin')).resolves.toBeDefined(); + }); + + it('CONTROL: banning the account itself is admitted, since it was never one of the administrators', async () => { + const engine = await environment(); + await expect(ban(engine, 'usr_bot')).resolves.toBeDefined(); + }); +}); diff --git a/packages/plugins/plugin-auth/src/last-admin-guard.ts b/packages/plugins/plugin-auth/src/last-admin-guard.ts index 5a85a85d10b..06a4b71d931 100644 --- a/packages/plugins/plugin-auth/src/last-admin-guard.ts +++ b/packages/plugins/plugin-auth/src/last-admin-guard.ts @@ -337,6 +337,7 @@ import { } from '@objectstack/core'; import { isOrgAdminGrade } from './invitation-role-cap.js'; +import { isAgentAccountRow } from './service-account-identity.js'; import { GRANT_SET_NAME_FIELD, grantSetNameOf } from './grant-set-name.js'; /** `sys_user_permission_set` has no `SystemObjectName` member; it is spelled once, here. */ @@ -1293,6 +1294,14 @@ function createStandingReader(engine: Pick, maxSca * `standing: 'platform-admins'` skips half 2 (organization owners and * admins), which is no platform-admin standing; the guard always reads all * three halves. + * + * [ADR-0151 D2/D3] An AI service account is never one of them, whatever + * its grade or its grants say: it holds no administrator standing (the + * resolver withholds every administrator set from it) and it can never + * sign in, so it is no escape hatch. The ids the three halves found are + * read once more, by id, and every account among them is dropped. The kind + * never changes (`service-account-identity.ts`), so no pending write can + * move a row onto or off it, and the stored rows are what is read. */ const resolveAdminUserIds = async ( op: StandingReadOp, @@ -1468,6 +1477,16 @@ function createStandingReader(engine: Pick, maxSca // The legacy service account is not loginable — it can never be the escape // hatch, so it must not be counted as one. ids.delete(SystemUserId.SYSTEM); + + // [ADR-0151 D2/D3] Nor is an AI service account (see above). Whole rows, + // by id: the kind is read off the row the way the resolver reads it. + if (ids.size > 0) { + const found = await scan(op, SystemObjectName.USER, { where: { id: { $in: [...ids] } } }); + for (const row of found) { + const uid = toId(row.id); + if (uid && isAgentAccountRow(row)) ids.delete(uid); + } + } return ids; }; diff --git a/packages/plugins/plugin-auth/src/service-account-doors.ts b/packages/plugins/plugin-auth/src/service-account-doors.ts new file mode 100644 index 00000000000..fd34acd3ba3 --- /dev/null +++ b/packages/plugins/plugin-auth/src/service-account-doors.ts @@ -0,0 +1,424 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0151 D1/D4] The doors that register an AI service account and mint + * its API keys. + * + * POST /api/v1/auth/service-account/register — register an account + * POST /api/v1/auth/service-account/create-key — mint a key for one + * + * An AI service account is a `sys_user` row of kind `agent`: a registered + * principal of its own, acting only through its own API keys, under the agent + * ceiling (`service-account-identity.ts` holds the row rules and the sign-in + * refusal; the resolver and the security plugin hold its authority). These + * two doors are how one comes to exist and how it gets a credential. Its + * lifecycle doors (suspend, resume, change owner, retire) are their own. + * + * ## Who may call them (the mount resolves the caller) + * + * A person signed in: both routes read the caller from the better-auth + * session, so an API key never reaches them, and an AI service account (which + * never holds a session) never calls them. A held session is refused with its + * posture before either handler runs. Then: + * + * - **Register**: an administrator of the caller's current organization + * (a membership whose grade is admin or owner, `isOrgAdminGrade`, inside + * its validity window), or a platform administrator. An ordinary member may + * not: an identity minted by any member would sit outside the + * organization's administration and outside any count. + * - **Create a key**: the account's accountable owner, an administrator of + * the account's organization, or a platform administrator. The account + * never mints its own (`POST /keys` stays self-only and session-only). + * + * ## What register writes, in one act + * + * The `sys_user` row — kind `agent`, the accountable owner, an undeliverable + * placeholder address (`placeholder-email.ts`, which every mail path refuses), + * `source: env_native` — and the account's one `sys_member` row, grade + * `member`, in the caller's current organization. One unit of work (the + * engine's `transaction()`), as `create-user` joins its organization: a + * membership the vendor refuses rolls the row back, so no account exists + * without its organization. The row is written through the data engine, not + * the vendor's `createUser`: the kind is not a better-auth field, and it must + * be on the insert that creates the row (D1, "born with its kind"). The + * engine's `sys_user` hooks therefore judge it — the row rules first (the + * owner exists and is a person), then every other hook, a licence plugin's + * included (D7). The membership goes through the vendor's server-only + * `addMember`, so its checks (the organization exists, the membership limit, + * its hooks) stay the vendor's. + * + * The owner defaults to the caller and must be a member of the organization + * today. The name is the only description an account carries. + * + * ## What create-key writes + * + * One `sys_api_key` row: `user_id` the account, `active_organization_id` the + * account's organization (never the caller's, never the body's), signed with + * the same lifecycle rule `POST /keys` applies (`signApiKeyExpiry`, core): the + * default life when no `expires_at` is asked for, the ceiling refusal past it. + * The raw secret is returned once, to the person who asked; only its hash is + * stored. An account with no membership (retired) gets no key. + * + * Every write is the system's, attributed to the person (the mount opens the + * attribution seam), so the CRUD audit records who registered and who minted. + * Refusals use the ADR-0112 envelope with codes already in the catalog. + */ + +import { + generateApiKey, + isGrantActive, + readRequestedApiKeyExpiry, + signApiKeyExpiry, + AuthzStoreUnavailableError, +} from '@objectstack/core'; +import type { ApiKeyLifecyclePolicy } from '@objectstack/spec/contracts'; +import { SystemObjectName } from '@objectstack/spec/system'; +import { validationFailureDetails } from '@objectstack/types'; +import type { EndpointResult } from './admin-user-endpoints.js'; +import { authSystemWriteContext } from './auth-actor-attribution.js'; +import { isOrgAdminGrade } from './invitation-role-cap.js'; +import { generatePlaceholderEmail } from './placeholder-email.js'; +import { readJsonRequestBody } from './request-json-body.js'; +import { AGENT_PRINCIPAL_KIND, isAgentAccountRow } from './service-account-identity.js'; + +const USER_OBJECT = SystemObjectName.USER; +const MEMBER_OBJECT = 'sys_member'; +const API_KEY_OBJECT = 'sys_api_key'; +const SYSTEM_CTX = { isSystem: true, positions: [], permissions: [] } as const; + +/** The longest name a `sys_user` row holds (`sys_user.name` `maxLength`). */ +const NAME_MAX_LENGTH = 255; + +/** The person calling, as the mount resolved them from their session. */ +export interface ServiceAccountCaller { + id: string; + /** The administrator at the keyboard of an impersonation session: attribution only. */ + impersonatedBy?: string; + /** Platform-administrator standing, as the session carries it (ADR-0068 D2). */ + isPlatformAdmin: boolean; + /** The session's current organization, or `null`. */ + activeOrganizationId: string | null; +} + +/** The engine surface these doors use. */ +export interface ServiceAccountDataEngine { + find(object: string, query?: unknown, options?: unknown): Promise; + insert(object: string, data: Record, options?: unknown): Promise; +} + +export interface ServiceAccountDoorDeps { + getDataEngine(): ServiceAccountDataEngine | undefined; + /** The vendor's server-only `addMember`, as a plain `member` of `organizationId`. */ + addMember(input: { userId: string; organizationId: string }): Promise; + /** Run `work` as one unit of work (the engine's `transaction()`). */ + runAtomically(work: () => Promise): Promise; + /** The API-key lifecycle policy (`AuthManager.resolveApiKeyLifecyclePolicy`); absent ⇒ none configured. */ + resolveApiKeyLifecyclePolicy?(): ApiKeyLifecyclePolicy | Promise; + now?(): number; +} + +const str = (v: unknown): string | undefined => (typeof v === 'string' && v.trim().length > 0 ? v.trim() : undefined); + +function fail(status: number, code: string, message: string): EndpointResult { + return { status, body: { success: false, error: { code, message } } }; +} + +async function parseJson( + request: Request, +): Promise<{ ok: true; body: Record } | { ok: false; message: string }> { + const reading = await readJsonRequestBody(request); + if (!reading.ok) return reading; + const parsed = reading.body; + return { ok: true, body: parsed && typeof parsed === 'object' ? (parsed as Record) : {} }; +} + +function rowsOf(found: unknown): Record[] { + const value = found && typeof found === 'object' && 'value' in (found as object) ? (found as { value: unknown }).value : found; + return Array.isArray(value) ? (value as Record[]) : []; +} + +/** + * A read these doors decide authority on. One that throws is an outage, never + * a caller without standing: `503`, through the shared outage error. + */ +async function readRows( + engine: ServiceAccountDataEngine, + object: string, + where: Record, + fields?: string[], +): Promise[]> { + try { + return rowsOf(await engine.find(object, { where, ...(fields ? { fields } : {}), context: SYSTEM_CTX })); + } catch (cause) { + throw new AuthzStoreUnavailableError(object, cause); + } +} + +/** The user's memberships that hold now, in `organizationId` or in every organization. */ +async function activeMemberships( + engine: ServiceAccountDataEngine, + userId: string, + nowMs: number, + organizationId?: string, +): Promise[]> { + const where: Record = { user_id: userId }; + if (organizationId) where.organization_id = organizationId; + // The whole row: its ADR-0091 validity window, where a deployment carries + // one, is read off it by `isGrantActive`. + const rows = await readRows(engine, MEMBER_OBJECT, where); + return rows.filter((m) => isGrantActive(m as never, nowMs)); +} + +/** Is `userId` an administrator of `organizationId` now (grade admin or owner)? */ +async function isOrganizationAdministrator( + engine: ServiceAccountDataEngine, + userId: string, + organizationId: string, + nowMs: number, +): Promise { + const rows = await activeMemberships(engine, userId, nowMs, organizationId); + return rows.some((m) => isOrgAdminGrade(m.role)); +} + +/** A refusal a write hook threw as `VALIDATION_FAILED`, passed through with its fields; else `undefined`. */ +function validationRefusal(error: unknown): EndpointResult | undefined { + const details = validationFailureDetails(error); + if (!details) return undefined; + return { + status: 400, + body: { + success: false, + error: { code: 'VALIDATION_FAILED', message: (error as Error).message, fields: details.fields }, + }, + }; +} + +/** The vendor's own verdict on the membership, forwarded with its status and code. */ +class MembershipRefused extends Error { + constructor(readonly result: EndpointResult) { + super(result.body.error?.message ?? 'membership refused'); + this.name = 'MembershipRefused'; + } +} + +function vendorRefusal(error: unknown): EndpointResult { + const e = error as { statusCode?: number; status?: number | string; body?: { code?: string; message?: string }; message?: string } | null; + const status = typeof e?.statusCode === 'number' ? e.statusCode : typeof e?.status === 'number' ? e.status : 500; + const code = e?.body?.code ?? 'INTERNAL_ERROR'; + const message = e?.body?.message ?? e?.message ?? 'organization/add-member failed'; + return fail( + status, + code, + `The AI service account could not be added to the organization, so it was not registered: ${message}`, + ); +} + +// ── POST /service-account/register ───────────────────────────────────────── + +export async function runRegisterServiceAccount( + deps: ServiceAccountDoorDeps, + caller: ServiceAccountCaller, + request: Request, +): Promise { + const read = await parseJson(request); + if (!read.ok) return fail(400, 'INVALID_REQUEST', read.message); + const body = read.body; + + const name = str(body.name); + if (!name) { + return { + status: 400, + body: { + success: false, + error: { + code: 'VALIDATION_FAILED', + message: 'Name the AI service account: what it is and what it is for.', + fields: [{ field: 'name', code: 'required', message: 'Name the AI service account: what it is and what it is for.' }], + }, + }, + }; + } + if (name.length > NAME_MAX_LENGTH) { + const message = `The AI service account's name is at most ${NAME_MAX_LENGTH} characters.`; + return { + status: 400, + body: { success: false, error: { code: 'VALIDATION_FAILED', message, fields: [{ field: 'name', code: 'max_length', message }] } }, + }; + } + + const organizationId = caller.activeOrganizationId; + if (!organizationId) { + return fail( + 400, + 'INVALID_REQUEST', + 'An AI service account is registered in your current organization, and you have none. Select an organization and try again.', + ); + } + + const engine = deps.getDataEngine(); + if (!engine) return fail(503, 'SERVICE_UNAVAILABLE', 'The data service is not available.'); + const nowMs = deps.now?.() ?? Date.now(); + + if (!caller.isPlatformAdmin && !(await isOrganizationAdministrator(engine, caller.id, organizationId, nowMs))) { + return fail( + 403, + 'PERMISSION_DENIED', + 'Only an administrator of this organization, or a platform administrator, can register an AI service account.', + ); + } + + // The accountable owner: a person who is a member of this organization + // today. The row rules (`service-account-identity.ts`) refuse an owner who + // does not exist or is not a person; membership is this door's to judge, + // because the act knows the organization and the row does not. + const ownerId = str(body.ownerId) ?? str(body.owner_id) ?? caller.id; + if ((await activeMemberships(engine, ownerId, nowMs, organizationId)).length === 0) { + const message = ownerId === caller.id + ? 'You are not a member of this organization, so you cannot be the AI service account\'s accountable owner. ' + + 'Name a person who is (ownerId).' + : `The accountable owner '${ownerId}' is not a member of this organization. Name a person who is.`; + return { + status: 400, + body: { success: false, error: { code: 'VALIDATION_FAILED', message, fields: [{ field: 'ownerId', code: 'invalid_value', message }] } }, + }; + } + + let userId: string; + try { + userId = await deps.runAtomically(async () => { + const inserted = await engine.insert( + USER_OBJECT, + { + name, + email: generatePlaceholderEmail(), + email_verified: false, + principal_kind: AGENT_PRINCIPAL_KIND, + accountable_user_id: ownerId, + source: 'env_native', + }, + { context: await authSystemWriteContext() }, + ); + const id = str((Array.isArray(inserted) ? inserted[0] : inserted as Record | undefined)?.id); + if (!id) throw new Error('the user row was written without an id'); + try { + await deps.addMember({ userId: id, organizationId }); + } catch (error) { + throw new MembershipRefused(vendorRefusal(error)); + } + return id; + }); + } catch (error) { + if (error instanceof MembershipRefused) return error.result; + const refused = validationRefusal(error); + if (refused) return refused; + throw error; + } + + return { + status: 201, + body: { + success: true, + data: { userId, name, principalKind: AGENT_PRINCIPAL_KIND, organizationId, ownerId }, + }, + }; +} + +// ── POST /service-account/create-key ─────────────────────────────────────── + +export async function runCreateServiceAccountKey( + deps: ServiceAccountDoorDeps, + caller: ServiceAccountCaller, + request: Request, +): Promise { + const read = await parseJson(request); + if (!read.ok) return fail(400, 'INVALID_REQUEST', read.message); + const body = read.body; + + const accountId = str(body.userId) ?? str(body.user_id); + if (!accountId) return fail(400, 'INVALID_REQUEST', 'userId is required: the AI service account the key is for.'); + const keyName = str(body.name) ?? 'API Key'; + const nowMs = deps.now?.() ?? Date.now(); + const requested = readRequestedApiKeyExpiry(body.expires_at, nowMs); + if (!requested.ok) return fail(requested.status, requested.code, requested.message); + + const engine = deps.getDataEngine(); + if (!engine) return fail(503, 'SERVICE_UNAVAILABLE', 'The data service is not available.'); + + // The account. A person's id is answered as an unknown one: this door + // mints only an account's key, and a person's key stays that person's own + // to mint (D4). + const [account] = await readRows(engine, USER_OBJECT, { id: accountId }, ['id', 'principal_kind', 'accountable_user_id']); + if (!account || !isAgentAccountRow(account)) { + return fail(404, 'RESOURCE_NOT_FOUND', `No AI service account '${accountId}' exists.`); + } + + // Its organization: its one membership that holds now. None means it was + // retired, and a retired account gets no key. + const [membership] = await activeMemberships(engine, accountId, nowMs); + const organizationId = str(membership?.organization_id); + if (!organizationId) { + return fail( + 409, + 'RESOURCE_CONFLICT', + `The AI service account '${accountId}' belongs to no organization, so no key can be created for it.`, + ); + } + + const isOwner = str(account.accountable_user_id) === caller.id + && (await activeMemberships(engine, caller.id, nowMs, organizationId)).length > 0; + if (!caller.isPlatformAdmin && !isOwner && !(await isOrganizationAdministrator(engine, caller.id, organizationId, nowMs))) { + return fail( + 403, + 'PERMISSION_DENIED', + 'Only the AI service account\'s accountable owner, an administrator of its organization, or a platform ' + + 'administrator can create a key for it.', + ); + } + + let policy: ApiKeyLifecyclePolicy | undefined; + try { + policy = deps.resolveApiKeyLifecyclePolicy ? await deps.resolveApiKeyLifecyclePolicy() : undefined; + } catch (cause) { + throw new AuthzStoreUnavailableError('api_key_policy', cause); + } + const signed = signApiKeyExpiry(policy, requested.requestedMs, nowMs); + if (!signed.ok) return fail(signed.status, signed.code, signed.message); + + // Generated after every check, so a refused request never mints. + const generated = generateApiKey(); + const row: Record = { + name: keyName, + key: generated.hash, + prefix: generated.prefix, + user_id: accountId, + revoked: false, + active_organization_id: organizationId, + }; + if (signed.expiresAt) row.expires_at = signed.expiresAt; + + let inserted: unknown; + try { + inserted = await engine.insert(API_KEY_OBJECT, row, { context: await authSystemWriteContext() }); + } catch { + // Never surface the underlying error: it could echo the row, hash included. + return fail(500, 'INTERNAL_ERROR', 'The API key could not be created.'); + } + const id = str((Array.isArray(inserted) ? inserted[0] : inserted as Record | undefined)?.id); + + // The raw key, once. Never logged. + return { + status: 201, + body: { + success: true, + data: { + id, + name: keyName, + prefix: generated.prefix, + key: generated.raw, + user_id: accountId, + active_organization_id: organizationId, + ...(signed.expiresAt ? { expires_at: signed.expiresAt } : {}), + }, + }, + }; +} diff --git a/packages/plugins/plugin-security/src/upgrade-report-delivery.test.ts b/packages/plugins/plugin-security/src/upgrade-report-delivery.test.ts index d32b1454b28..8563f4b738a 100644 --- a/packages/plugins/plugin-security/src/upgrade-report-delivery.test.ts +++ b/packages/plugins/plugin-security/src/upgrade-report-delivery.test.ts @@ -36,9 +36,17 @@ type Row = Record; const OBJECTS = ['sys_organization', 'sys_member', 'sys_user', 'sys_user_permission_set']; -/** Scalar equality only: a combinator or an operator object is refused, never answered silently wrong. */ +/** + * Scalar equality, and `{ $in: [...] }` on a field (the by-id read that drops + * AI service accounts, ADR-0151 D3). Any other combinator or operator object + * is refused, never answered silently wrong. + */ function matches(row: Row, where: Row): boolean { return Object.entries(where).every(([k, v]) => { + if (!k.startsWith('$') && v !== null && typeof v === 'object' && !Array.isArray(v) + && Object.keys(v).length === 1 && Array.isArray((v as { $in?: unknown }).$in)) { + return ((v as { $in: unknown[] }).$in).includes(row[k]); + } if (k.startsWith('$') || (v !== null && typeof v === 'object')) throw new Error(`fake engine: unsupported where '${k}'`); return row[k] === v; }); @@ -278,3 +286,54 @@ describe('single never reads the setting', () => { } }); }); + +/** + * [ADR-0151 D3] An AI service account (a `sys_user` row of kind `agent`) is + * never a recipient, and never counted as an administrator of the owner + * organization, whatever its grade or grants say. A system or seed writer is + * the only one that can store such a grant on an account; these rows are + * that write. Each pin sits beside a person holding the same thing. + */ +describe('an AI service account is never a recipient and never an administrator here', () => { + const withAccounts = (t: Record) => { + t.sys_user.push( + { id: 'usr_bot', email: 'bot@placeholder.invalid', principal_kind: 'agent', accountable_user_id: 'usr_operator' }, + { id: 'usr_person', email: 'person@vendor.example', principal_kind: 'human' }, + ); + }; + + it('single: an account holding the Default Organization\'s admin_full_access is not told; a person holding it is', async () => { + const r = await deliver(deployment((t) => { + withAccounts(t); + t.sys_user_permission_set.push( + { id: 'g4', user_id: 'usr_bot', permission_set: 'admin_full_access', organization_id: DEFAULT_ORG }, + { id: 'g5', user_id: 'usr_person', permission_set: 'admin_full_access', organization_id: DEFAULT_ORG }, + ); + }), { walled: false }); + expect(r.emit!.mock.calls[0][0].audience).toEqual([OPERATOR, 'usr_default_admin', 'usr_person']); + expect(r.delivery.recipients).not.toContain('usr_bot'); + }); + + it('walled: an account administering the owner organization by grade or by grant is not flagged; a person is', async () => { + const r = await deliver(deployment((t) => { + withAccounts(t); + t.sys_member.push( + { id: 'm5', organization_id: OWNER_ORG, user_id: 'usr_bot', role: 'admin' }, + { id: 'm6', organization_id: OWNER_ORG, user_id: 'usr_person', role: 'admin' }, + ); + t.sys_user_permission_set.push( + { id: 'g6', user_id: 'usr_bot', permission_set: 'organization_admin', organization_id: OWNER_ORG }, + ); + }), { ownerOrganization: OWNER_ORG }); + const warn = r.warns.find((w) => w.m.includes('are not configured operators')); + expect(warn?.meta).toEqual({ organizationId: OWNER_ORG, administrators: ['usr_person'] }); + }); + + it('walled: an organization whose only extra administrator is an account raises no warning', async () => { + const r = await deliver(deployment((t) => { + withAccounts(t); + t.sys_member.push({ id: 'm5', organization_id: OWNER_ORG, user_id: 'usr_bot', role: 'owner' }); + }), { ownerOrganization: OWNER_ORG }); + expect(r.warns).toEqual([]); + }); +}); diff --git a/packages/plugins/plugin-security/src/upgrade-report-delivery.ts b/packages/plugins/plugin-security/src/upgrade-report-delivery.ts index a6c807122c3..2723196c523 100644 --- a/packages/plugins/plugin-security/src/upgrade-report-delivery.ts +++ b/packages/plugins/plugin-security/src/upgrade-report-delivery.ts @@ -45,6 +45,15 @@ * the same two that answer the membership check. A set authored to read * `sys_notification` some other way is not read. * + * ## An AI service account is never an administrator here + * + * [ADR-0151 D3] An AI service account (a `sys_user` row of kind `agent`) + * holds no administrator standing whatever its grade or grants say, and it + * has no inbox a person reads. So it is never a recipient under `single`, and + * never counted as an administrator of the owner organization under a wall: + * the people found are read once more, by id, and every account among them is + * dropped. A composition with no `sys_user` drops nobody. + * * ## Never throws * * A read or a delivery that did not happen is said in the log with its cause. @@ -52,6 +61,7 @@ */ import { + isAgentAccountRow, readDefaultOrganizationId, resolvePlatformAdminEmails, type PlatformAdminEmailConfig, @@ -65,6 +75,7 @@ import { resolvePlatformAdminStanding } from './platform-admin-service.js'; const ORGANIZATION_OBJECT = 'sys_organization'; const MEMBER_OBJECT = 'sys_member'; +const USER_OBJECT = 'sys_user'; const SYSTEM_CTX = { isSystem: true } as const; /** The grants that make their holder an administrator of the organization they are scoped to. */ @@ -154,6 +165,21 @@ function rowsOf(value: unknown): Record[] { return Array.isArray(value) ? value.filter((r): r is Record => !!r && typeof r === 'object') : []; } +/** + * [ADR-0151 D3] `ids` without the AI service accounts among them, read by id + * as the system. A read that throws propagates, as every read here does. + */ +async function withoutAgentAccounts(engine: UpgradeReportEngine, ids: readonly string[]): Promise { + if (ids.length === 0 || !engine.getObject(USER_OBJECT)) return [...ids]; + const rows = rowsOf(await engine.find(USER_OBJECT, { + where: { id: { $in: [...ids] } }, + limit: ids.length, + context: SYSTEM_CTX, + })); + const accounts = new Set(rows.filter(isAgentAccountRow).map((row) => idOf(row.id))); + return ids.filter((id) => !accounts.has(id)); +} + function logError(logger: UpgradeReportLogger | undefined, message: string, meta: Record): void { if (logger?.error) logger.error(message, undefined, meta); else logger?.warn(message, meta); @@ -162,7 +188,8 @@ function logError(logger: UpgradeReportLogger | undefined, message: string, meta /** * The people who can act on a deployment-level finding under `single`: any * configured platform operator and every holder of the Default Organization's - * `admin_full_access` grant. A read that throws propagates. + * `admin_full_access` grant who is a person (an AI service account never is + * a recipient, ADR-0151 D3). A read that throws propagates. */ export async function resolveUpgradeReportAudience(engine: UpgradeReportEngine): Promise { const recipients = [...resolvePlatformAdminEmails().emails]; @@ -174,10 +201,12 @@ export async function resolveUpgradeReportAudience(engine: UpgradeReportEngine): limit: 10000, context: SYSTEM_CTX, }); + const granted: string[] = []; for (const row of rowsOf(grants)) { const userId = idOf(row.user_id); - if (userId !== undefined && !recipients.includes(userId)) recipients.push(userId); + if (userId !== undefined && !recipients.includes(userId) && !granted.includes(userId)) granted.push(userId); } + recipients.push(...(await withoutAgentAccounts(engine, granted))); return { recipients, organizationId }; } @@ -269,7 +298,9 @@ export async function auditOwnerOrganization( const set = g[GRANT_SET_NAME_FIELD]; if (userId !== undefined && typeof set === 'string' && ADMINISTRATOR_SETS.has(set)) administrators.add(userId); } - const nonOperatorAdministrators = [...administrators].filter((id) => !operatorIds.has(id)).sort(); + const nonOperatorAdministrators = (await withoutAgentAccounts(engine, [...administrators])) + .filter((id) => !operatorIds.has(id)) + .sort(); return { unreachedOperators, nonOperatorAdministrators }; } diff --git a/packages/runtime/src/domains/keys.ts b/packages/runtime/src/domains/keys.ts index b9b1fd321ef..916cdd61d1e 100644 --- a/packages/runtime/src/domains/keys.ts +++ b/packages/runtime/src/domains/keys.ts @@ -50,7 +50,7 @@ import { isGrantActive, effectiveTenancyPosture, AuthzStoreUnavailableError, shouldDenyAnonymous, ANONYMOUS_DENY_STATUS, ANONYMOUS_DENY_CODE, ANONYMOUS_DENY_MESSAGE, - apiKeyLifecyclePolicySourceOf, + apiKeyLifecyclePolicySourceOf, readRequestedApiKeyExpiry, signApiKeyExpiry, } from '@objectstack/core'; import type { ApiKeyLifecyclePolicy } from '@objectstack/spec/contracts'; import { postureEnforcesWall } from '@objectstack/spec/security'; @@ -61,19 +61,6 @@ import type { HttpProtocolContext, HttpDispatcherResult } from '../http-dispatch import type { DomainHandlerDeps, DomainRoute } from '../domain-handler-registry.js'; import { readDispatchedBody } from '../deferred-request-body.js'; -const DAY_MS = 86_400_000; - -/** - * [#23367] The clock skew the ceiling forgives. A client that computes "one - * year from now" on its own clock and sends it is asking for exactly the - * ceiling; a client clock a few seconds ahead of the server's must not turn - * that into a refusal. - */ -const EXPIRY_CEILING_SKEW_MS = 60_000; - -/** [#23367] The ceiling refusal, as its wire pair (ADR-0112 ledger, `@objectstack/runtime`). */ -const API_KEY_EXPIRY_TOO_LONG = { code: 'API_KEY_EXPIRY_TOO_LONG', status: 400 } as const; - /** * The one method this domain serves, on every path it claims (the handler * never reads the path): the `Allow` value of its 405. @@ -180,19 +167,13 @@ export async function handleKeysRequest( const rawName = typeof body?.name === 'string' ? body.name.trim() : ''; const name = rawName || 'API Key'; - let requestedMs: number | undefined; - if (body?.expires_at != null && body.expires_at !== '') { - const ms = typeof body.expires_at === 'number' - ? (body.expires_at < 1e12 ? body.expires_at * 1000 : body.expires_at) - : Date.parse(String(body.expires_at)); - if (Number.isNaN(ms)) { - return { handled: true, response: deps.error('Invalid expires_at: must be a parseable date', 400) }; - } - if (ms <= Date.now()) { - return { handled: true, response: deps.error('Invalid expires_at: must be in the future', 400) }; - } - requestedMs = ms; + // [#23367, ADR-0151 D4] The one signing-expiry rule (core), shared with + // the AI service account key door: step 1, the date asked for. + const requested = readRequestedApiKeyExpiry(body?.expires_at, Date.now()); + if (!requested.ok) { + return { handled: true, response: deps.error(requested.message, requested.status) }; } + const requestedMs = requested.requestedMs; const ql = (await deps.getObjectQL(context, context.environmentId)) ?? (await deps.resolveService(context, 'objectql', context.environmentId)); @@ -267,28 +248,16 @@ export async function handleKeysRequest( throw new AuthzStoreUnavailableError('api_key_policy', err); } - const nowMs = Date.now(); - let expiresAt: string | undefined; - if (requestedMs !== undefined) { - if (policy && requestedMs > nowMs + policy.maxExpiryDays * DAY_MS + EXPIRY_CEILING_SKEW_MS) { - const latest = new Date(nowMs + policy.maxExpiryDays * DAY_MS).toISOString(); - return { - handled: true, - response: deps.error( - `expires_at ${new Date(requestedMs).toISOString()} is further away than this deployment allows: the ` - + `Authentication API key policy's Maximum key lifetime is ${policy.maxExpiryDays} days, so the ` - + `latest expiry a key signed now may have is ${latest}. Ask for that date or an earlier one, and ` - + 'rotate the key before it expires.', - API_KEY_EXPIRY_TOO_LONG.status, - { code: API_KEY_EXPIRY_TOO_LONG.code }, - ), - }; - } - expiresAt = new Date(requestedMs).toISOString(); - } else if (policy) { - // No expiry asked for: the policy's default life, never a permanent key. - expiresAt = new Date(nowMs + policy.defaultExpiryDays * DAY_MS).toISOString(); + // Step 2, the policy: the default life when no date was asked for (never a + // permanent key), the ceiling refusal when the date is too far away. + const signed = signApiKeyExpiry(policy, requestedMs, Date.now()); + if (!signed.ok) { + return { + handled: true, + response: deps.error(signed.message, signed.status, { code: signed.code }), + }; } + const expiresAt = signed.expiresAt; if (walled && !activeOrganizationId) { // Refuse rather than mint. Under a walled posture an org-less key From dd1669fe57f0db822651de8686dd16df83d7b7bf Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:39:53 +0000 Subject: [PATCH 2/6] feat(platform-objects): sys_user actions to register an AI service account and create its API key Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- .../apps/translations/ar.objects.generated.ts | 37 +++++++ .../apps/translations/de.objects.generated.ts | 37 +++++++ .../de.source-hashes.generated.ts | 1 + .../apps/translations/en.objects.generated.ts | 37 +++++++ .../translations/es-ES.objects.generated.ts | 37 +++++++ .../apps/translations/fr.objects.generated.ts | 37 +++++++ .../translations/ja-JP.objects.generated.ts | 37 +++++++ .../apps/translations/ko.objects.generated.ts | 37 +++++++ .../translations/pt-BR.objects.generated.ts | 37 +++++++ .../apps/translations/ru.objects.generated.ts | 37 +++++++ .../translations/zh-CN.objects.generated.ts | 37 +++++++ .../translations/zh-Hant.objects.generated.ts | 37 +++++++ .../src/identity/sys-user.object.ts | 99 ++++++++++++++++++- 13 files changed, 506 insertions(+), 1 deletion(-) diff --git a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts index 28443b7d0b5..7b9c5814e7c 100644 --- a/packages/platform-objects/src/apps/translations/ar.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ar.objects.generated.ts @@ -267,6 +267,43 @@ export const arObjects: NonNullable = { } } }, + register_service_account: { + label: "تسجيل حساب خدمة للذكاء الاصطناعي", + description: "سجّل حساب خدمة للذكاء الاصطناعي في هذه المؤسسة: هوية خاصة بوكيل يعمل دون شخص، ولا يتصرف إلا عبر مفاتيح API المنشأة له. لا يمكنه فعل أي شيء حتى تُمنح له مجموعات أذونات، ولا يملك أبدًا صلاحية المسؤول.", + successMessage: "تم تسجيل حساب خدمة الذكاء الاصطناعي", + params: { + name: { + label: "الاسم", + helpText: "ما هو هذا الوكيل والغرض منه. بهذا الاسم يُعرف الحساب في قائمة المستخدمين وفي سجل التدقيق." + }, + ownerId: { + label: "المسؤول عن الحساب", + helpText: "الشخص المسؤول عن هذا الحساب، وهو عضو في هذه المؤسسة. اتركه فارغًا لتكون أنت المسؤول." + } + } + }, + create_service_account_key: { + label: "إنشاء مفتاح API", + description: "أنشئ مفتاح API لحساب خدمة الذكاء الاصطناعي هذا. يعمل المفتاح بصفة الحساب، وبصلاحيات الحساب نفسه، في مؤسسة الحساب.", + params: { + name: { + label: "اسم المفتاح" + }, + expires_at: { + label: "تاريخ الانتهاء", + helpText: "اتركه فارغًا لاستخدام مدة الصلاحية الافتراضية المضبوطة في الإعداد ← المصادقة ← مفاتيح API (مدة صلاحية المفتاح الافتراضية، 90 يومًا ما لم تُغيَّر). يُرفض أي تاريخ يتجاوز الحد الأقصى لمدة صلاحية المفتاح هناك." + } + }, + resultDialog: { + title: "تم إنشاء مفتاح API", + description: "انسخ المفتاح الآن — فهو يُعرض مرة واحدة فقط ولا يمكن استرداده. إذا تسرّب، فأبطله وأنشئ مفتاحًا جديدًا.", + acknowledge: "لقد حفظت المفتاح", + fields: { + key: "مفتاح API", + expires_at: "تاريخ الانتهاء" + } + } + }, update_my_profile: { label: "تحديث الملف الشخصي", successMessage: "تم تحديث الملف الشخصي" diff --git a/packages/platform-objects/src/apps/translations/de.objects.generated.ts b/packages/platform-objects/src/apps/translations/de.objects.generated.ts index d5ca7e6740e..33dc8bc0075 100644 --- a/packages/platform-objects/src/apps/translations/de.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.objects.generated.ts @@ -267,6 +267,43 @@ export const deObjects: NonNullable = { } } }, + register_service_account: { + label: "KI-Dienstkonto registrieren", + description: "Registrieren Sie ein KI-Dienstkonto in dieser Organisation: eine eigene Identität für einen Agenten, der ohne Person läuft und nur über die für ihn angelegten API-Schlüssel handelt. Es kann nichts tun, bis ihm Berechtigungssätze erteilt werden, und es hat nie Administratorzugriff.", + successMessage: "KI-Dienstkonto registriert", + params: { + name: { + label: "Name", + helpText: "Was der Agent ist und wofür er dient. Unter diesem Namen erscheint das Konto in der Benutzerliste und im Prüfprotokoll." + }, + ownerId: { + label: "Verantwortliche Person", + helpText: "Die für dieses Konto verantwortliche Person, ein Mitglied dieser Organisation. Leer lassen, um selbst verantwortlich zu sein." + } + } + }, + create_service_account_key: { + label: "API-Schlüssel anlegen", + description: "Legen Sie einen API-Schlüssel für dieses KI-Dienstkonto an. Der Schlüssel handelt als das Konto, mit dessen eigenen Berechtigungen, in der Organisation des Kontos.", + params: { + name: { + label: "Schlüsselname" + }, + expires_at: { + label: "Läuft ab am", + helpText: "Leer lassen für die Standardlaufzeit unter „Setup → Authentifizierung → API-Schlüssel“ (Standardlaufzeit für Schlüssel, 90 Tage, sofern nicht geändert). Ein Datum nach der dort festgelegten maximalen Schlüssellaufzeit wird abgelehnt." + } + }, + resultDialog: { + title: "API-Schlüssel angelegt", + description: "Kopieren Sie den Schlüssel jetzt – er wird nur einmal angezeigt und kann nicht wiederhergestellt werden. Falls er bekannt wird, widerrufen Sie ihn und legen einen neuen an.", + acknowledge: "Ich habe den Schlüssel gespeichert", + fields: { + key: "API-Schlüssel", + expires_at: "Läuft ab am" + } + } + }, update_my_profile: { label: "Profil aktualisieren", successMessage: "Profil aktualisiert" diff --git a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts index a1f7477d194..847da72da13 100644 --- a/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts +++ b/packages/platform-objects/src/apps/translations/de.source-hashes.generated.ts @@ -176,6 +176,7 @@ export const deGeneratedSourceHashes: Readonly> = { "objects.sys_team.label": "42b87165ac826b2b", "objects.sys_team.pluralLabel": "3fe8519872f65108", "objects.sys_team_member.fields.team_id.label": "42b87165ac826b2b", + "objects.sys_user._actions.register_service_account.params.name.label": "5274417ff1ccaf01", "objects.sys_user.fields.name.label": "5274417ff1ccaf01", "objects.sys_user.fields.principal_kind.options.human": "ed18d3469e10aef2", }; diff --git a/packages/platform-objects/src/apps/translations/en.objects.generated.ts b/packages/platform-objects/src/apps/translations/en.objects.generated.ts index 0dedfe13678..508caebc9d6 100644 --- a/packages/platform-objects/src/apps/translations/en.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/en.objects.generated.ts @@ -267,6 +267,43 @@ export const enObjects: NonNullable = { } } }, + register_service_account: { + label: "Register AI Service Account", + description: "Register an AI service account in this organization: an identity of its own for an agent that runs without a person, acting only through API keys created for it. It can do nothing until it is granted permission sets, and it never holds administrator access.", + successMessage: "AI service account registered", + params: { + name: { + label: "Name", + helpText: "What the agent is and what it is for. This name is how the account is recognised in the user list and the audit trail." + }, + ownerId: { + label: "Accountable Owner", + helpText: "The person accountable for this account, a member of this organization. Leave empty to be the owner yourself." + } + } + }, + create_service_account_key: { + label: "Create API Key", + description: "Create an API key for this AI service account. The key acts as the account, with the account's own grants, in the account's organization.", + params: { + name: { + label: "Key Name" + }, + expires_at: { + label: "Expires At", + helpText: "Leave empty for the default lifetime set under Setup → Authentication → API keys (Default key lifetime, 90 days unless changed). A date later than the Maximum key lifetime there is refused." + } + }, + resultDialog: { + title: "API key created", + description: "Copy the key now — it is shown only once and cannot be recovered. If it leaks, revoke it and create a new one.", + acknowledge: "I have saved the key", + fields: { + key: "API Key", + expires_at: "Expires At" + } + } + }, update_my_profile: { label: "Update Profile", successMessage: "Profile updated" diff --git a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts index dfa7a465be3..f743a212255 100644 --- a/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/es-ES.objects.generated.ts @@ -267,6 +267,43 @@ export const esESObjects: NonNullable = { } } }, + register_service_account: { + label: "Registrar cuenta de servicio de IA", + description: "Registra una cuenta de servicio de IA en esta organización: una identidad propia para un agente que funciona sin una persona y que actúa solo mediante las claves de API creadas para ella. No puede hacer nada hasta que se le concedan conjuntos de permisos, y nunca tiene acceso de administrador.", + successMessage: "Cuenta de servicio de IA registrada", + params: { + name: { + label: "Nombre", + helpText: "Qué es el agente y para qué sirve. Con este nombre se reconoce la cuenta en la lista de usuarios y en el registro de auditoría." + }, + ownerId: { + label: "Responsable", + helpText: "La persona responsable de esta cuenta, miembro de esta organización. Déjalo vacío para ser tú el responsable." + } + } + }, + create_service_account_key: { + label: "Crear clave de API", + description: "Crea una clave de API para esta cuenta de servicio de IA. La clave actúa como la cuenta, con los permisos propios de la cuenta, en la organización de la cuenta.", + params: { + name: { + label: "Nombre de la clave" + }, + expires_at: { + label: "Caduca el", + helpText: "Déjelo vacío para usar la duración predeterminada de la clave definida en Configuración → Autenticación → Claves de API (90 días si no se ha cambiado). Una fecha posterior a la duración máxima de la clave definida allí se rechaza." + } + }, + resultDialog: { + title: "Clave de API creada", + description: "Copia la clave ahora: solo se muestra una vez y no se puede recuperar. Si se filtra, revócala y crea una nueva.", + acknowledge: "He guardado la clave", + fields: { + key: "Clave de API", + expires_at: "Caduca el" + } + } + }, update_my_profile: { label: "Actualizar perfil", successMessage: "Perfil actualizado" diff --git a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts index 4f0b18dd4ee..e1ab599e8a5 100644 --- a/packages/platform-objects/src/apps/translations/fr.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/fr.objects.generated.ts @@ -267,6 +267,43 @@ export const frObjects: NonNullable = { } } }, + register_service_account: { + label: "Enregistrer un compte de service IA", + description: "Enregistrez un compte de service IA dans cette organisation : une identité propre pour un agent qui fonctionne sans personne et n'agit qu'au moyen des clés d'API créées pour lui. Il ne peut rien faire tant qu'aucun ensemble d'autorisations ne lui est attribué, et il n'a jamais d'accès administrateur.", + successMessage: "Compte de service IA enregistré", + params: { + name: { + label: "Nom", + helpText: "Ce qu'est l'agent et à quoi il sert. C'est sous ce nom que le compte apparaît dans la liste des utilisateurs et dans le journal d'audit." + }, + ownerId: { + label: "Responsable", + helpText: "La personne responsable de ce compte, membre de cette organisation. Laissez vide pour en être vous-même le responsable." + } + } + }, + create_service_account_key: { + label: "Créer une clé d'API", + description: "Créez une clé d'API pour ce compte de service IA. La clé agit en tant que compte, avec les autorisations propres du compte, dans l'organisation du compte.", + params: { + name: { + label: "Nom de la clé" + }, + expires_at: { + label: "Expire le", + helpText: "Laissez vide pour la durée de vie par défaut définie dans Configuration → Authentification → Clés API (Durée de vie par défaut des clés, 90 jours sauf modification). Une date postérieure à la Durée de vie maximale des clés qui y est définie est refusée." + } + }, + resultDialog: { + title: "Clé API créée", + description: "Copiez la clé maintenant — elle n’est affichée qu’une seule fois et ne peut pas être récupérée. En cas de fuite, révoquez-la et créez-en une nouvelle.", + acknowledge: "J’ai enregistré la clé", + fields: { + key: "Clé API", + expires_at: "Expire le" + } + } + }, update_my_profile: { label: "Mettre à jour le profil", successMessage: "Profil mis à jour" diff --git a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts index 5a4240f8322..a8fb0d8a55b 100644 --- a/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ja-JP.objects.generated.ts @@ -267,6 +267,43 @@ export const jaJPObjects: NonNullable = { } } }, + register_service_account: { + label: "AI サービスアカウントを登録", + description: "この組織に AI サービスアカウントを登録します。人が介在せずに動作するエージェントのための独立した ID で、作成された API キーを通じてのみ動作します。権限セットが付与されるまでは何もできず、管理者権限を持つことはありません。", + successMessage: "AI サービスアカウントを登録しました", + params: { + name: { + label: "名前", + helpText: "このエージェントが何であり、何のためのものか。ユーザー一覧と監査証跡では、この名前でアカウントを識別します。" + }, + ownerId: { + label: "責任者", + helpText: "このアカウントに責任を持つ人で、この組織のメンバーである必要があります。空欄のままにすると、あなた自身が責任者になります。" + } + } + }, + create_service_account_key: { + label: "API キーを作成", + description: "この AI サービスアカウントの API キーを作成します。キーはアカウント自身として、アカウント自身の権限で、アカウントの組織内で動作します。", + params: { + name: { + label: "キー名" + }, + expires_at: { + label: "有効期限", + helpText: "空欄のままにすると、「設定 → 認証 → API キー」のキーの既定の有効期間(変更していなければ 90 日)が使われます。そこにあるキーの最大有効期間より後の日付は拒否されます。" + } + }, + resultDialog: { + title: "API キーを作成しました", + description: "今すぐキーをコピーしてください。キーは一度しか表示されず、後から取得することはできません。漏えいした場合は失効させて新しいキーを作成してください。", + acknowledge: "キーを保存しました", + fields: { + key: "API キー", + expires_at: "有効期限" + } + } + }, update_my_profile: { label: "プロフィール更新", successMessage: "プロフィールを更新しました" diff --git a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts index 6f7b33db8f0..dcc9fc1c269 100644 --- a/packages/platform-objects/src/apps/translations/ko.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ko.objects.generated.ts @@ -267,6 +267,43 @@ export const koObjects: NonNullable = { } } }, + register_service_account: { + label: "AI 서비스 계정 등록", + description: "이 조직에 AI 서비스 계정을 등록합니다. 사람 없이 실행되는 에이전트를 위한 고유한 ID로, 이를 위해 만든 API 키를 통해서만 동작합니다. 권한 집합을 부여받기 전에는 아무것도 할 수 없으며, 관리자 권한은 절대 갖지 않습니다.", + successMessage: "AI 서비스 계정이 등록되었습니다", + params: { + name: { + label: "이름", + helpText: "이 에이전트가 무엇이며 무엇을 위한 것인지 적으세요. 사용자 목록과 감사 기록에서 이 이름으로 계정을 식별합니다." + }, + ownerId: { + label: "책임자", + helpText: "이 계정에 책임을 지는 사람으로, 이 조직의 구성원이어야 합니다. 비워 두면 본인이 책임자가 됩니다." + } + } + }, + create_service_account_key: { + label: "API 키 만들기", + description: "이 AI 서비스 계정의 API 키를 만듭니다. 키는 계정 자신으로서, 계정 자신의 권한으로, 계정의 조직에서 동작합니다.", + params: { + name: { + label: "키 이름" + }, + expires_at: { + label: "만료 시각", + helpText: "설정 → 인증 → API 키에서 정한 기본 수명(기본 키 수명, 변경하지 않았다면 90일)을 쓰려면 비워 두세요. 그곳의 최대 키 수명보다 늦은 날짜는 거부됩니다." + } + }, + resultDialog: { + title: "API 키 생성됨", + description: "지금 키를 복사하세요. 한 번만 표시되며 복구할 수 없습니다. 유출되면 취소하고 새 키를 만드세요.", + acknowledge: "키를 저장했습니다", + fields: { + key: "API 키", + expires_at: "만료 시각" + } + } + }, update_my_profile: { label: "프로필 업데이트", successMessage: "프로필 업데이트됨" diff --git a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts index cf565caf761..a38cbae0080 100644 --- a/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/pt-BR.objects.generated.ts @@ -267,6 +267,43 @@ export const ptBRObjects: NonNullable = { } } }, + register_service_account: { + label: "Registrar conta de serviço de IA", + description: "Registre uma conta de serviço de IA nesta organização: uma identidade própria para um agente que funciona sem uma pessoa e age apenas por meio das chaves de API criadas para ela. Ela não pode fazer nada até receber conjuntos de permissões e nunca tem acesso de administrador.", + successMessage: "Conta de serviço de IA registrada", + params: { + name: { + label: "Nome", + helpText: "O que o agente é e para que serve. É por este nome que a conta é reconhecida na lista de usuários e na trilha de auditoria." + }, + ownerId: { + label: "Responsável", + helpText: "A pessoa responsável por esta conta, membro desta organização. Deixe em branco para ser você o responsável." + } + } + }, + create_service_account_key: { + label: "Criar chave de API", + description: "Crie uma chave de API para esta conta de serviço de IA. A chave age como a conta, com as permissões da própria conta, na organização da conta.", + params: { + name: { + label: "Nome da chave" + }, + expires_at: { + label: "Expira em", + helpText: "Deixe em branco para usar a validade padrão definida em Configuração → Autenticação → Chaves de API (Validade padrão da chave, 90 dias se não for alterada). Uma data posterior à Validade máxima da chave definida lá é recusada." + } + }, + resultDialog: { + title: "Chave de API criada", + description: "Copie a chave agora — ela é mostrada apenas uma vez e não pode ser recuperada. Se ela vazar, revogue-a e crie uma nova.", + acknowledge: "Guardei a chave", + fields: { + key: "Chave de API", + expires_at: "Expira em" + } + } + }, update_my_profile: { label: "Atualizar perfil", successMessage: "Perfil atualizado" diff --git a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts index 9c13728147e..e0fcb7f3930 100644 --- a/packages/platform-objects/src/apps/translations/ru.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/ru.objects.generated.ts @@ -267,6 +267,43 @@ export const ruObjects: NonNullable = { } } }, + register_service_account: { + label: "Зарегистрировать сервисную учётную запись ИИ", + description: "Зарегистрируйте сервисную учётную запись ИИ в этой организации: собственную идентичность для агента, который работает без участия человека и действует только через созданные для него ключи API. Пока ей не назначены наборы разрешений, она ничего не может делать, и у неё никогда нет прав администратора.", + successMessage: "Сервисная учётная запись ИИ зарегистрирована", + params: { + name: { + label: "Название", + helpText: "Что это за агент и для чего он нужен. По этому названию учётная запись узнаётся в списке пользователей и в журнале аудита." + }, + ownerId: { + label: "Ответственное лицо", + helpText: "Человек, отвечающий за эту учётную запись, — участник этой организации. Оставьте пустым, чтобы ответственным были вы." + } + } + }, + create_service_account_key: { + label: "Создать ключ API", + description: "Создайте ключ API для этой сервисной учётной записи ИИ. Ключ действует от имени учётной записи, с её собственными разрешениями, в её организации.", + params: { + name: { + label: "Название ключа" + }, + expires_at: { + label: "Истекает", + helpText: "Оставьте пустым, чтобы использовать срок действия по умолчанию из раздела «Настройка → Аутентификация → API-ключи» (срок действия ключа по умолчанию — 90 дней, если не изменён). Дата позже указанного там максимального срока действия ключа отклоняется." + } + }, + resultDialog: { + title: "API-ключ создан", + description: "Скопируйте ключ сейчас — он показывается только один раз и не может быть восстановлен. При утечке отзовите его и создайте новый.", + acknowledge: "Я сохранил(а) ключ", + fields: { + key: "API-ключ", + expires_at: "Истекает" + } + } + }, update_my_profile: { label: "Обновить профиль", successMessage: "Профиль обновлён" diff --git a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts index fe69c7531b0..29cc3f779aa 100644 --- a/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-CN.objects.generated.ts @@ -267,6 +267,43 @@ export const zhCNObjects: NonNullable = { } } }, + register_service_account: { + label: "注册 AI 服务账号", + description: "在此组织中注册一个 AI 服务账号:为无人值守运行的智能体提供一个独立身份,它只能通过为其创建的 API 密钥行事。在被授予权限集之前它什么也做不了,并且永远不会拥有管理员权限。", + successMessage: "AI 服务账号已注册", + params: { + name: { + label: "名称", + helpText: "说明这个智能体是什么、用来做什么。用户列表和审计记录中靠这个名称识别该账号。" + }, + ownerId: { + label: "责任人", + helpText: "对该账号负责的人,须是此组织的成员。留空则由你本人担任责任人。" + } + } + }, + create_service_account_key: { + label: "创建 API 密钥", + description: "为此 AI 服务账号创建一个 API 密钥。该密钥以账号本身的身份、按账号自己的授权,在账号所属的组织中行事。", + params: { + name: { + label: "密钥名称" + }, + expires_at: { + label: "过期时间", + helpText: "留空则使用「设置 → 身份验证 → API 密钥」中的默认密钥有效期(未修改时为 90 天)。晚于该处密钥最长有效期的日期会被拒绝。" + } + }, + resultDialog: { + title: "API 密钥已创建", + description: "请立即复制密钥——它只显示这一次,之后无法找回。如果泄露,请撤销它并创建新的密钥。", + acknowledge: "我已保存密钥", + fields: { + key: "API 密钥", + expires_at: "过期时间" + } + } + }, update_my_profile: { label: "更新资料", successMessage: "已更新资料" diff --git a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts index 150cd134eb7..d593e608484 100644 --- a/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts +++ b/packages/platform-objects/src/apps/translations/zh-Hant.objects.generated.ts @@ -267,6 +267,43 @@ export const zhHantObjects: NonNullable = { } } }, + register_service_account: { + label: "註冊 AI 服務帳號", + description: "在此組織中註冊一個 AI 服務帳號:為無人值守執行的智慧代理提供獨立身分,它只能透過為其建立的 API 金鑰行事。在被授予權限集之前它什麼都不能做,而且永遠不會擁有管理員權限。", + successMessage: "AI 服務帳號已註冊", + params: { + name: { + label: "名稱", + helpText: "說明這個智慧代理是什麼、用來做什麼。使用者清單與稽核記錄中以此名稱辨識該帳號。" + }, + ownerId: { + label: "負責人", + helpText: "對此帳號負責的人,須為此組織的成員。留空則由你本人擔任負責人。" + } + } + }, + create_service_account_key: { + label: "建立 API 金鑰", + description: "為此 AI 服務帳號建立一個 API 金鑰。該金鑰以帳號本身的身分、依帳號自己的授權,在帳號所屬的組織中行事。", + params: { + name: { + label: "金鑰名稱" + }, + expires_at: { + label: "到期時間", + helpText: "留空則使用「設定 → 身分驗證 → API 金鑰」中的預設金鑰有效期(未修改時為 90 天)。晚於該處金鑰最長有效期的日期會被拒絕。" + } + }, + resultDialog: { + title: "API 金鑰已建立", + description: "請立即複製金鑰——它只顯示這一次,之後無法找回。如果洩露,請撤銷它並建立新的金鑰。", + acknowledge: "我已儲存金鑰", + fields: { + key: "API 金鑰", + expires_at: "到期時間" + } + } + }, update_my_profile: { label: "更新資料", successMessage: "已更新資料" diff --git a/packages/platform-objects/src/identity/sys-user.object.ts b/packages/platform-objects/src/identity/sys-user.object.ts index a986b2d6949..6e4064cf5ec 100644 --- a/packages/platform-objects/src/identity/sys-user.object.ts +++ b/packages/platform-objects/src/identity/sys-user.object.ts @@ -2,7 +2,9 @@ import { ObjectSchema, Field } from '@objectstack/spec/data'; import { PLATFORM_ADMIN_USERS_GATE } from './platform-admin-action-gate.js'; -import { INVITATION_ROLE_OPTIONS } from '@objectstack/spec/identity'; +import { + INVITATION_ROLE_OPTIONS, MEMBERSHIP_ROLE_ADMIN, MEMBERSHIP_ROLE_OWNER, mapMembershipRole, +} from '@objectstack/spec/identity'; import { INVITE_USER_OUTCOME_MESSAGES } from './invite-outcome-messages.js'; import { MEMBERSHIP_ROLE_PARAM_HELP } from './membership-role-help.js'; @@ -48,6 +50,19 @@ export const SYS_USER_LOCALE_TAG_PATTERN = '^[A-Za-z]{2,3}(?:-[A-Za-z0-9]{1,8})* * returns `temporaryPassword` only when it generated one: the instruction * shows exactly when there is a password to copy. */ +/** + * [ADR-0151 D1/D4] Who is offered the AI service account actions: a platform + * administrator, or an owner or admin of the current organization (the + * grades `isOrgAdminGrade` admits, read here off `current_user.positions` as + * the `requiresMembershipReach` sugar reads them). Display only: the + * plugin-auth doors judge the caller themselves, and a key's door also + * admits the account's accountable owner. + */ +const SERVICE_ACCOUNT_ADMIN_VISIBLE = [ + 'current_user.isPlatformAdmin == true', + ...[MEMBERSHIP_ROLE_OWNER, MEMBERSHIP_ROLE_ADMIN].map((grade) => `'${mapMembershipRole(grade)}' in current_user.positions`), +].join(' || '); + const TEMPORARY_PASSWORD_LABEL = 'Temporary password: copy it now, it is shown only once and never stored'; /** @@ -633,6 +648,88 @@ export const SysUser = ObjectSchema.create({ }, }, + // ── AI service accounts (ADR-0151) ─────────────────────────────── + // + // An AI service account is a `sys_user` row of kind `agent`: a registered + // principal of its own that acts only through its own API keys, under the + // agent ceiling, and never signs in. These two actions are its + // registration and its key mint (plugin-auth `service-account-doors.ts`). + // Each door reads the caller from the session and judges them itself; + // `visible` is display only. No `ai` block: an account and its keys are + // a person's decision, so both stay human-only. + { + name: 'register_service_account', + label: 'Register AI Service Account', + icon: 'bot', + variant: 'secondary', + locations: ['list_toolbar'], + type: 'api', + target: '/api/v1/auth/service-account/register', + // Offered in a cloud-managed environment too: an account is no person + // the identity provider brings, and a licence plugin observes or + // refuses the registration on its own `sys_user` write (ADR-0151 D7). + visible: SERVICE_ACCOUNT_ADMIN_VISIBLE, + description: + 'Register an AI service account in this organization: an identity of its own for an agent that runs ' + + 'without a person, acting only through API keys created for it. It can do nothing until it is granted ' + + 'permission sets, and it never holds administrator access.', + successMessage: 'AI service account registered', + refreshAfter: true, + params: [ + { + name: 'name', + label: 'Name', + type: 'text', + required: true, + helpText: 'What the agent is and what it is for. This name is how the account is recognised in the user list and the audit trail.', + }, + { + name: 'ownerId', + label: 'Accountable Owner', + type: 'lookup', + reference: 'sys_user', + required: false, + helpText: 'The person accountable for this account, a member of this organization. Leave empty to be the owner yourself.', + }, + ], + }, + { + name: 'create_service_account_key', + label: 'Create API Key', + icon: 'key-round', + variant: 'secondary', + locations: ['list_item', 'record_header'], + type: 'api', + target: '/api/v1/auth/service-account/create-key', + // An AI service account's row only. Its owner is admitted by the door + // too; this term offers it to administrators and to the owner. + visible: `has(record.principal_kind) && record.principal_kind == "agent" && ((${SERVICE_ACCOUNT_ADMIN_VISIBLE}) || (has(record.accountable_user_id) && record.accountable_user_id == current_user.id))`, + recordIdParam: 'userId', + description: + 'Create an API key for this AI service account. The key acts as the account, with the account\'s own ' + + 'grants, in the account\'s organization.', + refreshAfter: false, + params: [ + { name: 'name', label: 'Key Name', type: 'text', required: true }, + { + name: 'expires_at', + label: 'Expires At', + type: 'datetime', + required: false, + helpText: 'Leave empty for the default lifetime set under Setup → Authentication → API keys (Default key lifetime, 90 days unless changed). A date later than the Maximum key lifetime there is refused.', + }, + ], + resultDialog: { + title: 'API key created', + description: 'Copy the key now — it is shown only once and cannot be recovered. If it leaks, revoke it and create a new one.', + acknowledge: 'I have saved the key', + fields: [ + { path: 'key', label: 'API Key', format: 'secret' }, + { path: 'expires_at', label: 'Expires At', format: 'text' }, + ], + }, + }, + // ── Self-service actions (the row owner only) ───────────────────── // // These four actions are the "account settings" surfaces the standalone From e2699df42d02aca66bd006577ee0ff3625467f44 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:43:27 +0000 Subject: [PATCH 3/6] test(plugin-auth): the AI service account doors on a real engine; route ledger rows Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- .../plugins/plugin-auth/src/auth-plugin.ts | 48 ++- .../src/auth-route-ledger.conformance.test.ts | 8 + .../plugin-auth/src/auth-route-ledger.ts | 3 + .../src/service-account-doors.test.ts | 330 ++++++++++++++++++ 4 files changed, 364 insertions(+), 25 deletions(-) create mode 100644 packages/plugins/plugin-auth/src/service-account-doors.test.ts diff --git a/packages/plugins/plugin-auth/src/auth-plugin.ts b/packages/plugins/plugin-auth/src/auth-plugin.ts index 5febba3dddf..f4507e2d4fc 100644 --- a/packages/plugins/plugin-auth/src/auth-plugin.ts +++ b/packages/plugins/plugin-auth/src/auth-plugin.ts @@ -4150,42 +4150,40 @@ export class AuthPlugin implements Plugin { resolveApiKeyLifecyclePolicy: () => this.authManager!.resolveApiKeyLifecyclePolicy(), }); const serviceAccountRoute = ( - path: string, + path: 'register' | 'create-key', run: ( deps: import('./service-account-doors.js').ServiceAccountDoorDeps, caller: import('./service-account-doors.js').ServiceAccountCaller, request: Request, ) => Promise, - ): void => { - rawApp.post(`${basePath}/service-account/${path}`, async (c: any) => { - try { - const caller = await serviceAccountCaller(c); - if (caller instanceof Response) return caller; - const { status, body } = await runAttributedToUser(caller, () => run(serviceAccountDeps(), caller, c.req.raw)); - return c.json(body, status as any); - } catch (error) { - // An unreadable membership or policy is an outage, never a caller - // without standing: answered 503 in the shared seam's words. - if (isAuthzStoreUnavailableError(error)) { - return c.json( - { success: false, error: { code: AUTHZ_STORE_UNAVAILABLE_CODE, message: AUTHZ_STORE_UNAVAILABLE_MESSAGE } }, - AUTHZ_STORE_UNAVAILABLE_STATUS, - ); - } - const err = error instanceof Error ? error : new Error(String(error)); - ctx.logger.error(`[AuthPlugin] service-account/${path} failed`, err); - return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: 'The request could not be completed.' } }, 500); + ) => async (c: any) => { + try { + const caller = await serviceAccountCaller(c); + if (caller instanceof Response) return caller; + const { status, body } = await runAttributedToUser(caller, () => run(serviceAccountDeps(), caller, c.req.raw)); + return c.json(body, status as any); + } catch (error) { + // An unreadable membership or policy is an outage, never a caller + // without standing: answered 503 in the shared seam's words. + if (isAuthzStoreUnavailableError(error)) { + return c.json( + { success: false, error: { code: AUTHZ_STORE_UNAVAILABLE_CODE, message: AUTHZ_STORE_UNAVAILABLE_MESSAGE } }, + AUTHZ_STORE_UNAVAILABLE_STATUS, + ); } - }); + const err = error instanceof Error ? error : new Error(String(error)); + ctx.logger.error(`[AuthPlugin] service-account/${path} failed`, err); + return c.json({ success: false, error: { code: 'INTERNAL_ERROR', message: 'The request could not be completed.' } }, 500); + } }; - serviceAccountRoute('register', async (deps, caller, request) => { + rawApp.post(`${basePath}/service-account/register`, serviceAccountRoute('register', async (deps, caller, request) => { const { runRegisterServiceAccount } = await import('./service-account-doors.js'); return runRegisterServiceAccount(deps, caller, request); - }); - serviceAccountRoute('create-key', async (deps, caller, request) => { + })); + rawApp.post(`${basePath}/service-account/create-key`, serviceAccountRoute('create-key', async (deps, caller, request) => { const { runCreateServiceAccountKey } = await import('./service-account-doors.js'); return runCreateServiceAccountKey(deps, caller, request); - }); + })); // ──────────────────────────────────────────────────────────────────── // [#30398] ADR-0069 D5 — admin: the caller's own address as the diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts index 1e9cdd7fce0..52be67766e0 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.conformance.test.ts @@ -304,6 +304,14 @@ describe('auth route ledger hygiene', () => { 'POST /api/v1/auth/admin/unlock-user', 'POST /api/v1/auth/authorized-clients/withdraw', 'POST /api/v1/auth/organization/add-member', + // [ADR-0151 D1/D4] The AI service account's registration and key mint, + // on this pin's own terms: `auth-plugin.ts` mounts both itself (a + // `rawApp.post` on the `${basePath}/service-account/create-key` and + // `${basePath}/service-account/register` templates, ahead of the + // catch-all), and the `live.has(route)` loop below holds them to the same + // proof — better-auth serves no service-account endpoint. + 'POST /api/v1/auth/service-account/create-key', + 'POST /api/v1/auth/service-account/register', 'POST /api/v1/auth/set-initial-password', 'POST /api/v1/auth/sys-oauth-application/register', // The fourteenth, on this pin's own terms: `auth-plugin.ts` mounts it diff --git a/packages/plugins/plugin-auth/src/auth-route-ledger.ts b/packages/plugins/plugin-auth/src/auth-route-ledger.ts index 9e6ebe7c918..9cd05869e79 100644 --- a/packages/plugins/plugin-auth/src/auth-route-ledger.ts +++ b/packages/plugins/plugin-auth/src/auth-route-ledger.ts @@ -270,6 +270,9 @@ export const AUTH_ROUTE_LEDGER: readonly AuthRouteLedgerEntry[] = [ // #31030 — the tracker id stays HERE and never in the `note` string, per the // #16678 note above. { route: 'GET /api/v1/auth/client-address', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL. The organization administrator\'s twin of GET /admin/client-address: the caller\'s own address exactly as the access_policy.allowed_ip_ranges save check judges it, served before a save; the same { clientAddress, trustProxy } answer, Cache-Control: no-store, closed and empty query set. Gated to the caller who may save that list: setup.write in their current organization, resolved by resolveRequestExecutionContext with the settings door\'s parameters (401 UNAUTHENTICATED, a held session 403 with its posture code, otherwise 403 PERMISSION_DENIED). No parameter names another user, session or organization. ADR-0069 TL;DR 6 and D5' }, + // ADR-0151 D1/D4 — the AI service account's registration and key mint. + { route: 'POST /api/v1/auth/service-account/create-key', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_user create_service_account_key action posts it directly; mints one sys_api_key for an AI service account (userId: a sys_user row of kind agent; a person\'s id answers 404 as unknown), user_id the account and active_organization_id its one membership\'s organization (never the caller\'s, never the body\'s), signed with the same lifecycle rule as POST /keys (default life, API_KEY_EXPIRY_TOO_LONG past the ceiling), raw secret returned once and only its hash stored; a retired account (no membership) is refused 409. A signed-in session only (401 without one, a held session 403 with its posture): the account\'s accountable owner, an administrator of its organization (membership grade admin or owner), or a platform administrator; anyone else 403 PERMISSION_DENIED; an unreadable membership 503. ADR-0151 D4' }, + { route: 'POST /api/v1/auth/service-account/register', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_user register_service_account action posts it directly; registers an AI service account in the caller\'s current organization in one unit of work: the sys_user row (principal_kind agent, accountable_user_id the named owner or the caller, a placeholder .invalid address, source env_native), written through the data engine so its sys_user hooks judge it, and its one sys_member row as a plain member through the vendor\'s server-only addMember (a refused membership rolls the row back). The owner must be a member of the organization (400 VALIDATION_FAILED on ownerId); name required. A signed-in session only (401 without one, a held session 403 with its posture): an administrator of the current organization (membership grade admin or owner) or a platform administrator; anyone else 403 PERMISSION_DENIED; an unreadable membership 503. ADR-0151 D1' }, { route: 'POST /api/v1/auth/sys-oauth-application/register', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_oauth_application create action posts it directly; session-required self-service wrapper over better-auth /oauth2/create-client that splits the Console\'s newline-separated redirect-URL textarea into the redirect_uris array the vendor schema requires' }, { route: 'POST /api/v1/auth/sys-session/revoke', family: 'objectstack-mount', source: 'objectstack', disposition: 'server-only', note: 'no SDK method builds this URL — the sys_session revoke_session row action posts it directly with the row id; the server resolves the session from the id, so the session token never travels to or from the console. The session owner is re-dispatched to better-auth /revoke-session; another user\'s session is revocable by a platform admin only (ADR-0068 D2), tombstoned with reason admin (ADR-0069 D4)' }, { route: 'POST /api/v1/auth/organization/accept-invitation', family: 'organization', source: 'better-auth', disposition: 'sdk', client: 'organizations.invitations.accept', requires: 'organization' }, diff --git a/packages/plugins/plugin-auth/src/service-account-doors.test.ts b/packages/plugins/plugin-auth/src/service-account-doors.test.ts new file mode 100644 index 00000000000..d3943cb8b16 --- /dev/null +++ b/packages/plugins/plugin-auth/src/service-account-doors.test.ts @@ -0,0 +1,330 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [ADR-0151 D1/D4] The AI service account's registration and key mint + * (`service-account-doors.ts`), on a REAL ObjectQL engine over better-sqlite3 + * `:memory:` with the real `sys_user` row rules registered + * (`registerServiceAccountRowGuard`), so the engine dispatches the hooks the + * registration's insert must pass. The vendor's `addMember` is the one + * double: it writes the membership row (or refuses, where a pin says so). + * + * What is pinned, each refusal beside its CONTROL: + * + * - who may register (an organization administrator, a platform + * administrator) and who may not (a plain member; no current organization); + * - what register writes, in one act: the agent row with its owner, an + * undeliverable placeholder address and `env_native`, and one plain + * membership; a membership the vendor refuses leaves no row behind; + * - the owner: a member of the organization, never another account; + * - who may mint a key (the owner, an administrator of the account's + * organization, a platform administrator) and who may not (another member, + * an administrator of another organization); + * - what the key is: the account's, in the account's organization, signed + * under the lifecycle policy, its secret returned once and stored hashed; + * - a person's id, and a retired account, get no key; + * - an unreadable membership is an outage (503), never a verdict. + */ + +import { describe, it, expect, beforeEach, afterEach } from 'vitest'; +import { ObjectQL } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { hashApiKey, isAuthzStoreUnavailableError } from '@objectstack/core'; + +import { + runCreateServiceAccountKey, runRegisterServiceAccount, + type ServiceAccountCaller, type ServiceAccountDoorDeps, +} from './service-account-doors.js'; +import { registerServiceAccountRowGuard } from './service-account-identity.js'; +import { isPlaceholderEmail } from './placeholder-email.js'; +import { relaxTenantColumns } from './pre-18-tenant-column.testkit.js'; + +const SYSTEM = { context: { isSystem: true } } as const; +const ORG = 'org_a'; +const OTHER_ORG = 'org_b'; +const DAY_MS = 86_400_000; +const NOW = Date.parse('2026-11-09T12:00:00.000Z'); + +const text = (name: string) => ({ name, type: 'text' as const }); +const OBJECTS = [ + { + name: 'sys_user', + label: 'User', + fields: { + id: { ...text('id'), primaryKey: true }, + name: text('name'), + email: text('email'), + email_verified: { name: 'email_verified', type: 'boolean' as const }, + principal_kind: text('principal_kind'), + accountable_user_id: text('accountable_user_id'), + source: text('source'), + }, + }, + { + name: 'sys_member', + label: 'Member', + fields: { id: { ...text('id'), primaryKey: true }, user_id: text('user_id'), organization_id: text('organization_id'), role: text('role') }, + }, + { + name: 'sys_api_key', + label: 'API Key', + fields: { + id: { ...text('id'), primaryKey: true }, + name: text('name'), + key: text('key'), + prefix: text('prefix'), + user_id: text('user_id'), + revoked: { name: 'revoked', type: 'boolean' as const }, + expires_at: text('expires_at'), + active_organization_id: text('active_organization_id'), + }, + }, +]; + +let engine: ObjectQL; +let refuseMembership: Error | undefined; +let failMemberReads = false; + +const POLICY = { defaultExpiryDays: 90, maxExpiryDays: 365, inactivityDays: 90 } as any; + +const deps = (): ServiceAccountDoorDeps => ({ + getDataEngine: () => ({ + find: (object, query, options) => { + if (failMemberReads && object === 'sys_member') return Promise.reject(new Error('sys_member is unreachable')); + return engine.find(object, query as any, options as any); + }, + insert: (object, data, options) => engine.insert(object, data, options as any), + }), + addMember: async ({ userId, organizationId }) => { + if (refuseMembership) throw refuseMembership; + await engine.insert('sys_member', { user_id: userId, organization_id: organizationId, role: 'member' }, SYSTEM); + }, + runAtomically: (work) => engine.transaction(async () => work()), + resolveApiKeyLifecyclePolicy: () => POLICY, + now: () => NOW, +}); + +const caller = (id: string, opts: Partial = {}): ServiceAccountCaller => ({ + id, isPlatformAdmin: false, activeOrganizationId: ORG, ...opts, +}); + +const post = (body: unknown) => + new Request('http://localhost/api/v1/auth/service-account/x', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify(body), + }); + +const rows = async (object: string, where: Record = {}) => + (await engine.find(object, { where, ...SYSTEM } as any)) as Array>; + +beforeEach(async () => { + refuseMembership = undefined; + failMemberReads = false; + engine = new ObjectQL(); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }), + true, + ); + await engine.init(); + for (const o of OBJECTS) engine.registry.registerObject(o as never); + await engine.syncSchemas(); + await relaxTenantColumns(engine, ['sys_user', 'sys_member', 'sys_api_key']); + registerServiceAccountRowGuard(engine, { packageId: 'test.service-account-doors' }); + + for (const id of ['usr_admin', 'usr_owner', 'usr_member', 'usr_other_admin', 'usr_platform']) { + await engine.insert('sys_user', { id, name: id, email: `${id}@a.example`, email_verified: true, principal_kind: 'human' }, SYSTEM); + } + const members: Array<[string, string, string]> = [ + ['usr_admin', ORG, 'admin'], + ['usr_owner', ORG, 'member'], + ['usr_member', ORG, 'member'], + ['usr_other_admin', OTHER_ORG, 'owner'], + ]; + for (const [user_id, organization_id, role] of members) { + await engine.insert('sys_member', { user_id, organization_id, role }, SYSTEM); + } +}); + +afterEach(async () => { + try { await engine.destroy(); } catch { /* noop */ } +}); + +/** Register an account owned by `usr_owner`, as the organization administrator. */ +async function registered(name = 'Invoice bot'): Promise { + const r = await runRegisterServiceAccount(deps(), caller('usr_admin'), post({ name, ownerId: 'usr_owner' })); + expect(r.status, JSON.stringify(r.body)).toBe(201); + return String(r.body.data!.userId); +} + +describe('[ADR-0151 D1] register: who may, and what one act writes', () => { + it('an organization administrator registers an account: the agent row, its owner, an undeliverable address, and one plain membership', async () => { + const r = await runRegisterServiceAccount(deps(), caller('usr_admin'), post({ name: 'Invoice bot', ownerId: 'usr_owner' })); + expect(r.status).toBe(201); + expect(r.body.data).toMatchObject({ name: 'Invoice bot', principalKind: 'agent', organizationId: ORG, ownerId: 'usr_owner' }); + const id = String(r.body.data!.userId); + + const [row] = await rows('sys_user', { id }); + expect(row).toMatchObject({ name: 'Invoice bot', principal_kind: 'agent', accountable_user_id: 'usr_owner', source: 'env_native' }); + expect(isPlaceholderEmail(row.email)).toBe(true); + expect(await rows('sys_member', { user_id: id })).toEqual([ + expect.objectContaining({ organization_id: ORG, role: 'member' }), + ]); + }); + + it('the placeholder address never repeats: two accounts get two distinct undeliverable addresses', async () => { + const a = await registered('Bot A'); + const b = await registered('Bot B'); + const [ra] = await rows('sys_user', { id: a }); + const [rb] = await rows('sys_user', { id: b }); + expect(ra.email).not.toBe(rb.email); + for (const email of [ra.email, rb.email]) { + expect(isPlaceholderEmail(email)).toBe(true); + expect(email).toMatch(/@placeholder\.invalid$/); + } + }); + + it('the owner defaults to the caller', async () => { + const r = await runRegisterServiceAccount(deps(), caller('usr_admin'), post({ name: 'Bot' })); + expect(r.status).toBe(201); + const [row] = await rows('sys_user', { id: String(r.body.data!.userId) }); + expect(row.accountable_user_id).toBe('usr_admin'); + }); + + it('a platform administrator registers one too', async () => { + const r = await runRegisterServiceAccount( + deps(), caller('usr_platform', { isPlatformAdmin: true }), post({ name: 'Bot', ownerId: 'usr_owner' }), + ); + expect(r.status).toBe(201); + }); + + it('a plain member is refused 403 and nothing is written', async () => { + const before = (await rows('sys_user')).length; + const r = await runRegisterServiceAccount(deps(), caller('usr_member'), post({ name: 'Bot', ownerId: 'usr_member' })); + expect(r).toMatchObject({ status: 403, body: { error: { code: 'PERMISSION_DENIED' } } }); + expect((await rows('sys_user')).length).toBe(before); + }); + + it('an administrator of another organization is refused 403 in this one', async () => { + const r = await runRegisterServiceAccount(deps(), caller('usr_other_admin'), post({ name: 'Bot', ownerId: 'usr_owner' })); + expect(r).toMatchObject({ status: 403, body: { error: { code: 'PERMISSION_DENIED' } } }); + }); + + it('no current organization is refused 400', async () => { + const r = await runRegisterServiceAccount(deps(), caller('usr_admin', { activeOrganizationId: null }), post({ name: 'Bot' })); + expect(r).toMatchObject({ status: 400, body: { error: { code: 'INVALID_REQUEST' } } }); + }); + + it('a name is required', async () => { + const r = await runRegisterServiceAccount(deps(), caller('usr_admin'), post({ ownerId: 'usr_owner' })); + expect(r).toMatchObject({ status: 400, body: { error: { code: 'VALIDATION_FAILED', fields: [{ field: 'name', code: 'required' }] } } }); + }); + + it('an owner who is not a member of the organization is refused at ownerId', async () => { + const r = await runRegisterServiceAccount(deps(), caller('usr_admin'), post({ name: 'Bot', ownerId: 'usr_other_admin' })); + expect(r).toMatchObject({ status: 400, body: { error: { code: 'VALIDATION_FAILED', fields: [{ field: 'ownerId', code: 'invalid_value' }] } } }); + }); + + it('another account is never an owner: the row rules refuse it, and no row is written', async () => { + const bot = await registered(); + const before = (await rows('sys_user')).length; + const r = await runRegisterServiceAccount(deps(), caller('usr_admin'), post({ name: 'Bot 2', ownerId: bot })); + expect(r).toMatchObject({ status: 400, body: { error: { code: 'VALIDATION_FAILED', fields: [{ field: 'accountable_user_id', code: 'invalid_value' }] } } }); + expect((await rows('sys_user')).length).toBe(before); + }); + + it('a membership the vendor refuses rolls the row back: no account exists without its organization', async () => { + refuseMembership = Object.assign(new Error('limit'), { + statusCode: 403, body: { code: 'ORGANIZATION_MEMBERSHIP_LIMIT_REACHED', message: 'Organization membership limit reached' }, + }); + const before = (await rows('sys_user')).length; + const r = await runRegisterServiceAccount(deps(), caller('usr_admin'), post({ name: 'Bot', ownerId: 'usr_owner' })); + expect(r).toMatchObject({ status: 403, body: { error: { code: 'ORGANIZATION_MEMBERSHIP_LIMIT_REACHED' } } }); + expect((await rows('sys_user')).length).toBe(before); + expect(await rows('sys_user', { principal_kind: 'agent' })).toEqual([]); + }); + + it('an unreadable membership is an outage, never a verdict on the caller', async () => { + failMemberReads = true; + await expect(runRegisterServiceAccount(deps(), caller('usr_admin'), post({ name: 'Bot' }))) + .rejects.toSatisfy(isAuthzStoreUnavailableError); + }); +}); + +describe('[ADR-0151 D4] create-key: who may mint, and what the key is', () => { + it('the owner mints a key: the account\'s, in its organization, under the default life; the secret once, stored hashed', async () => { + const bot = await registered(); + const r = await runCreateServiceAccountKey(deps(), caller('usr_owner'), post({ userId: bot, name: 'prod' })); + expect(r.status, JSON.stringify(r.body)).toBe(201); + const data = r.body.data as Record; + expect(data).toMatchObject({ name: 'prod', user_id: bot, active_organization_id: ORG }); + expect(data.expires_at).toBe(new Date(NOW + 90 * DAY_MS).toISOString()); + expect(typeof data.key).toBe('string'); + + const [key] = await rows('sys_api_key', { id: data.id }); + expect(key).toMatchObject({ user_id: bot, active_organization_id: ORG, key: hashApiKey(data.key), prefix: data.prefix }); + expect(JSON.stringify(key)).not.toContain(data.key); + }); + + it('an administrator of the account\'s organization mints one, and so does a platform administrator', async () => { + const bot = await registered(); + expect((await runCreateServiceAccountKey(deps(), caller('usr_admin'), post({ userId: bot }))).status).toBe(201); + expect((await runCreateServiceAccountKey( + deps(), caller('usr_platform', { isPlatformAdmin: true, activeOrganizationId: null }), post({ userId: bot }), + )).status).toBe(201); + }); + + it('the organization is the account\'s, never the caller\'s current one', async () => { + const bot = await registered(); + const r = await runCreateServiceAccountKey( + deps(), caller('usr_admin', { activeOrganizationId: OTHER_ORG }), post({ userId: bot }), + ); + expect(r.body.data).toMatchObject({ active_organization_id: ORG }); + }); + + it('another member is refused 403, and so is an administrator of another organization; no key is written', async () => { + const bot = await registered(); + for (const who of ['usr_member', 'usr_other_admin']) { + const r = await runCreateServiceAccountKey(deps(), caller(who), post({ userId: bot })); + expect(r).toMatchObject({ status: 403, body: { error: { code: 'PERMISSION_DENIED' } } }); + } + expect(await rows('sys_api_key')).toEqual([]); + }); + + it('a person\'s id is answered as unknown: this door never mints a person\'s key', async () => { + const r = await runCreateServiceAccountKey(deps(), caller('usr_admin'), post({ userId: 'usr_member' })); + expect(r).toMatchObject({ status: 404, body: { error: { code: 'RESOURCE_NOT_FOUND' } } }); + expect(await rows('sys_api_key')).toEqual([]); + }); + + it('a retired account (no membership) gets no key', async () => { + const bot = await registered(); + await engine.delete('sys_member', { where: { user_id: bot }, multi: true, ...SYSTEM } as any); + const r = await runCreateServiceAccountKey(deps(), caller('usr_admin'), post({ userId: bot })); + expect(r).toMatchObject({ status: 409, body: { error: { code: 'RESOURCE_CONFLICT' } } }); + }); + + it('the owner who has left the organization is no longer admitted as owner', async () => { + const bot = await registered(); + await engine.delete('sys_member', { where: { user_id: 'usr_owner' }, multi: true, ...SYSTEM } as any); + const r = await runCreateServiceAccountKey(deps(), caller('usr_owner'), post({ userId: bot })); + expect(r).toMatchObject({ status: 403, body: { error: { code: 'PERMISSION_DENIED' } } }); + }); + + it('the same lifecycle policy as POST /keys: a date past the ceiling is refused, exactly the ceiling is signed', async () => { + const bot = await registered(); + const tooFar = await runCreateServiceAccountKey( + deps(), caller('usr_owner'), post({ userId: bot, expires_at: new Date(NOW + 400 * DAY_MS).toISOString() }), + ); + expect(tooFar).toMatchObject({ status: 400, body: { error: { code: 'API_KEY_EXPIRY_TOO_LONG' } } }); + const ceiling = new Date(NOW + 365 * DAY_MS).toISOString(); + const ok = await runCreateServiceAccountKey(deps(), caller('usr_owner'), post({ userId: bot, expires_at: ceiling })); + expect(ok.body.data).toMatchObject({ expires_at: ceiling }); + const past = await runCreateServiceAccountKey(deps(), caller('usr_owner'), post({ userId: bot, expires_at: '2020-01-01' })); + expect(past).toMatchObject({ status: 400, body: { error: { code: 'VALIDATION_ERROR' } } }); + }); + + it('userId is required', async () => { + const r = await runCreateServiceAccountKey(deps(), caller('usr_admin'), post({})); + expect(r).toMatchObject({ status: 400, body: { error: { code: 'INVALID_REQUEST' } } }); + }); +}); From 07646858a25ee84b0fb9d2cbf2783d557e6d1c73 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:48:31 +0000 Subject: [PATCH 4/6] test(dogfood): register an AI service account and mint its key over HTTP Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- ...rvice-account-register-key.dogfood.test.ts | 175 ++++++++++++++++++ 1 file changed, 175 insertions(+) create mode 100644 packages/qa/dogfood/test/service-account-register-key.dogfood.test.ts diff --git a/packages/qa/dogfood/test/service-account-register-key.dogfood.test.ts b/packages/qa/dogfood/test/service-account-register-key.dogfood.test.ts new file mode 100644 index 00000000000..f69ebd69e66 --- /dev/null +++ b/packages/qa/dogfood/test/service-account-register-key.dogfood.test.ts @@ -0,0 +1,175 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. +// test-budget: 20 — one showcase boot for the whole file, its auth and data doors driven in process; no timer is waited out + +/** + * [ADR-0151 D1/D4] Registering an AI service account and minting its key, + * over HTTP on the real showcase stack. + * + * POST /api/v1/auth/service-account/register + * POST /api/v1/auth/service-account/create-key + * + * Both doors read the caller from a signed-in session: anonymous is 401, and + * so is a caller carrying only an API key (a key never reaches them, so an + * account can never register another or mint its own). Registration is an + * organization or platform administrator's act; a key is minted by the + * account's accountable owner or an administrator. The key the owner receives + * is admitted at the data door as the account, and the account's ban (the + * existing platform-admin door, until the lifecycle doors land) refuses it on + * its next call exactly as an unknown key is refused, and lifting the ban + * lets it through again. The access matrix and the one-act write are pinned + * on a real engine in plugin-auth `service-account-doors.test.ts`. + */ + +import { randomBytes } from 'node:crypto'; +import { describe, it, expect, beforeAll, afterAll } from 'vitest'; +import { type VerifyStack } from '@objectstack/verify'; +import { bootShowcase } from './showcase-boot.js'; + +const SYS = { context: { isSystem: true } }; +const PASSWORD = 'Member-Pass-123'; +const OBJECT = 'showcase_private_note'; +const OWNER_EMAIL = 'service-account.owner@verify.test'; +const MEMBER_EMAIL = 'service-account.member@verify.test'; + +const rowsOf = (r: any): any[] => (Array.isArray(r) ? r : Array.isArray(r?.value) ? r.value : []); + +let stack: VerifyStack; +let ql: any; +let adminToken: string; +let ownerSession: string; +let ownerId: string; +let memberSession: string; +let organizationId: string; +let accountId: string; +let accountKey: string; +let priorScim: string | undefined; +/** A well-formed key no row holds: the answer a refused key is compared to. */ +const madeUpKey = `osk_${randomBytes(32).toString('base64url')}`; + +const userIdOf = async (session: string): Promise => { + const me = await stack.apiAs(session, 'GET', '/auth/get-session'); + return String(((await me.json()) as any)?.user?.id ?? ''); +}; + +const answerOf = async (res: Response) => { + const text = await res.text(); + let body: any; + try { body = JSON.parse(text); } catch { body = undefined; } + return { status: res.status, code: body?.error?.code ?? body?.code }; +}; + +const postWithKey = (path: string, key: string, body: unknown) => + stack.api(path, { + method: 'POST', + headers: { 'x-api-key': key, 'content-type': 'application/json' }, + body: JSON.stringify(body), + }); + +const readAs = (key: string) => stack.api(`/data/${OBJECT}`, { headers: { 'x-api-key': key } }); + +beforeAll(async () => { + // The ban routes answer 501 unless better-auth's admin plugin is on; + // `OS_SCIM_ENABLED` forces it on and is read when the auth manager is + // constructed, so it must precede the boot (as in the banned-owner pin). + priorScim = process.env.OS_SCIM_ENABLED; + process.env.OS_SCIM_ENABLED = 'true'; + stack = await bootShowcase(); + ql = await stack.kernel.getServiceAsync('objectql'); + adminToken = await stack.signIn(); + ownerSession = await stack.signUp(OWNER_EMAIL, PASSWORD); + ownerId = await userIdOf(ownerSession); + memberSession = await stack.signUp(MEMBER_EMAIL, PASSWORD); + const adminSession: any = await (await stack.apiAs(adminToken, 'GET', '/auth/get-session')).json(); + organizationId = String(adminSession?.session?.activeOrganizationId ?? ''); + expect(organizationId).not.toBe(''); + expect(ownerId).not.toBe(''); +}, 300_000); + +afterAll(async () => { + await stack?.stop?.(); + if (priorScim === undefined) delete process.env.OS_SCIM_ENABLED; + else process.env.OS_SCIM_ENABLED = priorScim; +}); + +describe('[ADR-0151 D1] registering an AI service account', () => { + it('anonymous is 401, a plain member is 403, and neither writes a row', async () => { + const before = rowsOf(await ql.find('sys_user', { where: { principal_kind: 'agent' }, ...SYS })).length; + const anonymous = await stack.api('/auth/service-account/register', { + method: 'POST', + headers: { 'content-type': 'application/json' }, + body: JSON.stringify({ name: 'Anonymous bot' }), + }); + expect(await answerOf(anonymous)).toEqual({ status: 401, code: 'UNAUTHENTICATED' }); + const member = await stack.apiAs(memberSession, 'POST', '/auth/service-account/register', { name: 'Member bot' }); + expect(await answerOf(member)).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + expect(rowsOf(await ql.find('sys_user', { where: { principal_kind: 'agent' }, ...SYS })).length).toBe(before); + }); + + it('an administrator registers one: an agent row owned by the named person, and one plain membership of the organization', async () => { + const res = await stack.apiAs(adminToken, 'POST', '/auth/service-account/register', { name: 'Invoice bot', ownerId }); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(201); + accountId = String(body.data.userId); + expect(body.data).toMatchObject({ principalKind: 'agent', organizationId, ownerId }); + + const [row] = rowsOf(await ql.find('sys_user', { where: { id: accountId }, ...SYS })); + expect(row).toMatchObject({ name: 'Invoice bot', principal_kind: 'agent', accountable_user_id: ownerId, source: 'env_native' }); + expect(String(row.email)).toMatch(/@placeholder\.invalid$/); + const members = rowsOf(await ql.find('sys_member', { where: { user_id: accountId }, ...SYS })); + expect(members.map((m) => [m.organization_id, m.role])).toEqual([[organizationId, 'member']]); + }); + + it('a caller carrying only an API key never reaches the door', async () => { + const minted: any = await (await stack.apiAs(adminToken, 'POST', '/keys', { name: 'admin script' })).json(); + const res = await postWithKey('/auth/service-account/register', String(minted.data.key), { name: 'Key bot' }); + expect(await answerOf(res)).toEqual({ status: 401, code: 'UNAUTHENTICATED' }); + }); +}); + +describe('[ADR-0151 D4] minting the account\'s key', () => { + it('another member is refused 403; the owner mints the key, the account\'s, in its organization', async () => { + expect(accountId).toBeTruthy(); + const other = await stack.apiAs(memberSession, 'POST', '/auth/service-account/create-key', { userId: accountId, name: 'x' }); + expect(await answerOf(other)).toEqual({ status: 403, code: 'PERMISSION_DENIED' }); + + const res = await stack.apiAs(ownerSession, 'POST', '/auth/service-account/create-key', { userId: accountId, name: 'prod' }); + const body: any = await res.json(); + expect(res.status, JSON.stringify(body)).toBe(201); + expect(body.data).toMatchObject({ user_id: accountId, active_organization_id: organizationId }); + expect(body.data.expires_at).toBeTruthy(); + accountKey = String(body.data.key); + + const [key] = rowsOf(await ql.find('sys_api_key', { where: { id: body.data.id }, ...SYS })); + expect(key).toMatchObject({ user_id: accountId, active_organization_id: organizationId }); + }); + + it('the key is admitted at the data door as the account, where a made-up key is not', async () => { + const made = await answerOf(await readAs(madeUpKey)); + expect(made.status).toBe(401); + const read = await answerOf(await readAs(accountKey)); + expect(read.status, JSON.stringify(read)).not.toBe(401); + }); + + it('the account\'s own key mints nothing: not here, and not at POST /keys', async () => { + const here = await postWithKey('/auth/service-account/create-key', accountKey, { userId: accountId }); + expect(await answerOf(here)).toEqual({ status: 401, code: 'UNAUTHENTICATED' }); + const keys = await postWithKey('/keys', accountKey, { name: 'self' }); + expect(keys.status).toBe(403); + expect(rowsOf(await ql.find('sys_api_key', { where: { user_id: accountId }, ...SYS })).length).toBe(1); + }); + + it('a person\'s id is answered as unknown: the door never mints a person\'s key', async () => { + const res = await stack.apiAs(adminToken, 'POST', '/auth/service-account/create-key', { userId: ownerId }); + expect(await answerOf(res)).toEqual({ status: 404, code: 'RESOURCE_NOT_FOUND' }); + }); + + it('banning the account refuses its key on the next call as a made-up key is refused; lifting the ban lets it through', async () => { + const ban = await stack.apiAs(adminToken, 'POST', '/auth/admin/ban-user', { userId: accountId }); + expect(ban.status, await ban.clone().text()).toBe(200); + expect(await answerOf(await readAs(accountKey))).toEqual(await answerOf(await readAs(madeUpKey))); + + const unban = await stack.apiAs(adminToken, 'POST', '/auth/admin/unban-user', { userId: accountId }); + expect(unban.status, await unban.clone().text()).toBe(200); + expect((await answerOf(await readAs(accountKey))).status).not.toBe(401); + }); +}); From 52082037f3ef6ff77fd269658255f982efc49412 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 12:49:41 +0000 Subject: [PATCH 5/6] docs(ai, permissions): the AI service account, its registration and its key; changeset Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- .../31739-ai-service-account-register.md | 20 +++++++++++++++++++ content/docs/ai/agents.mdx | 20 +++++++++++++++++++ content/docs/permissions/index.mdx | 13 ++++++++++++ 3 files changed, 53 insertions(+) create mode 100644 .changeset/31739-ai-service-account-register.md diff --git a/.changeset/31739-ai-service-account-register.md b/.changeset/31739-ai-service-account-register.md new file mode 100644 index 00000000000..d4d33ae8473 --- /dev/null +++ b/.changeset/31739-ai-service-account-register.md @@ -0,0 +1,20 @@ +--- +'@objectstack/core': patch +'@objectstack/runtime': patch +'@objectstack/plugin-auth': patch +'@objectstack/plugin-security': patch +'@objectstack/platform-objects': patch +--- + +feat(plugin-auth): register an AI service account and mint its API key (ADR-0151 D1, D4) + +Clause-②: yes (widening) — two new auth doors (`POST /api/v1/auth/service-account/register`, `POST /api/v1/auth/service-account/create-key`), two new `sys_user` actions, and `readRequestedApiKeyExpiry`, `signApiKeyExpiry`, `API_KEY_EXPIRY_TOO_LONG_CODE` and `ApiKeyExpiryRefusal` newly exported by `@objectstack/core`. Nothing existing is removed, retyped or refused: the break-glass guard and the upgrade-report audience now leave AI service accounts out, and an account row is only written by the new door (or by a seed). +Metadata-protocol: none + +An organization administrator, or a platform administrator, can now register an **AI service account**: Setup → Users → *Register AI Service Account*, or `POST /api/v1/auth/service-account/register` with a `name` and an optional `ownerId`. One act writes a `sys_user` of kind `agent`, accountable to the named owner (the caller by default; the owner must be an active member of the organization), with a placeholder email that is never delivered and never collides with a real address, and a plain `member` membership of the caller's active organization. If either write is refused, neither stays. + +The account's owner, an administrator of its organization, or a platform administrator mints its API key: *Create API Key* on the account, or `POST /api/v1/auth/service-account/create-key` with `userId`. The key is shown once, bound to the account's organization, and signed under the same expiry policy and ceiling as `POST /api/v1/keys` (the two now share one rule in `@objectstack/core`). The key acts as the account, under the agent ceiling. + +Both doors read the caller from a signed-in session only: anonymous is `401`, and a caller carrying only an API key (the account's own included) is `401` too, so an account can neither register another nor mint its own key. Refusals reuse the existing codes: `403 PERMISSION_DENIED`, `400 VALIDATION_FAILED`, `404 RESOURCE_NOT_FOUND` for an id that is not an account, `409 RESOURCE_CONFLICT` for an account with no active membership, `503` when the authority read is unavailable. + +An AI service account is never counted as one of the administrators the break-glass guard keeps (whatever grant or membership grade it holds), and never receives the upgrade report or counts as an organization's administrator there. diff --git a/content/docs/ai/agents.mdx b/content/docs/ai/agents.mdx index df65b89a4a7..4dedf1f981d 100644 --- a/content/docs/ai/agents.mdx +++ b/content/docs/ai/agents.mdx @@ -91,6 +91,26 @@ SKILL.md download (`GET /api/v1/mcp/skill`), and API-key minting. layer, is the boundary for what actions can do. - **API key (headless).** Mint a key (`POST /api/v1/keys`, shown once) and send it as `x-api-key` — for CI, scripts, and agents without a browser. +- **AI service account (unattended).** When an agent runs on its own, not + on your behalf, give it its own identity instead of your key. An + organization administrator (or a platform administrator) registers one + (Setup → Users → *Register AI Service Account*, or + `POST /api/v1/auth/service-account/register` with `name` and an optional + `ownerId`): a user of kind `agent`, a plain member of the active + organization, accountable to a named person who is a member there (the + caller by default). Its name carries its purpose. It never signs in: it has + no password and no session, and its email is a placeholder that is never + delivered. Its owner, or an administrator of its organization, mints its + key (*Create API Key* on the account, or + `POST /api/v1/auth/service-account/create-key` with `userId`), shown once, + bound to the account's organization and under the same expiry ceiling as + any key. The key acts as the account: only the grants given to the account + count, an account never holds administrator standing, and the agent + ceiling clears View All, Modify All and the other elevated permissions from + whatever sets it is given. Both doors take a signed-in session only, so a + key — the account's own included — can neither register an account nor mint + one's key. An account is never counted as one of the administrators that + keep an organization manageable, and never receives administrator mail. Per client: diff --git a/content/docs/permissions/index.mdx b/content/docs/permissions/index.mdx index b7dbdc56538..926dc24e8c0 100644 --- a/content/docs/permissions/index.mdx +++ b/content/docs/permissions/index.mdx @@ -117,6 +117,19 @@ ObjectStack implements a multi-layered security model: └─────────────────────────────────────┘ ``` +### AI service accounts + +An unattended agent gets its own identity, an **AI service account**: a user +of kind `agent`, accountable to a named person, holding a plain membership of +one organization. Its permissions are exactly the grants given to it; it never +holds administrator standing, and the agent ceiling clears View All, Modify +All, transfer, restore, purge, system permissions and admin scopes from any +set it is given (giving it such a set is refused). Registration is an +organization or platform administrator's act; its owner or an administrator +mints its API key. It never signs in, and it is never counted among the +administrators that keep an organization manageable. See +[AI service account](/docs/ai/agents#connect-your-ai-byo-ai-over-mcp). + ### Security Layers 1. **Object Permissions**: Control create, read, update, delete on entire objects From 3c52359aad959967e72e2dd5d9ef0cb08f556c69 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 13:31:53 +0000 Subject: [PATCH 6/6] fix(plugin-auth, core): the ceiling code stays the runtime's; census figures; typed test options The create-key door answers a too-distant expiry as a refusal of the field; POST /keys keeps its ledgered code in runtime, and core's shared rule carries no wire code. Claude-Session: https://claude.ai/code/session_01ADHkmPK8RUPmLyYjQGCe58 Co-authored-by: Claude --- .../31739-ai-service-account-register.md | 4 +- .../docs/permissions/tenant-audit-census.mdx | 40 +++++++++---------- ...08-tenant-audit-write-call-sites.counts.md | 22 +++++----- packages/core/src/security/api-key.ts | 30 +++++++++----- packages/core/src/security/index.ts | 2 +- .../last-admin-guard.agent-account.test.ts | 2 +- .../src/service-account-doors.test.ts | 18 ++++++--- .../plugin-auth/src/service-account-doors.ts | 16 +++++++- packages/runtime/src/domains/keys.ts | 9 ++++- 9 files changed, 92 insertions(+), 51 deletions(-) diff --git a/.changeset/31739-ai-service-account-register.md b/.changeset/31739-ai-service-account-register.md index d4d33ae8473..33ba59a85b8 100644 --- a/.changeset/31739-ai-service-account-register.md +++ b/.changeset/31739-ai-service-account-register.md @@ -8,12 +8,12 @@ feat(plugin-auth): register an AI service account and mint its API key (ADR-0151 D1, D4) -Clause-②: yes (widening) — two new auth doors (`POST /api/v1/auth/service-account/register`, `POST /api/v1/auth/service-account/create-key`), two new `sys_user` actions, and `readRequestedApiKeyExpiry`, `signApiKeyExpiry`, `API_KEY_EXPIRY_TOO_LONG_CODE` and `ApiKeyExpiryRefusal` newly exported by `@objectstack/core`. Nothing existing is removed, retyped or refused: the break-glass guard and the upgrade-report audience now leave AI service accounts out, and an account row is only written by the new door (or by a seed). +Clause-②: yes (widening) — two new auth doors (`POST /api/v1/auth/service-account/register`, `POST /api/v1/auth/service-account/create-key`), two new `sys_user` actions, and `readRequestedApiKeyExpiry`, `signApiKeyExpiry`, `ApiKeyExpiryRefusal` and `ApiKeyExpiryCeilingRefusal` newly exported by `@objectstack/core`. Nothing existing is removed, retyped or refused: the break-glass guard and the upgrade-report audience now leave AI service accounts out, and an account row is only written by the new door (or by a seed). Metadata-protocol: none An organization administrator, or a platform administrator, can now register an **AI service account**: Setup → Users → *Register AI Service Account*, or `POST /api/v1/auth/service-account/register` with a `name` and an optional `ownerId`. One act writes a `sys_user` of kind `agent`, accountable to the named owner (the caller by default; the owner must be an active member of the organization), with a placeholder email that is never delivered and never collides with a real address, and a plain `member` membership of the caller's active organization. If either write is refused, neither stays. -The account's owner, an administrator of its organization, or a platform administrator mints its API key: *Create API Key* on the account, or `POST /api/v1/auth/service-account/create-key` with `userId`. The key is shown once, bound to the account's organization, and signed under the same expiry policy and ceiling as `POST /api/v1/keys` (the two now share one rule in `@objectstack/core`). The key acts as the account, under the agent ceiling. +The account's owner, an administrator of its organization, or a platform administrator mints its API key: *Create API Key* on the account, or `POST /api/v1/auth/service-account/create-key` with `userId`. The key is shown once, bound to the account's organization, and signed under the same expiry policy and ceiling as `POST /api/v1/keys` (the two now share one rule in `@objectstack/core`); a date past the ceiling is refused `400 VALIDATION_FAILED` at `expires_at`, with the message `POST /api/v1/keys` gives, which names the latest date allowed. `POST /api/v1/keys` answers exactly as before. The key acts as the account, under the agent ceiling. Both doors read the caller from a signed-in session only: anonymous is `401`, and a caller carrying only an API key (the account's own included) is `401` too, so an account can neither register another nor mint its own key. Refusals reuse the existing codes: `403 PERMISSION_DENIED`, `400 VALIDATION_FAILED`, `404 RESOURCE_NOT_FOUND` for an id that is not an account, `409 RESOURCE_CONFLICT` for an account with no active membership, `503` when the authority read is unavailable. diff --git a/content/docs/permissions/tenant-audit-census.mdx b/content/docs/permissions/tenant-audit-census.mdx index eab8333ea71..1841c2dd058 100644 --- a/content/docs/permissions/tenant-audit-census.mdx +++ b/content/docs/permissions/tenant-audit-census.mdx @@ -132,7 +132,7 @@ are reported as `undecidable` rather than assumed either way. The same holds twice over for the context. An options argument spelled as a literal can be read; one spelled `options`, `{ ...opts }`, or handed through a -forwarding shim cannot, and **57 of the 280 sites are spelled that way**. A +forwarding shim cannot, and **57 of the 282 sites are spelled that way**. A context resolved from an inline literal or a local `const` can be tested for `isSystem`; one arriving from a helper call cannot. @@ -197,10 +197,10 @@ reproduce them. Where it disagrees, it disagrees on the page: | carried figure | where it survives | this census | | :--- | :--- | ---: | -| 175 write call sites | quoted in the merged changeset | **280** | +| 175 write call sites | quoted in the merged changeset | **282** | | 24 carrying no tenant context | quoted in the merged changeset | **3** provable and tenancy-enabled; **30** more whose options argument is unreadable | -| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **198 of 280** decidable, **82** undecidable | -| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 157 decidably elevated, 0 decidably not, 113 undecidable | +| 127 of 175 statically decidable, 48 runtime-parameter-name sites | restated on the `isSystem`-scoping card | **199 of 282** decidable, **83** undecidable | +| 135 (77%) silenced by the `isSystem` guard before the posture gate | the lost issue body — **no surviving corroboration** | **not reproduced**: 157 decidably elevated, 0 decidably not, 115 undecidable | | 141 and 132, two independent re-derivations | the card that filed this work | — | **The differences are not reconciled, and deliberately so.** The old census's @@ -211,17 +211,17 @@ at any commit. Two structural facts do plausibly widen this reading against any hand or regex one, and both are counted in the generated tables below: the 62 sites reached -through an erased (`any`) receiver, and the 72 that name their object through a +through an erased (`any`) receiver, and the 73 that name their object through a `const` rather than inline. An instrument that read either the way a person does would report a smaller number and would not say so. The fourth row is the one worth flagging to anyone citing it. **The 135 / 77% figure has no surviving corroboration anywhere in the tree.** This census reads -157 of 280 (56%) as decidably elevated, with 113 more whose elevation is a +157 of 282 (56%) as decidably elevated, with 115 more whose elevation is a run-time fact — so the claim is neither confirmed nor refuted, and the honest answer is that a static reading cannot settle it. -⇒ **Cite `3 / 280`, and say what it is**: the sites whose options argument was +⇒ **Cite `3 / 282`, and say what it is**: the sites whose options argument was READ and holds no tenant context, against a decidably tenancy-enabled object. That is the control's provable yield surface. ⛔ Do not cite it as "the sites without tenant context" — **30 further sites** have an options argument this @@ -233,31 +233,31 @@ cannot read, and they are neither in nor out. | what | count | | :--- | ---: | -| write call sites on the application surface | **280** | -| …whose object name is statically decidable | 198 | -| …whose object name is chosen at run time | 82 | +| write call sites on the application surface | **282** | +| …whose object name is statically decidable | 199 | +| …whose object name is chosen at run time | 83 | | …against an object with tenancy ENABLED | 192 | -| …against an object that declares tenancy off | 6 | -| threading a tenant context | 213 | +| …against an object that declares tenancy off | 7 | +| threading a tenant context | 215 | | PROVABLY carrying none (options read, no context key) | **10** | | …of those, against a decidably tenancy-enabled object | **3** | | options argument UNREADABLE — may or may not carry one | 57 | | …of those, against a decidably tenancy-enabled object | 30 | | threading a decidably ELEVATED (`isSystem`) context | 157 | | threading a context that is decidably NOT elevated | 0 | -| threading a context whose elevation is a run-time fact | 113 | +| threading a context whose elevation is a run-time fact | 115 | | how the instrument reached the site | count | | :--- | ---: | -| receiver carried a readable engine type | 218 | +| receiver carried a readable engine type | 220 | | receiver erased, placed by the object NAME | 52 | | receiver erased, placed by an `object: string` PARAMETER | 5 | | receiver erased, placed by an `UNTYPED_RECEIVERS` row | 5 | | object name spelled inline | 126 | -| object name spelled through a `const` | 72 | +| object name spelled through a `const` | 73 | | object name is an `object: string` parameter | 9 | -| object name is some other run-time expression | 73 | +| object name is some other run-time expression | 74 | ### Subtractions the census could NOT defend — enforced @@ -307,13 +307,13 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-09 at `4e6c24cf7`. +Measured on 2026-11-09 at `9a53066ce`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1088 | -| engine-shaped types recognised | 120 | +| tracked non-test sources scanned | 1091 | +| engine-shaped types recognised | 121 | | declared objects in the registry | 133 | -| same-named calls subtracted as non-engine | 253 | +| same-named calls subtracted as non-engine | 254 | {/* END GENERATED: tenant-audit-census */} diff --git a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md index 5007c8f13de..e9ab2a612a2 100644 --- a/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md +++ b/docs/audits/2026-08-tenant-audit-write-call-sites.counts.md @@ -33,19 +33,19 @@ silent, and `node scripts/tenant-audit-census.mjs --write` is the resolution. | Measure | Value | |---|---:| -| Write call sites | 280 | -| Object name statically decidable | 198 | -| Object name chosen at run time | 82 | +| Write call sites | 282 | +| Object name statically decidable | 199 | +| Object name chosen at run time | 83 | | Against a tenancy-enabled object | 192 | -| Against an object declaring tenancy off | 6 | -| Threading a tenant context | 213 | +| Against an object declaring tenancy off | 7 | +| Threading a tenant context | 215 | | Provably carrying none | 10 | | …and decidably tenancy-enabled | 3 | | Options argument unreadable | 57 | | …and decidably tenancy-enabled | 30 | | Threading a decidably elevated context | 157 | | Threading a decidably non-elevated context | 0 | -| Threading a context of undecidable elevation | 113 | +| Threading a context of undecidable elevation | 115 | ## Subtractions the census could NOT defend — enforced @@ -90,14 +90,14 @@ holds still. They are required to be HERE and to say WHEN they were true; their values are not compared. The reasoning, and the measurement behind it, are in `scripts/check-tenant-audit-census.mjs`. -Measured on 2026-11-09 at `4e6c24cf7`. +Measured on 2026-11-09 at `9a53066ce`. | corpus scale (not enforced) | count | | :--- | ---: | -| tracked non-test sources scanned | 1088 | -| engine-shaped types recognised | 120 | +| tracked non-test sources scanned | 1091 | +| engine-shaped types recognised | 121 | | declared objects in the registry | 133 | -| same-named calls subtracted as non-engine | 253 | +| same-named calls subtracted as non-engine | 254 | ## Every site @@ -181,6 +181,8 @@ Measured on 2026-11-09 at `4e6c24cf7`. | `packages/plugins/plugin-auth/src/scim-connection-service.ts` | `update` | `sys_scim_connection_credential` | enabled | elevated | 1 | | `packages/plugins/plugin-auth/src/scim-group-projection.ts` | `delete` | `sys_user_permission_set` | enabled | PROVABLY NONE | 1 | | `packages/plugins/plugin-auth/src/scim-group-projection.ts` | `insert` | `sys_user_permission_set` | enabled | elevated | 1 | +| `packages/plugins/plugin-auth/src/service-account-doors.ts` | `insert` | `sys_api_key` | disabled | context, elevation undecidable | 1 | +| `packages/plugins/plugin-auth/src/service-account-doors.ts` | `insert` | `USER_OBJECT` | undecidable | context, elevation undecidable | 1 | | `packages/plugins/plugin-auth/src/session-tombstone.ts` | `update` | `objectName` | undecidable | options unreadable | 1 | | `packages/plugins/plugin-auth/src/sso-client-secret.ts` | `update` | `sys_sso_provider` | disabled | elevated | 1 | | `packages/plugins/plugin-auth/src/sys-session-revoke.ts` | `update` | `SystemObjectName.SESSION` | undecidable | elevated | 1 | diff --git a/packages/core/src/security/api-key.ts b/packages/core/src/security/api-key.ts index 73672c10231..ee0b827e304 100644 --- a/packages/core/src/security/api-key.ts +++ b/packages/core/src/security/api-key.ts @@ -230,14 +230,25 @@ export function apiKeyLifecyclePolicySourceOf( */ const API_KEY_EXPIRY_CEILING_SKEW_MS = 60_000; -/** [#23367] The ceiling refusal's code (ADR-0112 ledger). */ -export const API_KEY_EXPIRY_TOO_LONG_CODE = 'API_KEY_EXPIRY_TOO_LONG'; - -/** A refused signing: always `400`, with the code and the located message. */ +/** A request `expires_at` that is no date, or not in the future: always `400 VALIDATION_ERROR`. */ export interface ApiKeyExpiryRefusal { ok: false; status: 400; - code: 'VALIDATION_ERROR' | typeof API_KEY_EXPIRY_TOO_LONG_CODE; + code: 'VALIDATION_ERROR'; + message: string; +} + +/** + * A date further away than the policy's ceiling. It carries no wire code: each + * door answers it with its own ledgered code (`POST /keys` with + * `API_KEY_EXPIRY_TOO_LONG`, under `@objectstack/runtime`), and `latest` is the + * latest expiry a key signed now may have. + */ +export interface ApiKeyExpiryCeilingRefusal { + ok: false; + status: 400; + ceiling: true; + latest: string; message: string; } @@ -270,14 +281,14 @@ export function readRequestedApiKeyExpiry( * for gets the policy's default life (never a permanent key), or no expiry * when no policy is configured (a kernel with no `auth` service has no auth * configuration). A date further away than the policy's ceiling is refused - * `400 API_KEY_EXPIRY_TOO_LONG`, naming the latest date that would be - * accepted; exactly the ceiling is accepted. + * with a message naming the latest date that would be accepted (each door + * picks the wire code); exactly the ceiling is accepted. */ export function signApiKeyExpiry( policy: ApiKeyLifecyclePolicy | undefined, requestedMs: number | undefined, nowMs: number, -): { ok: true; expiresAt?: string } | ApiKeyExpiryRefusal { +): { ok: true; expiresAt?: string } | ApiKeyExpiryCeilingRefusal { if (requestedMs === undefined) { return policy ? { ok: true, expiresAt: new Date(nowMs + policy.defaultExpiryDays * DAY_MS).toISOString() } @@ -288,7 +299,8 @@ export function signApiKeyExpiry( return { ok: false, status: 400, - code: API_KEY_EXPIRY_TOO_LONG_CODE, + ceiling: true, + latest, message: `expires_at ${new Date(requestedMs).toISOString()} is further away than this deployment allows: the ` + `Authentication API key policy's Maximum key lifetime is ${policy.maxExpiryDays} days, so the ` diff --git a/packages/core/src/security/index.ts b/packages/core/src/security/index.ts index c0e23e3cc9f..7402cfde169 100644 --- a/packages/core/src/security/index.ts +++ b/packages/core/src/security/index.ts @@ -168,8 +168,8 @@ export { // [ADR-0151 D4] The one signing-expiry rule both mint doors apply. readRequestedApiKeyExpiry, signApiKeyExpiry, - API_KEY_EXPIRY_TOO_LONG_CODE, type ApiKeyExpiryRefusal, + type ApiKeyExpiryCeilingRefusal, ApiKeyLifecycleRefusalError, isApiKeyLifecycleRefusalError, type ApiKeyLifecyclePolicySource, diff --git a/packages/plugins/plugin-auth/src/last-admin-guard.agent-account.test.ts b/packages/plugins/plugin-auth/src/last-admin-guard.agent-account.test.ts index 2e57296e942..b454d70254c 100644 --- a/packages/plugins/plugin-auth/src/last-admin-guard.agent-account.test.ts +++ b/packages/plugins/plugin-auth/src/last-admin-guard.agent-account.test.ts @@ -167,7 +167,7 @@ describe('[ADR-0151 D2/D3] the break-glass guard never counts an AI service acco it('revoking the last person administrator\'s grant is refused, although an account holds the same grant', async () => { const engine = await environment(); - await expect(engine.delete('sys_user_permission_set', { where: { id: 'ups_admin' }, ...SYSTEM } as any)) + await expect(engine.delete('sys_user_permission_set', { where: { id: 'ups_admin' }, ...SYSTEM })) .rejects.toMatchObject(refusal); }); diff --git a/packages/plugins/plugin-auth/src/service-account-doors.test.ts b/packages/plugins/plugin-auth/src/service-account-doors.test.ts index d3943cb8b16..c991932609e 100644 --- a/packages/plugins/plugin-auth/src/service-account-doors.test.ts +++ b/packages/plugins/plugin-auth/src/service-account-doors.test.ts @@ -86,13 +86,16 @@ let failMemberReads = false; const POLICY = { defaultExpiryDays: 90, maxExpiryDays: 365, inactivityDays: 90 } as any; +type FindArgs = Parameters; +type InsertArgs = Parameters; + const deps = (): ServiceAccountDoorDeps => ({ getDataEngine: () => ({ find: (object, query, options) => { if (failMemberReads && object === 'sys_member') return Promise.reject(new Error('sys_member is unreachable')); - return engine.find(object, query as any, options as any); + return engine.find(object, query as FindArgs[1], options as FindArgs[2]); }, - insert: (object, data, options) => engine.insert(object, data, options as any), + insert: (object, data, options) => engine.insert(object, data, options as InsertArgs[2]), }), addMember: async ({ userId, organizationId }) => { if (refuseMembership) throw refuseMembership; @@ -115,7 +118,7 @@ const post = (body: unknown) => }); const rows = async (object: string, where: Record = {}) => - (await engine.find(object, { where, ...SYSTEM } as any)) as Array>; + (await engine.find(object, { where, ...SYSTEM })) as Array>; beforeEach(async () => { refuseMembership = undefined; @@ -298,14 +301,14 @@ describe('[ADR-0151 D4] create-key: who may mint, and what the key is', () => { it('a retired account (no membership) gets no key', async () => { const bot = await registered(); - await engine.delete('sys_member', { where: { user_id: bot }, multi: true, ...SYSTEM } as any); + await engine.delete('sys_member', { where: { user_id: bot }, multi: true, ...SYSTEM }); const r = await runCreateServiceAccountKey(deps(), caller('usr_admin'), post({ userId: bot })); expect(r).toMatchObject({ status: 409, body: { error: { code: 'RESOURCE_CONFLICT' } } }); }); it('the owner who has left the organization is no longer admitted as owner', async () => { const bot = await registered(); - await engine.delete('sys_member', { where: { user_id: 'usr_owner' }, multi: true, ...SYSTEM } as any); + await engine.delete('sys_member', { where: { user_id: 'usr_owner' }, multi: true, ...SYSTEM }); const r = await runCreateServiceAccountKey(deps(), caller('usr_owner'), post({ userId: bot })); expect(r).toMatchObject({ status: 403, body: { error: { code: 'PERMISSION_DENIED' } } }); }); @@ -315,7 +318,10 @@ describe('[ADR-0151 D4] create-key: who may mint, and what the key is', () => { const tooFar = await runCreateServiceAccountKey( deps(), caller('usr_owner'), post({ userId: bot, expires_at: new Date(NOW + 400 * DAY_MS).toISOString() }), ); - expect(tooFar).toMatchObject({ status: 400, body: { error: { code: 'API_KEY_EXPIRY_TOO_LONG' } } }); + expect(tooFar).toMatchObject({ + status: 400, + body: { error: { code: 'VALIDATION_FAILED', fields: [{ field: 'expires_at', code: 'invalid_value' }] } }, + }); const ceiling = new Date(NOW + 365 * DAY_MS).toISOString(); const ok = await runCreateServiceAccountKey(deps(), caller('usr_owner'), post({ userId: bot, expires_at: ceiling })); expect(ok.body.data).toMatchObject({ expires_at: ceiling }); diff --git a/packages/plugins/plugin-auth/src/service-account-doors.ts b/packages/plugins/plugin-auth/src/service-account-doors.ts index fd34acd3ba3..034bb4e60d9 100644 --- a/packages/plugins/plugin-auth/src/service-account-doors.ts +++ b/packages/plugins/plugin-auth/src/service-account-doors.ts @@ -382,7 +382,21 @@ export async function runCreateServiceAccountKey( throw new AuthzStoreUnavailableError('api_key_policy', cause); } const signed = signApiKeyExpiry(policy, requested.requestedMs, nowMs); - if (!signed.ok) return fail(signed.status, signed.code, signed.message); + if (!signed.ok) { + // The ceiling, answered as a refusal of the field (`POST /keys` answers it + // with its own ledgered `API_KEY_EXPIRY_TOO_LONG`, which is the runtime's). + return { + status: 400, + body: { + success: false, + error: { + code: 'VALIDATION_FAILED', + message: signed.message, + fields: [{ field: 'expires_at', code: 'invalid_value', message: signed.message }], + }, + }, + }; + } // Generated after every check, so a refused request never mints. const generated = generateApiKey(); diff --git a/packages/runtime/src/domains/keys.ts b/packages/runtime/src/domains/keys.ts index 916cdd61d1e..5c1777a28a9 100644 --- a/packages/runtime/src/domains/keys.ts +++ b/packages/runtime/src/domains/keys.ts @@ -61,6 +61,9 @@ import type { HttpProtocolContext, HttpDispatcherResult } from '../http-dispatch import type { DomainHandlerDeps, DomainRoute } from '../domain-handler-registry.js'; import { readDispatchedBody } from '../deferred-request-body.js'; +/** [#23367] The ceiling refusal, as its wire pair (ADR-0112 ledger, `@objectstack/runtime`). */ +const API_KEY_EXPIRY_TOO_LONG = { code: 'API_KEY_EXPIRY_TOO_LONG', status: 400 } as const; + /** * The one method this domain serves, on every path it claims (the handler * never reads the path): the `Allow` value of its 405. @@ -254,7 +257,11 @@ export async function handleKeysRequest( if (!signed.ok) { return { handled: true, - response: deps.error(signed.message, signed.status, { code: signed.code }), + response: deps.error( + signed.message, + API_KEY_EXPIRY_TOO_LONG.status, + { code: API_KEY_EXPIRY_TOO_LONG.code }, + ), }; } const expiresAt = signed.expiresAt;