Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
94 changes: 94 additions & 0 deletions src/Wip.Core/Execution/CommandResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,8 @@ public string Resolve(string configured = "auto")
{
if (configured != "auto")
{
RejectRelativePath(configured);
RejectNonLocalPath(configured);
return TryGetFullPath(resolveExecutable(configured)) ?? throw NotFound([configured]);
}

Expand All @@ -64,6 +66,98 @@ public string Resolve(string configured = "auto")
throw NotFound(candidates);
}

/// <summary>
/// A configured command must be a bare name, searched on PATH, or a fully qualified path.
/// Anything else with a separator in it, or rooted, is refused before any resolver sees
/// it, an injected one included.
/// </summary>
/// <remarks>
/// <para>
/// The value comes from <c>wip.yml</c>, which is part of the project tree. A relative path
/// would be resolved against whatever directory wip was run from, so a <c>wip.yml</c> in a
/// freshly cloned repository could pick a binary inside that repository and have it run with
/// the user's privileges. A bare name is not affected: the PATH walk already skips entries
/// that are not fully qualified.
/// </para>
/// <para>
/// Refusing beats re-rooting against the project root. Re-rooting removes only the "depends
/// on where you ran wip from" part; the value would still come from the cloned tree and
/// still name a binary in it. <see cref="Path.IsPathFullyQualified(string)"/> rather than
/// <c>IsPathRooted</c>, because the drive-relative <c>C:wslc.exe</c> and the root-relative
/// <c>\wslc.exe</c> are rooted yet still depend on the current drive or directory.
/// </para>
/// <para>
/// Thrown as <see cref="CommandNotFoundException"/>, keeping it the only failure callers
/// have to handle; the message is what says why.
/// </para>
/// </remarks>
private void RejectRelativePath(string configured)
{
// Rooted catches C:wslc.exe, which has no separator, yet as a bare name would reach
// Path.Combine in the PATH walk and come back as itself.
var isPath = configured.Contains(Path.DirectorySeparatorChar)
|| configured.Contains(Path.AltDirectorySeparatorChar)
|| Path.IsPathRooted(configured);
if (!isPath || Path.IsPathFullyQualified(configured))
{
return;
}

throw new CommandNotFoundException(
$"""
{label} was configured as a relative path, which wip refuses: "{configured}"

Configure an absolute path, or a bare name to search for on PATH. A relative
path would be resolved against whatever directory wip was run from, so a wip.yml
in a cloned repository could choose a binary inside that repository.
""");
}

/// <summary>
/// On Windows a configured path must also sit on a drive: UNC (<c>\\server\share\...</c>,
/// <c>//server/share/...</c>) and device paths (<c>\\?\...</c>, <c>\\.\...</c>) are
/// refused, although <see cref="Path.IsPathFullyQualified(string)"/> accepts them.
/// </summary>
/// <remarks>
/// <para>
/// The threat is the one <see cref="RejectRelativePath"/> closes, only easier: a
/// <c>wip.yml</c> naming <c>\\host\share\wslc.exe</c> needs no knowledge of where the
/// victim cloned it, and the binary is fetched over SMB and run with the user's privileges.
/// </para>
/// <para>
/// A mapped network drive (<c>Z:\...</c>) is allowed on purpose. It looks exactly like a
/// local drive, it has to exist on the user's machine already, so the repository cannot
/// bring it along, and refusing it would break an operator who keeps tools there.
/// </para>
/// <para>
/// Unix has no UNC form, and a fully qualified path there already means one starting with
/// <c>/</c>, so nothing is added on Unix.
/// </para>
/// </remarks>
private void RejectNonLocalPath(string configured)
{
// A bare name has no root; RejectRelativePath has already refused any rooted value
// that is not fully qualified.
if (!OperatingSystem.IsWindows() || !Path.IsPathRooted(configured)
|| IsDriveRoot(Path.GetPathRoot(configured)))
{
return;
}

throw new CommandNotFoundException(
$"""
{label} was configured as a network or device path, which wip refuses: "{configured}"

Configure an absolute path on a drive, such as C:\, or a bare name to search for
on PATH. A UNC or device path lets a wip.yml in a cloned repository run a binary
from another machine.
""");
}

