From 9bffa6ee53ce3ce909275fd337c6f11433a8345e Mon Sep 17 00:00:00 2001 From: davidfowl <95136+davidfowl@users.noreply.github.com> Date: Sun, 1 Nov 2026 02:17:35 +0000 Subject: [PATCH] Bound the OpenSSH version probe by the caller's Git deadline The unattended-SSH verification ran `ssh -V` with a private 5s timeout. A cold first launch of ssh.exe on Windows CI exceeded it, so a working OpenSSH client was reported as "Unattended Git requires a verified OpenSSH executable". This failed GitCommandRunnerTests on main. The probe now uses the caller's acquisition deadline, like every other Git child. A hung probe still ends at that deadline with the Git timeout diagnostic. Contributes to #21600 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- docs/specs/cli-config-sources.md | 2 +- src/Aspire.Cli/Git/GitCommandRunner.cs | 6 +- .../GitCommandRunnerTests.Authentication.cs | 74 +++++++++++++++++++ 3 files changed, 80 insertions(+), 2 deletions(-) diff --git a/docs/specs/cli-config-sources.md b/docs/specs/cli-config-sources.md index 4e974356eb8..f0cb5b69d48 100644 --- a/docs/specs/cli-config-sources.md +++ b/docs/specs/cli-config-sources.md @@ -120,7 +120,7 @@ When the CLI host supports interactive input, fetch with inherited terminal inpu Unattended configuration-source Git operations (including opted-in JSON listing, non-interactive `new`/`init`, and advisory checks) override `core.askPass` only for the child process and disable `GIT_ASKPASS`, `SSH_ASKPASS`, terminal prompts and Git Credential Manager interaction. Standard input receives EOF. This also applies when `--non-interactive`, `ASPIRE_NON_INTERACTIVE`, or CI disables host input. Credential helpers remain enabled for cached credentials; custom credential helpers must themselves run without prompting. Interactive Git acquisition and captured template-repository acquisition retain their existing authentication behavior. -Unattended SSH resolves the selected executable through Git's effective child `PATH`, including Git for Windows' bundled executable directories, rather than substituting an OpenSSH client found on the CLI's own `PATH`. It verifies that executable and supplies `BatchMode=yes`, preserving configured identity files, known hosts and agent authentication. Unknown host keys and unavailable credentials fail rather than prompt. Bare OpenSSH executable selections through `GIT_SSH`, `GIT_SSH_COMMAND` or `core.sshCommand` are supported, but custom command strings with arguments, shell expansions or wrappers fail with an actionable diagnostic instead of being silently overwritten or receiving potentially incompatible OpenSSH options. Move identity/host options into OpenSSH configuration or use interactive acquisition for those commands. Custom credential helpers, SSH agents and proxy commands are not sandboxed and must already be unattended. Git URL rewrites are resolved before selecting this SSH policy, so HTTPS selectors rewritten to SSH receive the same protection. No user Git configuration is modified. +Unattended SSH resolves the selected executable through Git's effective child `PATH`, including Git for Windows' bundled executable directories, rather than substituting an OpenSSH client found on the CLI's own `PATH`. It verifies that executable's OpenSSH version within the caller's operation timeout, without a separate shorter limit that would misreport a slow first launch as an unsupported client, and supplies `BatchMode=yes`, preserving configured identity files, known hosts and agent authentication. Unknown host keys and unavailable credentials fail rather than prompt. Bare OpenSSH executable selections through `GIT_SSH`, `GIT_SSH_COMMAND` or `core.sshCommand` are supported, but custom command strings with arguments, shell expansions or wrappers fail with an actionable diagnostic instead of being silently overwritten or receiving potentially incompatible OpenSSH options. Move identity/host options into OpenSSH configuration or use interactive acquisition for those commands. Custom credential helpers, SSH agents and proxy commands are not sandboxed and must already be unattended. Git URL rewrites are resolved before selecting this SSH policy, so HTTPS selectors rewritten to SSH receive the same protection. No user Git configuration is modified. If a non-interactive fetch blocks waiting for a custom authentication helper, the 30-second timeout terminates its process tree and reports the timeout. Capture output without truncation, including prompts without a terminating newline, and display the last 64 Ki characters of the combined fetch output on stderr so the user can diagnose and correct authentication. Local query results remain complete. Do not display captured configuration-file contents or copy these diagnostics into exception messages, logs, or telemetry. User cancellation and shutdown cancellation do not display captured output. Advisory timeout output is deferred with the warning until command exit and does not change the foreground command's exit code. diff --git a/src/Aspire.Cli/Git/GitCommandRunner.cs b/src/Aspire.Cli/Git/GitCommandRunner.cs index 5654f45701f..e87c3085b7b 100644 --- a/src/Aspire.Cli/Git/GitCommandRunner.cs +++ b/src/Aspire.Cli/Git/GitCommandRunner.cs @@ -269,8 +269,12 @@ internal static string GetSshExecutable(string command) probe.FileName = executable; probe.ArgumentList.Clear(); probe.ArgumentList.Add("-V"); + // Bound the probe only by the caller's acquisition deadline, like every other + // Git child. A cold first launch (for example, Windows Defender scanning + // ssh.exe) can take several seconds. A private shorter timeout would misreport + // a working OpenSSH client as unsupported instead of a Git timeout. var result = await ProcessCaptureRunner.RunAsync( - probe, TimeSpan.FromSeconds(5), + probe, Timeout.InfiniteTimeSpan, async (process, token) => { process.StandardInput.Close(); diff --git a/tests/Aspire.Cli.Tests/Git/GitCommandRunnerTests.Authentication.cs b/tests/Aspire.Cli.Tests/Git/GitCommandRunnerTests.Authentication.cs index c0fb84324f3..63c471791ca 100644 --- a/tests/Aspire.Cli.Tests/Git/GitCommandRunnerTests.Authentication.cs +++ b/tests/Aspire.Cli.Tests/Git/GitCommandRunnerTests.Authentication.cs @@ -281,6 +281,66 @@ public async Task ConfigureUnattendedSsh_UsesExecutableDirectoryPrependedByRealG Assert.Equal("", await File.ReadAllTextAsync(config)); } + [Fact] + [PlatformSpecific(TestPlatforms.AnyUnix)] + [RequiresTools(["git"])] + public async Task ConfigureUnattendedSsh_SlowOpenSshVersionProbeIsBoundedOnlyByCallerDeadline() + { + using var workspace = TemporaryWorkspace.CreateForCli(outputHelper); + var config = Path.Combine(workspace.Path, "gitconfig"); + await File.WriteAllTextAsync(config, ""); + // Simulates a cold first launch, such as Windows Defender scanning ssh.exe on CI. + // The delay must exceed the former private 5s probe timeout. That timeout + // reported this working OpenSSH client as unsupported. + var ssh = await CreateFakeSshAsync(Path.Combine(workspace.Path, "slow-ssh"), + "sleep 6\necho 'OpenSSH_9.9p1, slow start' >&2"); + string[] arguments = ["ls-remote", "--", "ssh://git@example.test/repository"]; + var runner = CreateRunner(); + var info = runner.CreateStartInfo(workspace.Path, arguments, GitCommandMode.Unattended); + IsolateGit(info, workspace.Path, config); + info.Environment["GIT_SSH_COMMAND"] = $"'{ssh}'"; + + await runner.ConfigureUnattendedSshAsync(info, arguments, TestContext.Current.CancellationToken); + + AssertOpenSshCommand(ssh, info.Environment["GIT_SSH_COMMAND"]); + Assert.Equal("ssh", info.Environment["GIT_SSH_VARIANT"]); + } + + [Fact] + [PlatformSpecific(TestPlatforms.AnyUnix)] + [RequiresTools(["git"])] + public async Task ConfigureUnattendedSsh_CallerCancellationStopsHungOpenSshVersionProbe() + { + using var workspace = TemporaryWorkspace.CreateForCli(outputHelper); + var config = Path.Combine(workspace.Path, "gitconfig"); + await File.WriteAllTextAsync(config, ""); + var started = Path.Combine(workspace.Path, "probe-started"); + var ssh = await CreateFakeSshAsync(Path.Combine(workspace.Path, "hung-ssh"), + $": > '{ShellPath(started)}'\nexec sleep 600"); + string[] arguments = ["ls-remote", "--", "ssh://git@example.test/repository"]; + var runner = CreateRunner(); + var info = runner.CreateStartInfo(workspace.Path, arguments, GitCommandMode.Unattended); + IsolateGit(info, workspace.Path, config); + info.Environment["GIT_SSH_COMMAND"] = $"'{ssh}'"; + using var cancellation = CancellationTokenSource.CreateLinkedTokenSource(TestContext.Current.CancellationToken); + var probeStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously); + using var watcher = new FileSystemWatcher(workspace.Path, Path.GetFileName(started)); + watcher.Created += (_, _) => probeStarted.TrySetResult(); + watcher.EnableRaisingEvents = true; + + var configure = runner.ConfigureUnattendedSshAsync(info, arguments, cancellation.Token); + if (File.Exists(started)) + { + probeStarted.TrySetResult(); + } + await probeStarted.Task.WaitAsync(TestContext.Current.CancellationToken); + cancellation.Cancel(); + + // The caller's deadline maps cancellation to a Git timeout diagnostic. + // It must not be converted into the unsupported-SSH diagnostic. + await Assert.ThrowsAnyAsync(() => configure); + } + [Theory] [InlineData(null)] [InlineData("GIT_SSH")] @@ -335,6 +395,20 @@ public void NormalizeSshPath_ResolvesRelativeEntriesAndSkipsMalformedEntries() Assert.Equal($"{Path.Combine(gitDirectory, "tools")}{Path.PathSeparator}{absolute}", normalized); } + private static async Task CreateFakeSshAsync(string directory, string script) + { + if (OperatingSystem.IsWindows()) + { + throw new PlatformNotSupportedException("Fake SSH clients are POSIX shell scripts."); + } + Directory.CreateDirectory(directory); + var ssh = Path.Combine(directory, "ssh"); + await File.WriteAllTextAsync(ssh, $"#!/bin/sh\n{script}\n"); + File.SetUnixFileMode(ssh, UnixFileMode.UserRead | UnixFileMode.UserWrite | UnixFileMode.UserExecute); + + return ssh; + } + private static string ShellPath(string path) => path.Replace("\\", "/", StringComparison.Ordinal).Replace("'", "'\\''", StringComparison.Ordinal); private static void AssertOpenSshCommand(string executable, string? command)