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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 13 additions & 1 deletion packages/api/src/agent-side/tools.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -320,6 +320,16 @@ describe('runAgentTool', () => {
expect(getAgentTask).toHaveBeenCalledWith('org-1', 'agent-1', 'task-1');
});

test('a secret is given without its value, which only the person reads', async () => {
const {runAgentTool} = await import('./tools');
const secret = {id: 'secret-1', values: {name: 'API_KEY', value: 'sk-never-shown', note: 'For the reports'}, updatedAt: '2026-11-17T10:00:00.000Z'};
connector.get.mockResolvedValueOnce(Ok(secret));
connector.list.mockResolvedValueOnce(Ok({records: [secret], nextPage: null}));

expect((await runAgentTool(caller, 'vault-1', 'secrets_get', {id: 'secret-1'})).unwrap()).toEqual({record: {...secret, values: {name: 'API_KEY', note: 'For the reports'}}});
expect(JSON.stringify((await runAgentTool(caller, 'vault-1', 'secrets_list', {})).unwrap())).not.toContain('sk-never-shown');
});

test('a run for a task the agent does not have, or one finished already, is refused unlogged', async () => {
const {runAgentTool} = await import('./tools');
getAgentTask.mockResolvedValue(Ok(null));
Expand Down Expand Up @@ -806,11 +816,13 @@ describe("an integration's own tools", () => {
'entries_create',
'entries_update',
'entries_delete',
'secrets_list',
'secrets_get',
'entries_count',
'entries_purge',
]);
getAgentById.mockResolvedValue(Ok({...agent, grants: []}));
expect((await listAgentTools(signedIn, 'vault-1')).unwrap().map((tool) => tool.name)).toEqual(['entries_list', 'entries_get', 'entries_count']);
expect((await listAgentTools(signedIn, 'vault-1')).unwrap().map((tool) => tool.name)).toEqual(['entries_list', 'entries_get', 'secrets_list', 'secrets_get', 'entries_count']);
});

test('run by the runner with the params as given, for the caller on the connection, and logged by name with them', async () => {
Expand Down
24 changes: 23 additions & 1 deletion packages/api/src/agent-side/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -440,9 +440,31 @@ function runParamsTool(target: RunTarget, tool: ServerTool | ApiTool, params: un
});
}

// What a tool answers an agent, of whatever kind: never what is never given to one, as a vault's
// secret's value (`Field.secret`), which the person reads on the connection's page and a command
// uses by name. Taken out here, once, so that no kind of tool answers with it.
async function execute(run: ToolRun, params: Record<string, string>): Promise<Result<ToolResult, ApiError>> {
return (await executeKind(run, params)).map((answer) => withoutSecrets(run.target.collection, answer));
}

function withoutSecrets(collection: Collection, answer: ToolResult): ToolResult {
const hidden = collection.fields.filter((field) => field.secret).map((field) => field.key);
if (hidden.length === 0) {
return answer;
}
const hide = (record: DataRecord): DataRecord => ({...record, values: Object.fromEntries(Object.entries(record.values).filter(([key]) => !hidden.includes(key)))});
if ('records' in answer) {
return {...answer, records: answer.records.map(hide)};
}
if ('record' in answer && answer.record !== null) {
return {record: hide(answer.record)};
}
return answer;
}

