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
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
22 changed files with 1903 additions and 138 deletions

View file

@ -0,0 +1,255 @@
import express from "express";
import request from "supertest";
import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from "vitest";
import type { ServerAdapterModule } from "../adapters/index.js";
const mocks = vi.hoisted(() => {
const externalRecords = new Map<string, any>();
return {
externalRecords,
execFile: vi.fn((_file: string, _args: string[], optionsOrCallback: unknown, maybeCallback?: unknown) => {
const callback = typeof optionsOrCallback === "function" ? optionsOrCallback : maybeCallback;
if (typeof callback === "function") {
callback(null, "", "");
}
return {
kill: vi.fn(),
on: vi.fn(),
};
}),
listAdapterPlugins: vi.fn(),
addAdapterPlugin: vi.fn((record: any) => {
externalRecords.set(record.type, record);
}),
removeAdapterPlugin: vi.fn((type: string) => {
externalRecords.delete(type);
}),
getAdapterPluginByType: vi.fn((type: string) => externalRecords.get(type)),
getAdapterPluginsDir: vi.fn(),
getDisabledAdapterTypes: vi.fn(),
setAdapterDisabled: vi.fn(),
loadExternalAdapterPackage: vi.fn(),
buildExternalAdapters: vi.fn(async () => []),
reloadExternalAdapter: vi.fn(),
getUiParserSource: vi.fn(),
getOrExtractUiParserSource: vi.fn(),
};
});
vi.mock("node:child_process", () => ({
execFile: mocks.execFile,
}));
vi.mock("../services/adapter-plugin-store.js", () => ({
listAdapterPlugins: mocks.listAdapterPlugins,
addAdapterPlugin: mocks.addAdapterPlugin,
removeAdapterPlugin: mocks.removeAdapterPlugin,
getAdapterPluginByType: mocks.getAdapterPluginByType,
getAdapterPluginsDir: mocks.getAdapterPluginsDir,
getDisabledAdapterTypes: mocks.getDisabledAdapterTypes,
setAdapterDisabled: mocks.setAdapterDisabled,
}));
vi.mock("../adapters/plugin-loader.js", () => ({
buildExternalAdapters: mocks.buildExternalAdapters,
loadExternalAdapterPackage: mocks.loadExternalAdapterPackage,
getUiParserSource: mocks.getUiParserSource,
getOrExtractUiParserSource: mocks.getOrExtractUiParserSource,
reloadExternalAdapter: mocks.reloadExternalAdapter,
}));
const EXTERNAL_ADAPTER_TYPE = "external_admin_test";
const EXTERNAL_PACKAGE_NAME = "paperclip-external-adapter";
let adapterRoutes: typeof import("../routes/adapters.js").adapterRoutes;
let errorHandler: typeof import("../middleware/index.js").errorHandler;
let registerServerAdapter: typeof import("../adapters/registry.js").registerServerAdapter;
let unregisterServerAdapter: typeof import("../adapters/registry.js").unregisterServerAdapter;
let setOverridePaused: typeof import("../adapters/registry.js").setOverridePaused;
function createAdapter(type = EXTERNAL_ADAPTER_TYPE): ServerAdapterModule {
return {
type,
models: [],
execute: async () => ({ exitCode: 0, signal: null, timedOut: false }),
testEnvironment: async () => ({
adapterType: type,
status: "pass",
checks: [],
testedAt: new Date(0).toISOString(),
}),
};
}
function installedRecord(type = EXTERNAL_ADAPTER_TYPE) {
return {
packageName: EXTERNAL_PACKAGE_NAME,
type,
installedAt: new Date(0).toISOString(),
};
}
function createApp(actor: Express.Request["actor"]) {
if (!adapterRoutes || !errorHandler) {
throw new Error("adapter route test dependencies were not loaded");
}
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
req.actor = actor;
next();
});
app.use("/api", adapterRoutes());
app.use(errorHandler);
return app;
}
function boardMember(membershipRole: "admin" | "operator" | "viewer"): Express.Request["actor"] {
return {
type: "board",
userId: `${membershipRole}-user`,
userName: null,
userEmail: null,
source: "session",
isInstanceAdmin: false,
companyIds: ["company-1"],
memberships: [
{
companyId: "company-1",
membershipRole,
status: "active",
},
],
};
}
const instanceAdmin: Express.Request["actor"] = {
type: "board",
userId: "instance-admin",
userName: null,
userEmail: null,
source: "session",
isInstanceAdmin: true,
companyIds: [],
memberships: [],
};
function sendMutatingRequest(app: express.Express, name: string) {
switch (name) {
case "install":
return request(app)
.post("/api/adapters/install")
.send({ packageName: EXTERNAL_PACKAGE_NAME });
case "disable":
return request(app)
.patch(`/api/adapters/${EXTERNAL_ADAPTER_TYPE}`)
.send({ disabled: true });
case "override":
return request(app)
.patch("/api/adapters/claude_local/override")
.send({ paused: true });
case "delete":
return request(app).delete(`/api/adapters/${EXTERNAL_ADAPTER_TYPE}`);
case "reload":
return request(app).post(`/api/adapters/${EXTERNAL_ADAPTER_TYPE}/reload`);
case "reinstall":
return request(app).post(`/api/adapters/${EXTERNAL_ADAPTER_TYPE}/reinstall`);
default:
throw new Error(`Unknown mutating adapter route: ${name}`);
}
}
function seedInstalledExternalAdapter() {
mocks.externalRecords.set(EXTERNAL_ADAPTER_TYPE, installedRecord());
unregisterServerAdapter(EXTERNAL_ADAPTER_TYPE);
registerServerAdapter(createAdapter());
}
describe("adapter management route authorization", () => {
beforeAll(async () => {
const [routes, middleware, registry] = await Promise.all([
import("../routes/adapters.js"),
import("../middleware/index.js"),
import("../adapters/registry.js"),
]);
adapterRoutes = routes.adapterRoutes;
errorHandler = middleware.errorHandler;
registerServerAdapter = registry.registerServerAdapter;
unregisterServerAdapter = registry.unregisterServerAdapter;
setOverridePaused = registry.setOverridePaused;
}, 20_000);
beforeEach(() => {
vi.clearAllMocks();
mocks.externalRecords.clear();
unregisterServerAdapter(EXTERNAL_ADAPTER_TYPE);
setOverridePaused("claude_local", false);
mocks.listAdapterPlugins.mockImplementation(() => [...mocks.externalRecords.values()]);
mocks.getAdapterPluginsDir.mockReturnValue("/tmp/paperclip-adapter-route-authz-test");
mocks.getDisabledAdapterTypes.mockReturnValue([]);
mocks.setAdapterDisabled.mockReturnValue(true);
mocks.buildExternalAdapters.mockResolvedValue([]);
mocks.loadExternalAdapterPackage.mockResolvedValue(createAdapter());
mocks.reloadExternalAdapter.mockImplementation(async (type: string) => createAdapter(type));
});
afterEach(() => {
unregisterServerAdapter(EXTERNAL_ADAPTER_TYPE);
setOverridePaused("claude_local", false);
});
it.each([
"install",
"disable",
"override",
"delete",
"reload",
"reinstall",
])("rejects %s for a non-instance-admin board user with company membership", async (routeName) => {
seedInstalledExternalAdapter();
const app = createApp(boardMember("admin"));
const res = await sendMutatingRequest(app, routeName);
expect(res.status, JSON.stringify(res.body)).toBe(403);
});
it.each([
["install", 201],
["disable", 200],
["override", 200],
["delete", 200],
["reload", 200],
["reinstall", 200],
] as const)("allows instance admins to reach %s", async (routeName, expectedStatus) => {
if (routeName !== "install") {
seedInstalledExternalAdapter();
}
const app = createApp(instanceAdmin);
const res = await sendMutatingRequest(app, routeName);
expect(res.status, JSON.stringify(res.body)).toBe(expectedStatus);
});
it.each(["viewer", "operator"] as const)(
"does not let a company %s trigger adapter npm install or reload",
async (membershipRole) => {
seedInstalledExternalAdapter();
const app = createApp(boardMember(membershipRole));
const install = await request(app)
.post("/api/adapters/install")
.send({ packageName: EXTERNAL_PACKAGE_NAME });
const reload = await request(app).post(`/api/adapters/${EXTERNAL_ADAPTER_TYPE}/reload`);
expect(install.status, JSON.stringify(install.body)).toBe(403);
expect(reload.status, JSON.stringify(reload.body)).toBe(403);
expect(mocks.execFile).not.toHaveBeenCalled();
expect(mocks.loadExternalAdapterPackage).not.toHaveBeenCalled();
expect(mocks.reloadExternalAdapter).not.toHaveBeenCalled();
},
);
});