From 8283641f1e8bae8f502b5a871557a880e7d9352d Mon Sep 17 00:00:00 2001 From: "Maksym Hryzodub [DREAM]" Date: Tue, 1 Dec 2026 14:46:31 +0200 Subject: [PATCH 01/13] fix(api): record who granted an ability and who started a sign-in (RANCH-8) One migration: AssistantAccountAccess.grantedById (backfilled from the last writer of each custom pick), McpOauthState.startedById and startedVia, and every pending sign-in state dropped: none could be re-checked at its callback. Co-Authored-By: Claude --- .../migration.sql | 24 +++++++++++++++++++ api/src/slices/mcpServer/mcpServer.prisma | 7 ++++++ .../assistantAccess/assistantAccess.prisma | 6 +++++ 3 files changed, 37 insertions(+) create mode 100644 api/prisma/migrations/20261201120000_audit_access_holes/migration.sql diff --git a/api/prisma/migrations/20261201120000_audit_access_holes/migration.sql b/api/prisma/migrations/20261201120000_audit_access_holes/migration.sql new file mode 100644 index 000000000..cdb10bd78 --- /dev/null +++ b/api/prisma/migrations/20261201120000_audit_access_holes/migration.sql @@ -0,0 +1,24 @@ +-- RANCH-8: close the access-control holes found by the security audit. +-- +-- 1. Who ticked the custom assistant pick in force (FR-014). The best record +-- of who made each existing pick is its last writer, so grants made by +-- limited Admins before this release follow the Admin's ceiling at once +-- (spec Assumptions; the release note says so). +-- 2. Who started a tool-server sign-in, and through which door (FR-021): the +-- callback re-checks it with today's role and reach. +-- 3. Every pending sign-in state is dropped. Each lives ten minutes +-- (STATE_TTL_MS) and those started before this release name no starter, +-- so none could be re-checked; a person mid-sign-in starts again. + +-- AlterTable +ALTER TABLE "AssistantAccountAccess" ADD COLUMN "grantedById" TEXT; + +-- Backfill +UPDATE "AssistantAccountAccess" SET "grantedById" = "updatedById" WHERE "level" = 'custom'; + +-- AlterTable +ALTER TABLE "McpOauthState" ADD COLUMN "startedById" TEXT, +ADD COLUMN "startedVia" TEXT NOT NULL DEFAULT 'runtime'; + +-- Pending states cannot be re-checked +DELETE FROM "McpOauthState"; diff --git a/api/src/slices/mcpServer/mcpServer.prisma b/api/src/slices/mcpServer/mcpServer.prisma index b9aad07e0..b4001082a 100644 --- a/api/src/slices/mcpServer/mcpServer.prisma +++ b/api/src/slices/mcpServer/mcpServer.prisma @@ -55,6 +55,13 @@ model McpOauthState { // Where to bounce the user's browser after a successful/failed exchange // (the agent chat, or a small "you can return to the chat" page). redirectBack String? + // Who started this sign-in (RANCH-8, FR-021): the person behind + // start_mcp_oauth, null when a trusted party or the runtime started it. + // Re-read at the callback, with today's role and reach. + startedById String? + // 'tool' (start_mcp_oauth) or 'runtime' (POST …/oauth/start with the + // bridle key: the agent's own «server»__connect). + startedVia String @default("runtime") createdAt DateTime @default(now()) @@index([mcpServerId, agentId]) diff --git a/api/src/slices/user/assistantAccess/assistantAccess.prisma b/api/src/slices/user/assistantAccess/assistantAccess.prisma index e75334ce1..931c91afb 100644 --- a/api/src/slices/user/assistantAccess/assistantAccess.prisma +++ b/api/src/slices/user/assistantAccess/assistantAccess.prisma @@ -30,6 +30,12 @@ model AssistantAccountAccess { level String custom Json? updatedById String? + // Who ticked the custom pick in force (RANCH-8, FR-014). Set when `level` + // becomes 'custom' or `custom.on` changes; carried over by every other + // write (a switch toggle, the same pick saved again). Null for a pick made + // by a trusted party and on rows that hold no custom pick. A bare user id, + // as `updatedById`: the account may be gone, which then opens no agent. + grantedById String? createdAt DateTime @default(now()) updatedAt DateTime @updatedAt } From 73db458622ed22980942566dc9c2b9374479cfbb Mon Sep 17 00:00:00 2001 From: "Maksym Hryzodub [DREAM]" Date: Tue, 1 Dec 2026 14:46:32 +0200 Subject: [PATCH 02/13] fix(api): a limited Admin's new account gets the creator's ceiling (RANCH-8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit §1. POST /users and create_user copy a limited Admin's lists onto the new account in the transaction that creates it, and withhold the assistant when the Admin does not have it. A password or sign-in email change on an account that reaches beyond the Admin is refused, on the route and the tool alike. Disabling an account tells the access lists, which close what it holds open (used by the chat surface). Co-Authored-By: Claude --- .../agentAccess/data/agentAccess.gateway.ts | 39 +++ .../domain/__fixtures__/agentAccess.ts | 25 ++ .../domain/agentAccess.created.spec.ts | 217 +++++++++++++++ .../agentAccess/domain/agentAccess.gateway.ts | 14 + .../agentAccess/domain/agentAccess.service.ts | 109 ++++++++ .../agentAccess/domain/agentAccess.types.ts | 12 + api/src/slices/user/user/data/user.gateway.ts | 19 +- .../slices/user/user/domain/user.gateway.ts | 15 +- api/src/slices/user/user/domain/userEdit.ts | 6 + api/src/slices/user/user/user.ceiling.spec.ts | 260 ++++++++++++++++++ .../slices/user/user/user.controller.spec.ts | 1 + api/src/slices/user/user/user.controller.ts | 37 ++- api/src/slices/user/user/user.tool.spec.ts | 16 +- api/src/slices/user/user/user.tool.ts | 53 +++- 14 files changed, 802 insertions(+), 21 deletions(-) create mode 100644 api/src/slices/user/agentAccess/domain/agentAccess.created.spec.ts create mode 100644 api/src/slices/user/user/user.ceiling.spec.ts diff --git a/api/src/slices/user/agentAccess/data/agentAccess.gateway.ts b/api/src/slices/user/agentAccess/data/agentAccess.gateway.ts index 8c3bfc135..2ce37cc42 100644 --- a/api/src/slices/user/agentAccess/data/agentAccess.gateway.ts +++ b/api/src/slices/user/agentAccess/data/agentAccess.gateway.ts @@ -124,6 +124,45 @@ export class AgentAccessGateway extends IAgentAccessGateway { return true; } + async copyCeiling( + tx: unknown, + creatorId: string, + userId: string, + ): Promise { + if (!creatorId || !userId) return false; + const client = tx as Tx; + // Creator first, always: the Owner narrowing this Admin takes the same + // lock, so the copy sees the lists before or after that change, never + // half of it. `change()` locks only its target and `allowCreated` only + // an agent's creator, so nothing waits the other way round. + await this.lock(client, creatorId); + await this.lock(client, userId); + const creator = await this.loadWith(client, creatorId); + const source: Pick = + creator.accountMissing ? { limited: true, entries: [] } : creator; + const open = + !source.limited && !source.entries.some((e) => e.list === 'denied'); + if (open) return false; + await client.userAgentAccess.create({ + data: { + userId, + limited: source.limited, + updatedById: creatorId, + updatedAt: this.nextStamp(null), + }, + }); + if (source.entries.length > 0) { + await client.userAgentAccessEntry.createMany({ + data: source.entries.map((e) => ({ + userId, + agentId: e.agentId, + list: e.list, + })), + }); + } + return true; + } + async removeUser(userId: string): Promise { await this.prisma.$transaction(async (tx) => { await this.lock(tx, userId); diff --git a/api/src/slices/user/agentAccess/domain/__fixtures__/agentAccess.ts b/api/src/slices/user/agentAccess/domain/__fixtures__/agentAccess.ts index ae5fabed4..e5058b8f6 100644 --- a/api/src/slices/user/agentAccess/domain/__fixtures__/agentAccess.ts +++ b/api/src/slices/user/agentAccess/domain/__fixtures__/agentAccess.ts @@ -125,6 +125,31 @@ export class MemoryAgentAccessGateway extends IAgentAccessGateway { return Promise.resolve(true); } + copyCeiling( + _tx: unknown, + creatorId: string, + userId: string, + ): Promise { + const row = this.gone.has(creatorId) + ? { limited: true, entries: new Map() } + : this.rows.get(creatorId); + if (!row) return Promise.resolve(false); + const denies = [...row.entries.values()].some((e) => e.list === 'denied'); + if (!row.limited && !denies) return Promise.resolve(false); + this.rows.set(userId, { + limited: row.limited, + updatedAt: new Date((this.clock += 1000)), + entries: new Map( + [...row.entries.values()].map((e) => [e.agentId, { ...e }]), + ), + }); + this.copies.push({ creatorId, userId }); + return Promise.resolve(true); + } + + /** Every copy `copyCeiling` wrote, in order, for specs to inspect. */ + copies: { creatorId: string; userId: string }[] = []; + removeUser(userId: string): Promise { this.rows.delete(userId); // The account row goes in the same delete; a token may still name it. diff --git a/api/src/slices/user/agentAccess/domain/agentAccess.created.spec.ts b/api/src/slices/user/agentAccess/domain/agentAccess.created.spec.ts new file mode 100644 index 000000000..a46dd16b5 --- /dev/null +++ b/api/src/slices/user/agentAccess/domain/agentAccess.created.spec.ts @@ -0,0 +1,217 @@ +import { UserRoleTypes } from '#/user/user/domain/user.types'; +import { + ADMIN, + ADMIN2, + OWNER, + USER, + USER2, + accessHarness, + person, +} from './__fixtures__/agentAccess'; +import { AgentAccessError } from './agentAccess.types'; + +/** + * RANCH-8 (audit §1, owner decision C10): an Admin never hands out more than + * their own ceiling, through a new account included. A limited Admin's new + * account is created with a copy of the Admin's lists in the same + * transaction; a password or sign-in email is not changed on an account that + * reaches beyond the Admin; widening a copied account stays refused. + * + * Throughout: agents A, B, C; the Admin is limited to A and B. + */ + +function limitedAdmin(agentIds?: string[]) { + const h = accessHarness(agentIds); + h.gateway.seed(ADMIN.id, true, [ + { agentId: 'A', list: 'allowed' }, + { agentId: 'B', list: 'allowed' }, + ]); + return h; +} + +const refusal = async (run: Promise): Promise => { + try { + await run; + } catch (e) { + if (e instanceof AgentAccessError) return e.code; + throw e; + } + return 'saved'; +}; + +const admin = person(ADMIN); +const owner = person(OWNER); +const created = { id: USER2.id, role: UserRoleTypes.User }; + +describe('a limited Admin creates no account wider than themselves (FR-001)', () => { + it('a new account gets a copy of the creator’s allowed list, and reaches exactly that', async () => { + const { service, gateway } = limitedAdmin(); + expect(await service.seedCreated(null, admin, created)).toBe(true); + const copy = await gateway.load(USER2.id); + expect(copy.limited).toBe(true); + expect(copy.entries.map((e) => `${e.list}:${e.agentId}`).sort()).toEqual([ + 'allowed:A', + 'allowed:B', + ]); + gateway.agents.add('NEW'); + for (const id of ['A', 'B', 'C', 'NEW']) { + expect(await service.reaches(person(USER2), id)).toBe( + await service.reaches(admin, id), + ); + } + expect(await service.outcome(USER2.id)).toEqual({ + kind: 'only', + needsReview: false, + }); + }); + + it('a denied-list creator is copied as a denied list: a new agent is reached as the creator reaches it', async () => { + const { service, gateway } = accessHarness(); + gateway.seed(ADMIN.id, false, [{ agentId: 'C', list: 'denied' }]); + expect(await service.seedCreated(null, admin, created)).toBe(true); + gateway.agents.add('NEW'); + expect(await service.reaches(person(USER2), 'C')).toBe(false); + expect(await service.reaches(person(USER2), 'NEW')).toBe(true); + expect((await service.outcome(USER2.id)).kind).toBe('all_except'); + }); + + it('a creator limited to nothing creates an account that reaches nothing', async () => { + const { service, gateway } = accessHarness(); + gateway.seed(ADMIN.id, true, []); + expect(await service.seedCreated(null, admin, created)).toBe(true); + expect(await service.reaches(person(USER2), 'A')).toBe(false); + expect(await service.outcome(USER2.id)).toEqual({ + kind: 'none', + needsReview: true, + }); + }); + + it('the Owner, a trusted party and an Admin with no lists create accounts as before (FR-002)', async () => { + for (const creator of [owner, { kind: 'trusted' as const }]) { + const { service, gateway } = limitedAdmin(); + expect(await service.seedCreated(null, creator, created)).toBe(false); + expect(gateway.copies).toEqual([]); + expect(await service.reaches(person(USER2), 'C')).toBe(true); + } + const { service, gateway } = accessHarness(); + expect(await service.seedCreated(null, admin, created)).toBe(false); + expect(gateway.copies).toEqual([]); + expect((await service.outcome(USER2.id)).kind).toBe('all'); + }); + + it('the copy is not linked: narrowing the creator later leaves the account as it was', async () => { + const { service, gateway } = limitedAdmin(); + await service.seedCreated(null, admin, created); + gateway.seed(ADMIN.id, true, [{ agentId: 'A', list: 'allowed' }]); + expect(await service.reaches(person(USER2), 'B')).toBe(true); + }); + + it('withholds the assistant when the limited creator does not have it', async () => { + const { service } = limitedAdmin(); + const withheld: string[] = []; + service.attachAssistant({ + assistantId: () => Promise.resolve('R'), + forPerson: ({ userId }) => + Promise.resolve({ id: 'R', enabled: userId !== ADMIN.id }), + withholdFor: (_tx, who, by) => { + withheld.push(`${who.userId} by ${by}`); + return Promise.resolve(true); + }, + }); + await service.seedCreated(null, admin, created); + expect(withheld).toEqual([`${USER2.id} by ${ADMIN.id}`]); + }); + + it('leaves the assistant to the role setting when the creator has it', async () => { + const { service } = limitedAdmin(); + const withholdFor = jest.fn(() => Promise.resolve(true)); + service.attachAssistant({ + assistantId: () => Promise.resolve('R'), + forPerson: () => Promise.resolve({ id: 'R', enabled: true }), + withholdFor, + }); + await service.seedCreated(null, admin, created); + expect(withholdFor).not.toHaveBeenCalled(); + }); +}); + +describe('widening a copied account stays refused (FR-005)', () => { + it('a limited Admin cannot clear the lists of a User seeded from their ceiling', async () => { + const { service } = limitedAdmin(); + await service.seedCreated(null, admin, { id: USER.id, role: USER.role }); + expect( + await refusal( + service.replace( + admin, + USER.id, + { allowed: [], denied: [] }, + { confirmOpen: true }, + ), + ), + ).toBe('ACCESS_EXCEEDS_CEILING'); + expect( + await refusal(service.adjust(admin, USER.id, { allow: ['C'] })), + ).toBe('AGENT_NOT_FOUND'); + expect(await service.reaches(person(USER), 'C')).toBe(false); + }); + + it('and cannot edit the lists of an Admin they created at all', async () => { + const { service } = limitedAdmin(); + await service.seedCreated(null, admin, { + id: ADMIN2.id, + role: ADMIN2.role, + }); + expect( + await refusal( + service.replace( + admin, + ADMIN2.id, + { allowed: [], denied: [] }, + { confirmOpen: true }, + ), + ), + ).toBe('ACCESS_NOT_EDITABLE'); + expect(await service.reaches(person(ADMIN2), 'C')).toBe(false); + }); +}); + +describe('reachesBeyond: whose sign-in a limited Admin may change (FR-003)', () => { + it('an account that reaches an agent outside the Admin’s view is beyond', async () => { + const { service } = limitedAdmin(); + // USER has no lists: A, B and C. + expect(await service.reachesBeyond(admin, USER.id)).toBe(true); + }); + + it('an account within the ceiling, or exactly at it, is not', async () => { + const { service, gateway } = limitedAdmin(); + gateway.seed(USER.id, true, [{ agentId: 'A', list: 'allowed' }]); + expect(await service.reachesBeyond(admin, USER.id)).toBe(false); + gateway.seed(USER.id, true, [ + { agentId: 'A', list: 'allowed' }, + { agentId: 'B', list: 'allowed' }, + ]); + expect(await service.reachesBeyond(admin, USER.id)).toBe(false); + }); + + it('the assistant counts: an account that has it reaches beyond an Admin who does not', async () => { + const { service, gateway } = limitedAdmin(['A', 'B', 'C', 'R']); + gateway.seed(USER.id, true, [{ agentId: 'A', list: 'allowed' }]); + service.attachAssistant({ + assistantId: () => Promise.resolve('R'), + forPerson: ({ userId }) => + Promise.resolve({ id: 'R', enabled: userId !== ADMIN.id }), + }); + expect(await service.reachesBeyond(admin, USER.id)).toBe(true); + }); + + it('never for the Owner, a trusted party, an Admin with no lists, or the Admin’s own account', async () => { + const { service } = limitedAdmin(); + expect(await service.reachesBeyond(owner, USER.id)).toBe(false); + expect(await service.reachesBeyond({ kind: 'trusted' }, USER.id)).toBe( + false, + ); + expect(await service.reachesBeyond(admin, ADMIN.id)).toBe(false); + const open = accessHarness(); + expect(await open.service.reachesBeyond(admin, USER.id)).toBe(false); + }); +}); diff --git a/api/src/slices/user/agentAccess/domain/agentAccess.gateway.ts b/api/src/slices/user/agentAccess/domain/agentAccess.gateway.ts index 37851f494..8297abd0a 100644 --- a/api/src/slices/user/agentAccess/domain/agentAccess.gateway.ts +++ b/api/src/slices/user/agentAccess/domain/agentAccess.gateway.ts @@ -55,6 +55,20 @@ export abstract class IAgentAccessGateway { agentId: string, ): Promise; + /** + * Inside the transaction that creates an account (`tx` is that + * transaction's client), holding the creator's lock and then the new + * account's: when the creator has lists, give the new account a copy of + * them, row and entries as stored (RANCH-8, data-model.md I-1). A creator + * whose account is gone counts as limited with nothing allowed. True when + * a copy was written; false for a creator with no lists. + */ + abstract copyCeiling( + tx: unknown, + creatorId: string, + userId: string, + ): Promise; + /** The account's row and entries, when the account is deleted. */ abstract removeUser(userId: string): Promise; } diff --git a/api/src/slices/user/agentAccess/domain/agentAccess.service.ts b/api/src/slices/user/agentAccess/domain/agentAccess.service.ts index de9776e01..69c5101cd 100644 --- a/api/src/slices/user/agentAccess/domain/agentAccess.service.ts +++ b/api/src/slices/user/agentAccess/domain/agentAccess.service.ts @@ -108,6 +108,7 @@ export class AgentAccessService implements IAgentReach { private readonly logger = new Logger(AgentAccessService.name); private readonly listeners = new Set(); private readonly removedListeners = new Set(); + private readonly disabledListeners = new Set(); /** Whether a person has the assistant; null until its slice says (CLEAN-240). */ private assistant: IAssistantAvailability | null = null; @@ -521,6 +522,23 @@ export class AgentAccessService implements IAgentReach { : null; } + /** + * Whether the account that ticked an assistant ability still stands behind + * it on `agentId` (RANCH-8, FR-015): read now, never stored. Gone or + * disabled: no. The Owner: yes. An Admin: what their lists reach today. A + * User (an Admin demoted since): no. + */ + async granterReaches(granterId: string, agentId: string): Promise { + const granter = await this.liveAccount(granterId); + if (!granter) return false; + if (granter.role === UserRoleTypes.Owner) return true; + if (granter.role !== UserRoleTypes.Admin) return false; + return this.reaches( + { userId: granter.id, role: UserRoleTypes.Admin }, + agentId, + ); + } + /** * A new agent joins its creator's allowed list when that account is * limited (FR-023). `tx` is the transaction creating the agent, so the @@ -530,6 +548,97 @@ export class AgentAccessService implements IAgentReach { return this.gateway.allowCreated(tx, userId, agentId); } + /** + * An account is being created by `creator` (RANCH-8, FR-001). `tx` is the + * transaction creating it, so the account never exists without what is + * written here, not even between two statements. + * + * A limited Admin's new account gets a copy of the Admin's lists, as + * stored: it reaches exactly what the Admin reaches, agents created later + * included where the Admin's do. When the Admin does not have the + * assistant, the new account does not get it either. The Owner, a trusted + * party and an Admin with no lists create an account as before: no lists. + * + * The copy is not linked: what the Owner later does to the Admin's lists + * leaves the account's own alone, as for every account. + */ + async seedCreated( + tx: unknown, + creator: IAccessEditor, + created: { id: string; role: UserRoleTypes }, + ): Promise { + if (creator.kind !== 'person') return false; + if (creator.role !== UserRoleTypes.Admin) return false; + const copied = await this.gateway.copyCeiling( + tx, + creator.userId, + created.id, + ); + if (!copied || !this.assistant?.withholdFor) return copied; + const own = await this.assistant.forPerson({ + userId: creator.userId, + role: UserRoleTypes.Admin, + }); + if (own && !own.enabled) { + await this.assistant.withholdFor( + tx, + { userId: created.id, role: created.role }, + creator.userId, + ); + } + return true; + } + + /** + * Whether `targetId` reaches an agent `editor` does not (RANCH-8, FR-003): + * what makes a new password or sign-in email on that account a way into + * agents outside the editor's view. The assistant counts: an account that + * has it reaches beyond an Admin who does not. + * + * Never true for a trusted party, the Owner, an Admin with no lists (who + * keep every power they had over accounts) or an account's own editor. + * Asked for an Admin with lists only, and only by the two places that + * change sign-in credentials. + */ + async reachesBeyond( + editor: IAccessEditor, + targetId: string, + ): Promise { + if (editor.kind !== 'person') return false; + if (editor.role !== UserRoleTypes.Admin) return false; + if (!targetId || targetId === editor.userId) return false; + const own = await this.gateway.load(editor.userId); + if (summarize(own).kind === 'all' && !own.accountMissing) return false; + const target = await this.users.findById(targetId); + if (!target) return false; + const [editorReach, targetReach, agentIds] = await Promise.all([ + this.reachableIds(editor), + this.reachableIds({ userId: target.id, role: target.role }), + this.gateway.agentIds(), + ]); + return agentIds.some((id) => targetReach.has(id) && !editorReach.has(id)); + } + + /** + * The account was disabled (RANCH-8, FR-009): everything it holds open + * is closed, as for an account that was deleted. Its console token keeps + * its signature until it expires; the chat paths refuse it by asking + * `liveAccount`, and this closes the sockets it already has. + */ + accountDisabled(userId: string): void { + if (userId) this.notify(this.disabledListeners, userId); + } + + /** + * Called when an account is disabled. Kept apart from `onRemoved`: the + * account's settings stay (it may be enabled again), only what it holds + * open is closed. + */ + onDisabled(listener: ChangedListener): () => void { + this.disabledListeners.add(listener); + return () => this.disabledListeners.delete(listener); + } + private notifyChanged(userId: string): void { this.notify(this.listeners, userId); } diff --git a/api/src/slices/user/agentAccess/domain/agentAccess.types.ts b/api/src/slices/user/agentAccess/domain/agentAccess.types.ts index bacc5d7ea..996eb12aa 100644 --- a/api/src/slices/user/agentAccess/domain/agentAccess.types.ts +++ b/api/src/slices/user/agentAccess/domain/agentAccess.types.ts @@ -166,6 +166,18 @@ export interface IAssistantAvailability { assistantId(): Promise; /** The switch for one person; null while there is no assistant. */ forPerson(person: IAccessPerson): Promise; + /** + * Inside the transaction that creates `person`'s account (`tx`): switch + * the assistant off for them when their role's setting would switch it + * on (RANCH-8). Asked when the account's limited creator does not have the + * assistant, so that the new account never reaches more than its creator. + * True when an exception was written. + */ + withholdFor?( + tx: unknown, + person: IAccessPerson, + creatorId: string, + ): Promise; } export class AgentReach { diff --git a/api/src/slices/user/user/data/user.gateway.ts b/api/src/slices/user/user/data/user.gateway.ts index e42cefac5..9b5879ca8 100644 --- a/api/src/slices/user/user/data/user.gateway.ts +++ b/api/src/slices/user/user/data/user.gateway.ts @@ -1,7 +1,7 @@ import { Injectable } from '@nestjs/common'; import * as bcrypt from 'bcrypt'; import { PrismaService } from '#/setup/prisma/prisma.service'; -import { IUserGateway } from '../domain/user.gateway'; +import { IUserGateway, type IUserCreateOptions } from '../domain/user.gateway'; import { IUserData, ICreateUserData, @@ -32,12 +32,21 @@ export class UserGateway extends IUserGateway { return record ? this.mapper.toEntity(record) : null; } - async create(data: ICreateUserData): Promise { + async create( + data: ICreateUserData, + opts: IUserCreateOptions = {}, + ): Promise { const password = await bcrypt.hash(data.password, BCRYPT_ROUNDS); - const record = await this.prisma.user.create({ - data: this.mapper.toCreate({ ...data, password }), + // One transaction with whatever the caller seeds for the account + // (RANCH-8): it never exists without it, not even between statements. + return this.prisma.$transaction(async (tx) => { + const record = await tx.user.create({ + data: this.mapper.toCreate({ ...data, password }), + }); + const user = this.mapper.toEntity(record); + if (opts.within) await opts.within(tx, user); + return user; }); - return this.mapper.toEntity(record); } async update(id: string, data: IUpdateUserData): Promise { diff --git a/api/src/slices/user/user/domain/user.gateway.ts b/api/src/slices/user/user/domain/user.gateway.ts index 7037c7de2..5e43a9265 100644 --- a/api/src/slices/user/user/domain/user.gateway.ts +++ b/api/src/slices/user/user/domain/user.gateway.ts @@ -1,9 +1,22 @@ import { IUserData, ICreateUserData, IUpdateUserData } from './user.types'; +export interface IUserCreateOptions { + /** + * Runs inside the transaction that creates the account, before it + * commits (`tx` is that transaction's client): whatever it writes exists + * from the same moment as the account, and a failure undoes both. How a + * limited Admin's new account gets its creator's ceiling (RANCH-8). + */ + within?: (tx: unknown, user: IUserData) => Promise; +} + export abstract class IUserGateway { abstract findAll(): Promise; abstract findById(id: string): Promise; - abstract create(data: ICreateUserData): Promise; + abstract create( + data: ICreateUserData, + opts?: IUserCreateOptions, + ): Promise; abstract update(id: string, data: IUpdateUserData): Promise; abstract delete(id: string): Promise; } diff --git a/api/src/slices/user/user/domain/userEdit.ts b/api/src/slices/user/user/domain/userEdit.ts index 5b5558ff0..0051a9957 100644 --- a/api/src/slices/user/user/domain/userEdit.ts +++ b/api/src/slices/user/user/domain/userEdit.ts @@ -21,6 +21,12 @@ export const USER_EDIT_REFUSALS = { 'You cannot change the status of your own account. Ask the Owner, or ' + 'another administrator, to do it.', notAllowed: 'Your account cannot change other accounts.', + // RANCH-8 (FR-003): a limited Admin who set the password of a wider + // account would sign in as it and reach agents they cannot. Names no + // agent and no count. + reachesBeyond: + 'This account reaches agents outside your view, so you cannot change ' + + 'its password or sign-in email. Ask the Owner.', } as const; /** diff --git a/api/src/slices/user/user/user.ceiling.spec.ts b/api/src/slices/user/user/user.ceiling.spec.ts new file mode 100644 index 000000000..50e774e31 --- /dev/null +++ b/api/src/slices/user/user/user.ceiling.spec.ts @@ -0,0 +1,260 @@ +import { ForbiddenException } from '@nestjs/common'; +import type { Request } from 'express'; +import type { IUserGateway } from './domain'; +import { USER_EDIT_REFUSALS, UserRoleTypes } from './domain'; +import { UserController } from './user.controller'; +import { UserTool } from './user.tool'; +import { asPerson, asTrustedAgent } from '#/mcp/testing'; +import { + MemoryAgentAccessGateway, + usersGateway, +} from '#/user/agentAccess/domain/__fixtures__/agentAccess'; +import { AgentAccessService } from '#/user/agentAccess/domain/agentAccess.service'; +import type { IAgentPinGateway } from '#/agent/pin/domain/agentPin.gateway'; + +/** + * RANCH-8, audit §1 (`user/user:limited-admin-creates-unlimited-account`) and + * owner decision C10: an Admin never hands out more than their own ceiling. + * + * The audit's reproduction: an Admin limited to agent A created an Admin + * with empty lists, which reached every ordinary agent, and set the password + * of a User who reached agent B. Both doors are checked here as the console + * route and as the tool, which must answer identically (FR-004). + * + * Agents A, B, C. `lim` is an Admin limited to A; `open` is an Admin with no + * lists; `wide` is a User with no lists (A, B, C); `narrow` a User limited + * to A. + */ + +const at = new Date('2026-12-01T10:00:00.000Z'); +const account = (id: string, role: UserRoleTypes) => ({ + id, + name: id, + email: `${id}@ranch.test`, + role, + status: 'active' as const, + createdAt: at, + updatedAt: at, +}); +const owner = account('user-owner', UserRoleTypes.Owner); +const lim = account('user-lim', UserRoleTypes.Admin); +const open = account('user-open', UserRoleTypes.Admin); +const wide = account('user-wide', UserRoleTypes.User); +const narrow = account('user-narrow', UserRoleTypes.User); + +function stack() { + const rows = [owner, lim, open, wide, narrow]; + const lists = new MemoryAgentAccessGateway(['A', 'B', 'C']); + lists.seed(lim.id, true, [{ agentId: 'A', list: 'allowed' }]); + lists.seed(narrow.id, true, [{ agentId: 'A', list: 'allowed' }]); + const access = new AgentAccessService(lists, usersGateway(rows)); + let next = 0; + const users = { + findAll: jest.fn(() => Promise.resolve(rows)), + findById: jest.fn((id: string) => + Promise.resolve(rows.find((u) => u.id === id) ?? null), + ), + // As the Prisma gateway does: the row, then `within` in the same + // transaction, before anything is returned. + create: jest.fn( + async ( + data: { name: string; email: string; role?: UserRoleTypes }, + opts?: { + within?: ( + tx: unknown, + user: { id: string; role: UserRoleTypes }, + ) => Promise; + }, + ) => { + const user = { + ...account(`user-new-${++next}`, data.role ?? UserRoleTypes.User), + name: data.name, + email: data.email, + }; + rows.push(user); + await opts?.within?.({ tx: true }, user); + return user; + }, + ), + update: jest.fn((id: string, patch: object) => + Promise.resolve({ ...rows.find((u) => u.id === id), ...patch }), + ), + delete: jest.fn(() => Promise.resolve()), + }; + const pins = { + removeUser: jest.fn().mockResolvedValue(undefined), + } as unknown as IAgentPinGateway; + const gateway = users as unknown as IUserGateway; + return { + access, + lists, + users, + controller: new UserController(gateway, access, pins), + tool: new UserTool(gateway, access, pins), + }; +} + +const bearer = (who: { id: string; role: UserRoleTypes }) => + ({ user: { sub: who.id, email: '', roles: [who.role] } }) as never; + +/** The Ranch assistant answering `who`. */ +const asking = (who: { id: string; role: UserRoleTypes }) => + asPerson( + { + user: { sub: 'agent:ranch', email: '', roles: [UserRoleTypes.Owner] }, + } as unknown as Request, + who.role, + who.id, + ); + +const textOf = (result: { content: { text: string }[] }) => + result.content[0].text; + +const NEW_ADMIN = { + name: 'Shadow Admin', + email: 'shadow@ranch.test', + password: 'shadow-pass-1', + role: UserRoleTypes.Admin, +}; + +describe('POST /users and create_user by a limited Admin (FR-001, FR-004)', () => { + it('the route creates the account with the creator’s ceiling, and says so', async () => { + const { controller, access } = stack(); + const created = await controller.create(NEW_ADMIN, bearer(lim)); + expect(created.agentAccess).toEqual({ kind: 'only', needsReview: false }); + const shadow = { userId: created.id, role: UserRoleTypes.Admin }; + expect(await access.reaches(shadow, 'A')).toBe(true); + expect(await access.reaches(shadow, 'B')).toBe(false); + expect(await access.reaches(shadow, 'C')).toBe(false); + }); + + it('the tool does the same and says only the Owner can give more (FR-005a)', async () => { + const { tool, access } = stack(); + const result = await tool.createUser(NEW_ADMIN, null, asking(lim)); + const body = JSON.parse(textOf(result)) as { + user: { id: string }; + agentAccess: { kind: string }; + note: string; + }; + expect(body.agentAccess).toEqual({ kind: 'only', needsReview: false }); + expect(body.note).toBe( + 'The password is not repeated here; the person hands it over. This ' + + 'account reaches only the agents you can see. Only the Owner can ' + + 'give it more.', + ); + expect( + await access.reaches( + { userId: body.user.id, role: UserRoleTypes.Admin }, + 'B', + ), + ).toBe(false); + }); + + it('a creator who reaches nothing creates an account that reaches nothing, and the note says so', async () => { + const { tool, lists } = stack(); + lists.seed(lim.id, true, []); + const body = JSON.parse( + textOf(await tool.createUser(NEW_ADMIN, null, asking(lim))), + ) as { agentAccess: { kind: string }; note: string }; + expect(body.agentAccess.kind).toBe('none'); + expect(body.note).toContain( + 'This account reaches no agent yet, as you reach none. Only the Owner ' + + 'can give it more.', + ); + expect(body.note).not.toMatch(/\bA\b|\b1\b/); + }); + + it('the Owner and an Admin with no lists create accounts as before (FR-002)', async () => { + const { controller, tool } = stack(); + for (const who of [owner, open]) { + const created = await controller.create(NEW_ADMIN, bearer(who)); + expect(created.agentAccess).toEqual({ kind: 'all', needsReview: false }); + const body = JSON.parse( + textOf(await tool.createUser(NEW_ADMIN, null, asking(who))), + ) as Record; + expect(body.note).toBe( + 'The password is not repeated here; the person hands it over.', + ); + expect(body.agentAccess).toBeUndefined(); + } + const trusted = asTrustedAgent({ + user: { sub: 'agent:ranch', email: '', roles: [UserRoleTypes.Owner] }, + } as unknown as Request); + const body = JSON.parse( + textOf(await tool.createUser(NEW_ADMIN, null, trusted)), + ) as Record; + expect(body.agentAccess).toBeUndefined(); + }); +}); + +describe('PUT /users/:id and update_user: a wider account’s sign-in (FR-003, FR-004)', () => { + it('refuses a new password or email on a User who reaches beyond the Admin, and changes nothing', async () => { + const { controller, tool, users } = stack(); + for (const patch of [ + { password: 'takeover-pass-1' }, + { email: 'mine@ranch.test' }, + ]) { + await expect( + controller.update(wide.id, patch, bearer(lim)), + ).rejects.toThrow( + new ForbiddenException(USER_EDIT_REFUSALS.reachesBeyond), + ); + const result = await tool.updateUser( + { userId: wide.id, ...patch }, + null, + asking(lim), + ); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(USER_EDIT_REFUSALS.reachesBeyond); + } + expect(users.update).not.toHaveBeenCalled(); + }); + + it('the refusal names no agent and no count', () => { + expect(USER_EDIT_REFUSALS.reachesBeyond).toBe( + 'This account reaches agents outside your view, so you cannot change ' + + 'its password or sign-in email. Ask the Owner.', + ); + }); + + it('lets the name and the status of that User change: they hand nobody a sign-in', async () => { + const { controller, users } = stack(); + await controller.update(wide.id, { name: 'Wide' }, bearer(lim)); + expect(users.update).toHaveBeenCalledWith(wide.id, { name: 'Wide' }); + }); + + it('lets the password of a User within the ceiling change, as today', async () => { + const { controller, tool, users } = stack(); + await controller.update(narrow.id, { password: 'new-pass-1' }, bearer(lim)); + const result = await tool.updateUser( + { userId: narrow.id, password: 'new-pass-2' }, + null, + asking(lim), + ); + expect(result.isError).toBeUndefined(); + expect(users.update).toHaveBeenCalledTimes(2); + }); + + it('the Owner and an Admin with no lists keep every power over the wider User', async () => { + const { controller, users } = stack(); + await controller.update(wide.id, { password: 'p-owner-1' }, bearer(owner)); + await controller.update(wide.id, { password: 'p-open-1' }, bearer(open)); + expect(users.update).toHaveBeenCalledTimes(2); + }); +}); + +describe('disabling an account closes what it holds open (FR-009)', () => { + it('the route and the tool tell the access lists, which tell the chat hub', async () => { + const { controller, tool, access } = stack(); + const closed: string[] = []; + access.onDisabled((id) => closed.push(id)); + await controller.update(narrow.id, { status: 'disabled' }, bearer(owner)); + await tool.updateUser( + { userId: wide.id, status: 'disabled' }, + null, + asking(owner), + ); + await controller.update(narrow.id, { status: 'active' }, bearer(owner)); + expect(closed).toEqual([narrow.id, wide.id]); + }); +}); diff --git a/api/src/slices/user/user/user.controller.spec.ts b/api/src/slices/user/user/user.controller.spec.ts index 76838da45..30959efc7 100644 --- a/api/src/slices/user/user/user.controller.spec.ts +++ b/api/src/slices/user/user/user.controller.spec.ts @@ -213,6 +213,7 @@ describe('the roles on the user routes', () => { }); expect(users.create).toHaveBeenCalledWith( expect.objectContaining({ role: UserRoleTypes.Admin }), + expect.objectContaining({ within: expect.any(Function) }), ); }); }); diff --git a/api/src/slices/user/user/user.controller.ts b/api/src/slices/user/user/user.controller.ts index 834cdb427..b8ae16618 100644 --- a/api/src/slices/user/user/user.controller.ts +++ b/api/src/slices/user/user/user.controller.ts @@ -21,6 +21,7 @@ import type { Request } from 'express'; import { IUserGateway, refuseUserEdit, + USER_EDIT_REFUSALS, UserRoleTypes, type IUserData, type IUserEditor, @@ -111,10 +112,23 @@ export class UserController { } @Post() - @ApiOperation({ summary: 'Create a user (admin sets the password)' }) + @ApiOperation({ + summary: + 'Create a user (admin sets the password). An Admin whose agent access is limited creates an account limited the same way: it gets a copy of the creator’s lists, and only the Owner can widen it (`agentAccess` says what it reaches).', + }) @ApiOkResponse({ type: UserDto }) - async create(@Body() dto: CreateUserDto) { - return this.presentOne(await this.userGateway.create(dto)); + async create( + @Body() dto: CreateUserDto, + @Req() req?: Request & { user?: IAuthTokenPayload }, + ) { + const editor = editorOf(req); + // A limited Admin's new account gets the Admin's ceiling in the same + // transaction (RANCH-8, FR-001): with empty lists it would reach every + // agent, and the Admin would manage them all through it. + const user = await this.userGateway.create(dto, { + within: (tx, created) => this.access.seedCreated(tx, editor, created), + }); + return this.presentOne(user); } @Put(':id') @@ -131,18 +145,31 @@ export class UserController { // Who may change whom (CLEAN-232): an Admin edits Users and their own // name, email and password, never the Owner or another Admin. A new // password on either of those would be that person's role. + const editor = editorOf(req); const refusal = refuseUserEdit( - editorOf(req), + editor, target, EDITABLE_FIELDS.filter((field) => dto[field] !== undefined), ); if (refusal) throw new ForbiddenException(refusal); + // A limited Admin who set the password or sign-in email of an account + // that reaches beyond them would sign in as it (RANCH-8, FR-003). + if ( + (dto.password !== undefined || dto.email !== undefined) && + (await this.access.reachesBeyond(editor, target.id)) + ) { + throw new ForbiddenException(USER_EDIT_REFUSALS.reachesBeyond); + } if (dto.status !== undefined && target.role === UserRoleTypes.Owner) { throw new ForbiddenException( 'The Owner account status cannot be changed', ); } - return this.presentOne(await this.userGateway.update(id, dto)); + const updated = await this.userGateway.update(id, dto); + // A disabled account's open chat sockets close now; its console token + // is refused on the chat paths from the next request (RANCH-8, FR-009). + if (dto.status === 'disabled') this.access.accountDisabled(target.id); + return this.presentOne(updated); } @Put(':id/role') diff --git a/api/src/slices/user/user/user.tool.spec.ts b/api/src/slices/user/user/user.tool.spec.ts index f1f378ed0..7481cc1bb 100644 --- a/api/src/slices/user/user/user.tool.spec.ts +++ b/api/src/slices/user/user/user.tool.spec.ts @@ -305,12 +305,15 @@ describe('UserTool — creating', () => { operator(), ), ); - expect(users.create).toHaveBeenCalledWith({ - name: 'New Person', - email: 'new@ranch.test', - password: SENTINEL, - role: UserRoleTypes.Admin, - }); + expect(users.create).toHaveBeenCalledWith( + { + name: 'New Person', + email: 'new@ranch.test', + password: SENTINEL, + role: UserRoleTypes.Admin, + }, + expect.objectContaining({ within: expect.any(Function) }), + ); expect(text).toContain('"id": "user-new"'); expect(text).toContain('new@ranch.test'); expect(text).not.toContain(SENTINEL); @@ -705,6 +708,7 @@ describe('UserTool — who may change which account', () => { expect(result.isError).toBeUndefined(); expect(users.create).toHaveBeenCalledWith( expect.objectContaining({ role: UserRoleTypes.Admin }), + expect.objectContaining({ within: expect.any(Function) }), ); }); }); diff --git a/api/src/slices/user/user/user.tool.ts b/api/src/slices/user/user/user.tool.ts index 3db45a4a0..25d99f06c 100644 --- a/api/src/slices/user/user/user.tool.ts +++ b/api/src/slices/user/user/user.tool.ts @@ -20,6 +20,7 @@ import { ASSIGNABLE_USER_ROLES, IUserGateway, refuseUserEdit, + USER_EDIT_REFUSALS, UserRoleTypes, type IUpdateUserData, type IUserData, @@ -140,7 +141,10 @@ export class UserTool implements IConditionallyListedTool { 'console does (there is no invitation email). Role defaults to User; ' + 'Admin is the other option — Owner exists once and cannot be created. ' + 'The result is the new account without the password; the person must ' + - 'pass it on themselves, it is never shown again.', + 'pass it on themselves, it is never shown again. When the person is ' + + 'an Admin limited to some agents, the new account reaches only the ' + + 'agents they can see and only the Owner can give it more: the result ' + + 'says so, repeat it.', parameters: z.object({ name: nameSchema, email: emailSchema, @@ -159,13 +163,41 @@ export class UserTool implements IConditionallyListedTool { httpRequest: AuthedRequest, ): Promise { requireOperator(httpRequest); - const user = await this.users.create({ name, email, password, role }); + // The same rule as POST /users (RANCH-8, FR-001, FR-004): a limited + // Admin's new account gets a copy of the Admin's lists, in the + // transaction that creates it. + const person = callerPerson(httpRequest); + const editor = person + ? ({ kind: 'person', ...person } as const) + : ({ kind: 'trusted' } as const); + let seeded = false; + const user = await this.users.create( + { name, email, password, role }, + { + within: async (tx, created) => { + seeded = await this.access.seedCreated(tx, editor, created); + }, + }, + ); // Log who was created, never with what — the API log is not a vault. this.logger.log(`User created through MCP: id=${user.id} email=${email}`); + const handOver = + 'The password is not repeated here; the person hands it over.'; + if (!seeded) { + return ok({ ok: true, user: publicUser(user), note: handOver }); + } + // Said before the person relies on it (FR-005a): what the account + // reaches, never which agents or how many. + const agentAccess = await this.access.outcome(user.id); + const reach = + agentAccess.kind === 'none' + ? 'This account reaches no agent yet, as you reach none.' + : 'This account reaches only the agents you can see.'; return ok({ ok: true, user: publicUser(user), - note: 'The password is not repeated here; the person hands it over.', + agentAccess, + note: `${handOver} ${reach} Only the Owner can give it more.`, }); } @@ -216,8 +248,11 @@ export class UserTool implements IConditionallyListedTool { // password, never the Owner or another Admin. The editor is the person // the call is made for; the agent acting for itself is trusted. const person = callerPerson(httpRequest); + const editor = person + ? ({ kind: 'person', ...person } as const) + : ({ kind: 'trusted' } as const); const refusal = refuseUserEdit( - person ? { kind: 'person', ...person } : { kind: 'trusted' }, + editor, target, ( [ @@ -231,6 +266,14 @@ export class UserTool implements IConditionallyListedTool { .map(([field]) => field), ); if (refusal) return err(refusal); + // Same rule as UserController.update (RANCH-8, FR-003): no new sign-in + // on an account that reaches beyond a limited Admin. + if ( + (password !== undefined || email !== undefined) && + (await this.access.reachesBeyond(editor, target.id)) + ) { + return err(USER_EDIT_REFUSALS.reachesBeyond); + } // Same rule as UserController.update: the Owner's status is not for // changing, since a disabled Owner locks the Ranch. if (status !== undefined && target.role === UserRoleTypes.Owner) { @@ -251,6 +294,8 @@ export class UserTool implements IConditionallyListedTool { ); } const user = await this.users.update(userId, patch); + // As UserController.update (RANCH-8, FR-009): what it holds open closes. + if (status === 'disabled') this.access.accountDisabled(userId); this.logger.log( `User updated through MCP: id=${userId} fields=${Object.keys(patch).join(',')}`, ); From ebd49583e8731418cf06364f648670f67f9802b2 Mon Sep 17 00:00:00 2001 From: "Maksym Hryzodub [DREAM]" Date: Tue, 1 Dec 2026 14:46:42 +0200 Subject: [PATCH 03/13] fix(api): only a real sign-in speaks as a person in chat (RANCH-8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit §3. clientIdFromJwtPayload, which every chat surface asks, is an allowlist: a console session, an embed token, or the agent's own token. The browser-view link, both extension tokens and the file open link carry a purpose typ that their own endpoints accept (and none, for tokens from before) and JwtAuthGuard refuses. A disabled or deleted account's console session is refused on chat paths and its sockets close. Spec fixtures that stood for console tokens gain the sid every console token carries. auth.types also carries the RANCH-8 grant helpers (grantedBy, noteGrantNotCovering) used by the grant commit. Co-Authored-By: Claude --- .../activity/activityWs.handler.spec.ts | 112 +++++++++---- .../bridle/activity/activityWs.handler.ts | 8 +- api/src/slices/bridle/bridle.acting.spec.ts | 12 +- .../slices/bridle/bridle.controller.spec.ts | 50 ++++-- .../domain/chatIdentity.allowlist.spec.ts | 152 ++++++++++++++++++ .../slices/bridle/domain/chatIdentity.spec.ts | 43 +++-- api/src/slices/bridle/domain/chatIdentity.ts | 49 ++++-- .../domain/consoleReach.service.spec.ts | 71 +++++++- .../bridle/domain/consoleReach.service.ts | 29 +++- .../guards/bridleChatAuth.guard.spec.ts | 62 ++++++- .../handlers/bridleClientWs.handler.spec.ts | 58 ++++++- .../browser.extension.controller.spec.ts | 82 +++++++++- .../browser/browser.extension.controller.ts | 10 +- .../browser/data/browserless.client.spec.ts | 8 +- .../slices/browser/data/browserless.client.ts | 4 +- api/src/slices/chat/myChat.controller.spec.ts | 6 +- .../integration.extension.controller.spec.ts | 86 ++++++++-- .../integration.extension.controller.ts | 14 +- .../slices/stats/myStats.controller.spec.ts | 8 +- api/src/slices/stats/stats.tool.spec.ts | 30 +++- api/src/slices/user/auth/domain/auth.types.ts | 75 ++++++++- .../slices/user/auth/guards/jwtAuth.guard.ts | 10 ++ .../user/auth/guards/purposeTokens.spec.ts | 118 ++++++++++++++ 23 files changed, 971 insertions(+), 126 deletions(-) create mode 100644 api/src/slices/bridle/domain/chatIdentity.allowlist.spec.ts create mode 100644 api/src/slices/user/auth/guards/purposeTokens.spec.ts diff --git a/api/src/slices/bridle/activity/activityWs.handler.spec.ts b/api/src/slices/bridle/activity/activityWs.handler.spec.ts index 962b0fd38..aa50ec717 100644 --- a/api/src/slices/bridle/activity/activityWs.handler.spec.ts +++ b/api/src/slices/bridle/activity/activityWs.handler.spec.ts @@ -16,6 +16,8 @@ describe('ActivityWsHandler', () => { hidden?: Record; /** Agents each account manages. */ managed?: Record; + /** Accounts that are gone or disabled (RANCH-8). */ + dead?: string[]; } = {}, ) { const changes = new Subject>(); @@ -35,9 +37,13 @@ describe('ActivityWsHandler', () => { async (session: { userId: string }, agentId: string) => !(options.hidden?.[session.userId] ?? []).includes(agentId), ), - manages: jest.fn( - async (session: { userId: string }, agentId: string) => - (options.managed?.[session.userId] ?? []).includes(agentId), + manages: jest.fn(async (session: { userId: string }, agentId: string) => + (options.managed?.[session.userId] ?? []).includes(agentId), + ), + // RANCH-8: whether the account behind the session is there and enabled. + live: jest.fn( + async (session: { userId: string }) => + !(options.dead ?? []).includes(session.userId), ), onRemoved: jest.fn(() => () => undefined), }; @@ -49,7 +55,7 @@ describe('ActivityWsHandler', () => { handler.onModuleInit(); let seq = 0; - const connect = (payload: Record | 'bad' | null) => { + const connect = async (payload: Record | 'bad' | null) => { const frames: Frame[] = []; const socket = { id: `s${(seq += 1)}`, @@ -73,7 +79,7 @@ describe('ActivityWsHandler', () => { this.disconnected = true; }), }; - handler.handleConnection(socket as never); + await handler.handleConnection(socket as never); return { socket, frames }; }; const settle = async () => { @@ -98,40 +104,59 @@ describe('ActivityWsHandler', () => { }; describe('the handshake', () => { - it('drops a socket with no token, a bad one, or a token that is not a console session', () => { + it('drops a socket with no token, a bad one, or a token that is not a console session', async () => { const { connect } = build(); - expect(connect(null).socket.disconnect).toHaveBeenCalled(); - expect(connect('bad').socket.disconnect).toHaveBeenCalled(); + expect((await connect(null)).socket.disconnect).toHaveBeenCalled(); + expect((await connect('bad')).socket.disconnect).toHaveBeenCalled(); expect( - connect({ sub: 'u1', sid: 's', typ: 'acting' }).socket.disconnect, + (await connect({ sub: 'u1', sid: 's', typ: 'acting' })).socket + .disconnect, ).toHaveBeenCalled(); - expect(connect({ sub: 'agent:a1' }).socket.disconnect).toHaveBeenCalled(); + expect( + (await connect({ sub: 'agent:a1' })).socket.disconnect, + ).toHaveBeenCalled(); + }); + + it('drops the session of an account that is gone or disabled (RANCH-8)', async () => { + const { connect } = build({ dead: ['u1'] }); + const gone = await connect(person('u1')); + expect(gone.socket.disconnect).toHaveBeenCalled(); + expect(gone.socket.data).toBeUndefined(); }); - it('keeps a person own console session', () => { + it('keeps a person own console session', async () => { const { connect } = build(); - expect(connect(person('u1')).socket.disconnect).not.toHaveBeenCalled(); + expect( + (await connect(person('u1'))).socket.disconnect, + ).not.toHaveBeenCalled(); }); }); describe('activity frames', () => { it('go to the sockets of that identity only', async () => { const { connect, changes, settle } = build(); - const mine = connect(person('u1')); - const theirs = connect(person('u2')); + const mine = await connect(person('u1')); + const theirs = await connect(person('u2')); const clientId = (mine.socket.data as { clientId: string }).clientId; changes.next({ clientId, agentId: 'front', - activity: { kind: 'writing', since: Date.parse('2026-11-30T10:00:00Z') }, + activity: { + kind: 'writing', + since: Date.parse('2026-11-30T10:00:00Z'), + }, }); await settle(); expect(mine.frames).toEqual([ { event: 'activity', - data: { agentId: 'front', kind: 'writing', since: '2026-11-30T10:00:00.000Z' }, + data: { + agentId: 'front', + kind: 'writing', + since: '2026-11-30T10:00:00.000Z', + }, }, ]); expect(theirs.frames).toEqual([]); @@ -139,9 +164,13 @@ describe('ActivityWsHandler', () => { it('are not sent for an agent the person no longer reaches', async () => { const { connect, changes, settle } = build({ hidden: { u1: ['front'] } }); - const mine = connect(person('u1')); + const mine = await connect(person('u1')); const clientId = (mine.socket.data as { clientId: string }).clientId; - changes.next({ clientId, agentId: 'front', activity: { kind: 'writing', since: 1 } }); + changes.next({ + clientId, + agentId: 'front', + activity: { kind: 'writing', since: 1 }, + }); await settle(); expect(mine.frames).toEqual([]); }); @@ -150,7 +179,7 @@ describe('ActivityWsHandler', () => { describe('a question between agents', () => { it('reaches the conversation own person, with the asked agent', async () => { const { connect, exchanges, settle } = build(); - const mine = connect(person('u1')); + const mine = await connect(person('u1')); const clientId = (mine.socket.data as { clientId: string }).clientId; exchanges.next({ ...open, clientId }); @@ -159,14 +188,22 @@ describe('ActivityWsHandler', () => { expect(mine.frames).toEqual([ { event: 'exchange', - data: { id: 'd1', from: 'front', to: 'back', status: 'open', own: true }, + data: { + id: 'd1', + from: 'front', + to: 'back', + status: 'open', + own: true, + }, }, ]); }); it('does not name an asked agent that person does not reach', async () => { - const { connect, exchanges, settle } = build({ hidden: { u1: ['back'] } }); - const mine = connect(person('u1')); + const { connect, exchanges, settle } = build({ + hidden: { u1: ['back'] }, + }); + const mine = await connect(person('u1')); const clientId = (mine.socket.data as { clientId: string }).clientId; exchanges.next({ ...open, clientId }); await settle(); @@ -183,8 +220,8 @@ describe('ActivityWsHandler', () => { const { connect, exchanges, settle } = build({ managed: { u2: ['front', 'back'] }, }); - const mine = connect(person('u1')); - const other = connect(person('u2')); + const mine = await connect(person('u1')); + const other = await connect(person('u2')); const clientId = (mine.socket.data as { clientId: string }).clientId; exchanges.next({ ...open, clientId }); await settle(); @@ -195,23 +232,31 @@ describe('ActivityWsHandler', () => { const { connect, exchanges, settle } = build({ managed: { adm: ['front', 'back'] }, }); - const mine = connect(person('u1')); - const admin = connect(person('adm', 'Admin')); + const mine = await connect(person('u1')); + const admin = await connect(person('adm', 'Admin')); const clientId = (mine.socket.data as { clientId: string }).clientId; exchanges.next({ ...open, clientId }); await settle(); expect(admin.frames).toEqual([ { event: 'exchange', - data: { id: 'd1', from: 'front', to: 'back', status: 'open', own: false }, + data: { + id: 'd1', + from: 'front', + to: 'back', + status: 'open', + own: false, + }, }, ]); }); it('tells an Admin who manages only one of them nothing', async () => { - const { connect, exchanges, settle } = build({ managed: { adm: ['front'] } }); - const mine = connect(person('u1')); - const admin = connect(person('adm', 'Admin')); + const { connect, exchanges, settle } = build({ + managed: { adm: ['front'] }, + }); + const mine = await connect(person('u1')); + const admin = await connect(person('adm', 'Admin')); const clientId = (mine.socket.data as { clientId: string }).clientId; exchanges.next({ ...open, clientId }); await settle(); @@ -220,12 +265,15 @@ describe('ActivityWsHandler', () => { it('says how it ended to the same people', async () => { const { connect, exchanges, settle } = build(); - const mine = connect(person('u1')); + const mine = await connect(person('u1')); const clientId = (mine.socket.data as { clientId: string }).clientId; exchanges.next({ ...open, clientId }); exchanges.next({ ...open, clientId, status: 'refused' }); await settle(); - expect(mine.frames.map((f) => f.data.status)).toEqual(['open', 'refused']); + expect(mine.frames.map((f) => f.data.status)).toEqual([ + 'open', + 'refused', + ]); }); }); }); diff --git a/api/src/slices/bridle/activity/activityWs.handler.ts b/api/src/slices/bridle/activity/activityWs.handler.ts index 4e14263e2..fd6c573d7 100644 --- a/api/src/slices/bridle/activity/activityWs.handler.ts +++ b/api/src/slices/bridle/activity/activityWs.handler.ts @@ -70,7 +70,7 @@ export class ActivityWsHandler this.stopListening?.(); } - handleConnection(client: Socket): void { + async handleConnection(client: Socket): Promise { const token = (client.handshake.auth as { token?: unknown } | undefined) ?.token; let payload: Record | null = null; @@ -90,6 +90,12 @@ export class ActivityWsHandler client.disconnect(true); return; } + // A disabled or deleted account's token still verifies until it + // expires; its feed does not open (RANCH-8, FR-009). + if (!(await this.reach.live(session).catch(() => false))) { + client.disconnect(true); + return; + } client.data = { clientId: identity.clientId, session }; this.open.set(client.id, client); client.on('disconnect', () => this.open.delete(client.id)); diff --git a/api/src/slices/bridle/bridle.acting.spec.ts b/api/src/slices/bridle/bridle.acting.spec.ts index e708b23ed..8c1cbf755 100644 --- a/api/src/slices/bridle/bridle.acting.spec.ts +++ b/api/src/slices/bridle/bridle.acting.spec.ts @@ -88,8 +88,14 @@ function makeHub(assistant?: { // The real reach rule over access lists that hide nothing (CLEAN-231): a // console person here reaches the agent, so what is tested stays the token. + // Every account here is there and enabled (RANCH-8 asks on every chat). + const access = openAccess(); + jest.spyOn(access, 'liveAccount').mockImplementation(async (id: string) => ({ + id, + role: UserRoleTypes.User, + })); const reach = new ConsoleReachService( - openAccess(), + access, agentGateway as never, permissionOver(agentGateway), ); @@ -477,7 +483,9 @@ describe('the hub mints no acting token for anyone else', () => { const client = await h.connect({ token: noSid }); await h.say(client, 'hi'); - expect(h.last()).not.toHaveProperty('acting'); + // Since RANCH-8 it is no chat identity at all: the handshake refuses it, + // and no message reaches the agent, with or without an acting token. + expect(h.last()).toBeUndefined(); }); it('refuses an acting token at the handshake: it is not a chat credential', async () => { diff --git a/api/src/slices/bridle/bridle.controller.spec.ts b/api/src/slices/bridle/bridle.controller.spec.ts index f41b84a65..cf16f7a88 100644 --- a/api/src/slices/bridle/bridle.controller.spec.ts +++ b/api/src/slices/bridle/bridle.controller.spec.ts @@ -434,7 +434,7 @@ describe('BridleController — rejected share tokens', () => { describe('BridleController — identity precedence', () => { it('lets a valid JWT win over share headers that ride along', async () => { const { controller, registered, shareCalls } = makeController({ - verify: () => ({ sub: 'user-1', roles: ['User'] }), + verify: () => ({ sub: 'user-1', sid: 'session-1', roles: ['User'] }), }); await controller.sendMessageSync( @@ -461,10 +461,12 @@ describe('BridleController — identity precedence', () => { return registered[0].clientId; }; - expect(await identityOf({ sub: 'user-1', roles: ['Owner'] })).toBe('admin'); - expect(await identityOf({ sub: 'user-9', roles: ['Admin'] })).toBe( - 'user-9', - ); + expect( + await identityOf({ sub: 'user-1', sid: 'session-1', roles: ['Owner'] }), + ).toBe('admin'); + expect( + await identityOf({ sub: 'user-9', sid: 'session-1', roles: ['Admin'] }), + ).toBe('user-9'); }); it('answers 404 to a console person whose access lists hide the agent, on both routes', async () => { @@ -607,7 +609,7 @@ describe('BridleController — requester travels into attachment expansion', () it('marks a console sender jwt', async () => { const { controller, expandCalls } = makeController({ - verify: () => ({ sub: 'user-1', roles: ['User'] }), + verify: () => ({ sub: 'user-1', sid: 'session-1', roles: ['User'] }), }); await controller.sendMessage( @@ -617,7 +619,12 @@ describe('BridleController — requester travels into attachment expansion', () ); expect(expandCalls).toEqual([ - { clientId: 'user-1', kind: 'jwt', user: { id: 'user-1' } }, + { + clientId: 'user-1', + kind: 'jwt', + user: { id: 'user-1' }, + console: { userId: 'user-1', sid: 'session-1', role: 'User' }, + }, ]); }); @@ -721,7 +728,7 @@ describe('BridleController — transcripts on a share channel', () => { it('lets a console user read any share channel', async () => { const { controller, fileCalls } = makeController({ - verify: () => ({ sub: 'user-1', roles: ['Admin'] }), + verify: () => ({ sub: 'user-1', sid: 'session-1', roles: ['Admin'] }), }); const out = await controller.transcript( @@ -860,7 +867,9 @@ describe('BridleController — transcripts on a share channel', () => { * refuses and changes nothing. It never reports a clean slate it did not make. */ describe('BridleController — closing a conversation', () => { - const OWNER = { verify: () => ({ sub: 'user-1', roles: ['Owner'] }) }; + const OWNER = { + verify: () => ({ sub: 'user-1', sid: 'session-1', roles: ['Owner'] }), + }; const BEARER = request({ authorization: 'Bearer jwt-token' }); const LIVE = 'data/sessions/bridle:admin.jsonl'; const TRANSCRIPT = '{"type":"user","data":{"text":"hi"}}\n'; @@ -1062,7 +1071,9 @@ describe('BridleController — transcripts on a jwt channel (CLEAN-175)', () => const OWN = 'wslid-A1234567'; const OTHER = 'wslid-B9999999'; const BEARER = request({ authorization: 'Bearer embed-token' }); - const asVisitor = { verify: () => ({ sub: OWN, roles: [], typ: 'embed' }) }; + const asVisitor = { + verify: () => ({ sub: OWN, sid: 'session-1', roles: [], typ: 'embed' }), + }; it('lets the owner read, reset and archive their own channel', async () => { const { controller, fileCalls } = makeController(asVisitor); @@ -1194,7 +1205,12 @@ describe('BridleController — transcripts on a jwt channel (CLEAN-175)', () => it('an embed token minted with an administrator’s role reads its own channel and no other', async () => { const { controller, fileCalls } = makeController({ - verify: () => ({ sub: 'kiosk', roles: ['Owner'], typ: 'embed' }), + verify: () => ({ + sub: 'kiosk', + sid: 'session-1', + roles: ['Owner'], + typ: 'embed', + }), }); await controller.transcript(AGENT, BEARER, { channel: 'kiosk' } as never); @@ -1241,8 +1257,16 @@ describe('BridleController — request limits', () => { const FULL = { rateLimited: { retryAfterMs: 41_200, window: 'minute' as const }, }; - const ownerToken = () => ({ sub: 'user-1', roles: ['Owner'] }); - const userToken = () => ({ sub: 'user-9', roles: ['User'] }); + const ownerToken = () => ({ + sub: 'user-1', + sid: 'session-1', + roles: ['Owner'], + }); + const userToken = () => ({ + sub: 'user-9', + sid: 'session-1', + roles: ['User'], + }); const WITH_TOKEN = { authorization: 'Bearer jwt-token' }; it('answers 429 with the wait on the fire-and-forget route', async () => { diff --git a/api/src/slices/bridle/domain/chatIdentity.allowlist.spec.ts b/api/src/slices/bridle/domain/chatIdentity.allowlist.spec.ts new file mode 100644 index 000000000..3c3a219e1 --- /dev/null +++ b/api/src/slices/bridle/domain/chatIdentity.allowlist.spec.ts @@ -0,0 +1,152 @@ +import { clientIdFromJwtPayload, consoleSessionOf } from './chatIdentity'; + +/** + * RANCH-8, audit §3 (`chatIdentity.ts:clientIdFromJwtPayload:purpose-token- + * as-chat-identity`). Every chat surface takes its identity from this one + * function: the HTTP message and transcript routes, the attachment guard, + * the /ws/client handshake and /ws/me. It used to accept any signed payload + * with a `sub`, so a token issued for one narrow job opened the person's + * conversations on every agent, past their access lists: the link to a + * browser session view (handed to the agent itself), the browser and + * integration extension tokens (a year long) and a single-file open link. + * + * It is an allowlist now (FR-006, FR-007): a person's console session, a + * chat embed token, or the agent's own token for its own side. Anything else + * is no identity, which every caller answers as a missing credential. + */ + +const SESSION = { sub: 'user-p', email: 'p@ranch.test', sid: 'sess-1' }; + +describe('clientIdFromJwtPayload accepts three kinds of credential (FR-006)', () => { + it('a console session: the Owner is `admin`, anyone else their id', () => { + expect(clientIdFromJwtPayload({ ...SESSION, roles: ['Owner'] })).toEqual({ + clientId: 'admin', + isAdmin: true, + }); + expect(clientIdFromJwtPayload({ ...SESSION, roles: ['Admin'] })).toEqual({ + clientId: 'user-p', + isAdmin: true, + }); + expect(clientIdFromJwtPayload({ ...SESSION, roles: ['User'] })).toEqual({ + clientId: 'user-p', + isAdmin: false, + }); + }); + + it('an embed token, as before', () => { + expect( + clientIdFromJwtPayload({ sub: 'wslid-A1', roles: [], typ: 'embed' }), + ).toEqual({ clientId: 'wslid-A1', isAdmin: false }); + }); + + it('the agent’s own token, for its own side', () => { + expect( + clientIdFromJwtPayload({ sub: 'agent:agent-1', roles: ['Owner'] }), + ).toEqual({ clientId: 'agent:agent-1', isAdmin: false }); + }); +}); + +describe('and nothing else: every purpose token is no identity (FR-007, FR-008)', () => { + const PURPOSE: [string, Record][] = [ + // As BrowserlessClient.buildVncUrl signs it, before and after RANCH-8. + ['browser view link', { sub: 'user-p', sid: 'bs-1', scope: 'browser:vnc' }], + [ + 'browser view link, typed', + { sub: 'user-p', sid: 'bs-1', scope: 'browser:vnc', typ: 'vnc' }, + ], + // As the browser extension's mint signs it. + [ + 'browser extension', + { + sub: 'user-p', + agentId: 'agent-1', + userId: 'user-p', + scope: 'browser:cookies', + }, + ], + [ + 'browser extension, typed', + { + sub: 'user-p', + agentId: 'agent-1', + userId: 'user-p', + scope: 'browser:cookies', + typ: 'ext-browser', + }, + ], + ['integration extension', { sub: 'user-o', scope: 'integration:cookies' }], + [ + 'integration extension, typed', + { sub: 'user-o', scope: 'integration:cookies', typ: 'ext-integration' }, + ], + // As OpenLinkService.mint signs it. + [ + 'single-file open link', + { sub: 'open-link', agentId: 'agent-1', path: 'notes.md', kind: 'text' }, + ], + [ + 'single-file open link, typed', + { + sub: 'open-link', + agentId: 'agent-1', + path: 'notes.md', + kind: 'text', + typ: 'open-link', + }, + ], + ]; + + it.each(PURPOSE)('%s', (_label, payload) => { + expect(clientIdFromJwtPayload(payload)).toBeNull(); + expect(consoleSessionOf(payload)).toBeNull(); + }); + + it('a purpose token never becomes a person by carrying roles too', () => { + expect( + clientIdFromJwtPayload({ + ...SESSION, + roles: ['Owner'], + scope: 'browser:vnc', + }), + ).toBeNull(); + expect( + clientIdFromJwtPayload({ ...SESSION, roles: ['User'], typ: 'vnc' }), + ).toBeNull(); + expect( + clientIdFromJwtPayload({ + sub: 'open-link', + sid: 's', + roles: ['User'], + }), + ).toBeNull(); + }); + + it('roles without a console session prove nobody', () => { + expect( + clientIdFromJwtPayload({ sub: 'user-p', roles: ['Owner'] }), + ).toBeNull(); + expect( + clientIdFromJwtPayload({ sub: 'user-p', roles: ['User'] }), + ).toBeNull(); + expect(clientIdFromJwtPayload({ roles: ['Owner'] })).toBeNull(); + }); + + it('an embed token that also names a scope proves nothing', () => { + expect( + clientIdFromJwtPayload({ + sub: 'wslid-A1', + roles: [], + typ: 'embed', + scope: 'browser:vnc', + }), + ).toBeNull(); + }); + + it('a call token too: the verifiers drop them first, this is the second wall', () => { + for (const typ of ['acting', 'handover']) { + expect( + clientIdFromJwtPayload({ ...SESSION, roles: ['Owner'], typ }), + ).toBeNull(); + } + }); +}); diff --git a/api/src/slices/bridle/domain/chatIdentity.spec.ts b/api/src/slices/bridle/domain/chatIdentity.spec.ts index 4a708431a..0d4f11711 100644 --- a/api/src/slices/bridle/domain/chatIdentity.spec.ts +++ b/api/src/slices/bridle/domain/chatIdentity.spec.ts @@ -38,15 +38,21 @@ describe('clientIdFromJwtPayload', () => { // Owner wrote and a message sent during a turn joined it with the power of // whoever started it. it('gives the Owner the conversation the administrators shared, and every Admin their own', () => { - expect(clientIdFromJwtPayload({ sub: 'u1', roles: ['Owner'] })).toEqual({ + expect( + clientIdFromJwtPayload({ sub: 'u1', sid: 's', roles: ['Owner'] }), + ).toEqual({ clientId: 'admin', isAdmin: true, }); - expect(clientIdFromJwtPayload({ sub: 'u2', roles: ['Admin'] })).toEqual({ + expect( + clientIdFromJwtPayload({ sub: 'u2', sid: 's', roles: ['Admin'] }), + ).toEqual({ clientId: 'u2', isAdmin: true, }); - expect(clientIdFromJwtPayload({ sub: 'u3', roles: ['Admin'] })).toEqual({ + expect( + clientIdFromJwtPayload({ sub: 'u3', sid: 's', roles: ['Admin'] }), + ).toEqual({ clientId: 'u3', isAdmin: true, }); @@ -54,27 +60,30 @@ describe('clientIdFromJwtPayload', () => { it('an Admin token with no sub proves nobody in particular, and is unusable', () => { expect(clientIdFromJwtPayload({ roles: ['Admin'] })).toBeNull(); - expect(clientIdFromJwtPayload({ sub: '', roles: ['Admin'] })).toBeNull(); + expect( + clientIdFromJwtPayload({ sub: '', sid: 's', roles: ['Admin'] }), + ).toBeNull(); }); it('an Admin never becomes the Owner’s client by naming themselves so', () => { expect( - clientIdFromJwtPayload({ sub: 'admin', roles: ['Admin'] }), + clientIdFromJwtPayload({ sub: 'admin', sid: 's', roles: ['Admin'] }), ).toBeNull(); }); it('uses the sub for everyone else', () => { - expect(clientIdFromJwtPayload({ sub: 'u1', roles: ['User'] })).toEqual({ + expect( + clientIdFromJwtPayload({ sub: 'u1', sid: 's', roles: ['User'] }), + ).toEqual({ clientId: 'u1', isAdmin: false, }); }); - it('admits an admin token that carries no sub', () => { - expect(clientIdFromJwtPayload({ roles: ['Owner'] })).toEqual({ - clientId: 'admin', - isAdmin: true, - }); + // RANCH-8: a person is a console session, which names its person. + it('refuses an admin token that carries no sub, or no session id', () => { + expect(clientIdFromJwtPayload({ sid: 's', roles: ['Owner'] })).toBeNull(); + expect(clientIdFromJwtPayload({ sub: 'u1', roles: ['Owner'] })).toBeNull(); }); it('never reads an agent’s service token as an administrator (CLEAN-232)', () => { @@ -87,12 +96,16 @@ describe('clientIdFromJwtPayload', () => { } // Its own client: not the shared one, and not another agent's. expect( - clientIdFromJwtPayload({ sub: 'agent:other', roles: ['Owner'] }) + clientIdFromJwtPayload({ sub: 'agent:other', sid: 's', roles: ['Owner'] }) ?.clientId, ).toBe('agent:other'); // A person whose id merely contains the word is still a person. expect( - clientIdFromJwtPayload({ sub: 'user-agent:1', roles: ['Owner'] }), + clientIdFromJwtPayload({ + sub: 'user-agent:1', + sid: 's', + roles: ['Owner'], + }), ).toEqual({ clientId: 'admin', isAdmin: true }); }); @@ -268,7 +281,9 @@ describe('reserved client ids (CLEAN-232)', () => { }); it('an admin is still `admin`, whatever the sub says', () => { - expect(clientIdFromJwtPayload({ sub: 'cron', roles: ['Owner'] })).toEqual({ + expect( + clientIdFromJwtPayload({ sub: 'cron', sid: 's', roles: ['Owner'] }), + ).toEqual({ clientId: 'admin', isAdmin: true, }); diff --git a/api/src/slices/bridle/domain/chatIdentity.ts b/api/src/slices/bridle/domain/chatIdentity.ts index 1895b1a41..0bb22212e 100644 --- a/api/src/slices/bridle/domain/chatIdentity.ts +++ b/api/src/slices/bridle/domain/chatIdentity.ts @@ -81,8 +81,11 @@ export function consoleSessionOf( payload: Record | null | undefined, ): IConsoleSession | null { if (!payload || payload.typ !== undefined) return null; + // A token issued for one job (RANCH-8) is no session, roles or not. + if (payload.scope !== undefined) return null; const sub = payload.sub; const sid = payload.sid; + if (sub === 'open-link') return null; if (typeof sub !== 'string' || !sub || sub.startsWith('agent:')) return null; if (typeof sid !== 'string' || !sid) return null; const roles = Array.isArray(payload.roles) @@ -217,23 +220,41 @@ export function isReservedClientId(id: string): boolean { export function clientIdFromJwtPayload( payload: Record | null | undefined, ): { clientId: string; isAdmin: boolean } | null { - const sub = payload?.sub; - const isAgent = typeof sub === 'string' && sub.startsWith('agent:'); - const roles = payload?.roles as string[] | undefined; - const holds = (role: string) => - !isAgent && Array.isArray(roles) && roles.includes(role); - const isAdmin = holds('Owner') || holds('Admin'); + // An allowlist (RANCH-8, FR-006/FR-007). Three kinds of credential speak + // as somebody in chat; every other signed token is no identity, which the + // callers answer exactly as a missing credential. A token issued for one + // narrow job (the browser view link, an extension's token, a file link) + // used to open the person's conversations on every agent, past their + // lists: those carry a `scope`, a purpose `typ` or no person at all. + if (!payload || payload.scope !== undefined) return null; + const sub = payload.sub; + if (typeof sub !== 'string' || !sub) return null; + const roles = Array.isArray(payload.roles) + ? (payload.roles as unknown[]) + : []; + const holds = (role: string) => roles.includes(role); - // A person's own token (no `typ`) that carries Owner. Not an embed token, - // which is whatever the holder of an API key asked it to be. - if (holds('Owner') && payload?.typ === undefined) { - return { clientId: OWNER_CLIENT_ID, isAdmin: true }; + // 1. A chat embed token: its `sub`, whatever roles it was minted with. One + // minted with Owner is not the Owner's conversation (CLEAN-236). + if (payload.typ === 'embed') { + if (isReservedClientId(sub)) return null; + return { clientId: sub, isAdmin: holds('Owner') || holds('Admin') }; } + if (payload.typ !== undefined) return null; - if (typeof sub !== 'string' || !sub) return null; - const ownServiceToken = isAgent && payload?.typ === undefined; - if (!ownServiceToken && isReservedClientId(sub)) return null; - return { clientId: sub, isAdmin }; + // 2. The agent's own service token, for its own side: its own client, + // never an administrator, whatever roles it carries (CLEAN-232). + if (sub.startsWith('agent:')) return { clientId: sub, isAdmin: false }; + + // 3. A person's own console session (`sid`, a person role): the Owner is + // `admin`, anyone else their id. + const session = consoleSessionOf(payload); + if (!session) return null; + if (session.role === 'Owner') { + return { clientId: OWNER_CLIENT_ID, isAdmin: true }; + } + if (isReservedClientId(sub)) return null; + return { clientId: sub, isAdmin: session.role === 'Admin' }; } /** diff --git a/api/src/slices/bridle/domain/consoleReach.service.spec.ts b/api/src/slices/bridle/domain/consoleReach.service.spec.ts index 364adb787..c82128a49 100644 --- a/api/src/slices/bridle/domain/consoleReach.service.spec.ts +++ b/api/src/slices/bridle/domain/consoleReach.service.spec.ts @@ -18,8 +18,12 @@ describe('ConsoleReachService.manages', () => { : { id, isAdmin: id === 'agent-ranch', createdById: null }, ), }; + // Every account is there and enabled here; RANCH-8 cases are below. + const live = { + liveAccount: (id: string) => Promise.resolve({ id, role: 'User' }), + }; const service = new ConsoleReachService( - {} as never, + live as never, agents as never, permissionOver(agents), ); @@ -58,3 +62,68 @@ describe('ConsoleReachService.manages', () => { expect(await service.manages(undefined, 'agent-a')).toBe(false); }); }); + +/** + * RANCH-8, FR-009. A console token outlives a disabled account until it + * expires; the chat surface asks whether the account is there and enabled + * before anything else, for every session, the Owner's included. + */ +describe('ConsoleReachService: a disabled or deleted account', () => { + const agents = { + findById: (id: string) => + Promise.resolve({ id, isAdmin: false, createdById: null }), + }; + const dead = new Set(['user-gone']); + const access = { + liveAccount: (id: string) => + Promise.resolve(dead.has(id) ? null : { id, role: 'User' }), + reaches: () => Promise.resolve(true), + onRemoved: jest.fn(() => () => undefined), + onDisabled: jest.fn(() => () => undefined), + }; + const service = new ConsoleReachService( + access as never, + agents as never, + permissionOver(agents), + ); + const session = (userId: string, role: UserRoleTypes): IConsoleSession => ({ + userId, + sid: 'session-1', + role, + }); + + it('is not admitted to any chat, whatever its role', async () => { + for (const role of [ + UserRoleTypes.Owner, + UserRoleTypes.Admin, + UserRoleTypes.User, + ]) { + expect(await service.admits(session('user-gone', role), 'agent-a')).toBe( + false, + ); + expect(await service.manages(session('user-gone', role), 'agent-a')).toBe( + false, + ); + } + }); + + it('a live account is admitted as before', async () => { + expect( + await service.admits(session('user-1', UserRoleTypes.User), 'agent-a'), + ).toBe(true); + expect( + await service.admits(session('user-1', UserRoleTypes.Owner), 'agent-a'), + ).toBe(true); + }); + + it('nobody without a session is asked: an embed token, a share visitor', async () => { + expect(await service.admits(null, 'agent-a')).toBe(true); + }); + + it('listens to disabled accounts as to deleted ones', () => { + const stop = service.onRemoved(() => undefined); + expect(access.onRemoved).toHaveBeenCalled(); + expect(access.onDisabled).toHaveBeenCalled(); + stop(); + }); +}); diff --git a/api/src/slices/bridle/domain/consoleReach.service.ts b/api/src/slices/bridle/domain/consoleReach.service.ts index faad41fef..9cad5b762 100644 --- a/api/src/slices/bridle/domain/consoleReach.service.ts +++ b/api/src/slices/bridle/domain/consoleReach.service.ts @@ -47,6 +47,7 @@ export class ConsoleReachService { agentId: string, ): Promise { if (!session) return false; + if (!(await this.live(session))) return false; const managed = await this.permission.manageable( { kind: 'person', @@ -67,11 +68,25 @@ export class ConsoleReachService { }); } - /** Whether this session may use the chat of that agent. */ + /** + * Whether the account behind a console session is there and enabled + * (RANCH-8, FR-009). A console token outlives a disabled account until it + * expires; nothing that reads it as a chat identity may. + */ + async live(session: IConsoleSession): Promise { + return (await this.access.liveAccount(session.userId)) !== null; + } + + /** + * Whether this session may use the chat of that agent. A session whose + * account is gone or disabled may not, the Owner's included: the rule is + * one for everybody (RANCH-8). + */ async admits( session: IConsoleSession | null | undefined, agentId: string, ): Promise { + if (session && !(await this.live(session))) return false; const subject = this.subjectOf(session); if (!subject) return true; if (!(await this.access.reaches(subject, agentId))) return false; @@ -88,9 +103,17 @@ export class ConsoleReachService { return reach.filter(items, agentIdOf); } - /** Called when an account was deleted; see `AgentAccessService`. */ + /** + * Called when an account was deleted or disabled (RANCH-8); see + * `AgentAccessService`. Either way everything it holds open is closed. + */ onRemoved(listener: (userId: string) => void): () => void { - return this.access.onRemoved(listener); + const stopRemoved = this.access.onRemoved(listener); + const stopDisabled = this.access.onDisabled(listener); + return () => { + stopRemoved(); + stopDisabled(); + }; } /** Called when an account's access changed; see `AgentAccessService`. */ diff --git a/api/src/slices/bridle/guards/bridleChatAuth.guard.spec.ts b/api/src/slices/bridle/guards/bridleChatAuth.guard.spec.ts index 727040574..5db7a9658 100644 --- a/api/src/slices/bridle/guards/bridleChatAuth.guard.spec.ts +++ b/api/src/slices/bridle/guards/bridleChatAuth.guard.spec.ts @@ -31,7 +31,9 @@ interface IStubs { function makeGuard(stubs: IStubs = {}) { const calls: Array<[string, string, string]> = []; const jwt = { - verify: stubs.verify ?? (() => ({ sub: 'user-1', roles: ['User'] })), + verify: + stubs.verify ?? + (() => ({ sub: 'user-1', sid: 'session-1', roles: ['User'] })), } as unknown as JwtService; const shareLinks = { authorizeChat: async ( @@ -84,7 +86,7 @@ describe('BridleChatAuthGuard — JWT callers', () => { // same function. The Owner keeps the conversation every administrator // shared; an Admin is their own client since CLEAN-236. const asOwner = makeGuard({ - verify: () => ({ sub: 'user-9', roles: ['Owner'] }), + verify: () => ({ sub: 'user-9', sid: 'session-1', roles: ['Owner'] }), }); const owner = makeContext({ authorization: 'Bearer jwt-token' }); await asOwner.guard.canActivate(owner.context); @@ -95,7 +97,7 @@ describe('BridleChatAuthGuard — JWT callers', () => { }); const asAdmin = makeGuard({ - verify: () => ({ sub: 'user-7', roles: ['Admin'] }), + verify: () => ({ sub: 'user-7', sid: 'session-1', roles: ['Admin'] }), }); const admin = makeContext({ authorization: 'Bearer jwt-token' }); await asAdmin.guard.canActivate(admin.context); @@ -381,3 +383,57 @@ describe('BridleChatAuthGuard — acting tokens (CLEAN-232)', () => { expect(req.user).toBeUndefined(); }); }); + +/** + * RANCH-8, audit §3: a token issued for one job is no chat credential. The + * attachment, source content and rating routes answer it exactly as a + * forged bearer: 401, nothing on the request. + */ +describe('BridleChatAuthGuard — purpose tokens (RANCH-8)', () => { + const PURPOSE: [string, Record][] = [ + ['browser view link', { sub: 'user-1', sid: 'bs-1', scope: 'browser:vnc' }], + [ + 'browser view link, typed', + { sub: 'user-1', sid: 'bs-1', scope: 'browser:vnc', typ: 'vnc' }, + ], + [ + 'browser extension', + { + sub: 'user-1', + agentId: 'agent-1', + userId: 'user-1', + scope: 'browser:cookies', + typ: 'ext-browser', + }, + ], + [ + 'integration extension', + { sub: 'user-1', scope: 'integration:cookies', typ: 'ext-integration' }, + ], + [ + 'file open link', + { + sub: 'open-link', + agentId: 'agent-1', + path: 'a.md', + kind: 'text', + typ: 'open-link', + }, + ], + ]; + + it.each(PURPOSE)( + '%s: 401, and the lists are never asked', + async (_label, payload) => { + const { guard, admits } = makeGuard({ verify: () => payload }); + const { context, req } = makeContext({ authorization: 'Bearer purpose' }); + const err = await guard.canActivate(context).catch((e: unknown) => e); + expect(err).toBeInstanceOf(UnauthorizedException); + expect((err as UnauthorizedException).getResponse()).toMatchObject({ + code: 'TOKEN_INVALID', + }); + expect(req.chatAuth).toBeUndefined(); + expect(admits).not.toHaveBeenCalled(); + }, + ); +}); diff --git a/api/src/slices/bridle/handlers/bridleClientWs.handler.spec.ts b/api/src/slices/bridle/handlers/bridleClientWs.handler.spec.ts index 6440a5ac1..af23b8452 100644 --- a/api/src/slices/bridle/handlers/bridleClientWs.handler.spec.ts +++ b/api/src/slices/bridle/handlers/bridleClientWs.handler.spec.ts @@ -385,7 +385,12 @@ describe('BridleClientWsHandler — handshake identity', () => { it('stores the JWT sub and kind "jwt" on the socket', async () => { const { handler, client, registered } = makeConnection({ auth: { agentId: 'agent-1', token: 'signed' }, - verify: () => ({ sub: 'u1', email: 'u1@example.test', roles: ['User'] }), + verify: () => ({ + sub: 'u1', + email: 'u1@example.test', + sid: 'session-1', + roles: ['User'], + }), }); await handler.handleConnection(client); @@ -396,6 +401,7 @@ describe('BridleClientWsHandler — handshake identity', () => { email: 'u1@example.test', isAdmin: false, kind: 'jwt', + console: { userId: 'u1', sid: 'session-1', role: 'User' }, }); expect(registered).toEqual([ { @@ -412,6 +418,7 @@ describe('BridleClientWsHandler — handshake identity', () => { verify: () => ({ sub: 'u2', email: 'boss@example.test', + sid: 'session-1', roles: ['Owner'], }), }); @@ -434,6 +441,7 @@ describe('BridleClientWsHandler — handshake identity', () => { verify: () => ({ sub: 'u2', email: 'boss@example.test', + sid: 'session-1', roles: ['Owner'], }), }); @@ -456,6 +464,7 @@ describe('BridleClientWsHandler — handshake identity', () => { verify: () => ({ sub: 'u2', email: 'boss@example.test', + sid: 'session-1', roles: ['Owner'], }), }); @@ -712,7 +721,7 @@ describe('BridleClientWsHandler — share-link handshake', () => { shareVisitor: 'v7', }, agent: PRIVATE_AGENT, - verify: () => ({ sub: 'u1', roles: ['User'] }), + verify: () => ({ sub: 'u1', sid: 'session-1', roles: ['User'] }), authorizeChat: admitVisitor, }); @@ -815,10 +824,10 @@ describe('BridleClientWsHandler — access lists (CLEAN-231)', () => { }); it('does not ask the lists about a token that is no console session', async () => { - // An embed token and a token with no session id name no person the - // lists apply to; a refusal here would lock visitors out. + // An embed token names no person the lists apply to; a refusal here + // would lock visitors out. (A token with roles and no session id is no + // chat identity at all since RANCH-8: see the allowlist spec.) for (const payload of [ - { sub: 'u1', roles: ['User'] }, { sub: 'u1', sid: 'session-1', roles: ['User'], typ: 'embed' }, ]) { const { handler, client, registered, admits } = makeConnection({ @@ -899,7 +908,7 @@ describe('BridleClientWsHandler — limit state at connect (CLEAN-224)', () => { it('tells an operator too, so their chat can say visitors are waiting', async () => { const { handler, client, emitted } = makeConnection({ auth: { agentId: 'agent-1', token: 'signed' }, - verify: () => ({ sub: 'u2', roles: ['Owner'] }), + verify: () => ({ sub: 'u2', sid: 'session-1', roles: ['Owner'] }), limit: FULL, }); @@ -911,7 +920,7 @@ describe('BridleClientWsHandler — limit state at connect (CLEAN-224)', () => { it('says nothing when no limit is full', async () => { const { handler, client, emitted } = makeConnection({ auth: { agentId: 'agent-1', token: 'signed' }, - verify: () => ({ sub: 'u1', roles: ['User'] }), + verify: () => ({ sub: 'u1', sid: 'session-1', roles: ['User'] }), }); await handler.handleConnection(client); @@ -1003,3 +1012,38 @@ describe('BridleClientWsHandler — a deleted account’s sockets', () => { expect(admits).not.toHaveBeenCalled(); }); }); + +/** + * RANCH-8, audit §3: the live stream, its replay buffer and the sends of a + * socket open only for a chat credential. A purpose token gets the answer a + * forged token gets. + */ +describe('BridleClientWsHandler — purpose tokens (RANCH-8)', () => { + it.each([ + ['browser view link', { sub: 'u1', sid: 'bs-1', scope: 'browser:vnc' }], + [ + 'browser extension', + { sub: 'u1', agentId: 'agent-1', userId: 'u1', scope: 'browser:cookies' }, + ], + [ + 'integration extension', + { sub: 'u1', scope: 'integration:cookies', typ: 'ext-integration' }, + ], + [ + 'file open link', + { sub: 'open-link', agentId: 'agent-1', path: 'a.md', typ: 'open-link' }, + ], + ])('%s is refused at the handshake', async (_label, payload) => { + const { handler, client, emitted, registered } = makeConnection({ + auth: { agentId: 'agent-1', token: 'signed' }, + origin: 'https://embed.test', + agent: { isPublic: false, allowedOrigins: [] }, + verify: () => payload, + }); + + await handler.handleConnection(client); + + expect(registered).toHaveLength(0); + expect(emitted[0].payload).toMatchObject({ code: 'INVALID_TOKEN' }); + }); +}); diff --git a/api/src/slices/browser/browser.extension.controller.spec.ts b/api/src/slices/browser/browser.extension.controller.spec.ts index 6b8a585f2..c93090485 100644 --- a/api/src/slices/browser/browser.extension.controller.spec.ts +++ b/api/src/slices/browser/browser.extension.controller.spec.ts @@ -56,7 +56,23 @@ function harness(accounts: IAccount[]) { 'Bearer extension-token', ); }; - return { lists, importAs, importStorageState, accounts, controller, bridle }; + /** Any claims, as a token from before or after RANCH-8 carries them. */ + const importWith = (c: Record) => { + claims = c; + return controller.importState( + { profile: 'default', cookies: [], origins: [] } as never, + 'Bearer extension-token', + ); + }; + return { + lists, + importAs, + importWith, + importStorageState, + accounts, + controller, + bridle, + }; } const admin = (): IAccount => ({ @@ -191,15 +207,26 @@ describe('BrowserExtensionController — whose cookies', () => { const { controller } = harness([admin()]); const mint = (user: Record) => controller - .issueToken({ agentId: 'agent-a', userId: 'admin' } as never, { - user, - } as never) + .issueToken( + { agentId: 'agent-a', userId: 'admin' } as never, + { + user, + } as never, + ) .then((r) => JSON.parse(r.token) as Record); await expect( - mint({ sub: 'user-admin', roles: [UserRoleTypes.Admin] }), + mint({ + sub: 'user-admin', + sid: 'session-1', + roles: [UserRoleTypes.Admin], + }), ).resolves.toMatchObject({ sub: 'user-admin', userId: 'user-admin' }); await expect( - mint({ sub: 'user-owner', roles: [UserRoleTypes.Owner] }), + mint({ + sub: 'user-owner', + sid: 'session-1', + roles: [UserRoleTypes.Owner], + }), ).resolves.toMatchObject({ userId: 'admin' }); // A token that proves no person mints nothing. await expect(mint({ roles: [UserRoleTypes.User] })).rejects.toBeInstanceOf( @@ -207,3 +234,46 @@ describe('BrowserExtensionController — whose cookies', () => { ); }); }); + +/** + * RANCH-8 (FR-007, FR-008). The extension token names its job in `typ`. Its + * own endpoint takes it with that `typ`, and without one (a token minted + * before the change, good until it expires), never with another's. + */ +describe('BrowserExtensionController: the token’s purpose (RANCH-8)', () => { + it('mints `typ: ext-browser`', async () => { + const { controller } = harness([admin()]); + const minted = await controller.issueToken( + { agentId: 'agent-a' } as never, + { + user: { sub: 'user-admin', sid: 's', roles: [UserRoleTypes.Admin] }, + } as never, + ); + expect(JSON.parse(minted.token)).toMatchObject({ + scope: 'browser:cookies', + typ: 'ext-browser', + }); + }); + + it('accepts its own typ, and none; refuses another', async () => { + for (const [typ, ok] of [ + ['ext-browser', true], + [undefined, true], + ['ext-integration', false], + ['vnc', false], + ['open-link', false], + ['embed', false], + ] as const) { + const h = harness([admin()]); + const run = h.importWith({ + sub: 'user-admin', + agentId: 'agent-a', + userId: 'user-admin', + scope: 'browser:cookies', + ...(typ ? { typ } : {}), + }); + if (ok) await expect(run).resolves.toBeDefined(); + else await expect(run).rejects.toBeInstanceOf(UnauthorizedException); + } + }); +}); diff --git a/api/src/slices/browser/browser.extension.controller.ts b/api/src/slices/browser/browser.extension.controller.ts index bcca94b86..1228d1745 100644 --- a/api/src/slices/browser/browser.extension.controller.ts +++ b/api/src/slices/browser/browser.extension.controller.ts @@ -50,6 +50,8 @@ interface IExtensionTokenPayload { */ userId: string; scope: 'browser:cookies'; + /** What the token is for (RANCH-8); absent on tokens from before. */ + typ?: 'ext-browser'; iat: number; exp: number; } @@ -115,6 +117,7 @@ export class BrowserExtensionController { agentId: dto.agentId, userId: identity.clientId, scope: 'browser:cookies', + typ: 'ext-browser', } satisfies Omit, { expiresIn: `${ttlDays} days` }, ); @@ -187,7 +190,12 @@ export class BrowserExtensionController { this.logger.warn(`Extension token rejected: ${(err as Error).message}`); throw new UnauthorizedException('Invalid extension token'); } - if (payload.scope !== 'browser:cookies') { + // Its own `typ`, or none on a token from before RANCH-8: never another + // purpose's token, nor a sign-in that happens to carry the scope. + if ( + payload.scope !== 'browser:cookies' || + (payload.typ !== undefined && payload.typ !== 'ext-browser') + ) { throw new UnauthorizedException( 'Token scope mismatch — expected browser:cookies', ); diff --git a/api/src/slices/browser/data/browserless.client.spec.ts b/api/src/slices/browser/data/browserless.client.spec.ts index 701e4b303..ca68f8c52 100644 --- a/api/src/slices/browser/data/browserless.client.spec.ts +++ b/api/src/slices/browser/data/browserless.client.spec.ts @@ -156,7 +156,13 @@ describe('BrowserlessClient', () => { const vnc = client.buildVncUrl('alice', 'browser-abc-123'); expect(jwt.sign).toHaveBeenCalledWith( - { sub: 'alice', sid: 'browser-abc-123', scope: 'browser:vnc' }, + { + sub: 'alice', + sid: 'browser-abc-123', + scope: 'browser:vnc', + // RANCH-8: the job it is for; the proxy reads only `scope`. + typ: 'vnc', + }, { expiresIn: '15m' }, ); // The default template puts the session id and signed token into the diff --git a/api/src/slices/browser/data/browserless.client.ts b/api/src/slices/browser/data/browserless.client.ts index e83593a3a..efec719c9 100644 --- a/api/src/slices/browser/data/browserless.client.ts +++ b/api/src/slices/browser/data/browserless.client.ts @@ -141,8 +141,10 @@ export class BrowserlessClient { * swap the image (browserless, steel-browser, etc.) without code changes. */ buildVncUrl(userId: string, sessionId: string): string { + // `typ` names the job (RANCH-8): a browser view, no sign-in. The proxy + // checks `scope` and ignores the rest; every chat path refuses it. const token = this.jwt.sign( - { sub: userId, sid: sessionId, scope: 'browser:vnc' }, + { sub: userId, sid: sessionId, scope: 'browser:vnc', typ: 'vnc' }, { expiresIn: '15m' }, ); const path = this.vncUrlTemplate diff --git a/api/src/slices/chat/myChat.controller.spec.ts b/api/src/slices/chat/myChat.controller.spec.ts index 3aca2b187..28eb0149a 100644 --- a/api/src/slices/chat/myChat.controller.spec.ts +++ b/api/src/slices/chat/myChat.controller.spec.ts @@ -132,7 +132,11 @@ const req = ( acceptLanguage?: string, ) => ({ - user: sub ? ({ sub, roles, email: '' } as IAuthTokenPayload) : undefined, + // A console token carries its session id (RANCH-8: no chat identity + // without it). + user: sub + ? ({ sub, roles, email: '', sid: 'session-1' } as IAuthTokenPayload) + : undefined, headers: acceptLanguage ? { 'accept-language': acceptLanguage } : {}, }) as Request & { user?: IAuthTokenPayload }; diff --git a/api/src/slices/integration/integration.extension.controller.spec.ts b/api/src/slices/integration/integration.extension.controller.spec.ts index 1ebb6204a..889f0eef9 100644 --- a/api/src/slices/integration/integration.extension.controller.spec.ts +++ b/api/src/slices/integration/integration.extension.controller.spec.ts @@ -12,28 +12,51 @@ import type { IntegrationService } from './domain/integration.service'; * again on every use, as the browser import does: the minting account must * still be there, not disabled, and still allowed to mint the token. */ -function harness(accounts: { id: string; role: UserRoleTypes; status: string }[]) { +function harness( + accounts: { id: string; role: UserRoleTypes; status: string }[], +) { const users = { - findById: (id: string) => Promise.resolve(accounts.find((a) => a.id === id) ?? null), + findById: (id: string) => + Promise.resolve(accounts.find((a) => a.id === id) ?? null), } as unknown as IUserGateway; - const access = new AgentAccessService(new MemoryAgentAccessGateway([]), users); - const connectAndImport = jest - .fn() - .mockResolvedValue({ id: 'acc-1', service: 'instagram', accountKey: 'main' }); + const access = new AgentAccessService( + new MemoryAgentAccessGateway([]), + users, + ); + const connectAndImport = jest.fn().mockResolvedValue({ + id: 'acc-1', + service: 'instagram', + accountKey: 'main', + }); const service = { connectAndImport } as unknown as IntegrationService; let sub = ''; + // RANCH-8: the token names its job in `typ`; one from before has none. + let typ: string | undefined; const jwt = { - verify: () => ({ sub, scope: 'integration:cookies' }), + verify: () => ({ + sub, + scope: 'integration:cookies', + ...(typ ? { typ } : {}), + }), } as unknown as JwtService; const controller = new IntegrationExtensionController(service, jwt, access); const importAs = (who: string) => { sub = who; return controller.importState( - { service: 'instagram', accountKey: 'main', cookies: [], origins: [] } as never, + { + service: 'instagram', + accountKey: 'main', + cookies: [], + origins: [], + } as never, 'Bearer extension-token', ); }; - return { importAs, connectAndImport }; + const importTyped = (who: string, kind: string | undefined) => { + typ = kind; + return importAs(who); + }; + return { importAs, importTyped, connectAndImport }; } describe('IntegrationExtensionController.importState', () => { @@ -47,11 +70,46 @@ describe('IntegrationExtensionController.importState', () => { it.each([ ['deleted', []], - ['disabled', [{ id: 'u-admin', role: UserRoleTypes.Admin, status: 'disabled' }]], - ['demoted to User', [{ id: 'u-admin', role: UserRoleTypes.User, status: 'active' }]], - ])('refuses an account that was %s since the token was minted', async (_, accounts) => { - const { importAs, connectAndImport } = harness(accounts); - await expect(importAs('u-admin')).rejects.toBeInstanceOf(UnauthorizedException); + [ + 'disabled', + [{ id: 'u-admin', role: UserRoleTypes.Admin, status: 'disabled' }], + ], + [ + 'demoted to User', + [{ id: 'u-admin', role: UserRoleTypes.User, status: 'active' }], + ], + ])( + 'refuses an account that was %s since the token was minted', + async (_, accounts) => { + const { importAs, connectAndImport } = harness(accounts); + await expect(importAs('u-admin')).rejects.toBeInstanceOf( + UnauthorizedException, + ); + expect(connectAndImport).not.toHaveBeenCalled(); + }, + ); +}); + +describe('IntegrationExtensionController: the token’s purpose (RANCH-8)', () => { + const admin = [ + { id: 'u-admin', role: UserRoleTypes.Admin, status: 'active' }, + ]; + + it('takes its own typ, and none (a token from before)', async () => { + const { importTyped } = harness(admin); + await expect( + importTyped('u-admin', 'ext-integration'), + ).resolves.toBeDefined(); + await expect(importTyped('u-admin', undefined)).resolves.toBeDefined(); + }); + + it('refuses another purpose’s token that carries the same scope', async () => { + const { importTyped, connectAndImport } = harness(admin); + for (const kind of ['ext-browser', 'vnc', 'open-link', 'embed']) { + await expect(importTyped('u-admin', kind)).rejects.toBeInstanceOf( + UnauthorizedException, + ); + } expect(connectAndImport).not.toHaveBeenCalled(); }); }); diff --git a/api/src/slices/integration/integration.extension.controller.ts b/api/src/slices/integration/integration.extension.controller.ts index 9ac7f2d9c..74756c8e9 100644 --- a/api/src/slices/integration/integration.extension.controller.ts +++ b/api/src/slices/integration/integration.extension.controller.ts @@ -24,10 +24,7 @@ import * as archiver from 'archiver'; import { Request, Response } from 'express'; import { IAuthTokenPayload } from '#/user/auth/domain/auth.types'; import { JwtAuthGuard, Public } from '#/user/auth/guards'; -import { - hasAtLeastRole, - UserRoleTypes, -} from '#/user/user/domain/user.types'; +import { hasAtLeastRole, UserRoleTypes } from '#/user/user/domain/user.types'; import { AgentAccessService } from '#/user/agentAccess/domain/agentAccess.service'; import { IntegrationService } from './domain/integration.service'; import { @@ -42,6 +39,8 @@ interface IIntegrationExtensionTokenPayload { /** Ranch user that minted the token (audit/replay). Owns the imported cookies. */ sub: string; scope: 'integration:cookies'; + /** What the token is for (RANCH-8); absent on tokens from before. */ + typ?: 'ext-integration'; iat: number; exp: number; } @@ -85,6 +84,7 @@ export class IntegrationExtensionController { { sub: req.user.sub, scope: 'integration:cookies', + typ: 'ext-integration', } satisfies Omit, { expiresIn: `${ttlDays} days` }, ); @@ -193,7 +193,11 @@ export class IntegrationExtensionController { this.logger.warn(`Extension token rejected: ${(err as Error).message}`); throw new UnauthorizedException('Invalid extension token'); } - if (payload.scope !== 'integration:cookies') { + // Its own `typ`, or none on a token from before RANCH-8. + if ( + payload.scope !== 'integration:cookies' || + (payload.typ !== undefined && payload.typ !== 'ext-integration') + ) { throw new UnauthorizedException( 'Token scope mismatch — expected integration:cookies', ); diff --git a/api/src/slices/stats/myStats.controller.spec.ts b/api/src/slices/stats/myStats.controller.spec.ts index d0a086dfd..dade80fa9 100644 --- a/api/src/slices/stats/myStats.controller.spec.ts +++ b/api/src/slices/stats/myStats.controller.spec.ts @@ -39,7 +39,13 @@ const req = ( ): AuthedRequest => ({ user: sub - ? ({ sub, roles, email: '', ...extra } as IAuthTokenPayload) + ? ({ + sub, + roles, + email: '', + sid: 'session-1', + ...extra, + } as IAuthTokenPayload) : undefined, }) as AuthedRequest; diff --git a/api/src/slices/stats/stats.tool.spec.ts b/api/src/slices/stats/stats.tool.spec.ts index 85a3bed6f..d03242ad6 100644 --- a/api/src/slices/stats/stats.tool.spec.ts +++ b/api/src/slices/stats/stats.tool.spec.ts @@ -235,7 +235,12 @@ describe('get_my_stats: whose statistics', () => { it('answers a person on their own console token as that person', async () => { const { tool, forPerson } = recording(); const own = { - user: { sub: 'user-9', email: '', roles: [UserRoleTypes.User] }, + user: { + sub: 'user-9', + email: '', + sid: 'session-1', + roles: [UserRoleTypes.User], + }, } as unknown as Request; await tool.getMyStats({}, undefined, own); @@ -387,7 +392,12 @@ describe('get_my_stats: what it asks for and what it answers', () => { const viaRoute = await new MyStatsController(service).get( { period: 7, tz: 'Europe/Kyiv' }, { - user: { sub: 'user-7', email: '', roles: [UserRoleTypes.User] }, + user: { + sub: 'user-7', + email: '', + sid: 'session-1', + roles: [UserRoleTypes.User], + }, } as never, ); @@ -690,7 +700,12 @@ describe('get_installation_stats: who may ask, and for which agents', () => { it('refuses a User on their own console token, and a plain agent acting for itself', async () => { const { tool, forCaller } = recording(); const own = { - user: { sub: 'user-9', email: '', roles: [UserRoleTypes.User] }, + user: { + sub: 'user-9', + email: '', + sid: 'session-1', + roles: [UserRoleTypes.User], + }, } as unknown as Request; const plainAgent = asTrustedAgent({ user: { sub: 'agent:helper', email: '', roles: [UserRoleTypes.Agent] }, @@ -734,7 +749,12 @@ describe('get_installation_stats: who may ask, and for which agents', () => { it('answers an Admin on their own console token as that Admin', async () => { const { tool, forCaller } = recording(); const own = { - user: { sub: 'admin-9', email: '', roles: [UserRoleTypes.Admin] }, + user: { + sub: 'admin-9', + email: '', + sid: 'session-1', + roles: [UserRoleTypes.Admin], + }, } as unknown as Request; await tool.getInstallationStats({}, undefined, own); @@ -831,7 +851,7 @@ describe('get_installation_stats: who may ask, and for which agents', () => { ), ); const viaRoute = await new InstallationStatsController(service).get({}, { - user: { sub: ADMIN.id, email: '', roles: [ADMIN.role] }, + user: { sub: ADMIN.id, email: '', sid: 'session-1', roles: [ADMIN.role] }, } as never); expect(mine).not.toContain('a2'); diff --git a/api/src/slices/user/auth/domain/auth.types.ts b/api/src/slices/user/auth/domain/auth.types.ts index 60919f07a..4ece991b4 100644 --- a/api/src/slices/user/auth/domain/auth.types.ts +++ b/api/src/slices/user/auth/domain/auth.types.ts @@ -34,7 +34,15 @@ export interface IAuthTokenPayload { * token it is read from a tool call's `_meta` and from the A2A message it * arrives in, and every verifier of a bearer refuses it. */ - typ?: 'embed' | 'acting' | 'handover'; + /** + * The purpose tokens (RANCH-8): each issued for one narrow job and + * accepted by the endpoints of that job alone. `'vnc'`: the link to a + * browser session view. `'ext-browser'` / `'ext-integration'`: the + * browser and integration extension tokens. `'open-link'`: one stored + * file. None is a sign-in: every bearer verifier and every chat path + * refuses them. + */ + typ?: 'embed' | 'acting' | 'handover' | PurposeTokenTypes; /** * Acting and hand-over tokens only: `agent:` of the one agent the * token was minted for. A token carried to another agent's runtime is @@ -43,6 +51,25 @@ export interface IAuthTokenPayload { aud?: string; } +/** What a purpose token is for (RANCH-8): its `typ`. */ +export const PURPOSE_TOKEN_TYPES = [ + 'vnc', + 'ext-browser', + 'ext-integration', + 'open-link', +] as const; +export type PurposeTokenTypes = (typeof PURPOSE_TOKEN_TYPES)[number]; + +/** + * True for a token issued for one narrow job (RANCH-8, FR-007): it names + * its purpose in `typ` and is no credential anywhere else. + */ +export function isPurposeToken(payload: unknown): boolean { + if (typeof payload !== 'object' || payload === null) return false; + const typ = (payload as { typ?: unknown }).typ; + return (PURPOSE_TOKEN_TYPES as readonly unknown[]).includes(typ); +} + /** True for a verified payload that `mintEmbedToken` produced. */ export function isEmbedToken(payload: unknown): boolean { return ( @@ -110,6 +137,13 @@ export type ICallerParty = userId: string; role: UserRoleTypes; grantedThroughAssistant?: true; + /** + * With `grantedThroughAssistant` only: who ticked the ability in the + * custom pick in force, when it was not the Owner (RANCH-8, FR-014). + * The ability then works only on agents that account reaches at the + * time of the call. Absent for the Owner's pick. + */ + grantedBy?: string; } | { kind: 'trusted' } | { @@ -198,3 +232,42 @@ export function classifyJwtError(err: unknown): AuthErrorCode { ? AuthErrorCodes.TokenExpired : AuthErrorCodes.TokenInvalid; } + +// ── An ability that does not cover an agent (RANCH-8) ─────── + +const GRANT_NOT_COVERING = 'ranchGrantNotCovering'; + +/** + * Note on the party of one tool call that the ability the assistant setting + * gave it does not cover `agent`, and for that reason alone: the agent + * exists, the person reaches it, the tool was ticked for them, and the + * account that ticked it does not reach the agent today (FR-014). Written by + * `AgentPermissionService.canManage`, read by `agentNotFound`, which says so + * in words that name neither that account nor what it reaches (FR-017). Not + * enumerable: it never travels as part of the party. + */ +export function noteGrantNotCovering( + party: ICallerParty, + agent: { id: string; name?: string | null }, +): void { + Object.defineProperty(party, GRANT_NOT_COVERING, { + value: { id: agent.id, name: String(agent.name ?? '') }, + enumerable: false, + configurable: true, + writable: true, + }); +} + +/** What `noteGrantNotCovering` noted on this party, or null. */ +export function grantNotCoveringOf( + party: ICallerParty | null | undefined, +): { id: string; name: string } | null { + const noted = (party as unknown as Record | null)?.[ + GRANT_NOT_COVERING + ]; + if (typeof noted !== 'object' || noted === null) return null; + const { id, name } = noted as { id?: unknown; name?: unknown }; + return typeof id === 'string' && id + ? { id, name: typeof name === 'string' ? name : '' } + : null; +} diff --git a/api/src/slices/user/auth/guards/jwtAuth.guard.ts b/api/src/slices/user/auth/guards/jwtAuth.guard.ts index 86adf5668..b7540f13c 100644 --- a/api/src/slices/user/auth/guards/jwtAuth.guard.ts +++ b/api/src/slices/user/auth/guards/jwtAuth.guard.ts @@ -13,6 +13,7 @@ import { IAuthTokenPayload, isCallToken, isEmbedToken, + isPurposeToken, unauthorized, } from '../domain/auth.types'; import { PUBLIC_METADATA_KEY } from './public.decorator'; @@ -95,6 +96,15 @@ export class JwtAuthGuard implements CanActivate { ); throw unauthorized(AuthErrorCodes.TokenInvalid); } + if (isPurposeToken(payload)) { + // A token issued for one job (a browser view, an extension, a file + // link) is no sign-in (RANCH-8, FR-007). Untyped ones from before were + // already refused by the role guard, having no role. + this.logger.warn( + `Rejected ${String(payload.typ)} token as a bearer ${req.method} ${req.url}`, + ); + throw unauthorized(AuthErrorCodes.TokenInvalid); + } req.user = payload; return true; } diff --git a/api/src/slices/user/auth/guards/purposeTokens.spec.ts b/api/src/slices/user/auth/guards/purposeTokens.spec.ts new file mode 100644 index 000000000..524e5d64b --- /dev/null +++ b/api/src/slices/user/auth/guards/purposeTokens.spec.ts @@ -0,0 +1,118 @@ +import { UnauthorizedException } from '@nestjs/common'; +import type { ExecutionContext } from '@nestjs/common'; +import { Reflector } from '@nestjs/core'; +import { JwtService } from '@nestjs/jwt'; +import { OpenLinkService } from '#/agent/file/domain/openLink.service'; +import { JwtAuthGuard } from './jwtAuth.guard'; +import { + PURPOSE_TOKEN_TYPES, + isPurposeToken, + type IAuthTokenPayload, +} from '../domain/auth.types'; + +/** + * RANCH-8, audit §3 (FR-007, FR-008). Every token issued for one narrow job + * names that job in `typ` and is no sign-in anywhere else: the console + * routes refuse it as they refuse an embed or a call token, and the chat + * paths do (chatIdentity.allowlist.spec.ts). Its own endpoint takes it with + * its own `typ`, or with none (a token issued before the change, good until + * it expires), never with another's. + */ + +function guard(payload: Record) { + const jwt = { + verify: () => payload as unknown as IAuthTokenPayload, + decode: () => ({ + sub: typeof payload.sub === 'string' ? payload.sub : '', + }), + } as unknown as JwtService; + const reflector = { getAllAndOverride: () => false } as unknown as Reflector; + return new JwtAuthGuard(jwt, reflector); +} + +function context() { + const req = { + headers: { authorization: 'Bearer purpose' }, + method: 'GET', + url: '/users', + } as { user?: IAuthTokenPayload }; + return { + req, + context: { + switchToHttp: () => ({ getRequest: () => req }), + getHandler: () => undefined, + getClass: () => undefined, + } as unknown as ExecutionContext, + }; +} + +describe('purpose tokens on console routes (JwtAuthGuard)', () => { + it.each(PURPOSE_TOKEN_TYPES)( + '`typ: %s` is 401 TOKEN_INVALID, nothing on the request', + (typ) => { + // Roles on it change nothing: a purpose is not a sign-in. + const g = guard({ sub: 'user-1', roles: ['Owner'], sid: 's', typ }); + const { context: ctx, req } = context(); + let code: string | undefined; + try { + g.canActivate(ctx); + } catch (err) { + if (!(err instanceof UnauthorizedException)) throw err; + code = (err.getResponse() as { code?: string }).code; + } + expect(code).toBe('TOKEN_INVALID'); + expect(req.user).toBeUndefined(); + }, + ); + + it('a console session still passes', () => { + const g = guard({ sub: 'user-1', roles: ['User'], sid: 's' }); + const { context: ctx, req } = context(); + expect(g.canActivate(ctx)).toBe(true); + expect(req.user?.sub).toBe('user-1'); + }); + + it('isPurposeToken knows the four and nothing else', () => { + for (const typ of PURPOSE_TOKEN_TYPES) { + expect(isPurposeToken({ typ })).toBe(true); + } + for (const typ of [undefined, 'embed', 'acting', 'handover', 'other']) { + expect(isPurposeToken({ typ })).toBe(false); + } + expect(isPurposeToken(null)).toBe(false); + }); +}); + +describe('the single-file open link names its job (OpenLinkService)', () => { + const jwt = new JwtService({ secret: 'test' }); + const links = new OpenLinkService(jwt); + + it('mints `typ: open-link`', () => { + const { token } = links.mint('agent-1', 'notes.md', 'text'); + expect(jwt.decode<{ typ?: string }>(token)?.typ).toBe('open-link'); + }); + + it('opens a link from before the change, which has no typ', () => { + const old = jwt.sign( + { sub: 'open-link', agentId: 'agent-1', path: 'notes.md', kind: 'text' }, + { expiresIn: 60 }, + ); + expect(links.verify(old).path).toBe('notes.md'); + }); + + it('refuses a token of another purpose that names the same subject', () => { + for (const typ of ['vnc', 'ext-browser', 'embed']) { + const other = jwt.sign( + { + sub: 'open-link', + typ, + agentId: 'agent-1', + path: 'notes.md', + kind: 'text', + }, + { expiresIn: 60 }, + ); + expect(() => links.verify(other)).toThrow(UnauthorizedException); + } + }); +}); From ccdd9ddd02c6714942bdcf353e18d75039e091f5 Mon Sep 17 00:00:00 2001 From: "Maksym Hryzodub [DREAM]" Date: Tue, 1 Dec 2026 14:46:42 +0200 Subject: [PATCH 04/13] fix(api): stored secrets stay write-only through the workspace files (RANCH-8) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Audit §2. Every caller-facing file surface holds WorkspaceFiles instead of the raw gateway: data/secrets/, data/channels/, data/channels.json and browser-state/ are left out of lists, refused on read, write, delete and open link however the path is spelled, skipped by folder deletes and exports (with a note in the archive) and never written or removed by an import. The census refuses a route or tool that holds the raw gateway unless filed. Co-Authored-By: Claude --- .../file/data/file.gateway.export.spec.ts | 126 +++++++++ .../slices/agent/file/data/file.gateway.ts | 18 +- .../slices/agent/file/domain/file.gateway.ts | 12 +- .../file/domain/fileProposal.service.spec.ts | 3 +- .../agent/file/domain/fileProposal.service.ts | 4 +- api/src/slices/agent/file/domain/index.ts | 2 + .../agent/file/domain/openLink.service.ts | 18 +- .../file/domain/secretStorePaths.spec.ts | 107 ++++++++ .../agent/file/domain/secretStorePaths.ts | 81 ++++++ .../file/domain/syncGuard.service.spec.ts | 25 +- .../agent/file/domain/syncGuard.service.ts | 4 +- .../domain/workspaceArchive.service.spec.ts | 106 +++++++- .../file/domain/workspaceArchive.service.ts | 25 +- .../agent/file/domain/workspaceFiles.spec.ts | 175 +++++++++++++ .../agent/file/domain/workspaceFiles.ts | 209 +++++++++++++++ .../agent/file/file.controller.raw.spec.ts | 3 +- .../slices/agent/file/file.controller.spec.ts | 231 ++++++++++++++++ api/src/slices/agent/file/file.controller.ts | 25 +- api/src/slices/agent/file/file.module.ts | 4 + .../agent/file/file.tool.proposals.spec.ts | 3 +- api/src/slices/agent/file/file.tool.spec.ts | 3 +- api/src/slices/agent/file/file.tool.ts | 38 ++- .../agent/file/fileImport.controller.spec.ts | 7 +- .../agent/file/fileImport.controller.ts | 5 +- api/src/slices/mcp/tool-secrets.files.spec.ts | 246 ++++++++++++++++++ .../setup/writeOnly/writeOnly.census.spec.ts | 64 +++++ 26 files changed, 1488 insertions(+), 56 deletions(-) create mode 100644 api/src/slices/agent/file/data/file.gateway.export.spec.ts create mode 100644 api/src/slices/agent/file/domain/secretStorePaths.spec.ts create mode 100644 api/src/slices/agent/file/domain/secretStorePaths.ts create mode 100644 api/src/slices/agent/file/domain/workspaceFiles.spec.ts create mode 100644 api/src/slices/agent/file/domain/workspaceFiles.ts create mode 100644 api/src/slices/agent/file/file.controller.spec.ts create mode 100644 api/src/slices/mcp/tool-secrets.files.spec.ts diff --git a/api/src/slices/agent/file/data/file.gateway.export.spec.ts b/api/src/slices/agent/file/data/file.gateway.export.spec.ts new file mode 100644 index 000000000..9ea700138 --- /dev/null +++ b/api/src/slices/agent/file/data/file.gateway.export.spec.ts @@ -0,0 +1,126 @@ +import * as unzipper from 'unzipper'; +import { S3FileGateway } from './file.gateway'; +import { ISettingGateway } from '#/setting/domain'; +import { + SECRET_STORES_NOTE, + SECRET_STORES_NOTE_PATH, + isSecretStorePath, +} from '../domain/secretStorePaths'; + +/** + * RANCH-8, audit §2: an export leaves the secret stores out without reading + * them, and says so in the archive. The S3 client is a stand-in holding a + * planted marker in each store. + */ + +interface ISendCmd { + constructor: { name: string }; + input: Record; +} + +const MARK = 'LEAK-MARKER-ranch8'; + +function buildGateway(objects: Record) { + const read: string[] = []; + const send = jest.fn((cmd: ISendCmd) => { + const name = cmd.constructor.name; + if (name === 'ListObjectsV2Command') { + return Promise.resolve({ + Contents: Object.keys(objects).map((k) => ({ Key: `agents/a1/${k}` })), + }); + } + if (name === 'GetObjectCommand') { + const key = String(cmd.input.Key).slice('agents/a1/'.length); + read.push(key); + return Promise.resolve({ + Body: { + transformToByteArray: () => + Promise.resolve(new Uint8Array(Buffer.from(objects[key] ?? ''))), + }, + }); + } + return Promise.resolve({}); + }); + const gateway = new S3FileGateway({} as unknown as ISettingGateway); + jest + .spyOn(gateway as unknown as { connect: () => Promise }, 'connect') + .mockResolvedValue({ client: { send }, bucket: 'b' }); + return { gateway, read }; +} + +async function entriesOf(buffer: Buffer): Promise> { + const dir = await unzipper.Open.buffer(buffer); + const out: Record = {}; + for (const file of dir.files) { + out[file.path] = (await file.buffer()).toString('utf-8'); + } + return out; +} + +const NOTE = { path: SECRET_STORES_NOTE_PATH, content: SECRET_STORES_NOTE }; + +describe('S3FileGateway.exportZip with a skip rule (RANCH-8)', () => { + const objects = { + 'notes.md': 'ordinary', + 'data/usage.json': '{}', + 'data/secrets/a1.json': `{"API_KEY":"${MARK}"}`, + 'data/channels/telegram.json': `{"botToken":"${MARK}"}`, + 'data/channels.json': `{"telegram":{"botToken":"${MARK}"}}`, + 'browser-state/admin/default.json': `{"cookies":["${MARK}"]}`, + }; + + it('leaves every secret store out, unread, and adds the note', async () => { + const { gateway, read } = buildGateway(objects); + const { buffer, skipped } = await gateway.exportZip('a1', undefined, { + skip: isSecretStorePath, + note: NOTE, + }); + const entries = await entriesOf(buffer); + expect(Object.keys(entries).sort()).toEqual( + [SECRET_STORES_NOTE_PATH, 'data/usage.json', 'notes.md'].sort(), + ); + expect(JSON.stringify(entries)).not.toContain(MARK); + expect(entries[SECRET_STORES_NOTE_PATH]).toBe(SECRET_STORES_NOTE); + expect(skipped).toBe(4); + expect(read.some((k) => isSecretStorePath(k))).toBe(false); + }); + + it('a selection of `data` keeps the rest of the folder', async () => { + const { gateway } = buildGateway(objects); + const { buffer } = await gateway.exportZip('a1', ['data'], { + skip: isSecretStorePath, + note: NOTE, + }); + const entries = await entriesOf(buffer); + expect(Object.keys(entries).sort()).toEqual( + [SECRET_STORES_NOTE_PATH, 'data/usage.json'].sort(), + ); + }); + + it('no note when nothing was left out', async () => { + const { gateway } = buildGateway({ 'notes.md': 'x' }); + const { buffer, skipped } = await gateway.exportZip('a1', undefined, { + skip: isSecretStorePath, + note: NOTE, + }); + expect(Object.keys(await entriesOf(buffer))).toEqual(['notes.md']); + expect(skipped).toBe(0); + }); + + it('a workspace of nothing but secret stores is an archive with the note, not an error', async () => { + const { gateway } = buildGateway({ 'data/secrets/a1.json': MARK }); + const { buffer } = await gateway.exportZip('a1', undefined, { + skip: isSecretStorePath, + note: NOTE, + }); + expect(Object.keys(await entriesOf(buffer))).toEqual([ + SECRET_STORES_NOTE_PATH, + ]); + }); + + it('without a rule it exports everything, as before', async () => { + const { gateway } = buildGateway(objects); + const { buffer } = await gateway.exportZip('a1'); + expect(Object.keys(await entriesOf(buffer))).toHaveLength(6); + }); +}); diff --git a/api/src/slices/agent/file/data/file.gateway.ts b/api/src/slices/agent/file/data/file.gateway.ts index cb0a31636..5bbf536db 100644 --- a/api/src/slices/agent/file/data/file.gateway.ts +++ b/api/src/slices/agent/file/data/file.gateway.ts @@ -18,7 +18,7 @@ import { } from '@aws-sdk/client-s3'; import * as archiver from 'archiver'; import { ISettingGateway } from '#/setting/domain'; -import { IFileGateway } from '../domain/file.gateway'; +import { IFileGateway, type IExportOptions } from '../domain/file.gateway'; import { IFileChunk, IFileContent, @@ -855,7 +855,9 @@ export class S3FileGateway extends IFileGateway { async exportZip( agentId: string, paths?: string[], - ): Promise<{ filename: string; buffer: Buffer }> { + opts: IExportOptions = {}, + ): Promise<{ filename: string; buffer: Buffer; skipped: number }> { + let skipped = 0; const { client, bucket } = await this.connect(); const prefix = this.prefix(agentId); // A selection (CLEAN-112): exact files, or folders by prefix. @@ -892,6 +894,12 @@ export class S3FileGateway extends IFileGateway { if (!rel) continue; if (rel.split('/').some((s) => s === '..' || s === '.')) continue; if (!selected(rel)) continue; + // Left out without being read (RANCH-8): a secret store's bytes never + // reach the archive, nor this process. + if (opts.skip?.(rel)) { + skipped += 1; + continue; + } const res = await client.send( new GetObjectCommand({ Bucket: bucket, Key: obj.Key }), ); @@ -904,6 +912,11 @@ export class S3FileGateway extends IFileGateway { : undefined; } while (continuationToken); + if (skipped > 0 && opts.note) { + archive.append(Buffer.from(opts.note.content, 'utf-8'), { + name: opts.note.path, + }); + } await archive.finalize(); await done; @@ -913,6 +926,7 @@ export class S3FileGateway extends IFileGateway { ? `agent-${agentId}-selection.zip` : `agent-${agentId}.zip`, buffer: Buffer.concat(chunks), + skipped, }; } diff --git a/api/src/slices/agent/file/domain/file.gateway.ts b/api/src/slices/agent/file/domain/file.gateway.ts index efbe8abc2..c1dc5f143 100644 --- a/api/src/slices/agent/file/domain/file.gateway.ts +++ b/api/src/slices/agent/file/domain/file.gateway.ts @@ -7,6 +7,12 @@ import { } from './file.types'; import { IImportStageMeta } from './import.types'; +/** What an export leaves out, and what it says about it (RANCH-8). */ +export interface IExportOptions { + skip?: (relativePath: string) => boolean; + note?: { path: string; content: string }; +} + export abstract class IFileGateway { abstract list(agentId: string): Promise; abstract read(agentId: string, path: string): Promise; @@ -73,10 +79,14 @@ export abstract class IFileGateway { // by the admin UI before a destructive operation so the operator can // pre-download the agent's state. // `paths` (CLEAN-112): only these files, or folders by prefix. + // `opts.skip` (RANCH-8): keys left out of the archive, by relative path. + // When any was, `opts.note` is added as an entry of its own, so the person + // who unpacks it knows what is missing and why. `skipped` says how many. abstract exportZip( agentId: string, paths?: string[], - ): Promise<{ filename: string; buffer: Buffer }>; + opts?: IExportOptions, + ): Promise<{ filename: string; buffer: Buffer; skipped?: number }>; // ── Change proposals (CLEAN-112) ────────────────────────────── /** ETag of the stored object (quotes stripped), or null when absent. */ abstract headEtag(agentId: string, path: string): Promise; diff --git a/api/src/slices/agent/file/domain/fileProposal.service.spec.ts b/api/src/slices/agent/file/domain/fileProposal.service.spec.ts index 2e9892a8d..ea34b33b4 100644 --- a/api/src/slices/agent/file/domain/fileProposal.service.spec.ts +++ b/api/src/slices/agent/file/domain/fileProposal.service.spec.ts @@ -6,6 +6,7 @@ import { computeDiff, } from './fileProposal.service'; import type { IFileGateway } from './file.gateway'; +import { WorkspaceFiles } from './workspaceFiles'; import type { ICreateProposal, IFileChangeProposal, @@ -161,7 +162,7 @@ function build( apply: jest.fn(), }; const service = new FileProposalService( - files, + new WorkspaceFiles(files), repo, archive as never, hub as never, diff --git a/api/src/slices/agent/file/domain/fileProposal.service.ts b/api/src/slices/agent/file/domain/fileProposal.service.ts index 40d831633..df780a37b 100644 --- a/api/src/slices/agent/file/domain/fileProposal.service.ts +++ b/api/src/slices/agent/file/domain/fileProposal.service.ts @@ -15,7 +15,7 @@ import type { IBridleProposalEvent, IBridleProposalUpdateEvent, } from '#/bridle/domain'; -import { IFileGateway } from './file.gateway'; +import { WorkspaceFiles } from './workspaceFiles'; import { DIFF_COMPARE_MAX_BYTES, DIFF_INLINE_MAX_BYTES, @@ -107,7 +107,7 @@ export class FileProposalService { private readonly logger = new Logger(FileProposalService.name); constructor( - private readonly files: IFileGateway, + private readonly files: WorkspaceFiles, private readonly proposals: IFileProposalRepository, private readonly archive: WorkspaceArchiveService, @Inject(forwardRef(() => IBridleGateway)) diff --git a/api/src/slices/agent/file/domain/index.ts b/api/src/slices/agent/file/domain/index.ts index 3f389fe3c..66ce2336b 100644 --- a/api/src/slices/agent/file/domain/index.ts +++ b/api/src/slices/agent/file/domain/index.ts @@ -12,3 +12,5 @@ export * from './openLink.service'; export * from './syncGuard.service'; export * from './transcriptReader.service'; export * from './fileProposal.service'; +export * from './secretStorePaths'; +export * from './workspaceFiles'; diff --git a/api/src/slices/agent/file/domain/openLink.service.ts b/api/src/slices/agent/file/domain/openLink.service.ts index 116d6ea06..1aa160a5f 100644 --- a/api/src/slices/agent/file/domain/openLink.service.ts +++ b/api/src/slices/agent/file/domain/openLink.service.ts @@ -1,7 +1,12 @@ -import { Injectable, UnauthorizedException } from '@nestjs/common'; +import { + ForbiddenException, + Injectable, + UnauthorizedException, +} from '@nestjs/common'; import { JwtService } from '@nestjs/jwt'; import { OPEN_LINK_TTL_SEC } from './file.limits'; import type { FileKind } from './fileKind'; +import { SECRET_STORE_REFUSAL, isSecretStorePath } from './secretStorePaths'; export interface IOpenLinkClaims { agentId: string; @@ -10,6 +15,8 @@ export interface IOpenLinkClaims { } const SUBJECT = 'open-link'; +/** What the token is for (RANCH-8): one file, never a sign-in or a chat. */ +const TYP = 'open-link'; /** * "Open full" links (CLEAN-112, research R3): a short-lived token that names @@ -26,9 +33,14 @@ export class OpenLinkService { path: string, kind: FileKind, ): { token: string; expiresAt: Date } { + // No link is ever signed for a secret store (RANCH-8); the raw route + // refuses one from before the change as well. + if (isSecretStorePath(path)) { + throw new ForbiddenException(SECRET_STORE_REFUSAL); + } const expiresAt = new Date(Date.now() + OPEN_LINK_TTL_SEC * 1000); const token = this.jwt.sign( - { sub: SUBJECT, agentId, path, kind }, + { sub: SUBJECT, typ: TYP, agentId, path, kind }, { expiresIn: OPEN_LINK_TTL_SEC }, ); return { token, expiresAt }; @@ -43,6 +55,8 @@ export class OpenLinkService { } if ( payload.sub !== SUBJECT || + // Its own `typ`, or none on a link from before RANCH-8. + (payload.typ !== undefined && payload.typ !== TYP) || typeof payload.agentId !== 'string' || typeof payload.path !== 'string' ) { diff --git a/api/src/slices/agent/file/domain/secretStorePaths.spec.ts b/api/src/slices/agent/file/domain/secretStorePaths.spec.ts new file mode 100644 index 000000000..0b2c7b390 --- /dev/null +++ b/api/src/slices/agent/file/domain/secretStorePaths.spec.ts @@ -0,0 +1,107 @@ +import { + SECRET_STORE_PATHS, + isSecretStorePath, + mayHoldSecretStore, + normaliseWorkspacePath, +} from './secretStorePaths'; + +/** + * RANCH-8, audit §2 (FR-010, FR-012). The secret stores of a workspace are + * matched however a path is spelled: a rule that `data/secrets/x.json` + * passes and `./data//Secrets/x.json` does not is no rule. + */ +describe('isSecretStorePath', () => { + it.each([ + 'data/secrets/agent.json', + 'data/secrets/user-1.json', + 'data/channels/telegram.json', + 'data/channels/status.json', + 'data/channels.json', + 'browser-state/admin/default.json', + 'browser-state/admin-default.json', + // The folders themselves. + 'data/secrets', + 'data/secrets/', + 'data/channels', + 'browser-state', + // Other spellings of the same keys. + './data/secrets/agent.json', + 'data//secrets/agent.json', + 'data\\secrets\\agent.json', + 'Data/Secrets/Agent.json', + 'DATA/CHANNELS.JSON', + 'data%2Fsecrets%2Fagent.json', + 'data%5Csecrets%5Cagent.json', + 'data/./secrets/agent.json', + 'browser-state/', + '/data/secrets/agent.json', + ])('%p is a secret store', (path) => { + expect(isSecretStorePath(path)).toBe(true); + }); + + it.each([ + 'notes.md', + 'agent.config.json', + 'data/usage.json', + 'data/sessions/bridle:admin.jsonl', + 'data/secrets.md', + 'data/secretsx/a.json', + 'data/channels.json.bak', + 'data/channelsx/a.json', + 'browser-statement.md', + 'memory/data/secrets/notes.md', + 'skills/browser-state/SKILL.md', + '', + ])('%p is not', (path) => { + expect(isSecretStorePath(path)).toBe(false); + }); +}); + +describe('mayHoldSecretStore: a folder operation that could reach one', () => { + it.each([ + '', + '.', + 'data', + 'data/', + 'DATA', + 'data/secrets', + 'browser-state', + 'data/channels/x', + ])('%p', (path) => { + expect(mayHoldSecretStore(path)).toBe(true); + }); + + it.each(['skills', 'memory', 'data/sessions', 'workspace/data'])( + 'not %p', + (path) => { + expect(mayHoldSecretStore(path)).toBe(false); + }, + ); +}); + +describe('normaliseWorkspacePath', () => { + it('decodes once, reads a backslash as /, drops empty and . segments and the trailing /, lower-cases', () => { + expect(normaliseWorkspacePath('./Data//Secrets\\x.json/')).toBe( + 'data/secrets/x.json', + ); + expect(normaliseWorkspacePath('data%2Fsecrets')).toBe('data/secrets'); + // Once: a doubly encoded separator stays a character. + expect(normaliseWorkspacePath('data%252Fsecrets')).toBe('data%2fsecrets'); + expect(normaliseWorkspacePath('100%')).toBe('100%'); + }); + + it('keeps `..` for the gateway to refuse', () => { + expect(normaliseWorkspacePath('a/../data/secrets')).toBe( + 'a/../data/secrets', + ); + }); + + it('the four stores, as data-model.md lists them', () => { + expect([...SECRET_STORE_PATHS]).toEqual([ + 'data/secrets/', + 'data/channels/', + 'data/channels.json', + 'browser-state/', + ]); + }); +}); diff --git a/api/src/slices/agent/file/domain/secretStorePaths.ts b/api/src/slices/agent/file/domain/secretStorePaths.ts new file mode 100644 index 000000000..97ee25836 --- /dev/null +++ b/api/src/slices/agent/file/domain/secretStorePaths.ts @@ -0,0 +1,81 @@ +/** + * The workspace files that hold an agent's stored secrets (RANCH-8, audit + * §2). Secrets are write-only (CLEAN-275): they change through the Secrets + * and Channels settings, which never echo a value, and no file surface may + * hand one back or write one, whoever asks, the Owner included. + * + * data/secrets/ the agent's and each person's secrets, tool-server + * sign-ins (FileSecretGateway) + * data/channels/ a messaging bot's token (AgentChannelGateway) + * data/channels.json the legacy channel settings, with a bot token + * browser-state/ people's browser cookies and storage (BrowserGateway) + * + * Paths are relative to `agents//`. Folders end in `/`. + */ +export const SECRET_STORE_PATHS = [ + 'data/secrets/', + 'data/channels/', + 'data/channels.json', + 'browser-state/', +] as const; + +/** What every file surface answers for a secret store. */ +export const SECRET_STORE_REFUSAL = + "This file holds stored secrets and is write-only. Change them in the agent's Secrets or Channels settings."; + +/** The entry an export leaves in the archive when it skipped a secret store. */ +export const SECRET_STORES_NOTE_PATH = 'SECRET_STORES_NOT_EXPORTED.txt'; + +export const SECRET_STORES_NOTE = + "Stored secrets are write-only and are not exported: the agent's secrets, its\n" + + 'channel settings and saved browser sessions. Set them again on the target\n' + + 'agent through its Secrets and Channels settings.\n'; + +/** + * A path as the rule compares it: percent-decoded once, `\` read as `/`, + * empty and `.` segments dropped, a trailing `/` dropped, lower-cased. The + * comparison is all it is for: S3 keys are case-sensitive, but a pod's file + * system may not be, and `Data/Secrets/x.json` must not be a way round. + * `..` is left in: the gateway refuses it on its own. + */ +export function normaliseWorkspacePath(path: string): string { + let decoded = String(path ?? ''); + try { + decoded = decodeURIComponent(decoded); + } catch { + // A stray `%` is a character like any other here. + } + return decoded + .replace(/\\/g, '/') + .split('/') + .filter((segment) => segment !== '' && segment !== '.') + .join('/') + .toLowerCase(); +} + +/** + * Whether `path` is a secret store or inside one, however it is spelled + * (FR-012). `data/secrets` and `data/secrets/` are the folder itself. + */ +export function isSecretStorePath(path: string): boolean { + const p = normaliseWorkspacePath(path); + if (!p) return false; + return SECRET_STORE_PATHS.some((store) => + store.endsWith('/') + ? p === store.slice(0, -1) || p.startsWith(store) + : p === store, + ); +} + +/** + * Whether a folder operation on `path` (delete a folder, export a + * selection) could reach a secret store: the path is one, holds one (`data`, + * the workspace root) or is inside one. Such an operation is not refused for + * it; it goes object by object and leaves the secret stores alone. + */ +export function mayHoldSecretStore(path: string): boolean { + const p = normaliseWorkspacePath(path); + if (!p) return true; + if (isSecretStorePath(p)) return true; + return SECRET_STORE_PATHS.some((store) => store.startsWith(`${p}/`)); +} diff --git a/api/src/slices/agent/file/domain/syncGuard.service.spec.ts b/api/src/slices/agent/file/domain/syncGuard.service.spec.ts index 5b612f0a6..560609554 100644 --- a/api/src/slices/agent/file/domain/syncGuard.service.spec.ts +++ b/api/src/slices/agent/file/domain/syncGuard.service.spec.ts @@ -1,5 +1,10 @@ import { SyncGuardService, PULL_MARGIN_MS } from './syncGuard.service'; import { IFileGateway } from './file.gateway'; +import { WorkspaceFiles } from './workspaceFiles'; + +/** The guard over a stub gateway, through the facade production uses. */ +const syncGuard = (files: IFileGateway) => + new SyncGuardService(new WorkspaceFiles(files)); import { IFileNode } from './file.types'; const T0 = new Date('2026-08-31T10:00:00Z').getTime(); @@ -17,8 +22,8 @@ function fileStub( const tagged = new Set(ranchPaths); return { list: async (): Promise => nodes, - wasWrittenByRanch: jest.fn( - async (_agentId: string, path: string) => tagged.has(path), + wasWrittenByRanch: jest.fn(async (_agentId: string, path: string) => + tagged.has(path), ), } as unknown as IFileGateway & { wasWrittenByRanch: jest.Mock }; } @@ -33,7 +38,7 @@ const node = (path: string, updatedAt: Date): IFileNode => ({ describe('SyncGuardService', () => { describe('computeBaseline', () => { - const guard = new SyncGuardService(fileStub([])); + const guard = syncGuard(fileStub([])); it('returns null when both markers are null (legacy agent — skip check)', () => { expect(guard.computeBaseline(null, null)).toBeNull(); @@ -62,7 +67,7 @@ describe('SyncGuardService', () => { describe('assess', () => { it('returns empty atRisk without listing files when no baseline', async () => { const list = jest.fn(); - const guard = new SyncGuardService({ + const guard = syncGuard({ list, } as unknown as IFileGateway); const result = await guard.assess('agent-1', null, null); @@ -71,7 +76,7 @@ describe('SyncGuardService', () => { }); it('flags only files whose S3 copy is newer than the baseline', async () => { - const guard = new SyncGuardService( + const guard = syncGuard( fileStub([ node('SOUL.md', at(500)), // edited after sync → at risk node('notes.md', at(-500)), // untouched since boot → safe @@ -86,13 +91,13 @@ describe('SyncGuardService', () => { it('applies the pull margin: file edited just before connect is at risk', async () => { // Pull recorded at T0; S3 write landed 30s earlier (inside the // pull→connect window). Margin must catch it. - const guard = new SyncGuardService(fileStub([node('SOUL.md', at(-30))])); + const guard = syncGuard(fileStub([node('SOUL.md', at(-30))])); const result = await guard.assess('agent-1', at(0), null); expect(result.atRisk.map((n) => n.path)).toEqual(['SOUL.md']); }); it('passes through with no at-risk files (frictionless sync)', async () => { - const guard = new SyncGuardService( + const guard = syncGuard( fileStub([node('a.md', at(-120)), node('b.md', at(-90))]), ); const result = await guard.assess('agent-1', at(0), null); @@ -110,7 +115,7 @@ describe('SyncGuardService', () => { ], ['SOUL.md'], ); - const guard = new SyncGuardService(files); + const guard = syncGuard(files); const result = await guard.assess('agent-1', at(-1000), at(100)); expect(result.atRisk.map((n) => n.path)).toEqual(['SOUL.md']); }); @@ -120,7 +125,7 @@ describe('SyncGuardService', () => { node('data/usage.json', at(600)), node('notes.md', at(-500)), ]); - const guard = new SyncGuardService(files); + const guard = syncGuard(files); await guard.assess('agent-1', at(-1000), at(100)); expect(files.wasWrittenByRanch).toHaveBeenCalledTimes(1); expect(files.wasWrittenByRanch).toHaveBeenCalledWith( @@ -130,7 +135,7 @@ describe('SyncGuardService', () => { }); it('reports nothing when every newer file came from the pod', async () => { - const guard = new SyncGuardService( + const guard = syncGuard( fileStub( [node('data/usage.json', at(600)), node('memory/today.md', at(700))], [], diff --git a/api/src/slices/agent/file/domain/syncGuard.service.ts b/api/src/slices/agent/file/domain/syncGuard.service.ts index 3db26924a..da2dd5f6c 100644 --- a/api/src/slices/agent/file/domain/syncGuard.service.ts +++ b/api/src/slices/agent/file/domain/syncGuard.service.ts @@ -1,5 +1,5 @@ import { Injectable } from '@nestjs/common'; -import { IFileGateway } from './file.gateway'; +import { WorkspaceFiles } from './workspaceFiles'; import { IFileNode } from './file.types'; // The runtime pulls its working copy at boot, moments BEFORE the bridle @@ -31,7 +31,7 @@ export interface ISyncRiskAssessment { */ @Injectable() export class SyncGuardService { - constructor(private readonly files: IFileGateway) {} + constructor(private readonly files: WorkspaceFiles) {} computeBaseline( lastPullAt: Date | null, diff --git a/api/src/slices/agent/file/domain/workspaceArchive.service.spec.ts b/api/src/slices/agent/file/domain/workspaceArchive.service.spec.ts index ef90ddf20..8629b87d1 100644 --- a/api/src/slices/agent/file/domain/workspaceArchive.service.spec.ts +++ b/api/src/slices/agent/file/domain/workspaceArchive.service.spec.ts @@ -5,6 +5,11 @@ import { IFileGateway } from './file.gateway'; import { IMPORT_MAX_ENTRIES } from './file.limits'; import { IArchiveEntry } from './import.types'; import { WorkspaceArchiveService } from './workspaceArchive.service'; +import { WorkspaceFiles } from './workspaceFiles'; + +/** The service over a stub gateway, through the facade production uses. */ +const archiveOver = (files: IFileGateway) => + new WorkspaceArchiveService(new WorkspaceFiles(files)); // ── helpers ───────────────────────────────────────────────────── @@ -56,7 +61,7 @@ const entry = (path: string, body: string): IArchiveEntry => ({ // ── validate ──────────────────────────────────────────────────── describe('WorkspaceArchiveService.validate', () => { - const service = new WorkspaceArchiveService(fakeGateway().gateway); + const service = archiveOver(fakeGateway().gateway); it('reads every file entry with its size and md5', async () => { const zip = await zipOf({ 'SOUL.md': 'hi', 'skills/run.py': 'print(1)' }); @@ -207,7 +212,7 @@ describe('WorkspaceArchiveService.plan', () => { it('classifies add / change / unchanged / skip in merge mode', async () => { const { gateway } = fakeGateway(stored); - const service = new WorkspaceArchiveService(gateway); + const service = archiveOver(gateway); const plan = await service.plan( 'a1', entries, @@ -245,7 +250,7 @@ describe('WorkspaceArchiveService.plan', () => { }); it('includes session files when asked', async () => { - const service = new WorkspaceArchiveService(fakeGateway(stored).gateway); + const service = archiveOver(fakeGateway(stored).gateway); const plan = await service.plan('a1', entries, { mode: 'merge', includeSessions: true, @@ -257,7 +262,7 @@ describe('WorkspaceArchiveService.plan', () => { }); it('lists removals in replace mode, sparing runtime state unless included', async () => { - const service = new WorkspaceArchiveService(fakeGateway(stored).gateway); + const service = archiveOver(fakeGateway(stored).gateway); const plan = await service.plan('a1', entries, { mode: 'replace', includeSessions: false, @@ -270,7 +275,7 @@ describe('WorkspaceArchiveService.plan', () => { }); it('never removes in merge mode', async () => { - const service = new WorkspaceArchiveService(fakeGateway(stored).gateway); + const service = archiveOver(fakeGateway(stored).gateway); const plan = await service.plan('a1', entries, { mode: 'merge', includeSessions: false, @@ -280,7 +285,7 @@ describe('WorkspaceArchiveService.plan', () => { it('lists the gateway once per plan', async () => { const { gateway } = fakeGateway(stored); - const service = new WorkspaceArchiveService(gateway); + const service = archiveOver(gateway); await service.plan('a1', entries, { mode: 'merge', includeSessions: false, @@ -306,7 +311,7 @@ describe('WorkspaceArchiveService.apply', () => { it('writes add/change, skips unchanged and sessions, removes in replace mode', async () => { const { gateway, puts, deletes } = fakeGateway(stored); - const service = new WorkspaceArchiveService(gateway); + const service = archiveOver(gateway); const plan = await service.plan( 'a1', entries, @@ -330,7 +335,7 @@ describe('WorkspaceArchiveService.apply', () => { it('records a failing put instead of throwing', async () => { const { gateway, puts, failing } = fakeGateway(stored); failing.add('skills/new.py'); - const service = new WorkspaceArchiveService(gateway); + const service = archiveOver(gateway); const plan = await service.plan('a1', entries, { mode: 'merge', includeSessions: false, @@ -345,7 +350,7 @@ describe('WorkspaceArchiveService.apply', () => { it('writes nothing for an all-unchanged merge', async () => { const { gateway, puts, deletes } = fakeGateway(stored); - const service = new WorkspaceArchiveService(gateway); + const service = archiveOver(gateway); const only = [entry('SOUL.md', 'same')]; const plan = await service.plan('a1', only, { mode: 'merge', @@ -361,7 +366,7 @@ describe('WorkspaceArchiveService.apply', () => { it('refuses a row whose ETag moved since the preview and writes the rest', async () => { const { gateway, puts } = fakeGateway(stored); - const service = new WorkspaceArchiveService(gateway); + const service = archiveOver(gateway); const files = [ entry('workspace/old.txt', 'newer'), entry('memory/a.md', 'a'), @@ -383,7 +388,7 @@ describe('WorkspaceArchiveService.apply', () => { it('refuses a row planned as new that exists by now', async () => { const { gateway, puts } = fakeGateway(stored); - const service = new WorkspaceArchiveService(gateway); + const service = archiveOver(gateway); const files = [entry('workspace/old.txt', 'newer')]; const plan = await service.plan('a1', files, { mode: 'merge', @@ -398,7 +403,7 @@ describe('WorkspaceArchiveService.apply', () => { it('writes when the guard matches, and ignores paths the guard does not name', async () => { const { gateway, puts } = fakeGateway(stored); - const service = new WorkspaceArchiveService(gateway); + const service = archiveOver(gateway); const files = [ entry('workspace/old.txt', 'newer'), entry('memory/a.md', 'a'), @@ -416,7 +421,7 @@ describe('WorkspaceArchiveService.apply', () => { }); describe('WorkspaceArchiveService.validate without wrapper stripping (CLEAN-192)', () => { - const service = new WorkspaceArchiveService(fakeGateway().gateway); + const service = archiveOver(fakeGateway().gateway); it('keeps a shared custom folder when told not to strip', async () => { const zip = await zipOf({ 'notes/a.md': 'a', 'notes/b.md': 'b' }); @@ -430,3 +435,78 @@ describe('WorkspaceArchiveService.validate without wrapper stripping (CLEAN-192) ]); }); }); + +// ── secret stores (RANCH-8) ───────────────────────────────────── + +/** + * An export leaves an agent's secret stores out (they are write-only), so + * an import must neither write one from an archive nor remove an existing + * one in replace mode: otherwise "export, then replace-import" would wipe + * the bot token and every secret of the agent it was meant to restore. + */ +describe('WorkspaceArchiveService and the secret stores (RANCH-8)', () => { + const STORED: Stored[] = [ + { path: 'notes.md', size: 2, etag: md5('hi') }, + { path: 'data/secrets/a1.json', size: 9, etag: 'e1' }, + { path: 'data/channels/telegram.json', size: 9, etag: 'e2' }, + { path: 'data/channels.json', size: 9, etag: 'e3' }, + { path: 'browser-state/admin/default.json', size: 9, etag: 'e4' }, + ]; + + it('skips archive entries under a secret store, with the reason, in any mode', async () => { + const { gateway } = fakeGateway(STORED); + const service = archiveOver(gateway); + for (const mode of ['merge', 'replace'] as const) { + const plan = await service.plan( + 'a1', + [ + entry('notes.md', 'hi'), + entry('data/secrets/a1.json', '{"K":"attacker"}'), + entry('Data/Channels/telegram.json', '{"botToken":"x"}'), + entry('browser-state/x.json', '{}'), + ], + { mode, includeSessions: true }, + ); + const skipped = plan.entries.filter((e) => e.action === 'skip'); + expect(skipped.map((e) => e.path).sort()).toEqual( + [ + 'Data/Channels/telegram.json', + 'browser-state/x.json', + 'data/secrets/a1.json', + ].sort(), + ); + expect(skipped.every((e) => /write-only/.test(e.reason ?? ''))).toBe( + true, + ); + } + }); + + it('replace mode never lists an existing secret store for removal', async () => { + const { gateway } = fakeGateway(STORED); + const plan = await archiveOver(gateway).plan( + 'a1', + [entry('other.md', 'x')], + { mode: 'replace', includeSessions: true }, + ); + expect( + plan.entries.filter((e) => e.action === 'remove').map((e) => e.path), + ).toEqual(['notes.md']); + }); + + it('apply writes none and removes none', async () => { + const { gateway, puts, deletes } = fakeGateway(STORED); + const service = archiveOver(gateway); + const entries = [ + entry('other.md', 'x'), + entry('data/secrets/a1.json', '{"K":"attacker"}'), + ]; + const plan = await service.plan('a1', entries, { + mode: 'replace', + includeSessions: true, + }); + const result = await service.apply('a1', entries, plan); + expect(puts).toEqual(['other.md']); + expect(deletes).toEqual(['notes.md']); + expect(result.failed).toEqual([]); + }); +}); diff --git a/api/src/slices/agent/file/domain/workspaceArchive.service.ts b/api/src/slices/agent/file/domain/workspaceArchive.service.ts index 892e241a4..9c6a7c0bd 100644 --- a/api/src/slices/agent/file/domain/workspaceArchive.service.ts +++ b/api/src/slices/agent/file/domain/workspaceArchive.service.ts @@ -1,7 +1,7 @@ import { BadRequestException, Injectable } from '@nestjs/common'; import * as crypto from 'crypto'; import * as unzipper from 'unzipper'; -import { IFileGateway } from './file.gateway'; +import { WorkspaceFiles } from './workspaceFiles'; import { IMPORT_MAX_ARCHIVE_BYTES, IMPORT_MAX_ENTRIES, @@ -18,6 +18,11 @@ import { ImportMode, } from './import.types'; import { isRuntimeOwned, safeEntryPath } from './importPath'; +import { isSecretStorePath } from './secretStorePaths'; + +/** Why an archive entry under a secret store is not written (RANCH-8). */ +export const SECRET_STORE_SKIP_REASON = + 'stored secrets are write-only: set them in the Secrets or Channels settings'; // The runtime-owned list moved to importPath.ts (CLEAN-192) so the // selected-files resolver shares it; re-exported for existing importers. @@ -65,7 +70,7 @@ export const CHANGED_SINCE_PREVIEWED = 'changed since previewed'; */ @Injectable() export class WorkspaceArchiveService { - constructor(private readonly files: IFileGateway) {} + constructor(private readonly files: WorkspaceFiles) {} /** * Parse and check the whole archive. Any offending entry refuses the @@ -205,6 +210,18 @@ export class WorkspaceArchiveService { let multipart = 0; for (const entry of entries) { + // Never written by an import, whatever the options (RANCH-8): a + // secret changes only through its own settings. + if (isSecretStorePath(entry.path)) { + counts.skip += 1; + rows.push({ + path: entry.path, + action: 'skip', + size: entry.size, + reason: SECRET_STORE_SKIP_REASON, + }); + continue; + } if (!opts.includeSessions && this.isRuntimeOwned(entry.path)) { counts.skip += 1; rows.push({ @@ -373,6 +390,10 @@ export class WorkspaceArchiveService { const inArchive = new Set(entries.map((e) => e.path)); const out = new Map(); for (const entry of entries) { + if (isSecretStorePath(entry.path)) { + out.set(entry.path, 'skip'); + continue; + } if (!opts.includeSessions && this.isRuntimeOwned(entry.path)) { out.set(entry.path, 'skip'); continue; diff --git a/api/src/slices/agent/file/domain/workspaceFiles.spec.ts b/api/src/slices/agent/file/domain/workspaceFiles.spec.ts new file mode 100644 index 000000000..1cf71812c --- /dev/null +++ b/api/src/slices/agent/file/domain/workspaceFiles.spec.ts @@ -0,0 +1,175 @@ +import { ForbiddenException } from '@nestjs/common'; +import type { IFileGateway } from './file.gateway'; +import { + SECRET_STORES_NOTE_PATH, + SECRET_STORE_REFUSAL, +} from './secretStorePaths'; +import { WorkspaceFiles } from './workspaceFiles'; + +/** + * RANCH-8, audit §2 (`agent/file:workspace-read-bypasses-writeOnly`): the + * generic workspace file reader served the files that hold an agent's + * stored secrets. `WorkspaceFiles` is what every caller-facing surface holds + * now: secret stores are not listed, not read, not written, not deleted and + * not exported, by any spelling of their path, for every caller. + */ + +const MARK = 'LEAK-MARKER-ranch8'; +const OBJECTS: Record = { + 'notes.md': 'ordinary', + 'data/usage.json': '{}', + 'data/secrets/a1.json': MARK, + 'data/secrets/user-1.json': MARK, + 'data/channels/telegram.json': MARK, + 'data/channels/status.json': '{}', + 'data/channels.json': MARK, + 'browser-state/admin/default.json': MARK, +}; + +function gateway() { + const calls: string[] = []; + const at = new Date('2026-12-01T10:00:00Z'); + const raw = { + list: jest.fn(async () => + Object.keys(OBJECTS).map((path) => ({ + path, + size: OBJECTS[path].length, + updatedAt: at, + kind: 'text' as const, + editable: true, + })), + ), + listWithEtags: jest.fn(async () => + Object.keys(OBJECTS).map((path) => ({ path, size: 1, etag: 'e' })), + ), + read: jest.fn(async (_a: string, path: string) => { + calls.push(`read ${path}`); + return { path, content: OBJECTS[path] ?? '' }; + }), + readRange: jest.fn(async (_a: string, path: string) => { + calls.push(`readRange ${path}`); + return { path, content: OBJECTS[path] ?? '' }; + }), + streamRaw: jest.fn(async (_a: string, path: string) => { + calls.push(`streamRaw ${path}`); + return {}; + }), + headEtag: jest.fn(async () => 'e'), + wasWrittenByRanch: jest.fn(async () => true), + save: jest.fn(async (_a: string, path: string) => { + calls.push(`save ${path}`); + }), + saveRaw: jest.fn(async (_a: string, path: string) => { + calls.push(`saveRaw ${path}`); + }), + putObjectRaw: jest.fn(async (_a: string, path: string) => { + calls.push(`putObjectRaw ${path}`); + }), + delete: jest.fn(async (_a: string, path: string) => { + calls.push(`delete ${path}`); + }), + deletePrefix: jest.fn(async (_a: string, path: string) => { + calls.push(`deletePrefix ${path}`); + return 3; + }), + exportZip: jest.fn(async () => ({ + filename: 'x.zip', + buffer: Buffer.from(''), + })), + }; + return { + files: new WorkspaceFiles(raw as unknown as IFileGateway), + raw, + calls, + }; +} + +const SPELLINGS = [ + 'data/secrets/a1.json', + './data//Secrets/a1.json', + 'data\\secrets\\a1.json', + 'data%2Fsecrets%2Fa1.json', + 'DATA/CHANNELS/telegram.json', + 'data/channels.json', + 'browser-state/admin/default.json', + 'data/secrets/', +]; + +const refused = async (run: () => Promise) => { + const err = await run().catch((e: unknown) => e); + return ( + err instanceof ForbiddenException && err.message === SECRET_STORE_REFUSAL + ); +}; + +describe('WorkspaceFiles: secret stores are write-only for every caller (FR-010, FR-011, FR-012)', () => { + it('a list leaves them out, and says nothing of them', async () => { + const { files } = gateway(); + const paths = (await files.list('a1')).map((n) => n.path); + expect(paths).toEqual(['notes.md', 'data/usage.json']); + const withEtags = (await files.listWithEtags('a1')).map((e) => e.path); + expect(withEtags).toEqual(['notes.md', 'data/usage.json']); + }); + + it.each(SPELLINGS)( + '%p is refused on every one-file method, before the storage is asked', + async (path) => { + const { files, calls } = gateway(); + expect(await refused(() => files.read('a1', path))).toBe(true); + expect(await refused(() => files.readRange('a1', path, 0, 100))).toBe( + true, + ); + expect(await refused(() => files.streamRaw('a1', path))).toBe(true); + expect(await refused(() => files.headEtag('a1', path))).toBe(true); + expect(await refused(() => files.save('a1', path, '{}'))).toBe(true); + expect(await refused(() => files.saveRaw('a1', path, '{}'))).toBe(true); + expect( + await refused(() => files.putObjectRaw('a1', path, Buffer.from(''))), + ).toBe(true); + expect(await refused(() => files.delete('a1', path))).toBe(true); + expect(await refused(() => files.deletePrefix('a1', path))).toBe(true); + expect(calls).toEqual([]); + }, + ); + + it('an ordinary file works as before', async () => { + const { files, calls } = gateway(); + await files.read('a1', 'notes.md'); + await files.save('a1', 'notes.md', 'x'); + await files.delete('a1', 'notes.md'); + expect(calls).toEqual([ + 'read notes.md', + 'save notes.md', + 'delete notes.md', + ]); + }); + + it('deleting the folder `data` deletes the rest of it, file by file, and leaves the stores', async () => { + const { files, calls, raw } = gateway(); + expect(await files.deletePrefix('a1', 'data')).toBe(1); + expect(calls).toEqual(['delete data/usage.json']); + expect(raw.deletePrefix).not.toHaveBeenCalled(); + }); + + it('a folder that cannot hold a store is deleted in one go, as before', async () => { + const { files, calls } = gateway(); + expect(await files.deletePrefix('a1', 'skills/x')).toBe(3); + expect(calls).toEqual(['deletePrefix skills/x']); + }); + + it('an export asks the storage to skip the stores and leave the note', async () => { + const { files, raw } = gateway(); + await files.exportZip('a1', ['data']); + const [, paths, opts] = raw.exportZip.mock.calls[0] as unknown as [ + string, + string[], + { skip: (p: string) => boolean; note: { path: string } }, + ]; + expect(paths).toEqual(['data']); + expect(opts.note.path).toBe(SECRET_STORES_NOTE_PATH); + expect(Object.keys(OBJECTS).filter((p) => !opts.skip(p))).toEqual([ + 'notes.md', + 'data/usage.json', + ]); + }); +}); diff --git a/api/src/slices/agent/file/domain/workspaceFiles.ts b/api/src/slices/agent/file/domain/workspaceFiles.ts new file mode 100644 index 000000000..76515ae76 --- /dev/null +++ b/api/src/slices/agent/file/domain/workspaceFiles.ts @@ -0,0 +1,209 @@ +import { ForbiddenException, Injectable } from '@nestjs/common'; +import { IFileGateway } from './file.gateway'; +import type { + IFileChunk, + IFileContent, + IFileNode, + ISaveOptions, +} from './file.types'; +import type { IImportStageMeta } from './import.types'; +import { + SECRET_STORES_NOTE, + SECRET_STORES_NOTE_PATH, + SECRET_STORE_REFUSAL, + isSecretStorePath, + mayHoldSecretStore, +} from './secretStorePaths'; + +/** + * The workspace files as every caller-facing surface sees them (RANCH-8, + * audit §2): the Files routes, the import routes, the assistant's file + * tools, change proposals, import plans, the sync guard and the open link. + * + * Stored secrets are write-only (CLEAN-275), and some live in the + * workspace: an agent's and each person's secrets, its messaging bot's + * token, people's browser cookies (`secretStorePaths.ts`). Here they are not + * there for anybody, the Owner and the assistant included: + * + * - a list leaves them out, with no mark that anything was left out; + * - reading, writing, deleting, streaming or linking one is refused with + * `SECRET_STORE_REFUSAL`, however its path is spelled; + * - a folder delete and an export go object by object and leave them be; + * an export that left one out says so in the archive. + * + * The internal writers of those files (`AgentChannelGateway`, + * `BrowserGateway`; `FileSecretGateway` has its own S3 client) and the + * internal readers of fixed paths (transcripts, usage, the paddock envelope, + * wipe, seed and resync) keep `IFileGateway`. The write-only census fails + * a controller or tool that holds `IFileGateway` without being filed. + */ +@Injectable() +export class WorkspaceFiles { + constructor(private readonly files: IFileGateway) {} + + // ── Lists: secret stores are not there ───────────────────────── + + async list(agentId: string): Promise { + return (await this.files.list(agentId)).filter( + (node) => !isSecretStorePath(node.path), + ); + } + + async listWithEtags( + agentId: string, + ): Promise> { + return (await this.files.listWithEtags(agentId)).filter( + (entry) => !isSecretStorePath(entry.path), + ); + } + + // ── One file: refused ────────────────────────────────────────── + + async read(agentId: string, path: string): Promise { + this.refuse(path); + return this.files.read(agentId, path); + } + + async readRange( + agentId: string, + path: string, + offset: number, + limit: number, + ): Promise { + this.refuse(path); + return this.files.readRange(agentId, path, offset, limit); + } + + async streamRaw( + agentId: string, + path: string, + ): Promise>> { + this.refuse(path); + return this.files.streamRaw(agentId, path); + } + + async headEtag(agentId: string, path: string): Promise { + this.refuse(path); + return this.files.headEtag(agentId, path); + } + + async wasWrittenByRanch(agentId: string, path: string): Promise { + this.refuse(path); + return this.files.wasWrittenByRanch(agentId, path); + } + + async save( + agentId: string, + path: string, + content: string, + options?: ISaveOptions, + ): Promise { + this.refuse(path); + return this.files.save(agentId, path, content, options); + } + + async saveRaw(agentId: string, path: string, content: string): Promise { + this.refuse(path); + return this.files.saveRaw(agentId, path, content); + } + + async putObjectRaw( + agentId: string, + path: string, + bytes: Buffer, + contentType?: string, + ): Promise { + this.refuse(path); + return this.files.putObjectRaw(agentId, path, bytes, contentType); + } + + async delete(agentId: string, path: string): Promise { + this.refuse(path); + return this.files.delete(agentId, path); + } + + // ── Folders and selections: secret stores are skipped ────────── + + /** + * Delete a folder. One that is a secret store, or inside one, is refused; + * one that holds one (`data`) loses everything else, file by file. + */ + async deletePrefix(agentId: string, path: string): Promise { + this.refuse(path); + if (!path || !mayHoldSecretStore(path)) { + return this.files.deletePrefix(agentId, path); + } + const folder = path.endsWith('/') ? path : `${path}/`; + let deleted = 0; + for (const entry of await this.listWithEtags(agentId)) { + if (!entry.path.startsWith(folder)) continue; + await this.files.delete(agentId, entry.path); + deleted += 1; + } + return deleted; + } + + /** + * The workspace, or a selection of it, as a zip without the secret + * stores. When any was left out the archive carries a note saying so; an + * agent that holds nothing else exports the note alone. + */ + exportZip( + agentId: string, + paths?: string[], + ): Promise<{ filename: string; buffer: Buffer; skipped?: number }> { + return this.files.exportZip(agentId, paths, { + skip: isSecretStorePath, + note: { path: SECRET_STORES_NOTE_PATH, content: SECRET_STORES_NOTE }, + }); + } + + // ── No workspace path: passed through ────────────────────────── + + curatedLimits(agentId: string): Promise> { + return this.files.curatedLimits(agentId); + } + + putProposalContent(proposalId: string, content: string): Promise { + return this.files.putProposalContent(proposalId, content); + } + + getProposalContent(proposalId: string): Promise { + return this.files.getProposalContent(proposalId); + } + + deleteProposalContent(proposalId: string): Promise { + return this.files.deleteProposalContent(proposalId); + } + + putStage( + agentId: string, + importId: string, + zip: Buffer, + meta: IImportStageMeta, + ): Promise { + return this.files.putStage(agentId, importId, zip, meta); + } + + getStage( + agentId: string, + importId: string, + ): Promise<{ zip: Buffer; meta: IImportStageMeta } | null> { + return this.files.getStage(agentId, importId); + } + + deleteStage(agentId: string, importId: string): Promise { + return this.files.deleteStage(agentId, importId); + } + + sweepStages(olderThanMin: number): Promise { + return this.files.sweepStages(olderThanMin); + } + + /** Throws the write-only refusal for a secret store, by any spelling. */ + private refuse(path: string): void { + if (isSecretStorePath(path)) { + throw new ForbiddenException(SECRET_STORE_REFUSAL); + } + } +} diff --git a/api/src/slices/agent/file/file.controller.raw.spec.ts b/api/src/slices/agent/file/file.controller.raw.spec.ts index ad67f6ab2..318af1cfa 100644 --- a/api/src/slices/agent/file/file.controller.raw.spec.ts +++ b/api/src/slices/agent/file/file.controller.raw.spec.ts @@ -5,6 +5,7 @@ import type { Response } from 'express'; import { FileController } from './file.controller'; import { OpenLinkService } from './domain/openLink.service'; import type { IFileGateway } from './domain/file.gateway'; +import { WorkspaceFiles } from './domain/workspaceFiles'; import type { IAgentGateway } from '#/agent/agent/domain'; import type { IBridleGateway } from '#/bridle/domain'; import type { SyncGuardService } from './domain/syncGuard.service'; @@ -78,7 +79,7 @@ function makeController( } as unknown as IAgentGateway; const controller = new FileController( agentGateway, - fileGateway, + new WorkspaceFiles(fileGateway), {} as IBridleGateway, {} as SyncGuardService, openLinks, diff --git a/api/src/slices/agent/file/file.controller.spec.ts b/api/src/slices/agent/file/file.controller.spec.ts new file mode 100644 index 000000000..de5707b8d --- /dev/null +++ b/api/src/slices/agent/file/file.controller.spec.ts @@ -0,0 +1,231 @@ +import { ForbiddenException } from '@nestjs/common'; +import { JwtService } from '@nestjs/jwt'; +import { Readable, Writable } from 'stream'; +import type { Response } from 'express'; +import { FileController } from './file.controller'; +import { OpenLinkService } from './domain/openLink.service'; +import { WorkspaceFiles } from './domain/workspaceFiles'; +import { SECRET_STORE_REFUSAL } from './domain/secretStorePaths'; +import type { IFileGateway } from './domain/file.gateway'; +import type { IAgentGateway } from '#/agent/agent/domain'; +import type { IBridleGateway } from '#/bridle/domain'; +import type { SyncGuardService } from './domain/syncGuard.service'; + +/** + * RANCH-8, audit §2: the Files routes, for the Admin who manages the agent + * and for the Owner alike. The audit's reproduction was `GET files/content` + * on `data/channels/telegram.json`, which answered the bot token. Every + * route that names a path refuses a secret store with the write-only + * sentence (403); the list leaves them out; a selection delete leaves them + * be; an open link is never minted for one, and one minted before the + * change no longer opens it. + */ + +const MARK = 'LEAK-MARKER-routes'; +const STORED: Record = { + 'notes.md': 'ordinary', + 'data/usage.json': '{}', + 'data/secrets/agent-1.json': MARK, + 'data/channels/telegram.json': MARK, + 'data/channels.json': MARK, + 'browser-state/admin/default.json': MARK, +}; + +function make() { + const at = new Date('2026-12-01T10:00:00Z'); + const touched: string[] = []; + const raw = { + list: jest.fn(async () => + Object.keys(STORED).map((path) => ({ + path, + size: 1, + updatedAt: at, + kind: 'text' as const, + editable: true, + })), + ), + listWithEtags: jest.fn(async () => + Object.keys(STORED).map((path) => ({ path, size: 1, etag: 'e' })), + ), + readRange: jest.fn(async (_a: string, path: string) => { + touched.push(`readRange ${path}`); + return { path, content: STORED[path], updatedAt: at }; + }), + read: jest.fn(async (_a: string, path: string) => ({ + path, + content: STORED[path], + updatedAt: at, + })), + save: jest.fn(async (_a: string, path: string) => { + touched.push(`save ${path}`); + }), + delete: jest.fn(async (_a: string, path: string) => { + touched.push(`delete ${path}`); + }), + deletePrefix: jest.fn(async (_a: string, path: string) => { + touched.push(`deletePrefix ${path}`); + return 1; + }), + streamRaw: jest.fn(async (_a: string, path: string) => { + touched.push(`streamRaw ${path}`); + return { + body: Readable.from([Buffer.from(STORED[path] ?? '')]), + size: 1, + contentType: 'text/plain', + kind: 'text' as const, + }; + }), + }; + const jwt = new JwtService({ secret: 'test' }); + const openLinks = new OpenLinkService(jwt); + const controller = new FileController( + { findById: async (id: string) => ({ id }) } as unknown as IAgentGateway, + new WorkspaceFiles(raw as unknown as IFileGateway), + {} as IBridleGateway, + {} as SyncGuardService, + openLinks, + ); + return { controller, touched, jwt }; +} + +const SPELLINGS = [ + 'data/channels/telegram.json', + 'data/secrets/agent-1.json', + 'data/channels.json', + 'browser-state/admin/default.json', + './data//Secrets/agent-1.json', + 'data%2Fsecrets%2Fagent-1.json', + 'data\\secrets\\agent-1.json', + 'DATA/CHANNELS/TELEGRAM.JSON', +]; + +const refusal = async (run: Promise) => { + const err = await run.catch((e: unknown) => e); + return err instanceof ForbiddenException ? err.message : 'not refused'; +}; + +const req = { user: { sub: 'user-admin', roles: ['Admin'] } } as never; + +describe('Files routes and the secret stores (RANCH-8)', () => { + it.each(SPELLINGS)( + 'GET content %p: 403 write-only, nothing read', + async (path) => { + const { controller, touched } = make(); + expect(await refusal(controller.read('agent-1', { path } as never))).toBe( + SECRET_STORE_REFUSAL, + ); + expect(touched).toEqual([]); + }, + ); + + it('PUT and DELETE content: 403, nothing written', async () => { + const { controller, touched } = make(); + expect( + await refusal( + controller.save( + 'agent-1', + 'data/secrets/agent-1.json', + { content: '{"K":"v"}' } as never, + req, + ), + ), + ).toBe(SECRET_STORE_REFUSAL); + expect( + await refusal( + controller.delete( + 'agent-1', + { path: 'data/channels.json' } as never, + req, + ), + ), + ).toBe(SECRET_STORE_REFUSAL); + expect( + await refusal( + controller.delete( + 'agent-1', + { path: 'browser-state', recursive: true } as never, + req, + ), + ), + ).toBe(SECRET_STORE_REFUSAL); + expect(touched).toEqual([]); + }); + + it('the list leaves them out', async () => { + const { controller } = make(); + const paths = (await controller.list('agent-1')).map((n) => n.path); + expect(paths).toEqual(['notes.md', 'data/usage.json']); + }); + + it('a selection that names one deletes the rest and leaves the store', async () => { + const { controller, touched } = make(); + const out = await controller.deleteSelection( + 'agent-1', + { + paths: ['notes.md', 'data/secrets/agent-1.json', 'data'], + confirm: true, + } as never, + req, + ); + expect(touched).toEqual(['delete notes.md', 'delete data/usage.json']); + expect(out.deleted).toBe(2); + }); + + it('no open link is minted for one', async () => { + const { controller } = make(); + expect( + await refusal( + controller.openLink('agent-1', { path: 'Data/Channels.json' } as never), + ), + ).toBe(SECRET_STORE_REFUSAL); + const ok = await controller.openLink('agent-1', { + path: 'notes.md', + } as never); + expect(ok.url).toContain('/files/raw?token='); + }); + + it('a link minted before the change no longer opens one: 403, nothing streamed', async () => { + const { controller, touched, jwt } = make(); + // As OpenLinkService signed links before RANCH-8: no typ, any path. + const old = jwt.sign( + { + sub: 'open-link', + agentId: 'agent-1', + path: 'data/channels/telegram.json', + kind: 'text', + }, + { expiresIn: 60 }, + ); + const res = new (class extends Writable { + statusCode = 200; + body: string | null = null; + _write(_c: unknown, _e: string, cb: () => void) { + cb(); + } + status(code: number) { + this.statusCode = code; + return this; + } + type() { + return this; + } + send(body: string) { + this.body = body; + return this; + } + setHeader() { + return this; + } + })(); + await controller.raw('agent-1', old, res as unknown as Response); + expect(res.statusCode).toBe(403); + expect(res.body).toBe(SECRET_STORE_REFUSAL); + expect(touched).toEqual([]); + }); + + it('an ordinary file reads as before', async () => { + const { controller, touched } = make(); + await controller.read('agent-1', { path: 'notes.md' } as never); + expect(touched).toEqual(['readRange notes.md']); + }); +}); diff --git a/api/src/slices/agent/file/file.controller.ts b/api/src/slices/agent/file/file.controller.ts index c353205e7..1aad4a31e 100644 --- a/api/src/slices/agent/file/file.controller.ts +++ b/api/src/slices/agent/file/file.controller.ts @@ -2,6 +2,7 @@ import { Body, Controller, Delete, + ForbiddenException, Get, HttpCode, Inject, @@ -30,7 +31,12 @@ import { IAgentGateway } from '#/agent/agent/domain'; import { ManagesAgent } from '#/agent/agent/guards'; import { IBridleGateway } from '#/bridle/domain'; import { Public } from '#/user/auth/guards'; -import { IFileGateway, OpenLinkService, SyncGuardService } from './domain'; +import { + OpenLinkService, + SyncGuardService, + WorkspaceFiles, + isSecretStorePath, +} from './domain'; import { RANGE_BYTES, fileLimits } from './domain/file.limits'; import { TEXT_EXTENSIONS, kindFromPath } from './domain/fileKind'; import { rawResponseHeaders } from './domain/rawHeaders'; @@ -64,7 +70,8 @@ export class FileController { constructor( @Inject(forwardRef(() => IAgentGateway)) private agentGateway: IAgentGateway, - private fileGateway: IFileGateway, + // Not the raw gateway (RANCH-8): secret stores are write-only here. + private fileGateway: WorkspaceFiles, @Inject(forwardRef(() => IBridleGateway)) private bridleGateway: IBridleGateway, private syncGuard: SyncGuardService, @@ -74,7 +81,7 @@ export class FileController { @Get() @ApiOperation({ summary: - 'List files for an agent. Each node says whether it is text or binary and whether it can be edited in place.', + 'List files for an agent. Each node says whether it is text or binary and whether it can be edited in place. Files that hold stored secrets (data/secrets/, data/channels/, data/channels.json, browser-state/) are write-only and never listed; reading, writing or deleting one answers 403.', }) @ApiOkResponse({ type: [FileNodeDto] }) async list(@Param('agentId') agentId: string): Promise { @@ -197,6 +204,9 @@ export class FileController { let deleted = 0; const files = new Set(all.map((n) => n.path)); for (const p of wanted) { + // A selection is not refused for naming a secret store (RANCH-8): the + // store is left alone and everything else selected goes. + if (isSecretStorePath(p)) continue; if (files.has(p)) { await this.fileGateway.delete(agentId, p); deleted += 1; @@ -272,7 +282,7 @@ export class FileController { @ApiOperation({ operationId: 'exportAgentFiles', summary: - 'Download a ZIP archive of the agent’s entire S3 prefix (files, skills, runtime state). Used as a safety net before destructive actions.', + 'Download a ZIP archive of the agent’s entire S3 prefix (files, skills, runtime state). Used as a safety net before destructive actions. Stored secrets are write-only and not exported; when any were left out the archive holds SECRET_STORES_NOT_EXPORTED.txt.', }) async exportZip( @Param('agentId') agentId: string, @@ -335,7 +345,7 @@ export class FileController { @ApiOperation({ operationId: 'readAgentFileRaw', summary: - 'Stream the raw stored file for an open link. 401 when the token is invalid, expired or minted for another agent; 404 (plain text) when the file is gone.', + 'Stream the raw stored file for an open link. 401 when the token is invalid, expired or minted for another agent; 404 (plain text) when the file is gone; 403 for a file that holds stored secrets, which are write-only.', }) async raw( @Param('agentId') agentId: string, @@ -364,6 +374,11 @@ export class FileController { res.status(404).type('text/plain').send('File not found'); return; } + // A link minted before RANCH-8 for a secret store: write-only. + if (err instanceof ForbiddenException) { + res.status(403).type('text/plain').send(err.message); + return; + } throw err; } for (const [name, value] of Object.entries( diff --git a/api/src/slices/agent/file/file.module.ts b/api/src/slices/agent/file/file.module.ts index 080c45fc6..a0dec3e81 100644 --- a/api/src/slices/agent/file/file.module.ts +++ b/api/src/slices/agent/file/file.module.ts @@ -16,6 +16,7 @@ import { IFileGateway } from './domain/file.gateway'; import { S3FileGateway } from './data/file.gateway'; import { OpenLinkService } from './domain/openLink.service'; import { SyncGuardService } from './domain/syncGuard.service'; +import { WorkspaceFiles } from './domain/workspaceFiles'; import { TranscriptReaderService } from './domain/transcriptReader.service'; // AgentModule must be a forwardRef here because BridleModule (which imports @@ -43,6 +44,9 @@ import { TranscriptReaderService } from './domain/transcriptReader.service'; provide: IFileGateway, useClass: S3FileGateway, }, + // What every caller-facing surface holds instead of IFileGateway: the + // secret stores are write-only through it (RANCH-8). + WorkspaceFiles, OpenLinkService, SyncGuardService, TranscriptReaderService, diff --git a/api/src/slices/agent/file/file.tool.proposals.spec.ts b/api/src/slices/agent/file/file.tool.proposals.spec.ts index 2e9a670e3..e52d72115 100644 --- a/api/src/slices/agent/file/file.tool.proposals.spec.ts +++ b/api/src/slices/agent/file/file.tool.proposals.spec.ts @@ -3,6 +3,7 @@ import { FileTool, isPrivateAddress } from './file.tool'; import type { IAgentGateway } from '#/agent/agent/domain'; import type { IBridleGateway } from '#/bridle/domain'; import type { IFileGateway, SyncGuardService } from './domain'; +import { WorkspaceFiles } from './domain/workspaceFiles'; import { ProposalNeedsRemoveConfirmError } from './domain/fileProposal.service'; import { UserRoleTypes } from '#/user/user/domain'; import { asTrustedAgent } from '#/mcp/testing'; @@ -138,7 +139,7 @@ function harness() { }; const tool = new FileTool( agents as unknown as IAgentGateway, - files as unknown as IFileGateway, + new WorkspaceFiles(files as unknown as IFileGateway), {} as IBridleGateway, {} as SyncGuardService, archive as never, diff --git a/api/src/slices/agent/file/file.tool.spec.ts b/api/src/slices/agent/file/file.tool.spec.ts index 15ebdc2e2..25d204fa0 100644 --- a/api/src/slices/agent/file/file.tool.spec.ts +++ b/api/src/slices/agent/file/file.tool.spec.ts @@ -3,6 +3,7 @@ import { FileTool } from './file.tool'; import type { IAgentGateway } from '#/agent/agent/domain'; import type { IBridleGateway } from '#/bridle/domain'; import type { IFileGateway, SyncGuardService } from './domain'; +import { WorkspaceFiles } from './domain/workspaceFiles'; import { UserRoleTypes } from '#/user/user/domain'; import { asTrustedAgent } from '#/mcp/testing'; import { permissionOver } from '#/agent/agent/domain/__fixtures__/agentPermission'; @@ -176,7 +177,7 @@ function harness(): Harness { const tool = new FileTool( agents as unknown as IAgentGateway, - files as unknown as IFileGateway, + new WorkspaceFiles(files as unknown as IFileGateway), bridle as unknown as IBridleGateway, syncGuard as unknown as SyncGuardService, archive as never, diff --git a/api/src/slices/agent/file/file.tool.ts b/api/src/slices/agent/file/file.tool.ts index 6f9e6bb6d..552cf103e 100644 --- a/api/src/slices/agent/file/file.tool.ts +++ b/api/src/slices/agent/file/file.tool.ts @@ -1,4 +1,9 @@ -import { Inject, Injectable, forwardRef } from '@nestjs/common'; +import { + ForbiddenException, + Inject, + Injectable, + forwardRef, +} from '@nestjs/common'; import { Request } from 'express'; import { z } from 'zod'; import { Tool, ToolAudience, ToolTopics } from '#mcp'; @@ -18,7 +23,6 @@ import { IAuthTokenPayload } from '#/user/auth/domain'; import { callerAgentId, err } from '#/mcp/tooling'; import { FileProposalService, - IFileGateway, IMPORT_MAX_ARCHIVE_BYTES, IMPORT_MAX_FILES, IMPORT_MAX_FILE_BYTES, @@ -29,6 +33,7 @@ import { RANGE_BYTES, SyncGuardService, WorkspaceArchiveService, + WorkspaceFiles, buildFilesZip, expectedEtags, isZipSignature, @@ -89,7 +94,9 @@ export class FileTool implements IConditionallyListedTool { constructor( @Inject(forwardRef(() => IAgentGateway)) private readonly agents: IAgentGateway, - private readonly files: IFileGateway, + // Not the raw gateway (RANCH-8): secret stores are write-only here, + // for every caller, the Owner and the assistant included. + private readonly files: WorkspaceFiles, @Inject(forwardRef(() => IBridleGateway)) private readonly bridle: IBridleGateway, private readonly syncGuard: SyncGuardService, @@ -120,7 +127,9 @@ export class FileTool implements IConditionallyListedTool { description: 'Files stored for an agent (path, size, kind, editable, updated). Use ' + '`prefix` to narrow (for example `skills/`). Binary files can be listed ' + - 'and exported, not read. Resolve the agent id with list_agents first.', + 'and exported, not read. Files that hold stored secrets (the agent’s ' + + 'secrets, its channel settings, saved browser sessions) are write-only ' + + 'and never listed. Resolve the agent id with list_agents first.', parameters: z.object({ agentId: z.string(), prefix: z @@ -167,7 +176,9 @@ export class FileTool implements IConditionallyListedTool { description: 'Reads a text file in slices of up to 512 KB; the result carries ' + '`nextOffset` when more remains — pass it as `offset` to continue. ' + - 'Binary files are refused: offer export_agent_files instead.', + 'Binary files are refused: offer export_agent_files instead. A file ' + + 'that holds stored secrets is refused for everybody: secrets are ' + + 'write-only, set them with the secret and channel tools.', parameters: z.object({ agentId: z.string(), path: z.string().describe('Relative path, e.g. agent.config.json'), @@ -823,10 +834,16 @@ export class FileTool implements IConditionallyListedTool { if (refusal) return refusal; let deleted = 1; - if (args.recursive) { - deleted = await this.files.deletePrefix(args.agentId, args.path); - } else { - await this.files.delete(args.agentId, args.path); + try { + if (args.recursive) { + deleted = await this.files.deletePrefix(args.agentId, args.path); + } else { + await this.files.delete(args.agentId, args.path); + } + } catch (e) { + // A secret store is write-only (RANCH-8): say so, as the route does. + if (e instanceof ForbiddenException) return err(e.message); + throw e; } return ok({ @@ -931,7 +948,8 @@ export class FileTool implements IConditionallyListedTool { 'runtime state) as a zip — the safety net before a destructive change. ' + 'The zip cannot travel through the chat: the result gives the console ' + 'path to open (it needs the person’s login) and how many files the ' + - 'archive will hold. Resolve the agent id with list_agents first.', + 'archive will hold. Stored secrets are write-only and not exported. ' + + 'Resolve the agent id with list_agents first.', parameters: z.object({ agentId: z.string() }), }) async exportAgentFiles( diff --git a/api/src/slices/agent/file/fileImport.controller.spec.ts b/api/src/slices/agent/file/fileImport.controller.spec.ts index af8c55864..2ae751cb6 100644 --- a/api/src/slices/agent/file/fileImport.controller.spec.ts +++ b/api/src/slices/agent/file/fileImport.controller.spec.ts @@ -5,6 +5,7 @@ import { } from '@nestjs/common'; import { IAgentGateway } from '#/agent/agent/domain'; import { IFileGateway } from './domain/file.gateway'; +import { WorkspaceFiles } from './domain/workspaceFiles'; import { IArchiveEntry, IImportPlan } from './domain/import.types'; import { WorkspaceArchiveService } from './domain/workspaceArchive.service'; import { FileImportController } from './fileImport.controller'; @@ -75,7 +76,11 @@ function build( }; }), } as unknown as WorkspaceArchiveService; - const controller = new FileImportController(agents, files, archives); + const controller = new FileImportController( + agents, + new WorkspaceFiles(files), + archives, + ); return { controller, files, archives, release }; } diff --git a/api/src/slices/agent/file/fileImport.controller.ts b/api/src/slices/agent/file/fileImport.controller.ts index 4086840ae..0e2949bbe 100644 --- a/api/src/slices/agent/file/fileImport.controller.ts +++ b/api/src/slices/agent/file/fileImport.controller.ts @@ -36,7 +36,7 @@ import { } from '@nestjs/swagger'; import { randomUUID } from 'crypto'; import { IAgentGateway } from '#/agent/agent/domain'; -import { IFileGateway } from './domain/file.gateway'; +import { WorkspaceFiles } from './domain/workspaceFiles'; import { IMPORT_MAX_ARCHIVE_BYTES, IMPORT_MAX_FILES, @@ -93,7 +93,8 @@ export class FileImportController { constructor( @Inject(forwardRef(() => IAgentGateway)) private readonly agentGateway: IAgentGateway, - private readonly fileGateway: IFileGateway, + // Not the raw gateway (RANCH-8): secret stores are write-only here. + private readonly fileGateway: WorkspaceFiles, private readonly archives: WorkspaceArchiveService, ) {} diff --git a/api/src/slices/mcp/tool-secrets.files.spec.ts b/api/src/slices/mcp/tool-secrets.files.spec.ts new file mode 100644 index 000000000..83c6042d6 --- /dev/null +++ b/api/src/slices/mcp/tool-secrets.files.spec.ts @@ -0,0 +1,246 @@ +/** + * RANCH-8, audit §2 (FR-010, FR-013). CLEAN-275 made a stored secret + * write-only for everybody; the assistant's file tools still read the + * workspace files the secrets are kept in. Here the workspace holds a + * sentinel in each secret store (the agent's secrets, a person's secrets, + * the bot token, the legacy channel file, a person's browser cookies), and + * every file tool is called on them by an operator agent and by the Owner + * in person: no result carries the sentinel, reads and writes are refused + * with the write-only sentence, and the list and the export count leave the + * stores out. Ordinary files work as before. + * + * The tools run over the real `WorkspaceFiles` and the real + * `FileProposalService`, so a write is refused where production refuses it. + */ +import type { Request } from 'express'; +import { UserRoleTypes } from '#/user/user/domain'; +import { FileTool } from '#/agent/file/file.tool'; +import { WorkspaceFiles } from '#/agent/file/domain/workspaceFiles'; +import { FileProposalService } from '#/agent/file/domain/fileProposal.service'; +import { SECRET_STORE_REFUSAL } from '#/agent/file/domain/secretStorePaths'; +import type { IFileGateway } from '#/agent/file/domain/file.gateway'; +import type { IAgentGateway } from '#/agent/agent/domain'; +import { asPerson, asTrustedAgent } from '#/mcp/testing'; +import { permissionOver } from '#/agent/agent/domain/__fixtures__/agentPermission'; + +const SENTINEL = 'SENTINEL-SECRET-files-9c1e'; + +const STORED: Record = { + 'notes.md': 'ordinary notes', + 'data/usage.json': '{"turns":3}', + 'data/secrets/agent-a.json': `{"API_KEY":"${SENTINEL}"}`, + 'data/secrets/user-1.json': `{"PERSONAL":"${SENTINEL}"}`, + 'data/channels/telegram.json': `{"botToken":"${SENTINEL}"}`, + 'data/channels.json': `{"telegram":{"botToken":"${SENTINEL}"}}`, + 'browser-state/admin/default.json': `{"cookies":[{"value":"${SENTINEL}"}]}`, +}; + +/** A raw gateway that hands any stored object back, sentinel and all. */ +function leakyFiles() { + const at = new Date('2026-12-01T10:00:00Z'); + const writes: string[] = []; + const raw = { + list: jest.fn(async () => + Object.keys(STORED).map((path) => ({ + path, + size: STORED[path].length, + updatedAt: at, + kind: 'text' as const, + editable: true, + })), + ), + listWithEtags: jest.fn(async () => + Object.keys(STORED).map((path) => ({ path, size: 1, etag: 'e' })), + ), + readRange: jest.fn(async (_a: string, path: string) => ({ + path, + kind: 'text', + editable: true, + totalSize: (STORED[path] ?? '').length, + offset: 0, + size: (STORED[path] ?? '').length, + nextOffset: null, + hasMore: false, + updatedAt: at, + content: STORED[path] ?? '', + })), + read: jest.fn(async (_a: string, path: string) => ({ + path, + kind: 'text', + size: (STORED[path] ?? '').length, + content: STORED[path] ?? '', + updatedAt: at, + })), + headEtag: jest.fn(async (_a: string, path: string) => + path in STORED ? 'e' : null, + ), + save: jest.fn(async (_a: string, path: string) => { + writes.push(`save ${path}`); + }), + delete: jest.fn(async (_a: string, path: string) => { + writes.push(`delete ${path}`); + }), + deletePrefix: jest.fn(async (_a: string, path: string) => { + writes.push(`deletePrefix ${path}`); + return 1; + }), + putProposalContent: jest.fn(async () => { + writes.push('proposal'); + }), + }; + return { files: new WorkspaceFiles(raw as unknown as IFileGateway), writes }; +} + +function harness() { + const agents = { + findById: jest.fn(async (id: string) => ({ + id, + name: id === 'agent-ranch' ? 'Ranch' : 'Support', + isAdmin: id === 'agent-ranch', + createdById: null, + lastPullAt: null, + lastSyncAt: null, + })), + findAdmin: jest.fn(async () => ({ id: 'agent-ranch', name: 'Ranch' })), + } as unknown as IAgentGateway; + const { files, writes } = leakyFiles(); + const proposals = new FileProposalService( + files, + { create: jest.fn() } as never, + {} as never, + { findActiveTurn: () => null } as never, + agents, + ); + const tool = new FileTool( + agents, + files, + {} as never, + {} as never, + {} as never, + proposals, + {} as never, + permissionOver(agents), + ); + return { tool, writes }; +} + +const request = (): Request => + ({ + user: { sub: 'agent:agent-ranch', email: '', roles: [UserRoleTypes.Owner] }, + }) as unknown as Request; + +const CALLERS: [string, () => Request][] = [ + ['an operator agent', () => asTrustedAgent(request())], + [ + 'the Owner in person', + () => asPerson(request(), UserRoleTypes.Owner, 'user-owner'), + ], +]; + +const SECRET_PATHS = Object.keys(STORED).filter( + (p) => p !== 'notes.md' && p !== 'data/usage.json', +); + +const textOf = (r: { content: { text: string }[] }) => + r.content.map((c) => c.text).join('\n'); + +describe('the file tools never return a stored secret, to anybody (RANCH-8)', () => { + for (const [who, as] of CALLERS) { + for (const agentId of ['agent-a', 'agent-ranch']) { + describe(`${who}, on ${agentId}`, () => { + it('list_agent_files leaves every secret store out', async () => { + const { tool } = harness(); + const text = textOf( + await tool.listAgentFiles({ agentId }, null, as() as never), + ); + expect(text).not.toContain(SENTINEL); + expect(text).not.toMatch( + /data\/secrets|data\/channels|browser-state/, + ); + expect( + JSON.parse(text).files.map((f: { path: string }) => f.path), + ).toEqual(['notes.md', 'data/usage.json']); + }); + + it.each(SECRET_PATHS)( + 'read_agent_file %p is refused, without the value', + async (path) => { + const { tool } = harness(); + const result = await tool.readAgentFile( + { agentId, path }, + null, + as() as never, + ); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(SECRET_STORE_REFUSAL); + }, + ); + + it('write_agent_file and create_agent_file are refused before any proposal', async () => { + const { tool, writes } = harness(); + for (const call of [ + () => + tool.writeAgentFile( + { + agentId, + path: 'data/secrets/agent-a.json', + content: '{"K":"v"}', + }, + null, + as() as never, + ), + () => + tool.createAgentFile( + { agentId, path: 'browser-state/new.json', content: '{}' }, + null, + as() as never, + ), + ]) { + const result = await call(); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(SECRET_STORE_REFUSAL); + } + expect(writes).toEqual([]); + }); + + it('delete_agent_file is refused, for a file and for the folder', async () => { + const { tool, writes } = harness(); + for (const [path, recursive] of [ + ['data/channels/telegram.json', false], + ['Data/Secrets', true], + ] as const) { + const result = await tool.deleteAgentFile( + { agentId, path, recursive, confirm: true }, + null, + as() as never, + ); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(SECRET_STORE_REFUSAL); + } + expect(writes).toEqual([]); + }); + + it('export_agent_files counts no secret store', async () => { + const { tool } = harness(); + const text = textOf( + await tool.exportAgentFiles({ agentId }, null, as() as never), + ); + expect(JSON.parse(text).fileCount).toBe(2); + expect(text).not.toContain(SENTINEL); + }); + + it('an ordinary file reads as before', async () => { + const { tool } = harness(); + const text = textOf( + await tool.readAgentFile( + { agentId, path: 'notes.md' }, + null, + as() as never, + ), + ); + expect(JSON.parse(text).content).toBe('ordinary notes'); + }); + }); + } + } +}); diff --git a/api/src/slices/setup/writeOnly/writeOnly.census.spec.ts b/api/src/slices/setup/writeOnly/writeOnly.census.spec.ts index 559df0365..d1f27ef2e 100644 --- a/api/src/slices/setup/writeOnly/writeOnly.census.spec.ts +++ b/api/src/slices/setup/writeOnly/writeOnly.census.spec.ts @@ -15,6 +15,9 @@ * withheld, and none shown looks like a credential unless filed. * 5. A route or a tool that holds a gateway of a secret-bearing store * answers its rows through a presenter, never as the gateway gave them. + * 6. A route or a tool that holds the raw workspace gateway is filed with + * the fixed paths it touches; the file surfaces hold `WorkspaceFiles`, + * through which the secret stores are write-only (RANCH-8). * * And the helpers themselves: what `writeOnly`, `secretWrite`, * `envAsRead`, `runtimeServersAsRead` and `scrubSecrets` promise. @@ -450,6 +453,67 @@ describe('5. a route or a tool answers secret-bearing rows through a presenter', }); }); +// ── 6: workspace files (RANCH-8) ───────────────────────────── + +/** + * An agent's stored secrets are kept partly in its workspace: the agent's + * and each person's secrets, its messaging bot's token, people's browser + * cookies (`agent/file/domain/secretStorePaths.ts`). The raw `IFileGateway` + * serves any of them by path. A route or a tool hands paths a caller chose + * to `WorkspaceFiles` instead, which refuses or skips those files for + * everybody; holding `IFileGateway` itself is filed here with the fixed + * paths it touches. Row presenters cannot see file content, so the rule is + * who holds what, not what a line returns (research R4). + */ +const RAW_FILE_HOLDERS: Record = { + 'agent/agent/agent.controller.ts': + 'wipe() of a deleted agent, with the operator’s opt-in; no path from the caller', + 'agent/agent/agentAdmin.tool.ts': + 'wipe() of a deleted agent, as the route; no path from the caller', + 'bridle/bridle.controller.ts': + 'data/sessions/bridle:.jsonl only, behind requireChannelAccess', + 'usage/usage.controller.ts': 'data/usage.json only', + 'rancher/rancher.tool.ts': 'injected, not called', +}; + +describe('6. a route or a tool that holds the raw workspace gateway is filed', () => { + const sources = files( + SLICES, + (p) => p.endsWith('.controller.ts') || p.endsWith('.tool.ts'), + ); + const holdsRaw = (file: string) => + /(?:private|readonly|public)[\s\w]*?\s\w+\??:\s*IFileGateway\b/.test( + read(file), + ); + + it('every holder is filed with what it touches', () => { + const unfiled = sources + .filter(holdsRaw) + .map(rel) + .filter((file) => !(file in RAW_FILE_HOLDERS)); + expect(unfiled).toEqual([]); + }); + + it('the file slice’s own surfaces hold WorkspaceFiles', () => { + for (const file of [ + 'agent/file/file.controller.ts', + 'agent/file/fileImport.controller.ts', + 'agent/file/file.tool.ts', + ]) { + const source = read(join(SLICES, file)); + expect(holdsRaw(join(SLICES, file))).toBe(false); + expect(source).toMatch(/:\s*WorkspaceFiles\b/); + } + }); + + it('keeps no filing for a file that no longer holds it', () => { + const stale = Object.keys(RAW_FILE_HOLDERS).filter( + (file) => !holdsRaw(join(SLICES, file)), + ); + expect(stale).toEqual([]); + }); +}); + // ── The helpers ────────────────────────────────────────────── describe('the write-only helpers', () => { From ad918eabaa92b4d361c327a45e3d54bd26975ae1 Mon Sep 17 00:00:00 2001 From: "Maksym Hryzodub [DREAM]" Date: Tue, 1 Dec 2026 14:46:56 +0200 Subject: [PATCH 05/13] fix(api): an ability a limited Admin ticks stays within their ceiling (RANCH-8) Owner decision C10. The custom pick in force keeps who stated it (grantedById); the MCP handler notes that granter and manageCaller carries it on the party. canManage's assistant line also asks granterReaches: the Owner's pick works on every agent the person reaches, an Admin's only on agents that Admin reaches at the time of use, and none once the Admin is gone, disabled or a User. Refused for that reason alone, the tool says the ability does not cover that agent (reason not_covered) and names nobody. A limited Admin's new account without the assistant gets an exception switching it off (withholdFor). Co-Authored-By: Claude --- .../domain/agentPermission.granter.spec.ts | 144 ++++++++++++++++++ .../agent/domain/agentPermission.service.ts | 45 +++++- .../peer/domain/__fixtures__/peerAccess.ts | 9 ++ api/src/slices/agent/peer/peerAdmin.tool.ts | 5 + .../slices/mcp/assistantGrantCaller.spec.ts | 44 ++++++ .../slices/mcp/assistantGrantReach.spec.ts | 127 +++++++++++++++ .../interfaces/assistant-grant.interface.ts | 7 + .../services/handlers/mcp-tools.handler.ts | 21 ++- api/src/slices/mcp/tooling.ts | 120 ++++++++++++++- .../assistantAccess/assistantAccess.wiring.ts | 4 + .../data/assistantAccess.gateway.ts | 8 +- .../data/assistantAccess.mapper.ts | 6 +- .../domain/assistantAccess.gateway.ts | 10 +- .../domain/assistantAccess.service.spec.ts | 82 +++++++++- .../domain/assistantAccess.service.ts | 95 +++++++++++- .../domain/assistantAccess.types.ts | 12 ++ .../domain/assistantToolPolicy.service.ts | 9 ++ 17 files changed, 723 insertions(+), 25 deletions(-) create mode 100644 api/src/slices/agent/agent/domain/agentPermission.granter.spec.ts diff --git a/api/src/slices/agent/agent/domain/agentPermission.granter.spec.ts b/api/src/slices/agent/agent/domain/agentPermission.granter.spec.ts new file mode 100644 index 000000000..6fb253b64 --- /dev/null +++ b/api/src/slices/agent/agent/domain/agentPermission.granter.spec.ts @@ -0,0 +1,144 @@ +import { + grantNotCoveringOf, + type ICallerParty, +} from '#/user/auth/domain/auth.types'; +import { UserRoleTypes } from '#/user/user/domain'; +import { + MemoryAgentAccessGateway, + usersGateway, +} from '#/user/agentAccess/domain/__fixtures__/agentAccess'; +import { AgentAccessService } from '#/user/agentAccess/domain/agentAccess.service'; +import type { IAgentGateway } from './agent.gateway'; +import type { IAgentData } from './agent.types'; +import { AgentPermissionService } from './agentPermission.service'; + +/** + * RANCH-8, owner decision C10 (FR-014, FR-015, FR-016). The fourth line of + * `canManage`, the one an assistant ability opens, now also asks whoever + * ticked the ability: the Owner's pick works on every agent the person + * reaches, an Admin's only on those the Admin reaches at the time of use, + * and a pick whose Admin is gone, disabled or no longer an Admin opens no + * agent. The reach is the real one, over lists in memory. + * + * Agents A, B, C. `lim` is an Admin limited to A; `open` an Admin with no + * lists; the User reaches every agent. + */ + +const agent = (id: string, name: string): IAgentData => + ({ id, name, isAdmin: false, createdById: null }) as IAgentData; +const AGENTS = [ + agent('A', 'alpha'), + agent('B', 'bravo'), + agent('C', 'charlie'), +]; + +function make( + people: { id: string; role: UserRoleTypes; status?: string }[] = [ + { id: 'owner', role: UserRoleTypes.Owner }, + { id: 'lim', role: UserRoleTypes.Admin }, + { id: 'open', role: UserRoleTypes.Admin }, + { id: 'user', role: UserRoleTypes.User }, + ], +) { + const lists = new MemoryAgentAccessGateway(['A', 'B', 'C']); + lists.seed('lim', true, [{ agentId: 'A', list: 'allowed' }]); + const access = new AgentAccessService(lists, usersGateway(people as never)); + const agents = { + findById: (id: string) => + Promise.resolve(AGENTS.find((a) => a.id === id) ?? null), + findAdmin: () => Promise.resolve(null), + } as unknown as IAgentGateway; + return { permission: new AgentPermissionService(agents, access), lists }; +} + +/** The User, admitted by an assistant ability ticked by `grantedBy`. */ +const granted = (grantedBy?: string): ICallerParty => ({ + kind: 'person', + userId: 'user', + role: UserRoleTypes.User, + grantedThroughAssistant: true, + ...(grantedBy ? { grantedBy } : {}), +}); + +const managed = async ( + permission: AgentPermissionService, + party: ICallerParty, + id: string, +) => (await permission.manageable(party, id)) !== null; + +describe('an assistant ability works within whoever ticked it (RANCH-8)', () => { + it('ticked by an Admin limited to A: A works, B and C do not', async () => { + const { permission } = make(); + expect(await managed(permission, granted('lim'), 'A')).toBe(true); + expect(await managed(permission, granted('lim'), 'B')).toBe(false); + expect(await managed(permission, granted('lim'), 'C')).toBe(false); + }); + + it('the refusal is noted on the party, naming the agent and nothing of the Admin', async () => { + const { permission } = make(); + const party = granted('lim'); + await permission.manageable(party, 'B'); + expect(grantNotCoveringOf(party)).toEqual({ id: 'B', name: 'bravo' }); + expect(JSON.stringify(grantNotCoveringOf(party))).not.toContain('lim'); + // Nothing is noted for an agent the person may manage. + const ok = granted('lim'); + await permission.manageable(ok, 'A'); + expect(grantNotCoveringOf(ok)).toBeNull(); + }); + + it('ticked by the Owner, or by an Admin with no lists: every agent the User reaches (FR-016)', async () => { + const { permission } = make(); + for (const by of [undefined, 'owner', 'open']) { + for (const id of ['A', 'B', 'C']) { + expect(await managed(permission, granted(by), id)).toBe(true); + } + } + }); + + it('follows the Admin’s ceiling at the time of use, not of granting (FR-015)', async () => { + const { permission, lists } = make(); + expect(await managed(permission, granted('lim'), 'A')).toBe(true); + lists.seed('lim', true, [{ agentId: 'B', list: 'allowed' }]); + expect(await managed(permission, granted('lim'), 'A')).toBe(false); + expect(await managed(permission, granted('lim'), 'B')).toBe(true); + }); + + it('opens nothing once its Admin is gone, disabled or a User (FR-015)', async () => { + for (const lim of [ + null, + { id: 'lim', role: UserRoleTypes.Admin, status: 'disabled' }, + { id: 'lim', role: UserRoleTypes.User }, + ]) { + const { permission, lists } = make([ + { id: 'owner', role: UserRoleTypes.Owner }, + { id: 'user', role: UserRoleTypes.User }, + ...(lim ? [lim] : []), + ]); + // Even with no lists left, a demoted or disabled Admin vouches for nothing. + lists.seed('lim', false, []); + for (const id of ['A', 'B', 'C']) { + expect(await managed(permission, granted('lim'), id)).toBe(false); + } + } + }); + + it('never widens the User: an agent out of the User’s reach stays not found, with no note', async () => { + const { permission, lists } = make(); + lists.seed('user', true, [{ agentId: 'B', list: 'allowed' }]); + const party = granted('open'); + expect(await managed(permission, party, 'A')).toBe(false); + expect(grantNotCoveringOf(party)).toBeNull(); + }); + + it('an Admin or the creator is not held to a granter: they manage by their own line', async () => { + const { permission } = make(); + const admin: ICallerParty = { + kind: 'person', + userId: 'open', + role: UserRoleTypes.Admin, + grantedThroughAssistant: true, + grantedBy: 'lim', + }; + expect(await managed(permission, admin, 'C')).toBe(true); + }); +}); diff --git a/api/src/slices/agent/agent/domain/agentPermission.service.ts b/api/src/slices/agent/agent/domain/agentPermission.service.ts index 5e763441d..0177eaf62 100644 --- a/api/src/slices/agent/agent/domain/agentPermission.service.ts +++ b/api/src/slices/agent/agent/domain/agentPermission.service.ts @@ -2,6 +2,7 @@ import { Injectable } from '@nestjs/common'; import type { IAgentManagerResolver } from '#/mcp/interfaces/agent-manager.interface'; import { highestPersonRole, + noteGrantNotCovering, type IAuthTokenPayload, type ICallerParty, } from '#/user/auth/domain/auth.types'; @@ -26,6 +27,16 @@ export type IManagedAgent = Pick; */ export abstract class IAgentReach { abstract reaches(caller: IManagingPerson, agentId: string): Promise; + + /** + * Whether the account that ticked an assistant ability still stands + * behind it on this agent (RANCH-8, FR-015): it exists, is enabled, and + * is the Owner, or an Admin who reaches the agent today. A reach that + * cannot tell says no: an ability nobody can vouch for opens nothing. + */ + granterReaches(_granterId: string, _agentId: string): Promise { + return Promise.resolve(false); + } } /** The default: no access lists yet, everybody reaches every agent. */ @@ -34,6 +45,10 @@ export class OpenAgentReach extends IAgentReach { reaches(): Promise { return Promise.resolve(true); } + + granterReaches(): Promise { + return Promise.resolve(true); + } } const GUEST: ICallerParty = { kind: 'guest' }; @@ -50,7 +65,9 @@ const GUEST: ICallerParty = { kind: 'guest' }; * AND caller reaches the agent) * OR (agent is not the Ranch admin agent AND the tool this call runs * was ticked for the caller in a custom pick of the assistant - * setting AND caller reaches the agent) + * setting AND caller reaches the agent AND (the pick is the + * Owner's OR whoever ticked it is a live Admin who reaches the + * agent today)) * * The caller is a party (`ICallerParty`): a person, a trusted agent, or a * guest. A trusted party is the Ranch admin agent acting for itself and is @@ -59,7 +76,13 @@ const GUEST: ICallerParty = { kind: 'guest' }; * The last line is for tools only, and for one tool at a time (CLEAN-254). * The Owner or an Admin ticks agent abilities for a person in a custom pick * of the assistant setting (CLEAN-240); such an ability works through the - * assistant on every agent that person reaches, whoever created it. A + * assistant on the agents that person reaches, whoever created them; ticked + * by an Admin, only on those of them that Admin reaches when it is used + * (RANCH-8, C10: an Admin never hands out more than their own ceiling, and a + * narrower ceiling later narrows what they handed out). When that is the + * only reason an agent is refused, the party is told so + * (`noteGrantNotCovering`) and the tool says the ability does not cover it, + * naming neither the Admin nor what they reach. A * built-in level (basic, standard, full) never does: nothing widens by * default, and for a User a level's agent abilities stay with line three. It arrives here as * `grantedThroughAssistant` on the party, which `manageCaller` sets when the @@ -127,12 +150,24 @@ export class AgentPermissionService implements IAgentManagerResolver { // being called is one the assistant setting gave this person. const isGranted = caller.grantedThroughAssistant === true; if (!isAdmin && !isCreator && !isGranted) return false; - return ( + const reaches = (await this.reach.reaches( { userId: caller.userId, role: caller.role }, agent.id, - )) === true - ); + )) === true; + if (!reaches) return false; + // Admitted by the grant alone: whoever ticked it must still reach the + // agent (RANCH-8, FR-014/FR-015). The Owner's pick carries no granter. + if (isAdmin || isCreator || typeof caller.grantedBy !== 'string') { + return true; + } + if ( + (await this.reach.granterReaches(caller.grantedBy, agent.id)) === true + ) { + return true; + } + noteGrantNotCovering(caller, agent as { id: string; name?: string }); + return false; } /** diff --git a/api/src/slices/agent/peer/domain/__fixtures__/peerAccess.ts b/api/src/slices/agent/peer/domain/__fixtures__/peerAccess.ts index 9bb5f1a50..951edbb6d 100644 --- a/api/src/slices/agent/peer/domain/__fixtures__/peerAccess.ts +++ b/api/src/slices/agent/peer/domain/__fixtures__/peerAccess.ts @@ -79,6 +79,15 @@ export function peerAccessOver(agents: unknown, world: IPeerWorld = {}) { const agentReach: IAgentReach = { reaches: (person, agentId) => Promise.resolve(reachOf(person.userId, person.role).has(agentId)), + // RANCH-8: whoever ticked an ability reaches the agent as their role and + // lists say, read now. + granterReaches: (granterId, agentId) => { + const granter = (world.users ?? PEOPLE).find((u) => u.id === granterId); + if (!granter) return Promise.resolve(false); + if (granter.role === UserRoleTypes.Owner) return Promise.resolve(true); + if (granter.role !== UserRoleTypes.Admin) return Promise.resolve(false); + return Promise.resolve(reachOf(granter.id, granter.role).has(agentId)); + }, }; const permission = permissionOver(agents, agentReach); const people = world.users ?? PEOPLE; diff --git a/api/src/slices/agent/peer/peerAdmin.tool.ts b/api/src/slices/agent/peer/peerAdmin.tool.ts index 316136fdf..112aeebdc 100644 --- a/api/src/slices/agent/peer/peerAdmin.tool.ts +++ b/api/src/slices/agent/peer/peerAdmin.tool.ts @@ -15,6 +15,7 @@ import { confirmed, manageCaller, operatorOnly, + grantNotCoveringRefusal, ownerOnlyRefusal, PERSON_REFUSAL, } from '#/mcp/tooling'; @@ -614,6 +615,10 @@ export class PeerAdminTool implements IConditionallyListedTool { // refusal that says who manages the agent (CLEAN-263). const ownerOnly = ownerOnlyRefusal(httpRequest, agentId); if (ownerOnly) return ownerOnly; + // An ability an Admin ticked that does not cover this agent: said + // so, naming neither the Admin nor what they reach (RANCH-8). + const notCovered = grantNotCoveringRefusal(httpRequest, agentId); + if (notCovered) return notCovered; throw new NotFoundException({ code: PeerErrorCodes.NotFound, message: 'Agent not found', diff --git a/api/src/slices/mcp/assistantGrantCaller.spec.ts b/api/src/slices/mcp/assistantGrantCaller.spec.ts index b0f8e62d4..4743192c2 100644 --- a/api/src/slices/mcp/assistantGrantCaller.spec.ts +++ b/api/src/slices/mcp/assistantGrantCaller.spec.ts @@ -244,3 +244,47 @@ describe('managesByGrantOnly / operatorOnly: a grant is not an operator’s powe ).toBeNull(); }); }); + +/** + * RANCH-8 (FR-014): who ticked the ability travels on the party of the call, + * so `canManage` can bound it by that account's reach. The Owner's pick + * carries nobody. + */ +describe('manageCaller carries who ticked the ability (RANCH-8)', () => { + it('an Admin’s pick: grantedBy is that Admin', () => { + const req = asPerson(assistantToken(), UserRoleTypes.User); + setCallerAssistantGrant(req, ['restart_agent'], 'user-admin'); + setCalledTool(req, 'restart_agent', 'Restart an agent'); + expect(manageCaller(req)).toEqual({ + ...USER, + grantedThroughAssistant: true, + grantedBy: 'user-admin', + }); + }); + + it('the Owner’s pick: no grantedBy', () => { + const req = granted(['restart_agent'], 'restart_agent'); + expect(manageCaller(req)).toEqual({ + ...USER, + grantedThroughAssistant: true, + }); + }); + + it('a tool the pick does not hold: no grant and no granter', () => { + const req = asPerson(assistantToken(), UserRoleTypes.User); + setCallerAssistantGrant(req, ['restart_agent'], 'user-admin'); + setCalledTool(req, 'delete_agent'); + expect(manageCaller(req)).toEqual(USER); + }); + + it('one party per call view; a new note builds it again', () => { + const req = asPerson(assistantToken(), UserRoleTypes.User); + setCallerAssistantGrant(req, ['restart_agent'], 'user-admin'); + setCalledTool(req, 'restart_agent'); + const first = manageCaller(req); + expect(manageCaller(req)).toBe(first); + setCalledTool(req, 'delete_agent'); + expect(manageCaller(req)).not.toBe(first); + expect(manageCaller(req)).toEqual(USER); + }); +}); diff --git a/api/src/slices/mcp/assistantGrantReach.spec.ts b/api/src/slices/mcp/assistantGrantReach.spec.ts index 96011841e..32ddd7cb0 100644 --- a/api/src/slices/mcp/assistantGrantReach.spec.ts +++ b/api/src/slices/mcp/assistantGrantReach.spec.ts @@ -1275,3 +1275,130 @@ describe('the Ranch admin agent is the Owner’s, and a person who has it is tol }); }); }); + +/** + * RANCH-8, owner decision C10 (FR-014 – FR-017). An ability an Admin ticked + * works only on agents that Admin reaches when it is used. Here ADMIN is + * limited to alpha, and the second User, who reaches alpha and bravo, holds + * every manage-agent tool from ADMIN's pick. Through the assistant: + * + * - alpha works as before; + * - bravo is refused, by every tool that answers an unknown agent with + * `agentNotFound`, with one sentence that names the ability and the + * agent, `reason: "not_covered"`, and nothing of ADMIN; + * - the Owner's pick of the same tools works on bravo. + */ +describe('an ability ticked by a limited Admin stays within that Admin (RANCH-8)', () => { + const pickBy = (userId: string, on: string[], grantedById: string | null) => + assistantSettings.set(userId, { + enabled: true, + level: 'custom', + custom: { on, known: registered.map((t) => t.metadata.name) }, + updatedById: grantedById ?? OWNER.id, + grantedById, + updatedAt: new Date('2026-12-01T10:00:00.000Z'), + } as IAssistantSettingData); + + beforeEach(() => + lists.seed(ADMIN.id, true, [{ agentId: A, list: 'allowed' }]), + ); + afterEach(() => lists.seed(ADMIN.id, false, [])); + + const NOT_COVERED = (title: string, name: string) => ({ + error: `${title} through the assistant does not cover agent «${name}». Ask the Owner.`, + reason: 'not_covered', + }); + + it('restart_agent: alpha works, bravo is not covered, and nothing is restarted there', async () => { + pickBy(USER2.id, ['restart_agent'], ADMIN.id); + const { call } = session(); + expect(await call('restart_agent', { id: A }, as('user2'))).toContain( + 'Restart started', + ); + const said = await call('restart_agent', { id: B }, as('user2')); + expect(JSON.parse(said)).toEqual(NOT_COVERED('Restart an agent', 'bravo')); + expect(said).not.toContain(ADMIN.id); + expect(said).not.toMatch(/admin(?!.*Owner)|alpha|limited|reach/i); + expect(agentDeploy.restartAgent.mock.calls).toEqual([[A]]); + }); + + it('the same agent named by its name is answered the same', async () => { + pickBy(USER2.id, ['restart_agent'], ADMIN.id); + const said = await session().call( + 'restart_agent', + { id: 'bravo' }, + as('user2'), + ); + // A tool that takes only an id says not found for a name; one that + // reads names would say not_covered. Either way nothing is restarted. + expect(agentDeploy.restartAgent).not.toHaveBeenCalled(); + expect(said).not.toContain(ADMIN.id); + }); + + it('the Owner’s pick of the same tool works on bravo (FR-016)', async () => { + pickBy(USER2.id, ['restart_agent'], null); + expect( + await session().call('restart_agent', { id: B }, as('user2')), + ).toContain('Restart started'); + }); + + it('an unknown agent and one out of the User’s reach keep their own answer', async () => { + pickBy(USER.id, ['restart_agent'], ADMIN.id); + const { call } = session(); + // USER reaches alpha only; bravo is out of their own reach. + const hidden = JSON.parse( + await call('restart_agent', { id: B }, as('user')), + ); + const ghost = JSON.parse( + await call('restart_agent', { id: GHOST }, as('user')), + ); + expect(hidden.reason).toBeUndefined(); + expect(hidden.error).toMatch(/not found/); + expect(ghost.error).toMatch(/not found/); + }); + + it('every manage-agent tool that answers an unknown agent with not found answers not_covered on bravo', async () => { + const naming = (id: string) => ({ + id, + agentId: id, + agent: id, + confirm: true, + peerId: 'peer-1', + peerAgentId: A, + path: 'SOUL.md', + content: 'text', + key: 'KEY', + value: 'value', + secrets: {}, + channels: [], + card: '{}', + open: true, + isPublic: true, + }); + const titleOf = (name: string) => + registered.find((t) => t.metadata.name === name)!.metadata.title; + const checked: string[] = []; + for (const name of MANAGE_AGENT) { + pickBy(USER2.id, [name], ADMIN.id); + const { call } = session(); + const ghost = await call(name, naming(GHOST), as('user2')); + if (!/not found/.test(ghost)) continue; + const said = await call(name, naming(B), as('user2')); + let parsed: { reason?: string; error?: string } | null = null; + try { + parsed = JSON.parse(said) as { reason?: string; error?: string }; + } catch { + parsed = null; + } + expect({ name, parsed }).toEqual({ + name, + parsed: NOT_COVERED(titleOf(name), 'bravo'), + }); + checked.push(name); + } + expect(checked.length).toBeGreaterThanOrEqual(10); + expect(agentDeploy.restartAgent).not.toHaveBeenCalled(); + expect(agentDeploy.stopAgent).not.toHaveBeenCalled(); + expect(agents.update).not.toHaveBeenCalled(); + }); +}); diff --git a/api/src/slices/mcp/interfaces/assistant-grant.interface.ts b/api/src/slices/mcp/interfaces/assistant-grant.interface.ts index f95282cd2..9c935fdc9 100644 --- a/api/src/slices/mcp/interfaces/assistant-grant.interface.ts +++ b/api/src/slices/mcp/interfaces/assistant-grant.interface.ts @@ -23,4 +23,11 @@ export const ASSISTANT_GRANT_RESOLVER = Symbol('ASSISTANT_GRANT_RESOLVER'); export interface IAssistantGrantResolver { grantedToolsFor(httpRequest: Request): Promise | null>; + /** + * Who ticked those names (RANCH-8, FR-014): the account behind the custom + * pick in force, when it was not the Owner. The abilities then work only + * on agents that account reaches at the time of the call. Null for the + * Owner's pick, and wherever `grantedToolsFor` answers null. + */ + grantedByFor?(httpRequest: Request): Promise; } diff --git a/api/src/slices/mcp/services/handlers/mcp-tools.handler.ts b/api/src/slices/mcp/services/handlers/mcp-tools.handler.ts index 66e7b4850..c2a127a21 100644 --- a/api/src/slices/mcp/services/handlers/mcp-tools.handler.ts +++ b/api/src/slices/mcp/services/handlers/mcp-tools.handler.ts @@ -169,7 +169,13 @@ export class McpToolsHandler extends McpHandlerBase { if (typeof client === 'string' && client) { setCallerTurnClient(view, client); } - if (calledTool) setCalledTool(view, calledTool); + if (calledTool) { + setCalledTool( + view, + calledTool, + this.registry.findTool?.(calledTool)?.metadata.title, + ); + } await this.noteManagedAgents(view); await this.noteAssistantGrant(view); return view; @@ -250,6 +256,7 @@ export class McpToolsHandler extends McpHandlerBase { if (!person || callerIsOperator(callRequest)) return; if (callerAgentId(callRequest) === null) return; let granted: string[] = []; + let grantedBy: string | null = null; try { const resolver = this.moduleRef.get( ASSISTANT_GRANT_RESOLVER, @@ -267,16 +274,26 @@ export class McpToolsHandler extends McpHandlerBase { tool.audience === 'manage-agent' && names.has(tool.metadata.name), ) .map((tool) => tool.metadata.name); + // Who ticked them (RANCH-8): an Admin's pick works only on agents + // that Admin reaches when it is used. A resolver that cannot say + // leaves the names to the Owner's rule, as before. + if ( + granted.length > 0 && + typeof resolver?.grantedByFor === 'function' + ) { + grantedBy = await resolver.grantedByFor(callRequest); + } } } catch (e) { granted = []; + grantedBy = null; this.logger.warn( `could not tell what the assistant setting gives user ${person.userId}: ${ e instanceof Error ? e.message : String(e) }`, ); } - setCallerAssistantGrant(callRequest, granted); + setCallerAssistantGrant(callRequest, granted, grantedBy); } /** diff --git a/api/src/slices/mcp/tooling.ts b/api/src/slices/mcp/tooling.ts index 7d771ce4d..f0cc333a8 100644 --- a/api/src/slices/mcp/tooling.ts +++ b/api/src/slices/mcp/tooling.ts @@ -1,6 +1,7 @@ import { ForbiddenException } from '@nestjs/common'; import type { Request } from 'express'; import { + grantNotCoveringOf, highestPersonRole, type IAuthTokenPayload, type ICallerParty, @@ -112,6 +113,7 @@ export function setCallerParty( configurable: true, writable: true, }); + forgetManageParty(httpRequest); } /** @@ -294,8 +296,9 @@ export function callerManagesAgents(httpRequest: Request): boolean { // // The Owner, or an Admin, may tick agent abilities for a person in a custom // pick of the assistant setting (CLEAN-240). Such an ability works through -// the assistant on every agent that person reaches, whoever created it, and -// never on the Ranch admin agent. A built-in level opens nothing this way. Two facts carry that, both noted by the MCP handler on +// the assistant on the agents that person reaches, whoever created them, and +// never on the Ranch admin agent. Ticked by an Admin, only on those of them +// that Admin reaches at the time of the call (RANCH-8). A built-in level opens nothing this way. Two facts carry that, both noted by the MCP handler on // the per-call view and never taken from the runtime or the model: // // - the `manage-agent` tool names ticked in the person's custom pick, when @@ -306,7 +309,10 @@ export function callerManagesAgents(httpRequest: Request): boolean { // `restart_agent`; it says nothing about `delete_agent`. const GRANT_PROPERTY = 'ranchAssistantGrant'; +const GRANTED_BY_PROPERTY = 'ranchAssistantGrantedBy'; const CALLED_TOOL_PROPERTY = 'ranchCalledTool'; +const CALLED_TITLE_PROPERTY = 'ranchCalledToolTitle'; +const MANAGE_PARTY_PROPERTY = 'ranchManageParty'; /** * Note the `manage-agent` tools the assistant setting gives the person this @@ -317,6 +323,7 @@ const CALLED_TOOL_PROPERTY = 'ranchCalledTool'; export function setCallerAssistantGrant( httpRequest: Request, names: Iterable, + grantedBy: string | null = null, ): void { Object.defineProperty(httpRequest, GRANT_PROPERTY, { value: new Set(names), @@ -324,6 +331,23 @@ export function setCallerAssistantGrant( configurable: true, writable: true, }); + forgetManageParty(httpRequest); + // Who ticked them, when it was not the Owner (RANCH-8): the abilities then + // work only on agents that account reaches when they are used. + Object.defineProperty(httpRequest, GRANTED_BY_PROPERTY, { + value: typeof grantedBy === 'string' && grantedBy ? grantedBy : null, + enumerable: false, + configurable: true, + writable: true, + }); +} + +/** Who ticked the noted abilities; null for the Owner's pick. */ +function assistantGrantedBy(httpRequest: Request): string | null { + const noted = (httpRequest as unknown as Record | null)?.[ + GRANTED_BY_PROPERTY + ]; + return typeof noted === 'string' && noted ? noted : null; } /** @@ -371,13 +395,32 @@ export function callerHoldsManageTools(httpRequest: Request): boolean { * Note which tool this call runs. The handler does this on tools/call, on * the per-call view, with the name it looked the tool up by. */ -export function setCalledTool(httpRequest: Request, toolName: string): void { +export function setCalledTool( + httpRequest: Request, + toolName: string, + title?: string, +): void { Object.defineProperty(httpRequest, CALLED_TOOL_PROPERTY, { value: toolName, enumerable: false, configurable: true, writable: true, }); + forgetManageParty(httpRequest); + // What the ability is called where a person reads it (RANCH-8). + Object.defineProperty(httpRequest, CALLED_TITLE_PROPERTY, { + value: typeof title === 'string' ? title : null, + enumerable: false, + configurable: true, + writable: true, + }); +} + +function calledToolTitle(httpRequest: Request): string | null { + const title = (httpRequest as unknown as Record | null)?.[ + CALLED_TITLE_PROPERTY + ]; + return typeof title === 'string' && title.trim() ? title.trim() : null; } function calledTool(httpRequest: Request): string | null { @@ -402,14 +445,80 @@ export function manageCaller(httpRequest: Request): ICallerParty { if (isPlainAgentToken(httpRequest)) return GUEST; const party = callerParty(httpRequest); if (party.kind !== 'person') return party; + // One party per call view (RANCH-8): what `canManage` notes on it about + // this call is what `agentNotFound` reads back. + const cached = (httpRequest as unknown as Record | null)?.[ + MANAGE_PARTY_PROPERTY + ] as ICallerParty | undefined; + if (cached) return cached; const person: ICallerParty = { kind: 'person', userId: party.userId, role: party.role, }; - return callerGrantedTool(httpRequest, calledTool(httpRequest)) - ? { ...person, grantedThroughAssistant: true } + const grantedBy = assistantGrantedBy(httpRequest); + const built: ICallerParty = callerGrantedTool( + httpRequest, + calledTool(httpRequest), + ) + ? { + ...person, + grantedThroughAssistant: true, + ...(grantedBy ? { grantedBy } : {}), + } : person; + if (httpRequest && typeof httpRequest === 'object') { + Object.defineProperty(httpRequest, MANAGE_PARTY_PROPERTY, { + value: built, + enumerable: false, + configurable: true, + writable: true, + }); + } + return built; +} + +/** A new note on the call view makes the party be built again. */ +function forgetManageParty(httpRequest: Request): void { + const view = httpRequest as unknown as Record | null; + if ( + view && + Object.prototype.hasOwnProperty.call(view, MANAGE_PARTY_PROPERTY) + ) { + delete view[MANAGE_PARTY_PROPERTY]; + } +} + +/** The reason a `not_covered` refusal carries; the model reads it. */ +export const NOT_COVERED_REASON = 'not_covered'; + +/** + * The refusal for `ref` when the ability the assistant setting gave this + * person does not cover that agent, and for that reason alone (RANCH-8, + * FR-014): an Admin limited to some agents ticked it, and the agent is not + * one of theirs today. It names the ability and the agent the person + * already sees, and never who ticked it or what that account reaches + * (FR-017). Null for anything else, which keeps its own answer. + */ +export function grantNotCoveringRefusal( + httpRequest: Request, + ref: string, +): ToolResult | null { + const party = (httpRequest as unknown as Record | null)?.[ + MANAGE_PARTY_PROPERTY + ] as ICallerParty | undefined; + const agent = grantNotCoveringOf(party); + if (!agent || typeof ref !== 'string') return null; + const wanted = ref.trim().toLowerCase(); + const named = + ref === agent.id || + (wanted !== '' && wanted === agent.name.trim().toLowerCase()); + if (!named) return null; + const ability = calledToolTitle(httpRequest) ?? 'This ability'; + return ok({ + error: `${ability} through the assistant does not cover agent «${agent.name || agent.id}». Ask the Owner.`, + reason: NOT_COVERED_REASON, + }); } /** @@ -556,6 +665,7 @@ export function agentNotFound( ): ToolResult { return ( ownerOnlyRefusal(httpRequest, ref, kind) ?? + grantNotCoveringRefusal(httpRequest, ref) ?? ok({ error: agentNotFoundText(httpRequest, ref) }) ); } diff --git a/api/src/slices/user/assistantAccess/assistantAccess.wiring.ts b/api/src/slices/user/assistantAccess/assistantAccess.wiring.ts index 444e0a4de..a21576a00 100644 --- a/api/src/slices/user/assistantAccess/assistantAccess.wiring.ts +++ b/api/src/slices/user/assistantAccess/assistantAccess.wiring.ts @@ -40,6 +40,10 @@ export class AssistantAccessWiring implements OnModuleInit { }); return { id: assistant.id, enabled: grant.enabled }; }, + // A limited Admin without the assistant creates accounts without it + // too (RANCH-8): never more than the creator. + withholdFor: (tx, person, creatorId) => + this.assistant.withholdFor(tx, person, creatorId), }); this.catalog.addPolicy(this.policy); diff --git a/api/src/slices/user/assistantAccess/data/assistantAccess.gateway.ts b/api/src/slices/user/assistantAccess/data/assistantAccess.gateway.ts index e06ff4f9b..b520aff55 100644 --- a/api/src/slices/user/assistantAccess/data/assistantAccess.gateway.ts +++ b/api/src/slices/user/assistantAccess/data/assistantAccess.gateway.ts @@ -58,12 +58,14 @@ export class AssistantAccessGateway extends IAssistantAccessGateway { async saveAccount( userId: string, data: IAssistantSettingWrite, + tx?: unknown, ): Promise { const values = this.values(data); - const row = await this.prisma.assistantAccountAccess.upsert({ + const client = (tx as Prisma.TransactionClient | undefined) ?? this.prisma; + const row = await client.assistantAccountAccess.upsert({ where: { userId }, - create: { userId, ...values }, - update: values, + create: { userId, ...values, grantedById: data.grantedById ?? null }, + update: { ...values, grantedById: data.grantedById ?? null }, }); return this.mapper.toAccount(row); } diff --git a/api/src/slices/user/assistantAccess/data/assistantAccess.mapper.ts b/api/src/slices/user/assistantAccess/data/assistantAccess.mapper.ts index fe56708c9..76e7387de 100644 --- a/api/src/slices/user/assistantAccess/data/assistantAccess.mapper.ts +++ b/api/src/slices/user/assistantAccess/data/assistantAccess.mapper.ts @@ -30,7 +30,11 @@ export class AssistantAccessMapper { } toAccount(row: AssistantAccountAccess): IAssistantAccountData { - return { userId: row.userId, ...this.toSetting(row) }; + return { + userId: row.userId, + ...this.toSetting(row), + grantedById: row.grantedById ?? null, + }; } /** diff --git a/api/src/slices/user/assistantAccess/domain/assistantAccess.gateway.ts b/api/src/slices/user/assistantAccess/domain/assistantAccess.gateway.ts index bc9eabe36..6728b300d 100644 --- a/api/src/slices/user/assistantAccess/domain/assistantAccess.gateway.ts +++ b/api/src/slices/user/assistantAccess/domain/assistantAccess.gateway.ts @@ -7,7 +7,10 @@ import type { export type IAssistantSettingWrite = Pick< IAssistantSettingData, 'enabled' | 'level' | 'custom' | 'updatedById' ->; +> & { + /** Account rows only (RANCH-8): who stands behind the custom pick. */ + grantedById?: string | null; +}; /** The two tables behind the assistant's settings (CLEAN-240). */ export abstract class IAssistantAccessGateway { @@ -22,9 +25,14 @@ export abstract class IAssistantAccessGateway { abstract listAccounts(): Promise; + /** + * `tx`: the client of a transaction already open, when the row must be + * written with something else (an account being created, RANCH-8). + */ abstract saveAccount( userId: string, data: IAssistantSettingWrite, + tx?: unknown, ): Promise; /** True when there was a row to remove. */ diff --git a/api/src/slices/user/assistantAccess/domain/assistantAccess.service.spec.ts b/api/src/slices/user/assistantAccess/domain/assistantAccess.service.spec.ts index 8bf17eb82..9321b8293 100644 --- a/api/src/slices/user/assistantAccess/domain/assistantAccess.service.spec.ts +++ b/api/src/slices/user/assistantAccess/domain/assistantAccess.service.spec.ts @@ -746,9 +746,7 @@ describe('each ability of a person’s role, and how it stands for them', () => }); // Which abilities act on one agent is the tool's audience, not a list a // console keeps (CLEAN-259): the manage-agent ones, whatever their state. - expect( - mine.abilities.filter((a) => a.onAgent).map((a) => a.name), - ).toEqual( + expect(mine.abilities.filter((a) => a.onAgent).map((a) => a.name)).toEqual( TOOLS.filter(([, , , audience]) => audience === 'manage-agent').map( ([name]) => name, ), @@ -1099,3 +1097,81 @@ describe('what a User is told about agent abilities', () => { ).toEqual([0, 0, 0]); }); }); + +/** + * RANCH-8 (owner decision C10, FR-014): an ability works only on agents + * whoever ticked it reaches when it is used. That person is recorded with + * the pick, apart from the last writer: turning the switch of an account + * does not make a pick the switcher's. + */ +describe('who stands behind a custom pick (RANCH-8)', () => { + const PICK = { level: 'custom' as const, on: ['restart_agent'] }; + + it('a pick an Admin states is the Admin’s; the Owner stating the same pick makes it the Owner’s', async () => { + const { service, accounts } = harness(); + await service.setAccount(asAdmin, USER.id, PICK); + expect(accounts.get(USER.id)?.grantedById).toBe(ADMIN.id); + expect( + ( + await service.grantFor({ + kind: 'person', + userId: USER.id, + role: UserRoleTypes.User, + }) + ).grantedBy, + ).toBe(ADMIN.id); + + await service.setAccount(asOwner, USER.id, PICK); + expect(accounts.get(USER.id)?.grantedById).toBe(OWNER.id); + }); + + it('a switch toggle carries the granter, whoever turns it', async () => { + const { service, accounts } = harness(); + await service.setAccount(asAdmin, USER.id, PICK); + await service.setAccount(asOwner, USER.id, { enabled: false }); + await service.setAccount(asOwner, USER.id, { enabled: true }); + expect(accounts.get(USER.id)?.grantedById).toBe(ADMIN.id); + expect(accounts.get(USER.id)?.updatedById).toBe(OWNER.id); + }); + + it('a built-in level has nobody behind it', async () => { + const { service, accounts } = harness(); + await service.setAccount(asAdmin, USER.id, PICK); + await service.setAccount(asAdmin, USER.id, { level: 'basic' }); + expect(accounts.get(USER.id)?.grantedById).toBeNull(); + }); + + it('a trusted party’s pick is the Owner’s: nobody to bound it by', async () => { + const { service, accounts } = harness(); + await service.setAccount({ kind: 'trusted' }, USER.id, PICK); + expect(accounts.get(USER.id)?.grantedById).toBeNull(); + }); + + it('a role pick (the Owner’s) and a row with no granter answer grantedBy null', async () => { + const { service } = harness(); + await service.setRole(asOwner, UserRoleTypes.User, PICK); + const grant = await service.grantFor({ + kind: 'person', + userId: USER_2.id, + role: UserRoleTypes.User, + }); + expect(grant.level).toBe('custom'); + expect(grant.grantedBy).toBeNull(); + }); + + it('a limited Admin’s new account without the assistant: withholdFor writes the exception with no granter', async () => { + const { service, accounts } = harness(); + expect( + await service.withholdFor( + { tx: true }, + { userId: USER_2.id, role: UserRoleTypes.User }, + ADMIN.id, + ), + ).toBe(true); + expect(accounts.get(USER_2.id)).toMatchObject({ + enabled: false, + updatedById: ADMIN.id, + grantedById: null, + }); + }); +}); diff --git a/api/src/slices/user/assistantAccess/domain/assistantAccess.service.ts b/api/src/slices/user/assistantAccess/domain/assistantAccess.service.ts index 05e90c130..4d73cf15e 100644 --- a/api/src/slices/user/assistantAccess/domain/assistantAccess.service.ts +++ b/api/src/slices/user/assistantAccess/domain/assistantAccess.service.ts @@ -29,6 +29,7 @@ import { IAssistantCustom, IAssistantEditor, IAssistantGrant, + IAssistantPerson, IAssistantPick, IAssistantResolved, IAssistantSettingData, @@ -43,6 +44,8 @@ interface IEffective { custom: IAssistantCustom | null; source: 'role' | 'account'; updatedAt: Date | null; + /** The account row's granter of its custom pick (RANCH-8); null otherwise. */ + grantedById: string | null; } export interface IAssistantAreaCount { @@ -271,16 +274,22 @@ export class AssistantAccessService { party: ICallerParty | null | undefined, ): Promise { if (!party || party.kind !== 'person') { - return { enabled: true, names: null, level: 'owner' }; + return { enabled: true, names: null, level: 'owner', grantedBy: null }; } if (!isAssistantRole(party.role)) { - return { enabled: true, names: null, level: 'owner' }; + return { enabled: true, names: null, level: 'owner', grantedBy: null }; } const effective = await this.effectiveFor(party.userId, party.role); return { enabled: effective.enabled, names: this.offeredNames(party.role, effective), level: effective.level, + // Only a custom pick on the account itself has a granter to bound it + // by; a role pick is the Owner's (RANCH-8, FR-014). + grantedBy: + effective.level === 'custom' && effective.source === 'account' + ? effective.grantedById + : null, }; } @@ -289,18 +298,27 @@ export class AssistantAccessService { role: AssistantRole, ): Promise { const own = await this.gateway.findAccount(userId); - if (own) return { ...this.pickFields(own), source: 'account' }; + if (own) { + return { + ...this.pickFields(own), + source: 'account', + grantedById: own.grantedById ?? null, + }; + } return this.effectiveForRole(role); } private async effectiveForRole(role: AssistantRole): Promise { const row = await this.gateway.findRole(role); - if (row) return { ...this.pickFields(row), source: 'role' }; + if (row) { + return { ...this.pickFields(row), source: 'role', grantedById: null }; + } return { ...ASSISTANT_ROLE_DEFAULTS[role], custom: null, source: 'role', updatedAt: null, + grantedById: null, }; } @@ -534,9 +552,16 @@ export class AssistantAccessService { } } + const editorId = editor.kind === 'person' ? editor.userId : null; await this.gateway.saveAccount(userId, { ...next, - updatedById: editor.kind === 'person' ? editor.userId : null, + updatedById: editorId, + grantedById: grantedByAfter( + before, + next, + editorId, + input.on !== undefined, + ), }); this.audit(editor, `account ${userId}`, before, next); return this.accountView(editor, userId); @@ -561,6 +586,36 @@ export class AssistantAccessService { return (await this.users.findById(userId))?.email ?? null; } + /** + * An account is being created by a limited Admin who does not have the + * assistant (RANCH-8): the account does not get it either. `tx` is the + * transaction creating it. Writes an exception switching it off only when + * the role's setting would switch it on; the role's level stays, so + * switching it on later is the Owner's one click. True when written. + */ + async withholdFor( + tx: unknown, + person: IAssistantPerson, + creatorId: string, + ): Promise { + if (!isAssistantRole(person.role)) return false; + const ofRole = await this.effectiveForRole(person.role); + if (!ofRole.enabled) return false; + await this.gateway.saveAccount( + person.userId, + { + enabled: false, + level: ofRole.level, + custom: ofRole.custom, + updatedById: creatorId, + // A role's pick is the Owner's: no granter to bound it by. + grantedById: null, + }, + tx, + ); + return true; + } + /** The exception goes with the account. */ async removeUser(userId: string): Promise { await this.gateway.deleteAccount(userId); @@ -598,6 +653,7 @@ export class AssistantAccessService { const effective: IEffective = { ...this.pickFields(row), source: 'account', + grantedById: row.grantedById ?? null, }; const chosen = this.chosenNames(effective); const offered = this.offeredNames(person.role, effective); @@ -1098,3 +1154,32 @@ export class AssistantAccessService { ); } } + +/** + * Who stands behind an account's custom pick once it is saved (RANCH-8, + * FR-014). Its abilities work only on agents that person reaches at the + * time of use, so the answer follows the act of picking, not the last + * writer: + * + * - not a custom pick: nobody; + * - a pick the editor states (`on` given): whoever saved it, null for a + * trusted party, which holds the Owner's power. The Owner saving the + * pick a limited Admin made makes it the Owner's, and the reverse; + * - the pick only carried along (the switch turned, the level re-chosen as + * custom without a list): whoever stood behind it before. A pick that + * was the role's is the Owner's and stays so. + */ +export function grantedByAfter( + before: { + level: AssistantLevelOrCustom; + source: 'role' | 'account'; + grantedById: string | null; + }, + next: { level: AssistantLevelOrCustom }, + editorId: string | null, + stated: boolean, +): string | null { + if (next.level !== 'custom') return null; + if (stated || before.level !== 'custom') return editorId; + return before.source === 'account' ? before.grantedById : null; +} diff --git a/api/src/slices/user/assistantAccess/domain/assistantAccess.types.ts b/api/src/slices/user/assistantAccess/domain/assistantAccess.types.ts index fdc4746f6..9f715772a 100644 --- a/api/src/slices/user/assistantAccess/domain/assistantAccess.types.ts +++ b/api/src/slices/user/assistantAccess/domain/assistantAccess.types.ts @@ -39,6 +39,12 @@ export interface IAssistantSettingData { export interface IAssistantAccountData extends IAssistantSettingData { userId: string; + /** + * Who ticked the custom pick in force (RANCH-8): its abilities work only + * on agents that person reaches at the time of use. Null for a pick made + * by a trusted party and for a row that holds no custom pick. + */ + grantedById?: string | null; } /** What an editor asks for. `on` only with `level: 'custom'`. */ @@ -88,6 +94,12 @@ export interface IAssistantGrant { /** null ⇒ no setting applies to this caller (Owner, trusted, not a person). */ names: ReadonlySet | null; level: AssistantLevelOrCustom | 'owner'; + /** + * Who made the custom pick in force (RANCH-8, FR-014): the account row's + * granter. Null for a role pick (only the Owner makes those), a trusted + * party's pick and anything that is not a custom pick. + */ + grantedBy: string | null; } export interface IAssistantPerson { diff --git a/api/src/slices/user/assistantAccess/domain/assistantToolPolicy.service.ts b/api/src/slices/user/assistantAccess/domain/assistantToolPolicy.service.ts index 6c5d0fd38..176457f65 100644 --- a/api/src/slices/user/assistantAccess/domain/assistantToolPolicy.service.ts +++ b/api/src/slices/user/assistantAccess/domain/assistantToolPolicy.service.ts @@ -95,6 +95,15 @@ export class AssistantToolPolicyService return grant.names; } + /** + * Who stands behind the names `grantedToolsFor` gives (RANCH-8): the + * account that ticked the custom pick in force, or null for the Owner's. + */ + async grantedByFor(httpRequest: Request): Promise { + if ((await this.grantedToolsFor(httpRequest)) === null) return null; + return (await this.settingFor(httpRequest))?.grantedBy ?? null; + } + /** The setting behind this call; null when the call is not the assistant's. */ private settingFor(httpRequest: Request): Promise { let pending = this.memo.get(httpRequest); From f736820b6177f7bd99200313a096b0c54c2ff984 Mon Sep 17 00:00:00 2001 From: "Maksym Hryzodub [DREAM]" Date: Tue, 1 Dec 2026 14:46:56 +0200 Subject: [PATCH 06/13] fix(api): only the Owner connects a tool server for someone else (RANCH-8) Owner decision C11. start_mcp_oauth refuses every non-Owner on the Ranch assistant, whatever the subject, and a subject that is not the caller's own anywhere. The runtime route lets through only the Owner's identity on the assistant. The state records who started it, and the callback asks again with that account as it is then, before the code exchange: a refused sign-in stores nothing. Co-Authored-By: Claude --- api/src/slices/mcp/narrowedLists.spec.ts | 15 +- .../oauth/domain/mcpOauth.service.spec.ts | 375 ++++++++++++++++-- .../oauth/domain/mcpOauth.service.ts | 108 ++++- .../mcpServer/oauth/mcpOauth.controller.ts | 12 +- .../mcpServer/oauth/mcpOauth.tool.spec.ts | 181 ++++++++- .../slices/mcpServer/oauth/mcpOauth.tool.ts | 55 ++- 6 files changed, 674 insertions(+), 72 deletions(-) diff --git a/api/src/slices/mcp/narrowedLists.spec.ts b/api/src/slices/mcp/narrowedLists.spec.ts index 35ff98be9..484478f31 100644 --- a/api/src/slices/mcp/narrowedLists.spec.ts +++ b/api/src/slices/mcp/narrowedLists.spec.ts @@ -1801,18 +1801,17 @@ describe('a tool server is connected for the assistant by the Owner alone', () = }, ); - it('their own account on that server is theirs to connect: it changes nothing about the assistant', async () => { + // RANCH-8, owner decision C11: this used to be allowed. On the assistant + // nobody but the Owner connects anything, their own account included: the + // assistant reads it in the Owner's conversations too. + it('not even their own account on that server: only the Owner connects anything on the assistant', async () => { const said = await asOpen('start_mcp_oauth', { ...SERVER, subject: ADMIN2.id, }); - expect(said).not.toMatch(/owner_only|not found/); - expect(oauth.start).toHaveBeenCalledWith({ - serverId: 'srv-1', - agentId: RANCH, - subject: ADMIN2.id, - }); + expect(await parsed(Promise.resolve(said))).toEqual(MANAGED); + expect(oauth.start).not.toHaveBeenCalled(); }); it('an agent they reach is theirs to connect; one out of reach is not found', async () => { @@ -2007,6 +2006,8 @@ const REACH_SERVICES: Record = { 'get_my_stats: the person’s own conversations, and `board.agents.reachable` says over how many agents', 'installationStats.service.ts': 'get_installation_stats: filed among the lists above; it carries `scope` and `notIncluded`', + 'mcpOauth.service.ts': + 'the callback of a tool-server sign-in asks again whether its starter reaches the agent (RANCH-8); start_mcp_oauth refuses before, as not found', }; describe('services that ask the reach for a tool', () => { diff --git a/api/src/slices/mcpServer/oauth/domain/mcpOauth.service.spec.ts b/api/src/slices/mcpServer/oauth/domain/mcpOauth.service.spec.ts index da9403309..eadd160c6 100644 --- a/api/src/slices/mcpServer/oauth/domain/mcpOauth.service.spec.ts +++ b/api/src/slices/mcpServer/oauth/domain/mcpOauth.service.spec.ts @@ -1,5 +1,17 @@ -import { BadRequestException } from '@nestjs/common'; -import { EPHEMERAL_BUNDLE_TTL_MS, McpOauthService, allowedReturnTo } from './mcpOauth.service'; +import { BadRequestException, ForbiddenException } from '@nestjs/common'; +import { + EPHEMERAL_BUNDLE_TTL_MS, + McpOauthService, + SIGNIN_NO_LONGER_ALLOWED, + SUBJECT_NOT_YOURS, + allowedReturnTo, +} from './mcpOauth.service'; +import { UserRoleTypes } from '#/user/user/domain/user.types'; +import { + MemoryAgentAccessGateway, + usersGateway, +} from '#/user/agentAccess/domain/__fixtures__/agentAccess'; +import { AgentAccessService } from '#/user/agentAccess/domain/agentAccess.service'; import { isEphemeralSubject, mcpOauthSecretKey, @@ -55,8 +67,9 @@ function harness() { states.set(data.state as string, { ...data, createdAt: new Date() }); return data; }), - findUnique: jest.fn(async ({ where }: { where: { state: string } }) => - states.get(where.state) ?? null, + findUnique: jest.fn( + async ({ where }: { where: { state: string } }) => + states.get(where.state) ?? null, ), delete: jest.fn(async ({ where }: { where: { state: string } }) => { states.delete(where.state); @@ -79,13 +92,17 @@ function harness() { }), }; const client = { - discover: jest - .fn() - .mockResolvedValue({ metadata: META, resource: SERVER.url, via: 'origin' }), + discover: jest.fn().mockResolvedValue({ + metadata: META, + resource: SERVER.url, + via: 'origin', + }), register: jest.fn().mockResolvedValue('client-1'), - exchangeCode: jest - .fn() - .mockResolvedValue({ access_token: 'at-new', refresh_token: 'rt-new', expires_in: 3600 }), + exchangeCode: jest.fn().mockResolvedValue({ + access_token: 'at-new', + refresh_token: 'rt-new', + expires_in: 3600, + }), revoke: jest.fn().mockResolvedValue(undefined), }; const servers = { @@ -94,11 +111,31 @@ function harness() { setOauthClientId: jest.fn().mockResolvedValue(undefined), }; const bridle = { notifyMcpConnected: jest.fn() }; - const agents = { findAll: jest.fn().mockResolvedValue([{ id: 'agent-1' }]) }; + const agents = { + findAll: jest.fn().mockResolvedValue([{ id: 'agent-1' }]), + // The Ranch assistant (RANCH-8): only the Owner connects anything on it. + findAdmin: jest + .fn() + .mockResolvedValue({ id: 'agent-ranch', name: 'Ranch' }), + }; + // Who is who today (RANCH-8): the callback asks again. + const people = [ + { id: 'user-owner', role: UserRoleTypes.Owner, status: 'active' }, + { id: 'user-admin', role: UserRoleTypes.Admin, status: 'active' }, + { id: 'user-a', role: UserRoleTypes.User, status: 'active' }, + ]; + const lists = new MemoryAgentAccessGateway([ + 'agent-1', + 'agent-2', + 'agent-ranch', + ]); + const access = new AgentAccessService(lists, usersGateway(people as never)); // Stands in for IInfraConfigGateway — the explicitly configured public // origin (setting or env), already stripped of a trailing slash. const infra = { - getConfiguredApiPublicUrl: jest.fn().mockResolvedValue('https://ranch.test'), + getConfiguredApiPublicUrl: jest + .fn() + .mockResolvedValue('https://ranch.test'), }; const service = new McpOauthService( @@ -109,8 +146,22 @@ function harness() { bridle as never, agents as never, infra as never, + access, ); - return { service, prisma, secrets, client, servers, bridle, agents, infra, stores }; + return { + service, + prisma, + secrets, + client, + servers, + bridle, + agents, + infra, + stores, + people, + lists, + states, + }; } /** Runs start + callback and returns what the callback stored. */ @@ -131,9 +182,17 @@ describe('McpOauthService — where a token lands', () => { it('stores a personal bundle under server + subject and names the subject to the agent', async () => { const h = harness(); - const result = await connect(h, { subject: 'user-a', email: 'a@example.test' }); + const result = await connect(h, { + subject: 'user-a', + email: 'a@example.test', + }); - expect(result).toEqual({ agentId: 'agent-1', serverName: 'Silpo', subject: 'user-a', redirectBack: null }); + expect(result).toEqual({ + agentId: 'agent-1', + serverName: 'Silpo', + subject: 'user-a', + redirectBack: null, + }); const stored = JSON.parse( h.stores.get('agent-1')!.get('mcpOauth:srv-1:user-a') as string, ) as IMcpOauthBundle; @@ -180,9 +239,9 @@ describe('McpOauthService — where a token lands', () => { it('refuses a state it never minted', async () => { const h = harness(); - await expect(h.service.handleCallback('srv-1', 'nope', 'code')).rejects.toBeInstanceOf( - BadRequestException, - ); + await expect( + h.service.handleCallback('srv-1', 'nope', 'code'), + ).rejects.toBeInstanceOf(BadRequestException); }); }); @@ -196,18 +255,24 @@ describe('McpOauthService — status', () => { bundle({ subject: 'user-a', email: 'a@example.test', connectedAt: 5 }), ); - await expect(h.service.status('srv-1', 'agent-1', 'user-a')).resolves.toEqual({ + await expect( + h.service.status('srv-1', 'agent-1', 'user-a'), + ).resolves.toEqual({ connected: true, scope: 'subject', email: 'a@example.test', connectedAt: 5, }); - await expect(h.service.status('srv-1', 'agent-1', 'user-b')).resolves.toEqual({ + await expect( + h.service.status('srv-1', 'agent-1', 'user-b'), + ).resolves.toEqual({ connected: true, scope: 'agent', }); await h.secrets.delete('agent-1', mcpOauthSecretKey('srv-1')); - await expect(h.service.status('srv-1', 'agent-1', 'user-b')).resolves.toEqual({ + await expect( + h.service.status('srv-1', 'agent-1', 'user-b'), + ).resolves.toEqual({ connected: false, scope: null, }); @@ -215,7 +280,11 @@ describe('McpOauthService — status', () => { it('does not count a bundle without a refresh token as connected', async () => { const h = harness(); - await h.secrets.set('agent-1', mcpOauthSecretKey('srv-1'), bundle({ refreshToken: null })); + await h.secrets.set( + 'agent-1', + mcpOauthSecretKey('srv-1'), + bundle({ refreshToken: null }), + ); await expect(h.service.status('srv-1', 'agent-1')).resolves.toMatchObject({ connected: false, }); @@ -228,11 +297,31 @@ describe('McpOauthService — sweeping per-browser subjects', () => { const now = Date.now(); const stale = now - EPHEMERAL_BUNDLE_TTL_MS - DAY; const fresh = now - DAY; - await h.secrets.set('agent-1', mcpOauthSecretKey('srv-1', 'anon-old'), bundle({ lastUsedAt: stale })); - await h.secrets.set('agent-1', mcpOauthSecretKey('srv-1', 'share-old'), bundle({ connectedAt: stale })); - await h.secrets.set('agent-1', mcpOauthSecretKey('srv-1', 'anon-new'), bundle({ lastUsedAt: fresh })); - await h.secrets.set('agent-1', mcpOauthSecretKey('srv-1', 'user-old'), bundle({ lastUsedAt: stale })); - await h.secrets.set('agent-1', mcpOauthSecretKey('srv-1'), bundle({ lastUsedAt: stale })); + await h.secrets.set( + 'agent-1', + mcpOauthSecretKey('srv-1', 'anon-old'), + bundle({ lastUsedAt: stale }), + ); + await h.secrets.set( + 'agent-1', + mcpOauthSecretKey('srv-1', 'share-old'), + bundle({ connectedAt: stale }), + ); + await h.secrets.set( + 'agent-1', + mcpOauthSecretKey('srv-1', 'anon-new'), + bundle({ lastUsedAt: fresh }), + ); + await h.secrets.set( + 'agent-1', + mcpOauthSecretKey('srv-1', 'user-old'), + bundle({ lastUsedAt: stale }), + ); + await h.secrets.set( + 'agent-1', + mcpOauthSecretKey('srv-1'), + bundle({ lastUsedAt: stale }), + ); await h.secrets.set('agent-1', 'OTHER_SECRET', 'keep'); const dropped = await h.service.sweepEphemeral(now); @@ -245,7 +334,11 @@ describe('McpOauthService — sweeping per-browser subjects', () => { 'mcpOauth:srv-1:user-old', ]); expect(h.client.revoke).toHaveBeenCalledTimes(2); - expect(h.client.revoke).toHaveBeenCalledWith(META.revocation_endpoint, 'rt', 'client-1'); + expect(h.client.revoke).toHaveBeenCalledWith( + META.revocation_endpoint, + 'rt', + 'client-1', + ); }); it('still deletes when the provider refuses the revocation', async () => { @@ -263,7 +356,11 @@ describe('McpOauthService — sweeping per-browser subjects', () => { it('treats a bundle with no timestamps as stale — nothing ever used it', async () => { const h = harness(); - await h.secrets.set('agent-1', mcpOauthSecretKey('srv-1', 'anon-x'), bundle()); + await h.secrets.set( + 'agent-1', + mcpOauthSecretKey('srv-1', 'anon-x'), + bundle(), + ); await expect(h.service.sweepEphemeral()).resolves.toBe(1); }); }); @@ -272,7 +369,10 @@ describe('secret key helpers', () => { it('builds and parses both key shapes', () => { expect(mcpOauthSecretKey('srv-1')).toBe('mcpOauth:srv-1'); expect(mcpOauthSecretKey('srv-1', 'user-a')).toBe('mcpOauth:srv-1:user-a'); - expect(parseMcpOauthSecretKey('mcpOauth:srv-1')).toEqual({ serverId: 'srv-1', subject: null }); + expect(parseMcpOauthSecretKey('mcpOauth:srv-1')).toEqual({ + serverId: 'srv-1', + subject: null, + }); expect(parseMcpOauthSecretKey('mcpOauth:srv-1:share-v7')).toEqual({ serverId: 'srv-1', subject: 'share-v7', @@ -306,7 +406,9 @@ describe('McpOauthService — scoped secret names from the file gateway', () => ], }); - await expect(h.service.status('srv-1', 'agent-1', 'user-a')).resolves.toMatchObject({ + await expect( + h.service.status('srv-1', 'agent-1', 'user-a'), + ).resolves.toMatchObject({ connected: true, scope: 'subject', email: 'a@example.test', @@ -335,7 +437,10 @@ describe('McpOauthService — scoped secret names from the file gateway', () => describe('McpOauthService — public API URL', () => { it('builds the redirect from the resolved public URL', async () => { const h = harness(); - const { authorizeUrl } = await h.service.start({ serverId: 'srv-1', agentId: 'agent-1' }); + const { authorizeUrl } = await h.service.start({ + serverId: 'srv-1', + agentId: 'agent-1', + }); expect(new URL(authorizeUrl).searchParams.get('redirect_uri')).toBe( 'https://ranch.test/mcp-servers/srv-1/oauth/callback', ); @@ -365,7 +470,10 @@ describe('McpOauthService — remembering the registered client id', () => { await h.service.start({ serverId: 'srv-1', agentId: 'agent-1' }); expect(h.client.register).toHaveBeenCalledTimes(1); - expect(h.servers.setOauthClientId).toHaveBeenCalledWith('srv-1', 'client-1'); + expect(h.servers.setOauthClientId).toHaveBeenCalledWith( + 'srv-1', + 'client-1', + ); expect(h.servers.update).not.toHaveBeenCalled(); }); @@ -438,9 +546,208 @@ describe('McpOauthService — where the callback page returns to', () => { it('accepts localhost for development and refuses non-http schemes', () => { const own = ['https://admin.ranch.test']; - expect(allowedReturnTo('http://localhost:3002/agents/a', own)).toBe('http://localhost:3002/agents/a'); + expect(allowedReturnTo('http://localhost:3002/agents/a', own)).toBe( + 'http://localhost:3002/agents/a', + ); expect(allowedReturnTo('javascript:alert(1)', own)).toBeNull(); expect(allowedReturnTo('not a url', own)).toBeNull(); expect(allowedReturnTo(undefined, own)).toBeNull(); }); }); + +/** + * RANCH-8, owner decision C11 (FR-019 – FR-021). Only the Owner connects a + * tool-server account on the Ranch assistant, and only the Owner connects + * one for another person anywhere. The runtime's door names no person, so on + * the assistant it lets through only the Owner's own identity. Whoever + * started a sign-in is asked again at the callback, as they are then, + * before the code is exchanged: a refused sign-in stores nothing and costs + * no call to the provider. + */ +describe('McpOauthService — who may connect (RANCH-8)', () => { + const startAndCallback = async ( + h: ReturnType, + input: Record, + ) => { + const { authorizeUrl } = await h.service.start({ + serverId: 'srv-1', + agentId: 'agent-1', + ...input, + } as never); + const state = new URL(authorizeUrl).searchParams.get('state') as string; + return h.service + .handleCallback('srv-1', state, 'code-1') + .catch((e: unknown) => e); + }; + + describe('the runtime door', () => { + it('on the assistant: the Owner’s channel and a live Owner pass; anybody else, and agent-wide, do not', async () => { + const h = harness(); + expect(await h.service.runtimeRefusal('agent-ranch', 'admin')).toBeNull(); + expect( + await h.service.runtimeRefusal('agent-ranch', 'user-owner'), + ).toBeNull(); + const refused = + 'Ranch is the Ranch assistant. Only the Owner can connect a tool server on it.'; + expect(await h.service.runtimeRefusal('agent-ranch', 'user-a')).toBe( + refused, + ); + expect(await h.service.runtimeRefusal('agent-ranch', 'user-admin')).toBe( + refused, + ); + expect(await h.service.runtimeRefusal('agent-ranch', undefined)).toBe( + refused, + ); + expect(await h.service.runtimeRefusal('agent-ranch', 'anon-x')).toBe( + refused, + ); + }); + + it('on another agent: as before', async () => { + const h = harness(); + expect(await h.service.runtimeRefusal('agent-1', 'user-a')).toBeNull(); + expect(await h.service.runtimeRefusal('agent-1', undefined)).toBeNull(); + }); + }); + + describe('the start is kept with who made it', () => { + it('records startedVia and startedById', async () => { + const h = harness(); + await h.service.start({ + serverId: 'srv-1', + agentId: 'agent-1', + startedVia: 'tool', + startedById: 'user-admin', + }); + await h.service.start({ serverId: 'srv-1', agentId: 'agent-1' }); + const rows = [...h.states.values()]; + expect(rows[0]).toMatchObject({ + startedVia: 'tool', + startedById: 'user-admin', + }); + expect(rows[1]).toMatchObject({ + startedVia: 'runtime', + startedById: null, + }); + }); + }); + + describe('the callback asks again (FR-021)', () => { + const refusedBefore = async ( + h: ReturnType, + out: unknown, + sentence: string, + ) => { + expect(out).toBeInstanceOf(ForbiddenException); + expect((out as ForbiddenException).message).toBe(sentence); + expect(h.client.exchangeCode).not.toHaveBeenCalled(); + expect(h.secrets.set).not.toHaveBeenCalled(); + expect(h.bridle.notifyMcpConnected).not.toHaveBeenCalled(); + expect(h.states.size).toBe(0); + }; + + it('an Admin who started it for themselves completes it, as before', async () => { + const h = harness(); + const out = await startAndCallback(h, { + subject: 'user-admin', + startedVia: 'tool', + startedById: 'user-admin', + }); + expect(out).toMatchObject({ subject: 'user-admin' }); + }); + + it('refused once the Admin is a User, disabled or gone', async () => { + for (const change of ['demote', 'disable', 'delete'] as const) { + const h = harness(); + const { authorizeUrl } = await h.service.start({ + serverId: 'srv-1', + agentId: 'agent-1', + subject: 'user-admin', + startedVia: 'tool', + startedById: 'user-admin', + }); + const admin = h.people.find((p) => p.id === 'user-admin')!; + if (change === 'demote') admin.role = UserRoleTypes.User; + if (change === 'disable') admin.status = 'disabled'; + if (change === 'delete') h.people.splice(h.people.indexOf(admin), 1); + const state = new URL(authorizeUrl).searchParams.get('state') as string; + const out = await h.service + .handleCallback('srv-1', state, 'code-1') + .catch((e: unknown) => e); + await refusedBefore(h, out, SIGNIN_NO_LONGER_ALLOWED); + } + }); + + it('refused once the agent is out of the Admin’s reach', async () => { + const h = harness(); + const { authorizeUrl } = await h.service.start({ + serverId: 'srv-1', + agentId: 'agent-1', + startedVia: 'tool', + startedById: 'user-admin', + }); + h.lists.seed('user-admin', true, [ + { agentId: 'agent-2', list: 'allowed' }, + ]); + const state = new URL(authorizeUrl).searchParams.get('state') as string; + const out = await h.service + .handleCallback('srv-1', state, 'code-1') + .catch((e: unknown) => e); + await refusedBefore(h, out, SIGNIN_NO_LONGER_ALLOWED); + }); + + it('a state an Admin started for somebody else is refused', async () => { + const h = harness(); + const out = await startAndCallback(h, { + subject: 'user-a', + startedVia: 'tool', + startedById: 'user-admin', + }); + await refusedBefore(h, out, SUBJECT_NOT_YOURS); + }); + + it('a state an Admin started on the assistant is refused, owner-only', async () => { + const h = harness(); + const out = await startAndCallback(h, { + agentId: 'agent-ranch', + subject: 'user-admin', + startedVia: 'tool', + startedById: 'user-admin', + }); + await refusedBefore( + h, + out, + 'Ranch is the Ranch assistant. Only the Owner can restart, stop or change it.', + ); + }); + + it('a runtime state on the assistant for a non-Owner subject is refused', async () => { + const h = harness(); + const out = await startAndCallback(h, { + agentId: 'agent-ranch', + subject: 'user-a', + }); + await refusedBefore( + h, + out, + 'Ranch is the Ranch assistant. Only the Owner can connect a tool server on it.', + ); + }); + + it('the Owner’s and a trusted party’s states complete anywhere, for anybody', async () => { + for (const startedById of ['user-owner', null]) { + const h = harness(); + const out = await startAndCallback(h, { + agentId: 'agent-ranch', + subject: 'user-a', + startedVia: 'tool', + startedById, + }); + expect(out).toMatchObject({ + agentId: 'agent-ranch', + subject: 'user-a', + }); + } + }); + }); +}); diff --git a/api/src/slices/mcpServer/oauth/domain/mcpOauth.service.ts b/api/src/slices/mcpServer/oauth/domain/mcpOauth.service.ts index 7367ef11d..0891bc690 100644 --- a/api/src/slices/mcpServer/oauth/domain/mcpOauth.service.ts +++ b/api/src/slices/mcpServer/oauth/domain/mcpOauth.service.ts @@ -1,5 +1,6 @@ import { BadRequestException, + ForbiddenException, Inject, Injectable, Logger, @@ -15,6 +16,13 @@ import { ISecretGateway } from '#/agent/secret/domain'; import { IBridleGateway } from '#/bridle/domain'; import { IInfraConfigGateway } from '#/setting/domain/infraConfig.gateway'; import { resolveAppOrigin } from '#/agent/shareLink/shareLink.tool'; +import { AgentAccessService } from '#/user/agentAccess/domain/agentAccess.service'; +import { UserRoleTypes } from '#/user/user/domain/user.types'; +import { + OWNER_CLIENT_ID, + clientIdOfAccount, +} from '#/bridle/domain/chatIdentity'; +import { ownerOnlyText } from '#/mcp/tooling'; import { IMcpServerGateway } from '../../domain/mcpServer.gateway'; import { McpOauthClient } from '../data/mcpOauth.client'; import { @@ -38,6 +46,22 @@ export const EPHEMERAL_BUNDLE_TTL_MS = 30 * 24 * 60 * 60 * 1000; const SWEEP_INTERVAL_MS = 6 * 60 * 60 * 1000; const SWEEP_INITIAL_DELAY_MS = 5 * 60 * 1000; +/** + * A person may connect only their own account, or the agent-wide connection + * of an agent they manage (RANCH-8, owner decision C11). + */ +export const SUBJECT_NOT_YOURS = + 'You can connect only your own account, or the agent-wide connection of ' + + 'an agent you manage. Only the Owner connects an account for another person.'; + +/** The callback's answer when whoever started a sign-in may no longer finish it. */ +export const SIGNIN_NO_LONGER_ALLOWED = + 'The account that started this sign-in may no longer connect it. Start ' + + 'again from the chat.'; + +/** Who started a sign-in, as `McpOauthState` keeps it (RANCH-8, FR-021). */ +export type McpOauthStartedVia = 'tool' | 'runtime'; + export interface IMcpOauthStartInput { serverId: string; /** The agent whose secret store receives the bundle. */ @@ -50,6 +74,14 @@ export interface IMcpOauthStartInput { subject?: string; /** Display only — "connected as …". */ email?: string; + /** + * Through which door it was started (RANCH-8): `tool` is start_mcp_oauth, + * whose person is `startedById` (null for a trusted party); `runtime` is + * the agent's own «server»__connect, which names no person. Re-checked at + * the callback. + */ + startedVia?: McpOauthStartedVia; + startedById?: string | null; /** * Where the callback page sends the person afterwards (CLEAN-120): the * chat they started from, as an absolute URL. Kept only when its origin is @@ -91,8 +123,62 @@ export class McpOauthService implements OnModuleInit, OnModuleDestroy { @Inject(forwardRef(() => IAgentGateway)) private readonly agents: IAgentGateway, private readonly infra: IInfraConfigGateway, + private readonly access: AgentAccessService, ) {} + // ── Who may connect what (RANCH-8, owner decision C11) ───────── + + /** + * The runtime's door (`POST …/oauth/start` with the bridle key). It names + * no person, only the chat sender as `subject`: on the Ranch assistant + * only the Owner's own identity passes (`admin`, or a live account whose + * role is Owner); anything else there, the agent-wide connection + * included, is refused. Other agents: as before. Null when allowed. + */ + async runtimeRefusal( + agentId: string, + subject: string | null | undefined, + ): Promise { + const assistant = await this.agents.findAdmin(); + if (!assistant || assistant.id !== agentId) return null; + if (subject === OWNER_CLIENT_ID) return null; + if (subject) { + const account = await this.access.liveAccount(subject); + if (account?.role === UserRoleTypes.Owner) return null; + } + return `${assistant.name.trim() || 'This agent'} is the Ranch assistant. Only the Owner can connect a tool server on it.`; + } + + /** + * Whether the person who started a sign-in may still complete it, asked + * with their role and reach today (FR-021): gone or disabled, no longer + * an Admin, the agent now out of their reach, or a rule the start broke. + * Null when it may complete. + */ + async personRefusal( + starterId: string, + agentId: string, + subject: string | null | undefined, + ): Promise { + const account = await this.access.liveAccount(starterId); + if (!account) return SIGNIN_NO_LONGER_ALLOWED; + if (account.role === UserRoleTypes.Owner) return null; + if (account.role !== UserRoleTypes.Admin) return SIGNIN_NO_LONGER_ALLOWED; + const assistant = await this.agents.findAdmin(); + if (assistant && assistant.id === agentId) { + return ownerOnlyText(assistant.name, 'change'); + } + const own = [account.id, clientIdOfAccount(account)]; + if (subject && !own.includes(subject)) return SUBJECT_NOT_YOURS; + const reach = await this.access.reachableIds({ + userId: account.id, + role: account.role, + }); + return (subject ? reach : reach.forChanges()).has(agentId) + ? null + : SIGNIN_NO_LONGER_ALLOWED; + } + onModuleInit(): void { // Late first pass so boot is not spent listing every agent's secrets; // unref so a cache sweep never holds the process open. @@ -216,6 +302,8 @@ export class McpOauthService implements OnModuleInit, OnModuleDestroy { codeVerifier, subject: input.subject ?? null, subjectEmail: input.email ?? null, + startedVia: input.startedVia ?? 'runtime', + startedById: input.startedById ?? null, redirectBack: allowedReturnTo(input.returnTo, await this.ownOrigins()), }, }); @@ -265,6 +353,16 @@ export class McpOauthService implements OnModuleInit, OnModuleDestroy { if (Date.now() - st.createdAt.getTime() > STATE_TTL_MS) { throw new BadRequestException('OAuth handshake expired — start again'); } + // Who started it is asked again, as they are now (RANCH-8, FR-021): + // before the code is exchanged, so a refused sign-in costs no call to + // the provider and stores nothing. The state is already gone. + const refusal = + st.startedVia === 'tool' + ? st.startedById + ? await this.personRefusal(st.startedById, st.agentId, st.subject) + : null + : await this.runtimeRefusal(st.agentId, st.subject); + if (refusal) throw new ForbiddenException(refusal); const server = await this.servers.findById(serverId); if (!server || !server.oauthClientId) { @@ -388,7 +486,9 @@ export class McpOauthService implements OnModuleInit, OnModuleDestroy { continue; } for (const entry of list.secrets) { - const key = parseMcpOauthSecretKey(bareSecretName(entry.name, agent.id)); + const key = parseMcpOauthSecretKey( + bareSecretName(entry.name, agent.id), + ); if (!key?.subject || !isEphemeralSubject(key.subject)) continue; const bundle = parseBundle(entry.value); const lastUsed = bundle?.lastUsedAt ?? bundle?.connectedAt ?? 0; @@ -396,7 +496,11 @@ export class McpOauthService implements OnModuleInit, OnModuleDestroy { if (bundle?.revocationEndpoint && bundle.refreshToken) { await this.client - .revoke(bundle.revocationEndpoint, bundle.refreshToken, bundle.clientId) + .revoke( + bundle.revocationEndpoint, + bundle.refreshToken, + bundle.clientId, + ) .catch((error: unknown) => this.logger.debug( `revoke failed for ${entry.name} on agent ${agent.id}: ${error instanceof Error ? error.message : String(error)}`, diff --git a/api/src/slices/mcpServer/oauth/mcpOauth.controller.ts b/api/src/slices/mcpServer/oauth/mcpOauth.controller.ts index 05692587d..3f85df945 100644 --- a/api/src/slices/mcpServer/oauth/mcpOauth.controller.ts +++ b/api/src/slices/mcpServer/oauth/mcpOauth.controller.ts @@ -1,6 +1,7 @@ import { randomBytes } from 'crypto'; import { BadRequestException, + ForbiddenException, Body, Controller, Get, @@ -52,14 +53,20 @@ export class McpOauthController { @ApiOperation({ operationId: 'startMcpOauth', summary: - 'Begin an OAuth connect for an agent. Returns the authorization URL the agent sends the user in chat.', + 'Begin an OAuth connect for an agent. Returns the authorization URL the agent sends the user in chat. On the Ranch assistant only the Owner connects anything: a subject that is not the Owner, and the agent-wide connection, answer 403.', }) @ApiOkResponse({ type: StartMcpOauthResultDto }) async start( @Param('serverId') serverId: string, @Body() dto: StartMcpOauthDto, ): Promise { + // The runtime cannot say who asked (one bridle key for all): on the + // Ranch assistant only the Owner's own identity is let through + // (RANCH-8, C11). + const refusal = await this.service.runtimeRefusal(dto.agentId, dto.subject); + if (refusal) throw new ForbiddenException(refusal); return this.service.start({ + startedVia: 'runtime', serverId, agentId: dto.agentId, ...(dto.subject ? { subject: dto.subject } : {}), @@ -134,7 +141,8 @@ export class McpOauthController { @ApiHeader({ name: 'x-bridle-api-key', required: true }) @ApiOperation({ operationId: 'mcpOauthStatus', - summary: 'Whether the given agent already has a usable token for this server.', + summary: + 'Whether the given agent already has a usable token for this server.', }) @ApiOkResponse({ type: McpOauthStatusDto }) async status( diff --git a/api/src/slices/mcpServer/oauth/mcpOauth.tool.spec.ts b/api/src/slices/mcpServer/oauth/mcpOauth.tool.spec.ts index f46bde4c9..d4f4436d1 100644 --- a/api/src/slices/mcpServer/oauth/mcpOauth.tool.spec.ts +++ b/api/src/slices/mcpServer/oauth/mcpOauth.tool.spec.ts @@ -8,7 +8,14 @@ import { McpOauthTool } from './mcpOauth.tool'; import type { McpOauthService } from './domain/mcpOauth.service'; import { UserRoleTypes } from '#/user/user/domain'; import { asPerson, asTrustedAgent } from '#/mcp/testing'; -import { openAccess } from '#/user/agentAccess/domain/__fixtures__/agentAccess'; +import { + MemoryAgentAccessGateway, + openAccess, + usersGateway, +} from '#/user/agentAccess/domain/__fixtures__/agentAccess'; +import { AgentAccessService } from '#/user/agentAccess/domain/agentAccess.service'; +import { setCallerOwnerOnlyAgent } from '#/mcp/tooling'; +import { SUBJECT_NOT_YOURS } from './domain/mcpOauth.service'; const AUTHORIZE_URL = 'https://auth.provider.test/authorize?client_id=abc&state=xyz'; @@ -34,6 +41,31 @@ function harness() { return { tool, oauth }; } +/** + * The Ranch assistant behind the access lists (RANCH-8): it is not among the + * agents a non-Owner may change, which is what `forChanges` takes out. + */ +function withAssistant( + adminLists: { agentId: string; list: 'allowed' | 'denied' }[] = [], +) { + const oauth = { + start: jest.fn().mockResolvedValue({ authorizeUrl: AUTHORIZE_URL }), + }; + const lists = new MemoryAgentAccessGateway([ + 'agent-ops', + 'agent-b', + 'agent-ranch', + ]); + if (adminLists.length) lists.seed('user-a', true, adminLists); + const access = new AgentAccessService(lists, usersGateway()); + access.attachAssistant({ + assistantId: () => Promise.resolve('agent-ranch'), + forPerson: () => Promise.resolve({ id: 'agent-ranch', enabled: true }), + }); + const tool = new McpOauthTool(oauth as unknown as McpOauthService, access); + return { tool, oauth }; +} + const textOf = (result: { content: { text: string }[] }) => result.content[0].text; @@ -69,7 +101,10 @@ describe('McpOauthTool — who may use it', () => { expect(oauth.start).not.toHaveBeenCalled(); }); - it('lets an Admin start a connection for another user, as an operator may', async () => { + // RANCH-8, C11: this used to be allowed. An Admin who connected their own + // account at a provider under another person's subject had that person's + // turns run with the Admin's account, and read what they sent there. + it('refuses an Admin who starts a connection for another user', async () => { const { tool, oauth } = harness(); const admin = asPerson( request([UserRoleTypes.Owner]), @@ -83,12 +118,9 @@ describe('McpOauthTool — who may use it', () => { admin, ); - expect(result.isError).toBeUndefined(); - expect(oauth.start).toHaveBeenCalledWith({ - serverId: 'mcp-1', - agentId: 'agent-ops', - subject: 'user-7', - }); + expect(result.isError).toBe(true); + expect(textOf(result)).toBe(SUBJECT_NOT_YOURS); + expect(oauth.start).not.toHaveBeenCalled(); }); it('refuses a call from a plain agent even by name', async () => { @@ -109,6 +141,8 @@ describe('McpOauthTool — starting a connect', () => { expect(oauth.start).toHaveBeenCalledWith({ serverId: 'mcp-1', agentId: 'agent-ops', + startedVia: 'tool', + startedById: null, }); expect(text).toContain(AUTHORIZE_URL); expect(text).toContain('"agentId": "agent-ops"'); @@ -125,6 +159,8 @@ describe('McpOauthTool — starting a connect', () => { expect(oauth.start).toHaveBeenCalledWith({ serverId: 'mcp-1', agentId: 'agent-support', + startedVia: 'tool', + startedById: null, }); }); @@ -177,3 +213,132 @@ describe('McpOauthTool — starting a connect', () => { ).rejects.toThrow('discovery timed out'); }); }); + +/** + * RANCH-8, owner decision C11 (FR-019, FR-020): who may start a sign-in, + * as contracts/tool-server-signin.md tabulates it. + */ +describe('McpOauthTool — who connects what (RANCH-8)', () => { + const admin = () => { + const req = asPerson( + request([UserRoleTypes.Owner], 'agent:agent-ranch'), + UserRoleTypes.Admin, + 'user-a', + ); + // What the MCP handler notes for a person who has the assistant. + setCallerOwnerOnlyAgent(req, { id: 'agent-ranch', name: 'Ranch' }, false); + return req; + }; + const owner = () => + asPerson( + request([UserRoleTypes.Owner], 'agent:agent-ranch'), + UserRoleTypes.Owner, + 'user-owner', + ); + const OWNER_ONLY = { + error: + 'Ranch is the Ranch assistant. Only the Owner can restart, stop or change it.', + reason: 'owner_only', + }; + + it.each([ + ['for the Owner', 'admin'], + ['for themselves', 'user-a'], + ['agent-wide', undefined], + ['for another person', 'user-7'], + ])( + 'an Admin on the assistant, %s: owner-only, nothing started', + async (_label, subject) => { + const { tool, oauth } = withAssistant(); + const result = await tool.startMcpOauth( + { + serverId: 'mcp-1', + agentId: 'agent-ranch', + ...(subject ? { subject } : {}), + }, + null, + admin(), + ); + expect(JSON.parse(textOf(result))).toEqual(OWNER_ONLY); + expect(oauth.start).not.toHaveBeenCalled(); + }, + ); + + it('an Admin on an agent they manage: their own and agent-wide go, recording who started them', async () => { + const { tool, oauth } = withAssistant(); + for (const subject of ['user-a', undefined]) { + const result = await tool.startMcpOauth( + { + serverId: 'mcp-1', + agentId: 'agent-b', + ...(subject ? { subject } : {}), + }, + null, + admin(), + ); + expect(result.isError).toBeUndefined(); + } + expect(oauth.start.mock.calls.map((c) => c[0])).toEqual([ + { + serverId: 'mcp-1', + agentId: 'agent-b', + subject: 'user-a', + startedVia: 'tool', + startedById: 'user-a', + }, + { + serverId: 'mcp-1', + agentId: 'agent-b', + startedVia: 'tool', + startedById: 'user-a', + }, + ]); + }); + + it('an Admin on an agent they manage, for anybody else or a reserved id: refused', async () => { + const { tool, oauth } = withAssistant(); + for (const subject of ['user-7', 'admin', 'cron', 'agent:agent-b']) { + const result = await tool.startMcpOauth( + { serverId: 'mcp-1', agentId: 'agent-b', subject }, + null, + admin(), + ); + expect(textOf(result)).toBe(SUBJECT_NOT_YOURS); + } + expect(oauth.start).not.toHaveBeenCalled(); + }); + + it('an Admin out of reach of the agent: not found, as before', async () => { + const { tool, oauth } = withAssistant([ + { agentId: 'agent-ops', list: 'allowed' }, + ]); + const result = await tool.startMcpOauth( + { serverId: 'mcp-1', agentId: 'agent-b', subject: 'user-a' }, + null, + admin(), + ); + expect(textOf(result)).toMatch(/not found/); + expect(oauth.start).not.toHaveBeenCalled(); + }); + + it('the Owner on the assistant, for anybody: goes', async () => { + const { tool, oauth } = withAssistant(); + for (const subject of ['admin', 'user-7', undefined]) { + const result = await tool.startMcpOauth( + { + serverId: 'mcp-1', + agentId: 'agent-ranch', + ...(subject ? { subject } : {}), + }, + null, + owner(), + ); + expect(result.isError).toBeUndefined(); + } + expect(oauth.start).toHaveBeenCalledTimes(3); + expect(oauth.start.mock.calls[0][0]).toMatchObject({ + startedVia: 'tool', + startedById: 'user-owner', + }); + }); +}); diff --git a/api/src/slices/mcpServer/oauth/mcpOauth.tool.ts b/api/src/slices/mcpServer/oauth/mcpOauth.tool.ts index 35eecfaca..e56849796 100644 --- a/api/src/slices/mcpServer/oauth/mcpOauth.tool.ts +++ b/api/src/slices/mcpServer/oauth/mcpOauth.tool.ts @@ -5,6 +5,7 @@ import { Tool, ToolAudience, ToolTopics } from '#mcp'; import { callerAgentId, callerIsOperator, + callerIsOwner, callerPerson, err, ok, @@ -13,10 +14,11 @@ import { agentNotFound, callerParty, } from '#/mcp/tooling'; +import { clientIdOfAccount } from '#/bridle/domain/chatIdentity'; import { AgentAccessService } from '#/user/agentAccess/domain/agentAccess.service'; import type { IConditionallyListedTool } from '#/mcp/interfaces/conditional-listing.interface'; import { IAuthTokenPayload } from '#/user/auth/domain'; -import { McpOauthService } from './domain/mcpOauth.service'; +import { McpOauthService, SUBJECT_NOT_YOURS } from './domain/mcpOauth.service'; type AuthedRequest = Request & { user?: IAuthTokenPayload }; @@ -34,11 +36,17 @@ type AuthedRequest = Request & { user?: IAuthTokenPayload }; * * Audience `admin`, which is stricter than `person`: registering and * connecting MCP servers is an operator's job in the console (`mcp-servers` - * routes, Owner and Admin). `subject` stays an argument, because an Owner or - * Admin may start a connection for another user, and is checked against the - * party all the same: whoever is not an operator may name only themselves. - * That second check cannot fire while the audience is `admin`; it is there so - * that lowering the audience later does not reopen "name any user" (CLEAN-232). + * routes, Owner and Admin). Who connects what (RANCH-8, owner decision C11): + * + * - the Owner, or the assistant acting for itself: any agent, for anybody; + * - anybody else: never on the Ranch assistant, whatever the subject, their + * own included (someone else's account there would be read in the + * Owner's conversations); on another agent they manage, their own + * account (`subject` = their id) or the agent-wide connection, never + * somebody else's. + * + * Who started it is kept with the sign-in, and the callback asks again with + * that account's role and reach on the day it completes. */ @ToolAudience('admin') @Injectable() @@ -66,8 +74,9 @@ export class McpOauthTool implements IConditionallyListedTool { 'their browser; they log in at the provider, and the callback stores ' + 'the token for the agent named by `agentId` (the calling agent when ' + 'omitted) and wakes it. Without `subject` this is the agent-wide ' + - 'connection everyone who talks to that agent shares, which for the ' + - 'Ranch assistant only the Owner can make; a person who ' + + 'connection everyone who talks to that agent shares. On the Ranch ' + + 'assistant only the Owner connects anything; elsewhere only the Owner ' + + 'connects an account for another person (subject); a person who ' + "wants their own account connects from that agent's chat instead, " + 'where its «server»__connect tool keys the token to them. The link is ' + 'single-use and expires in ten minutes. Find the server id with ' + @@ -101,16 +110,6 @@ export class McpOauthTool implements IConditionallyListedTool { httpRequest: AuthedRequest, ): Promise { requireOperator(httpRequest); - if ( - subject && - subject !== callerPerson(httpRequest)?.userId && - !callerIsOperator(httpRequest) - ) { - return err( - 'A connection for another person needs an administrator. Omit ' + - 'subject for the agent-wide connection.', - ); - } const owner = agentId ?? callerAgentId(httpRequest); if (!owner) { return err( @@ -127,7 +126,22 @@ export class McpOauthTool implements IConditionallyListedTool { // With `subject` it is one person's own account, keyed to them, and // changes nothing about the agent: reaching it is enough, as before. const reach = await this.access.reachableIds(callerParty(httpRequest)); - if (!(subject ? reach : reach.forChanges()).has(owner)) { + const person = callerPerson(httpRequest); + if (!callerIsOwner(httpRequest)) { + // Not the Owner (RANCH-8, C11): the Ranch assistant is out whatever + // the subject, which is what `forChanges` takes out; and a subject is + // the caller's own or none. + if (!reach.forChanges().has(owner)) { + return agentNotFound(httpRequest, owner, 'change'); + } + const own = person + ? [ + person.userId, + clientIdOfAccount({ id: person.userId, role: person.role }), + ] + : []; + if (subject && !own.includes(subject)) return err(SUBJECT_NOT_YOURS); + } else if (!(subject ? reach : reach.forChanges()).has(owner)) { return agentNotFound(httpRequest, owner, 'change'); } try { @@ -135,6 +149,9 @@ export class McpOauthTool implements IConditionallyListedTool { serverId, agentId: owner, ...(subject ? { subject } : {}), + // Asked again at the callback, with that account as it is then. + startedVia: 'tool', + startedById: person?.userId ?? null, }); this.logger.log( `OAuth connect started through MCP: server=${serverId} agent=${owner} subject=${subject ?? 'agent-wide'}`, From 67e030eb9bc615e59e9db66d494eebe00e1a6fa8 Mon Sep 17 00:00:00 2001 From: "Maksym Hryzodub [DREAM]" Date: Tue, 1 Dec 2026 14:46:56 +0200 Subject: [PATCH 07/13] fix(admin): tell a limited Admin their ceiling before they create or grant (RANCH-8) The new-account form shows a limited Admin an amber block directly above Create user: the account will reach only the agents they can see, and only the Owner can give it more. The assistant-access row and the custom-pick sheet say that abilities they tick work only on agents they can see. Both read the viewer's own row from the user store; nothing is shown to the Owner or an Admin with no lists. Co-Authored-By: Claude --- .../components/assistantAccess/AccountRow.vue | 24 +++++++++++++- .../components/assistantAccess/Advanced.vue | 8 +++++ .../user/components/user/create/Provider.vue | 14 +++++++++ .../user/user/components/user/item/Form.vue | 20 +++++++++++- admin/slices/user/user/stores/user.ts | 11 +++++++ admin/slices/user/user/utils/viewer.test.ts | 31 +++++++++++++++++++ admin/slices/user/user/utils/viewer.ts | 17 ++++++++++ 7 files changed, 123 insertions(+), 2 deletions(-) create mode 100644 admin/slices/user/user/utils/viewer.test.ts create mode 100644 admin/slices/user/user/utils/viewer.ts diff --git a/admin/slices/user/assistantAccess/components/assistantAccess/AccountRow.vue b/admin/slices/user/assistantAccess/components/assistantAccess/AccountRow.vue index 43513b0c0..a164b3293 100644 --- a/admin/slices/user/assistantAccess/components/assistantAccess/AccountRow.vue +++ b/admin/slices/user/assistantAccess/components/assistantAccess/AccountRow.vue @@ -24,6 +24,18 @@ import { const props = defineProps<{ userId: string; name: string }>(); const store = useAssistantAccessStore(); +const auth = useAuthStore(); +const userStore = useUserStore(); + +/** + * The editor is an Admin limited to some agents (RANCH-8, FR-018): an + * ability they tick works only on agents they can see. Read from the + * viewer's own row in the user store; until it is in, nothing is said, and + * the API applies the rule either way. + */ +const grantCeilingNote = computed( + () => !!account.value?.editable && userStore.isLimitedAdmin(auth.user), +); const loadError = ref(null); const saveError = ref(null); @@ -49,7 +61,12 @@ async function load() { : messageOf(err, 'The assistant setting could not be read.'); } } -onMounted(load); +onMounted(() => { + void load(); + if (auth.user?.role === 'Admin') { + void userStore.fetchById(auth.user.id).catch(() => undefined); + } +}); watch(() => props.userId, load); const account = computed(() => store.accountOf(props.userId)); @@ -178,6 +195,10 @@ async function onAdvancedSave(choice: {

+ + Abilities you tick here work only on agents you can see. + +

+ + Abilities you tick here work only on agents you can see. +

diff --git a/admin/slices/user/user/components/user/create/Provider.vue b/admin/slices/user/user/components/user/create/Provider.vue index 683667334..47c7dc071 100644 --- a/admin/slices/user/user/components/user/create/Provider.vue +++ b/admin/slices/user/user/components/user/create/Provider.vue @@ -2,8 +2,21 @@ import type { ICreateUserData } from '#user/domain/user.types'; const userStore = useUserStore(); +const auth = useAuthStore(); const submitting = ref(false); +// The viewer's own row says whether their agent access is limited (RANCH-8): +// a limited Admin's new account reaches only what the Admin reaches, and the +// form says so before Create. Until the row is in, nothing is said; the API +// applies the rule either way. +const ceilingWarning = computed(() => userStore.isLimitedAdmin(auth.user)); + +onMounted(() => { + if (auth.user?.role === 'Admin') { + void userStore.fetchById(auth.user.id).catch(() => undefined); + } +}); + async function onSubmit(values: ICreateUserData) { submitting.value = true; const created = await userStore.create(values); @@ -27,6 +40,7 @@ function onCancel() { diff --git a/admin/slices/user/user/components/user/item/Form.vue b/admin/slices/user/user/components/user/item/Form.vue index 2a5e032c0..a58502304 100644 --- a/admin/slices/user/user/components/user/item/Form.vue +++ b/admin/slices/user/user/components/user/item/Form.vue @@ -1,4 +1,5 @@