/// <summary>True for a root shaped like <c>C:\</c> or <c>C:/</c>, the only root a configured path may have on Windows.</summary>
internal static bool IsDriveRoot(string? root) =>
root is { Length: 3 } && char.IsAsciiLetter(root[0]) && root[1] == ':' && root[2] is '\\' or '/';

private static IReadOnlyList<string> BuildDefaultCandidates()
{
var candidates = new List<string>();
Expand Down
147 changes: 139 additions & 8 deletions tests/Wip.Tests/CommandResolverTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -122,29 +122,158 @@ public void ResolvedPathIsNotReplacedBySameNamedFileInNewWorkingDirectory()
}

[Fact]
public void ExplicitRelativePathIsFrozenAsAbsolutePath()
public void RelativeConfiguredCommandIsRefusedEvenWhenTheFileExists()
{
using var directory = new TemporaryDirectory();
var originalDirectory = Environment.CurrentDirectory;
try
{
// A real file at the relative location, so only the guard can make this throw.
Environment.CurrentDirectory = directory.Path;
var relative = Path.Combine("bin", "tool");
Directory.CreateDirectory(Path.GetDirectoryName(Path.GetFullPath(relative))!);
File.WriteAllText(relative, string.Empty);
Directory.CreateDirectory(Path.Combine(directory.Path, "bin"));
File.WriteAllText(Path.Combine(directory.Path, relative), string.Empty);

var resolved = new CommandResolver([]).Resolve(relative);
Environment.CurrentDirectory = originalDirectory;
var refused = Assert.Throws<CommandNotFoundException>(() => new CommandResolver([]).Resolve(relative));

Assert.Equal(Path.Combine(directory.Path, "bin", "tool"), resolved);
Assert.True(File.Exists(resolved));
Assert.Contains($"\"{relative}\"", refused.Message);
Assert.Contains("absolute path", refused.Message);
}
finally
{
Environment.CurrentDirectory = originalDirectory;
}
}

[Fact]
public void AbsoluteConfiguredCommandStillResolves()
{
using var directory = new TemporaryDirectory();
var executable = Path.Combine(directory.Path, "bin", "tool");
Directory.CreateDirectory(Path.Combine(directory.Path, "bin"));
File.WriteAllText(executable, string.Empty);

Assert.Equal(executable, new CommandResolver([]).Resolve(executable));
}

[Fact]
public void BareConfiguredNameStillResolvesOnPath()
{
using var directory = new TemporaryDirectory();
const string commandName = "wip-configured-bare-name-test";
var executable = Path.Combine(directory.Path, commandName);
File.WriteAllText(executable, string.Empty);

var originalPath = Environment.GetEnvironmentVariable("PATH");
try
{
Environment.SetEnvironmentVariable("PATH", directory.Path);

Assert.Equal(Path.GetFullPath(executable), new CommandResolver([]).Resolve(commandName));
}
finally
{
Environment.SetEnvironmentVariable("PATH", originalPath);
}
}

[Theory]
[InlineData("C:wslc.exe")]
[InlineData(@"C:tools\wslc.exe")]
[InlineData(@"\wslc.exe")]
[InlineData("/wslc.exe")]
public void DriveRelativeAndRootRelativeConfiguredCommandsAreRefusedOnWindows(string configured)
{
Assert.SkipWhen(!OperatingSystem.IsWindows(), "drive- and root-relative paths exist only on Windows");

// Every value resolves to a file, so only the guard can make this throw.
var resolver = new CommandResolver([], resolveExecutable: _ => Path.Combine(Path.GetTempPath(), "wslc.exe"));

var refused = Assert.Throws<CommandNotFoundException>(() => resolver.Resolve(configured));
Assert.Contains($"\"{configured}\"", refused.Message);
}

