Skip to content

Commit 3230a6b

Browse files
fix(git): explain fetch failures without exposing remote output
1 parent ccad9f6 commit 3230a6b

2 files changed

Lines changed: 214 additions & 12 deletions

File tree

‎apps/server/src/vcs/GitVcsDriverCore.test.ts‎

Lines changed: 144 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ import * as Effect from "effect/Effect";
88
import * as FileSystem from "effect/FileSystem";
99
import * as Fiber from "effect/Fiber";
1010
import * as Layer from "effect/Layer";
11+
import * as Logger from "effect/Logger";
1112
import * as Metric from "effect/Metric";
1213
import * as Path from "effect/Path";
1314
import * as PlatformError from "effect/PlatformError";
@@ -35,6 +36,8 @@ import {
3536
} from "./GitVcsDriverCore.ts";
3637
import * as GitVcsDriver from "./GitVcsDriver.ts";
3738

39+
const encodeGitCommandError = Schema.encodeEffect(Schema.fromJsonString(GitCommandError));
40+
3841
const ServerConfigLayer = ServerConfig.layerTest(process.cwd(), {
3942
prefix: "t3-git-vcs-driver-test-",
4043
});
@@ -718,7 +721,7 @@ it.effect("refreshes the current branch after an external checkout", () =>
718721
).pipe(Effect.provide(TestLayer)),
719722
);
720723

