Files
PaperClipAI/server/src/__tests__/health-dev-server-token.test.ts
T
Devin Foley 51bb41c7e3 Expose the running build commit on the unauthenticated health response (#10563)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - Instances run self-hosted or under hosting/deploy tooling, and
operators need to observe what build a server is actually running
> - `/api/health` carries the git SHA only inside `serverInfo`, which is
gated to board/agent actors — anonymous callers get a redacted body with
no version signal at all
> - Deploy tooling that manages instances from outside (fleet rollouts,
hosting providers, upgrade scripts) therefore cannot ground-truth that a
deploy actually shipped without holding credentials
> - A build commit is a plain git SHA of this public repository — it is
not a secret, and gating it buys no security while blocking legitimate
verification
> - This pull request surfaces the running build commit as a top-level
`commit` field on every `/api/health` response, including the redacted
anonymous one
> - The benefit is credential-free deploy verification: any operator or
tool can confirm which commit an instance serves, while the fuller
`serverInfo` block stays access-controlled as before

## Linked Issues or Issue Description

No existing public issue — inline description following the feature
request template:

**Subsystem affected**

Server (API, runs, routes)

**Problem or motivation**

An anonymous `GET /api/health` returns a redacted body with no version
information; the running git SHA exists only in
`serverInfo.git.fullSha`, which requires a board/agent actor. External
deploy tooling (fleet rollouts, hosting providers, upgrade scripts)
therefore cannot verify that an instance is actually serving the build
it was just upgraded to — a rollout that silently keeps running the old
image is indistinguishable from a successful one at the health endpoint.

**Proposed solution**

Surface the running build commit as a top-level nullable `commit` field
on every `/api/health` response shape, including the redacted anonymous
one, while keeping the fuller `serverInfo` block access-controlled as
before. A build commit is a plain git SHA of this public repository —
exposing it costs nothing and enables credential-free deploy
verification, like the `version` endpoints on most server software.

**Alternatives considered**

Authenticating deploy tooling as a board actor to read `serverInfo` —
rejected: it forces credential plumbing into infrastructure that only
needs a public SHA, and adds a whole class of auth-misconfiguration
failure to deploy verification.

**Roadmap alignment**

Not on ROADMAP.md; a small operational observability improvement, no
overlap with planned core work.

## What Changed

- `server/src/routes/health.ts`: derive `commit` from the server info
snapshot (`serverInfo.git.fullSha` when git metadata is available, else
`null`) and include it as a top-level field on every `/api/health`
response shape — the redacted anonymous body, the full-details body, the
no-db body, and the 503 database-unreachable body.
- `serverInfo` itself remains gated to full-details responses exactly as
before; only the bare commit is newly public.
- `server/src/__tests__/health.test.ts`: updated exact-shape assertions
to include `commit`, and added an assertion that `commit` is `null` (not
omitted) when git metadata is unavailable. The redacted-response tests
now pin that anonymous callers receive the commit.

## Verification

- `pnpm vitest run src/__tests__/health.test.ts` in `server/` — 13 tests
pass, including the redacted-anonymous shapes (which now pin the
`commit` field) and the git-unavailable `null` case.
- `tsc -p server/tsconfig.json --noEmit` — clean.
- Manual: `curl -s https://<instance>/api/health` as an anonymous caller
returns `"commit": "<full sha>"` alongside the existing redacted fields.

## Risks

- **Version disclosure:** anonymous callers can now fingerprint the
exact running commit. This is a deliberate trade-off: the builds are of
a public repository (the SHA reveals no private code), the endpoint
already responds to anonymous callers, and the operational value —
verifying deploys actually shipped — outweighs the marginal
fingerprinting surface. Operators who consider this sensitive are
typically fronting `/api` with their own access controls already.
- Otherwise low risk: no behavioral change to any gated field, no schema
or API-surface removal; `commit: null` keeps the field shape stable when
git metadata is absent (e.g. non-git installs).

## Model Used

Claude Opus 4.8 (`claude-opus-4-8`, extended thinking, via Claude Code
with tool use and code execution) authored the change and tests;
finalized and PR'd under Claude Fable 5 (`claude-fable-5`).

## 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 (none
needed beyond code comments — health endpoint has no standalone doc)
- [x] I have considered and documented any risks above
- [x] All Paperclip CI gates are green
- [x] Greptile is 5/5 with no open P2s, recommendations, or follow-ups
- [x] I will address all Greptile and reviewer comments before
requesting merge
2026-07-31 11:46:34 -07:00

214 lines
6.9 KiB
TypeScript

