Files
PaperClipAI/packages/adapter-utils/src/github-launcher.test.ts
T
0666aff4a4 fix(workspaces): clone network repositories blobless in remote sandboxes (#23347)
## Thinking Path

> - Paperclip is the open source app people use to manage AI agents for
work
> - A Paperclip Runner task in a Cloud sandbox gets a fresh workspace:
the server clones the task's repositories into the sandbox before the
agent starts
> - The clone is a full clone, so it downloads every historical blob. A
full clone of `paperclipai/paperclip` now grows the disk by about 856
MiB
> - The Cloud sandbox wraps Git in a storage guard. The guard stops one
Git command when the net disk growth gets to 1 GiB, and the growth
includes other writers on the same disk
> - On hosted staging, the clone now stops with `stage=clone disk=full
git=storage_limit exit=75`. Paperclip records `sandbox_disk_full`, the
run fails during setup, and the task does not start. This happens more
frequently as the repository history grows
> - This pull request makes a fresh clone from a network remote blobless
(`--filter=blob:none`). The clone gets all commits and trees, but only
the file contents that the checkout needs
> - Agent commands that the managed GitHub launcher treats as local
(`git show`, `git blame`, `git log -p`, checkout) do not ask the
credential broker. In a blobless clone they can need to fetch an old
blob, which fails for a private repository without credentials. So the
launcher now gives these commands the broker credential on demand, at
most once per command
> - The benefit is that the same clone grows the disk by about 409 MiB
and takes less than half the time, so large repositories start again in
Cloud sandboxes

## Linked Issues or Issue Description

Refs #22848 (classifies the Git storage guard refusal during clone as a
full sandbox disk; this PR removes the cause of that refusal for large
histories)
Refs #22837 (moves a restore off a full reused sandbox; the clone path
in this PR is a fresh sandbox, so a new sandbox does not help)

**What happened?**
On hosted staging, Paperclip Runner runs fail before the agent starts.
The run error is `remote_workspace_operation_failed: operation=prepare
exit=1; remote_workspace_prepare_failed: stage=clone disk=full
git=storage_limit exit=75 program=git` (and the same refusal with
`operation=repository` for a secondary repository). The error code is
`sandbox_disk_full`. Between 2026-11-27 and 2026-11-30 there were 20
such failures for three different agents. The tasks used fresh
workspaces for `paperclipai/paperclip` with
`paperclipai/paperclip-cloud` as a secondary repository.

**Expected behavior**
A fresh sandbox workspace for a large repository starts without hitting
the sandbox Git storage budget.

**Steps to reproduce**
1. Run `git clone --no-hardlinks
https://github.com/paperclipai/paperclip.git` and measure the disk
growth. I measured 856 MiB (39 s).
2. Compare with the Cloud sandbox Git storage guard budget: it stops one
Git command at 1 GiB of net disk growth, and it counts other writers on
the same disk.
3. Run the same clone with `--filter=blob:none`. I measured 409 MiB (17
s).

**Paperclip version or commit**
`master` at `c737187ec7`. The hosted staging failures were on releases
`635ed5a364`, `c49e80da6c`, `629281b1e8`, `e55b475f30` and `bc98abda0c`.

**Deployment mode**
Hosted Cloud, Paperclip Runner with remote sandbox workspaces.

## What Changed

