Files
PaperClipAI/server/src/routes/ephemeral-enrollment.test.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

106 lines
5.7 KiB
TypeScript

import { generateKeyPairSync, randomUUID, sign } from "node:crypto";
import express from "express";
import request from "supertest";
import { afterEach, beforeEach, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
import { ephemeralEnrollmentRoutes } from "./ephemeral-enrollment.js";
import { cloudControlMiddleware } from "../middleware/cloud-control.js";
import { isSecretSensitiveHttpRequest } from "../middleware/http-log-policy.js";
import { CLOUD_CONTROL_AUDIENCE, CLOUD_CONTROL_HEADER, CLOUD_CONTROL_JWS_TYPE,
CLOUD_RUNTIME_IDENTITY_ISSUER, resetCloudControlReplayFenceForTests } from "../services/cloud-runtime-identity.js";
const prepare = vi.hoisted(() => vi.fn());
const eligibility = vi.hoisted(() => vi.fn());
vi.mock("../services/ephemeral-enrollment.js", () => ({ prepareOnlineEphemeralEnrollment: prepare,
readOnlineEphemeralEnrollmentEligibility: eligibility }));
const pair = generateKeyPairSync("ed25519");
const jwk = { ...pair.publicKey.export({ format: "jwk" }), kid: "enrollment-fixture", alg: "EdDSA", use: "sig" };
const path = "/api/instance/ephemeral-enrollment/prepare";
const attemptId = randomUUID();
const encode = (value: unknown) => Buffer.from(JSON.stringify(value)).toString("base64url");
function assertion(action = "ephemeral-enrollment:prepare", stackId = "stack-fixture") {
const iat = Math.floor(Date.now() / 1000);
const body = `${encode({ alg: "EdDSA", typ: CLOUD_CONTROL_JWS_TYPE, kid: jwk.kid })}.${encode({
v: 1, iss: CLOUD_RUNTIME_IDENTITY_ISSUER, aud: CLOUD_CONTROL_AUDIENCE,
sub: stackId, action, requestId: randomUUID(), iat, exp: iat + 60,
})}`;
return `${body}.${sign(null, Buffer.from(body, "ascii"), pair.privateKey).toString("base64url")}`;
}
function app(tenant = false) {
const result = express(); result.use(express.json());
result.use((req, _res, next) => {
req.actor = tenant ? { type: "board", source: "cloud_tenant", userId: "fixture-user", isInstanceAdmin: true }
: { type: "none", source: "none" };
next();
});
result.use(cloudControlMiddleware()); result.use("/api", ephemeralEnrollmentRoutes({} as Db));
result.use((error: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
res.status(400).json({ error: "fixture_validation_failed" });
});
return result;
}
beforeEach(() => {
vi.resetAllMocks(); resetCloudControlReplayFenceForTests();
vi.stubEnv("PAPERCLIP_CLOUD_STACK_ID", "stack-fixture");
vi.stubEnv("PAPERCLIP_CLOUD_RUNTIME_IDENTITY_JWKS", JSON.stringify({ keys: [jwk] }));
prepare.mockResolvedValue({ attemptId, enrollmentReady: false, decisionSigningSecret: "fixture-original-key" });
eligibility.mockResolvedValue({ eligible: false, blockers: ["workspaces_require_migration"], ephemeralServer: false });
});
afterEach(() => vi.unstubAllEnvs());
it("exports once only to a fresh stack-bound signed prepare assertion", async () => {
const server = app(), token = assertion();
const accepted = await request(server).post(path).set(CLOUD_CONTROL_HEADER, token).send({ attemptId });
expect(accepted.status).toBe(200);
expect(accepted.headers["cache-control"]).toBe("no-store");
expect(accepted.body).toMatchObject({ decisionSigningSecret: "fixture-original-key", enrollmentReady: false });
expect((await request(server).post(path).set(CLOUD_CONTROL_HEADER, token).send({ attemptId })).status).toBe(401);
expect(prepare).toHaveBeenCalledOnce();
});
it.each([false, true])("refuses an unsigned caller, including a tenant instance admin (%s)", async tenant => {
expect((await request(app(tenant)).post(path).send({ attemptId })).status).toBe(403);
expect(prepare).not.toHaveBeenCalled();
});
it.each([["task-drain:read", "stack-fixture"], ["ephemeral-enrollment:prepare", "stack-other"]])(
"refuses mismatched action or stack (%s, %s)", async (action, stack) => {
const result = await request(app()).post(path).set(CLOUD_CONTROL_HEADER, assertion(action, stack)).send({ attemptId });
expect(result.status).toBe(401); expect(prepare).not.toHaveBeenCalled();
});
it("rejects malformed or additional caller-supplied authority before export", async () => {
for (const body of [{ attemptId: "bad" }, { attemptId, stackId: "stack-other" }]) {
expect((await request(app()).post(path).set(CLOUD_CONTROL_HEADER, assertion()).send(body)).status).toBe(400);
}
expect(prepare).not.toHaveBeenCalled();
});
it("keeps enrollment HTTP diagnostics secret-sensitive, including rejected methods", () => {
for (const method of ["POST", "GET", "DELETE"]) {
expect(isSecretSensitiveHttpRequest(method, path)).toBe(true);
expect(isSecretSensitiveHttpRequest(method, `https://fixture.test${path}`)).toBe(true);
}
});
const eligibilityPath = "/api/instance/ephemeral-enrollment/eligibility";
it("reports durable-data eligibility to a signed read and changes nothing", async () => {
const result = await request(app()).get(eligibilityPath).set(CLOUD_CONTROL_HEADER, assertion("ephemeral-enrollment:eligibility"));
expect(result.status).toBe(200);
expect(result.headers["cache-control"]).toBe("no-store");
expect(result.body).toEqual({ eligible: false, blockers: ["workspaces_require_migration"], ephemeralServer: false });
expect(prepare).not.toHaveBeenCalled();
});
it.each([false, true])("refuses an unsigned eligibility read, including a tenant instance admin (%s)", async tenant => {
expect((await request(app(tenant)).get(eligibilityPath)).status).toBe(403);
expect(eligibility).not.toHaveBeenCalled();
});
it("refuses a prepare assertion on the eligibility read", async () => {
const result = await request(app()).get(eligibilityPath).set(CLOUD_CONTROL_HEADER, assertion("ephemeral-enrollment:prepare"));
expect(result.status).toBe(401);
expect(eligibility).not.toHaveBeenCalled();
});