diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-05-16 08:47:11 -0500 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-05-16 08:47:11 -0500 |
| commit | dfffce208c34165b83e7b2a7192cbbc81cd3a47e (patch) | |
| tree | 6716a4cefe9194283678d9b788491fd8c31874ea | |
| parent | 5b9309b4dba91fe317f1c04bc02493cf3d1f18f3 (diff) | |
| parent | 014c9616e1e3120a729896ddd9bd701e7d84ec9d (diff) | |
| download | slskd-dfffce208c34165b83e7b2a7192cbbc81cd3a47e.tar.gz | |
Merge branch 'master' into dependabot/npm_and_yarn/src/web/babel/plugin-transform-modules-systemjs-7.29.4
22 files changed, 1963 insertions, 56 deletions
diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index e36a5539..e3d212f7 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -572,6 +572,14 @@ namespace slskd { Metrics.Enqueue.RequestsReceived.Inc(1); + // it shouldn't be possible for us to be sharing any such files, as share paths are required to be absolute and rooted + // if someone is requesting a file like this, something is either really wrong, or they are a bad actor + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt from user {Username} to enqueue a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", username, filename); + throw new DownloadEnqueueException("File not shared."); + } + /* circuit breaker/failsafe: @@ -1413,6 +1421,14 @@ namespace slskd /// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns> private async Task<IEnumerable<Soulseek.Directory>> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { + // we shouldn't be sharing any files with these segments because shares are required to be absolute and rooted + // if we see this, something has either gone really wrong, or someone is trying something funny + if (FileSafety.ContainsTraversalSegments(directory)) + { + Log.Warning("Suspicious attempt from user {Username} to list a directory containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", username, directory); + return []; + } + if (Users.IsBlacklisted(username, endpoint.Address)) { Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address); diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 77db91ef..e0d56511 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -390,9 +390,10 @@ namespace slskd /// <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 Path.Combine(baseDirectory, remoteFilename.ToLocalRelativeFilename()); + return FileSafety.CombineSafely(baseDirectory, remoteFilename.ToLocalRelativeFilename()); } /// <summary> @@ -445,6 +446,7 @@ namespace slskd /// </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)) @@ -465,7 +467,7 @@ namespace slskd var file = parts.Last().ReplaceInvalidFileNameCharacters(); var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters(); - return Path.Combine(directory, file); + return FileSafety.CombineSafely(directory, file); } /// <summary> diff --git a/src/slskd/Common/Exceptions/ConflictException.cs b/src/slskd/Common/Exceptions/ConflictException.cs new file mode 100644 index 00000000..c58708d0 --- /dev/null +++ b/src/slskd/Common/Exceptions/ConflictException.cs @@ -0,0 +1,75 @@ +// <copyright file="ConflictException.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 +{ + using System; + using System.Diagnostics.CodeAnalysis; + + /// <summary> + /// Represents errors that originate due to duplication. + /// </summary> + [ExcludeFromCodeCoverage] + public class ConflictException : Exception + { + /// <summary> + /// Initializes a new instance of the <see cref="ConflictException"/> class. + /// </summary> + public ConflictException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ConflictException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public ConflictException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="ConflictException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public ConflictException(string message, Exception innerException) + : base(message, innerException) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Exceptions/DuplicateException.cs b/src/slskd/Common/Exceptions/DuplicateException.cs new file mode 100644 index 00000000..da603d87 --- /dev/null +++ b/src/slskd/Common/Exceptions/DuplicateException.cs @@ -0,0 +1,75 @@ +// <copyright file="DuplicateException.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 +{ + using System; + using System.Diagnostics.CodeAnalysis; + + /// <summary> + /// Represents errors that originate due to duplication. + /// </summary> + [ExcludeFromCodeCoverage] + public class DuplicateException : Exception + { + /// <summary> + /// Initializes a new instance of the <see cref="DuplicateException"/> class. + /// </summary> + public DuplicateException() + : base() + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="DuplicateException"/> class with a specified error message. + /// </summary> + /// <param name="message">The message that describes the error.</param> + public DuplicateException(string message) + : base(message) + { + } + + /// <summary> + /// Initializes a new instance of the <see cref="DuplicateException"/> class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// </summary> + /// <param name="message">The message that describes the error.</param> + /// <param name="innerException"> + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// </param> + public DuplicateException(string message, Exception innerException) + : base(message, innerException) + { + } + } +}
\ No newline at end of file diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs new file mode 100644 index 00000000..f94b9c7b --- /dev/null +++ b/src/slskd/Common/FileSafety.cs @@ -0,0 +1,149 @@ +// <copyright file="FileSafety.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; + +using System; +using System.IO; +using System.Linq; + +/// <summary> +/// Utility functions to help safely work with paths from untrusted sources. +/// </summary> +public static class FileSafety +{ + /// <summary> + /// An alternative to <see cref="Path.Combine(string, string)"/> that disallows rooted segments in the second or + /// subsequent position, and disallows segments containing path traversal characters "." and "..". + /// </summary> + /// <param name="root">The root directory.</param> + /// <param name="segments">The segments to append.</param> + /// <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, params string[] segments) + { + // ensure no inputs are null. matches the behavior of Path.Combine() + if (string.IsNullOrWhiteSpace(root)) + { + throw new ArgumentNullException(nameof(root), $"Specified root directory is null or consists only of whitespace"); + } + + if (segments is null || segments.Any(s => s is null)) + { + throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); + } + + 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! + if (IsPathAbsolute(segment)) + { + throw new ArgumentException($"Rooted paths are not permitted in segments: '{segment}'"); + } + + var parts = segment.Split(Path.DirectorySeparatorChar, '\\', '/'); + + // 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 + if (parts.Any(s => s is "." or "..")) + { + throw new ArgumentException($"Path traversal is not permitted: '{segment}'"); + } + } + + var combined = Path.Combine(root, Path.Combine(segments)); + + // not sure how we could possibly get here, but if we do, throw. + if (!Path.GetFullPath(combined).StartsWith(Path.GetFullPath(root))) + { + throw new ArgumentException($"Path traversal detected in path {combined}, which is not allowed"); + } + + return combined; + } + + /// <summary> + /// Returns a value indicating whether the specified <paramref name="path"/> contains path traversal segments. + /// </summary> + /// <param name="path">The path to check.</param> + /// <returns>True if one or more segments is present, false otherwise.</returns> + public static bool ContainsTraversalSegments(string path) => path?.Split('\\', '/')?.Any(s => s is "." or "..") ?? false; + + /// <summary> + /// Returns a value indicating whether the specified <paramref name="path"/> is absolute (rooted), using + /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// </summary> + /// <remarks> + /// This is necessary because the base library is opaque and untestable in a cross-platform way, so we are + /// implementing the nuclear option and merging the logic for Windows and non-Windows. + /// </remarks> + /// <param name="path">The path to check.</param> + /// <returns>True if the path is absolute, false otherwise.</returns> + public static bool IsPathAbsolute(string path) + { + if (string.IsNullOrEmpty(path)) + { + return false; + } + + // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with / + // Windows root-relative paths and UNC paths start with \ + if (path[0] is '/' or '\\') + { + return true; + } + + // Windows drive-letter paths: X:\ or X:/ + // X:foo is a "drive relative" path so it doesn't _technically_ count, but + // it's questionable and the user probably intended to root it anyway + // this matches the built in IsPathRooted but not IsPathFullyQualified + if (path.Length >= 2 + && char.IsAsciiLetter(path[0]) + && path[1] == ':') + { + return true; + } + + return false; + } + + /// <summary> + /// Returns a value indicating whether the specified <paramref name="path"/>, using + /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// </summary> + /// <param name="path">The path to check.</param> + /// <returns>True if the path is relative, false otherwise.</returns> + public static bool IsPathRelative(string path) => !IsPathAbsolute(path); +}
\ No newline at end of file diff --git a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 8f87e479..4c9f5e53 100644 --- a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -1,4 +1,4 @@ -// <copyright file="AbsoluteFilePathAttribute.cs" company="JP Dillingham"> +// <copyright file="AbsolutePathAttribute.cs" company="JP Dillingham"> // ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ // ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ // █__ --█ █__ --█ ◄█ - █ @@ -33,22 +33,27 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.IO; /// <summary> /// Validates that the specified path is absolute. /// </summary> - public class AbsoluteFilePathAttribute : ValidationAttribute + public class AbsolutePathAttribute : ValidationAttribute { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - if (value != null) + if (value != null && value is string str && !string.IsNullOrEmpty(str)) { - var filePath = value.ToString(); + var path = value.ToString(); - if (!string.IsNullOrEmpty(filePath) && !Path.IsPathRooted(filePath)) + if (!FileSafety.IsPathAbsolute(path)) { - return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); + } + + // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here + if (FileSafety.ContainsTraversalSegments(path)) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); } } diff --git a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs new file mode 100644 index 00000000..90ed3d81 --- /dev/null +++ b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs @@ -0,0 +1,71 @@ +// <copyright file="DisallowedCharactersAttribute.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.Validation; + +using System.ComponentModel.DataAnnotations; +using System.Linq; + +/// <summary> +/// Validates that the value does not contain any of the <see cref="Disallowed"/> characters. +/// </summary> +public class DisallowedCharactersAttribute : ValidationAttribute +{ + public DisallowedCharactersAttribute(params char[] disallowed) + { + Disallowed = disallowed; + } + + /// <summary> + /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to <see langword="true"/>. + /// </summary> + public bool IgnoreCase { get; set; } = true; + + private char[] Disallowed { get; } + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value is not null and string str) + { + var invalid = IgnoreCase + ? str.Where(c => Disallowed.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d))) + : str.Where(c => Disallowed.Contains(c)); + + if (invalid.Any()) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}"); + } + } + + return ValidationResult.Success; + } +}
\ No newline at end of file diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs new file mode 100644 index 00000000..edaef1be --- /dev/null +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -0,0 +1,63 @@ +// <copyright file="RelativePathAttribute.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.Validation +{ + using System.ComponentModel.DataAnnotations; + + /// <summary> + /// Validates that the specified path is relative. + /// </summary> + public class RelativePathAttribute : ValidationAttribute + { + 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)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + } + + // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here + if (FileSafety.ContainsTraversalSegments(path)) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); + } + } + + return ValidationResult.Success; + } + } +}
\ No newline at end of file diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 8cc369af..51b3cab1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -198,6 +198,7 @@ namespace slskd [Argument('i', "instance-name")] [EnvironmentVariable("INSTANCE_NAME")] [Description("optional; a unique name for this instance")] + [DisallowedCharacters('/', '\\')] [RequiresRestart] public string InstanceName { get; init; } = "default"; @@ -654,6 +655,7 @@ namespace slskd [Description("the name for this agent")] [StringLength(255, MinimumLength = 1)] [NotNullOrWhiteSpace] + [DisallowedCharacters('/', '\\')] [Secret] public string InstanceName { get; init; } @@ -765,6 +767,7 @@ namespace slskd [Argument(default, "incomplete")] [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] + [AbsolutePath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory; @@ -775,6 +778,7 @@ namespace slskd [Argument('o', "downloads")] [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] + [AbsolutePath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; @@ -2010,7 +2014,7 @@ namespace slskd [Argument(default, "http-socket")] [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] - [AbsoluteFilePath] + [AbsolutePath] [RequiresRestart] public string Socket { get; init; } diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 575619d5..4b281863 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -164,7 +164,7 @@ namespace slskd.Files } // important! we must fully expand the given paths with GetFullPath() to resolve a given relative directory, like '..' - bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed)); + bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed + Path.DirectorySeparatorChar) || path == allowed); // if any of the resolved directory paths aren't rooted in one of the allowed directories, forbid the entire request if (!directories.All(directory => IsAllowed(directory))) @@ -222,7 +222,7 @@ namespace slskd.Files } // important! we must fully expand the given paths with GetFullPath() to resolve a given relative directory, like '..' - bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed)); + bool IsAllowed(string path) => AllowedDirectories.Any(allowed => path.StartsWith(allowed + Path.DirectorySeparatorChar) || path == allowed); // if any of the resolved file paths aren't rooted in one of the allowed directories, forbid the entire request if (!files.All(file => IsAllowed(file))) diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index 0d2ef9c5..fdc6dbe6 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -149,6 +149,14 @@ namespace slskd.Relay return BadRequest(); } + // check the path; the caller has a valid API key but we haven't validated the credential yet, so this is worth + // doing here instead of relying on the CombineSafely() backstop + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to download a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); + return BadRequest(); + } + Log.Information("Handling file download of {Filename} ({Token}) from a caller claiming to be agent {Agent}", filename, token, agentName); // note: the token remains valid after the validation attempt, unlike most other endpoints. @@ -159,7 +167,12 @@ namespace slskd.Relay return Unauthorized(); } - var sourceFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename); + // if we get this far, the caller has supplied a valid credential and filename, meaning the request + // to download is being made in response to the controller signaling the agent that a download had completed. + // it's not possible for the client to download arbitrary files; credentials are computed from a token, and + // this token is cached in the controller, so only file downloads that the controller solicited are possible + // still, for the abundance of caution, use the CombineSafely method in case the filename has traversal segments + var sourceFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, filename); Log.Information("Agent {Agent} authenticated for token {Token}. Sending file {Filename}", agentName, guid, filename); @@ -225,6 +238,14 @@ namespace slskd.Relay throw new ArgumentException("Upload filename is null or empty"); } + // use an abundance of caution; the caller has a valid API key but we haven't validated the credential yet + // this is a really unlikely attack vector and it wouldn't do anything, but we're taking a hard stance on input validation + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to upload a file containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); + return BadRequest(); + } + if (stream == null || !stream.CanRead) { throw new ArgumentException("Unable to obtain stream from request"); @@ -323,8 +344,8 @@ namespace slskd.Relay return Unauthorized(); } - Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), Program.AppName)); - var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_{agentName}_{Path.GetRandomFileName()}.db"); + Directory.CreateDirectory(FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName)); + var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_{agentName.ReplaceInvalidFileNameCharacters()}_{Path.GetRandomFileName()}.db"); try { diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 9aec7b00..2e001bdc 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -370,6 +370,12 @@ namespace slskd.Relay private async Task HandleFileInfoRequest(string filename, Guid id) { + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to request file info containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); + await HubConnection.InvokeAsync(nameof(RelayHub.ReturnFileInfo), id, false, 0); + } + Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id); try @@ -387,8 +393,14 @@ namespace slskd.Relay } } - private Task HandleFileUploadRequest(string filename, long startOffset, Guid token) + private async Task HandleFileUploadRequest(string filename, long startOffset, Guid token) { + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to request a file upload containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); + await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token); + } + _ = Task.Run(async () => { Log.Information("Relay controller requested file {Filename} with ID {Id}", filename, token); @@ -442,28 +454,32 @@ namespace slskd.Relay await HubConnection.InvokeAsync(nameof(RelayHub.NotifyFileUploadFailed), token); } }); - - return Task.CompletedTask; } - private Task HandleNotifyFileDownloadCompleted(string filename, Guid token) + private async Task HandleNotifyFileDownloadCompleted(string filename, Guid token) { + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to solicit a file download containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}", filename); + return; + } + if (!OptionsMonitor.CurrentValue.Relay.Controller.Downloads) { - return Task.CompletedTask; + return; } Log.Information("Relay controller sent a download notification for {Filename} ({Token})", filename, token); _ = Task.Run(async () => { - var destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, filename); + var destinationFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, filename); if (OptionsMonitor.CurrentValue.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Debug) { // if we're debugging, we're referencing the same file for both the controller and agent which will lead to an // access violation. prefix the destination file to avoid this. - destinationFile = Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed"); + destinationFile = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, $"{filename}.relayed"); } // if the controller is Windows and the agent is Linux or vice versa, we need to translate the filename to the @@ -498,8 +514,6 @@ namespace slskd.Relay Log.Information("File {Filename} successfully downloaded to {Destination}", filename, destinationFile); }); - - return Task.CompletedTask; } private Task HubConnection_Closed(Exception arg) @@ -579,7 +593,7 @@ namespace slskd.Relay return; } - var temp = Path.Combine(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db"); + var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_backup_{Path.GetRandomFileName()}.db"); try { diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index a1dde4eb..054561bf 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -188,7 +188,9 @@ namespace slskd.Shares directories.TryAdd(directory, new Directory(directory)); } - var files = repositories.SelectMany(r => r.ListFiles(prefix, includeFullPath: true)); + var files = repositories.SelectMany(r => r.ListFiles( + parentDirectory: prefix, + includeFullPath: true)); // includes the full *masked* filename; directory and file name and extension. not the local filename. var groups = files .GroupBy(file => file.Filename.GetNormalizedDirectoryName()) @@ -280,7 +282,7 @@ namespace slskd.Shares /// <returns>The contents of the directory.</returns> public Task<Directory> ListDirectoryAsync(string directory) { - var files = AllRepositories.SelectMany(r => r.ListFiles(directory)); + var files = AllRepositories.SelectMany(r => r.ListFiles(directory, includeFullPath: false)); return Task.FromResult(new Directory(directory, files)); } diff --git a/src/slskd/Shares/SqliteShareRepository.cs b/src/slskd/Shares/SqliteShareRepository.cs index b6c5fc9d..ed594209 100644 --- a/src/slskd/Shares/SqliteShareRepository.cs +++ b/src/slskd/Shares/SqliteShareRepository.cs @@ -418,7 +418,7 @@ namespace slskd.Shares while (reader.Read()) { - var filename = reader.GetString(0); + var maskedFilename = reader.GetString(0); var code = reader.GetInt32(1); var size = reader.GetInt64(2); var extension = reader.GetString(3); @@ -426,9 +426,9 @@ namespace slskd.Shares var attributeList = attributeJson.FromJson<List<FileAttribute>>(); - filename = includeFullPath ? filename : filename.GetNormalizedFileName(); + maskedFilename = includeFullPath ? maskedFilename : maskedFilename.GetNormalizedFileName(); - var file = new Soulseek.File(code, filename, size, extension, attributeList); + var file = new Soulseek.File(code, maskedFilename, size, extension, attributeList); results.Add(file); } diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 4205c57e..74a35dc1 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -13,7 +13,7 @@ "@codemirror/legacy-modes": "^6.0.0", "@microsoft/signalr": "^7.0.7", "@uiw/react-codemirror": "^4.2.4", - "axios": "^1.15.0", + "axios": "^1.15.2", "lz-string": "^1.4.4", "react": "^16.8.6", "react-dom": "^16.8.6", @@ -5819,9 +5819,9 @@ } }, "node_modules/axios": { - "version": "1.15.0", - "resolved": "https://registry.npmjs.org/axios/-/axios-1.15.0.tgz", - "integrity": "sha512-wWyJDlAatxk30ZJer+GeCWS209sA42X+N5jU2jy6oHTp7ufw8uzUTVFBX9+wTfAlhiJXGS0Bq7X6efruWjuK9Q==", + "version": "1.15.2", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.15.2.tgz", + "integrity": "sha512-wLrXxPtcrPTsNlJmKjkPnNPK2Ihe0hn0wGSaTEiHRPxwjvJwT3hKmXF4dpqxmPO9SoNb2FsYXj/xEo0gHN+D5A==", "license": "MIT", "dependencies": { "follow-redirects": "^1.15.11", @@ -10464,9 +10464,9 @@ } }, "node_modules/fast-uri": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.0.tgz", - "integrity": "sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==", + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/fast-uri/-/fast-uri-3.1.2.tgz", + "integrity": "sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==", "dev": true, "funding": [ { diff --git a/src/web/package.json b/src/web/package.json index 00491c52..57bb8d70 100644 --- a/src/web/package.json +++ b/src/web/package.json @@ -18,7 +18,7 @@ "@codemirror/legacy-modes": "^6.0.0", "@microsoft/signalr": "^7.0.7", "@uiw/react-codemirror": "^4.2.4", - "axios": "^1.15.0", + "axios": "^1.15.2", "lz-string": "^1.4.4", "react": "^16.8.6", "react-dom": "^16.8.6", diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs new file mode 100644 index 00000000..f6264661 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs @@ -0,0 +1,144 @@ +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); + } + } +}
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs index 1012ddfa..78539142 100644 --- a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs @@ -1,6 +1,8 @@ namespace slskd.Tests.Unit.Common.Extensions { using System; + using System.IO; + using System.Linq; using Xunit; public class ToLocalRelativeFilenameTests @@ -18,36 +20,141 @@ namespace slskd.Tests.Unit.Common.Extensions } [Fact] - public void Returns_Localized_Filename_And_Parent_Directory() + public void Returns_Last_Directory_And_Filename_From_Deep_Path() { - if (Environment.OSVersion.Platform == PlatformID.Win32NT) + 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 => { - Assert.Equal(@"path\file.ext", "deeply/nested/path/file.ext".ToLocalRelativeFilename()); - } - else + 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 => { - Assert.Equal(@"path/file.ext", @"C:\deeply\nested\path\file.ext".ToLocalRelativeFilename()); - } + 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 Returns_Just_File_If_Only_File_Given() + public void Handles_Forward_Slash_As_Segment_Separator() { - Assert.Equal("file.ext", "file.ext".ToLocalRelativeFilename()); + // 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 Removes_Invalid_Characters_From_Path_And_Filename() + public void Handles_Mixed_Slash_Separators() { - if (Environment.OSVersion.Platform == PlatformID.Win32NT) - { - Assert.Equal(@"p_a_t_h\fi_le.ext", @"p?a|t<h/fi>le.ext".ToLocalRelativeFilename()); - } - else + 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 => { - Assert.Equal(@"_", $"{'\0'}".ToLocalRelativeFilename()); - } + 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/FileSafetyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs new file mode 100644 index 00000000..ae1efccf --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs @@ -0,0 +1,545 @@ +using System; +using System.IO; +using Xunit; + +namespace slskd.Tests.Unit.Files; + +public class FileSafetyTests +{ + // Use a platform-appropriate absolute base path. Backslash roots are not recognised on Linux/macOS, + // so a Windows-style base would make containment assertions meaningless on those platforms. + private static readonly string Base = OperatingSystem.IsWindows() ? "C:\\base" : "/base"; + + private static void AssertContainedInBase(string result) + { + var resolvedBase = Path.GetFullPath(Base); + var resolvedResult = Path.GetFullPath(result); + Assert.True( + resolvedResult == resolvedBase || + resolvedResult.StartsWith(resolvedBase + Path.DirectorySeparatorChar), + $"Result '{resolvedResult}' escapes base '{resolvedBase}'"); + } + + public class ContainsTraversalSegments_ReturnsTrue + { + [Theory] + // Bare traversal segments + [InlineData("..")] + [InlineData(".")] + // Traversal as first component — forward slash + [InlineData("../escape")] + [InlineData("./dir")] + // Traversal at end — forward slash + [InlineData("sub/..")] + [InlineData("sub/.")] + // Traversal in middle — forward slash + [InlineData("sub/../escape")] + [InlineData("sub/./dir")] + // Double traversal — forward slash + [InlineData("sub/../../escape")] + [InlineData("a/b/c/../../..")] + // Traversal via backslash + [InlineData("sub\\..")] + [InlineData("sub\\.")] + [InlineData("sub\\..\\escape")] + [InlineData("sub\\.\\dir")] + // Mixed separators + [InlineData("sub/..\\escape")] + [InlineData("sub\\./../escape")] + // Unicode path components mixed with forward-slash traversal + [InlineData("Ünïcödé/../escape")] + [InlineData("Ünïcödé/./escape")] + [InlineData("пользователь/../etc")] + [InlineData("пользователь/./etc")] + [InlineData("用户/../escape")] + [InlineData("ユーザー/../../escape")] + [InlineData("사용자/../escape")] + [InlineData("مستخدم/../escape")] + [InlineData("χρήστης/../μουσική")] + [InlineData("משתמש/../מוזיקה")] + // Unicode path components mixed with backslash traversal + [InlineData("用户\\..\\escape")] + [InlineData("ユーザー\\..\\escape")] + [InlineData("пользователь\\..\\Музыка")] + // Traversal between two valid Unicode segments + [InlineData("Ünïcödé/../пользователь")] + [InlineData("用户/music/../escape")] + // Traversal at end after unicode + [InlineData("Ünïcödé/..")] + [InlineData("пользователь/..")] + [InlineData("用户\\..")] + public void Path_ContainsTraversal(string path) + { + Assert.True(FileSafety.ContainsTraversalSegments(path)); + } + } + + public class ContainsTraversalSegments_ReturnsFalse + { + [Theory] + // Simple names — no separators, no dots + [InlineData("subdir")] + [InlineData("file.flac")] + [InlineData("My Artist")] + [InlineData("Artist.Name")] + // Dotfile and dot-prefixed names — not exactly . or .. + [InlineData(".hidden")] + [InlineData("..hidden")] + [InlineData("...")] + [InlineData("...dir")] + // Segments that start with .. but are not exactly .. + [InlineData("dir/..dir")] + [InlineData("dir/...")] + // Forward-slash paths — no traversal + [InlineData("sub/dir")] + [InlineData("Artist/Album")] + [InlineData("Artist/Album/Song.flac")] + // Backslash paths — no traversal + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("Artist\\Album\\Song.flac")] + // Mixed separators — no traversal + [InlineData("Artist/Album\\Song.flac")] + // Double separators — empty segment is not . or .. + [InlineData("sub//dir")] + [InlineData("sub\\\\dir")] + // Null and empty string — both return false without throwing + [InlineData(null)] + [InlineData("")] + // Unicode — no traversal, forward slash + [InlineData("Ünïcödé")] + [InlineData("Ünïcödé/Àrtïst/Àlbüm")] + [InlineData("пользователь/Музыка")] + [InlineData("用户/音乐/专辑")] + [InlineData("ユーザー/音楽/アルバム")] + [InlineData("사용자/음악/앨범")] + [InlineData("مستخدم/موسيقى")] + [InlineData("χρήστης/μουσική")] + [InlineData("משתמש/מוזיקה")] + // Unicode — no traversal, backslash + [InlineData("пользователь\\Музыка\\Альбом")] + [InlineData("用户\\音乐\\专辑")] + [InlineData("ユーザー\\音楽\\アルバム")] + [InlineData("사용자\\음악\\앨범")] + // Unicode names that start with dots — not traversal + [InlineData("Ünïcödé/..hidden")] + [InlineData("пользователь/...dir")] + [InlineData("用户/..名前")] + public void Path_DoesNotContainTraversal(string path) + { + Assert.False(FileSafety.ContainsTraversalSegments(path)); + } + } + + public class CombineSafely_Returns + { + [Fact] + public void NoSegments_ReturnsBasePath() + { + var result = FileSafety.CombineSafely(Base); + Assert.Equal(Base, result); + } + + [Fact] + public void EmptySegment_ReturnsBasePath() + { + var result = FileSafety.CombineSafely(Base, string.Empty); + Assert.Equal(Base, result); + } + + [Fact] + public void SingleSegment_ReturnsBaseAndSegment() + { + var result = FileSafety.CombineSafely(Base, "subdir"); + Assert.Equal(Path.Combine(Base, "subdir"), result); + } + + [Fact] + public void MultipleSegments_CombinesAll() + { + var result = FileSafety.CombineSafely(Base, "sub", "dir", "file.flac"); + Assert.Equal(Path.Combine(Base, "sub", "dir", "file.flac"), result); + } + + [Fact] + public void SegmentWithForwardSlash_CombinesCorrectly() + { + var result = FileSafety.CombineSafely(Base, "sub/dir"); + AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithBackslash_CombinesCorrectly() + { + var result = FileSafety.CombineSafely(Base, "sub\\dir"); + AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithDoubleSlash_CollapsedAndContained() + { + var result = FileSafety.CombineSafely(Base, "sub//dir"); + AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithDoubleBackslash_CollapsedAndContained() + { + var result = FileSafety.CombineSafely(Base, "sub\\\\dir"); + AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithSpaces_Contained() + { + var result = FileSafety.CombineSafely(Base, "My Artist", "My Album"); + AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithUnicode_Contained() + { + var result = FileSafety.CombineSafely(Base, "Ünïcödé", "пользователь", "音楽"); + AssertContainedInBase(result); + } + + [Fact] + public void DotfileSegment_Contained() + { + var result = FileSafety.CombineSafely(Base, ".hidden"); + AssertContainedInBase(result); + } + + [Fact] + public void ThreeDotsSegment_Contained() + { + var result = FileSafety.CombineSafely(Base, "...dir"); + AssertContainedInBase(result); + } + + [Fact] + public void DotDotPrefixedName_Contained() + { + var result = FileSafety.CombineSafely(Base, "..hidden"); + AssertContainedInBase(result); + } + } + + public class CombineSafely_AlwaysContainedInBase + { + [Theory] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("sub//dir")] + [InlineData("sub\\\\dir")] + [InlineData("My Artist")] + [InlineData("Artist.Name")] + [InlineData("...dir")] + [InlineData("..hidden")] + [InlineData(".hidden")] + [InlineData("dir/..dir")] + [InlineData("Ünïcödé")] + [InlineData("пользователь/Музыка")] + [InlineData("用户/音乐")] + [InlineData("ユーザー/音楽")] + [InlineData("사용자/음악")] + public void SingleSegment_IsContained(string segment) + { + var result = FileSafety.CombineSafely(Base, segment); + var resolvedBase = Path.GetFullPath(Base); + var resolvedResult = Path.GetFullPath(result); + Assert.True( + resolvedResult == resolvedBase || + resolvedResult.StartsWith(resolvedBase + Path.DirectorySeparatorChar), + $"Result '{resolvedResult}' escapes base '{resolvedBase}'"); + } + } + + public class CombineSafely_Throws_ForRootedSegment + { + [Theory] + [InlineData("/Music")] // Unix absolute / Windows root-relative, forward slash + [InlineData("//server/share")] // Unix-style UNC + [InlineData("C:\\Music")] // Windows drive-letter, backslash + [InlineData("C:/Music")] // Windows drive-letter, forward slash + [InlineData("D:\\path")] // alternate drive letter + [InlineData("C:relative")] // Windows drive-relative + [InlineData("\\Music")] // Windows root-relative, backslash + [InlineData("\\\\server\\share")] // Windows UNC + public void Throws_ArgumentException(string segment) + { + var ex = Assert.Throws<ArgumentException>(() => FileSafety.CombineSafely(Base, segment)); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentIsRooted() + { + var ex = Assert.Throws<ArgumentException>(() => + FileSafety.CombineSafely(Base, "valid", "/escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentIsRooted_Windows() + { + var ex = Assert.Throws<ArgumentException>(() => + FileSafety.CombineSafely(Base, "valid", "C:\\escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsRooted() + { + var ex = Assert.Throws<ArgumentException>(() => + FileSafety.CombineSafely(Base, "sub", "dir", "/escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsRooted_Windows() + { + var ex = Assert.Throws<ArgumentException>(() => + FileSafety.CombineSafely(Base, "sub", "dir", "C:\\escape")); + Assert.Contains("Rooted", ex.Message); + } + } + + public class CombineSafely_Throws_ForTraversalSegment + { + [Theory] + // Bare traversal + [InlineData("..")] + [InlineData(".")] + // Traversal as first component + [InlineData("../escape")] + [InlineData("./dir")] + // Traversal in middle + [InlineData("sub/../escape")] + [InlineData("sub/./dir")] + // Traversal at end + [InlineData("sub/..")] + [InlineData("sub/.")] + // Double traversal + [InlineData("sub/../../escape")] + [InlineData("a/b/c/../../..")] + // Via backslash + [InlineData("sub\\..")] + [InlineData("sub\\.")] + [InlineData("sub\\..\\escape")] + // Unicode path components mixed with traversal + [InlineData("Ünïcödé/../escape")] + [InlineData("пользователь/../../escape")] + [InlineData("用户\\..\\escape")] + public void Throws_ArgumentException(string segment) + { + var ex = Assert.Throws<ArgumentException>(() => FileSafety.CombineSafely(Base, segment)); + Assert.Contains("traversal", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentContainsTraversal() + { + var ex = Assert.Throws<ArgumentException>(() => + FileSafety.CombineSafely(Base, "valid", "../escape")); + Assert.Contains("traversal", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsTraversal() + { + var ex = Assert.Throws<ArgumentException>(() => + FileSafety.CombineSafely(Base, "sub", "dir", "..")); + Assert.Contains("traversal", ex.Message); + } + } + + public class IsPathAbsolute_ReturnsTrue + { + // Unix/Linux/macOS absolute paths + [Theory] + [InlineData("/")] // filesystem root + [InlineData("/home")] // single component + [InlineData("/home/user/Music")] // deep path + [InlineData("/home/user/My Music")] // spaces in component + [InlineData("/etc/hosts")] // config file + [InlineData("/tmp")] // temp directory + [InlineData("/home/Ünïcödé")] // latin extended + [InlineData("/home/пользователь/Музыка")] // Cyrillic + [InlineData("/home/用户/音乐")] // Chinese + [InlineData("/home/ユーザー/音楽")] // Japanese + [InlineData("/home/사용자/음악")] // Korean + public void Unix_Paths(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path)); + } + + // Unix-style UNC paths (// prefix) + [Theory] + [InlineData("//server/share")] + [InlineData("//server/share/folder")] + [InlineData("//192.168.1.1/share")] + [InlineData("//server/Ünïcödé")] + [InlineData("//server/share/пользователь")] + public void Unix_UNCPaths(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path)); + } + + // Windows root-relative paths (rooted to the current drive, no drive letter) + [Theory] + [InlineData("\\Music")] + [InlineData("\\Music\\Artist\\Album")] + [InlineData("/Music")] + [InlineData("/Music/Artist/Album")] + [InlineData("\\Ünïcödé")] + [InlineData("\\пользователь\\Музыка")] + public void Windows_RootRelativePaths(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path)); + } + + // Windows UNC paths (\\ prefix) + [Theory] + [InlineData("\\\\server\\share")] + [InlineData("\\\\server\\share\\folder")] + [InlineData("\\\\server\\share\\My Music")] + [InlineData("\\\\192.168.1.1\\share")] + [InlineData("\\\\server\\Ünïcödé")] + [InlineData("\\\\server\\share\\пользователь")] + [InlineData("\\\\server\\share\\用户\\音乐")] + public void Windows_UNCPaths(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path)); + } + + // Windows drive-letter paths — with or without a separator after the colon + [Theory] + [InlineData("C:\\")] // drive root, backslash + [InlineData("C:/")] // drive root, forward slash + [InlineData("C:\\Music")] // basic, backslash + [InlineData("C:/Music")] // basic, forward slash + [InlineData("C:\\Music\\Artist\\Album")] // deep, backslash + [InlineData("D:\\path")] // different drive letter + [InlineData("Z:\\downloads")] // drive letter Z + [InlineData("C:")] // bare drive letter + [InlineData("C:Music")] // drive-relative, no separator + [InlineData("D:path")] // different drive letter, no separator + [InlineData("C:\\Users\\Ünïcödé\\Music")] // latin extended + [InlineData("C:\\Users\\пользователь\\Музыка")] // Cyrillic + [InlineData("C:\\Users\\用户\\音乐")] // Chinese + public void Windows_DriveLetterPaths(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path)); + } + } + + public class IsPathAbsolute_ReturnsFalse + { + [Theory] + [InlineData(null)] // null + [InlineData("")] // empty string + [InlineData("subdir")] // simple name + [InlineData("sub/dir")] // forward slash + [InlineData("sub\\dir")] // backslash + [InlineData("Artist\\Album")] // multi-level backslash + [InlineData("Artist/Album/Song")] // deep forward slash + [InlineData("music.flac")] // file name with extension + [InlineData("My Music")] // spaces + [InlineData(".hidden")] // dotfile + [InlineData("..hidden")] // dot-prefixed name + [InlineData("...dir")] // three dots — relative, not traversal + [InlineData("../escape")] // traversal — still relative + [InlineData("./dir")] // current-dir segment — still relative + [InlineData("..")] // bare double-dot + [InlineData(".")] // bare single-dot + [InlineData("Ünïcödé")] // unicode, no root + [InlineData("пользователь/Музыка")] // unicode with separator, no root + public void Relative_Paths(string path) + { + Assert.False(FileSafety.IsPathAbsolute(path)); + } + } + + public class IsPathRelative_ReturnsTrue + { + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("music.flac")] + [InlineData(".hidden")] + [InlineData("../escape")] + public void Relative_Paths(string path) + { + Assert.True(FileSafety.IsPathRelative(path)); + } + + } + + public class IsPathRelative_ReturnsFalse + { + [Theory] + [InlineData("/home/user")] + [InlineData("//server/share")] + [InlineData("\\Music")] + [InlineData("\\\\server\\share")] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\")] + [InlineData("C:")] + [InlineData("C:Music")] + [InlineData("D:path")] + public void Absolute_Paths(string path) + { + Assert.False(FileSafety.IsPathRelative(path)); + } + } + + public class CombineSafely_NullAndEdgeCases + { + [Fact] + public void NullSegmentsArray_Throws() + { + // Passing null without an explicit cast is interpreted as a null params array. + // foreach over a null array throws NullReferenceException. + Assert.ThrowsAny<Exception>(() => FileSafety.CombineSafely(Base, null)); + } + + [Fact] + public void NullSegment_Throws() + { + // A null element inside the params array reaches Path.IsPathRooted(null), + // which throws ArgumentNullException. + Assert.Throws<ArgumentNullException>(() => FileSafety.CombineSafely(Base, null, "subdir")); + } + + [Fact] + public void NullSegmentAlone_Throws() + { + // Explicit cast to string forces a single-element array containing null. + // Path.IsPathRooted(null) throws ArgumentNullException. + Assert.Throws<ArgumentNullException>(() => FileSafety.CombineSafely(Base, (string)null)); + } + + [Fact] + public void NullBasePath_Throws() + { + Assert.ThrowsAny<Exception>(() => FileSafety.CombineSafely(null, "subdir")); + } + + [Fact] + public void TraversalInRoot_IsNotValidated() + { + // CombineSafely only validates segments, not the root parameter — root is assumed + // to be a known-good value supplied by the application, not untrusted input. + // This test documents that a traversal-containing root is NOT rejected. + var root = OperatingSystem.IsWindows() ? "C:\\base\\..\\etc" : "/base/../etc"; + var result = FileSafety.CombineSafely(root, "subdir"); + Assert.NotNull(result); + } + } +}
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs new file mode 100644 index 00000000..5013ec3a --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs @@ -0,0 +1,229 @@ +using System.ComponentModel.DataAnnotations; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class AbsolutePathAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(string value) + { + var attribute = new AbsolutePathAttribute(); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); + } + + // paths can be null or empty; [Required] dictates whether they must be defined + [Fact] + public void Null_Passes() + { + var (isValid, _) = Validate(null); + Assert.True(isValid); + } + + [Fact] + public void EmptyString_Passes() + { + var (isValid, _) = Validate(string.Empty); + Assert.True(isValid); + } + + public class Passes + { + // Standard Windows drive-letter absolute paths + [Theory] + [InlineData("C:\\Music")] // basic + [InlineData("C:/Music")] // forward slash separator + [InlineData("C:\\Music\\Artist\\Album")] // multi-level backslash + [InlineData("C:\\Music\\Artist/Album")] // mixed separators + [InlineData("C:\\Music\\My Artist")] // spaces in component + [InlineData("C:\\Program Files\\App")] // spaces, typical Windows path + [InlineData("D:\\path")] // different drive letter + [InlineData("Z:\\downloads")] // drive letter Z + [InlineData("C:")] // bare drive + [InlineData("C:\\Users\\Ünïcödé\\Music")] // latin extended + [InlineData("C:\\Users\\пользователь\\Музыка")] // Cyrillic + [InlineData("C:\\Users\\用户\\音乐")] // Chinese + [InlineData("C:\\Users\\ユーザー\\音楽")] // Japanese + [InlineData("C:\\Users\\사용자\\음악")] // Korean + [InlineData("C:\\Users\\مستخدم\\موسيقى")] // Arabic + [InlineData("C:\\Users\\χρήστης\\μουσική")] // Greek + [InlineData("C:Music")] // drive-relative (no separator) + public void Windows_DriveLetterPaths_Pass(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + + // Windows root paths (drive root with trailing separator) + [Theory] + [InlineData("C:\\")] // Windows C: root + [InlineData("D:\\")] // Windows D: root + [InlineData("Z:\\")] // Windows Z: root + [InlineData("C:/")] // root with forward slash + public void Windows_RootPaths_Pass(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + + // Windows root-relative paths (rooted to the current drive, no drive letter) + [Theory] + [InlineData("\\Music")] // root-relative, backslash + [InlineData("\\Music\\Artist\\Album")] // deep, backslash + [InlineData("/Music")] // root-relative, forward slash + [InlineData("/Music/Artist/Album")] // deep, forward slash + [InlineData("\\Ünïcödé")] // latin extended + [InlineData("\\пользователь\\Музыка")] // Cyrillic + [InlineData("\\用户\\音乐")] // Chinese + [InlineData("\\ユーザー\\音楽")] // Japanese + [InlineData("\\사용자\\음악")] // Korean + public void Windows_RootRelativePaths_Pass(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + + // Windows UNC (Universal Naming Convention) paths. + // Server name is DNS-constrained (ASCII), but share names and path components support Unicode. + [Theory] + [InlineData("\\\\server\\share")] // basic UNC + [InlineData("\\\\server\\share\\folder")] // UNC with subfolder + [InlineData("\\\\server\\share\\My Music")] // UNC with spaces + [InlineData("\\\\192.168.1.1\\share")] // UNC with IP address + [InlineData("\\\\DESKTOP-ABC\\SharedFolder")] // UNC with machine name + [InlineData("\\\\192.168.1.1\\Ünïcödé")] // latin extended share name + [InlineData("\\\\server\\Müsïk")] // latin extended share name + [InlineData("\\\\server\\share\\Ünïcödé Artist")] // latin extended path component + [InlineData("\\\\server\\音楽")] // Japanese share name + [InlineData("\\\\server\\share\\пользователь")] // Cyrillic path component + [InlineData("\\\\server\\share\\用户\\音乐")] // Chinese path components + [InlineData("\\\\server\\share\\사용자\\음악")] // Korean path components + public void Windows_UNCPaths_Pass(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + + // Unix/Linux absolute paths — always start with a leading / + [Theory] + [InlineData("/")] // filesystem root + [InlineData("/home")] // single component + [InlineData("/home/user")] // typical home directory + [InlineData("/home/user/Music")] // deep path + [InlineData("/home/user/My Music")] // spaces in component + [InlineData("/etc/hosts")] // config file path + [InlineData("/usr/local/bin")] // system path + [InlineData("/var/log/app.log")] // log file + [InlineData("/tmp")] // temp directory + [InlineData("/media/usb0")] // mounted device + [InlineData("/mnt/storage/Music")] // mounted storage + [InlineData("/home/user/Ünïcödé")] // latin extended + [InlineData("/home/пользователь/Музыка")] // Cyrillic + [InlineData("/home/用户/音乐")] // Chinese + [InlineData("/home/ユーザー/音楽")] // Japanese + [InlineData("/home/사용자/음악")] // Korean + [InlineData("/home/مستخدم/موسيقى")] // Arabic + [InlineData("/home/χρήστης/μουσική")] // Greek + [InlineData("/home/משתמש/מוזיקה")] // Hebrew + public void Unix_Paths_Pass(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + + // macOS absolute paths — same format as Unix, with macOS-specific conventions + [Theory] + [InlineData("/Users/username")] // home directory + [InlineData("/Users/username/Music")] // music library + [InlineData("/Users/username/Music/Artist/Album")] // deep path + [InlineData("/Volumes/External Drive")] // mounted external drive + [InlineData("/Volumes/External Drive/Music")] // file on external drive + [InlineData("/Applications/App.app")] // application bundle + [InlineData("/Library/Application Support/App")] // system library + [InlineData("/Users/Ünïcödé")] // latin extended username + [InlineData("/Users/пользователь/Музыка")] // Cyrillic + [InlineData("/Users/用户/音乐")] // Chinese + [InlineData("/Users/ユーザー/音楽")] // Japanese + [InlineData("/Users/사용자/음악")] // Korean + [InlineData("/Volumes/Ünïcödé Drive/Music")] // latin extended volume name + [InlineData("/Volumes/音楽ドライブ")] // Japanese volume name + [InlineData("/Volumes/외장 드라이브/음악")] // Korean volume name + public void MacOS_Paths_Pass(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + + // Unix-style UNC equivalents (// prefix, used on some systems) + [Theory] + [InlineData("//server/share")] // basic + [InlineData("//server/share/folder")] // with subfolder + [InlineData("//server/Ünïcödé")] // latin extended share name + [InlineData("//server/share/Ünïcödé Artist")] // latin extended path component + [InlineData("//server/音楽")] // Japanese share name + [InlineData("//server/share/пользователь")] // Cyrillic path component + public void Unix_UNCPaths_Pass(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + } + + // Paths containing . or .. segments, which are valid directory names in isolation + // but indicate traversal or ambiguity and must be rejected regardless of whether + // the path is otherwise absolute or relative. + public class Traversal_Fails + { + [Theory] + // Windows-style traversal + [InlineData("C:\\Music\\..\\Windows")] // traversal to sibling via backslash + [InlineData("C:\\Music\\.\\Artist")] // current-dir segment via backslash + [InlineData("C:/Music/../Windows")] // traversal via forward slash + [InlineData("C:/Music/./Artist")] // current-dir via forward slash + [InlineData("C:\\..")] // traversal at drive root + [InlineData("D:\\a\\b\\..\\c")] // traversal deep in path + // Unix-style traversal + [InlineData("/../etc")] // traversal at Unix root + [InlineData("/home/user/../etc")] // traversal to sibling on Unix + [InlineData("/home/user/./Music")] // current-dir on Unix + [InlineData("/home/../../etc")] // double traversal on Unix + // UNC traversal (backslash) + [InlineData("\\\\server\\..\\Windows")] // traversal past UNC server + [InlineData("\\\\server\\share\\..\\other")] // traversal within UNC share + [InlineData("\\\\server\\share\\.\\folder")] // current-dir within UNC share + // UNC traversal (forward slash) + [InlineData("//server/../share")] // traversal past server, forward slash + [InlineData("//server/share/../other")] // traversal within share, forward slash + public void TraversalSegment_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Contains("traversal segments", errorMessage); + } + } + + public class Relative_Fails + { + [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); + Assert.False(isValid); + Assert.Equal("The Field field must be an absolute file path.", errorMessage); + } + } +}
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs new file mode 100644 index 00000000..f430c181 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs @@ -0,0 +1,254 @@ +using System.ComponentModel.DataAnnotations; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class DisallowedCharactersAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) + { + var attribute = new DisallowedCharactersAttribute(disallowed) { IgnoreCase = ignoreCase }; + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); + } + + // null and empty pass — [Required] handles presence; this attribute only checks content + [Fact] + public void Null_Passes() + { + var (isValid, _) = Validate(null, ['!']); + Assert.True(isValid); + } + + [Fact] + public void EmptyString_Passes() + { + var (isValid, _) = Validate(string.Empty, ['!']); + Assert.True(isValid); + } + + public class Passes + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) + => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase); + + // Punctuation has no case variants — IgnoreCase must not affect the result either way + [Theory] + [InlineData(true)] + [InlineData(false)] + public void NoDisallowedCharsPresent_Passes_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello", ['!', '@'], ignoreCase); + Assert.True(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void EmptyDisallowedSet_Passes_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello!@#", [], ignoreCase); + Assert.True(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Unicode_AllowedChars_Pass_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("пользователь/音楽", ['!', '@'], ignoreCase); + Assert.True(isValid); + } + + [Fact] + public void NonString_Passes() + { + var attribute = new DisallowedCharactersAttribute('!'); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(42, context); + Assert.Equal(ValidationResult.Success, result); + } + + // IgnoreCase = false only: a disallowed letter in one case does not block the other case + [Fact] + public void CaseSensitive_LowerCaseDisallowed_DoesNotBlock_UpperCase() + { + var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o'], ignoreCase: false); + Assert.True(isValid); + } + + [Fact] + public void CaseSensitive_UpperCaseDisallowed_DoesNotBlock_LowerCase() + { + var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O'], ignoreCase: false); + Assert.True(isValid); + } + } + + public class Fails + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) + => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase); + + // Punctuation has no case variants — IgnoreCase must not affect the result either way + [Theory] + [InlineData(true)] + [InlineData(false)] + public void SingleDisallowedChar_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello!", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DisallowedCharAtStart_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("!hello", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DisallowedCharAtEnd_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello!", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DisallowedCharInMiddle_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hel!lo", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void OneOfMultipleDisallowedCharsPresent_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello!", ['!', '@', '#'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void MultipleDisallowedCharsAllPresent_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("h!e@l#lo", ['!', '@', '#'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DisallowedCharRepeated_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("he!lo!", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AllCharsDisallowed_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("!@#", ['!', '@', '#'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Unicode_DisallowedChar_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("пользователь", ['е'], ignoreCase); + Assert.False(isValid); + } + + // IgnoreCase = true only: a disallowed letter blocks its other-case equivalent + [Fact] + public void IgnoreCase_LowerCaseDisallowed_Blocks_UpperCase() + { + var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o'], ignoreCase: true); + Assert.False(isValid); + } + + [Fact] + public void IgnoreCase_UpperCaseDisallowed_Blocks_LowerCase() + { + var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O'], ignoreCase: true); + Assert.False(isValid); + } + + [Fact] + public void CaseSensitive_ExactMatch_Fails() + { + var (isValid, _) = Validate("hello", ['h'], ignoreCase: false); + Assert.False(isValid); + } + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) + => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase); + + [Fact] + public void DisplayName() + { + var (_, errorMessage) = Validate("hello!", ['!']); + Assert.Contains("Field", errorMessage); + } + + [Fact] + public void TheDisallowedChar() + { + var (_, errorMessage) = Validate("hello!", ['!']); + Assert.Contains("'!'", errorMessage); + } + + [Fact] + public void AllPresentDisallowedChars() + { + var (_, errorMessage) = Validate("h!@l", ['!', '@']); + Assert.Contains("'!'", errorMessage); + Assert.Contains("'@'", errorMessage); + } + + [Fact] + public void EachOccurrenceOfRepeatedChar() + { + // "he!lo!" has two '!' — both occurrences are listed + var (_, errorMessage) = Validate("he!lo!", ['!']); + Assert.Equal(2, errorMessage.Split("'!'").Length - 1); + } + + [Fact] + public void OnlyCharsActuallyPresent_NotAllDisallowedChars() + { + // '@' is disallowed but not in the value — must not appear in the message + var (_, errorMessage) = Validate("hello!", ['!', '@']); + Assert.Contains("'!'", errorMessage); + Assert.DoesNotContain("'@'", errorMessage); + } + + [Fact] + public void IgnoreCase_ShowsActualChar_NotDisallowedChar() + { + // 'a' is disallowed (lowercase); value contains 'A' (uppercase). + // The message reports what the user supplied ('A'), not the disallowed definition ('a'). + var (_, errorMessage) = Validate("A", ['a'], ignoreCase: true); + Assert.Contains("'A'", errorMessage); + Assert.DoesNotContain("'a'", errorMessage); + } + } +}
\ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs new file mode 100644 index 00000000..647bc05f --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -0,0 +1,131 @@ +using System.ComponentModel.DataAnnotations; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class RelativePathAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(string value) + { + var attribute = new RelativePathAttribute(); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); + } + + // null and empty are explicitly allowed; presence is enforced by [Required] separately + [Fact] + public void Null_Passes() + { + var (isValid, _) = Validate(null); + Assert.True(isValid); + } + + [Fact] + public void EmptyString_Passes() + { + var (isValid, _) = Validate(string.Empty); + Assert.True(isValid); + } + + public class Passes + { + [Theory] + [InlineData("Artist")] // simple name + [InlineData("music.flac")] // file with extension + [InlineData("My Artist")] // spaces + [InlineData("Artist.Name")] // dots that are not traversal + [InlineData("Artist/Album")] // forward slash + [InlineData("Artist\\Album")] // backslash + [InlineData("Artist/Album/Song.flac")] // multi-level forward slash + [InlineData("Artist\\Album\\Song.flac")] // multi-level backslash + [InlineData("Artist/Album\\Song.flac")] // mixed separators + [InlineData("...dir")] // three dots — not a traversal segment + [InlineData("..hidden")] // starts with .. but is a name, not traversal + [InlineData(".hidden")] // dotfile name, not a traversal segment + [InlineData("dir/..dir")] // segment starts with .. but is not exactly .. + [InlineData("Ünïcödé Àrtïst")] // latin extended + [InlineData("Ünïcödé/Àrtïst/Àlbüm")] // latin extended, forward slash + [InlineData("Ünïcödé\\Àrtïst\\Àlbüm")] // latin extended, backslash + [InlineData("пользователь/Музыка")] // Cyrillic, forward slash + [InlineData("пользователь\\Музыка\\Альбом")] // Cyrillic, backslash + [InlineData("用户/音乐/专辑")] // Chinese, forward slash + [InlineData("用户\\音乐\\专辑")] // Chinese, backslash + [InlineData("ユーザー/音楽/アルバム")] // Japanese, forward slash + [InlineData("ユーザー\\音楽\\アルバム")] // Japanese, backslash + [InlineData("사용자/음악/앨범")] // Korean, forward slash + [InlineData("사용자\\음악\\앨범")] // Korean, backslash + [InlineData("مستخدم/موسيقى")] // Arabic + [InlineData("χρήστης/μουσική")] // Greek + [InlineData("משתמש/מוזיקה")] // Hebrew + public void RelativePath_Passes(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + } + + public class Traversal_Fails + { + [Theory] + [InlineData("..")] // bare traversal + [InlineData(".")] // bare current-dir + [InlineData("../music")] // traversal prefix, forward slash + [InlineData("./music")] // current-dir prefix + [InlineData("music/../other")] // traversal in middle + [InlineData("music/./other")] // current-dir in middle + [InlineData("sub/../../escape")] // double traversal + [InlineData("music\\..")] // traversal via backslash + [InlineData("music\\.")] // current-dir via backslash + [InlineData("music/dir/..")] // traversal at end + [InlineData("a/b/c/../../d")] // multi-level traversal + [InlineData("Ünïcödé/../escape")] // latin extended with traversal + [InlineData("пользователь/../etc")] // Cyrillic with traversal + [InlineData("用户/音乐/../../escape")] // Chinese with deep traversal + [InlineData("ユーザー\\..\\escape")] // Japanese with backslash traversal + public void TraversalSegment_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Contains("traversal segments", errorMessage); + } + } + + public class Absolute_Fails + { + [Theory] + // Windows drive-letter paths + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("D:\\path\\to\\file")] + [InlineData("Z:/downloads")] + [InlineData("C:")] + // Windows root-relative (no drive letter) + [InlineData("\\Music")] + [InlineData("\\Music\\Artist\\Album")] + // Windows UNC + [InlineData("\\\\server\\share")] + [InlineData("\\\\server\\share\\folder")] + [InlineData("\\\\192.168.1.1\\share")] + // Unix/Linux + [InlineData("/")] + [InlineData("/home/user")] + [InlineData("/etc/hosts")] + [InlineData("/usr/local/bin")] + // macOS + [InlineData("/Users/username")] + [InlineData("/Volumes/External Drive")] + // Unix-style UNC (// prefix) + [InlineData("//server/share")] + [InlineData("//server/share/folder")] + // Windows drive-relative (no separator after colon; still rooted) + [InlineData("C:Music")] + public void AbsolutePath_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Equal("The Field field must be a relative path.", errorMessage); + } + } +}
\ No newline at end of file |
