diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-05-27 21:59:45 -0500 |
|---|---|---|
| committer | JP Dillingham <jp@dillingham.me> | 2026-05-27 21:59:45 -0500 |
| commit | 845da6c1c95ed18ec88c93a48f0a04c539f28bc3 (patch) | |
| tree | d1ccc31a63b1113faaf9c4358f601847fcbaf42d | |
| parent | 953733c42b4f7556a8619c32da1ef897a0027ae9 (diff) | |
| download | slskd-845da6c1c95ed18ec88c93a48f0a04c539f28bc3.tar.gz | |
wip
| -rw-r--r-- | config/slskd.example.yml | 7 | ||||
| -rw-r--r-- | src/slskd/Core/Options.cs | 50 | ||||
| -rw-r--r-- | src/slskd/Transfers/Downloads/DownloadService.cs | 205 | ||||
| -rw-r--r-- | src/slskd/Transfers/Types/DestinationConflictStrategy.cs | 49 | ||||
| -rw-r--r-- | tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs | 512 |
5 files changed, 802 insertions, 21 deletions
diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 367d8e4d..d295b964 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: ~ # chmod syntax, e.g. 644, 777. not for Windows. +# 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} +# conflict: rename # 'overwrite' or 'rename' +# permissions: +# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # groups: # default: # upload: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index bac86ea2..298ea2c0 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1029,6 +1029,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 +1063,50 @@ namespace slskd [Enum(typeof(RetryPartialStrategy))] public string Partial { get; init; } = RetryPartialStrategy.Resume.ToString().ToLowerInvariant(); } + + /// <summary> + /// Download destination options. + /// </summary> + public class DestinationOptions + { + [RelativePath] + [NonTraversingPath] + [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] + public string Subdirectory { get; init; } = "{SOURCE_DIRECTORY}"; + + [Enum(typeof(DestinationConflictStrategy))] + public string Conflict { get; init; } = DestinationConflictStrategy.Rename.ToString().ToLowerInvariant(); + + [Validate] + public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions(); + + public class DestinationPermissionsOptions : IValidatableObject + { + public string Mode { get; init; } + + /// <summary> + /// Extended validation. + /// </summary> + /// <param name="validationContext"></param> + /// <returns></returns> + 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> diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 013e6a7a..af7a4699 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,144 @@ 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) + { + 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' + source_path = (Path.GetDirectoryName(filename) ?? string.Empty).TrimEnd('/', '\\'); + + // name of the remote parent directory, so using the example above, 'Baz' + source_directory = (Path.GetFileName(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: search?.SearchText ?? "unknown_search_text", + 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, + }; + + // 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; + + // 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); + + Log.Debug("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", Path.GetFileName(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})", Path.GetFileName(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 +1210,18 @@ 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 + // 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. if the remote file + // changes size between attempts, Soulseek.NET's DownloadAsync() will throw, so the only real risk is + // in a case where the file contents have changed but the size remains. the resulting file will be + // corrupted in that case. users that are concerned about this (extremely unlikely) case should + // configure slskd to always overwrite partial files. var incompleteFilename = transfer.Filename.ToLocalFilename( - baseDirectory: FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Incomplete, transfer.Username.ReplaceInvalidFileNameCharacters())); + baseDirectory: FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Incomplete, FileSafety.SanitizeFilename(transfer.Username))); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; @@ -1140,22 +1309,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 conflictStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Conflict.ToEnum<DestinationConflictStrategy>(); Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory); @@ -1163,7 +1328,7 @@ namespace slskd.Transfers.Downloads sourceFilename: incompleteFilename, destinationDirectory: destinationDirectory, unixFileMode: unixFileMode, - overwrite: false, + overwrite: conflictStrategy == DestinationConflictStrategy.Overwrite, deleteSourceDirectoryIfEmptyAfterMove: true); Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); 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/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..cd8060ef --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -0,0 +1,512 @@ +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)); + } + } + + 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; } + } +} |
