diff --git a/server/src/__tests__/customer-success.test.ts b/server/src/__tests__/customer-success.test.ts index 30afb1d3103..19b48f979b2 100644 --- a/server/src/__tests__/customer-success.test.ts +++ b/server/src/__tests__/customer-success.test.ts @@ -22,7 +22,11 @@ import { readCustomerSuccessResource, inspectionReaders, } from "../services/customer-success-inspection.js"; -import { customerSuccessRoutes, verifyInspectionPermit } from "../routes/customer-success.js"; +import { + customerSuccessRoutes, + fitInspectionResponse, + verifyInspectionPermit, +} from "../routes/customer-success.js"; import { agentIdentityService } from "../services/agent-identity.js"; import { createLocalAgentJwt, verifyLocalAgentJwt } from "../agent-auth-jwt.js"; import { errorHandler } from "../middleware/error-handler.js"; @@ -460,6 +464,106 @@ describe("customer-success read authority", () => { ), ).toThrow(); }); + it("fits an oversized list page to the response limit and points nextOffset at the first omitted row", async () => { + vi.stubEnv("PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_ENABLED", "true"); + vi.stubEnv("PAPERCLIP_CLOUD_STACK_ID", "fixture-stack"); + vi.stubEnv("PAPERCLIP_CUSTOMER_SUCCESS_CLOUD_ORIGIN", "https://cloud.example.test"); + const keys = generateKeyPairSync("ed25519"); + vi.stubEnv( + "PAPERCLIP_CUSTOMER_SUCCESS_INSPECTION_JWKS", + JSON.stringify({ keys: [{ ...keys.publicKey.export({ format: "jwk" }), kid: "cloud" }] }), + ); + const [bulky] = await db + .insert(schema.companies) + .values({ name: "Bulky", issuePrefix: "BLK" }) + .returning(); + await db.insert(schema.issues).values( + Array.from({ length: 40 }, (_, index) => ({ + companyId: bulky.id, + title: `Large task ${index}`, + description: "x".repeat(200 * 1024), + })), + ); + function permitFor(query: InspectionQuery) { + const now = Math.floor(Date.now() / 1000); + const claims: InspectionPermit = { + v: 1, + iss: "paperclip-cloud", + aud: INSPECTION_AUDIENCE, + sub: "fixture-stack", + iat: now, + exp: now + 60, + jti: randomUUID(), + bindingVersion: 1, + grantId: randomUUID(), + requestId: randomUUID(), + agentId, + keyId: "sha256:fixture", + runId, + query, + }; + const header = Buffer.from( + JSON.stringify({ alg: "EdDSA", typ: INSPECTION_PERMIT_TYPE, kid: "cloud" }), + ).toString("base64url"); + const input = `${header}.${Buffer.from(JSON.stringify(claims)).toString("base64url")}`; + return `${input}.${sign(null, Buffer.from(input), keys.privateKey).toString("base64url")}`; + } + vi.stubGlobal("fetch", vi.fn().mockResolvedValue(Response.json({ consumed: true }))); + const app = express(); + app.use(express.json()); + app.use("/api/customer-success/v1", customerSuccessRoutes(db, storage)); + app.use(errorHandler); + async function page(offset: number) { + const query: InspectionQuery = { + operation: "list", + resource: "tasks", + companyId: bulky.id, + limit: 25, + offset, + }; + return request(app) + .post("/api/customer-success/v1/read") + .set(INSPECTION_HEADER, permitFor(query)) + .send(query); + } + const ordered = ( + await db + .select({ id: schema.issues.id }) + .from(schema.issues) + .where(eq(schema.issues.companyId, bulky.id)) + .orderBy(schema.issues.id) + ).map((row) => row.id); + + const first = await page(5); + expect(first.status).toEqual(200); + expect(Buffer.byteLength(first.text)).toBeLessThanOrEqual(2 * 1024 * 1024); + const count = first.body.items.length; + expect(count).toBeGreaterThan(0); + expect(count).toBeLessThan(20); + expect(first.body.nextOffset).toEqual(5 + count); + expect(first.body.items.map((item: { id: string }) => item.id)).toEqual(ordered.slice(5, 5 + count)); + + const second = await page(first.body.nextOffset); + expect(second.status).toEqual(200); + const next = second.body.items.map((item: { id: string }) => item.id); + expect(next).toEqual(ordered.slice(5 + count, 5 + count + next.length)); + vi.unstubAllGlobals(); + }); + + it("returns null only when a single item cannot fit, and fits only list pages", () => { + const files = { kind: "files", truncated: true, items: ["a".repeat(40), "b".repeat(40), "c".repeat(40)] }; + expect(fitInspectionResponse(files, "files.list", 0, 120)).toBeNull(); + const small = { items: [1, 2, 3], nextOffset: null }; + expect(fitInspectionResponse(small, "list", 0, 1024)).toEqual(JSON.stringify(small)); + const big = { items: ["a".repeat(40), "b".repeat(40), "c".repeat(40)], nextOffset: 3 }; + expect(JSON.parse(fitInspectionResponse(big, "list", 10, 120)!)).toEqual({ + items: ["a".repeat(40), "b".repeat(40)], + nextOffset: 12, + }); + expect(fitInspectionResponse({ items: ["a".repeat(200), "b"], nextOffset: null }, "list", 0, 100)).toBeNull(); + expect(fitInspectionResponse({ content: "a".repeat(200) }, "get", 0, 100)).toBeNull(); + }); + it("reads assigned repository URLs, snapshotted skill files, and workspace downloads with existing file restrictions", async () => { const root = await mkdtemp(join(directory, "workspace-")); await writeFile(join(root, "result.bin"), Buffer.alloc(2 * 1024 * 1024, 7)); diff --git a/server/src/routes/customer-success.ts b/server/src/routes/customer-success.ts index 0e2109753f3..94083ffd5db 100644 --- a/server/src/routes/customer-success.ts +++ b/server/src/routes/customer-success.ts @@ -8,6 +8,7 @@ import { INSPECTION_PERMIT_TYPE, INSPECTION_HEADER, type InspectionPermit, + type InspectionQuery, } from "@paperclipai/shared"; import type { StorageService } from "../storage/types.js"; import { getCloudRuntimeIdentity } from "../services/cloud-runtime-identity.js"; @@ -134,6 +135,36 @@ export function verifyRunLivenessQuestion( } } +export const MAX_INSPECTION_RESPONSE_BYTES = 2 * 1024 * 1024; + +export function fitInspectionResponse( + result: unknown, + operation: InspectionQuery["operation"], + offset: number, + maxBytes = MAX_INSPECTION_RESPONSE_BYTES, +): string | null { + const body = JSON.stringify(result); + if (Buffer.byteLength(body) <= maxBytes) return body; + if (operation !== "list") return null; + const page = result as { items?: unknown; nextOffset?: unknown } | null; + if (!page || !Array.isArray(page.items) || page.items.length < 2) return null; + const items = page.items; + let low = 0; + let high = items.length - 1; + let fitted: string | null = null; + while (low < high) { + const count = Math.ceil((low + high) / 2); + const candidate = JSON.stringify({ ...page, items: items.slice(0, count), nextOffset: offset + count }); + if (Buffer.byteLength(candidate) <= maxBytes) { + low = count; + fitted = candidate; + } else { + high = count - 1; + } + } + return fitted; +} + /** Mounted before actor middleware: none of these reads creates tenant state. */ export function customerSuccessRoutes(db: Db, storage: StorageService, options: CustomerSuccessInspectionOptions = {}) { const router = Router(); @@ -188,8 +219,8 @@ export function customerSuccessRoutes(db: Db, storage: StorageService, options: }); if (!consumed.ok) throw forbidden("Inspection permit could not be consumed"); const result = await readCustomerSuccessResource(db, storage, query, options); - const body = JSON.stringify(result); - if (Buffer.byteLength(body) > 2 * 1024 * 1024) + const body = fitInspectionResponse(result, query.operation, query.offset ?? 0); + if (body === null) throw unprocessable("Inspection response is too large; use pagination or a byte range"); res.type("application/json").send(body); });