diff --git a/doc/execution-github-identity.md b/doc/execution-github-identity.md index 945e7427809..10786facda0 100644 --- a/doc/execution-github-identity.md +++ b/doc/execution-github-identity.md @@ -48,6 +48,8 @@ security boundary: any command that receives the token can call the GitHub API. A `git` command that never uses the network does not ask the broker. The launcher reads past the global options, such as `-C` and `-c`, and checks the subcommand against a short list (for example `status`, `diff`, `diff-files`, `write-tree`, `log`, `rev-parse`, `add`, `config`, `branch`, `checkout`). This includes the index comparison and tree writing used by workspace snapshots. An unknown subcommand or option still asks. `commit` and `var` still ask, because the managed author comes from the broker answer. The launcher keeps no broker answer between invocations and never writes a credential to a file. +A local command can still need GitHub. In a partial (blobless) clone, `git show`, `git blame`, `git log -p` and a checkout of another revision fetch the file contents they need from the origin. For a local `git` command, the launcher sets itself as `GIT_ASKPASS`. Git calls askpass only after every credential helper declines. The launcher answers only for `https://github.com` and `https://www.github.com`. It asks the broker on the first password prompt and keeps that answer in memory for the rest of the command, so one command asks the broker at most once. A command that fetches nothing does not ask the broker. Askpass prompts reach the command's launcher through a Unix socket in a private temporary directory. If that socket cannot be created, each prompt asks the broker itself. Anonymous launchers and launchers without a broker capability do not set askpass. + GitHub credential capture reads the current task, project, and retained trust policy bindings without transferring saved prompts, runner profiles, results, or log excerpts. It keeps the existing task/run lock order and accepted-identity diff --git a/doc/workspace-storage.md b/doc/workspace-storage.md index 92dc535f532..a34af183503 100644 --- a/doc/workspace-storage.md +++ b/doc/workspace-storage.md @@ -111,6 +111,15 @@ precedence over the stored choice. Enrolled workspaces retain remote authority when enrollment is disabled; losing a storage prerequisite fails their admission instead of falling back to a controller checkout. +A fresh sandbox clone of a network Git remote (`https`, `http`, `ssh`, `git`, or +`user@host:path`) is a blobless partial clone (`--filter=blob:none`). It holds all +commits and trees but only the file contents that its checkout needs, so a large +history does not use the sandbox's per-command Git storage budget. Git fetches +other file contents from the origin when a command needs them. Agent commands +get the run's GitHub credential for these fetches through the managed launcher +(see `doc/execution-github-identity.md`). Snapshots keep the promisor remote. A local path or `file://` +origin is cloned in full, because a snapshot cannot keep a machine-local promisor. + After enrollment, roll back only to binaries that understand the same remote workspace authority and saved-version format. Older local-only binaries are unsupported rollback targets. diff --git a/packages/adapter-utils/src/github-launcher.test.ts b/packages/adapter-utils/src/github-launcher.test.ts index 4bf744b0ece..99975e2370f 100644 --- a/packages/adapter-utils/src/github-launcher.test.ts +++ b/packages/adapter-utils/src/github-launcher.test.ts @@ -1,6 +1,6 @@ import { execFile } from "node:child_process"; import { createServer } from "node:http"; -import { mkdtemp, mkdir, readFile, writeFile, rm } from "node:fs/promises"; +import { mkdtemp, mkdir, readFile, realpath, writeFile, rm } from "node:fs/promises"; import os from "node:os"; import path from "node:path"; import { promisify } from "node:util"; @@ -411,6 +411,100 @@ process.stdout.write(JSON.stringify({identity, token:process.env.GH_TOKEN ?? nul expect((await git("-C", "repo", "commit", "--allow-empty", "-m", "Managed work")).posts).toBe(1); expect((await git("-C", "repo", "log", "-1", "--format=%an <%ae>")).stdout).toBe("Managed "); }, 20_000); + it.each([false, true])("lets a local git command fetch a private object with the managed credential only when Git asks (broker file: %s)", async brokerFile => { + const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-lazy-")); + cleanups.push(() => rm(root, { recursive: true, force: true })); + // Git runs GIT_ASKPASS without a shell, so a quote and space in the path are safe. + const bin = path.join(root, "it's managed"), realBin = path.join(root, "real"); + await mkdir(bin); await mkdir(realBin); + const realGit = (await exec("sh", ["-c", "command -v git"])).stdout.trim(); + // Stands in for partial-clone lazy fetches: each one makes the real Git + // child ask for credentials for a URL. Other commands run real Git. + await writeFile(path.join(realBin, "git"), `#!${process.execPath} +const {spawnSync} = require("node:child_process"); +const args = process.argv.slice(2); +if (args[0] === "show") { + const host = args[1] || "github.com"; + const fetches = Array.from({length: Number(args[2] || 1)}, () => spawnSync(${JSON.stringify(realGit)}, ["credential", "fill"], {env: process.env, + input: "protocol=https\\nhost=" + host + "\\npath=org/private.git\\n\\n", encoding: "utf8"})); + process.stdout.write(JSON.stringify({status: Math.max(...fetches.map(result => result.status)), stdout: fetches.map(result => result.stdout), + operation: process.env.PAPERCLIP_GITHUB_OPERATION_ACTIVE, token: process.env.PAPERCLIP_GIT_TOKEN ?? null})); + process.exit(0); +} +process.exit(spawnSync(${JSON.stringify(realGit)}, args, {stdio: "inherit"}).status ?? 1); +`, { mode: 0o700 }); + await writeFile(path.join(bin, "git"), githubLauncherSource({ brokerFile }), { mode: 0o700 }); + let posts = 0; + const server = createServer((_req, res) => { + posts++; + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify({ status: "available", env: { PAPERCLIP_GIT_TOKEN: "managed-token", GH_TOKEN: "managed-token" } })); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + cleanups.push(() => new Promise(resolve => server.close(() => resolve()))); + const { port } = server.address() as { port: number }; + const broker = { url: `http://127.0.0.1:${port}`, token: "run-capability" }; + if (brokerFile) await writeFile(path.join(bin, "broker.json"), JSON.stringify(broker), { mode: 0o600 }); + const env = { ...process.env, ...githubBrokerEnvironment({}, brokerFile ? { url: "", token: "" } : broker), + GH_CONFIG_DIR: path.join(root, "config"), PATH: `${bin}${path.delimiter}${realBin}${path.delimiter}${process.env.PATH}` }; + const git = async (...args: string[]) => (await exec(path.join(bin, "git"), args, { cwd: root, env, timeout: 10_000 })).stdout; + + await exec(realGit, ["init", "-q", root]); + await git("status", "--porcelain"); + expect(posts).toBe(0); + + // One operation asks the broker once, however many objects it fetches. + const fetched = JSON.parse(await git("show", "github.com", "3")); + expect(fetched).toMatchObject({ status: 0, operation: "local", token: null }); + expect(fetched.stdout).toEqual(Array(3).fill("protocol=https\nhost=github.com\nusername=x-access-token\npassword=managed-token\n")); + expect(posts).toBe(1); + expect(JSON.parse(await git("show")).stdout).toEqual(["protocol=https\nhost=github.com\nusername=x-access-token\npassword=managed-token\n"]); + expect(posts).toBe(2); + + // Another host gets no answer and causes no broker request. + const other = JSON.parse(await git("show", "example.test")); + expect(other.status).not.toBe(0); + expect(other.stdout).toEqual([""]); + expect(posts).toBe(2); + await expect(exec(path.join(bin, "git"), ["Password for 'https://x-access-token@github.com.example.test': "], + { env: { ...env, PAPERCLIP_GITHUB_OPERATION_ACTIVE: "local" } })).rejects.toMatchObject({ code: 1, stdout: "" }); + expect(posts).toBe(2); + }, 20_000); + + it("gives Git the launcher as askpass only for local commands of a connected launcher", async () => { + const root = await mkdtemp(path.join(os.tmpdir(), "paperclip-github-lazy-scope-")); + cleanups.push(() => rm(root, { recursive: true, force: true })); + const bin = path.join(root, "managed"), anonymousBin = path.join(root, "anonymous"), realBin = path.join(root, "real"); + await mkdir(bin); await mkdir(anonymousBin); await mkdir(realBin); + await writeFile(path.join(bin, "git"), githubLauncherSource(), { mode: 0o700 }); + await writeFile(path.join(anonymousBin, "git"), githubLauncherSource({ anonymous: true }), { mode: 0o700 }); + await writeFile(path.join(realBin, "git"), `#!${process.execPath} +process.stdout.write(JSON.stringify({askpass: process.env.GIT_ASKPASS ?? null, operation: process.env.PAPERCLIP_GITHUB_OPERATION_ACTIVE})); +`, { mode: 0o700 }); + const server = createServer((_req, res) => { + res.setHeader("content-type", "application/json"); + res.end(JSON.stringify({ status: "available", env: { PAPERCLIP_GIT_TOKEN: "managed-token" } })); + }); + await new Promise(resolve => server.listen(0, "127.0.0.1", resolve)); + cleanups.push(() => new Promise(resolve => server.close(() => resolve()))); + const { port } = server.address() as { port: number }; + const base = { ...process.env, ...githubBrokerEnvironment({}, { url: `http://127.0.0.1:${port}`, token: "run-capability" }) }; + const run = async (launcherBin: string, args: string[], extra: Record = {}) => JSON.parse((await exec( + path.join(launcherBin, "git"), args, { cwd: root, env: { ...base, ...extra, + PATH: `${launcherBin}${path.delimiter}${realBin}${path.delimiter}${process.env.PATH}` } })).stdout); + expect(await run(bin, ["show"])).toEqual({ askpass: path.join(await realpath(bin), "git"), operation: "local" }); + expect(await run(bin, ["fetch"])).toEqual({ askpass: null, operation: "1" }); + expect(await run(anonymousBin, ["show"])).toEqual({ askpass: null, operation: "local" }); + expect(await run(bin, ["show"], { PAPERCLIP_GITHUB_BROKER_TOKEN: "" })).toEqual({ askpass: null, operation: "local" }); + // Only a prompt inside a local operation, which holds no credential, may run the launcher again. + for (const [operation, args] of [["1", ["Password for 'https://x-access-token@github.com': "]], ["local", ["show"]], + ["local", ["Password for 'https://github.com': ", "extra"]]] as const) { + await expect(exec(path.join(bin, "git"), [...args], { env: { ...base, PAPERCLIP_GITHUB_OPERATION_ACTIVE: operation, + PATH: `${bin}${path.delimiter}${realBin}${path.delimiter}${process.env.PATH}` } })) + .rejects.toMatchObject({ code: 126, stderr: expect.stringContaining("launcher_recursion_rejected") }); + } + }); + }); it("captures the current task broker file once per invocation and never falls back to inherited authority", async () => { diff --git a/packages/adapter-utils/src/github-launcher.ts b/packages/adapter-utils/src/github-launcher.ts index 68f6d682535..8c549981cce 100644 --- a/packages/adapter-utils/src/github-launcher.ts +++ b/packages/adapter-utils/src/github-launcher.ts @@ -16,9 +16,19 @@ const fs = require('node:fs'); const path = require('node:path'); const os = require('node:os'); const { spawn } = require('node:child_process'); +// A local git command runs with this launcher as GIT_ASKPASS. Git asks it only +// when no credential helper answers a request, for example when it fetches a +// blob that a blobless clone left at a private origin. Git passes one prompt. +const askpassPrompt = process.env.PAPERCLIP_GITHUB_OPERATION_ACTIVE === 'local' && process.argv.length === 3 + ? /^(Username|Password) for '([^']+)': $/.exec(process.argv[2]) : null; +// Only GitHub over HTTPS gets an answer. A GitHub username needs no broker answer. +const askpassUrl = askpassPrompt ? (() => { try { return new URL(askpassPrompt[2]); } catch { return null; } })() : null; +const askpassGitHub = Boolean(askpassUrl && askpassUrl.protocol === 'https:' + && ['github.com', 'www.github.com'].includes(askpassUrl.hostname) && !askpassUrl.port); // A PATH shim can capture this launcher's absolute path and call it again. // Reject that cycle before resolving another executable or capturing authority. -if (process.env.PAPERCLIP_GITHUB_OPERATION_ACTIVE) { +// Only a prompt from a local operation, which holds no credential, may continue. +if (process.env.PAPERCLIP_GITHUB_OPERATION_ACTIVE && !askpassPrompt) { process.stderr.write('Paperclip: GitHub launcher_recursion_rejected.\n'); process.exit(126); } @@ -57,7 +67,29 @@ function connectorRepositoryTool(args) { if (program !== 'gh' || args[0] !== 'repo' || args.includes('--help') || args.includes('-h')) return null; return connectorRepositoryTools.get(args[1]) || null; } +// The local operation that set GIT_ASKPASS serves its password, so one +// operation asks the broker at most once however many objects Git fetches. +function askOperation(socketPath) { + return new Promise(resolve => { + let answer = ''; + const socket = require('node:net').connect(socketPath, () => socket.end('password')); + socket.setEncoding('utf8'); + socket.on('data', chunk => { answer += chunk; }); + socket.once('error', () => resolve(null)); + socket.once('close', hadError => { if (!hadError) resolve(answer); }); + }); +} async function main() { + if (askpassPrompt) { + if (!askpassGitHub) { process.exitCode = 1; return; } + if (askpassPrompt[1] === 'Username') { process.stdout.write('x-access-token\n'); return; } + const answer = process.env.PAPERCLIP_GITHUB_ASKPASS_SOCKET ? await askOperation(process.env.PAPERCLIP_GITHUB_ASKPASS_SOCKET) : null; + if (answer !== null) { + if (answer && !/[\r\n]/.test(answer)) process.stdout.write(answer + '\n'); + else process.exitCode = 1; + return; + } + } let env = { ...process.env }; const anonymousLauncher = ${anonymousLauncher ? 'true' : 'false'}; let brokerAnonymous = false; @@ -92,6 +124,8 @@ ${options.brokerFile ? String.raw` `} const diagnostic = (code) => process.stderr.write('Paperclip: GitHub ' + code + '; continuing without managed credentials.\n'); let connected = false; + let localOperation = false; + let closeAskpass = () => {}; const configRoot = env.GH_CONFIG_DIR || os.tmpdir(); // A missing/unwritable scratch directory must not break local Git. The // fallback deliberately cannot load the host's gh authentication files. @@ -122,7 +156,55 @@ ${options.brokerFile ? String.raw` GIT_CONFIG_KEY_4: 'user.useConfigOnly', GIT_CONFIG_VALUE_4: 'true', }); const base = env.PAPERCLIP_GITHUB_BROKER_URL || env.PAPERCLIP_API_URL; - const askBroker = !anonymousLauncher && !brokerAnonymous && !isLocalCommand(process.argv.slice(2)); + const brokerAllowed = !anonymousLauncher && !brokerAnonymous; + localOperation = !askpassPrompt && isLocalCommand(process.argv.slice(2)); + const askBroker = brokerAllowed && !localOperation; + // A local command asks no broker. It can still need GitHub when it reads an + // object that a partial clone did not download, so Git can ask the broker + // through this launcher then. Git runs GIT_ASKPASS directly, without a shell. + delete env.PAPERCLIP_GITHUB_ASKPASS_SOCKET; + if (localOperation && program === 'git' && brokerAllowed && base && env.PAPERCLIP_GITHUB_BROKER_TOKEN) { + const launcher = env.GIT_ASKPASS = fs.realpathSync(process.argv[1]); + // The first password prompt runs this launcher once more to ask the broker. + // Later prompts reuse that answer, which stays in this process's memory. + // Without the socket, each prompt asks the broker itself. + let password = null; + const askBrokerOnce = () => password || (password = new Promise(resolve => { + const request = spawn(launcher, ["Password for 'https://github.com': "], { env: { ...env, + PAPERCLIP_GITHUB_OPERATION_ACTIVE: 'local', PAPERCLIP_GITHUB_ASKPASS_SOCKET: '' }, stdio: ['ignore', 'pipe', 'inherit'] }); + let output = ''; + request.stdout.setEncoding('utf8'); + request.stdout.on('data', chunk => { output += chunk; }); + request.once('error', () => resolve('')); + request.once('close', code => resolve(code === 0 ? output.trim() : '')); + })); + const server = require('node:net').createServer({ allowHalfOpen: true }, socket => { + let request = ''; + socket.setEncoding('utf8'); + socket.on('error', () => {}); + socket.on('data', chunk => { request += chunk; if (request.length > 64) socket.destroy(); }); + socket.on('end', () => { + if (request !== 'password') { socket.end(); return; } + askBrokerOnce().then(answer => socket.end(answer)); + }); + }); + // A socket path has a limit of about 100 bytes, and the launcher directory + // can use most of that. So the socket gets its own private temporary directory. + let socketPath = null; + try { + const socketDirectory = fs.mkdtempSync(path.join(os.tmpdir(), 'paperclip-askpass-')); + process.once('exit', () => { try { fs.rmSync(socketDirectory, { recursive: true, force: true }); } catch {} }); + socketPath = path.join(socketDirectory, 'socket'); + } catch {} + if (socketPath && await new Promise(resolve => { + server.once('error', () => resolve(false)); + server.listen(socketPath, () => resolve(true)); + })) { + server.unref(); + env.PAPERCLIP_GITHUB_ASKPASS_SOCKET = socketPath; + closeAskpass = () => server.close(); + } + } try { let response; if (askBroker && base && env.PAPERCLIP_GITHUB_BROKER_TOKEN) { @@ -189,6 +271,13 @@ ${options.brokerFile ? String.raw` } else if (askBroker) { diagnostic('capability_missing'); } } catch { diagnostic('broker_transport_unavailable'); } } + if (askpassPrompt) { + // Without an answer, Git fails as it did before. + const token = connected ? env.PAPERCLIP_GIT_TOKEN : ''; + if (token && !/[\r\n]/.test(token)) process.stdout.write(token + '\n'); + else process.exitCode = 1; + return; + } const connectorTool = connected ? connectorRepositoryTool(process.argv.slice(2)) : null; if (connectorTool) { process.stderr.write("Paperclip: use the GitHub connection's " + connectorTool + " tool instead of gh repo " + process.argv[3] + @@ -198,7 +287,8 @@ ${options.brokerFile ? String.raw` return; } // Only this invocation and its children inherit the captured credential. - env.PAPERCLIP_GITHUB_OPERATION_ACTIVE = '1'; + // A local operation holds none, so only its askpass prompts may run the launcher again. + env.PAPERCLIP_GITHUB_OPERATION_ACTIVE = localOperation ? 'local' : '1'; // Its Git children use the real binary, so steering cannot split a gh operation. env.PATH = originalPath.join(path.delimiter); // Nested shell aliases must not reload the parent launcher profile and @@ -209,7 +299,7 @@ ${options.brokerFile ? String.raw` const child = spawn(executable, process.argv.slice(2), { env, stdio: 'inherit' }); for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => child.kill(signal)); child.once('error', () => { process.stderr.write('Paperclip: GitHub command could not start.\n'); process.exitCode = 1; }); - child.once('exit', (code, signal) => { process.exitCode = code === null ? 128 : code; }); + child.once('exit', (code, signal) => { closeAskpass(); process.exitCode = code === null ? 128 : code; }); } main().catch(() => { process.stderr.write('Paperclip: GitHub launcher_setup_failed.\n'); process.exitCode = 1; }); `; diff --git a/server/src/services/remote-workspace-transport.test.ts b/server/src/services/remote-workspace-transport.test.ts index 3c59aa97cc1..056eec604d4 100644 --- a/server/src/services/remote-workspace-transport.test.ts +++ b/server/src/services/remote-workspace-transport.test.ts @@ -2289,4 +2289,71 @@ return result};`); ref: "HEAD~1", pinnedCommit: receipt.pinnedCommit, resolveGitAuth: unavailableAuth })).resolves.toEqual(receipt); expect(unavailableAuth).not.toHaveBeenCalled(); }); + + it("clones without history-only blobs and fetches an older revision's files with the clone credentials", async () => { + // A full clone downloads every historical blob. In a Cloud sandbox that alone + // can spend Git's per-command storage budget, so the clone fails with a full disk. + const origin = await repository({ revisions: true }); + await fs.writeFile(path.join(origin, "history-only.bin"), randomBytes(64 * 1024)); + await git(origin, "add", "history-only.bin"); + await git(origin, "commit", "-m", "History-only blob"); + const historyBlob = (await git(origin, "rev-parse", "HEAD:history-only.bin")).stdout.trim(); + await git(origin, "rm", "-q", "history-only.bin"); + await git(origin, "commit", "-m", "Remove history-only blob"); + await git(origin, "config", "uploadpack.allowFilter", "true"); + // The origin is reachable only through the credential rewrite, like a private repository. + const remoteUrl = "ssh://git@127.0.0.1:1/synthetic-partial-repository"; + const resolveGitAuth = async () => ({ configArgs: [], env: { GIT_CONFIG_COUNT: "1", + GIT_CONFIG_KEY_0: `url.${pathToFileURL(origin).href}.insteadOf`, GIT_CONFIG_VALUE_0: remoteUrl }, + source: "company_secret" as const, secretName: "SYNTHETIC_FIXTURE" }); + const { remote } = target(); + const missingObjects = async (repo: string) => (await git(repo, "rev-list", "--objects", "--missing=print", "--all")) + .stdout.split("\n").filter(line => line.startsWith("?")).map(line => line.slice(1)); + + const root = path.join(workspace, "partial-root"); + await prepareRemoteWorkspaceDirectory({ target: remote, remoteCwd: root, preparationIdentity: "b".repeat(64), + source: { kind: "git", repoUrl: remoteUrl, ref: "HEAD" }, resolveGitAuth }); + expect(await missingObjects(root)).toContain(historyBlob); + expect((await git(root, "config", "--get", "remote.origin.promisor")).stdout.trim()).toBe("true"); + await expect(fs.access(path.join(root, "history-only.bin"))).rejects.toThrow(); + + // An older configured revision needs a blob the clone left on the server. + const older = path.join(workspace, "partial-older-root"); + await prepareRemoteWorkspaceDirectory({ target: remote, remoteCwd: older, preparationIdentity: "c".repeat(64), + source: { kind: "git", repoUrl: remoteUrl, ref: "HEAD~1" }, resolveGitAuth }); + expect((await fs.readFile(path.join(older, "history-only.bin"))).length).toBe(64 * 1024); + + const nested = path.join(workspace, "partial-repository"); + const receipt = await prepareRemoteRepository({ target: remote, remoteCwd: nested, repoUrl: remoteUrl, + ref: "HEAD~1", resolveGitAuth }); + expect((await fs.readFile(path.join(nested, "history-only.bin"))).length).toBe(64 * 1024); + expect((await git(nested, "config", "--get", "remote.origin.promisor")).stdout.trim()).toBe("true"); + expect(receipt.pinnedCommit).toMatch(/^[a-f0-9]{40}$/); + + // A local origin stays a full clone: a saved workspace cannot keep a promisor + // remote that only exists on this machine. + const local = path.join(workspace, "partial-local-origin"); + await prepareRemoteRepository({ target: remote, remoteCwd: local, repoUrl: pathToFileURL(origin).href, + ref: "HEAD", resolveGitAuth: async () => null }); + expect(await missingObjects(local)).toEqual([]); + await expect(git(local, "config", "--get", "remote.origin.promisor")).rejects.toThrow(); + + // The blobless clone is saved and restored with its promisor remote; the + // restore does not need the origin. + await fs.writeFile(path.join(root, "source.txt"), "agent edit in a blobless clone\n"); + const captured = await captureRemoteWorkspaceArchive({ target: remote, remoteCwd: root, operationId: randomUUID() }); + try { + await fs.rm(origin, { recursive: true }); + const restoredRoot = path.join(scratch, "partial-saved-root"); + const restored = await restoreRemoteWorkspaceDirectory({ target: remote, remoteCwd: restoredRoot, + archivePath: captured.archivePath, manifestDigest: captured.manifestDigest, restorationIdentity: "d".repeat(64) }); + await cleanupRemoteWorkspaceArchive({ target: remote, remoteCwd: restored.stagingRoot, operationId: restored.operationId }); + expect(await fs.readFile(path.join(restoredRoot, "source.txt"), "utf8")).toBe("agent edit in a blobless clone\n"); + expect((await git(restoredRoot, "config", "--get", "remote.origin.promisor")).stdout.trim()).toBe("true"); + expect((await git(restoredRoot, "config", "--get", "remote.origin.url")).stdout.trim()).toBe(remoteUrl); + expect(await missingObjects(restoredRoot)).toContain(historyBlob); + expect((await git(restoredRoot, "rev-parse", "HEAD")).stdout.trim()) + .toBe((await git(root, "rev-parse", "HEAD")).stdout.trim()); + } finally { await captured.cleanup(); } + }); }); diff --git a/server/src/services/remote-workspace-transport.ts b/server/src/services/remote-workspace-transport.ts index 6849043940c..45d2f3ecfaa 100644 --- a/server/src/services/remote-workspace-transport.ts +++ b/server/src/services/remote-workspace-transport.ts @@ -355,6 +355,25 @@ export async function removeRemoteRecoveryAttachment(input: { return output === "removed"; } +// A fresh clone from a network remote is blobless (--filter=blob:none): it gets +// every commit and tree, but only the file contents a checkout needs. A full +// clone also downloads every historical blob, which alone can exceed a Cloud +// sandbox's per-command Git storage budget. Checkout of another revision can +// fetch missing blobs, so the staged checkout steps use the clone's credentials. +// A server without filter support ignores the filter and sends a full clone. +// A local path or file:// origin is cloned in full: a saved workspace keeps +// only a promisor remote whose URL works on another machine. +function bloblessCloneSource(repoUrl: string): boolean { + if (!repoUrl || /[\u0000-\x20\u007f\\]/u.test(repoUrl)) return false; + if (/^[a-z][a-z0-9+.-]*:\/\//iu.test(repoUrl)) { + try { + const url = new URL(repoUrl); + return ["http:", "https:", "ssh:", "git:"].includes(url.protocol) && Boolean(url.hostname); + } catch { return false; } + } + return !/^[a-z]:[\/\\]/iu.test(repoUrl) && /^(?:[a-z0-9._-]+@)?(?:[a-z0-9._-]+|\[[a-f0-9:]+\]):[^\s]+$/iu.test(repoUrl); +} + const PREPARE = String.raw` const fs = require('node:fs/promises'), path = require('node:path'), cp = require('node:child_process'); const {promisify}=require('node:util'); const exec=promisify(cp.execFile); @@ -365,7 +384,6 @@ ${DISK_FULL_CHECK}${CAPTURE_FAILURE_CHECK}${SETUP_FAILURE_CHECK}let stage='valid const noConfig={GIT_TERMINAL_PROMPT:'0',GIT_CONFIG_NOSYSTEM:'1',GIT_CONFIG_GLOBAL:'/dev/null',GIT_CONFIG_SYSTEM:'/dev/null',GIT_CONFIG_COUNT:'0',GIT_CONFIG_PARAMETERS:'',GIT_TEMPLATE_DIR:'',GIT_ASKPASS:'',SSH_ASKPASS:''}; const isolated={...process.env,...noConfig};for(const key of Object.keys(isolated))if(/^GIT_CONFIG_(KEY|VALUE)_\d+$/.test(key))delete isolated[key]; const cloneEnv={...isolated};for(const key of input.authEnvKeys)if(/^GIT_CONFIG_(COUNT|(KEY|VALUE)_\d+)$/.test(key)&&process.env[key]!==undefined)cloneEnv[key]=process.env[key]; - const localEnv={...isolated};for(const key of input.authEnvKeys)delete localEnv[key];Object.assign(localEnv,noConfig); stage='create_parent';let current='/'; for(const part of path.dirname(root).split('/').filter(Boolean)) { current=path.join(current,part); await fs.mkdir(current,{mode:0o700}).catch(e=>{if(e.code!=='EEXIST')throw e}); const s=await fs.lstat(current); if(!s.isDirectory()||s.isSymbolicLink())throw Error('unsafe_root'); @@ -383,8 +401,8 @@ ${DISK_FULL_CHECK}${CAPTURE_FAILURE_CHECK}${SETUP_FAILURE_CHECK}let stage='valid stage='stage';const staged=await fs.mkdtemp(root+'.preparing-');let published=false; try{ if(input.kind==='git'){ - stage='clone';await exec('git',['-c','core.hooksPath=/dev/null','-c','init.templateDir=',...input.authArgs,'clone','--no-hardlinks','--',input.repoUrl,staged],{env:cloneEnv}); - const git=async args=>exec('git',['-c','core.hooksPath=/dev/null','-C',staged,...args],{env:localEnv}); + stage='clone';await exec('git',['-c','core.hooksPath=/dev/null','-c','init.templateDir=',...input.authArgs,'clone','--no-hardlinks',...(input.blobless?['--filter=blob:none']:[]),'--',input.repoUrl,staged],{env:cloneEnv}); + const git=async args=>exec('git',['-c','core.hooksPath=/dev/null',...input.authArgs,'-C',staged,...args],{env:cloneEnv}); if(input.branchMode==='existing'){ stage='checkout_branch';if(!input.branchName)throw Error('existing_branch_required'); await git(['check-ref-format','--branch',input.branchName]); @@ -425,6 +443,7 @@ export async function prepareRemoteWorkspaceDirectory(input: { const auth = input.source.kind === "git" ? await input.resolveGitAuth(input.source.repoUrl) : null; const output = await command(input.target, "prepare", ["-e", PREPARE, input.remoteCwd, JSON.stringify({ ...input.source, preparationIdentity: input.preparationIdentity, + blobless: input.source.kind === "git" && bloblessCloneSource(input.source.repoUrl), authArgs: auth?.configArgs ?? [], authEnvKeys: Object.keys(auth?.env ?? {}) })], auth?.env); const result = JSON.parse(output) as { cwd: string }; if (result.cwd !== input.remoteCwd) throw new Error("remote_workspace_root_changed"); @@ -458,8 +477,8 @@ export async function prepareRemoteRepository(input: { if(existing){if(!existing.isDirectory()||existing.isSymbolicLink())throw Error('unsafe_repository')} else{if(input.verifyOnly||input.savedArchive)throw Error('repository_missing');if(input.probeOnly){process.stdout.write(JSON.stringify({cloneRequired:true}));return;} stage='stage';const staged=await fs.mkdtemp(root+'.preparing-');try{ - stage='clone';await exec('git',['-c','core.hooksPath=/dev/null','-c','init.templateDir=',...input.authArgs,'clone','--no-hardlinks','--',input.repoUrl,staged],{env:cloneEnv}); - const git=async args=>exec('git',['-c','core.hooksPath=/dev/null','-C',staged,...args],opts); + stage='clone';await exec('git',['-c','core.hooksPath=/dev/null','-c','init.templateDir=',...input.authArgs,'clone','--no-hardlinks',...(input.blobless?['--filter=blob:none']:[]),'--',input.repoUrl,staged],{env:cloneEnv}); + const git=async args=>exec('git',['-c','core.hooksPath=/dev/null',...input.authArgs,'-C',staged,...args],{env:cloneEnv}); stage='checkout_ref'; ${checkoutConfiguredRefScript} stage='publish';await fs.rename(staged,root); @@ -483,7 +502,8 @@ export async function prepareRemoteRepository(input: { } const auth = await input.resolveGitAuth(input.repoUrl); const output = await command(input.target, "repository", ["-e", script, input.remoteCwd, - JSON.stringify({ ...payload, authArgs: auth?.configArgs ?? [], authEnvKeys: Object.keys(auth?.env ?? {}) })], auth?.env); + JSON.stringify({ ...payload, blobless: bloblessCloneSource(input.repoUrl), + authArgs: auth?.configArgs ?? [], authEnvKeys: Object.keys(auth?.env ?? {}) })], auth?.env); const value = JSON.parse(output) as { cwd: string; pinnedCommit: string; branchName: string | null }; if (value.cwd !== input.remoteCwd || !/^[a-f0-9]{40,64}$/.test(value.pinnedCommit)) throw new Error("remote_workspace_repository_receipt_invalid"); return value;