aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorJP Dillingham <jp@dillingham.me>2026-05-13 18:15:16 -0500
committerJP Dillingham <jp@dillingham.me>2026-05-13 18:38:34 -0500
commit8336a3c3ebdfc65dd7d7419f27c195a4aa729856 (patch)
tree253c6dd1b62b8276d3fa880c92bd1c24db3c7a6e
parentfe1a6a3298116bc3980306cbb287f7137b378d1a (diff)
downloadslskd-8336a3c3ebdfc65dd7d7419f27c195a4aa729856.tar.gz
write our own logic for path relative/absolute
-rw-r--r--src/slskd/Common/FileSafety.cs48
-rw-r--r--src/slskd/Common/Validation/AbsolutePathAttribute.cs11
-rw-r--r--src/slskd/Common/Validation/RelativePathAttribute.cs9
-rw-r--r--tests/slskd.Tests.Unit/Common/FileSafetyTests.cs176
-rw-r--r--tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs8
5 files changed, 209 insertions, 43 deletions
diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs
index a3899397..f94b9c7b 100644
--- a/src/slskd/Common/FileSafety.cs
+++ b/src/slskd/Common/FileSafety.cs
@@ -68,7 +68,7 @@ public static class FileSafety
// if any segment is rooted (leading slash), Path.Combine drops everyting up to that segment
// and it becomes the new root. example: Path.Combine("/home/users/foo", "/etc") results in "/etc"
// not what we want!
- if (Path.IsPathRooted(segment))
+ if (IsPathAbsolute(segment))
{
throw new ArgumentException($"Rooted paths are not permitted in segments: '{segment}'");
}
@@ -100,4 +100,50 @@ public static class FileSafety
/// <param name="path">The path to check.</param>
/// <returns>True if one or more segments is present, false otherwise.</returns>
public static bool ContainsTraversalSegments(string path) => path?.Split('\\', '/')?.Any(s => s is "." or "..") ?? false;
+
+ /// <summary>
+ /// Returns a value indicating whether the specified <paramref name="path"/> is absolute (rooted), using
+ /// platform-independent rules that recognize both Unix and Windows absolute path formats.
+ /// </summary>
+ /// <remarks>
+ /// This is necessary because the base library is opaque and untestable in a cross-platform way, so we are
+ /// implementing the nuclear option and merging the logic for Windows and non-Windows.
+ /// </remarks>
+ /// <param name="path">The path to check.</param>
+ /// <returns>True if the path is absolute, false otherwise.</returns>
+ public static bool IsPathAbsolute(string path)
+ {
+ if (string.IsNullOrEmpty(path))
+ {
+ return false;
+ }
+
+ // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with /
+ // Windows root-relative paths and UNC paths start with \
+ if (path[0] is '/' or '\\')
+ {
+ return true;
+ }
+
+ // Windows drive-letter paths: X:\ or X:/
+ // X:foo is a "drive relative" path so it doesn't _technically_ count, but
+ // it's questionable and the user probably intended to root it anyway
+ // this matches the built in IsPathRooted but not IsPathFullyQualified
+ if (path.Length >= 2
+ && char.IsAsciiLetter(path[0])
+ && path[1] == ':')
+ {
+ return true;
+ }
+
+ return false;
+ }
+
+ /// <summary>
+ /// Returns a value indicating whether the specified <paramref name="path"/>, using
+ /// platform-independent rules that recognize both Unix and Windows absolute path formats.
+ /// </summary>
+ /// <param name="path">The path to check.</param>
+ /// <returns>True if the path is relative, false otherwise.</returns>
+ public static bool IsPathRelative(string path) => !IsPathAbsolute(path);
} \ No newline at end of file
diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
index 0eeb4a38..4c9f5e53 100644
--- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs
+++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs
@@ -33,8 +33,6 @@
namespace slskd.Validation
{
using System.ComponentModel.DataAnnotations;
- using System.IO;
- using System.Linq;
/// <summary>
/// Validates that the specified path is absolute.
@@ -47,14 +45,13 @@ namespace slskd.Validation
{
var path = value.ToString();
- if (!Path.IsPathRooted(path))
+ if (!FileSafety.IsPathAbsolute(path))
{
- return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path.");
+ return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path.");
}
- var segments = path.Split('/', '\\');
-
- if (segments.Any(s => s == ".." || s == "."))
+ // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here
+ if (FileSafety.ContainsTraversalSegments(path))
{
return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')");
}
diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs
index 824ff18d..e8865554 100644
--- a/src/slskd/Common/Validation/RelativePathAttribute.cs
+++ b/src/slskd/Common/Validation/RelativePathAttribute.cs
@@ -33,8 +33,6 @@
namespace slskd.Validation
{
using System.ComponentModel.DataAnnotations;
- using System.IO;
- using System.Linq;
/// <summary>
/// Validates that the specified path is relative.
@@ -47,14 +45,13 @@ namespace slskd.Validation
{
var path = value.ToString();
- if (Path.IsPathRooted(path))
+ if (!FileSafety.IsPathRelative(path))
{
return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path.");
}
- var segments = path.Split('/', '\\');
-
- if (segments.Any(s => s == ".." || s == "."))
+ // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here
+ if (FileSafety.ContainsTraversalSegments(path))
{
return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')");
}
diff --git a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs
index ab4df5c4..a37e9e74 100644
--- a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs
+++ b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs
@@ -258,29 +258,17 @@ public class FileSafetyTests
public class CombineSafely_Throws_ForRootedSegment
{
- // Paths that are rooted on all platforms
[Theory]
- [InlineData("/Music")] // Unix absolute / Windows root-relative via forward slash
- [InlineData("//server/share")] // Unix-style UNC
- public void Throws_ArgumentException(string segment)
- {
- var ex = Assert.Throws<ArgumentException>(() => FileSafety.CombineSafely(Base, segment));
- Assert.Contains("Rooted", ex.Message);
- }
-
- // Paths that are only rooted on Windows; on Linux/macOS backslash is a valid filename character
- // and "C:" is not a special prefix, so IsPathRooted returns false and they would not be rejected.
- [Theory]
- [InlineData("C:\\Music")] // Windows drive-letter absolute, backslash
- [InlineData("C:/Music")] // Windows drive-letter absolute, forward slash
+ [InlineData("/Music")] // Unix absolute / Windows root-relative, forward slash
+ [InlineData("//server/share")] // Unix-style UNC
+ [InlineData("C:\\Music")] // Windows drive-letter, backslash
+ [InlineData("C:/Music")] // Windows drive-letter, forward slash
[InlineData("D:\\path")] // alternate drive letter
- [InlineData("C:relative")] // Windows drive-relative; IsPathRooted returns true
+ [InlineData("C:relative")] // Windows drive-relative
[InlineData("\\Music")] // Windows root-relative, backslash
[InlineData("\\\\server\\share")] // Windows UNC
- public void Throws_ArgumentException_WindowsOnly(string segment)
+ public void Throws_ArgumentException(string segment)
{
- if (!OperatingSystem.IsWindows()) { return; }
-
var ex = Assert.Throws<ArgumentException>(() => FileSafety.CombineSafely(Base, segment));
Assert.Contains("Rooted", ex.Message);
}
@@ -294,10 +282,8 @@ public class FileSafetyTests
}
[Fact]
- public void Throws_WhenLaterSegmentIsRooted_WindowsOnly()
+ public void Throws_WhenLaterSegmentIsRooted_Windows()
{
- if (!OperatingSystem.IsWindows()) { return; }
-
var ex = Assert.Throws<ArgumentException>(() =>
FileSafety.CombineSafely(Base, "valid", "C:\\escape"));
Assert.Contains("Rooted", ex.Message);
@@ -312,10 +298,8 @@ public class FileSafetyTests
}
[Fact]
- public void Throws_WhenLastSegmentIsRooted_WindowsOnly()
+ public void Throws_WhenLastSegmentIsRooted_Windows()
{
- if (!OperatingSystem.IsWindows()) { return; }
-
var ex = Assert.Throws<ArgumentException>(() =>
FileSafety.CombineSafely(Base, "sub", "dir", "C:\\escape"));
Assert.Contains("Rooted", ex.Message);
@@ -371,6 +355,150 @@ public class FileSafetyTests
}
}
+ public class IsPathAbsolute_ReturnsTrue
+ {
+ // Unix/Linux/macOS absolute paths
+ [Theory]
+ [InlineData("/")] // filesystem root
+ [InlineData("/home")] // single component
+ [InlineData("/home/user/Music")] // deep path
+ [InlineData("/home/user/My Music")] // spaces in component
+ [InlineData("/etc/hosts")] // config file
+ [InlineData("/tmp")] // temp directory
+ [InlineData("/home/Ünïcödé")] // latin extended
+ [InlineData("/home/пользователь/Музыка")] // Cyrillic
+ [InlineData("/home/用户/音乐")] // Chinese
+ [InlineData("/home/ユーザー/音楽")] // Japanese
+ [InlineData("/home/사용자/음악")] // Korean
+ public void Unix_Paths(string path)
+ {
+ Assert.True(FileSafety.IsPathAbsolute(path));
+ }
+
+ // Unix-style UNC paths (// prefix)
+ [Theory]
+ [InlineData("//server/share")]
+ [InlineData("//server/share/folder")]
+ [InlineData("//192.168.1.1/share")]
+ [InlineData("//server/Ünïcödé")]
+ [InlineData("//server/share/пользователь")]
+ public void Unix_UNCPaths(string path)
+ {
+ Assert.True(FileSafety.IsPathAbsolute(path));
+ }
+
+ // Windows root-relative paths (rooted to the current drive, no drive letter)
+ [Theory]
+ [InlineData("\\Music")]
+ [InlineData("\\Music\\Artist\\Album")]
+ [InlineData("/Music")]
+ [InlineData("/Music/Artist/Album")]
+ [InlineData("\\Ünïcödé")]
+ [InlineData("\\пользователь\\Музыка")]
+ public void Windows_RootRelativePaths(string path)
+ {
+ Assert.True(FileSafety.IsPathAbsolute(path));
+ }
+
+ // Windows UNC paths (\\ prefix)
+ [Theory]
+ [InlineData("\\\\server\\share")]
+ [InlineData("\\\\server\\share\\folder")]
+ [InlineData("\\\\server\\share\\My Music")]
+ [InlineData("\\\\192.168.1.1\\share")]
+ [InlineData("\\\\server\\Ünïcödé")]
+ [InlineData("\\\\server\\share\\пользователь")]
+ [InlineData("\\\\server\\share\\用户\\音乐")]
+ public void Windows_UNCPaths(string path)
+ {
+ Assert.True(FileSafety.IsPathAbsolute(path));
+ }
+
+ // Windows drive-letter paths — with or without a separator after the colon
+ [Theory]
+ [InlineData("C:\\")] // drive root, backslash
+ [InlineData("C:/")] // drive root, forward slash
+ [InlineData("C:\\Music")] // basic, backslash
+ [InlineData("C:/Music")] // basic, forward slash
+ [InlineData("C:\\Music\\Artist\\Album")] // deep, backslash
+ [InlineData("D:\\path")] // different drive letter
+ [InlineData("Z:\\downloads")] // drive letter Z
+ [InlineData("C:")] // bare drive letter
+ [InlineData("C:Music")] // drive-relative, no separator
+ [InlineData("D:path")] // different drive letter, no separator
+ [InlineData("C:\\Users\\Ünïcödé\\Music")] // latin extended
+ [InlineData("C:\\Users\\пользователь\\Музыка")] // Cyrillic
+ [InlineData("C:\\Users\\用户\\音乐")] // Chinese
+ public void Windows_DriveLetterPaths(string path)
+ {
+ Assert.True(FileSafety.IsPathAbsolute(path));
+ }
+ }
+
+ public class IsPathAbsolute_ReturnsFalse
+ {
+ [Theory]
+ [InlineData(null)] // null
+ [InlineData("")] // empty string
+ [InlineData("subdir")] // simple name
+ [InlineData("sub/dir")] // forward slash
+ [InlineData("sub\\dir")] // backslash
+ [InlineData("Artist\\Album")] // multi-level backslash
+ [InlineData("Artist/Album/Song")] // deep forward slash
+ [InlineData("music.flac")] // file name with extension
+ [InlineData("My Music")] // spaces
+ [InlineData(".hidden")] // dotfile
+ [InlineData("..hidden")] // dot-prefixed name
+ [InlineData("...dir")] // three dots — relative, not traversal
+ [InlineData("../escape")] // traversal — still relative
+ [InlineData("./dir")] // current-dir segment — still relative
+ [InlineData("..")] // bare double-dot
+ [InlineData(".")] // bare single-dot
+ [InlineData("Ünïcödé")] // unicode, no root
+ [InlineData("пользователь/Музыка")] // unicode with separator, no root
+ public void Relative_Paths(string path)
+ {
+ Assert.False(FileSafety.IsPathAbsolute(path));
+ }
+ }
+
+ public class IsPathRelative_ReturnsTrue
+ {
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData("subdir")]
+ [InlineData("sub/dir")]
+ [InlineData("sub\\dir")]
+ [InlineData("music.flac")]
+ [InlineData(".hidden")]
+ [InlineData("../escape")]
+ public void Relative_Paths(string path)
+ {
+ Assert.True(FileSafety.IsPathRelative(path));
+ }
+
+ }
+
+ public class IsPathRelative_ReturnsFalse
+ {
+ [Theory]
+ [InlineData("/home/user")]
+ [InlineData("//server/share")]
+ [InlineData("\\Music")]
+ [InlineData("\\\\server\\share")]
+ [InlineData("C:\\Music")]
+ [InlineData("C:/Music")]
+ [InlineData("C:\\")]
+ [InlineData("C:")]
+ [InlineData("C:Music")]
+ [InlineData("D:path")]
+ public void Absolute_Paths(string path)
+ {
+ Assert.False(FileSafety.IsPathRelative(path));
+ }
+ }
+
public class CombineSafely_NullAndEdgeCases
{
[Fact]
diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs
index 03729eab..53e25ac6 100644
--- a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs
+++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs
@@ -41,7 +41,7 @@ public class AbsolutePathAttributeTests
[InlineData("C:\\Program Files\\App")] // spaces, typical Windows path
[InlineData("D:\\path")] // different drive letter
[InlineData("Z:\\downloads")] // drive letter Z
- [InlineData("C:")] // bare drive — IsPathRooted returns true
+ [InlineData("C:")] // bare drive
[InlineData("C:\\Users\\Ünïcödé\\Music")] // latin extended
[InlineData("C:\\Users\\пользователь\\Музыка")] // Cyrillic
[InlineData("C:\\Users\\用户\\音乐")] // Chinese
@@ -49,7 +49,7 @@ public class AbsolutePathAttributeTests
[InlineData("C:\\Users\\사용자\\음악")] // Korean
[InlineData("C:\\Users\\مستخدم\\موسيقى")] // Arabic
[InlineData("C:\\Users\\χρήστης\\μουσική")] // Greek
- [InlineData("C:Music")] // drive-relative (no separator); IsPathRooted returns true
+ [InlineData("C:Music")] // drive-relative (no separator)
public void Windows_DriveLetterPaths_Pass(string value)
{
var (isValid, _) = Validate(value);
@@ -204,8 +204,6 @@ public class AbsolutePathAttributeTests
}
}
- // Relative paths that have no empty segments and no traversal reach the
- // final IsPathRooted check and fail there.
public class Relative_Fails
{
[Theory]
@@ -225,7 +223,7 @@ public class AbsolutePathAttributeTests
{
var (isValid, errorMessage) = Validate(value);
Assert.False(isValid);
- Assert.Equal("The Field field must specify an absolute file path.", errorMessage);
+ Assert.Equal("The Field field must be an absolute file path.", errorMessage);
}
}
}