[Theory]
[InlineData("WSLC")]
[InlineData("compose command")]
[InlineData("Git")]
public void RefusalReadsCorrectlyForEveryLabel(string label)
{
var resolver = new CommandResolver([], label, resolveExecutable: _ => Path.Combine(Path.GetTempPath(), "x"));

var refused = Assert.Throws<CommandNotFoundException>(() => resolver.Resolve(Path.Combine("bin", "x")));

Assert.StartsWith($"{label} was configured as a relative path", refused.Message);
Assert.DoesNotContain("command command", refused.Message);
}

[Theory]
[InlineData(@"\\server\share\wslc.exe")]
[InlineData("//server/share/wslc.exe")]
[InlineData(@"\\?\C:\wslc.exe")]
[InlineData(@"\\.\C:\wslc.exe")]
public void NetworkAndDeviceConfiguredCommandsAreRefusedOnWindows(string configured)
{
Assert.SkipWhen(!OperatingSystem.IsWindows(), "UNC and device paths exist only on Windows");

// Every value resolves to a file, so only the guard can make this throw.
var resolver = new CommandResolver([], resolveExecutable: _ => Path.Combine(Path.GetTempPath(), "wslc.exe"));

var refused = Assert.Throws<CommandNotFoundException>(() => resolver.Resolve(configured));
Assert.Contains("network or device path", refused.Message);
Assert.Contains($"\"{configured}\"", refused.Message);
}

[Fact]
public void MappedDriveConfiguredCommandIsNotRefusedOnWindows()
{
Assert.SkipWhen(!OperatingSystem.IsWindows(), "drive letters exist only on Windows");

// Nothing resolves, so the outcome is not-found unless the guard refuses first.
var resolver = new CommandResolver([], resolveExecutable: _ => null);

var failure = Assert.Throws<CommandNotFoundException>(() => resolver.Resolve(@"Z:\tools\wslc.exe"));
Assert.StartsWith("WSLC was not found.", failure.Message);
Assert.DoesNotContain("refuses", failure.Message);
}

[Fact]
public void DoubleSlashConfiguredCommandIsUnchangedOnUnix()
{
Assert.SkipWhen(OperatingSystem.IsWindows(), "on Windows this is a UNC path");

var resolved = Path.Combine(Path.GetTempPath(), "wslc");
var resolver = new CommandResolver([], resolveExecutable: _ => resolved);

Assert.Equal(resolved, resolver.Resolve("//server/share/wslc"));
}

[Theory]
[InlineData(@"C:\", true)]
[InlineData("z:/", true)]
[InlineData(@"\\server\share\", false)]
[InlineData("//server/share/", false)]
[InlineData(@"\\?\C:\", false)]
[InlineData(@"\\.\C:\", false)]
[InlineData("C:", false)]
[InlineData("/", false)]
[InlineData("", false)]
[InlineData(null, false)]
public void OnlyADriveRootCountsAsLocal(string? root, bool expected)
{
Assert.Equal(expected, CommandResolver.IsDriveRoot(root));
}

[Theory]
[InlineData("./wslc")]
[InlineData("../wslc")]
public void InjectedResolverCannotRouteAroundTheGuard(string configured)
{
var resolver = new CommandResolver([], resolveExecutable: _ => Path.Combine(Path.GetTempPath(), "wslc"));

Assert.Throws<CommandNotFoundException>(() => resolver.Resolve(configured));
}

[Fact]
public void ResolveNormalizesRelativePathReturnedByExecutableResolver()
{
Expand All @@ -163,7 +292,9 @@ public void UnnormalizableCandidateReportsCommandNotFoundInsteadOfThrowingIoExce
{
var resolver = new CommandResolver([]);

Assert.Throws<CommandNotFoundException>(() => resolver.Resolve(Path.Combine("bin", "to\0ol")));
// Absolute, so this reaches normalization rather than the relative-path guard.
Assert.Throws<CommandNotFoundException>(() =>
resolver.Resolve(Path.Combine(Path.GetTempPath(), "bin", "to\0ol")));
}

private sealed class TemporaryDirectory : IDisposable
Expand Down
Loading