Files
PaperClipAI/server/src/middleware/cloud-control.ts
T
DottaandClaude Opus 5.5 98ff5e002a feat(cloud): read-only durable-data eligibility for online enrollment (#22051)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Hosted Paperclip servers can move from a server with a persistent
volume to a volume-free server, which allows deploys without downtime
> - The online move is allowed only when no durable data still lives on
the local disk; Core checks this in `readEphemeralServerDataEligibility`
> - Cloud can only learn the result by calling the preparation endpoint,
and that call starts a real move when the server is eligible
> - So Cloud cannot safely survey many servers, or watch a background
migration make progress
> - This pull request adds a signed, read-only GET that runs the same
check and returns the blocker names
> - The benefit is that operators can see which data blocks each server,
and move only the servers that are ready

## Linked Issues or Issue Description

**What existing behavior does this improve?**
Cloud can see a server's durable-data eligibility only through `POST
/api/instance/ephemeral-enrollment/prepare`. A refused call returns the
blockers. An accepted call starts the online move.

**Subsystem affected**
Server: Cloud control endpoints and ephemeral enrollment
(`server/src/routes/ephemeral-enrollment.ts`,
`server/src/services/ephemeral-enrollment.ts`,
`server/src/middleware/cloud-control.ts`).

**Current behavior**
There is no way to read eligibility without the side effect of
preparation.

**Proposed behavior**
`GET /api/instance/ephemeral-enrollment/eligibility` accepts only a
Cloud control assertion for the new action
`ephemeral-enrollment:eligibility`. It returns `{ eligible, blockers,
ephemeralServer }` and writes nothing.

**Reason and benefit**
A rollout to many servers needs to know which servers are ready, and
which data owners block the others, before it starts any move.

**Breaking changes**
None. This adds one endpoint and one action. Existing actions are
unchanged.

## What Changed

- `routes/ephemeral-enrollment.ts`: new `GET
/instance/ephemeral-enrollment/eligibility`. It requires a verified
Cloud control claim for `ephemeral-enrollment:eligibility` and sets
`Cache-Control: no-store`.
- `services/ephemeral-enrollment.ts`: new
`readOnlineEphemeralEnrollmentEligibility`. It uses the same check as
preparation (`purpose: "startup"`) and returns only the eligibility
flag, the canonical blocker names, and whether this server is already
volume-free.
- `middleware/cloud-control.ts` and
`services/cloud-runtime-identity.ts`: register the endpoint and the
action. Each assertion stays bound to one action, so a prepare token
cannot read eligibility, and the reverse.
- `__tests__/openapi-routes.test.ts`: list the route with the other
Cloud-control endpoints that are not in the board OpenAPI document.

## Verification

- `npx vitest run src/routes/ephemeral-enrollment.test.ts
src/__tests__/openapi-routes.test.ts
src/services/ephemeral-enrollment.test.ts
src/services/cloud-runtime-identity.test.ts`: 83/83 pass.
- New route tests:
  - a signed read returns the result and does not call preparation;
  - an unsigned caller and a tenant instance admin get 403;
  - a prepare assertion on this path gets 401.
- The three new tests fail without the route (red) and pass with it
(green).
- `tsc --noEmit` reports no errors in the touched files. A full local
typecheck needs the Runner build, so CI covers it.

## Risks

- Low risk. The endpoint is read-only and reachable only with a Cloud
control assertion bound to this stack and this action.
- The check runs a few indexed reads and pages skill installations.
Cloud calls it on request, not on a timer.

## Model Used

- Claude Opus 5.5 (`claude-opus-5-5`) in Claude Code, with tool use
(shell, file edits).

## 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-17 13:02:37 -06:00

90 lines
3.7 KiB
TypeScript

import type { Request } from "express";
import type { VerifiedIdleCapabilities } from "../services/idle-incoming-wake-capability.js";
import type { RequestHandler } from "express";
import { logger } from "./logger.js";
import {
CLOUD_CONTROL_HEADER,
verifyCloudControlAssertion,
type CloudControlAction,
type CloudControlClaims,
} from "../services/cloud-runtime-identity.js";
const idleCapabilities = new WeakMap<Request, VerifiedIdleCapabilities>();
const controlClaims = new WeakMap<Request, CloudControlClaims>();
export function verifiedCloudControlClaims(req: Request): CloudControlClaims | undefined {
return controlClaims.get(req);
}
/** Only this middleware's verified assertion can install request capabilities. */
export function verifiedIdleCapabilities(req: Request): VerifiedIdleCapabilities | undefined {
return idleCapabilities.get(req);
}
/** Endpoint → method → the one action a control assertion must name to take it. */
const ACTIONS_BY_ENDPOINT: Record<string, Record<string, CloudControlAction>> = {
"/api/instance/ephemeral-enrollment/prepare": { POST: "ephemeral-enrollment:prepare" },
"/api/instance/ephemeral-enrollment/eligibility": { GET: "ephemeral-enrollment:eligibility" },
"/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",
DELETE: "task-drain:stop",
},
"/api/instance/lifecycle": {
GET: "lifecycle:read",
},
"/api/instance/lifecycle/unarchive-primary": {
POST: "lifecycle:unarchive-primary",
},
};
/**
* Accepts Cloud's signed control assertion only on the closed endpoint set
* above — the task-drain hold the deploy path uses, and the lifecycle
* read-back/unarchive pair behind the Cloud archive sync. The JWS is the entire
* authorization: a valid assertion installs a synthetic instance-admin board
* actor (replacing whatever weaker actor the request carried), each assertion
* is bound to exactly one method's action, and the header is rejected loudly
* anywhere else so it can never become an ambient credential. Instances
* without a Cloud stack identity reject every assertion. The browser-facing
* Cloud proxy strips this header, and possession of the shared tenant-session
* token cannot mint it.
*/
export function cloudControlMiddleware(): RequestHandler {
return (req, res, next) => {
const assertion = req.get(CLOUD_CONTROL_HEADER)?.trim();
if (!assertion) {
next();
return;
}
// Express's non-strict routing treats a trailing slash as the same
// route; the endpoint check must agree with it.
const normalizedPath = req.path.length > 1 && req.path.endsWith("/") ? req.path.slice(0, -1) : req.path;
const expectedAction = ACTIONS_BY_ENDPOINT[normalizedPath]?.[req.method];
if (!expectedAction) {
res.status(400).json({ error: "cloud_control_wrong_endpoint" });
return;
}
try {
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) {
logger.warn({ err: error }, "Rejected Cloud control assertion");
res.status(401).json({ error: "invalid_cloud_control_assertion" });
return;
}
req.actor = {
type: "board",
userId: "paperclip-cloud",
userName: "Paperclip Cloud",
userEmail: null,
isInstanceAdmin: true,
source: "cloud_control",
};
next();
};
}