Skip to content

Commit 61b8981

Browse files
fix(server): name the cause of a failed git command
Git states why a command failed on stderr, but stderr is deliberately kept off GitCommandError — it echoes argv and remote URLs, which can carry credentials. Callers were left with "git fetch origin failed" and no way to tell a tag conflict from an auth failure without re-running git by hand. Match stderr at the driver against a fixed set of well-known failures and carry the result as a closed set of diagnostic tags, appended to the message the way EnvironmentInternalError does it. The tag names the cause; it selects no text, so nothing matched from stderr is ever quoted and the existing redaction guarantee is unchanged. Only git's own diagnostic lines are classified, plus the refusals ssh prints. Hooks write to the same stream unprefixed, so a pre-push hook echoing "authentication failed" would otherwise be reported as a credential failure. ssh states its refusal unprefixed too, naming whichever methods it tried, and git adds only a generic "could not read from remote repository" afterwards — so every refusal shape is matched, and an untrusted host key gets its own tag rather than being blamed on credentials. Fixes #4380
1 parent 053affb commit 61b8981

3 files changed

Lines changed: 354 additions & 1 deletion

File tree

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

Lines changed: 273 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -712,6 +712,279 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => {
712712
assert.notInclude(error.message, secret);
713713
assert.notProperty(error, "args");
714714
assert.notProperty(error, "stderr");
715+
assert.notProperty(error, "reason");
716+
}),
717+
);
718+
719+
it.effect("names the branch conflict behind a failed worktree add", () =>
720+
Effect.gen(function* () {
721+
const parent = yield* makeTmpDir();
722+
const pathService = yield* Path.Path;
723+
const cwd = pathService.join(parent, "repo");
724+
const fileSystem = yield* FileSystem.FileSystem;
725+
yield* fileSystem.makeDirectory(cwd);
726+
const driver = yield* GitVcsDriver.GitVcsDriver;
727+
yield* initRepoWithCommit(cwd);
728+
const firstWorktree = pathService.join(parent, "first");
729+
yield* git(cwd, ["worktree", "add", firstWorktree, "-b", "shared-branch"]);
730+
731+
const error = yield* driver
732+
.execute({
733+
operation: "GitVcsDriver.test.worktreeAddConflict",
734+
cwd,
735+
args: ["worktree", "add", pathService.join(parent, "second"), "shared-branch"],
736+
env: { LC_ALL: "C" },
737+
})
738+
.pipe(Effect.flip);
739+
740+
assert.deepInclude(error, {
741+
_tag: "GitCommandError",
742+
operation: "GitVcsDriver.test.worktreeAddConflict",
743+
reason: "branch_checked_out_in_worktree",
744+
});
745+
assert.include(error.message, "(branch_checked_out_in_worktree)");
746+
assert.notInclude(error.message, firstWorktree);
747+
}),
748+
);
749+
750+
it.effect("names a missing repository behind a failed command", () =>
751+
Effect.gen(function* () {
752+
const cwd = yield* makeTmpDir();
753+
const driver = yield* GitVcsDriver.GitVcsDriver;
754+
755+
const error = yield* driver
756+
.execute({
757+
operation: "GitVcsDriver.test.notARepository",
758+
cwd,
759+
args: ["rev-parse", "--abbrev-ref", "HEAD"],
760+
env: { LC_ALL: "C" },
761+
})
762+
.pipe(Effect.flip);
763+
764+
assert.deepInclude(error, {
765+
_tag: "GitCommandError",
766+
operation: "GitVcsDriver.test.notARepository",
767+
reason: "not_a_repository",
768+
});
769+
assert.include(error.message, "(not_a_repository)");
770+
}),
771+
);
772+
773+
it.effect("appends the reason tag to a caller-supplied detail", () =>
774+
Effect.gen(function* () {
775+
const parent = yield* makeTmpDir();
776+
const pathService = yield* Path.Path;
777+
const cwd = pathService.join(parent, "repo");
778+
const fileSystem = yield* FileSystem.FileSystem;
779+
yield* fileSystem.makeDirectory(cwd);
780+
const driver = yield* GitVcsDriver.GitVcsDriver;
781+
yield* initRepoWithCommit(cwd);
782+
yield* git(cwd, [
783+
"worktree",
784+
"add",
785+
pathService.join(parent, "taken"),
786+
"-b",
787+
"taken-branch",
788+
]);
789+
790+
const error = yield* driver
791+
.createWorktree({
792+
cwd,
793+
refName: "taken-branch",
794+
path: pathService.join(parent, "second"),
795+
})
796+
.pipe(Effect.flip);
797+
798+
assert.equal(error.detail, "git worktree add failed");
799+
assert.include(error.message, "git worktree add failed (branch_checked_out_in_worktree)");
800+
}),
801+
);
802+
803+
for (const { label, sshMessage, expectedReason, expectedText } of [
804+
{
805+
label: "a refused key",
806+
sshMessage: "[email protected]: Permission denied (publickey).",
807+
expectedReason: "authentication_failed" as const,
808+
expectedText: "(authentication_failed)",
809+
},
810+
{
811+
label: "a refused key among several methods",
812+
sshMessage: "[email protected]: Permission denied (publickey,password).",
813+
expectedReason: "authentication_failed" as const,
814+
expectedText: "(authentication_failed)",
815+
},
816+
{
817+
label: "a refused keyboard-interactive attempt",
818+
sshMessage: "[email protected]: Permission denied (keyboard-interactive).",
819+
expectedReason: "authentication_failed" as const,
820+
expectedText: "(authentication_failed)",
821+
},
822+
{
823+
label: "a rejected password",
824+
sshMessage: "Permission denied, please try again.",
825+
expectedReason: "authentication_failed" as const,
826+
expectedText: "(authentication_failed)",
827+
},
828+
{
829+
label: "an untrusted host key",
830+
sshMessage: "Host key verification failed.",
831+
expectedReason: "host_key_unverified" as const,
832+
expectedText: "(host_key_unverified)",
833+
},
834+
]) {
835+
it.effect(`names ${label} rather than an unreachable remote`, () =>
836+
Effect.gen(function* () {
837+
const parent = yield* makeTmpDir();
838+
const pathService = yield* Path.Path;
839+
const cwd = pathService.join(parent, "repo");
840+
const fileSystem = yield* FileSystem.FileSystem;
841+
const driver = yield* GitVcsDriver.GitVcsDriver;
842+
yield* fileSystem.makeDirectory(cwd);
843+
yield* initRepoWithCommit(cwd);
844+
yield* git(cwd, ["remote", "add", "origin", "[email protected]:owner/repo.git"]);
845+
// Stands in for ssh, which prints its refusal unprefixed and leaves
846+
// git to add only a generic "could not read" line after it.
847+
const fakeSsh = pathService.join(parent, "fake-ssh");
848+
yield* writeTextFile(
849+
parent,
850+
"fake-ssh",
851+
`#!/bin/sh\necho "${sshMessage}" >&2\nexit 255\n`,
852+
);
853+
yield* fileSystem.chmod(fakeSsh, 0o755);
854+
855+
const error = yield* driver
856+
.execute({
857+
operation: "GitVcsDriver.test.sshRefusal",
858+
cwd,
859+
args: ["fetch", "origin"],
860+
env: { LC_ALL: "C", GIT_SSH_COMMAND: fakeSsh },
861+
})
862+
.pipe(Effect.flip);
863+
864+
assert.deepInclude(error, { reason: expectedReason });
865+
assert.include(error.message, expectedText);
866+
}),
867+
);
868+
}
869+
870+
it.effect("does not read a filesystem permission error as an ssh refusal", () =>
871+
Effect.gen(function* () {
872+
const parent = yield* makeTmpDir();
873+
const pathService = yield* Path.Path;
874+
const cwd = pathService.join(parent, "repo");
875+
const fileSystem = yield* FileSystem.FileSystem;
876+
const driver = yield* GitVcsDriver.GitVcsDriver;
877+
yield* fileSystem.makeDirectory(cwd);
878+
yield* initRepoWithCommit(cwd);
879+
yield* git(cwd, ["remote", "add", "origin", "[email protected]:owner/repo.git"]);
880+
const fakeSsh = pathService.join(parent, "fake-ssh");
881+
yield* writeTextFile(
882+
parent,
883+
"fake-ssh",
884+
'#!/bin/sh\necho "fatal: cannot open backup file: Permission denied (os error 13)" >&2\nexit 255\n',
885+
);
886+
yield* fileSystem.chmod(fakeSsh, 0o755);
887+
888+
const error = yield* driver
889+
.execute({
890+
operation: "GitVcsDriver.test.osPermission",
891+
cwd,
892+
args: ["fetch", "origin"],
893+
env: { LC_ALL: "C", GIT_SSH_COMMAND: fakeSsh },
894+
})
895+
.pipe(Effect.flip);
896+
897+
assert.notInclude(error.message, "(authentication_failed)");
898+
}),
899+
);
900+
901+
it.effect("does not read remote hook output as a git failure reason", () =>
902+
Effect.gen(function* () {
903+
const parent = yield* makeTmpDir();
904+
const pathService = yield* Path.Path;
905+
const remote = pathService.join(parent, "origin.git");
906+
const cwd = pathService.join(parent, "work");
907+
const fileSystem = yield* FileSystem.FileSystem;
908+
const driver = yield* GitVcsDriver.GitVcsDriver;
909+
yield* fileSystem.makeDirectory(cwd);
910+
yield* initRepoWithCommit(cwd);
911+
yield* git(cwd, ["init", "--bare", remote]);
912+
yield* git(cwd, ["remote", "add", "origin", remote]);
913+
// Git prefixes everything the server says with `remote:`, so a remote
914+
// hook can put arbitrary text in front of the classifier.
915+
const preReceive = pathService.join(remote, "hooks", "pre-receive");
916+
yield* writeTextFile(
917+
remote,
918+
"hooks/pre-receive",
919+
'#!/bin/sh\necho "authentication failed" >&2\nexit 1\n',
920+
);
921+
yield* fileSystem.chmod(preReceive, 0o755);
922+
923+
const error = yield* driver
924+
.execute({
925+
operation: "GitVcsDriver.test.remoteHookOutput",
926+
cwd,
927+
args: ["push", "origin", "HEAD"],
928+
env: { LC_ALL: "C" },
929+
})
930+
.pipe(Effect.flip);
931+
932+
assert.notProperty(error, "reason");
933+
assert.notInclude(error.message, "(authentication_failed)");
934+
}),
935+
);
936+
937+
it.effect("does not read hook output as a git failure reason", () =>
938+
Effect.gen(function* () {
939+
const parent = yield* makeTmpDir();
940+
const pathService = yield* Path.Path;
941+
const remote = pathService.join(parent, "origin.git");
942+
const cwd = pathService.join(parent, "work");
943+
const fileSystem = yield* FileSystem.FileSystem;
944+
const driver = yield* GitVcsDriver.GitVcsDriver;
945+
yield* fileSystem.makeDirectory(cwd);
946+
yield* initRepoWithCommit(cwd);
947+
yield* git(cwd, ["init", "--bare", remote]);
948+
yield* git(cwd, ["remote", "add", "origin", remote]);
949+
yield* writeTextFile(
950+
cwd,
951+
".git/hooks/pre-push",
952+
'#!/bin/sh\necho "authentication failed" >&2\nexit 1\n',
953+
);
954+
yield* fileSystem.chmod(pathService.join(cwd, ".git/hooks/pre-push"), 0o755);
955+
956+
const error = yield* driver
957+
.execute({
958+
operation: "GitVcsDriver.test.hookOutput",
959+
cwd,
960+
args: ["push", "origin", "HEAD"],
961+
env: { LC_ALL: "C" },
962+
})
963+
.pipe(Effect.flip);
964+
965+
assert.notProperty(error, "reason");
966+
assert.notInclude(error.message, "(authentication_failed)");
967+
}),
968+
);
969+
970+
it.effect("leaves a tag collision unclassified rather than calling it a path", () =>
971+
Effect.gen(function* () {
972+
const cwd = yield* makeTmpDir();
973+
const driver = yield* GitVcsDriver.GitVcsDriver;
974+
yield* initRepoWithCommit(cwd);
975+
yield* git(cwd, ["tag", "v1"]);
976+
977+
const error = yield* driver
978+
.execute({
979+
operation: "GitVcsDriver.test.tagCollision",
980+
cwd,
981+
args: ["tag", "v1"],
982+
env: { LC_ALL: "C" },
983+
})
984+
.pipe(Effect.flip);
985+
986+
assert.notProperty(error, "reason");
987+
assert.notInclude(error.message, "(path_already_exists)");
715988
}),
716989
);
717990

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

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process";
2121

