Bind complete Cloud idle-safety catalogs to a bounded request body

This commit is contained in:
Dotta committed 2026-11-07 17:38:40 -06:00
1 parent ec73713117
commit cb99342653
13 files changed
+199 -15

No files matched your search

+11 -1
View File
@@ -5,6 +5,16 @@ instance-wide `idleSleepSafety` report for instance administrators and signed
Cloud control callers. Ordinary task drains keep their existing behavior.
Company members and agents cannot read this report.
Cloud callers carrying full idle catalogs use `POST /api/instance/task-drain/status`
with the same read query and `{ "idleCapabilities": ... }` JSON body. A short
`task-drain:read-body` control JWT binds the exact raw-body SHA256. The existing
10 MiB JSON limit, fatal UTF8 decoding, strict catalog parsing, stack/action/expiry
checks and exact byte digest all apply before consuming the single-use request ID
or installing any capability. Embedded catalogs and body digests cannot be mixed.
Unsigned bodies and browser authority alone cannot authorize this Cloud-only read.
GET remains compatible; POST drain start and DELETE stop are unchanged.
Instance administrators and signed Cloud control callers may add
`idleSleepDiagnostics=1` to an owned safety request for fixed-key blocker
diagnostics. This explicit one-shot read evaluates all current predicates in
@@ -48,7 +58,7 @@ and `Retry-After: 1`. Health checks and authenticated task-drain control remain
available. Ordinary deploy drains do not enable this HTTP gate. The host must
handle retry/wake at its ingress before enabling automatic sleep.
Health and control mutations remain tracked through completion, including
signed bootstrap writes. Only the task-drain read skips request tracking.
signed bootstrap writes. Only the exact GET task-drain read and POST task-drain/status body read skip request tracking.
Its authentication finishes under a separate work token before entering the
report, so it counts concurrent writes without blocking on its own scan.
@@ -168,6 +168,12 @@ API: `present` — representative operation IDs:
status remains an in-memory read. [Route coverage](../../server/src/__tests__/instance-settings-routes.test.ts)
and [PostgreSQL coverage](../../server/src/services/heartbeat/upgrade-readiness.test.ts)
establish this local boundary; hosted active-run continuity requires separate proof.
- `POST /api/instance/task-drain/status?idleSleepSafety=1` — Cloud-only body read.
The short `task-drain:read-body` control assertion signs the exact raw JSON
SHA256; the complete catalog remains in the body under the existing 10 MiB
JSON limit. A browser actor or unsigned body grants no wake authority. It
shares GET status/owner/deadline semantics, never starts or stops a drain.
This documents the source contract, not fleet deployment or sleep acceptance.
- `GET /api/instance/task-drain?idleSleepSafety=1` — the negotiated incoming-wake
extension requires a verified stack/action/owner-scoped Cloud control capability;
query parameters and tenant credentials cannot grant it. Its version-3 proof
+5
View File
@@ -171,3 +171,8 @@ then saves immutable version selections in the heartbeat execution context. New
resolve latest installed content; resumed runs retain selections and recheck access.
An unavailable explicit reference produces an actionable configuration error.
Live agent execution across an upstream update remains required acceptance evidence.
Signed Cloud catalog reads may instead use `POST /api/instance/task-drain/status`
with the same `idleSleepSafety`, `scheduledWake` and exact `ownerId` query. The
`task-drain:read-body` assertion binds the complete raw JSON body by SHA256; it
grants no routine execution or management authority. Existing GET is compatible.
@@ -1,6 +1,6 @@
import { connectionEventWakeRoutes } from "../routes/connection-event-wake.js";
import { registerConnectionEventWake } from "../services/connection-event-wake.js";
import { generateKeyPairSync, sign } from "node:crypto";
import { createHash, generateKeyPairSync, sign } from "node:crypto";
import express from "express";
import request from "supertest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -382,3 +382,65 @@ describe("cloudControlMiddleware", () => {
expect(res.status).toBe(200);
});
});
describe("body-bound Cloud idle status assertion", () => {
const body = Buffer.from(JSON.stringify({ idleCapabilities: { deadlineCatalog: "domain_deadlines_v1" } }));
const digest = (value: Uint8Array) => createHash("sha256").update(value).digest("hex");
const token = (raw: Uint8Array, extra: Record<string, unknown> = {}) => controlAssertion({ action: "task-drain:read-body", claims: { bodySha256: digest(raw), ...extra } });
const read = (compactJws: string, rawBody?: Uint8Array) => verifyCloudControlAssertion({ compactJws, rawBody,
expectedAction: "task-drain:read-body", env: ENV, now: NOW });
beforeEach(() => resetCloudControlReplayFenceForTests());
it("installs the complete closed body only after its exact-byte binding and rejects replay", () => {
const jws = token(body);
const claims = read(jws, body);
expect(claims.idleCapabilities).toEqual({ deadlineCatalog: "domain_deadlines_v1" });
expect(Object.isFrozen(claims.idleCapabilities)).toBe(true);
expect(() => read(jws, body)).toThrow(/already been used/);
});
it("rejects changed or missing bytes without burning the valid exact request", () => {
const jws = token(body);
expect(() => read(jws)).toThrow(/body binding/);
expect(() => read(jws, Buffer.concat([body, Buffer.from(" ")]))).toThrow(/digest changed/);
expect(read(jws, body).idleCapabilities?.deadlineCatalog).toBe("domain_deadlines_v1");
});
it("rejects malformed UTF8 before consuming the same nonce", () => {
const requestId = "invalid-utf8-status-read";
const malformed = Buffer.concat([Buffer.from('{"idleCapabilities":{"deadlineCatalog":"'), Buffer.from([0xff]), Buffer.from('"}}')]);
expect(() => read(token(malformed, { requestId }), malformed)).toThrow(TypeError);
expect(read(token(body, { requestId }), body).idleCapabilities?.deadlineCatalog).toBe("domain_deadlines_v1");
});
it.each([
["unknown catalog", '{"idleCapabilities":{"deadlineCatalog":"unowned"}}'],
["extra field", '{"idleCapabilities":{"deadlineCatalog":"domain_deadlines_v1"},"extra":true}'],
["array body", '[{"idleCapabilities":{"deadlineCatalog":"domain_deadlines_v1"}}]'],
["malformed JSON", "{"],
])("rejects %s before consuming the same nonce", (_name, text) => {
const requestId = "rejected-status-body";
const raw = Buffer.from(text);
expect(() => read(token(raw, { requestId }), raw)).toThrow();
expect(read(token(body, { requestId }), body).idleCapabilities?.deadlineCatalog).toBe("domain_deadlines_v1");
});
it("rejects mixed embedded capabilities and malformed digest without consuming a nonce", () => {
for (const extra of [{ idleCapabilities: { deadlineCatalog: "domain_deadlines_v1" } }, { bodySha256: "invalid" }]) {
resetCloudControlReplayFenceForTests();
const requestId = "mixed-status-body";
expect(() => read(token(body, { requestId, ...extra }), body)).toThrow(/body binding/);
expect(read(token(body, { requestId }), body).idleCapabilities?.deadlineCatalog).toBe("domain_deadlines_v1");
}
});
it("enforces the unchanged ten MiB JSON limit before consuming the same nonce", () => {
const raw = Buffer.alloc(10 * 1024 * 1024 + 1, 32), requestId = "oversized-status-body";
expect(() => read(token(raw, { requestId }), raw)).toThrow(/body binding/);
expect(read(token(body, { requestId }), body).idleCapabilities?.deadlineCatalog).toBe("domain_deadlines_v1");
});
it("does not turn body-read authority into start or stop authority", () => {
for (const action of ["task-drain:start", "task-drain:stop"] as const) {
const jws = token(body);
expect(() => verifyCloudControlAssertion({ compactJws: jws, expectedAction: action, rawBody: body, env: ENV, now: NOW })).toThrow(/authorize/);
expect(read(jws, body).action).toBe("task-drain:read-body");
expect(() => verifyCloudControlAssertion({ compactJws: controlAssertion({ action, claims: { bodySha256: digest(body) } }),
expectedAction: action, rawBody: body, env: ENV, now: NOW })).toThrow(/Body|body/);
}
});
});
@@ -34,6 +34,19 @@ describe("idle admission", () => {
expect(idleWorkSnapshot().active).toBe(0);
});
it("exempts only the exact body status read from self-accounting and keeps drain mutations tracked", async () => {
const server = app();
server.post("/api/instance/task-drain/status", (_req, res) => res.json({ active: idleWorkSnapshot().active }));
server.post("/api/instance/task-drain", (_req, res) => res.json({ active: idleWorkSnapshot().active }));
trackIdleRequestHandlers(server);
startTaskDrain({ purpose: "idle", ttlMs: 60_000 });
expect((await request(server).post("/api/instance/task-drain/status").expect(200)).body.active).toBe(0);
expect((await request(server).post("/api/instance/task-drain").expect(200)).body.active).toBe(1);
await request(server).post("/api/instance/task-drain/status/mutate").expect(503);
await request(server).get("/api/instance/task-drain/status").expect(503);
expect(idleWorkSnapshot().active).toBe(0);
});
it("counts a nested async handler after it sends a response", async () => {
const server = app();
const router = express.Router();
@@ -1,4 +1,5 @@
import { generateKeyPairSync, randomUUID, sign } from "node:crypto";
import { DEFAULT_JSON_BODY_LIMIT } from "../http/body-limits.js";
import { createHash, generateKeyPairSync, randomUUID, sign } from "node:crypto";
import express from "express";
import request from "supertest";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -100,7 +101,7 @@ describe("instance settings routes", () => {
function createApp(actor: any, pluginWorkers?: PluginWorkerManager, prepareBackup?: () => Promise<boolean>, verifyControl = false) {
const { errorHandler, instanceSettingsRoutes, cloudControlMiddleware } = routeModules.value;
const app = express();
app.use(express.json());
app.use(express.json({ limit: DEFAULT_JSON_BODY_LIMIT, verify: (req, _res, raw) => { Reflect.set(req, "rawBody", raw); } }));
app.use((req, _res, next) => {
req.actor = actor;
next();
@@ -1190,6 +1191,46 @@ describe("instance settings routes", () => {
});
afterEach(() => vi.unstubAllEnvs());
it("reads the same owner and deadline scope through the real body-bound middleware and production handler", async () => {
const raw = JSON.stringify({ idleCapabilities: catalog });
const token = assertion({ action: "task-drain:read-body", idleCapabilities: undefined, bodySha256: createHash("sha256").update(raw).digest("hex") });
const url = `/api/instance/task-drain/status?idleSleepSafety=1&scheduledWake=domain-deadlines-v1&ownerId=${ownerId}`;
await request(createControlApp({ type: "none" })).post(url).set("content-type", "application/json")
.set("x-paperclip-cloud-control", token).send(raw).expect(200);
expect(mockReadIdleSleepSafety).toHaveBeenCalledExactlyOnceWith(mockDb, expect.any(Function), Date.now,
ownerId, expect.any(Function), undefined, undefined, true, true,
{ incomingWake: catalog, deadlineCapability: catalog, prepareLocalWork: expect.any(Function) });
expect(Object.isFrozen(mockReadIdleSleepSafety.mock.calls[0][9].incomingWake)).toBe(true);
await request(createControlApp({ type: "none" })).post(url).set("content-type", "application/json")
.set("x-paperclip-cloud-control", token).send(raw).expect(401);
});
it("rejects body tampering before installing capabilities or consuming the valid request", async () => {
const raw = JSON.stringify({ idleCapabilities: catalog });
const token = assertion({ action: "task-drain:read-body", idleCapabilities: undefined, bodySha256: createHash("sha256").update(raw).digest("hex") });
const url = `/api/instance/task-drain/status?idleSleepSafety=1&ownerId=${ownerId}`;
await request(createControlApp(adminActor)).post(url).set("content-type", "application/json")
.set("x-paperclip-cloud-control", token).send(raw + " ").expect(401);
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
await request(createControlApp({ type: "none" })).post(url).set("content-type", "application/json")
.set("x-paperclip-cloud-control", token).send(raw).expect(200);
});
it("rejects unsigned and actor-only body authority and cross-route method replay", async () => {
const raw = JSON.stringify({ idleCapabilities: catalog }), url = `/api/instance/task-drain/status?idleSleepSafety=1&ownerId=${ownerId}`;
for (const source of ["session", "cloud_tenant", "local_implicit", "cloud_control"]) {
await request(createControlApp({ ...adminActor, source, idleCapabilities: catalog })).post(url)
.set("content-type", "application/json").send(raw).expect(403);
}
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
const token = assertion({ action: "task-drain:read-body", idleCapabilities: undefined, bodySha256: createHash("sha256").update(raw).digest("hex") });
await request(createControlApp(adminActor)).get(url).set("x-paperclip-cloud-control", token).expect(400);
await request(createControlApp(adminActor)).post("/api/instance/task-drain").set("content-type", "application/json")
.set("x-paperclip-cloud-control", token).send(raw).expect(401);
await request(createControlApp(adminActor)).delete("/api/instance/task-drain").set("x-paperclip-cloud-control", token).expect(401);
expect(mockReadIdleSleepSafety).not.toHaveBeenCalled();
await request(createControlApp({ type: "none" })).post(url).set("content-type", "application/json")
.set("x-paperclip-cloud-control", token).send(raw).expect(200);
});
it("passes only the immutable signed catalog through real middleware and the production route", async () => {
const token = assertion();
const response = await request(createControlApp({ type: "none" }))
+1
View File
@@ -1,4 +1,5 @@
export const DEFAULT_JSON_BODY_LIMIT = "10mb";
export const DEFAULT_JSON_BODY_LIMIT_BYTES = 10 * 1024 * 1024;
export const CHAT_WEBHOOK_BODY_LIMIT = "1mb";
export const CHAT_WEBHOOK_BODY_LIMIT_BYTES = 1024 * 1024;
export const PORTABLE_JSON_BODY_LIMIT = "64mb";
+4 -1
View File
@@ -23,6 +23,7 @@ export function verifiedIdleCapabilities(req: Request): VerifiedIdleCapabilities
const ACTIONS_BY_ENDPOINT: Record<string, Record<string, CloudControlAction>> = {
"/api/instance/ephemeral-enrollment/prepare": { POST: "ephemeral-enrollment:prepare" },
"/api/instance/connector-events/wake": { POST: "connector-events:wake" },
"/api/instance/task-drain/status": { POST: "task-drain:read-body" },
"/api/instance/task-drain": {
GET: "task-drain:read",
POST: "task-drain:start",
@@ -64,7 +65,9 @@ export function cloudControlMiddleware(): RequestHandler {
return;
}
try {
const claims = verifyCloudControlAssertion({ compactJws: assertion, expectedAction });
const rawBody: unknown = Reflect.get(req, "rawBody");
const claims = verifyCloudControlAssertion({ compactJws: assertion, expectedAction,
...(Buffer.isBuffer(rawBody) ? { rawBody } : {}) });
controlClaims.set(req, claims);
if (claims.idleCapabilities) idleCapabilities.set(req, claims.idleCapabilities as VerifiedIdleCapabilities);
} catch (error) {
@@ -195,7 +195,7 @@ describe("resolveCloudTenantActor (shared-pool hardening)", () => {
expect(insertedTables).toContain(companyMemberships);
});
it.each(["/api/health", "/api/instance/task-drain"])("counts unfinished authentication on exempt %s requests", async (path) => {
it.each(["/api/health", "/api/instance/task-drain", "/api/instance/task-drain/status"])("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; });
@@ -211,8 +211,9 @@ describe("resolveCloudTenantActor (shared-pool hardening)", () => {
res.json(await readIdleSleepSafety(emptyDb, () => ({ ...hold, draining: true, activeRuns: 0, pendingWakes: 0 }),
Date.now, hold.ownerId, async () => "none"));
});
server.post("/api/instance/task-drain/status", (_req, res) => res.sendStatus(204));
trackIdleRequestHandlers(server);
const accepted = request(server).get(path).set(VALID_HEADERS).then(response => response);
const accepted = (path.endsWith("/status") ? request(server).post(path) : request(server).get(path)).set(VALID_HEADERS).then(response => response);
try {
await entered;
expect(idleWorkSnapshot().active).toBeGreaterThan(0);
+3 -1
View File
@@ -55,6 +55,7 @@ export function completeIdleReadOnlyResponse(req: Request, application: Applicat
function isControlRequest(req: Request) {
const path = req.path.replace(/\/$/, "");
return (path === "/api/instance/task-drain" && ["GET", "POST", "DELETE"].includes(req.method)) ||
(path === "/api/instance/task-drain/status" && req.method === "POST") ||
(path === "/api/health" && ["GET", "HEAD"].includes(req.method));
}
@@ -71,7 +72,8 @@ export const idleAdmissionMiddleware: RequestHandler = (req, res, next) => {
res.set("Retry-After", "1").status(503).json({ error: "instance_preparing_to_sleep" });
return;
}
if (controlRequest && req.method === "GET" && req.path.replace(/\/$/, "") === "/api/instance/task-drain") {
if (controlRequest && ((req.method === "GET" && req.path.replace(/\/$/, "") === "/api/instance/task-drain")
|| (req.method === "POST" && req.path.replace(/\/$/, "") === "/api/instance/task-drain/status"))) {
next();
return;
}
+10 -3
View File
@@ -1,7 +1,7 @@
import type { IdleDeadlineOwners } from "../services/idle-deadline-types.js";
import { verifiedIdleCapabilities } from "../middleware/cloud-control.js";
import { verifiedCloudControlClaims, verifiedIdleCapabilities } from "../middleware/cloud-control.js";
import { trackIdleWork } from "../services/task-admission.js";
import { Router, type Request } from "express";
import { Router, type Request, type RequestHandler } from "express";
import { companies, type Db } from "@paperclipai/db";
import {
patchInstanceSettingsSchema,
@@ -304,7 +304,7 @@ export function instanceSettingsRoutes(
},
);
router.get("/instance/task-drain", async (req, res) => {
const readTaskDrainStatus: RequestHandler = async (req, res) => {
assertBoardOrgAccess(req);
if (req.query.upgradeReadiness === "1") {
// This covers all companies and must not expose instance-wide work to a member.
@@ -350,6 +350,13 @@ export function instanceSettingsRoutes(
return;
}
res.json(heartbeat.getTaskDrainStatus());
};
router.get("/instance/task-drain", readTaskDrainStatus);
router.post("/instance/task-drain/status", async (req, res, next) => {
if (req.actor.source !== "cloud_control" || verifiedCloudControlClaims(req)?.action !== "task-drain:read-body") {
throw forbidden("Cloud body-bound read authority is required");
}
await readTaskDrainStatus(req, res, next);
});
router.post(
+11
View File
@@ -7131,6 +7131,17 @@ registry.registerPath({
responses: { 200: r.ok(), 401: r.unauthorized, 403: r.forbidden },
});
registry.registerPath({
method: "post",
path: "/api/instance/task-drain/status",
tags: ["instance"],
summary: "Read task-drain status with body-bound signed Cloud idle capabilities",
description: "Requires the task-drain:read-body Cloud control assertion bound to the exact raw JSON SHA256. The body alone and browser administrator access do not grant this authority. Uses the same status/idle-safety reader and owner/scheduled-wake semantics as GET; does not start or stop a drain.",
request: { body: jsonBody(z.object({ idleCapabilities: z.unknown().describe("Complete closed incoming-wake and deadline catalogs, validated by the existing capability parser after signature and exact raw-body binding") }).strict()),
query: z.object({ upgradeReadiness: z.literal("1").optional(), ownerId: z.string().uuid().optional(), idleSleepSafety: z.literal("1").optional(), scheduledWake: z.enum(["1", "2", "domain-deadlines-v1"]).optional() }) },
responses: { 200: r.ok(), 400: r.badRequest, 401: r.unauthorized, 403: r.forbidden },
});
registry.registerPath({
method: "post",
path: "/api/instance/task-drain",
+26 -4
View File
@@ -1,5 +1,6 @@
import { DEFAULT_JSON_BODY_LIMIT_BYTES } from "../http/body-limits.js";
import { parseIdleCapabilities, type IdleCapabilities } from "./idle-incoming-wake-capability.js";
import { createPublicKey, timingSafeEqual, verify, type JsonWebKey } from "node:crypto";
import { createHash, createPublicKey, timingSafeEqual, verify, type JsonWebKey } from "node:crypto";
import { eq } from "drizzle-orm";
import type { Db } from "@paperclipai/db";
import { instanceSettings } from "@paperclipai/db";
@@ -449,6 +450,7 @@ export const CLOUD_CONTROL_JWS_TYPE = "paperclip-cloud-control+jwt";
export const CLOUD_CONTROL_ACTIONS = [
"ephemeral-enrollment:prepare",
"task-drain:read",
"task-drain:read-body",
"task-drain:start",
"task-drain:stop",
"lifecycle:read",
@@ -496,6 +498,7 @@ export type CloudControlClaims = {
action: CloudControlAction;
requestId: string;
idleCapabilities?: IdleCapabilities;
bodySha256?: string;
iat: number;
exp: number;
};
@@ -509,6 +512,7 @@ export type CloudControlClaims = {
*/
export function verifyCloudControlAssertion(input: {
compactJws: string;
rawBody?: Uint8Array;
expectedAction: CloudControlAction;
env?: NodeJS.ProcessEnv;
now?: Date;
@@ -577,9 +581,27 @@ export function verifyCloudControlAssertion(input: {
) {
throw new Error("Cloud control assertion is expired or has an invalid lifetime");
}
if (payload.idleCapabilities !== undefined) {
if (payload.action !== "task-drain:read") throw new Error("Idle capabilities require task-drain:read");
payload.idleCapabilities = parseIdleCapabilities(payload.idleCapabilities);
if (payload.action === "task-drain:read-body") {
if (payload.idleCapabilities !== undefined || typeof payload.bodySha256 !== "string" || !/^[a-f0-9]{64}$/.test(payload.bodySha256)
|| !input.rawBody || input.rawBody.byteLength === 0 || input.rawBody.byteLength > DEFAULT_JSON_BODY_LIMIT_BYTES) {
throw new Error("Invalid Cloud idle status body binding");
}
const raw = Buffer.from(input.rawBody);
if (createHash("sha256").update(raw).digest("hex") !== payload.bodySha256) throw new Error("Cloud idle status body digest changed");
const text = new TextDecoder("utf-8", { fatal: true }).decode(raw);
let body: unknown;
try { body = JSON.parse(text); }
catch { throw new Error("Invalid Cloud idle status body JSON"); }
if (!body || typeof body !== "object" || Array.isArray(body) || Object.keys(body).join() !== "idleCapabilities") {
throw new Error("Invalid Cloud idle status body");
}
payload.idleCapabilities = parseIdleCapabilities(Reflect.get(body, "idleCapabilities"));
} else {
if (payload.bodySha256 !== undefined) throw new Error("Cloud body binding requires task-drain:read-body");
if (payload.idleCapabilities !== undefined) {
if (payload.action !== "task-drain:read") throw new Error("Idle capabilities require task-drain:read");
payload.idleCapabilities = parseIdleCapabilities(payload.idleCapabilities);
}
}
// Consumed LAST, only after every other check passed: a rejected
// assertion must not burn its request id, or an attacker could deny a