Files
PaperClipAI/server/src/__tests__/company-import-cloud-floor.test.ts
T
DottaandPaperclip 9dd6526b47 fix(security): harden privileged server boundaries (#12776)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The server controls secrets, host files, outbound requests, and
workspace commands
> - A red-team review found cases where restricted callers could cross
these trust boundaries
> - These cases could expose credentials or let untrusted input reach
privileged resources
> - This pull request applies least-privilege checks at each affected
server boundary
> - The benefit is safer agent execution without changing the
private-instance bootstrap contract

## Linked Issues or Issue Description

**What happened?**

Several server paths used authorization, redaction, or content-delivery
rules that were too broad. Restricted agent keys could obtain
company-level operational data. Some adapter and instruction paths could
reach server-owned network or file resources without the required owner
approval.

**Expected behavior**

Paperclip must redact credential values, enforce restricted-key scopes,
guard outbound network access, prevent same-origin script execution, and
reserve host-level file and command controls for authorized operators.

**Steps to reproduce**

1. Configure an authenticated development instance at the parent commit.
2. Exercise the affected APIs with a restricted agent key or a
non-instance-admin company user.
3. Observe that the parent commit returns privileged data or accepts a
privileged operation.
4. Repeat on this branch and observe a redacted response, a safe
download, or an HTTP 403 response.

**Paperclip version or commit**

The findings reproduce from commit `39898ab22` and are fixed by this
pull request.

**Deployment mode**

Authenticated self-hosted server and local development modes.

**Installation method**

Built from source with pnpm.

## What Changed

- Redact generic secret `value` and `token` fields recursively in
structured logs.
- Classify exact and separator-suffixed `KEY` environment names as
secrets in company exports.
- Limit restricted self-identity responses and protect company run, log,
and secret catalog APIs.
- Route HTTP adapter requests through DNS-pinned SSRF protection with
exact private-origin allowlisting.
- Download HTML, SVG, and other script-capable assets with `nosniff` and
a sandbox CSP.
- Require instance-admin access for external instruction roots and
exports that read them.
- Block agent-authenticated host command persistence across supported
workspace runtime shapes.
- Apply the central runtime-management decision before workspace command
controls.
- Keep the documented first-user instance-admin claim contract
unchanged.
- Add regression tests and server-owner configuration documentation.

## Verification

- `pnpm -r typecheck` passes.
- The Node 24 remediation suite passes with 365 tests. It skips 25
environment-gated tests.
- `pnpm build` passes under Node 24.
- `git diff --check` passes.
- The full local runner reaches known macOS-only general-server harness
failures before the serialized route lane. The Linux PR matrix is the
authoritative full-suite gate.

## Risks

- Restricted agent keys now receive HTTP 403 responses from company-wide
run, log, and secret catalog endpoints.
- Script-capable assets now download instead of rendering inline.
- External instruction roots now require instance-admin access.
- Private HTTP adapter endpoints now require an exact origin in
`PAPERCLIP_HTTP_ADAPTER_PRIVATE_ENDPOINT_ALLOWLIST`.
- Public HTTP adapter endpoints remain enabled. Redirects and metadata
or link-local targets remain blocked.
- No database migration is required.

> 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. The exact serving snapshot and context-window size
are not exposed. The model used tool-enabled reasoning, repository
access, code execution, and test execution.

## 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
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge

---------

Co-authored-by: Paperclip <noreply@paperclip.ing>
2026-09-03 14:15:32 -05:00

206 lines
7.4 KiB
TypeScript

import express from "express";
import request from "supertest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const mockPortabilityService = vi.hoisted(() => ({
previewExport: vi.fn(),
exportBundle: vi.fn(),
previewImport: vi.fn(),
importBundle: vi.fn(),
}));
const mockTransferRunService = vi.hoisted(() => ({
resumeOrCreate: vi.fn(),
getRunForActor: vi.fn(),
recordCompletedPart: vi.fn(),
claimApply: vi.fn(),
releaseApplyClaim: vi.fn(),
completeRun: vi.fn(),
failRun: vi.fn(),
}));
const mockLogActivity = vi.hoisted(() => vi.fn());
vi.mock("../services/index.js", () => ({
accessService: () => ({}),
agentService: () => ({ list: vi.fn().mockResolvedValue([]) }),
budgetService: () => ({}),
companyArtifactsService: () => ({}),
companyPortabilityService: () => mockPortabilityService,
companyService: () => ({}),
feedbackService: () => ({}),
logActivity: mockLogActivity,
workTimelineService: () => ({}),
}));
vi.mock("../services/company-transfer-runs.js", () => ({
companyTransferRunService: mockTransferRunService,
}));
const TRANSFER_ID = "6e0a4f6e-6f7d-4a37-9a83-0b8f2f9f2b11";
/**
* Every route in the company-import surface. The floor must answer all of
* them, including the read-only polling routes: with imports disabled no job
* or transfer can exist, so a uniform 403 is clearer than a mixed surface.
*/
const IMPORT_ROUTES: Array<{ method: "get" | "post" | "put"; path: string }> = [
{ method: "post", path: "/api/companies/import/preview" },
{ method: "post", path: "/api/companies/import" },
{ method: "get", path: "/api/companies/import/jobs/some-job" },
{ method: "post", path: "/api/companies/import/transfers" },
{ method: "put", path: `/api/companies/import/transfers/${TRANSFER_ID}/parts/0` },
{ method: "get", path: `/api/companies/import/transfers/${TRANSFER_ID}` },
{ method: "post", path: `/api/companies/import/transfers/${TRANSFER_ID}/preview` },
{ method: "post", path: `/api/companies/import/transfers/${TRANSFER_ID}/apply` },
{ method: "post", path: "/api/companies/11111111-2222-4333-8444-555555555555/imports/preview" },
{ method: "post", path: "/api/companies/11111111-2222-4333-8444-555555555555/imports/apply" },
];
async function createApp(actor: Record<string, unknown>) {
const [{ companyRoutes }, { errorHandler }] = await Promise.all([
import("../routes/companies.js"),
import("../middleware/index.js"),
]);
const app = express();
app.use(express.json());
app.use((req, _res, next) => {
(req as any).actor = actor;
next();
});
app.use("/api/companies", companyRoutes({} as any));
app.use(errorHandler);
return app;
}
const boardAdmin = {
type: "board",
source: "local_implicit",
userId: "local-user",
isInstanceAdmin: true,
};
function expectNoImportWork() {
expect(mockPortabilityService.previewImport).not.toHaveBeenCalled();
expect(mockPortabilityService.importBundle).not.toHaveBeenCalled();
expect(mockTransferRunService.resumeOrCreate).not.toHaveBeenCalled();
expect(mockTransferRunService.getRunForActor).not.toHaveBeenCalled();
}
describe("company import Cloud floor", () => {
beforeEach(() => {
vi.clearAllMocks();
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
delete process.env.PAPERCLIP_MANAGED_CONFIG;
delete process.env.PAPERCLIP_HIDDEN_SETTINGS;
});
afterEach(() => {
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
delete process.env.PAPERCLIP_MANAGED_CONFIG;
delete process.env.PAPERCLIP_HIDDEN_SETTINGS;
});
it("returns 403 cloud_managed on every import route on a cloud-managed instance", async () => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "tenant-secret";
const app = await createApp(boardAdmin);
for (const route of IMPORT_ROUTES) {
const res = await request(app)[route.method](route.path).send({});
expect(res.status, `${route.method.toUpperCase()} ${route.path}`).toBe(403);
expect(res.body, `${route.method.toUpperCase()} ${route.path}`).toMatchObject({
code: "cloud_managed",
});
}
expectNoImportWork();
});
it("floors on the managed-config signal alone", async () => {
process.env.PAPERCLIP_MANAGED_CONFIG = JSON.stringify({ v: 1, mode: "cloud" });
const app = await createApp(boardAdmin);
const res = await request(app).post("/api/companies/import").send({});
expect(res.status).toBe(403);
expect(res.body).toMatchObject({ code: "cloud_managed" });
expectNoImportWork();
});
it("applies the floor before auth and request-body validation", async () => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "tenant-secret";
// An agent actor never passes the import routes' own assertBoard, and the
// body is not schema-valid either — the floor must still answer first so a
// Cloud caller sees one consistent refusal.
const app = await createApp({ type: "agent", agentId: "agent-1", companyId: "company-1" });
const res = await request(app)
.post("/api/companies/import/transfers")
.send({ nonsense: true });
expect(res.status).toBe(403);
expect(res.body).toMatchObject({ code: "cloud_managed" });
expectNoImportWork();
});
it("floors every import route with settings_operator_managed when company.import is hidden", async () => {
process.env.PAPERCLIP_HIDDEN_SETTINGS = "company.import";
const app = await createApp(boardAdmin);
for (const route of IMPORT_ROUTES) {
const res = await request(app)[route.method](route.path).send({});
expect(res.status, `${route.method.toUpperCase()} ${route.path}`).toBe(403);
expect(res.body, `${route.method.toUpperCase()} ${route.path}`).toMatchObject({
code: "settings_operator_managed",
});
}
expectNoImportWork();
});
it("keeps import open when only other company pages are hidden", async () => {
process.env.PAPERCLIP_HIDDEN_SETTINGS = "company.secrets,company.members";
const app = await createApp(boardAdmin);
const res = await request(app).get("/api/companies/import/jobs/unknown-job");
expect(res.status).toBe(404);
expect(res.body).toMatchObject({ error: "Import job not found" });
});
it("keeps company export open on a cloud-managed instance", async () => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "tenant-secret";
mockPortabilityService.exportBundle.mockResolvedValue({ ok: true });
const app = await createApp(boardAdmin);
const res = await request(app)
.post("/api/companies/11111111-2222-4333-8444-555555555555/exports")
.send({});
expect(res.status).toBe(200);
expect(mockPortabilityService.exportBundle).toHaveBeenCalledTimes(1);
});
it("preserves self-hosted import preview", async () => {
mockPortabilityService.previewImport.mockResolvedValue({ companies: [] });
const app = await createApp(boardAdmin);
const res = await request(app)
.post("/api/companies/import/preview")
.send({
source: { type: "github", url: "https://github.com/example/export" },
target: { mode: "new_company" },
});
expect(res.status).toBe(200);
expect(mockPortabilityService.previewImport).toHaveBeenCalledTimes(1);
});
it("preserves self-hosted import job polling", async () => {
const app = await createApp(boardAdmin);
const res = await request(app).get("/api/companies/import/jobs/unknown-job");
expect(res.status).toBe(404);
expect(res.body).toMatchObject({ error: "Import job not found" });
});
});