Files
PaperClipAI/server/src/__tests__/live-events-ws.test.ts
T
Devin Foley 2c53437fc9 fix(server): authenticate cloud-proxied browsers on the live-events websocket (#11290)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - The UI receives live run/issue events over a websocket at
`/api/companies/:id/events/ws`; the server authorizes upgrades with a
bearer token or a Better Auth session
> - On a cloud-managed deployment, browsers authenticate through trusted
`x-paperclip-cloud-*` headers injected by the managing front door — they
never hold a local Better Auth session, and the Express middleware lane
that understands those headers is not consulted for websocket upgrades
> - Every browser websocket upgrade behind the front door therefore
resolves no identity and is rejected 403: the live-events socket has
never connected on a managed instance, leaving permanent reconnect churn
and console failure noise while the UI silently degrades to polling
> - This pull request adds a cloud-actor lane to the upgrade
authorization, reusing the same trusted-header resolver the HTTP
middleware uses
> - The benefit is working realtime updates on managed instances, an end
to the reconnect churn, and unchanged self-hosted behavior

## Linked Issues or Issue Description

No existing issue. Description follows the bug template:

**What happened?**

On a cloud-managed instance, the browser console shows `WebSocket
connection to 'wss://…/api/companies/<id>/events/ws' failed:` repeating
indefinitely for every company, on a healthy instance. The server
rejects each upgrade with 403 because `authorizeUpgrade` in
`server/src/realtime/live-events-ws.ts` only knows bearer tokens and
Better Auth sessions, while cloud-proxied browsers authenticate via
`x-paperclip-cloud-*` trusted headers (handled only by the Express
`actorMiddleware` lane in `server/src/middleware/auth.ts`).

**Expected behavior**

A browser that authenticates through the trusted cloud headers can open
the live-events websocket for any company in its membership scope,
exactly as it can call the HTTP API for those companies.

**Steps to reproduce**

1. Run Paperclip in `authenticated` mode behind a proxy that injects the
`x-paperclip-cloud-*` headers with a valid
`PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN`.
2. Load any company page in a browser (no local Better Auth session).
3. HTTP API calls succeed; every `/events/ws` upgrade is rejected 403
and the UI retries forever.

## What Changed

- `server/src/middleware/auth.ts`: `resolveCloudTenantActor` now accepts
a minimal `CloudActorHeaderSource` (`header(name)`) instead of an
Express `Request` — `Request` satisfies it unchanged — plus
`cloudActorHeaderSourceFromHeaders` to adapt raw
`IncomingMessage.headers`.
- `server/src/realtime/live-events-ws.ts`: `authorizeUpgrade` gains an
injected `resolveCloudActor` lane, tried before the Better Auth session
fallback in `authenticated` mode. A resolved cloud actor is
authoritative: the upgrade is authorized only for a company in the
actor's membership scope (`companyIds`, the same scope the HTTP lane
grants). Absent/unresolvable cloud headers fall through to the session
path.
- `server/src/index.ts`: wires `resolveCloudActor` through
`resolveCloudTenantActor` + the header shim. The resolver self-gates:
without `PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN` and a matching trust token
it returns null, so self-hosted deployments never take this path.
- Tests: upgrade authorized for an in-scope company (session resolver
not consulted), rejected for an out-of-scope company, fall-through to
session auth when no cloud actor resolves; header-shim resolution from a
raw lowercased header map including `string[]` values.

## Verification

- `pnpm vitest run server/src/__tests__/live-events-ws.test.ts
server/src/middleware/cloud-tenant-actor.test.ts` — 25 tests pass.
- `pnpm typecheck` in `server/` — clean.
- Not verified live end-to-end: that requires a managed instance running
this build; the direct probe evidence (HTTP authenticated fine, every WS
upgrade 403) matches the code path exactly.

## Risks

Low risk. The new lane only activates when the deployment configures the
cloud trust token and the request presents it; both checks already
protect the HTTP lane. Authorization scope is the same `companyIds` set
the HTTP middleware computes (primary stack company plus the user's real
membership rows). The cloud resolver's user/company materialization
writes are debounced (existing behavior shared with the HTTP lane), so
websocket reconnect storms do not amplify database writes. Self-hosted
instances see no behavioral change, covered by the fall-through test.

## Model Used

- Claude (Anthropic), Claude Fable 5 (`claude-fable-5`), via Claude Code
CLI with extended thinking and tool use (code search, edit, test
execution; diagnosis included live websocket handshake probes against a
managed instance).

## 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
2026-08-12 11:22:50 -07:00

184 lines
6.2 KiB
TypeScript

