fix(authz): require board authority for agent budget changes on every route (#20213)

## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Budgets stop agent spending. The budget hard stop is a control-plane
invariant
> - The budget routes (`PATCH /api/agents/:id/budgets`, `PATCH
/api/companies/:id/budgets`) are board-only
> - `PATCH /api/agents/:id` also accepts `budgetMonthlyCents`, and the
configuration service writes the agent budget policy from it. That route
had no board check for the field
> - So an agent, such as a CEO, a manager or the agent itself, can
change a monthly budget without a board user. This is a second route
around a board-only control, like the pause bypass that #20164 fixed
> - This pull request applies the budget route authority to every route
that writes an agent budget, and gives agents the final board-only
denial with a link to the budget page (#20151)
> - The benefit is that only the board changes budgets, and an agent
that asks gets a final answer that it can pass to the person

## Linked Issues or Issue Description

Refs #17857 (earlier fix, now in conflict with master; this PR rebases
it and adds the budget page link). Refs #20164 and #20151 (same pattern
for PATCH status and board-only denials).

**What happened**

An agent can send `PATCH /api/agents/{id}` with `budgetMonthlyCents`.
The route accepts it, and the configuration service writes the agent
budget policy. This works for the agent's own budget and, with update
permission, for other agents. The same field also reaches budget policy
through a configuration rollback, direct agent creation, an immediate
hire and a built-in agent provision. A chat eval
(`budgets-costs.resolve-budget`) found the route.

**Expected behavior**

Only a board user can change an active budget, as on the dedicated
budget routes. An agent gets `403` with code `board_access_required`.
The denial says it is final and links the agent's budget tab
(`/<prefix>/agents/<id>/budgets`) or the company budgets page
(`/<prefix>/activity/budgets`). An agent can still propose a budget in a
hire that waits for board approval. The approving board user activates
it.

**Steps to reproduce**

1. On master, authenticate as an agent of a company (for example the
CEO).
2. Send `PATCH /api/agents/{agentId}` with body `{"budgetMonthlyCents":
5000}`, for its own id or for another agent.
3. See `200`. The agent budget policy changes with no board action.
4. The new route tests reproduce this: on master source they fail with
`expected 200 to be 403`.

## What Changed

- `PATCH /api/agents/:id`: a changed `budgetMonthlyCents` requires a
board actor. An unchanged amount with other edits still works.
- Configuration rollback: a rollback that changes the budget requires a
board actor.
- `POST /api/companies/:id/agents` and an immediate `agent-hires`: a
positive budget requires a board actor. A hire that needs board approval
keeps the proposed budget and does not activate it before approval.
- Built-in agent provision: a budget override requires a board actor.
- `prepareAgentConfiguration` rejects an agent-originated budget change
again (defense in depth). An agent rollback with an unchanged amount
does not rewrite the policy.
- Board writes keep the actual operator identity. The initial hire
budget is saved in the hire transaction.
- `assertBoard` and `boardAccessRequired` take an optional board page.
Budget denials link the agent's budget tab or the company budgets page,
not the general agent profile.
- Agent access map updated.
- This includes the four commits of #17857 (f970f6b01f, 8c06aba41c,
e5682d22fa, b6cd49d4b6), rebased onto master with the conflicts
resolved, then squashed.

## Verification

- Red on master source, same tests: 12 budget tests fail. The PATCH
tests fail with `expected 200 to be 403` for the agent's own budget and
for a CEO on another agent. Built-in provision fails with `expected 200
to be 403`. Creation and immediate hire fail with `expected 201 to be
403`.
- Green with the fix: `cd server && npx vitest run
src/__tests__/agent-permissions-routes.test.ts
src/__tests__/built-in-agent-routes.test.ts
src/__tests__/built-in-agents.test.ts
src/__tests__/agent-hire-idempotency-routes.test.ts
src/__tests__/board-access-denial.test.ts
src/__tests__/agent-budget-configuration.test.ts`: 222 passed.
- `src/modules/agent-lifecycle/__tests__/lifecycle.test.ts` (embedded
Postgres): 76 passed.
- `agent-skills-routes`, `agent-adapter-validation-routes`,
`openapi-routes`, `agent-cross-tenant-authz-routes`: 275 passed.
- `node scripts/check-maps.mjs`: passed. `git diff --check`: passed.
- Server `tsc --noEmit`: no errors in changed files. One error in
`native-session-executor.ts` comes from a linked runner build in the
local worktree, not from this change. CI runs the full typecheck.