import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import express from "express";
import request from "supertest";
import { afterEach, describe, expect, it, vi } from "vitest";
import type { Db } from "@paperclipai/db";
import { healthRoutes } from "../routes/health.js";
const tempDirs: string[] = [];
function createDevServerStatusFile(payload: unknown) {
const dir = mkdtempSync(path.join(os.tmpdir(), "paperclip-health-dev-server-"));
tempDirs.push(dir);
const filePath = path.join(dir, "dev-server-status.json");
writeFileSync(filePath, `${JSON.stringify(payload)}\n`, "utf8");
return filePath;
}
afterEach(() => {
for (const dir of tempDirs.splice(0)) {
rmSync(dir, { recursive: true, force: true });
}
});
describe("GET /health dev-server supervisor access", () => {
it("exposes dev-server metadata to the supervising dev runner in authenticated mode", async () => {
const previousFile = process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
const previousToken = process.env.PAPERCLIP_DEV_SERVER_STATUS_TOKEN;
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = createDevServerStatusFile({
dirty: true,
lastChangedAt: "2026-03-20T12:00:00.000Z",
changedPathCount: 1,
changedPathsSample: ["server/src/routes/health.ts"],
pendingMigrations: [],
lastRestartAt: "2026-03-20T11:30:00.000Z",
});
process.env.PAPERCLIP_DEV_SERVER_STATUS_TOKEN = "dev-runner-token";
let selectCall = 0;
const db = {
execute: vi.fn().mockResolvedValue([{ "?column?": 1 }]),
select: vi.fn(() => {
selectCall += 1;
if (selectCall === 1) {
return {
from: vi.fn(() => ({
where: vi.fn().mockResolvedValue([{ count: 1 }]),
})),
};
}
if (selectCall === 2) {
return {
from: vi.fn(() => ({
where: vi.fn().mockResolvedValue([
{
id: "settings-1",
general: {},
experimental: { autoRestartDevServerWhenIdle: true },
createdAt: new Date("2026-03-20T11:00:00.000Z"),
updatedAt: new Date("2026-03-20T11:00:00.000Z"),
},
]),
})),
};
}
return {
from: vi.fn(() => ({
where: vi.fn().mockResolvedValue([{ count: 0 }]),
})),
};
}),
} as unknown as Db;
try {
const app = express();
app.use((req, _res, next) => {
(req as any).actor = { type: "none", source: "none" };
next();
});
app.use(
"/health",
healthRoutes(db, {
deploymentMode: "authenticated",
deploymentExposure: "private",
authReady: true,
companyDeletionEnabled: true,
// Pin server info so the commit field is deterministic (null)
// instead of picking up the checkout's real git metadata.
serverInfo: {
processStartedAt: "2026-03-20T11:00:00.000Z",
git: { available: false, unavailableReason: "git_unavailable" },
},
}),
);
const res = await request(app)
.get("/health")
.set("X-Paperclip-Dev-Server-Status-Token", "dev-runner-token");
expect(res.status).toBe(200);
expect(res.body).toEqual({
status: "ok",
deploymentMode: "authenticated",
deploymentExposure: "private",
commit: null,
bootstrapStatus: "ready",
bootstrapInviteActive: false,
devServer: {
enabled: true,
restartRequired: true,
reason: "backend_changes",
lastChangedAt: "2026-03-20T12:00:00.000Z",
changedPathCount: 1,
changedPathsSample: ["server/src/routes/health.ts"],
pendingMigrations: [],
autoRestartEnabled: true,
activeRunCount: 0,
waitingForIdle: false,
lastRestartAt: "2026-03-20T11:30:00.000Z",
},
});
} finally {
if (previousFile === undefined) {
delete process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
} else {
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = previousFile;
}
if (previousToken === undefined) {
delete process.env.PAPERCLIP_DEV_SERVER_STATUS_TOKEN;
} else {
process.env.PAPERCLIP_DEV_SERVER_STATUS_TOKEN = previousToken;
}
}
});
});
describe("POST /health/dev-server/restart", () => {
it("records a manual restart request for the dev runner", async () => {
const previousFile = process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = createDevServerStatusFile({
dirty: true,
lastChangedAt: "2026-03-20T12:00:00.000Z",
changedPathCount: 1,
changedPathsSample: ["server/src/routes/health.ts"],
pendingMigrations: [],
lastRestartAt: "2026-03-20T11:30:00.000Z",
});
try {
const app = express();
app.use("/health", healthRoutes(undefined));
const res = await request(app).post("/health/dev-server/restart");
expect(res.status).toBe(202);
expect(res.body).toEqual({ status: "restart_requested" });
const requestPath = path.join(
path.dirname(process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE),
"dev-server-restart-request.json",
);
expect(existsSync(requestPath)).toBe(true);
expect(JSON.parse(readFileSync(requestPath, "utf8"))).toMatchObject({
reason: "manual_restart_now",
});
} finally {
if (previousFile === undefined) {
delete process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
} else {
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = previousFile;
}
}
});
it("rejects unauthenticated manual restarts in authenticated mode", async () => {
const previousFile = process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = createDevServerStatusFile({
dirty: true,
changedPathCount: 1,
changedPathsSample: ["server/src/routes/health.ts"],
pendingMigrations: [],
});
try {
const app = express();
app.use((req, _res, next) => {
(req as any).actor = { type: "none", source: "none" };
next();
});
app.use(
"/health",
healthRoutes(undefined, {
deploymentMode: "authenticated",
deploymentExposure: "private",
authReady: true,
companyDeletionEnabled: true,
}),
);
const res = await request(app).post("/health/dev-server/restart");
expect(res.status).toBe(403);
expect(res.body).toEqual({ error: "board_access_required" });
} finally {
if (previousFile === undefined) {
delete process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE;
} else {
process.env.PAPERCLIP_DEV_SERVER_STATUS_FILE = previousFile;
}
}
});
});