Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Bots' git to GitHub over the credential broker: a github grant, a push guard, the box's git env, and an unboxed helper (#7265)

Milind Sonifbdd6d96ff9d
diff --git a/server/bot-box/box.ts b/server/bot-box/box.ts
index 487cff773f..c296dc060d 100644
--- a/server/bot-box/box.ts
+++ b/server/bot-box/box.ts
@@ -10,6 +10,7 @@ import { engineInstallRoots } from "../engine-roots.ts";
import { homeProgramDirs, resetPathCache } from "../env-path.ts";
import { SERVER_ROOT, resolveProxy } from "../proxy-paths.ts";
import { bridgedCommand, type BridgeTools } from "./bridge.ts";
+import { GITHUB_GRANT, boxGithubGit } from "../github/git-access.ts";
import { brokerRewrite } from "./broker-env.ts";
import { openCredentialBroker, type BrokerGrant, type CredentialBroker } from "./broker.ts";
import { detectBox, type BoxDetection, type BoxKind } from "./detect.ts";
@@ -185,7 +186,9 @@ export class BoxRunner {
}
}
- /** Keys become a per-process token when the broker is on and the box has its own network (the bridge to the broker). */
+ /** Keys become a per-process token when the broker is on and the box has its own network (the bridge to the broker).
+ * With a GitHub sign-in for the spawn's conversation, the same token also carries the github grant, and git is pointed
+ * at it (server/github/git-access.ts). */
private broker(env: Record<string, string>, plan: BoxPlan, request: BoxRequest): { env: Record<string, string>; token: string | null; release(): void; unbrokered: string[] } {
const broker = this.options.broker;
if (!broker || plan.net !== "isolated") return { env, token: null, release: () => {}, unbrokered: [] };
@@ -196,10 +199,12 @@ export class BoxRunner {
const minted = broker.mintForProcess({ botId: plan.botId, threadId, grants: {} });
const rewrite = brokerRewrite(env, minted.token, broker.port);
broker.revoke(minted.token);
- if (!Object.keys(rewrite.grants).length) return { env, token: null, release: () => {}, unbrokered: rewrite.unbrokered };
- const granted = broker.mintForProcess({ botId: plan.botId, threadId, grants: rewrite.grants });
+ const github = boxGithubGit(request.botThreads ? null : this.conversation(request).threadId, [request.cwd, request.conversationFolder].filter((folder): folder is string => Boolean(folder)));
+ if (!Object.keys(rewrite.grants).length && !github) return { env, token: null, release: () => {}, unbrokered: rewrite.unbrokered };
+ const granted = broker.mintForProcess({ botId: plan.botId, threadId, grants: { ...rewrite.grants, ...(github ? { [GITHUB_GRANT]: github.grant } : {}) } });
const again = brokerRewrite(env, granted.token, broker.port);
- return { env: again.env, token: granted.token, release: () => broker.revoke(granted.token), unbrokered: again.unbrokered };
+ const out = github ? { ...again.env, ...github.env({ port: broker.port, token: granted.token }) } : again.env;
+ return { env: out, token: granted.token, release: () => broker.revoke(granted.token), unbrokered: again.unbrokered };
}
}
diff --git a/server/bot-box/broker-github.e2e.test.ts b/server/bot-box/broker-github.e2e.test.ts
new file mode 100644
index 0000000000..cd9b47d440
--- /dev/null
+++ b/server/bot-box/broker-github.e2e.test.ts
@@ -0,0 +1,222 @@
+// A real git, with the box's git env (server/github/git-env.ts), cloning and pushing to "github.com" through the
+// broker's github grant, against git's own http-backend standing in for GitHub. The broker listens on a unix socket as
+// in a box; a loopback port is bridged to it here as the box's bridge does.
+import { spawn } from "node:child_process";
+import { randomBytes } from "node:crypto";
+import { mkdirSync, mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs";
+import { createConnection, createServer, type AddressInfo, type Server } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterAll, beforeAll, describe, expect, it } from "vitest";
+
+import { openCredentialBroker, type CredentialBroker } from "./broker.ts";
+import { GITHUB_GRANT, githubGrant } from "./broker-github.ts";
+import { boxGitEnv } from "../github/git-env.ts";
+import { conversationRepos, forgetConversationRepos } from "../github/git-repos.ts";
+import { httpBackend, openFakeGithub, type FakeGithub } from "../testing/fake-github-git.ts";
+
+const TOKEN = "ghp_e2eFakeToken0123456789abcdefABCDEF";
+const BASIC = `Basic ${Buffer.from(`x-access-token:${TOKEN}`).toString("base64")}`;
+const backend = process.platform === "win32" ? null : httpBackend();
+
+interface Ran { status: number | null; stdout: string; stderr: string }
+
+// Unix sockets and git's http-backend: Linux and macOS (the box itself runs only on Linux).
+describe.skipIf(!backend)("git through the broker's github grant", () => {
+ let dir: string, fake: FakeGithub, broker: CredentialBroker, bridge: Server, env: Record<string, string>, brokerToken: string;
+ const reported: Array<string | null> = [];
+
+ // Never spawnSync here: the broker and the fake GitHub answer on this process's event loop.
+ const git = (args: string[], cwd = dir): Promise<Ran> => new Promise((resolve) => {
+ const child = spawn("git", args, { cwd, env, stdio: ["ignore", "pipe", "pipe"] });
+ let stdout = "", stderr = "";
+ child.stdout.on("data", (chunk) => { stdout += chunk; });
+ child.stderr.on("data", (chunk) => { stderr += chunk; });
+ child.on("close", (status) => resolve({ status, stdout, stderr }));
+ });
+ const bare = (args: string[]) => git(["--git-dir", join(dir, "github", "acme", "widgets.git"), ...args]);
+ const receivePosts = () => fake.seen.filter((request) => request.method === "POST" && request.url.endsWith("/git-receive-pack")).length;
+
+ beforeAll(async () => {
+ dir = mkdtempSync(join(tmpdir(), "omb-gh-e2e-"));
+ mkdirSync(join(dir, "home"));
+ const repo = join(dir, "github", "acme", "widgets.git");
+ env = {
+ PATH: process.env.PATH ?? "", HOME: join(dir, "home"), GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null", LANG: "C", LC_ALL: "C",
+ GIT_AUTHOR_NAME: "Bot", GIT_AUTHOR_EMAIL: "[email protected]", GIT_COMMITTER_NAME: "Bot", GIT_COMMITTER_EMAIL: "[email protected]",
+ };
+ // A repository whose default branch is neither main nor master, so the guard has to learn it.
+ expect((await git(["init", "-q", "--bare", "-b", "trunk", repo])).status).toBe(0);
+ const seed = join(dir, "seed");
+ expect((await git(["init", "-q", "-b", "trunk", seed])).status).toBe(0);
+ writeFileSync(join(seed, "README.md"), "widgets\n");
+ expect((await git(["add", "."], seed)).status).toBe(0);
+ expect((await git(["commit", "-q", "-m", "first"], seed)).status).toBe(0);
+ expect((await git(["push", "-q", repo, "trunk", "trunk:refs/heads/old", "trunk:refs/tags/v1"], seed)).status).toBe(0);
+ // Another repository the token reaches, which this conversation never cloned.
+ expect((await git(["init", "-q", "--bare", "-b", "trunk", join(dir, "github", "acme", "elsewhere.git")])).status).toBe(0);
+ expect((await git(["push", "-q", join(dir, "github", "acme", "elsewhere.git"), "trunk"], seed)).status).toBe(0);
+
+ fake = await openFakeGithub({ root: join(dir, "github"), backend: backend!, basic: BASIC });
+ broker = await openCredentialBroker({ socketPath: join(dir, "broker.sock") });
+ bridge = createServer((client) => {
+ const upstream = createConnection(join(dir, "broker.sock"));
+ client.pipe(upstream).pipe(client);
+ client.on("error", () => upstream.destroy());
+ upstream.on("error", () => client.destroy());
+ });
+ await new Promise<void>((done) => bridge.listen(0, "127.0.0.1", () => done()));
+ const port = (bridge.address() as AddressInfo).port;
+ forgetConversationRepos();
+ const repos = conversationRepos("thread:t1", [join(dir, "conversation")]);
+ mkdirSync(join(dir, "conversation"));
+ const grant = githubGrant({ audience: () => "owner", token: async () => TOKEN, reportAuthFailure: (who) => reported.push(who), upstream: fake.url, mayPush: repos.mayPush, fetched: repos.fetched });
+ brokerToken = broker.mintForProcess({ botId: "b1", threadId: "t1", grants: { [GITHUB_GRANT]: grant } }).token;
+ // What the box sets, plus a credential the bot tried to send itself, which the broker must drop.
+ env = { ...env, ...boxGitEnv({ port, token: brokerToken }) };
+ env.GIT_CONFIG_PARAMETERS = `${env.GIT_CONFIG_PARAMETERS} 'http.extraheader=Authorization: Bearer bot-made-this-up'`;
+ }, 60_000);
+
+ afterAll(async () => {
+ await broker?.close();
+ await new Promise<void>((done) => bridge ? bridge.close(() => done()) : done());
+ await fake?.close();
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ });
+
+ it("clones an https://github.com/ remote, with GitHub's credential added and the bot's own dropped", async () => {
+ const cloned = await git(["clone", "-q", "https://github.com/acme/widgets.git", join("conversation", "work")]);
+ expect(cloned.status, cloned.stderr).toBe(0);
+ expect((await git(["log", "--format=%s"], join(dir, "conversation", "work"))).stdout.trim()).toBe("first");
+ expect(fake.seen.length).toBeGreaterThan(0);
+ for (const request of fake.seen) {
+ expect(request.headers.authorization).toBe(BASIC);
+ expect(JSON.stringify(request.headers)).not.toContain("bot-made-this-up");
+ }
+ // The remote keeps its github.com address; only the broker's token, never GitHub's, is in the box's git env.
+ expect((await git(["config", "--get", "remote.origin.url"], join(dir, "conversation", "work"))).stdout.trim()).toBe("https://github.com/acme/widgets.git");
+ expect(JSON.stringify(env)).not.toContain(TOKEN);
+ }, 60_000);
+
+ it("pushes a new branch", async () => {
+ const work = join(dir, "conversation", "work");
+ writeFileSync(join(work, "feature.txt"), "a feature\n");
+ expect((await git(["add", "."], work)).status).toBe(0);
+ expect((await git(["commit", "-q", "-m", "feature"], work)).status).toBe(0);
+ const pushed = await git(["push", "origin", "HEAD:refs/heads/bot/feature"], work);
+ expect(pushed.status, pushed.stderr).toBe(0);
+ expect((await bare(["log", "--format=%s", "-1", "bot/feature"])).stdout.trim()).toBe("feature");
+ }, 60_000);
+
+ it("refuses a push to the default branch, with words git shows the bot, and GitHub never sees it", async () => {
+ const work = join(dir, "conversation", "work");
+ const before = (await bare(["rev-parse", "trunk"])).stdout.trim();
+ const posts = receivePosts();
+ const pushed = await git(["push", "origin", "HEAD:trunk"], work);
+ expect(pushed.status).not.toBe(0);
+ expect(pushed.stderr).toContain("remote rejected");
+ expect(pushed.stderr).toContain("push to a new branch");
+ expect(pushed.stderr).toMatch(/remote: .*default branch \(trunk\)/);
+ expect((await bare(["rev-parse", "trunk"])).stdout.trim()).toBe(before);
+ expect(receivePosts()).toBe(posts);
+ }, 60_000);
+
+ it("refuses deleting a branch, and a push that mixes a new branch with a refused update applies neither", async () => {
+ const work = join(dir, "conversation", "work");
+ const deleted = await git(["push", "origin", "--delete", "old"], work);
+ expect(deleted.status).not.toBe(0);
+ expect(deleted.stderr).toContain("deleting a ref is not allowed here");
+ expect((await bare(["rev-parse", "--verify", "-q", "refs/heads/old"])).status).toBe(0);
+ const mixed = await git(["push", "origin", "HEAD:refs/heads/bot/other", "HEAD:trunk"], work);
+ expect(mixed.status).not.toBe(0);
+ expect((await bare(["rev-parse", "--verify", "-q", "refs/heads/bot/other"])).status).not.toBe(0);
+ }, 60_000);
+
+ it("streams a push larger than git's post buffer (chunked, after git's probe) to a new branch", async () => {
+ const work = join(dir, "conversation", "work");
+ writeFileSync(join(work, "blob.bin"), randomBytes(3 * 1024 * 1024));
+ expect((await git(["add", "."], work)).status).toBe(0);
+ expect((await git(["commit", "-q", "-m", "big"], work)).status).toBe(0);
+ const pushed = await git(["-c", "http.postBuffer=65536", "push", "origin", "HEAD:refs/heads/bot/big"], work);
+ expect(pushed.status, pushed.stderr).toBe(0);
+ expect((await bare(["log", "--format=%s", "-1", "bot/big"])).stdout.trim()).toBe("big");
+ }, 60_000);
+
+ it("never writes the broker token into git's records: a merge, FETCH_HEAD, remotes, a failed fetch's error, any file of the clone", async () => {
+ const work = join(dir, "conversation", "work");
+ // Someone else moves trunk on, so a pull makes a merge commit whose message names where it fetched from.
+ const other = join(dir, "other");
+ expect((await git(["clone", "-q", join(dir, "github", "acme", "widgets.git"), other])).status).toBe(0);
+ writeFileSync(join(other, "upstream.txt"), "moved on\n");
+ expect((await git(["add", "."], other)).status).toBe(0);
+ expect((await git(["commit", "-q", "-m", "upstream change"], other)).status).toBe(0);
+ expect((await git(["push", "-q", "origin", "trunk"], other)).status).toBe(0);
+ const pulled = await git(["pull", "--no-rebase", "--no-edit", "origin", "trunk"], work);
+ expect(pulled.status, pulled.stderr).toBe(0);
+ const merge = (await git(["log", "-1", "--format=%B"], work)).stdout;
+ expect(merge).toMatch(/Merge branch 'trunk' of \S+\/acme\/widgets/);
+ const failed = await git(["fetch", "https://github.com/acme/no-such-repo.git"], work);
+ expect(failed.status).not.toBe(0);
+ const remotes = (await git(["remote", "-v"], work)).stdout;
+ // `remote -v` shows the address git uses after insteadOf: the broker's, with no token in it.
+ expect(remotes).toContain("/g/github/acme/widgets.git");
+ const texts = [merge, failed.stderr, failed.stdout, remotes, pulled.stderr, pulled.stdout];
+ const files = (folder: string): string[] => readdirSync(folder).flatMap((name) => {
+ const path = join(folder, name);
+ return statSync(path).isDirectory() ? files(path) : [path];
+ });
+ for (const file of files(work)) texts.push(readFileSync(file, "latin1"));
+ for (const text of texts) {
+ expect(text).not.toContain(brokerToken);
+ expect(text).not.toContain("omb_t0_");
+ expect(text).not.toContain(TOKEN);
+ }
+ }, 60_000);
+
+ it("pushes a new tag but refuses moving one, and refuses refs outside branches and tags", async () => {
+ const work = join(dir, "conversation", "work");
+ expect((await git(["tag", "v2"], work)).status).toBe(0);
+ const tagged = await git(["push", "origin", "refs/tags/v2"], work);
+ expect(tagged.status, tagged.stderr).toBe(0);
+ expect((await git(["tag", "-f", "v1"], work)).status).toBe(0);
+ const moved = await git(["push", "--force", "origin", "refs/tags/v1"], work);
+ expect(moved.status).not.toBe(0);
+ expect(moved.stderr).toContain("moving a tag is not allowed here");
+ const pull = await git(["push", "origin", "HEAD:refs/pull/1/head"], work);
+ expect(pull.status).not.toBe(0);
+ expect(pull.stderr).toContain("only branches and new tags may be pushed here");
+ }, 60_000);
+
+ it("refuses a push to a repository this conversation never cloned or fetched", async () => {
+ const work = join(dir, "conversation", "work");
+ const pushed = await git(["push", "https://github.com/acme/elsewhere.git", "HEAD:refs/heads/bot/sneak"], work);
+ expect(pushed.status).not.toBe(0);
+ expect(pushed.stderr).toContain("acme/elsewhere is not a repository this conversation has cloned or fetched");
+ expect((await git(["--git-dir", join(dir, "github", "acme", "elsewhere.git"), "rev-parse", "--verify", "-q", "refs/heads/bot/sneak"])).status).not.toBe(0);
+ }, 60_000);
+
+ it("keeps a credential helper of another git host working; the broker's address gets none", async () => {
+ // The bot's own helper, in its own global git config as `git config --global credential.helper` would put it.
+ const global = join(dir, "home", "own.gitconfig");
+ writeFileSync(global, "[credential]\n\thelper = \"!f() { echo username=me; echo password=gitlab-secret; }; f\"\n");
+ const fill = (host: string, protocol = "https") => new Promise<string>((resolve) => {
+ const child = spawn("git", ["credential", "fill"], { env: { ...env, GIT_CONFIG_GLOBAL: global }, stdio: ["pipe", "pipe", "ignore"] });
+ let out = "";
+ child.stdout.on("data", (chunk) => { out += chunk; });
+ child.on("close", () => resolve(out));
+ child.stdin.end(`protocol=${protocol}\nhost=${host}\n\n`);
+ });
+ expect(await fill("gitlab.example")).toContain("password=gitlab-secret");
+ const port = (bridge.address() as AddressInfo).port;
+ expect(await fill(`127.0.0.1:${port}`, "http")).not.toContain("gitlab-secret");
+ }, 60_000);
+
+ it("takes the SSH forms of a github.com remote over the same HTTPS way", async () => {
+ for (const remote of ["[email protected]:acme/widgets.git", "ssh://[email protected]/acme/widgets.git"]) {
+ const listed = await git(["ls-remote", remote]);
+ expect(listed.status, listed.stderr).toBe(0);
+ expect(listed.stdout).toContain("refs/heads/trunk");
+ }
+ expect(reported).toEqual([]);
+ }, 60_000);
+});
diff --git a/server/bot-box/broker-github.test.ts b/server/bot-box/broker-github.test.ts
new file mode 100644
index 0000000000..76baf4389b
--- /dev/null
+++ b/server/bot-box/broker-github.test.ts
@@ -0,0 +1,316 @@
+import { createServer, request, type IncomingHttpHeaders, type Server, type ServerResponse } from "node:http";
+import { mkdtempSync, rmSync } from "node:fs";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { BROKER_TOKEN_HEADER, openCredentialBroker, type CredentialBroker } from "./broker.ts";
+import { DEFAULT_BRANCH_REUSE_MS, GITHUB_TOKEN_REUSE_MS, brokeredLocation, gitRequest, githubGrant, type GithubGrantDeps } from "./broker-github.ts";
+
+const TOKEN = "ghp_unitFakeToken0123456789abcdefABCDEF";
+const basic = (token: string) => `Basic ${Buffer.from(`x-access-token:${token}`).toString("base64")}`;
+const pkt = (text: string) => `${(Buffer.byteLength(text) + 4).toString(16).padStart(4, "0")}${text}`;
+const A = "1".repeat(40), B = "2".repeat(40);
+
+describe("which requests the github grant takes", () => {
+ it("only git's smart-HTTP requests to one repository", () => {
+ expect(gitRequest("GET", "/acme/widgets.git/info/refs", "?service=git-upload-pack")).toEqual({ repo: "acme/widgets", service: "git-upload-pack", advertisement: true });
+ expect(gitRequest("GET", "/Acme/Widgets/info/refs", "?service=git-receive-pack")).toEqual({ repo: "acme/widgets", service: "git-receive-pack", advertisement: true });
+ expect(gitRequest("POST", "/acme/widgets.git/git-receive-pack", "")).toEqual({ repo: "acme/widgets", service: "git-receive-pack", advertisement: false });
+ expect(gitRequest("POST", "/acme/w.x_y-z/git-upload-pack", "")).toMatchObject({ repo: "acme/w.x_y-z" });
+ });
+
+ it("nothing else: another page, another method, a dumb-HTTP read, a traversal or an encoded path", () => {
+ for (const [method, path, query] of [
+ ["GET", "/acme/widgets.git/info/refs", ""], ["GET", "/acme/widgets.git/info/refs", "?service=git-upload-archive"],
+ ["POST", "/acme/widgets.git/info/refs", "?service=git-upload-pack"], ["GET", "/acme/widgets.git/git-upload-pack", ""],
+ ["POST", "/acme/widgets.git/git-receive-pack", "?x=1"], ["GET", "/acme/widgets/issues", ""], ["GET", "/login", ""],
+ ["GET", "/acme/widgets.git/HEAD", ""], ["GET", "/acme/widgets.git/objects/info/packs", ""],
+ ["GET", "/acme/../evil/widgets.git/info/refs", "?service=git-upload-pack"], ["GET", "/../acme/w/info/refs", "?service=git-upload-pack"],
+ ["GET", "/acme/..%2fevil/info/refs", "?service=git-upload-pack"], ["GET", "/acme/%2e%2e/info/refs", "?service=git-upload-pack"],
+ ["GET", "/acme/../info/refs", "?service=git-upload-pack"], ["GET", "/acme/.git/info/refs", "?service=git-upload-pack"],
+ ["GET", "//evil.example/acme/w/info/refs", "?service=git-upload-pack"], ["GET", "/-acme/w/info/refs", "?service=git-upload-pack"],
+ ["GET", "/acme/w/x/info/refs", "?service=git-upload-pack"],
+ ] as const) expect(gitRequest(method, path, query), `${method} ${path}${query}`).toBeNull();
+ });
+
+ it("points a Location on the upstream back through the broker and leaves any other alone", () => {
+ expect(brokeredLocation("https://github.com/acme/new-name.git/info/refs?service=git-upload-pack", "https://github.com/", "/b/t/github")).toBe("/b/t/github/acme/new-name.git/info/refs?service=git-upload-pack");
+ expect(brokeredLocation("https://evil.example/x", "https://github.com/", "/b/t/github")).toBe("https://evil.example/x");
+ expect(brokeredLocation("https://github.com.evil.example/x", "https://github.com/", "/b/t/github")).toBe("https://github.com.evil.example/x");
+ });
+});
+
+// The broker listens on a unix socket, which Windows refuses at a file path (EACCES): Linux and macOS.
+const unixSocket = describe.skipIf(process.platform === "win32");
+
+unixSocket("the github grant in the broker", () => {
+ let dir: string, upstream: Server, broker: CredentialBroker, clock = 1_800_000_000_000;
+ const seen: Array<{ method: string; url: string; headers: IncomingHttpHeaders; body: Buffer }> = [];
+ let answer: (url: string, res: ServerResponse, body: Buffer) => void = (_url, res) => res.writeHead(200, { "content-type": "text/plain" }).end("ok");
+ let onFirstChunk: (() => void) | null = null;
+
+ afterEach(async () => {
+ await broker?.close();
+ await new Promise<void>((done) => upstream ? (upstream.closeAllConnections(), upstream.close(() => done())) : done());
+ rmSync(dir, { recursive: true, force: true });
+ seen.length = 0;
+ answer = (_url, res) => res.writeHead(200, { "content-type": "text/plain" }).end("ok");
+ onFirstChunk = null;
+ });
+
+ async function start(deps: Partial<GithubGrantDeps> = {}): Promise<string> {
+ dir = mkdtempSync(join(tmpdir(), "omb-gh-grant-"));
+ upstream = createServer((req, res) => {
+ const chunks: Buffer[] = [];
+ req.on("data", (chunk: Buffer) => { if (!chunks.length) onFirstChunk?.(); chunks.push(chunk); });
+ req.on("end", () => {
+ const body = Buffer.concat(chunks);
+ seen.push({ method: req.method ?? "", url: req.url ?? "", headers: req.headers, body });
+ answer(req.url ?? "", res, body);
+ });
+ });
+ await new Promise<void>((done) => upstream.listen(0, "127.0.0.1", () => done()));
+ broker = await openCredentialBroker({ socketPath: join(dir, "broker.sock"), now: () => clock });
+ const grant = githubGrant({ audience: () => "owner", token: async () => TOKEN, reportAuthFailure: () => {}, now: () => clock, ...deps, upstream: `http://127.0.0.1:${(upstream.address() as AddressInfo).port}` });
+ return broker.mintForProcess({ botId: "b1", threadId: "t1", grants: { github: grant } }).token;
+ }
+
+ const call = (method: string, path: string, headers: Record<string, string> = {}, body?: Buffer | string) =>
+ new Promise<{ status: number; body: Buffer; headers: IncomingHttpHeaders }>((resolve, reject) => {
+ const req = request({ socketPath: join(dir, "broker.sock"), path, method, headers }, (res) => {
+ const chunks: Buffer[] = [];
+ res.on("data", (chunk: Buffer) => chunks.push(chunk));
+ res.on("end", () => resolve({ status: res.statusCode ?? 0, body: Buffer.concat(chunks), headers: res.headers }));
+ });
+ req.on("error", reject);
+ req.end(body);
+ });
+
+ it("adds GitHub's Basic credential for the fixed upstream and drops every credential the client sent", async () => {
+ const token = await start();
+ const res = await call("GET", `/b/${token}/github/acme/widgets.git/info/refs?service=git-upload-pack`, {
+ authorization: "Bearer bot-made-this-up", cookie: "user_session=stolen", "x-api-key": "k", "proxy-authorization": "Basic eA==", "git-protocol": "version=2",
+ });
+ expect(res.status).toBe(200);
+ expect(seen).toHaveLength(1);
+ expect(seen[0]!.url).toBe("/acme/widgets.git/info/refs?service=git-upload-pack");
+ expect(seen[0]!.headers.authorization).toBe(basic(TOKEN));
+ expect(seen[0]!.headers["git-protocol"]).toBe("version=2");
+ expect(seen[0]!.headers.host).toBe(`127.0.0.1:${(upstream.address() as AddressInfo).port}`);
+ for (const name of ["cookie", "x-api-key", "proxy-authorization"]) expect(seen[0]!.headers[name]).toBeUndefined();
+ });
+
+ it("takes the token from its header at /g/, which never reaches GitHub, and refuses /g/ without a good one", async () => {
+ const token = await start();
+ const res = await call("GET", "/g/github/acme/widgets.git/info/refs?service=git-upload-pack", { [BROKER_TOKEN_HEADER]: token });
+ expect(res.status).toBe(200);
+ expect(seen[0]!.url).toBe("/acme/widgets.git/info/refs?service=git-upload-pack");
+ expect(seen[0]!.headers[BROKER_TOKEN_HEADER]).toBeUndefined();
+ expect(JSON.stringify(seen[0]!.headers)).not.toContain(token);
+ expect((await call("GET", "/g/github/acme/widgets.git/info/refs?service=git-upload-pack")).status).toBe(401);
+ expect((await call("GET", "/g/github/acme/widgets.git/info/refs?service=git-upload-pack", { [BROKER_TOKEN_HEADER]: `omb_t0_${"0".repeat(48)}` })).status).toBe(401);
+ // A Location on the upstream comes back under /g/, where the header still goes.
+ answer = (_url, res) => res.writeHead(301, { location: `http://127.0.0.1:${(upstream.address() as AddressInfo).port}/acme/new.git/info/refs?service=git-upload-pack` }).end();
+ expect((await call("GET", "/g/github/acme/old.git/info/refs?service=git-upload-pack", { [BROKER_TOKEN_HEADER]: token })).headers.location).toBe("/g/github/acme/new.git/info/refs?service=git-upload-pack");
+ expect(seen).toHaveLength(2);
+ });
+
+ it("refuses any other path before it reaches GitHub, and a token for another grant or none", async () => {
+ const token = await start();
+ for (const path of ["/acme/widgets/issues", "/acme/../evil/w.git/info/refs?service=git-upload-pack", "/acme/%2e%2e/info/refs?service=git-upload-pack", "/login", "//evil.example/a/b/info/refs?service=git-upload-pack"]) {
+ const res = await call("GET", `/b/${token}/github${path}`);
+ expect(res.status, path).toBe(403);
+ }
+ expect((await call("POST", `/b/${token}/github/acme/w/info/refs?service=git-upload-pack`)).status).toBe(403);
+ expect((await call("GET", `/b/omb_t0_${"0".repeat(48)}/github/acme/w/info/refs?service=git-upload-pack`)).status).toBe(401);
+ expect(seen).toEqual([]);
+ });
+
+ it("streams both ways: the upstream has the first bytes before the client ends, and the client before the upstream ends", async () => {
+ const token = await start();
+ let release!: () => void;
+ const upstreamGotData = new Promise<void>((done) => { onFirstChunk = done; });
+ const req = request({ socketPath: join(dir, "broker.sock"), path: `/b/${token}/github/acme/w.git/git-upload-pack`, method: "POST", headers: { "content-type": "application/x-git-upload-pack-request" } });
+ req.write(Buffer.alloc(64 * 1024, 1));
+ await upstreamGotData;
+ answer = (_url, res) => {
+ res.writeHead(200, { "content-type": "application/x-git-upload-pack-result" });
+ res.write("first");
+ new Promise<void>((done) => { release = done; }).then(() => res.end("last"));
+ };
+ const firstOut = new Promise<string>((resolve) => req.on("response", (res) => res.once("data", (chunk: Buffer) => { resolve(chunk.toString()); res.resume(); })));
+ req.end(Buffer.alloc(64 * 1024, 2));
+ expect(await firstOut).toBe("first");
+ release();
+ expect(seen[0]!.body.length).toBe(128 * 1024);
+ });
+
+ it("tells the sign-in on GitHub's 401, not on a 403 or 404", async () => {
+ const reported: Array<string | null> = [];
+ const token = await start({ reportAuthFailure: (who) => reported.push(who) });
+ for (const status of [403, 404]) {
+ answer = (_url, res) => res.writeHead(status).end();
+ expect((await call("GET", `/b/${token}/github/acme/w/info/refs?service=git-upload-pack`)).status).toBe(status);
+ }
+ expect(reported).toEqual([]);
+ answer = (_url, res) => res.writeHead(401, { "www-authenticate": 'Basic realm="GitHub"' }).end();
+ expect((await call("GET", `/b/${token}/github/acme/w/info/refs?service=git-upload-pack`)).status).toBe(401);
+ expect(reported).toEqual(["owner"]);
+ });
+
+ it("after GitHub refuses the token, asks again without it, so a public repository still clones; a new token is sent again", async () => {
+ let current = TOKEN;
+ const reported: Array<string | null> = [];
+ const token = await start({ token: async () => current, reportAuthFailure: (who) => reported.push(who) });
+ // Like GitHub: a refused credential is a 401 even for a public repository, which answers without one.
+ answer = (_url, res) => res.writeHead(seen.at(-1)!.headers.authorization ? 401 : 200, { "content-type": "text/plain" }).end("ok");
+ const get = () => call("GET", `/b/${token}/github/acme/public/info/refs?service=git-upload-pack`);
+ expect((await get()).status).toBe(200);
+ expect(seen.map((request) => request.headers.authorization)).toEqual([basic(TOKEN), undefined]);
+ expect(reported).toEqual(["owner"]);
+ clock += GITHUB_TOKEN_REUSE_MS;
+ expect((await get()).status).toBe(200);
+ expect(seen.at(-1)!.headers.authorization).toBeUndefined();
+ expect(seen).toHaveLength(3);
+ // The person signs in again: the new token goes out.
+ current = "ghp_renewed";
+ clock += GITHUB_TOKEN_REUSE_MS;
+ answer = (_url, res) => res.writeHead(200).end("ok");
+ await get();
+ expect(seen.at(-1)!.headers.authorization).toBe(basic("ghp_renewed"));
+ expect(reported).toEqual(["owner"]);
+ });
+
+ it("asks for the token on each request after a short while, and for the audience every time", async () => {
+ let audience: string | null = "owner";
+ const asked: Array<string | null> = [];
+ const token = await start({ audience: () => audience, token: async (who) => { asked.push(who); return who === "owner" ? TOKEN : "ghp_other"; } });
+ const get = () => call("GET", `/b/${token}/github/acme/w/info/refs?service=git-upload-pack`);
+ await get();
+ await get();
+ expect(asked).toEqual(["owner"]);
+ clock += GITHUB_TOKEN_REUSE_MS;
+ await get();
+ expect(asked).toEqual(["owner", "owner"]);
+ audience = "p_member";
+ await get();
+ expect(seen.at(-1)!.headers.authorization).toBe(basic("ghp_other"));
+ // A conversation that is nobody's own any more gets no credential at all.
+ audience = null;
+ await get();
+ expect(seen.at(-1)!.headers.authorization).toBeUndefined();
+ expect(asked).toEqual(["owner", "owner", "p_member"]);
+ });
+
+ it("points a renamed repository's redirect back through the broker", async () => {
+ const token = await start();
+ answer = (url, res) => res.writeHead(301, { location: `http://127.0.0.1:${(upstream.address() as AddressInfo).port}/acme/new.git${url.slice(url.indexOf("/info/refs"))}` }).end();
+ const res = await call("GET", `/b/${token}/github/acme/old.git/info/refs?service=git-upload-pack`);
+ expect(res.status).toBe(301);
+ expect(res.headers.location).toBe(`/b/${token}/github/acme/new.git/info/refs?service=git-upload-pack`);
+ });
+
+ describe("a push", () => {
+ const advertise = (branch: string) => (url: string, res: ServerResponse, body: Buffer) => {
+ if (url.includes("service=git-upload-pack")) {
+ res.writeHead(200, { "content-type": "application/x-git-upload-pack-advertisement" });
+ res.end(`001e# service=git-upload-pack\n0000${pkt(`${A} HEAD\u0000multi_ack symref=HEAD:refs/heads/${branch} agent=git/2\n`)}0000`);
+ return;
+ }
+ res.writeHead(200, { "content-type": "application/x-git-receive-pack-result" }).end(`forwarded ${body.length}`);
+ };
+ const push = (token: string, ref: string, extra: Buffer = Buffer.alloc(0), headers: Record<string, string> = {}) =>
+ call("POST", `/b/${token}/github/acme/w.git/git-receive-pack`, { "content-type": "application/x-git-receive-pack-request", ...headers },
+ Buffer.concat([Buffer.from(`${pkt(`${A} ${B} ${ref}\u0000 report-status-v2 side-band-64k`)}0000`, "latin1"), extra]));
+
+ it("forwards a new branch's push byte for byte, with the pack behind its command list", async () => {
+ const token = await start();
+ answer = advertise("dev");
+ const pack = Buffer.alloc(200 * 1024, 9);
+ const res = await push(token, "refs/heads/bot/x", pack);
+ const commands = Buffer.from(`${pkt(`${A} ${B} refs/heads/bot/x\u0000 report-status-v2 side-band-64k`)}0000`, "latin1");
+ expect(res.body.toString()).toBe(`forwarded ${commands.length + pack.length}`);
+ const sent = seen.find((request) => request.url === "/acme/w.git/git-receive-pack")!;
+ expect(sent.body.equals(Buffer.concat([commands, pack]))).toBe(true);
+ expect(sent.headers.authorization).toBe(basic(TOKEN));
+ });
+
+ it("refuses the default branch it learns from the upstream, which never sees that push, and asks once per repository", async () => {
+ const token = await start();
+ answer = advertise("dev");
+ const refused = await push(token, "refs/heads/dev", Buffer.alloc(1024, 9));
+ expect(refused.status).toBe(200);
+ expect(refused.headers["content-type"]).toBe("application/x-git-receive-pack-result");
+ expect(refused.body.toString("latin1")).toContain("ng refs/heads/dev the default branch is protected here; push to a new branch");
+ expect(refused.body.toString("latin1")).toContain("Push your work to a new branch");
+ expect((await push(token, "refs/heads/main")).body.toString()).toMatch(/^forwarded/);
+ expect(seen.filter((request) => request.url.endsWith("/git-receive-pack"))).toHaveLength(1);
+ expect(seen.filter((request) => request.url.includes("service=git-upload-pack"))).toHaveLength(1);
+ expect(seen.find((request) => request.url.includes("service=git-upload-pack"))!.headers["git-protocol"]).toBeUndefined();
+ });
+
+ it("protects main and master for a repository that names no default branch (an empty one)", async () => {
+ const token = await start();
+ answer = (url, res, body) => url.includes("service=git-upload-pack")
+ ? res.writeHead(200, { "content-type": "application/x-git-upload-pack-advertisement" }).end(`001e# service=git-upload-pack\n0000${pkt(`${"0".repeat(40)} capabilities^{}\u0000multi_ack\n`)}0000`)
+ : res.writeHead(200).end(`forwarded ${body.length}`);
+ for (const ref of ["refs/heads/main", "refs/heads/master"]) expect((await push(token, ref)).body.toString("latin1")).toContain(`ng ${ref} the default branch is protected here`);
+ expect((await push(token, "refs/heads/trunk")).body.toString()).toMatch(/^forwarded/);
+ });
+
+ it("refuses the push outright, with words to push again, when the default branch cannot be read: an error or no answer in time", async () => {
+ let token = await start();
+ answer = (url, res, body) => url.includes("service=git-upload-pack") ? res.writeHead(503).end() : res.writeHead(200).end(`forwarded ${body.length}`);
+ const failed = (await push(token, "refs/heads/feature")).body.toString("latin1");
+ expect(failed).toContain("ng refs/heads/feature the default branch could not be read; push again");
+ expect(failed).toContain("could not be read (GitHub answered 503). Nothing was applied; push again in a moment.");
+ expect(seen.filter((request) => request.url.endsWith("/git-receive-pack"))).toEqual([]);
+ await broker.close();
+ await new Promise<void>((done) => { upstream.closeAllConnections(); upstream.close(() => done()); });
+ rmSync(dir, { recursive: true, force: true });
+ token = await start({ defaultBranchTimeoutMs: 1_000 });
+ answer = (url, res, body) => { if (!url.includes("service=git-upload-pack")) res.writeHead(200).end(`forwarded ${body.length}`); };
+ expect((await push(token, "refs/heads/feature")).body.toString("latin1")).toContain("GitHub did not answer in time");
+ });
+
+ it("reads the default branch again after a few minutes, not once for the process", async () => {
+ const token = await start();
+ answer = advertise("dev");
+ await push(token, "refs/heads/a");
+ await push(token, "refs/heads/b");
+ const asked = () => seen.filter((request) => request.url.includes("service=git-upload-pack")).length;
+ expect(asked()).toBe(1);
+ clock += DEFAULT_BRANCH_REUSE_MS;
+ answer = advertise("main");
+ expect((await push(token, "refs/heads/main")).body.toString("latin1")).toContain("ng refs/heads/main the default branch is protected here");
+ expect(asked()).toBe(2);
+ });
+
+ it("refuses a push to a repository the conversation may not push to, and counts a clone's ref list as fetched", async () => {
+ const fetched: string[] = [];
+ const token = await start({ mayPush: async (repo) => fetched.includes(repo), fetched: (repo) => fetched.push(repo) });
+ answer = advertise("main");
+ const refused = (await push(token, "refs/heads/bot/x")).body.toString("latin1");
+ expect(refused).toContain("acme/w is not a repository this conversation has cloned or fetched");
+ expect(seen).toEqual([]);
+ // A push's own ref list is not a fetch; a clone's or fetch's is.
+ await call("GET", `/b/${token}/github/acme/W.git/info/refs?service=git-receive-pack`);
+ expect(fetched).toEqual([]);
+ await call("GET", `/b/${token}/github/acme/W.git/info/refs?service=git-upload-pack`);
+ expect(fetched).toEqual(["acme/w"]);
+ expect((await push(token, "refs/heads/bot/x")).body.toString()).toMatch(/^forwarded/);
+ });
+
+ it("refuses a compressed or unreadable push without forwarding it", async () => {
+ const token = await start();
+ answer = advertise("main");
+ const gz = await push(token, "refs/heads/bot/x", Buffer.alloc(0), { "content-encoding": "gzip" });
+ expect(gz.body.toString("latin1")).toContain("unpack This push was sent compressed");
+ const odd = await call("POST", `/b/${token}/github/acme/w.git/git-receive-pack`, {}, `${pkt("push-cert\u0000report-status")}0000`);
+ expect(odd.body.toString("latin1")).toContain("unpack This push was refused: signed pushes are not taken here.");
+ expect(seen.filter((request) => request.url.endsWith("/git-receive-pack"))).toEqual([]);
+ });
+ });
+});
diff --git a/server/bot-box/broker-github.ts b/server/bot-box/broker-github.ts
new file mode 100644
index 0000000000..3e46a50014
--- /dev/null
+++ b/server/bot-box/broker-github.ts
@@ -0,0 +1,251 @@
+// The broker's github grant: a bot's git reaches github.com over HTTPS with the person's GitHub sign-in, and never
+// holds the token. The box's git config sends https://github.com/ (and the SSH forms) to
+// http://127.0.0.1:<broker>/g/github/ with the broker token in a header (server/github/git-env.ts); the broker checks the
+// token like any grant's,
+// takes only git's smart-HTTP paths, drops whatever credential the client sent, asks for the token of the conversation's
+// audience on each request (so a sign-out or a renewed token counts at once) and adds it as GitHub's Basic credential for
+// the fixed upstream. Bodies stream both ways. A receive-pack request is held only until its command list is read
+// (git-push-guard.ts): a push that deletes a ref, moves a tag or updates the default branch never reaches GitHub, nor
+// a push to a repository the conversation has not cloned or fetched (`mayPush`), and git shows the bot why. GitHub's
+// 401 tells the sign-in its token is refused (server/github/token.ts). Reads are not narrowed: the grant reaches every
+// repository the person's token can.
+import { request as httpRequest, type IncomingMessage, type ServerResponse } from "node:http";
+import { request as httpsRequest } from "node:https";
+
+import type { BrokerGrant, BrokerServeRequest } from "./broker.ts";
+import { forwardableHeaders, relayableHeaders } from "./broker.ts";
+import { CommandListReader, advertisedDefaultBranch, type CommandList, refusalBody, refusalMessage, refusedCommands } from "./git-push-guard.ts";
+
+export const GITHUB_GRANT = "github";
+export const GITHUB_UPSTREAM = "https://github.com";
+/** A token asked for this long ago is asked for again: a git clone or push is a few requests in a row. */
+export const GITHUB_TOKEN_REUSE_MS = 60_000;
+/** A repository's default branch is read again after this long. */
+export const DEFAULT_BRANCH_REUSE_MS = 10 * 60_000;
+/** Reading it gives up after this long, and the push is refused (git can push again). */
+export const DEFAULT_BRANCH_TIMEOUT_MS = 15_000;
+const ADVERTISEMENT_MAX = 64 * 1024;
+const MAX_REPOS = 200;
+
+const OWNER = /^[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})$/;
+const REPO = /^[A-Za-z0-9._-]{1,100}$/;
+const SERVICES = new Set(["git-upload-pack", "git-receive-pack"]);
+
+export interface GithubGrantDeps {
+ /** Whose sign-in this grant uses, asked on each request: null gives no credential. */
+ audience(): string | null;
+ token(audience: string | null): Promise<string | null>;
+ reportAuthFailure(audience: string | null): void;
+ now?(): number;
+ /** Whether this conversation may push to `repo` (owner/name, lower case): one it has a clone of, or fetched through
+ * this broker. None lets every push through to the guard. */
+ mayPush?(repo: string): Promise<boolean>;
+ /** The conversation read `repo`'s refs through this broker (a clone or a fetch). */
+ fetched?(repo: string): void;
+ /** Test seam, in code only: another upstream than github.com. */
+ upstream?: string;
+ /** Test seam: DEFAULT_BRANCH_TIMEOUT_MS. */
+ defaultBranchTimeoutMs?: number;
+}
+
+/** The smart-HTTP request this path and query are, or null: `/<owner>/<repo>[.git]/info/refs?service=git-…-pack` on
+ * GET, `/<owner>/<repo>[.git]/git-…-pack` on POST, and nothing else (no `%`, no `..`, no other GitHub page). */
+export function gitRequest(method: string, path: string, query: string): { repo: string; service: string; advertisement: boolean } | null {
+ const parts = path.split("/");
+ if (parts.length < 4 || parts[0] !== "") return null;
+ const [, owner = "", repo = "", ...rest] = parts;
+ const name = repo.replace(/\.git$/, "");
+ if (!OWNER.test(owner) || !REPO.test(repo) || !name || name === "." || name === "..") return null;
+ const key = `${owner}/${name}`.toLowerCase();
+ const tail = rest.join("/");
+ if (tail === "info/refs" && method === "GET") {
+ const service = /^\?service=(git-upload-pack|git-receive-pack)$/.exec(query)?.[1];
+ return service ? { repo: key, service, advertisement: true } : null;
+ }
+ if (SERVICES.has(tail) && method === "POST" && query === "") return { repo: key, service: tail, advertisement: false };
+ return null;
+}
+
+/** A Location GitHub answered (a renamed repository), pointed back through the broker when it is on the upstream. */
+export function brokeredLocation(location: string, upstream: string, prefix: string): string {
+ for (const base of new Set([upstream.replace(/\/+$/, ""), GITHUB_UPSTREAM])) {
+ if (location.startsWith(`${base}/`)) return `${prefix}${location.slice(base.length)}`;
+ }
+ return location;
+}
+
+const basic = (token: string) => `Basic ${Buffer.from(`x-access-token:${token}`, "utf8").toString("base64")}`;
+
+export function githubGrant(deps: GithubGrantDeps): BrokerGrant {
+ const upstream = new URL(deps.upstream ?? GITHUB_UPSTREAM);
+ const now = deps.now ?? Date.now;
+ let held: { audience: string | null; token: string | null; at: number } | null = null;
+ /** A token GitHub answered 401 to: not sent again while the sign-in still gives it, so public repositories (a
+ * package's git dependency) keep working without a credential until the person signs in again. */
+ let refusedToken: string | null = null;
+ const defaults = new Map<string, { branch: string | null; at: number }>();
+
+ const credential = async (): Promise<{ audience: string | null; token: string | null }> => {
+ const audience = deps.audience();
+ if (held && held.audience === audience && now() - held.at < GITHUB_TOKEN_REUSE_MS) return held;
+ const given = audience === null ? null : await deps.token(audience).catch(() => null);
+ held = { audience, token: given !== null && given === refusedToken ? null : given, at: now() };
+ return held;
+ };
+
+ /** GitHub refused the token: tell the sign-in, and send no credential while it gives the same one. */
+ const tokenRefused = (audience: string | null, token: string) => {
+ deps.reportAuthFailure(audience);
+ refusedToken = token;
+ if (held?.token === token) held = { ...held, token: null };
+ };
+
+ const send = (input: BrokerServeRequest, method: string, path: string, headers: Record<string, string | string[]>, answer: (res: IncomingMessage) => void) => {
+ const fn = input.request ?? (upstream.protocol === "https:" ? httpsRequest : httpRequest);
+ return fn({ protocol: upstream.protocol, host: upstream.hostname, port: upstream.port || (upstream.protocol === "https:" ? 443 : 80), method, path, headers: { ...headers, host: upstream.host } }, answer);
+ };
+
+ /** The repository's default branch, from its upload-pack ref list (v0, whose first ref line names HEAD's target):
+ * null for a list that names none (an empty repository), or why it could not be read. */
+ const defaultBranch = (input: BrokerServeRequest, repoPath: string, repo: string, token: string | null): Promise<{ branch: string | null } | { failed: string }> => {
+ const known = defaults.get(repo);
+ if (known && now() - known.at < DEFAULT_BRANCH_REUSE_MS) return Promise.resolve({ branch: known.branch });
+ return new Promise((resolve) => {
+ let done = false;
+ const finish = (outcome: { branch: string | null } | { failed: string }) => {
+ if (done) return;
+ done = true;
+ if ("branch" in outcome) {
+ defaults.delete(repo);
+ defaults.set(repo, { branch: outcome.branch, at: now() });
+ if (defaults.size > MAX_REPOS) defaults.delete(defaults.keys().next().value!);
+ }
+ resolve(outcome);
+ asked.destroy();
+ };
+ const asked = send(input, "GET", `${repoPath}/info/refs?service=git-upload-pack`, { "user-agent": "git/2.0 (openmausbot-broker)", ...(token ? { authorization: basic(token) } : {}) }, (answer) => {
+ if (answer.statusCode !== 200) { answer.resume(); return finish({ failed: `GitHub answered ${answer.statusCode}` }); }
+ let body = Buffer.alloc(0);
+ answer.on("data", (chunk: Buffer) => {
+ body = Buffer.concat([body, chunk]);
+ const found = advertisedDefaultBranch(body);
+ if (found !== "more") finish({ branch: found });
+ else if (body.length > ADVERTISEMENT_MAX) finish({ failed: "its ref list could not be read" });
+ });
+ answer.on("end", () => finish({ branch: null }));
+ answer.on("error", () => finish({ failed: "the connection failed" }));
+ });
+ asked.setTimeout(deps.defaultBranchTimeoutMs ?? DEFAULT_BRANCH_TIMEOUT_MS, () => finish({ failed: "GitHub did not answer in time" }));
+ asked.on("error", () => finish({ failed: "GitHub could not be reached" }));
+ asked.end();
+ });
+ };
+
+ const relay = (input: BrokerServeRequest, audience: string | null, sentToken: string | null) => (answer: IncomingMessage) => {
+ if (answer.statusCode === 401 && sentToken) tokenRefused(audience, sentToken);
+ const headers = relayableHeaders(answer.headers);
+ if (typeof headers.location === "string") headers.location = brokeredLocation(headers.location, upstream.href, input.prefix);
+ input.res.writeHead(answer.statusCode ?? 502, headers);
+ answer.pipe(input.res);
+ };
+
+ const failed = (res: ServerResponse) => () => { if (!res.headersSent) res.writeHead(502, { "content-type": "text/plain" }).end("GitHub could not be reached.\n"); else res.destroy(); };
+
+ const refuse = (res: ServerResponse, status: number, text: string) => {
+ res.writeHead(status, { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" }).end(`${text}\n`);
+ };
+
+ /** Answers a push it will not send on, once the client has sent it all (git reads the answer only then). */
+ const refusePush = (input: BrokerServeRequest, body: Buffer) => {
+ const answer = () => {
+ if (input.res.headersSent) return;
+ input.res.writeHead(200, { "content-type": "application/x-git-receive-pack-result", "cache-control": "no-store" }).end(body);
+ };
+ if (input.req.readableEnded) answer();
+ else { input.req.on("end", answer); input.req.resume(); }
+ };
+
+ async function serve(input: BrokerServeRequest): Promise<void> {
+ const { req, res } = input;
+ const method = req.method ?? "GET";
+ const git = gitRequest(method, input.path, input.query);
+ if (!git) { req.resume(); return refuse(res, 403, "Only git's own requests to a GitHub repository go through here."); }
+ const repoPath = `${upstream.pathname.replace(/\/+$/, "")}${input.path.slice(0, input.path.lastIndexOf(git.advertisement ? "/info/refs" : `/${git.service}`))}`;
+ const target = `${upstream.pathname.replace(/\/+$/, "")}${input.path}${input.query}`;
+ const headers = forwardableHeaders(req.headers);
+ // Node's server has already answered a client's 100-continue; GitHub is sent the body at once.
+ delete headers.expect;
+ if (!(git.service === "git-receive-pack" && !git.advertisement)) {
+ req.pause();
+ const { audience, token } = await credential();
+ // A ref list (a GET, no body) GitHub refused with the token is asked again at once without one.
+ const forward = (sent: string | null) => {
+ const forwarded = send(input, method, target, { ...headers, ...(sent ? { authorization: basic(sent) } : {}) }, (answer) => {
+ if (answer.statusCode === 401 && sent && method === "GET") {
+ tokenRefused(audience, sent);
+ answer.resume();
+ forward(null).end();
+ return;
+ }
+ if (answer.statusCode === 200 && git.advertisement && git.service === "git-upload-pack") deps.fetched?.(git.repo);
+ relay(input, audience, sent)(answer);
+ });
+ forwarded.on("error", failed(res));
+ res.on("close", () => forwarded.destroy());
+ return forwarded;
+ };
+ const first = forward(token);
+ if (method === "GET") { req.resume(); first.end(); } else req.pipe(first);
+ return;
+ }
+ // A push: the command list first, then the decision, then the bytes held and the rest streamed on.
+ const encoding = String(req.headers["content-encoding"] ?? "identity").toLowerCase();
+ if (encoding !== "identity") {
+ return refusePush(input, refusalBody({ capabilities: [], refused: [], message: "This push was sent compressed, which is not taken here; push again with git's defaults." }));
+ }
+ const held: Buffer[] = [];
+ let heldBytes = 0;
+ const reader = new CommandListReader();
+ const list = await new Promise<Exclude<CommandList, { state: "more" }>>((resolve) => {
+ const check = (chunk: Buffer, ended: boolean) => {
+ const read = reader.feed(chunk, ended);
+ if (read.state === "more") return false;
+ req.off("data", onData);
+ req.off("end", onEnd);
+ req.pause();
+ resolve(read);
+ return true;
+ };
+ const onData = (chunk: Buffer) => { held.push(chunk); heldBytes += chunk.length; check(chunk, false); };
+ const onEnd = () => { check(Buffer.alloc(0), true); };
+ req.on("data", onData);
+ req.on("end", onEnd);
+ });
+ if (list.state === "bad") return refusePush(input, refusalBody({ capabilities: [], refused: [], message: `This push was refused: ${list.reason}.` }));
+ const { audience, token } = await credential();
+ const notHere = (reason: string, message: string) => refusePush(input, refusalBody({ capabilities: list.capabilities, refused: list.commands.map((command) => ({ ref: command.ref, reason })), message }));
+ if (list.commands.length && deps.mayPush && !(await deps.mayPush(git.repo).catch(() => false))) {
+ return notHere("not a repository this conversation works in", `This push was refused: ${git.repo} is not a repository this conversation has cloned or fetched. Push from a clone of it made here, to a new branch.`);
+ }
+ const touchesBranches = list.commands.some((command) => command.ref.startsWith("refs/heads/") && !/^0+$/.test(command.new));
+ const learned = touchesBranches ? await defaultBranch(input, repoPath, git.repo, token) : { branch: null };
+ if ("failed" in learned) {
+ return notHere("the default branch could not be read; push again", `This push was refused because the repository's default branch could not be read (${learned.failed}). Nothing was applied; push again in a moment.`);
+ }
+ const branch = learned.branch;
+ const refused = refusedCommands(list.commands, branch);
+ if (refused.length) return refusePush(input, refusalBody({ capabilities: list.capabilities, refused, message: refusalMessage(refused, branch) }));
+ const forwarded = send(input, method, target, { ...headers, ...(token ? { authorization: basic(token) } : {}) }, relay(input, audience, token));
+ forwarded.on("error", failed(res));
+ res.on("close", () => forwarded.destroy());
+ forwarded.write(Buffer.concat(held, heldBytes));
+ if (req.readableEnded) forwarded.end();
+ else req.pipe(forwarded);
+ }
+
+ return {
+ upstream: upstream.href.replace(/\/+$/, ""),
+ headers: {},
+ serve: (input) => { serve(input).catch(() => failed(input.res)()); },
+ };
+}
diff --git a/server/bot-box/broker.ts b/server/bot-box/broker.ts
index bc6a54a72d..33427166c3 100644
--- a/server/bot-box/broker.ts
+++ b/server/bot-box/broker.ts
@@ -28,6 +28,20 @@ export interface BrokerGrant {
mcpServer?: string;
/** With `mcpServer`: the connected app that refusal points the bot to instead. */
mcpApp?: McpServerApp;
+ /** A grant that answers its requests itself once the token is checked (the github grant, broker-github.ts): it adds
+ * its credential per request and checks what is sent. `headers` and `upstream` are then only its description. */
+ serve?(request: BrokerServeRequest): void;
+}
+
+/** What a grant's own `serve` gets: the request below `/b/<token>/<grant>`, and that prefix (for a Location header). */
+export interface BrokerServeRequest {
+ req: IncomingMessage;
+ res: ServerResponse;
+ path: string;
+ query: string;
+ prefix: string;
+ /** The broker's upstream request function (a test seam), or none for node's own. */
+ request?: typeof httpRequest;
}
export interface BrokerToken {
@@ -41,11 +55,28 @@ export interface BrokerToken {
interface Stored { hash: Buffer; botId: string | null; threadId: string | null; expiresAt: number; grants: Record<string, BrokerGrant>; bound: "process" | "thread" }
/** Credential headers a client may send; the broker never forwards them. */
-const CREDENTIAL_HEADERS = new Set(["authorization", "x-api-key", "x-goog-api-key", "proxy-authorization", "cookie"]);
+/** The header a client sends its token in at `/g/<grant>`, where the token is kept out of the address (git writes the
+ * address it fetched from into its own records: merge messages, FETCH_HEAD, error text). */
+export const BROKER_TOKEN_HEADER = "x-omb-broker";
+const CREDENTIAL_HEADERS = new Set(["authorization", "x-api-key", "x-goog-api-key", "proxy-authorization", "cookie", BROKER_TOKEN_HEADER]);
const HOP_BY_HOP = new Set(["connection", "keep-alive", "transfer-encoding", "te", "trailer", "upgrade", "proxy-connection", "host"]);
const TOKEN = /^omb_t0_[a-f0-9]{48}$/;
const GRANT = /^[a-z][a-z0-9_-]{0,63}$/;
+/** A client's request headers as the broker forwards them: no hop-by-hop header and no credential the client sent. */
+export function forwardableHeaders(headers: IncomingMessage["headers"]): Record<string, string | string[]> {
+ const out: Record<string, string | string[]> = {};
+ for (const [name, value] of Object.entries(headers)) if (value !== undefined && !HOP_BY_HOP.has(name) && !CREDENTIAL_HEADERS.has(name)) out[name] = value;
+ return out;
+}
+
+/** An upstream's answer headers as the broker relays them: no hop-by-hop header. */
+export function relayableHeaders(headers: IncomingMessage["headers"]): Record<string, string | string[]> {
+ const out: Record<string, string | string[]> = {};
+ for (const [name, value] of Object.entries(headers)) if (value !== undefined && !HOP_BY_HOP.has(name)) out[name] = value;
+ return out;
+}
+
export interface CredentialBrokerOptions {
socketPath: string;
now?: () => number;
@@ -73,6 +104,11 @@ export function brokerUrl(port: number, token: string, grant: string): string {
return `http://127.0.0.1:${port}/b/${token}/${grant}`;
}
+/** The address of `grant` with the token in BROKER_TOKEN_HEADER instead of the address. */
+export function brokerHeaderUrl(port: number, grant: string): string {
+ return `http://127.0.0.1:${port}/g/${grant}`;
+}
+
/** Where a request for `/b/<token>/<grant><path><query>` goes: the grant's upstream exactly as it was given when the
* client asks for the grant itself (an MCP server at `/mcp` is not one at `/mcp/`: a Cloudflare Worker answers that 404),
* the client's path below it otherwise, and the client's query beside the upstream's own. */
@@ -101,7 +137,7 @@ export function openCredentialBroker(options: CredentialBrokerOptions): Promise<
for (const name of Object.keys(input.grants)) if (!GRANT.test(name)) throw new Error(`Not a grant name: ${name.slice(0, 40)}`);
const token = `${BROKER_TOKEN_PREFIX}${randomBytes(24).toString("hex")}`;
const expiresAt = now() + (input.ttlMs ?? (bound === "process" ? BROKER_PROCESS_TTL_MS : BROKER_THREAD_TTL_MS));
- const grants = Object.fromEntries(Object.entries(input.grants).map(([name, grant]) => [name, { upstream: grant.upstream, headers: { ...grant.headers }, ...(grant.mcpServer ? { mcpServer: grant.mcpServer } : {}), ...(grant.mcpApp ? { mcpApp: { ...grant.mcpApp } } : {}) }]));
+ const grants = Object.fromEntries(Object.entries(input.grants).map(([name, grant]) => [name, { upstream: grant.upstream, headers: { ...grant.headers }, ...(grant.mcpServer ? { mcpServer: grant.mcpServer } : {}), ...(grant.mcpApp ? { mcpApp: { ...grant.mcpApp } } : {}), ...(grant.serve ? { serve: grant.serve } : {}) }]));
tokens.set(hashToken(token).toString("hex"), { hash: hashToken(token), botId: input.botId ?? null, threadId: input.threadId ?? null, expiresAt, grants, bound });
return { token, botId: input.botId ?? null, threadId: input.threadId ?? null, expiresAt, grants };
};
@@ -119,22 +155,26 @@ export function openCredentialBroker(options: CredentialBrokerOptions): Promise<
const server: Server = createServer((req: IncomingMessage, res: ServerResponse) => {
const refuse = (status: number, error: string) => { res.writeHead(status, { "content-type": "application/json", "cache-control": "no-store" }).end(JSON.stringify({ error })); req.resume(); };
- const match = /^\/b\/([^/]+)\/([^/?]+)(\/[^?]*)?(\?.*)?$/.exec(req.url ?? "");
- if (!match) return refuse(404, "not_found");
- const [, token = "", grant = "", path = "", query = ""] = match;
+ const inPath = /^\/b\/([^/]+)\/([^/?]+)(\/[^?]*)?(\?.*)?$/.exec(req.url ?? "");
+ const inHeader = inPath ? null : /^\/g\/([^/?]+)(\/[^?]*)?(\?.*)?$/.exec(req.url ?? "");
+ if (!inPath && !inHeader) return refuse(404, "not_found");
+ const presented = req.headers[BROKER_TOKEN_HEADER];
+ const [, token = "", grant = "", path = "", query = ""] = inPath ?? [inHeader![0], typeof presented === "string" ? presented.trim() : "", ...inHeader!.slice(1)];
+ const prefix = inPath ? `/b/${token}/${grant}` : `/g/${grant}`;
const verdict = lookup(token, grant);
if (!verdict.ok) return refuse(verdict.status, verdict.error);
+ if (verdict.grant.serve) {
+ stats.forwarded += 1;
+ return verdict.grant.serve({ req, res, path, query, prefix, ...(requestFn ? { request: requestFn } : {}) });
+ }
const upstream = upstreamUrl(verdict.grant.upstream, path, query);
if (!upstream) return refuse(502, "bad_upstream");
- const headers: Record<string, string | string[]> = {};
- for (const [name, value] of Object.entries(req.headers)) if (value !== undefined && !HOP_BY_HOP.has(name) && !CREDENTIAL_HEADERS.has(name)) headers[name] = value;
+ const headers = forwardableHeaders(req.headers);
for (const [name, value] of Object.entries(verdict.grant.headers)) headers[name.toLowerCase()] = value;
headers.host = upstream.host;
const send = requestFn ?? (upstream.protocol === "https:" ? httpsRequest : httpRequest);
const relay = (answer: IncomingMessage) => {
- const out: Record<string, string | string[]> = {};
- for (const [name, value] of Object.entries(answer.headers)) if (value !== undefined && !HOP_BY_HOP.has(name)) out[name] = value;
- res.writeHead(answer.statusCode ?? 502, out);
+ res.writeHead(answer.statusCode ?? 502, relayableHeaders(answer.headers));
answer.pipe(res);
};
const mcpServer = req.method === "POST" ? verdict.grant.mcpServer : undefined;
diff --git a/server/bot-box/git-push-guard.test.ts b/server/bot-box/git-push-guard.test.ts
new file mode 100644
index 0000000000..5a41d4e4fa
--- /dev/null
+++ b/server/bot-box/git-push-guard.test.ts
@@ -0,0 +1,160 @@
+import { describe, expect, it } from "vitest";
+
+import { CommandListReader, MAX_COMMANDS, MAX_COMMAND_BYTES, advertisedDefaultBranch, readCommandList, refusalBody, refusalMessage, refusedCommands } from "./git-push-guard.ts";
+
+// The command lists git 2.50.1 sent at the head of its receive-pack POST (recorded through git's own http-backend):
+// `git push <url> HEAD:refs/heads/bot/new`, `HEAD:main` and `--delete old`. The pack, when there is one, follows the flush.
+const CAPS = " report-status-v2 side-band-64k quiet object-format=sha1 agent=git/2.50.1-Darwin";
+const RECORDED = {
+ create: `00b90000000000000000000000000000000000000000 4b06e618527a5d9eca7e35d39d2c6506608d9631 refs/heads/bot/new\u0000${CAPS}0000`,
+ updateMain: `00b603f43c881a5f647a3b5f1aa28b223f922ce07bdb 4b06e618527a5d9eca7e35d39d2c6506608d9631 refs/heads/main\u0000${CAPS}0000`,
+ deleteOld: `00b503f43c881a5f647a3b5f1aa28b223f922ce07bdb 0000000000000000000000000000000000000000 refs/heads/old\u0000${CAPS}0000`,
+};
+const bytes = (text: string) => Buffer.from(text, "latin1");
+const PACK = Buffer.concat([bytes("PACK"), Buffer.from([0, 0, 0, 2, 0, 0, 0, 1]), Buffer.alloc(40, 7)]);
+
+const pkt = (text: string) => `${(Buffer.byteLength(text) + 4).toString(16).padStart(4, "0")}${text}`;
+const A = "1".repeat(40), B = "2".repeat(40), Z = "0".repeat(40);
+
+/** Reads pkt-lines back: [band, text] for a side-band answer's packets. */
+function packets(body: Buffer): Buffer[] {
+ const out: Buffer[] = [];
+ let at = 0;
+ while (at < body.length) {
+ const length = parseInt(body.subarray(at, at + 4).toString("latin1"), 16);
+ if (length === 0) { at += 4; continue; }
+ out.push(body.subarray(at + 4, at + length));
+ at += length;
+ }
+ return out;
+}
+
+describe("the push guard's command list", () => {
+ it("reads git's recorded command lists, with the pack behind them untouched", () => {
+ const create = readCommandList(Buffer.concat([bytes(RECORDED.create), PACK]), false);
+ expect(create).toEqual({ state: "done", commands: [{ old: Z, new: "4b06e618527a5d9eca7e35d39d2c6506608d9631", ref: "refs/heads/bot/new" }], capabilities: CAPS.trim().split(" ") });
+ expect(readCommandList(bytes(RECORDED.updateMain), true)).toMatchObject({ state: "done", commands: [{ ref: "refs/heads/main" }] });
+ expect(readCommandList(bytes(RECORDED.deleteOld), true)).toMatchObject({ state: "done", commands: [{ new: Z, ref: "refs/heads/old" }] });
+ });
+
+ it("waits for more while a line or the flush has not arrived, and refuses a body that ends first", () => {
+ const whole = bytes(RECORDED.create);
+ for (const cut of [0, 3, 4, 100, whole.length - 4, whole.length - 1]) {
+ expect(readCommandList(whole.subarray(0, cut), false)).toEqual({ state: "more" });
+ expect(readCommandList(whole.subarray(0, cut), true).state).toBe("bad");
+ }
+ });
+
+ it("reads a list fed in pieces once each: a 1 MiB list in 100-byte pieces costs about what it costs at once", () => {
+ const a = "a".repeat(40), b = "b".repeat(40);
+ let body = pkt(`${a} ${b} refs/heads/x0\u0000report-status\n`);
+ for (let i = 1; Buffer.byteLength(body) < 1000 * 1024 && i < MAX_COMMANDS; i++) body += pkt(`${a} ${b} refs/heads/x${i}\n`);
+ const whole = Buffer.from(`${body}0000`, "latin1");
+ const started = performance.now();
+ const reader = new CommandListReader();
+ let verdict = reader.feed(Buffer.alloc(0));
+ for (let at = 0; at < whole.length; at += 100) verdict = reader.feed(whole.subarray(at, at + 100));
+ // Re-reading everything on each piece took about 15 s here; one pass over the pieces takes well under a second.
+ expect(performance.now() - started).toBeLessThan(3_000);
+ expect(verdict).toMatchObject({ state: "done" });
+ expect((verdict as { commands: unknown[] }).commands.length).toBe(readCommandList(whole, true).state === "done" ? (readCommandList(whole, true) as { commands: unknown[] }).commands.length : -1);
+ });
+
+ it("refuses more commands than it takes, and a list longer than it takes without its end", () => {
+ const many = Buffer.from(`${Array.from({ length: MAX_COMMANDS + 1 }, (_, i) => pkt(`${A} ${B} refs/heads/b${i}`)).join("")}0000`, "latin1");
+ expect(readCommandList(many, true)).toEqual({ state: "bad", reason: "the push updates too many refs at once" });
+ const reader = new CommandListReader();
+ let verdict = reader.feed(Buffer.from(pkt(`${A} ${B} refs/heads/x\u0000report-status`), "latin1"));
+ // Lines too long for MAX_COMMANDS to be reached first.
+ const piece = Buffer.from(pkt(`${A} ${B} refs/heads/${"y".repeat(4000)}`).repeat(10), "latin1");
+ let sent = 0;
+ while (verdict.state === "more" && sent < 2 * MAX_COMMAND_BYTES) { verdict = reader.feed(piece); sent += piece.length; }
+ expect(verdict).toEqual({ state: "bad", reason: "the push updates too many refs at once" });
+ expect(sent).toBeGreaterThan(MAX_COMMAND_BYTES);
+ });
+
+ it("takes git's flush-only probe as a push of nothing, and shallow lines before the commands", () => {
+ expect(readCommandList(bytes("0000"), true)).toEqual({ state: "done", commands: [], capabilities: [] });
+ const shallow = `${pkt(`shallow ${A}`)}${pkt(`${A} ${B} refs/heads/x\u0000report-status`)}0000`;
+ expect(readCommandList(bytes(shallow), true)).toMatchObject({ state: "done", commands: [{ ref: "refs/heads/x" }] });
+ });
+
+ it("refuses what it cannot read: a signed push, a line that is no command, a ref outside refs/, a second capability list, a list too long", () => {
+ expect(readCommandList(bytes(`${pkt("push-cert\u0000report-status")}0000`), true)).toEqual({ state: "bad", reason: "signed pushes are not taken here" });
+ expect(readCommandList(bytes(`${pkt("hello world")}0000`), true).state).toBe("bad");
+ expect(readCommandList(bytes(`${pkt(`${A} ${B} HEAD`)}0000`), true).state).toBe("bad");
+ expect(readCommandList(bytes(`${pkt(`${A} ${B} refs/heads/a\u0000x`)}${pkt(`${A} ${B} refs/heads/b\u0000y`)}0000`), true).state).toBe("bad");
+ expect(readCommandList(bytes("zzzz"), false).state).toBe("bad");
+ expect(readCommandList(bytes("0003"), false).state).toBe("bad");
+ const long = Buffer.from(pkt(`${A} ${B} refs/heads/${"x".repeat(200)}`).repeat(Math.ceil(MAX_COMMAND_BYTES / 250) + 1), "latin1");
+ expect(readCommandList(long, false)).toEqual({ state: "bad", reason: "the push updates too many refs at once" });
+ });
+});
+
+describe("what the push guard refuses", () => {
+ const read = (text: string) => { const list = readCommandList(bytes(text), true); if (list.state !== "done") throw new Error(list.state); return list.commands; };
+
+ it("lets a new branch through and refuses the default branch and a delete", () => {
+ expect(refusedCommands(read(RECORDED.create), "refs/heads/main")).toEqual([]);
+ expect(refusedCommands(read(RECORDED.updateMain), "refs/heads/main")).toEqual([{ ref: "refs/heads/main", reason: "the default branch is protected here; push to a new branch" }]);
+ expect(refusedCommands(read(RECORDED.deleteOld), "refs/heads/main")).toEqual([{ ref: "refs/heads/old", reason: "deleting a ref is not allowed here; push to a new branch" }]);
+ });
+
+ it("protects the default branch it learned, and main and master when it learned none", () => {
+ expect(refusedCommands(read(RECORDED.updateMain), "refs/heads/trunk")).toEqual([]);
+ expect(refusedCommands([{ old: A, new: B, ref: "refs/heads/trunk" }], "refs/heads/trunk")).toHaveLength(1);
+ for (const ref of ["refs/heads/main", "refs/heads/master"]) expect(refusedCommands([{ old: A, new: B, ref }], null)).toHaveLength(1);
+ expect(refusedCommands([{ old: A, new: B, ref: "refs/heads/feature" }], null)).toEqual([]);
+ });
+
+ it("lets a new tag through but refuses moving or deleting one, and anything outside branches and tags", () => {
+ expect(refusedCommands([{ old: Z, new: B, ref: "refs/tags/v2" }], "refs/heads/main")).toEqual([]);
+ expect(refusedCommands([{ old: A, new: B, ref: "refs/tags/v1" }], "refs/heads/main")).toEqual([{ ref: "refs/tags/v1", reason: "moving a tag is not allowed here; push a new tag" }]);
+ expect(refusedCommands([{ old: A, new: Z, ref: "refs/tags/v1" }], "refs/heads/main")[0]!.reason).toContain("deleting a ref");
+ for (const ref of ["refs/pull/1/head", "refs/notes/commits", "refs/remotes/origin/x", "refs/heads"]) {
+ expect(refusedCommands([{ old: Z, new: B, ref }], "refs/heads/main"), ref).toEqual([{ ref, reason: "only branches and new tags may be pushed here; push to a new branch" }]);
+ }
+ });
+
+ it("refuses every update of a push in which one is refused", () => {
+ expect(refusedCommands([{ old: Z, new: B, ref: "refs/heads/ok" }, { old: A, new: Z, ref: "refs/tags/v1" }], "refs/heads/main")).toEqual([
+ { ref: "refs/heads/ok", reason: "not applied: another update in this push was refused" },
+ { ref: "refs/tags/v1", reason: "deleting a ref is not allowed here; push to a new branch" },
+ ]);
+ });
+});
+
+describe("the push guard's answers", () => {
+ it("reports each refused ref on side band 1 and the bot's message on side band 2, as receive-pack would", () => {
+ const refused = [{ ref: "refs/heads/main", reason: "the default branch is protected here; push to a new branch" }];
+ const message = refusalMessage(refused, "refs/heads/main");
+ expect(message).toContain("Push your work to a new branch");
+ expect(message).toContain("(main)");
+ const [progress, report] = packets(refusalBody({ capabilities: ["report-status-v2", "side-band-64k"], refused, message }));
+ expect(progress![0]).toBe(2);
+ expect(progress!.subarray(1).toString()).toBe(`${message}\n`);
+ expect(report![0]).toBe(1);
+ expect(packets(report!.subarray(1)).map((line) => line.toString())).toEqual(["unpack ok\n", "ng refs/heads/main the default branch is protected here; push to a new branch\n"]);
+ });
+
+ it("answers without side bands when none was asked, and an unreadable push as a failed unpack", () => {
+ const plain = refusalBody({ capabilities: ["report-status"], refused: [{ ref: "refs/heads/x", reason: "no\nnewlines" }], message: "m" });
+ expect(packets(plain).map((line) => line.toString())).toEqual(["unpack ok\n", "ng refs/heads/x no newlines\n"]);
+ expect(packets(refusalBody({ capabilities: [], refused: [], message: "This push was refused: x." })).map((line) => line.toString())).toEqual(["unpack This push was refused: x.\n"]);
+ });
+});
+
+describe("the default branch from an upload-pack ref list", () => {
+ // `git upload-pack --advertise-refs` (protocol v0) over HTTP, as git 2.50.1 sends it, with the service line first.
+ const advertised = `001e# service=git-upload-pack\n0000${pkt(`8c3fc07a2f7618abbd057b9ce868923c48acc74d HEAD\u0000multi_ack thin-pack side-band side-band-64k ofs-delta shallow no-done symref=HEAD:refs/heads/trunk object-format=sha1 agent=git/2.50.1\n`)}${pkt("8c3fc07a2f7618abbd057b9ce868923c48acc74d refs/heads/trunk\n")}0000`;
+
+ it("is HEAD's symref, read from the first ref line only", () => {
+ expect(advertisedDefaultBranch(bytes(advertised))).toBe("refs/heads/trunk");
+ expect(advertisedDefaultBranch(bytes(advertised.slice(0, 60)))).toBe("more");
+ });
+
+ it("is none for an empty repository's list or anything else", () => {
+ expect(advertisedDefaultBranch(bytes(`001e# service=git-upload-pack\n0000${pkt(`${Z} capabilities^{}\u0000multi_ack object-format=sha1\n`)}0000`))).toBeNull();
+ expect(advertisedDefaultBranch(bytes("<html>"))).toBeNull();
+ });
+});
diff --git a/server/bot-box/git-push-guard.ts b/server/bot-box/git-push-guard.ts
new file mode 100644
index 0000000000..d7ab24ec76
--- /dev/null
+++ b/server/bot-box/git-push-guard.ts
@@ -0,0 +1,154 @@
+// The push guard of the broker's github grant (broker-github.ts): reads the command list at the head of a smart-HTTP
+// receive-pack request (git's pkt-lines, before the pack) and decides before any byte reaches GitHub. A bot may create
+// and update branches other than the default one and create tags; it may not delete a ref, move a tag, update the
+// repository's default branch or touch anything outside refs/heads/ and refs/tags/ (refs/pull/, refs/notes/). It is a
+// boundary against the bot, not only against git, so anything it cannot read (a signed push, an unknown line, a list
+// too long) is refused. A force push to another branch is not detected: the command list names the old and new ids,
+// and whether one descends from the other needs the objects, which the broker does not have.
+
+/** A command list longer than this, or with more commands than MAX_COMMANDS, is refused rather than buffered. */
+export const MAX_COMMAND_BYTES = 1024 * 1024;
+export const MAX_COMMANDS = 5_000;
+const ZERO = /^0+$/;
+const COMMAND = /^([0-9a-f]{40}|[0-9a-f]{64}) ([0-9a-f]{40}|[0-9a-f]{64}) (refs\/[^\0\s]+)$/;
+const SHALLOW = /^shallow [0-9a-f]{40,64}$/;
+const NOT_GIT = "the push is not in git's format";
+
+export interface PushCommand { old: string; new: string; ref: string }
+
+export type CommandList =
+ | { state: "more" }
+ | { state: "done"; commands: PushCommand[]; capabilities: string[] }
+ | { state: "bad"; reason: string };
+
+/** Reads a command list as its bytes arrive: each pkt-line is read once, when it is whole, so a long list sent in small
+ * pieces costs no more than one sent at once. Only the part of a line not yet complete is kept between pieces. */
+export class CommandListReader {
+ private pending: Buffer = Buffer.alloc(0);
+ private seen = 0;
+ private readonly commands: PushCommand[] = [];
+ private capabilities: string[] = [];
+ private result: CommandList = { state: "more" };
+
+ /** The verdict after `chunk` (and with `ended`, after the body ended); once decided it no longer changes. */
+ feed(chunk: Buffer, ended = false): CommandList {
+ if (this.result.state !== "more") return this.result;
+ this.seen += chunk.length;
+ const buffer = this.pending.length ? Buffer.concat([this.pending, chunk]) : chunk;
+ let at = 0;
+ for (;;) {
+ if (buffer.length - at < 4) break;
+ const size = buffer.subarray(at, at + 4).toString("latin1");
+ if (!/^[0-9a-f]{4}$/.test(size)) return this.decide({ state: "bad", reason: NOT_GIT });
+ const length = parseInt(size, 16);
+ if (length === 0) return this.decide({ state: "done", commands: this.commands, capabilities: this.capabilities });
+ if (length < 5) return this.decide({ state: "bad", reason: NOT_GIT });
+ if (buffer.length - at < length) break;
+ const refused = this.line(buffer.subarray(at + 4, at + length).toString("utf8"));
+ if (refused) return this.decide({ state: "bad", reason: refused });
+ at += length;
+ }
+ this.pending = Buffer.from(buffer.subarray(at));
+ if (this.seen > MAX_COMMAND_BYTES) return this.decide({ state: "bad", reason: "the push updates too many refs at once" });
+ return ended ? this.decide({ state: "bad", reason: "the push ended early" }) : this.result;
+ }
+
+ /** Why one whole pkt-line is refused, or null. */
+ private line(text: string): string | null {
+ let line = text.endsWith("\n") ? text.slice(0, -1) : text;
+ const nul = line.indexOf("\0");
+ if (nul >= 0) {
+ if (this.commands.length) return NOT_GIT;
+ this.capabilities = line.slice(nul + 1).split(" ").filter(Boolean);
+ line = line.slice(0, nul);
+ }
+ if (line === "push-cert") return "signed pushes are not taken here";
+ if (SHALLOW.test(line) && !this.commands.length) return null;
+ const match = COMMAND.exec(line);
+ if (!match) return NOT_GIT;
+ if (this.commands.length >= MAX_COMMANDS) return "the push updates too many refs at once";
+ this.commands.push({ old: match[1]!, new: match[2]!, ref: match[3]! });
+ return null;
+ }
+
+ private decide(result: CommandList): CommandList {
+ this.pending = Buffer.alloc(0);
+ this.result = result;
+ return result;
+ }
+}
+
+/** The commands at the head of `head` (the bytes received so far; `ended`: the body has no more). */
+export function readCommandList(head: Buffer, ended: boolean): CommandList {
+ return new CommandListReader().feed(head, ended);
+}
+
+/** The ref names a push may not update: the default branch, or main and master when it is unknown. */
+export function protectedRefs(defaultBranch: string | null): string[] {
+ return defaultBranch ? [defaultBranch] : ["refs/heads/main", "refs/heads/master"];
+}
+
+/** Why one command is refused, or null. */
+function refusal(command: PushCommand, kept: ReadonlySet<string>): string | null {
+ if (ZERO.test(command.new)) return "deleting a ref is not allowed here; push to a new branch";
+ if (command.ref.startsWith("refs/tags/")) return ZERO.test(command.old) ? null : "moving a tag is not allowed here; push a new tag";
+ if (!command.ref.startsWith("refs/heads/")) return "only branches and new tags may be pushed here; push to a new branch";
+ return kept.has(command.ref) ? "the default branch is protected here; push to a new branch" : null;
+}
+
+/** Empty when the push may go; else every command with why, since a push with one refused update goes nowhere. */
+export function refusedCommands(commands: readonly PushCommand[], defaultBranch: string | null): Array<{ ref: string; reason: string }> {
+ const kept = new Set(protectedRefs(defaultBranch));
+ if (!commands.some((command) => refusal(command, kept) !== null)) return [];
+ return commands.map((command) => ({ ref: command.ref, reason: refusal(command, kept) ?? "not applied: another update in this push was refused" }));
+}
+
+/** The default branch from an upload-pack v0 ref advertisement (`symref=HEAD:refs/heads/x` on its first ref line):
+ * "more" until that line has arrived, null when it has none. */
+export function advertisedDefaultBranch(body: Buffer): string | null | "more" {
+ let at = 0;
+ for (;;) {
+ if (body.length - at < 4) return "more";
+ const size = body.subarray(at, at + 4).toString("latin1");
+ if (!/^[0-9a-f]{4}$/.test(size)) return null;
+ const length = parseInt(size, 16);
+ if (length === 0) { at += 4; continue; }
+ if (length < 5) return null;
+ if (body.length - at < length) return "more";
+ const line = body.subarray(at + 4, at + length).toString("utf8");
+ at += length;
+ if (line.startsWith("# service=")) continue;
+ const symref = /(?:^|[\0 ])symref=HEAD:(refs\/heads\/[^\s\0]+)/.exec(line);
+ return symref ? symref[1]! : null;
+ }
+}
+
+const pkt = (payload: Buffer | string) => {
+ const bytes = typeof payload === "string" ? Buffer.from(payload, "utf8") : payload;
+ return Buffer.concat([Buffer.from((bytes.length + 4).toString(16).padStart(4, "0"), "latin1"), bytes]);
+};
+const FLUSH = Buffer.from("0000", "latin1");
+
+/** What a refused push is answered with, as receive-pack would: its report-status (each ref `ng` with why, so git prints
+ * "! [remote rejected] <ref> (<why>)"), and `message` on side band 2 when the client asked for side bands, which git
+ * prints as "remote: ...". With no refs to name, the report says the unpack failed, with `message` as the reason. */
+export function refusalBody(input: { capabilities: readonly string[]; refused: ReadonlyArray<{ ref: string; reason: string }>; message: string }): Buffer {
+ const oneLine = (text: string) => text.replace(/[\r\n\0]+/g, " ").slice(0, 900);
+ const report = input.refused.length
+ ? Buffer.concat([pkt("unpack ok\n"), ...input.refused.map((item) => pkt(`ng ${item.ref} ${oneLine(item.reason)}\n`)), FLUSH])
+ : Buffer.concat([pkt(`unpack ${oneLine(input.message)}\n`), FLUSH]);
+ const reports = input.capabilities.includes("report-status") || input.capabilities.includes("report-status-v2") || !input.refused.length;
+ const sideband = input.capabilities.includes("side-band-64k") || input.capabilities.includes("side-band");
+ if (!sideband) return reports ? report : FLUSH;
+ const parts: Buffer[] = [pkt(Buffer.concat([Buffer.from([2]), Buffer.from(`${oneLine(input.message)}\n`, "utf8")]))];
+ if (reports) parts.push(pkt(Buffer.concat([Buffer.from([1]), report])));
+ parts.push(FLUSH);
+ return Buffer.concat(parts);
+}
+
+/** The message a bot reads on a refused push. */
+export function refusalMessage(refused: ReadonlyArray<{ ref: string; reason: string }>, defaultBranch: string | null): string {
+ const branch = defaultBranch ? defaultBranch.replace(/^refs\/heads\//, "") : "main or master";
+ if (!refused.length) return "This push was refused: push your work to a new branch, for example git push origin HEAD:refs/heads/<new-branch-name>.";
+ return `This push was refused: bots may not push to the default branch (${branch}), delete a branch or tag, move a tag, or push anything but branches and new tags here. Push your work to a new branch instead, for example git push origin HEAD:refs/heads/<new-branch-name>, and nothing in this push was applied.`;
+}
diff --git a/server/github/git-access.test.ts b/server/github/git-access.test.ts
new file mode 100644
index 0000000000..da5f6ba4ba
--- /dev/null
+++ b/server/github/git-access.test.ts
@@ -0,0 +1,131 @@
+import { afterEach, describe, expect, it } from "vitest";
+
+import { BOX_BROKER_PORT, BOX_EGRESS_PORT, BoxRunner } from "../bot-box/box.ts";
+import type { BrokerGrant } from "../bot-box/broker.ts";
+import { engineInstallRoots } from "../engine-roots.ts";
+import { gitAudience, provideGitAudience } from "./git-access.ts";
+import { GITHUB_REMOTE_FORMS, boxGitEnv, gitConfigParameters, shellQuote } from "./git-env.ts";
+import { provideGithubSignIn } from "./token.ts";
+
+const TOKEN = "ghp_boxPlanFakeToken0123456789abcdefABCD";
+const bridge = { socat: "/usr/bin/socat", bridgeScript: "/app/dist-server/bot-box/box-bridge.js", node: "/usr/local/bin/node" };
+const setup = {
+ dataDir: "/data/.openmausbot", home: "/data", codeRoots: ["/app"], engineRoots: engineInstallRoots("/data/.openmausbot"),
+ bridges: [{ name: "egress", port: BOX_EGRESS_PORT, socket: "/data/.openmausbot/box/egress.sock" }, { name: "broker", port: BOX_BROKER_PORT, socket: "/data/.openmausbot/box/broker.sock" }],
+};
+
+/** A broker that records what each token was minted with. */
+function fakeBroker() {
+ const minted: Array<{ token: string; threadId: string | null; grants: Record<string, BrokerGrant> }> = [];
+ const revoked: string[] = [];
+ let n = 0;
+ return {
+ minted, revoked,
+ broker: {
+ port: BOX_BROKER_PORT,
+ mintForProcess(input: { threadId?: string | null; grants: Record<string, BrokerGrant> }) {
+ const token = `omb_t0_${String(++n).padStart(48, "0")}`;
+ minted.push({ token, threadId: input.threadId ?? null, grants: input.grants });
+ return { token };
+ },
+ revoke(token: string) { revoked.push(token); },
+ },
+ };
+}
+
+function signIn(signedIn: (audience: string | null | undefined) => boolean) {
+ provideGithubSignIn({ token: async () => TOKEN, reportAuthFailure: () => {}, signedIn });
+}
+
+const wrapIn = (runner: BoxRunner, cwd: string, extra: Record<string, unknown> = {}) =>
+ runner.wrap({ command: "/usr/local/bin/claude", args: ["-p"], cwd, env: { PATH: "/usr/bin", HOME: "/data", GIT_CONFIG_PARAMETERS: "'core.hookspath=/tmp/x'", GIT_CONFIG_COUNT: "1" }, ...extra });
+
+describe("a boxed bot's git", () => {
+ afterEach(() => {
+ provideGithubSignIn(null);
+ provideGitAudience(null);
+ });
+
+ it("with a sign-in: every GitHub remote form goes to the broker under the process's token, and GitHub's token is nowhere in the box", () => {
+ signIn(() => true);
+ const { broker, minted } = fakeBroker();
+ const runner = new BoxRunner({ bwrap: "/usr/bin/bwrap", bridge, setup, denyEnv: new Set(), broker });
+ const wrapped = wrapIn(runner, "/data/.openmausbot/task-workspaces/b1/t1");
+ const process = minted.at(-1)!;
+ expect(wrapped.token).toBe(process.token);
+ expect(Object.keys(process.grants)).toEqual(["github"]);
+ expect(process.grants.github!.upstream).toBe("https://github.com");
+ expect(process.grants.github!.headers).toEqual({});
+ const origin = `http://127.0.0.1:${BOX_BROKER_PORT}`;
+ // The server's own git settings never pass the allow-list; only ours are there.
+ expect(wrapped.env.GIT_CONFIG_PARAMETERS).toBe(boxGitEnv({ port: BOX_BROKER_PORT, token: process.token }).GIT_CONFIG_PARAMETERS);
+ expect(wrapped.env.GIT_CONFIG_COUNT).toBeUndefined();
+ // The remote's address carries no token: git writes that address down (merge messages, FETCH_HEAD, errors).
+ for (const form of GITHUB_REMOTE_FORMS) expect(wrapped.env.GIT_CONFIG_PARAMETERS).toContain(shellQuote(`url.${origin}/g/github/.insteadof=${form}`));
+ expect(wrapped.env.GIT_CONFIG_PARAMETERS).not.toMatch(/insteadof=[^']*omb_t0_/);
+ expect(wrapped.env.GIT_CONFIG_PARAMETERS).not.toContain(`/b/${process.token}`);
+ // The token goes in a header git sends only to the broker's address, and no helper is asked for that address alone.
+ expect(wrapped.env.GIT_CONFIG_PARAMETERS).toContain(shellQuote(`http.${origin}/.extraheader=x-omb-broker: ${process.token}`));
+ expect(wrapped.env.GIT_CONFIG_PARAMETERS).toContain(shellQuote(`credential.${origin}.helper=`));
+ expect(wrapped.env.GIT_CONFIG_PARAMETERS).not.toContain("'credential.helper=");
+ expect(wrapped.env.GIT_TERMINAL_PROMPT).toBe("0");
+ // git reaches the broker's loopback port directly, not through the box's network gate.
+ expect(wrapped.env.HTTPS_PROXY).toBe(`http://127.0.0.1:${BOX_EGRESS_PORT}`);
+ for (const name of ["NO_PROXY", "no_proxy"]) expect(wrapped.env[name]!.split(",")).toContain("127.0.0.1");
+ expect(JSON.stringify([wrapped.env, wrapped.args, wrapped.command])).not.toContain(TOKEN);
+ });
+
+ it("survives each engine's shell: no name holds KEY, SECRET or TOKEN, which Codex's default shell policy drops", () => {
+ for (const name of Object.keys(boxGitEnv({ port: 18080, token: `omb_t0_${"a".repeat(48)}` }))) expect(name).not.toMatch(/KEY|SECRET|TOKEN/i);
+ });
+
+ it("with no sign-in: nothing changes, no token is minted for git and no git setting is added", () => {
+ signIn(() => false);
+ const { broker, minted, revoked } = fakeBroker();
+ const runner = new BoxRunner({ bwrap: "/usr/bin/bwrap", bridge, setup, denyEnv: new Set(), broker });
+ const wrapped = wrapIn(runner, "/data/.openmausbot/task-workspaces/b1/t1");
+ expect(wrapped.token).toBeNull();
+ expect(minted.map((entry) => entry.token)).toEqual(revoked);
+ expect(Object.keys(wrapped.env).filter((name) => name.startsWith("GIT_"))).toEqual([]);
+ provideGithubSignIn(null);
+ expect(Object.keys(wrapIn(runner, "/data/.openmausbot/task-workspaces/b1/t1").env).filter((name) => name.startsWith("GIT_"))).toEqual([]);
+ });
+
+ it("shares the one per-process token with a provider key the broker took over", () => {
+ signIn(() => true);
+ const { broker, minted } = fakeBroker();
+ const runner = new BoxRunner({ bwrap: "/usr/bin/bwrap", bridge, setup, denyEnv: new Set(), broker });
+ const wrapped = runner.wrap({ command: "/usr/local/bin/claude", args: [], cwd: "/data/.openmausbot/task-workspaces/b1/t1", env: { PATH: "/usr/bin", ANTHROPIC_API_KEY: "sk-ant-real" } });
+ const process = minted.at(-1)!;
+ expect(Object.keys(process.grants).sort()).toEqual(["anthropic", "github"]);
+ expect(wrapped.env.ANTHROPIC_API_KEY).toBe(process.token);
+ expect(wrapped.env.GIT_CONFIG_PARAMETERS).toContain(`x-omb-broker: ${process.token}`);
+ });
+
+ it("on a Team Cloud: the member's own conversation gets that member's sign-in; a room's, the team's and a shared process get none", () => {
+ const asked: Array<string | null | undefined> = [];
+ signIn((audience) => { asked.push(audience); return audience === "p_aaaaaaaaaaaaaaaaaaaaaa"; });
+ provideGitAudience((threadId) => (threadId === "mine" ? "p_aaaaaaaaaaaaaaaaaaaaaa" : null));
+ const { broker, minted } = fakeBroker();
+ const runner = new BoxRunner({ bwrap: "/usr/bin/bwrap", bridge, setup, denyEnv: new Set(), broker });
+ expect(wrapIn(runner, "/data/.openmausbot/task-workspaces/b1/mine").env.GIT_CONFIG_PARAMETERS).toContain("/github/");
+ expect(minted.at(-1)!.grants.github).toBeDefined();
+ expect(wrapIn(runner, "/data/.openmausbot/task-workspaces/b1/room").env.GIT_CONFIG_PARAMETERS).toBeUndefined();
+ expect(wrapIn(runner, "/data/.openmausbot/task-workspaces/b1/mine", { botThreads: true }).env.GIT_CONFIG_PARAMETERS).toBeUndefined();
+ expect(asked).toEqual(["p_aaaaaaaaaaaaaaaaaaaaaa"]);
+ expect(gitAudience(null)).toBeNull();
+ provideGitAudience(null);
+ expect(gitAudience(null)).toBe("owner");
+ expect(gitAudience("any")).toBe("owner");
+ });
+});
+
+describe("git settings in the environment", () => {
+ it("are quoted as git quotes them and added after what is there", () => {
+ expect(shellQuote("it's")).toBe("'it'\\''s'");
+ expect(gitConfigParameters([["a.b", "c d"]], "'x.y=z'")).toBe("'x.y=z' 'a.b=c d'");
+ expect(gitConfigParameters([["a.b", ""]])).toBe("'a.b='");
+ expect(() => gitConfigParameters([["a=b", "c"]])).toThrow();
+ expect(() => gitConfigParameters([["a.b", "c\nd"]])).toThrow();
+ });
+});
diff --git a/server/github/git-access.ts b/server/github/git-access.ts
new file mode 100644
index 0000000000..68a9f4e4f1
--- /dev/null
+++ b/server/github/git-access.ts
@@ -0,0 +1,44 @@
+// Which GitHub sign-in a bot's git uses, and what a boxed spawn gets for it. Off a Team Cloud it is the server's one
+// ("owner"). On a Team Cloud the host registers who a conversation is private to (cloud-team-host.ts): a member's own
+// conversation gets that member's sign-in, a room's, the team's or a shared one gets none, and a process the bot's
+// conversations share gets none. With no sign-in for that audience a spawn gets nothing at all: no grant, no env.
+import { GITHUB_GRANT, githubGrant } from "../bot-box/broker-github.ts";
+import type { BrokerGrant } from "../bot-box/broker.ts";
+import { boxGitEnv } from "./git-env.ts";
+import { conversationRepos } from "./git-repos.ts";
+import { githubSignedIn, githubToken, reportGithubAuthFailure } from "./token.ts";
+
+let memberOf: ((threadId: string) => string | null) | null = null;
+
+/** On a Team Cloud: the person a conversation is private to, or null. Null takes it away (off a team). */
+export function provideGitAudience(resolver: ((threadId: string) => string | null) | null): void {
+ memberOf = resolver;
+}
+
+/** Whose sign-in git in `threadId` uses (null: a process several conversations share), or null for none. */
+export function gitAudience(threadId: string | null): string | null {
+ if (!memberOf) return "owner";
+ if (!threadId) return null;
+ try {
+ return memberOf(threadId);
+ } catch {
+ return null;
+ }
+}
+
+let processes = 0;
+
+/** The github grant and git env for one boxed spawn, or null when its audience has no sign-in. The audience is asked
+ * again on every request, so a conversation shared later stops getting the member's token at once. `folders`: where the
+ * spawn works (its conversation's folder, a project folder), whose clones it may push to. */
+export function boxGithubGit(threadId: string | null, folders: readonly string[]): { grant: BrokerGrant; env(input: { port: number; token: string }): Record<string, string> } | null {
+ const audience = gitAudience(threadId);
+ if (!audience || !githubSignedIn(audience)) return null;
+ const repos = conversationRepos(threadId ? `thread:${threadId}` : `process:${++processes}`, folders);
+ return {
+ grant: githubGrant({ audience: () => gitAudience(threadId), token: (who) => githubToken(who), reportAuthFailure: (who) => reportGithubAuthFailure(who), mayPush: repos.mayPush, fetched: repos.fetched }),
+ env: boxGitEnv,
+ };
+}
+
+export { GITHUB_GRANT };
diff --git a/server/github/git-credential.test.ts b/server/github/git-credential.test.ts
new file mode 100644
index 0000000000..bc52b5b62c
--- /dev/null
+++ b/server/github/git-credential.test.ts
@@ -0,0 +1,142 @@
+import { spawn, spawnSync } from "node:child_process";
+import { createServer, type Server } from "node:http";
+import { mkdtempSync, rmSync } from "node:fs";
+import type { AddressInfo } from "node:net";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it } from "vitest";
+
+import { json, readBody } from "../harness/http.ts";
+import type { RequestAuth } from "../request-auth.ts";
+import { GIT_CREDENTIAL_TTL_MS, createGitCredentialRoutes, resetGitCredentials, unboxedGitCredential } from "./git-credential.ts";
+import { GIT_CREDENTIAL_HEADER, GIT_CREDENTIAL_PATH, unboxedGitEnv } from "./git-env.ts";
+import { provideGithubSignIn } from "./token.ts";
+
+const TOKEN = "ghp_helperFakeToken0123456789abcdefABCD";
+const loopback = { kind: "loopback", scopes: [] } as unknown as RequestAuth;
+
+/** The route behind a plain server, with `auth` standing in for the auth gate's verdict. */
+async function serve(route: ReturnType<typeof createGitCredentialRoutes>, auth: RequestAuth = loopback): Promise<{ server: Server; port: number }> {
+ const server = createServer((req, res) => {
+ const url = new URL(req.url ?? "/", "http://127.0.0.1");
+ void route({ req, res, url, path: url.pathname, method: req.method ?? "GET", auth, json, readBody }).then((out) => { if (!res.headersSent) res.writeHead(404).end(); return out; });
+ });
+ await new Promise<void>((done) => server.listen(0, "127.0.0.1", () => done()));
+ return { server, port: (server.address() as AddressInfo).port };
+}
+
+describe("the unboxed credential helper", () => {
+ let server: Server | null = null, dir: string | null = null, clock = 1_800_000_000_000;
+ afterEach(async () => {
+ resetGitCredentials();
+ provideGithubSignIn(null);
+ await new Promise<void>((done) => server ? server.close(() => done()) : done());
+ server = null;
+ if (dir) rmSync(dir, { recursive: true, force: true });
+ dir = null;
+ });
+
+ it("is added only where the route is served, enabled and signed in, after the person's own git settings", () => {
+ const env = { PATH: "/usr/bin", GIT_CONFIG_PARAMETERS: "'user.name=Me'" };
+ expect(unboxedGitCredential(env)).toBeNull();
+ let enabled = false;
+ createGitCredentialRoutes({ port: 8799, enabled: () => enabled });
+ provideGithubSignIn({ token: async () => TOKEN, reportAuthFailure: () => {}, signedIn: (who) => who === "owner" });
+ expect(unboxedGitCredential(env)).toBeNull();
+ enabled = true;
+ const added = unboxedGitCredential(env)!;
+ expect(added.env.GIT_CONFIG_PARAMETERS!.startsWith("'user.name=Me' 'credential.https://github.com.helper=!f() {")).toBe(true);
+ expect(added.env.PATH).toBe("/usr/bin");
+ expect(JSON.stringify(added.env)).not.toContain(TOKEN);
+ provideGithubSignIn({ token: async () => TOKEN, reportAuthFailure: () => {}, signedIn: () => false });
+ expect(unboxedGitCredential(env)).toBeNull();
+ });
+
+ it("answers git's credential lines to the loopback with a live secret only, and nothing once the process exited", async () => {
+ createGitCredentialRoutes({ port: 1, enabled: () => true, now: () => clock });
+ provideGithubSignIn({ token: async () => TOKEN, reportAuthFailure: () => {}, signedIn: () => true });
+ const route = createGitCredentialRoutes({ port: 1, enabled: () => true, now: () => clock });
+ ({ server } = await serve(route));
+ const port = (server.address() as AddressInfo).port;
+ const added = unboxedGitCredential({})!;
+ const secret = /x-omb-git-credential: ([A-Za-z0-9_-]+)/.exec(added.env.GIT_CONFIG_PARAMETERS!)![1]!;
+ const ask = (headers: Record<string, string>, method = "GET") => fetch(`http://127.0.0.1:${port}${GIT_CREDENTIAL_PATH}`, { method, headers });
+ const good = await ask({ [GIT_CREDENTIAL_HEADER]: secret });
+ expect(good.status).toBe(200);
+ expect(good.headers.get("cache-control")).toBe("no-store");
+ expect(await good.text()).toBe(`username=x-access-token\npassword=${TOKEN}\n`);
+ expect((await ask({})).status).toBe(403);
+ expect((await ask({ [GIT_CREDENTIAL_HEADER]: `${secret.slice(0, -1)}x` })).status).toBe(403);
+ expect((await ask({ [GIT_CREDENTIAL_HEADER]: secret }, "POST")).status).toBe(403);
+ clock += GIT_CREDENTIAL_TTL_MS;
+ expect((await ask({ [GIT_CREDENTIAL_HEADER]: secret })).status).toBe(403);
+ clock -= GIT_CREDENTIAL_TTL_MS;
+ added.release();
+ expect((await ask({ [GIT_CREDENTIAL_HEADER]: secret })).status).toBe(403);
+ });
+
+ it("never answers a session or a shared server's bot shells, and nothing for a signed-out server", async () => {
+ provideGithubSignIn({ token: async () => null, reportAuthFailure: () => {}, signedIn: () => true });
+ const route = createGitCredentialRoutes({ port: 1, enabled: () => true });
+ const added = unboxedGitCredential({})!;
+ const secret = /x-omb-git-credential: ([A-Za-z0-9_-]+)/.exec(added.env.GIT_CONFIG_PARAMETERS!)![1]!;
+ for (const auth of [{ kind: "session", scopes: ["admin"] }, { kind: "loopback", scopes: [], trust: "service" }]) {
+ ({ server } = await serve(route, auth as unknown as RequestAuth));
+ expect((await fetch(`http://127.0.0.1:${(server.address() as AddressInfo).port}${GIT_CREDENTIAL_PATH}`, { headers: { [GIT_CREDENTIAL_HEADER]: secret } })).status).toBe(403);
+ await new Promise<void>((done) => server!.close(() => done()));
+ }
+ ({ server } = await serve(route));
+ expect((await fetch(`http://127.0.0.1:${(server.address() as AddressInfo).port}${GIT_CREDENTIAL_PATH}`, { headers: { [GIT_CREDENTIAL_HEADER]: secret } })).status).toBe(204);
+ });
+
+ it("refuses a secret or port that is not one", () => {
+ expect(() => unboxedGitEnv({ port: 8799, secret: "a b" })).toThrow();
+ expect(() => unboxedGitEnv({ port: 0, secret: "a".repeat(24) })).toThrow();
+ });
+
+ // The helper as git runs it: `git credential fill` with the spawn's environment, through git's shell and curl.
+ const haveTools = spawnSync("git", ["--version"]).status === 0 && spawnSync("curl", ["--version"]).status === 0;
+ it.skipIf(!haveTools)("gives git the token for github.com, after a helper of the person's own that has nothing, and nothing for another host", async () => {
+ dir = mkdtempSync(join(tmpdir(), "omb-git-helper-"));
+ provideGithubSignIn({ token: async () => TOKEN, reportAuthFailure: () => {}, signedIn: () => true });
+ const route = createGitCredentialRoutes({ port: 1, enabled: () => true });
+ ({ server } = await serve(route));
+ createGitCredentialRoutes({ port: (server.address() as AddressInfo).port, enabled: () => true });
+ const base = { PATH: process.env.PATH ?? "", HOME: dir, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: join(dir, "nothing"), GIT_TERMINAL_PROMPT: "0", ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}) };
+ const added = unboxedGitCredential({ ...base, GIT_CONFIG_PARAMETERS: "'credential.helper=!true'" })!;
+ const fill = (host: string, env: Record<string, string | undefined>) => new Promise<{ status: number | null; out: string }>((resolve) => {
+ const child = spawn("git", ["credential", "fill"], { env: env as NodeJS.ProcessEnv, stdio: ["pipe", "pipe", "ignore"] });
+ let out = "";
+ child.stdout.on("data", (chunk) => { out += chunk; });
+ child.on("close", (status) => resolve({ status, out }));
+ child.stdin.end(`protocol=https\nhost=${host}\n\n`);
+ });
+ const github = await fill("github.com", added.env);
+ expect(github.status).toBe(0);
+ expect(github.out).toContain("username=x-access-token\n");
+ expect(github.out).toContain(`password=${TOKEN}\n`);
+ expect((await fill("gitlab.example", added.env)).status).not.toBe(0);
+ added.release();
+ });
+
+ it.skipIf(!haveTools)("leaves the person's own working credentials in charge: their helper answers and ours is never asked", async () => {
+ dir = mkdtempSync(join(tmpdir(), "omb-git-helper-"));
+ provideGithubSignIn({ token: async () => TOKEN, reportAuthFailure: () => {}, signedIn: () => true });
+ let asked = 0;
+ const counted = createGitCredentialRoutes({ port: 1, enabled: () => true });
+ ({ server } = await serve(async (ctx) => { asked += 1; return counted(ctx); }));
+ createGitCredentialRoutes({ port: (server.address() as AddressInfo).port, enabled: () => true });
+ const own = "'credential.helper=!f() { echo username=me; echo password=mine; }; f'";
+ const added = unboxedGitCredential({ PATH: process.env.PATH ?? "", HOME: dir, GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: join(dir, "nothing"), GIT_CONFIG_PARAMETERS: own, ...(process.env.SystemRoot ? { SystemRoot: process.env.SystemRoot } : {}) })!;
+ const out = await new Promise<string>((resolve) => {
+ const child = spawn("git", ["credential", "fill"], { env: added.env as NodeJS.ProcessEnv, stdio: ["pipe", "pipe", "ignore"] });
+ let text = "";
+ child.stdout.on("data", (chunk) => { text += chunk; });
+ child.on("close", () => resolve(text));
+ child.stdin.end("protocol=https\nhost=github.com\n\n");
+ });
+ expect(out).toContain("password=mine");
+ expect(asked).toBe(0);
+ added.release();
+ });
+});
diff --git a/server/github/git-credential.ts b/server/github/git-credential.ts
new file mode 100644
index 0000000000..bedb62a15b
--- /dev/null
+++ b/server/github/git-credential.ts
@@ -0,0 +1,63 @@
+// GitHub for an unboxed bot's git on This computer: no broker there, so each bot spawn gets a credential helper for
+// github.com (git-env.ts unboxedGitEnv) that asks this server's loopback for the token with a secret minted for that
+// spawn, which dies with the process. It is appended after the person's own helpers, so their own working credentials
+// still win, and it is never written to any git config file. Only off Clouds and off a team (a Cloud's loopback is every
+// bot's shell, and a boxed bot gets the broker's github grant instead). An unboxed bot runs as the person and can read
+// what their own gh holds anyway; here it could ask the helper's address for the token too.
+import { randomBytes, timingSafeEqual } from "node:crypto";
+
+import { GIT_CREDENTIAL_HEADER, GIT_CREDENTIAL_PATH, unboxedGitEnv } from "./git-env.ts";
+import { githubSignedIn, githubToken } from "./token.ts";
+import { PASS, type RouteHandler } from "../routes/table.ts";
+
+/** A secret lives this long at most; its process's exit ends it sooner. */
+export const GIT_CREDENTIAL_TTL_MS = 24 * 60 * 60_000;
+const MAX_SECRETS = 2_000;
+
+let served: { port: number; enabled(): boolean; now(): number } | null = null;
+const secrets = new Map<string, number>();
+
+/** Test seam: forget every secret and the route's settings. */
+export function resetGitCredentials(): void {
+ secrets.clear();
+ served = null;
+}
+
+/** An unboxed bot spawn's env with the helper added, and what to call when it exits; null leaves the spawn as it is
+ * (the route is not served here, it is a Cloud or a team, or there is no GitHub sign-in). */
+export function unboxedGitCredential(env: Record<string, string | undefined>): { env: Record<string, string | undefined>; release(): void } | null {
+ if (!served || !served.enabled() || !githubSignedIn("owner")) return null;
+ const at = served.now();
+ for (const [secret, expires] of secrets) if (expires <= at) secrets.delete(secret);
+ if (secrets.size >= MAX_SECRETS) secrets.delete(secrets.keys().next().value!);
+ const secret = randomBytes(24).toString("base64url");
+ secrets.set(secret, at + GIT_CREDENTIAL_TTL_MS);
+ return { env: { ...env, ...unboxedGitEnv({ port: served.port, secret, existing: env.GIT_CONFIG_PARAMETERS }) }, release: () => { secrets.delete(secret); } };
+}
+
+const known = (presented: string, now: number): boolean => {
+ const given = Buffer.from(presented);
+ for (const [secret, expires] of secrets) {
+ const held = Buffer.from(secret);
+ if (expires > now && held.length === given.length && timingSafeEqual(held, given)) return true;
+ }
+ return false;
+};
+
+/** The route git's helper asks: the owner-trust loopback only (never a shared server's bot shells), with a live spawn's secret; the answer is git's credential lines. */
+export function createGitCredentialRoutes(deps: { port: number; enabled(): boolean; now?(): number }): RouteHandler {
+ const now = deps.now ?? Date.now;
+ served = { port: deps.port, enabled: deps.enabled, now };
+ return async ({ req, res, path, method, auth }) => {
+ if (path !== GIT_CREDENTIAL_PATH) return PASS;
+ res.setHeader("cache-control", "no-store");
+ const presented = req.headers[GIT_CREDENTIAL_HEADER];
+ if (method !== "GET" || auth.kind !== "loopback" || auth.trust === "service" || !deps.enabled() || typeof presented !== "string" || !known(presented, now())) {
+ res.writeHead(403, { "content-type": "text/plain" }).end("forbidden\n");
+ return;
+ }
+ const token = await githubToken("owner");
+ if (!token) { res.writeHead(204).end(); return; }
+ res.writeHead(200, { "content-type": "text/plain; charset=utf-8" }).end(`username=x-access-token\npassword=${token}\n`);
+ };
+}
diff --git a/server/github/git-env.ts b/server/github/git-env.ts
new file mode 100644
index 0000000000..bdcdd99ac4
--- /dev/null
+++ b/server/github/git-env.ts
@@ -0,0 +1,53 @@
+// A bot's git settings for GitHub, carried in its environment only: never a file, never the person's ~/.gitconfig.
+// They go in GIT_CONFIG_PARAMETERS, the variable `git -c` itself hands to the gits it starts. GIT_CONFIG_COUNT with
+// GIT_CONFIG_KEY_<n> would not survive: Codex's shell drops every variable whose name holds KEY, and a count whose keys
+// are gone makes every git command fail. Each entry is written `'name=value'`, which every git since 2.0 reads.
+import { BROKER_TOKEN_HEADER, brokerHeaderUrl } from "../bot-box/broker.ts";
+
+/** git's own shell quoting of one word (quote.c sq_quote). */
+export function shellQuote(word: string): string {
+ return `'${word.replace(/'/g, "'\\''")}'`;
+}
+
+/** `entries` added after whatever `existing` (a GIT_CONFIG_PARAMETERS value) already holds. */
+export function gitConfigParameters(entries: ReadonlyArray<readonly [string, string]>, existing?: string): string {
+ const ours = entries.map(([name, value]) => {
+ if (name.includes("=") || /[\0\n]/.test(name) || /[\0\n]/.test(value)) throw new Error(`Not a git setting: ${name.slice(0, 60)}`);
+ return shellQuote(`${name}=${value}`);
+ }).join(" ");
+ return existing?.trim() ? `${existing.trim()} ${ours}` : ours;
+}
+
+/** The forms of a github.com remote the box sends through the broker: HTTPS, and the SSH ones, which then go over HTTPS. */
+export const GITHUB_REMOTE_FORMS = ["https://github.com/", "[email protected]:", "ssh://[email protected]/"] as const;
+
+/** A boxed bot's git: every GitHub remote through the broker's github grant at http://127.0.0.1:<port>/g/github/,
+ * with the broker token in a header git sends only to that address. The token is never in the address, so it never
+ * reaches what git writes down (merge messages, FETCH_HEAD, `git remote -v`, error text). No credential helper is asked
+ * for that address (the broker adds the credential), and git never prompts; credential helpers for other hosts stay. */
+export function boxGitEnv(input: { port: number; token: string }): Record<string, string> {
+ if (!/^omb_t0_[a-f0-9]{48}$/.test(input.token)) throw new Error("Not a broker token.");
+ const origin = `http://127.0.0.1:${input.port}`;
+ const url = `url.${brokerHeaderUrl(input.port, "github")}/.insteadof`;
+ return {
+ GIT_CONFIG_PARAMETERS: gitConfigParameters([
+ ...GITHUB_REMOTE_FORMS.map((form) => [url, form] as const),
+ [`http.${origin}/.extraheader`, `${BROKER_TOKEN_HEADER}: ${input.token}`],
+ [`credential.${origin}.helper`, ""],
+ ]),
+ GIT_TERMINAL_PROMPT: "0",
+ };
+}
+
+/** The header the credential helper sends its secret in (server/github/git-credential.ts). */
+export const GIT_CREDENTIAL_HEADER = "x-omb-git-credential";
+export const GIT_CREDENTIAL_PATH = "/api/github/git-credential";
+
+/** The credential helper of an unboxed bot (This computer): for github.com only, asked after the person's own helpers,
+ * so their own working credentials still win; it asks this server for the token with the spawn's secret. curl comes with
+ * macOS, Windows 10 and later, and Git for Windows' shell, so the helper names no path of this machine. */
+export function unboxedGitEnv(input: { port: number; secret: string; existing?: string }): Record<string, string> {
+ if (!/^[A-Za-z0-9_-]{16,128}$/.test(input.secret) || !Number.isInteger(input.port) || input.port < 1 || input.port > 65_535) throw new Error("Not a git credential helper.");
+ const helper = `!f() { test "$1" = get || exit 0; curl -fsS --noproxy 127.0.0.1 --max-time 30 -H "${GIT_CREDENTIAL_HEADER}: ${input.secret}" "http://127.0.0.1:${input.port}${GIT_CREDENTIAL_PATH}"; }; f`;
+ return { GIT_CONFIG_PARAMETERS: gitConfigParameters([["credential.https://github.com.helper", helper]], input.existing) };
+}
diff --git a/server/github/git-repos.test.ts b/server/github/git-repos.test.ts
new file mode 100644
index 0000000000..1afbb162c6
--- /dev/null
+++ b/server/github/git-repos.test.ts
@@ -0,0 +1,71 @@
+import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+import { conversationRepos, forgetConversationRepos, githubRepoOf, remoteUrls, reposOnDisk } from "./git-repos.ts";
+
+describe("a github.com remote's repository", () => {
+ it("in every form git takes, the broker's included", () => {
+ for (const url of [
+ "https://github.com/Acme/Widgets.git", "https://github.com/acme/widgets", "https://github.com/acme/widgets/", "http://github.com/acme/widgets.git",
+ "https://[email protected]/acme/widgets.git", "[email protected]:acme/widgets.git", "ssh://[email protected]/acme/widgets", "ssh://[email protected]:22/acme/widgets.git",
+ "http://127.0.0.1:18080/g/github/acme/widgets.git", `http://127.0.0.1:18080/b/omb_t0_${"a".repeat(48)}/github/acme/widgets`,
+ ]) expect(githubRepoOf(url), url).toBe("acme/widgets");
+ expect(githubRepoOf("https://github.com/acme/my.repo.git")).toBe("acme/my.repo");
+ });
+
+ it("and nothing for another host, another shape or a traversal", () => {
+ for (const url of ["https://gitlab.com/acme/widgets.git", "https://github.com.evil.example/acme/widgets", "https://github.com/acme", "https://github.com/acme/widgets/tree/main", "https://github.com/acme/..", "/srv/git/widgets.git", "../widgets"]) {
+ expect(githubRepoOf(url), url).toBeNull();
+ }
+ });
+
+ it("read from a config file's remote sections only", () => {
+ const config = `[core]\n\turl = https://github.com/not/a-remote\n[remote "origin"]\n\turl = https://github.com/acme/one.git\n\tfetch = +refs/heads/*:refs/remotes/origin/*\n[remote "fork"]\n\tpushurl = "[email protected]:me/two.git"\n[branch "main"]\n\tremote = origin\n`;
+ expect(remoteUrls(config)).toEqual(["https://github.com/acme/one.git", "[email protected]:me/two.git"]);
+ expect(remoteUrls(config.replace(/\n/g, "\r\n"))).toEqual(["https://github.com/acme/one.git", "[email protected]:me/two.git"]);
+ });
+});
+
+describe("the repositories a conversation works in", () => {
+ let dir: string;
+ beforeEach(() => { dir = mkdtempSync(join(tmpdir(), "omb-git-repos-")); });
+ afterEach(() => { rmSync(dir, { recursive: true, force: true }); forgetConversationRepos(); });
+
+ const clone = (folder: string, url: string) => {
+ mkdirSync(join(folder, ".git"), { recursive: true });
+ writeFileSync(join(folder, ".git", "config"), `[remote "origin"]\n\turl = ${url}\n`);
+ };
+
+ // A link needs a privilege on Windows; the box that uses this runs only on Linux.
+ it.skipIf(process.platform === "win32")("are the clones in its folders and up to two levels below, worktrees too, and no link is followed", async () => {
+ clone(join(dir, "conv"), "https://github.com/acme/root.git");
+ clone(join(dir, "conv", "one"), "[email protected]:acme/one.git");
+ clone(join(dir, "conv", "a", "two"), "https://github.com/acme/two");
+ clone(join(dir, "conv", "a", "b", "three"), "https://github.com/acme/three");
+ clone(join(dir, "conv", "node_modules", "dep"), "https://github.com/acme/dep");
+ clone(join(dir, "elsewhere", "secret"), "https://github.com/acme/secret");
+ symlinkSync(join(dir, "elsewhere"), join(dir, "conv", "link"));
+ // A worktree: its .git is a file naming its git folder, whose common folder holds the config.
+ clone(join(dir, "main"), "https://github.com/acme/worktreed");
+ mkdirSync(join(dir, "main", ".git", "worktrees", "wt"), { recursive: true });
+ writeFileSync(join(dir, "main", ".git", "worktrees", "wt", "commondir"), "../..\n");
+ mkdirSync(join(dir, "conv", "wt"));
+ writeFileSync(join(dir, "conv", "wt", ".git"), `gitdir: ${join(dir, "main", ".git", "worktrees", "wt")}\n`);
+ expect([...await reposOnDisk([join(dir, "conv")])].sort()).toEqual(["acme/one", "acme/root", "acme/two", "acme/worktreed"]);
+ expect([...await reposOnDisk([join(dir, "nowhere")])]).toEqual([]);
+ });
+
+ it("may be pushed to once cloned there or fetched through the broker in that conversation, and not from another", async () => {
+ clone(join(dir, "conv", "work"), "https://github.com/acme/work.git");
+ const mine = conversationRepos("thread:t1", [join(dir, "conv")]);
+ const theirs = conversationRepos("thread:t2", [join(dir, "other")]);
+ expect(await mine.mayPush("acme/work")).toBe(true);
+ expect(await mine.mayPush("acme/fetched")).toBe(false);
+ mine.fetched("acme/fetched");
+ expect(await conversationRepos("thread:t1", []).mayPush("acme/fetched")).toBe(true);
+ expect(await theirs.mayPush("acme/fetched")).toBe(false);
+ expect(await theirs.mayPush("acme/work")).toBe(false);
+ });
+});
diff --git a/server/github/git-repos.ts b/server/github/git-repos.ts
new file mode 100644
index 0000000000..649a1cde0b
--- /dev/null
+++ b/server/github/git-repos.ts
@@ -0,0 +1,112 @@
+// Which GitHub repositories a conversation works in, for the github grant's push scope (server/bot-box/broker-github.ts
+// mayPush): those its folders already hold clones of (their remotes, read from each clone's config file as text: no git
+// is run, so nothing a repository configures runs), and those it cloned or fetched through the broker since this server
+// started. A push to any other repository is refused. Reads are not narrowed by this.
+import { lstat, readdir, readFile } from "node:fs/promises";
+import { isAbsolute, join, resolve } from "node:path";
+
+/** How far below a folder clones are looked for, and how many folders are looked in at most. */
+const DEPTH = 2;
+const MAX_FOLDERS = 400;
+const MAX_CONFIG_BYTES = 256 * 1024;
+const MAX_CONVERSATIONS = 2_000;
+const MAX_REPOS_EACH = 500;
+const SKIPPED = new Set(["node_modules", ".git", ".venv", "venv", "__pycache__", "target", "dist", "build"]);
+
+/** owner/name (lower case) of a github.com remote in any form git takes, including the broker's own address; else null. */
+export function githubRepoOf(url: string): string | null {
+ const value = url.trim();
+ const match = /^(?:https?:\/\/(?:[^@/]+@)?github\.com\/|git@github\.com:|ssh:\/\/git@github\.com(?::22)?\/|http:\/\/127\.0\.0\.1:\d+\/(?:g\/github|b\/[^/]+\/github)\/)([A-Za-z0-9][A-Za-z0-9-]{0,38})\/([A-Za-z0-9._-]{1,100}?)(?:\.git)?\/?$/i.exec(value);
+ if (!match) return null;
+ const name = match[2]!;
+ return name === "." || name === ".." ? null : `${match[1]}/${name}`.toLowerCase();
+}
+
+/** The remote URLs a git config file names (`url` and `pushurl` of each `[remote "…"]` section). */
+export function remoteUrls(config: string): string[] {
+ const urls: string[] = [];
+ let inRemote = false;
+ for (const raw of config.split(/\r?\n/)) {
+ const line = raw.trim();
+ if (line.startsWith("[")) { inRemote = /^\[remote\s+"[^"]*"\]/i.test(line); continue; }
+ if (!inRemote) continue;
+ const match = /^(url|pushurl)\s*=\s*(.*)$/i.exec(line);
+ if (match) urls.push(match[2]!.replace(/^"(.*)"$/, "$1"));
+ }
+ return urls;
+}
+
+async function readSmall(file: string): Promise<string | null> {
+ try {
+ const info = await lstat(file);
+ if (!info.isFile() || info.size > MAX_CONFIG_BYTES) return null;
+ return await readFile(file, "utf8");
+ } catch {
+ return null;
+ }
+}
+
+/** The config file of the clone at `folder`: `.git/config`, or for a worktree or submodule whose `.git` is a file, its
+ * git folder's (or that folder's common one's). Links are not followed. */
+async function cloneConfig(folder: string): Promise<string | null> {
+ const dotGit = join(folder, ".git");
+ let info;
+ try { info = await lstat(dotGit); } catch { return null; }
+ if (info.isDirectory()) return readSmall(join(dotGit, "config"));
+ if (!info.isFile()) return null;
+ const pointer = /^gitdir:\s*(.+)$/m.exec((await readSmall(dotGit)) ?? "")?.[1]?.trim();
+ if (!pointer) return null;
+ const gitDir = isAbsolute(pointer) ? pointer : resolve(folder, pointer);
+ const own = await readSmall(join(gitDir, "config"));
+ if (own !== null) return own;
+ const common = (await readSmall(join(gitDir, "commondir")))?.trim();
+ return common ? readSmall(join(isAbsolute(common) ? common : resolve(gitDir, common), "config")) : null;
+}
+
+/** The GitHub repositories cloned in `folders` or up to two levels below them. */
+export async function reposOnDisk(folders: readonly string[]): Promise<Set<string>> {
+ const found = new Set<string>();
+ const queue: Array<{ folder: string; depth: number }> = [...new Set(folders.map((folder) => resolve(folder)))].map((folder) => ({ folder, depth: 0 }));
+ let visited = 0;
+ while (queue.length && visited < MAX_FOLDERS) {
+ const { folder, depth } = queue.shift()!;
+ visited += 1;
+ const config = await cloneConfig(folder);
+ for (const url of config ? remoteUrls(config) : []) {
+ const repo = githubRepoOf(url);
+ if (repo) found.add(repo);
+ }
+ if (depth >= DEPTH) continue;
+ let entries;
+ try { entries = await readdir(folder, { withFileTypes: true }); } catch { continue; }
+ for (const entry of entries) {
+ if (entry.isDirectory() && !entry.isSymbolicLink() && !SKIPPED.has(entry.name)) queue.push({ folder: join(folder, entry.name), depth: depth + 1 });
+ }
+ }
+ return found;
+}
+
+const fetchedBy = new Map<string, Set<string>>();
+
+/** What one conversation (or one process several share, keyed by its own key) may push to. */
+export function conversationRepos(key: string, folders: readonly string[]): { mayPush(repo: string): Promise<boolean>; fetched(repo: string): void } {
+ return {
+ async mayPush(repo) {
+ return fetchedBy.get(key)?.has(repo) === true || (await reposOnDisk(folders)).has(repo);
+ },
+ fetched(repo) {
+ let repos = fetchedBy.get(key);
+ if (!repos) {
+ repos = new Set();
+ fetchedBy.set(key, repos);
+ if (fetchedBy.size > MAX_CONVERSATIONS) fetchedBy.delete(fetchedBy.keys().next().value!);
+ }
+ if (repos.size < MAX_REPOS_EACH) repos.add(repo);
+ },
+ };
+}
+
+/** Test seam: forget what conversations fetched. */
+export function forgetConversationRepos(): void {
+ fetchedBy.clear();
+}
diff --git a/server/github/personal-hosts.test.ts b/server/github/personal-hosts.test.ts
new file mode 100644
index 0000000000..3bb25cd56d
--- /dev/null
+++ b/server/github/personal-hosts.test.ts
@@ -0,0 +1,30 @@
+import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { describe, expect, it } from "vitest";
+
+import { personalGhHostsFile, personalGhLogin } from "./personal-hosts.ts";
+
+describe("the person's own gh hosts file", () => {
+ it("is where gh keeps it on each platform", () => {
+ expect(personalGhHostsFile({ GH_CONFIG_DIR: "/cfg", XDG_CONFIG_HOME: "/xdg", HOME: "/home/me" }, "linux")).toBe(join("/cfg", "hosts.yml"));
+ expect(personalGhHostsFile({ XDG_CONFIG_HOME: "/xdg", HOME: "/home/me" }, "linux")).toBe(join("/xdg", "gh", "hosts.yml"));
+ expect(personalGhHostsFile({ HOME: "/Users/me" }, "darwin")).toBe(join("/Users/me", ".config", "gh", "hosts.yml"));
+ expect(personalGhHostsFile({ AppData: "C:\\Users\\me\\AppData\\Roaming", HOME: "C:\\Users\\me" }, "win32")).toBe(join("C:\\Users\\me\\AppData\\Roaming", "GitHub CLI", "hosts.yml"));
+ });
+
+ it("names a login only when it lists a github.com account", () => {
+ const dir = mkdtempSync(join(tmpdir(), "omb-gh-hosts-"));
+ try {
+ expect(personalGhLogin({ GH_CONFIG_DIR: dir })).toBeNull();
+ writeFileSync(join(dir, "hosts.yml"), "ghe.example.com:\n user: corp\n");
+ expect(personalGhLogin({ GH_CONFIG_DIR: dir })).toBeNull();
+ writeFileSync(join(dir, "hosts.yml"), "github.com:\n git_protocol: https\n user: octo\n");
+ expect(personalGhLogin({ GH_CONFIG_DIR: dir })).toBe("octo");
+ mkdirSync(join(dir, "folder.yml"));
+ expect(personalGhLogin({ GH_CONFIG_DIR: join(dir, "folder.yml") })).toBeNull();
+ } finally {
+ rmSync(dir, { recursive: true, force: true });
+ }
+ });
+});
diff --git a/server/github/personal-hosts.ts b/server/github/personal-hosts.ts
new file mode 100644
index 0000000000..66e42b4dc2
--- /dev/null
+++ b/server/github/personal-hosts.ts
@@ -0,0 +1,25 @@
+// Whether the person's own GitHub CLI has an account for github.com, from its hosts file alone: for a spawn that must
+// decide at once whether to set git up, where a gh program on PATH says nothing about a sign-in. gh keeps the file in
+// GH_CONFIG_DIR, else XDG_CONFIG_HOME/gh, else %AppData%/GitHub CLI on Windows, else ~/.config/gh. The token itself is
+// often in the OS keyring and is not read here.
+import { readFileSync } from "node:fs";
+import { homedir } from "node:os";
+import { join } from "node:path";
+
+import { hostsFileLogin } from "./gh-output.ts";
+
+export function personalGhHostsFile(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): string {
+ if (env.GH_CONFIG_DIR) return join(env.GH_CONFIG_DIR, "hosts.yml");
+ if (env.XDG_CONFIG_HOME) return join(env.XDG_CONFIG_HOME, "gh", "hosts.yml");
+ if (platform === "win32" && env.AppData) return join(env.AppData, "GitHub CLI", "hosts.yml");
+ return join(env.HOME || homedir(), ".config", "gh", "hosts.yml");
+}
+
+/** The login the person's own gh lists for github.com, or null. */
+export function personalGhLogin(env: NodeJS.ProcessEnv = process.env, platform: NodeJS.Platform = process.platform): string | null {
+ try {
+ return hostsFileLogin(readFileSync(personalGhHostsFile(env, platform), "utf8"));
+ } catch {
+ return null;
+ }
+}
diff --git a/server/github/sign-in.test.ts b/server/github/sign-in.test.ts
index f49966774a..d5deb67617 100644
--- a/server/github/sign-in.test.ts
+++ b/server/github/sign-in.test.ts
@@ -430,6 +430,44 @@ describe("the accessor for server-side callers", () => {
provideGithubSignIn(null);
}
});
+
+ it("says from disk alone whether an audience has a sign-in, without running gh", async () => {
+ const { githubSignedIn, provideGithubSignIn } = await import("./token.ts");
+ expect(githubSignedIn("owner")).toBe(false);
+ const team = setup({ team: true });
+ expect(team.signIn.signedIn(MEMBER)).toBe(false);
+ const child = await showCode(team, MEMBER);
+ child.approve();
+ await settle();
+ const calls = team.calls.length;
+ provideGithubSignIn(team.signIn);
+ try {
+ expect(githubSignedIn(MEMBER)).toBe(true);
+ expect(githubSignedIn(OTHER)).toBe(false);
+ expect(githubSignedIn("owner")).toBe(false);
+ expect(githubSignedIn()).toBe(false);
+ expect(team.calls.length).toBe(calls);
+ } finally {
+ provideGithubSignIn(null);
+ }
+ const own = setup();
+ expect(own.signIn.signedIn()).toBe(false);
+ own.vault.saved.set("owner", { token: TOKEN, login: "octo" });
+ expect(own.signIn.signedIn()).toBe(true);
+ own.vault.saved.clear();
+ // A gh on PATH is not a sign-in: only one whose hosts file lists a github.com account.
+ const ghConfig = join(dataDir, "personal-gh");
+ mkdirSync(ghConfig);
+ vi.stubEnv("GH_CONFIG_DIR", ghConfig);
+ own.set.personal = "/usr/local/bin/gh";
+ expect(own.signIn.signedIn("owner")).toBe(false);
+ writeFileSync(join(ghConfig, "hosts.yml"), "github.com:\n git_protocol: https\n users:\n octo:\n user: octo\n");
+ expect(own.signIn.signedIn("owner")).toBe(true);
+ expect(own.signIn.signedIn(MEMBER)).toBe(false);
+ own.set.personal = null;
+ expect(own.signIn.signedIn("owner")).toBe(false);
+ vi.unstubAllEnvs();
+ });
});
describe("only Start downloads, and overlapping asks share one answer", () => {
diff --git a/server/github/sign-in.ts b/server/github/sign-in.ts
index a7117441e9..e565f5287a 100644
--- a/server/github/sign-in.ts
+++ b/server/github/sign-in.ts
@@ -18,6 +18,7 @@ import type { GithubSignInLast, GithubSignInSource, GithubSignInStatus } from ".
import type { VaultStore } from "../vault-store.ts";
import { GH_SIGN_IN_FLOOR, loginArgs, ownGhEnv, personalGhEnv, type GhChild, type GhTools } from "./gh-cli.ts";
import { hostsFileLogin, hostsFileToken, loginFailure, parseDeviceCode, parseScopes, parseStatusJson, parseStatusText, plain, tokenFrom, versionAtLeast, type GhAccount } from "./gh-output.ts";
+import { personalGhLogin } from "./personal-hosts.ts";
/** GitHub's device codes last 15 minutes (its `expires_in`, 900 s); gh does not print it. */
export const DEVICE_CODE_TTL_MS = 15 * 60_000;
@@ -85,6 +86,10 @@ export interface GithubSignIn {
token(audience?: string | null): Promise<string | null>;
/** A git or GitHub call with this audience's token was refused: the next status asks GitHub again. */
reportAuthFailure(audience?: string | null): void;
+ /** Whether `audience` has a sign-in to ask token() for, answered from disk without running gh or asking GitHub: for a
+ * spawn that must decide at once whether to set git up (server/github/git-access.ts). It may say yes for a sign-in
+ * GitHub no longer accepts; token() is still the answer. */
+ signedIn(audience?: string | null): boolean;
/** A member who left a Team Cloud: their sign-in folder and pasted token go. */
forgetPerson(person: string): void;
}
@@ -475,6 +480,15 @@ export function createGithubSignIn(deps: GithubSignInDeps): GithubSignIn {
const audience = resolve(audienceIn);
if (audience) of(audience).stale = true;
},
+ signedIn(audienceIn) {
+ const audience = resolve(audienceIn);
+ if (!audience) return false;
+ try {
+ return ownSignedIn(audience) || deps.vault.githubToken(audience) !== null || (!deps.team && deps.tools.personal() !== null && personalGhLogin() !== null);
+ } catch {
+ return false;
+ }
+ },
forgetPerson(person) {
if (!AUDIENCE.test(person) || person === OWNER) return;
const state = audiences.get(person);
diff --git a/server/github/token.ts b/server/github/token.ts
index a3b2908c9e..c65eea6c71 100644
--- a/server/github/token.ts
+++ b/server/github/token.ts
@@ -4,9 +4,9 @@
// environment or arguments.
import type { GithubSignIn } from "./sign-in.ts";
-let current: Pick<GithubSignIn, "token" | "reportAuthFailure"> | null = null;
+let current: Pick<GithubSignIn, "token" | "reportAuthFailure" | "signedIn"> | null = null;
-export function provideGithubSignIn(signIn: Pick<GithubSignIn, "token" | "reportAuthFailure"> | null): void {
+export function provideGithubSignIn(signIn: Pick<GithubSignIn, "token" | "reportAuthFailure" | "signedIn"> | null): void {
current = signIn;
}
@@ -20,3 +20,8 @@ export function githubToken(audience?: string | null): Promise<string | null> {
export function reportGithubAuthFailure(audience?: string | null): void {
current?.reportAuthFailure(audience);
}
+
+/** Whether `audience` has a sign-in, from disk only (GithubSignIn.signedIn): false with none provided. */
+export function githubSignedIn(audience?: string | null): boolean {
+ return current ? current.signedIn(audience) : false;
+}
diff --git a/server/host/cloud-team-host.ts b/server/host/cloud-team-host.ts
index 27ecdd55d8..8753530172 100644
--- a/server/host/cloud-team-host.ts
+++ b/server/host/cloud-team-host.ts
@@ -13,6 +13,7 @@ import { storeThreads, type StoreBotThreads } from "../engine-homes/migrate.ts";
import type { ConversationShares } from "./conversation-shares.ts";
import { createTeamBoxScope, type TeamBoxBots, type TeamBoxScopeDeps } from "./team-box-scope.ts";
import type { BoxAudienceScope } from "../bot-box/box.ts";
+import { provideGitAudience } from "../github/git-access.ts";
export interface CloudTeamHostDeps {
team: CloudTeam | null;
@@ -58,6 +59,8 @@ export function createCloudTeamHost(deps: CloudTeamHostDeps) {
};
if (team) deps.engineHomes?.start({ dataDir: deps.dataDir, audienceOf, threads: () => storeThreads(deps.store.bots ?? []) });
if (team) deps.box?.scopeAudiences(createTeamBoxScope({ audienceOf, bots: () => deps.store.bots ?? [], ...(deps.teamFiles ? { teamFiles: deps.teamFiles } : {}) }));
+ // A bot's git uses the GitHub sign-in of the member whose own conversation it is, and nobody's elsewhere.
+ if (team) provideGitAudience((threadId) => ownPerson(audienceOf(threadId)));
/** The layer a turn in this conversation writes into: the bot's own folder off a team or for the team's conversations,
* a sibling folder for a room's or a member's. The folder exists before the turn starts, so the box can bind it. */
const layer = (botId: string, threadId: string): string => {
diff --git a/server/index.ts b/server/index.ts
index 84b9f02d05..147c97916c 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -114,7 +114,7 @@ import { boatCreateRecoverySnapshot } from "./boat-create-idempotency.ts";
import { boatDeletionSnapshot } from "./boat-delete-journal.ts";
import { liveDecisionRefusal } from "../shared/live-approval.ts"; import type { PersonWaitKind } from "../shared/person-wait.ts";
import { vpsLeftBehindNotice, vpsNotChosenReason } from "./cloud-backend.ts";
-import * as composio from "./composio.ts"; import { createConnectorListingRoutes } from "./routes/connectors-listing.ts"; import { createGhTools } from "./github/gh-cli.ts"; import { createGithubSignIn } from "./github/sign-in.ts"; import { provideGithubSignIn } from "./github/token.ts"; import { createGithubSignInRoutes } from "./routes/github-sign-in.ts";
+import * as composio from "./composio.ts"; import { createConnectorListingRoutes } from "./routes/connectors-listing.ts"; import { createGhTools } from "./github/gh-cli.ts"; import { createGithubSignIn } from "./github/sign-in.ts"; import { provideGithubSignIn } from "./github/token.ts"; import { createGitCredentialRoutes } from "./github/git-credential.ts"; import { createGithubSignInRoutes } from "./routes/github-sign-in.ts";
import { appSandboxRule, connectorCallFromFrame, connectorRefusalText, connectorScopeRefusalText, connectorUnrecognizedText, evaluateConnectorTools } from "./connector-verdict.ts";
import { signInCardText } from "./connector-card-text.ts";
import { BOT_HELD_CODE, BOT_PAUSED_CODE } from "../shared/bot-limit.ts"; import { createBotHolds } from "./host/bot-holds.ts"; import { createBotHoldRoutes } from "./routes/bot-holds.ts"; import { createCliLogin } from "./routes/cli-login.ts"; import { createStarterAwake } from "./host/starter-awake.ts"; import { createStarterCaps } from "./host/starter-caps.ts"; import { createStarterRoutineWake, workInFlight, type StarterRoutineWake } from "./host/starter-routine-wake.ts"; import { createStarterAwakeRoutes } from "./routes/starter-awake.ts"; import { chiefOfStaffPrompt, chiefOfStaffSystemPrompt } from "./chief-of-staff.ts"; import { coordinateMessageMax, coordinateTooLong, reportBackTooLong } from "./too-long.ts"; import { chiefAbsentFrom, createChiefRooms } from "./host/chief-rooms.ts"; import { chiefLevel, readTeamRolesWith } from "./chief-level.ts"; import { defaultBotRefusal, ensureDefaultBot } from "./default-bot.ts";
@@ -12059,7 +12059,7 @@ const teamMoveIn = CLOUD_TEAM ? createTeamMoveIn({ team: CLOUD_TEAM, dataDir: DA
if (CLOUD_TEAM) teamHost.adoptServerProfile(sessions.list().flatMap((session) => session.email ? [session.email] : []));
const sidebarRoutes = createSidebarSectionRoutes({ store, teamComputers, maxBots: MAX_WORKSPACE_BOTS, assertTeamComputerChangeIdle, wireBot, renamed: (from, to) => (to ? botHolds.rename(from, to) : botHolds.forget("department", from)) }); ROUTES.push(teamPresence.routes, sidebarRoutes, createPresenceRoutes({ isOwner: ownerOrAdmin, heard: (auth, language) => personLanguages.heard(auth.kind === "session" ? actorKey(auth) : THIS_COMPUTER, language), sawChat: (_auth, threadId) => { if (store.botByThread(threadId)) sawThread(threadId); }, active: async (source, zone, language) => { const answer = await proactive.brief.active(source, zone, language); firstHourHooks.arrived(); return answer; }, ...(CLOUD_TEAM ? { member: (auth) => { noAiNotice.flush(); return teamMessages.arrived(auth); } } : {}) }), createMeRoutes({ team: CLOUD_TEAM, session: (auth) => (auth.kind === "session" ? auth.session : null), welcome: teamWelcome, profile: teamHost.memberProfile, save: teamHost.saveMemberProfile, seed: teamHost.seedMemberProfile, seeded: teamHost.seededFields, changed: () => broadcast({ kind: "config", ...configStatus() }), names: SELF_HOSTED ? { store: personNames, shownAs: sessionPersonName } : null }), teamAway.routes, createTeamPhoneRoutes({ team: CLOUD_TEAM, sessions, publicBase: (req, auth) => pairingLinkBase(publicUrl(), auth.kind === "session" ? requestOrigin(req) : null) }),
createTeamConnectionRoutes({ host: teamConnections, cfg: () => cfg, composio, policy: managedPolicy, publicOrigin: CLOUD_HOME?.publicOrigin ?? null, record: (auth, row) => appendAdminAction(DATA_DIR, { ...row, actor: decisionActorFor(auth) }) }), createSignInCardRoutes({ settle: signInSettle.settle, saveLogin: (botId, threadId, messageId, body, auth) => CLOUD_TEAM && !auth.scopes.includes("admin") ? Promise.resolve({ status: 403 as const, body: memberLoginRefusal(CLOUD_TEAM) }) : saveLoginFromCard(botId, threadId, messageId, body), saveTarget: signInSaveTarget, threadVisible: (auth, threadId) => visibleTo(viewerFor(auth)).thread(threadId), vault: createSignInVaultChoices({ logins, cardBots: (id) => botLogins.cardBots(id), settle: signInSettle.settle, openCard: (botId, threadId, messageId) => { const card = signInMessage(botId, threadId, messageId)?.signIn; return card && card.place === "browser" && !card.superseded && !card.answeredInChat && !card.stopped && !signInOutcome(card) ? card : null; } }) })); const appSuggestions = createAppSuggestions({ dataDir: DATA_DIR, store, configured: () => composio.configured(cfg), catalog: () => composio.listToolkits(cfg), services: async (live) => live ? composio.connectedServices(cfg) : (await composio.sharedConnectedInventory(cfg)).services, offerable: (slug) => !managedPolicy.appRefusal(slug) && !managedConnectorUnavailableReason(composio.connectionMode(cfg), slug) && !teamConnections.personApps().includes(slug), pickAvailable: () => appPickAvailable(cfg), decider }); ROUTES.push(createAppSuggestionRoutes(appSuggestions));
-ROUTES.push(createConnectorListingRoutes({ cfg: () => cfg, composio, managedHost: DESKTOP_MANAGED || CLOUD_HOME !== null })); composio.rememberCatalogIn(DATA_DIR); composio.onCatalogChange(() => broadcast({ kind: "apps-catalog" }, { adminOnly: true })); const githubSignIn = createGithubSignIn({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM), vault: logins, tools: createGhTools({ dataDir: DATA_DIR, personalAllowed: () => !CLOUD_HOME && !HOSTED_WORKSPACE && !botBox.enabled() }), remember: (token) => heldSecrets.remember(token, "password") }); provideGithubSignIn(githubSignIn); ROUTES.push(createGithubSignInRoutes({ signIn: githubSignIn, team: Boolean(CLOUD_TEAM) }));
+ROUTES.push(createConnectorListingRoutes({ cfg: () => cfg, composio, managedHost: DESKTOP_MANAGED || CLOUD_HOME !== null })); composio.rememberCatalogIn(DATA_DIR); composio.onCatalogChange(() => broadcast({ kind: "apps-catalog" }, { adminOnly: true })); const githubSignIn = createGithubSignIn({ dataDir: DATA_DIR, team: Boolean(CLOUD_TEAM), vault: logins, tools: createGhTools({ dataDir: DATA_DIR, personalAllowed: () => !CLOUD_HOME && !HOSTED_WORKSPACE && !botBox.enabled() }), remember: (token) => heldSecrets.remember(token, "password") }); provideGithubSignIn(githubSignIn); ROUTES.push(createGithubSignInRoutes({ signIn: githubSignIn, team: Boolean(CLOUD_TEAM) })); ROUTES.push(createGitCredentialRoutes({ port: PORT, enabled: () => !CLOUD_HOME && !HOSTED_WORKSPACE && !CLOUD_TEAM && !botBox.enabled() }));
ROUTES.push(createRoomHoldRoutes({
group: (id) => store.group(id),
groupFor: personRooms.groupForAuth,
diff --git a/server/procs.ts b/server/procs.ts
index 74f41c16fc..4807d1f2ef 100644
--- a/server/procs.ts
+++ b/server/procs.ts
@@ -28,6 +28,7 @@ import { spawnBotWork } from "./oom-score.ts";
import { noticeFailure } from "./chat-notices.ts";
import { processBudget } from "./process-room.ts";
import { shortageCode } from "./process-shortage.ts";
+import { unboxedGitCredential } from "./github/git-credential.ts";
export function resolveCli(cli: string, args: string[] = [], env?: NodeJS.ProcessEnv): ResolvedSpawn {
return resolveCliSpawn(cli, args, env);
@@ -418,6 +419,9 @@ export function spawnCli(
: homed ? { ...opts, env } : opts;
const boxed = boxedSpawn(resolved, options, owner, homed);
const { box: _box, engineHome: _engineHome, botWork, ...spawnOpts } = boxed ? options : outsideBoxOptions(resolved.command, options);
+ // An unboxed bot's git gets this server's GitHub sign-in after the person's own credentials (git-credential.ts).
+ const github = !boxed && owner === "bot" ? unboxedGitCredential(spawnOpts.env ?? process.env) : null;
+ if (github) spawnOpts.env = github.env as NodeJS.ProcessEnv;
// The box's extra descriptors (its seccomp filter) follow stdio; only a plain three-entry stdio can take them.
const stdio = boxed?.extraFds.length && Array.isArray(spawnOpts.stdio) && spawnOpts.stdio.length === 3 ? [...spawnOpts.stdio, ...boxed.extraFds] : spawnOpts.stdio;
// A server that restarts in place stops what an earlier one left by this tag (engine-records.ts).
@@ -436,6 +440,7 @@ export function spawnCli(
} catch (error) {
// Node throws some refusals (ENOMEM) at once rather than reporting them on the child.
if (shortageCode(error)) refused((error as NodeJS.ErrnoException).code);
+ github?.release();
throw error;
} finally {
for (const fd of boxed?.extraFds ?? []) try { closeSync(fd); } catch {}
@@ -445,6 +450,7 @@ export function spawnCli(
child.once("error", (error: NodeJS.ErrnoException) => { if (!child.pid) refused(error.code); });
// The broker token minted for this process dies with it.
if (boxed?.token) child.once("exit", boxed.release);
+ if (github) { child.once("exit", github.release); child.once("error", () => { if (!child.pid) github.release(); }); }
if (process.platform !== "win32") cliGroups.add(child);
if ((process.platform === "linux" || process.platform === "darwin") && child.pid) {
const tree = new Map<number, string>();
diff --git a/server/testing/fake-github-git.ts b/server/testing/fake-github-git.ts
new file mode 100644
index 0000000000..f487f60823
--- /dev/null
+++ b/server/testing/fake-github-git.ts
@@ -0,0 +1,78 @@
+// Test fixture: a stand-in for github.com's git over HTTPS, serving bare repositories with git's own `http-backend`
+// (smart HTTP, both upload-pack and receive-pack), behind a Basic credential check like GitHub's. Plain HTTP on the
+// loopback; the broker's github grant is pointed at it in code (server/bot-box/broker-github.ts GithubGrantDeps.upstream).
+import { spawn, spawnSync } from "node:child_process";
+import { createServer, type IncomingHttpHeaders, type Server } from "node:http";
+import type { AddressInfo } from "node:net";
+import { join } from "node:path";
+
+export interface FakeGithub {
+ url: string;
+ seen: Array<{ method: string; url: string; headers: IncomingHttpHeaders }>;
+ close(): Promise<void>;
+}
+
+/** Where git's http-backend is, or null when this git has none. */
+export function httpBackend(): string | null {
+ const found = spawnSync("git", ["--exec-path"], { encoding: "utf8" });
+ if (found.status !== 0) return null;
+ const file = join(found.stdout.trim(), "git-http-backend");
+ return spawnSync(file, [], { env: { PATH: process.env.PATH ?? "", REQUEST_METHOD: "GET", PATH_INFO: "/" }, encoding: "utf8" }).error ? null : file;
+}
+
+/** Serves every bare repository under `root` at /<owner>/<repo>.git, answering 401 to any request without `basic`. */
+export function openFakeGithub(input: { root: string; backend: string; basic: string }): Promise<FakeGithub> {
+ const seen: FakeGithub["seen"] = [];
+ const server: Server = createServer((req, res) => {
+ seen.push({ method: req.method ?? "", url: req.url ?? "", headers: req.headers });
+ if (req.headers.authorization !== input.basic) {
+ req.resume();
+ res.writeHead(401, { "www-authenticate": 'Basic realm="GitHub"', "content-type": "text/plain" }).end("Invalid username or token.\n");
+ return;
+ }
+ const url = new URL(req.url ?? "/", "http://fake");
+ const child = spawn(input.backend, [], {
+ env: {
+ PATH: process.env.PATH ?? "", GIT_PROJECT_ROOT: input.root, GIT_HTTP_EXPORT_ALL: "1", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null",
+ REQUEST_METHOD: req.method ?? "GET", PATH_INFO: decodeURIComponent(url.pathname), QUERY_STRING: url.search.slice(1),
+ CONTENT_TYPE: String(req.headers["content-type"] ?? ""), REMOTE_USER: "x-access-token", REMOTE_ADDR: "127.0.0.1",
+ ...(req.headers["content-length"] ? { CONTENT_LENGTH: String(req.headers["content-length"]) } : {}),
+ ...(req.headers["content-encoding"] ? { HTTP_CONTENT_ENCODING: String(req.headers["content-encoding"]) } : {}),
+ ...(req.headers["git-protocol"] ? { GIT_PROTOCOL: String(req.headers["git-protocol"]) } : {}),
+ },
+ stdio: ["pipe", "pipe", "ignore"],
+ });
+ req.pipe(child.stdin);
+ child.stdin.on("error", () => {});
+ let head = Buffer.alloc(0), started = false;
+ child.stdout.on("data", (chunk: Buffer) => {
+ if (started) { res.write(chunk); return; }
+ head = Buffer.concat([head, chunk]);
+ const text = head.toString("latin1");
+ const end = text.search(/\r?\n\r?\n/);
+ if (end < 0) return;
+ const gap = /\r?\n\r?\n/.exec(text.slice(end))![0].length;
+ let status = 200;
+ const headers: Record<string, string> = {};
+ for (const line of text.slice(0, end).split(/\r?\n/)) {
+ const at = line.indexOf(":");
+ const name = line.slice(0, at).trim().toLowerCase(), value = line.slice(at + 1).trim();
+ if (name === "status") status = Number.parseInt(value, 10);
+ else if (name) headers[name] = value;
+ }
+ started = true;
+ res.writeHead(status, headers);
+ res.write(head.subarray(end + gap));
+ });
+ child.stdout.on("end", () => { if (!started) res.writeHead(502); res.end(); });
+ });
+ return new Promise((resolve) => {
+ server.listen(0, "127.0.0.1", () => {
+ resolve({
+ url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
+ seen,
+ close: () => new Promise<void>((closed) => { server.closeAllConnections(); server.close(() => closed()); }),
+ });
+ });
+ });
+}