Files
PaperClipAI/server/src/middleware/cloud-tenant-actor.test.ts
T
DottaandPaperclip d9bcf4dfe8 fix(auth): let Cloud stack admins manage experimental settings (#16907)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work.
> - People use experimental settings to opt into product features.
> - Cloud stack Admins can manage their company, but cannot save an
experiment.
> - Requiring an Owner role adds unrelated privileges to this workflow.
> - This pull request gives trusted Cloud stack Admins permission to
update experiments.
> - Other instance administration and platform settings keep their
existing checks.

## Linked Issues or Issue Description

**What happened?**

A person with the Cloud stack Admin role receives “Instance admin access
required” when they enable an experimental setting, such as Fast
responses.

**Expected behavior**

Cloud stack Admins can save editable experimental settings. This
permission does not grant general instance-admin authority. Members,
Support users, and agents cannot change experiments. Cloud-managed and
operator-hidden settings remain protected.

**Steps to reproduce**

1. Sign into a Cloud staging workspace as a stack Admin.
2. Open Settings → Experimental.
3. Enable Experimental fast responses.
4. Observe the permission error instead of a saved setting.

**Additional context**

Related: #10343 introduced computed Owner elevation. #15748 added Fast
responses and the company Connections settings page. The roadmap and
existing PRs were checked. This is a small authorization fix for the
existing settings path.

## What Changed

- Derive experiment-management authority from the current trusted Cloud
stack Admin role on each request.
- Apply that authority only to the experimental settings PATCH route.
Keep general settings, environment defaults, and task drain restricted
to instance admins.
- Preserve existing hidden-setting checks, managed feature restrictions,
and activity records.
- Add role and role-downgrade regressions, allowed and denied route
cases, staging coverage, and updated OpenAPI and access documentation.

## Verification

- Before the fix, the Admin fast-response request returned 403 and the
new role assertions failed. The first sandboxed HTTP run could not bind
local sockets; the regression run outside that sandbox reached the
expected authorization failures.
- Focused Cloud actor, settings route, managed-overlay, and health
tests: 149 passed.
- `node scripts/check-maps.mjs` and `git diff --check` pass.
- `pnpm -r typecheck` and `pnpm build` pass.
- Greptile reviewed commit `7c33b90066121f03183579d2fae2650755e025e4` at
5/5. Its one style finding is fixed and resolved.
- The full local `pnpm test:run` did not pass. It reported two early
collection failures before workspace build outputs were ready and a
15-second timeout in the unchanged AgentMail recovery test. The run was
stopped after those failures while the full CI suite continued. No full
local-suite pass is claimed.
- The first current-head CI attempt failed the unchanged Runner test
“preserves a real listening process and its marker when a health RPC
times out” with `runner_remote_process_identity_unavailable` /
`process_identity_changed`. The test passes in a local isolated run.
This recovery does not establish the CI failure's cause. [Failed
job](https://github.com/paperclipai/paperclip/actions/runs/39332989655/job/118336142261).
The failed shard passed on its single rerun. The failure cause remains
unconfirmed. All CI checks on commit
`7c33b90066121f03183579d2fae2650755e025e4` are now green. [Final CI
run](https://github.com/paperclipai/paperclip/actions/runs/39332989655).
- No deployed staging behavior is claimed. Manual acceptance after
deployment: as a stack Admin, enable Fast responses, reload, and confirm
Connections appears. Confirm Members and Support users still cannot save
experiments.

## Risks

- This intentionally extends experimental settings write access to Cloud
stack Admins. It does not persist an instance-admin role or expand other
instance controls.
- Production retains its existing managed feature policy. Staging
retains its editable experiment allowlist and protected execution and
owner-elevation settings.
- No database migration or UI change is required.

## Model Used

OpenAI Codex, based on GPT-6, with reasoning, repository tools, code
execution, and browser inspection. The runtime does not expose an exact
model snapshot or context-window size.

## 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-10-19 21:48:00 -05:00

419 lines
18 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it } from "vitest";
import express, { type Request } from "express";
import request from "supertest";
import { and, eq } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import {
authUsers,
companies,
companyMemberships,
instanceSettings,
instanceUserRoles,
principalPermissionGrants,
} from "@paperclipai/db";
import { actorMiddleware, cloudActorHeaderSourceFromHeaders, resolveCloudTenantActor } from "./auth.js";
import { idleAdmissionMiddleware, trackIdleRequestHandlers } from "./idle-admission.js";
import { idleWorkSnapshot, startTaskDrain, stopTaskDrain } from "../services/task-admission.js";
import { readIdleSleepSafety } from "../services/idle-sleep-safety.js";
// Minimal fake Drizzle Db: records every table passed to .insert() / .delete() and
// supports the chained call shapes used by resolveCloudTenantActor (values /
// onConflictDo* / returning().then() / delete().where()), plus the
// select().from(table).where() reads: instanceSettings for the owner-elevation
// flag resolution through instanceSettingsService, and companyMemberships for
// the user's own membership rows (rows configurable via membershipQueryRows,
// where-conditions captured in selectWheres). The chain is awaitable so
// directly-awaited statements resolve.
function createFakeDb(options: {
membershipRow?: { companyId: string; membershipRole: string; status: string };
membershipQueryRows?: Array<{ companyId: string; membershipRole: string | null; status: string }>;
settingsRow?: Record<string, unknown> | null;
selectThrows?: boolean;
beforeWrite?: () => Promise<void>;
} = {}) {
const membershipRow =
options.membershipRow ?? { companyId: "company-x", membershipRole: "owner", status: "active" };
const settingsRow =
options.settingsRow === undefined
? {
id: "00000000-0000-0000-0000-000000000001",
singletonKey: "default",
defaultEnvironmentId: null,
general: {},
experimental: {},
createdAt: new Date(),
updatedAt: new Date(),
}
: options.settingsRow;
const insertedTables: unknown[] = [];
const deletedTables: unknown[] = [];
const selectWheres: Array<{ table: unknown; condition: unknown }> = [];
const chain: Record<string, unknown> = {};
chain.values = () => chain;
chain.onConflictDoUpdate = () => chain;
chain.onConflictDoNothing = () => chain;
chain.where = () => chain;
chain.returning = async () => { await options.beforeWrite?.(); return [membershipRow]; };
chain.then = (resolve: (v: unknown) => unknown, reject?: (error: unknown) => unknown) =>
Promise.resolve().then(options.beforeWrite).then(resolve, reject);
const db = {
insert: (table: unknown) => {
insertedTables.push(table);
return chain;
},
delete: (table: unknown) => {
deletedTables.push(table);
return chain;
},
select: () => {
return {
from: (table: unknown) => ({
where: (condition: unknown) => {
// Role-default grant seeding reads existing grants first; keep that
// read working so selectThrows exercises only the degradable reads.
if (options.selectThrows && table !== principalPermissionGrants) {
throw new Error("select unavailable");
}
selectWheres.push({ table, condition });
const rows =
table === instanceSettings && settingsRow
? [settingsRow]
: table === companyMemberships
? (options.membershipQueryRows ?? [])
: [];
return {
then: (resolve: (v: unknown) => unknown) => Promise.resolve(rows).then(resolve),
};
},
}),
};
},
} as unknown as Db;
return { db, insertedTables, deletedTables, selectWheres };
}
function settingsRowWith(experimental: Record<string, unknown>) {
return {
id: "00000000-0000-0000-0000-000000000001",
singletonKey: "default",
defaultEnvironmentId: null,
general: {},
experimental,
createdAt: new Date(),
updatedAt: new Date(),
};
}
function fakeReq(headers: Record<string, string>): Request {
const lower: Record<string, string> = {};
for (const [k, v] of Object.entries(headers)) lower[k.toLowerCase()] = v;
return { header: (name: string) => lower[name.toLowerCase()] } as unknown as Request;
}
const VALID_HEADERS = {
"x-paperclip-cloud-tenant-token": "test-server-token",
"x-paperclip-cloud-user-id": "user-123",
"x-paperclip-cloud-user-email": "Owner@Example.com",
"x-paperclip-cloud-stack-id": "stack-abc",
"x-paperclip-cloud-stack-role": "owner",
};
const MANAGED_CONFIG_FLAG_ON = JSON.stringify({
v: 1,
mode: "cloud",
catalogVersion: "test",
features: { enableOwnerInstanceAdmin: true },
plugins: { autoInstall: [] },
});
const MANAGED_CONFIG_FLAG_OFF = JSON.stringify({
v: 1,
mode: "cloud",
catalogVersion: "test",
features: { enableOwnerInstanceAdmin: false },
plugins: { autoInstall: [] },
});
describe("resolveCloudTenantActor (shared-pool hardening)", () => {
beforeEach(() => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "test-server-token";
});
afterEach(() => {
stopTaskDrain();
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
delete process.env.PAPERCLIP_MANAGED_CONFIG;
});
it("does not grant instance admin by default (flag off)", async () => {
const { db, insertedTables } = createFakeDb();
const actor = await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
expect(actor).not.toBeNull();
expect(actor!.isInstanceAdmin).toBe(false);
expect(insertedTables).not.toContain(instanceUserRoles);
});
it("stays scoped to exactly the stack's company when the user has no other membership rows", async () => {
const { db } = createFakeDb();
const actor = await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
expect(actor!.companyIds).toHaveLength(1);
expect(actor!.memberships).toHaveLength(1);
expect(actor?.memberships?.[0]?.companyId).toBe(actor?.companyIds?.[0]);
expect(actor?.memberships?.[0]?.membershipRole).toBe("owner");
expect(actor!.source).toBe("cloud_tenant");
});
it("purges stale instance_admin rows left by pre-hardening deployments", async () => {
const { db, deletedTables } = createFakeDb();
const actor = await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
expect(actor).not.toBeNull();
expect(deletedTables).toContain(instanceUserRoles);
});
it("still upserts the user, company, and membership", async () => {
const { db, insertedTables } = createFakeDb();
await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
expect(insertedTables).toContain(authUsers);
expect(insertedTables).toContain(companies);
expect(insertedTables).toContain(companyMemberships);
});
it.each(["/api/health", "/api/instance/task-drain"])("counts unfinished authentication on exempt %s requests", async (path) => {
let enterWrite!: () => void, finishWrite!: () => void;
const entered = new Promise<void>(resolve => { enterWrite = resolve; });
const pending = new Promise<void>(resolve => { finishWrite = resolve; });
const { db, insertedTables } = createFakeDb({ beforeWrite: async () => { enterWrite(); await pending; } });
const server = express();
server.use(idleAdmissionMiddleware);
server.use(actorMiddleware(db, { deploymentMode: "authenticated", resolveSession: async () => null }));
const hold = startTaskDrain({ purpose: "idle", ttlMs: 60_000 });
const emptyDb = { transaction: async (run: (tx: unknown) => Promise<unknown>) =>
run({ execute: async () => [{ blocked: false }] }) } as unknown as Db;
server.get("/api/health", (_req, res) => res.sendStatus(204));
server.get("/api/instance/task-drain", async (_req, res) => {
res.json(await readIdleSleepSafety(emptyDb, () => ({ ...hold, draining: true, activeRuns: 0, pendingWakes: 0 }),
Date.now, hold.ownerId, async () => "none"));
});
trackIdleRequestHandlers(server);
const accepted = request(server).get(path).set(VALID_HEADERS).then(response => response);
try {
await entered;
expect(idleWorkSnapshot().active).toBeGreaterThan(0);
const during = await request(server).get("/api/instance/task-drain").expect(200);
expect(during.body.backgroundWork).toBe("unknown");
} finally {
finishWrite();
await accepted;
}
expect(insertedTables).toEqual(expect.arrayContaining([authUsers, companies, companyMemberships]));
expect(idleWorkSnapshot().active).toBe(0);
const after = await request(server).get("/api/instance/task-drain").expect(200);
expect(after.body.backgroundWork).toBe("none");
});
it("releases failed control authentication and preserves Express error handling", async () => {
const { db } = createFakeDb({ beforeWrite: async () => { throw new Error("fixture write failed"); } });
const server = express();
server.use(idleAdmissionMiddleware);
server.use(actorMiddleware(db, { deploymentMode: "authenticated", resolveSession: async () => null }));
server.get("/api/health", (_req, res) => res.sendStatus(204));
server.use((_err: Error, _req: express.Request, res: express.Response, _next: express.NextFunction) => res.sendStatus(500));
trackIdleRequestHandlers(server);
await request(server).get("/api/health").set(VALID_HEADERS).expect(500);
expect(idleWorkSnapshot().active).toBe(0);
await request(server).get("/api/health").expect(204);
});
it("resyncs an A to B to A context transition inside the debounce window", async () => {
const { db, insertedTables } = createFakeDb();
const contextA = VALID_HEADERS;
const contextB = { ...VALID_HEADERS, "x-paperclip-cloud-stack-role": "member" };
await resolveCloudTenantActor(db, fakeReq(contextA));
await resolveCloudTenantActor(db, fakeReq(contextB));
await resolveCloudTenantActor(db, fakeReq(contextA));
expect(insertedTables.filter((table) => table === authUsers)).toHaveLength(3);
expect(insertedTables.filter((table) => table === companyMemberships)).toHaveLength(3);
});
it("returns null when the server token is unset", async () => {
delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
const { db } = createFakeDb();
const actor = await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
expect(actor).toBeNull();
});
it("resolves identically from a raw upgrade-request header map via the shim", async () => {
// Websocket upgrades hand us IncomingMessage.headers (lowercased keys,
// possibly string[] values), not an Express Request. The shim must feed
// resolveCloudTenantActor the same way Express header() does.
const { db } = createFakeDb();
const rawHeaders: Record<string, string | string[] | undefined> = {};
for (const [k, v] of Object.entries(VALID_HEADERS)) rawHeaders[k.toLowerCase()] = v;
rawHeaders["x-paperclip-cloud-user-name"] = ["Cloud Owner", "ignored-duplicate"];
const actor = await resolveCloudTenantActor(db, cloudActorHeaderSourceFromHeaders(rawHeaders));
expect(actor).not.toBeNull();
expect(actor!.userId).toBe("user-123");
expect(actor!.userName).toBe("Cloud Owner");
expect(actor!.companyIds).toHaveLength(1);
});
it("maps a non-owner stack role through to the membership without elevating", async () => {
const { db } = createFakeDb({
membershipRow: { companyId: "company-y", membershipRole: "member", status: "active" },
});
const actor = await resolveCloudTenantActor(
db,
fakeReq({ ...VALID_HEADERS, "x-paperclip-cloud-stack-role": "member" }),
);
expect(actor!.isInstanceAdmin).toBe(false);
expect(actor?.memberships?.[0]?.membershipRole).toBe("member");
});
it.each(["admin", "member", "support"])(
"grants experimental settings access only to the admin stack role (%s)",
async (stackRole) => {
const { db, insertedTables } = createFakeDb();
const actor = await resolveCloudTenantActor(
db,
fakeReq({ ...VALID_HEADERS, "x-paperclip-cloud-stack-role": stackRole }),
);
expect(actor?.canManageExperimentalSettings).toBe(stackRole === "admin");
expect(actor?.isInstanceAdmin).toBe(false);
expect(insertedTables).not.toContain(instanceUserRoles);
},
);
it("removes experimental settings access on the next request after a stack admin is demoted", async () => {
const { db } = createFakeDb();
const admin = await resolveCloudTenantActor(
db,
fakeReq({ ...VALID_HEADERS, "x-paperclip-cloud-stack-role": "admin" }),
);
const member = await resolveCloudTenantActor(
db,
fakeReq({ ...VALID_HEADERS, "x-paperclip-cloud-stack-role": "member" }),
);
expect(admin?.canManageExperimentalSettings).toBe(true);
expect(member?.canManageExperimentalSettings).toBe(false);
});
describe("company membership union", () => {
// The primary company id is derived from the stack id; resolve it once
// through the same code path instead of duplicating the hash here.
async function resolvePrimaryCompanyId() {
const { db } = createFakeDb();
const actor = await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
return actor!.companyIds![0]!;
}
it("unions the pinned primary with the user's own active membership rows, primary first and deduped", async () => {
const primaryCompanyId = await resolvePrimaryCompanyId();
const { db } = createFakeDb({
membershipQueryRows: [
// The user's own row for the primary company comes back from the
// query too — it must not appear twice.
{ companyId: primaryCompanyId, membershipRole: "owner", status: "active" },
{ companyId: "company-imported", membershipRole: "member", status: "active" },
],
});
const actor = await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
expect(actor!.companyIds).toEqual([primaryCompanyId, "company-imported"]);
expect(actor!.memberships).toEqual([
{ companyId: primaryCompanyId, membershipRole: "owner", status: "active" },
{ companyId: "company-imported", membershipRole: "member", status: "active" },
]);
});
it("loads memberships with the session path's exact own-user active-status filter", async () => {
const { db, selectWheres } = createFakeDb();
await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
const membershipSelects = selectWheres.filter((entry) => entry.table === companyMemberships);
expect(membershipSelects).toHaveLength(1);
// Rows for other users and rows in any non-active status are excluded
// by the query itself: the filter binds exactly this user id and the
// "active" status — the same condition the session path applies.
expect(membershipSelects[0]!.condition).toEqual(
and(
eq(companyMemberships.principalType, "user"),
eq(companyMemberships.principalId, "user-123"),
eq(companyMemberships.status, "active"),
),
);
});
it("degrades to the primary company when the membership read fails", async () => {
const { db } = createFakeDb({ selectThrows: true });
const actor = await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
expect(actor).not.toBeNull();
expect(actor!.companyIds).toHaveLength(1);
expect(actor!.memberships).toHaveLength(1);
});
});
describe("owner instance-admin elevation (enableOwnerInstanceAdmin)", () => {
it("elevates the owner while the flag is enabled, still without any role row", async () => {
const { db, insertedTables, deletedTables } = createFakeDb({
settingsRow: settingsRowWith({ enableOwnerInstanceAdmin: true }),
});
const actor = await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
expect(actor!.isInstanceAdmin).toBe(true);
expect(actor!.source).toBe("cloud_tenant");
// Elevation is computed, never persisted: no instance_user_roles insert,
// and the stale-row purge still runs on every authentication.
expect(insertedTables).not.toContain(instanceUserRoles);
expect(deletedTables).toContain(instanceUserRoles);
});
it("does not elevate the owner while the flag is disabled", async () => {
const { db } = createFakeDb({
settingsRow: settingsRowWith({ enableOwnerInstanceAdmin: false }),
});
const actor = await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
expect(actor!.isInstanceAdmin).toBe(false);
});
it.each(["member", "admin", "support"] as const)(
"never elevates the %s stack role even with the flag enabled",
async (stackRole) => {
const { db } = createFakeDb({
membershipRow: { companyId: "company-y", membershipRole: "member", status: "active" },
settingsRow: settingsRowWith({ enableOwnerInstanceAdmin: true }),
});
const actor = await resolveCloudTenantActor(
db,
fakeReq({ ...VALID_HEADERS, "x-paperclip-cloud-stack-role": stackRole }),
);
expect(actor).not.toBeNull();
expect(actor!.isInstanceAdmin).toBe(false);
},
);
it("resolves the flag through the managed overlay: overlay on elevates over a DB value of off", async () => {
process.env.PAPERCLIP_MANAGED_CONFIG = MANAGED_CONFIG_FLAG_ON;
const { db } = createFakeDb({
settingsRow: settingsRowWith({ enableOwnerInstanceAdmin: false }),
});
const actor = await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
expect(actor!.isInstanceAdmin).toBe(true);
});
it("resolves the flag through the managed overlay: overlay off wins over a DB value of on", async () => {
process.env.PAPERCLIP_MANAGED_CONFIG = MANAGED_CONFIG_FLAG_OFF;
const { db } = createFakeDb({
settingsRow: settingsRowWith({ enableOwnerInstanceAdmin: true }),
});
const actor = await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
expect(actor!.isInstanceAdmin).toBe(false);
});
it("fails closed when the settings read errors: actor resolves without elevation", async () => {
const { db, deletedTables } = createFakeDb({ selectThrows: true });
const actor = await resolveCloudTenantActor(db, fakeReq(VALID_HEADERS));
expect(actor).not.toBeNull();
expect(actor!.isInstanceAdmin).toBe(false);
expect(deletedTables).toContain(instanceUserRoles);
});
});
});