diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-06-07 14:45:04 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-06-07 14:45:04 -0500 |
| commit | b747b68ba0ba777be578e73bd1328fbde940e436 (patch) | |
| tree | 160d23aeb8707dc04f81bb52e81913c1b77bb2a4 | |
| parent | e06999e5eec1616d93b34ffbab0eade617d1aaf6 (diff) | |
| parent | 2d069bbf1f71f38e1286e27d45c24b478feb11ac (diff) | |
| download | slskd-b747b68ba0ba777be578e73bd1328fbde940e436.tar.gz | |
Merge branch 'master' into dependabot/npm_and_yarn/src/web/launch-editor-2.14.1
40 files changed, 2216 insertions, 971 deletions
diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 1063e7f5..475ac65a 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -39,7 +39,7 @@ # cidr: 0.0.0.0/0,::/0 # permissions: # file: -# mode: ~ # not for Windows, chmod syntax, e.g. 644, 777. can't escalate beyond umask +# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # directories: # incomplete: ~ # downloads: ~ @@ -78,6 +78,11 @@ # attempts: 3 # delay: 5000 # initial time between retries, in milliseconds # max_delay: 60000 # maximum time between retries, in milliseconds +# destination: +# subdirectory: ${SOURCE_DIRECTORY} # options: SOURCE_USERNAME, SOURCE_PATH, SOURCE_DIRECTORY, BATCH_ID, BATCH_EXTERNAL_ID, SEARCH_ID, SEARCH_TEXT +# exists: rename # 'overwrite' or 'rename' +# permissions: +# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # groups: # default: # upload: diff --git a/docs/config.md b/docs/config.md index 8848060a..c8a8fca2 100644 --- a/docs/config.md +++ b/docs/config.md @@ -117,21 +117,11 @@ Users wishing to create files with different permissions can change the umask va When running within a docker container the environment variable `SLSKD_UMASK` can be used to change the umask for the process within the container, and this will in turn change the resulting file mode on a mounted volume. -Users can optionally configure alternative permissions for files by setting the file permission mode option. It's not possible to supersede the configured umask value; setting a mode of 777, for example, will have no effect with a umask of 022. - -These options have no effect on Windows. +This option has no effect on Windows. | Command-Line | Environment Variable | Description | | ------------------------ | -----------------------------| -------------------------------------------------------------------------------- | | n/a | `SLSKD_UMASK` | When running within the slskd Docker container, the umask for the process | -| `--file-permission-mode` | `SLSKD_FILE_PERMISSION_MODE` | The permissions to apply to newly created files (chmod syntax, non-Windows only) | - -#### **YAML** -```yaml -permissions: - file: - mode: 644 # not for Windows, chmod syntax, e.g. 644, 777. can't escalate beyond umask -``` # Application Directory Configuration @@ -377,6 +367,25 @@ transfers: max_delay: 60000 # maximum time between retries, in milliseconds ``` +## Destination + +### Permissions + +On [Unix-like](https://en.wikipedia.org/wiki/Unix-like) operating systems, downloaded files will be created according to the [umask](https://en.wikipedia.org/wiki/Umask) of the process (see [Permissions](#permissions) for more info). + +Users can optionally configure alternative permissions by setting the permission mode option which, when enabled, effectively causes slskd to `chmod` files and directories with the configured mode immediately after creation. + +This option has no effect on Windows. + +#### **YAML** +```yaml +transfers: + download: + destination: + permissions: + mode: 644 # chmod syntax, e.g. 644, 777. has no effect on Windows +``` + ## Global Upload Limits Global upload limits define the number of queued, daily, and weekly uploads on a _per user_ basis. These limits behave as defaults and are applied if limits for a user's group have not been set. diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index e3d212f7..2b9a1f93 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -551,7 +551,7 @@ namespace slskd { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); - if (OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive) + if (System.OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive) { return; } diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 5ff3e519..95721163 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -382,21 +382,6 @@ namespace slskd .Deserialize<T>(str); /// <summary> - /// Converts a fully qualified remote filename to a local filename based in the provided - /// <paramref name="baseDirectory"/>, swapping directory characters for those specific to the local OS, removing any - /// characters that are invalid for the local OS, and making the path relative to the remote store (including the - /// filename and the parent folder). - /// </summary> - /// <param name="remoteFilename">The fully qualified remote filename to convert.</param> - /// <param name="baseDirectory">The base directory for the local filename.</param> - /// <returns>The converted filename.</returns> - [Obsolete("Find something more intelligent to do instead of this")] - public static string ToLocalFilename(this string remoteFilename, string baseDirectory) - { - return FileSafety.CombineSafely(baseDirectory, remoteFilename.ToLocalRelativeFilename()); - } - - /// <summary> /// Converts the given path to the normalized format (normalizes path separators to backslashes). /// </summary> /// <remarks> @@ -410,16 +395,6 @@ namespace slskd } /// <summary> - /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). - /// </summary> - /// <param name="path">The path to convert.</param> - /// <returns>The converted path.</returns> - public static string LocalizePath(this string path) - { - return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar); - } - - /// <summary> /// <see cref="Path.GetDirectoryName(string)"/>, but for paths normalized to use backslashes. /// </summary> /// <param name="path"></param> @@ -440,55 +415,6 @@ namespace slskd } /// <summary> - /// Converts a fully qualified remote filename to a local filename, swapping directory characters for those specific - /// to the local OS, removing any characters that are invalid for the local OS, and making the path relative to the - /// remote store (including the filename and the parent folder). - /// </summary> - /// <param name="remoteFilename">The fully qualified remote filename to convert.</param> - /// <returns>The converted filename.</returns> - [Obsolete("Find something more intelligent to do instead of this")] - public static string ToLocalRelativeFilename(this string remoteFilename) - { - if (string.IsNullOrWhiteSpace(remoteFilename)) - { - throw new ArgumentException($"Invalid remote filename; expected a non-whitespace value, received '{remoteFilename}'", nameof(remoteFilename)); - } - - // normalize path separators - var localizedRemoteFilename = remoteFilename.LocalizePath(); - - var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar); - - if (parts.Length == 1) - { - return parts.First().ReplaceInvalidFileNameCharacters(); - } - - var file = parts.Last().ReplaceInvalidFileNameCharacters(); - var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters(); - - return FileSafety.CombineSafely(directory, file); - } - - /// <summary> - /// Replaces any occurrence of an invalid filename character with the specified <see paramref="replacement"/>. - /// </summary> - /// <param name="path">The path to sanitize.</param> - /// <param name="replacement">The character with which to replace invalid characters.</param> - /// <returns>The sanitized path.</returns> - public static string ReplaceInvalidFileNameCharacters(this string path, char replacement = '_') - { - var sanitized = path; - - foreach (var c in Path.GetInvalidFileNameChars()) - { - sanitized = sanitized.Replace(c, replacement); - } - - return sanitized; - } - - /// <summary> /// Converts a ModelStateDictionary into a human-readable format. /// </summary> /// <param name="dictionary">The ModelStateDictionary to format.</param> diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index dc565806..d235a87c 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -66,24 +66,14 @@ namespace slskd return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty); } - public static OSPlatform OSPlatform() + public static OperatingSystem OperatingSystem() { - if (OperatingSystem.IsWindows()) + if (System.OperatingSystem.IsWindows()) { - return System.Runtime.InteropServices.OSPlatform.Windows; + return slskd.OperatingSystem.Windows; } - if (OperatingSystem.IsMacOS()) - { - return System.Runtime.InteropServices.OSPlatform.OSX; - } - - if (OperatingSystem.IsFreeBSD()) - { - return System.Runtime.InteropServices.OSPlatform.FreeBSD; - } - - return System.Runtime.InteropServices.OSPlatform.Linux; + return slskd.OperatingSystem.Linux; } } }
\ No newline at end of file diff --git a/src/slskd/Common/Dumper.cs b/src/slskd/Common/Dumper.cs index f4367e61..27304873 100644 --- a/src/slskd/Common/Dumper.cs +++ b/src/slskd/Common/Dumper.cs @@ -84,7 +84,7 @@ namespace slskd await Download(url, BinFile); - if (!OperatingSystem.IsWindows()) + if (!System.OperatingSystem.IsWindows()) { await ExecAsync("/bin/sh", $"-c \"chmod +x {BinFile}\""); } @@ -139,15 +139,15 @@ namespace slskd string os = default; // seems like there should be a way to just retrieve this, but there is not as of .NET 6 - if (OperatingSystem.IsLinux()) + if (System.OperatingSystem.IsLinux()) { os = "linux"; } - else if (OperatingSystem.IsWindows()) + else if (System.OperatingSystem.IsWindows()) { os = "win"; } - else if (OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD()) + else if (System.OperatingSystem.IsMacOS() || System.OperatingSystem.IsFreeBSD()) { os = "osx"; } diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 5a5d964e..6a6dea22 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -35,7 +35,6 @@ namespace slskd; using System; using System.IO; using System.Linq; -using System.Runtime.InteropServices; using System.Text.RegularExpressions; /// <summary> @@ -85,7 +84,7 @@ public static class FileSafety /// <returns>The combined path.</returns> /// <exception cref="ArgumentNullException">Thrown if the root, list of segments, or one or more segments is null.</exception> /// <exception cref="ArgumentException">Thrown if any of the specified segments is rooted, or if any contain path traversal characters.</exception> - public static string CombineSafely(string root, OSPlatform? os, params string[] segments) + public static string CombineSafely(string root, OperatingSystem? os, params string[] segments) { // ensure no inputs are null. matches the behavior of Path.Combine() if (string.IsNullOrWhiteSpace(root)) @@ -103,13 +102,21 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } - var isWindows = os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows(); + root = root.TrimEnd('/', '\\'); + + if (segments.Length == 0) + { + return root; + } + + var isWindows = os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows(); + var sep = isWindows ? '\\' : '/'; foreach (var segment in segments) { - // 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! + // disallow any segments that: + // windows: are drive letter (C:\) or UNC path (\\) + // linux: begin with a forward slash (any number, covering both local and UNC paths) if (IsPathAbsolute(segment, os)) { throw new ArgumentException($"Absolute paths are not permitted in segments: '{segment}'"); @@ -134,17 +141,26 @@ public static class FileSafety // ensure the segments we're combining don't contain traversal segments "." or ".." // untrusted input could use this to "break out" of the root directory and access sensitive areas + // this covers cases where the entire segment is . or .., or foo\..\bar, or \.. or ..\ or \..\ if (parts.Any(s => s is "." or "..")) { throw new ArgumentException($"Path traversal is not permitted in segments: '{segment}'"); } } - var combined = Path.Combine(root, Path.Combine(segments)); + segments = [.. segments + .Where(s => !string.IsNullOrEmpty(s))]; + + var combined = string.Join(sep, [root, .. segments]); + + if (combined.TrimEnd('/', '\\') == root.TrimEnd('/', '\\')) + { + return combined; + } // this is a backstop to catch any condition we haven't thought of; it makes sure that the resulting // path is actually rooted in the root we provided; if not the input was successful in traversal - if (!Path.GetFullPath(combined).StartsWith(Path.GetFullPath(root))) + if (!combined.StartsWith($"{root}/") && !combined.StartsWith($"{root}\\")) { throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } @@ -170,14 +186,14 @@ public static class FileSafety /// <param name="path">The path to check.</param> /// <param name="os">An optional operating system override, for testing.</param> /// <returns>True if the path is absolute, false otherwise.</returns> - public static bool IsPathAbsolute(string path, OSPlatform? os = null) + public static bool IsPathAbsolute(string path, OperatingSystem? os = null) { if (string.IsNullOrEmpty(path)) { return false; } - if (os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows()) + if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows()) { // Windows drive-letter path: X:\ or X:/ // X:foo is relative on windows @@ -214,7 +230,7 @@ public static class FileSafety /// <param name="path">The path to check.</param> /// <param name="os">An optional operating system override, for testing.</param> /// <returns>True if the path is relative, false otherwise.</returns> - public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); + public static bool IsPathRelative(string path, OperatingSystem? os = null) => !IsPathAbsolute(path, os); /// <summary> /// Returns the filename from the specified <paramref name="path"/>, properly @@ -224,7 +240,7 @@ public static class FileSafety /// <param name="sanitize">An optional value indicating that invalid characters should not be replaced.</param> /// <param name="os">An optional operating system override, for testing.</param> /// <returns>The extracted filename.</returns> - public static string GetFileNameSafely(string path, bool sanitize = true, OSPlatform? os = null) + public static string GetFileNameSafely(string path, bool sanitize = true, OperatingSystem? os = null) { if (path is null or "" || path.EndsWith('/') || path.EndsWith('\\')) { @@ -256,7 +272,7 @@ public static class FileSafety /// <param name="os">An optional operating system override, for testing.</param> /// <returns>The directory name.</returns> /// <exception cref="ArgumentNullException">Thrown if the specified path is null.</exception> - public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OSPlatform? os = null) + public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OperatingSystem? os = null) { if (path is null or "") { @@ -271,8 +287,8 @@ public static class FileSafety var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); - os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; var local = LocalizePath(path, os) .TrimEnd('/', '\\'); // treat file-less paths the same as files @@ -322,15 +338,15 @@ public static class FileSafety /// <param name="path">The path to convert.</param> /// <param name="os">An optional operating system override, for testing.</param> /// <returns>The converted path.</returns> - public static string LocalizePath(string path, OSPlatform? os = null) + public static string LocalizePath(string path, OperatingSystem? os = null) { if (path is null) { return null; } - os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; return path.Replace('\\', sep).Replace('/', sep); } @@ -344,7 +360,7 @@ public static class FileSafety /// <param name="replacement">The character to substitute for invalid characters.</param> /// <param name="os">An optional operating system override, for testing.</param> /// <returns>The sanitized filename.</returns> - public static string SanitizeFilename(string filename, char replacement = '_', OSPlatform? os = null) + public static string SanitizeFilename(string filename, char replacement = '_', OperatingSystem? os = null) { if (filename is null) { @@ -356,9 +372,9 @@ public static class FileSafety throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); } - os ??= Compute.OSPlatform(); + os ??= Compute.OperatingSystem(); - var characters = os.Value == OSPlatform.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; + var characters = os.Value == OperatingSystem.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; if (characters.Contains(replacement)) { @@ -388,7 +404,7 @@ public static class FileSafety /// <param name="replacement">The character to substitute for invalid characters.</param> /// <param name="os">An optional operating system override, for testing.</param> /// <returns>The sanitized path segment.</returns> - public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) + public static string SanitizePathSegment(string segment, char replacement = '_', OperatingSystem? os = null) { var sanitized = SanitizeFilename(segment, replacement, os); @@ -413,49 +429,36 @@ public static class FileSafety /// <summary> /// Sanitizes the specified <paramref name="path"/> to make it suitable and safe on the local operating system - /// by converting to the correct slashes, dropping a root (if present), replacing any invalid characters with - /// the specified <paramref name="replacement"/>, and by dropping any path traversal segments. + /// by converting to the correct slashes, replacing any invalid characters with the specified + /// <paramref name="replacement"/>, and by dropping any path traversal segments. /// </summary> /// <param name="path">The path.</param> /// <param name="replacement">The character to substitute for invalid characters.</param> - /// <param name="retainRoot">An optional value indicating whether to keep the path's root, if present.</param> /// <param name="os">An optional operating system override, for testing.</param> /// <returns>The sanitized path.</returns> - public static string SanitizePath(string path, char replacement = '_', bool retainRoot = false, OSPlatform? os = null) + public static string SanitizePath(string path, char replacement = '_', OperatingSystem? os = null) { if (path is null) { return null; } - var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); - - os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; // flip slashes the correct way path = LocalizePath(path, os); - if (!retainRoot) - { - // strip C:\ or //server, if present (regardless of slash variant, etc) - path = StripPathRoot(path, os); - } - - // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings + // for each segment, drop nulls (created by double slashes), sanitize, replace traversal strings, + // and drop any segments that sanitization reduced to empty (e.g. a single invalid char with '.' replacement) var segments = path .Split('/', '\\') .Where(s => s is not "") - .Select(s => SanitizePathSegment(s, replacement, os)); + .Select(s => SanitizePathSegment(s, replacement, os)) + .Where(s => s is not ""); var newPath = string.Join(sep, segments); - if (retainRoot) - { - // leading slashes are stripped of leading slashes by Split() so we must add them back - return new string(sep, leadingSlashCount) + newPath; - } - return newPath; } @@ -467,7 +470,7 @@ public static class FileSafety /// <param name="path">The path to strip.</param> /// <param name="os">An optional operating system override, for testing.</param> /// <returns>The path with the root stripped, if one was present.</returns> - public static string StripPathRoot(string path, OSPlatform? os = null) + public static string StripPathRoot(string path, OperatingSystem? os = null) { if (path is null) { diff --git a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs index a7e7e0dc..760f7ba9 100644 --- a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs +++ b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs @@ -36,7 +36,7 @@ using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Formatters; -using Microsoft.OpenApi.Models; +using Microsoft.OpenApi; using Swashbuckle.AspNetCore.SwaggerGen; /// <summary> diff --git a/src/slskd/Common/OperatingSystem.cs b/src/slskd/Common/OperatingSystem.cs new file mode 100644 index 00000000..0c3dae2c --- /dev/null +++ b/src/slskd/Common/OperatingSystem.cs @@ -0,0 +1,43 @@ +// <copyright file="OperatingSystem.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd; + +public enum OperatingSystem +{ + None = 0, + Linux = 1, + Windows = 2, + Current = 3, + Any = 4, + All = 5, +}
\ No newline at end of file diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index eb1c9069..217a4eea 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -33,23 +33,24 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.Runtime.InteropServices; /// <summary> /// Validates that the specified path is absolute. /// </summary> public class AbsolutePathAttribute : ValidationAttribute { - public AbsolutePathAttribute() + public AbsolutePathAttribute(OperatingSystem os = OperatingSystem.Current) { - } + if (os != OperatingSystem.Current && os != OperatingSystem.Any && os != OperatingSystem.All) + { + throw new System.ArgumentException("OperatingSystem argument for AbsolutePathAttribute must be one of: Current, Any, All", nameof(os)); + } - public AbsolutePathAttribute(OSPlatform? os = null) - { OS = os; } - public OSPlatform? OS { get; } + public OperatingSystem OS { get; } + private OperatingSystem? Injected { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { @@ -57,9 +58,20 @@ namespace slskd.Validation { var path = value.ToString(); - if (!FileSafety.IsPathAbsolute(path, os: OS)) + if (OS == OperatingSystem.Current) + { + if (!FileSafety.IsPathAbsolute(path, os: Injected ?? Compute.OperatingSystem())) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on the current operating system."); + } + + return ValidationResult.Success; + } + + // OS == OperatingSystem.All or .Any + if (!FileSafety.IsPathAbsolute(path, os: OperatingSystem.Linux) || !FileSafety.IsPathAbsolute(path, os: OperatingSystem.Windows)) { - return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on all operating systems."); } } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index f465ba98..ea2b627b 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -33,36 +33,50 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.Runtime.InteropServices; /// <summary> /// Validates that the specified path is relative. /// </summary> public class RelativePathAttribute : ValidationAttribute { - public RelativePathAttribute() + public RelativePathAttribute(OperatingSystem os = OperatingSystem.Current) { - } + if (os != OperatingSystem.Current && os != OperatingSystem.Any && os != OperatingSystem.All) + { + throw new System.ArgumentException("OperatingSystem argument for RelativePathAttribute must be one of: Current, Any, All", nameof(os)); + } - public RelativePathAttribute(OSPlatform? os = null) - { OS = os; } - public OSPlatform? OS { get; } + public OperatingSystem OS { get; } + + private OperatingSystem? Injected { get; } + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && value is string str && !string.IsNullOrEmpty(str)) { var path = value.ToString(); - if (!FileSafety.IsPathRelative(path, os: OS)) + if (OS == OperatingSystem.Current) + { + if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem())) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system."); + } + + return ValidationResult.Success; + } + + // OS == OperatingSystem.All or .Any; + if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows)) { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); } } return ValidationResult.Success; } } -} +}
\ No newline at end of file diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index bac86ea2..f35a56df 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -235,11 +235,8 @@ namespace slskd [Validate] public RelayOptions Relay { get; init; } = new RelayOptions(); - /// <summary> - /// Gets permission options. - /// </summary> - [Validate] - public PermissionsOptions Permissions { get; init; } = new PermissionsOptions(); + [Obsolete("temporary sentinel to warn users about breaking change. use Transfers.Download.Destination.Permissions instead.")] + public object Permissions { get; init; } = null; /// <summary> /// Gets directory options. @@ -364,6 +361,11 @@ namespace slskd { results.Add(new ValidationResult("The 'integration' key has been renamed to 'integrations'. Add an 's' to the end of the key to remove this error (no other changes were made)")); } + + if (Permissions is not null) + { + results.Add(new ValidationResult("The 'permissions' keys have been moved under a new 'destination' key under transfers -> download, and the behavior has changed. See https://github.com/slskd/slskd/pull/1756 for details")); + } #pragma warning restore CS0618 // Type or member is obsolete return results; @@ -765,7 +767,7 @@ namespace slskd [Argument(default, "incomplete")] [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] - [AbsolutePath] + [AbsolutePath(OperatingSystem.Current)] [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] @@ -777,7 +779,7 @@ namespace slskd [Argument('o', "downloads")] [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] - [AbsolutePath] + [AbsolutePath(OperatingSystem.Current)] [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] @@ -832,22 +834,22 @@ namespace slskd var directories = Directories ?? Enumerable.Empty<string>(); - bool IsBlankPath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])$"); + bool IsBlankPath(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])$"); directories?.Where(share => IsBlankPath(share)).ToList() .ForEach(blank => results.Add(new ValidationResult($"Share {blank} does not specify a path"))); - bool IsRootMount(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])/$"); + bool IsRootMount(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])/$"); directories?.Where(share => IsRootMount(share)).ToList() .ForEach(blank => results.Add(new ValidationResult($"Share {blank} specifies a root mount, which is not supported."))); // starts with '/', 'X:', or '\\' - bool IsAbsolutePath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); + bool IsAbsolutePath(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); directories?.Where(share => !IsAbsolutePath(share)).ToList() .ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported."))); // contains /./ or /../ or \.\ or \..\ or ..\ or ../ or \.. or /.. // which is resolved by some OS and will cause weird, unintended side effects - bool ContainsTraversalSegments(string share) => Regex.IsMatch(share.LocalizePath(), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$"); + bool ContainsTraversalSegments(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$"); directories?.Where(share => ContainsTraversalSegments(share)).ToList() .ForEach(badPath => results.Add(new ValidationResult($"Share {badPath} contains an unsafe path traversal segment."))); @@ -1029,6 +1031,12 @@ namespace slskd public RetryOptions Retry { get; init; } = new RetryOptions(); /// <summary> + /// Gets download destination options. + /// </summary> + [Validate] + public DestinationOptions Destination { get; init; } = new DestinationOptions(); + + /// <summary> /// Download retry options. /// </summary> public class RetryOptions @@ -1057,6 +1065,63 @@ namespace slskd [Enum(typeof(RetryPartialStrategy))] public string Partial { get; init; } = RetryPartialStrategy.Resume.ToString().ToLowerInvariant(); } + + /// <summary> + /// Download destination options. + /// </summary> + public class DestinationOptions + { + /// <summary> + /// Gets the destination subdirectory for the files in the batch. + /// </summary> + [RelativePath(OperatingSystem.All)] + [NonTraversingPath] + [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] + public string Subdirectory { get; init; } = "${SOURCE_DIRECTORY}"; + + /// <summary> + /// Gets the strategy for handling existing files on disk. + /// </summary> + [Enum(typeof(DestinationExistsStrategy))] + public string Exists { get; init; } = DestinationExistsStrategy.Rename.ToString().ToLowerInvariant(); + + /// <summary> + /// Gets the permissions to apply to downloaded files and directories. + /// </summary> + [Validate] + public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions(); + + /// <summary> + /// Download destination permission options. + /// </summary> + public class DestinationPermissionsOptions : IValidatableObject + { + /// <summary> + /// Gets the permissions to apply to newly created files. + /// </summary> + /// <remarks> + /// Applicable to non-Windows operating systems, only. + /// </remarks> + public string Mode { get; init; } + + public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) + { + var results = new List<ValidationResult>(); + + if (!string.IsNullOrEmpty(Mode)) + { + var regEx = new Regex("^[0-7]{3,4}$", RegexOptions.Compiled); + + if (!regEx.IsMatch(Mode)) + { + results.Add(new ValidationResult($"Field {nameof(Mode)} is invalid. Specify a three- or four-character string consisting of only 0-7 (chmod syntax, [0]000-[7]777, inclusive)")); + } + } + + return results; + } + } + } } /// <summary> @@ -2020,7 +2085,7 @@ namespace slskd [Argument(default, "http-socket")] [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] - [AbsolutePath] + [AbsolutePath(OperatingSystem.Current)] [NonTraversingPath] [RequiresRestart] public string Socket { get; init; } diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 3b304d99..62d17f20 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -389,13 +389,15 @@ namespace slskd.Files var path = Path.GetDirectoryName(filename); - UnixFileMode? unixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Permissions.File.Mode?.ToUnixFileMode(); + UnixFileMode? unixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode?.ToUnixFileMode(); if (!Directory.Exists(path)) { if (!OperatingSystem.IsWindows() && unixCreateMode.HasValue) { - Directory.CreateDirectory(path, unixCreateMode.Value.WithExecuteFlagsForEachReadFlag()); + var mode = unixCreateMode.Value.WithExecuteFlagsForEachReadFlag(); + Directory.CreateDirectory(path, unixCreateMode: mode); + File.SetUnixFileMode(path, mode: mode); } else { @@ -469,13 +471,15 @@ namespace slskd.Files throw new FileNotFoundException($"The specified source file does not exist", fileName: sourceFilename); } - UnixFileMode? unixCreateMode = unixFileMode ?? OptionsMonitor.CurrentValue.Permissions.File.Mode?.ToUnixFileMode(); + UnixFileMode? unixCreateMode = unixFileMode ?? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode?.ToUnixFileMode(); if (!Directory.Exists(destinationDirectory)) { if (!OperatingSystem.IsWindows() && unixCreateMode.HasValue) { - Directory.CreateDirectory(destinationDirectory, unixCreateMode.Value.WithExecuteFlagsForEachReadFlag()); + var mode = unixCreateMode.Value.WithExecuteFlagsForEachReadFlag(); + Directory.CreateDirectory(destinationDirectory, unixCreateMode: mode); + File.SetUnixFileMode(destinationDirectory, mode: mode); } else { diff --git a/src/slskd/Integrations/FTP/FTPService.cs b/src/slskd/Integrations/FTP/FTPService.cs index 8c270d6a..597a34f3 100644 --- a/src/slskd/Integrations/FTP/FTPService.cs +++ b/src/slskd/Integrations/FTP/FTPService.cs @@ -109,7 +109,7 @@ namespace slskd.Integrations.FTP private async Task AttemptUploadAsync(string filename) { var fileAndParentDirectory = GetFileAndParentDirectoryFromFilename(filename); - var remotePath = FtpOptions.RemotePath.TrimEnd('/').TrimEnd('\\'); + var remotePath = FtpOptions.RemotePath.TrimEnd('/', '\\'); var remoteFilename = $"{remotePath}/{fileAndParentDirectory}"; var existsMode = FtpOptions.OverwriteExisting ? FtpRemoteExists.Overwrite : FtpRemoteExists.Skip; diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index d4baf276..9a2914ea 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -62,11 +62,12 @@ namespace slskd using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders.Physical; using Microsoft.IdentityModel.Tokens; - using Microsoft.OpenApi.Models; + using Microsoft.OpenApi; using Prometheus.DotNetRuntime; using Prometheus.SystemMetrics; using Serilog; using Serilog.Events; + using Serilog.Formatting.Display; using Serilog.Sinks.Grafana.Loki; using Serilog.Sinks.SystemConsole.Themes; using slskd.Authentication; @@ -1007,6 +1008,7 @@ namespace slskd services.AddSwaggerGen(options => { options.DescribeAllParametersInCamelCase(); + options.CustomSchemaIds(type => type.FullName); options.SwaggerDoc("v0", new OpenApiInfo { Version = "v0", @@ -1216,6 +1218,7 @@ namespace slskd .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning) .MinimumLevel.Override("slskd.Authentication.ApiKeyAuthenticationHandler", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", LogEventLevel.Warning) // bump this down to Information to show SQL + .Enrich.WithProperty("App", AppName) .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) .Enrich.WithProperty("ProcessId", ProcessId) @@ -1234,9 +1237,13 @@ namespace slskd retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs)))) .WriteTo.Conditional( e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), - config => config.GrafanaLoki( - OptionsAtStartup.Logger.Loki ?? string.Empty, - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) + config => + { + if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) + { + config.GrafanaLoki(OptionsAtStartup.Logger.Loki); + } + }) .WriteTo.Sink(new DelegatingSink(logEvent => { string message = default; diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index fdc6dbe6..ddb8d0b0 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -345,7 +345,7 @@ namespace slskd.Relay } Directory.CreateDirectory(FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName)); - var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_{agentName.ReplaceInvalidFileNameCharacters()}_{Path.GetRandomFileName()}.db"); + var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_{FileSafety.SanitizeFilename(agentName)}_{Path.GetRandomFileName()}.db"); try { diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 974ca71e..5c5f9d38 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -484,7 +484,7 @@ namespace slskd.Relay // if the controller is Windows and the agent is Linux or vice versa, we need to translate the filename to the // local OS or we're going to get funny results when we go to write the file - destinationFile = destinationFile.LocalizePath(); + destinationFile = FileSafety.LocalizePath(destinationFile); await Retry.Do(task: async () => { diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index c1b7d725..fe34bfec 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -106,8 +106,13 @@ public record EnqueueDownloadBatchOptions /// <summary> /// The destination directory for the files, relative to the configured download directory. /// </summary> - [RelativePath] + [RelativePath(OperatingSystem.All)] [NonTraversingPath] [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] public string Destination { get; init; } + + /// <summary> + /// An optional external ID for the batch. + /// </summary> + public string ExternalId { get; init; } }
\ No newline at end of file diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 013e6a7a..7c794e55 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -38,9 +38,11 @@ namespace slskd.Transfers.Downloads using System; using System.Collections.Concurrent; using System.Collections.Generic; + using System.IO; using System.Linq; using System.Linq.Expressions; using System.Net; + using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; @@ -49,6 +51,7 @@ namespace slskd.Transfers.Downloads using slskd.Files; using slskd.Integrations.FTP; using slskd.Relay; + using slskd.Search; /// <summary> /// Manages downloads. @@ -68,6 +71,26 @@ namespace slskd.Transfers.Downloads void AddOrSupersede(Transfer transfer); /// <summary> + /// Derives the destination subdirectory for the specified <paramref name="transfer"/> based on user and batch + /// configuration. + /// </summary> + /// <remarks> + /// <para> + /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments. + /// Otherwise, an instance of <see cref="SlskdException"/> will be thrown as a backstop. + /// </para> + /// <para> + /// Empty segments may be present in the output, which more closely aligns with user intent. The + /// <see cref="Path.Combine(string, string)"/> method drops them silently, so there's no functional impact. + /// </para> + /// </remarks> + /// <param name="transfer">The transfer.</param> + /// <returns>The derived destination directory.</returns> + /// <exception cref="NotFoundException">Thrown if the specified download doesn't exist.</exception> + /// <exception cref="SlskdException">Thrown if the derivation logic produces an absolute path, or one with traversal segments.</exception> + Task<string> DeriveDestination(Transfer transfer); + + /// <summary> /// Enqueues the requested list of <paramref name="files"/>. /// </summary> /// <remarks> @@ -165,6 +188,7 @@ namespace slskd.Transfers.Downloads { public DownloadService( IBatchService batchService, + ISearchService searchService, IOptionsMonitor<Options> optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory<TransfersDbContext> contextFactory, @@ -174,6 +198,7 @@ namespace slskd.Transfers.Downloads EventBus eventBus) { Batches = batchService; + Searches = searchService; Client = soulseekClient; OptionsMonitor = optionsMonitor; ContextFactory = contextFactory; @@ -213,10 +238,12 @@ namespace slskd.Transfers.Downloads private IDbContextFactory<TransfersDbContext> ContextFactory { get; } private IFTPService FTP { get; } private FileService Files { get; } + private ISearchService Searches { get; } private IRelayService Relay { get; } private ILogger Log { get; } = Serilog.Log.ForContext<DownloadService>(); private IOptionsMonitor<Options> OptionsMonitor { get; } private EventBus EventBus { get; } + private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\$\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// <summary> /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they @@ -708,6 +735,152 @@ namespace slskd.Transfers.Downloads } /// <summary> + /// Derives the destination subdirectory for the specified <paramref name="transfer"/> based on user and + /// batch configuration. + /// </summary> + /// <remarks> + /// <para> + /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments. + /// Otherwise, an instance of <see cref="SlskdException"/> will be thrown as a backstop. + /// </para> + /// <para> + /// Empty segments may be present in the output, which more closely aligns with user intent. The + /// <see cref="Path.Combine(string, string)"/> method drops them silently, so there's no functional impact. + /// </para> + /// </remarks> + /// <param name="transfer">The transfer.</param> + /// <returns>The derived destination directory.</returns> + /// <exception cref="SlskdException">Thrown if the derivation logic produces an absolute path, or one with traversal segments.</exception> + public async Task<string> DeriveDestination(Transfer transfer) + { + // validation should ensure this is a relative path and that it contains no traversal segments + // we accept any type of slash in the pattern and convert it to the correct variant for the local OS + var pattern = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Subdirectory; + + // users can enter '{}' if they want the files to go directly into the root of the downloads directory + if (pattern.Equals("{}", StringComparison.OrdinalIgnoreCase)) + { + return string.Empty; + } + + string source_username; + string source_path; + string source_directory; + string batch_id; + string batch_external_id; + string search_id; + string search_text; + + /* + fetch/extract/derive and sanitize each of the values we're going to replace + + when flow leaves this block we can expect that all of the string values + defined above have a value that can be safely substituted for its placeholder + */ + try + { + Batch batch = null; + + if (transfer.BatchId is not null) + { + batch = await Batches.FindAsync(b => b.Id == transfer.BatchId); + } + + // destination supplied with the batch enqueue request takes precedence over all; return early + if (!string.IsNullOrWhiteSpace(batch?.Options?.Destination)) + { + var explicitDestination = FileSafety.SanitizePath(batch.Options.Destination, replacement: '_'); + + // the only way to get here is through a regression in the logic above; if we are seeing this, ensure we are + // properly sanitizing user input both via the API and in the logic above + if (FileSafety.IsPathAbsolute(explicitDestination) || FileSafety.ContainsTraversalSegments(explicitDestination)) + { + throw new SlskdException("Derived a transfer destination that is either not relative or contains traversal segments; neither is allowed. Please report this on GitHub."); + } + + return explicitDestination; + } + + Search search = null; + + if (batch?.SearchId is not null) + { + search = await Searches.FindAsync(s => s.Id == batch.SearchId); + } + + source_username = FileSafety.SanitizeFilename(transfer.Username, replacement: '_'); + + var filename = FileSafety.SanitizePath(transfer.Filename, replacement: '_'); + + // full remote path, e.g. '@@abcd\Foo\Bar\Baz\Qux.ext' => '@@abcd\Foo\Bar\Baz' + // retains the path root, if there is one (Soulseek NS does this), which may not be what + // people want, so possibly revisit and add StripPathRoot() + source_path = (FileSafety.GetDirectoryNameSafely(filename, retainRoot: false) ?? string.Empty).TrimEnd('/', '\\'); + + // name of the remote parent directory, so using the example above, 'Baz' + source_directory = (FileSafety.GetFileNameSafely(source_path) ?? string.Empty).TrimEnd('/', '\\'); + + batch_id = (batch?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_batch_id" : batch.Id.ToString(); + + // the external id can be any string (it is supplied via API call) so we have to sanitize it just like the destination, + // except we don't want to allow it to tack on directories; that's not what it is for and it could be unintended + batch_external_id = FileSafety.SanitizeFilename( + filename: string.IsNullOrWhiteSpace(batch?.Options?.ExternalId) ? "unknown_batch_external_id" : batch.Options.ExternalId, + replacement: '_'); + + search_id = (search?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_search_id" : search.Id.ToString(); + search_text = FileSafety.SanitizeFilename( + filename: string.IsNullOrWhiteSpace(search?.SearchText) ? "unknown_search_text" : search.SearchText, + replacement: '_'); + } + catch (Exception ex) + { + Log.Error(ex, "Failed fetch information for download {Id}: {Message}", transfer.Id, ex.Message); + throw; + } + + var args = new Dictionary<string, string>( + StringComparer.OrdinalIgnoreCase) // important! + { + ["SOURCE_USERNAME"] = source_username, + ["SOURCE_PATH"] = source_path, + ["SOURCE_DIRECTORY"] = source_directory, + ["BATCH_ID"] = batch_id, + ["BATCH_EXTERNAL_ID"] = batch_external_id, + ["SEARCH_ID"] = search_id, + ["SEARCH_TEXT"] = search_text, + }; + + // use Regex.Replace here because it makes one pass; if we chained .Replace() calls the output from one could + // cascade into others and produce unintended results + var destination = SubdirectoryPatternTokenRegex.Replace( + input: pattern, + evaluator: match => + { + if (args.TryGetValue(match.Groups[1].Value, out var value)) + { + return value; + } + + return match.Value; + }); + + destination = FileSafety.SanitizePath(destination, replacement: '_'); + + Log.Debug("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text }); + + // the only way to get here is through a regression in the logic above; if we are seeing this, ensure we are + // properly sanitizing the final output to strip leading slashes and replace traversal segments + if (FileSafety.IsPathAbsolute(destination) || FileSafety.ContainsTraversalSegments(destination)) + { + Log.Error("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text }); + throw new SlskdException("Derived a transfer destination that is either not relative or contains traversal segments; neither is allowed. Please report this on GitHub."); + } + + return destination; + } + + /// <summary> /// Returns a list of all downloads matching the optional <paramref name="expression"/>. /// </summary> /// <param name="expression">An optional expression used to match downloads.</param> @@ -1045,14 +1218,42 @@ namespace slskd.Transfers.Downloads }), disposeOutputStreamOnCompletion: true); - System.IO.UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) - ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() + UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode) + ? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode.ToUnixFileMode() : null; - // store incomplete files under a username subdirectory to prevent collisions between users - // and to make it safe to resume partial downloads without risking picking up an unrelated file - var incompleteFilename = transfer.Filename.ToLocalFilename( - baseDirectory: FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Incomplete, transfer.Username.ReplaceInvalidFileNameCharacters())); + /* + store incomplete files under a username subdirectory to prevent collisions between users and to make + it safe to resume partial downloads without risking picking up an unrelated file. + + we're going to store the file as: + + <incomplete directory>/<username>/<full path to file on remote client>/<filename> + + so, a remote file 'C:\Music\Public_Domain\Foo\Bar\Baz.ext' from user 'FooBar' becomes: + + linux: incomplete/C:/FooBar/Music/Public_Domain/Foo/Bar/Baz.ext + windows: incomplete\C_\FooBar\Music\Public_Domain\Foo\Bar\Baz.ext + + slashes are normalized to the current OS and any invalid characters are replaced with an underscore, _. + this mitigates the risk of an improper partial resume to a great extent. + + if the remote file changes size between attempts, Soulseek.NET's DownloadAsync() will throw because + the size we send originates from the original file, and there will be a mismatch. + + the only remaining risk is in a case where the file contents have changed but the size remains the same. + the resulting file will be corrupted in that case, and there's nothing we can really do about it. users + that are concerned about this (extremely unlikely) case should configure slskd to always overwrite + partial files. + */ + var incompleteDirectory = OptionsMonitor.CurrentValue.Directories.Incomplete; + var sanitizedUsername = FileSafety.SanitizePathSegment(transfer.Username); + var sanitizedFilename = FileSafety.GetFileNameSafely(transfer.Filename, sanitize: true); + var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true) ?? string.Empty; + + var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename); + + Log.Debug("Incomplete file for {Filename} from {Username} will be: {IncompleteFilename}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; @@ -1140,22 +1341,18 @@ namespace slskd.Transfers.Downloads move the file from incomplete to complete users have a lot of strong opinions about this! + + the destination is always rooted in the configured download directory. we derive the subdirectory + for this file based on either the Destination property defined for the Batch that contains this transfer, + or by applying replacements to the user's configured Destination.Subdirectory string. + + what we get back will be a relative path (or perhaps an empty string if that's what the user wanted) + that has sanitized and checked for safety against traversal */ - string destinationDirectory; + var subdirectory = await DeriveDestination(transfer); + var destinationDirectory = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, subdirectory); - if (transfer.BatchId is not null) - { - // if the transfer has an associated batch id, then: - // some/long/remote/path/folder/file.ext -> download_directory/batch_id/file.ext - destinationDirectory = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, transfer.BatchId.Value.ToString()); - } - else - { - // ToLocalFilename chops all but the containing folder off of the path and localizes slashes, so: - // some/long/remote/path/folder/file.ext -> folder/file.ext -> download_directory/folder/file.ext - // this is "legacy" behavior that will be familiar to most Soulseek users - destinationDirectory = System.IO.Path.GetDirectoryName(transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Downloads)); - } + var existsStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Exists.ToEnum<DestinationExistsStrategy>(); Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory); @@ -1163,10 +1360,10 @@ namespace slskd.Transfers.Downloads sourceFilename: incompleteFilename, destinationDirectory: destinationDirectory, unixFileMode: unixFileMode, - overwrite: false, + overwrite: existsStrategy == DestinationExistsStrategy.Overwrite, deleteSourceDirectoryIfEmptyAfterMove: true); - Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); + Log.Information("Moved file {Filename} from {Username} from {Incomplete} to {Destination}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename, finalFilename); if (OptionsMonitor.CurrentValue.Relay.Enabled) { diff --git a/src/slskd/Transfers/Types/BatchOptions.cs b/src/slskd/Transfers/Types/BatchOptions.cs index 6bacef8c..2ea22997 100644 --- a/src/slskd/Transfers/Types/BatchOptions.cs +++ b/src/slskd/Transfers/Types/BatchOptions.cs @@ -45,4 +45,9 @@ public record BatchOptions /// If specified, takes precedence over other configured placement rules. /// </remarks> public string Destination { get; init; } + + /// <summary> + /// Gets an optional external ID for the batch. + /// </summary> + public string ExternalId { get; init; } }
\ No newline at end of file diff --git a/src/slskd/Transfers/Types/DestinationConflictStrategy.cs b/src/slskd/Transfers/Types/DestinationConflictStrategy.cs new file mode 100644 index 00000000..27281a2d --- /dev/null +++ b/src/slskd/Transfers/Types/DestinationConflictStrategy.cs @@ -0,0 +1,49 @@ +// <copyright file="DestinationConflictStrategy.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Transfers; + +/// <summary> +/// Strategy for handling downloaded files with conflicting names. +/// </summary> +public enum DestinationConflictStrategy +{ + /// <summary> + /// Rename the new file by appending something. + /// </summary> + Rename = 0, + + /// <summary> + /// Overwrite the existing file. + /// </summary> + Overwrite = 1, +}
\ No newline at end of file diff --git a/src/slskd/Transfers/Types/DestinationExistsStrategy.cs b/src/slskd/Transfers/Types/DestinationExistsStrategy.cs new file mode 100644 index 00000000..18837563 --- /dev/null +++ b/src/slskd/Transfers/Types/DestinationExistsStrategy.cs @@ -0,0 +1,49 @@ +// <copyright file="DestinationExistsStrategy.cs" company="JP Dillingham"> +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// </copyright> + +namespace slskd.Transfers; + +/// <summary> +/// Strategy for handling downloaded files when the destination file already exists. +/// </summary> +public enum DestinationExistsStrategy +{ + /// <summary> + /// Rename the new file by appending something to the file name. + /// </summary> + Rename = 0, + + /// <summary> + /// Overwrite the existing file. + /// </summary> + Overwrite = 1, +}
\ No newline at end of file diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index cf825701..cb6a7d83 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -43,41 +43,41 @@ </Target> <ItemGroup> - <PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="8.1.0" /> - <PackageReference Include="Dapper" Version="2.1.66" /> + <PackageReference Include="Asp.Versioning.Mvc.ApiExplorer" Version="10.0.0" /> + <PackageReference Include="Dapper" Version="2.1.79" /> <PackageReference Include="FluentFTP" Version="49.0.2" /> - <PackageReference Include="IPAddressRange" Version="6.0.0" /> - <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="8.0.6" /> - <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="8.0.6" /> - <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="8.0.0"> + <PackageReference Include="IPAddressRange" Version="6.3.0" /> + <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="10.0.8" /> + <PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.8" /> + <PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="10.0.300"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Microsoft.Data.Sqlite" Version="8.0.6" /> - <PackageReference Include="Microsoft.EntityFrameworkCore" Version="8.0.6" /> - <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="8.0.6" /> + <PackageReference Include="Microsoft.Data.Sqlite" Version="10.0.8" /> + <PackageReference Include="Microsoft.EntityFrameworkCore" Version="10.0.8" /> + <PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite.Core" Version="10.0.8" /> <PackageReference Include="OneOf" Version="3.0.271" /> <PackageReference Include="prometheus-net" Version="8.2.1" /> <PackageReference Include="prometheus-net.AspNetCore" Version="8.2.1" /> <PackageReference Include="prometheus-net.AspNetCore.HealthChecks" Version="8.2.1" /> - <PackageReference Include="prometheus-net.DotNetRuntime" Version="4.4.0" /> + <PackageReference Include="prometheus-net.DotNetRuntime" Version="4.4.1" /> <PackageReference Include="prometheus-net.SystemMetrics" Version="3.1.0" /> - <PackageReference Include="Serilog" Version="3.1.1" /> - <PackageReference Include="Serilog.AspNetCore" Version="8.0.1" /> - <PackageReference Include="Serilog.Sinks.Async" Version="1.5.0" /> - <PackageReference Include="Serilog.Sinks.Console" Version="5.0.1" /> - <PackageReference Include="Serilog.Sinks.File" Version="5.0.0" /> - <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="7.1.1" /> - <PackageReference Include="Serilog.Sinks.Http" Version="8.0.0" /> - <PackageReference Include="Soulseek" Version="10.0.0" /> + <PackageReference Include="Serilog" Version="4.3.1" /> + <PackageReference Include="Serilog.AspNetCore" Version="10.0.0" /> + <PackageReference Include="Serilog.Sinks.Async" Version="2.1.0" /> + <PackageReference Include="Serilog.Sinks.Console" Version="6.1.1" /> + <PackageReference Include="Serilog.Sinks.File" Version="7.0.0" /> + <PackageReference Include="Serilog.Sinks.Grafana.Loki" Version="9.0.0" /> + <PackageReference Include="Serilog.Sinks.Http" Version="9.2.1" /> + <PackageReference Include="Soulseek" Version="10.0.1" /> <PackageReference Include="StyleCop.Analyzers" Version="1.2.0-beta.556"> <PrivateAssets>all</PrivateAssets> <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> </PackageReference> - <PackageReference Include="Swashbuckle.AspNetCore" Version="6.6.2" /> + <PackageReference Include="Swashbuckle.AspNetCore" Version="10.2.1" /> <PackageReference Include="TagLibSharp" Version="2.3.0" /> <PackageReference Include="Utility.CommandLine.Arguments" Version="6.0.0" /> <PackageReference Include="Utility.EnvironmentVariables" Version="1.0.5" /> - <PackageReference Include="YamlDotNet" Version="15.3.0" /> + <PackageReference Include="YamlDotNet" Version="18.0.0" /> </ItemGroup> </Project> diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs deleted file mode 100644 index eff24587..00000000 --- a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs +++ /dev/null @@ -1,144 +0,0 @@ -namespace slskd.Tests.Unit.Common.Extensions -{ - using System; - using System.IO; - using System.Linq; - using Xunit; - - public class ReplaceInvalidFileNameCharactersTests - { - [Fact] - public void Throws_NullReferenceException_Given_Null() - { - string path = null; - Assert.Throws<NullReferenceException>(() => path.ReplaceInvalidFileNameCharacters()); - } - - [Fact] - public void Returns_Empty_String_Given_Empty_Input() - { - Assert.Equal(string.Empty, string.Empty.ReplaceInvalidFileNameCharacters()); - } - - [Fact] - public void Returns_Input_Unchanged_When_No_Invalid_Characters_Present() - { - var valid = "valid_filename.ext"; - Assert.Equal(valid, valid.ReplaceInvalidFileNameCharacters()); - } - - [Fact] - public void Preserves_Valid_Characters() - { - // Common valid filename chars that must not be touched - var valid = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._- "; - Assert.Equal(valid, valid.ReplaceInvalidFileNameCharacters()); - } - - [Fact] - public void Default_Replacement_Character_Is_Underscore() - { - var c = Path.GetInvalidFileNameChars().First(); - var result = $"a{c}b".ReplaceInvalidFileNameCharacters(); - Assert.Equal("a_b", result); - } - - [Fact] - public void Replaces_Each_Invalid_Filename_Character_With_Default_Replacement() - { - // Each invalid char is tested individually so failures identify the exact offending char - Assert.All(Path.GetInvalidFileNameChars(), c => - { - var result = $"prefix{c}suffix".ReplaceInvalidFileNameCharacters(); - Assert.False(result.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced"); - Assert.Equal("prefix_suffix", result); - }); - } - - [Fact] - public void Replaces_All_Invalid_Filename_Characters_Simultaneously() - { - var invalidChars = Path.GetInvalidFileNameChars(); - var allInvalid = new string(invalidChars); - var result = allInvalid.ReplaceInvalidFileNameCharacters(); - - Assert.All(invalidChars, c => - Assert.False(result.Contains(c), $"Invalid character U+{(int)c:X4} remained after sanitization")); - } - - [Fact] - public void Result_Contains_Only_Replacement_Character_When_All_Input_Characters_Are_Invalid() - { - var invalidChars = Path.GetInvalidFileNameChars(); - var allInvalid = new string(invalidChars); - var result = allInvalid.ReplaceInvalidFileNameCharacters(); - - Assert.Equal(new string('_', invalidChars.Length), result); - } - - [Fact] - public void Uses_Custom_Replacement_Character() - { - char replacement = '-'; - - Assert.All(Path.GetInvalidFileNameChars(), c => - { - var result = $"a{c}b".ReplaceInvalidFileNameCharacters(replacement); - Assert.False(result.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced"); - Assert.Equal("a-b", result); - }); - } - - [Fact] - public void Replaces_Consecutive_Invalid_Characters() - { - var chars = Path.GetInvalidFileNameChars(); - if (chars.Length < 2) - { - return; - } - - var input = $"a{chars[0]}{chars[1]}b"; - var result = input.ReplaceInvalidFileNameCharacters(); - - Assert.Equal("a__b", result); - } - - [Fact] - public void Replaces_Invalid_Character_At_Start_Of_String() - { - var c = Path.GetInvalidFileNameChars().First(); - var result = $"{c}filename.ext".ReplaceInvalidFileNameCharacters(); - Assert.Equal("_filename.ext", result); - } - - [Fact] - public void Replaces_Invalid_Character_At_End_Of_String() - { - var c = Path.GetInvalidFileNameChars().First(); - var result = $"filename.ext{c}".ReplaceInvalidFileNameCharacters(); - Assert.Equal("filename.ext_", result); - } - - [Fact] - public void Result_Contains_No_Invalid_Filename_Characters() - { - var invalidChars = Path.GetInvalidFileNameChars(); - var input = "valid" + new string(invalidChars) + "also_valid"; - var result = input.ReplaceInvalidFileNameCharacters(); - - Assert.All(invalidChars, c => - Assert.False(result.Contains(c), $"Character U+{(int)c:X4} remained after sanitization")); - } - - [Fact] - public void Valid_Characters_Surrounding_Invalid_Characters_Are_Preserved() - { - var c = Path.GetInvalidFileNameChars().First(); - var result = $"before{c}after".ReplaceInvalidFileNameCharacters(); - - Assert.StartsWith("before", result); - Assert.EndsWith("after", result); - } - } -} diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs deleted file mode 100644 index 78539142..00000000 --- a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs +++ /dev/null @@ -1,160 +0,0 @@ -namespace slskd.Tests.Unit.Common.Extensions -{ - using System; - using System.IO; - using System.Linq; - using Xunit; - - public class ToLocalRelativeFilenameTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("\t")] - public void Throws_ArgumentException_Given_Bad_Remote_Filename(string filename) - { - var ex = Record.Exception(() => filename.ToLocalRelativeFilename()); - - Assert.NotNull(ex); - Assert.IsType<ArgumentException>(ex); - } - - [Fact] - public void Returns_Last_Directory_And_Filename_From_Deep_Path() - { - var expected = "path" + Path.DirectorySeparatorChar + "file.ext"; - Assert.Equal(expected, @"deeply\nested\path\file.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Returns_Just_Filename_If_No_Directory_Given() - { - Assert.Equal("file.ext", "file.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Replaces_Invalid_Characters_In_Filename() - { - // Exclude backslash and forward slash — they act as segment separators in the input - // and would cause the dirty string to be split rather than treated as a filename. - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - var dirtyName = new string(invalidChars); - var result = $@"a\b\{dirtyName}".ToLocalRelativeFilename(); - var filename = Path.GetFileName(result); - - Assert.All(invalidChars, c => - Assert.False(filename.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in filename")); - } - - [Fact] - public void Replaces_Invalid_Characters_In_Directory() - { - // Directory segments are sanitized with ReplaceInvalidFileNameCharacters, so the full - // GetInvalidFileNameChars() set applies (excluding path separators, which split the input). - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - var dirtyName = new string(invalidChars); - var result = $@"a\{dirtyName}\file.ext".ToLocalRelativeFilename(); - var directory = Path.GetDirectoryName(result); - - Assert.All(invalidChars, c => - Assert.False(directory.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in directory")); - } - - [Fact] - public void Replaces_Each_Invalid_Filename_Character_Individually() - { - // Tests each invalid filename char in isolation so that failures identify the exact - // offending character rather than only reporting that something in a concatenated - // string was not replaced. - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - Assert.All(invalidChars, c => - { - var result = $@"a\b\prefix{c}suffix.ext".ToLocalRelativeFilename(); - var filename = Path.GetFileName(result); - Assert.False(filename.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in filename"); - }); - } - - [Fact] - public void Replaces_Each_Invalid_Filename_Character_In_Directory_Individually() - { - // Tests each invalid filename char in the directory segment in isolation so that - // failures identify the exact offending character. - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - Assert.All(invalidChars, c => - { - var result = $@"a\prefix{c}suffix\file.ext".ToLocalRelativeFilename(); - var directory = Path.GetDirectoryName(result); - Assert.False(directory.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in directory"); - }); - } - - [Fact] - public void Returns_Last_Directory_And_Filename_From_Two_Segment_Path() - { - var expected = "dir" + Path.DirectorySeparatorChar + "file.ext"; - Assert.Equal(expected, @"dir\file.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Handles_Forward_Slash_As_Segment_Separator() - { - // LocalizePath normalizes '/' to Path.DirectorySeparatorChar before splitting, - // so forward-slash paths must produce the same result as backslash paths. - var expected = "b" + Path.DirectorySeparatorChar + "c.ext"; - Assert.Equal(expected, "a/b/c.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Handles_Mixed_Slash_Separators() - { - var expected = "b" + Path.DirectorySeparatorChar + "c.ext"; - Assert.Equal(expected, @"a/b\c.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Preserves_Spaces_In_Filename() - { - // Spaces are valid in file names and must survive sanitization. - var expected = "dir" + Path.DirectorySeparatorChar + "file name.ext"; - Assert.Equal(expected, @"root\dir\file name.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Preserves_Spaces_In_Directory() - { - var expected = "my dir" + Path.DirectorySeparatorChar + "file.ext"; - Assert.Equal(expected, @"root\my dir\file.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Directory_Segment_Contains_No_Characters_Invalid_For_Directory_Names() - { - // All GetInvalidFileNameChars() (minus separators) must be absent from the directory - // segment. Directory segments are sanitized with ReplaceInvalidFileNameCharacters, so - // the full filename-invalid set applies. - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - Assert.All(invalidChars, c => - { - var result = $@"a\prefix{c}suffix\file.ext".ToLocalRelativeFilename(); - var directory = Path.GetDirectoryName(result); - Assert.False(directory.Contains(c), $"Character U+{(int)c:X4} is invalid for directory names but was not replaced"); - }); - } - } -}
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index 0ffa0129..ceba3b86 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -1,6 +1,5 @@ using System; using System.IO; -using System.Runtime.InteropServices; using Xunit; namespace slskd.Tests.Unit.Common; @@ -9,13 +8,14 @@ public partial class FileSafetyTests { public class CombineSafelyTests { - public static string Base = OperatingSystem.IsWindows() ? "C:\\base" : "/base"; + public static string Base = System.OperatingSystem.IsWindows() ? "C:\\base" : "/base"; public static string ExpectedStartsWith = Base + Path.DirectorySeparatorChar; [Theory] [InlineData(null)] + [InlineData("")] [InlineData(" ")] - public void Throws_ArgumentException_Given_NullOrWhiteSpaceRoot(string root) + public void Throws_ArgumentNullException_Given_NullOrWhiteSpaceRoot(string root) { var ex = Record.Exception(() => FileSafety.CombineSafely(root)); @@ -24,6 +24,10 @@ public partial class FileSafetyTests } [Theory] + [InlineData(".")] + [InlineData("..")] + [InlineData("./foo")] + [InlineData("../bar")] [InlineData("foo/../bar")] [InlineData("foo\\..\\bar")] public void Throws_ArgumentException_Given_TraversingRoot(string root) @@ -119,7 +123,7 @@ public partial class FileSafetyTests [InlineData("//server/share")] public void Throws_ArgumentException_Given_AbsolutePath_On_Unix(string segment) { - var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Linux, segment)); + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); Assert.NotNull(ex); Assert.Contains("Absolute", ex.Message); @@ -131,7 +135,7 @@ public partial class FileSafetyTests [InlineData("\\\\server\\share")] public void Throws_ArgumentException_Given_AbsolutePath_On_Windows(string segment) { - var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Windows, segment)); + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Windows, segment)); Assert.NotNull(ex); Assert.Contains("Absolute", ex.Message); @@ -144,7 +148,7 @@ public partial class FileSafetyTests [InlineData("sub/foo/bar:qux")] public void Throws_ArgumentException_Given_Colon_In_Segment_On_Windows(string segment) { - var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Windows, segment)); + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Windows, segment)); Assert.NotNull(ex); Assert.Contains("Colon", ex.Message); @@ -156,30 +160,18 @@ public partial class FileSafetyTests [InlineData("sub/foo/bar:qux")] public void Accepts_Colon_In_Segment_On_Linux(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Linux, segment)); + var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); Assert.Null(result); } [Theory] [InlineData("C:relative")] - public void Accepts_Colon_In_Segment_On_Linux_Hits_Backstop_On_Windows(string segment) + public void Accepts_Colon_In_Segment_On_Linux_When_Running_On_Windows(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!OperatingSystem.IsWindows()) - { - Assert.Null(result); - } - else - { - // this test breaks when run on windows - // this is valid on linux (which we're trying to test for) - // but invalid on windows because it is a drive-relative path and it successfully traverses - Assert.NotNull(result); - Assert.IsType<ArgumentException>(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/C:relative", result); } [Theory] @@ -187,7 +179,7 @@ public partial class FileSafetyTests [InlineData("\\Music")] public void Throws_ArgumentException_Given_Leading_Slash_In_Segment_On_Windows(string segment) { - var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Windows, segment)); + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Windows, segment)); Assert.NotNull(ex); Assert.Contains("Drive-relative", ex.Message); @@ -197,21 +189,47 @@ public partial class FileSafetyTests [InlineData("\\Music")] public void Accepts_Leading_Backslash_In_Segment_On_Linux(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Linux, segment)); - - if (!OperatingSystem.IsWindows()) - { - Assert.Null(result); - } - else - { - // this test breaks when run on windows - // this is valid on linux (which we're trying to test for) - // but invalid on windows because it is a drive-relative path and it successfully traverses - Assert.NotNull(result); - Assert.IsType<ArgumentException>(result); - Assert.Contains("traversal detected", result.Message); - } + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); + + Assert.Equal($"{Base}/\\Music", result); + } + + [Fact] + public void Returns_Root_Given_Single_Empty_Segment() + { + var result = FileSafety.CombineSafely(Base, ""); + + Assert.Equal(Base, result); + } + + [Fact] + public void Returns_Root_Given_All_Empty_Segments() + { + var result = FileSafety.CombineSafely(Base, "", ""); + + Assert.Equal(Base, result); + } + + [Fact] + public void Handles_Root_With_Trailing_Separator() + { + var rootWithTrailing = Base + Path.DirectorySeparatorChar; + var result = FileSafety.CombineSafely(rootWithTrailing, "foo"); + + Assert.StartsWith(ExpectedStartsWith, result); + Assert.EndsWith("foo", result); + } + + [Theory] + [InlineData("./foo")] + [InlineData("../bar")] + [InlineData("foo/../bar")] + public void Throws_ArgumentException_Given_TraversingRoot_With_Os_Override(string root) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(root, OperatingSystem.Linux, "segment")); + + Assert.NotNull(ex); + Assert.IsType<ArgumentException>(ex); } [Theory] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs index 205c87c2..f0b1a394 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs @@ -106,6 +106,9 @@ public partial class FileSafetyTests [InlineData("Ünïcödé/..hidden")] [InlineData("пользователь/...dir")] [InlineData("用户/..名前")] + // Segments that look like traversal but have surrounding whitespace — not exact matches + [InlineData(" . ")] + [InlineData(" .. ")] public void Path_DoesNotContainTraversal(string path) { Assert.False(FileSafety.ContainsTraversalSegments(path)); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs index f60c4c9a..eaeaa29f 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -1,13 +1,20 @@ -using System.Runtime.InteropServices; -using Xunit; - namespace slskd.Tests.Unit.Common; +using Xunit; + public partial class FileSafetyTests { public class GetDirectoryNameSafelyTests { [Fact] + public void NullOs_UsesPlatformDefault_DoesNotThrow() + { + var result = FileSafety.GetDirectoryNameSafely("foo/bar"); + + Assert.Equal("foo", result); + } + + [Fact] public void Returns_Null_Given_Null() { var result = FileSafety.GetDirectoryNameSafely(null); @@ -38,6 +45,14 @@ public partial class FileSafetyTests Assert.Null(result); } + [Fact] + public void Returns_Null_Given_Whitespace_Only() + { + var result = FileSafety.GetDirectoryNameSafely(" "); + + Assert.Null(result); + } + [Theory] [InlineData("foo")] [InlineData("foo.bar")] @@ -72,7 +87,7 @@ public partial class FileSafetyTests [InlineData("@@abcde\\file.txt")] public void Returns_Null_When_File_Is_Directly_In_Root_With_RetainRoot_False_Linux(string input) { - var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, os: OSPlatform.Linux); + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, os: OperatingSystem.Linux); Assert.Null(result); } @@ -86,7 +101,7 @@ public partial class FileSafetyTests [InlineData("@@abcde\\file.txt")] public void Returns_Null_When_File_Is_Directly_In_Root_With_RetainRoot_False_Windows(string input) { - var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, os: OSPlatform.Windows); + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, os: OperatingSystem.Windows); Assert.Null(result); } @@ -100,7 +115,7 @@ public partial class FileSafetyTests [InlineData("@@abcde\\file.txt", "@@abcde")] public void Returns_Root_When_File_Is_Directly_In_Root_With_RetainRoot_True_Linux(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Linux); + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -114,7 +129,7 @@ public partial class FileSafetyTests [InlineData("@@abcde\\file.txt", "@@abcde")] public void Returns_Sanitized_Root_When_File_Is_Directly_In_Root_With_RetainRoot_True_Windows(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Windows); + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -148,7 +163,7 @@ public partial class FileSafetyTests [InlineData("/foo//bar//baz", "foo\\bar")] public void Removes_Empty_Segments_And_Leading_Slashes_Windows(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Windows); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -158,12 +173,105 @@ public partial class FileSafetyTests [InlineData("/foo//bar//baz", "foo/bar")] public void Removes_Empty_Segments_And_Leading_Slashes_Linux(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Linux); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo/../bar/file.txt", "foo/_/bar")] + [InlineData("../bar/file.txt", "_/bar")] + [InlineData("a/./b/file.txt", "a/_/b")] + public void Sanitizes_Traversal_Segments_In_Directory_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo\\..\\bar\\file.txt", "foo\\_\\bar")] + [InlineData("..\\bar\\file.txt", "_\\bar")] + [InlineData("a\\.\\b\\file.txt", "a\\_\\b")] + public void Sanitizes_Traversal_Segments_In_Directory_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("Artist/Album/", "Artist")] + [InlineData("Artist\\Album\\", "Artist")] + [InlineData("foo/bar/baz/", "foo/bar")] + public void Treats_Trailing_Slash_As_Directory_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("Artist/Album/", "Artist")] + [InlineData("Artist\\Album\\", "Artist")] + [InlineData("foo/bar/baz/", "foo\\bar")] + public void Treats_Trailing_Slash_As_Directory_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o/bar", "fo\0o")] + [InlineData("C:/Mu\0sic/song.flac", "Mu\0sic")] + public void Returns_Unrooted_Unsanitized_Directory_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, sanitize: false, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o\\bar", "fo\0o")] + [InlineData("C:\\Mu\0sic\\song.flac", "Mu\0sic")] + public void Returns_Unrooted_Unsanitized_Directory_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, sanitize: false, os: OperatingSystem.Windows); Assert.Equal(expected, result); } [Theory] + [InlineData("foo/../bar/file.txt", "foo/../bar")] + [InlineData("../etc/file.txt", "../etc")] + public void Preserves_Traversal_Segments_When_Sanitize_False_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: false, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo\\..\\bar\\file.txt", "foo\\..\\bar")] + [InlineData("..\\etc\\file.txt", "..\\etc")] + public void Preserves_Traversal_Segments_When_Sanitize_False_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: false, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcd/foo/bar/file.txt")] + public void Short_Qt_Prefix_Treated_As_Segment_Linux(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Linux); + + Assert.StartsWith("@@abcd", result); + } + + [Theory] [InlineData("fo\0o\\bar", "fo_o")] [InlineData("foo/bar", "foo")] [InlineData("C:\\Music\\song.flac", "Music")] @@ -177,7 +285,7 @@ public partial class FileSafetyTests [InlineData("@@abcde\\foo\\bar", "foo")] public void Returns_Unrooted_Sanitized_Directory_Given_Path_With_File_Linux(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Linux); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -196,7 +304,7 @@ public partial class FileSafetyTests [InlineData("@@abcde\\foo\\bar", "foo")] public void Returns_Unrooted_Sanitized_Directory_Given_Path_With_File_Windows(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Windows); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -214,7 +322,7 @@ public partial class FileSafetyTests [InlineData("@@abcde\\foo\\bar", "@@abcde\\foo")] public void Retains_Path_Root_When_RetainRoot_True_Windows(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Windows); + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -232,7 +340,7 @@ public partial class FileSafetyTests [InlineData("@@abcde\\foo\\bar", "@@abcde/foo")] public void Retains_Path_Root_When_RetainRoot_True_Linux(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Linux); + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -248,7 +356,7 @@ public partial class FileSafetyTests [InlineData("@@abcde/fo*o/bar", "@@abcde\\fo*o")] public void Returns_Rooted_Unsanitized_If_Directed_Windows(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OSPlatform.Windows); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -264,7 +372,7 @@ public partial class FileSafetyTests [InlineData("@@abcde/fo*o/bar", "@@abcde/fo*o")] public void Returns_Rooted_Unsanitized_If_Directed_Linux(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OSPlatform.Linux); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OperatingSystem.Linux); Assert.Equal(expected, result); } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs index 93acaf42..59ba2b54 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs @@ -1,8 +1,7 @@ -using System.Runtime.InteropServices; -using Xunit; - namespace slskd.Tests.Unit.Common; +using Xunit; + public partial class FileSafetyTests { public class GetFileNameSafelyTests @@ -73,7 +72,7 @@ public partial class FileSafetyTests [Fact] public void Sanitize_True_Replaces_InvalidCharacters_On_Windows() { - var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true, os: OSPlatform.Windows); + var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true, os: OperatingSystem.Windows); Assert.Equal("file_name.flac", result); } @@ -81,7 +80,7 @@ public partial class FileSafetyTests [Fact] public void Sanitize_True_Replaces_InvalidCharacters_On_Linux() { - var result = FileSafety.GetFileNameSafely("Music\\file\0name.flac", sanitize: true, os: OSPlatform.Linux); + var result = FileSafety.GetFileNameSafely("Music\\file\0name.flac", sanitize: true, os: OperatingSystem.Linux); Assert.Equal("file_name.flac", result); } @@ -89,7 +88,7 @@ public partial class FileSafetyTests [Fact] public void Sanitize_False_Preserves_InvalidCharacters_On_Windows() { - var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: false, os: OSPlatform.Windows); + var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: false, os: OperatingSystem.Windows); Assert.Equal("file:name.flac", result); } @@ -97,7 +96,7 @@ public partial class FileSafetyTests [Fact] public void Sanitize_False_Preserves_InvalidCharacters_On_Linux() { - var result = FileSafety.GetFileNameSafely("Music\\file\0name.flac", sanitize: false, os: OSPlatform.Linux); + var result = FileSafety.GetFileNameSafely("Music\\file\0name.flac", sanitize: false, os: OperatingSystem.Linux); Assert.Equal("file\0name.flac", result); } @@ -105,10 +104,92 @@ public partial class FileSafetyTests [Fact] public void Default_Sanitize_Is_True() { - var resultDefault = FileSafety.GetFileNameSafely("Music\\file:name.flac", os: OSPlatform.Windows); - var resultExplicit = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true, os: OSPlatform.Windows); + var resultDefault = FileSafety.GetFileNameSafely("Music\\file:name.flac", os: OperatingSystem.Windows); + var resultExplicit = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true, os: OperatingSystem.Windows); Assert.Equal(resultExplicit, resultDefault); } + + [Fact] + public void NullOs_UsesPlatformDefault_DoesNotThrow() + { + var result = FileSafety.GetFileNameSafely("Music/song.flac"); + + Assert.Equal("song.flac", result); + } + + [Theory] + [InlineData(".")] + [InlineData("..")] + public void Sanitize_True_Replaces_BareTraversalFilename(string input) + { + var result = FileSafety.GetFileNameSafely(input, sanitize: true); + + Assert.Equal("_", result); + } + + [Theory] + [InlineData(".")] + [InlineData("..")] + public void Sanitize_False_Preserves_BareTraversalFilename(string input) + { + var result = FileSafety.GetFileNameSafely(input, sanitize: false); + + Assert.Equal(input, result); + } + + [Theory] + [InlineData("foo/.")] + [InlineData("foo/..")] + [InlineData("foo\\..")] + public void Sanitize_True_Replaces_Traversal_As_Last_Path_Segment(string input) + { + var result = FileSafety.GetFileNameSafely(input, sanitize: true); + + Assert.Equal("_", result); + } + + [Theory] + [InlineData("foo/.", ".")] + [InlineData("foo/..", "..")] + [InlineData("foo\\..", "..")] + public void Sanitize_False_Preserves_Traversal_As_Last_Path_Segment(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input, sanitize: false); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo//bar.flac", "bar.flac")] + [InlineData("foo\\\\bar.flac", "bar.flac")] + public void Returns_Filename_Given_Double_Separator(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde/song.flac", "song.flac")] + [InlineData("@@abcde\\song.flac", "song.flac")] + [InlineData("@@abcdefgh/Music/song.flac", "song.flac")] + public void Returns_Filename_Given_SoulseekQt_Prefixed_Path_Linux(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde\\song.flac", "song.flac")] + [InlineData("@@abcde/song.flac", "song.flac")] + [InlineData("@@abcdefgh\\Music\\song.flac", "song.flac")] + public void Returns_Filename_Given_SoulseekQt_Prefixed_Path_Windows(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } } }
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs index 42eab9b8..771a1ea0 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs @@ -1,8 +1,7 @@ -using System.Runtime.InteropServices; -using Xunit; - namespace slskd.Tests.Unit.Common; +using Xunit; + public partial class FileSafetyTests { public class IsPathTests @@ -23,6 +22,9 @@ public partial class FileSafetyTests [InlineData("C:\\Users\\Ünïcödé\\Music")] [InlineData("C:\\Users\\пользователь\\Музыка")] [InlineData("C:\\Users\\用户\\音乐")] + // lowercase drive letters + [InlineData("c:\\Music")] + [InlineData("a:/path")] // UNC paths (\\ prefix) [InlineData("\\\\server\\share")] [InlineData("\\\\server\\share\\folder")] @@ -31,10 +33,11 @@ public partial class FileSafetyTests [InlineData("\\\\server\\Ünïcödé")] [InlineData("\\\\server\\share\\пользователь")] [InlineData("\\\\server\\share\\用户\\音乐")] + [InlineData("\\\\server")] public void IsAbsolute_NotRelative(string path) { - Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.Windows)); - Assert.False(FileSafety.IsPathRelative(path, OSPlatform.Windows)); + Assert.True(FileSafety.IsPathAbsolute(path, OperatingSystem.Windows)); + Assert.False(FileSafety.IsPathRelative(path, OperatingSystem.Windows)); } } @@ -59,17 +62,18 @@ public partial class FileSafetyTests [InlineData(".")] [InlineData("Ünïcödé")] [InlineData("пользователь/Музыка")] - [InlineData("/Music")] // root-relative — no drive letter, not absolute on Windows - [InlineData("\\Music")] // root-relative — no drive letter, not absolute on Windows - [InlineData("/home/user")] // Unix-style — not recognised as absolute on Windows - [InlineData("//server/share")] // Unix UNC — not recognised as absolute on Windows - [InlineData("C:")] // bare drive letter — length < 3, not absolute - [InlineData("C:Music")] // drive-relative — no separator after colon, not absolute - [InlineData("D:path")] // drive-relative — no separator after colon, not absolute + [InlineData("/Music")] + [InlineData("\\Music")] + [InlineData("/home/user")] + [InlineData("//server/share")] + [InlineData("//server")] + [InlineData("C:")] + [InlineData("C:Music")] + [InlineData("D:path")] public void IsRelative_NotAbsolute(string path) { - Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.Windows)); - Assert.True(FileSafety.IsPathRelative(path, OSPlatform.Windows)); + Assert.False(FileSafety.IsPathAbsolute(path, OperatingSystem.Windows)); + Assert.True(FileSafety.IsPathRelative(path, OperatingSystem.Windows)); } } } @@ -95,8 +99,8 @@ public partial class FileSafetyTests [InlineData("//192.168.1.1/share")] public void IsAbsolute_NotRelative(string path) { - Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.Linux)); - Assert.False(FileSafety.IsPathRelative(path, OSPlatform.Linux)); + Assert.True(FileSafety.IsPathAbsolute(path, OperatingSystem.Linux)); + Assert.False(FileSafety.IsPathRelative(path, OperatingSystem.Linux)); } } @@ -116,14 +120,14 @@ public partial class FileSafetyTests [InlineData(".")] [InlineData("Ünïcödé")] [InlineData("пользователь/Музыка")] - [InlineData("C:\\Music")] // Windows drive-letter — not absolute on Linux - [InlineData("C:/Music")] // Windows drive-letter — not absolute on Linux - [InlineData("\\\\server\\share")] // Windows UNC — not absolute on Linux - [InlineData("\\Music")] // Windows root-relative — not absolute on Linux + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("\\\\server\\share")] + [InlineData("\\Music")] public void IsRelative_NotAbsolute(string path) { - Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.Linux)); - Assert.True(FileSafety.IsPathRelative(path, OSPlatform.Linux)); + Assert.False(FileSafety.IsPathAbsolute(path, OperatingSystem.Linux)); + Assert.True(FileSafety.IsPathRelative(path, OperatingSystem.Linux)); } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index 97a64d6c..f0fc196c 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -20,9 +20,11 @@ public partial class FileSafetyTests [InlineData("C:\\Windows\\foo", "C:/Windows/foo")] [InlineData("C:/Windows/foo", "C:/Windows/foo")] [InlineData("", "")] + [InlineData("/", "/")] + [InlineData("\\", "/")] public void Linux_NormalizesToForwardSlash(string input, string expected) { - var result = FileSafety.LocalizePath(input, OSPlatform.Linux); + var result = FileSafety.LocalizePath(input, OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -40,9 +42,11 @@ public partial class FileSafetyTests [InlineData("C:\\Windows\\foo", "C:\\Windows\\foo")] [InlineData("C:/Windows/foo", "C:\\Windows\\foo")] [InlineData("", "")] + [InlineData("/", "\\")] + [InlineData("\\", "\\")] public void Windows_NormalizesToBackslash(string input, string expected) { - var result = FileSafety.LocalizePath(input, OSPlatform.Windows); + var result = FileSafety.LocalizePath(input, OperatingSystem.Windows); Assert.Equal(expected, result); } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs index 618e691e..c53b95fc 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs @@ -24,7 +24,7 @@ public partial class FileSafetyTests public void Throws_Given_OsInvalid_Replacement_On_Unix() { // '\0' is invalid on Unix but not caught by the slash guard - var ex = Record.Exception(() => FileSafety.SanitizeFilename("file", '\0', OSPlatform.Linux)); + var ex = Record.Exception(() => FileSafety.SanitizeFilename("file", '\0', OperatingSystem.Linux)); Assert.NotNull(ex); Assert.IsType<ArgumentException>(ex); @@ -35,7 +35,7 @@ public partial class FileSafetyTests public void Throws_Given_OsInvalid_Replacement_On_Windows() { // '*' is invalid on Windows but not caught by the slash guard - var ex = Record.Exception(() => FileSafety.SanitizeFilename("file", '*', OSPlatform.Windows)); + var ex = Record.Exception(() => FileSafety.SanitizeFilename("file", '*', OperatingSystem.Windows)); Assert.NotNull(ex); Assert.IsType<ArgumentException>(ex); @@ -58,7 +58,7 @@ public partial class FileSafetyTests [InlineData("пользователь", "пользователь")] public void Linux_ReturnsUnchanged_Given_Safe_Filename(string input, string expected) { - var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Linux); + var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -69,7 +69,7 @@ public partial class FileSafetyTests [InlineData("trailing\0", "trailing_")] public void Linux_Replaces_NullByte(string input, string expected) { - var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Linux); + var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -80,7 +80,7 @@ public partial class FileSafetyTests [InlineData("has/both\\types", "has_both_types")] public void Linux_Replaces_Slashes(string input, string expected) { - var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Linux); + var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -92,7 +92,7 @@ public partial class FileSafetyTests [InlineData("\\\\server\\share", "__server_share")] public void Linux_Sanitizes_Full_Paths(string input, string expected) { - var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Linux); + var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -100,7 +100,7 @@ public partial class FileSafetyTests [Fact] public void Linux_Uses_Custom_Replacement() { - var result = FileSafety.SanitizeFilename("has/slash", '-', OSPlatform.Linux); + var result = FileSafety.SanitizeFilename("has/slash", '-', OperatingSystem.Linux); Assert.Equal("has-slash", result); } @@ -116,7 +116,7 @@ public partial class FileSafetyTests [InlineData("file/name", "file_name")] public void Windows_Replaces_InvalidCharacters(string input, string expected) { - var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Windows); + var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -128,7 +128,7 @@ public partial class FileSafetyTests [InlineData("\\\\server\\share", "__server_share")] public void Windows_Sanitizes_Full_Paths(string input, string expected) { - var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Windows); + var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -137,7 +137,7 @@ public partial class FileSafetyTests public void Windows_Replaces_ControlCharacters() { var input = "file\x01\x1fname"; - var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Windows); + var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.Windows); Assert.Equal("file__name", result); } @@ -148,17 +148,41 @@ public partial class FileSafetyTests [InlineData("My Artist", "My Artist")] public void Windows_ReturnsUnchanged_Given_Safe_Filename(string input, string expected) { - var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Windows); + var result = FileSafety.SanitizeFilename(input, '_', OperatingSystem.Windows); Assert.Equal(expected, result); } [Fact] + public void Linux_Accepts_Period_As_Replacement() + { + var result = FileSafety.SanitizeFilename("file\0name", '.', OperatingSystem.Linux); + + Assert.Equal("file.name", result); + } + + [Fact] + public void Windows_Accepts_Period_As_Replacement() + { + var result = FileSafety.SanitizeFilename("file*name", '.', OperatingSystem.Windows); + + Assert.Equal("file.name", result); + } + + [Fact] public void Returns_Null_Given_Null() { var result = FileSafety.SanitizeFilename(null); Assert.Null(result); } + + [Fact] + public void Returns_EmptyString_Given_EmptyString() + { + var result = FileSafety.SanitizeFilename(string.Empty); + + Assert.Equal(string.Empty, result); + } } }
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs index ecf5bdf9..230c9a89 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -1,9 +1,9 @@ using System; -using System.Runtime.InteropServices; -using Xunit; namespace slskd.Tests.Unit.Common; +using Xunit; + public partial class FileSafetyTests { public class SanitizePathSegmentTests @@ -66,7 +66,7 @@ public partial class FileSafetyTests [InlineData("пользователь", "пользователь")] public void Linux_ReturnsUnchanged_Given_Safe_Segment(string input, string expected) { - var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Linux); + var result = FileSafety.SanitizePathSegment(input, '_', OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -77,7 +77,7 @@ public partial class FileSafetyTests [InlineData("has/both\\types", "has_both_types")] public void Linux_Replaces_Slashes(string input, string expected) { - var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Linux); + var result = FileSafety.SanitizePathSegment(input, '_', OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -91,7 +91,7 @@ public partial class FileSafetyTests [InlineData("file\\name", "file_name")] public void Windows_Replaces_InvalidCharacters(string input, string expected) { - var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Windows); + var result = FileSafety.SanitizePathSegment(input, '_', OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -103,5 +103,40 @@ public partial class FileSafetyTests Assert.Null(result); } + + [Fact] + public void Returns_EmptyString_Given_EmptyString() + { + var result = FileSafety.SanitizePathSegment(string.Empty); + + Assert.Equal(string.Empty, result); + } + + [Fact] + public void NullOs_UsesPlatformDefault_DoesNotThrow() + { + var result = FileSafety.SanitizePathSegment("safe_segment"); + + Assert.NotNull(result); + } + + [Theory] + [InlineData("*")] + [InlineData("*?")] + [InlineData("*.")] // one invalid char + one period → ".." + public void Windows_Returns_EmptyString_When_Period_Replacement_Produces_Traversal(string input) + { + var result = FileSafety.SanitizePathSegment(input, replacement: '.', os: OperatingSystem.Windows); + + Assert.Equal(string.Empty, result); + } + + [Fact] + public void Linux_Returns_EmptyString_When_Period_Replacement_Produces_Traversal() + { + var result = FileSafety.SanitizePathSegment("\0", replacement: '.', os: OperatingSystem.Linux); + + Assert.Equal(string.Empty, result); + } } }
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index 5848b5f0..61233e44 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -1,9 +1,7 @@ -using System; -using System.Runtime.InteropServices; -using Xunit; - namespace slskd.Tests.Unit.Common; +using Xunit; + public partial class FileSafetyTests { public class SanitizePathTests @@ -21,9 +19,11 @@ public partial class FileSafetyTests [InlineData("foo\\bar", "foo/bar")] [InlineData("Artist/Album/song.flac", "Artist/Album/song.flac")] [InlineData("Ünïcödé/пользователь", "Ünïcödé/пользователь")] + [InlineData("foo//bar", "foo/bar")] + [InlineData("foo\\\\bar", "foo/bar")] public void Linux_NormalizesSlashes(string input, string expected) { - var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -32,91 +32,16 @@ public partial class FileSafetyTests [InlineData("foo/bar", "foo\\bar")] [InlineData("foo\\bar", "foo\\bar")] [InlineData("Artist/Album/song.flac", "Artist\\Album\\song.flac")] + [InlineData("foo//bar", "foo\\bar")] + [InlineData("foo\\\\bar", "foo\\bar")] public void Windows_NormalizesSlashes(string input, string expected) { - var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); - - Assert.Equal(expected, result); - } - - [Theory] - [InlineData("C:\\Music\\Artist", "Music\\Artist")] - [InlineData("C:/Music/Artist", "Music\\Artist")] - [InlineData("D:\\path\\to\\file", "path\\to\\file")] - [InlineData("Z:\\", "")] - public void Windows_Strips_DriveRoot(string input, string expected) - { - var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); - - Assert.Equal(expected, result); - } - - [Theory] - [InlineData("C:\\Music\\Artist", "Music/Artist")] - [InlineData("C:/Music/Artist", "Music/Artist")] - [InlineData("D:\\path", "path")] - public void Linux_Strips_DriveRoot(string input, string expected) - { - var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); - - Assert.Equal(expected, result); - } - - [Theory] - [InlineData("\\\\server\\share\\Music", "share\\Music")] - [InlineData("\\\\server\\Music", "Music")] - [InlineData("\\\\192.168.1.1\\share\\folder", "share\\folder")] - public void Windows_Strips_UncRoot(string input, string expected) - { - var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); - - Assert.Equal(expected, result); - } - - [Theory] - [InlineData("//server/share/Music", "share/Music")] - [InlineData("//server/Music", "Music")] - [InlineData("//192.168.1.1/share/folder", "share/folder")] - public void Linux_Strips_UncRoot(string input, string expected) - { - var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); - - Assert.Equal(expected, result); - } - - [Theory] - [InlineData("@@abcde/Music/Artist", "Music/Artist")] - [InlineData("@@abcdefgh/Music", "Music")] - [InlineData("@@abcde\\Music\\Artist", "Music/Artist")] - public void Linux_Strips_SoulseekQtPrefix(string input, string expected) - { - var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OperatingSystem.Windows); Assert.Equal(expected, result); } [Theory] - [InlineData("@@abcde\\Music\\Artist", "Music\\Artist")] - [InlineData("@@abcdefgh\\Music", "Music")] - [InlineData("@@abcde/Music/Artist", "Music\\Artist")] - public void Windows_Strips_SoulseekQtPrefix(string input, string expected) - { - var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); - - Assert.Equal(expected, result); - } - - [Theory] - [InlineData("@@abc/Music")] // only 3 alphanumeric chars — does not match - [InlineData("@@abcd/Music")] // only 4 — does not match - public void DoesNotStrip_SoulseekQtPrefix_When_Prefix_Too_Short(string input) - { - var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); - - Assert.StartsWith("@@", result); - } - - [Theory] [InlineData("foo/../bar", "foo/_/bar")] [InlineData("foo/./bar", "foo/_/bar")] [InlineData("../etc", "_/etc")] @@ -125,7 +50,7 @@ public partial class FileSafetyTests [InlineData("foo/.", "foo/_")] public void Linux_Replaces_TraversalSegments(string input, string expected) { - var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -136,7 +61,7 @@ public partial class FileSafetyTests [InlineData("..\\etc", "_\\etc")] public void Windows_Replaces_TraversalSegments(string input, string expected) { - var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -144,7 +69,7 @@ public partial class FileSafetyTests [Fact] public void Linux_Replaces_InvalidFilenameChars_In_Segments() { - var result = FileSafety.SanitizePath("seg\0ment/file\0name", os: OSPlatform.Linux); + var result = FileSafety.SanitizePath("seg\0ment/file\0name", os: OperatingSystem.Linux); Assert.Equal("seg_ment/file_name", result); } @@ -152,7 +77,7 @@ public partial class FileSafetyTests [Fact] public void Windows_Replaces_InvalidFilenameChars_In_Segments() { - var result = FileSafety.SanitizePath("seg*ment\\file:name", os: OSPlatform.Windows); + var result = FileSafety.SanitizePath("seg*ment\\file:name", os: OperatingSystem.Windows); Assert.Equal("seg_ment\\file_name", result); } @@ -160,7 +85,7 @@ public partial class FileSafetyTests [Fact] public void Uses_Custom_Replacement() { - var result = FileSafety.SanitizePath("foo/../bar", replacement: '-', os: OSPlatform.Linux); + var result = FileSafety.SanitizePath("foo/../bar", replacement: '-', os: OperatingSystem.Linux); Assert.Equal("foo/-/bar", result); } @@ -173,97 +98,72 @@ public partial class FileSafetyTests Assert.Null(result); } - // --- retainRoot: true --- - // These verify that SanitizePath honours retainRoot. The UNC and single-slash absolute - // cases are EXPECTED TO FAIL: SanitizePath filters empty segments produced by splitting on - // leading slashes, so "//server/share" becomes "server/share" — the root is silently lost. - // Drive-letter and @@-prefix cases pass because they produce no empty segments. - - - [Theory] - [InlineData("C:/Music/Artist", "C:/Music/Artist")] - [InlineData("C:\\Music\\Artist", "C:/Music/Artist")] - public void Linux_RetainsDriveRoot_When_RetainRoot_True(string input, string expected) - { - var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); - - Assert.Equal(expected, result); - } - - [Theory] - [InlineData("C:\\Music\\Artist", "C_\\Music\\Artist")] - [InlineData("C:/Music/Artist", "C_\\Music\\Artist")] - public void Windows_RetainsDriveRoot_When_RetainRoot_True(string input, string expected) + [Fact] + public void Returns_EmptyString_Given_EmptyString() { - var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(string.Empty); - Assert.Equal(expected, result); + Assert.Equal(string.Empty, result); } [Theory] - [InlineData("@@abcde/Music/Artist", "@@abcde/Music/Artist")] - [InlineData("@@abcde\\Music\\Artist", "@@abcde/Music/Artist")] - public void Linux_RetainsSoulseekQtPrefix_When_RetainRoot_True(string input, string expected) + [InlineData("/foo/bar")] + [InlineData("//foo/bar")] + [InlineData("\\foo\\bar")] + [InlineData("\\\\foo\\bar")] + public void Linux_NeverReturns_LeadingSlash(string input) { - var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OperatingSystem.Linux); - Assert.Equal(expected, result); + Assert.False(result.StartsWith('/') || result.StartsWith('\\')); } [Theory] - [InlineData("@@abcde\\Music\\Artist", "@@abcde\\Music\\Artist")] - [InlineData("@@abcde/Music/Artist", "@@abcde\\Music\\Artist")] - public void Windows_RetainsSoulseekQtPrefix_When_RetainRoot_True(string input, string expected) + [InlineData("/foo/bar")] + [InlineData("//foo/bar")] + [InlineData("\\foo\\bar")] + [InlineData("\\\\foo\\bar")] + public void Windows_NeverReturns_LeadingSlash(string input) { - var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OperatingSystem.Windows); - Assert.Equal(expected, result); + Assert.False(result.StartsWith('/') || result.StartsWith('\\')); } - [Theory] - [InlineData("//server/share/Music", "//server/share/Music")] - [InlineData("//server/Music", "//server/Music")] - [InlineData("\\\\server\\share\\Music", "//server/share/Music")] - [InlineData("\\\\server\\Music", "//server/Music")] - public void Linux_RetainsUncRoot_When_RetainRoot_True(string input, string expected) + [Fact] + public void Linux_NeverReturns_LeadingSlash_When_First_Segment_Sanitizes_To_Empty() { - var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + // '\0' replaced with '.' produces "." — SanitizePathSegment converts that to "" + // joining ["", "foo"] with '/' would yield "/foo" without a guard + var result = FileSafety.SanitizePath("\0/foo", replacement: '.', os: OperatingSystem.Linux); - Assert.Equal(expected, result); + Assert.False(result.StartsWith('/') || result.StartsWith('\\')); } [Theory] - [InlineData("/absolute/Music", "/absolute/Music")] - [InlineData("/single", "/single")] - [InlineData("\\absolute\\Music", "/absolute/Music")] - [InlineData("\\single", "/single")] - public void Linux_RetainsAbsoluteRoot_When_RetainRoot_True(string input, string expected) + [InlineData("../..")] + [InlineData("./.")] + public void Linux_Replaces_All_Traversal_Segments(string input) { - var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OperatingSystem.Linux); - Assert.Equal(expected, result); + Assert.Equal("_/_", result); } - [Theory] - [InlineData("\\\\server\\share\\Music", "\\\\server\\share\\Music")] - [InlineData("\\\\server\\Music", "\\\\server\\Music")] - [InlineData("//server/share/Music", "\\\\server\\share\\Music")] - [InlineData("//server/Music", "\\\\server\\Music")] - public void Windows_RetainsUncRoot_When_RetainRoot_True(string input, string expected) + [Fact] + public void Linux_Handles_SoulseekQt_Prefixed_Path() { - var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + var result = FileSafety.SanitizePath("@@abcde/foo/bar", os: OperatingSystem.Linux); - Assert.Equal(expected, result); + Assert.Equal("@@abcde/foo/bar", result); } - [Theory] - [InlineData("\\absolute\\Music", "\\absolute\\Music")] - [InlineData("/absolute/Music", "\\absolute\\Music")] - public void Windows_RetainsDriveRelativeRoot_When_RetainRoot_True(string input, string expected) + [Fact] + public void Windows_Sanitizes_Colon_In_Drive_Like_Segment() { - var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + var result = FileSafety.SanitizePath("C:/Music/song.flac", os: OperatingSystem.Windows); - Assert.Equal(expected, result); + Assert.Equal("C_\\Music\\song.flac", result); } } }
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs index a3641f8b..d547843b 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs @@ -34,7 +34,7 @@ public partial class FileSafetyTests [InlineData("A:/single", "single")] public void Linux_Strips_DriveRoot(string input, string expected) { - var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + var result = FileSafety.StripPathRoot(input, OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -48,7 +48,7 @@ public partial class FileSafetyTests [InlineData("c:\\Music", "Music")] public void Windows_Strips_DriveRoot(string input, string expected) { - var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + var result = FileSafety.StripPathRoot(input, OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -60,7 +60,7 @@ public partial class FileSafetyTests [InlineData("//server", "")] // no path after server public void Linux_Strips_UncRoot(string input, string expected) { - var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + var result = FileSafety.StripPathRoot(input, OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -69,10 +69,22 @@ public partial class FileSafetyTests [InlineData("\\\\server\\share\\Music", "share\\Music")] [InlineData("\\\\server\\Music", "Music")] [InlineData("\\\\192.168.1.1\\share\\folder", "share\\folder")] - [InlineData("\\\\server", "")] // no path after server + [InlineData("\\\\server", "")] // no path after server public void Windows_Strips_UncRoot(string input, string expected) { - var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + var result = FileSafety.StripPathRoot(input, OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("//server/share/Music", "share\\Music")] + [InlineData("//server/Music", "Music")] + [InlineData("//192.168.1.1/share/folder", "share\\folder")] + [InlineData("//server", "")] + public void Windows_Strips_ForwardSlash_UncRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -83,7 +95,7 @@ public partial class FileSafetyTests [InlineData("@@abcde\\Music\\Artist", "Music/Artist")] public void Linux_Strips_SoulseekQtPrefix(string input, string expected) { - var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + var result = FileSafety.StripPathRoot(input, OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -94,7 +106,7 @@ public partial class FileSafetyTests [InlineData("@@abcde/Music/Artist", "Music\\Artist")] public void Windows_Strips_SoulseekQtPrefix(string input, string expected) { - var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + var result = FileSafety.StripPathRoot(input, OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -104,11 +116,29 @@ public partial class FileSafetyTests [InlineData("@@abcd/Music")] // only 4 — does not match public void DoesNotStrip_SoulseekQtPrefix_When_Prefix_Too_Short(string input) { - var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + var result = FileSafety.StripPathRoot(input, OperatingSystem.Linux); Assert.StartsWith("@@", result); } + [Fact] + public void Linux_Strips_Bare_SoulseekQtPrefix_Returning_Empty() + { + var result = FileSafety.StripPathRoot("@@abcde", OperatingSystem.Linux); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("/")] + [InlineData("//")] + public void Linux_ReturnsUnchanged_Given_Slash_Only_Path(string input) + { + var result = FileSafety.StripPathRoot(input, OperatingSystem.Linux); + + Assert.Equal(input, result); + } + [Theory] [InlineData("Music/Artist", "Music/Artist")] [InlineData("Artist/Album/song.flac", "Artist/Album/song.flac")] @@ -117,7 +147,7 @@ public partial class FileSafetyTests [InlineData("foo", "foo")] public void Linux_ReturnsUnchanged_Given_Relative_Path(string input, string expected) { - var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + var result = FileSafety.StripPathRoot(input, OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -129,7 +159,7 @@ public partial class FileSafetyTests [InlineData("foo", "foo")] public void Windows_ReturnsUnchanged_Given_Relative_Path(string input, string expected) { - var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + var result = FileSafety.StripPathRoot(input, OperatingSystem.Windows); Assert.Equal(expected, result); } @@ -140,7 +170,7 @@ public partial class FileSafetyTests [InlineData("/single", "/single")] public void Linux_ReturnsUnchanged_Given_Single_ForwardSlash_Prefix(string input, string expected) { - var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + var result = FileSafety.StripPathRoot(input, OperatingSystem.Linux); Assert.Equal(expected, result); } @@ -150,7 +180,7 @@ public partial class FileSafetyTests [InlineData("\\home\\user", "\\home\\user")] public void Windows_ReturnsUnchanged_Given_Single_BackwardSlash_Prefix(string input, string expected) { - var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + var result = FileSafety.StripPathRoot(input, OperatingSystem.Windows); Assert.Equal(expected, result); } diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs index b1375e45..beaecd9c 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs @@ -1,5 +1,6 @@ +using System; using System.ComponentModel.DataAnnotations; -using System.Runtime.InteropServices; +using System.Reflection; using slskd.Validation; using Xunit; @@ -7,134 +8,312 @@ namespace slskd.Tests.Unit.Common.Validation; public class AbsolutePathAttributeTests { - private static (bool IsValid, string ErrorMessage) Validate(string value, OSPlatform? os = null) + private static AbsolutePathAttribute CreateAttribute(OperatingSystem os, OperatingSystem? injected = null) { - var attribute = new AbsolutePathAttribute(os); - var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; - var result = attribute.GetValidationResult(value, context); - return (result == null, result?.ErrorMessage); + var attr = new AbsolutePathAttribute(os); + + if (injected.HasValue) + { + var field = typeof(AbsolutePathAttribute) + .GetField("<Injected>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance); + field.SetValue(attr, injected.Value); + } + + return attr; } - // paths can be null or empty; [Required] dictates whether they must be defined - [Fact] - public void Null_Passes() + private static (bool IsValid, string ErrorMessage) Validate(string value, OperatingSystem os, OperatingSystem? injected = null) { - var (isValid, _) = Validate(null); - Assert.True(isValid); + var attr = CreateAttribute(os, injected); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attr.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); } - [Fact] - public void EmptyString_Passes() + public class Constructor { - var (isValid, _) = Validate(string.Empty); - Assert.True(isValid); + [Fact] + public void AcceptsCurrentOsValue() + { + var ex = Record.Exception(() => _ = new AbsolutePathAttribute(OperatingSystem.Current)); + + Assert.Null(ex); + } + + [Fact] + public void AcceptsAnyOsValue() + { + var ex = Record.Exception(() => _ = new AbsolutePathAttribute(OperatingSystem.Any)); + + Assert.Null(ex); + } + + [Fact] + public void AcceptsAllOsValue() + { + var ex = Record.Exception(() => _ = new AbsolutePathAttribute(OperatingSystem.All)); + + Assert.Null(ex); + } + + [Fact] + public void ThrowsForWindowsOsValue() + { + Assert.Throws<ArgumentException>(() => new AbsolutePathAttribute(OperatingSystem.Windows)); + } + + [Fact] + public void ThrowsForLinuxOsValue() + { + Assert.Throws<ArgumentException>(() => new AbsolutePathAttribute(OperatingSystem.Linux)); + } + + [Fact] + public void ThrowsForNoneOsValue() + { + Assert.Throws<ArgumentException>(() => new AbsolutePathAttribute(OperatingSystem.None)); + } } - public class Windows + public class NullOrEmpty { [Theory] - [InlineData("C:\\Music")] - [InlineData("C:/Music")] - [InlineData("C:\\Music\\Artist\\Album")] - [InlineData("C:\\Music\\Artist/Album")] - [InlineData("C:/Music/My Artist")] - public void Windows_DriveLetterPaths_Pass(string value) + [InlineData(null)] + [InlineData("")] + public void Passes_ForCurrentWithWindowsInjected(string value) { - var (isValid, _) = Validate(value, OSPlatform.Windows); + var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Windows); Assert.True(isValid); } [Theory] - [InlineData("C:\\")] - [InlineData("Z:\\")] - [InlineData("C:/")] - public void Windows_RootPaths_Pass(string value) + [InlineData(null)] + [InlineData("")] + public void Passes_ForCurrentWithLinuxInjected(string value) { - var (isValid, _) = Validate(value, OSPlatform.Windows); + var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Linux); Assert.True(isValid); } [Theory] - [InlineData("\\\\server\\share")] - [InlineData("\\\\server\\share\\folder")] - [InlineData("\\\\192.168.1.1\\share")] - public void Windows_UNCPaths_Pass(string value) + [InlineData(null)] + [InlineData("")] + public void Passes_ForAny(string value) { - var (isValid, _) = Validate(value, OSPlatform.Windows); + var (isValid, _) = Validate(value, OperatingSystem.Any); Assert.True(isValid); } [Theory] - [InlineData("\\Music")] - [InlineData("/Music")] - [InlineData("/Music/Artist/Album")] - [InlineData("C:")] - [InlineData("C:Music")] - public void Windows_RootRelativePaths_Fail(string value) + [InlineData(null)] + [InlineData("")] + public void Passes_ForAll(string value) { - var (isValid, _) = Validate(value, OSPlatform.Windows); - Assert.False(isValid); + var (isValid, _) = Validate(value, OperatingSystem.All); + Assert.True(isValid); + } + } + + // Current mode: validates using only the injected (or actual current) OS + public class Current + { + public class WithWindowsInjected + { + [Theory] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\Music\\Artist\\Album")] + [InlineData("C:\\")] + [InlineData("Z:\\")] + [InlineData("\\\\server\\share")] + [InlineData("\\\\server\\share\\folder")] + [InlineData("\\\\192.168.1.1\\share")] + [InlineData("\\\\server")] // bare UNC (server only, no share) — StartsWith("\\") → absolute + public void AbsolutePaths_Pass(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Windows); + Assert.True(isValid); + } + + [Theory] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("music.flac")] + [InlineData("My Music")] + [InlineData("..")] + [InlineData(".hidden")] + [InlineData("...dir")] + [InlineData("\\Music")] // drive-relative on Windows, not absolute + [InlineData("/Music")] // same + [InlineData("/home/user")] // same — leading slash without drive letter is not absolute on Windows + [InlineData("//server/share")] // forward-slash UNC is not recognized as absolute on Windows + [InlineData("C:")] + [InlineData("C:Music")] + public void NonAbsolutePaths_Fail(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Windows); + Assert.False(isValid); + } + } + + public class WithLinuxInjected + { + [Theory] + [InlineData("/")] + [InlineData("/home")] + [InlineData("/home/user")] + [InlineData("/Music")] + [InlineData("//server/share")] + [InlineData("//192.168.1.1/share")] + public void AbsolutePaths_Pass(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Linux); + Assert.True(isValid); + } + + [Theory] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("music.flac")] + [InlineData("My Music")] + [InlineData("..")] + [InlineData(".hidden")] + [InlineData("...dir")] + [InlineData("C:\\Music")] // backslash paths are relative on Linux + [InlineData("C:/Music")] // starts with 'C', not '/' — relative on Linux + [InlineData("\\\\server\\share")] // backslash UNC is relative on Linux + [InlineData("\\")] + [InlineData("\\home")] + public void NonAbsolutePaths_Fail(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Linux); + Assert.False(isValid); + } + } + } + + public class ErrorMessages + { + [Fact] + public void Current_Message_MentionsCurrentOperatingSystem() + { + var (_, msg) = Validate("relative/path", OperatingSystem.Current, OperatingSystem.Windows); + Assert.Contains("current operating system", msg); + } + + [Fact] + public void Current_Message_IncludesFieldName() + { + var (_, msg) = Validate("relative/path", OperatingSystem.Current, OperatingSystem.Windows); + Assert.Contains("Field", msg); + } + + [Fact] + public void AnyAll_Message_MentionsAllOperatingSystems() + { + var (_, msg) = Validate("/home/user", OperatingSystem.Any); + Assert.Contains("all operating systems", msg); } } - public class Unix + // Any and All use identical logic: path must be absolute on both Windows and Linux. + // No common path satisfies this — Windows uses drive letters or \\ UNC, Linux uses /, + // and no single path form is recognized as absolute by both detection rules. + public class Any { + [Fact] + public void UsesAndLogic_NoPathCanEverPass_BecauseLinuxAndWindowsAbsoluteFormsAreIncompatible() + { + // If Any used OR-logic ("absolute on at least one OS"), a Linux-absolute path would pass. + // Any actually requires absolute on ALL checked OSes (AND-logic), identical to All. + // No path form satisfies both: Linux requires '/', Windows requires a drive letter or '\\'. + var (linuxAbsPath, _) = Validate("/home/user", OperatingSystem.Any); + var (winAbsPath, _) = Validate("C:\\Music", OperatingSystem.Any); + Assert.False(linuxAbsPath); + Assert.False(winAbsPath); + } + [Theory] - [InlineData("/")] - [InlineData("/home")] - [InlineData("/home/user")] - public void Unix_Paths_Pass(string value) + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("music.flac")] + [InlineData("..")] + [InlineData(".hidden")] + public void RelativePaths_Fail(string value) { - var (isValid, _) = Validate(value, OSPlatform.Linux); - Assert.True(isValid); + var (isValid, _) = Validate(value, OperatingSystem.Any); + Assert.False(isValid); } + // These are absolute on Windows but relative on Linux — fail because not absolute on both [Theory] - [InlineData("//server/share")] - [InlineData("//server/share/folder")] - [InlineData("//192.168.1.1/share")] - public void Unix_UNCPaths_Pass(string value) + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\")] + [InlineData("\\\\server\\share")] + public void WindowsAbsolutePaths_Fail(string value) { - var (isValid, _) = Validate(value, OSPlatform.Linux); - Assert.True(isValid); + var (isValid, _) = Validate(value, OperatingSystem.Any); + Assert.False(isValid); } + // These are absolute on Linux but relative on Windows — fail because not absolute on both [Theory] - [InlineData("\\")] - [InlineData("\\home")] - public void Unix_Backslash_Fail(string value) + [InlineData("/home/user")] + [InlineData("/Music")] + [InlineData("//server/share")] + [InlineData("/")] + public void LinuxAbsolutePaths_Fail(string value) { - var (isValid, _) = Validate(value, OSPlatform.Linux); + var (isValid, _) = Validate(value, OperatingSystem.Any); Assert.False(isValid); } } - public class Relative + public class All { [Theory] - [InlineData("subdir")] // simple name - [InlineData("sub/dir")] // forward slash - [InlineData("sub\\dir")] // backslash - [InlineData("Artist\\Album")] // multi-level - [InlineData("music.flac")] // file name with extension - [InlineData("My Music")] // spaces - [InlineData("Ünïcödé")] // latin extended, still relative - [InlineData("Artist/Album/Song")] // deep relative - [InlineData("...dir")] // three dots — relative, not traversal - [InlineData(".hidden")] // dotfile — relative, not traversal - [InlineData("..")] // traversal-like but fundamentally not absolute - [InlineData(".")] // current-dir but fundamentally not absolute - public void RelativePath_Fails(string value) - { - var (isValid, errorMessage) = Validate(value, OSPlatform.Linux); - + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("music.flac")] + [InlineData("..")] + [InlineData(".hidden")] + public void RelativePaths_Fail(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.All); Assert.False(isValid); - Assert.Equal("The Field field must be an absolute file path.", errorMessage); + } - var (isValid2, errorMessage2) = Validate(value, OSPlatform.Windows); + // These are absolute on Windows but relative on Linux — fail because not absolute on both + [Theory] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\")] + [InlineData("\\\\server\\share")] + public void WindowsAbsolutePaths_Fail(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.All); + Assert.False(isValid); + } - Assert.False(isValid2); - Assert.Equal("The Field field must be an absolute file path.", errorMessage2); + // These are absolute on Linux but relative on Windows — fail because not absolute on both + [Theory] + [InlineData("/home/user")] + [InlineData("/Music")] + [InlineData("//server/share")] + [InlineData("/")] + public void LinuxAbsolutePaths_Fail(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.All); + Assert.False(isValid); } } } diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index 1d480010..ea74f822 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -1,5 +1,6 @@ +using System; using System.ComponentModel.DataAnnotations; -using System.Runtime.InteropServices; +using System.Reflection; using slskd.Validation; using Xunit; @@ -7,139 +8,310 @@ namespace slskd.Tests.Unit.Common.Validation; public class RelativePathAttributeTests { - private static (bool IsValid, string ErrorMessage) Validate(string value, OSPlatform? os = null) + private static RelativePathAttribute CreateAttribute(OperatingSystem os, OperatingSystem? injected = null) { - var attribute = new RelativePathAttribute(os); - var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; - var result = attribute.GetValidationResult(value, context); - return (result == null, result?.ErrorMessage); + var attr = new RelativePathAttribute(os); + + if (injected.HasValue) + { + var field = typeof(RelativePathAttribute) + .GetField("<Injected>k__BackingField", BindingFlags.NonPublic | BindingFlags.Instance); + field.SetValue(attr, injected.Value); + } + + return attr; } - // paths can be null or empty; [Required] dictates whether they must be defined - [Fact] - public void Null_Passes() + private static (bool IsValid, string ErrorMessage) Validate(string value, OperatingSystem os, OperatingSystem? injected = null) { - var (isValid, _) = Validate(null); - Assert.True(isValid); + var attr = CreateAttribute(os, injected); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attr.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); } - [Fact] - public void EmptyString_Passes() + public class Constructor { - var (isValid, _) = Validate(string.Empty); - Assert.True(isValid); + [Fact] + public void AcceptsCurrentOsValue() + { + var ex = Record.Exception(() => _ = new RelativePathAttribute(OperatingSystem.Current)); + + Assert.Null(ex); + } + + [Fact] + public void AcceptsAnyOsValue() + { + var ex = Record.Exception(() => _ = new RelativePathAttribute(OperatingSystem.Any)); + + Assert.Null(ex); + } + + [Fact] + public void AcceptsAllOsValue() + { + var ex = Record.Exception(() => _ = new RelativePathAttribute(OperatingSystem.All)); + + Assert.Null(ex); + } + + [Fact] + public void ThrowsForWindowsOsValue() + { + Assert.Throws<ArgumentException>(() => new RelativePathAttribute(OperatingSystem.Windows)); + } + + [Fact] + public void ThrowsForLinuxOsValue() + { + Assert.Throws<ArgumentException>(() => new RelativePathAttribute(OperatingSystem.Linux)); + } + + [Fact] + public void ThrowsForNoneOsValue() + { + Assert.Throws<ArgumentException>(() => new RelativePathAttribute(OperatingSystem.None)); + } } - public class Relative + public class NullOrEmpty { [Theory] - [InlineData("subdir")] // simple name - [InlineData("sub/dir")] // forward slash - [InlineData("sub\\dir")] // backslash - [InlineData("Artist\\Album")] // multi-level - [InlineData("music.flac")] // file name with extension - [InlineData("My Music")] // spaces - [InlineData("Ünïcödé")] // latin extended, still relative - [InlineData("Artist/Album/Song")] // deep relative - [InlineData("...dir")] // three dots — relative, not traversal - [InlineData(".hidden")] // dotfile — relative, not traversal - [InlineData("..")] // traversal-like but fundamentally not absolute - [InlineData(".")] // current-dir but fundamentally not absolute - public void RelativePath_Passes(string value) - { - var (isValid, _) = Validate(value, OSPlatform.Linux); + [InlineData(null)] + [InlineData("")] + public void Passes_ForCurrentWithWindowsInjected(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Windows); + Assert.True(isValid); + } + [Theory] + [InlineData(null)] + [InlineData("")] + public void Passes_ForCurrentWithLinuxInjected(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Linux); Assert.True(isValid); + } - var (isValid2, _) = Validate(value, OSPlatform.Windows); + [Theory] + [InlineData(null)] + [InlineData("")] + public void Passes_ForAny(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.Any); + Assert.True(isValid); + } - Assert.True(isValid2); + [Theory] + [InlineData(null)] + [InlineData("")] + public void Passes_ForAll(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.All); + Assert.True(isValid); } } - public class Windows + public class ErrorMessages { - [Theory] - [InlineData("C:\\Music")] - [InlineData("C:/Music")] - [InlineData("C:\\Music\\Artist\\Album")] - [InlineData("C:\\Music\\Artist/Album")] - [InlineData("C:/Music/My Artist")] - public void Windows_DriveLetterPaths_Fail(string value) + [Fact] + public void Current_Message_IncludesFieldName() { - var (isValid, _) = Validate(value, OSPlatform.Windows); - - Assert.False(isValid); + var (_, msg) = Validate("C:\\Music", OperatingSystem.Current, OperatingSystem.Windows); + Assert.Contains("Field", msg); } - [Theory] - [InlineData("C:\\")] - [InlineData("Z:\\")] - [InlineData("C:/")] - public void Windows_RootPaths_Fail(string value) + [Fact] + public void Current_Message_Text() { - var (isValid, _) = Validate(value, OSPlatform.Windows); + var (_, msg) = Validate("C:\\Music", OperatingSystem.Current, OperatingSystem.Windows); + // Note: the implementation uses the same message for Current as for Any/All. + // "on all operating systems" is misleading here since Current only validates + // against the current (or injected) OS. + Assert.Equal("The Field field must be a relative path on the current operating system.", msg); + } - Assert.False(isValid); + [Fact] + public void AnyAll_Message_MentionsRelativePath() + { + var (_, msg) = Validate("C:\\Music", OperatingSystem.Any); + Assert.Contains("relative path", msg); } + } - [Theory] - [InlineData("\\\\server\\share")] - [InlineData("\\\\server\\share\\folder")] - [InlineData("\\\\192.168.1.1\\share")] - public void Windows_UNCPaths_Fail(string value) + // Current mode: validates using only the injected (or actual current) OS + public class Current + { + public class WithWindowsInjected { - var (isValid, _) = Validate(value, OSPlatform.Windows); + [Theory] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("music.flac")] + [InlineData("My Music")] + [InlineData("..")] + [InlineData(".hidden")] + [InlineData("...dir")] + [InlineData("/Music")] // drive-relative on Windows, not absolute + [InlineData("/home/user")] // same — leading slash without drive letter is not absolute on Windows + [InlineData("//server/share")] // forward-slash UNC is not recognized as absolute on Windows + public void RelativePaths_Pass(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Windows); + Assert.True(isValid); + } - Assert.False(isValid); + [Theory] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\Music\\Artist\\Album")] + [InlineData("C:\\")] + [InlineData("Z:\\")] + [InlineData("\\\\server\\share")] + [InlineData("\\\\server\\share\\folder")] + [InlineData("\\\\192.168.1.1\\share")] + [InlineData("\\\\server")] // bare UNC (server only, no share) — StartsWith("\\") → absolute + public void AbsolutePaths_Fail(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Windows); + Assert.False(isValid); + } } - [Theory] - [InlineData("\\Music")] - [InlineData("/Music")] - [InlineData("/Music/Artist/Album")] - [InlineData("C:")] - [InlineData("C:Music")] - public void Windows_RootRelativePaths_Pass(string value) + public class WithLinuxInjected { - var (isValid, _) = Validate(value, OSPlatform.Windows); + [Theory] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("music.flac")] + [InlineData("My Music")] + [InlineData("..")] + [InlineData(".hidden")] + [InlineData("...dir")] + [InlineData("C:\\Music")] // backslash paths are relative on Linux + [InlineData("C:/Music")] // starts with 'C', not '/' — relative on Linux + [InlineData("\\\\server\\share")] // backslash UNC is relative on Linux + public void RelativePaths_Pass(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Linux); + Assert.True(isValid); + } - Assert.True(isValid); + [Theory] + [InlineData("/")] + [InlineData("/home")] + [InlineData("/home/user")] + [InlineData("/Music")] + [InlineData("//server/share")] + [InlineData("//192.168.1.1/share")] + public void AbsolutePaths_Fail(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.Current, OperatingSystem.Linux); + Assert.False(isValid); + } } } - public class Unix + // Any and All use identical logic: path must be relative on both Windows and Linux + public class Any { [Theory] - [InlineData("/")] - [InlineData("/home")] - [InlineData("/home/user")] - public void Unix_Paths_Fail(string value) + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("music.flac")] + [InlineData("My Music")] + [InlineData("..")] + [InlineData(".hidden")] + [InlineData("...dir")] + public void TrulyRelativePaths_Pass(string value) { - var (isValid, _) = Validate(value, OSPlatform.Linux); + var (isValid, _) = Validate(value, OperatingSystem.Any); + Assert.True(isValid); + } + // These are absolute on Windows, so they fail even though they're relative on Linux + [Theory] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\Music\\Artist\\Album")] + [InlineData("C:\\")] + [InlineData("Z:\\")] + [InlineData("\\\\server\\share")] + [InlineData("\\\\server\\share\\folder")] + public void WindowsAbsolutePaths_Fail(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.Any); Assert.False(isValid); } + // These are absolute on Linux, so they fail even though they're relative on Windows [Theory] + [InlineData("/")] + [InlineData("/home")] + [InlineData("/home/user")] + [InlineData("/Music")] [InlineData("//server/share")] - [InlineData("//server/share/folder")] [InlineData("//192.168.1.1/share")] - public void Unix_UNCPaths_Fail(string value) + public void LinuxAbsolutePaths_Fail(string value) { - var (isValid, _) = Validate(value, OSPlatform.Linux); - + var (isValid, _) = Validate(value, OperatingSystem.Any); Assert.False(isValid); } + } + public class All + { [Theory] - [InlineData("\\")] - [InlineData("\\home")] - public void Unix_Backslash_Pass(string value) + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("music.flac")] + [InlineData("My Music")] + [InlineData("..")] + [InlineData(".hidden")] + [InlineData("...dir")] + public void TrulyRelativePaths_Pass(string value) { - var (isValid, _) = Validate(value, OSPlatform.Linux); - + var (isValid, _) = Validate(value, OperatingSystem.All); Assert.True(isValid); } + + // These are absolute on Windows, so they fail even though they're relative on Linux + [Theory] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\Music\\Artist\\Album")] + [InlineData("C:\\")] + [InlineData("Z:\\")] + [InlineData("\\\\server\\share")] + [InlineData("\\\\server\\share\\folder")] + public void WindowsAbsolutePaths_Fail(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.All); + Assert.False(isValid); + } + + // These are absolute on Linux, so they fail even though they're relative on Windows + [Theory] + [InlineData("/")] + [InlineData("/home")] + [InlineData("/home/user")] + [InlineData("/Music")] + [InlineData("//server/share")] + [InlineData("//192.168.1.1/share")] + public void LinuxAbsolutePaths_Fail(string value) + { + var (isValid, _) = Validate(value, OperatingSystem.All); + Assert.False(isValid); + } } } diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 137fd73e..f608467b 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -280,12 +280,12 @@ public class QueueDownloadBatchRequestTests [InlineData("\\\\server\\share")] // UNC public void AbsolutePath_Fails_Windows(string value) { - if (OperatingSystem.IsWindows()) + if (System.OperatingSystem.IsWindows()) { var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + Assert.Contains("must be a relative path", results[0].ErrorMessage); } } @@ -295,12 +295,12 @@ public class QueueDownloadBatchRequestTests [InlineData("//server/share")] // UNC public void AbsolutePath_Fails_Non_Windows(string value) { - if (!OperatingSystem.IsWindows()) + if (!System.OperatingSystem.IsWindows()) { var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + Assert.Contains("must be a relative path", results[0].ErrorMessage); } } diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs new file mode 100644 index 00000000..fcf3c45a --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -0,0 +1,608 @@ +namespace slskd.Tests.Unit.Transfers.Downloads; + +using System; +using System.IO; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Moq; +using slskd.Search; +using slskd.Transfers; +using slskd.Transfers.Downloads; +using Xunit; + +public partial class DownloadServiceTests +{ + public class DeriveDestination + { + [Fact] + public async Task Explicit_Destination_Takes_Precedence_Over_Subdirectory_Pattern() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "explicit-dir" } }; + var (service, _) = GetFixture("${SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("explicit-dir", result); + } + + [Fact] + public async Task Explicit_Destination_Tokens_Are_Not_Expanded() + { + // explicit destination is sanitized but not token-substituted + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "${SOURCE_USERNAME}" } }; + var (service, _) = GetFixture("${SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("${SOURCE_USERNAME}", result); + } + + [Fact] + public async Task Explicit_Destination_Is_Always_Relative() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "/etc/passwd" } }; + var (service, _) = GetFixture("irrelevant", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.IsPathAbsolute(result)); + } + + [Fact] + public async Task Explicit_Destination_Traversal_Segments_Do_Not_Survive() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "../../../etc/passwd" } }; + var (service, _) = GetFixture("irrelevant", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task Explicit_Destination_Null_Byte_Replaced() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "down\0loads" } }; + var (service, _) = GetFixture("irrelevant", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("down_loads", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Is_Substituted() + { + var (service, _) = GetFixture("${SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Pattern_Match_Is_Case_Insensitive() + { + var (service, _) = GetFixture("${source_username}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Forward_Slash_Replaced_With_Underscore() + { + var (service, _) = GetFixture("${SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "al/ice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_ice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Backslash_Replaced_With_Underscore() + { + var (service, _) = GetFixture("${SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "al\\ice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_ice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Null_Byte_Replaced_With_Underscore() + { + var (service, _) = GetFixture("${SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "al\0ice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_ice", result); + } + + [Theory] + [InlineData("al\\..\\ice")] + [InlineData("al/../ice")] + [InlineData("al\\../ice")] + [InlineData("al/..\\ice")] + public async Task SOURCE_USERNAME_Traversal_Segment_Periods_Remains_After_Replacing_Slashes_With_Underscore(string username) + { + var (service, _) = GetFixture("${SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = username, Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_.._ice", result); + } + + [Fact] + public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Backslash() + { + var (service, _) = GetFixture("${SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" }); + + Assert.Equal("album", result); + } + + [Fact] + public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Forward_Slash() + { + var (service, _) = GetFixture("${SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice/Music/album/track.mp3" }); + + Assert.Equal("album", result); + } + + [Fact] + public async Task SOURCE_DIRECTORY_Is_Empty_If_File_Is_In_Root() + { + var (service, _) = GetFixture("${SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" }); + + Assert.Equal(string.Empty, result); + } + + [Fact] + public async Task SOURCE_PATH_Is_Full_Directory_Of_Remote_Filename() + { + var (service, _) = GetFixture("${SOURCE_PATH}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" }); + + Assert.Equal(Path.Combine("@alice", "Music", "album"), result); + } + + [Fact] + public async Task SOURCE_PATH_Is_Empty_If_File_Is_In_Root() + { + var (service, _) = GetFixture("${SOURCE_PATH}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" }); + + Assert.Equal(string.Empty, result); + } + + [Fact] + public async Task SOURCE_PATH_And_SOURCE_DIRECTORY_Match_If_File_Is_In_One_Subdirectory() + { + var (service, _) = GetFixture("${SOURCE_PATH}-${SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("@alice-@alice", result); + } + + [Fact] + public async Task BATCH_ID_Is_Substituted_When_Batch_Exists() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId }; + var (service, _) = GetFixture("${BATCH_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal(batchId.ToString(), result); + } + + [Fact] + public async Task BATCH_ID_Is_Fallback_When_No_Batch() + { + var (service, _) = GetFixture("${BATCH_ID}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + Assert.Equal("unknown_batch_id", result); + } + + [Fact] + public async Task BATCH_ID_Is_Fallback_When_Batch_Id_Is_Empty_Guid() + { + var batch = new Batch { Id = Guid.Empty }; + var (service, _) = GetFixture("${BATCH_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = Guid.Empty }); + + Assert.Equal("unknown_batch_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Substituted_When_Batch_Has_External_Id() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "my-ext-id" } }; + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("my-ext-id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_No_Batch() + { + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Null() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = null } }; + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Whitespace() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = " " } }; + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Forward_Slash_In_Value_Replaced_With_Underscore() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo/bar" } }; + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Backslash_In_Value_Replaced_With_Underscore() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo\\bar" } }; + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Null_Byte_In_Value_Replaced_With_Underscore() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo\0bar" } }; + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Substituted_When_Search_Exists() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "some query" }; + var (service, _) = GetFixture("${SEARCH_ID}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal(searchId.ToString(), result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_No_Batch() + { + // no batch → SearchId is never consulted + var (service, _) = GetFixture("${SEARCH_ID}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_Batch_Has_No_SearchId() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = null }; + var (service, _) = GetFixture("${SEARCH_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_Search_Not_Found() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() }; + var (service, _) = GetFixture("${SEARCH_ID}", batch: batch, search: null); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_Search_ID_Is_Empty_Guid() + { + var searchId = Guid.Empty; + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "some query" }; + var (service, _) = GetFixture("${SEARCH_ID}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Substituted_When_Search_Exists() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo bar baz" }; + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo bar baz", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_No_Search() + { + var (service, _) = GetFixture("${SEARCH_TEXT}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Forward_Slash_In_Value_Replaced_With_Underscore() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo/bar" }; + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task SEARCH_TEXT_Backlash_In_Value_Replaced_With_Underscore() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo\\bar" }; + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task Batch_With_Null_Options_Falls_Through_To_Pattern() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = null }; + var (service, _) = GetFixture("${SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task Batch_With_Whitespace_Destination_Falls_Through_To_Pattern() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = " " } }; + var (service, _) = GetFixture("${SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task Pattern_Forward_Slash_Separator_Preserved_In_Output() + { + var (service, _) = GetFixture("${SOURCE_USERNAME}/downloads"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal(Path.Combine("alice", "downloads"), result); + } + + [Fact] + public async Task Pattern_Backslash_Separator_Preserved_In_Output() + { + var (service, _) = GetFixture("${SOURCE_USERNAME}\\downloads"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal(Path.Combine("alice", "downloads"), result); + } + + [Fact] + public async Task Pattern_Output_Is_Always_Relative() + { + var (service, _) = GetFixture("/etc/passwd"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.False(FileSafety.IsPathAbsolute(result)); + } + + [Fact] + public async Task Pattern_Traversal_Segments_Do_Not_Survive() + { + var (service, _) = GetFixture("../../../etc/passwd"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task Username_Containing_Traversal_Is_Safe() + { + // exact '..' in username must not produce a traversal segment in the final output + var (service, _) = GetFixture("${SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "..", Filename = "@alice\\track.mp3" }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task SEARCH_TEXT_Null_Byte_In_Value_Replaced_With_Underscore() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo\0bar" }; + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_Search_Not_Found() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() }; + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: null); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_Batch_Has_No_SearchId() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = null }; + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Empty() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "" }; + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Whitespace() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = " " }; + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Traversal_Segments_Do_Not_Survive() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "../evil" }; + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Empty_String() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "" } }; + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Traversal_Segments_Do_Not_Survive() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "../evil" } }; + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + } + + private static (DownloadService service, Mocks mocks) GetFixture( + string subdirectory = "${SOURCE_USERNAME}", + Batch batch = null, + Search search = null) + { + var mocks = new Mocks(subdirectory, batch, search); + var service = new DownloadService( + mocks.BatchService.Object, + mocks.SearchService.Object, + mocks.OptionsMonitor, + null, + new Mock<IDbContextFactory<TransfersDbContext>>().Object, + null, + null, + null, + null); + return (service, mocks); + } + + private class Mocks + { + public Mocks(string subdirectory = null, Batch batch = null, Search search = null) + { + OptionsMonitor = new TestOptionsMonitor<Options>(new Options + { + Transfers = new Options.TransfersOptions + { + Download = new Options.TransfersOptions.GlobalDownloadOptions + { + Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions + { + Subdirectory = subdirectory + } + } + } + }); + + BatchService.Setup(b => b.FindAsync(It.IsAny<Expression<Func<Batch, bool>>>())) + .ReturnsAsync(batch); + SearchService.Setup(s => s.FindAsync(It.IsAny<Expression<Func<Search, bool>>>(), It.IsAny<bool>())) + .ReturnsAsync(search); + } + + public Mock<IBatchService> BatchService { get; } = new(); + public Mock<ISearchService> SearchService { get; } = new(); + public TestOptionsMonitor<Options> OptionsMonitor { get; } + } +} diff --git a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj index d1e76222..7278bd6d 100644 --- a/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj +++ b/tests/slskd.Tests.Unit/slskd.Tests.Unit.csproj @@ -7,14 +7,14 @@ <ItemGroup>
<PackageReference Include="AutoFixture.Xunit2" Version="4.18.1" />
- <PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.8.0" />
+ <PackageReference Include="Microsoft.NET.Test.Sdk" Version="18.6.0" />
<PackageReference Include="Moq" Version="4.16.1" />
- <PackageReference Include="xunit" Version="2.6.6" />
- <PackageReference Include="xunit.runner.visualstudio" Version="2.5.6">
+ <PackageReference Include="xunit" Version="2.9.3" />
+ <PackageReference Include="xunit.runner.visualstudio" Version="3.1.5">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
- <PackageReference Include="coverlet.msbuild" Version="6.0.0">
+ <PackageReference Include="coverlet.msbuild" Version="10.0.1">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
|