- `server/src/services/remote-workspace-transport.ts`:
- The primary workspace clone (`prepareRemoteWorkspaceDirectory`) and
the secondary repository clone (`prepareRemoteRepository`) add
`--filter=blob:none` when the repository URL is a network remote
(`https`, `http`, `ssh`, `git`, or `user@host:path`).
- The staged checkout steps after the clone (`checkout_branch`,
`checkout_ref`) use the clone's credentials. Checkout of a revision
other than the default branch can fetch missing blobs from the origin.
Without credentials, that fetch fails for a private repository. The
checks after publication still run without credentials.
- A local path or `file://` origin stays a full clone. A saved workspace
keeps only a promisor remote whose URL works on another machine, so a
partial clone of a local origin cannot be saved.
- A server that does not support filters ignores the filter and sends a
full clone, so the old behavior stays available.
- `server/src/services/remote-workspace-transport.test.ts`: a
real-subprocess regression with a history-only blob and an origin that
is reachable only through the clone credentials. It checks the blobless
clone, the fetch of an older revision's files with credentials, the full
clone of a local origin, and a save and restore of the blobless clone
after the origin is removed.
- `packages/adapter-utils/src/github-launcher.ts` (managed `git`/`gh`
launcher): a local `git` command (one that does not ask the broker since
#17886) now runs with the launcher as `GIT_ASKPASS`, when the launcher
has a broker capability and is not anonymous.
- Git calls askpass only after every credential helper declines, for
example on a lazy fetch of a missing blob from a private repository.
Askpass was not used before, so a lazy fetch failed with `could not read
Username for 'https://github.com'`.
- The launcher answers only prompts for `https://github.com` and
`https://www.github.com`. It answers `x-access-token` for the username
without the broker. For the password, it asks the broker.
- The command's launcher keeps the first broker answer in memory and
serves later prompts through a Unix socket in a private (`0700`)
temporary directory. So one command asks the broker at most once,
however many objects Git fetches. A command that fetches nothing does
not ask the broker, as before. If the socket cannot be created, each
prompt asks the broker itself.
- The recursion guard still rejects every launcher invocation inside an
operation, except an askpass prompt inside a local operation (which
holds no credential).
- I used askpass instead of a URL-scoped `credential.helper`, because a
Git wrapper that adds its own `credential.<url>.helper` reset (as the
Paperclip tools Git bundle does through `-c include.path`) is applied
after the launcher's `GIT_CONFIG_*` entries and would remove the helper.
`GIT_ASKPASS` takes priority over any `core.askPass` configuration.
- `packages/adapter-utils/src/github-launcher.test.ts`: launcher tests
with real Git. A local command runs `git credential fill` three times
for a GitHub URL. The test checks that the managed token is returned
with one broker request, that `git status` makes no request, that
another host gets no answer and no request, and both broker modes
(inherited URL and broker file). A second test checks that askpass is
set only for local commands of a connected, non-anonymous launcher, and
that the recursion guard still rejects other re-entries.
- `doc/workspace-storage.md`: a note about the blobless clone.
`doc/execution-github-identity.md`: the askpass behavior for local
commands.

## Verification

- Red: on the unfixed code, the new test fails because the clone
downloads the history-only blob (`expected [] to include '<blob>'`).
- A second red: with the filter but without credentials for the checkout
steps, the test fails with `stage=checkout_ref git=network exit=128`.
This proves that the test also covers the private-repository case.
- Green: `pnpm --filter @paperclipai/server exec vitest run
src/services/remote-workspace-transport.test.ts
src/services/remote-workspace-readonly-capture-cause.test.ts
src/services/remote-workspace-readonly-inventory-git-guard.test.ts
src/services/remote-workspace-restore-disk-full.test.ts` passes (201
tests).
- `src/services/remote-workspaces.integration.test.ts`,
`remote-workspace-lifecycle.test.ts` and
`remote-workspace-migration.test.ts` pass (347 passed, 16 skipped; the
integration file skips locally).
- `pnpm --filter @paperclipai/server typecheck` passes.
- Launcher, red/green: without the launcher change, the 3 new launcher
tests fail. With it, `src/github-launcher.test.ts` passes (44 tests).
`github-launcher.test.ts`, `github-launcher-environment.test.ts` and
`sandbox-callback-bridge.test.ts` in adapter-utils pass (175 tests).
`packages/paperclip-runner` `src/drivers/acpx/github-launcher.test.ts`
(3) and server `heartbeat-github-launchers.test.ts` (12) pass. `tsc
--noEmit` passes in `packages/adapter-utils`.
- Launcher, real private repository: I made a blobless clone of a
private GitHub repository and ran the generated launcher with a local
fake broker that returned a real GitHub token. With the old launcher,
`git show <old commit>:README.md` failed with `could not read Username
for 'https://github.com': terminal prompts disabled` / `could not fetch
<blob> from promisor remote`. With the new launcher, it printed the file
with 1 broker request. On a fresh blobless clone, `git log -p -40 --
README.md` (about 150 lazy fetches in the trace) made 1 broker request,
and `git status` made 0.
- Measurement on a Linux host: a full clone of `paperclipai/paperclip`
grows the disk by 856 MiB; a blobless clone grows it by 409 MiB.
- Not run: a live Cloud sandbox run. Hosted staging gets this change
through the normal automatic deployment. After that deployment, the
Sentry case gets a check that new fresh workspaces for this repository
start without the refusal.
- Local environment note: the tests rewrite the remote URL through
`GIT_CONFIG_COUNT`. A Git wrapper first on `PATH` that sets its own
`GIT_CONFIG_COUNT` makes the rewrite tests fail, also on `master`. I ran
the tests with the system Git first on `PATH`.

## Risks

- A blobless clone fetches file contents from the origin when an agent
command needs old blobs (for example `git log -p`, `git blame`, or a
checkout of another branch). These commands need network access and the
run's Git credentials, the same as `git fetch`. The launcher now
supplies the credential on demand (one broker request per command that
needs it). The Cloud Git storage guard already measures these lazy
downloads.
- While a local `git` command runs, a process of the same user can read
the password from the askpass socket. That user can already get the
token with `gh auth token`, so this adds no new access. The token is not
written to disk.
- A saved workspace of a blobless clone keeps its promisor remote. The
existing snapshot capture and restore support this. The new test proves
a save and restore after the origin is removed.
- Medium-low risk: the clone of a repository on a server without filter
support is unchanged (Git ignores the filter).

## Model Used

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

## 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
- [ ] I will address all Greptile and reviewer comments before
requesting merge

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: devinfoley <139239+devinfoley@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 09:14:24 +00:00

687 lines
46 KiB
TypeScript

import { execFile } from "node:child_process";
import { createServer } from "node:http";
import { mkdtemp, mkdir, readFile, realpath, writeFile, rm } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
import { afterEach, describe, expect, it } from "vitest";
import { githubBrokerEnvironment, githubLauncherSource } from "./github-launcher.js";
const exec = promisify(execFile);
const cleanups: Array<() => Promise<unknown>> = [];
afterEach(async () => { for (const cleanup of cleanups.splice(0).reverse()) await cleanup(); });
describe("managed GitHub launchers", () => {
it("uses a private interpreter without selecting Node from PATH", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-interpreter-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const managed = path.join(root, "managed"), real = path.join(root, "real");
await mkdir(managed); await mkdir(real);
const source = githubLauncherSource({ interpreterPath: process.execPath });
const defaultSource = githubLauncherSource();
expect(defaultSource.split("\n")[0]).toBe("#!/usr/bin/env node");
expect(source.split("\n")[0]).toBe(`#!${process.execPath}`);
expect(source.slice(source.indexOf("\n"))).toBe(defaultSource.slice(defaultSource.indexOf("\n")));
const launcher = path.join(managed, "git");
await writeFile(launcher, source, { mode: 0o700 });
await writeFile(path.join(real, "node"), "#!/bin/sh\nexit 126\n", { mode: 0o700 });
await writeFile(path.join(real, "git"), "#!/bin/sh\nprintf 'private interpreter works'\n", { mode: 0o700 });
const env = { ...githubBrokerEnvironment({}, { url: "", token: "" }), HOME: root,
GH_CONFIG_DIR: path.join(root, "config"), PATH: `${managed}${path.delimiter}${real}` };
expect((await exec(launcher, ["--version"], { env })).stdout).toBe("private interpreter works");
});
it.each(["", "relative/node", "/runtime/node --flag", "/runtime/node\nexit 1", "/runtime/node\0"])(
"rejects an invalid interpreter path %j", interpreterPath => {
expect(() => githubLauncherSource({ interpreterPath })).toThrow("absolute path without whitespace");
},
);
it.each([false, true])("rejects a PATH shim that re-enters the same helper before it can recurse (broker file: %s)", async brokerFile => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-recursion-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const managed = path.join(root, "managed"), shim = path.join(root, "shim"), calls = path.join(root, "calls");
await mkdir(managed); await mkdir(shim);
const launcher = path.join(managed, "git");
await writeFile(launcher, githubLauncherSource({ brokerFile }), { mode: 0o700 });
// Bound the pre-fix reproduction: the fixture stops at three invocations.
await writeFile(path.join(shim, "git"), `#!${process.execPath}
const fs = require("node:fs"), {spawnSync} = require("node:child_process");
fs.appendFileSync(${JSON.stringify(calls)}, "call\\n");
if (fs.readFileSync(${JSON.stringify(calls)}, "utf8").trim().split("\\n").length >= 3) process.exit(99);
const result = spawnSync(${JSON.stringify(launcher)}, process.argv.slice(2), {env: process.env, stdio: "inherit"});
process.exit(result.status ?? 98);
`, { mode: 0o700 });
const env = { ...process.env, ...githubBrokerEnvironment({}, {url: "", token: ""}),
PATH: `${managed}${path.delimiter}${shim}${path.delimiter}${path.dirname(process.execPath)}${path.delimiter}/usr/bin${path.delimiter}/bin` };
await expect(exec(launcher, ["--version"], {env, timeout: 5000})).rejects.toMatchObject({
code: 126, stderr: expect.stringContaining("launcher_recursion_rejected"),
});
expect((await readFile(calls, "utf8")).trim().split("\n")).toEqual(["call"]);
});
it("snapshots a staged tree and reports unstaged files without capturing GitHub credentials", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-snapshot-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed"), repo = path.join(root, "repo");
await mkdir(bin); await mkdir(repo);
await exec("git", ["init", "-q", repo]);
await writeFile(path.join(repo, "tracked.txt"), "staged contents\n");
await exec("git", ["-C", repo, "add", "tracked.txt"]);
const expectedTree = (await exec("git", ["-C", repo, "write-tree"])).stdout;
await writeFile(path.join(repo, "tracked.txt"), "unstaged contents\n");
await writeFile(path.join(bin, "git"), githubLauncherSource(), { mode: 0o700 });
let captures = 0;
const server = createServer((_req, res) => {
captures++;
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ status: "unavailable", reason: "No GitHub connection" }));
});
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
const { port } = server.address() as { port: number };
const env = { ...process.env, ...githubBrokerEnvironment({}, { url: `http://127.0.0.1:${port}`, token: "run-capability" }), PATH: `${bin}:${process.env.PATH}` };
const git = (...args: string[]) => exec(path.join(bin, "git"), args, { cwd: root, env });
const tree = await git("--git-dir", path.join(repo, ".git"), "--work-tree", repo, "write-tree");
const diff = await git("-C", repo, "-c", "core.quotepath=false", "diff-files", "--name-only", "-z", "--", ".");
expect(tree.stdout).toBe(expectedTree);
expect(diff.stdout).toBe("tracked.txt\0");
expect(captures).toBe(0);
});
it.each(["missing", "absent", "unavailable", "rejected"])("commits local work without an identity when GitHub access is %s", async (access) => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-default-author-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed");
await mkdir(bin);
await exec("git", ["init", root]);
await writeFile(path.join(bin, "git"), githubLauncherSource(), { mode: 0o700 });
const server = createServer((_req, res) => {
res.writeHead(access === "rejected" ? 403 : 200, { "content-type": "application/json" });
res.end(JSON.stringify({ status: access, env: {
GH_TOKEN: "rejected-token", GIT_AUTHOR_NAME: "Rejected", GIT_AUTHOR_EMAIL: "rejected@example.test",
GIT_COMMITTER_NAME: "Rejected", GIT_COMMITTER_EMAIL: "rejected@example.test",
} }));
});
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
const { port } = server.address() as { port: number };
const env = { ...process.env, ...githubBrokerEnvironment({
GH_TOKEN: "host-token", GIT_AUTHOR_NAME: "Host", GIT_AUTHOR_EMAIL: "host@example.test",
GIT_COMMITTER_NAME: "Host", GIT_COMMITTER_EMAIL: "host@example.test",
}, { url: `http://127.0.0.1:${port}`, token: access === "missing" ? "" : "run-capability" }),
PATH: `${bin}:${process.env.PATH}` };
await writeFile(path.join(root, "work.txt"), "saved work\n");
await exec(path.join(bin, "git"), ["add", "work.txt"], { cwd: root, env });
await exec(path.join(bin, "git"), ["commit", "-m", "Save local work"], { cwd: root, env });
expect((await exec("git", ["-C", root, "log", "-1", "--format=%an <%ae>|%cn <%ce>"])).stdout.trim())
.toBe("Paperclip <noreply@paperclip.ing>|Paperclip <noreply@paperclip.ing>");
expect((await exec("git", ["-C", root, "show", "HEAD:work.txt"])).stdout).toBe("saved work\n");
await expect(exec("git", ["-C", root, "config", "--local", "--get", "user.name"])).rejects.toThrow();
await expect(exec("git", ["-C", root, "config", "--local", "--get", "user.email"])).rejects.toThrow();
});
it.each(["repository", "command"])("uses explicit %s identity for local commits without managed credentials", async (identitySource) => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-local-identity-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed");
await mkdir(bin);
await exec("git", ["init", root]);
await writeFile(path.join(bin, "git"), githubLauncherSource(), { mode: 0o700 });
const env = { ...process.env, ...githubBrokerEnvironment({
GH_TOKEN: "host-token", GIT_AUTHOR_NAME: "Host", GIT_COMMITTER_NAME: "Host",
}, { url: "", token: "" }), PATH: `${bin}:${process.env.PATH}` };
const git = async (...args: string[]) => (await exec(path.join(bin, "git"), args, { cwd: root, env })).stdout.trim();
expect(await git("var", "GIT_AUTHOR_IDENT")).toMatch(/^Paperclip <noreply@paperclip.ing>/);
expect(await git("var", "GIT_COMMITTER_IDENT")).toMatch(/^Paperclip <noreply@paperclip.ing>/);
if (identitySource === "repository") {
await git("config", "user.name", "Local Author");
await git("config", "user.email", "local@example.test");
}
await git(...(identitySource === "command" ? ["-c", "user.name=Local Author", "-c", "user.email=local@example.test"] : []),
"commit", "--allow-empty", "-m", "Local work");
expect(await git("log", "-1", "--format=%an <%ae>|%cn <%ce>"))
.toBe("Local Author <local@example.test>|Local Author <local@example.test>");
});
it.each(["broker-offline", "config-unwritable", "capability-rejected"])("keeps real local Git usable when %s", async (failure) => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-failure-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed");
await mkdir(bin);
await exec("git", ["init", root]);
await exec("git", ["-C", root, "config", "user.name", "Local Author"]);
await exec("git", ["-C", root, "config", "user.email", "local@example.test"]);
await writeFile(path.join(bin, "git"), githubLauncherSource(), { mode: 0o700 });
const server = createServer((_req, res) => { res.writeHead(403); res.end(); });
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
const { port } = server.address() as { port: number };
if (failure === "broker-offline") await new Promise<void>(resolve => server.close(() => resolve()));
else cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
const configRoot = path.join(root, "config");
if (failure === "config-unwritable") await writeFile(configRoot, "not a directory");
const result = await exec(path.join(bin, "git"), ["remote"], { cwd: root, env: {
...process.env, ...githubBrokerEnvironment({ GH_TOKEN: "host-must-not-leak" }, { url: `http://127.0.0.1:${port}`, token: "private-capability" }),
GH_CONFIG_DIR: configRoot, PATH: `${bin}:${process.env.PATH}`,
} });
expect(result.stderr).toContain(failure === "broker-offline" ? "broker_transport_unavailable" : failure === "config-unwritable" ? "configuration_directory_unavailable" : "capability_rejected");
expect(result.stderr).not.toMatch(/host-must-not-leak|private-capability/);
await exec(path.join(bin, "git"), ["commit", "--allow-empty", "-m", "Offline work"], { cwd: root, env: {
...process.env, ...githubBrokerEnvironment({}, { url: `http://127.0.0.1:${port}`, token: "private-capability" }),
GH_CONFIG_DIR: configRoot, PATH: `${bin}:${process.env.PATH}`,
} });
}, 15_000); // broker-offline retries the transport twice per command before it falls back
it("explains unavailable access while allowing local work without credentials", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-diagnostic-"));
cleanups.push(() => rm(root, {recursive:true,force:true}));
const bin = path.join(root,"managed"), realBin = path.join(root,"real");
await mkdir(bin); await mkdir(realBin);
await writeFile(path.join(bin,"gh"), githubLauncherSource(), {mode:0o700});
await writeFile(path.join(realBin,"gh"), '#!/usr/bin/env node\nprocess.stdout.write(JSON.stringify({token:process.env.GH_TOKEN ?? null}));', {mode:0o700});
const server = createServer((_req,res) => {
res.setHeader("content-type","application/json");
res.end(JSON.stringify({status:"unavailable",reason:"More than one managed GitHub identity matches this run",env:{GH_TOKEN:"must-not-be-used"}}));
});
await new Promise<void>(resolve => server.listen(0,"127.0.0.1",resolve));
cleanups.push(() => new Promise<void>((resolve,reject) => server.close(error => error ? reject(error) : resolve())));
const {port} = server.address() as {port:number};
const result = await exec(path.join(bin,"gh"), [], {env:{...process.env,...githubBrokerEnvironment({GH_TOKEN:"host-token"},{url:`http://127.0.0.1:${port}`,token:"run-capability"}),PATH:`${bin}:${realBin}:${process.env.PATH}`}});
expect(JSON.parse(result.stdout)).toEqual({token:null});
expect(result.stderr).toContain("More than one managed GitHub identity matches this run");
expect(result.stderr).not.toMatch(/host-token|must-not-be-used|run-capability/);
});
it("sends repository creation and forks to the connection's tools when a connection is in use", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-repository-tools-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed"), realBin = path.join(root, "real");
await mkdir(bin); await mkdir(realBin);
await writeFile(path.join(bin, "gh"), githubLauncherSource(), { mode: 0o700 });
await writeFile(path.join(realBin, "gh"), '#!/usr/bin/env node\nprocess.stdout.write(JSON.stringify({args:process.argv.slice(2),token:process.env.GH_TOKEN ?? null}));', { mode: 0o700 });
let status = "available";
const server = createServer((_req, res) => {
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ status, env: { GH_TOKEN: "managed-token" } }));
});
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
const { port } = server.address() as { port: number };
const env = { ...process.env, ...githubBrokerEnvironment({}, { url: `http://127.0.0.1:${port}`, token: "run-capability" }),
PATH: `${bin}:${realBin}:${process.env.PATH}` };
const gh = (...args: string[]) => exec(path.join(bin, "gh"), args, { env });
for (const [args, tool] of [
[["repo", "create", "demo", "--private"], "create_repository"],
[["repo", "new", "demo"], "create_repository"],
[["repo", "fork", "octo-org/tools", "--org", "acme"], "fork_repository"],
] as const) {
const failure = await gh(...args).catch((error: { code?: number; stdout?: string; stderr?: string }) => error);
expect(failure).toMatchObject({ code: 1, stdout: "" });
expect(failure.stderr).toContain(`GitHub connection's ${tool} tool`);
expect(failure.stderr).not.toContain("managed-token");
}
expect(JSON.parse((await gh("repo", "create", "--help")).stdout))
.toEqual({ args: ["repo", "create", "--help"], token: "managed-token" });
expect(JSON.parse((await gh("repo", "view", "octo-org/tools")).stdout))
.toEqual({ args: ["repo", "view", "octo-org/tools"], token: "managed-token" });
// Without a connection there are no connection tools; gh runs unchanged.
status = "absent";
expect(JSON.parse((await gh("repo", "create", "demo")).stdout)).toEqual({ args: ["repo", "create", "demo"], token: null });
});
it.each(["before-write", "partial-write"])("keeps Git and managed credentials available after a %s failure", async (failure) => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-default-write-failure-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed"), realBin = path.join(root, "real");
await mkdir(bin); await mkdir(realBin);
await exec("git", ["init", root]);
for (const name of ["git", "gh"]) await writeFile(path.join(bin, name), githubLauncherSource(), { mode: 0o700 });
await writeFile(path.join(realBin, "gh"), '#!/usr/bin/env node\nprocess.stdout.write(process.env.GH_TOKEN || "anonymous");', { mode: 0o700 });
const fault = path.join(root, "write-fault.cjs");
await writeFile(fault, `const fs = require('node:fs'); const write = fs.writeFileSync;
fs.writeFileSync = (file, ...args) => {
if (String(file).endsWith('/gitconfig')) {
if (${failure === "partial-write"}) write(file, '[user', { mode: 0o600 });
throw new Error('fixture disk full');
}
return write(file, ...args);
};`);
const server = createServer((_req, res) => {
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ status: "available", env: { GH_TOKEN: "managed-token" } }));
});
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
const { port } = server.address() as { port: number };
const env = {
...process.env, ...githubBrokerEnvironment({}, { url: `http://127.0.0.1:${port}`, token: "run-capability" }),
PATH: `${bin}:${realBin}:${process.env.PATH}`,
};
const result = await exec(process.execPath, ["--require", fault, path.join(bin, "gh")], { cwd: root, env });
expect(result.stdout).toBe("managed-token");
expect(result.stderr).toContain("configuration_directory_unavailable");
const git = (...args: string[]) => exec(process.execPath, ["--require", fault, path.join(bin, "git"), ...args], { cwd: root, env });
expect((await git("status", "--porcelain", "--untracked-files=no")).stdout).toBe("");
await expect(git("commit", "--allow-empty", "-m", "No default")).rejects.toMatchObject({ stderr: expect.stringContaining("Author identity unknown") });
await git("-c", "user.name=Explicit", "-c", "user.email=explicit@example.test", "commit", "--allow-empty", "-m", "Explicit identity");
expect((await exec("git", ["-C", root, "log", "-1", "--format=%an <%ae>|%cn <%ce>"])).stdout.trim())
.toBe("Explicit <explicit@example.test>|Explicit <explicit@example.test>");
});
// The first broker request fails, the second succeeds: the managed token must still reach gh.
it.each([
["connection drops before the response", (res: import("node:http").ServerResponse) => { res.socket?.destroy(); }],
["body read fails mid-response", (res: import("node:http").ServerResponse) => {
res.writeHead(200, {"content-type":"application/json"}); res.write('{"status":'); setTimeout(() => res.socket?.destroy(), 20);
}],
])("retries when the %s and still uses managed credentials", async (_label, fail) => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-retry-"));
cleanups.push(() => rm(root, {recursive:true,force:true}));
const bin = path.join(root,"managed"), realBin = path.join(root,"real");
await mkdir(bin); await mkdir(realBin);
await writeFile(path.join(bin,"gh"), githubLauncherSource(), {mode:0o700});
await writeFile(path.join(realBin,"gh"), '#!/usr/bin/env node\nprocess.stdout.write(JSON.stringify({token:process.env.GH_TOKEN ?? null}));', {mode:0o700});
let requests = 0;
const server = createServer((_req,res) => {
requests++;
if (requests === 1) return fail(res);
res.setHeader("content-type","application/json");
res.end(JSON.stringify({status:"available",env:{GH_TOKEN:"managed-token"}}));
});
await new Promise<void>(resolve => server.listen(0,"127.0.0.1",resolve));
cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
const {port} = server.address() as {port:number};
const result = await exec(path.join(bin,"gh"), [], {env:{...process.env,...githubBrokerEnvironment({GH_TOKEN:"host-token"},{url:`http://127.0.0.1:${port}`,token:"run-capability"}),PATH:`${bin}:${realBin}:${process.env.PATH}`}});
expect(JSON.parse(result.stdout)).toEqual({token:"managed-token"});
expect(requests).toBe(2);
expect(result.stderr).not.toContain("broker_transport_unavailable");
expect(result.stderr).not.toMatch(/host-token|run-capability/);
});
it("captures each command's identity and clears host credentials when the next person has none", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-launcher-test-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed"), realBin = path.join(root, "real"), repo = path.join(root, "repo");
for (const dir of [bin, realBin, repo, path.join(bin, "gh-config")]) await mkdir(dir, { recursive: true });
for (const name of ["git", "gh"]) await writeFile(path.join(bin, name), githubLauncherSource(), { mode: 0o700 });
await writeFile(path.join(realBin, "gh"), `#!/usr/bin/env node
const {execFileSync}=require('node:child_process');
const identity=execFileSync('git',['var','GIT_AUTHOR_IDENT'],{encoding:'utf8'}).trim();
process.stdout.write(JSON.stringify({identity, token:process.env.GH_TOKEN ?? null, global:process.env.GIT_CONFIG_GLOBAL, config:process.env.GH_CONFIG_DIR}));
`, { mode: 0o700 });
let user: string | null = "A", captures = 0;
let heldCapture: (() => void) | null = null;
let releaseCapture: (() => void) | null = null;
const server = createServer((req, res) => {
captures++;
expect(req.headers.authorization).toBe("Bearer run-capability");
const selected = user;
res.setHeader("content-type", "application/json");
const finish = () => res.end(JSON.stringify(selected ? { status: "available", env: {
GH_TOKEN: `credential-${selected}`, GITHUB_TOKEN: `credential-${selected}`,
GIT_AUTHOR_NAME: selected, GIT_AUTHOR_EMAIL: `${selected}@example.test`,
GIT_COMMITTER_NAME: selected, GIT_COMMITTER_EMAIL: `${selected}@example.test`,
} } : { status: "absent", env: {} }));
if (heldCapture) { const captured = heldCapture; heldCapture = null; releaseCapture = finish; captured(); }
else finish();
});
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>((resolve, reject) => server.close(error => error ? reject(error) : resolve())));
const address = server.address() as { port: number };
const env: NodeJS.ProcessEnv = { ...process.env, ...githubBrokerEnvironment({
GH_TOKEN: "ambient-host-token", GIT_AUTHOR_NAME: "Host", GIT_AUTHOR_EMAIL: "host@example.test",
}, { url: `http://127.0.0.1:${address.port}`, token: "run-capability" }), PATH: `${bin}:${realBin}:${process.env.PATH}` };
const git = async (...args: string[]) => (await exec(path.join(bin, "git"), args, { cwd: repo, env })).stdout.trim();
await git("init");
await git("config", "user.name", "Repository Author");
await git("config", "user.email", "repository@example.test");
await git("commit", "--allow-empty", "-m", "A");
user = "B";
await git("commit", "--allow-empty", "-m", "B");
user = "A";
await git("commit", "--allow-empty", "-m", "A again");
expect(await git("log", "--format=%an <%ae>|%cn <%ce>" )).toBe("A <A@example.test>|A <A@example.test>\nB <B@example.test>|B <B@example.test>\nA <A@example.test>|A <A@example.test>");
const before = captures;
const gh = JSON.parse((await exec(path.join(bin, "gh"), [], { cwd: repo, env })).stdout);
expect(gh.identity).toContain("A <A@example.test>");
expect(gh.token).toBe("credential-A");
expect(captures - before).toBe(1); // gh's child Git retains the same capture.
const captured = new Promise<void>(resolve => { heldCapture = resolve; });
const operationA = exec(path.join(bin, "gh"), [], { cwd: repo, env });
await captured;
user = "B";
const operationB = JSON.parse((await exec(path.join(bin, "gh"), [], { cwd: repo, env })).stdout);
releaseCapture!();
const completedA = JSON.parse((await operationA).stdout);
expect(completedA.token).toBe("credential-A");
expect(operationB.token).toBe("credential-B");
expect(completedA.config).not.toBe(operationB.config);
user = null;
await git("commit", "--allow-empty", "-m", "Local identity");
expect(await git("log", "-1", "--format=%an <%ae>|%cn <%ce>"))
.toBe("Repository Author <repository@example.test>|Repository Author <repository@example.test>");
const anonymous = JSON.parse((await exec(path.join(bin, "gh"), [], { cwd: repo, env })).stdout);
expect(anonymous.token).toBeNull();
await git("config", "--unset", "user.name");
await git("config", "--unset", "user.email");
await git("commit", "--allow-empty", "-m", "Default identity after revocation");
expect(await git("log", "-1", "--format=%an <%ae>|%cn <%ce>"))
.toBe("Paperclip <noreply@paperclip.ing>|Paperclip <noreply@paperclip.ing>");
expect(await git("status", "--porcelain")).toBe(""); // unrelated public/local Git still works
expect(env.GH_TOKEN).toBe("");
expect(env.GIT_AUTHOR_NAME).toBe("");
});
it("keeps local Git commands off the broker and still asks for the rest", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-local-skip-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed");
await mkdir(bin);
await writeFile(path.join(bin, "git"), githubLauncherSource(), { mode: 0o700 });
let posts = 0;
const server = createServer((_req, res) => {
posts++;
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ status: "available", env: {
GH_TOKEN: "managed-token", GIT_AUTHOR_NAME: "Managed", GIT_AUTHOR_EMAIL: "managed@example.test",
GIT_COMMITTER_NAME: "Managed", GIT_COMMITTER_EMAIL: "managed@example.test",
} }));
});
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
const { port } = server.address() as { port: number };
const env = { ...process.env, ...githubBrokerEnvironment({}, { url: `http://127.0.0.1:${port}`, token: "run-capability" }), PATH: `${bin}:${process.env.PATH}` };
const git = async (...args: string[]) => {
const before = posts;
const { stdout } = await exec(path.join(bin, "git"), args, { cwd: root, env }).catch(() => ({ stdout: "" }));
return { stdout: stdout.trim(), posts: posts - before };
};
for (const args of [
["init", "-q", "repo"],
["-C", "repo", "status", "--short"],
["-C", "repo", "-c", "core.quotepath=off", "--no-pager", "diff"],
["--git-dir=repo/.git", "rev-parse", "--git-dir"],
["--git-dir", "repo/.git", "--work-tree", "repo", "status"],
["-C", "repo", "config", "user.useConfigOnly"],
["--version"],
]) expect((await git(...args)).posts, args.join(" ")).toBe(0);
expect((await git("-C", "repo", "config", "user.useConfigOnly")).stdout).toBe("true");
for (const args of [
["-C", "repo", "remote"],
["-C", "repo", "var", "GIT_AUTHOR_IDENT"],
["-C", "repo", "fetch", "--dry-run"],
["-C", "repo", "-c", "alias.noop=!true", "noop"],
["-C", "repo", "--unknown-option", "status"],
["-C"],
]) expect((await git(...args)).posts, args.join(" ")).toBe(1);
expect((await git("-C", "repo", "var", "GIT_AUTHOR_IDENT")).stdout).toMatch(/^Managed <managed@example.test>/);
expect((await git("-C", "repo", "commit", "--allow-empty", "-m", "Managed work")).posts).toBe(1);
expect((await git("-C", "repo", "log", "-1", "--format=%an <%ae>")).stdout).toBe("Managed <managed@example.test>");
}, 20_000);
it.each([false, true])("lets a local git command fetch a private object with the managed credential only when Git asks (broker file: %s)", async brokerFile => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-lazy-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
// Git runs GIT_ASKPASS without a shell, so a quote and space in the path are safe.
const bin = path.join(root, "it's managed"), realBin = path.join(root, "real");
await mkdir(bin); await mkdir(realBin);
const realGit = (await exec("sh", ["-c", "command -v git"])).stdout.trim();
// Stands in for partial-clone lazy fetches: each one makes the real Git
// child ask for credentials for a URL. Other commands run real Git.
await writeFile(path.join(realBin, "git"), `#!${process.execPath}
const {spawnSync} = require("node:child_process");
const args = process.argv.slice(2);
if (args[0] === "show") {
const host = args[1] || "github.com";
const fetches = Array.from({length: Number(args[2] || 1)}, () => spawnSync(${JSON.stringify(realGit)}, ["credential", "fill"], {env: process.env,
input: "protocol=https\\nhost=" + host + "\\npath=org/private.git\\n\\n", encoding: "utf8"}));
process.stdout.write(JSON.stringify({status: Math.max(...fetches.map(result => result.status)), stdout: fetches.map(result => result.stdout),
operation: process.env.PAPERCLIP_GITHUB_OPERATION_ACTIVE, token: process.env.PAPERCLIP_GIT_TOKEN ?? null}));
process.exit(0);
}
process.exit(spawnSync(${JSON.stringify(realGit)}, args, {stdio: "inherit"}).status ?? 1);
`, { mode: 0o700 });
await writeFile(path.join(bin, "git"), githubLauncherSource({ brokerFile }), { mode: 0o700 });
let posts = 0;
const server = createServer((_req, res) => {
posts++;
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ status: "available", env: { PAPERCLIP_GIT_TOKEN: "managed-token", GH_TOKEN: "managed-token" } }));
});
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
const { port } = server.address() as { port: number };
const broker = { url: `http://127.0.0.1:${port}`, token: "run-capability" };
if (brokerFile) await writeFile(path.join(bin, "broker.json"), JSON.stringify(broker), { mode: 0o600 });
const env = { ...process.env, ...githubBrokerEnvironment({}, brokerFile ? { url: "", token: "" } : broker),
GH_CONFIG_DIR: path.join(root, "config"), PATH: `${bin}${path.delimiter}${realBin}${path.delimiter}${process.env.PATH}` };
const git = async (...args: string[]) => (await exec(path.join(bin, "git"), args, { cwd: root, env, timeout: 10_000 })).stdout;
await exec(realGit, ["init", "-q", root]);
await git("status", "--porcelain");
expect(posts).toBe(0);
// One operation asks the broker once, however many objects it fetches.
const fetched = JSON.parse(await git("show", "github.com", "3"));
expect(fetched).toMatchObject({ status: 0, operation: "local", token: null });
expect(fetched.stdout).toEqual(Array(3).fill("protocol=https\nhost=github.com\nusername=x-access-token\npassword=managed-token\n"));
expect(posts).toBe(1);
expect(JSON.parse(await git("show")).stdout).toEqual(["protocol=https\nhost=github.com\nusername=x-access-token\npassword=managed-token\n"]);
expect(posts).toBe(2);
// Another host gets no answer and causes no broker request.
const other = JSON.parse(await git("show", "example.test"));
expect(other.status).not.toBe(0);
expect(other.stdout).toEqual([""]);
expect(posts).toBe(2);
await expect(exec(path.join(bin, "git"), ["Password for 'https://x-access-token@github.com.example.test': "],
{ env: { ...env, PAPERCLIP_GITHUB_OPERATION_ACTIVE: "local" } })).rejects.toMatchObject({ code: 1, stdout: "" });
expect(posts).toBe(2);
}, 20_000);
it("gives Git the launcher as askpass only for local commands of a connected launcher", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-lazy-scope-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed"), anonymousBin = path.join(root, "anonymous"), realBin = path.join(root, "real");
await mkdir(bin); await mkdir(anonymousBin); await mkdir(realBin);
await writeFile(path.join(bin, "git"), githubLauncherSource(), { mode: 0o700 });
await writeFile(path.join(anonymousBin, "git"), githubLauncherSource({ anonymous: true }), { mode: 0o700 });
await writeFile(path.join(realBin, "git"), `#!${process.execPath}
process.stdout.write(JSON.stringify({askpass: process.env.GIT_ASKPASS ?? null, operation: process.env.PAPERCLIP_GITHUB_OPERATION_ACTIVE}));
`, { mode: 0o700 });
const server = createServer((_req, res) => {
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ status: "available", env: { PAPERCLIP_GIT_TOKEN: "managed-token" } }));
});
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
const { port } = server.address() as { port: number };
const base = { ...process.env, ...githubBrokerEnvironment({}, { url: `http://127.0.0.1:${port}`, token: "run-capability" }) };
const run = async (launcherBin: string, args: string[], extra: Record<string, string> = {}) => JSON.parse((await exec(
path.join(launcherBin, "git"), args, { cwd: root, env: { ...base, ...extra,
PATH: `${launcherBin}${path.delimiter}${realBin}${path.delimiter}${process.env.PATH}` } })).stdout);
expect(await run(bin, ["show"])).toEqual({ askpass: path.join(await realpath(bin), "git"), operation: "local" });
expect(await run(bin, ["fetch"])).toEqual({ askpass: null, operation: "1" });
expect(await run(anonymousBin, ["show"])).toEqual({ askpass: null, operation: "local" });
expect(await run(bin, ["show"], { PAPERCLIP_GITHUB_BROKER_TOKEN: "" })).toEqual({ askpass: null, operation: "local" });
// Only a prompt inside a local operation, which holds no credential, may run the launcher again.
for (const [operation, args] of [["1", ["Password for 'https://x-access-token@github.com': "]], ["local", ["show"]],
["local", ["Password for 'https://github.com': ", "extra"]]] as const) {
await expect(exec(path.join(bin, "git"), [...args], { env: { ...base, PAPERCLIP_GITHUB_OPERATION_ACTIVE: operation,
PATH: `${bin}${path.delimiter}${realBin}${path.delimiter}${process.env.PATH}` } }))
.rejects.toMatchObject({ code: 126, stderr: expect.stringContaining("launcher_recursion_rejected") });
}
});
});
it("captures the current task broker file once per invocation and never falls back to inherited authority", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-task-github-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed"), real = path.join(root, "real");
await mkdir(bin); await mkdir(real);
await writeFile(path.join(bin, "gh"), githubLauncherSource({ brokerFile: true }), { mode: 0o700 });
await writeFile(path.join(real, "gh"), '#!/usr/bin/env node\nprocess.stdout.write(process.env.GH_TOKEN || "anonymous");\n', { mode: 0o700 });
const captured: string[] = [];
const server = createServer((req, res) => {
captured.push(req.headers.authorization!);
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ status: "available", env: { GH_TOKEN: req.headers.authorization!.slice(7) + "-credential" } }));
});
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
const url = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
const env = { ...process.env, PATH: `${bin}:${real}:${process.env.PATH}`, GH_TOKEN: "ambient-secret",
PAPERCLIP_GITHUB_BROKER_URL: url, PAPERCLIP_GITHUB_BROKER_TOKEN: "stale-capability", PAPERCLIP_API_KEY: "unrelated-api-key" };
const run = () => exec(path.join(bin, "gh"), [], { env });
for (const token of ["first-run", "next-run"]) {
await writeFile(path.join(bin, "broker.json"), JSON.stringify({ url, token }));
expect((await run()).stdout).toBe(token + "-credential");
}
await rm(path.join(bin, "broker.json"));
expect((await run()).stdout).toBe("anonymous");
expect(captured).toEqual(["Bearer first-run", "Bearer next-run"]);
});
// A control-plane restart stops the task's broker while its provider keeps
// running. The replacement broker is published to broker.json a few seconds later.
// An HTTP/2 gateway can outlive its controller and answer 503 instead of refusing.
// The replacement file can also be read while it is only partly written.
it.each(["closed port", "bridge unavailable", "partly written broker file"])(
"waits for a replacement task broker instead of running without credentials (%s)", async (outage) => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-task-github-outage-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed"), real = path.join(root, "real");
await mkdir(bin); await mkdir(real);
await writeFile(path.join(bin, "gh"), githubLauncherSource({ brokerFile: true }), { mode: 0o700 });
await writeFile(path.join(real, "gh"), '#!/usr/bin/env node\nprocess.stdout.write(process.env.GH_TOKEN || "anonymous");\n', { mode: 0o700 });
const stopped = createServer((_req, res) => {
res.writeHead(503, { "content-type": "application/json" });
res.end(JSON.stringify({ error: "bridge_unavailable" }));
});
await new Promise<void>(resolve => stopped.listen(0, "127.0.0.1", resolve));
const stoppedUrl = `http://127.0.0.1:${(stopped.address() as { port: number }).port}`;
if (outage === "bridge unavailable") cleanups.push(() => new Promise<void>(resolve => stopped.close(() => resolve())));
else await new Promise<void>(resolve => stopped.close(() => resolve()));
const replacement = createServer((req, res) => {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ status: "available", env: { GH_TOKEN: req.headers.authorization!.slice(7) + "-credential" } }));
});
await new Promise<void>(resolve => replacement.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>(resolve => replacement.close(() => resolve())));
const replacementUrl = `http://127.0.0.1:${(replacement.address() as { port: number }).port}`;
await writeFile(path.join(bin, "broker.json"), JSON.stringify({ url: stoppedUrl, token: "stopped-run" }));
const operation = exec(path.join(bin, "gh"), [], { env: { ...process.env, PATH: `${bin}:${real}:${process.env.PATH}` } });
if (outage === "partly written broker file") {
await new Promise(resolve => setTimeout(resolve, 1000));
await writeFile(path.join(bin, "broker.json"), '{"url":');
}
await new Promise(resolve => setTimeout(resolve, outage === "partly written broker file" ? 2000 : 3000));
await writeFile(path.join(bin, "broker.json"), JSON.stringify({ url: replacementUrl, token: "reattached-run" }));
const result = await operation;
expect(result.stdout).toBe("reattached-run-credential");
expect(result.stderr).not.toContain("continuing without managed credentials");
expect(result.stderr).not.toMatch(/stopped-run|reattached-run/);
}, 20_000);
// A failed replacement bridge publishes empty broker values instead of removing the file.
it.each(["removed", "emptied"])("stops waiting for an unreachable task broker once its broker file is %s", async (ending) => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-task-github-ended-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed"), real = path.join(root, "real");
await mkdir(bin); await mkdir(real);
await writeFile(path.join(bin, "gh"), githubLauncherSource({ brokerFile: true }), { mode: 0o700 });
await writeFile(path.join(real, "gh"), '#!/usr/bin/env node\nprocess.stdout.write(process.env.GH_TOKEN || "anonymous");\n', { mode: 0o700 });
const stopped = createServer();
await new Promise<void>(resolve => stopped.listen(0, "127.0.0.1", resolve));
const stoppedUrl = `http://127.0.0.1:${(stopped.address() as { port: number }).port}`;
await new Promise<void>(resolve => stopped.close(() => resolve()));
await writeFile(path.join(bin, "broker.json"), JSON.stringify({ url: stoppedUrl, token: "ended-run" }));
const started = Date.now();
const operation = exec(path.join(bin, "gh"), [], { env: { ...process.env, PATH: `${bin}:${real}:${process.env.PATH}` } });
await new Promise(resolve => setTimeout(resolve, 2500));
if (ending === "removed") await rm(path.join(bin, "broker.json"));
else await writeFile(path.join(bin, "broker.json"), JSON.stringify({ url: "", token: "" }));
const result = await operation;
expect(result.stdout).toBe("anonymous");
expect(result.stderr).toContain("broker_transport_unavailable");
expect(Date.now() - started).toBeLessThan(10_000);
}, 20_000);
it.each([401, 403])("does not wait when the task broker denies the capability (%s)", async (status) => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-task-github-denied-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed"), real = path.join(root, "real");
await mkdir(bin); await mkdir(real);
await writeFile(path.join(bin, "gh"), githubLauncherSource({ brokerFile: true }), { mode: 0o700 });
await writeFile(path.join(real, "gh"), '#!/usr/bin/env node\nprocess.stdout.write(process.env.GH_TOKEN || "anonymous");\n', { mode: 0o700 });
let requests = 0;
const server = createServer((_req, res) => { requests++; res.writeHead(status); res.end(); });
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
const url = `http://127.0.0.1:${(server.address() as { port: number }).port}`;
await writeFile(path.join(bin, "broker.json"), JSON.stringify({ url, token: "denied-run" }));
const started = Date.now();
const result = await exec(path.join(bin, "gh"), [], { env: { ...process.env, PATH: `${bin}:${real}:${process.env.PATH}` } });
expect(result.stdout).toBe("anonymous");
expect(result.stderr).toContain("capability_rejected");
expect(requests).toBe(1);
expect(Date.now() - started).toBeLessThan(3000);
});
it("keeps intentionally anonymous launchers silent on git and gh operations while isolating ambient credentials", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-anonymous-silent-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed"), real = path.join(root, "real"), repo = path.join(root, "repo");
await mkdir(bin); await mkdir(real);
await exec("git", ["init", "-q", repo]);
for (const name of ["git", "gh"]) {
await writeFile(path.join(bin, name), githubLauncherSource({ anonymous: true }), { mode: 0o700 });
}
await writeFile(path.join(real, "gh"), '#!/usr/bin/env node\nprocess.stdout.write(process.env.GH_TOKEN || "anonymous");\n', { mode: 0o700 });
const env = { ...process.env, ...githubBrokerEnvironment({
GH_TOKEN: "ambient-secret", GIT_AUTHOR_NAME: "Ambient", GIT_AUTHOR_EMAIL: "ambient@example.test",
}, { url: "", token: "" }), PATH: `${bin}:${real}:${process.env.PATH}` };
const ghResult = await exec(path.join(bin, "gh"), ["auth", "status"], { env });
expect(ghResult.stdout).toBe("anonymous");
expect(ghResult.stderr).toBe("");
const commitResult = await exec(path.join(bin, "git"), ["-C", repo, "commit", "--allow-empty", "-qm", "Anonymous local work"], { env });
expect(commitResult.stderr).toBe("");
expect((await exec("git", ["-C", repo, "log", "-1", "--format=%an <%ae>"])).stdout.trim()).toBe("Paperclip <noreply@paperclip.ing>");
});
it("keeps broker-file launchers silent only when broker.json explicitly marks anonymous mode", async () => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-task-github-anonymous-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed"), real = path.join(root, "real");
await mkdir(bin); await mkdir(real);
await writeFile(path.join(bin, "gh"), githubLauncherSource({ brokerFile: true }), { mode: 0o700 });
await writeFile(path.join(real, "gh"), '#!/usr/bin/env node\nprocess.stdout.write(process.env.GH_TOKEN || "anonymous");\n', { mode: 0o700 });
const env = { ...process.env, PATH: `${bin}:${real}:${process.env.PATH}`, GH_TOKEN: "ambient-secret" };
await writeFile(path.join(bin, "broker.json"), JSON.stringify({ anonymous: true, url: "", token: "" }));
const anonymousResult = await exec(path.join(bin, "gh"), ["auth", "status"], { env });
expect(anonymousResult.stdout).toBe("anonymous");
expect(anonymousResult.stderr).toBe("");
// A failed bridge publishes empty url/token without anonymous:true and still reports capability_missing.
await writeFile(path.join(bin, "broker.json"), JSON.stringify({ url: "", token: "" }));
const failedBridgeResult = await exec(path.join(bin, "gh"), ["auth", "status"], { env });
expect(failedBridgeResult.stdout).toBe("anonymous");
expect(failedBridgeResult.stderr).toContain("capability_missing");
});
it.each(["--version", "--help", "-h", "version", "help"])(
"runs local gh %j without calling the broker or reporting missing capabilities",
async (arg) => {
const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-gh-local-"));
cleanups.push(() => rm(root, { recursive: true, force: true }));
const bin = path.join(root, "managed"), real = path.join(root, "real");
await mkdir(bin); await mkdir(real);
await writeFile(path.join(bin, "gh"), githubLauncherSource(), { mode: 0o700 });
await writeFile(path.join(real, "gh"), '#!/usr/bin/env node\nprocess.stdout.write("gh-local-ok");\n', { mode: 0o700 });
let requests = 0;
const server = createServer((_req, res) => { requests++; res.writeHead(500); res.end(); });
await new Promise<void>(resolve => server.listen(0, "127.0.0.1", resolve));
cleanups.push(() => new Promise<void>(resolve => server.close(() => resolve())));
const { port } = server.address() as { port: number };
for (const broker of [{ url: "", token: "" }, { url: `http://127.0.0.1:${port}`, token: "run-capability" }]) {
const env = { ...process.env, ...githubBrokerEnvironment({}, broker), PATH: `${bin}:${real}:${process.env.PATH}` };
const result = await exec(path.join(bin, "gh"), [arg], { env });
expect(result.stdout).toBe("gh-local-ok");
expect(result.stderr).toBe("");
}
expect(requests).toBe(0);
},
);