## Risks

- Agent clients that set an active budget directly now get `403`. They
must propose the budget in an approval-gated hire, or ask a board user.
- Agent creation with no budget or a zero budget is not changed. Pending
hire budgets do not activate before approval.
- Trusted internal plugin provisioning keeps its prior behavior and gets
no board identity.
- No schema or migration change.

## Model Used

- Anthropic Claude Opus 5.5 (`claude-opus-5-5`), with tool use and code
execution, in Claude Code. The rebased commits from #17857 were first
written with OpenAI `gpt-6.1-sol` through Codex.

## Checklist

- [x] I have included a thinking path that traces from project context
to this change
- [x] I have specified the model used (with version and capability
details)
- [x] I have checked ROADMAP.md and confirmed this PR does not duplicate
planned core work
- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] I have either (a) linked existing issues with `Fixes: #` / `Closes
#` / `Refs #` OR (b) described the issue in-PR following the relevant
issue template
- [x] I have not referenced internal/instance-local Paperclip issues or
links (only public GitHub `#NNN` / `github.com/paperclipai/paperclip`
URLs)
- [x] My branch name describes the change (e.g. `docs/...`, `fix/...`)
and contains no internal Paperclip ticket id or instance-derived details
- [x] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [ ] All Paperclip CI gates are green
- [ ] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
DottaandClaude Opus 5.5 authored and GitHub committed 2026-11-09 02:50:16 -06:00
1 parent b1049b174e
commit 6383eb8033
14 files changed
+226 -41

No files matched your search

