From 9376c6a3b47ecffc1f1acc880c931d784db3c18b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 22 May 2026 11:56:59 -0500 Subject: adjust FileSafety tests --- src/slskd/Common/FileSafety.cs | 23 ++++++++++++++++++++--- 1 file changed, 20 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 1e25ccd0..c024aa86 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -51,7 +51,19 @@ public static class FileSafety /// The combined path. /// Thrown if the root, list of segments, or one or more segments is null. /// Thrown if any of the specified segments is rooted, or if any contain path traversal characters. - public static string CombineSafely(string root, params string[] segments) + public static string CombineSafely(string root, params string[] segments) => CombineSafely(root, os: null, segments: segments); + + /// + /// An alternative to that disallows rooted segments in the second or + /// subsequent position, and disallows segments containing path traversal characters "." and "..". + /// + /// The root directory. + /// An optional operating system override, for testing. + /// The segments to append. + /// The combined path. + /// Thrown if the root, list of segments, or one or more segments is null. + /// Thrown if any of the specified segments is rooted, or if any contain path traversal characters. + public static string CombineSafely(string root, OSPlatform? os, params string[] segments) { // ensure no inputs are null. matches the behavior of Path.Combine() if (string.IsNullOrWhiteSpace(root)) @@ -59,6 +71,11 @@ public static class FileSafety throw new ArgumentNullException(nameof(root), $"Specified root directory is null or consists only of whitespace"); } + if (ContainsTraversalSegments(root)) + { + throw new ArgumentException("Specified root directory contains path traversal segments", nameof(root)); + } + if (segments is null || segments.Any(s => s is null)) { throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); @@ -69,9 +86,9 @@ 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 (IsPathAbsolute(segment)) + if (IsPathAbsolute(segment, os)) { - throw new ArgumentException($"Rooted paths are not permitted in segments: '{segment}'"); + throw new ArgumentException($"Absolute paths are not permitted in segments: '{segment}'"); } var parts = segment.Split(Path.DirectorySeparatorChar, '\\', '/'); -- cgit v1.2.3