721-
it.effect("backs off failed upstream refreshes across linked worktrees", () =>
724+
it.effect("backs off and logs failed fetch attempts across linked worktrees", () =>
722725
Effect.scoped(
723726
Effect.gen(function* () {
724727
const delegate = yield* ChildProcessSpawner.ChildProcessSpawner;
@@ -738,6 +741,14 @@ it.effect("backs off failed upstream refreshes across linked worktrees", () =>
738741
const driver = yield* makeGitVcsDriverCore().pipe(
739742
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, failingFetchSpawner),
740743
);
744+
const warnings: string[] = [];
745+
const logger = Logger.make<unknown, void>(({ message }) => {
746+
warnings.push(String(message));
747+
});
748+
const readRemoteStatus = (workingDirectory: string) =>
749+
driver
750+
.statusDetailsRemote(workingDirectory)
751+
.pipe(Effect.provideService(Logger.CurrentLoggers, new Set([logger])));
741752
const cwd = yield* makeTmpDir();
742753
const remote = yield* makeTmpDir("git-vcs-driver-remote-");
743754
const worktreesRoot = yield* makeTmpDir("git-vcs-driver-worktrees-");
@@ -781,29 +792,134 @@ it.effect("backs off failed upstream refreshes across linked worktrees", () =>
781792
);
782793
yield* Ref.set(fetchAttempts, 0);
783794

784-
yield* driver.statusDetailsRemote(cwd);
785-
yield* driver.statusDetailsRemote(worktreePath);
795+
yield* readRemoteStatus(cwd);
796+
yield* readRemoteStatus(worktreePath);
786797
assert.equal(yield* Ref.get(fetchAttempts), 1);
798+
assert.lengthOf(warnings, 1);
799+
assert.include(warnings[0], "Background Git fetch failed");
787800

788801
yield* TestClock.adjust("29 seconds");
789-
yield* driver.statusDetailsRemote(worktreePath);
802+
yield* readRemoteStatus(worktreePath);
790803
assert.equal(yield* Ref.get(fetchAttempts), 1);
804+
assert.lengthOf(warnings, 1);
791805

792806
yield* TestClock.adjust("1 second");
793-
yield* driver.statusDetailsRemote(cwd);
807+
yield* readRemoteStatus(cwd);
794808
assert.equal(yield* Ref.get(fetchAttempts), 2);
809+
assert.lengthOf(warnings, 2);
795810

796811
yield* TestClock.adjust("59 seconds");
797-
yield* driver.statusDetailsRemote(worktreePath);
812+
yield* readRemoteStatus(worktreePath);
798813
assert.equal(yield* Ref.get(fetchAttempts), 2);
814+
assert.lengthOf(warnings, 2);
799815

800816
yield* TestClock.adjust("1 second");
801-
yield* driver.statusDetailsRemote(cwd);
817+
yield* readRemoteStatus(cwd);
802818
assert.equal(yield* Ref.get(fetchAttempts), 3);
819+
assert.lengthOf(warnings, 3);
803820
}),
804821
).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
805822
);
806823

824+
for (const scenario of [
825+
{
826+
name: "HTTPS credentials",
827+
stderr: "fatal: Authentication failed for",
828+
expected: "could not authenticate",
829+
},
830+
{
831+
name: "SSH credentials",
832+
stderr: "[email protected]: Permission denied (publickey).",
833+
expected: "could not authenticate",
834+
},
835+
{
836+
name: "disabled prompts",
837+
stderr: "fatal: could not read Username: terminal prompts disabled",
838+
expected: "could not authenticate",
839+
},
840+
{
841+
name: "DNS failure",
842+
stderr: "fatal: Could not resolve host: example.com",
843+
expected: "could not reach the remote",
844+
},
845+
{
846+
name: "connection failure",
847+
stderr: "ssh: connect to host example.com port 22: Connection refused",
848+
expected: "could not reach the remote",
849+
},
850+
{
851+
name: "missing remote",
852+
stderr: "remote: Repository not found.",
853+
expected: "could not access the remote repository",
854+
},
855+
{
856+
name: "invalid remote",
857+
stderr: "fatal: remote does not appear to be a git repository",
858+
expected: "could not access the remote repository",
859+
},
860+
{
861+
name: "reference lock",
862+
stderr: "error: cannot lock ref 'refs/remotes/origin/main': is at abc but expected def",
863+
expected: "could not update a local reference",
864+
},
865+
{
866+
name: "lock file",
867+
stderr: "fatal: Unable to create '/repo/.git/FETCH_HEAD.lock': File exists.",
868+
expected: "could not update a local reference",
869+
},
870+
{
871+
name: "unknown failure",
872+
stderr: "fatal: unexpected remote failure",
873+
expected: "git fetch origin failed",
874+
},
875+
] as const) {
876+
it.effect(`reports ${scenario.name} during fetch without retaining remote output`, () =>
877+
Effect.gen(function* () {
878+
const secret = "secret-fetch-token";
879+
const stderr = `${scenario.stderr}\nhttps://user:${secret}@example.com/private?token=${secret}`;
880+
const attempts = yield* Ref.make(0);
881+
const spawner = ChildProcessSpawner.make((command) =>
882+
Effect.gen(function* () {
883+
if (!ChildProcess.isStandardCommand(command))
884+
return yield* Effect.die("expected Git command");
885+
if (command.args[0] !== "fetch") return makeNonRepositoryHandle();
886+
assert.deepEqual(command.args, ["fetch", "--quiet", "origin"]);
887+
assert.equal(command.options.env?.LC_ALL, "C");
888+
assert.equal(command.options.env?.GIT_TERMINAL_PROMPT, "0");
889+
yield* Ref.update(attempts, (count) => count + 1);
890+
return ChildProcessSpawner.makeHandle({
891+
pid: ChildProcessSpawner.ProcessId(1),
892+
exitCode: Effect.succeed(ChildProcessSpawner.ExitCode(128)),
893+
isRunning: Effect.succeed(false),
894+
kill: () => Effect.void,
895+
unref: Effect.succeed(Effect.void),
896+
stdin: Sink.drain,
897+
stdout: Stream.encodeText(Stream.make(secret)),
898+
stderr: Stream.encodeText(Stream.make(stderr)),
899+
all: Stream.empty,
900+
getInputFd: () => Sink.drain,
901+
getOutputFd: () => Stream.empty,
902+
});
903+
}),
904+
);
905+
const driver = yield* makeGitVcsDriverCore().pipe(
906+
Effect.provideService(ChildProcessSpawner.ChildProcessSpawner, spawner),
907+
);
908+
const cwd = yield* makeTmpDir();
909+
const error = yield* driver.fetchRemote({ cwd, remoteName: "origin" }).pipe(Effect.flip);
910+
assert.include(error.detail, scenario.expected);
911+
assert.equal(error.exitCode, 128);
912+
assert.equal(error.stderrLength, stderr.length);
913+
assert.equal(error.stdoutLength, secret.length);
914+
assert.notInclude(error.message, secret);
915+
assert.notInclude(yield* encodeGitCommandError(error), secret);
916+
assert.notProperty(error, "stderr");
917+
assert.notProperty(error, "args");
918+
assert.equal(yield* Ref.get(attempts), 1);
919+
}).pipe(Effect.provide(ServerConfigLayer.pipe(Layer.provideMerge(NodeServices.layer)))),
920+
);
921+
}
922+
807923
it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
808924
describe("process environment", () => {
809925
it.effect("preserves the caller locale for general Git subprocesses", () =>
@@ -2398,6 +2514,22 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
23982514
});
23992515

24002516
describe("remote operations", () => {
2517+
it.effect("explains a real fetch failure for a missing local remote", () =>
2518+
Effect.gen(function* () {
2519+
const cwd = yield* makeTmpDir();
2520+
yield* initRepoWithCommit(cwd);
2521+
const driver = yield* GitVcsDriver.GitVcsDriver;
2522+
const missingRemote = `${cwd}/private-missing-remote`;
2523+
yield* git(cwd, ["remote", "add", "origin", missingRemote]);
2524+
const error = yield* driver.fetchRemote({ cwd, remoteName: "origin" }).pipe(Effect.flip);
2525+
assert.include(error.detail, "could not access the remote repository");
2526+
assert.equal(error.exitCode, 128);
2527+
assert.isAbove(error.stderrLength ?? 0, 0);
2528+
assert.notInclude(error.detail, missingRemote);
2529+
assert.notProperty(error, "stderr");
2530+
}),
2531+
);
2532+
24012533
it.effect("ensureRemote reuses an existing remote across ssh/https transport variants", () =>
24022534
Effect.gen(function* () {
24032535
const cwd = yield* makeTmpDir();
@@ -2544,7 +2676,11 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
25442676
if (Result.isFailure(result)) {
25452677
assert.equal(
25462678
result.failure.detail,
2547-
failure === "timeout" ? "Git command timed out." : "git fetch origin failed",
2679+
failure === "timeout"
2680+
? "Git command timed out."
2681+
: failure === "offline"
2682+
? "Git could not reach the remote. Check the server's network connection and remote host, then retry."
2683+
: "Git could not authenticate with the remote. Check Git credentials or SSH access on the server, then retry.",
25482684
);
25492685
}
25502686
}),

‎apps/server/src/vcs/GitVcsDriverCore.ts‎

Lines changed: 70 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -469,6 +469,44 @@ function isMissingWorktreeStderr(stderr: string): boolean {
469469
);
470470
}
471471

472+
// Fetch stderr can contain remote credentials. Only fixed diagnoses may enter
473+
// persisted errors; unrecognized output keeps the generic failure message.
474+
function fetchFailureDetail(stderr: string): string | undefined {
475+
const normalized = stderr.toLowerCase();
476+
if (
477+
normalized.includes("authentication failed") ||
478+
normalized.includes("permission denied (publickey") ||
479+
normalized.includes("could not read username") ||
480+
normalized.includes("could not read password") ||
481+
normalized.includes("terminal prompts disabled")
482+
) {
483+
return "Git could not authenticate with the remote. Check Git credentials or SSH access on the server, then retry.";
484+
}
485+
if (
486+
normalized.includes("could not resolve host") ||
487+
normalized.includes("could not resolve hostname") ||
488+
normalized.includes("failed to connect") ||
489+
normalized.includes("connection timed out") ||
490+
normalized.includes("connection refused") ||
491+
normalized.includes("network is unreachable")
492+
) {
493+
return "Git could not reach the remote. Check the server's network connection and remote host, then retry.";
494+
}
495+
if (
496+
normalized.includes("repository not found") ||
497+
normalized.includes("does not appear to be a git repository")
498+
) {
499+
return "Git could not access the remote repository. Check the remote URL and repository permissions on the server.";
500+
}
501+
if (
502+
normalized.includes("cannot lock ref") ||
503+
(normalized.includes("unable to create") && normalized.includes(".lock"))
504+
) {
505+
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.";
506+
}
507+
return undefined;
508+
}
509+
472510
interface Trace2Monitor {
473511
readonly env: NodeJS.ProcessEnv;
474512
readonly flush: Effect.Effect<void, never>;
@@ -1307,6 +1345,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
13071345
return yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName).pipe(
13081346
Effect.tap(() => Effect.sync(() => clearStatusRemoteRefreshFailures(cacheKey))),
13091347
Effect.tapError(() => Effect.sync(() => recordStatusRemoteRefreshFailure(cacheKey))),
1348+
Effect.tapCause((cause) => Effect.logWarning("Background Git fetch failed", cause)),
13101349
Effect.as(true as const),
13111350
);
13121351
});
@@ -1331,13 +1370,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
13311370
const upstream = yield* resolveCurrentUpstream(cwd);
13321371
if (!upstream) return;
13331372
const gitCommonDir = yield* resolveGitCommonDir(cwd);
1373+
// The cache loader logs failed attempts; cache hits keep using the last fetched refs.
13341374
yield* Cache.get(
13351375
statusRemoteRefreshCache,
13361376
new StatusRemoteRefreshCacheKey({
13371377
gitCommonDir,
13381378
remoteName: upstream.remoteName,
13391379
}),
1340-
);
1380+
).pipe(Effect.ignore);
13411381
});
13421382

