Files
PaperClipAI/server/src/__tests__/approval-routes-idempotency.test.ts
Jannes StubbemannandClaude Opus 4.7 7f2ed0ad90 security(server): close cross-tenant existence oracle (404 instead of 403) (#3967)
## Thinking Path

> - Paperclip orchestrates AI agents for zero-human companies
> - In a multi-tenant deployment, route handlers that take a resource id
(`issue`, `goal`, `project`, `approval`, etc.) look the resource up by
id and then call `assertCompanyAccess` on its `companyId` — 404 if it
doesn't exist, 403 if it exists in another tenant
> - The split status codes are a classic *existence oracle*: any
authenticated user can enumerate ids across tenants by probing for the
403/404 boundary, mapping out which issues, labels, approvals, etc.
exist in other customers' tenants even when they cannot read the
contents
> - The right fix is a single uniform 404 for both "not found" and
"found but cross-tenant", which collapses the oracle but still preserves
write-path checks (active membership, viewer-readonly) for *authorized*
tenants
> - This pull request adds a non-throwing `hasCompanyAccess(req,
companyId)` helper plus a `getAccessibleResource` wrapper that ~130
handlers across 14 route files now use, folding the access check into
the existence check while still running `assertCompanyAccess` for
authorized tenants so viewer-readonly / inactive-membership rejections
fire unchanged on write paths
> - The benefit is closing a multi-tenant information leak without
breaking write-path security or single-tenant local-first behavior

## Linked Issues or Issue Description

Refs #709 — asks for company-scope regression coverage across
approval/activity/access routes, because a subtle route refactor could
leak cross-tenant data; this PR hardens exactly those surfaces (uniform
404 across 14 route files including `approvals`, `activity`, `secrets`)
and updates cross-tenant expectations in test files. It does not add the
full coverage matrix #709 asks for — hence Refs, not Closes.

No existing issue covers the oracle itself — described in-PR:

- Route handlers returned 404 for "not found" but 403 for "exists in
another tenant", a classic *existence oracle*: any authenticated user
could enumerate ids across tenants by probing the 403/404 boundary.
- That maps out which issues, labels, approvals, etc. exist in other
customers' tenants even when their contents are unreadable.
- Fix: a uniform 404 for both cases, while keeping write-path checks
(active membership, viewer-readonly) for authorized tenants.

## What Changed

- **`server/src/routes/authz.ts`** — new `hasCompanyAccess(req,
companyId): boolean` helper alongside the existing
`assertCompanyAccess`. Docstring spells out the two-step pattern (404
gate, then `assertCompanyAccess` for write-path checks). The helper
mirrors `assertCompanyAccess`'s company-scope semantics exactly — in
particular, signed-in instance admins do **not** get blanket access to
companies they are not a member of (the repo's `authz-company-access`
tests pin that behavior for `assertCompanyAccess`; an earlier draft of
the helper accidentally widened it for reads).
- **`getAccessibleResource(req, res, lookup, notFoundMessage)`** — the
safe thing is now the easy thing. One helper wraps the whole pattern
(uniform 404 for missing/cross-tenant, then `assertCompanyAccess` for
write-path membership checks) and ~130 handlers across 14 route files
use it:
  ```ts
const goal = await getAccessibleResource(req, res, svc.getById(id),
"Goal not found");
  if (!goal) return;
  ```
Files: `activity`, `agents`, `approvals`, `assets`, `costs`,
`environments`, `execution-workspaces`, `file-resources`, `goals`,
`issue-tree-control`, `issues`, `projects`, `routines`, `secrets`.
Handlers with bespoke not-found behavior (the legacy `200 []` contract,
audit-logged denials in `file-resources`, null-returning authz helpers)
compose `hasCompanyAccess` directly using the documented two-step
pattern:
  ```ts
// step 1: close the oracle (uniform 404 for both not-found and
cross-tenant)
  if (!existing || !hasCompanyAccess(req, existing.companyId)) {
    res.status(404).json({ error: "Goal not found" });
    return;
  }
// step 2: enforce write-path membership checks for authorised tenants
(no-op on GET)
  assertCompanyAccess(req, existing.companyId);
  ```
Routes where `companyId` comes from *request input*
(`req.params.companyId`, `req.body.companyId`, e.g. in `companies.ts`
and `plugins.ts`) deliberately retain plain `assertCompanyAccess` —
there's no existence oracle to close because the companyId is an input,
not a discovered value.
- **Full-sweep coverage** — a scripted audit of every
`assertCompanyAccess(req, <resource>.companyId)` call site in
`server/src/routes/` found ~55 lookup-then-assert pairs the first pass
missed; all are now gated. Notable ones: the
`/secret-provider-configs/:id` CRUD routes, the agents
instructions-bundle/config-revision/skills-sync routes (which check
access via the `assertCanUpdateAgent` / `assertCanReadAgent` /
`assertCanManageInstructionsPath` helpers), `POST
/heartbeat-runs/:runId/watchdog-decisions`, `GET
/issues/:id/cost-summary`, the environment + environment-lease GET
routes, all six issue-tree-control routes, ~24 issue sub-resource routes
(document annotations, interactions, approvals links, recovery actions,
plan decompositions, lock/unlock), and the three workspace file-resource
routes (these throw `notFound` instead of `forbidden` inside their
audit-logging wrappers, so denied attempts are still activity-logged
server-side while the client sees a uniform 404).
- **Helpers made self-defending** — `assertCanUpdateAgent` /
`assertCanReadAgent` / `assertCanManageInstructionsPath` (agents) and
`assertCanManage{Project,Execution}WorkspaceRuntimeServices` throw
`notFound` for cross-tenant resources before their `assertCompanyAccess`
step, so a future caller that forgets the route-level gate still can't
reopen the oracle.
- **Pattern enforcement** — new `authz-existence-oracle-guard.test.ts`
statically scans `server/src/routes/*.ts` and fails CI on any
`assertCompanyAccess(req, <resource>.companyId)` call that is not
preceded by a `hasCompanyAccess` gate, with an explicit allowlist (plus
staleness check) for the request-input cases. New routes that regress to
the 403/404 split fail the suite with a message pointing at the
documented pattern.
- **Tests** — cross-tenant expectations updated from 403→404 where
routes are now gated; new `hasCompanyAccess` unit tests in
`authz-company-access.test.ts` pin the
instance-admin/local-implicit/agent/none semantics in lockstep with
`assertCompanyAccess`; `write-path-membership.test.ts` (added in an
earlier round) confirms viewer/inactive users are still rejected on
writes.
- **One legacy-contract preserve** — `GET /heartbeat-runs/:runId/issues`
still returns `200 []` for both "doesn't exist" and "cross-tenant" so
the legacy contract is preserved while the oracle stays closed.

## Verification

- `pnpm run typecheck` — PASS.
- `pnpm -F @paperclipai/server exec vitest run` — full server suite
green locally apart from 4 pre-existing local-environment failures
(`paperclip-skill-utils` ×2 and `workspace-runtime` ×1 are
cwd/git-environment dependent — verified identical on a clean checkout
of the base; `heartbeat-process-recovery` is the known macOS flake).
- The new `authz-existence-oracle-guard` test sweeps
`server/src/routes/*.ts` and confirms no remaining
`assertCompanyAccess(resource.companyId)` site without a
`hasCompanyAccess` gate; the only allowlisted holdouts take `companyId`
from request input.

## Risks

- **API contract narrowing.** Any client that specifically checked for
`403` on cross-tenant access now sees `404`. This is a strict narrowing
(one status instead of two for the same negative outcome) and matches
what a client should expect for any id it can't access.
- **Write-path checks preserved.** `assertCompanyAccess` still runs
after the 404 gate on write routes, so viewer-readonly /
inactive-membership rejections fire unchanged for legitimate users.
- **Instance-admin scope unchanged.** `hasCompanyAccess` denies
signed-in instance admins without an explicit membership, exactly like
`assertCompanyAccess` (pinned by unit tests) — so the gate introduces no
new read access for admins.
- **Single-tenant local-first deploys** behave identically — the helper
short-circuits to `true` for `local_implicit` sessions.
- No new env vars, no deployment-mode switch.

## Model Used

Claude Opus 4.7 (1M context), extended thinking mode; completeness sweep
+ instance-admin parity fix by Claude Fable 5 (1M context).

## Checklist

- [x] I have searched GitHub for duplicate or related PRs and linked
them above
- [x] Thinking path traces from project context to this change
- [x] Model used specified
- [x] Checked ROADMAP.md — part of the multi-tenant hardening initiative
- [x] Tests run locally and pass
- [x] Added/updated cross-tenant 404 expectations across test files
- [x] No UI changes
- [x] Documented risks above
- [x] Will address all Greptile and reviewer comments before merge

Part of the multi-tenant hardening initiative — see also #5864
(per-company JWT keys) and #5865 (plugin tables `company_id`).

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-07-14 15:53:09 -07:00

450 lines
14 KiB
TypeScript

import express from "express";
import request from "supertest";
import { beforeEach, describe, expect, it, vi } from "vitest";
const mockApprovalService = vi.hoisted(() => ({
list: vi.fn(),
getById: vi.fn(),
create: vi.fn(),
approve: vi.fn(),
reject: vi.fn(),
requestRevision: vi.fn(),
resubmit: vi.fn(),
listComments: vi.fn(),
addComment: vi.fn(),
}));
const mockHeartbeatService = vi.hoisted(() => ({
wakeup: vi.fn(),
}));
const mockIssueApprovalService = vi.hoisted(() => ({
listIssuesForApproval: vi.fn(),
linkManyForApproval: vi.fn(),
}));
const mockSecretService = vi.hoisted(() => ({
normalizeHireApprovalPayloadForPersistence: vi.fn(),
}));
const mockLogActivity = vi.hoisted(() => vi.fn());
const mockAccessService = vi.hoisted(() => ({
decide: vi.fn(),
}));
function registerModuleMocks() {
vi.doMock("../services/index.js", () => ({
accessService: () => mockAccessService,
approvalService: () => mockApprovalService,
heartbeatService: () => mockHeartbeatService,
issueApprovalService: () => mockIssueApprovalService,
logActivity: mockLogActivity,
secretService: () => mockSecretService,
}));
}
async function createApp(actorOverrides: Record<string, unknown> = {}) {
const [{ errorHandler }, { approvalRoutes }] = await Promise.all([
import("../middleware/index.js"),
import("../routes/approvals.js"),
]);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as any).actor = {
type: "board",
userId: "user-1",
companyIds: ["company-1"],
source: "session",
isInstanceAdmin: false,
...actorOverrides,
};
next();
});
app.use("/api", approvalRoutes(createRouteDb()));
app.use(errorHandler);
return app;
}
function createRouteDb(contextSnapshot: Record<string, unknown> = {}, runId = "run-1", agentId = "agent-1") {
const runRows = [{
id: runId,
companyId: "company-1",
agentId,
contextSnapshot,
}];
return {
select: vi.fn((selection: Record<string, unknown> = {}) => ({
from: vi.fn(() => ({
where: vi.fn(() => ({
then: async (resolve: (rows: unknown[]) => unknown) => resolve(
Object.keys(selection).includes("contextSnapshot") ? runRows : [],
),
})),
})),
})),
} as any;
}
async function createAgentApp(options: { runId?: string; contextSnapshot?: Record<string, unknown> } = {}) {
const [{ errorHandler }, { approvalRoutes }] = await Promise.all([
import("../middleware/index.js"),
import("../routes/approvals.js"),
]);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as any).actor = {
type: "agent",
agentId: "agent-1",
companyId: "company-1",
runId: options.runId ?? "run-1",
source: "api_key",
isInstanceAdmin: false,
};
next();
});
app.use("/api", approvalRoutes(createRouteDb(options.contextSnapshot, options.runId ?? "run-1")));
app.use(errorHandler);
return app;
}
describe("approval routes idempotent retries", () => {
beforeEach(() => {
vi.resetModules();
vi.doUnmock("../services/index.js");
vi.doUnmock("../routes/approvals.js");
vi.doUnmock("../routes/authz.js");
vi.doUnmock("../middleware/index.js");
registerModuleMocks();
vi.clearAllMocks();
mockApprovalService.list.mockReset();
mockApprovalService.getById.mockReset();
mockApprovalService.create.mockReset();
mockApprovalService.approve.mockReset();
mockApprovalService.reject.mockReset();
mockApprovalService.requestRevision.mockReset();
mockApprovalService.resubmit.mockReset();
mockApprovalService.listComments.mockReset();
mockApprovalService.addComment.mockReset();
mockHeartbeatService.wakeup.mockReset();
mockIssueApprovalService.listIssuesForApproval.mockReset();
mockIssueApprovalService.linkManyForApproval.mockReset();
mockSecretService.normalizeHireApprovalPayloadForPersistence.mockReset();
mockLogActivity.mockReset();
mockAccessService.decide.mockReset();
mockAccessService.decide.mockResolvedValue({
allowed: true,
action: "company_scope:read",
reason: "allow_test",
explanation: "Allowed by test mock.",
});
mockHeartbeatService.wakeup.mockResolvedValue({ id: "wake-1" });
mockIssueApprovalService.listIssuesForApproval.mockResolvedValue([{ id: "issue-1" }]);
mockLogActivity.mockResolvedValue(undefined);
});
it("does not emit duplicate approval side effects when approve is already resolved", async () => {
mockApprovalService.getById.mockResolvedValue({
id: "approval-1",
companyId: "company-1",
type: "hire_agent",
status: "approved",
payload: {},
requestedByAgentId: "agent-1",
});
mockApprovalService.approve.mockResolvedValue({
approval: {
id: "approval-1",
companyId: "company-1",
type: "hire_agent",
status: "approved",
payload: {},
requestedByAgentId: "agent-1",
},
applied: false,
});
const res = await request(await createApp())
.post("/api/approvals/approval-1/approve")
.send({});
expect(res.status).toBe(200);
expect(mockIssueApprovalService.listIssuesForApproval).not.toHaveBeenCalled();
expect(mockHeartbeatService.wakeup).not.toHaveBeenCalled();
expect(mockLogActivity).not.toHaveBeenCalled();
});
it("does not emit duplicate rejection logs when reject is already resolved", async () => {
mockApprovalService.getById.mockResolvedValue({
id: "approval-1",
companyId: "company-1",
type: "hire_agent",
status: "rejected",
payload: {},
});
mockApprovalService.reject.mockResolvedValue({
approval: {
id: "approval-1",
companyId: "company-1",
type: "hire_agent",
status: "rejected",
payload: {},
},
applied: false,
});
const res = await request(await createApp())
.post("/api/approvals/approval-1/reject")
.send({});
expect(res.status).toBe(200);
expect(mockLogActivity).not.toHaveBeenCalled();
});
it("rejects approval decisions for companies outside the caller scope", async () => {
mockApprovalService.getById.mockResolvedValue({
id: "approval-2",
companyId: "company-2",
type: "hire_agent",
status: "pending",
payload: {},
});
const res = await request(await createApp())
.post("/api/approvals/approval-2/approve")
.send({});
expect(res.status).toBe(404);
expect(res.body.error).toBe("Approval not found");
expect(mockApprovalService.approve).not.toHaveBeenCalled();
});
it("rejects approval revision requests for companies outside the caller scope", async () => {
mockApprovalService.getById.mockResolvedValue({
id: "approval-3",
companyId: "company-2",
type: "hire_agent",
status: "pending",
payload: {},
});
const res = await request(await createApp())
.post("/api/approvals/approval-3/request-revision")
.send({ decisionNote: "Need changes" });
expect(res.status).toBe(404);
expect(res.body.error).toBe("Approval not found");
expect(mockApprovalService.requestRevision).not.toHaveBeenCalled();
});
it("derives approval attribution from the authenticated actor on approve", async () => {
mockApprovalService.getById.mockResolvedValue({
id: "approval-4",
companyId: "company-1",
type: "hire_agent",
status: "pending",
payload: {},
requestedByAgentId: null,
});
mockApprovalService.approve.mockResolvedValue({
approval: {
id: "approval-4",
companyId: "company-1",
type: "hire_agent",
status: "approved",
payload: {},
requestedByAgentId: null,
},
applied: true,
});
const res = await request(await createApp())
.post("/api/approvals/approval-4/approve")
.send({ decidedByUserId: "forged-user", decisionNote: "ship it" });
expect(res.status).toBe(200);
expect(mockApprovalService.approve).toHaveBeenCalledWith("approval-4", "user-1", "ship it");
});
it("derives approval attribution from the authenticated actor on reject", async () => {
mockApprovalService.getById.mockResolvedValue({
id: "approval-5",
companyId: "company-1",
type: "hire_agent",
status: "pending",
payload: {},
});
mockApprovalService.reject.mockResolvedValue({
approval: {
id: "approval-5",
companyId: "company-1",
type: "hire_agent",
status: "rejected",
payload: {},
},
applied: true,
});
const res = await request(await createApp())
.post("/api/approvals/approval-5/reject")
.send({ decidedByUserId: "forged-user", decisionNote: "not now" });
expect(res.status).toBe(200);
expect(mockApprovalService.reject).toHaveBeenCalledWith("approval-5", "user-1", "not now");
});
it("derives approval attribution from the authenticated actor on request revision", async () => {
mockApprovalService.getById.mockResolvedValue({
id: "approval-6",
companyId: "company-1",
type: "hire_agent",
status: "pending",
payload: {},
});
mockApprovalService.requestRevision.mockResolvedValue({
id: "approval-6",
companyId: "company-1",
type: "hire_agent",
status: "revision_requested",
payload: {},
});
const res = await request(await createApp())
.post("/api/approvals/approval-6/request-revision")
.send({ decidedByUserId: "forged-user", decisionNote: "Need changes" });
expect(res.status).toBe(200);
expect(mockApprovalService.requestRevision).toHaveBeenCalledWith(
"approval-6",
"user-1",
"Need changes",
);
});
it("lets agents create generic issue-linked board approval requests", async () => {
mockApprovalService.create.mockResolvedValue({
id: "approval-1",
companyId: "company-1",
type: "request_board_approval",
requestedByAgentId: "agent-1",
requestedByUserId: null,
status: "pending",
payload: { title: "Approve hosting spend" },
decisionNote: null,
decidedByUserId: null,
decidedAt: null,
createdAt: new Date("2026-04-06T00:00:00.000Z"),
updatedAt: new Date("2026-04-06T00:00:00.000Z"),
});
const res = await request(await createAgentApp())
.post("/api/companies/company-1/approvals")
.send({
type: "request_board_approval",
issueIds: ["00000000-0000-0000-0000-000000000001"],
payload: { title: "Approve hosting spend" },
});
expect([200, 201], JSON.stringify(res.body)).toContain(res.status);
expect(res.body).toMatchObject({
companyId: "company-1",
type: "request_board_approval",
requestedByAgentId: "agent-1",
requestedByUserId: null,
status: "pending",
});
expect(mockSecretService.normalizeHireApprovalPayloadForPersistence).not.toHaveBeenCalled();
expect(mockIssueApprovalService.linkManyForApproval).toHaveBeenCalledWith(
"approval-1",
["00000000-0000-0000-0000-000000000001"],
{ agentId: "agent-1", userId: null },
);
expect(mockLogActivity).toHaveBeenCalledWith(
expect.anything(),
expect.objectContaining({
companyId: "company-1",
actorType: "agent",
actorId: "agent-1",
action: "approval.created",
}),
);
});
it("blocks status-only recovery runs from creating approvals", async () => {
const res = await request(await createAgentApp({
contextSnapshot: {
modelProfile: "cheap",
recoveryIntent: "status_only",
allowDeliverableWork: false,
allowDocumentUpdates: false,
resumeRequiresNormalModel: true,
},
}))
.post("/api/companies/company-1/approvals")
.send({
type: "request_board_approval",
payload: { title: "Approve hosting spend" },
});
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toContain("Cheap status-only recovery runs cannot create or modify approvals");
expect(mockApprovalService.create).not.toHaveBeenCalled();
expect(mockIssueApprovalService.linkManyForApproval).not.toHaveBeenCalled();
});
it("blocks status-only recovery runs from resubmitting approvals", async () => {
mockApprovalService.getById.mockResolvedValue({
id: "approval-7",
companyId: "company-1",
type: "request_board_approval",
status: "revision_requested",
payload: {},
requestedByAgentId: "agent-1",
});
const res = await request(await createAgentApp({
contextSnapshot: {
modelProfile: "cheap",
recoveryIntent: "status_only",
allowDeliverableWork: false,
allowDocumentUpdates: false,
resumeRequiresNormalModel: true,
},
}))
.post("/api/approvals/approval-7/resubmit")
.send({ payload: { title: "Retry" } });
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toContain("Cheap status-only recovery runs cannot create or modify approvals");
expect(mockApprovalService.resubmit).not.toHaveBeenCalled();
});
it("blocks status-only recovery runs from commenting on approvals", async () => {
mockApprovalService.getById.mockResolvedValue({
id: "approval-8",
companyId: "company-1",
type: "request_board_approval",
status: "pending",
payload: {},
requestedByAgentId: "agent-1",
});
const res = await request(await createAgentApp({
contextSnapshot: {
modelProfile: "cheap",
recoveryIntent: "status_only",
allowDeliverableWork: false,
allowDocumentUpdates: false,
resumeRequiresNormalModel: true,
},
}))
.post("/api/approvals/approval-8/comments")
.send({ body: "please approve" });
expect(res.status, JSON.stringify(res.body)).toBe(403);
expect(res.body.error).toContain("Cheap status-only recovery runs cannot create or modify approvals");
expect(mockApprovalService.addComment).not.toHaveBeenCalled();
});
});