mirror of
https://github.com/paperclipai/paperclip.git
synced 2026-11-27 03:07:57 +01:00
## Thinking Path
> - Paperclip is the open source app people use to manage AI agents for
work
> - A hosted stack reads its tenant portfolio from Paperclip Cloud
through `GET /api/cloud/stacks`
> - Paperclip Cloud can answer that read with 429 when it throttles a
stack
> - The proxy changed every non-OK upstream status into a 502, and the
error handler reports every 5xx to Sentry
> - So Cloud backpressure showed up as a server crash on a staging stack
(`upstreamStatus=429`, `phase=http_response`)
> - This pull request passes an upstream 429 through as a 429 with a
bounded `Retry-After` hint
> - The benefit is a correct status for clients and no false crash
reports for throttling
## Linked Issues or Issue Description
Refs #15340 (bounded Cloud portfolio diagnostics), Refs #19033 (retry
one Cloud portfolio connection reset).
**What happened?**
A hosted staging stack reported "Paperclip Cloud portfolio request
failed" to Sentry. The diagnostics show `upstreamStatus=429` after 44
ms. Cloud throttled the read, and the proxy answered 502 and reported a
crash.
**What did you expect to happen?**
The proxy tells the client that Cloud is rate limiting the read. It does
not report a server fault.
**Steps to reproduce**
Make the Cloud tenant portfolio endpoint answer 429, then call `GET
/api/cloud/stacks`. Before this change the route answers 502
`cloud_portfolio_upstream_error` and reports to Sentry.
## What Changed
- `server/src/routes/cloud.ts`: an upstream 429 now gives 429
`cloud_portfolio_rate_limited`.
- The route copies Cloud's `Retry-After` as whole seconds. It accepts
delta seconds or an HTTP-date and clamps the value to 1–300 seconds. It
omits the header when the value is missing or malformed.
- The route logs the bounded diagnostics at warn level. It does not
report the 429 to Sentry and does not cache the throttled answer.
- 401, 403, 503 and the other failure phases keep the 502 contract and
the crash report.
- `server/src/__tests__/cloud-routes.test.ts`: new cases for the 429
status, the `Retry-After` forms, no Sentry report, and no cache entry.
- `docs/api/cloud.md` (new, in the API Reference nav): documents `GET
/api/cloud/stacks`, its error codes, and the 429 with its bounded
`Retry-After`.
- `server/src/routes/openapi.ts`: the `/api/cloud/stacks` entry now
lists the 429 response.
## Verification
- Red: with the old `cloud.ts`, `cloud-routes.test.ts` gave 5 failed
(the new 429 cases) and 23 passed.
- Green: `cd server && npx vitest run src/__tests__/cloud-routes.test.ts
src/__tests__/sentry.test.ts src/__tests__/cloud-portfolio-error.test.ts
src/__tests__/run-failure-sentry-real-sdk.test.ts` gave 68 passed and 18
skipped.
- `npx tsc --noEmit -p server/tsconfig.json` shows no errors in the
changed files.
- After review fixes (6a8f146c55): `cd server && npx vitest run
src/__tests__/cloud-routes.test.ts src/__tests__/openapi-routes.test.ts`
gave 80 passed.
## Risks
- Low risk. Only the 429 path changes.
- The two UI consumers (`useCloudInviteUrl`, `CompanyAccess`) treat any
error the same way, so the UI needs no change.
## Model Used
- Anthropic Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with
tool use and code 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
- [ ] 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: Paperclip <noreply@paperclip.ing>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: paperclipbugbot <356415228+paperclipbugbot@users.noreply.github.com>
370 lines
18 KiB
TypeScript
370 lines
18 KiB
TypeScript
import { createServer } from "node:http";
|
|
import type { AddressInfo, Socket } from "node:net";
|
|
import express from "express";
|
|
import request from "supertest";
|
|
import { afterEach, describe, expect, it, vi } from "vitest";
|
|
import { errorHandler } from "../middleware/index.js";
|
|
import { cloudRoutes } from "../routes/cloud.js";
|
|
import { CloudPortfolioError } from "../services/cloud-portfolio-error.js";
|
|
import * as sentry from "../sentry.js";
|
|
import { logger } from "../middleware/logger.js";
|
|
|
|
afterEach(() => vi.restoreAllMocks());
|
|
|
|
const cloudEnv = {
|
|
PAPERCLIP_CLOUD_TENANT_SERVER_TOKEN: "tenant-secret",
|
|
PAPERCLIP_CLOUD_STACK_ID: "stack-current",
|
|
PAPERCLIP_CLOUD_API_ORIGIN: "https://cloud.example.test/control-plane",
|
|
};
|
|
|
|
function cloudActor(userId: string) {
|
|
return {
|
|
type: "board" as const,
|
|
source: "cloud_tenant" as const,
|
|
userId,
|
|
companyIds: ["company-1"],
|
|
};
|
|
}
|
|
|
|
function createApp(options: {
|
|
actor?: ReturnType<typeof cloudActor> | {
|
|
type: "board";
|
|
source: "session";
|
|
userId: string;
|
|
};
|
|
runtimeEnv?: Record<string, string | undefined>;
|
|
fetchImpl: typeof fetch;
|
|
now?: () => number;
|
|
}) {
|
|
const app = express();
|
|
app.use((req, _res, next) => {
|
|
(req as any).actor = options.actor ?? cloudActor("actor-user");
|
|
next();
|
|
});
|
|
app.use("/api/cloud", cloudRoutes({
|
|
runtimeEnv: options.runtimeEnv ?? cloudEnv,
|
|
fetchImpl: options.fetchImpl,
|
|
now: options.now,
|
|
}));
|
|
app.use(errorHandler);
|
|
return app;
|
|
}
|
|
|
|
function fetchReset(code: string) {
|
|
return new TypeError("private fetch message", { cause: Object.assign(new Error("private cause"), { code }) });
|
|
}
|
|
|
|
function jsonResponse(payload: unknown, status = 200) {
|
|
return new Response(JSON.stringify(payload), {
|
|
status,
|
|
headers: { "content-type": "application/json" },
|
|
});
|
|
}
|
|
|
|
describe("GET /api/cloud/stacks", () => {
|
|
it.each([
|
|
["delta seconds", "7", "7"],
|
|
["an HTTP date", new Date(Date.UTC(2026, 10, 10, 14, 25, 0)).toUTCString(), "34"],
|
|
["an excessive delay", "86400", "300"],
|
|
["a malformed hint", "soon", undefined],
|
|
["no hint", null, undefined],
|
|
])("passes an upstream 429 with %s through as a rate limit without reporting it", async (_case, hint, retryAfter) => {
|
|
const upstream = jsonResponse({ secret: "private upstream payload" }, 429);
|
|
if (hint !== null) upstream.headers.set("retry-after", hint);
|
|
const json = vi.spyOn(upstream, "json");
|
|
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(upstream);
|
|
const capture = vi.spyOn(sentry, "captureException").mockImplementation(() => {});
|
|
const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
|
|
const app = createApp({ fetchImpl, now: () => Date.UTC(2026, 10, 10, 14, 24, 26, 209) });
|
|
const response = await request(app).get("/api/cloud/stacks");
|
|
expect(response.status).toBe(429);
|
|
expect(response.body).toEqual({ error: "Paperclip Cloud portfolio is rate limited", code: "cloud_portfolio_rate_limited", details: { code: "cloud_portfolio_rate_limited" } });
|
|
expect(response.headers["retry-after"]).toBe(retryAfter);
|
|
expect(json).not.toHaveBeenCalled();
|
|
expect(capture).not.toHaveBeenCalled();
|
|
expect(warn).toHaveBeenCalledWith(
|
|
{ cloudPortfolio: expect.objectContaining({ phase: "http_response", upstreamStatus: 429, networkCode: "unknown" }) },
|
|
"Paperclip Cloud portfolio request rate limited",
|
|
);
|
|
expect(JSON.stringify(warn.mock.calls)).not.toContain("private");
|
|
fetchImpl.mockResolvedValueOnce(jsonResponse({ stacks: [] }));
|
|
expect((await request(app).get("/api/cloud/stacks")).body).toEqual({ stacks: [] });
|
|
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it.each([401, 403, 503])("preserves the response contract for upstream HTTP %s without reading the body", async (status) => {
|
|
const upstream = jsonResponse({ secret: "private upstream payload" }, status);
|
|
const json = vi.spyOn(upstream, "json");
|
|
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(upstream);
|
|
const capture = vi.spyOn(sentry, "captureException").mockImplementation(() => {});
|
|
const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
|
|
const response = await request(createApp({ fetchImpl })).get("/api/cloud/stacks").set("Cookie", "client-session=private-cookie");
|
|
expect(response.status).toBe(502);
|
|
expect(response.body).toEqual({ error: "Paperclip Cloud portfolio request failed", code: "cloud_portfolio_upstream_error", details: { code: "cloud_portfolio_upstream_error" } });
|
|
expect(response.headers["set-cookie"]).toBeUndefined();
|
|
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
|
expect(new Headers(fetchImpl.mock.calls[0]![1]!.headers).has("cookie")).toBe(false);
|
|
expect(json).not.toHaveBeenCalled();
|
|
expect(capture).toHaveBeenCalledWith(expect.any(CloudPortfolioError));
|
|
const error = capture.mock.calls[0]![0] as CloudPortfolioError;
|
|
expect(error.diagnostics).toMatchObject({ phase: "http_response", upstreamStatus: status, networkCode: "unknown", elapsedMs: expect.any(Number) });
|
|
expect(error.stack).toContain("routes/cloud.ts:");
|
|
expect(error.stack).not.toContain("at portfolioError");
|
|
expect(warn).toHaveBeenCalledWith({ cloudPortfolio: error.diagnostics }, "Paperclip Cloud portfolio request failed");
|
|
expect(JSON.stringify(warn.mock.calls)).not.toContain("private");
|
|
});
|
|
|
|
it.each(["ECONNRESET", "UND_ERR_SOCKET"])("retries one pre-response %s within the same deadline", async (code) => {
|
|
const fetchImpl = vi.fn<typeof fetch>()
|
|
.mockRejectedValueOnce(fetchReset(code))
|
|
.mockResolvedValueOnce(jsonResponse({ stacks: [] }));
|
|
const capture = vi.spyOn(sentry, "captureException").mockImplementation(() => {});
|
|
const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
|
|
const timeout = vi.spyOn(AbortSignal, "timeout");
|
|
const response = await request(createApp({ fetchImpl })).get("/api/cloud/stacks");
|
|
expect(response.status).toBe(200);
|
|
expect(response.body).toEqual({ stacks: [] });
|
|
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
|
expect(timeout).toHaveBeenCalledTimes(1);
|
|
expect(fetchImpl.mock.calls[1]![1]?.signal).toBe(fetchImpl.mock.calls[0]![1]?.signal);
|
|
expect(fetchImpl.mock.calls[1]![1]?.headers).toEqual(fetchImpl.mock.calls[0]![1]?.headers);
|
|
expect(capture).not.toHaveBeenCalled();
|
|
expect(warn).toHaveBeenCalledWith(
|
|
{ cloudPortfolio: expect.objectContaining({ phase: "fetch", upstreamStatus: null, networkCode: code }) },
|
|
"Paperclip Cloud portfolio connection reset; retrying once",
|
|
);
|
|
expect(JSON.stringify(warn.mock.calls)).not.toContain("private");
|
|
});
|
|
|
|
it("reports a second consecutive fetch reset without caching the failure", async () => {
|
|
const fetchImpl = vi.fn<typeof fetch>()
|
|
.mockRejectedValueOnce(fetchReset("ECONNRESET"))
|
|
.mockRejectedValueOnce(fetchReset("ECONNRESET"))
|
|
.mockResolvedValueOnce(jsonResponse({ stacks: [] }));
|
|
const capture = vi.spyOn(sentry, "captureException").mockImplementation(() => {});
|
|
const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
|
|
const app = createApp({ fetchImpl });
|
|
const failure = await request(app).get("/api/cloud/stacks");
|
|
expect(failure.status).toBe(502);
|
|
expect(failure.body).toEqual({ error: "Paperclip Cloud portfolio request failed", code: "cloud_portfolio_upstream_error", details: { code: "cloud_portfolio_upstream_error" } });
|
|
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
|
expect(capture).toHaveBeenCalledTimes(1);
|
|
const error = capture.mock.calls[0]![0] as CloudPortfolioError;
|
|
expect(error.diagnostics).toMatchObject({ phase: "fetch", upstreamStatus: null, networkCode: "ECONNRESET" });
|
|
expect(error.stack).toContain("routes/cloud.ts:");
|
|
expect(warn).toHaveBeenLastCalledWith({ cloudPortfolio: error.diagnostics }, "Paperclip Cloud portfolio request failed");
|
|
expect(JSON.stringify(warn.mock.calls)).not.toContain("private");
|
|
expect((await request(app).get("/api/cloud/stacks")).body).toEqual({ stacks: [] });
|
|
expect(fetchImpl).toHaveBeenCalledTimes(3);
|
|
});
|
|
|
|
it.each(["ECONNREFUSED", "ENOTFOUND", "UND_ERR_CONNECT_TIMEOUT", "unclassified"])("does not retry a %s fetch failure", async (code) => {
|
|
const fetchImpl = vi.fn<typeof fetch>().mockRejectedValue(fetchReset(code));
|
|
const capture = vi.spyOn(sentry, "captureException").mockImplementation(() => {});
|
|
vi.spyOn(logger, "warn").mockImplementation(() => {});
|
|
const response = await request(createApp({ fetchImpl })).get("/api/cloud/stacks");
|
|
expect(response.status).toBe(502);
|
|
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
|
expect((capture.mock.calls[0]![0] as CloudPortfolioError).diagnostics).toMatchObject({
|
|
phase: "fetch", networkCode: code === "unclassified" ? "unknown" : code,
|
|
});
|
|
});
|
|
|
|
it("does not retry a reset that arrives after the deadline", async () => {
|
|
const signal = AbortSignal.abort(new DOMException("private timeout", "TimeoutError"));
|
|
vi.spyOn(AbortSignal, "timeout").mockReturnValue(signal);
|
|
const fetchImpl = vi.fn<typeof fetch>().mockRejectedValue(fetchReset("ECONNRESET"));
|
|
const capture = vi.spyOn(sentry, "captureException").mockImplementation(() => {});
|
|
vi.spyOn(logger, "warn").mockImplementation(() => {});
|
|
const response = await request(createApp({ fetchImpl })).get("/api/cloud/stacks");
|
|
expect(response.status).toBe(502);
|
|
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
|
expect((capture.mock.calls[0]![0] as CloudPortfolioError).diagnostics).toMatchObject({ phase: "fetch", networkCode: "DEADLINE_EXCEEDED" });
|
|
});
|
|
|
|
it.each([
|
|
["ECONNRESET", (socket: Socket) => socket.resetAndDestroy()],
|
|
["UND_ERR_SOCKET", (socket: Socket) => socket.destroy()],
|
|
] as const)("recovers from a real %s on the native fetch path", async (code, closeSocket) => {
|
|
let requests = 0;
|
|
const server = createServer((req, res) => {
|
|
requests++;
|
|
if (requests === 1) {
|
|
closeSocket(req.socket);
|
|
return;
|
|
}
|
|
res.setHeader("content-type", "application/json");
|
|
res.end(JSON.stringify({ stacks: [{ slug: "current" }], authorization: req.headers.authorization }));
|
|
});
|
|
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
try {
|
|
const { port } = server.address() as AddressInfo;
|
|
const capture = vi.spyOn(sentry, "captureException").mockImplementation(() => {});
|
|
const warn = vi.spyOn(logger, "warn").mockImplementation(() => {});
|
|
const app = createApp({
|
|
fetchImpl: fetch,
|
|
runtimeEnv: { ...cloudEnv, PAPERCLIP_CLOUD_API_ORIGIN: `http://127.0.0.1:${port}` },
|
|
});
|
|
const response = await request(app).get("/api/cloud/stacks");
|
|
expect(response.status).toBe(200);
|
|
expect(response.body).toEqual({ stacks: [{ slug: "current" }], authorization: "Bearer tenant-secret" });
|
|
expect(requests).toBe(2);
|
|
expect(capture).not.toHaveBeenCalled();
|
|
expect(warn).toHaveBeenCalledWith(
|
|
{ cloudPortfolio: expect.objectContaining({ phase: "fetch", networkCode: code }) },
|
|
"Paperclip Cloud portfolio connection reset; retrying once",
|
|
);
|
|
} finally {
|
|
server.closeAllConnections();
|
|
await new Promise((resolve) => server.close(resolve));
|
|
}
|
|
});
|
|
|
|
it.each(["invalid_json", "body_reset", "deadline"] as const)("keeps body-phase %s failures separate from fetch failures", async (kind) => {
|
|
const capture = vi.spyOn(sentry, "captureException").mockImplementation(() => {});
|
|
const controller = new AbortController();
|
|
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(controller.signal);
|
|
const upstream = jsonResponse({});
|
|
vi.spyOn(upstream, "json").mockImplementation(async () => {
|
|
if (kind === "deadline") controller.abort(new DOMException("private timeout", "TimeoutError"));
|
|
throw kind === "body_reset" ? Object.assign(new Error("private body"), { code: "ECONNRESET" }) : new SyntaxError("private body");
|
|
});
|
|
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(upstream);
|
|
const app = createApp({ fetchImpl });
|
|
for (let count = 1; count <= 2; count++) {
|
|
const response = await request(app).get("/api/cloud/stacks");
|
|
expect(response.status).toBe(502);
|
|
expect(response.body).toEqual({ error: "Paperclip Cloud portfolio returned invalid JSON", code: "cloud_portfolio_invalid_response", details: { code: "cloud_portfolio_invalid_response" } });
|
|
expect(fetchImpl).toHaveBeenCalledTimes(count);
|
|
}
|
|
expect(timeout).toHaveBeenCalledWith(10_000);
|
|
expect((capture.mock.calls[0]![0] as CloudPortfolioError).diagnostics).toMatchObject({
|
|
phase: "response_body", upstreamStatus: 200,
|
|
networkCode: kind === "deadline" ? "DEADLINE_EXCEEDED" : kind === "body_reset" ? "ECONNRESET" : "unknown",
|
|
});
|
|
});
|
|
|
|
it("records the owned fetch deadline without changing the ten-second signal", async () => {
|
|
const signal = AbortSignal.abort(new DOMException("private timeout", "TimeoutError"));
|
|
const timeout = vi.spyOn(AbortSignal, "timeout").mockReturnValue(signal);
|
|
const fetchImpl = vi.fn<typeof fetch>().mockRejectedValue(signal.reason);
|
|
const capture = vi.spyOn(sentry, "captureException").mockImplementation(() => {});
|
|
const response = await request(createApp({ fetchImpl })).get("/api/cloud/stacks");
|
|
expect(response.body).toEqual({ error: "Paperclip Cloud portfolio request failed", code: "cloud_portfolio_upstream_error", details: { code: "cloud_portfolio_upstream_error" } });
|
|
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
|
expect(fetchImpl.mock.calls[0]![1]?.signal).toBe(signal);
|
|
expect(timeout).toHaveBeenCalledWith(10_000);
|
|
expect((capture.mock.calls[0]![0] as CloudPortfolioError).diagnostics).toMatchObject({ phase: "fetch", networkCode: "DEADLINE_EXCEEDED" });
|
|
});
|
|
|
|
it("does not mislabel a response serialization failure as an upstream fetch error", async () => {
|
|
const payload: { cycle?: unknown } = {};
|
|
payload.cycle = payload;
|
|
const upstream = jsonResponse({});
|
|
vi.spyOn(upstream, "json").mockResolvedValue(payload);
|
|
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(upstream);
|
|
const capture = vi.spyOn(sentry, "captureException").mockImplementation(() => {});
|
|
const response = await request(createApp({ fetchImpl })).get("/api/cloud/stacks");
|
|
expect(response.status).toBe(502);
|
|
expect(response.body).toEqual({ error: "Paperclip Cloud portfolio request failed", code: "cloud_portfolio_upstream_error", details: { code: "cloud_portfolio_upstream_error" } });
|
|
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
|
expect((capture.mock.calls[0]![0] as CloudPortfolioError).diagnostics).toMatchObject({ phase: "response_write", upstreamStatus: 200, networkCode: "unknown" });
|
|
});
|
|
|
|
it("returns the actor's portfolio without forwarding client-supplied identity", async () => {
|
|
const portfolio = { stacks: [{ slug: "current", displayName: "Current" }] };
|
|
const fetchImpl = vi.fn<typeof fetch>().mockResolvedValue(jsonResponse(portfolio));
|
|
const app = createApp({ fetchImpl });
|
|
|
|
const res = await request(app)
|
|
.get("/api/cloud/stacks?userId=client-supplied-user")
|
|
.set("x-paperclip-cloud-user-id", "spoofed-header-user")
|
|
.set("authorization", "Bearer client-token");
|
|
|
|
expect(res.status).toBe(200);
|
|
expect(res.body).toEqual(portfolio);
|
|
expect(res.headers["cache-control"]).toBe("no-store");
|
|
expect(fetchImpl).toHaveBeenCalledTimes(1);
|
|
|
|
const [url, init] = fetchImpl.mock.calls[0]!;
|
|
expect(url.toString()).toBe("https://cloud.example.test/v1/tenant/portfolio");
|
|
expect(init).toMatchObject({ method: "GET" });
|
|
expect(init?.headers).toEqual({
|
|
accept: "application/json",
|
|
authorization: "Bearer tenant-secret",
|
|
"x-paperclip-cloud-user-id": "actor-user",
|
|
"x-paperclip-cloud-stack-id": "stack-current",
|
|
});
|
|
expect(JSON.stringify(init)).not.toContain("client-supplied-user");
|
|
expect(JSON.stringify(init)).not.toContain("spoofed-header-user");
|
|
expect(JSON.stringify(init)).not.toContain("client-token");
|
|
});
|
|
|
|
it("caches successful portfolios per actor for 30 seconds", async () => {
|
|
let currentTime = 1_000;
|
|
const fetchImpl = vi.fn<typeof fetch>()
|
|
.mockResolvedValueOnce(jsonResponse({ generation: 1 }))
|
|
.mockResolvedValueOnce(jsonResponse({ generation: 2 }));
|
|
const app = createApp({ fetchImpl, now: () => currentTime });
|
|
|
|
const first = await request(app).get("/api/cloud/stacks");
|
|
currentTime += 29_999;
|
|
const cached = await request(app).get("/api/cloud/stacks");
|
|
currentTime += 1;
|
|
const refreshed = await request(app).get("/api/cloud/stacks");
|
|
|
|
expect(first.body).toEqual({ generation: 1 });
|
|
expect(cached.body).toEqual({ generation: 1 });
|
|
expect(refreshed.body).toEqual({ generation: 2 });
|
|
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it("keeps cache entries isolated by the server-derived actor user id", async () => {
|
|
const fetchImpl = vi.fn<typeof fetch>().mockImplementation(async (_url, init) => {
|
|
const headers = new Headers(init?.headers);
|
|
return jsonResponse({ userId: headers.get("x-paperclip-cloud-user-id") });
|
|
});
|
|
const app = express();
|
|
app.use((req, _res, next) => {
|
|
const userId = req.header("x-test-actor-user") ?? "user-a";
|
|
(req as any).actor = cloudActor(userId);
|
|
next();
|
|
});
|
|
app.use("/api/cloud", cloudRoutes({ runtimeEnv: cloudEnv, fetchImpl }));
|
|
app.use(errorHandler);
|
|
|
|
const first = await request(app).get("/api/cloud/stacks").set("x-test-actor-user", "user-a");
|
|
const second = await request(app).get("/api/cloud/stacks").set("x-test-actor-user", "user-b");
|
|
const firstAgain = await request(app).get("/api/cloud/stacks").set("x-test-actor-user", "user-a");
|
|
|
|
expect(first.body).toEqual({ userId: "user-a" });
|
|
expect(second.body).toEqual({ userId: "user-b" });
|
|
expect(firstAgain.body).toEqual({ userId: "user-a" });
|
|
expect(fetchImpl).toHaveBeenCalledTimes(2);
|
|
});
|
|
|
|
it("returns 404 on self-hosted instances without calling upstream", async () => {
|
|
const fetchImpl = vi.fn<typeof fetch>();
|
|
const app = createApp({ runtimeEnv: {}, fetchImpl });
|
|
|
|
const res = await request(app).get("/api/cloud/stacks");
|
|
|
|
expect(res.status).toBe(404);
|
|
expect(fetchImpl).not.toHaveBeenCalled();
|
|
});
|
|
|
|
it("rejects non-tenant actors on managed instances without calling upstream", async () => {
|
|
const fetchImpl = vi.fn<typeof fetch>();
|
|
const app = createApp({
|
|
actor: { type: "board", source: "session", userId: "session-user" },
|
|
fetchImpl,
|
|
});
|
|
|
|
const res = await request(app).get("/api/cloud/stacks");
|
|
|
|
expect(res.status).toBe(403);
|
|
expect(res.body.code).toBe("cloud_tenant_required");
|
|
expect(fetchImpl).not.toHaveBeenCalled();
|
|
});
|
|
});
|