TypeScript
fix(git): explain fetch failures without exposing remote output (#12485)
Julius Marmingec03b240265a1
diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.tsindex c09f36ed315..f798abba74b 100644--- a/apps/server/src/vcs/GitVcsDriverCore.test.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts@@ -8,6 +8,7 @@ import * as Effect from "effect/Effect";import * as FileSystem from "effect/FileSystem";import * as Fiber from "effect/Fiber";import * as Layer from "effect/Layer";+import * as Logger from "effect/Logger";import * as Metric from "effect/Metric";import * as Path from "effect/Path";import * as PlatformError from "effect/PlatformError";@@ -35,6 +36,8 @@ import {} from "./GitVcsDriverCore.ts";import * as GitVcsDriver from "./GitVcsDriver.ts";+const encodeGitCommandError = Schema.encodeEffect(Schema.fromJsonString(GitCommandError));+const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {prefix: "t3-git-vcs-driver-test-",});@@ -718,7 +721,7 @@ it.effect("refreshes the current branch after an external checkout", () =>).pipe(Effect.provide(TestLayer)),);-it.effect("backs off failed upstream refreshes across linked worktrees", () =>+it.effect("backs off and logs failed fetch attempts across linked worktrees", () =>Effect.scoped(Effect.gen(function* () {const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;@@ -738,6 +741,14 @@ it.effect("backs off failed upstream refreshes across linked worktrees", () =>const driver = yield* makeGitVcsDriverCore().pipe(Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, failingFetchSpawner),);+ const warnings: string[] = [];+ const logger = Logger.make<unknown, void>(({ message }) => {+ warnings.push(String(message));+ });+ const readRemoteStatus = (workingDirectory: string) =>+ driver+ .statusDetailsRemote(workingDirectory)+ .pipe(Effect.provideService(Logger.CurrentLoggers, new Set([logger])));const cwd = yield* makeTmpDir();const remote = yield* makeTmpDir("git-vcs-driver-remote-");const worktreesRoot = yield* makeTmpDir("git-vcs-driver-worktrees-");@@ -781,29 +792,146 @@ it.effect("backs off failed upstream refreshes across linked worktrees", () =>);yield* Ref.set(fetchAttempts, 0);- yield* driver.statusDetailsRemote(cwd);- yield* driver.statusDetailsRemote(worktreePath);+ yield* readRemoteStatus(cwd);+ yield* readRemoteStatus(worktreePath);assert.equal(yield* Ref.get(fetchAttempts), 1);+ assert.lengthOf(warnings, 1);+ assert.include(warnings[0], "Background Git fetch failed");yield* TestClock.adjust("29 seconds");- yield* driver.statusDetailsRemote(worktreePath);+ yield* readRemoteStatus(worktreePath);assert.equal(yield* Ref.get(fetchAttempts), 1);+ assert.lengthOf(warnings, 1);yield* TestClock.adjust("1 second");- yield* driver.statusDetailsRemote(cwd);+ yield* readRemoteStatus(cwd);assert.equal(yield* Ref.get(fetchAttempts), 2);+ assert.lengthOf(warnings, 2);yield* TestClock.adjust("59 seconds");- yield* driver.statusDetailsRemote(worktreePath);+ yield* readRemoteStatus(worktreePath);assert.equal(yield* Ref.get(fetchAttempts), 2);+ assert.lengthOf(warnings, 2);yield* TestClock.adjust("1 second");- yield* driver.statusDetailsRemote(cwd);+ yield* readRemoteStatus(cwd);assert.equal(yield* Ref.get(fetchAttempts), 3);+ assert.lengthOf(warnings, 3);}),).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),);+for (const scenario of [+ {+ name: "HTTPS credentials",+ stderr: "fatal: Authentication failed for",+ expected: "could not authenticate",+ },+ {+ name: "SSH credentials",+ stderr: "[email protected]: Permission denied (publickey).",+ expected: "could not authenticate",+ },+ {+ name: "disabled prompts",+ stderr: "fatal: could not read Username: terminal prompts disabled",+ expected: "could not authenticate",+ },+ {+ name: "DNS failure",+ stderr: "fatal: Could not resolve host: example.com",+ expected: "could not reach the remote",+ },+ {+ name: "connection failure",+ stderr: "ssh: connect to host example.com port 22: Connection refused",+ expected: "could not reach the remote",+ },+ {+ name: "missing remote",+ stderr: "remote: Repository not found.",+ expected: "could not access the remote repository",+ },+ {+ name: "invalid remote",+ stderr: "fatal: remote does not appear to be a git repository",+ expected: "could not access the remote repository",+ },+ {+ name: "reference lock",+ stderr: "error: cannot lock ref 'refs/remotes/origin/main': is at abc but expected def",+ expected: "could not update a local reference",+ },+ {+ name: "lock file",+ stderr: "fatal: Unable to create '/repo/.git/FETCH_HEAD.lock': File exists.",+ expected: "could not update a local reference",+ },+ {+ name: "unrelated remote chatter",+ stderr:+ "remote: Help: authentication failed, connection refused, cannot lock ref\nremote: unrelated service error",+ expected: "git fetch origin failed",+ },+ {+ name: "HTTPS DNS failure",+ stderr:+ "fatal: unable to access 'https://example.com/repo.git/': Could not resolve host: example.com",+ expected: "could not reach the remote",+ },+ {+ name: "unknown failure",+ stderr: "fatal: unexpected remote failure",+ expected: "git fetch origin failed",+ },+] as const) {+ it.effect(`reports ${scenario.name} during fetch without retaining remote output`, () =>+ Effect.gen(function* () {+ const secret = "secret-fetch-token";+ const stderr = `${scenario.stderr}\nhttps://user:${secret}@example.com/private?token=${secret}`;+ const attempts = yield* Ref.make(0);+ const spawner = ChildProcessSpawner.make((command) =>+ Effect.gen(function* () {+ if (!ChildProcess.isStandardCommand(command))+ return yield* Effect.die("expected Git command");+ if (command.args[0] !== "fetch") return makeNonRepositoryHandle();+ assert.deepEqual(command.args, ["fetch", "--quiet", "origin"]);+ assert.equal(command.options.env?.LC_ALL, "C");+ assert.equal(command.options.env?.GIT_TERMINAL_PROMPT, "0");+ yield* Ref.update(attempts, (count) => count + 1);+ return ChildProcessSpawner.makeHandle({+ pid: ChildProcessSpawner.ProcessId(1),+ exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)),+ isRunning: Effect.succeed(false),+ kill: () => Effect.void,+ unref: Effect.succeed(Effect.void),+ stdin: Sink.drain,+ stdout: Stream.encodeText(Stream.make(secret)),+ stderr: Stream.encodeText(Stream.make(stderr)),+ all: Stream.empty,+ getInputFd: () => Sink.drain,+ getOutputFd: () => Stream.empty,+ });+ }),+ );+ const driver = yield* makeGitVcsDriverCore().pipe(+ Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),+ );+ const cwd = yield* makeTmpDir();+ const error = yield* driver.fetchRemote({ cwd, remoteName: "origin" }).pipe(Effect.flip);+ assert.include(error.detail, scenario.expected);+ assert.equal(error.exitCode, 128);+ assert.equal(error.stderrLength, stderr.length);+ assert.equal(error.stdoutLength, secret.length);+ assert.notInclude(error.message, secret);+ assert.notInclude(yield* encodeGitCommandError(error), secret);+ assert.notProperty(error, "stderr");+ assert.notProperty(error, "args");+ assert.equal(yield* Ref.get(attempts), 1);+ }).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),+ );+}+it.layer(TestLayer)("GitVcsDriver core integration", (it) => {describe("process environment", () => {it.effect("preserves the caller locale for general Git subprocesses", () =>@@ -2398,6 +2526,22 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {});describe("remote operations", () => {+ it.effect("explains a real fetch failure for a missing local remote", () =>+ Effect.gen(function* () {+ const cwd = yield* makeTmpDir();+ yield* initRepoWithCommit(cwd);+ const driver = yield* GitVcsDriver.GitVcsDriver;+ const missingRemote = `${cwd}/private-missing-remote`;+ yield* git(cwd, ["remote", "add", "origin", missingRemote]);+ const error = yield* driver.fetchRemote({ cwd, remoteName: "origin" }).pipe(Effect.flip);+ assert.include(error.detail, "could not access the remote repository");+ assert.equal(error.exitCode, 128);+ assert.isAbove(error.stderrLength ?? 0, 0);+ assert.notInclude(error.detail, missingRemote);+ assert.notProperty(error, "stderr");+ }),+ );+it.effect("ensureRemote reuses an existing remote across ssh/https transport variants", () =>Effect.gen(function* () {const cwd = yield* makeTmpDir();@@ -2544,7 +2688,11 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {if (Result.isFailure(result)) {assert.equal(result.failure.detail,- failure === "timeout" ? "Git command timed out." : "git fetch origin failed",+ failure === "timeout"+ ? "Git command timed out."+ : failure === "offline"+ ? "Git could not reach the remote. Check the server's network connection and remote host, then retry."+ : "Git could not authenticate with the remote. Check Git credentials or SSH access on the server, then retry.",);}}),diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.tsindex c1136bb9260..56cff0cb9a5 100644--- a/apps/server/src/vcs/GitVcsDriverCore.ts+++ b/apps/server/src/vcs/GitVcsDriverCore.ts@@ -469,6 +469,49 @@ function isMissingWorktreeStderr(stderr: string): boolean {);}+// Fetch stderr can contain remote credentials. Only fixed diagnoses may enter+// persisted errors; unrecognized output keeps the generic failure message.+function fetchFailureDetail(stderr: string): string | undefined {+ const lines = stderr.split(/\r?\n/).map((line) => line.trim());+ if (+ lines.some((line) =>+ /^(?:fatal: (?:Authentication failed|could not read (?:Username|Password))\b|\S+: Permission denied \(publickey)/i.test(+ line,+ ),+ )+ ) {+ return "Git could not authenticate with the remote. Check Git credentials or SSH access on the server, then retry.";+ }+ if (+ lines.some((line) =>+ /^(?:(?:fatal: |ssh: )?Could not resolve host(?:name)?\b|fatal: unable to access .+: (?:Could not resolve host|Failed to connect)\b|ssh: connect to host \S+ port \d+: (?:Connection timed out|Connection refused|Network is unreachable)\b)/i.test(+ line,+ ),+ )+ ) {+ return "Git could not reach the remote. Check the server's network connection and remote host, then retry.";+ }+ if (+ lines.some((line) =>+ /^(?:remote: Repository not found\.?$|fatal: repository .+ not found$|fatal: .+ does not appear to be a git repository$)/i.test(+ line,+ ),+ )+ ) {+ return "Git could not access the remote repository. Check the remote URL and repository permissions on the server.";+ }+ if (+ lines.some((line) =>+ /^(?:(?:error|fatal): cannot lock ref\b|fatal: Unable to create ['"].+\.lock['"]:)/i.test(+ line,+ ),+ )+ ) {+ return "Git could not update a local reference. Another Git operation or a stale lock may be blocking the fetch; check the repository on the server, then retry.";+ }+ return undefined;+}+interface Trace2Monitor {readonly env: NodeJS.ProcessEnv;readonly flush: Effect.Effect<void, never>;@@ -1307,6 +1350,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*return yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName).pipe(Effect.tap(() => Effect.sync(() => clearStatusRemoteRefreshFailures(cacheKey))),Effect.tapError(() => Effect.sync(() => recordStatusRemoteRefreshFailure(cacheKey))),+ Effect.tapCause((cause) => Effect.logWarning("Background Git fetch failed", cause)),Effect.as(true as const),);});@@ -1331,13 +1375,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*const upstream = yield* resolveCurrentUpstream(cwd);if (!upstream) return;const gitCommonDir = yield* resolveGitCommonDir(cwd);+ // The cache loader logs failed attempts; cache hits keep using the last fetched refs.yield* Cache.get(statusRemoteRefreshCache,new StatusRemoteRefreshCacheKey({gitCommonDir,remoteName: upstream.remoteName,}),- );+ ).pipe(Effect.ignore);});const resolveDefaultBranchName = (@@ -3224,7 +3269,33 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*env: STATUS_UPSTREAM_REFRESH_ENV,fallbackErrorDetail: `git fetch ${input.remoteName} failed`,};- const fetchAll = executeGit("GitVcsDriver.fetchRemote", input.cwd, args, options);+ const fetchAll = executeGitWithStableDiagnostics(+ "GitVcsDriver.fetchRemote",+ input.cwd,+ args,+ {+ ...options,+ allowNonZeroExit: true,+ },+ ).pipe(+ Effect.flatMap((result) =>+ result.exitCode === 0+ ? Effect.void+ : Effect.fail(+ new GitCommandError({+ ...gitCommandContext({+ operation: "GitVcsDriver.fetchRemote",+ cwd: input.cwd,+ args,+ }),+ detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail,+ ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),+ stdoutLength: result.stdout.length,+ stderrLength: result.stderr.length,+ }),+ ),+ ),+ );if (input.refName === undefined) {return yield* fetchAll.pipe(Effect.asVoid);}@@ -3255,8 +3326,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*cwd: input.cwd,args: scopedArgs,}),- detail: options.fallbackErrorDetail,- exitCode: result.exitCode,+ detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail,+ ...(result.exitCode === null ? {} : { exitCode: result.exitCode }),stdoutLength: result.stdout.length,stderrLength: result.stderr.length,});