+5 -1
View File
@@ -11,7 +11,7 @@ import { and, eq } from "drizzle-orm";
import { assets, agentConfigRevisions, agentTaskSessions, agentRuntimeState, type Db } from "@paperclipai/db";
import { normalizeAgentUrlKey } from "@paperclipai/shared";
import { normalizePaperclipRunnerAdapterConfig } from "@paperclipai/adapter-utils/server-utils";
import { conflict, notFound, unprocessable } from "../errors.js";
import { conflict, forbidden, notFound, unprocessable } from "../errors.js";
import { agentRecordQueries, type UpdateAgentOptions, type AgentConfigurationPatch, type AgentConfigurationRecord, isPlainRecord, buildConfigSnapshot,
hasConfigPatchFields, changedPendingApprovalConfigFields, diffConfigSnapshot, jsonEqual } from "../lib/agent-records.js";
import { CEO_HIRING_DENIAL_KEY, ceoHiringDenial, normalizeAgentPermissions } from "../lib/agent-permissions.js";
@@ -22,6 +22,9 @@ import { clearPrimaryAgent } from "./primary-agent.js";
import { budgetServiceInTransaction } from "./budgets.js";
export async function prepareAgentConfiguration(db: Db, existing: AgentConfigurationRecord, data: AgentConfigurationPatch, options?: UpdateAgentOptions): Promise<AgentConfigurationPatch> {
if (options?.recordRevision?.createdByAgentId && data.budgetMonthlyCents !== undefined && data.budgetMonthlyCents !== existing.budgetMonthlyCents) {
throw forbidden("Only board operators can change agent budgets");
}
await notifyAttentionRetentionWork(db, { companyId: existing.companyId });
const id = existing.id;
const { ensureManager, assertNoCycle, assertCompanyShortnameAvailable, assertBuiltInAgentMetadataMutationAllowed } = agentRecordQueries(db);
@@ -65,6 +68,7 @@ export async function prepareAgentConfiguration(db: Db, existing: AgentConfigura
}
}
const normalizedPatch = { ...data } as AgentConfigurationPatch;
if (options?.recordRevision?.createdByAgentId) delete normalizedPatch.budgetMonthlyCents;
if (data.permissions !== undefined) {
// Only the permissions control records a CEO hiring restriction. Keep an
// existing one unless this write turns hiring on, and never take one from input.
+7 -6
View File
@@ -1732,7 +1732,7 @@ export function builtInAgentService(db: Db) {
companyId: string,
key: string,
input: BuiltInAgentProvisionInput = {},
options: { isRaceRetry?: boolean; createdByUserId?: string | null } = {},
options: { isRaceRetry?: boolean; createdByUserId?: string | null; createdByAgentId?: string | null } = {},
) {
const definition = requireBuiltInAgentDefinition(key);
await ensureCompany(companyId);
@@ -1800,7 +1800,7 @@ export function builtInAgentService(db: Db) {
}
const updated = await agentSvc.update(existing.id, patch, {
allowBuiltInAgentMetadata: true,
recordRevision: { source: "built-in-agent:ensure" },
recordRevision: { source: "built-in-agent:ensure", createdByUserId: options.createdByUserId, createdByAgentId: options.createdByAgentId },
});
if (!updated) throw notFound("Built-in agent not found");
if (existingPendingApproval) {
@@ -1835,13 +1835,14 @@ export function builtInAgentService(db: Db) {
permissions: definition.defaultPermissions ?? {},
spentMonthlyCents: 0,
lastHeartbeatAt: null,
}, { allowBuiltInAgentMetadata: true, createdByUserId: options.createdByUserId ?? null }) as Agent;
}, { allowBuiltInAgentMetadata: true, createdByUserId: options.createdByUserId ?? null,
...(options.createdByUserId && resolvedInput.budgetMonthlyCents ? { initialBudgetPolicyUserId: options.createdByUserId } : {}) }) as Agent;
} catch (error) {
// Lost the provisioning race: a concurrent writer inserted the row first
// and the partial unique index rejected ours. Re-run once; the winning
// row now exists, so we take the update path instead of inserting again.
if (!options.isRaceRetry && isBuiltInAgentMarkerConflict(error)) {
return ensure(companyId, key, input, { isRaceRetry: true, createdByUserId: options.createdByUserId });
return ensure(companyId, key, input, { isRaceRetry: true, createdByUserId: options.createdByUserId, createdByAgentId: options.createdByAgentId });
}
throw error;
}
@@ -1874,7 +1875,7 @@ export function builtInAgentService(db: Db) {
const definition = requireBuiltInAgentDefinition(key);
const company = await ensureCompany(companyId);
if (!company.requireBoardApprovalForNewAgents) {
return { state: await ensure(companyId, key, input, { createdByUserId: actor.requestedByUserId ?? null }), approval: null };
return { state: await ensure(companyId, key, input, { createdByUserId: actor.requestedByUserId ?? null, createdByAgentId: actor.requestedByAgentId ?? null }), approval: null };
}
await assertKnownBuiltInAgentModel(definition, input);
@@ -1906,7 +1907,7 @@ export function builtInAgentService(db: Db) {
// it does when board approval is not required, instead of dead-ending on a
// fresh board-approval requirement the operator can never satisfy.
if (providesAdapterSetup && (existing.metadata?.paperclipBuiltInSetupRequired === true || !hasCompleteAdapterConfig(existing.adapterType, existing.adapterConfig))) {
return { state: await ensure(companyId, key, input), approval: null };
return { state: await ensure(companyId, key, input, { createdByUserId: actor.requestedByUserId ?? null, createdByAgentId: actor.requestedByAgentId ?? null }), approval: null };
}
// Changing the adapter of an already-configured (`ready`/`paused`)