Skip to content

The open-source app everyone uses to manage agents at work

fix(server): let Git expiration verify public commits without a run identity (#16621)

Devin Foley5555817c2b18
diff --git a/doc/DEVELOPING.md b/doc/DEVELOPING.md
index a5dc1e0f13..c80697188d 100644
--- a/doc/DEVELOPING.md
+++ b/doc/DEVELOPING.md
@@ -2619,7 +2619,9 @@ run contexts. Unshared paths still require every existing task, run, recovery,
lease, service and filesystem check in the same lifecycle lock.
Before deletion the worker fetches the exact commit into a fresh object store
-using the company's normal Git identity and commits a versioned restoration
+using the company's normal Git identity (anonymously when no identity resolves
+outside an agent run, which still proves public repositories; a private
+repository that cannot be verified keeps its workspace) and commits a versioned restoration
recipe to workspace metadata. Current runs, previews, pending reopening,
unresolved recovery, dirty/untracked files, unknown ignored files, unproven
ownership, and unsupported or unique Git state prevent deletion. Ignored files
diff --git a/server/src/__tests__/git-expiration-auth-fallback.test.ts b/server/src/__tests__/git-expiration-auth-fallback.test.ts
new file mode 100644
index 0000000000..3e44d43ec3
--- /dev/null
+++ b/server/src/__tests__/git-expiration-auth-fallback.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from "vitest";
+import { gitExpirationSkipReason, withAnonymousGitFallback } from "../services/git-workspace-expiration.js";
+import { GitCacheRestorationFailure } from "../services/git-workspace-restoration.js";
+
+describe("Git expiration upstream access", () => {
+ it("falls back to anonymous access when the company identity cannot be resolved", async () => {
+ const unavailable = withAnonymousGitFallback(async () => {
+ throw new Error("No managed GitHub identity is available for this run");
+ });
+ await expect(unavailable("https://github.com/example/public")).resolves.toBeNull();
+ });
+
+ it("passes resolved credentials through unchanged", async () => {
+ const credential = { env: { GIT_ASKPASS: "/bin/true" }, configArgs: ["-c", "credential.helper="] };
+ const resolved = withAnonymousGitFallback(async () => credential);
+ await expect(resolved("https://github.com/example/private")).resolves.toBe(credential);
+ });
+
+ it("names upstream verification failures instead of reporting them as inspection failures", () => {
+ expect(gitExpirationSkipReason(new GitCacheRestorationFailure())).toBe("upstream_commit_unverified");
+ expect(gitExpirationSkipReason(new Error("unpushed_managed_checkout"))).toBe("unpushed_managed_checkout");
+ expect(gitExpirationSkipReason(new Error("spawn git ENOENT"))).toBe("inspection_failed");
+ });
+});
diff --git a/server/src/__tests__/git-reproducible-managed-checkouts.test.ts b/server/src/__tests__/git-reproducible-managed-checkouts.test.ts
index 4cba912d77..08ed639410 100644
--- a/server/src/__tests__/git-reproducible-managed-checkouts.test.ts
+++ b/server/src/__tests__/git-reproducible-managed-checkouts.test.ts
@@ -3,7 +3,7 @@ import fs from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { promisify } from "node:util";
-import { afterEach, beforeEach, describe, expect, it } from "vitest";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import {
assertReproducibleGitFiles,
assertReproducibleManagedCheckout,
@@ -157,6 +157,32 @@ describe("assertReproducibleGitFiles with Paperclip-managed files", () => {
await expectAccepted();
});
+ it("keeps a checkout whose upstream cannot be reached or authenticated", async () => {
+ await managedCheckout();
+ prove = (checkout, _name, signal) => assertReproducibleManagedCheckout(checkout, {
+ repoUrl: path.join(root, "missing.git"), resolveGitAuth: async () => null, signal,
+ });
+ await expectRejected("managed_checkout_upstream_unavailable");
+ prove = (checkout, _name, signal) => assertReproducibleManagedCheckout(checkout, {
+ repoUrl: projectRemote, resolveGitAuth: async () => { throw new Error("credentials refused"); }, signal,
+ });
+ await expectRejected("managed_checkout_upstream_unavailable");
+ });
+
+ it("reports a local proof failure as local, not as an upstream problem", async () => {
+ await managedCheckout();
+ const writeFile = fs.writeFile.bind(fs);
+ const spy = vi.spyOn(fs, "writeFile").mockImplementation(async (file, ...rest) => {
+ if (String(file).endsWith(path.join("objects", "info", "alternates"))) throw new Error("ENOSPC: no space left on device");
+ return writeFile(file, ...(rest as [never]));
+ });
+ try {
+ await expectRejected("ENOSPC");
+ } finally {
+ spy.mockRestore();
+ }
+ });
+
it("does not trust a stale remote-tracking ref", async () => {
await git(projectSeed, "checkout", "-q", "-b", "feature");
await commit(projectSeed, "feature.txt", "feature work");
diff --git a/server/src/services/git-workspace-expiration.ts b/server/src/services/git-workspace-expiration.ts
index 726f5ea24e..fdc7a3a1e8 100644
--- a/server/src/services/git-workspace-expiration.ts
+++ b/server/src/services/git-workspace-expiration.ts
@@ -8,7 +8,7 @@ import { withIsolatedRepositorySourceLock, verifiedRecordedIsolatedRemoteSource
import { managedProjectCheckoutName } from "./managed-project-checkout-name.js";
import type { GitRemoteAuthProvider } from "./git-credentials.js";
import { assertReproducibleGitFiles, assertReproducibleBaseGitStorage, assertReproducibleManagedCheckout, inspectGitCacheRecipe, readGitCacheRestoration,
- verifyRemoteGitCommit, type ManagedCheckoutProver, gitCacheCommand, readGitCacheExpiration, finishGitCacheTrash, type GitCacheExpiration, GIT_CACHE_RESTORATION_KEY, GIT_CACHE_EXPIRATION_REASON } from "./git-workspace-restoration.js";
+ verifyRemoteGitCommit, GitCacheRestorationFailure, type ManagedCheckoutProver, gitCacheCommand, readGitCacheExpiration, finishGitCacheTrash, type GitCacheExpiration, GIT_CACHE_RESTORATION_KEY, GIT_CACHE_EXPIRATION_REASON } from "./git-workspace-restoration.js";
async function allocatedBytes(target: string, shouldContinue: () => boolean): Promise<number> {
@@ -19,9 +19,26 @@ async function allocatedBytes(target: string, shouldContinue: () => boolean): Pr
if (entry.isDirectory()) for (const name of await fs.readdir(target)) bytes += await allocatedBytes(path.join(target, name), shouldContinue);
return bytes;
}
-function skipReason(error: unknown) {
+export function gitExpirationSkipReason(error: unknown) {
+ if (error instanceof GitCacheRestorationFailure) return "upstream_commit_unverified";
return error instanceof Error && /^[a-z][a-z_]+$/.test(error.message) ? error.message : "inspection_failed";
}
+const skipReason = gitExpirationSkipReason;
+
+/**
+ * Expiration runs outside any agent run, so a company's managed GitHub
+ * connection has no run identity to resolve, and its provider throws instead
+ * of returning credentials. Upstream proofs then fall back to anonymous
+ * access: a public repository still proves its commits, and a private one
+ * fails to verify, so its workspace is kept, as before.
+ */
+export function withAnonymousGitFallback(provider: GitRemoteAuthProvider): GitRemoteAuthProvider {
+ return async (remoteUrl) => provider(remoteUrl).catch(() => null);
+}
+
+function expirationGitAuth(db: Db, workspace: Workspace) {
+ return withAnonymousGitFallback(createGitRemoteAuthProvider(db, workspace.companyId, { issueId: workspace.sourceIssueId! }));
+}
const EXPIRATION_KEY = "gitCacheExpiration";
const DAY_MS = 24 * 60 * 60 * 1000;
@@ -118,7 +135,7 @@ async function inspectBase(db: Db, workspace: Workspace, signal?: AbortSignal, a
const commits = new Set([...refs.map(ref => ref.split(" ")[0]!),
...(await gitCacheCommand(recipe.sourcePath, ["reflog", "show", "--all", "--format=%H"], signal)).trim().split("\n").filter(Boolean)]);
if (commits.size > 50) throw new Error("base_ref_verification_budget");
- const auth = createGitRemoteAuthProvider(db, workspace.companyId, { issueId: workspace.sourceIssueId! });
+ const auth = expirationGitAuth(db, workspace);
for (const commit of commits) await verifyRemoteGitCommit(recipe.repoUrl, commit, auth, signal);
// Unreachable objects may contain unique rewritten work not present in a reflog.
const unreachable = await gitCacheCommand(recipe.sourcePath, ["fsck", "--no-reflogs", "--unreachable", "--no-progress"], signal);
@@ -165,7 +182,7 @@ export async function expireReconstructableGitWorkspace(db: Db, snapshot: Worksp
// A restored active workspace starts a new expiration cycle and records its new HEAD.
if (!hasPendingGitExpiration(workspace) && !["active", "idle", "in_review"].includes(workspace.status)) throw new Error("not_expirable");
if (["active", "idle", "in_review"].includes(workspace.status)) state = null;
- const auth = createGitRemoteAuthProvider(db, workspace.companyId, { issueId: workspace.sourceIssueId! });
+ const auth = expirationGitAuth(db, workspace);
const proveManagedCheckout = managedCheckoutProver(db, workspace, auth);
let recipe = state ? readGitCacheRestoration(workspace)! : await inspectGitCacheRecipe(workspace,
auth, options.signal, { proveManagedCheckout });
diff --git a/server/src/services/git-workspace-restoration.ts b/server/src/services/git-workspace-restoration.ts
index 2675bb7870..386f6d69b8 100644
--- a/server/src/services/git-workspace-restoration.ts
+++ b/server/src/services/git-workspace-restoration.ts
@@ -250,13 +250,23 @@ async function hasCommitsMissingUpstream(checkout: string, localTips: string[],
resolveGitAuth: GitRemoteAuthProvider, signal?: AbortSignal) {
const store = await fs.mkdtemp(path.join(os.tmpdir(), "paperclip-git-checkout-proof-"));
try {
- const auth = await resolveGitAuth(repoUrl);
- const env = { ...process.env, ...auth?.env, GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: os.devNull };
- const options = { timeout: 120_000, signal, maxBuffer: 16 * 1024 * 1024, env, cwd: os.tmpdir() };
+ const options = { timeout: 120_000, signal, maxBuffer: 16 * 1024 * 1024, cwd: os.tmpdir(),
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: os.devNull } };
+ // Local setup stays outside the catch below: a local failure (a full
+ // disk, say) must not be reported as an upstream problem.
await execFile("git", ["init", "--bare", "--quiet", store], options);
await fs.writeFile(path.join(store, "objects", "info", "alternates"), `${path.join(await fs.realpath(checkout), ".git", "objects")}\n`);
- await execFile("git", [...auth?.configArgs ?? [], "-C", store, "fetch", "--quiet", "--no-tags", "--no-recurse-submodules",
- "--", repoUrl, "+refs/heads/*:refs/upstream/heads/*", "+refs/tags/*:refs/upstream/tags/*"], options);
+ try {
+ const auth = await resolveGitAuth(repoUrl);
+ await execFile("git", [...auth?.configArgs ?? [], "-C", store, "fetch", "--quiet", "--no-tags", "--no-recurse-submodules",
+ "--", repoUrl, "+refs/heads/*:refs/upstream/heads/*", "+refs/tags/*:refs/upstream/tags/*"],
+ { ...options, env: { ...options.env, ...auth?.env } });
+ } catch (error) {
+ if (signal?.aborted) throw error;
+ // An unreachable upstream or refused credentials proves nothing, so the
+ // checkout is kept.
+ throw new Error("managed_checkout_upstream_unavailable");
+ }
const missing = await execFile("git", ["-C", store, "rev-list", "--max-count=1", ...localTips, "--not", "--glob=refs/upstream/*"], options);
return missing.stdout.trim() !== "";
} finally {