Files
PaperClipAI/server/src/__tests__/auth-session-route.test.ts
T
DottaandClaude Opus 5.5 99a6daf5bc perf(auth): resolve a Cloud tenant actor in one database round trip (#20390)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - On Paperclip Cloud, each request resolves its board actor from
trusted Cloud headers in `actorMiddleware`
> - This runs for every request after the liveness probe, also for
static files such as `favicon.ico` and `index.html`
> - The resolution ran three database statements one after another: the
stale `instance_admin` purge, the membership read and the
owner-elevation read
> - On a loaded database, each statement waits. Three sequential waits
make every request slow, also a request that needs no data
> - This pull request keeps the purge and the tenant sync in order and
runs the two reads at the same time as them
> - The benefit is one database wait per request instead of three

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Cloud tenant actor resolution in `server/src/middleware/auth.ts`
(`resolveCloudTenantActorOnce`).

**Subsystem affected**
Server authentication middleware (Cloud trusted-header path).

**Current behavior**
Measured on the hosted staging instance on 2026-11-09 from a signed-in
browser, 45 paired samples in 40 s:
- `/api/liveness` (mounted before actor resolution): client median 92
ms, p90 255 ms, server time ≤ 1 ms.
- `/favicon.ico` with a session (after actor resolution): client median
413 ms, p90 1,751 ms, max 4.6 s.
- `/api/cli-auth/me`: server median 346 ms, p90 1,528 ms.
The same Node process answers liveness quickly, so the event loop is not
blocked. The database is busy (6–8 of 8 vCPU for the whole day), and
trivial primary-key reads waited 100–280 ms each. Three sequential reads
explain the ~320 ms median gap between liveness and favicon.

**Proposed behavior**
The purge and the debounced tenant sync stay ordered. The membership
read and the owner-elevation read run at the same time as them. The sync
writes only the primary company's membership, and the membership read
excludes that company, so the result does not change.

**Reason and benefit**
A synced request costs one database wait instead of three. With 150 ms
of injected database latency, a synced resolution goes from 914 ms to
310 ms (3 runs each, same machine).

**Breaking changes**
None.

## What Changed

- `resolveCloudTenantActorOnce` starts the purge-and-sync, the
additional-membership read and `resolveOwnerInstanceAdmin` together and
awaits them with `Promise.all`. A membership read failure still degrades
to the primary company. The owner-elevation read still fails closed.
- New regression test
`server/src/__tests__/cloud-tenant-actor-round-trips.test.ts`. It
connects through a TCP proxy that delays every client write by 150 ms
and asserts that a synced resolution finishes in less than 4 × the
delay. Before the change it takes about 6 × (914 ms); after the change
about 2 × (310 ms).
- `auth-session-route.test.ts`: the fake database binds each
`returning()` to its own insert, and the test matches inserts by content
instead of position, because the instance-settings insert can now happen
in parallel with the tenant sync.

## Verification

- `cd server && npx vitest run
src/__tests__/cloud-tenant-actor-round-trips.test.ts` — red on
`origin/master` (914 ms, 913 ms, 916 ms), green with the change (310
ms).
- `cd server && npx vitest run
src/__tests__/cloud-tenant-company-provisioning.test.ts
src/__tests__/auth-session-route.test.ts src/__tests__/liveness.test.ts
src/__tests__/cloud-warm-standby.test.ts
src/middleware/cloud-tenant-actor.test.ts`
- `pnpm verify` (selected tests), and CI.
- After deploy: compare `/favicon.ico` and `/api/cli-auth/me` client
time with `/api/liveness` on staging. Expect the median gap to drop from
about 3 database waits to about 1.

## Risks

- Low risk. Authorization does not change: the same statements run and
the request waits for all of them before it continues.
- Each request now uses up to three pooled connections at the same time
instead of one. The staging pool limit is 500, so this is not a concern
there. Smaller pools reach their limit sooner under a burst.
- The diff re-indents the purge-and-sync block. The statements in it do
not change.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`), Anthropic, via Claude Code with
tool use (shell, browser, code execution). Extended reasoning on.

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

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-09 20:29:37 -06:00

432 lines
15 KiB
TypeScript

import express from "express";
import request from "supertest";
import { afterEach, describe, expect, it, vi } from "vitest";
import { activityLog, companies, companyMemberships, instanceUserRoles } from "@paperclipai/db";
import {
actorMiddleware,
humanizeCloudStackSlug,
isKnownBadCloudCompanyName,
} from "../middleware/auth.js";
import { errorHandler } from "../middleware/error-handler.js";
import { assertCompanyAccess } from "../routes/authz.js";
function queryResult<T>(rows: T) {
return Object.assign(Promise.resolve(rows), {
for: () => Promise.resolve(rows),
orderBy: () => ({ limit: () => Promise.resolve(rows) }),
});
}
function createSelectChain(rows: unknown[] | ((table: unknown) => unknown[])) {
return {
from(table: unknown) {
const selected = typeof rows === "function" ? rows(table) : rows;
const where = () => queryResult(selected);
return { where, innerJoin: () => ({ where }) };
},
};
}
function createDb() {
return {
select: vi
.fn()
.mockImplementationOnce(() => createSelectChain([]))
.mockImplementationOnce(() => createSelectChain([])),
} as any;
}
describe("actorMiddleware authenticated session profile", () => {
const originalCloudTenantToken = process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
afterEach(() => {
if (originalCloudTenantToken === undefined) delete process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN;
else process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = originalCloudTenantToken;
});
it("preserves the signed-in user name and email on the board actor", async () => {
const app = express();
app.use(
actorMiddleware(createDb(), {
deploymentMode: "authenticated",
resolveSession: async () => ({
session: { id: "session-1", userId: "user-1" },
user: {
id: "user-1",
name: "User One",
email: "user@example.com",
},
}),
}),
);
app.get("/actor", (req, res) => {
res.json(req.actor);
});
const res = await request(app).get("/actor");
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
type: "board",
userId: "user-1",
userName: "User One",
userEmail: "user@example.com",
source: "session",
companyIds: [],
memberships: [],
isInstanceAdmin: false,
});
});
it("trusts Cloud tenant identity headers and seeds board access", async () => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "tenant-token";
const inserts: Array<{ values: Record<string, unknown> }> = [];
const db = {
insert: vi.fn(() => {
let own: { values: Record<string, unknown> } | undefined;
const chain = {
values(values: Record<string, unknown>) {
own = { values };
inserts.push(own);
return chain;
},
onConflictDoUpdate() {
return chain;
},
onConflictDoNothing() {
return chain;
},
returning() {
return Promise.resolve([{
companyId: own?.values.companyId,
membershipRole: own?.values.membershipRole,
status: own?.values.status,
}]);
},
};
return chain;
}),
delete: vi.fn(() => ({ where: () => Promise.resolve(undefined) })),
select: vi.fn(() => createSelectChain([])),
} as any;
db.transaction = vi.fn(async (run: (tx: typeof db) => Promise<unknown>) => run(db));
const app = express();
app.use(
actorMiddleware(db, {
deploymentMode: "authenticated",
resolveSession: async () => null,
}),
);
app.get("/actor", (req, res) => {
res.json(req.actor);
});
const res = await request(app)
.get("/actor")
.set("x-paperclip-cloud-tenant-token", "tenant-token")
.set("x-paperclip-cloud-user-id", "global-user-1")
.set("x-paperclip-cloud-user-email", "owner@example.com")
.set("x-paperclip-cloud-user-name", "Stack Owner")
.set("x-paperclip-cloud-stack-id", "stack-alpha")
.set("x-paperclip-cloud-paperclip-company-id", "paperclip-stack-alpha")
.set("x-paperclip-cloud-paperclip-company-name", "Purple Rain")
.set("x-paperclip-cloud-stack-role", "owner");
expect(res.status).toBe(200);
expect(res.body).toMatchObject({
type: "board",
userId: "global-user-1",
userName: "Stack Owner",
userEmail: "owner@example.com",
source: "cloud_tenant",
isInstanceAdmin: false,
memberships: [expect.objectContaining({ membershipRole: "owner", status: "active" })],
});
expect(res.body.companyIds[0]).toMatch(/^[0-9a-f-]{36}$/);
// authUsers, companies, companyMemberships, the role-default
// principalPermissionGrants, and the lazily initialized instance setting.
// The instance setting is read concurrently with the tenant sync, so
// match inserts by content rather than position.
expect(inserts).toHaveLength(5);
expect(inserts.map((insert) => insert.values)).toEqual(expect.arrayContaining([
expect.objectContaining({
id: "global-user-1",
email: "owner@example.com",
emailVerified: true,
}),
expect.objectContaining({ name: "Purple Rain" }),
expect.objectContaining({ singletonKey: "default" }),
]));
});
it("lets the cloud tenant actor through assertCompanyAccess for a company it holds a membership row in", async () => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "tenant-token";
// A company created on the instance after provisioning (e.g. by a company
// import) — the user has a real membership row, but it is not the stack's
// seeded primary company.
const importedCompanyId = "33333333-3333-4333-8333-333333333333";
const unrelatedCompanyId = "44444444-4444-4444-8444-444444444444";
const insertChain = {
values() {
return insertChain;
},
onConflictDoUpdate() {
return insertChain;
},
onConflictDoNothing() {
return insertChain;
},
returning() {
return Promise.resolve([{ companyId: "company-1", membershipRole: "member", status: "active" }]);
},
then(resolve: (value: unknown) => unknown) {
return Promise.resolve(undefined).then(resolve);
},
};
const db = {
select: vi.fn(() => ({
from: (table: unknown) => ({
where: () =>
queryResult(
table === companyMemberships
? [{ companyId: importedCompanyId, membershipRole: "member", status: "active" }]
: [],
),
}),
})),
insert: vi.fn(() => insertChain),
delete: vi.fn(() => ({ where: () => Promise.resolve(undefined) })),
} as any;
db.transaction = vi.fn(async (run: (tx: typeof db) => Promise<unknown>) => run(db));
const app = express();
app.use(
actorMiddleware(db, {
deploymentMode: "authenticated",
resolveSession: async () => null,
}),
);
app.get("/companies/:companyId/resource", (req, res) => {
assertCompanyAccess(req, req.params.companyId);
res.json({ ok: true, companyIds: req.actor.companyIds });
});
app.post("/companies/:companyId/resource", (req, res) => {
assertCompanyAccess(req, req.params.companyId);
res.json({ ok: true });
});
app.use(errorHandler);
const cloudHeaders = {
"x-paperclip-cloud-tenant-token": "tenant-token",
"x-paperclip-cloud-user-id": "global-user-1",
"x-paperclip-cloud-user-email": "owner@example.com",
"x-paperclip-cloud-stack-id": "stack-alpha",
"x-paperclip-cloud-stack-role": "member",
};
// Reads and writes both reach the imported company through the real
// membership row (write access also consults actor.memberships).
const read = await request(app).get(`/companies/${importedCompanyId}/resource`).set(cloudHeaders);
expect(read.status).toBe(200);
expect(read.body.companyIds).toContain(importedCompanyId);
const write = await request(app).post(`/companies/${importedCompanyId}/resource`).set(cloudHeaders);
expect(write.status).toBe(200);
// Companies the user holds no membership row in stay unreachable.
const denied = await request(app).get(`/companies/${unrelatedCompanyId}/resource`).set(cloudHeaders);
expect(denied.status).toBe(403);
});
it("repairs a legacy machine company name from the trusted human-name header", async () => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "tenant-token";
const updates: Array<Record<string, unknown>> = [];
const activities: Array<Record<string, unknown>> = [];
const insertChain = {
values() {
return insertChain;
},
onConflictDoUpdate() {
return insertChain;
},
onConflictDoNothing() {
return insertChain;
},
returning() {
return Promise.resolve([
{ companyId: "company-1", membershipRole: "owner", status: "active" },
]);
},
then(resolve: (value: unknown) => unknown) {
return Promise.resolve(undefined).then(resolve);
},
};
const db = {
select: vi.fn(() => createSelectChain(table => table === companies
? [{ name: "paperclip-stack-purple-rain" }] : [])),
insert: vi.fn((table: unknown) => {
if (table !== activityLog) return insertChain;
return {
values(values: Record<string, unknown>) {
activities.push(values);
return Promise.resolve(undefined);
},
};
}),
update: vi.fn(() => ({
set(values: Record<string, unknown>) {
updates.push(values);
return {
where: () => ({
returning: () => Promise.resolve([{ id: "company-1" }]),
}),
};
},
})),
delete: vi.fn(() => ({ where: () => Promise.resolve(undefined) })),
} as any;
db.transaction = vi.fn(async (run: (tx: typeof db) => Promise<unknown>) => run(db));
const app = express();
app.use(
actorMiddleware(db, {
deploymentMode: "authenticated",
resolveSession: async () => null,
}),
);
app.get("/actor", (req, res) => res.json(req.actor));
const res = await request(app)
.get("/actor")
.set("x-paperclip-cloud-tenant-token", "tenant-token")
.set("x-paperclip-cloud-user-id", "global-user-1")
.set("x-paperclip-cloud-user-email", "owner@example.com")
.set("x-paperclip-cloud-stack-id", "stack-purple-rain")
.set(
"x-paperclip-cloud-paperclip-company-id",
"paperclip-stack-purple-rain",
)
.set("x-paperclip-cloud-paperclip-company-name", "Purple Rain")
.set("x-paperclip-cloud-stack-role", "owner");
expect(res.status).toBe(200);
expect(updates).toHaveLength(1);
expect(updates[0]).toMatchObject({ name: "Purple Rain" });
expect(activities).toEqual([
expect.objectContaining({
companyId: expect.any(String),
actorType: "system",
actorId: "cloud-tenant-auth",
action: "company.updated",
entityType: "company",
details: expect.objectContaining({
reason: "legacy_machine_name_repair",
previousName: "paperclip-stack-purple-rain",
name: "Purple Rain",
}),
}),
]);
});
it("purges a stale instance_admin row so the session path stops elevating the cloud-tenant user", async () => {
process.env.PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN = "tenant-token";
// Simulates a deployment that previously ran the pre-hardening cloud_tenant
// path: instance_user_roles still holds an instance_admin row for the
// tenant user, who can also resolve a BetterAuth session for the same id.
const state = { staleInstanceAdminRow: true };
const insertChain = {
values() {
return insertChain;
},
onConflictDoUpdate() {
return insertChain;
},
onConflictDoNothing() {
return insertChain;
},
returning() {
return Promise.resolve([{ companyId: "company-1", membershipRole: "owner", status: "active" }]);
},
then(resolve: (value: unknown) => unknown) {
return Promise.resolve(undefined).then(resolve);
},
};
const db = {
select: vi.fn(() => createSelectChain(table =>
table === instanceUserRoles && state.staleInstanceAdminRow ? [{ id: "stale-role-row" }] : [])),
insert: vi.fn(() => insertChain),
delete: vi.fn((table: unknown) => ({
where: () => {
if (table === instanceUserRoles) state.staleInstanceAdminRow = false;
return Promise.resolve(undefined);
},
})),
} as any;
db.transaction = vi.fn(async (run: (tx: typeof db) => Promise<unknown>) => run(db));
const app = express();
app.use(
actorMiddleware(db, {
deploymentMode: "authenticated",
resolveSession: async () => ({
session: { id: "session-1", userId: "global-user-1" },
user: { id: "global-user-1", name: "Stack Owner", email: "owner@example.com" },
}),
}),
);
app.get("/actor", (req, res) => {
res.json(req.actor);
});
// Control: while the stale row exists, the session path still elevates.
const before = await request(app).get("/actor");
expect(before.body).toMatchObject({ source: "session", isInstanceAdmin: true });
// One trusted-header authentication purges the stale grant.
const cloud = await request(app)
.get("/actor")
.set("x-paperclip-cloud-tenant-token", "tenant-token")
.set("x-paperclip-cloud-user-id", "global-user-1")
.set("x-paperclip-cloud-user-email", "owner@example.com")
.set("x-paperclip-cloud-stack-id", "stack-alpha")
.set("x-paperclip-cloud-stack-role", "owner");
expect(cloud.body).toMatchObject({ source: "cloud_tenant", isInstanceAdmin: false });
expect(state.staleInstanceAdminRow).toBe(false);
// The same user no longer gets instance admin via the session path.
const after = await request(app).get("/actor");
expect(after.body).toMatchObject({
source: "session",
userId: "global-user-1",
isInstanceAdmin: false,
});
});
});
describe("Cloud tenant company naming", () => {
const ids = {
companyId: "11111111-1111-4111-8111-111111111111",
paperclipCompanyId: "paperclip-stack-purple-rain",
};
it.each([
"paperclip-stack-purple-rain",
"stack-purple-rain Paperclip",
ids.companyId,
])("repairs the known-bad machine name %s", (name) => {
expect(isKnownBadCloudCompanyName(name, ids)).toBe(true);
});
it.each([
"Purple Rain",
"Paperclip Stack Purple Rain",
"The Purple Rain Paperclip",
])("preserves the genuine company name %s", (name) => {
expect(isKnownBadCloudCompanyName(name, ids)).toBe(false);
});
it("humanizes the stack slug for old harnesses without a name header", () => {
expect(humanizeCloudStackSlug("stack-purple-rain")).toBe("Purple Rain");
expect(humanizeCloudStackSlug("paperclip-stack-purple-rain")).toBe(
"Purple Rain",
);
});
});