import { EventEmitter } from "node:events";
import type { IncomingMessage } from "node:http";
import type { Duplex } from "node:stream";
import { beforeEach, describe, expect, it, vi } from "vitest";
import { setupLiveEventsWebSocketServer } from "../realtime/live-events-ws.js";
import { logger } from "../middleware/logger.js";
vi.mock("../middleware/logger.js", () => ({
logger: {
warn: vi.fn(),
error: vi.fn(),
},
}));
class FakeUpgradeSocket extends EventEmitter {
destroyed = false;
writable = true;
writableEnded = false;
writableDestroyed = false;
endedChunks: string[] = [];
destroyCalls = 0;
end(chunk?: string) {
if (chunk) this.endedChunks.push(chunk);
this.writableEnded = true;
this.writable = false;
setImmediate(() => {
if (this.destroyed) return;
this.emit("finish");
if (!this.destroyed) {
this.emit("close");
}
});
return this;
}
destroy() {
this.destroyCalls += 1;
this.destroyed = true;
this.writable = false;
this.writableDestroyed = true;
this.emit("close");
return this;
}
emitSocketError(err: Error) {
this.writable = false;
this.writableDestroyed = true;
this.emit("error", err);
}
}
function createUpgradeRequest(overrides: Partial<IncomingMessage> = {}) {
return {
url: "/api/companies/company-1/events/ws",
headers: {},
...overrides,
} as IncomingMessage;
}
async function flushPromises() {
await new Promise<void>((resolve) => setImmediate(resolve));
}
describe("setupLiveEventsWebSocketServer", () => {
beforeEach(() => {
vi.clearAllMocks();
});
it("does not write a rejection response after the raw upgrade socket is already closed", async () => {
const server = new EventEmitter();
setupLiveEventsWebSocketServer(server as never, {} as never, { deploymentMode: "authenticated" });
const socket = new FakeUpgradeSocket();
server.emit("upgrade", createUpgradeRequest(), socket as unknown as Duplex, Buffer.alloc(0));
socket.destroy();
await flushPromises();
expect(socket.endedChunks).toEqual([]);
expect(socket.destroyCalls).toBe(1);
});
it("handles raw upgrade socket errors during async authorization", async () => {
const server = new EventEmitter();
let resolveSession: (value: null) => void = () => undefined;
setupLiveEventsWebSocketServer(server as never, {} as never, {
deploymentMode: "authenticated",
resolveSessionFromHeaders: () =>
new Promise((resolve) => {
resolveSession = resolve;
}),
});
const socket = new FakeUpgradeSocket();
server.emit("upgrade", createUpgradeRequest(), socket as unknown as Duplex, Buffer.alloc(0));
expect(() => socket.emitSocketError(new Error("write EPIPE"))).not.toThrow();
resolveSession(null);
await flushPromises();
expect(logger.warn).toHaveBeenCalledWith(
expect.objectContaining({ err: expect.any(Error), path: "/api/companies/company-1/events/ws" }),
"live websocket upgrade socket error",
);
expect(socket.endedChunks).toEqual([]);
expect(socket.destroyed).toBe(true);
});
it("destroys and cleans up listeners after flushing a rejection response", async () => {
const server = new EventEmitter();
setupLiveEventsWebSocketServer(server as never, {} as never, { deploymentMode: "authenticated" });
const socket = new FakeUpgradeSocket();
server.emit("upgrade", createUpgradeRequest(), socket as unknown as Duplex, Buffer.alloc(0));
await flushPromises();
await flushPromises();
expect(socket.endedChunks[0]).toContain("403 Forbidden");
expect(socket.destroyed).toBe(true);
expect(socket.listenerCount("error")).toBe(0);
expect(socket.listenerCount("close")).toBe(0);
expect(socket.listenerCount("finish")).toBe(0);
});
it("authorizes a cloud-proxied browser for a company in its membership scope", async () => {
const server = new EventEmitter();
const resolveSessionFromHeaders = vi.fn(async () => null);
const socket = new FakeUpgradeSocket();
setupLiveEventsWebSocketServer(server as never, {} as never, {
deploymentMode: "authenticated",
resolveSessionFromHeaders,
resolveCloudActor: async () => {
// Stop before the ws handshake writes to the fake socket; the
// assertion is that authorization passed without any rejection.
socket.writable = false;
return { userId: "cloud-user-1", companyIds: ["company-1", "company-2"] };
},
});
server.emit("upgrade", createUpgradeRequest(), socket as unknown as Duplex, Buffer.alloc(0));
await flushPromises();
await flushPromises();
expect(socket.endedChunks).toEqual([]);
expect(resolveSessionFromHeaders).not.toHaveBeenCalled();
});
it("rejects a cloud actor for a company outside its membership scope", async () => {
const server = new EventEmitter();
const resolveSessionFromHeaders = vi.fn(async () => null);
setupLiveEventsWebSocketServer(server as never, {} as never, {
deploymentMode: "authenticated",
resolveSessionFromHeaders,
resolveCloudActor: async () => ({ userId: "cloud-user-1", companyIds: ["company-other"] }),
});
const socket = new FakeUpgradeSocket();
server.emit("upgrade", createUpgradeRequest(), socket as unknown as Duplex, Buffer.alloc(0));
await flushPromises();
await flushPromises();
expect(socket.endedChunks[0]).toContain("403 Forbidden");
// A resolved cloud actor is authoritative; the session path must not run.
expect(resolveSessionFromHeaders).not.toHaveBeenCalled();
});
it("falls through to session auth when no cloud actor resolves", async () => {
const server = new EventEmitter();
const resolveSessionFromHeaders = vi.fn(async () => null);
setupLiveEventsWebSocketServer(server as never, {} as never, {
deploymentMode: "authenticated",
resolveSessionFromHeaders,
resolveCloudActor: async () => null,
});
const socket = new FakeUpgradeSocket();
server.emit("upgrade", createUpgradeRequest(), socket as unknown as Duplex, Buffer.alloc(0));
await flushPromises();
await flushPromises();
expect(resolveSessionFromHeaders).toHaveBeenCalledTimes(1);
expect(socket.endedChunks[0]).toContain("403 Forbidden");
});
});