2222
import {
2323
GitCommandError,
24+
type GitCommandFailureReason,
2425
type ReviewDiffFileContentsInput,
2526
type ReviewDiffPreviewInput,
2627
type ReviewDiffPreviewSource,
@@ -391,6 +392,62 @@ function gitCommandContext(
391392
} as const;
392393
}
393394

395+
// Git states the actual cause on stderr, but stderr never leaves this module:
396+
// it echoes argv and remote URLs, which can carry credentials. Matching it
397+
// against fixed patterns yields a tag the caller can act on and a message that
398+
// quotes none of the matched text. Patterns run in order, specific first.
399+
const GIT_FAILURE_REASON_PATTERNS: ReadonlyArray<readonly [RegExp, GitCommandFailureReason]> = [
400+
[/would clobber existing tag/i, "tag_would_be_clobbered"],
401+
[/is already (?:used by worktree at|checked out at)/i, "branch_checked_out_in_worktree"],
402+
[/a branch named .+ already exists/i, "branch_already_exists"],
403+
// ssh names the methods it tried, so the parenthesized list varies:
404+
// `(publickey)`, `(publickey,password)`, `(keyboard-interactive)`.
405+
[
406+
/(?:authentication failed|could not read Username|could not read Password|permission denied \([a-z-]+(?:,[a-z-]+)*\)|permission denied, please try again)/i,
407+
"authentication_failed",
408+
],
409+
// Distinct from a credential failure: the remote answered and the key it
410+
// presented is untrusted, so pointing the user at credentials would misdirect.
411+
[/host key verification failed/i, "host_key_unverified"],
412+
[
413+
/(?:could not read from remote repository|does not appear to be a git repository|repository .+ not found)/i,
414+
"remote_unreachable",
415+
],
416+
// Quoted-path forms only: an unquoted `fatal: <thing> already exists` also
417+
// covers tag and ref collisions, which are not path collisions.
418+
[/fatal: '[^']+' already exists|destination path .+ already exists/i, "path_already_exists"],
419+
];
420+
421+
// Hooks write to the same stream git does, and nothing distinguishes their
422+
// text from git's: a pre-push hook echoing "authentication failed" would
423+
// otherwise be read as a credential failure. Git prefixes its own diagnostics
424+
// and states a push rejection on a `! [rejected]` line, so only those are
425+
// classified. `remote:` is deliberately excluded — git prefixes every byte the
426+
// server sends that way, remote hook output included, so trusting it would
427+
// reintroduce the same false positive from the other end of the connection.
428+
const GIT_DIAGNOSTIC_LINE_PATTERN = /^(?:fatal|error):|^!\s|^\s+!\s/;
429+
// ssh reports the refusal itself, unprefixed, and git only adds a generic
430+
// "Could not read from remote repository" after it. Dropping ssh's line would
431+
// leave that generic one to be read as an unreachable remote when the real
432+
// cause is credentials, so these specific refusals are classified too.
433+
const SSH_TRANSPORT_REFUSAL_PATTERN =
434+
/Permission denied \((?:publickey|password|keyboard-interactive)|Permission denied, please try again|Host key verification failed/i;
435+
436+
function classifyGitFailure(stderr: string): GitCommandFailureReason | null {
437+
const diagnostics = stderr
438+
.split(/\r?\n/)
439+
.filter(
440+
(line) => GIT_DIAGNOSTIC_LINE_PATTERN.test(line) || SSH_TRANSPORT_REFUSAL_PATTERN.test(line),
441+
)
442+
.join("\n");
443+
if (diagnostics.length === 0) return null;
444+
if (isNonRepositoryGitStderr(diagnostics)) return "not_a_repository";
445+
for (const [pattern, reason] of GIT_FAILURE_REASON_PATTERNS) {
446+
if (pattern.test(diagnostics)) return reason;
447+
}
448+
return null;
449+
}
450+
394451
function parseDefaultBranchFromRemoteHeadRef(value: string, remoteName: string): string | null {
395452
const trimmed = value.trim();
396453
const prefix = `refs/remotes/${remoteName}/`;
@@ -811,8 +868,10 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
811868
yield* trace2Monitor.flush;
812869

813870
if (!input.allowNonZeroExit && exitCode !== 0) {
871+
const reason = classifyGitFailure(stderr.text);
814872
return yield* new GitCommandError({
815873
...gitCommandContext(commandInput),
874+
...(reason === null ? {} : { reason }),
816875
detail: "Git command exited with a non-zero status.",
817876
exitCode,
818877
stdoutLength: stdout.text.length,
@@ -895,9 +954,11 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function*
895954
if (options.allowNonZeroExit || result.exitCode === 0) {
896955
return Effect.succeed(result);
897956
}
957+
const reason = classifyGitFailure(result.stderr);
898958
return Effect.fail(
899959
new GitCommandError({
900960
...gitCommandContext({ operation, cwd, args }),
961+
...(reason === null ? {} : { reason }),
901962
detail: options.fallbackErrorDetail ?? "Git command exited with a non-zero status.",
902963
...(result.exitCode === null ? {} : { exitCode: result.exitCode }),
903964
stdoutLength: result.stdout.length,

0 commit comments

Comments
 (0)