13431383
const resolveDefaultBranchName = (
@@ -3224,7 +3264,33 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
32243264
env: STATUS_UPSTREAM_REFRESH_ENV,
32253265
fallbackErrorDetail: `git fetch ${input.remoteName} failed`,
32263266
};
3227-
const fetchAll = executeGit("GitVcsDriver.fetchRemote", input.cwd, args, options);
3267+
const fetchAll = executeGitWithStableDiagnostics(
3268+
"GitVcsDriver.fetchRemote",
3269+
input.cwd,
3270+
args,
3271+
{
3272+
...options,
3273+
allowNonZeroExit: true,
3274+
},
3275+
).pipe(
3276+
Effect.flatMap((result) =>
3277+
result.exitCode === 0
3278+
? Effect.void
3279+
: Effect.fail(
3280+
new GitCommandError({
3281+
...gitCommandContext({
3282+
operation: "GitVcsDriver.fetchRemote",
3283+
cwd: input.cwd,
3284+
args,
3285+
}),
3286+
detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail,
3287+
...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
3288+
stdoutLength: result.stdout.length,
3289+
stderrLength: result.stderr.length,
3290+
}),
3291+
),
3292+
),
3293+
);
32283294
if (input.refName === undefined) {
32293295
return yield* fetchAll.pipe(Effect.asVoid);
32303296
}
@@ -3255,8 +3321,8 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
32553321
cwd: input.cwd,
32563322
args: scopedArgs,
32573323
}),
3258-
detail: options.fallbackErrorDetail,
3259-
exitCode: result.exitCode,
3324+
detail: fetchFailureDetail(result.stderr) ?? options.fallbackErrorDetail,
3325+
...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
32603326
stdoutLength: result.stdout.length,
32613327
stderrLength: result.stderr.length,
32623328
});

0 commit comments

Comments
 (0)