// Only a command on values typed in runs on a collection that is only run; the catalog gives such
// a collection no other tool, so a run of another on it is a tool it doesn't have.
function execute(run: ToolRun, params: Record<string, string>): Promise<Result<ToolResult, ApiError>> {
function executeKind(run: ToolRun, params: Record<string, string>): Promise<Result<ToolResult, ApiError>> {
const {kind} = run.tool;
if (kind === 'newCommand') {
return newCommand(run, params);
Expand Down
27 changes: 25 additions & 2 deletions packages/api/src/mcp/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,27 @@ function vaultInstructions(connections: AgentConnection[]): string[] {
];
}

// The vaults' secrets, where the agent may use or add them: that a sandbox command is given them
// by name, and that their values are never shown to it.
function secretInstructions(connections: AgentConnection[]): string[] {
const vaults = connections.filter((connection) => connection.integrationId === VAULT_INTEGRATION_ID);
const uses = vaults.some((vault) => vault.actions.includes('useSecrets'));
const adds = vaults.some((vault) => vault.actions.includes('writeSecrets'));
if (!uses && !adds) {
return [];
}
return [
[
...(uses
? [
'A vault’s secrets (secrets_list), such as API keys, are given to a sandbox command as environment variables by name: sandbox_exec {secrets: ["NAME"]}. Their values are kept from you: where a command prints one, it is shown as [secret NAME]. Don’t print them.',
]
: []),
...(adds ? ['Keep a key you made with secrets_create {name, value, note}: it can’t be read back.'] : []),
].join(' '),
];
}

const GITHUB_INTEGRATION_ID = 'github';

function runsCommands(connection: AgentConnection): boolean {
Expand Down Expand Up @@ -201,8 +222,9 @@ export function pageInstructions(signedIn: SignedInAgent): Promise<Result<string

/**
* What any agent with this login is told: who it is, how to go about it (`flow`, which is where
* the MCP server and the built-in agent differ), what it can use, the vault, where to send the
* person, and that what records say is information. The built-in agent's loop gives these too.
* the MCP server and the built-in agent differ), what it can use, the vault and its secrets,
* where to send the person, and that what records say is information. The built-in agent's loop
* gives these too.
*/
export function agentInstructions(signedIn: SignedInAgent, flow: string, folder?: string): Promise<Result<string, ApiError>> {
return Do(async ($) => {
Expand All @@ -221,6 +243,7 @@ export function agentInstructions(signedIn: SignedInAgent, flow: string, folder?
flow,
lines.length > 0 ? `Connections:\n${lines.join('\n')}` : 'This login has no access yet: the person who made it has to give it some.',
...vaultInstructions(connections),
...secretInstructions(connections),
...sandboxInstructions(connections),
...filesInstructions(connections, folder),
...chatInstructions(connections),
Expand Down
31 changes: 31 additions & 0 deletions packages/api/src/native/sandbox/exec.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,11 @@ const wakeSandbox = mock(async () => Ok(sandbox));

mock.module('./machines', () => ({requireBackend, wakeSandbox}));

type Secret = {name: string; value: string};
const secretsFor = mock(async (): Promise<Result<{given: Secret[]; masked: Secret[]}, ApiError>> => Ok({given: [], masked: []}));

mock.module('./secrets', () => ({secretsFor}));

const signedIn = {agentId: 'agent-1', orgId: 'org-1', ownerUserId: 'user-1', providerId: 'claude', name: 'Claude', orgSlug: 'org-1', experiments: []};
const caller = {agent: signedIn, via: 'mcp' as const, taskId: 'task-1'};
const connection = {id: 'sandboxes-1'} as never;
Expand All @@ -58,6 +63,7 @@ beforeEach(() => {
mock.clearAllMocks();
sandbox.papVersion = 'v2';
exec.mockImplementation(async () => Ok(done));
secretsFor.mockImplementation(async () => Ok({given: [], masked: []}));
mockEnv.AUTH_SECRET = 'test-auth-secret';
mockEnv.APP_URL = 'https://app.example.com';
});
Expand All @@ -78,6 +84,31 @@ describe('runSandboxCommand', () => {
expect(left).toBeLessThanOrEqual(91);
});

test('with secrets, the command is given each by its name, and what it writes shows each by its name', async () => {
const key = {name: 'API_KEY', value: 'sk-test-123'};
secretsFor.mockImplementation(async () => Ok({given: [key], masked: [key]}));
exec.mockImplementation(async () => Ok({...done, stdout: 'key is sk-test-123\n'}));
const answer = (await run({secrets: ['API_KEY']})).unwrap();
expect(exec.mock.calls.at(-1)?.[1].env).toEqual({API_KEY: 'sk-test-123'});
expect(answer).toContain('key is [secret API_KEY]');
expect(answer).not.toContain('sk-test-123');
});

test('without secrets, the command is given none, and what it writes still shows each the agent may use by its name', async () => {
secretsFor.mockImplementation(async () => Ok({given: [], masked: [{name: 'API_KEY', value: 'sk-test-123'}]}));
exec.mockImplementation(async () => Ok({...done, stdout: 'API_KEY=sk-test-123\n'}));
const answer = (await run({command: 'cat env.txt'})).unwrap();
expect(exec.mock.calls.at(-1)?.[1].env).toBeUndefined();
expect(answer).toContain('API_KEY=[secret API_KEY]');
expect(answer).not.toContain('sk-test-123');
});

test('a secret no vault lets the agent use fails the call, and nothing is run', async () => {
secretsFor.mockImplementation(async () => Err(ApiErr.validationError('No vault lets you use its secrets')));
expect((await run({secrets: ['API_KEY']})).isErr()).toBe(true);
expect(exec).not.toHaveBeenCalled();
});

test('without pap, no environment at all', async () => {
await run({});
await run({pap: false});
Expand Down
21 changes: 16 additions & 5 deletions packages/api/src/native/sandbox/exec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import type {NativeToolRunner} from '../tool';
import {holdForTask} from './lease';
import {requireBackend, wakeSandbox} from './machines';
import {ensurePap, withPapOnPath} from './pap';
import {maskSecrets, secretEnv} from './secret-values';
import {secretsFor} from './secrets';

/**
* The console, `sandbox_exec`: a command run in a sandbox of the connection's for the caller's
Expand All @@ -22,7 +24,10 @@ import {ensurePap, withPapOnPath} from './pap';
* the `pap` CLI on its PATH, installed first where it isn't this server's (pap.ts); without it, no
* credential and nothing installed. The activity log has the command as the agent gave it. The
* token is signed once the sandbox is woken and pap installed, so it lasts as long as the command
* may.
* may. With `secrets`, it is given the vaults' secrets named, as environment variables
* (secrets.ts); what any command writes back has the values of every secret the agent may use
* shown by their names, so one isn't read by accident. The log has the names alone, as the agent
* gave them.
*/

const paramsSchema = z.object({
Expand All @@ -32,6 +37,7 @@ const paramsSchema = z.object({
cwd: z.string().optional(),
timeout: z.number().positive().max(SANDBOX_EXEC_MAX_SECONDS).optional(),
pap: z.boolean().optional(),
secrets: z.array(z.string().min(1)).max(50).optional(),
});

// How much of each stream the model is given; the gate cuts the whole answer further.
Expand Down Expand Up @@ -65,9 +71,12 @@ export const runSandboxCommand: NativeToolRunner = ({caller, connection, params}
Do(async ($): Promise<string> => {
const parsed = parseSchema(paramsSchema, params);
if (parsed.isErr()) {
return $(Err(ApiErr.validationError(`sandbox_exec takes sandbox, command, and stdin, cwd, timeout and pap where wanted: ${parsed.error.kind === 'parse_error' ? parsed.error.message : ''}`)));
return $(
Err(ApiErr.validationError(`sandbox_exec takes sandbox, command, and stdin, cwd, timeout, pap and secrets where wanted: ${parsed.error.kind === 'parse_error' ? parsed.error.message : ''}`)),
);
}
const {sandbox: sandboxId, command, stdin, cwd, timeout = SANDBOX_EXEC_DEFAULT_SECONDS, pap = false} = parsed.value;
const {sandbox: sandboxId, command, stdin, cwd, timeout = SANDBOX_EXEC_DEFAULT_SECONDS, pap = false, secrets: asked = []} = parsed.value;
const {given: secrets, masked} = $(await secretsFor(caller, asked));
const config = pap ? $(requireCliTokenConfig()) : null;
const bundle = pap ? $(await papBundle()) : null;
const backend = $(await requireBackend());
Expand All @@ -78,8 +87,10 @@ export const runSandboxCommand: NativeToolRunner = ({caller, connection, params}
$(await ensurePap(backend, running, bundle));
}
const claims = {agentId: caller.agent.agentId, orgId: caller.agent.orgId, ownerUserId: caller.agent.ownerUserId, taskId: caller.taskId, sandboxId: running.id, connectionId: connection.id};
const sent = config === null ? {command} : {command: withPapOnPath(command), env: cliCommandEnv(config, claims, timeout)};
const given = secretEnv(secrets);
const plain = secrets.length === 0 ? {command} : {command, env: given};
const sent = config === null ? plain : {command: withPapOnPath(command), env: {...given, ...cliCommandEnv(config, claims, timeout)}};
const output = $(await backend.exec(running.backendRef, {...sent, stdin, cwd, timeoutMs: Math.round(timeout * 1000)}));
$(await touchSandbox(running.id));
return describeOutput(output, timeout);
return describeOutput({...output, stdout: maskSecrets(output.stdout, masked), stderr: maskSecrets(output.stderr, masked)}, timeout);
});
59 changes: 59 additions & 0 deletions packages/api/src/native/sandbox/secret-values.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import {describe, expect, test} from 'bun:test';

import {maskSecrets, pickSecret, secretEnv} from './secret-values';

const own = {id: 'vault-1', integrationId: 'vault', account: 'Acme', shared: false, actions: ['useSecrets'], name: null, signInNeeded: false};
const work = {...own, id: 'vault-2', name: 'Work', shared: true};

describe('pickSecret', () => {
test('finds a name one vault has', () => {
const held = [{name: 'API_KEY', value: 'sk-one', vault: own}];
expect(pickSecret(held, 'API_KEY').unwrap()).toEqual({name: 'API_KEY', value: 'sk-one'});
});

test('asks which vault where two have the name, and takes one named by its name or id', () => {
const held = [
{name: 'API_KEY', value: 'sk-one', vault: own},
{name: 'API_KEY', value: 'sk-two', vault: work},
];
expect(pickSecret(held, 'API_KEY').isErr()).toBe(true);
expect(pickSecret(held, 'Work/API_KEY').unwrap().value).toBe('sk-two');
expect(pickSecret(held, 'vault-1/API_KEY').unwrap().value).toBe('sk-one');
expect(pickSecret(held, 'Vault/API_KEY').unwrap().value).toBe('sk-one');
});

test('a name no vault has is not found', () => {
expect(pickSecret([], 'MISSING').unwrapErr().kind).toBe('not_found');
});
});

describe('maskSecrets', () => {
test('shows each value as its name, the longer first', () => {
const secrets = [
{name: 'SHORT', value: 'abcd'},
{name: 'LONG', value: 'abcdefgh'},
];
expect(maskSecrets('key=abcdefgh and abcd', secrets)).toBe('key=[secret LONG] and [secret SHORT]');
});

test('never takes a name already shown for a value', () => {
const secrets = [
{name: 'OPENAI_API_KEY', value: 'sk-long-key-123'},
{name: 'PROVIDER', value: 'OPENAI'},
];
expect(maskSecrets('sk-long-key-123 from OPENAI', secrets)).toBe('[secret OPENAI_API_KEY] from [secret PROVIDER]');
});

test('finds a value as it is, whatever it has in it', () => {
const secrets = [{name: 'PASSWORD', value: 'a.b*c(d)[e]$/-'}];
expect(maskSecrets('pw: a.b*c(d)[e]$/- and axbxc', secrets)).toBe('pw: [secret PASSWORD] and axbxc');
});

test('leaves values too short to tell apart as they are', () => {
expect(maskSecrets('a b c', [{name: 'TINY', value: 'b'}])).toBe('a b c');
});
});

test('secretEnv gives each secret by its name', () => {
expect(secretEnv([{name: 'API_KEY', value: 'sk-one'}])).toEqual({API_KEY: 'sk-one'});
});
66 changes: 66 additions & 0 deletions packages/api/src/native/sandbox/secret-values.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import {Err, Ok, type Result} from 'ts-results-es';

import {ApiErr, type ApiError} from '@proxy/utils';
import type {AgentConnection} from '@proxy/contracts/agent-side';

/**
* Secrets as a sandbox command is given them (secrets.ts finds them): the one a name asks for,
* the environment they make, and what the command wrote with each value shown as its name.
*/

/** A secret as a command is given it. */
export type GivenSecret = {name: string; value: string};

/** A secret of a vault the agent may use the secrets of. */
export type HeldSecret = GivenSecret & {vault: AgentConnection};

// Whether the vault is the one a name was asked for in: by its id, or by what it is called, the
// person's own being called Vault.
function vaultCalled(vault: AgentConnection, called: string): boolean {
return vault.id === called || vault.name === called || (vault.name === null && called.toLowerCase() === 'vault');
}

/** The secret a name asks for, among those held: the one vault that has it, or the one named, as Work/OPENAI_API_KEY. */
export function pickSecret(held: HeldSecret[], asked: string): Result<GivenSecret, ApiError> {
const slash = asked.lastIndexOf('/');
const name = slash === -1 ? asked : asked.slice(slash + 1);
const vault = slash === -1 ? null : asked.slice(0, slash);
const found = held.filter((secret) => secret.name === name && (vault === null || vaultCalled(secret.vault, vault)));
if (found.length > 1) {
return Err(ApiErr.validationError(`${name} is in more than one vault: ask for it as ${found.map((secret) => `${secret.vault.id}/${name}`).join(' or ')}`));
}
const [only] = found;
if (!only) {
return Err(ApiErr.notFound('secret', asked, 'secrets_list, in a vault you may use the secrets of, lists them.'));
}
return Ok({name: only.name, value: only.value});
}

// Values shorter than this are left as they are in what a command writes: a word that short is
// more likely to be anything else.
const MASKED_FROM = 4;

// A value as a pattern matching it as it is, whatever it has in it.
function escaped(value: string): string {
return value.replace(/[\\^$.*+?()[\]{}|/-]/g, '\\$&');
}

/**
* What a command wrote, each secret's value in it shown as [secret NAME]: all in one pass, the
* longest first where values overlap, so one inside another is never half shown and a name already
* shown is never mistaken for a value.
*/
export function maskSecrets(text: string, secrets: GivenSecret[]): string {
const masked = secrets.filter((secret) => secret.value.length >= MASKED_FROM).toSorted((a, b) => b.value.length - a.value.length);
if (masked.length === 0) {
return text;
}
const names = new Map(masked.map((secret) => [secret.value, secret.name]));
const pattern = new RegExp(masked.map((secret) => escaped(secret.value)).join('|'), 'g');
return text.replace(pattern, (value) => `[secret ${names.get(value) ?? ''}]`);
}

/** The secrets as environment variables, by their names. */
export function secretEnv(secrets: GivenSecret[]): Record<string, string> {
return Object.fromEntries(secrets.map((secret) => [secret.name, secret.value]));
}
Loading
Loading