Harden API route authorization boundaries (#4122)

## Thinking Path

> - Paperclip orchestrates AI agents for zero-human companies.
> - The REST API is the control-plane boundary for companies, agents,
plugins, adapters, costs, invites, and issue mutations.
> - Several routes still relied on broad board or company access checks
without consistently enforcing the narrower actor, company, and
active-checkout boundaries those operations require.
> - That can allow agents or non-admin users to mutate sensitive
resources outside the intended governance path.
> - This pull request hardens the route authorization layer and adds
regression coverage for the audited API surfaces.
> - The benefit is tighter multi-company isolation, safer plugin and
adapter administration, and stronger enforcement of active issue
ownership.

## What Changed

- Added route-level authorization checks for budgets, plugin
administration/scoped routes, adapter management, company import/export,
direct agent creation, invite test resolution, and issue mutation/write
surfaces.
- Enforced active checkout ownership for agent-authenticated issue
mutations, while preserving explicit management overrides for permitted
managers.
- Restricted sensitive adapter and plugin management operations to
instance-admin or properly scoped actors.
- Tightened company portability and invite probing routes so agents
cannot cross company boundaries.
- Updated access constants and the Company Access UI copy for the new
active-checkout management grant.
- Added focused regression tests covering cross-company denial, agent
self-mutation denial, admin-only operations, and active checkout
ownership.
- Rebased the branch onto `public-gh/master` and fixed validation
fallout from the rebase: heartbeat-context route ordering and a company
import/export e2e fixture that now opts out of direct-hire approval
before using direct agent creation.
- Updated onboarding and signoff e2e setup to create seed agents through
`/agent-hires` plus board approval, so they remain compatible with the
approval-gated new-agent default.
- Addressed Greptile feedback by removing a duplicate company export API
alias, avoiding N+1 reporting-chain lookups in active-checkout override
checks, allowing agent mutations on unassigned `in_progress` issues, and
blocking NAT64 invite-probe targets.

## Verification

- `pnpm exec vitest run
server/src/__tests__/issues-goal-context-routes.test.ts
cli/src/__tests__/company-import-export-e2e.test.ts`
- `pnpm exec vitest run server/src/__tests__/plugin-routes-authz.test.ts
server/src/__tests__/adapter-routes-authz.test.ts
server/src/__tests__/agent-permissions-routes.test.ts
server/src/__tests__/company-portability-routes.test.ts
server/src/__tests__/costs-service.test.ts
server/src/__tests__/invite-test-resolution-route.test.ts
server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts
server/src/__tests__/agent-adapter-validation-routes.test.ts`
- `pnpm exec vitest run
server/src/__tests__/issue-agent-mutation-ownership-routes.test.ts`
- `pnpm exec vitest run
server/src/__tests__/invite-test-resolution-route.test.ts`
- `pnpm -r typecheck`
- `pnpm --filter server typecheck`
- `pnpm --filter ui typecheck`
- `pnpm build`
- `pnpm test:e2e -- tests/e2e/onboarding.spec.ts
tests/e2e/signoff-policy.spec.ts`
- `pnpm test:e2e -- tests/e2e/signoff-policy.spec.ts`
- `pnpm test:run` was also run. It failed under default full-suite
parallelism with two order-dependent failures in
`plugin-routes-authz.test.ts` and `routines-e2e.test.ts`; both files
passed when rerun directly together with `pnpm exec vitest run
server/src/__tests__/plugin-routes-authz.test.ts
server/src/__tests__/routines-e2e.test.ts`.

## Risks

- Medium risk: this changes authorization behavior across multiple
sensitive API surfaces, so callers that depended on broad board/company
access may now receive `403` or `409` until they use the correct
governance path.
- Direct agent creation now respects the company-level board-approval
requirement; integrations that need pending hires should use
`/api/companies/:companyId/agent-hires`.
- Active in-progress issue mutations now require checkout ownership or
an explicit management override, which may reveal workflow assumptions
in older automation.

> For core feature work, check [`ROADMAP.md`](ROADMAP.md) first and
discuss it in `#dev` before opening the PR. Feature PRs that overlap
with planned core work may need to be redirected — check the roadmap
first. See `CONTRIBUTING.md`.

## Model Used

OpenAI Codex, GPT-5 coding agent, tool-using workflow with local shell,
Git, GitHub CLI, and repository tests.

## 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
- [ ] I have run tests locally and they pass
- [x] I have added or updated tests where applicable
- [x] If this change affects the UI, I have included before/after
screenshots
- [x] I have updated relevant documentation to reflect my changes
- [x] I have considered and documented any risks above
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
This commit is contained in:
Dotta
2026-04-20 10:56:48 -05:00
committed by GitHub
parent 549ef11c14
commit 7a329fb8bb
22 changed files with 1903 additions and 138 deletions

View File

@@ -35,7 +35,12 @@ vi.mock("../services/live-events.js", () => ({
async function createApp(
actor: Record<string, unknown>,
loaderOverrides: Record<string, unknown> = {},
bridgeDeps?: Record<string, unknown>,
routeOverrides: {
db?: unknown;
jobDeps?: unknown;
toolDeps?: unknown;
bridgeDeps?: unknown;
} = {},
) {
const [{ pluginRoutes }, { errorHandler }] = await Promise.all([
import("../routes/plugins.js"),
@@ -53,12 +58,58 @@ async function createApp(
req.actor = actor as typeof req.actor;
next();
});
app.use("/api", pluginRoutes({} as never, loader as never, undefined, undefined, undefined, bridgeDeps as never));
app.use("/api", pluginRoutes(
(routeOverrides.db ?? {}) as never,
loader as never,
routeOverrides.jobDeps as never,
undefined,
routeOverrides.toolDeps as never,
routeOverrides.bridgeDeps as never,
));
app.use(errorHandler);
return { app, loader };
}
function createSelectQueueDb(rows: Array<Array<Record<string, unknown>>>) {
return {
select: vi.fn(() => ({
from: vi.fn(() => ({
where: vi.fn(() => ({
limit: vi.fn(() => Promise.resolve(rows.shift() ?? [])),
})),
})),
})),
};
}
const companyA = "22222222-2222-4222-8222-222222222222";
const companyB = "33333333-3333-4333-8333-333333333333";
const agentA = "44444444-4444-4444-8444-444444444444";
const runA = "55555555-5555-4555-8555-555555555555";
const projectA = "66666666-6666-4666-8666-666666666666";
const pluginId = "11111111-1111-4111-8111-111111111111";
function boardActor(overrides: Record<string, unknown> = {}) {
return {
type: "board",
userId: "user-1",
source: "session",
isInstanceAdmin: false,
companyIds: [companyA],
...overrides,
};
}
function readyPlugin() {
mockRegistry.getById.mockResolvedValue({
id: pluginId,
pluginKey: "paperclip.example",
version: "1.0.0",
status: "ready",
});
}
describe("plugin install and upgrade authz", () => {
beforeEach(() => {
vi.resetAllMocks();
@@ -244,7 +295,7 @@ describe("scoped plugin API routes", () => {
companyIds: ["company-1"],
},
{},
{ workerManager },
{ bridgeDeps: { workerManager } },
);
const res = await request(app)
@@ -265,3 +316,227 @@ describe("scoped plugin API routes", () => {
);
}, 20_000);
});
describe("plugin tool and bridge authz", () => {
beforeEach(() => {
vi.resetAllMocks();
});
it("rejects tool execution when the board user cannot access runContext.companyId", async () => {
const executeTool = vi.fn();
const getTool = vi.fn();
const { app } = await createApp(boardActor(), {}, {
toolDeps: {
toolDispatcher: {
listToolsForAgent: vi.fn(),
getTool,
executeTool,
},
},
});
const res = await request(app)
.post("/api/plugins/tools/execute")
.send({
tool: "paperclip.example:search",
parameters: {},
runContext: {
agentId: agentA,
runId: runA,
companyId: companyB,
projectId: projectA,
},
});
expect(res.status).toBe(403);
expect(getTool).not.toHaveBeenCalled();
expect(executeTool).not.toHaveBeenCalled();
});
it.each([
[
"agentId",
[
[{ companyId: companyB }],
],
],
[
"runId company",
[
[{ companyId: companyA }],
[{ companyId: companyB, agentId: agentA }],
],
],
[
"runId agent",
[
[{ companyId: companyA }],
[{ companyId: companyA, agentId: "77777777-7777-4777-8777-777777777777" }],
],
],
[
"projectId",
[
[{ companyId: companyA }],
[{ companyId: companyA, agentId: agentA }],
[{ companyId: companyB }],
],
],
])("rejects tool execution when runContext.%s is outside the company scope", async (_case, rows) => {
const executeTool = vi.fn();
const { app } = await createApp(boardActor(), {}, {
db: createSelectQueueDb(rows),
toolDeps: {
toolDispatcher: {
listToolsForAgent: vi.fn(),
getTool: vi.fn(() => ({ name: "paperclip.example:search" })),
executeTool,
},
},
});
const res = await request(app)
.post("/api/plugins/tools/execute")
.send({
tool: "paperclip.example:search",
parameters: {},
runContext: {
agentId: agentA,
runId: runA,
companyId: companyA,
projectId: projectA,
},
});
expect(res.status).toBe(403);
expect(executeTool).not.toHaveBeenCalled();
});
it("allows tool execution when agent, run, and project all belong to runContext.companyId", async () => {
const executeTool = vi.fn().mockResolvedValue({ content: "ok" });
const { app } = await createApp(boardActor(), {}, {
db: createSelectQueueDb([
[{ companyId: companyA }],
[{ companyId: companyA, agentId: agentA }],
[{ companyId: companyA }],
]),
toolDeps: {
toolDispatcher: {
listToolsForAgent: vi.fn(),
getTool: vi.fn(() => ({ name: "paperclip.example:search" })),
executeTool,
},
},
});
const res = await request(app)
.post("/api/plugins/tools/execute")
.send({
tool: "paperclip.example:search",
parameters: { q: "test" },
runContext: {
agentId: agentA,
runId: runA,
companyId: companyA,
projectId: projectA,
},
});
expect(res.status).toBe(200);
expect(executeTool).toHaveBeenCalledWith(
"paperclip.example:search",
{ q: "test" },
{
agentId: agentA,
runId: runA,
companyId: companyA,
projectId: projectA,
},
);
});
it.each([
["legacy data", "post", `/api/plugins/${pluginId}/bridge/data`, { key: "health" }],
["legacy action", "post", `/api/plugins/${pluginId}/bridge/action`, { key: "sync" }],
["url data", "post", `/api/plugins/${pluginId}/data/health`, {}],
["url action", "post", `/api/plugins/${pluginId}/actions/sync`, {}],
] as const)("rejects %s bridge calls without companyId for non-admin users", async (_name, _method, path, body) => {
readyPlugin();
const call = vi.fn();
const { app } = await createApp(boardActor(), {}, {
bridgeDeps: {
workerManager: { call },
},
});
const res = await request(app)
.post(path)
.send(body);
expect(res.status).toBe(403);
expect(call).not.toHaveBeenCalled();
});
it("allows omitted-company bridge calls for instance admins as global plugin actions", async () => {
readyPlugin();
const call = vi.fn().mockResolvedValue({ ok: true });
const { app } = await createApp(boardActor({
userId: "admin-1",
isInstanceAdmin: true,
companyIds: [],
}), {}, {
bridgeDeps: {
workerManager: { call },
},
});
const res = await request(app)
.post(`/api/plugins/${pluginId}/actions/sync`)
.send({});
expect(res.status).toBe(200);
expect(res.body).toEqual({ data: { ok: true } });
expect(call).toHaveBeenCalledWith(pluginId, "performAction", {
key: "sync",
params: {},
renderEnvironment: null,
});
});
it("rejects manual job triggers for non-admin board users", async () => {
const scheduler = { triggerJob: vi.fn() };
const jobStore = { getJobByIdForPlugin: vi.fn() };
const { app } = await createApp(boardActor(), {}, {
jobDeps: { scheduler, jobStore },
});
const res = await request(app)
.post(`/api/plugins/${pluginId}/jobs/job-1/trigger`)
.send({});
expect(res.status).toBe(403);
expect(scheduler.triggerJob).not.toHaveBeenCalled();
expect(jobStore.getJobByIdForPlugin).not.toHaveBeenCalled();
});
it("allows manual job triggers for instance admins", async () => {
readyPlugin();
const scheduler = { triggerJob: vi.fn().mockResolvedValue({ runId: "run-1", jobId: "job-1" }) };
const jobStore = { getJobByIdForPlugin: vi.fn().mockResolvedValue({ id: "job-1" }) };
const { app } = await createApp(boardActor({
userId: "admin-1",
isInstanceAdmin: true,
companyIds: [],
}), {}, {
jobDeps: { scheduler, jobStore },
});
const res = await request(app)
.post(`/api/plugins/${pluginId}/jobs/job-1/trigger`)
.send({});
expect(res.status).toBe(200);
expect(res.body).toEqual({ runId: "run-1", jobId: "job-1" });
expect(scheduler.triggerJob).toHaveBeenCalledWith("job-1", "manual");
});
});