From f12d89de3381c59393444b602e762ae5d8146984 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Apr 2026 19:11:42 -0500 Subject: wip --- .../API/Controllers/TransfersController.cs | 60 ++++++++++++++++++++++ 1 file changed, 60 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 494ee722..ad537dfb 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -216,6 +216,66 @@ namespace slskd.Transfers.API } } + [HttpPost("downloads")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(201)] + [ProducesResponseType(typeof(string), 403)] + [ProducesResponseType(typeof(string), 500)] + public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) + { + if (Program.IsRelayAgent) + { + return Forbid(); + } + + // todo, check: username null or whitespace + if (!ModelState.IsValid) + { + return BadRequest(ModelState.GetReadableString()); + } + + if ((request.Files?.Count ?? 0) == 0) + { + return BadRequest("At least one file is required"); + } + + // todo, check: + // * filename null or whitespace + // * size -1 + if (request.Files.Any(r => r is null)) + { + return BadRequest("One or more files in the request are invalid"); + } + + if (!DownloadRequestLimiter.Wait(0)) + { + return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); + } + + try + { + var endpoint = await Users.GetIPEndPointAsync(request.Username); + + if (Users.IsBlacklisted(request.Username, endpoint.Address)) + { + throw new UserOfflineException($"User {request.Username} appears to be offline"); + } + + var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(request.Username, requests.Select(r => (r.Filename, r.Size))); + + return StatusCode(201, new { Enqueued = enqueued, Failed = failed }); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", requests.Count(), username, ex.Message); + return StatusCode(500, ex.Message); + } + finally + { + DownloadRequestLimiter.Release(); + } + } + /// /// Enqueues the specified download. /// -- cgit v1.2.3 From 11f4fe864ac67cd6cba54845afc1ab943cdaa564 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 12:43:27 -0500 Subject: add Batch type --- src/slskd/Transfers/Types/Batch.cs | 49 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 src/slskd/Transfers/Types/Batch.cs (limited to 'src') diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs new file mode 100644 index 00000000..820db66e --- /dev/null +++ b/src/slskd/Transfers/Types/Batch.cs @@ -0,0 +1,49 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers; + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +public class Batch +{ + public Guid? SearchId { get; init; } = null; + + [Key] + public Guid Id { get; init; } + public string Destination { get; init; } + public DateTime CreatedAt { get; init; } = DateTime.UtcNow; + + public ICollection Transfers { get; set; } +} \ No newline at end of file -- cgit v1.2.3 From 003b291e20788bba6229bd043688d208eb6261fe Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 12:44:20 -0500 Subject: add Batch to dbcontext --- src/slskd/Transfers/TransfersDbContext.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index be312e8e..063253cf 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -43,6 +43,7 @@ namespace slskd.Transfers { } + public DbSet Batches { get; set; } public DbSet Transfers { get; set; } public override int SaveChanges(bool acceptAllChangesOnSuccess) @@ -113,6 +114,18 @@ namespace slskd.Transfers .Entity() .HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size }) .HasDatabaseName("IDX_Transfers_UserUploadStatistics"); + + modelBuilder + .Entity() + .Property(e => e.CreatedAt) + .HasConversion(v => v, v => DateTime.SpecifyKind(v, DateTimeKind.Utc)); + + modelBuilder + .Entity() + .HasMany(b => b.Transfers) + .WithOne() + .HasForeignKey(t => t.BatchId) + .IsRequired(false); } } } -- cgit v1.2.3 From da732237ce6e87b40ccd0b042255e19e40d27682 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 13:16:32 -0500 Subject: remove deprecated Summarize method from UploadService --- src/slskd/Transfers/Uploads/UploadService.cs | 50 ---------------------------- 1 file changed, 50 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 72e3c0ef..e0d11a11 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -100,16 +100,6 @@ namespace slskd.Transfers.Uploads /// The found transfer, or default if not found. Transfer Find(Expression> expression); - /// - /// Returns a summary of the uploads matching the specified . This can be expensive; - /// consider caching. - /// - /// The expression used to select uploads for summarization. - /// - /// The generated summary, including the number of files and total size in bytes. - /// - (int Files, long Bytes) Summarize(Expression> expression); - /// /// Gets upload statistics for the specified . /// @@ -740,46 +730,6 @@ namespace slskd.Transfers.Uploads } } - /// - /// Returns a summary of the uploads matching the specified . This can be expensive; - /// consider caching. - /// - /// The expression used to select uploads for summarization. - /// - /// The generated summary, including the number of files and total size in bytes. - /// - public (int Files, long Bytes) Summarize(Expression> expression) - { - expression ??= t => true; - - try - { - using var context = ContextFactory.CreateDbContext(); - - var query = context.Transfers - .AsNoTracking() - .Where(t => t.Direction == TransferDirection.Upload) - .Where(expression) - .GroupBy(t => true) // https://stackoverflow.com/a/25489456: The GroupBy(x => true) statement places all items into a single group. The Select statement the allows operations against each group. - .Select(t => new - { - Files = t.Count(), - Bytes = t.Sum(x => x.Size), - }); - - Log.Verbose("{Method} SQL: {@Query}", nameof(Summarize), query.ToQueryString()); - - var stats = query.FirstOrDefault(); - - return (stats?.Files ?? 0, stats?.Bytes ?? 0); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to list uploads: {Message}", ex.Message); - throw; - } - } - /// /// Returns a list of all uploads matching the optional . /// -- cgit v1.2.3 From 169cd154ba14c97073899b3b6db947419ecf267e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:19:12 -0500 Subject: rough in Batch --- src/slskd/Transfers/Types/Batch.cs | 72 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 70 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index 820db66e..30633cc9 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -35,6 +35,9 @@ namespace slskd.Transfers; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; +using Soulseek; public class Batch { @@ -42,8 +45,73 @@ public class Batch [Key] public Guid Id { get; init; } - public string Destination { get; init; } + public string Username { get; init; } + public TransferDirection Direction { get; } = TransferDirection.Download; + + [NotMapped] + public TransferStates State => ComputeState(); + public DateTime CreatedAt { get; init; } = DateTime.UtcNow; - public ICollection Transfers { get; set; } + [NotMapped] + public DateTime? EndedAt => Transfers.Max(t => t.EndedAt); + + public ICollection Transfers { get; set; } = []; + + public string Destination { get; init; } + + [NotMapped] + public long BytesTransferred => Transfers.Sum(t => t.BytesTransferred); + [NotMapped] + public int Files => Transfers.Count; + [NotMapped] + public long Size => Transfers.Sum(t => t.Size); + [NotMapped] + public long BytesRemaining => Size - BytesTransferred; + [NotMapped] + public TimeSpan ElapsedTime => DateTime.UtcNow - CreatedAt; + [NotMapped] + public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100; + + [NotMapped] + public double AverageSpeed => Transfers + .Where(t => TransferStateCategories.Successful.Contains(t.State)) + .Select(t => t.AverageSpeed) + .DefaultIfEmpty(0) + .Average(); + + [NotMapped] + public bool Removed => Transfers.All(t => t.Removed); + + private TransferStates ComputeState() + { + // if there's a transfer in progress, the batch is in progress + if (Transfers.Any(t => TransferStateCategories.InProgress.Contains(t.State))) + { + return TransferStates.InProgress; + } + + // if no transfers are in progress but at least one is queued (doesn't matter locally or remotely), + // the batch is queued. it doesn't matter if one or more are errored, they might be retried + if (Transfers.Any(t => TransferStateCategories.Queued.Contains(t.State))) + { + return TransferStates.Queued; + } + + // if all transfers completed successfully, the batch did too + if (Transfers.All(t => TransferStateCategories.Successful.Contains(t.State))) + { + return TransferStates.Completed | TransferStates.Succeeded; + } + + // if one or more transfers failed and there are no more enqueued files, + // the batch errored and it will not recover on its own + if (Transfers.Any(t => TransferStateCategories.Failed.Contains(t.State))) + { + return TransferStates.Completed | TransferStates.Errored; + } + + // unclear how we would get here + return TransferStates.None; + } } \ No newline at end of file -- cgit v1.2.3 From da6c14ad62fc201eaf7c24470b5da972dd861ace Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:19:29 -0500 Subject: add Requested to Queued category (optimistically) --- src/slskd/Transfers/Types/TransferStateCategories.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Transfers/Types/TransferStateCategories.cs b/src/slskd/Transfers/Types/TransferStateCategories.cs index 603c669a..333ae525 100644 --- a/src/slskd/Transfers/Types/TransferStateCategories.cs +++ b/src/slskd/Transfers/Types/TransferStateCategories.cs @@ -111,6 +111,7 @@ public static class TransferStateCategories /// /// public static readonly HashSet Queued = [ + TransferStates.Requested, // optimistically assume that we will be allowed to enqueue TransferStates.Queued, // 2, in case of some sort of a malfunction or regression TransferStates.Queued | TransferStates.Locally, // 2 | 2048 = 2050 TransferStates.Queued | TransferStates.Remotely, // 2 | 4096 = 4098 -- cgit v1.2.3 From 96fda39aeb290524c00a24846c448bdfd2527663 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:21:34 -0500 Subject: prevent downloads from transitioning into terminal state while retries are available (but not if the Soulseek.NET transfer is not dead) --- src/slskd/Transfers/Downloads/DownloadService.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index d4d8004a..0ccf52c3 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -973,9 +973,11 @@ namespace slskd.Transfers.Downloads // the final update after all retry attempts have been exhausted to add it. // this means that the ONLY way to check whether a transfer is really 'dead' inclusive of all // retries is to look for this flag - if (transfer.Attempts < retryOptions.Attempts) + if (args.Transfer.State.HasFlag(TransferStates.Completed) + && !args.Transfer.State.HasFlag(TransferStates.Succeeded) + && transfer.Attempts < retryOptions.Attempts) { - transfer.State &= ~TransferStates.Completed; // remove the Completed flag + transfer.State = TransferStates.Queued | TransferStates.Locally; } // todo: broadcast -- cgit v1.2.3 From a5e624121469cd84a4b197ad204c2ac5c2d7274d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:21:58 -0500 Subject: improve readability of TransfersDbContext --- src/slskd/Transfers/TransfersDbContext.cs | 9 +++++++++ 1 file changed, 9 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 063253cf..ce2d9f52 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -61,6 +61,12 @@ namespace slskd.Transfers } protected override void OnModelCreating(ModelBuilder modelBuilder) + { + ConfigureTransfers(modelBuilder); + ConfigureBatches(modelBuilder); + } + + private void ConfigureTransfers(ModelBuilder modelBuilder) { modelBuilder .Entity() @@ -114,7 +120,10 @@ namespace slskd.Transfers .Entity() .HasIndex(e => new { e.Username, e.Direction, e.EndedAt, e.StartedAt, e.State, e.Size }) .HasDatabaseName("IDX_Transfers_UserUploadStatistics"); + } + private void ConfigureBatches(ModelBuilder modelBuilder) + { modelBuilder .Entity() .Property(e => e.CreatedAt) -- cgit v1.2.3 From 920d11fffbecf84d737781037992fdfc06ffa1cf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:23:46 -0500 Subject: rough in batch service --- src/slskd/Transfers/Batches/BatchService.cs | 179 ++++++++++++++++++++++++++++ 1 file changed, 179 insertions(+) create mode 100644 src/slskd/Transfers/Batches/BatchService.cs (limited to 'src') diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs new file mode 100644 index 00000000..515201c9 --- /dev/null +++ b/src/slskd/Transfers/Batches/BatchService.cs @@ -0,0 +1,179 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers +{ + using System; + using System.Collections.Generic; + using System.Linq; + using System.Linq.Expressions; + using System.Threading.Tasks; + using Microsoft.EntityFrameworkCore; + using Serilog; + + /// + /// Manages transfer batches. + /// + public interface IBatchService + { + /// + /// Creates a new batch record. + /// + /// The batch to create. + /// The created batch. + Batch Create(Batch batch); + + /// + /// Finds a single batch matching the specified . + /// + /// The expression to use to match batches. + /// The found batch, or default if not found. + /// Thrown when an expression is not supplied. + Task FindAsync(Expression> expression); + + /// + /// Returns a list of all batches matching the optional . + /// + /// An optional expression used to match batches. + /// The list of batches matching the specified expression, or all batches if no expression is specified. + Task> ListAsync(Expression> expression = null); + + /// + /// Marks all transfers associated with the specified batch as removed. + /// + /// The unique identifier of the batch. + /// Thrown when the batch does not exist. + void Remove(Guid id); + } + + /// + /// Manages transfer batches. + /// + public class BatchService : IBatchService + { + /// + /// Initializes a new instance of the class. + /// + /// The database context factory to use. + public BatchService(IDbContextFactory contextFactory) + { + ContextFactory = contextFactory; + } + + private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Creates a new batch record. + /// + /// The batch to create. + /// The created batch. + public Batch Create(Batch batch) + { + if (batch == default) + { + throw new ArgumentNullException(nameof(batch)); + } + + using var context = ContextFactory.CreateDbContext(); + context.Batches.Add(batch); + context.SaveChanges(); + + Log.Debug("Created batch {Id}", batch.Id); + + return batch; + } + + /// + /// Finds a single batch matching the specified . + /// + /// The expression to use to match batches. + /// The found batch, or default if not found. + /// Thrown when an expression is not supplied. + public Task FindAsync(Expression> expression) + { + if (expression == default) + { + throw new ArgumentException("An expression must be supplied.", nameof(expression)); + } + + using var context = ContextFactory.CreateDbContext(); + + return context.Batches + .AsNoTracking() + .Where(expression) + .Include(b => b.Transfers) + .FirstOrDefaultAsync(); + } + + /// + /// Returns a list of all batches matching the optional . + /// + /// An optional expression used to match batches. + /// The list of batches matching the specified expression, or all batches if no expression is specified. + public Task> ListAsync(Expression> expression = null) + { + expression ??= b => true; + + using var context = ContextFactory.CreateDbContext(); + + return context.Batches + .AsNoTracking() + .Where(expression) + .Include(b => b.Transfers) + .ToListAsync(); + } + + /// + /// Marks all transfers associated with the specified batch as removed. + /// + /// The unique identifier of the batch. + /// Thrown when the batch does not exist. + public void Remove(Guid id) + { + using var context = ContextFactory.CreateDbContext(); + + var exists = context.Batches.Any(b => b.Id == id); + + if (!exists) + { + throw new NotFoundException($"No batch with id {id}"); + } + + context.Transfers + .Where(t => t.BatchId == id) + .ExecuteUpdate(s => s.SetProperty(t => t.Removed, true)); + + Log.Debug("Marked transfers for batch {Id} as removed", id); + } + } +} -- cgit v1.2.3 From 59e2e9de29de2dea134c5fbaf3a518b2fe0d82b2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:23:58 -0500 Subject: wip transferscontroller --- .../API/Controllers/TransfersController.cs | 118 ++++++++++----------- 1 file changed, 59 insertions(+), 59 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index ad537dfb..9f2fba6d 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -216,65 +216,65 @@ namespace slskd.Transfers.API } } - [HttpPost("downloads")] - [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(201)] - [ProducesResponseType(typeof(string), 403)] - [ProducesResponseType(typeof(string), 500)] - public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) - { - if (Program.IsRelayAgent) - { - return Forbid(); - } - - // todo, check: username null or whitespace - if (!ModelState.IsValid) - { - return BadRequest(ModelState.GetReadableString()); - } - - if ((request.Files?.Count ?? 0) == 0) - { - return BadRequest("At least one file is required"); - } - - // todo, check: - // * filename null or whitespace - // * size -1 - if (request.Files.Any(r => r is null)) - { - return BadRequest("One or more files in the request are invalid"); - } - - if (!DownloadRequestLimiter.Wait(0)) - { - return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); - } - - try - { - var endpoint = await Users.GetIPEndPointAsync(request.Username); - - if (Users.IsBlacklisted(request.Username, endpoint.Address)) - { - throw new UserOfflineException($"User {request.Username} appears to be offline"); - } - - var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(request.Username, requests.Select(r => (r.Filename, r.Size))); - - return StatusCode(201, new { Enqueued = enqueued, Failed = failed }); - } - catch (Exception ex) - { - Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", requests.Count(), username, ex.Message); - return StatusCode(500, ex.Message); - } - finally - { - DownloadRequestLimiter.Release(); - } - } + // [HttpPost("downloads")] + // [Authorize(Policy = AuthPolicy.Any)] + // [ProducesResponseType(201)] + // [ProducesResponseType(typeof(string), 403)] + // [ProducesResponseType(typeof(string), 500)] + // public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) + // { + // if (Program.IsRelayAgent) + // { + // return Forbid(); + // } + + // // todo, check: username null or whitespace + // if (!ModelState.IsValid) + // { + // return BadRequest(ModelState.GetReadableString()); + // } + + // if ((request.Files?.Count ?? 0) == 0) + // { + // return BadRequest("At least one file is required"); + // } + + // // todo, check: + // // * filename null or whitespace + // // * size -1 + // if (request.Files.Any(r => r is null)) + // { + // return BadRequest("One or more files in the request are invalid"); + // } + + // if (!DownloadRequestLimiter.Wait(0)) + // { + // return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); + // } + + // try + // { + // var endpoint = await Users.GetIPEndPointAsync(request.Username); + + // if (Users.IsBlacklisted(request.Username, endpoint.Address)) + // { + // throw new UserOfflineException($"User {request.Username} appears to be offline"); + // } + + // var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(request.Username, requests.Select(r => (r.Filename, r.Size))); + + // return StatusCode(201, new { Enqueued = enqueued, Failed = failed }); + // } + // catch (Exception ex) + // { + // Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", requests.Count(), username, ex.Message); + // return StatusCode(500, ex.Message); + // } + // finally + // { + // DownloadRequestLimiter.Release(); + // } + // } /// /// Enqueues the specified download. -- cgit v1.2.3 From 9507e547dd68f1142b0b7a455a52ce5b6ad3d50e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 23:12:51 -0500 Subject: tweak Batch more --- src/slskd/Transfers/Types/Batch.cs | 43 +++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index 30633cc9..aa61f069 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -37,6 +37,7 @@ using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; +using System.Text.Json.Serialization; using Soulseek; public class Batch @@ -47,41 +48,41 @@ public class Batch public Guid Id { get; init; } public string Username { get; init; } public TransferDirection Direction { get; } = TransferDirection.Download; + public string Destination { get; init; } + public int Files { get; init; } + public long Size { get; init; } [NotMapped] public TransferStates State => ComputeState(); public DateTime CreatedAt { get; init; } = DateTime.UtcNow; + public DateTime? EndedAt { get; set; } // todo: set when the last file is completed, for performance reasons - [NotMapped] - public DateTime? EndedAt => Transfers.Max(t => t.EndedAt); - - public ICollection Transfers { get; set; } = []; + /// + /// The transfers associated with the batch. + /// + /// + /// Lazy loaded. If not loaded with the batch record, the collection and all of the statistics will be null. + /// + public ICollection Transfers { get; set; } - public string Destination { get; init; } - - [NotMapped] - public long BytesTransferred => Transfers.Sum(t => t.BytesTransferred); [NotMapped] - public int Files => Transfers.Count; - [NotMapped] - public long Size => Transfers.Sum(t => t.Size); - [NotMapped] - public long BytesRemaining => Size - BytesTransferred; + public long BytesTransferred { get; set; } + [NotMapped] - public TimeSpan ElapsedTime => DateTime.UtcNow - CreatedAt; + public long BytesRemaining { get; set; } + [NotMapped] - public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100; + public TimeSpan ElapsedTime => (EndedAt ?? DateTime.UtcNow) - CreatedAt; [NotMapped] - public double AverageSpeed => Transfers - .Where(t => TransferStateCategories.Successful.Contains(t.State)) - .Select(t => t.AverageSpeed) - .DefaultIfEmpty(0) - .Average(); + public double PercentComplete { get; set; } [NotMapped] - public bool Removed => Transfers.All(t => t.Removed); + public double AverageSpeed { get; set; } + + [JsonIgnore] + public bool Removed { get; set; } private TransferStates ComputeState() { -- cgit v1.2.3 From 3eec5bd5d1f6ebd48ce183435cca4a96740c35ba Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 23:50:19 -0500 Subject: optimized list and find --- src/slskd/Transfers/Batches/BatchService.cs | 83 ++++++++++++++++++++++++++--- src/slskd/Transfers/Types/Batch.cs | 18 +++---- 2 files changed, 86 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs index 515201c9..565e715e 100644 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ b/src/slskd/Transfers/Batches/BatchService.cs @@ -39,6 +39,7 @@ namespace slskd.Transfers using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; + using Soulseek; /// /// Manages transfer batches. @@ -119,7 +120,7 @@ namespace slskd.Transfers /// The expression to use to match batches. /// The found batch, or default if not found. /// Thrown when an expression is not supplied. - public Task FindAsync(Expression> expression) + public async Task FindAsync(Expression> expression) { if (expression == default) { @@ -128,11 +129,32 @@ namespace slskd.Transfers using var context = ContextFactory.CreateDbContext(); - return context.Batches + var batch = await context.Batches .AsNoTracking() .Where(expression) - .Include(b => b.Transfers) .FirstOrDefaultAsync(); + + if (batch is null) + { + return null; + } + + var transfers = await context.Transfers + .AsNoTracking() + .Where(t => t.BatchId == batch.Id) + .ToListAsync(); + + var bytesTransferred = transfers.Sum(t => t.BytesTransferred); + + return batch with + { + Transfers = transfers, + BytesTransferred = bytesTransferred, + BytesRemaining = transfers.Sum(t => t.BytesRemaining), + PercentComplete = batch.Size == 0 ? 0 : bytesTransferred / (double)batch.Size, + AverageSpeed = transfers.Average(t => t.AverageSpeed), + Removed = transfers.All(t => t.Removed), + }; } /// @@ -140,17 +162,66 @@ namespace slskd.Transfers /// /// An optional expression used to match batches. /// The list of batches matching the specified expression, or all batches if no expression is specified. - public Task> ListAsync(Expression> expression = null) + public async Task> ListAsync(Expression> expression = null) { expression ??= b => true; using var context = ContextFactory.CreateDbContext(); - return context.Batches + var batches = await context.Batches .AsNoTracking() .Where(expression) - .Include(b => b.Transfers) .ToListAsync(); + + if (batches.Count == 0) + { + return batches; + } + + var batchIds = batches.Select(b => b.Id).ToList(); + + var stats = (await context.Transfers + .AsNoTracking() + .Where(t => t.BatchId.HasValue && batchIds.Contains(t.BatchId.Value)) + .GroupBy(t => t.BatchId) + .Select(g => new + { + BatchId = g.Key, + BytesTransferred = g.Sum(t => t.BytesTransferred), + BytesRemaining = g.Sum(t => t.BytesRemaining), + AverageSpeed = g.Average(t => t.AverageSpeed), + Removed = g.All(t => t.Removed), + AnyInProgress = g.Any(t => TransferStateCategories.InProgress.Contains(t.State)), + AnyQueued = g.Any(t => TransferStateCategories.Queued.Contains(t.State)), + AllSuccessful = g.All(t => TransferStateCategories.Successful.Contains(t.State)), + AnyFailed = g.Any(t => TransferStateCategories.Failed.Contains(t.State)), + }) + .ToListAsync()) + .ToDictionary(s => s.BatchId); + + return batches.Select(b => + { + if (!stats.TryGetValue(b.Id, out var s)) + { + return b; + } + + var state = s.AnyInProgress ? TransferStates.InProgress + : s.AnyQueued ? TransferStates.Queued + : s.AllSuccessful ? TransferStates.Completed | TransferStates.Succeeded + : s.AnyFailed ? TransferStates.Completed | TransferStates.Errored + : TransferStates.None; + + return b with + { + BytesTransferred = s.BytesTransferred, + BytesRemaining = s.BytesRemaining, + PercentComplete = b.Size == 0 ? 0 : s.BytesTransferred / (double)b.Size, + AverageSpeed = s.AverageSpeed, + Removed = s.Removed, + State = state, + }; + }).ToList(); } /// diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index aa61f069..e15ecde3 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -40,20 +40,20 @@ using System.Linq; using System.Text.Json.Serialization; using Soulseek; -public class Batch +public record Batch { public Guid? SearchId { get; init; } = null; [Key] public Guid Id { get; init; } public string Username { get; init; } - public TransferDirection Direction { get; } = TransferDirection.Download; + public TransferDirection Direction { get; init; } = TransferDirection.Download; public string Destination { get; init; } public int Files { get; init; } public long Size { get; init; } [NotMapped] - public TransferStates State => ComputeState(); + public TransferStates State { get; init; } public DateTime CreatedAt { get; init; } = DateTime.UtcNow; public DateTime? EndedAt { get; set; } // todo: set when the last file is completed, for performance reasons @@ -64,25 +64,25 @@ public class Batch /// /// Lazy loaded. If not loaded with the batch record, the collection and all of the statistics will be null. /// - public ICollection Transfers { get; set; } + public ICollection Transfers { get; init; } [NotMapped] - public long BytesTransferred { get; set; } + public long BytesTransferred { get; init; } [NotMapped] - public long BytesRemaining { get; set; } + public long BytesRemaining { get; init; } [NotMapped] public TimeSpan ElapsedTime => (EndedAt ?? DateTime.UtcNow) - CreatedAt; [NotMapped] - public double PercentComplete { get; set; } + public double PercentComplete { get; init; } [NotMapped] - public double AverageSpeed { get; set; } + public double AverageSpeed { get; init; } [JsonIgnore] - public bool Removed { get; set; } + public bool Removed { get; init; } private TransferStates ComputeState() { -- cgit v1.2.3 From 6daeed10807243ca98718eefe6eeb70e952e553c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 23:56:28 -0500 Subject: use single or default for find --- src/slskd/Transfers/Batches/BatchService.cs | 2 +- src/slskd/Transfers/Uploads/UploadService.cs | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs index 565e715e..a19ada98 100644 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ b/src/slskd/Transfers/Batches/BatchService.cs @@ -132,7 +132,7 @@ namespace slskd.Transfers var batch = await context.Batches .AsNoTracking() .Where(expression) - .FirstOrDefaultAsync(); + .SingleOrDefaultAsync(); if (batch is null) { diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index e0d11a11..13915e82 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -721,7 +721,8 @@ namespace slskd.Transfers.Uploads return context.Transfers .AsNoTracking() .Where(t => t.Direction == TransferDirection.Upload) - .Where(expression).FirstOrDefault(); + .Where(expression) + .SingleOrDefault(); } catch (Exception ex) { -- cgit v1.2.3 From 2b39b7ee61610ca4526269d321f0ece0be6bb521 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 Apr 2026 22:13:30 -0500 Subject: make state derivation static --- src/slskd/Transfers/Types/Batch.cs | 23 ++++++++++++++--------- 1 file changed, 14 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index e15ecde3..6b3cf15c 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -48,14 +48,19 @@ public record Batch public Guid Id { get; init; } public string Username { get; init; } public TransferDirection Direction { get; init; } = TransferDirection.Download; - public string Destination { get; init; } public int Files { get; init; } public long Size { get; init; } + public string Destination { get; init; } + public DateTime CreatedAt { get; init; } = DateTime.UtcNow; - [NotMapped] - public TransferStates State { get; init; } + /// + /// Gets the current batch state. + /// + /// + /// If the database value is null, value must be derived from the associated transfers. + /// + public TransferStates? State { get; set; } // todo: set when the last file is completed - public DateTime CreatedAt { get; init; } = DateTime.UtcNow; public DateTime? EndedAt { get; set; } // todo: set when the last file is completed, for performance reasons /// @@ -84,30 +89,30 @@ public record Batch [JsonIgnore] public bool Removed { get; init; } - private TransferStates ComputeState() + public static TransferStates DeriveState(IEnumerable transfers) { // if there's a transfer in progress, the batch is in progress - if (Transfers.Any(t => TransferStateCategories.InProgress.Contains(t.State))) + if (transfers.Any(t => TransferStateCategories.InProgress.Contains(t.State))) { return TransferStates.InProgress; } // if no transfers are in progress but at least one is queued (doesn't matter locally or remotely), // the batch is queued. it doesn't matter if one or more are errored, they might be retried - if (Transfers.Any(t => TransferStateCategories.Queued.Contains(t.State))) + if (transfers.Any(t => TransferStateCategories.Queued.Contains(t.State))) { return TransferStates.Queued; } // if all transfers completed successfully, the batch did too - if (Transfers.All(t => TransferStateCategories.Successful.Contains(t.State))) + if (transfers.All(t => TransferStateCategories.Successful.Contains(t.State))) { return TransferStates.Completed | TransferStates.Succeeded; } // if one or more transfers failed and there are no more enqueued files, // the batch errored and it will not recover on its own - if (Transfers.Any(t => TransferStateCategories.Failed.Contains(t.State))) + if (transfers.Any(t => TransferStateCategories.Failed.Contains(t.State))) { return TransferStates.Completed | TransferStates.Errored; } -- cgit v1.2.3 From c502e5fa4595c6db45386aaf210019d56ce20171 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 27 Apr 2026 22:16:19 -0500 Subject: set state in findasync --- src/slskd/Transfers/Batches/BatchService.cs | 10 ++++++++++ 1 file changed, 10 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs index a19ada98..ac547d1e 100644 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ b/src/slskd/Transfers/Batches/BatchService.cs @@ -146,9 +146,19 @@ namespace slskd.Transfers var bytesTransferred = transfers.Sum(t => t.BytesTransferred); + // if the batch record has a non-null state, it has ended and it is safe to use the + // stored value. otherwise we must compute it from the associated transfers + var state = batch.State ?? ( + transfers.Any(t => TransferStateCategories.InProgress.Contains(t.State)) ? TransferStates.InProgress + : transfers.Any(t => TransferStateCategories.Queued.Contains(t.State)) ? TransferStates.Queued + : transfers.All(t => TransferStateCategories.Successful.Contains(t.State)) ? TransferStates.Completed | TransferStates.Succeeded + : transfers.Any(t => TransferStateCategories.Failed.Contains(t.State)) ? TransferStates.Completed | TransferStates.Errored + : TransferStates.None); + return batch with { Transfers = transfers, + State = state, BytesTransferred = bytesTransferred, BytesRemaining = transfers.Sum(t => t.BytesRemaining), PercentComplete = batch.Size == 0 ? 0 : bytesTransferred / (double)batch.Size, -- cgit v1.2.3 From b70f0ce9fcaf122ae25d19779ee3cd195e73e3d6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 29 Apr 2026 22:16:34 -0500 Subject: tweak queries --- src/slskd/Transfers/Batches/BatchService.cs | 28 ++++++++++------------------ 1 file changed, 10 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs index ac547d1e..daedbdc6 100644 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ b/src/slskd/Transfers/Batches/BatchService.cs @@ -131,6 +131,7 @@ namespace slskd.Transfers var batch = await context.Batches .AsNoTracking() + .Include(b => b.Transfers) .Where(expression) .SingleOrDefaultAsync(); @@ -139,31 +140,21 @@ namespace slskd.Transfers return null; } - var transfers = await context.Transfers - .AsNoTracking() - .Where(t => t.BatchId == batch.Id) - .ToListAsync(); - - var bytesTransferred = transfers.Sum(t => t.BytesTransferred); - - // if the batch record has a non-null state, it has ended and it is safe to use the + // if the batch record State has a non-null state, it has ended and it is safe to use the // stored value. otherwise we must compute it from the associated transfers - var state = batch.State ?? ( - transfers.Any(t => TransferStateCategories.InProgress.Contains(t.State)) ? TransferStates.InProgress - : transfers.Any(t => TransferStateCategories.Queued.Contains(t.State)) ? TransferStates.Queued - : transfers.All(t => TransferStateCategories.Successful.Contains(t.State)) ? TransferStates.Completed | TransferStates.Succeeded - : transfers.Any(t => TransferStateCategories.Failed.Contains(t.State)) ? TransferStates.Completed | TransferStates.Errored - : TransferStates.None); + var state = batch.State ?? Batch.DeriveState(batch.Transfers); + var endedAt = batch.EndedAt ?? batch.Transfers.Max(t => t.EndedAt); + + var bytesTransferred = batch.Transfers.Sum(t => t.BytesTransferred); return batch with { - Transfers = transfers, State = state, BytesTransferred = bytesTransferred, - BytesRemaining = transfers.Sum(t => t.BytesRemaining), + BytesRemaining = batch.Transfers.Sum(t => t.BytesRemaining), PercentComplete = batch.Size == 0 ? 0 : bytesTransferred / (double)batch.Size, - AverageSpeed = transfers.Average(t => t.AverageSpeed), - Removed = transfers.All(t => t.Removed), + AverageSpeed = batch.Transfers.Average(t => t.AverageSpeed), + Removed = batch.Transfers.All(t => t.Removed), }; } @@ -197,6 +188,7 @@ namespace slskd.Transfers .Select(g => new { BatchId = g.Key, + EndedAt = g.Max(t => t.EndedAt), BytesTransferred = g.Sum(t => t.BytesTransferred), BytesRemaining = g.Sum(t => t.BytesRemaining), AverageSpeed = g.Average(t => t.AverageSpeed), -- cgit v1.2.3 From ff430b438a6498c1f26e318d6d850de41a3634b4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 22:11:16 -0500 Subject: document Batch --- src/slskd/Transfers/Types/Batch.cs | 137 ++++++++++++++++++++----------------- 1 file changed, 73 insertions(+), 64 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index 6b3cf15c..3fe692f2 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -35,89 +35,98 @@ namespace slskd.Transfers; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using System.Linq; -using System.Text.Json.Serialization; using Soulseek; +/// +/// +/// A Transfer Batch is a lightweight association between a number of related Transfer +/// records and optionally the associated Search the Transfers are intended to fulfil. +/// +/// +/// Transfers may be enqueued in a Batch, and a caller that enqueued a Batch may use the +/// available API(s) to determine whether all of the Transfers within the Batch is complete, +/// but otherwise a Batch serves no functional purpose within the application. +/// +/// public record Batch { + /// + /// Gets the associated , if one was specified when the + /// Batch was enqueued. + /// public Guid? SearchId { get; init; } = null; + /// + /// Gets the unique identifier for the Batch. + /// [Key] public Guid Id { get; init; } - public string Username { get; init; } - public TransferDirection Direction { get; init; } = TransferDirection.Download; - public int Files { get; init; } - public long Size { get; init; } - public string Destination { get; init; } - public DateTime CreatedAt { get; init; } = DateTime.UtcNow; /// - /// Gets the current batch state. + /// Gets the username associated with the Batch. /// - /// - /// If the database value is null, value must be derived from the associated transfers. - /// - public TransferStates? State { get; set; } // todo: set when the last file is completed - - public DateTime? EndedAt { get; set; } // todo: set when the last file is completed, for performance reasons + public string Username { get; init; } /// - /// The transfers associated with the batch. + /// Gets the Batch direction (Upload, Download). /// /// - /// Lazy loaded. If not loaded with the batch record, the collection and all of the statistics will be null. + /// We don't have, and likely will never be able to implement, upload batches, + /// nor are they of any particular use. /// - public ICollection Transfers { get; init; } - - [NotMapped] - public long BytesTransferred { get; init; } - - [NotMapped] - public long BytesRemaining { get; init; } - - [NotMapped] - public TimeSpan ElapsedTime => (EndedAt ?? DateTime.UtcNow) - CreatedAt; - - [NotMapped] - public double PercentComplete { get; init; } - - [NotMapped] - public double AverageSpeed { get; init; } - - [JsonIgnore] - public bool Removed { get; init; } + public TransferDirection Direction { get; init; } = TransferDirection.Download; - public static TransferStates DeriveState(IEnumerable transfers) - { - // if there's a transfer in progress, the batch is in progress - if (transfers.Any(t => TransferStateCategories.InProgress.Contains(t.State))) - { - return TransferStates.InProgress; - } + /// + /// Gets the number of files included in the Batch. + /// + public int FileCount { get; init; } - // if no transfers are in progress but at least one is queued (doesn't matter locally or remotely), - // the batch is queued. it doesn't matter if one or more are errored, they might be retried - if (transfers.Any(t => TransferStateCategories.Queued.Contains(t.State))) - { - return TransferStates.Queued; - } + /// + /// Gets the sum of the included file's sizes. + /// + public long FileSize { get; init; } - // if all transfers completed successfully, the batch did too - if (transfers.All(t => TransferStateCategories.Successful.Contains(t.State))) - { - return TransferStates.Completed | TransferStates.Succeeded; - } + /// + /// Gets the timestamp at which the Batch was created. + /// + public DateTime CreatedAt { get; init; } = DateTime.UtcNow; - // if one or more transfers failed and there are no more enqueued files, - // the batch errored and it will not recover on its own - if (transfers.Any(t => TransferStateCategories.Failed.Contains(t.State))) - { - return TransferStates.Completed | TransferStates.Errored; - } + /// + /// Gets the optional destination directory for the files in the Batch, relative to the configured + /// download directory. + /// + /// + /// If specified, takes precedence over other configured placement rules. + /// + public string DestinationDirectory { get; init; } - // unclear how we would get here - return TransferStates.None; - } + /// + /// Gets the Transfer records associated with the batch. + /// + /// + /// Lazy loaded. If not explicitly loaded with the Batch record using Include(), the collection and + /// all of the (future?) statistics will be null. + /// + public ICollection Transfers { get; init; } = null; + + /* + future: [NotMapped] properties that aggregate values from the associated Transfer records. + there's no use for these now, but if we ever decide to leverage Batch records for anything + but determining whether a Search has been fulfilled, allowing a user to override a download directory, + or to handle an event when a batch is completed, we can add them and figure out how persistence should work. + + loading Transfers and doing aggregation in memory (if fetching 1 batch) or querying and aggregating Transfer + records in SQL and then updating a list of Batch records in memory (if fetching a list) technically works, + but is unlikely to perform well, especially as data grows, and ESPECIALLY when excliding 'Removed' Batches + from results (as this must be aggregated on the fly for each batch.. forever) + + my thinking (and reason for punting on this for now); add the interesting properties (Removed, BytesTransferred, + AverageSpeed, etc) to this class as nullable, and don't set a value until all of the associated Transfer + records have been finalized, then update the columns. when fetching batches we can deduce that any Batch + record missing those properties is still in progress, and we can aggregate the data on the fly. for historical + records that have completed, the data is all in the database and is quick to query. + + this can sit until/if we have further use for Batch records, i want to get this out and don't want to sit + and go back and forth trying to speculate on how this might need to work in the future. + */ } \ No newline at end of file -- cgit v1.2.3 From 3abaadcd87383c22bc380d6c2fd9b05e38e7d353 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 23:43:50 -0500 Subject: remove StartOffset from Transfers table (unused) --- ...Z2026_04_30_DropTransferStartOffsetMigration.cs | 101 +++++++++++++++++++++ src/slskd/Transfers/Downloads/DownloadService.cs | 1 - src/slskd/Transfers/Types/Transfer.cs | 2 +- src/slskd/Transfers/Uploads/UploadService.cs | 1 - 4 files changed, 102 insertions(+), 3 deletions(-) create mode 100644 src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs new file mode 100644 index 00000000..4fb25b1f --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs @@ -0,0 +1,101 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Updates the Transfers table to drop the unused StartOffset column. +/// +public class Z2026_04_30_DropTransferStartOffsetMigration : IMigration +{ + public Z2026_04_30_DropTransferStartOffsetMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + + var columns = schema["Transfers"]; + + if (columns.Any(c => c.Name == "StartOffset")) + { + return true; + } + + return false; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_04_30_DropTransferStartOffsetMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } + + Log.Information("> Dropping StartOffset column from the Transfers table..."); + + Exec("ALTER TABLE Transfers DROP COLUMN StartOffset;"); + + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 0ccf52c3..aba6ca9d 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -435,7 +435,6 @@ namespace slskd.Transfers.Downloads Direction = TransferDirection.Download, Filename = file.Filename, // important! use the remote filename Size = file.Size, - StartOffset = 0, // todo: maybe implement resumeable downloads? RequestedAt = DateTime.UtcNow, State = TransferStates.Queued | TransferStates.Locally, }; diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 93a23380..90fbe612 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -30,7 +30,7 @@ // ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ // -namespace slskd.Transfers +namespace slskd.Transfers; { using System; using System.ComponentModel.DataAnnotations; diff --git a/src/slskd/Transfers/Uploads/UploadService.cs b/src/slskd/Transfers/Uploads/UploadService.cs index 13915e82..9bb09f66 100644 --- a/src/slskd/Transfers/Uploads/UploadService.cs +++ b/src/slskd/Transfers/Uploads/UploadService.cs @@ -622,7 +622,6 @@ namespace slskd.Transfers.Uploads Direction = TransferDirection.Upload, Filename = filename, // important! use the remote filename Size = localFileLength, - StartOffset = 0, // potentially updated later during handshaking RequestedAt = DateTime.UtcNow, State = TransferStates.Queued | TransferStates.Locally, }; -- cgit v1.2.3 From 4323178f7e795e26bc3906411c6403746f2f8bb5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 23:44:03 -0500 Subject: straggling StartOffset --- src/slskd/Transfers/Extensions.cs | 1 - 1 file changed, 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Extensions.cs b/src/slskd/Transfers/Extensions.cs index 48179ff2..3180dbd9 100644 --- a/src/slskd/Transfers/Extensions.cs +++ b/src/slskd/Transfers/Extensions.cs @@ -44,7 +44,6 @@ namespace slskd.Transfers Direction = transfer.Direction, Filename = transfer.Filename, Size = transfer.Size, - StartOffset = t.StartOffset, State = t.State, RequestedAt = transfer.RequestedAt, EnqueuedAt = transfer.EnqueuedAt, -- cgit v1.2.3 From eba232fe9de343359b96ca4686c5414912d4b276 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 23:44:56 -0500 Subject: finalize batchservice --- src/slskd/Transfers/Batches/BatchService.cs | 79 ++--------------------------- src/slskd/Transfers/Types/Batch.cs | 18 +++---- 2 files changed, 12 insertions(+), 85 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs index daedbdc6..aadaa820 100644 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ b/src/slskd/Transfers/Batches/BatchService.cs @@ -39,7 +39,6 @@ namespace slskd.Transfers using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Serilog; - using Soulseek; /// /// Manages transfer batches. @@ -129,33 +128,11 @@ namespace slskd.Transfers using var context = ContextFactory.CreateDbContext(); - var batch = await context.Batches + return await context.Batches .AsNoTracking() .Include(b => b.Transfers) .Where(expression) .SingleOrDefaultAsync(); - - if (batch is null) - { - return null; - } - - // if the batch record State has a non-null state, it has ended and it is safe to use the - // stored value. otherwise we must compute it from the associated transfers - var state = batch.State ?? Batch.DeriveState(batch.Transfers); - var endedAt = batch.EndedAt ?? batch.Transfers.Max(t => t.EndedAt); - - var bytesTransferred = batch.Transfers.Sum(t => t.BytesTransferred); - - return batch with - { - State = state, - BytesTransferred = bytesTransferred, - BytesRemaining = batch.Transfers.Sum(t => t.BytesRemaining), - PercentComplete = batch.Size == 0 ? 0 : bytesTransferred / (double)batch.Size, - AverageSpeed = batch.Transfers.Average(t => t.AverageSpeed), - Removed = batch.Transfers.All(t => t.Removed), - }; } /// @@ -169,61 +146,11 @@ namespace slskd.Transfers using var context = ContextFactory.CreateDbContext(); - var batches = await context.Batches + return await context.Batches .AsNoTracking() + .Include(b => b.Transfers) .Where(expression) .ToListAsync(); - - if (batches.Count == 0) - { - return batches; - } - - var batchIds = batches.Select(b => b.Id).ToList(); - - var stats = (await context.Transfers - .AsNoTracking() - .Where(t => t.BatchId.HasValue && batchIds.Contains(t.BatchId.Value)) - .GroupBy(t => t.BatchId) - .Select(g => new - { - BatchId = g.Key, - EndedAt = g.Max(t => t.EndedAt), - BytesTransferred = g.Sum(t => t.BytesTransferred), - BytesRemaining = g.Sum(t => t.BytesRemaining), - AverageSpeed = g.Average(t => t.AverageSpeed), - Removed = g.All(t => t.Removed), - AnyInProgress = g.Any(t => TransferStateCategories.InProgress.Contains(t.State)), - AnyQueued = g.Any(t => TransferStateCategories.Queued.Contains(t.State)), - AllSuccessful = g.All(t => TransferStateCategories.Successful.Contains(t.State)), - AnyFailed = g.Any(t => TransferStateCategories.Failed.Contains(t.State)), - }) - .ToListAsync()) - .ToDictionary(s => s.BatchId); - - return batches.Select(b => - { - if (!stats.TryGetValue(b.Id, out var s)) - { - return b; - } - - var state = s.AnyInProgress ? TransferStates.InProgress - : s.AnyQueued ? TransferStates.Queued - : s.AllSuccessful ? TransferStates.Completed | TransferStates.Succeeded - : s.AnyFailed ? TransferStates.Completed | TransferStates.Errored - : TransferStates.None; - - return b with - { - BytesTransferred = s.BytesTransferred, - BytesRemaining = s.BytesRemaining, - PercentComplete = b.Size == 0 ? 0 : s.BytesTransferred / (double)b.Size, - AverageSpeed = s.AverageSpeed, - Removed = s.Removed, - State = state, - }; - }).ToList(); } /// diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index 3fe692f2..ac7025fb 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -87,27 +87,27 @@ public record Batch public long FileSize { get; init; } /// - /// Gets the timestamp at which the Batch was created. + /// Gets the time at which the Batch was created. /// public DateTime CreatedAt { get; init; } = DateTime.UtcNow; /// - /// Gets the optional destination directory for the files in the Batch, relative to the configured - /// download directory. + /// Gets the Transfer records associated with the batch. /// /// - /// If specified, takes precedence over other configured placement rules. + /// Lazy loaded. If not explicitly loaded with the Batch record using Include(), the collection and + /// all of the (future?) statistics will be null. /// - public string DestinationDirectory { get; init; } + public ICollection Transfers { get; init; } = null; /// - /// Gets the Transfer records associated with the batch. + /// Gets the optional destination directory for the files in the Batch, relative to the configured + /// download directory. /// /// - /// Lazy loaded. If not explicitly loaded with the Batch record using Include(), the collection and - /// all of the (future?) statistics will be null. + /// If specified, takes precedence over other configured placement rules. /// - public ICollection Transfers { get; init; } = null; + public string DestinationDirectory { get; init; } /* future: [NotMapped] properties that aggregate values from the associated Transfer records. -- cgit v1.2.3 From e3f6063d841933c3dcc6b16674613458a95c8c6f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 23:45:02 -0500 Subject: fix up transfer --- src/slskd/Transfers/Types/Transfer.cs | 205 +++++++++++++++++++++++----------- 1 file changed, 139 insertions(+), 66 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 90fbe612..8d1afa25 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -31,71 +31,144 @@ // namespace slskd.Transfers; + +using System; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; +using Soulseek; + +/// +/// A file Transfer between network peers. +/// +public class Transfer { - using System; - using System.ComponentModel.DataAnnotations; - using System.ComponentModel.DataAnnotations.Schema; - using System.Text.Json.Serialization; - using Soulseek; - - public class Transfer - { - public Guid? BatchId { get; init; } = null; - - [Key] - public Guid Id { get; init; } - public string Username { get; init; } - public TransferDirection Direction { get; init; } - - /// - /// Gets the remote filename. - /// - public string Filename { get; init; } - public long Size { get; set; } - public long StartOffset { get; init; } - - public TransferStates State { get; set; } = TransferStates.None; - - /// - /// Gets the string representation of the transfer . - /// - /// - /// This is a hack to get the string into the database. *DO NOT* use this property in code - /// and especially **DO NOT** set the value. The getter and setter can't be protected because - /// EF Core needs them to be public. - /// - public string StateDescription { get; set; } - public DateTime RequestedAt { get; set; } - public DateTime? EnqueuedAt { get; set; } - public DateTime? StartedAt { get; set; } - - /// - /// The time at which the transfer ended, or null if the transfer has not yet started or is in progress. - /// - /// - /// Guaranteed to be set for transfers in a terminal state. - /// - public DateTime? EndedAt { get; set; } - public long BytesTransferred { get; set; } - public double AverageSpeed { get; set; } - - public int? PlaceInQueue { get; set; } - public string Exception { get; set; } - - public int Attempts { get; set; } = 0; - - public DateTime? NextAttemptAt { get; set; } = null; - - [JsonIgnore] - public bool Removed { get; set; } - - [NotMapped] - public long BytesRemaining => Size - BytesTransferred; - [NotMapped] - public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value; - [NotMapped] - public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100; - [NotMapped] - public TimeSpan? RemainingTime => AverageSpeed == 0 ? null : TimeSpan.FromSeconds(BytesRemaining / AverageSpeed); - } + /// + /// Gets the associated , if one was specified when the Transfer was created. + /// + public Guid? BatchId { get; init; } = null; + + /// + /// Gets the unique identifier for the Transfer. + /// + [Key] + public Guid Id { get; init; } + + /// + /// Gets the remote username associated with the Transfer. + /// + public string Username { get; init; } + + /// + /// Gets the Transfer direction (Upload, Download). + /// + public TransferDirection Direction { get; init; } + + /// + /// Gets the remote filename of the file. + /// + /// + /// Exactly as it appeared in the originating Search, Browse, or file directory contents response. + /// + public string Filename { get; init; } + + /// + /// Gets or sets the remote size of the file. + /// + public long Size { get; set; } + + /// + /// Gets or sets the state of the Transfer. + /// + public TransferStates State { get; set; } = TransferStates.None; + + /// + /// Gets or sets the string representation of the transfer . + /// + /// + /// This is a hack to get the string into the database. *DO NOT* use this property in code + /// and especially **DO NOT** set the value. The getter and setter can't be protected because + /// EF Core needs them to be public. + /// + public string StateDescription { get; set; } + + /// + /// Gets or sets the time at which the Transfer was requested from the remote peer. + /// + public DateTime RequestedAt { get; set; } + + /// + /// Gets or sets the time at which the Transfer was enqueued, or null if the Transfer has not yet been enqueued. + /// + /// + /// For downloads, this is the time at which the remote peer responded to our enqueue request. For uploads this + /// is the time at which the transfer was made available for scheduling by the upload queue, after we have + /// responded to the remote peer's request to enqueue. + /// + public DateTime? EnqueuedAt { get; set; } + + /// + /// Gets or sets the time at which the Transfer connection was established and data transfer began, or null if the + /// Transfer has not yet been started. + /// + public DateTime? StartedAt { get; set; } + + /// + /// Gets or sets the time at which the Transfer ended, or null if the Transfer has not yet started or is still in progress. + /// + /// + /// Guaranteed to be set for transfers in a terminal state. + /// + public DateTime? EndedAt { get; set; } + + /// + /// Gets or sets the number of bytes transferred. + /// + public long BytesTransferred { get; set; } + + /// + /// Gets or sets the average speed of the Transfer over the duration. + /// + public double AverageSpeed { get; set; } + + /// + /// Gets or sets the current place in line in the remote peer's queue, if place has been requested. + /// + /// + /// May be wildly innacurate to the point of uselessness. + /// + public int? PlaceInQueue { get; set; } + + /// + /// Gets or sets the associated Exception, if the Transfer did not end successfully, or null if it did. + /// + public string Exception { get; set; } + + /// + /// Gets or sets the number of attempts. Incremented each time the Transfer is retried. + /// + /// + /// Applicable to downloads only. + /// + public int Attempts { get; set; } = 0; + + /// + /// Gets or sets the time at which the next retry attempt will be made, if applicable. + /// + public DateTime? NextAttemptAt { get; set; } = null; + + /// + /// Gets or sets a value indicating whether the Transfer has been removed from the UI. + /// + [JsonIgnore] + public bool Removed { get; set; } + + [NotMapped] + public long BytesRemaining => Size - BytesTransferred; + [NotMapped] + public TimeSpan? ElapsedTime => StartedAt == null ? null : (EndedAt ?? DateTime.UtcNow) - StartedAt.Value; + [NotMapped] + public double PercentComplete => Size == 0 ? 0 : (BytesTransferred / (double)Size) * 100; + [NotMapped] + public TimeSpan? RemainingTime => AverageSpeed == 0 ? null : TimeSpan.FromSeconds(BytesRemaining / AverageSpeed); } \ No newline at end of file -- cgit v1.2.3 From 8ddc38f768e18a7c72a3b904446fdb01835092bd Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 10:04:14 -0500 Subject: disable weird rule --- src/web/.eslintrc.js | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/web/.eslintrc.js b/src/web/.eslintrc.js index 0c36e3ed..81d1001c 100644 --- a/src/web/.eslintrc.js +++ b/src/web/.eslintrc.js @@ -5,6 +5,7 @@ const overrides = { 'no-eq-null': 'off', // noisy 'react/forbid-component-props': 'off', // noisy 'react/prop-types': 'off', // noisy + 'canonical/sort-keys': 'off', // noisy 'unicorn/no-array-reduce': 'off', // noisy }; -- cgit v1.2.3 From 8a22018aefbb89d1b74788a0d6bda97b0d8da6b0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 10:05:03 -0500 Subject: use state for message input instead of dom ref (causing delay in updates) --- src/web/src/components/Chat/Chat.jsx | 26 ++++++++++---------------- 1 file changed, 10 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx index 23619bd1..9e3605b8 100644 --- a/src/web/src/components/Chat/Chat.jsx +++ b/src/web/src/components/Chat/Chat.jsx @@ -20,6 +20,7 @@ const initialState = { conversations: {}, interval: undefined, loading: false, + message: '', }; class Chat extends Component { @@ -106,21 +107,15 @@ class Chat extends Component { await chat.acknowledge({ username }); }; - sendMessage = async (username, message) => { - if (!username || !message || username === '') return; - await chat.send({ message, username }); - }; - sendReply = async () => { - const { active } = this.state; - const message = this.messageRef.current.value; + const { active, message } = this.state; if (!this.validInput()) { return; } - await this.sendMessage(active, message); - this.messageRef.current.value = ''; + await chat.send({ username: active, message }); + this.setState({ message: '' }); // force a refresh to append the message // we could probably do this in the browser but we can be lazy @@ -129,12 +124,7 @@ class Chat extends Component { validInput = () => (this.state.active || '').length > 0 && - ( - (this.messageRef && - this.messageRef.current && - this.messageRef.current.value) || - '' - ).length > 0; + (this.state.message || '').length > 0; focusInput = () => { this.messageRef.current.focus(); @@ -294,7 +284,7 @@ class Chat extends Component { name="send" /> ), - onClick: this.sendMessage, + onClick: this.sendReply, }} fluid input={ @@ -302,7 +292,11 @@ class Chat extends Component { autoComplete="off" data-lpignore="true" id="chat-message-input" + onChange={(event) => + this.setState({ message: event.target.value }) + } type="text" + value={this.state.message} /> } onKeyUp={(event) => -- cgit v1.2.3 From e70664167d1766b63a12fa1833b452a217e8b6cc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 10:05:18 -0500 Subject: focus input when conversation is loaded --- src/web/src/components/Chat/Chat.jsx | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx index 9e3605b8..0a080466 100644 --- a/src/web/src/components/Chat/Chat.jsx +++ b/src/web/src/components/Chat/Chat.jsx @@ -170,6 +170,12 @@ class Chat extends Component { } catch { // no-op } + + try { + this.messageRef.current.focus(); + } catch { + // no-op + } }, ); }, -- cgit v1.2.3 From 402b4d7509c582bd2d93e73a33778068e660259e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 11:09:33 -0500 Subject: use state instead of dom ref for rooms --- src/web/src/components/Rooms/Rooms.jsx | 31 ++++++++++++++++++++----------- 1 file changed, 20 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx index 0f2e4382..d30828eb 100644 --- a/src/web/src/components/Rooms/Rooms.jsx +++ b/src/web/src/components/Rooms/Rooms.jsx @@ -32,6 +32,7 @@ const initialState = { }, joined: [], loading: false, + message: '', room: { messages: [], users: [], @@ -131,6 +132,12 @@ class Rooms extends Component { } catch { // no-op } + + try { + this.messageRef.current.focus(); + } catch { + // no-op + } }); }, ); @@ -150,12 +157,7 @@ class Rooms extends Component { validInput = () => (this.state.active || '').length > 0 && - ( - (this.messageRef && - this.messageRef.current && - this.messageRef.current.value) || - '' - ).length > 0; + (this.state.message || '').length > 0; focusInput = () => { this.messageRef.current.focus(); @@ -174,15 +176,14 @@ class Rooms extends Component { }; sendMessage = async () => { - const { active } = this.state; - const message = this.messageRef.current.value; + const { active, message } = this.state; if (!this.validInput()) { return; } await rooms.sendMessage({ message, roomName: active }); - this.messageRef.current.value = ''; + this.setState({ message: '' }); }; handleContextMenu = (clickEvent, message) => { @@ -207,8 +208,12 @@ class Rooms extends Component { }; handleReply = () => { - this.messageRef.current.value = `[${this.state.contextMenu.message.username}] ${this.state.contextMenu.message.message} --> `; - this.focusInput(); + this.setState( + (previousState) => ({ + message: `[${previousState.contextMenu.message.username}] ${previousState.contextMenu.message.message} --> `, + }), + () => this.focusInput(), + ); }; handleUserProfile = () => { @@ -364,7 +369,11 @@ class Rooms extends Component { autoComplete="off" data-lpignore="true" id="room-message-input" + onChange={(event) => + this.setState({ message: event.target.value }) + } type="text" + value={this.state.message} /> } onKeyUp={(event) => -- cgit v1.2.3 From a232848ee4f5539b0041e3581705edd00aec80f0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 13:27:20 -0500 Subject: clear any captured message when changing room/conversation --- src/web/src/components/Chat/Chat.jsx | 1 + src/web/src/components/Rooms/Rooms.jsx | 1 + 2 files changed, 2 insertions(+) (limited to 'src') diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx index 0a080466..72960129 100644 --- a/src/web/src/components/Chat/Chat.jsx +++ b/src/web/src/components/Chat/Chat.jsx @@ -147,6 +147,7 @@ class Chat extends Component { { active: username, loading: true, + message: '', }, async () => { const { active, conversations } = this.state; diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx index d30828eb..0b1366fd 100644 --- a/src/web/src/components/Rooms/Rooms.jsx +++ b/src/web/src/components/Rooms/Rooms.jsx @@ -118,6 +118,7 @@ class Rooms extends Component { { active: roomName, loading: true, + message: '', room: initialState.room, }, async () => { -- cgit v1.2.3 From 9a7556a9c9b3c1313f11f369d8b38ad8fe144b58 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 13:30:50 -0500 Subject: don't clear the message if the same room/convo is re-selected Co-authored-by: Copilot --- src/web/src/components/Chat/Chat.jsx | 6 +++--- src/web/src/components/Rooms/Rooms.jsx | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx index 72960129..086d2cd8 100644 --- a/src/web/src/components/Chat/Chat.jsx +++ b/src/web/src/components/Chat/Chat.jsx @@ -144,11 +144,11 @@ class Chat extends Component { selectConversation = (username) => { this.setState( - { + (previousState) => ({ active: username, loading: true, - message: '', - }, + message: previousState.active === username ? previousState.message : '', + }), async () => { const { active, conversations } = this.state; diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx index 0b1366fd..3d29242b 100644 --- a/src/web/src/components/Rooms/Rooms.jsx +++ b/src/web/src/components/Rooms/Rooms.jsx @@ -115,12 +115,12 @@ class Rooms extends Component { selectRoom = async (roomName) => { this.setState( - { + (previousState) => ({ active: roomName, loading: true, - message: '', + message: previousState.active === roomName ? previousState.message : '', room: initialState.room, - }, + }), async () => { const { active } = this.state; -- cgit v1.2.3 From 9ad8b004544e9edcf5141f536bb6be99b49dba51 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 13:51:20 -0500 Subject: memoize history Co-authored-by: Copilot --- src/web/src/components/Chat/Chat.jsx | 58 ++++++++++++++++++++++------------ src/web/src/components/Rooms/Rooms.jsx | 58 ++++++++++++++++++++-------------- 2 files changed, 73 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/web/src/components/Chat/Chat.jsx b/src/web/src/components/Chat/Chat.jsx index 086d2cd8..39dd1a44 100644 --- a/src/web/src/components/Chat/Chat.jsx +++ b/src/web/src/components/Chat/Chat.jsx @@ -23,6 +23,32 @@ const initialState = { message: '', }; +const ChatMessageHistory = React.memo( + ({ formatTimestamp, messages, selfUsername }) => { + return ( + <> + {messages.map((message) => ( + + + {formatTimestamp(message.timestamp)} + + + {message.direction === 'Out' ? selfUsername : message.username}: + + {message.message} + + ))} + + + ); + }, +); + +ChatMessageHistory.displayName = 'ChatMessageHistory'; + class Chat extends Component { constructor(props) { super(props); @@ -63,6 +89,13 @@ class Chat extends Component { // fetch all of the active conversations (but no messages) let conversations = await chat.getAll(); + // the username '..' breaks nearly everything in slskd because it's a path traversal + // sequence and no API endpoints that expect usernames in the path work + // rather than letting this sit broken, i'm making the choice to filter it out + // eslint-disable-next-line no-warning-comments + // todo: remove this filter when the API can handle '..' + conversations = conversations.filter((f) => f.username !== '..'); + // turn into a map, keyed by username // if there are no active conversations, set to an empty map if (conversations.length === 0) { @@ -257,26 +290,11 @@ class Chat extends Component { - {messages.map((message) => ( - - - {this.formatTimestamp(message.timestamp)} - - - {message.direction === 'Out' - ? user.username - : message.username} - :{' '} - - - {message.message} - - - ))} - + diff --git a/src/web/src/components/Rooms/Rooms.jsx b/src/web/src/components/Rooms/Rooms.jsx index 3d29242b..f6bdb685 100644 --- a/src/web/src/components/Rooms/Rooms.jsx +++ b/src/web/src/components/Rooms/Rooms.jsx @@ -39,6 +39,36 @@ const initialState = { }, }; +const RoomMessageHistory = React.memo( + ({ formatTimestamp, messages, onHandleContextMenu }) => { + return ( + <> + {messages.map((message) => ( +
+ onHandleContextMenu(clickEvent, message) + } + > + + + {formatTimestamp(message.timestamp)} + + {message.username}: + {message.message} + +
+ ))} + + + ); + }, +); + +RoomMessageHistory.displayName = 'RoomMessageHistory'; + class Rooms extends Component { constructor(props) { super(props); @@ -325,29 +355,11 @@ class Rooms extends Component { - {room.messages.map((message) => ( -
- this.handleContextMenu(clickEvent, message) - } - > - - - {this.formatTimestamp(message.timestamp)} - - - {message.username}:{' '} - - - {message.message} - - -
- ))} - +
-- cgit v1.2.3 From c935b990b7979491b03d7b5d861d75a67ad6f3f9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:02:25 -0500 Subject: remove file counts and size --- src/slskd/Transfers/Types/Batch.cs | 14 ++++---------- 1 file changed, 4 insertions(+), 10 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index ac7025fb..3da583f3 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -76,16 +76,6 @@ public record Batch /// public TransferDirection Direction { get; init; } = TransferDirection.Download; - /// - /// Gets the number of files included in the Batch. - /// - public int FileCount { get; init; } - - /// - /// Gets the sum of the included file's sizes. - /// - public long FileSize { get; init; } - /// /// Gets the time at which the Batch was created. /// @@ -115,6 +105,10 @@ public record Batch but determining whether a Search has been fulfilled, allowing a user to override a download directory, or to handle an event when a batch is completed, we can add them and figure out how persistence should work. + file count and size are also not included because of the transfer deduplication that takes place during + the enqueue; if a batch is created and some or all of the files within are already in progress, they are + dropped and no new transfer records are created. this would create data inconsistency, and for no reason (for now) + loading Transfers and doing aggregation in memory (if fetching 1 batch) or querying and aggregating Transfer records in SQL and then updating a list of Batch records in memory (if fetching a list) technically works, but is unlikely to perform well, especially as data grows, and ESPECIALLY when excliding 'Removed' Batches -- cgit v1.2.3 From 08380a1a150f58839798ca3289aa8b5542f41086 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:37:00 -0500 Subject: shuffle some things around --- src/slskd/Program.cs | 1 + src/slskd/Transfers/Batches/BatchService.cs | 179 ----------------------- src/slskd/Transfers/Downloads/BatchService.cs | 122 +++++++++++++++ src/slskd/Transfers/Downloads/DownloadService.cs | 12 ++ 4 files changed, 135 insertions(+), 179 deletions(-) delete mode 100644 src/slskd/Transfers/Batches/BatchService.cs create mode 100644 src/slskd/Transfers/Downloads/BatchService.cs (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 42f43918..d4baf276 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -780,6 +780,7 @@ namespace slskd services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); + services.AddSingleton(); services.AddSingleton(); services.AddSingleton(); diff --git a/src/slskd/Transfers/Batches/BatchService.cs b/src/slskd/Transfers/Batches/BatchService.cs deleted file mode 100644 index aadaa820..00000000 --- a/src/slskd/Transfers/Batches/BatchService.cs +++ /dev/null @@ -1,179 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Transfers -{ - using System; - using System.Collections.Generic; - using System.Linq; - using System.Linq.Expressions; - using System.Threading.Tasks; - using Microsoft.EntityFrameworkCore; - using Serilog; - - /// - /// Manages transfer batches. - /// - public interface IBatchService - { - /// - /// Creates a new batch record. - /// - /// The batch to create. - /// The created batch. - Batch Create(Batch batch); - - /// - /// Finds a single batch matching the specified . - /// - /// The expression to use to match batches. - /// The found batch, or default if not found. - /// Thrown when an expression is not supplied. - Task FindAsync(Expression> expression); - - /// - /// Returns a list of all batches matching the optional . - /// - /// An optional expression used to match batches. - /// The list of batches matching the specified expression, or all batches if no expression is specified. - Task> ListAsync(Expression> expression = null); - - /// - /// Marks all transfers associated with the specified batch as removed. - /// - /// The unique identifier of the batch. - /// Thrown when the batch does not exist. - void Remove(Guid id); - } - - /// - /// Manages transfer batches. - /// - public class BatchService : IBatchService - { - /// - /// Initializes a new instance of the class. - /// - /// The database context factory to use. - public BatchService(IDbContextFactory contextFactory) - { - ContextFactory = contextFactory; - } - - private IDbContextFactory ContextFactory { get; } - private ILogger Log { get; } = Serilog.Log.ForContext(); - - /// - /// Creates a new batch record. - /// - /// The batch to create. - /// The created batch. - public Batch Create(Batch batch) - { - if (batch == default) - { - throw new ArgumentNullException(nameof(batch)); - } - - using var context = ContextFactory.CreateDbContext(); - context.Batches.Add(batch); - context.SaveChanges(); - - Log.Debug("Created batch {Id}", batch.Id); - - return batch; - } - - /// - /// Finds a single batch matching the specified . - /// - /// The expression to use to match batches. - /// The found batch, or default if not found. - /// Thrown when an expression is not supplied. - public async Task FindAsync(Expression> expression) - { - if (expression == default) - { - throw new ArgumentException("An expression must be supplied.", nameof(expression)); - } - - using var context = ContextFactory.CreateDbContext(); - - return await context.Batches - .AsNoTracking() - .Include(b => b.Transfers) - .Where(expression) - .SingleOrDefaultAsync(); - } - - /// - /// Returns a list of all batches matching the optional . - /// - /// An optional expression used to match batches. - /// The list of batches matching the specified expression, or all batches if no expression is specified. - public async Task> ListAsync(Expression> expression = null) - { - expression ??= b => true; - - using var context = ContextFactory.CreateDbContext(); - - return await context.Batches - .AsNoTracking() - .Include(b => b.Transfers) - .Where(expression) - .ToListAsync(); - } - - /// - /// Marks all transfers associated with the specified batch as removed. - /// - /// The unique identifier of the batch. - /// Thrown when the batch does not exist. - public void Remove(Guid id) - { - using var context = ContextFactory.CreateDbContext(); - - var exists = context.Batches.Any(b => b.Id == id); - - if (!exists) - { - throw new NotFoundException($"No batch with id {id}"); - } - - context.Transfers - .Where(t => t.BatchId == id) - .ExecuteUpdate(s => s.SetProperty(t => t.Removed, true)); - - Log.Debug("Marked transfers for batch {Id} as removed", id); - } - } -} diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs new file mode 100644 index 00000000..7a4ba055 --- /dev/null +++ b/src/slskd/Transfers/Downloads/BatchService.cs @@ -0,0 +1,122 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers.Downloads; + +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Serilog; + +/// +/// Manages transfer batches. +/// +public interface IBatchService +{ + /// + /// Creates a new batch record. + /// + /// The batch to create. + /// The created batch. + Batch Create(Batch batch); + + /// + /// Finds a single batch matching the specified . + /// + /// The expression to use to match batches. + /// The found batch, or default if not found. + /// Thrown when an expression is not supplied. + Task FindAsync(Expression> expression); +} + +/// +/// Manages transfer batches. +/// +public class BatchService : IBatchService +{ + /// + /// Initializes a new instance of the class. + /// + /// The database context factory to use. + public BatchService(IDbContextFactory contextFactory) + { + ContextFactory = contextFactory; + } + + private IDbContextFactory ContextFactory { get; } + private ILogger Log { get; } = Serilog.Log.ForContext(); + + /// + /// Creates a new batch record. + /// + /// The batch to create. + /// The created batch. + public Batch Create(Batch batch) + { + if (batch == default) + { + throw new ArgumentNullException(nameof(batch)); + } + + using var context = ContextFactory.CreateDbContext(); + context.Batches.Add(batch); + context.SaveChanges(); + + Log.Debug("Created batch {Id}", batch.Id); + + return batch; + } + + /// + /// Finds a single batch matching the specified . + /// + /// The expression to use to match batches. + /// The found batch, or default if not found. + /// Thrown when an expression is not supplied. + public async Task FindAsync(Expression> expression) + { + if (expression == default) + { + throw new ArgumentException("An expression must be supplied.", nameof(expression)); + } + + using var context = ContextFactory.CreateDbContext(); + + return await context.Batches + .AsNoTracking() + .Include(b => b.Transfers) + .Where(expression) + .SingleOrDefaultAsync(); + } +} diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index aba6ca9d..9e898570 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -55,6 +55,11 @@ namespace slskd.Transfers.Downloads ///
public interface IDownloadService { + /// + /// Gets download batch service. + /// + IBatchService Batches { get; } + /// /// Adds the specified . Supersedes any existing record for the same file and username. /// @@ -158,6 +163,7 @@ namespace slskd.Transfers.Downloads public class DownloadService : IDownloadService { public DownloadService( + IBatchService batchService, IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory contextFactory, @@ -166,6 +172,7 @@ namespace slskd.Transfers.Downloads IFTPService ftpClient, EventBus eventBus) { + Batches = batchService; Client = soulseekClient; OptionsMonitor = optionsMonitor; ContextFactory = contextFactory; @@ -177,6 +184,11 @@ namespace slskd.Transfers.Downloads Clock.EveryMinute += (_, _) => Task.Run(() => CleanupEnqueueSemaphoresAsync()); } + /// + /// Gets download batch service. + /// + public IBatchService Batches { get; } + /// /// These tokens give users the ability to cancel transfers via the UI (or API). /// -- cgit v1.2.3 From d45e33185daf1e0320ce60e3c324dbf3efae49ef Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:44:16 -0500 Subject: rough in options json support --- src/slskd/Transfers/TransfersDbContext.cs | 9 ++++++ src/slskd/Transfers/Types/Batch.cs | 8 ++---- src/slskd/Transfers/Types/BatchOptions.cs | 48 +++++++++++++++++++++++++++++++ 3 files changed, 59 insertions(+), 6 deletions(-) create mode 100644 src/slskd/Transfers/Types/BatchOptions.cs (limited to 'src') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index ce2d9f52..699eed6c 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -33,6 +33,7 @@ namespace slskd.Transfers { using System; + using System.Text.Json; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Storage.ValueConversion; @@ -135,6 +136,14 @@ namespace slskd.Transfers .WithOne() .HasForeignKey(t => t.BatchId) .IsRequired(false); + + modelBuilder + .Entity() + .Property(b => b.Options) + .HasConversion( + convertToProviderExpression: v => JsonSerializer.Serialize(v, JsonSerializerOptions.Default), + convertFromProviderExpression: v => JsonSerializer.Deserialize(v, JsonSerializerOptions.Default)) + .HasColumnType("TEXT"); } } } diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index 3da583f3..d4234e30 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -91,13 +91,9 @@ public record Batch public ICollection Transfers { get; init; } = null; /// - /// Gets the optional destination directory for the files in the Batch, relative to the configured - /// download directory. + /// Gets the options for the batch. /// - /// - /// If specified, takes precedence over other configured placement rules. - /// - public string DestinationDirectory { get; init; } + public BatchOptions Options { get; init; } /* future: [NotMapped] properties that aggregate values from the associated Transfer records. diff --git a/src/slskd/Transfers/Types/BatchOptions.cs b/src/slskd/Transfers/Types/BatchOptions.cs new file mode 100644 index 00000000..6bacef8c --- /dev/null +++ b/src/slskd/Transfers/Types/BatchOptions.cs @@ -0,0 +1,48 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers; + +/// +/// Options for es. +/// +public record BatchOptions +{ + /// + /// Gets the optional destination directory for the files in the Batch, relative to the configured + /// download directory. + /// + /// + /// If specified, takes precedence over other configured placement rules. + /// + public string Destination { get; init; } +} \ No newline at end of file -- cgit v1.2.3 From 3371921f4897dbff370c91b3171df4f953bfe21f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:44:35 -0500 Subject: move destination to options --- src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs index ce3331ca..28cc7859 100644 --- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs @@ -45,6 +45,7 @@ public record EnqueueDownloadBatchRequest [StringLength(500, MinimumLength = 1)] public string Username { get; init; } public List Files { get; init; } = []; + public EnqueueDownloadBatchOptions Options { get; init; } = new(); } public record EnqueueDownloadBatchItem @@ -54,4 +55,9 @@ public record EnqueueDownloadBatchItem [Range(0, int.MaxValue)] public long Size { get; set; } +} + +public record EnqueueDownloadBatchOptions +{ + public string Destination { get; init; } } \ No newline at end of file -- cgit v1.2.3 From 6585216de3a191b3260c1960f4a0f29daab6b04a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:48:14 -0500 Subject: populate batchid if supplied --- src/slskd/Transfers/Downloads/DownloadService.cs | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9e898570..184acb5d 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -76,12 +76,13 @@ namespace slskd.Transfers.Downloads /// /// The username of remote user. /// The list of files to enqueue. + /// The optional batch id for the transfers. /// The token to monitor for cancellation. /// The operation context. /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default); + Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default); /// /// Finds a single download matching the specified . @@ -261,12 +262,13 @@ namespace slskd.Transfers.Downloads /// /// The username of the remote user. /// The list of files to enqueue. + /// The optional batch id for the transfers. /// The token to monitor for cancellation. /// The operation context. /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, CancellationToken cancellationToken = default) + public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -443,6 +445,7 @@ namespace slskd.Transfers.Downloads var transfer = new Transfer() { Id = transferId, + BatchId = batchId, Username = username, Direction = TransferDirection.Download, Filename = file.Filename, // important! use the remote filename -- cgit v1.2.3 From 89b6bdc087db0fc442492fcc52d0ca7d68e415aa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:48:24 -0500 Subject: rough in batch endpoints --- .../API/Controllers/TransfersController.cs | 173 +++++++++++++-------- 1 file changed, 112 insertions(+), 61 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 9f2fba6d..2e42c6cf 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -216,68 +216,8 @@ namespace slskd.Transfers.API } } - // [HttpPost("downloads")] - // [Authorize(Policy = AuthPolicy.Any)] - // [ProducesResponseType(201)] - // [ProducesResponseType(typeof(string), 403)] - // [ProducesResponseType(typeof(string), 500)] - // public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) - // { - // if (Program.IsRelayAgent) - // { - // return Forbid(); - // } - - // // todo, check: username null or whitespace - // if (!ModelState.IsValid) - // { - // return BadRequest(ModelState.GetReadableString()); - // } - - // if ((request.Files?.Count ?? 0) == 0) - // { - // return BadRequest("At least one file is required"); - // } - - // // todo, check: - // // * filename null or whitespace - // // * size -1 - // if (request.Files.Any(r => r is null)) - // { - // return BadRequest("One or more files in the request are invalid"); - // } - - // if (!DownloadRequestLimiter.Wait(0)) - // { - // return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); - // } - - // try - // { - // var endpoint = await Users.GetIPEndPointAsync(request.Username); - - // if (Users.IsBlacklisted(request.Username, endpoint.Address)) - // { - // throw new UserOfflineException($"User {request.Username} appears to be offline"); - // } - - // var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(request.Username, requests.Select(r => (r.Filename, r.Size))); - - // return StatusCode(201, new { Enqueued = enqueued, Failed = failed }); - // } - // catch (Exception ex) - // { - // Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", requests.Count(), username, ex.Message); - // return StatusCode(500, ex.Message); - // } - // finally - // { - // DownloadRequestLimiter.Release(); - // } - // } - /// - /// Enqueues the specified download. + /// (Obsolete) Enqueues the specified download. /// /// The username of the download source. /// The list of download requests. @@ -285,6 +225,7 @@ namespace slskd.Transfers.API /// The download was successfully enqueued. /// The download was rejected. /// An unexpected error was encountered. + [Obsolete("Will be phased out in future versions; use batches")] [HttpPost("downloads/{username}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(201)] @@ -341,6 +282,75 @@ namespace slskd.Transfers.API } } + [HttpPost("downloads/batches")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(201)] + [ProducesResponseType(typeof(string), 403)] + [ProducesResponseType(typeof(string), 500)] + public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) + { + if (Program.IsRelayAgent) + { + return Forbid(); + } + + if (!ModelState.IsValid) + { + return BadRequest(ModelState.GetReadableString()); + } + + if ((request.Files?.Count ?? 0) == 0) + { + return BadRequest("At least one file is required"); + } + + if (request.Files.Any( + r => r is null + || string.IsNullOrWhiteSpace(r.Filename) + || r.Size < 0)) + { + return BadRequest("One or more files in the request are invalid"); + } + + if (!DownloadRequestLimiter.Wait(0)) + { + return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); + } + + try + { + var endpoint = await Users.GetIPEndPointAsync(request.Username); + + if (Users.IsBlacklisted(request.Username, endpoint.Address)) + { + throw new UserOfflineException($"User {request.Username} appears to be offline"); + } + + // todo: finish this + // await Transfers.Downloads.Batches.Create(new() + // { + // Id = request.BatchId, + // SearchId = request.SearchId, + // Options = request.Options, + // }); + + var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(request.Username, request.Files.Select(r => (r.Filename, r.Size))); + + var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == request.BatchId); + + return StatusCode(201, batch); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", request.Files.Count(), request.Username, ex.Message); + return StatusCode(500, ex.Message); + } + finally + { + DownloadRequestLimiter.Release(); + } + } + /// /// Gets all downloads. /// @@ -372,6 +382,47 @@ namespace slskd.Transfers.API return Ok(response); } + /// + /// Gets the specified batch and associated transfers. + /// + /// The id of the batch. + /// + /// The specified id is not valid. + /// The request completed successfully. + /// The specified batch was not found. + [HttpGet("downloads/batches/{id}")] + [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(200)] + public async Task Get([FromRoute, Required] string id) + { + if (Program.IsRelayAgent) + { + return Forbid(); + } + + if (!Guid.TryParse(id, out var guid)) + { + return BadRequest(); + } + + try + { + var found = await Transfers.Downloads.Batches.FindAsync(b => b.Id == guid); + + if (found is null) + { + return NotFound(); + } + + return Ok(found); + } + catch (Exception ex) + { + Log.Error(ex, "Failed to get batch with ID {Id}: {Message}", guid, ex.Message); + return StatusCode(500, ex.Message); + } + } + /// /// Gets all downloads for the specified username. /// -- cgit v1.2.3 From 2084810036f695f0766c9cb972a3d6f1eea234cb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 22:20:47 -0500 Subject: add extension to get json serializer settings --- src/slskd/Common/CommonExtensions.cs | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 77db91ef..8e6d5603 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -555,9 +555,17 @@ namespace slskd /// The new object deserialized from the string. public static T FromJson(this string str) => JsonSerializer.Deserialize(str, GetJsonSerializerOptions()); - private static JsonSerializerOptions GetJsonSerializerOptions() + /// + /// Applies the standard json serializer options to the specified instance. + /// + /// The instance. + /// The instances with the standard options applied. + public static JsonSerializerOptions WithStandardOptions(this JsonSerializerOptions opt) + => GetJsonSerializerOptions(opt); + + private static JsonSerializerOptions GetJsonSerializerOptions(JsonSerializerOptions opt = null) { - var options = new JsonSerializerOptions(); + var options = opt ?? new JsonSerializerOptions(); options.Converters.Add(new IPAddressConverter()); options.Converters.Add(new JsonStringEnumConverter()); options.Converters.Add(new KnownUnsupportedTypeConverter()); -- cgit v1.2.3 From 8508606e16aa5ed00ca9d3e19d85e576e383aa63 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 22:21:00 -0500 Subject: use standard json options --- src/slskd/Transfers/TransfersDbContext.cs | 4 ++-- src/slskd/Transfers/Types/Batch.cs | 6 +----- 2 files changed, 3 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 699eed6c..912c1ada 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -141,8 +141,8 @@ namespace slskd.Transfers .Entity() .Property(b => b.Options) .HasConversion( - convertToProviderExpression: v => JsonSerializer.Serialize(v, JsonSerializerOptions.Default), - convertFromProviderExpression: v => JsonSerializer.Deserialize(v, JsonSerializerOptions.Default)) + convertToProviderExpression: v => JsonSerializer.Serialize(v, new JsonSerializerOptions().WithStandardOptions()), + convertFromProviderExpression: v => JsonSerializer.Deserialize(v, new JsonSerializerOptions().WithStandardOptions())) .HasColumnType("TEXT"); } } diff --git a/src/slskd/Transfers/Types/Batch.cs b/src/slskd/Transfers/Types/Batch.cs index d4234e30..a0d71bef 100644 --- a/src/slskd/Transfers/Types/Batch.cs +++ b/src/slskd/Transfers/Types/Batch.cs @@ -44,7 +44,7 @@ using Soulseek; /// /// /// Transfers may be enqueued in a Batch, and a caller that enqueued a Batch may use the -/// available API(s) to determine whether all of the Transfers within the Batch is complete, +/// available API(s) to determine whether all of the Transfers within the Batch are complete, /// but otherwise a Batch serves no functional purpose within the application. /// /// @@ -84,10 +84,6 @@ public record Batch /// /// Gets the Transfer records associated with the batch. /// - /// - /// Lazy loaded. If not explicitly loaded with the Batch record using Include(), the collection and - /// all of the (future?) statistics will be null. - /// public ICollection Transfers { get; init; } = null; /// -- cgit v1.2.3 From 16aeb34e118ee2d4770bcace3aa06a7615a2eae6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 4 May 2026 22:13:44 -0500 Subject: tweak dto --- .../API/DTO/EnqueueDownloadBatchRequest.cs | 63 --------------- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 93 ++++++++++++++++++++++ 2 files changed, 93 insertions(+), 63 deletions(-) delete mode 100644 src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs create mode 100644 src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs deleted file mode 100644 index 28cc7859..00000000 --- a/src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs +++ /dev/null @@ -1,63 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -using System; -using System.Collections.Generic; -using System.ComponentModel.DataAnnotations; - -namespace slskd.Transfers.API; - -public record EnqueueDownloadBatchRequest -{ - public Guid? BatchId { get; init; } - public Guid? SearchId { get; init; } - - [Required] - [StringLength(500, MinimumLength = 1)] - public string Username { get; init; } - public List Files { get; init; } = []; - public EnqueueDownloadBatchOptions Options { get; init; } = new(); -} - -public record EnqueueDownloadBatchItem -{ - [Required] - public string Filename { get; set; } - - [Range(0, int.MaxValue)] - public long Size { get; set; } -} - -public record EnqueueDownloadBatchOptions -{ - public string Destination { get; init; } -} \ No newline at end of file diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs new file mode 100644 index 00000000..0aaf1034 --- /dev/null +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -0,0 +1,93 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +using System; +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; + +namespace slskd.Transfers.API; + +public record QueueDownloadBatchRequest +{ + /// + /// The ID of the Batch. + /// + /// + /// If not supplied, one will be randomly generated. + /// + public Guid? Id { get; init; } = Guid.NewGuid(); + + /// + /// The ID of the associated Search, if applicable. + /// + public Guid? SearchId { get; init; } + + /// + /// The username of the user from which to download. + /// + [Required] + [StringLength(500, MinimumLength = 1)] + public string Username { get; init; } + + /// + /// The list of files to download. + /// + public List Files { get; init; } = []; + + /// + /// Options for the Batch. + /// + public EnqueueDownloadBatchOptions Options { get; init; } = new(); +} + +public record EnqueueDownloadBatchItem +{ + /// + /// The name of the file. + /// + [Required] + public string Filename { get; set; } + + /// + /// The file size. + /// + [Range(0, int.MaxValue)] + public long Size { get; set; } +} + +public record EnqueueDownloadBatchOptions +{ + /// + /// The destination directory for the files, relative to the configured download directory. + /// + public string Destination { get; init; } +} \ No newline at end of file -- cgit v1.2.3 From 7e61670105fdb1efd164b2d89194a1699a9943db Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 4 May 2026 22:13:53 -0500 Subject: make create async --- src/slskd/Transfers/Downloads/BatchService.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs index 7a4ba055..29de8e14 100644 --- a/src/slskd/Transfers/Downloads/BatchService.cs +++ b/src/slskd/Transfers/Downloads/BatchService.cs @@ -49,7 +49,7 @@ public interface IBatchService /// /// The batch to create. /// The created batch. - Batch Create(Batch batch); + Task CreateAsync(Batch batch); /// /// Finds a single batch matching the specified . @@ -82,7 +82,7 @@ public class BatchService : IBatchService /// /// The batch to create. /// The created batch. - public Batch Create(Batch batch) + public async Task CreateAsync(Batch batch) { if (batch == default) { @@ -91,7 +91,7 @@ public class BatchService : IBatchService using var context = ContextFactory.CreateDbContext(); context.Batches.Add(batch); - context.SaveChanges(); + await context.SaveChangesAsync(); Log.Debug("Created batch {Id}", batch.Id); -- cgit v1.2.3 From 22cc518863f5f2f0169e5fcbd83a91ebda15a5ef Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 4 May 2026 22:14:03 -0500 Subject: finish endpoint --- .../API/Controllers/TransfersController.cs | 44 ++++++++++++++++------ 1 file changed, 33 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 2e42c6cf..44f7a146 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -282,12 +282,13 @@ namespace slskd.Transfers.API } } - [HttpPost("downloads/batches")] + [HttpPost("downloads")] [Authorize(Policy = AuthPolicy.Any)] + [ProducesResponseType(200)] [ProducesResponseType(201)] [ProducesResponseType(typeof(string), 403)] [ProducesResponseType(typeof(string), 500)] - public async Task EnqueueBatchAsync([FromBody] EnqueueDownloadBatchRequest request) + public async Task EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request) { if (Program.IsRelayAgent) { @@ -326,17 +327,38 @@ namespace slskd.Transfers.API throw new UserOfflineException($"User {request.Username} appears to be offline"); } - // todo: finish this - // await Transfers.Downloads.Batches.Create(new() - // { - // Id = request.BatchId, - // SearchId = request.SearchId, - // Options = request.Options, - // }); + var batchId = request.Id ?? Guid.NewGuid(); - var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync(request.Username, request.Files.Select(r => (r.Filename, r.Size))); + await Transfers.Downloads.Batches.CreateAsync(new() + { + Id = batchId, + SearchId = request.SearchId, + Username = request.Username, + Options = new() + { + Destination = request.Options.Destination, + }, + }); + + // Transfer records will have been inserted before this returns, unless they were rejected + // because they were already in progress, in which case they will show up in 'failed' + var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync( + username: request.Username, + files: request.Files.Select(r => (r.Filename, r.Size)), + batchId: batchId); + + if (failed.Count > 0) + { + Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already in progress", failed.Count, request.Files.Count); + } - var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == request.BatchId); + // the returned batch will have whatever Transfers were successfully inserted attached + var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == request.Id); + + if (batch.Transfers.Count == 0) + { + return Ok(batch); + } return StatusCode(201, batch); } -- cgit v1.2.3 From eec45b7ddaa7fb33cc3831af4d4c849a5c39ca40 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 4 May 2026 22:28:01 -0500 Subject: size is a long, not an int --- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 0aaf1034..21a77e83 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -80,7 +80,7 @@ public record EnqueueDownloadBatchItem /// /// The file size. /// - [Range(0, int.MaxValue)] + [Range(0, long.MaxValue)] public long Size { get; set; } } -- cgit v1.2.3 From a4f0bd664849652893dea35055a186eeab25b06b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 6 May 2026 19:18:32 -0500 Subject: stub migration for batches table --- .../Z2026_05_06_AddBatchesTableMigration.cs | 107 +++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs new file mode 100644 index 00000000..89d718ef --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs @@ -0,0 +1,107 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Migrations; + +using System; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Creates the Batches table in the Transfers database. +/// +public class Z2026_05_06_AddBatchesTableMigration : IMigration +{ + public Z2026_05_06_AddBatchesTableMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + + if (schema.ContainsKey("Batches")) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_05_06_AddBatchesTableMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } + + Log.Information("> Creating the Batches table..."); + + Exec(@" + CREATE TABLE Batches ( + Id TEXT NOT NULL, + SearchId TEXT, + Username TEXT, + Direction INTEGER NOT NULL, + CreatedAt TEXT NOT NULL, + Options TEXT, + CONSTRAINT PK_Batches PRIMARY KEY(Id) + );"); + + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} -- cgit v1.2.3 From 666bdeaea28e2f3a5fdea9d2404a8aa6ffc076da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 6 May 2026 19:25:28 -0500 Subject: add cascade deletes for batches, add index on SearchId --- src/slskd/Transfers/TransfersDbContext.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 912c1ada..13d0984d 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -135,7 +135,8 @@ namespace slskd.Transfers .HasMany(b => b.Transfers) .WithOne() .HasForeignKey(t => t.BatchId) - .IsRequired(false); + .IsRequired(false) + .OnDelete(DeleteBehavior.Cascade); modelBuilder .Entity() @@ -144,6 +145,11 @@ namespace slskd.Transfers convertToProviderExpression: v => JsonSerializer.Serialize(v, new JsonSerializerOptions().WithStandardOptions()), convertFromProviderExpression: v => JsonSerializer.Deserialize(v, new JsonSerializerOptions().WithStandardOptions())) .HasColumnType("TEXT"); + + modelBuilder + .Entity() + .HasIndex(b => b.SearchId) + .HasDatabaseName("IDX_Batches_SearchId"); } } } -- cgit v1.2.3 From 8948664a68875ea4b68a5a5ba61628f985926c2f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 6 May 2026 19:30:54 -0500 Subject: tweak migration --- .../Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs index 89d718ef..fe124680 100644 --- a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs @@ -86,15 +86,16 @@ public class Z2026_05_06_AddBatchesTableMigration : IMigration Exec(@" CREATE TABLE Batches ( - Id TEXT NOT NULL, - SearchId TEXT, - Username TEXT, + Id TEXT NOT NULL CONSTRAINT PK_Batches PRIMARY KEY, + SearchId TEXT NULL, + Username TEXT NULL, Direction INTEGER NOT NULL, CreatedAt TEXT NOT NULL, - Options TEXT, - CONSTRAINT PK_Batches PRIMARY KEY(Id) + Options TEXT NULL );"); + Exec(@"CREATE INDEX IDX_Batches_SearchId ON Batches (SearchId);"); + transaction.Commit(); Log.Information("> Done!"); } -- cgit v1.2.3 From f77b8a40a242d00f72882aff33fe4a4c00fdc06a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 6 May 2026 19:32:02 -0500 Subject: remove nulls --- .../Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs index fe124680..be56bfed 100644 --- a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs @@ -87,11 +87,11 @@ public class Z2026_05_06_AddBatchesTableMigration : IMigration Exec(@" CREATE TABLE Batches ( Id TEXT NOT NULL CONSTRAINT PK_Batches PRIMARY KEY, - SearchId TEXT NULL, - Username TEXT NULL, + SearchId TEXT, + Username TEXT, Direction INTEGER NOT NULL, CreatedAt TEXT NOT NULL, - Options TEXT NULL + Options TEXT );"); Exec(@"CREATE INDEX IDX_Batches_SearchId ON Batches (SearchId);"); -- cgit v1.2.3 From 1bd12fee8216e31f5c13ac0cf07e5fd42f26e8e2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 6 May 2026 19:32:37 -0500 Subject: wire up migration --- src/slskd/Core/Data/Migrator.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 7289b070..61d64e76 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -60,6 +60,7 @@ public class Migrator { nameof(Z2025_07_26_PrivateMessageWasReplayedMigration), new Z2025_07_26_PrivateMessageWasReplayedMigration(connectionStrings: Databases) }, { nameof(Z2025_12_28_AdditionalTransferIndexesMigration), new Z2025_12_28_AdditionalTransferIndexesMigration(connectionStrings: Databases) }, { nameof(Z2026_02_17_TransferAttemptsAndBatchIdMigration), new Z2026_02_17_TransferAttemptsAndBatchIdMigration(connectionStrings: Databases) }, + { nameof(Z2026_05_06_AddBatchesTableMigration), new Z2026_05_06_AddBatchesTableMigration(connectionStrings: Databases) }, }; } -- cgit v1.2.3 From 43524239edba37a1e7b8b9a8e34a0c8f31c4f332 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:13:08 -0500 Subject: add some exceptions --- src/slskd/Common/Exceptions/ConflictException.cs | 75 +++++++++++++++++++++++ src/slskd/Common/Exceptions/DuplicateException.cs | 75 +++++++++++++++++++++++ 2 files changed, 150 insertions(+) create mode 100644 src/slskd/Common/Exceptions/ConflictException.cs create mode 100644 src/slskd/Common/Exceptions/DuplicateException.cs (limited to 'src') 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + + /// + /// Represents errors that originate due to duplication. + /// + [ExcludeFromCodeCoverage] + public class ConflictException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public ConflictException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public ConflictException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + + /// + /// Represents errors that originate due to duplication. + /// + [ExcludeFromCodeCoverage] + public class DuplicateException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public DuplicateException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public DuplicateException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public DuplicateException(string message, Exception innerException) + : base(message, innerException) + { + } + } +} \ No newline at end of file -- cgit v1.2.3 From fb600f5b90e6c313635687414b50869bf86ab653 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:13:28 -0500 Subject: add a validator for relative paths --- .../Common/Validation/AbsoluteFilePathAttribute.cs | 58 ----------------- .../Common/Validation/AbsolutePathAttribute.cs | 58 +++++++++++++++++ .../Common/Validation/RelativePathAttribute.cs | 72 ++++++++++++++++++++++ src/slskd/Core/Options.cs | 2 +- 4 files changed, 131 insertions(+), 59 deletions(-) delete mode 100644 src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs create mode 100644 src/slskd/Common/Validation/AbsolutePathAttribute.cs create mode 100644 src/slskd/Common/Validation/RelativePathAttribute.cs (limited to 'src') diff --git a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs b/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs deleted file mode 100644 index 8f87e479..00000000 --- a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Validation -{ - using System.ComponentModel.DataAnnotations; - using System.IO; - - /// - /// Validates that the specified path is absolute. - /// - public class AbsoluteFilePathAttribute : ValidationAttribute - { - protected override ValidationResult IsValid(object value, ValidationContext validationContext) - { - if (value != null) - { - var filePath = value.ToString(); - - if (!string.IsNullOrEmpty(filePath) && !Path.IsPathRooted(filePath)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); - } - } - - return ValidationResult.Success; - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs new file mode 100644 index 00000000..ef6db8ca --- /dev/null +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -0,0 +1,58 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + using System.IO; + + /// + /// Validates that the specified path is absolute. + /// + public class AbsolutePathAttribute : ValidationAttribute + { + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value != null) + { + var filePath = value.ToString(); + + if (!string.IsNullOrEmpty(filePath) && !Path.IsPathRooted(filePath)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); + } + } + + 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..05f7630d --- /dev/null +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -0,0 +1,72 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation +{ + using System; + using System.ComponentModel.DataAnnotations; + using System.IO; + + /// + /// Validates that the specified path is relative and contains no path traversal segments. + /// + public class RelativePathAttribute : ValidationAttribute + { + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value != null) + { + var path = value.ToString(); + + if (!string.IsNullOrEmpty(path)) + { + if (Path.IsPathRooted(path)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + } + + // use a dummy absolute base to normalize the path; GetFullPath resolves all .. and . segments + var dummyBase = Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + + Path.DirectorySeparatorChar; + var combined = Path.GetFullPath(Path.Combine(dummyBase, path)); + + if (!combined.StartsWith(dummyBase, StringComparison.OrdinalIgnoreCase)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain path traversal segments."); + } + } + } + + return ValidationResult.Success; + } + } +} diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 8cc369af..1ca5b84a 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2010,7 +2010,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; } -- cgit v1.2.3 From 51a5f28e8a946287cf883ccb4403a0efabe3c426 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:14:36 -0500 Subject: punt on traversal for now --- src/slskd/Common/Validation/RelativePathAttribute.cs | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 05f7630d..6cf87e7a 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -32,7 +32,6 @@ namespace slskd.Validation { - using System; using System.ComponentModel.DataAnnotations; using System.IO; @@ -47,22 +46,9 @@ namespace slskd.Validation { var path = value.ToString(); - if (!string.IsNullOrEmpty(path)) + if (!string.IsNullOrEmpty(path) && Path.IsPathRooted(path)) { - if (Path.IsPathRooted(path)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - - // use a dummy absolute base to normalize the path; GetFullPath resolves all .. and . segments - var dummyBase = Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) - + Path.DirectorySeparatorChar; - var combined = Path.GetFullPath(Path.Combine(dummyBase, path)); - - if (!combined.StartsWith(dummyBase, StringComparison.OrdinalIgnoreCase)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must not contain path traversal segments."); - } + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } } -- cgit v1.2.3 From 3afb1123087a03e15c23a75602b8f91094964e79 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:15:49 -0500 Subject: destination must be relative (to the configured download directory) --- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 21a77e83..4a1d32f1 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -33,6 +33,7 @@ using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; +using slskd.Validation; namespace slskd.Transfers.API; @@ -89,5 +90,6 @@ public record EnqueueDownloadBatchOptions /// /// The destination directory for the files, relative to the configured download directory. /// + [RelativePath] public string Destination { get; init; } } \ No newline at end of file -- cgit v1.2.3 From a61917f50b3874640b1bcd3c536a5ca4f38f10e0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:16:19 -0500 Subject: handle conflicts/PK violations, validate more properties --- .../API/Controllers/TransfersController.cs | 9 +++++-- src/slskd/Transfers/Downloads/BatchService.cs | 28 ++++++++++++++++++---- 2 files changed, 30 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 44f7a146..b1275c52 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -282,7 +282,7 @@ namespace slskd.Transfers.API } } - [HttpPost("downloads")] + [HttpPost("downloads/batches")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(201)] @@ -362,9 +362,14 @@ namespace slskd.Transfers.API return StatusCode(201, batch); } + catch (DuplicateException ex) + { + Log.Error(ex, "Failed to enqueue {Count} files for {Username}: A Batch with ID {BatchId} already exists", request.Files.Count, request.Username, request.Id); + return Conflict(); + } catch (Exception ex) { - Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", request.Files.Count(), request.Username, ex.Message); + Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", request.Files.Count, request.Username, ex.Message); return StatusCode(500, ex.Message); } finally diff --git a/src/slskd/Transfers/Downloads/BatchService.cs b/src/slskd/Transfers/Downloads/BatchService.cs index 29de8e14..7ea9a70a 100644 --- a/src/slskd/Transfers/Downloads/BatchService.cs +++ b/src/slskd/Transfers/Downloads/BatchService.cs @@ -36,6 +36,7 @@ using System; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; +using Microsoft.Data.Sqlite; using Microsoft.EntityFrameworkCore; using Serilog; @@ -89,13 +90,30 @@ public class BatchService : IBatchService throw new ArgumentNullException(nameof(batch)); } - using var context = ContextFactory.CreateDbContext(); - context.Batches.Add(batch); - await context.SaveChangesAsync(); + if (batch.Id == Guid.Empty) + { + throw new ArgumentOutOfRangeException(nameof(batch.Id), message: $"Batch ID may not be an empty uuid ({Guid.Empty})"); + } + + try + { + using var context = ContextFactory.CreateDbContext(); + + context.Batches.Add(batch); - Log.Debug("Created batch {Id}", batch.Id); + await context.SaveChangesAsync(); - return batch; + return batch; + } + catch (DbUpdateException ex) when (ex.InnerException is SqliteException { SqliteErrorCode: 19 }) + { + throw new DuplicateException($"A Batch with ID {batch.Id} already exists."); + } + catch (Exception ex) + { + Log.Error("Failed to create Batch: {Message}", ex.Message); + throw; + } } /// -- cgit v1.2.3 From 2d7d768c5b60713b9886e89773a1eadc0091d132 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 8 May 2026 00:57:12 +0000 Subject: Bump axios from 1.15.0 to 1.15.2 in /src/web Bumps [axios](https://github.com/axios/axios) from 1.15.0 to 1.15.2. - [Release notes](https://github.com/axios/axios/releases) - [Changelog](https://github.com/axios/axios/blob/v1.x/CHANGELOG.md) - [Commits](https://github.com/axios/axios/compare/v1.15.0...v1.15.2) --- updated-dependencies: - dependency-name: axios dependency-version: 1.15.2 dependency-type: direct:production ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 8 ++++---- src/web/package.json | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 22d9c714..22b83fa6 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", @@ -5984,9 +5984,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", 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", -- cgit v1.2.3 From 072d9ad430042d1666f3260a57608119ffead254 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Fri, 8 May 2026 23:37:49 +0000 Subject: Bump fast-uri from 3.1.0 to 3.1.2 in /src/web Bumps [fast-uri](https://github.com/fastify/fast-uri) from 3.1.0 to 3.1.2. - [Release notes](https://github.com/fastify/fast-uri/releases) - [Commits](https://github.com/fastify/fast-uri/compare/v3.1.0...v3.1.2) --- updated-dependencies: - dependency-name: fast-uri dependency-version: 3.1.2 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 22d9c714..af43771d 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -10641,9 +10641,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": [ { -- cgit v1.2.3 From 5b9309b4dba91fe317f1c04bc02493cf3d1f18f3 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Sat, 9 May 2026 01:03:09 +0000 Subject: Bump @babel/plugin-transform-modules-systemjs in /src/web Bumps [@babel/plugin-transform-modules-systemjs](https://github.com/babel/babel/tree/HEAD/packages/babel-plugin-transform-modules-systemjs) from 7.22.5 to 7.29.4. - [Release notes](https://github.com/babel/babel/releases) - [Changelog](https://github.com/babel/babel/blob/main/CHANGELOG.md) - [Commits](https://github.com/babel/babel/commits/v7.29.4/packages/babel-plugin-transform-modules-systemjs) --- updated-dependencies: - dependency-name: "@babel/plugin-transform-modules-systemjs" dependency-version: 7.29.4 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 393 ++++++++++++---------------------------------- 1 file changed, 104 insertions(+), 289 deletions(-) (limited to 'src') diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 22d9c714..4205c57e 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -83,89 +83,20 @@ } }, "node_modules/@babel/code-frame": { - "version": "7.23.5", - "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.23.5.tgz", - "integrity": "sha512-CgH3s1a96LipHCmSUmYFPwY7MNx8C3avkq7i4Wl3cfa662ldtUe4VM1TPXX70pfmrlWTb6jLqTYrZyT2ZTJBgA==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.0.tgz", + "integrity": "sha512-9NhCeYjq9+3uxgdtp20LSiJXJvN0FeCtNGpJxuMFZ1Kv3cWUNb6DOhJwUvcVCzKGR66cw4njwM6hrJLqgOwbcw==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/highlight": "^7.23.4", - "chalk": "^2.4.2" + "@babel/helper-validator-identifier": "^7.28.5", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" }, "engines": { "node": ">=6.9.0" } }, - "node_modules/@babel/code-frame/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/code-frame/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/code-frame/node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "dependencies": { - "color-name": "1.1.3" - } - }, - "node_modules/@babel/code-frame/node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true - }, - "node_modules/@babel/code-frame/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true, - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/@babel/code-frame/node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/code-frame/node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", - "dev": true, - "dependencies": { - "has-flag": "^3.0.0" - }, - "engines": { - "node": ">=4" - } - }, "node_modules/@babel/compat-data": { "version": "7.23.5", "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.23.5.tgz", @@ -273,15 +204,17 @@ } }, "node_modules/@babel/generator": { - "version": "7.23.6", - "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.23.6.tgz", - "integrity": "sha512-qrSfCYxYQB5owCmGLbl8XRpX1ytXlpueOb0N0UmQwA073KZxejgQTzAmJezxvpwQD9uGtK2shHdi55QT+MbjIw==", + "version": "7.29.1", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.1.tgz", + "integrity": "sha512-qsaF+9Qcm2Qv8SRIMMscAvG4O3lJ0F1GuMo5HR/Bp02LopNgnZBC/EkbevHFeGs4ls/oPz9v+Bsmzbkbe+0dUw==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/types": "^7.23.6", - "@jridgewell/gen-mapping": "^0.3.2", - "@jridgewell/trace-mapping": "^0.3.17", - "jsesc": "^2.5.1" + "@babel/parser": "^7.29.0", + "@babel/types": "^7.29.0", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" }, "engines": { "node": ">=6.9.0" @@ -442,14 +375,12 @@ "node": ">=6.9.0" } }, - "node_modules/@babel/helper-hoist-variables": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-hoist-variables/-/helper-hoist-variables-7.22.5.tgz", - "integrity": "sha512-wGjk9QZVzvknA6yKIUURb8zY3grXCcOZt+/7Wcy8O2uctxhplmUPkOdlgoNhmdVee2c92JXbf1xpMtVNbfoxRw==", + "node_modules/@babel/helper-globals": { + "version": "7.28.0", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.28.0.tgz", + "integrity": "sha512-+W6cISkXFa1jXsDEdYA8HeevQT/FULhxzR99pxphltZcVaugps53THCeiWA8SguxxpSp3gKPiuYfSWopkLQ4hw==", "dev": true, - "dependencies": { - "@babel/types": "^7.22.5" - }, + "license": "MIT", "engines": { "node": ">=6.9.0" } @@ -467,28 +398,29 @@ } }, "node_modules/@babel/helper-module-imports": { - "version": "7.22.15", - "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.22.15.tgz", - "integrity": "sha512-0pYVBnDKZO2fnSPCrgM/6WMc7eS20Fbok+0r88fp+YtWVLZrp4CkafFGIp+W0VKw4a22sgebPT99y+FDNMdP4w==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.28.6.tgz", + "integrity": "sha512-l5XkZK7r7wa9LucGw9LwZyyCUscb4x37JWTPz7swwFE/0FMQAGpiWUZn8u9DzkSBWEcK25jmvubfpw2dnAMdbw==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/types": "^7.22.15" + "@babel/traverse": "^7.28.6", + "@babel/types": "^7.28.6" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-module-transforms": { - "version": "7.23.3", - "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.23.3.tgz", - "integrity": "sha512-7bBs4ED9OmswdfDzpz4MpWgSrV7FXlc3zIagvLFjS5H+Mk7Snr21vQ6QwrsoCGMfNC4e4LQPdoULEt4ykz0SRQ==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.28.6.tgz", + "integrity": "sha512-67oXFAYr2cDLDVGLXTEABjdBJZ6drElUSI7WKp70NrpyISso3plG9SAGEF6y7zbha/wOzUByWWTJvEDVNIUGcA==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-module-imports": "^7.22.15", - "@babel/helper-simple-access": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/helper-validator-identifier": "^7.22.20" + "@babel/helper-module-imports": "^7.28.6", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.28.6" }, "engines": { "node": ">=6.9.0" @@ -510,10 +442,11 @@ } }, "node_modules/@babel/helper-plugin-utils": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.22.5.tgz", - "integrity": "sha512-uLls06UVKgFG9QD4OeFYLEGteMIAa5kpTPcFL28yuCIIzsf6ZyKZMllKVOCZFhiZ5ptnwX4mtKdWCBE/uT4amg==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/helper-plugin-utils/-/helper-plugin-utils-7.28.6.tgz", + "integrity": "sha512-S9gzZ/bz83GRysI7gAD4wPT/AI3uCnY+9xn+Mx/KPs2JwHJIz1W8PZkg2cqyt3RNOBM8ejcXhV6y8Og7ly/Dug==", "dev": true, + "license": "MIT", "engines": { "node": ">=6.9.0" } @@ -590,19 +523,21 @@ } }, "node_modules/@babel/helper-string-parser": { - "version": "7.23.4", - "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.23.4.tgz", - "integrity": "sha512-803gmbQdqwdf4olxrX4AJyFBV/RTr3rSmOj0rKwesmzlfhYNDEs+/iOcznzpNWlJlIlTJC2QfPFcHB6DlzdVLQ==", + "version": "7.27.1", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.27.1.tgz", + "integrity": "sha512-qMlSxKbpRlAridDExk92nSobyDdpPijUq2DW6oDnUqd0iOGxmQjyqhMIihI9+zv4LPyZdRje2cavWPbCbWm3eA==", "dev": true, + "license": "MIT", "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/helper-validator-identifier": { - "version": "7.22.20", - "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.22.20.tgz", - "integrity": "sha512-Y4OZ+ytlatR8AI+8KZfKuL5urKp7qey08ha31L8b3BwewJAoJamTzyvxPR/5D+KkdJCGPq/+8TukHBlY10FX9A==", + "version": "7.28.5", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.28.5.tgz", + "integrity": "sha512-qSs4ifwzKJSV39ucNjsvc6WVHs6b7S03sOh2OcHF9UHfVPqWWALUsNUVzhSBiItjRZoLHx7nIarVjqKVusUZ1Q==", "dev": true, + "license": "MIT", "engines": { "node": ">=6.9.0" } @@ -645,96 +580,15 @@ "node": ">=6.9.0" } }, - "node_modules/@babel/highlight": { - "version": "7.23.4", - "resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.23.4.tgz", - "integrity": "sha512-acGdbYSfp2WheJoJm/EBBBLh/ID8KDc64ISZ9DYtBmC8/Q204PZJLHyzeB5qMzJ5trcOkybd78M4x2KWsUq++A==", - "dev": true, - "dependencies": { - "@babel/helper-validator-identifier": "^7.22.20", - "chalk": "^2.4.2", - "js-tokens": "^4.0.0" - }, - "engines": { - "node": ">=6.9.0" - } - }, - "node_modules/@babel/highlight/node_modules/ansi-styles": { - "version": "3.2.1", - "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-3.2.1.tgz", - "integrity": "sha512-VT0ZI6kZRdTh8YyJw3SMbYm/u+NqfsAxEpWO0Pf9sq8/e94WxxOpPKx9FR1FlyCtOVDNOQ+8ntlqFxiRc+r5qA==", - "dev": true, - "dependencies": { - "color-convert": "^1.9.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/highlight/node_modules/chalk": { - "version": "2.4.2", - "resolved": "https://registry.npmjs.org/chalk/-/chalk-2.4.2.tgz", - "integrity": "sha512-Mti+f9lpJNcwF4tWV8/OrTTtF1gZi+f8FqlyAdouralcFWFQWF2+NgCHShjkCb+IFBLq9buZwE1xckQU4peSuQ==", - "dev": true, - "dependencies": { - "ansi-styles": "^3.2.1", - "escape-string-regexp": "^1.0.5", - "supports-color": "^5.3.0" - }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/highlight/node_modules/color-convert": { - "version": "1.9.3", - "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-1.9.3.tgz", - "integrity": "sha512-QfAUtd+vFdAtFQcC8CCyYt1fYWxSqAiK2cSD6zDB8N3cpsEBAvRxp9zOGg6G/SHHJYAT88/az/IuDGALsNVbGg==", - "dev": true, - "dependencies": { - "color-name": "1.1.3" - } - }, - "node_modules/@babel/highlight/node_modules/color-name": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.3.tgz", - "integrity": "sha512-72fSenhMw2HZMTVHeCA9KCmpEIbzWiQsjN+BHcBbS9vr1mtt+vJjPdksIBNUmKAW8TFUDPJK5SUU3QhE9NEXDw==", - "dev": true - }, - "node_modules/@babel/highlight/node_modules/escape-string-regexp": { - "version": "1.0.5", - "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-1.0.5.tgz", - "integrity": "sha512-vbRorB5FUQWvla16U8R/qgaFIya2qGzwDrNmCZuYKrbdSUMG6I1ZCGQRefkRVhuOkIGVne7BQ35DSfo1qvJqFg==", - "dev": true, - "engines": { - "node": ">=0.8.0" - } - }, - "node_modules/@babel/highlight/node_modules/has-flag": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-3.0.0.tgz", - "integrity": "sha512-sKJf1+ceQBr4SMkvQnBDNDtf4TXpVhVGateu0t918bl30FnbE2m4vNLX+VWe/dpjlb+HugGYzW7uQXH98HPEYw==", - "dev": true, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/highlight/node_modules/supports-color": { - "version": "5.5.0", - "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-5.5.0.tgz", - "integrity": "sha512-QjVjwdXIt408MIiAqCX4oUKsgU2EqAGzs2Ppkm4aQYbjm+ZEWEcW4SfFNTr4uMNZma0ey4f5lgLrkB0aX0QMow==", + "node_modules/@babel/parser": { + "version": "7.29.3", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.3.tgz", + "integrity": "sha512-b3ctpQwp+PROvU/cttc4OYl4MzfJUWy6FZg+PMXfzmt/+39iHVF0sDfqay8TQM3JA2EUOyKcFZt75jWriQijsA==", "dev": true, + "license": "MIT", "dependencies": { - "has-flag": "^3.0.0" + "@babel/types": "^7.29.0" }, - "engines": { - "node": ">=4" - } - }, - "node_modules/@babel/parser": { - "version": "7.23.9", - "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.23.9.tgz", - "integrity": "sha512-9tcKgqKbs3xGJ+NtKF2ndOBBLVwPjl1SHxPQkd36r3Dlirw3xWUeGaTbqr7uGZcTaxkVNwc+03SVP7aCdWrTlA==", - "dev": true, "bin": { "parser": "bin/babel-parser.js" }, @@ -1614,15 +1468,16 @@ } }, "node_modules/@babel/plugin-transform-modules-systemjs": { - "version": "7.22.5", - "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.22.5.tgz", - "integrity": "sha512-emtEpoaTMsOs6Tzz+nbmcePl6AKVtS1yC4YNAeMun9U8YCsgadPNxnOPQ8GhHFB2qdx+LZu9LgoC0Lthuu05DQ==", + "version": "7.29.4", + "resolved": "https://registry.npmjs.org/@babel/plugin-transform-modules-systemjs/-/plugin-transform-modules-systemjs-7.29.4.tgz", + "integrity": "sha512-N7QmZ0xRZfjHOfZeQLJjwgX2zS9pdGHSVl/cjSGlo4dXMqvurfxXDMKY4RqEKzPozV78VMcd0lxyG13mlbKc4w==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/helper-hoist-variables": "^7.22.5", - "@babel/helper-module-transforms": "^7.22.5", - "@babel/helper-plugin-utils": "^7.22.5", - "@babel/helper-validator-identifier": "^7.22.5" + "@babel/helper-module-transforms": "^7.28.6", + "@babel/helper-plugin-utils": "^7.28.6", + "@babel/helper-validator-identifier": "^7.28.5", + "@babel/traverse": "^7.29.0" }, "engines": { "node": ">=6.9.0" @@ -2353,58 +2208,48 @@ "license": "MIT" }, "node_modules/@babel/template": { - "version": "7.23.9", - "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.23.9.tgz", - "integrity": "sha512-+xrD2BWLpvHKNmX2QbpdpsBaWnRxahMwJjO+KZk2JOElj5nSmKezyS1B4u+QbHMTX69t4ukm6hh9lsYQ7GHCKA==", + "version": "7.28.6", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.28.6.tgz", + "integrity": "sha512-YA6Ma2KsCdGb+WC6UpBVFJGXL58MDA6oyONbjyF/+5sBgxY/dwkhLogbMT2GXXyU84/IhRw/2D1Os1B/giz+BQ==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.23.5", - "@babel/parser": "^7.23.9", - "@babel/types": "^7.23.9" + "@babel/code-frame": "^7.28.6", + "@babel/parser": "^7.28.6", + "@babel/types": "^7.28.6" }, "engines": { "node": ">=6.9.0" } }, "node_modules/@babel/traverse": { - "version": "7.23.9", - "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.23.9.tgz", - "integrity": "sha512-I/4UJ9vs90OkBtY6iiiTORVMyIhJ4kAVmsKo9KFc8UOxMeUfi2hvtIBsET5u9GizXE6/GFSuKCTNfgCswuEjRg==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.0.tgz", + "integrity": "sha512-4HPiQr0X7+waHfyXPZpWPfWL/J7dcN1mx9gL6WdQVMbPnF3+ZhSMs8tCxN7oHddJE9fhNE7+lxdnlyemKfJRuA==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/code-frame": "^7.23.5", - "@babel/generator": "^7.23.6", - "@babel/helper-environment-visitor": "^7.22.20", - "@babel/helper-function-name": "^7.23.0", - "@babel/helper-hoist-variables": "^7.22.5", - "@babel/helper-split-export-declaration": "^7.22.6", - "@babel/parser": "^7.23.9", - "@babel/types": "^7.23.9", - "debug": "^4.3.1", - "globals": "^11.1.0" + "@babel/code-frame": "^7.29.0", + "@babel/generator": "^7.29.0", + "@babel/helper-globals": "^7.28.0", + "@babel/parser": "^7.29.0", + "@babel/template": "^7.28.6", + "@babel/types": "^7.29.0", + "debug": "^4.3.1" }, "engines": { "node": ">=6.9.0" } }, - "node_modules/@babel/traverse/node_modules/globals": { - "version": "11.12.0", - "resolved": "https://registry.npmjs.org/globals/-/globals-11.12.0.tgz", - "integrity": "sha512-WOBp/EEGUiIsJSp7wcv/y6MO+lV9UoncWqxuFfm8eBwzWNgyfBd6Gz+IeKQ9jCmyhoH99g15M3T+QaVHFjizVA==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/@babel/types": { - "version": "7.23.9", - "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.23.9.tgz", - "integrity": "sha512-dQjSq/7HaSjRM43FFGnv5keM2HsxpmyV1PfaSVm0nzzjwwTmjOe6J4bC8e3+pTEIgHaHj+1ZlLThRJ2auc/w1Q==", + "version": "7.29.0", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.0.tgz", + "integrity": "sha512-LwdZHpScM4Qz8Xw2iKSzS+cfglZzJGvofQICy7W7v4caru4EaAmyUuO6BGrbyQ2mYV11W0U8j5mBhd14dd3B0A==", "dev": true, + "license": "MIT", "dependencies": { - "@babel/helper-string-parser": "^7.23.4", - "@babel/helper-validator-identifier": "^7.22.20", - "to-fast-properties": "^2.0.0" + "@babel/helper-string-parser": "^7.27.1", + "@babel/helper-validator-identifier": "^7.28.5" }, "engines": { "node": ">=6.9.0" @@ -3827,17 +3672,14 @@ } }, "node_modules/@jridgewell/gen-mapping": { - "version": "0.3.3", - "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.3.tgz", - "integrity": "sha512-HLhSWOLRi875zjjMG/r+Nv0oCW8umGb0BgEhyX3dDX3egwZtB8PqLnjz3yedt8R5StBrzcg4aBpnh8UA9D1BoQ==", + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", "dev": true, + "license": "MIT", "dependencies": { - "@jridgewell/set-array": "^1.0.1", - "@jridgewell/sourcemap-codec": "^1.4.10", - "@jridgewell/trace-mapping": "^0.3.9" - }, - "engines": { - "node": ">=6.0.0" + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" } }, "node_modules/@jridgewell/resolve-uri": { @@ -3849,15 +3691,6 @@ "node": ">=6.0.0" } }, - "node_modules/@jridgewell/set-array": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/@jridgewell/set-array/-/set-array-1.1.2.tgz", - "integrity": "sha512-xnkseuNADM0gt2bs+BvhO0p78Mk762YnZdsuzFV018NoG1Sj1SCQvpSqa7XUaTam5vAGasABV9qXASMKnFMwMw==", - "dev": true, - "engines": { - "node": ">=6.0.0" - } - }, "node_modules/@jridgewell/source-map": { "version": "0.3.3", "resolved": "https://registry.npmjs.org/@jridgewell/source-map/-/source-map-0.3.3.tgz", @@ -3869,16 +3702,18 @@ } }, "node_modules/@jridgewell/sourcemap-codec": { - "version": "1.4.15", - "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", - "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==", - "dev": true + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" }, "node_modules/@jridgewell/trace-mapping": { - "version": "0.3.25", - "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.25.tgz", - "integrity": "sha512-vNk6aEwybGtawWmy/PzwnGDOjCkLWSD2wqvjGGAgOAwCGWySYXfYoxt00IJkTF+8Lb57DwOb3Aa0o9CApepiYQ==", + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", "dev": true, + "license": "MIT", "dependencies": { "@jridgewell/resolve-uri": "^3.1.0", "@jridgewell/sourcemap-codec": "^1.4.14" @@ -9881,18 +9716,6 @@ "eslint": ">=8.44.0" } }, - "node_modules/eslint-plugin-unicorn/node_modules/jsesc": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.0.2.tgz", - "integrity": "sha512-xKqzzWXDttJuOcawBt4KnKHHIf5oQ/Cxax+0PWFG+DFDgHNAdi+TXECADI+RYiFUMmx8792xsMbbgXj4CwnP4g==", - "dev": true, - "bin": { - "jsesc": "bin/jsesc" - }, - "engines": { - "node": ">=6" - } - }, "node_modules/eslint-plugin-unicorn/node_modules/regjsparser": { "version": "0.10.0", "resolved": "https://registry.npmjs.org/regjsparser/-/regjsparser-0.10.0.tgz", @@ -14157,15 +13980,16 @@ } }, "node_modules/jsesc": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-2.5.2.tgz", - "integrity": "sha512-OYu7XEzjkCQ3C5Ps3QIZsQfNpqoJyZZA99wd9aWd05NCtC5pWOkShK2mkL6HXQR6/Cy2lbNdPlZBpuQHXE63gA==", + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", "dev": true, + "license": "MIT", "bin": { "jsesc": "bin/jsesc" }, "engines": { - "node": ">=4" + "node": ">=6" } }, "node_modules/json-parse-even-better-errors": { @@ -19942,15 +19766,6 @@ "integrity": "sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw==", "dev": true }, - "node_modules/to-fast-properties": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/to-fast-properties/-/to-fast-properties-2.0.0.tgz", - "integrity": "sha512-/OaKK0xYrs3DmxRYqL/yDc+FxFUVYhDlXMhRmv3z915w2HF1tnN1omB354j8VUGO/hbRzyD6Y3sA7v7GS/ceog==", - "dev": true, - "engines": { - "node": ">=4" - } - }, "node_modules/to-regex-range": { "version": "5.0.1", "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", -- cgit v1.2.3 From 6921d36d324c3c459b851824df2aa574fb4953c5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 12:33:13 -0500 Subject: add GuidAttribute --- src/slskd/Common/Validation/GuidAttribute.cs | 57 ++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/slskd/Common/Validation/GuidAttribute.cs (limited to 'src') diff --git a/src/slskd/Common/Validation/GuidAttribute.cs b/src/slskd/Common/Validation/GuidAttribute.cs new file mode 100644 index 00000000..9139ffef --- /dev/null +++ b/src/slskd/Common/Validation/GuidAttribute.cs @@ -0,0 +1,57 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + + /// + /// Validates that the value is a valid Guid. + /// + public class GuidAttribute : ValidationAttribute + { + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value is null) + { + return ValidationResult.Success; + } + + if (value is string str && System.Guid.TryParse(str, out _)) + { + return ValidationResult.Success; + } + + return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUIDv4"); + } + } +} -- cgit v1.2.3 From f70c670e1dfbc6e6642365f57ba138501a8826fa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 12:33:24 -0500 Subject: parse guids from strings --- .../API/Controllers/TransfersController.cs | 23 +++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index b1275c52..50ff7199 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -313,6 +313,21 @@ namespace slskd.Transfers.API return BadRequest("One or more files in the request are invalid"); } + Guid? batchId; + Guid? searchId; + + // validation rules should prevent any problems here, but we have a backstop just in case + try + { + batchId = string.IsNullOrWhiteSpace(request.Id) ? null : Guid.Parse(request.Id); + searchId = string.IsNullOrWhiteSpace(request.SearchId) ? null : Guid.Parse(request.SearchId); + } + catch (Exception ex) + { + Log.Warning("Failed to parse Guid from enqueue batch input: {Message}", ex.Message); + return BadRequest("One or more provided identifiers is not a valid GUID/UUIDv4"); + } + if (!DownloadRequestLimiter.Wait(0)) { return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); @@ -327,12 +342,10 @@ namespace slskd.Transfers.API throw new UserOfflineException($"User {request.Username} appears to be offline"); } - var batchId = request.Id ?? Guid.NewGuid(); - await Transfers.Downloads.Batches.CreateAsync(new() { - Id = batchId, - SearchId = request.SearchId, + Id = batchId ?? Guid.NewGuid(), + SearchId = searchId, Username = request.Username, Options = new() { @@ -353,7 +366,7 @@ namespace slskd.Transfers.API } // the returned batch will have whatever Transfers were successfully inserted attached - var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == request.Id); + var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == batchId); if (batch.Transfers.Count == 0) { -- cgit v1.2.3 From b3041a9daffa98a0acda701e5e6b26345a185bde Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 12:41:23 -0500 Subject: add validation and tests for batch request DTO --- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 7 +- .../API/DTO/QueueDownloadBatchRequestTests.cs | 212 +++++++++++++++++++++ 2 files changed, 217 insertions(+), 2 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 4a1d32f1..6d08f8f3 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -45,12 +45,14 @@ public record QueueDownloadBatchRequest /// /// If not supplied, one will be randomly generated. /// - public Guid? Id { get; init; } = Guid.NewGuid(); + [Guid] + public string Id { get; init; } /// /// The ID of the associated Search, if applicable. /// - public Guid? SearchId { get; init; } + [Guid] + public string SearchId { get; init; } /// /// The username of the user from which to download. @@ -76,6 +78,7 @@ public record EnqueueDownloadBatchItem /// The name of the file. /// [Required] + [StringLength(int.MaxValue, MinimumLength = 1)] public string Filename { get; set; } /// diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs new file mode 100644 index 00000000..3863c649 --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -0,0 +1,212 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using slskd.Transfers.API; +using Xunit; + +namespace slskd.Tests.Unit.Transfers.API.DTO; + +public class QueueDownloadBatchRequestTests +{ + private static (bool IsValid, List Results) Validate(object obj) + { + var results = new List(); + var isValid = Validator.TryValidateObject(obj, new ValidationContext(obj), results, validateAllProperties: true); + return (isValid, results); + } + + private static QueueDownloadBatchRequest ValidRequest() => new() + { + Username = "testuser", + }; + + public class Id_Field + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Passes() + { + var (isValid, _) = Validate(ValidRequest() with { Id = null }); + Assert.True(isValid); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("not-a-guid")] + [InlineData("b5bde3d1-4aba-4d64-b64a")] + public void NonGuid_Fails(string value) + { + var (isValid, _) = Validate(ValidRequest() with { Id = value }); + Assert.False(isValid); + } + + [Theory] + [InlineData("b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b")] + [InlineData("B5BDE3D14ABA4D64B64A7A00A3CE5E1B")] + [InlineData("{b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b}")] + public void ValidGuid_Passes(string value) + { + var (isValid, _) = Validate(ValidRequest() with { Id = value }); + Assert.True(isValid); + } + } + + public class SearchId_Field + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Passes() + { + var (isValid, _) = Validate(ValidRequest() with { SearchId = null }); + Assert.True(isValid); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("not-a-guid")] + [InlineData("b5bde3d1-4aba-4d64-b64a")] + public void NonGuid_Fails(string value) + { + var (isValid, _) = Validate(ValidRequest() with { SearchId = value }); + Assert.False(isValid); + } + + [Theory] + [InlineData("b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b")] + [InlineData("B5BDE3D14ABA4D64B64A7A00A3CE5E1B")] + [InlineData("{b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b}")] + public void ValidGuid_Passes(string value) + { + var (isValid, _) = Validate(ValidRequest() with { SearchId = value }); + Assert.True(isValid); + } + } + + public class Username_Field + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Fails() + { + var (isValid, _) = Validate(ValidRequest() with { Username = null }); + Assert.False(isValid); + } + + [Fact] + public void Empty_Fails() + { + var (isValid, _) = Validate(ValidRequest() with { Username = "" }); + Assert.False(isValid); + } + + [Fact] + public void OneChar_Passes() + { + var (isValid, _) = Validate(ValidRequest() with { Username = "a" }); + Assert.True(isValid); + } + + [Fact] + public void FiveHundredChars_Passes() + { + var (isValid, _) = Validate(ValidRequest() with { Username = new string('a', 500) }); + Assert.True(isValid); + } + + [Fact] + public void FiveHundredOneChars_Fails() + { + var (isValid, _) = Validate(ValidRequest() with { Username = new string('a', 501) }); + Assert.False(isValid); + } + } + + public class Files_Item + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void NullFilename_Fails() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); + Assert.False(isValid); + } + + [Fact] + public void EmptyFilename_Fails() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); + Assert.False(isValid); + } + + [Fact] + public void ValidFilename_Passes() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 }); + Assert.True(isValid); + } + + [Fact] + public void NegativeSize_Fails() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = -1 }); + Assert.False(isValid); + } + + [Fact] + public void ZeroSize_Passes() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 }); + Assert.True(isValid); + } + + [Fact] + public void PositiveSize_Passes() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 1 }); + Assert.True(isValid); + } + } + + public class Options_Destination + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Passes() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = null }); + Assert.True(isValid); + } + + [Theory] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + public void RelativePath_Passes(string value) + { + var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.True(isValid); + } + + [Theory] + [InlineData("C:\\Music")] + [InlineData("/music")] + [InlineData("\\\\server\\share")] + public void AbsolutePath_Fails(string value) + { + var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.False(isValid); + } + } +} -- cgit v1.2.3 From c86fbec378b42dbd5ae6133c8ac706669f5709bb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 12:59:32 -0500 Subject: require at least 1 file --- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 + .../API/DTO/QueueDownloadBatchRequestTests.cs | 61 ++++++++++++++++++---- 2 files changed, 54 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 6d08f8f3..823a4e40 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -64,6 +64,8 @@ public record QueueDownloadBatchRequest /// /// The list of files to download. /// + [Required] + [MinLength(1)] public List Files { get; init; } = []; /// diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 3863c649..1f12d787 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -17,6 +17,7 @@ public class QueueDownloadBatchRequestTests private static QueueDownloadBatchRequest ValidRequest() => new() { Username = "testuser", + Files = [new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 }], }; public class Id_Field @@ -38,8 +39,10 @@ public class QueueDownloadBatchRequestTests [InlineData("b5bde3d1-4aba-4d64-b64a")] public void NonGuid_Fails(string value) { - var (isValid, _) = Validate(ValidRequest() with { Id = value }); + var (isValid, results) = Validate(ValidRequest() with { Id = value }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Id field must be a valid GUID/UUIDv4", results[0].ErrorMessage); } [Theory] @@ -72,8 +75,10 @@ public class QueueDownloadBatchRequestTests [InlineData("b5bde3d1-4aba-4d64-b64a")] public void NonGuid_Fails(string value) { - var (isValid, _) = Validate(ValidRequest() with { SearchId = value }); + var (isValid, results) = Validate(ValidRequest() with { SearchId = value }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The SearchId field must be a valid GUID/UUIDv4", results[0].ErrorMessage); } [Theory] @@ -95,15 +100,19 @@ public class QueueDownloadBatchRequestTests [Fact] public void Omitted_Fails() { - var (isValid, _) = Validate(ValidRequest() with { Username = null }); + var (isValid, results) = Validate(ValidRequest() with { Username = null }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Username field is required.", results[0].ErrorMessage); } [Fact] public void Empty_Fails() { - var (isValid, _) = Validate(ValidRequest() with { Username = "" }); + var (isValid, results) = Validate(ValidRequest() with { Username = "" }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Username field is required.", results[0].ErrorMessage); } [Fact] @@ -123,8 +132,34 @@ public class QueueDownloadBatchRequestTests [Fact] public void FiveHundredOneChars_Fails() { - var (isValid, _) = Validate(ValidRequest() with { Username = new string('a', 501) }); + var (isValid, results) = Validate(ValidRequest() with { Username = new string('a', 501) }); + Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The field Username must be a string with a minimum length of 1 and a maximum length of 500.", results[0].ErrorMessage); + } + } + + public class Files_Field + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Fails_WithRequiredMessage() + { + var (isValid, results) = Validate(ValidRequest() with { Files = null }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Files field is required.", results[0].ErrorMessage); + } + + [Fact] + public void EmptyList_Fails_WithMinLengthMessage() + { + var (isValid, results) = Validate(ValidRequest() with { Files = [] }); + Assert.False(isValid); + Assert.Single(results); + Assert.Contains("minimum length of '1'", results[0].ErrorMessage); } } @@ -136,15 +171,19 @@ public class QueueDownloadBatchRequestTests [Fact] public void NullFilename_Fails() { - var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Filename field is required.", results[0].ErrorMessage); } [Fact] public void EmptyFilename_Fails() { - var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); Assert.False(isValid); + Assert.Single(results); + Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); } [Fact] @@ -157,8 +196,10 @@ public class QueueDownloadBatchRequestTests [Fact] public void NegativeSize_Fails() { - var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = -1 }); + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = -1 }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The field Size must be between 0 and 9.223372036854776E+18.", results[0].ErrorMessage); } [Fact] @@ -205,8 +246,10 @@ public class QueueDownloadBatchRequestTests [InlineData("\\\\server\\share")] public void AbsolutePath_Fails(string value) { - var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); } } } -- cgit v1.2.3 From bd07234c29601c2c491d6582c58b257ea4e03296 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 15:58:34 -0500 Subject: check for malformed paths in relative/absolute validation --- src/slskd/Common/Validation/AbsolutePathAttribute.cs | 17 +++++++++++++++-- src/slskd/Common/Validation/RelativePathAttribute.cs | 15 ++++++++++++++- 2 files changed, 29 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index ef6db8ca..9f6184ce 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -34,6 +34,7 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; using System.IO; + using System.Linq; /// /// Validates that the specified path is absolute. @@ -44,9 +45,21 @@ namespace slskd.Validation { if (value != null) { - var filePath = value.ToString(); + var path = value.ToString(); - if (!string.IsNullOrEmpty(filePath) && !Path.IsPathRooted(filePath)) + var segments = path.Split('/', '\\'); + + if (segments.Any(s => string.IsNullOrEmpty(s))) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more empty segments ('\\\\' or '//')"); + } + + if (segments.Any(s => s == ".." || s == ".")) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); + } + + if (!string.IsNullOrEmpty(path) && !Path.IsPathRooted(path)) { return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 6cf87e7a..3bd48766 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -34,9 +34,10 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; using System.IO; + using System.Linq; /// - /// Validates that the specified path is relative and contains no path traversal segments. + /// Validates that the specified path is relative. /// public class RelativePathAttribute : ValidationAttribute { @@ -46,6 +47,18 @@ namespace slskd.Validation { var path = value.ToString(); + var segments = path.Split('/', '\\'); + + if (segments.Any(s => string.IsNullOrEmpty(s))) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more empty segments ('\\\\' or '//')"); + } + + if (segments.Any(s => s == ".." || s == ".")) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); + } + if (!string.IsNullOrEmpty(path) && Path.IsPathRooted(path)) { return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); -- cgit v1.2.3 From 7ffc9bda6aba0556df27339ee5976f98db3b5ff0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 15:58:44 -0500 Subject: add TODO --- src/slskd/Shares/ShareService.cs | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index a1dde4eb..7364d351 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)); // TODO: figure out how to eliminate this and work with masked directories only var groups = files .GroupBy(file => file.Filename.GetNormalizedDirectoryName()) -- cgit v1.2.3 From 0e9d1a75eb3e954829e86f20c7f64724d21e780e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 19:00:59 -0500 Subject: mark incomplete/downloads as absolute --- src/slskd/Core/Options.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 1ca5b84a..21f2c75f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -765,6 +765,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 +776,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; -- cgit v1.2.3 From 40d8fcc3e80c2c518d87d37e2a60ab53c7c4c81f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 19:01:21 -0500 Subject: use the list of invalid path characters when cleaning directory names --- src/slskd/Common/CommonExtensions.cs | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 8e6d5603..89f1c328 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -463,7 +463,7 @@ namespace slskd } var file = parts.Last().ReplaceInvalidFileNameCharacters(); - var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters(); + var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidDirectoryNameCharacters(); return Path.Combine(directory, file); } @@ -486,6 +486,24 @@ namespace slskd return sanitized; } + /// + /// Replaces any occurrence of an invalid directory character with the specified . + /// + /// The path to sanitize. + /// The character with which to replace invalid characters. + /// The sanitized path. + public static string ReplaceInvalidDirectoryNameCharacters(this string path, char replacement = '_') + { + var sanitized = path; + + foreach (var c in Path.GetInvalidPathChars()) + { + sanitized = sanitized.Replace(c, replacement); + } + + return sanitized; + } + /// /// Converts a ModelStateDictionary into a human-readable format. /// -- cgit v1.2.3 From c00f611d37342dab1d0c0c5f5cd3264b2c8d0616 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 19:02:06 -0500 Subject: strip path traversal segments from configured paths --- .../Common/Validation/AbsolutePathAttribute.cs | 15 +- .../Common/Validation/RelativePathAttribute.cs | 15 +- .../Validation/AbsolutePathAttributeTests.cs | 231 +++++++++++++++++++++ .../Validation/RelativePathAttributeTests.cs | 131 ++++++++++++ 4 files changed, 372 insertions(+), 20 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs (limited to 'src') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 9f6184ce..0eeb4a38 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -43,26 +43,21 @@ namespace slskd.Validation { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - if (value != null) + if (value != null && value is string str && !string.IsNullOrEmpty(str)) { var path = value.ToString(); - var segments = path.Split('/', '\\'); - - if (segments.Any(s => string.IsNullOrEmpty(s))) + if (!Path.IsPathRooted(path)) { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more empty segments ('\\\\' or '//')"); + return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); } + var segments = path.Split('/', '\\'); + if (segments.Any(s => s == ".." || s == ".")) { return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); } - - if (!string.IsNullOrEmpty(path) && !Path.IsPathRooted(path)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); - } } return ValidationResult.Success; diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 3bd48766..824ff18d 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -43,26 +43,21 @@ namespace slskd.Validation { protected override ValidationResult IsValid(object value, ValidationContext validationContext) { - if (value != null) + if (value != null && value is string str && !string.IsNullOrEmpty(str)) { var path = value.ToString(); - var segments = path.Split('/', '\\'); - - if (segments.Any(s => string.IsNullOrEmpty(s))) + if (Path.IsPathRooted(path)) { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more empty segments ('\\\\' or '//')"); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } + var segments = path.Split('/', '\\'); + if (segments.Any(s => s == ".." || s == ".")) { return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); } - - if (!string.IsNullOrEmpty(path) && Path.IsPathRooted(path)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } } return ValidationResult.Success; 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..03729eab --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs @@ -0,0 +1,231 @@ +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 — IsPathRooted returns true + [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); IsPathRooted returns true + 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); + } + } + + // Relative paths that have no empty segments and no traversal reach the + // final IsPathRooted check and fail there. + 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 specify an absolute file path.", errorMessage); + } + } +} 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..1692bceb --- /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); + } + } +} -- cgit v1.2.3 From 6d07d6ffd9ac33a597da5f25e927b7f857469cad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 19:02:24 -0500 Subject: add note about path usage in browseasync --- src/slskd/Shares/ShareService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Shares/ShareService.cs b/src/slskd/Shares/ShareService.cs index 7364d351..054561bf 100644 --- a/src/slskd/Shares/ShareService.cs +++ b/src/slskd/Shares/ShareService.cs @@ -190,7 +190,7 @@ namespace slskd.Shares var files = repositories.SelectMany(r => r.ListFiles( parentDirectory: prefix, - includeFullPath: true)); // TODO: figure out how to eliminate this and work with masked directories only + 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()) @@ -282,7 +282,7 @@ namespace slskd.Shares /// The contents of the directory. public Task 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)); } -- cgit v1.2.3 From be4408fdeb0c46855cd10832bd7d9e0b67bb7bd4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 19:02:40 -0500 Subject: rename variable to clarify usage --- src/slskd/Shares/SqliteShareRepository.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') 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>(); - 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); } -- cgit v1.2.3 From 9f68821f91a643c872a7023d6abf2c2f7cb60474 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 19:03:12 -0500 Subject: disallow path traversal characters as aliases --- src/slskd/Core/Options.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 21f2c75f..9fe8270b 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -880,6 +880,10 @@ namespace slskd { results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; aliases may not contain path separators '/' or '\\'")); } + else if (share.Alias == "." || share.Alias == "..") + { + results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; aliases may not be path traversal characters '.' or '..'")); + } } return results; -- cgit v1.2.3 From 4d35aa93d565b931ae06188beb2aca242619cb7f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 19:03:59 -0500 Subject: guard against path traversal in enqueue/directory requests --- src/slskd/Application.cs | 12 ++++++++++++ 1 file changed, 12 insertions(+) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index e36a5539..c69df4c9 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -572,6 +572,12 @@ namespace slskd { Metrics.Enqueue.RequestsReceived.Inc(1); + if (filename.Split('\\', '/').Any(s => s == ".." || s == ".")) + { + Log.Warning("Suspicious attempt from user {Username} to enqueue a file containing unsafe or malformed path segments (one or more of: empty segments, path traversal characters '.' and '..'). Requested file: {File}", username, filename); + throw new DownloadEnqueueException("File not shared."); + } + /* circuit breaker/failsafe: @@ -1413,6 +1419,12 @@ namespace slskd /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. private async Task> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { + if (directory.Split('\\', '/').Any(s => s == ".." || s == ".")) + { + Log.Warning("Suspicious attempt from user {Username} to list the contents of a directory containing unsafe or malformed path segments (one or more of: empty segments, path traversal characters '.' and '..'). Requested directory: {Directory}", username, directory); + throw new DownloadEnqueueException("File not shared."); + } + if (Users.IsBlacklisted(username, endpoint.Address)) { Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address); -- cgit v1.2.3 From e73ccbe4b6bd35449e88e261aa6bfb869952517c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 19:04:10 -0500 Subject: mark contentpath relative --- src/slskd/Core/Options.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 9fe8270b..7c391959 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2043,6 +2043,7 @@ namespace slskd [EnvironmentVariable("CONTENT_PATH")] [Description("path to static web content")] [StringLength(255, MinimumLength = 1)] + [RelativePath] [DirectoryExists(relativeToApplicationDirectory: true)] [RequiresRestart] public string ContentPath { get; init; } = "wwwroot"; -- cgit v1.2.3 From 5de28546177a57b086e299d98d3077721aa9d868 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 15:57:52 -0500 Subject: add file safety functions --- src/slskd/Common/FileSafety.cs | 103 ++++++ tests/slskd.Tests.Unit/Common/FileSafetyTests.cs | 417 +++++++++++++++++++++++ 2 files changed, 520 insertions(+) create mode 100644 src/slskd/Common/FileSafety.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafetyTests.cs (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs new file mode 100644 index 00000000..a3899397 --- /dev/null +++ b/src/slskd/Common/FileSafety.cs @@ -0,0 +1,103 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd; + +using System; +using System.IO; +using System.Linq; + +/// +/// Utility functions to help safely work with paths from untrusted sources. +/// +public static class FileSafety +{ + /// + /// An alternative to that disallows rooted segments in the second or + /// subsequent position, and disallows segments containing path traversal characters "." and "..". + /// + /// The root directory. + /// The segments to append. + /// The combined path. + /// Thrown if the root, list of segments, or one or more segments is null. + /// Thrown if any of the specified segments is rooted, or if any contain path traversal characters. + public static string CombineSafely(string root, 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 (Path.IsPathRooted(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; + } + + /// + /// Returns a value indicating whether the specified contains path traversal segments. + /// + /// The path to check. + /// True if one or more segments is present, false otherwise. + public static bool ContainsTraversalSegments(string path) => path?.Split('\\', '/')?.Any(s => s is "." or "..") ?? false; +} \ 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..ab4df5c4 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs @@ -0,0 +1,417 @@ +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 + { + // Paths that are rooted on all platforms + [Theory] + [InlineData("/Music")] // Unix absolute / Windows root-relative via forward slash + [InlineData("//server/share")] // Unix-style UNC + public void Throws_ArgumentException(string segment) + { + var ex = Assert.Throws(() => FileSafety.CombineSafely(Base, segment)); + Assert.Contains("Rooted", ex.Message); + } + + // Paths that are only rooted on Windows; on Linux/macOS backslash is a valid filename character + // and "C:" is not a special prefix, so IsPathRooted returns false and they would not be rejected. + [Theory] + [InlineData("C:\\Music")] // Windows drive-letter absolute, backslash + [InlineData("C:/Music")] // Windows drive-letter absolute, forward slash + [InlineData("D:\\path")] // alternate drive letter + [InlineData("C:relative")] // Windows drive-relative; IsPathRooted returns true + [InlineData("\\Music")] // Windows root-relative, backslash + [InlineData("\\\\server\\share")] // Windows UNC + public void Throws_ArgumentException_WindowsOnly(string segment) + { + if (!OperatingSystem.IsWindows()) { return; } + + var ex = Assert.Throws(() => FileSafety.CombineSafely(Base, segment)); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentIsRooted() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(Base, "valid", "/escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentIsRooted_WindowsOnly() + { + if (!OperatingSystem.IsWindows()) { return; } + + var ex = Assert.Throws(() => + FileSafety.CombineSafely(Base, "valid", "C:\\escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsRooted() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(Base, "sub", "dir", "/escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsRooted_WindowsOnly() + { + if (!OperatingSystem.IsWindows()) { return; } + + var ex = Assert.Throws(() => + 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(() => FileSafety.CombineSafely(Base, segment)); + Assert.Contains("traversal", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentContainsTraversal() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(Base, "valid", "../escape")); + Assert.Contains("traversal", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsTraversal() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(Base, "sub", "dir", "..")); + Assert.Contains("traversal", ex.Message); + } + } + + 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(() => 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(() => 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(() => FileSafety.CombineSafely(Base, (string)null)); + } + + [Fact] + public void NullBasePath_Throws() + { + Assert.ThrowsAny(() => 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); + } + } +} -- cgit v1.2.3 From 68801041daa2709c892aa6ac09c11f463daeb8d9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 16:00:52 -0500 Subject: guard file/directory requests --- src/slskd/Application.cs | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index c69df4c9..e3d212f7 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -572,9 +572,11 @@ namespace slskd { Metrics.Enqueue.RequestsReceived.Inc(1); - if (filename.Split('\\', '/').Any(s => s == ".." || s == ".")) + // 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 or malformed path segments (one or more of: empty segments, path traversal characters '.' and '..'). Requested file: {File}", username, 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."); } @@ -1419,10 +1421,12 @@ namespace slskd /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. private async Task> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory) { - if (directory.Split('\\', '/').Any(s => s == ".." || s == ".")) + // 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 the contents of a directory containing unsafe or malformed path segments (one or more of: empty segments, path traversal characters '.' and '..'). Requested directory: {Directory}", username, directory); - throw new DownloadEnqueueException("File not shared."); + 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)) -- cgit v1.2.3 From 166addef37753e1cb116721973b0fca8e25506ba Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 17:50:33 -0500 Subject: GetInvalidPathChars() is invalid garbage --- src/slskd/Common/CommonExtensions.cs | 20 +-- .../ReplaceInvalidFileNameCharactersTests.cs | 144 +++++++++++++++++++++ 2 files changed, 145 insertions(+), 19 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 89f1c328..8e6d5603 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -463,7 +463,7 @@ namespace slskd } var file = parts.Last().ReplaceInvalidFileNameCharacters(); - var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidDirectoryNameCharacters(); + var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters(); return Path.Combine(directory, file); } @@ -486,24 +486,6 @@ namespace slskd return sanitized; } - /// - /// Replaces any occurrence of an invalid directory character with the specified . - /// - /// The path to sanitize. - /// The character with which to replace invalid characters. - /// The sanitized path. - public static string ReplaceInvalidDirectoryNameCharacters(this string path, char replacement = '_') - { - var sanitized = path; - - foreach (var c in Path.GetInvalidPathChars()) - { - sanitized = sanitized.Replace(c, replacement); - } - - return sanitized; - } - /// /// Converts a ModelStateDictionary into a human-readable format. /// 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..eff24587 --- /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(() => 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); + } + } +} -- cgit v1.2.3 From fb6dfe1498e2ca0cb0c9b65e00634169cf2d16c0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 18:31:05 -0500 Subject: obsolete local filename methods --- src/slskd/Common/CommonExtensions.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 8e6d5603..33e59382 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -390,6 +390,7 @@ namespace slskd /// The fully qualified remote filename to convert. /// The base directory for the local filename. /// The converted filename. + [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()); @@ -445,6 +446,7 @@ namespace slskd /// /// The fully qualified remote filename to convert. /// The converted filename. + [Obsolete("Find something more intelligent to do instead of this")] public static string ToLocalRelativeFilename(this string remoteFilename) { if (string.IsNullOrWhiteSpace(remoteFilename)) -- cgit v1.2.3 From 3fb834ecb2afb7c112e191d03b20f7ae39f7a62e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 18:51:20 -0500 Subject: use CombineSafely --- src/slskd/Common/CommonExtensions.cs | 4 ++-- src/slskd/Transfers/Downloads/DownloadService.cs | 7 ++++--- 2 files changed, 6 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 33e59382..5ff3e519 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -393,7 +393,7 @@ namespace slskd [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()); } /// @@ -467,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); } /// diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 184acb5d..7d9d9521 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1046,10 +1046,11 @@ namespace slskd.Transfers.Downloads // if the transfer has an associated batch id, store the incomplete file in a directory of the same name // this is to ensure maximal safety when resuming failed downloads (otherwise we risk resuming an unrelated file) + // if there is no batch id, sanitize the username and use that var incompleteFilename = transfer.Filename.ToLocalFilename( - baseDirectory: System.IO.Path.Combine( + baseDirectory: FileSafety.CombineSafely( OptionsMonitor.CurrentValue.Directories.Incomplete, - transfer.BatchId.HasValue ? transfer.BatchId.ToString() : string.Empty)); + transfer.BatchId.HasValue ? transfer.BatchId.ToString() : transfer.Username.ReplaceInvalidFileNameCharacters())); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; @@ -1144,7 +1145,7 @@ namespace slskd.Transfers.Downloads { // if the transfer has an associated batch id, then: // some/long/remote/path/folder/file.ext -> download_directory/batch_id/file.ext - destinationDirectory = System.IO.Path.Combine(OptionsMonitor.CurrentValue.Directories.Downloads, transfer.BatchId.Value.ToString()); + destinationDirectory = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, transfer.BatchId.Value.ToString()); } else { -- cgit v1.2.3 From 7cd70a730b6cd57952f2e233378cd6bb244f56b1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 18:51:35 -0500 Subject: block downloads of files with traversal segments --- .../Transfers/API/Controllers/TransfersController.cs | 17 ++++++++++++++++- src/slskd/Transfers/Downloads/DownloadService.cs | 5 +++++ 2 files changed, 21 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 50ff7199..1d748f35 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -250,7 +250,12 @@ namespace slskd.Transfers.API if (requests.Any(r => r is null)) { - return BadRequest("One or more records in the request are null"); + return BadRequest("One or more files in the request are null"); + } + + if (requests.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) + { + return BadRequest("One or more files in the request contain a dangerous path traversal segment"); } if (!DownloadRequestLimiter.Wait(0)) @@ -313,6 +318,16 @@ namespace slskd.Transfers.API return BadRequest("One or more files in the request are invalid"); } + if (request.Files.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) + { + return BadRequest("One or more files in the request contain a dangerous path traversal segment"); + } + + if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count) + { + return BadRequest("One or more files in the request are duplicates"); + } + Guid? batchId; Guid? searchId; diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 7d9d9521..14048fac 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -287,6 +287,11 @@ namespace slskd.Transfers.Downloads throw new ArgumentException("At least one filename is null or empty", nameof(files)); } + if (fileList.Any(f => FileSafety.ContainsTraversalSegments(f.Filename))) + { + throw new ArgumentException("One or more files contains a dangerous path traversal segment", nameof(files)); + } + if (fileList.Count != fileList.Distinct().Count()) { throw new ArgumentException("Two or more files in request are duplicated", nameof(files)); -- cgit v1.2.3 From 4b0b663a5bc1dc64d52485eb7be1bce5df73478c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 11 May 2026 19:04:44 -0500 Subject: wip --- src/slskd/Relay/API/Controllers/RelayController.cs | 7 +++++- src/slskd/Relay/RelayClient.cs | 25 ++++++++++++++++++++-- 2 files changed, 29 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index 0d2ef9c5..f0ab0457 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -159,7 +159,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); diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 9aec7b00..6d4b872a 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -370,6 +370,13 @@ namespace slskd.Relay private async Task HandleFileInfoRequest(string filename, Guid id) { + if (FileSafety.ContainsTraversalSegments(filename)) + { + var msg = $"Suspicious attempt to request file info containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}"; + Log.Warning(msg, filename); + throw new ArgumentException(msg, nameof(filename)); + } + Log.Information("Relay controller requested file info for {Filename} with ID {Id}", filename, id); try @@ -389,6 +396,13 @@ namespace slskd.Relay private Task HandleFileUploadRequest(string filename, long startOffset, Guid token) { + if (FileSafety.ContainsTraversalSegments(filename)) + { + var msg = $"Suspicious attempt to request a file upload containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}"; + Log.Warning(msg, filename); + throw new ArgumentException(msg, nameof(filename)); + } + _ = Task.Run(async () => { Log.Information("Relay controller requested file {Filename} with ID {Id}", filename, token); @@ -448,6 +462,13 @@ namespace slskd.Relay private Task HandleNotifyFileDownloadCompleted(string filename, Guid token) { + if (FileSafety.ContainsTraversalSegments(filename)) + { + var msg = $"Suspicious attempt to solicit a file download containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}"; + Log.Warning(msg, filename); + throw new ArgumentException(msg, nameof(filename)); + } + if (!OptionsMonitor.CurrentValue.Relay.Controller.Downloads) { return Task.CompletedTask; @@ -457,13 +478,13 @@ namespace slskd.Relay _ = 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.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 -- cgit v1.2.3 From 298539af4b3d49733073bedd68862973596b9b00 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 12 May 2026 18:59:16 -0500 Subject: add DisallowedCharacters attribute, ensure no slashes in instance/agent name --- .../Validation/DisallowedCharactersAttribute.cs | 71 ++++++ src/slskd/Core/Options.cs | 2 + .../DisallowedCharactersAttributeTests.cs | 254 +++++++++++++++++++++ 3 files changed, 327 insertions(+) create mode 100644 src/slskd/Common/Validation/DisallowedCharactersAttribute.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs (limited to 'src') 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation; + +using System.ComponentModel.DataAnnotations; +using System.Linq; + +/// +/// Validates that the value does not contain any of the characters. +/// +public class DisallowedCharactersAttribute : ValidationAttribute +{ + public DisallowedCharactersAttribute(params char[] disallowed) + { + Disallowed = disallowed; + } + + /// + /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to . + /// + 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/Core/Options.cs b/src/slskd/Core/Options.cs index 7c391959..90a72f7d 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; } 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..4654fd25 --- /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); + } + } +} -- cgit v1.2.3 From 6367208d8255f33af83a3cfd7cf2d29897caee5c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 12 May 2026 18:59:44 -0500 Subject: swap out remaining path.combine --- src/slskd/Relay/API/Controllers/RelayController.cs | 20 ++++++++++++++-- src/slskd/Relay/RelayClient.cs | 27 ++++++++-------------- 2 files changed, 28 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index f0ab0457..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. @@ -230,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"); @@ -328,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 6d4b872a..2e001bdc 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -372,9 +372,8 @@ namespace slskd.Relay { if (FileSafety.ContainsTraversalSegments(filename)) { - var msg = $"Suspicious attempt to request file info containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}"; - Log.Warning(msg, filename); - throw new ArgumentException(msg, nameof(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); @@ -394,13 +393,12 @@ 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)) { - var msg = $"Suspicious attempt to request a file upload containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}"; - Log.Warning(msg, filename); - throw new ArgumentException(msg, nameof(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 () => @@ -456,22 +454,19 @@ 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)) { - var msg = $"Suspicious attempt to solicit a file download containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {filename}"; - Log.Warning(msg, filename); - throw new ArgumentException(msg, nameof(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); @@ -519,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) @@ -600,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 { -- cgit v1.2.3 From fe1a6a3298116bc3980306cbb287f7137b378d1a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 12 May 2026 19:04:25 -0500 Subject: tweak IsAllowed test --- src/slskd/Files/FileService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') 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))) -- cgit v1.2.3 From 8336a3c3ebdfc65dd7d7419f27c195a4aa729856 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 13 May 2026 18:15:16 -0500 Subject: write our own logic for path relative/absolute --- src/slskd/Common/FileSafety.cs | 48 +++++- .../Common/Validation/AbsolutePathAttribute.cs | 11 +- .../Common/Validation/RelativePathAttribute.cs | 9 +- tests/slskd.Tests.Unit/Common/FileSafetyTests.cs | 176 ++++++++++++++++++--- .../Validation/AbsolutePathAttributeTests.cs | 8 +- 5 files changed, 209 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index a3899397..f94b9c7b 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -68,7 +68,7 @@ public static class FileSafety // if any segment is rooted (leading slash), Path.Combine drops everyting up to that segment // and it becomes the new root. example: Path.Combine("/home/users/foo", "/etc") results in "/etc" // not what we want! - if (Path.IsPathRooted(segment)) + if (IsPathAbsolute(segment)) { throw new ArgumentException($"Rooted paths are not permitted in segments: '{segment}'"); } @@ -100,4 +100,50 @@ public static class FileSafety /// The path to check. /// True if one or more segments is present, false otherwise. public static bool ContainsTraversalSegments(string path) => path?.Split('\\', '/')?.Any(s => s is "." or "..") ?? false; + + /// + /// Returns a value indicating whether the specified is absolute (rooted), using + /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// + /// + /// 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. + /// + /// The path to check. + /// True if the path is absolute, false otherwise. + 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; + } + + /// + /// Returns a value indicating whether the specified , using + /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// + /// The path to check. + /// True if the path is relative, false otherwise. + public static bool IsPathRelative(string path) => !IsPathAbsolute(path); } \ No newline at end of file diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 0eeb4a38..4c9f5e53 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -33,8 +33,6 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.IO; - using System.Linq; /// /// Validates that the specified path is absolute. @@ -47,14 +45,13 @@ namespace slskd.Validation { var path = value.ToString(); - if (!Path.IsPathRooted(path)) + if (!FileSafety.IsPathAbsolute(path)) { - return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); } - var segments = path.Split('/', '\\'); - - if (segments.Any(s => s == ".." || s == ".")) + // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here + if (FileSafety.ContainsTraversalSegments(path)) { return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 824ff18d..e8865554 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -33,8 +33,6 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.IO; - using System.Linq; /// /// Validates that the specified path is relative. @@ -47,14 +45,13 @@ namespace slskd.Validation { var path = value.ToString(); - if (Path.IsPathRooted(path)) + if (!FileSafety.IsPathRelative(path)) { return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } - var segments = path.Split('/', '\\'); - - if (segments.Any(s => s == ".." || s == ".")) + // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here + if (FileSafety.ContainsTraversalSegments(path)) { return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); } diff --git a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs index ab4df5c4..a37e9e74 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs @@ -258,29 +258,17 @@ public class FileSafetyTests public class CombineSafely_Throws_ForRootedSegment { - // Paths that are rooted on all platforms [Theory] - [InlineData("/Music")] // Unix absolute / Windows root-relative via forward slash - [InlineData("//server/share")] // Unix-style UNC - public void Throws_ArgumentException(string segment) - { - var ex = Assert.Throws(() => FileSafety.CombineSafely(Base, segment)); - Assert.Contains("Rooted", ex.Message); - } - - // Paths that are only rooted on Windows; on Linux/macOS backslash is a valid filename character - // and "C:" is not a special prefix, so IsPathRooted returns false and they would not be rejected. - [Theory] - [InlineData("C:\\Music")] // Windows drive-letter absolute, backslash - [InlineData("C:/Music")] // Windows drive-letter absolute, forward slash + [InlineData("/Music")] // Unix absolute / Windows root-relative, forward slash + [InlineData("//server/share")] // Unix-style UNC + [InlineData("C:\\Music")] // Windows drive-letter, backslash + [InlineData("C:/Music")] // Windows drive-letter, forward slash [InlineData("D:\\path")] // alternate drive letter - [InlineData("C:relative")] // Windows drive-relative; IsPathRooted returns true + [InlineData("C:relative")] // Windows drive-relative [InlineData("\\Music")] // Windows root-relative, backslash [InlineData("\\\\server\\share")] // Windows UNC - public void Throws_ArgumentException_WindowsOnly(string segment) + public void Throws_ArgumentException(string segment) { - if (!OperatingSystem.IsWindows()) { return; } - var ex = Assert.Throws(() => FileSafety.CombineSafely(Base, segment)); Assert.Contains("Rooted", ex.Message); } @@ -294,10 +282,8 @@ public class FileSafetyTests } [Fact] - public void Throws_WhenLaterSegmentIsRooted_WindowsOnly() + public void Throws_WhenLaterSegmentIsRooted_Windows() { - if (!OperatingSystem.IsWindows()) { return; } - var ex = Assert.Throws(() => FileSafety.CombineSafely(Base, "valid", "C:\\escape")); Assert.Contains("Rooted", ex.Message); @@ -312,10 +298,8 @@ public class FileSafetyTests } [Fact] - public void Throws_WhenLastSegmentIsRooted_WindowsOnly() + public void Throws_WhenLastSegmentIsRooted_Windows() { - if (!OperatingSystem.IsWindows()) { return; } - var ex = Assert.Throws(() => FileSafety.CombineSafely(Base, "sub", "dir", "C:\\escape")); Assert.Contains("Rooted", ex.Message); @@ -371,6 +355,150 @@ public class FileSafetyTests } } + public class IsPathAbsolute_ReturnsTrue + { + // Unix/Linux/macOS absolute paths + [Theory] + [InlineData("/")] // filesystem root + [InlineData("/home")] // single component + [InlineData("/home/user/Music")] // deep path + [InlineData("/home/user/My Music")] // spaces in component + [InlineData("/etc/hosts")] // config file + [InlineData("/tmp")] // temp directory + [InlineData("/home/Ünïcödé")] // latin extended + [InlineData("/home/пользователь/Музыка")] // Cyrillic + [InlineData("/home/用户/音乐")] // Chinese + [InlineData("/home/ユーザー/音楽")] // Japanese + [InlineData("/home/사용자/음악")] // Korean + public void Unix_Paths(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path)); + } + + // Unix-style UNC paths (// prefix) + [Theory] + [InlineData("//server/share")] + [InlineData("//server/share/folder")] + [InlineData("//192.168.1.1/share")] + [InlineData("//server/Ünïcödé")] + [InlineData("//server/share/пользователь")] + public void Unix_UNCPaths(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path)); + } + + // Windows root-relative paths (rooted to the current drive, no drive letter) + [Theory] + [InlineData("\\Music")] + [InlineData("\\Music\\Artist\\Album")] + [InlineData("/Music")] + [InlineData("/Music/Artist/Album")] + [InlineData("\\Ünïcödé")] + [InlineData("\\пользователь\\Музыка")] + public void Windows_RootRelativePaths(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path)); + } + + // Windows UNC paths (\\ prefix) + [Theory] + [InlineData("\\\\server\\share")] + [InlineData("\\\\server\\share\\folder")] + [InlineData("\\\\server\\share\\My Music")] + [InlineData("\\\\192.168.1.1\\share")] + [InlineData("\\\\server\\Ünïcödé")] + [InlineData("\\\\server\\share\\пользователь")] + [InlineData("\\\\server\\share\\用户\\音乐")] + public void Windows_UNCPaths(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path)); + } + + // Windows drive-letter paths — with or without a separator after the colon + [Theory] + [InlineData("C:\\")] // drive root, backslash + [InlineData("C:/")] // drive root, forward slash + [InlineData("C:\\Music")] // basic, backslash + [InlineData("C:/Music")] // basic, forward slash + [InlineData("C:\\Music\\Artist\\Album")] // deep, backslash + [InlineData("D:\\path")] // different drive letter + [InlineData("Z:\\downloads")] // drive letter Z + [InlineData("C:")] // bare drive letter + [InlineData("C:Music")] // drive-relative, no separator + [InlineData("D:path")] // different drive letter, no separator + [InlineData("C:\\Users\\Ünïcödé\\Music")] // latin extended + [InlineData("C:\\Users\\пользователь\\Музыка")] // Cyrillic + [InlineData("C:\\Users\\用户\\音乐")] // Chinese + public void Windows_DriveLetterPaths(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path)); + } + } + + public class IsPathAbsolute_ReturnsFalse + { + [Theory] + [InlineData(null)] // null + [InlineData("")] // empty string + [InlineData("subdir")] // simple name + [InlineData("sub/dir")] // forward slash + [InlineData("sub\\dir")] // backslash + [InlineData("Artist\\Album")] // multi-level backslash + [InlineData("Artist/Album/Song")] // deep forward slash + [InlineData("music.flac")] // file name with extension + [InlineData("My Music")] // spaces + [InlineData(".hidden")] // dotfile + [InlineData("..hidden")] // dot-prefixed name + [InlineData("...dir")] // three dots — relative, not traversal + [InlineData("../escape")] // traversal — still relative + [InlineData("./dir")] // current-dir segment — still relative + [InlineData("..")] // bare double-dot + [InlineData(".")] // bare single-dot + [InlineData("Ünïcödé")] // unicode, no root + [InlineData("пользователь/Музыка")] // unicode with separator, no root + public void Relative_Paths(string path) + { + Assert.False(FileSafety.IsPathAbsolute(path)); + } + } + + public class IsPathRelative_ReturnsTrue + { + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("music.flac")] + [InlineData(".hidden")] + [InlineData("../escape")] + public void Relative_Paths(string path) + { + Assert.True(FileSafety.IsPathRelative(path)); + } + + } + + public class IsPathRelative_ReturnsFalse + { + [Theory] + [InlineData("/home/user")] + [InlineData("//server/share")] + [InlineData("\\Music")] + [InlineData("\\\\server\\share")] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\")] + [InlineData("C:")] + [InlineData("C:Music")] + [InlineData("D:path")] + public void Absolute_Paths(string path) + { + Assert.False(FileSafety.IsPathRelative(path)); + } + } + public class CombineSafely_NullAndEdgeCases { [Fact] diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs index 03729eab..53e25ac6 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs @@ -41,7 +41,7 @@ public class AbsolutePathAttributeTests [InlineData("C:\\Program Files\\App")] // spaces, typical Windows path [InlineData("D:\\path")] // different drive letter [InlineData("Z:\\downloads")] // drive letter Z - [InlineData("C:")] // bare drive — IsPathRooted returns true + [InlineData("C:")] // bare drive [InlineData("C:\\Users\\Ünïcödé\\Music")] // latin extended [InlineData("C:\\Users\\пользователь\\Музыка")] // Cyrillic [InlineData("C:\\Users\\用户\\音乐")] // Chinese @@ -49,7 +49,7 @@ public class AbsolutePathAttributeTests [InlineData("C:\\Users\\사용자\\음악")] // Korean [InlineData("C:\\Users\\مستخدم\\موسيقى")] // Arabic [InlineData("C:\\Users\\χρήστης\\μουσική")] // Greek - [InlineData("C:Music")] // drive-relative (no separator); IsPathRooted returns true + [InlineData("C:Music")] // drive-relative (no separator) public void Windows_DriveLetterPaths_Pass(string value) { var (isValid, _) = Validate(value); @@ -204,8 +204,6 @@ public class AbsolutePathAttributeTests } } - // Relative paths that have no empty segments and no traversal reach the - // final IsPathRooted check and fail there. public class Relative_Fails { [Theory] @@ -225,7 +223,7 @@ public class AbsolutePathAttributeTests { var (isValid, errorMessage) = Validate(value); Assert.False(isValid); - Assert.Equal("The Field field must specify an absolute file path.", errorMessage); + Assert.Equal("The Field field must be an absolute file path.", errorMessage); } } } -- cgit v1.2.3 From d99fb89062d58e6335d52e0363377f6db1d6896c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 13 May 2026 20:39:09 -0500 Subject: add new exception types --- src/slskd/Common/Exceptions/ConflictException.cs | 75 +++++++++++++++++++++++ src/slskd/Common/Exceptions/DuplicateException.cs | 75 +++++++++++++++++++++++ 2 files changed, 150 insertions(+) create mode 100644 src/slskd/Common/Exceptions/ConflictException.cs create mode 100644 src/slskd/Common/Exceptions/DuplicateException.cs (limited to 'src') 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + + /// + /// Represents errors that originate due to duplication. + /// + [ExcludeFromCodeCoverage] + public class ConflictException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public ConflictException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public ConflictException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd +{ + using System; + using System.Diagnostics.CodeAnalysis; + + /// + /// Represents errors that originate due to duplication. + /// + [ExcludeFromCodeCoverage] + public class DuplicateException : Exception + { + /// + /// Initializes a new instance of the class. + /// + public DuplicateException() + : base() + { + } + + /// + /// Initializes a new instance of the class with a specified error message. + /// + /// The message that describes the error. + public DuplicateException(string message) + : base(message) + { + } + + /// + /// Initializes a new instance of the class with a specified error message and a + /// reference to the inner exception that is the cause of this exception. + /// + /// The message that describes the error. + /// + /// The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no + /// inner exception is specified. + /// + public DuplicateException(string message, Exception innerException) + : base(message, innerException) + { + } + } +} \ No newline at end of file -- cgit v1.2.3 From 95847e83d2be4cdb865c17a82cbc140d06bad7c6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 13 May 2026 20:39:37 -0500 Subject: add FileSafety --- src/slskd/Common/FileSafety.cs | 149 +++++++ tests/slskd.Tests.Unit/Common/FileSafetyTests.cs | 545 +++++++++++++++++++++++ 2 files changed, 694 insertions(+) create mode 100644 src/slskd/Common/FileSafety.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafetyTests.cs (limited to 'src') 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd; + +using System; +using System.IO; +using System.Linq; + +/// +/// Utility functions to help safely work with paths from untrusted sources. +/// +public static class FileSafety +{ + /// + /// An alternative to that disallows rooted segments in the second or + /// subsequent position, and disallows segments containing path traversal characters "." and "..". + /// + /// The root directory. + /// The segments to append. + /// The combined path. + /// Thrown if the root, list of segments, or one or more segments is null. + /// Thrown if any of the specified segments is rooted, or if any contain path traversal characters. + public static string CombineSafely(string root, 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; + } + + /// + /// Returns a value indicating whether the specified contains path traversal segments. + /// + /// The path to check. + /// True if one or more segments is present, false otherwise. + public static bool ContainsTraversalSegments(string path) => path?.Split('\\', '/')?.Any(s => s is "." or "..") ?? false; + + /// + /// Returns a value indicating whether the specified is absolute (rooted), using + /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// + /// + /// 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. + /// + /// The path to check. + /// True if the path is absolute, false otherwise. + 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; + } + + /// + /// Returns a value indicating whether the specified , using + /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// + /// The path to check. + /// True if the path is relative, false otherwise. + public static bool IsPathRelative(string path) => !IsPathAbsolute(path); +} \ 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(() => FileSafety.CombineSafely(Base, segment)); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentIsRooted() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(Base, "valid", "/escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentIsRooted_Windows() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(Base, "valid", "C:\\escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsRooted() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(Base, "sub", "dir", "/escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsRooted_Windows() + { + var ex = Assert.Throws(() => + 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(() => FileSafety.CombineSafely(Base, segment)); + Assert.Contains("traversal", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentContainsTraversal() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(Base, "valid", "../escape")); + Assert.Contains("traversal", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsTraversal() + { + var ex = Assert.Throws(() => + 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(() => 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(() => 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(() => FileSafety.CombineSafely(Base, (string)null)); + } + + [Fact] + public void NullBasePath_Throws() + { + Assert.ThrowsAny(() => 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 -- cgit v1.2.3 From 29ad269c1b688d7e06935cf95ba337bbe946ced4 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 13 May 2026 20:40:03 -0500 Subject: add validators for absolute and relative paths --- .../Common/Validation/AbsoluteFilePathAttribute.cs | 58 ------ .../Common/Validation/AbsolutePathAttribute.cs | 63 ++++++ .../Common/Validation/RelativePathAttribute.cs | 63 ++++++ .../Validation/AbsolutePathAttributeTests.cs | 229 +++++++++++++++++++++ .../Validation/RelativePathAttributeTests.cs | 131 ++++++++++++ 5 files changed, 486 insertions(+), 58 deletions(-) delete mode 100644 src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs create mode 100644 src/slskd/Common/Validation/AbsolutePathAttribute.cs create mode 100644 src/slskd/Common/Validation/RelativePathAttribute.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs (limited to 'src') diff --git a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs b/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs deleted file mode 100644 index 8f87e479..00000000 --- a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Validation -{ - using System.ComponentModel.DataAnnotations; - using System.IO; - - /// - /// Validates that the specified path is absolute. - /// - public class AbsoluteFilePathAttribute : ValidationAttribute - { - protected override ValidationResult IsValid(object value, ValidationContext validationContext) - { - if (value != null) - { - var filePath = value.ToString(); - - if (!string.IsNullOrEmpty(filePath) && !Path.IsPathRooted(filePath)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); - } - } - - return ValidationResult.Success; - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs new file mode 100644 index 00000000..4c9f5e53 --- /dev/null +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -0,0 +1,63 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + + /// + /// Validates that the specified path is absolute. + /// + public class AbsolutePathAttribute : 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.IsPathAbsolute(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 '..')"); + } + } + + 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + + /// + /// Validates that the specified path is relative. + /// + 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/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/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 -- cgit v1.2.3 From affd1cd7d6ceefd978431f421df4041d6d57f3da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 13 May 2026 20:40:53 -0500 Subject: add validator for disallowed characters --- .../Validation/DisallowedCharactersAttribute.cs | 71 ++++++ .../DisallowedCharactersAttributeTests.cs | 254 +++++++++++++++++++++ 2 files changed, 325 insertions(+) create mode 100644 src/slskd/Common/Validation/DisallowedCharactersAttribute.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs (limited to 'src') 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation; + +using System.ComponentModel.DataAnnotations; +using System.Linq; + +/// +/// Validates that the value does not contain any of the characters. +/// +public class DisallowedCharactersAttribute : ValidationAttribute +{ + public DisallowedCharactersAttribute(params char[] disallowed) + { + Disallowed = disallowed; + } + + /// + /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to . + /// + 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/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 -- cgit v1.2.3 From 2f6ccf6bf20cf0ac1c05f1dbc917a553e0544705 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 13 May 2026 21:04:38 -0500 Subject: oops --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 8cc369af..1ca5b84a 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2010,7 +2010,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; } -- cgit v1.2.3 From 945e032cc9ea5d1b8a5acf0e0a6cd908c214d911 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 09:11:33 -0500 Subject: use combinesafety in extension methods --- src/slskd/Common/CommonExtensions.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') 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 /// The fully qualified remote filename to convert. /// The base directory for the local filename. /// The converted filename. + [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()); } /// @@ -445,6 +446,7 @@ namespace slskd /// /// The fully qualified remote filename to convert. /// The converted filename. + [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); } /// -- cgit v1.2.3 From 71b400568e6be399531cb0185c4c9a2dea24a3a5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 09:13:11 -0500 Subject: disallow slashes in instance/agent names --- src/slskd/Core/Options.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 1ca5b84a..2b6adc29 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; } -- cgit v1.2.3 From 4f40140e9debd0976b0cabf47a1f2ec02598e3ea Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 09:13:33 -0500 Subject: require absolute paths for downloads and incomplete --- src/slskd/Core/Options.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 2b6adc29..51b3cab1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -767,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; @@ -777,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; -- cgit v1.2.3 From 95d0bf9a6558fdb32066e1d028795c4693dedf02 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 09:22:27 -0500 Subject: strengthen check of allowed paths --- src/slskd/Files/FileService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') 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))) -- cgit v1.2.3 From 71e3db84a2104af09ee386b3e75e8fee07720f08 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 09:24:57 -0500 Subject: sanitize inputs for relay routes --- src/slskd/Relay/API/Controllers/RelayController.cs | 27 +++++++++++++++++++--- 1 file changed, 24 insertions(+), 3 deletions(-) (limited to 'src') 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 { -- cgit v1.2.3 From 744c2cc326e5ac634415c9905ebd31a84e102e5f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 09:26:08 -0500 Subject: sanitize inputs for relay client --- src/slskd/Relay/RelayClient.cs | 34 ++++++++++++++++++++++++---------- 1 file changed, 24 insertions(+), 10 deletions(-) (limited to 'src') 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.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 { -- cgit v1.2.3 From ad279b4dfe756302f8985eb440717c205031ef84 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 09:27:49 -0500 Subject: clarify paths in the share service --- src/slskd/Shares/ShareService.cs | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) (limited to 'src') 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 /// The contents of the directory. public Task 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)); } -- cgit v1.2.3 From 016246421704db4311dcdfb8e611c7ca6a2198a3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 09:28:20 -0500 Subject: clarify variable name --- src/slskd/Shares/SqliteShareRepository.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') 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>(); - 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); } -- cgit v1.2.3 From e6cc409dbe1818b3cd60b2fe7241428684e2665f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 09:30:35 -0500 Subject: prevent path traversal attacks from enqueue or directory content requests --- src/slskd/Application.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) (limited to 'src') 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 /// A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory. private async Task> 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); -- cgit v1.2.3 From f13782644f835162186d1630809ee8508600cf9b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 19:01:05 -0500 Subject: wire up missed migration --- src/slskd/Core/Data/Migrator.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src') diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 61d64e76..d53d7c8c 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -60,6 +60,7 @@ public class Migrator { nameof(Z2025_07_26_PrivateMessageWasReplayedMigration), new Z2025_07_26_PrivateMessageWasReplayedMigration(connectionStrings: Databases) }, { nameof(Z2025_12_28_AdditionalTransferIndexesMigration), new Z2025_12_28_AdditionalTransferIndexesMigration(connectionStrings: Databases) }, { nameof(Z2026_02_17_TransferAttemptsAndBatchIdMigration), new Z2026_02_17_TransferAttemptsAndBatchIdMigration(connectionStrings: Databases) }, + { nameof(Z2026_04_30_DropTransferStartOffsetMigration), new Z2026_04_30_DropTransferStartOffsetMigration(connectionStrings: Databases) }, { nameof(Z2026_05_06_AddBatchesTableMigration), new Z2026_05_06_AddBatchesTableMigration(connectionStrings: Databases) }, }; } -- cgit v1.2.3 From 38cdbb2a30358a509fd1c080747c4ad8101cd344 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 19:02:41 -0500 Subject: revert option tweaks --- src/slskd/Core/Options.cs | 5 ----- 1 file changed, 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 90a72f7d..51b3cab1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -882,10 +882,6 @@ namespace slskd { results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; aliases may not contain path separators '/' or '\\'")); } - else if (share.Alias == "." || share.Alias == "..") - { - results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; aliases may not be path traversal characters '.' or '..'")); - } } return results; @@ -2045,7 +2041,6 @@ namespace slskd [EnvironmentVariable("CONTENT_PATH")] [Description("path to static web content")] [StringLength(255, MinimumLength = 1)] - [RelativePath] [DirectoryExists(relativeToApplicationDirectory: true)] [RequiresRestart] public string ContentPath { get; init; } = "wwwroot"; -- cgit v1.2.3 From d4c06cba98911c1fdad4ba65a6450180c0df9684 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 May 2026 19:03:04 -0500 Subject: tweaks --- src/slskd/Common/Validation/GuidAttribute.cs | 2 +- .../Z2026_05_06_AddBatchesTableMigration.cs | 2 +- .../API/Controllers/TransfersController.cs | 41 +++++++++++++++------- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 4 +-- 4 files changed, 32 insertions(+), 17 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/GuidAttribute.cs b/src/slskd/Common/Validation/GuidAttribute.cs index 9139ffef..5728b8f6 100644 --- a/src/slskd/Common/Validation/GuidAttribute.cs +++ b/src/slskd/Common/Validation/GuidAttribute.cs @@ -51,7 +51,7 @@ namespace slskd.Validation return ValidationResult.Success; } - return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUIDv4"); + return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUID"); } } } diff --git a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs index be56bfed..9b373f71 100644 --- a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs @@ -46,7 +46,7 @@ public class Z2026_05_06_AddBatchesTableMigration : IMigration ConnectionString = connectionStrings[Database.Transfers]; } - private ILogger Log { get; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); private string ConnectionString { get; } public bool NeedsToBeApplied() diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 1d748f35..4fcb8d5a 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -287,11 +287,22 @@ namespace slskd.Transfers.API } } + /// + /// Enqueues a batch of downloads. + /// + /// The batch details. + /// + /// One or more downloads were successfully enqueued. + /// The request succeeded, but all downloads were already enqueued. + /// An unexpected error was encountered. [HttpPost("downloads/batches")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(201)] + [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 403)] + [ProducesResponseType(typeof(string), 409)] + [ProducesResponseType(typeof(string), 429)] [ProducesResponseType(typeof(string), 500)] public async Task EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request) { @@ -310,22 +321,22 @@ namespace slskd.Transfers.API return BadRequest("At least one file is required"); } - if (request.Files.Any( - r => r is null - || string.IsNullOrWhiteSpace(r.Filename) - || r.Size < 0)) + if (request.Files.Any(r => r is null)) { - return BadRequest("One or more files in the request are invalid"); + return BadRequest("One or more files in the request are null"); } - if (request.Files.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) + if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count) { - return BadRequest("One or more files in the request contain a dangerous path traversal segment"); + return BadRequest("Two or more files in the request are repeated"); } - if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count) + // a user would have to deliberately fake this, as no OS and no client are capable of scanning + // such a file into configured shares + if (request.Files.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) { - return BadRequest("One or more files in the request are duplicates"); + Log.Warning("Attempt to enqueue one or more files containing unsafe path segments from user {Username} (one or more of path traversal characters '.' and '..')", request.Username); + return BadRequest("One or more files in the request contain an unsafe path traversal segment"); } Guid? batchId; @@ -343,6 +354,8 @@ namespace slskd.Transfers.API return BadRequest("One or more provided identifiers is not a valid GUID/UUIDv4"); } + batchId ??= Guid.NewGuid(); + if (!DownloadRequestLimiter.Wait(0)) { return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); @@ -357,9 +370,10 @@ namespace slskd.Transfers.API throw new UserOfflineException($"User {request.Username} appears to be offline"); } + // throws DuplicateException if a record already exists await Transfers.Downloads.Batches.CreateAsync(new() { - Id = batchId ?? Guid.NewGuid(), + Id = batchId.Value, SearchId = searchId, Username = request.Username, Options = new() @@ -377,12 +391,13 @@ namespace slskd.Transfers.API if (failed.Count > 0) { - Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already in progress", failed.Count, request.Files.Count); + Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already queued or in progress", failed.Count, request.Files.Count); } - // the returned batch will have whatever Transfers were successfully inserted attached + // the returned batch will have whatever Transfers were successfully inserted attached (via Include()) var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == batchId); + // all of the files were already queued; list of transfers should be empty if (batch.Transfers.Count == 0) { return Ok(batch); @@ -393,7 +408,7 @@ namespace slskd.Transfers.API catch (DuplicateException ex) { Log.Error(ex, "Failed to enqueue {Count} files for {Username}: A Batch with ID {BatchId} already exists", request.Files.Count, request.Username, request.Id); - return Conflict(); + return Conflict($"A batch with ID {batchId} already exists"); } catch (Exception ex) { diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 823a4e40..fe539ce7 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -81,13 +81,13 @@ public record EnqueueDownloadBatchItem /// [Required] [StringLength(int.MaxValue, MinimumLength = 1)] - public string Filename { get; set; } + public string Filename { get; init; } /// /// The file size. /// [Range(0, long.MaxValue)] - public long Size { get; set; } + public long Size { get; init; } } public record EnqueueDownloadBatchOptions -- cgit v1.2.3 From c2055a762d3d5df2ac26845ca7a45a292cc6b6e1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 May 2026 22:04:37 -0500 Subject: fix tests --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 2 +- tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs | 6 +++--- .../Transfers/API/DTO/QueueDownloadBatchRequestTests.cs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 4fcb8d5a..ee3dfe2d 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -351,7 +351,7 @@ namespace slskd.Transfers.API catch (Exception ex) { Log.Warning("Failed to parse Guid from enqueue batch input: {Message}", ex.Message); - return BadRequest("One or more provided identifiers is not a valid GUID/UUIDv4"); + return BadRequest("One or more provided identifiers is not a valid GUID/UUID"); } batchId ??= Guid.NewGuid(); diff --git a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs index 85522c18..e574c130 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs @@ -46,7 +46,7 @@ public class GuidAttributeTests { var (isValid, errorMessage) = Validate(string.Empty); Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); } [Theory] @@ -60,7 +60,7 @@ public class GuidAttributeTests { var (isValid, errorMessage) = Validate(value); Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); } [Fact] @@ -68,7 +68,7 @@ public class GuidAttributeTests { var (isValid, errorMessage) = Validate(42); Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); } } } diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 9fa4d304..019e8cd5 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -42,7 +42,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(ValidRequest() with { Id = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The Id field must be a valid GUID/UUIDv4", results[0].ErrorMessage); + Assert.Equal("The Id field must be a valid GUID/UUID", results[0].ErrorMessage); } [Theory] @@ -78,7 +78,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(ValidRequest() with { SearchId = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The SearchId field must be a valid GUID/UUIDv4", results[0].ErrorMessage); + Assert.Equal("The SearchId field must be a valid GUID/UUID", results[0].ErrorMessage); } [Theory] -- cgit v1.2.3 From 61703575cf9038f6a0de89bb5b9be44431439618 Mon Sep 17 00:00:00 2001 From: maskedmaxx Date: Sat, 16 May 2026 14:20:48 -0400 Subject: Fix: strip trailing slashes from relay controller address - Normalize controller address in SignalR hub connection URL - Normalize controller address in HTTP client base address - Prevents connection issues when address ends w/ '/' fixes #1726 --- src/slskd/Relay/RelayClient.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 2e001bdc..974ca71e 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -273,7 +273,7 @@ namespace slskd.Relay StartCancellationTokenSource?.Cancel(); HubConnection = new HubConnectionBuilder() - .WithUrl($"{options.Relay.Controller.Address}/hub/relay", builder => + .WithUrl($"{options.Relay.Controller.Address.TrimEnd('/')}/hub/relay", builder => { builder.AccessTokenProvider = () => Task.FromResult(options.Relay.Controller.ApiKey); builder.HttpMessageHandlerFactory = (message) => @@ -338,7 +338,7 @@ namespace slskd.Relay } client.Timeout = TimeSpan.FromMilliseconds(int.MaxValue); - client.BaseAddress = new(options.Address); + client.BaseAddress = new(options.Address.TrimEnd('/')); return client; } -- cgit v1.2.3 From 8265857697b6116f97fc435d7313f0a8161b9e13 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 14:53:34 -0500 Subject: add NonTraversingPathAttribute --- .../Validation/NonTraversingPathAttribute.cs | 57 +++++++++++++ .../Validation/NonTraversingPathAttributeTests.cs | 94 ++++++++++++++++++++++ 2 files changed, 151 insertions(+) create mode 100644 src/slskd/Common/Validation/NonTraversingPathAttribute.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs (limited to 'src') diff --git a/src/slskd/Common/Validation/NonTraversingPathAttribute.cs b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs new file mode 100644 index 00000000..1e2616bd --- /dev/null +++ b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs @@ -0,0 +1,57 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + + /// + /// Validates that the specified path does not contain traversal segments '.' or '..'. + /// + public class NonTraversingPathAttribute : 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.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/tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs new file mode 100644 index 00000000..12efb899 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs @@ -0,0 +1,94 @@ +using System.ComponentModel.DataAnnotations; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class NonTraversingPathAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(string value) + { + var attribute = new NonTraversingPathAttribute(); + 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 NonTraversal_Passes + { + [Theory] + // Windows-style + [InlineData("C:\\Music\\foo\\Windows")] + [InlineData("C:/Music/foo/Windows")] + // Unix-style + [InlineData("/home/user/foo/etc")] + [InlineData("\\home\\user\\foo\\etc")] + // UNC (backslash) + [InlineData("\\\\server\\share\\foo\\folder")] + // UNC (forward slash) + [InlineData("//server/foo/share")] + // soulseek + [InlineData("@foo/bar/baz")] + [InlineData("@foo\\bar\\baz")] + // filenames + [InlineData("@foo/bar/baz/baz../..qux/file.ext")] + public void NonTraversalSegment_Passes(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.True(isValid); + Assert.Null(errorMessage); + } + } + + // 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 + [InlineData("C:\\Music\\..\\Windows")] + [InlineData("C:\\Music\\.\\Artist")] + [InlineData("C:/Music/../Windows")] + [InlineData("C:/Music/./Artist")] + [InlineData("C:\\..")] + [InlineData("D:\\a\\b\\..\\c")] + // Unix-style + [InlineData("/../etc")] + [InlineData("/home/user/../etc")] + [InlineData("/home/user/./Music")] + [InlineData("/home/../../etc")] + // UNC (backslash) + [InlineData("\\\\server\\..\\Windows")] + [InlineData("\\\\server\\share\\..\\other")] + [InlineData("\\\\server\\share\\.\\folder")] + // UNC (forward slash) + [InlineData("//server/../share")] + [InlineData("//server/share/../other")] + // soulseek + [InlineData("@foo/bar/baz/baz/../file.ext")] + [InlineData("@foo/bar/baz/./../file.ext")] + [InlineData("@foo/bar/baz/./baz/file.ext")] + public void TraversalSegment_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Contains("traversal segments", errorMessage); + } + } +} -- cgit v1.2.3 From 8dc86c07d7e3c0ad82ad8e1c1c64b26a460774ac Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 14:54:14 -0500 Subject: tweak validation on batch request --- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 7 +++- .../API/DTO/QueueDownloadBatchRequestTests.cs | 47 ++++++++++++++++++---- 2 files changed, 45 insertions(+), 9 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index fe539ce7..05a913bd 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -58,7 +58,8 @@ public record QueueDownloadBatchRequest /// The username of the user from which to download. /// [Required] - [StringLength(500, MinimumLength = 1)] + [NotNullOrWhiteSpace] + [StringLength(maximumLength: 500)] public string Username { get; init; } /// @@ -80,7 +81,8 @@ public record EnqueueDownloadBatchItem /// The name of the file. /// [Required] - [StringLength(int.MaxValue, MinimumLength = 1)] + [NotNullOrWhiteSpace] + [NonTraversingPath] public string Filename { get; init; } /// @@ -96,5 +98,6 @@ public record EnqueueDownloadBatchOptions /// The destination directory for the files, relative to the configured download directory. /// [RelativePath] + [NonTraversingPath] public string Destination { get; init; } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 019e8cd5..2440291c 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -102,8 +102,7 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(ValidRequest() with { Username = null }); Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Username field is required.", results[0].ErrorMessage); + Assert.Contains(results, r => r.ErrorMessage == "The Username field is required."); } [Fact] @@ -111,8 +110,15 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(ValidRequest() with { Username = "" }); Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Username field is required.", results[0].ErrorMessage); + Assert.Contains(results, r => r.ErrorMessage == "The Username field is required."); + } + + [Fact] + public void Whitespace_Fails() + { + var (isValid, results) = Validate(ValidRequest() with { Username = " " }); + Assert.False(isValid); + Assert.Contains(results, r => r.ErrorMessage == "The Username field is required."); } [Fact] @@ -173,8 +179,7 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Filename field is required.", results[0].ErrorMessage); + Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); } [Fact] @@ -182,7 +187,14 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); Assert.False(isValid); - Assert.Single(results); + Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); + } + + [Fact] + public void WhitespaceFilename_Fails() + { + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = " ", Size = 0 }); + Assert.False(isValid); Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); } @@ -215,6 +227,27 @@ public class QueueDownloadBatchRequestTests var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 1 }); Assert.True(isValid); } + + [Theory] + [InlineData("@foo/bar/../baz/file.mp3")] + [InlineData("@foo/bar/./baz/file.mp3")] + [InlineData("@foo\\bar\\..\\baz\\file.mp3")] + public void TraversalSegmentInFilename_Fails(string value) + { + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = value, Size = 0 }); + Assert.False(isValid); + Assert.Contains(results, r => r.ErrorMessage != null && r.ErrorMessage.Contains("traversal segments")); + } + + [Theory] + [InlineData("@foo/bar/baz/file.mp3")] + [InlineData("@foo/bar/baz/file..ext")] + [InlineData("@foo\\bar\\baz\\file.mp3")] + public void NonTraversalFilename_Passes(string value) + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = value, Size = 0 }); + Assert.True(isValid); + } } public class Options_Destination -- cgit v1.2.3 From b59d4b6b9b497c9c9c767e11da2af30dfd41983a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 14:54:22 -0500 Subject: add response --- .../API/DTO/QueueDownloadBatchResponse.cs | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs new file mode 100644 index 00000000..8e134c29 --- /dev/null +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs @@ -0,0 +1,41 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +using System.Collections.Generic; + +namespace slskd.Transfers.API; + +public record QueueDownloadBatchResponse +{ + public Batch Batch { get; init; } + public Dictionary Failures { get; init; } = []; +} -- cgit v1.2.3 From d8bebbbe1ead96b99246c88816f846747eed5bb7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 14:54:42 -0500 Subject: return a message when failing a file --- src/slskd/Transfers/Downloads/DownloadService.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 14048fac..89b8a6a7 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -82,7 +82,7 @@ namespace slskd.Transfers.Downloads /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default); + Task<(List Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default); /// /// Finds a single download matching the specified . @@ -268,7 +268,7 @@ namespace slskd.Transfers.Downloads /// Thrown when the username is null or an empty string. /// Thrown when no files are requested. /// Thrown when at least one of the requested files throws. - public async Task<(List Enqueued, List Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default) + public async Task<(List Enqueued, List<(string Filename, string Message)> Failed)> EnqueueAsync(string username, IEnumerable<(string Filename, long Size)> files, Guid? batchId = null, CancellationToken cancellationToken = default) { if (string.IsNullOrEmpty(username)) { @@ -325,7 +325,7 @@ namespace slskd.Transfers.Downloads } List enqueued = []; - List failed = []; + List<(string Filename, string Message)> failed = []; SemaphoreSlim userSemaphore; Task userSemaphoreWaitTask; @@ -423,7 +423,7 @@ namespace slskd.Transfers.Downloads if (existingInProgressRecord is not null) { Log.Debug("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} already in progress (id: {Id})", file.Filename, username, existingInProgressRecord.Id); - failed.Add(file.Filename); + failed.Add((file.Filename, "Skipped: Already in progress")); continue; } @@ -435,7 +435,7 @@ namespace slskd.Transfers.Downloads if (Client.Downloads?.Any(u => u.Username == username && u.Filename == file.Filename) ?? false) { Log.Warning("Ignoring concurrent download enqueue attempt; transfer for {Filename} from {Username} is tracked by the Soulseek client but not slskd", file.Filename, username); - failed.Add(file.Filename); + failed.Add((file.Filename, "Skipped: Already in progress")); continue; } @@ -626,7 +626,7 @@ namespace slskd.Transfers.Downloads { Log.Error(ex, "Failed to enqueue download of {Filename} from {Username}: {Message}", file.Filename, username, ex.Message); TryFail(transferId, exception: ex); - failed.Add(file.Filename); + failed.Add((file.Filename, $"Error: {ex.Message}")); if (CancellationTokens.TryRemove(transferId, out var cts)) { -- cgit v1.2.3 From 147aad8cca088734587c144434044a02d9ec7a96 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 17:40:44 -0500 Subject: tweak endpoint, docs, annotation. obsolete StateDescription to avoid usage --- .../Z2025_04_01_TransferStateMigration.cs | 3 + .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 13 +- src/slskd/Transfers/API/DTO/Transfer.cs | 169 --------------------- src/slskd/Transfers/TransfersDbContext.cs | 6 + src/slskd/Transfers/Types/Transfer.cs | 3 +- 5 files changed, 23 insertions(+), 171 deletions(-) delete mode 100644 src/slskd/Transfers/API/DTO/Transfer.cs (limited to 'src') diff --git a/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs index 6c5810c5..1a155f18 100644 --- a/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs @@ -69,7 +69,10 @@ public class Z2025_04_01_TransferStateMigration : IMigration var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); var txfers = schema["Transfers"]; +#pragma warning disable CS0618 // Type or member is obsolete return !txfers.Any(c => c.Name == nameof(Transfer.StateDescription)); +#pragma warning restore CS0618 // Type or member is obsolete + } public void Apply() diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 05a913bd..77f7e7a9 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -37,6 +37,9 @@ using slskd.Validation; namespace slskd.Transfers.API; +/// +/// Enqueue a batch of downloads. +/// public record QueueDownloadBatchRequest { /// @@ -75,6 +78,9 @@ public record QueueDownloadBatchRequest public EnqueueDownloadBatchOptions Options { get; init; } = new(); } +/// +/// An item in a download batch. +/// public record EnqueueDownloadBatchItem { /// @@ -88,10 +94,14 @@ public record EnqueueDownloadBatchItem /// /// The file size. /// + [Required] [Range(0, long.MaxValue)] - public long Size { get; init; } + public long? Size { get; init; } } +/// +/// Download batch options. +/// public record EnqueueDownloadBatchOptions { /// @@ -99,5 +109,6 @@ public record EnqueueDownloadBatchOptions /// [RelativePath] [NonTraversingPath] + [MinLength(1)] public string Destination { get; init; } } \ No newline at end of file diff --git a/src/slskd/Transfers/API/DTO/Transfer.cs b/src/slskd/Transfers/API/DTO/Transfer.cs deleted file mode 100644 index 949f15d4..00000000 --- a/src/slskd/Transfers/API/DTO/Transfer.cs +++ /dev/null @@ -1,169 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Transfers.API -{ - using System; - using System.Net; - using Soulseek; - - /// - /// A single file transfer. - /// - public class Transfer - { - /// - /// Gets the current average transfer speed. - /// - public double AverageSpeed { get; set; } - - /// - /// Gets the number of remaining bytes to be transferred. - /// - public long BytesRemaining { get; set; } - - /// - /// Gets the total number of bytes transferred. - /// - public long BytesTransferred { get; set; } - - /// - /// Gets the transfer direction. - /// - public TransferDirection Direction { get; set; } - - /// - /// Gets the current duration of the transfer, if it has been started. - /// - public double? ElapsedTime { get; set; } - - /// - /// Gets the UTC time at which the transfer transitioned into the state. - /// - public DateTime? EndTime { get; set; } - - /// - /// Gets the filename of the file to be transferred. - /// - public string Filename { get; set; } - - /// - /// Gets the transfer id. - /// - public string Id => Compute.Sha1Hash(Filename); - - /// - /// Gets the ip endpoint of the remote transfer connection, if one has been established. - /// - public IPEndPoint IPEndPoint { get; set; } - - /// - /// Gets the current progress in percent. - /// - public double PercentComplete { get; set; } - - /// - /// Gets the current place in queue, if it has been fetched. - /// - public int? PlaceInQueue { get; set; } - - /// - /// Gets the projected remaining duration of the transfer. - /// - public double? RemainingTime { get; set; } - - /// - /// Gets the remote unique token for the transfer. - /// - public int? RemoteToken { get; set; } - - /// - /// Gets the size of the file to be transferred, in bytes. - /// - public long Size { get; set; } - - /// - /// Gets the starting offset of the transfer, in bytes. - /// - public long StartOffset { get; set; } - - /// - /// Gets the UTC time at which the transfer transitioned into the state. - /// - public DateTime? StartTime { get; set; } - - /// - /// Gets the state of the transfer. - /// - public TransferStates State { get; set; } - - /// - /// Gets the unique token for the transfer. - /// - public int Token { get; set; } - - /// - /// Gets the username of the peer to or from which the file is to be transferred. - /// - public string Username { get; set; } - - /// - /// Gets the Exception that caused the failure of the transfer, if applicable. - /// - public string Exception { get; set; } - - public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer) - { - return new Transfer() - { - AverageSpeed = transfer.AverageSpeed, - BytesRemaining = transfer.BytesRemaining, - BytesTransferred = transfer.BytesTransferred, - Direction = transfer.Direction, - ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds, - EndTime = transfer.EndTime, - Filename = transfer.Filename, - IPEndPoint = transfer.IPEndPoint, - PercentComplete = transfer.PercentComplete, - RemainingTime = transfer.RemainingTime?.TotalMilliseconds, - RemoteToken = transfer.RemoteToken, - Size = transfer.Size, - StartOffset = transfer.StartOffset, - StartTime = transfer.StartTime, - State = transfer.State, - Token = transfer.Token, - Username = transfer.Username, - Exception = transfer.Exception?.Message, - }; - } - } -} \ No newline at end of file diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 13d0984d..b25e7663 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -50,11 +50,17 @@ namespace slskd.Transfers public override int SaveChanges(bool acceptAllChangesOnSuccess) { // this is absolutely NOT IDEAL and will accellerate the move away from EF + // we have to do this to store both the integer and the string value in the database + // well, we don't *HAVE* to, but storing the string allows external apps to understand transfer history + // and not need to work out the flags. storing the integer allows us to use bitwise operations in queries, + // which is the main driver for this. foreach (var entry in ChangeTracker.Entries()) { if (entry.State == EntityState.Added || entry.State == EntityState.Modified) { +#pragma warning disable CS0618 // Type or member is obsolete entry.Entity.StateDescription = entry.Entity.State.ToString(); +#pragma warning restore CS0618 // Type or member is obsolete } } diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 8d1afa25..d33a5efc 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -90,6 +90,8 @@ public class Transfer /// and especially **DO NOT** set the value. The getter and setter can't be protected because /// EF Core needs them to be public. /// + [Obsolete("Use State isntead; this is a hack for EF")] + [JsonIgnore] public string StateDescription { get; set; } /// @@ -160,7 +162,6 @@ public class Transfer /// /// Gets or sets a value indicating whether the Transfer has been removed from the UI. /// - [JsonIgnore] public bool Removed { get; set; } [NotMapped] -- cgit v1.2.3 From 772df82d0faf98f00fc8cc2ee59051e386eaa998 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 18:52:44 -0500 Subject: remove disallowed character validation from instancename --- src/slskd/Core/Options.cs | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 51b3cab1..21f2c75f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -198,7 +198,6 @@ 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"; @@ -655,7 +654,6 @@ namespace slskd [Description("the name for this agent")] [StringLength(255, MinimumLength = 1)] [NotNullOrWhiteSpace] - [DisallowedCharacters('/', '\\')] [Secret] public string InstanceName { get; init; } -- cgit v1.2.3 From 74810d42ea08d9782bd83a02d06eaca9c2ecd9a5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 18:53:07 -0500 Subject: add StringAttribute to cover all string related validation --- .../Validation/DisallowedCharactersAttribute.cs | 71 --- src/slskd/Common/Validation/StringAttribute.cs | 92 ++++ .../DisallowedCharactersAttributeTests.cs | 254 ---------- .../Common/Validation/StringAttributeTests.cs | 517 +++++++++++++++++++++ 4 files changed, 609 insertions(+), 325 deletions(-) delete mode 100644 src/slskd/Common/Validation/DisallowedCharactersAttribute.cs create mode 100644 src/slskd/Common/Validation/StringAttribute.cs delete mode 100644 tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs (limited to 'src') diff --git a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs deleted file mode 100644 index 90ed3d81..00000000 --- a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs +++ /dev/null @@ -1,71 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Validation; - -using System.ComponentModel.DataAnnotations; -using System.Linq; - -/// -/// Validates that the value does not contain any of the characters. -/// -public class DisallowedCharactersAttribute : ValidationAttribute -{ - public DisallowedCharactersAttribute(params char[] disallowed) - { - Disallowed = disallowed; - } - - /// - /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to . - /// - 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/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs new file mode 100644 index 00000000..2fcf4283 --- /dev/null +++ b/src/slskd/Common/Validation/StringAttribute.cs @@ -0,0 +1,92 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + using System.Linq; + using System.Text.RegularExpressions; + + /// + /// Validates that the value is not null or whitespace. + /// + public class StringAttribute : ValidationAttribute + { + public bool AllowNull { get; set; } = true; + public bool AllowEmpty { get; set; } = true; + public bool AllowWhiteSpace { get; set; } = true; + public char[] DisallowedCharacters { get; set; } = []; + public int MinimumLength { get; set; } = 0; + public int MaximumLength { get; set; } = int.MaxValue; + public Regex Pattern { get; set; } = null; + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + var val = (string)value; + + if (!AllowNull && val is null) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not be null"); + } + + if (!AllowEmpty && val is "") + { + return new ValidationResult($"The {validationContext.DisplayName} field must contain at least one character"); + } + + // check this after empty to avoid overlap + if (!AllowWhiteSpace && string.IsNullOrWhiteSpace(val)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain only whitespace"); + } + + if (val.Length < MinimumLength || val.Length > MaximumLength) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be between {MinimumLength} and {MaximumLength} characters"); + } + + var invalid = val.Where(c => DisallowedCharacters.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d))); + + if (invalid.Any()) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}"); + } + + if (Pattern is not null && Pattern.IsMatch(val)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must match the regular expression {Pattern.ToJson()}"); + } + + return ValidationResult.Success; + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs deleted file mode 100644 index 4654fd25..00000000 --- a/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs +++ /dev/null @@ -1,254 +0,0 @@ -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); - } - } -} diff --git a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs new file mode 100644 index 00000000..dfa964f7 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs @@ -0,0 +1,517 @@ +using System; +using System.ComponentModel.DataAnnotations; +using System.Text.RegularExpressions; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class StringAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + { + var attr = new StringAttribute(); + configure?.Invoke(attr); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attr.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); + } + + // empty string passes all default checks — [Required] handles presence + [Fact] + public void EmptyString_Passes() + { + var (isValid, _) = Validate(string.Empty); + Assert.True(isValid); + } + + public class DisallowedCharacters + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) + => StringAttributeTests.Validate(value, a => a.DisallowedCharacters = disallowed); + + public class Passes + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) + => DisallowedCharacters.Validate(value, disallowed); + + [Fact] + public void EmptyString_Passes() + { + var (isValid, _) = Validate(string.Empty, ['!']); + Assert.True(isValid); + } + + [Fact] + public void NoDisallowedCharsPresent_Passes() + { + var (isValid, _) = Validate("hello", ['!', '@']); + Assert.True(isValid); + } + + [Fact] + public void EmptyDisallowedSet_Passes() + { + var (isValid, _) = Validate("hello!@#", []); + Assert.True(isValid); + } + + [Fact] + public void Unicode_AllowedChars_Pass() + { + var (isValid, _) = Validate("пользователь/音楽", ['!', '@']); + Assert.True(isValid); + } + + // Case-insensitive matching only folds the declared disallowed chars, not all letters; + // a disallowed lower-case letter does not block an entirely different upper-case letter. + [Fact] + public void LowerCaseDisallowed_DoesNotBlock_Different_UpperCaseLetter() + { + var (isValid, _) = Validate("B", ['a']); + Assert.True(isValid); + } + } + + public class Fails + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) + => DisallowedCharacters.Validate(value, disallowed); + + [Fact] + public void SingleDisallowedChar_Fails() + { + var (isValid, _) = Validate("hello!", ['!']); + Assert.False(isValid); + } + + [Fact] + public void DisallowedCharAtStart_Fails() + { + var (isValid, _) = Validate("!hello", ['!']); + Assert.False(isValid); + } + + [Fact] + public void DisallowedCharAtEnd_Fails() + { + var (isValid, _) = Validate("hello!", ['!']); + Assert.False(isValid); + } + + [Fact] + public void DisallowedCharInMiddle_Fails() + { + var (isValid, _) = Validate("hel!lo", ['!']); + Assert.False(isValid); + } + + [Fact] + public void OneOfMultipleDisallowedCharsPresent_Fails() + { + var (isValid, _) = Validate("hello!", ['!', '@', '#']); + Assert.False(isValid); + } + + [Fact] + public void MultipleDisallowedCharsAllPresent_Fails() + { + var (isValid, _) = Validate("h!e@l#lo", ['!', '@', '#']); + Assert.False(isValid); + } + + [Fact] + public void DisallowedCharRepeated_Fails() + { + var (isValid, _) = Validate("he!lo!", ['!']); + Assert.False(isValid); + } + + [Fact] + public void AllCharsDisallowed_Fails() + { + var (isValid, _) = Validate("!@#", ['!', '@', '#']); + Assert.False(isValid); + } + + [Fact] + public void Unicode_DisallowedChar_Fails() + { + var (isValid, _) = Validate("пользователь", ['е']); + Assert.False(isValid); + } + + // character matching is always case-insensitive + [Fact] + public void LowerCaseDisallowed_Blocks_UpperCase() + { + var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o']); + Assert.False(isValid); + } + + [Fact] + public void UpperCaseDisallowed_Blocks_LowerCase() + { + var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O']); + Assert.False(isValid); + } + + [Fact] + public void ExactMatch_Fails() + { + var (isValid, _) = Validate("hello", ['h']); + Assert.False(isValid); + } + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) + => DisallowedCharacters.Validate(value, disallowed); + + [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 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']); + Assert.Contains("'A'", errorMessage); + Assert.DoesNotContain("'a'", errorMessage); + } + } + } + + // ----------------------------------------------------------------------- + // AllowNull + // ----------------------------------------------------------------------- + public class AllowNull + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => StringAttributeTests.Validate(value, configure); + + [Fact] + public void Null_Fails_When_AllowNull_Is_False() + { + var (isValid, _) = Validate(null, a => a.AllowNull = false); + Assert.False(isValid); + } + + [Fact] + public void NonNull_Passes_When_AllowNull_Is_False() + { + var (isValid, _) = Validate("hello", a => a.AllowNull = false); + Assert.True(isValid); + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => AllowNull.Validate(value, configure); + + [Fact] + public void Null_Keyword() + { + var (_, message) = Validate(null, a => a.AllowNull = false); + Assert.Contains("null", message); + } + } + } + + // ----------------------------------------------------------------------- + // AllowEmpty + // ----------------------------------------------------------------------- + public class AllowEmpty + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => StringAttributeTests.Validate(value, configure); + + [Fact] + public void Empty_Passes_When_AllowEmpty_Is_True() + { + var (isValid, _) = Validate(string.Empty); + Assert.True(isValid); + } + + [Fact] + public void Empty_Fails_When_AllowEmpty_Is_False() + { + var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = false); + Assert.False(isValid); + } + + [Fact] + public void NonEmpty_Passes_When_AllowEmpty_Is_False() + { + var (isValid, _) = Validate("hello", a => a.AllowEmpty = false); + Assert.True(isValid); + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => AllowEmpty.Validate(value, configure); + + [Fact] + public void Character_Keyword() + { + var (_, message) = Validate(string.Empty, a => a.AllowEmpty = false); + Assert.Contains("character", message); + } + } + } + + // ----------------------------------------------------------------------- + // AllowWhiteSpace + // ----------------------------------------------------------------------- + public class AllowWhiteSpace + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => StringAttributeTests.Validate(value, configure); + + [Fact] + public void WhiteSpace_Passes_When_AllowWhiteSpace_Is_True() + { + var (isValid, _) = Validate(" "); + Assert.True(isValid); + } + + [Fact] + public void WhiteSpace_Fails_When_AllowWhiteSpace_Is_False() + { + var (isValid, _) = Validate(" ", a => a.AllowWhiteSpace = false); + Assert.False(isValid); + } + + [Fact] + public void NonWhiteSpace_Passes_When_AllowWhiteSpace_Is_False() + { + var (isValid, _) = Validate("hello", a => a.AllowWhiteSpace = false); + Assert.True(isValid); + } + + // IsNullOrWhiteSpace("") is true, so empty string also fails the whitespace check + // when AllowEmpty=true (default) and AllowWhiteSpace=false + [Fact] + public void EmptyString_Fails_When_AllowWhiteSpace_Is_False_And_AllowEmpty_Is_True() + { + var (isValid, _) = Validate(string.Empty, a => a.AllowWhiteSpace = false); + Assert.False(isValid); + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => AllowWhiteSpace.Validate(value, configure); + + [Fact] + public void Whitespace_Keyword() + { + var (_, message) = Validate(" ", a => a.AllowWhiteSpace = false); + Assert.Contains("whitespace", message); + } + } + } + + // ----------------------------------------------------------------------- + // Length (MinimumLength / MaximumLength) + // ----------------------------------------------------------------------- + public class Length + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => StringAttributeTests.Validate(value, configure); + + [Fact] + public void Within_Range_Passes() + { + var (isValid, _) = Validate("hello", a => { a.MinimumLength = 3; a.MaximumLength = 10; }); + Assert.True(isValid); + } + + [Fact] + public void ExactlyAtMinimumLength_Passes() + { + var (isValid, _) = Validate("hi", a => a.MinimumLength = 2); + Assert.True(isValid); + } + + [Fact] + public void ExactlyAtMaximumLength_Passes() + { + var (isValid, _) = Validate("hello", a => a.MaximumLength = 5); + Assert.True(isValid); + } + + [Fact] + public void BelowMinimumLength_Fails() + { + var (isValid, _) = Validate("hi", a => a.MinimumLength = 5); + Assert.False(isValid); + } + + [Fact] + public void ExceedsMaximumLength_Fails() + { + var (isValid, _) = Validate("hello world", a => a.MaximumLength = 5); + Assert.False(isValid); + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => Length.Validate(value, configure); + + [Fact] + public void MinimumLength_Value() + { + var (_, message) = Validate("hi", a => { a.MinimumLength = 5; a.MaximumLength = 20; }); + Assert.Contains("5", message); + } + + [Fact] + public void MaximumLength_Value() + { + var (_, message) = Validate("hi", a => { a.MinimumLength = 5; a.MaximumLength = 20; }); + Assert.Contains("20", message); + } + } + } + + // ----------------------------------------------------------------------- + // Pattern + // ----------------------------------------------------------------------- + // The Pattern check fails validation when the value *matches* the regex — + // Pattern acts as a "disallowed pattern" rather than a "required pattern". + public class Pattern + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => StringAttributeTests.Validate(value, configure); + + [Fact] + public void NullPattern_Passes() + { + // Pattern defaults to null; any value passes the pattern check + var (isValid, _) = Validate("hello"); + Assert.True(isValid); + } + + [Fact] + public void ValueMatchingPattern_Fails() + { + var (isValid, _) = Validate("hello1", a => a.Pattern = new Regex("[0-9]")); + Assert.False(isValid); + } + + [Fact] + public void ValueNotMatchingPattern_Passes() + { + var (isValid, _) = Validate("hello", a => a.Pattern = new Regex("[0-9]")); + Assert.True(isValid); + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => Pattern.Validate(value, configure); + + [Fact] + public void RegularExpression_Keyword() + { + var (_, message) = Validate("hello1", a => a.Pattern = new Regex("[0-9]")); + Assert.Contains("regular expression", message); + } + } + } + + // ----------------------------------------------------------------------- + // Check ordering + // ----------------------------------------------------------------------- + // Validation checks run in declaration order; when a value violates multiple + // conditions the error from the first check in code is the one returned. + public class CheckOrdering + { + private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) + => StringAttributeTests.Validate(value, configure); + + // AllowNull is checked before AllowEmpty: + // null with both disabled returns the null error, not the empty error. + [Fact] + public void Null_ReturnsNullError_Not_EmptyError() + { + var (_, message) = Validate(null, a => { a.AllowNull = false; a.AllowEmpty = false; }); + Assert.Contains("null", message); + Assert.DoesNotContain("character", message); + } + + // AllowEmpty is checked before AllowWhiteSpace: + // "" with both disabled returns the empty error, not the whitespace error. + [Fact] + public void Empty_ReturnsEmptyError_Not_WhitespaceError() + { + var (_, message) = Validate(string.Empty, a => { a.AllowEmpty = false; a.AllowWhiteSpace = false; }); + Assert.Contains("character", message); + Assert.DoesNotContain("whitespace", message); + } + + // AllowWhiteSpace is checked before the length check: + // a whitespace string that is also below MinimumLength returns the whitespace error. + [Fact] + public void Whitespace_ReturnsWhitespaceError_Not_LengthError() + { + var (_, message) = Validate(" ", a => { a.AllowWhiteSpace = false; a.MinimumLength = 10; }); + Assert.Contains("whitespace", message); + Assert.DoesNotContain("between", message); + } + + // Length is checked before DisallowedCharacters: + // a too-short string that also contains a disallowed character returns the length error. + [Fact] + public void TooShort_ReturnsLengthError_Not_DisallowedCharsError() + { + var (_, message) = Validate("hi!", a => { a.MinimumLength = 10; a.DisallowedCharacters = ['!']; }); + Assert.Contains("between", message); + Assert.DoesNotContain("disallowed", message); + } + + // DisallowedCharacters is checked before Pattern: + // a string with a disallowed character that also matches the pattern returns the disallowed-chars error. + [Fact] + public void DisallowedChar_ReturnsDisallowedError_Not_PatternError() + { + var (_, message) = Validate("hello!1", a => { a.DisallowedCharacters = ['!']; a.Pattern = new Regex("[0-9]"); }); + Assert.Contains("disallowed", message); + Assert.DoesNotContain("expression", message); + } + } +} -- cgit v1.2.3 From 21167d26a62add9ba54c50faa9b93970a478d27b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 18:53:38 -0500 Subject: failures as objects to avoid dictionary keys containing crap --- src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs index 8e134c29..84b570bc 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs @@ -37,5 +37,11 @@ namespace slskd.Transfers.API; public record QueueDownloadBatchResponse { public Batch Batch { get; init; } - public Dictionary Failures { get; init; } = []; + public IReadOnlyCollection Failures { get; init; } = []; +} + +public record QueueDownloadBatchResponseFailure +{ + public string Filename { get; init; } + public string Message { get; init; } } -- cgit v1.2.3 From aee67635e0c1048b890bc98812678086407d3b92 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 18:54:15 -0500 Subject: readonly fils, validatie destination --- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 77f7e7a9..53f5290f 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -70,7 +70,7 @@ public record QueueDownloadBatchRequest /// [Required] [MinLength(1)] - public List Files { get; init; } = []; + public IReadOnlyCollection Files { get; init; } = []; /// /// Options for the Batch. @@ -109,6 +109,6 @@ public record EnqueueDownloadBatchOptions /// [RelativePath] [NonTraversingPath] - [MinLength(1)] + [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] public string Destination { get; init; } } \ No newline at end of file -- cgit v1.2.3 From 0346199c4ed5edb0d502f2e3f5972aafeea6c923 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 19:01:50 -0500 Subject: fix test --- src/slskd/Common/Validation/StringAttribute.cs | 13 ++++++++++--- .../Common/Validation/StringAttributeTests.cs | 7 +++++++ 2 files changed, 17 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs index 2fcf4283..bb323ba2 100644 --- a/src/slskd/Common/Validation/StringAttribute.cs +++ b/src/slskd/Common/Validation/StringAttribute.cs @@ -53,9 +53,16 @@ namespace slskd.Validation { var val = (string)value; - if (!AllowNull && val is null) + if (val is null) { - return new ValidationResult($"The {validationContext.DisplayName} field must not be null"); + if (!AllowNull) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not be null"); + } + else + { + return ValidationResult.Success; + } } if (!AllowEmpty && val is "") @@ -64,7 +71,7 @@ namespace slskd.Validation } // check this after empty to avoid overlap - if (!AllowWhiteSpace && string.IsNullOrWhiteSpace(val)) + if (!AllowWhiteSpace && val.All(c => char.IsWhiteSpace(c))) { return new ValidationResult($"The {validationContext.DisplayName} field must not contain only whitespace"); } diff --git a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs index dfa964f7..71e6ce8b 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs @@ -221,6 +221,13 @@ public class StringAttributeTests private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) => StringAttributeTests.Validate(value, configure); + [Fact] + public void Null_Passes_When_AllowNull_Is_True() + { + var (isValid, _) = Validate(null); + Assert.True(isValid); + } + [Fact] public void Null_Fails_When_AllowNull_Is_False() { -- cgit v1.2.3 From 5d16f6f9cccf72c29b8bbf206c851005e3375d79 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 19:02:40 -0500 Subject: wip --- .../API/Controllers/TransfersController.cs | 84 +++++++++++++--------- 1 file changed, 50 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index ee3dfe2d..01dd61bd 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -42,6 +42,7 @@ namespace slskd.Transfers.API using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; using slskd.Users; @@ -292,18 +293,24 @@ namespace slskd.Transfers.API /// /// The batch details. /// - /// One or more downloads were successfully enqueued. - /// The request succeeded, but all downloads were already enqueued. + /// All downloads were successfully enqueued. + /// The request succeeded, but all downloads failed to be enqueued. + /// Some downloads were successfully enqueued, while some failed. + /// Bad request. + /// The request was forbidden. + /// A batch with the same ID already exists. + /// Request throttled. /// An unexpected error was encountered. [HttpPost("downloads/batches")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(200)] - [ProducesResponseType(201)] - [ProducesResponseType(typeof(string), 400)] - [ProducesResponseType(typeof(string), 403)] - [ProducesResponseType(typeof(string), 409)] - [ProducesResponseType(typeof(string), 429)] - [ProducesResponseType(typeof(string), 500)] + [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status201Created)] + [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status207MultiStatus)] + [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(string), StatusCodes.Status403Forbidden)] + [ProducesResponseType(typeof(string), StatusCodes.Status409Conflict)] + [ProducesResponseType(typeof(string), StatusCodes.Status429TooManyRequests)] + [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)] public async Task EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request) { if (Program.IsRelayAgent) @@ -316,11 +323,6 @@ namespace slskd.Transfers.API return BadRequest(ModelState.GetReadableString()); } - if ((request.Files?.Count ?? 0) == 0) - { - return BadRequest("At least one file is required"); - } - if (request.Files.Any(r => r is null)) { return BadRequest("One or more files in the request are null"); @@ -331,18 +333,9 @@ namespace slskd.Transfers.API return BadRequest("Two or more files in the request are repeated"); } - // a user would have to deliberately fake this, as no OS and no client are capable of scanning - // such a file into configured shares - if (request.Files.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) - { - Log.Warning("Attempt to enqueue one or more files containing unsafe path segments from user {Username} (one or more of path traversal characters '.' and '..')", request.Username); - return BadRequest("One or more files in the request contain an unsafe path traversal segment"); - } - Guid? batchId; Guid? searchId; - // validation rules should prevent any problems here, but we have a backstop just in case try { batchId = string.IsNullOrWhiteSpace(request.Id) ? null : Guid.Parse(request.Id); @@ -383,27 +376,50 @@ namespace slskd.Transfers.API }); // Transfer records will have been inserted before this returns, unless they were rejected - // because they were already in progress, in which case they will show up in 'failed' + // because they were already in progress, in which case they will show up in 'failed'. or maybe they + // failed with an error. either way this complicates the return code var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync( username: request.Username, - files: request.Files.Select(r => (r.Filename, r.Size)), + files: request.Files.Select(r => (r.Filename, r.Size.Value)), batchId: batchId); if (failed.Count > 0) { - Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already queued or in progress", failed.Count, request.Files.Count); + Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, batchId, failed); } // the returned batch will have whatever Transfers were successfully inserted attached (via Include()) + // failed transfers MAY or MAY NOT have an associated database record. if they do, it should have been + // properly finalized and marked as a failure var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == batchId); - // all of the files were already queued; list of transfers should be empty - if (batch.Transfers.Count == 0) + var response = new QueueDownloadBatchResponse + { + Batch = batch, + Failures = failed.Select(f => new QueueDownloadBatchResponseFailure { Filename = f.Filename, Message = f.Message }).ToList(), + }; + + // basically a no-op, but we did create the batch record (and it's useless, but it's there) + // there's nothing to process asynchronously, so we'll return 200. 204 makes more sense to me, + // but it doesn't allow a body and without it the caller will never know the id unless they supplied it + if (response.Failures.Count == request.Files.Count) { - return Ok(batch); + return StatusCode(StatusCodes.Status200OK, response); } - return StatusCode(201, batch); + // if at least one (but not all) failed, we're in a weird state so send the most appropriate status code + // along with the batch and list of failures; the caller will have to pick through it and decide what to do + if (response.Failures.Count > 0) + { + return StatusCode(StatusCodes.Status207MultiStatus, response); + } + + // everything passed and we are now (or will eventually be) downloading asynchronously + return StatusCode(StatusCodes.Status201Created, response); + } + catch (UserOfflineException ex) + { + return StatusCode(StatusCodes.Status404NotFound, ex.Message); } catch (DuplicateException ex) { @@ -412,8 +428,8 @@ namespace slskd.Transfers.API } catch (Exception ex) { - Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", request.Files.Count, request.Username, ex.Message); - return StatusCode(500, ex.Message); + Log.Error(ex, "Failed to enqueue {Count} files for {Username} (batch Id: {BatchId}): {Message}", request.Files.Count, request.Username, batchId, ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } finally { @@ -532,7 +548,7 @@ namespace slskd.Transfers.API [HttpGet("downloads/{username}/{id}")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(API.Transfer), 200)] + [ProducesResponseType(typeof(Transfer), 200)] [ProducesResponseType(404)] public IActionResult GetDownload([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) { @@ -567,7 +583,7 @@ namespace slskd.Transfers.API /// The specified download was not found. [HttpGet("downloads/{username}/{id}/position")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(API.Transfer), 200)] + [ProducesResponseType(typeof(Transfer), 200)] [ProducesResponseType(404)] public async Task GetPlaceInQueueAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) { -- cgit v1.2.3 From 946333991d4f06aa139e9659952b2ce2ca9e988d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 13:40:48 -0500 Subject: mess with tests and validation --- .../Common/Validation/AbsolutePathAttribute.cs | 6 - src/slskd/Common/Validation/GuidAttribute.cs | 26 +- .../Common/Validation/RelativePathAttribute.cs | 6 - src/slskd/Core/Options.cs | 3 + .../API/Controllers/TransfersController.cs | 4 +- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 3 +- .../Validation/AbsolutePathAttributeTests.cs | 33 --- .../Common/Validation/GuidAttributeTests.cs | 120 +++++--- .../Validation/RelativePathAttributeTests.cs | 26 -- .../Common/Validation/StringAttributeTests.cs | 308 +++++++-------------- .../API/DTO/QueueDownloadBatchRequestTests.cs | 2 +- 11 files changed, 211 insertions(+), 326 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 4c9f5e53..1999220f 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -49,12 +49,6 @@ namespace slskd.Validation { 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 '..')"); - } } return ValidationResult.Success; diff --git a/src/slskd/Common/Validation/GuidAttribute.cs b/src/slskd/Common/Validation/GuidAttribute.cs index 5728b8f6..f61527a4 100644 --- a/src/slskd/Common/Validation/GuidAttribute.cs +++ b/src/slskd/Common/Validation/GuidAttribute.cs @@ -32,6 +32,8 @@ namespace slskd.Validation { + using System; + using System.ComponentModel.DataAnnotations; /// @@ -39,6 +41,13 @@ namespace slskd.Validation /// public class GuidAttribute : ValidationAttribute { + public GuidAttribute(bool allowEmpty = false) + { + AllowEmpty = allowEmpty; + } + + public bool AllowEmpty { get; } + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value is null) @@ -46,8 +55,23 @@ namespace slskd.Validation return ValidationResult.Success; } - if (value is string str && System.Guid.TryParse(str, out _)) + if (value is Guid guid) { + if (!AllowEmpty && guid == Guid.Empty) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID"); + } + + return ValidationResult.Success; + } + + if (value is string str && Guid.TryParse(str, out guid)) + { + if (!AllowEmpty && guid == Guid.Empty) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID"); + } + return ValidationResult.Success; } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index e8865554..64e418b1 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -49,12 +49,6 @@ namespace slskd.Validation { 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; diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 21f2c75f..3d9c8fb2 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -766,6 +766,7 @@ namespace slskd [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] [AbsolutePath] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory; @@ -777,6 +778,7 @@ namespace slskd [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] [AbsolutePath] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; @@ -2013,6 +2015,7 @@ namespace slskd [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] [AbsolutePath] + [NonTraversingPath] [RequiresRestart] public string Socket { get; init; } diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 01dd61bd..3191e3a8 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -385,7 +385,7 @@ namespace slskd.Transfers.API if (failed.Count > 0) { - Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, batchId, failed); + Log.Warning("Failed to enqueue {Count} of {Total} files from {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, request.Username, batchId, failed); } // the returned batch will have whatever Transfers were successfully inserted attached (via Include()) @@ -488,7 +488,7 @@ namespace slskd.Transfers.API if (!Guid.TryParse(id, out var guid)) { - return BadRequest(); + return BadRequest($"The specified id {id} is not a valid GUID/UUID"); } try diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 53f5290f..c1b7d725 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -61,8 +61,7 @@ public record QueueDownloadBatchRequest /// The username of the user from which to download. /// [Required] - [NotNullOrWhiteSpace] - [StringLength(maximumLength: 500)] + [String(AllowNull = false, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1, MaximumLength = 500)] public string Username { get; init; } /// diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs index 53e25ac6..bc8601c5 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs @@ -171,39 +171,6 @@ public class AbsolutePathAttributeTests } } - // 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] diff --git a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs index e574c130..a26bb160 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs @@ -1,3 +1,4 @@ +using System; using System.ComponentModel.DataAnnotations; using slskd.Validation; using Xunit; @@ -6,9 +7,9 @@ namespace slskd.Tests.Unit.Common.Validation; public class GuidAttributeTests { - private static (bool IsValid, string ErrorMessage) Validate(object value) + private static (bool IsValid, string ErrorMessage) Validate(object value, bool allowEmpty = false) { - var attribute = new GuidAttribute(); + var attribute = new GuidAttribute(allowEmpty); var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; var result = attribute.GetValidationResult(value, context); return (result == null, result?.ErrorMessage); @@ -22,53 +23,84 @@ public class GuidAttributeTests Assert.True(isValid); } - public class Passes + [Fact] + public void Empty_String_Fails_If_AllowEmpty_False() + { + var (isValid, message) = Validate("00000000-0000-0000-0000-000000000000", allowEmpty: false); + Assert.False(isValid); + Assert.Contains("empty", message); + } + + [Fact] + public void Empty_Guid_Fails_If_AllowEmpty_False() { - [Theory] - [InlineData("d3b07384-d9a0-4b9b-abcd-012345678901")] // lowercase with hyphens - [InlineData("D3B07384-D9A0-4B9B-ABCD-012345678901")] // uppercase with hyphens - [InlineData("d3b07384d9a04b9babcd012345678901")] // no hyphens (N format) - [InlineData("{d3b07384-d9a0-4b9b-abcd-012345678901}")] // braces format - [InlineData("(d3b07384-d9a0-4b9b-abcd-012345678901)")] // parentheses format - [InlineData("00000000-0000-0000-0000-000000000000")] // all zeros - [InlineData("ffffffff-ffff-ffff-ffff-ffffffffffff")] // all f's - public void ValidGuidString_Passes(string value) - { - var (isValid, _) = Validate(value); - Assert.True(isValid); - } + var (isValid, message) = Validate(Guid.Empty, allowEmpty: false); + Assert.False(isValid); + Assert.Contains("empty", message); } - public class Fails + [Fact] + public void AllowEmpty_Guid_Defaults_False() { - [Fact] - public void EmptyString_Fails() - { - var (isValid, errorMessage) = Validate(string.Empty); - Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); - } + var (isValid, message) = Validate(Guid.Empty); + Assert.False(isValid); + Assert.Contains("empty", message); + } - [Theory] - [InlineData("not-a-guid")] // arbitrary string - [InlineData("d3b07384-d9a0-4b9b-abcd")] // too short - [InlineData("d3b07384-d9a0-4b9b-abcd-01234567890Z")] // invalid character Z - [InlineData("d3b07384-d9a0-4b9b-abcd-0123456789012")] // one char too long - [InlineData("g3b07384-d9a0-4b9b-abcd-012345678901")] // invalid hex char g - [InlineData("d3b07384 d9a0 4b9b abcd 012345678901")] // spaces instead of hyphens - public void InvalidGuidString_Fails(string value) - { - var (isValid, errorMessage) = Validate(value); - Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); - } + [Fact] + public void AllowEmpty_String_Defaults_False() + { + var (isValid, message) = Validate(Guid.Empty.ToString()); + Assert.False(isValid); + Assert.Contains("empty", message); + } + + [Fact] + public void Empty_String_Passes_If_AllowEmpty_True() + { + var (isValid, _) = Validate(Guid.Empty.ToString(), allowEmpty: true); + Assert.True(isValid); + } - [Fact] - public void NonStringValue_Fails() - { - var (isValid, errorMessage) = Validate(42); - Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); - } + [Fact] + public void Empty_Guid_Passes_If_AllowEmpty_True() + { + var (isValid, _) = Validate(Guid.Empty, allowEmpty: true); + Assert.True(isValid); + } + + [Theory] + [InlineData("d3b07384-d9a0-4b9b-abcd-012345678901")] // lowercase with hyphens + [InlineData("D3B07384-D9A0-4B9B-ABCD-012345678901")] // uppercase with hyphens + [InlineData("d3b07384d9a04b9babcd012345678901")] // no hyphens (N format) + [InlineData("{d3b07384-d9a0-4b9b-abcd-012345678901}")] // braces format + [InlineData("(d3b07384-d9a0-4b9b-abcd-012345678901)")] // parentheses format + [InlineData("ffffffff-ffff-ffff-ffff-ffffffffffff")] // all f's + public void ValidGuidString_Passes(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + + [Theory] + [InlineData("not-a-guid")] // arbitrary string + [InlineData("d3b07384-d9a0-4b9b-abcd")] // too short + [InlineData("d3b07384-d9a0-4b9b-abcd-01234567890Z")] // invalid character Z + [InlineData("d3b07384-d9a0-4b9b-abcd-0123456789012")] // one char too long + [InlineData("g3b07384-d9a0-4b9b-abcd-012345678901")] // invalid hex char g + [InlineData("d3b07384 d9a0 4b9b abcd 012345678901")] // spaces instead of hyphens + public void InvalidGuidString_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); + } + + [Fact] + public void NonStringValue_Fails() + { + var (isValid, errorMessage) = Validate(42); + Assert.False(isValid); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); } } diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index 1692bceb..bc581bf1 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -66,32 +66,6 @@ public class RelativePathAttributeTests } } - 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] diff --git a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs index 71e6ce8b..dbc82736 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs @@ -17,49 +17,119 @@ public class StringAttributeTests return (result == null, result?.ErrorMessage); } - // empty string passes all default checks — [Required] handles presence - [Fact] - public void EmptyString_Passes() + public class Null { - var (isValid, _) = Validate(string.Empty); - Assert.True(isValid); + [Fact] + public void Passes_When_AllowNull() + { + var (isValid, message) = Validate(null, a => a.AllowNull = true); + Assert.True(isValid); + } + + [Fact] + public void Fails_When_Not_AllowNull() + { + var (isValid, message) = Validate(null, a => a.AllowNull = false); + Assert.False(isValid); + Assert.Contains("must not be null", message); + } + + [Fact] + public void NonNull_Passes_Regardless() + { + var (isValid, message) = Validate("foo", a => a.AllowNull = true); + Assert.True(isValid); + + var (isValid2, message2) = Validate("foo", a => a.AllowNull = false); + Assert.True(isValid); + } } - public class DisallowedCharacters + public class Empty { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => StringAttributeTests.Validate(value, a => a.DisallowedCharacters = disallowed); + [Fact] + public void Empty_Passes_When_AllowEmpty_Is_True() + { + var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = true); + Assert.True(isValid); + } - public class Passes + [Fact] + public void Empty_Fails_When_AllowEmpty_Is_False() + { + var (isValid, message) = Validate(string.Empty, a => a.AllowEmpty = false); + Assert.False(isValid); + Assert.Contains("at least one character", message); + } + + [Fact] + public void NonEmpty_Passes_Regardless() + { + var (isValid, _) = Validate("hello", a => a.AllowEmpty = false); + Assert.True(isValid); + + var (isValid2, _) = Validate("hello", a => a.AllowEmpty = true); + Assert.True(isValid); + } + } + + public class WhiteSpace + { + [Fact] + public void WhiteSpace_Passes_When_AllowWhiteSpace_Is_True() + { + var (isValid, _) = Validate(" ", a => a.AllowWhiteSpace = true); + Assert.True(isValid); + } + + [Fact] + public void WhiteSpace_Fails_When_AllowWhiteSpace_Is_False() + { + var (isValid, message) = Validate(" ", a => a.AllowWhiteSpace = false); + Assert.False(isValid); + Assert.Contains("whitespace", message); + } + + [Fact] + public void NonWhiteSpace_Passes_Regardless() { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => DisallowedCharacters.Validate(value, disallowed); + var (isValid, _) = Validate("hello", a => a.AllowWhiteSpace = false); + Assert.True(isValid); + var (isValid2, _) = Validate("hello", a => a.AllowWhiteSpace = true); + Assert.True(isValid); + } + } + + public class DisallowedCharacters + { + public class Passes + { [Fact] public void EmptyString_Passes() { - var (isValid, _) = Validate(string.Empty, ['!']); + var (isValid, _) = Validate(string.Empty, a => a.DisallowedCharacters = ['!']); Assert.True(isValid); } [Fact] public void NoDisallowedCharsPresent_Passes() { - var (isValid, _) = Validate("hello", ['!', '@']); + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['!', '@']); Assert.True(isValid); } [Fact] public void EmptyDisallowedSet_Passes() { - var (isValid, _) = Validate("hello!@#", []); + var (isValid, _) = Validate("hello!@#", a => a.DisallowedCharacters = []); Assert.True(isValid); } [Fact] public void Unicode_AllowedChars_Pass() { - var (isValid, _) = Validate("пользователь/音楽", ['!', '@']); + var (isValid, _) = Validate("пользователь/音楽", a => a.DisallowedCharacters = ['!', '@']); Assert.True(isValid); } @@ -68,76 +138,73 @@ public class StringAttributeTests [Fact] public void LowerCaseDisallowed_DoesNotBlock_Different_UpperCaseLetter() { - var (isValid, _) = Validate("B", ['a']); + var (isValid, _) = Validate("B", a => a.DisallowedCharacters = ['a']); Assert.True(isValid); } } public class Fails { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => DisallowedCharacters.Validate(value, disallowed); - [Fact] public void SingleDisallowedChar_Fails() { - var (isValid, _) = Validate("hello!", ['!']); + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void DisallowedCharAtStart_Fails() { - var (isValid, _) = Validate("!hello", ['!']); + var (isValid, _) = Validate("!hello", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void DisallowedCharAtEnd_Fails() { - var (isValid, _) = Validate("hello!", ['!']); + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void DisallowedCharInMiddle_Fails() { - var (isValid, _) = Validate("hel!lo", ['!']); + var (isValid, _) = Validate("hel!lo", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void OneOfMultipleDisallowedCharsPresent_Fails() { - var (isValid, _) = Validate("hello!", ['!', '@', '#']); + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@', '#']); Assert.False(isValid); } [Fact] public void MultipleDisallowedCharsAllPresent_Fails() { - var (isValid, _) = Validate("h!e@l#lo", ['!', '@', '#']); + var (isValid, _) = Validate("h!e@l#lo", a => a.DisallowedCharacters = ['!', '@', '#']); Assert.False(isValid); } [Fact] public void DisallowedCharRepeated_Fails() { - var (isValid, _) = Validate("he!lo!", ['!']); + var (isValid, _) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void AllCharsDisallowed_Fails() { - var (isValid, _) = Validate("!@#", ['!', '@', '#']); + var (isValid, _) = Validate("!@#", a => a.DisallowedCharacters = ['!', '@', '#']); Assert.False(isValid); } [Fact] public void Unicode_DisallowedChar_Fails() { - var (isValid, _) = Validate("пользователь", ['е']); + var (isValid, _) = Validate("пользователь", a => a.DisallowedCharacters = ['е']); Assert.False(isValid); } @@ -145,41 +212,38 @@ public class StringAttributeTests [Fact] public void LowerCaseDisallowed_Blocks_UpperCase() { - var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o']); + var (isValid, _) = Validate("HELLO", a => a.DisallowedCharacters = ['h', 'e', 'l', 'o']); Assert.False(isValid); } [Fact] public void UpperCaseDisallowed_Blocks_LowerCase() { - var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O']); + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['H', 'E', 'L', 'O']); Assert.False(isValid); } [Fact] public void ExactMatch_Fails() { - var (isValid, _) = Validate("hello", ['h']); + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['h']); Assert.False(isValid); } } public class ErrorMessage_Contains { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => DisallowedCharacters.Validate(value, disallowed); - [Fact] public void TheDisallowedChar() { - var (_, errorMessage) = Validate("hello!", ['!']); + var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!']); Assert.Contains("'!'", errorMessage); } [Fact] public void AllPresentDisallowedChars() { - var (_, errorMessage) = Validate("h!@l", ['!', '@']); + var (_, errorMessage) = Validate("h!@l", a => a.DisallowedCharacters = ['!', '@']); Assert.Contains("'!'", errorMessage); Assert.Contains("'@'", errorMessage); } @@ -188,7 +252,7 @@ public class StringAttributeTests public void EachOccurrenceOfRepeatedChar() { // "he!lo!" has two '!' — both occurrences are listed - var (_, errorMessage) = Validate("he!lo!", ['!']); + var (_, errorMessage) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']); Assert.Equal(2, errorMessage.Split("'!'").Length - 1); } @@ -196,7 +260,7 @@ public class StringAttributeTests public void OnlyCharsActuallyPresent_NotAllDisallowedChars() { // '@' is disallowed but not in the value — must not appear in the message - var (_, errorMessage) = Validate("hello!", ['!', '@']); + var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@']); Assert.Contains("'!'", errorMessage); Assert.DoesNotContain("'@'", errorMessage); } @@ -206,159 +270,15 @@ public class StringAttributeTests { // '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']); + var (_, errorMessage) = Validate("A", a => a.DisallowedCharacters = ['a']); Assert.Contains("'A'", errorMessage); Assert.DoesNotContain("'a'", errorMessage); } } } - // ----------------------------------------------------------------------- - // AllowNull - // ----------------------------------------------------------------------- - public class AllowNull - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - - [Fact] - public void Null_Passes_When_AllowNull_Is_True() - { - var (isValid, _) = Validate(null); - Assert.True(isValid); - } - - [Fact] - public void Null_Fails_When_AllowNull_Is_False() - { - var (isValid, _) = Validate(null, a => a.AllowNull = false); - Assert.False(isValid); - } - - [Fact] - public void NonNull_Passes_When_AllowNull_Is_False() - { - var (isValid, _) = Validate("hello", a => a.AllowNull = false); - Assert.True(isValid); - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => AllowNull.Validate(value, configure); - - [Fact] - public void Null_Keyword() - { - var (_, message) = Validate(null, a => a.AllowNull = false); - Assert.Contains("null", message); - } - } - } - - // ----------------------------------------------------------------------- - // AllowEmpty - // ----------------------------------------------------------------------- - public class AllowEmpty - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - - [Fact] - public void Empty_Passes_When_AllowEmpty_Is_True() - { - var (isValid, _) = Validate(string.Empty); - Assert.True(isValid); - } - - [Fact] - public void Empty_Fails_When_AllowEmpty_Is_False() - { - var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = false); - Assert.False(isValid); - } - - [Fact] - public void NonEmpty_Passes_When_AllowEmpty_Is_False() - { - var (isValid, _) = Validate("hello", a => a.AllowEmpty = false); - Assert.True(isValid); - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => AllowEmpty.Validate(value, configure); - - [Fact] - public void Character_Keyword() - { - var (_, message) = Validate(string.Empty, a => a.AllowEmpty = false); - Assert.Contains("character", message); - } - } - } - - // ----------------------------------------------------------------------- - // AllowWhiteSpace - // ----------------------------------------------------------------------- - public class AllowWhiteSpace - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - - [Fact] - public void WhiteSpace_Passes_When_AllowWhiteSpace_Is_True() - { - var (isValid, _) = Validate(" "); - Assert.True(isValid); - } - - [Fact] - public void WhiteSpace_Fails_When_AllowWhiteSpace_Is_False() - { - var (isValid, _) = Validate(" ", a => a.AllowWhiteSpace = false); - Assert.False(isValid); - } - - [Fact] - public void NonWhiteSpace_Passes_When_AllowWhiteSpace_Is_False() - { - var (isValid, _) = Validate("hello", a => a.AllowWhiteSpace = false); - Assert.True(isValid); - } - - // IsNullOrWhiteSpace("") is true, so empty string also fails the whitespace check - // when AllowEmpty=true (default) and AllowWhiteSpace=false - [Fact] - public void EmptyString_Fails_When_AllowWhiteSpace_Is_False_And_AllowEmpty_Is_True() - { - var (isValid, _) = Validate(string.Empty, a => a.AllowWhiteSpace = false); - Assert.False(isValid); - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => AllowWhiteSpace.Validate(value, configure); - - [Fact] - public void Whitespace_Keyword() - { - var (_, message) = Validate(" ", a => a.AllowWhiteSpace = false); - Assert.Contains("whitespace", message); - } - } - } - - // ----------------------------------------------------------------------- - // Length (MinimumLength / MaximumLength) - // ----------------------------------------------------------------------- public class Length { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - [Fact] public void Within_Range_Passes() { @@ -396,9 +316,6 @@ public class StringAttributeTests public class ErrorMessage_Contains { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => Length.Validate(value, configure); - [Fact] public void MinimumLength_Value() { @@ -415,16 +332,8 @@ public class StringAttributeTests } } - // ----------------------------------------------------------------------- - // Pattern - // ----------------------------------------------------------------------- - // The Pattern check fails validation when the value *matches* the regex — - // Pattern acts as a "disallowed pattern" rather than a "required pattern". public class Pattern { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - [Fact] public void NullPattern_Passes() { @@ -449,9 +358,6 @@ public class StringAttributeTests public class ErrorMessage_Contains { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => Pattern.Validate(value, configure); - [Fact] public void RegularExpression_Keyword() { @@ -461,16 +367,8 @@ public class StringAttributeTests } } - // ----------------------------------------------------------------------- - // Check ordering - // ----------------------------------------------------------------------- - // Validation checks run in declaration order; when a value violates multiple - // conditions the error from the first check in code is the one returned. public class CheckOrdering { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - // AllowNull is checked before AllowEmpty: // null with both disabled returns the null error, not the empty error. [Fact] diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 2440291c..a9f30129 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -141,7 +141,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(ValidRequest() with { Username = new string('a', 501) }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The field Username must be a string with a minimum length of 1 and a maximum length of 500.", results[0].ErrorMessage); + Assert.Contains("between 1 and 500 characters", results[0].ErrorMessage); } } -- cgit v1.2.3 From 97104a235b705bc1b8151a4a0b244efbf875b866 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 15:25:59 -0500 Subject: add regex to block shares with path traversal segments --- src/slskd/Core/Options.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 3d9c8fb2..f952f014 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -845,6 +845,12 @@ namespace slskd directories?.Where(share => !IsAbsolutePath(share)).ToList() .ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported."))); + // contains /./ or /../ or \.\ or \..\ or ..\ or ../ or \.. or /.. + // which is resolved by some OS and will cause weird, unintended side effects + bool ContainsTraversalSegments(string share) => Regex.IsMatch(share.LocalizePath(), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$"); + directories?.Where(share => ContainsTraversalSegments(share)).ToList() + .ForEach(badPath => results.Add(new ValidationResult($"Share {badPath} contains an unsafe path traversal segment."))); + (string Raw, string Alias, string Path) Digest(string share) { var matches = Regex.Matches(share, @"^(!|-){0,1}\[(.*)\](.*)$"); -- cgit v1.2.3 From 4d37deb2cd7f46f1e3a0a683bf9f8507ef39ef54 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 15:30:56 -0500 Subject: remove path traversal test from absolute/relative path validation --- src/slskd/Common/Validation/AbsolutePathAttribute.cs | 6 ------ src/slskd/Common/Validation/RelativePathAttribute.cs | 6 ------ 2 files changed, 12 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 4c9f5e53..1999220f 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -49,12 +49,6 @@ namespace slskd.Validation { 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 '..')"); - } } return ValidationResult.Success; diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index edaef1be..edbb3483 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -49,12 +49,6 @@ namespace slskd.Validation { 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; -- cgit v1.2.3 From 486b62df5942c6dc06a52d4683d25be8b30e5824 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 15:33:07 -0500 Subject: add GuidAttribute --- src/slskd/Common/Validation/GuidAttribute.cs | 81 ++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 src/slskd/Common/Validation/GuidAttribute.cs (limited to 'src') diff --git a/src/slskd/Common/Validation/GuidAttribute.cs b/src/slskd/Common/Validation/GuidAttribute.cs new file mode 100644 index 00000000..7c04f1f9 --- /dev/null +++ b/src/slskd/Common/Validation/GuidAttribute.cs @@ -0,0 +1,81 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation +{ + using System; + + using System.ComponentModel.DataAnnotations; + + /// + /// Validates that the value is a valid Guid. + /// + public class GuidAttribute : ValidationAttribute + { + public GuidAttribute(bool allowEmpty = false) + { + AllowEmpty = allowEmpty; + } + + public bool AllowEmpty { get; } + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value is null) + { + return ValidationResult.Success; + } + + if (value is Guid guid) + { + if (!AllowEmpty && guid == Guid.Empty) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID"); + } + + return ValidationResult.Success; + } + + if (value is string str && Guid.TryParse(str, out guid)) + { + if (!AllowEmpty && guid == Guid.Empty) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID"); + } + + return ValidationResult.Success; + } + + return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUID"); + } + } +} \ No newline at end of file -- cgit v1.2.3 From 822d31235c3dbf440a733db72452d5d58eb554e8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 15:38:22 -0500 Subject: add NonTraversingPathAttribute --- .../Validation/NonTraversingPathAttribute.cs | 57 ++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/slskd/Common/Validation/NonTraversingPathAttribute.cs (limited to 'src') diff --git a/src/slskd/Common/Validation/NonTraversingPathAttribute.cs b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs new file mode 100644 index 00000000..1e2616bd --- /dev/null +++ b/src/slskd/Common/Validation/NonTraversingPathAttribute.cs @@ -0,0 +1,57 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + + /// + /// Validates that the specified path does not contain traversal segments '.' or '..'. + /// + public class NonTraversingPathAttribute : 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.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 -- cgit v1.2.3 From 29364a5a9cef23cee399e31c2d81c7239ad324da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 15:38:44 -0500 Subject: add general purpose StringAttribute that covers everything --- .../Validation/DisallowedCharactersAttribute.cs | 71 ---------------- src/slskd/Common/Validation/StringAttribute.cs | 99 ++++++++++++++++++++++ 2 files changed, 99 insertions(+), 71 deletions(-) delete mode 100644 src/slskd/Common/Validation/DisallowedCharactersAttribute.cs create mode 100644 src/slskd/Common/Validation/StringAttribute.cs (limited to 'src') diff --git a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs deleted file mode 100644 index 90ed3d81..00000000 --- a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs +++ /dev/null @@ -1,71 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Validation; - -using System.ComponentModel.DataAnnotations; -using System.Linq; - -/// -/// Validates that the value does not contain any of the characters. -/// -public class DisallowedCharactersAttribute : ValidationAttribute -{ - public DisallowedCharactersAttribute(params char[] disallowed) - { - Disallowed = disallowed; - } - - /// - /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to . - /// - 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/StringAttribute.cs b/src/slskd/Common/Validation/StringAttribute.cs new file mode 100644 index 00000000..807fef4c --- /dev/null +++ b/src/slskd/Common/Validation/StringAttribute.cs @@ -0,0 +1,99 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + using System.Linq; + using System.Text.RegularExpressions; + + /// + /// Validates that the value is not null or whitespace. + /// + public class StringAttribute : ValidationAttribute + { + public bool AllowNull { get; set; } = true; + public bool AllowEmpty { get; set; } = true; + public bool AllowWhiteSpace { get; set; } = true; + public char[] DisallowedCharacters { get; set; } = []; + public int MinimumLength { get; set; } = 0; + public int MaximumLength { get; set; } = int.MaxValue; + public Regex Pattern { get; set; } = null; + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + var val = (string)value; + + if (val is null) + { + if (!AllowNull) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not be null"); + } + else + { + return ValidationResult.Success; + } + } + + if (!AllowEmpty && val is "") + { + return new ValidationResult($"The {validationContext.DisplayName} field must contain at least one character"); + } + + // check this after empty to avoid overlap + if (!AllowWhiteSpace && val.All(c => char.IsWhiteSpace(c))) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain only whitespace"); + } + + if (val.Length < MinimumLength || val.Length > MaximumLength) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be between {MinimumLength} and {MaximumLength} characters"); + } + + var invalid = val.Where(c => DisallowedCharacters.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d))); + + if (invalid.Any()) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}"); + } + + if (Pattern is not null && Pattern.IsMatch(val)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must match the regular expression {Pattern.ToJson()}"); + } + + return ValidationResult.Success; + } + } +} \ No newline at end of file -- cgit v1.2.3 From 08f4afda39774ab4872a6699b50ca80589938caa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 15:39:26 -0500 Subject: mark directories as non traversing --- src/slskd/Core/Options.cs | 3 +++ 1 file changed, 3 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 51b3cab1..a50e3f70 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -768,6 +768,7 @@ namespace slskd [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] [AbsolutePath] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory; @@ -779,6 +780,7 @@ namespace slskd [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] [AbsolutePath] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; @@ -2015,6 +2017,7 @@ namespace slskd [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] [AbsolutePath] + [NonTraversingPath] [RequiresRestart] public string Socket { get; init; } -- cgit v1.2.3 From f4500909ce50e54bba4e3dc83c6c88aef31fb0b8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 15:39:59 -0500 Subject: remove prohibiton on slashes in instance names --- src/slskd/Core/Options.cs | 2 -- 1 file changed, 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index a50e3f70..3d9c8fb2 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -198,7 +198,6 @@ 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"; @@ -655,7 +654,6 @@ namespace slskd [Description("the name for this agent")] [StringLength(255, MinimumLength = 1)] [NotNullOrWhiteSpace] - [DisallowedCharacters('/', '\\')] [Secret] public string InstanceName { get; init; } -- cgit v1.2.3 From 4e609714dd84a5774f9adae54b838c0c5a8d3d2d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 15:40:15 -0500 Subject: add path traversal prevention to share config --- src/slskd/Core/Options.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 3d9c8fb2..f952f014 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -845,6 +845,12 @@ namespace slskd directories?.Where(share => !IsAbsolutePath(share)).ToList() .ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported."))); + // contains /./ or /../ or \.\ or \..\ or ..\ or ../ or \.. or /.. + // which is resolved by some OS and will cause weird, unintended side effects + bool ContainsTraversalSegments(string share) => Regex.IsMatch(share.LocalizePath(), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$"); + directories?.Where(share => ContainsTraversalSegments(share)).ToList() + .ForEach(badPath => results.Add(new ValidationResult($"Share {badPath} contains an unsafe path traversal segment."))); + (string Raw, string Alias, string Path) Digest(string share) { var matches = Regex.Matches(share, @"^(!|-){0,1}\[(.*)\](.*)$"); -- cgit v1.2.3 From 6f0d9682fde688cf1fd8d3f330aca71616f28a9f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 17:02:27 -0500 Subject: capture alias up to the first closing square bracket --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index f952f014..83e534a1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -853,7 +853,7 @@ namespace slskd (string Raw, string Alias, string Path) Digest(string share) { - var matches = Regex.Matches(share, @"^(!|-){0,1}\[(.*)\](.*)$"); + var matches = Regex.Matches(share, @"^(!|-){0,1}\[([^\]]*)\](.*)$"); if (matches.Any()) { -- cgit v1.2.3 From 96ea096105f4fe0371a58cdc9ecf5c6b82a937e3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 18 May 2026 19:14:25 -0500 Subject: fix path detection (again) --- src/slskd/Common/FileSafety.cs | 48 +- .../Common/FileSafety/CombineSafelyTests.cs | 285 +++++++++++ .../FileSafety/ContainsTraversalSegmentsTests.cs | 114 +++++ .../Common/FileSafety/IsPathTests.cs | 213 ++++++++ tests/slskd.Tests.Unit/Common/FileSafetyTests.cs | 545 --------------------- .../API/DTO/QueueDownloadBatchRequestTests.cs | 29 +- 6 files changed, 665 insertions(+), 569 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs delete mode 100644 tests/slskd.Tests.Unit/Common/FileSafetyTests.cs (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index f94b9c7b..1e25ccd0 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -35,6 +35,7 @@ namespace slskd; using System; using System.IO; using System.Linq; +using System.Runtime.InteropServices; /// /// Utility functions to help safely work with paths from untrusted sources. @@ -102,36 +103,46 @@ public static class FileSafety public static bool ContainsTraversalSegments(string path) => path?.Split('\\', '/')?.Any(s => s is "." or "..") ?? false; /// - /// Returns a value indicating whether the specified is absolute (rooted), using - /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// Returns a value indicating whether the specified is absolute (rooted) on the current + /// operating system. /// /// /// 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. + /// implementing the nuclear option and doing it ourselves. /// /// The path to check. + /// An optional operating system override, for testing. /// True if the path is absolute, false otherwise. - public static bool IsPathAbsolute(string path) + public static bool IsPathAbsolute(string path, OSPlatform? os = null) { 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 '\\') + if (os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows()) { - return true; + // Windows drive-letter path: X:\ or X:/ + // X:foo is relative on windows + if (path.Length >= 3 + && char.IsAsciiLetter(path[0]) + && path[1] == ':' + && (path[2] == '\\' || path[2] == '/')) + { + return true; + } + + // UNC path \\server\share + if (path.StartsWith("\\\\")) + { + return true; + } + + return false; } - // 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] == ':') + // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with / + if (path.StartsWith('/')) { return true; } @@ -140,10 +151,11 @@ public static class FileSafety } /// - /// Returns a value indicating whether the specified , using - /// platform-independent rules that recognize both Unix and Windows absolute path formats. + /// Returns a value indicating whether the specified is relative on the current + /// operating system. /// /// The path to check. + /// An optional operating system override, for testing. /// True if the path is relative, false otherwise. - public static bool IsPathRelative(string path) => !IsPathAbsolute(path); + public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs new file mode 100644 index 00000000..4cac90c5 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -0,0 +1,285 @@ +using System; +using System.IO; +using Xunit; + +namespace slskd.Tests.Unit.Files; + +internal static class CombineSafelyTestHelpers +{ + // 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. + public static readonly string Base = OperatingSystem.IsWindows() ? "C:\\base" : "/base"; + + public 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 CombineSafely_Returns +{ + [Fact] + public void NoSegments_ReturnsBasePath() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base); + Assert.Equal(CombineSafelyTestHelpers.Base, result); + } + + [Fact] + public void EmptySegment_ReturnsBasePath() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, string.Empty); + Assert.Equal(CombineSafelyTestHelpers.Base, result); + } + + [Fact] + public void SingleSegment_ReturnsBaseAndSegment() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "subdir"); + Assert.Equal(Path.Combine(CombineSafelyTestHelpers.Base, "subdir"), result); + } + + [Fact] + public void MultipleSegments_CombinesAll() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub", "dir", "file.flac"); + Assert.Equal(Path.Combine(CombineSafelyTestHelpers.Base, "sub", "dir", "file.flac"), result); + } + + [Fact] + public void SegmentWithForwardSlash_CombinesCorrectly() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub/dir"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithBackslash_CombinesCorrectly() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub\\dir"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithDoubleSlash_CollapsedAndContained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub//dir"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithDoubleBackslash_CollapsedAndContained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub\\\\dir"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithSpaces_Contained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "My Artist", "My Album"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void SegmentWithUnicode_Contained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "Ünïcödé", "пользователь", "音楽"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void DotfileSegment_Contained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, ".hidden"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void ThreeDotsSegment_Contained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "...dir"); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } + + [Fact] + public void DotDotPrefixedName_Contained() + { + var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "..hidden"); + CombineSafelyTestHelpers.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(CombineSafelyTestHelpers.Base, segment); + CombineSafelyTestHelpers.AssertContainedInBase(result); + } +} + +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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, segment)); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentIsRooted() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "valid", "/escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentIsRooted_Windows() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "valid", "C:\\escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsRooted() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub", "dir", "/escape")); + Assert.Contains("Rooted", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsRooted_Windows() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(CombineSafelyTestHelpers.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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, segment)); + Assert.Contains("traversal", ex.Message); + } + + [Fact] + public void Throws_WhenLaterSegmentContainsTraversal() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "valid", "../escape")); + Assert.Contains("traversal", ex.Message); + } + + [Fact] + public void Throws_WhenLastSegmentIsTraversal() + { + var ex = Assert.Throws(() => + FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub", "dir", "..")); + Assert.Contains("traversal", ex.Message); + } +} + +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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, null)); + } + + [Fact] + public void NullSegment_Throws() + { + // A null element inside the params array reaches Path.IsPathRooted(null), + // which throws ArgumentNullException. + Assert.Throws(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, (string)null)); + } + + [Fact] + public void NullBasePath_Throws() + { + Assert.ThrowsAny(() => 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); + } +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs new file mode 100644 index 00000000..9667789e --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs @@ -0,0 +1,114 @@ +using Xunit; + +namespace slskd.Tests.Unit.Files; + +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)); + } +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs new file mode 100644 index 00000000..723879a0 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs @@ -0,0 +1,213 @@ +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Files; + +public class IsPath_Windows +{ + public class Absolute + { + [Theory] + // drive-letter paths (X:\ or X:/) + [InlineData("C:\\")] + [InlineData("C:/")] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\Music\\Artist\\Album")] + [InlineData("D:\\path")] + [InlineData("Z:\\downloads")] + [InlineData("C:\\Users\\Ünïcödé\\Music")] + [InlineData("C:\\Users\\пользователь\\Музыка")] + [InlineData("C:\\Users\\用户\\音乐")] + // UNC paths (\\ prefix) + [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 IsAbsolute_NotRelative(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.Windows)); + Assert.False(FileSafety.IsPathRelative(path, OSPlatform.Windows)); + } + } + + public class Relative + { + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("Artist/Album/Song")] + [InlineData("music.flac")] + [InlineData("My Music")] + [InlineData(".hidden")] + [InlineData("..hidden")] + [InlineData("...dir")] + [InlineData("../escape")] + [InlineData("./dir")] + [InlineData("..")] + [InlineData(".")] + [InlineData("Ünïcödé")] + [InlineData("пользователь/Музыка")] + [InlineData("/Music")] // root-relative — no drive letter, not absolute on Windows + [InlineData("\\Music")] // root-relative — no drive letter, not absolute on Windows + [InlineData("/home/user")] // Unix-style — not recognised as absolute on Windows + [InlineData("//server/share")] // Unix UNC — not recognised as absolute on Windows + [InlineData("C:")] // bare drive letter — length < 3, not absolute + [InlineData("C:Music")] // drive-relative — no separator after colon, not absolute + [InlineData("D:path")] // drive-relative — no separator after colon, not absolute + public void IsRelative_NotAbsolute(string path) + { + Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.Windows)); + Assert.True(FileSafety.IsPathRelative(path, OSPlatform.Windows)); + } + } +} + +public class IsPath_Linux +{ + public class Absolute + { + [Theory] + [InlineData("/")] + [InlineData("/home")] + [InlineData("/home/user/Music")] + [InlineData("/home/user/My Music")] + [InlineData("/etc/hosts")] + [InlineData("/tmp")] + [InlineData("/home/Ünïcödé")] + [InlineData("/home/пользователь/Музыка")] + [InlineData("/home/用户/音乐")] + [InlineData("/home/ユーザー/音楽")] + [InlineData("/home/사용자/음악")] + [InlineData("//server/share")] + [InlineData("//server/share/folder")] + [InlineData("//192.168.1.1/share")] + public void IsAbsolute_NotRelative(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.Linux)); + Assert.False(FileSafety.IsPathRelative(path, OSPlatform.Linux)); + } + } + + public class Relative + { + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("music.flac")] + [InlineData(".hidden")] + [InlineData("../escape")] + [InlineData("./dir")] + [InlineData("..")] + [InlineData(".")] + [InlineData("Ünïcödé")] + [InlineData("пользователь/Музыка")] + [InlineData("C:\\Music")] // Windows drive-letter — not absolute on Linux + [InlineData("C:/Music")] // Windows drive-letter — not absolute on Linux + [InlineData("\\\\server\\share")] // Windows UNC — not absolute on Linux + [InlineData("\\Music")] // Windows root-relative — not absolute on Linux + public void IsRelative_NotAbsolute(string path) + { + Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.Linux)); + Assert.True(FileSafety.IsPathRelative(path, OSPlatform.Linux)); + } + } +} + +public class IsPath_MacOS +{ + public class Absolute + { + [Theory] + [InlineData("/")] + [InlineData("/Users")] + [InlineData("/Users/user/Music")] + [InlineData("/Volumes/ExternalDrive")] + [InlineData("/home/Ünïcödé")] + [InlineData("/home/пользователь/Музыка")] + [InlineData("//server/share")] + [InlineData("//server/share/folder")] + [InlineData("//192.168.1.1/share")] + public void IsAbsolute_NotRelative(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.OSX)); + Assert.False(FileSafety.IsPathRelative(path, OSPlatform.OSX)); + } + } + + public class Relative + { + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("music.flac")] + [InlineData(".hidden")] + [InlineData("../escape")] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("\\\\server\\share")] + [InlineData("\\Music")] + public void IsRelative_NotAbsolute(string path) + { + Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.OSX)); + Assert.True(FileSafety.IsPathRelative(path, OSPlatform.OSX)); + } + } +} + +public class IsPath_FreeBSD +{ + public class Absolute + { + [Theory] + [InlineData("/")] + [InlineData("/usr")] + [InlineData("/usr/local/music")] + [InlineData("/home/user/Music")] + [InlineData("/home/Ünïcödé")] + [InlineData("/home/пользователь/Музыка")] + [InlineData("//server/share")] + [InlineData("//server/share/folder")] + [InlineData("//192.168.1.1/share")] + public void IsAbsolute_NotRelative(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.FreeBSD)); + Assert.False(FileSafety.IsPathRelative(path, OSPlatform.FreeBSD)); + } + } + + public class Relative + { + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("music.flac")] + [InlineData(".hidden")] + [InlineData("../escape")] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("\\\\server\\share")] + [InlineData("\\Music")] + public void IsRelative_NotAbsolute(string path) + { + Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.FreeBSD)); + Assert.True(FileSafety.IsPathRelative(path, OSPlatform.FreeBSD)); + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs deleted file mode 100644 index a37e9e74..00000000 --- a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs +++ /dev/null @@ -1,545 +0,0 @@ -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(() => FileSafety.CombineSafely(Base, segment)); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentIsRooted() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(Base, "valid", "/escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentIsRooted_Windows() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(Base, "valid", "C:\\escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsRooted() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(Base, "sub", "dir", "/escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsRooted_Windows() - { - var ex = Assert.Throws(() => - 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(() => FileSafety.CombineSafely(Base, segment)); - Assert.Contains("traversal", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentContainsTraversal() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(Base, "valid", "../escape")); - Assert.Contains("traversal", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsTraversal() - { - var ex = Assert.Throws(() => - 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(() => 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(() => 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(() => FileSafety.CombineSafely(Base, (string)null)); - } - - [Fact] - public void NullBasePath_Throws() - { - Assert.ThrowsAny(() => 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); - } - } -} diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index a9f30129..137fd73e 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using slskd.Transfers.API; @@ -276,15 +277,31 @@ public class QueueDownloadBatchRequestTests [Theory] [InlineData("C:\\Music")] // Windows absolute [InlineData("C:/Music")] // Windows absolute, forward slash + [InlineData("\\\\server\\share")] // UNC + public void AbsolutePath_Fails_Windows(string value) + { + if (OperatingSystem.IsWindows()) + { + var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + } + } + + [Theory] [InlineData("/music")] // Unix absolute [InlineData("/home/user/Music")] // Unix absolute, deep - [InlineData("\\\\server\\share")] // UNC - public void AbsolutePath_Fails(string value) + [InlineData("//server/share")] // UNC + public void AbsolutePath_Fails_Non_Windows(string value) { - var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); - Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + if (!OperatingSystem.IsWindows()) + { + var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.False(isValid); + Assert.Single(results); + Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + } } [Theory] -- cgit v1.2.3 From 33c37b535d4ce68313b77d3a466933c8b047e825 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 19 May 2026 18:44:38 -0500 Subject: fix bug handling incomplete filenames --- src/slskd/Transfers/Downloads/DownloadService.cs | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 89b8a6a7..83e91ced 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1049,13 +1049,10 @@ namespace slskd.Transfers.Downloads ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() : null; - // if the transfer has an associated batch id, store the incomplete file in a directory of the same name - // this is to ensure maximal safety when resuming failed downloads (otherwise we risk resuming an unrelated file) - // if there is no batch id, sanitize the username and use that + // store incomplete files under a username subdirectory to prevent collisions between users + // and to make it safe to resume partial downloads without risking picking up an unrelated file var incompleteFilename = transfer.Filename.ToLocalFilename( - baseDirectory: FileSafety.CombineSafely( - OptionsMonitor.CurrentValue.Directories.Incomplete, - transfer.BatchId.HasValue ? transfer.BatchId.ToString() : transfer.Username.ReplaceInvalidFileNameCharacters())); + baseDirectory: FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Incomplete, transfer.Username.ReplaceInvalidFileNameCharacters())); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; @@ -1163,7 +1160,7 @@ namespace slskd.Transfers.Downloads Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory); var finalFilename = Files.MoveFile( - sourceFilename: transfer.Filename.ToLocalFilename(baseDirectory: OptionsMonitor.CurrentValue.Directories.Incomplete), + sourceFilename: incompleteFilename, destinationDirectory: destinationDirectory, unixFileMode: unixFileMode, overwrite: false, -- cgit v1.2.3 From 8b5505ba5e1c102cd639666df96e139a5858ed55 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 21 May 2026 23:10:22 -0500 Subject: add overload allowing OS selection --- src/slskd/Common/Validation/AbsolutePathAttribute.cs | 14 +++++++++++++- src/slskd/Common/Validation/RelativePathAttribute.cs | 13 ++++++++++++- 2 files changed, 25 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 1999220f..eb1c9069 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -33,19 +33,31 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; + using System.Runtime.InteropServices; /// /// Validates that the specified path is absolute. /// public class AbsolutePathAttribute : ValidationAttribute { + public AbsolutePathAttribute() + { + } + + public AbsolutePathAttribute(OSPlatform? os = null) + { + OS = os; + } + + public OSPlatform? OS { get; } + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && value is string str && !string.IsNullOrEmpty(str)) { var path = value.ToString(); - if (!FileSafety.IsPathAbsolute(path)) + if (!FileSafety.IsPathAbsolute(path, os: OS)) { return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 64e418b1..f465ba98 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -33,19 +33,30 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; + using System.Runtime.InteropServices; /// /// Validates that the specified path is relative. /// public class RelativePathAttribute : ValidationAttribute { + public RelativePathAttribute() + { + } + + public RelativePathAttribute(OSPlatform? os = null) + { + OS = os; + } + + public OSPlatform? OS { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && value is string str && !string.IsNullOrEmpty(str)) { var path = value.ToString(); - if (!FileSafety.IsPathRelative(path)) + if (!FileSafety.IsPathRelative(path, os: OS)) { return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } -- cgit v1.2.3 From 9376c6a3b47ecffc1f1acc880c931d784db3c18b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 22 May 2026 11:56:59 -0500 Subject: adjust FileSafety tests --- src/slskd/Common/FileSafety.cs | 23 +- .../Common/FileSafety/CombineSafelyTests.cs | 420 +++++++-------------- .../FileSafety/ContainsTraversalSegmentsTests.cs | 214 +++++------ .../Common/FileSafety/IsPathTests.cs | 316 ++++++---------- .../Validation/AbsolutePathAttributeTests.cs | 154 +++----- .../Validation/RelativePathAttributeTests.cs | 9 +- 6 files changed, 436 insertions(+), 700 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 1e25ccd0..c024aa86 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -51,7 +51,19 @@ public static class FileSafety /// The combined path. /// Thrown if the root, list of segments, or one or more segments is null. /// Thrown if any of the specified segments is rooted, or if any contain path traversal characters. - public static string CombineSafely(string root, params string[] segments) + public static string CombineSafely(string root, params string[] segments) => CombineSafely(root, os: null, segments: segments); + + /// + /// An alternative to that disallows rooted segments in the second or + /// subsequent position, and disallows segments containing path traversal characters "." and "..". + /// + /// The root directory. + /// An optional operating system override, for testing. + /// The segments to append. + /// The combined path. + /// Thrown if the root, list of segments, or one or more segments is null. + /// Thrown if any of the specified segments is rooted, or if any contain path traversal characters. + public static string CombineSafely(string root, OSPlatform? os, params string[] segments) { // ensure no inputs are null. matches the behavior of Path.Combine() if (string.IsNullOrWhiteSpace(root)) @@ -59,6 +71,11 @@ public static class FileSafety throw new ArgumentNullException(nameof(root), $"Specified root directory is null or consists only of whitespace"); } + if (ContainsTraversalSegments(root)) + { + throw new ArgumentException("Specified root directory contains path traversal segments", nameof(root)); + } + if (segments is null || segments.Any(s => s is null)) { throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); @@ -69,9 +86,9 @@ public static class FileSafety // if any segment is rooted (leading slash), Path.Combine drops everyting up to that segment // and it becomes the new root. example: Path.Combine("/home/users/foo", "/etc") results in "/etc" // not what we want! - if (IsPathAbsolute(segment)) + if (IsPathAbsolute(segment, os)) { - throw new ArgumentException($"Rooted paths are not permitted in segments: '{segment}'"); + throw new ArgumentException($"Absolute paths are not permitted in segments: '{segment}'"); } var parts = segment.Split(Path.DirectorySeparatorChar, '\\', '/'); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index 4cac90c5..dce61235 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -1,285 +1,147 @@ using System; using System.IO; +using System.Runtime.InteropServices; using Xunit; -namespace slskd.Tests.Unit.Files; +namespace slskd.Tests.Unit.Common; -internal static class CombineSafelyTestHelpers +public partial 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. - public static readonly string Base = OperatingSystem.IsWindows() ? "C:\\base" : "/base"; - - public 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 CombineSafely_Returns -{ - [Fact] - public void NoSegments_ReturnsBasePath() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base); - Assert.Equal(CombineSafelyTestHelpers.Base, result); - } - - [Fact] - public void EmptySegment_ReturnsBasePath() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, string.Empty); - Assert.Equal(CombineSafelyTestHelpers.Base, result); - } - - [Fact] - public void SingleSegment_ReturnsBaseAndSegment() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "subdir"); - Assert.Equal(Path.Combine(CombineSafelyTestHelpers.Base, "subdir"), result); - } - - [Fact] - public void MultipleSegments_CombinesAll() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub", "dir", "file.flac"); - Assert.Equal(Path.Combine(CombineSafelyTestHelpers.Base, "sub", "dir", "file.flac"), result); - } - - [Fact] - public void SegmentWithForwardSlash_CombinesCorrectly() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub/dir"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithBackslash_CombinesCorrectly() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub\\dir"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithDoubleSlash_CollapsedAndContained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub//dir"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithDoubleBackslash_CollapsedAndContained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub\\\\dir"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithSpaces_Contained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "My Artist", "My Album"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void SegmentWithUnicode_Contained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "Ünïcödé", "пользователь", "音楽"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void DotfileSegment_Contained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, ".hidden"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void ThreeDotsSegment_Contained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "...dir"); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } - - [Fact] - public void DotDotPrefixedName_Contained() - { - var result = FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "..hidden"); - CombineSafelyTestHelpers.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(CombineSafelyTestHelpers.Base, segment); - CombineSafelyTestHelpers.AssertContainedInBase(result); - } -} - -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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, segment)); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentIsRooted() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "valid", "/escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentIsRooted_Windows() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "valid", "C:\\escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsRooted() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub", "dir", "/escape")); - Assert.Contains("Rooted", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsRooted_Windows() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(CombineSafelyTestHelpers.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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, segment)); - Assert.Contains("traversal", ex.Message); - } - - [Fact] - public void Throws_WhenLaterSegmentContainsTraversal() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "valid", "../escape")); - Assert.Contains("traversal", ex.Message); - } - - [Fact] - public void Throws_WhenLastSegmentIsTraversal() - { - var ex = Assert.Throws(() => - FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, "sub", "dir", "..")); - Assert.Contains("traversal", ex.Message); - } -} - -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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, null)); - } - - [Fact] - public void NullSegment_Throws() - { - // A null element inside the params array reaches Path.IsPathRooted(null), - // which throws ArgumentNullException. - Assert.Throws(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.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(() => FileSafety.CombineSafely(CombineSafelyTestHelpers.Base, (string)null)); - } - - [Fact] - public void NullBasePath_Throws() - { - Assert.ThrowsAny(() => 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); - } -} + public class CombineSafelyTests + { + public static string Base = OperatingSystem.IsWindows() ? "C:\\base" : "/base"; + public static string ExpectedStartsWith = Base + Path.DirectorySeparatorChar; + + [Theory] + [InlineData(null)] + [InlineData(" ")] + public void Throws_ArgumentException_Given_NullOrWhiteSpaceRoot(string root) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(root)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Theory] + [InlineData("foo/../bar")] + [InlineData("foo\\..\\bar")] + public void Throws_ArgumentException_Given_TraversingRoot(string root) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(root)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Fact] + public void Returns_Root_Given_No_Segments() + { + var result = FileSafety.CombineSafely(Base); + + Assert.StartsWith(ExpectedStartsWith.TrimEnd(Path.DirectorySeparatorChar), result); + } + + [Fact] + public void Drops_Empty_Segments() + { + var result = FileSafety.CombineSafely(Base, string.Empty, "foo", string.Empty, "bar"); + + Assert.StartsWith(ExpectedStartsWith, result); + Assert.EndsWith(Path.Combine("foo", "bar"), 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); + Assert.StartsWith(ExpectedStartsWith, result); + } + + [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 Combines_Safe_Segments(string segment) + { + var result = FileSafety.CombineSafely(Base, segment); + + Assert.Equal(Path.Combine(Base, segment), result); + Assert.StartsWith(ExpectedStartsWith, result); + } + + [Theory] + [InlineData("/Music")] + [InlineData("//server/share")] + public void Throws_ArgumentException_Given_AbsolutePath_On_Unix(string segment) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Linux, segment)); + + Assert.NotNull(ex); + Assert.Contains("Absolute", ex.Message); + } + + [Theory] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("\\\\server\\share")] + public void Throws_ArgumentException_Given_AbsolutePath_On_Windows(string segment) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Windows, segment)); + + Assert.NotNull(ex); + Assert.Contains("Absolute", ex.Message); + } + + [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")] + public void Throws_ArgumentException_Given_Traversing_Segment(string segment) + { + var ex = Assert.Throws(() => FileSafety.CombineSafely(Base, segment)); + + Assert.NotNull(ex); + Assert.Contains("traversal", ex.Message); + } + } +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs index 9667789e..205c87c2 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs @@ -1,114 +1,114 @@ using Xunit; -namespace slskd.Tests.Unit.Files; +namespace slskd.Tests.Unit.Common; -public class ContainsTraversalSegments_ReturnsTrue +public partial class FileSafetyTests { - [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) + public class ContainsTraversalSegmentTests { - Assert.True(FileSafety.ContainsTraversalSegments(path)); - } -} + [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)); + [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)); + } } -} +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs index 723879a0..42eab9b8 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs @@ -1,213 +1,131 @@ using System.Runtime.InteropServices; using Xunit; -namespace slskd.Tests.Unit.Files; +namespace slskd.Tests.Unit.Common; -public class IsPath_Windows +public partial class FileSafetyTests { - public class Absolute + public class IsPathTests { - [Theory] - // drive-letter paths (X:\ or X:/) - [InlineData("C:\\")] - [InlineData("C:/")] - [InlineData("C:\\Music")] - [InlineData("C:/Music")] - [InlineData("C:\\Music\\Artist\\Album")] - [InlineData("D:\\path")] - [InlineData("Z:\\downloads")] - [InlineData("C:\\Users\\Ünïcödé\\Music")] - [InlineData("C:\\Users\\пользователь\\Музыка")] - [InlineData("C:\\Users\\用户\\音乐")] - // UNC paths (\\ prefix) - [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 IsAbsolute_NotRelative(string path) + public class Windows { - Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.Windows)); - Assert.False(FileSafety.IsPathRelative(path, OSPlatform.Windows)); - } - } + public class Absolute + { + [Theory] + // drive-letter paths (X:\ or X:/) + [InlineData("C:\\")] + [InlineData("C:/")] + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\Music\\Artist\\Album")] + [InlineData("D:\\path")] + [InlineData("Z:\\downloads")] + [InlineData("C:\\Users\\Ünïcödé\\Music")] + [InlineData("C:\\Users\\пользователь\\Музыка")] + [InlineData("C:\\Users\\用户\\音乐")] + // UNC paths (\\ prefix) + [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 IsAbsolute_NotRelative(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.Windows)); + Assert.False(FileSafety.IsPathRelative(path, OSPlatform.Windows)); + } + } - public class Relative - { - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("subdir")] - [InlineData("sub/dir")] - [InlineData("sub\\dir")] - [InlineData("Artist\\Album")] - [InlineData("Artist/Album/Song")] - [InlineData("music.flac")] - [InlineData("My Music")] - [InlineData(".hidden")] - [InlineData("..hidden")] - [InlineData("...dir")] - [InlineData("../escape")] - [InlineData("./dir")] - [InlineData("..")] - [InlineData(".")] - [InlineData("Ünïcödé")] - [InlineData("пользователь/Музыка")] - [InlineData("/Music")] // root-relative — no drive letter, not absolute on Windows - [InlineData("\\Music")] // root-relative — no drive letter, not absolute on Windows - [InlineData("/home/user")] // Unix-style — not recognised as absolute on Windows - [InlineData("//server/share")] // Unix UNC — not recognised as absolute on Windows - [InlineData("C:")] // bare drive letter — length < 3, not absolute - [InlineData("C:Music")] // drive-relative — no separator after colon, not absolute - [InlineData("D:path")] // drive-relative — no separator after colon, not absolute - public void IsRelative_NotAbsolute(string path) - { - Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.Windows)); - Assert.True(FileSafety.IsPathRelative(path, OSPlatform.Windows)); + public class Relative + { + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + [InlineData("Artist/Album/Song")] + [InlineData("music.flac")] + [InlineData("My Music")] + [InlineData(".hidden")] + [InlineData("..hidden")] + [InlineData("...dir")] + [InlineData("../escape")] + [InlineData("./dir")] + [InlineData("..")] + [InlineData(".")] + [InlineData("Ünïcödé")] + [InlineData("пользователь/Музыка")] + [InlineData("/Music")] // root-relative — no drive letter, not absolute on Windows + [InlineData("\\Music")] // root-relative — no drive letter, not absolute on Windows + [InlineData("/home/user")] // Unix-style — not recognised as absolute on Windows + [InlineData("//server/share")] // Unix UNC — not recognised as absolute on Windows + [InlineData("C:")] // bare drive letter — length < 3, not absolute + [InlineData("C:Music")] // drive-relative — no separator after colon, not absolute + [InlineData("D:path")] // drive-relative — no separator after colon, not absolute + public void IsRelative_NotAbsolute(string path) + { + Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.Windows)); + Assert.True(FileSafety.IsPathRelative(path, OSPlatform.Windows)); + } + } } - } -} -public class IsPath_Linux -{ - public class Absolute - { - [Theory] - [InlineData("/")] - [InlineData("/home")] - [InlineData("/home/user/Music")] - [InlineData("/home/user/My Music")] - [InlineData("/etc/hosts")] - [InlineData("/tmp")] - [InlineData("/home/Ünïcödé")] - [InlineData("/home/пользователь/Музыка")] - [InlineData("/home/用户/音乐")] - [InlineData("/home/ユーザー/音楽")] - [InlineData("/home/사용자/음악")] - [InlineData("//server/share")] - [InlineData("//server/share/folder")] - [InlineData("//192.168.1.1/share")] - public void IsAbsolute_NotRelative(string path) + public class Linux { - Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.Linux)); - Assert.False(FileSafety.IsPathRelative(path, OSPlatform.Linux)); - } - } + public class Absolute + { + [Theory] + [InlineData("/")] + [InlineData("/home")] + [InlineData("/home/user/Music")] + [InlineData("/home/user/My Music")] + [InlineData("/etc/hosts")] + [InlineData("/tmp")] + [InlineData("/home/Ünïcödé")] + [InlineData("/home/пользователь/Музыка")] + [InlineData("/home/用户/音乐")] + [InlineData("/home/ユーザー/音楽")] + [InlineData("/home/사용자/음악")] + [InlineData("//server/share")] + [InlineData("//server/share/folder")] + [InlineData("//192.168.1.1/share")] + public void IsAbsolute_NotRelative(string path) + { + Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.Linux)); + Assert.False(FileSafety.IsPathRelative(path, OSPlatform.Linux)); + } + } - public class Relative - { - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("subdir")] - [InlineData("sub/dir")] - [InlineData("sub\\dir")] - [InlineData("music.flac")] - [InlineData(".hidden")] - [InlineData("../escape")] - [InlineData("./dir")] - [InlineData("..")] - [InlineData(".")] - [InlineData("Ünïcödé")] - [InlineData("пользователь/Музыка")] - [InlineData("C:\\Music")] // Windows drive-letter — not absolute on Linux - [InlineData("C:/Music")] // Windows drive-letter — not absolute on Linux - [InlineData("\\\\server\\share")] // Windows UNC — not absolute on Linux - [InlineData("\\Music")] // Windows root-relative — not absolute on Linux - public void IsRelative_NotAbsolute(string path) - { - Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.Linux)); - Assert.True(FileSafety.IsPathRelative(path, OSPlatform.Linux)); - } - } -} - -public class IsPath_MacOS -{ - public class Absolute - { - [Theory] - [InlineData("/")] - [InlineData("/Users")] - [InlineData("/Users/user/Music")] - [InlineData("/Volumes/ExternalDrive")] - [InlineData("/home/Ünïcödé")] - [InlineData("/home/пользователь/Музыка")] - [InlineData("//server/share")] - [InlineData("//server/share/folder")] - [InlineData("//192.168.1.1/share")] - public void IsAbsolute_NotRelative(string path) - { - Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.OSX)); - Assert.False(FileSafety.IsPathRelative(path, OSPlatform.OSX)); - } - } - - public class Relative - { - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("subdir")] - [InlineData("sub/dir")] - [InlineData("sub\\dir")] - [InlineData("music.flac")] - [InlineData(".hidden")] - [InlineData("../escape")] - [InlineData("C:\\Music")] - [InlineData("C:/Music")] - [InlineData("\\\\server\\share")] - [InlineData("\\Music")] - public void IsRelative_NotAbsolute(string path) - { - Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.OSX)); - Assert.True(FileSafety.IsPathRelative(path, OSPlatform.OSX)); - } - } -} - -public class IsPath_FreeBSD -{ - public class Absolute - { - [Theory] - [InlineData("/")] - [InlineData("/usr")] - [InlineData("/usr/local/music")] - [InlineData("/home/user/Music")] - [InlineData("/home/Ünïcödé")] - [InlineData("/home/пользователь/Музыка")] - [InlineData("//server/share")] - [InlineData("//server/share/folder")] - [InlineData("//192.168.1.1/share")] - public void IsAbsolute_NotRelative(string path) - { - Assert.True(FileSafety.IsPathAbsolute(path, OSPlatform.FreeBSD)); - Assert.False(FileSafety.IsPathRelative(path, OSPlatform.FreeBSD)); - } - } - - public class Relative - { - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("subdir")] - [InlineData("sub/dir")] - [InlineData("sub\\dir")] - [InlineData("music.flac")] - [InlineData(".hidden")] - [InlineData("../escape")] - [InlineData("C:\\Music")] - [InlineData("C:/Music")] - [InlineData("\\\\server\\share")] - [InlineData("\\Music")] - public void IsRelative_NotAbsolute(string path) - { - Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.FreeBSD)); - Assert.True(FileSafety.IsPathRelative(path, OSPlatform.FreeBSD)); + public class Relative + { + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("music.flac")] + [InlineData(".hidden")] + [InlineData("../escape")] + [InlineData("./dir")] + [InlineData("..")] + [InlineData(".")] + [InlineData("Ünïcödé")] + [InlineData("пользователь/Музыка")] + [InlineData("C:\\Music")] // Windows drive-letter — not absolute on Linux + [InlineData("C:/Music")] // Windows drive-letter — not absolute on Linux + [InlineData("\\\\server\\share")] // Windows UNC — not absolute on Linux + [InlineData("\\Music")] // Windows root-relative — not absolute on Linux + public void IsRelative_NotAbsolute(string path) + { + Assert.False(FileSafety.IsPathAbsolute(path, OSPlatform.Linux)); + Assert.True(FileSafety.IsPathRelative(path, OSPlatform.Linux)); + } + } } } -} +} \ 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 index bc8601c5..c5c94209 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using System.Runtime.InteropServices; using slskd.Validation; using Xunit; @@ -6,9 +7,9 @@ namespace slskd.Tests.Unit.Common.Validation; public class AbsolutePathAttributeTests { - private static (bool IsValid, string ErrorMessage) Validate(string value) + private static (bool IsValid, string ErrorMessage) Validate(string value, OSPlatform? os = null) { - var attribute = new AbsolutePathAttribute(); + var attribute = new AbsolutePathAttribute(os); var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; var result = attribute.GetValidationResult(value, context); return (result == null, result?.ErrorMessage); @@ -29,149 +30,86 @@ public class AbsolutePathAttributeTests Assert.True(isValid); } - public class Passes + public class Windows { - // 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) + [InlineData("C:\\Music")] + [InlineData("C:/Music")] + [InlineData("C:\\Music\\Artist\\Album")] + [InlineData("C:\\Music\\Artist/Album")] + [InlineData("C:/Music/My Artist")] public void Windows_DriveLetterPaths_Pass(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Windows); 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 + [InlineData("C:\\")] + [InlineData("Z:\\")] + [InlineData("C:/")] public void Windows_RootPaths_Pass(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Windows); 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) + [InlineData("\\\\server\\share")] + [InlineData("\\\\server\\share\\folder")] + [InlineData("\\\\192.168.1.1\\share")] + public void Windows_UNCPaths_Pass(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Windows); 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) + [InlineData("\\Music")] + [InlineData("/Music")] + [InlineData("/Music/Artist/Album")] + [InlineData("C:")] + [InlineData("C:Music")] + public void Windows_RootRelativePaths_Fail(string value) { - var (isValid, _) = Validate(value); - Assert.True(isValid); + var (isValid, _) = Validate(value, OSPlatform.Windows); + Assert.False(isValid); } + } - // Unix/Linux absolute paths — always start with a leading / + public class Unix + { [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 + [InlineData("/")] + [InlineData("/home")] + [InlineData("/home/user")] public void Unix_Paths_Pass(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Linux); 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) + [InlineData("//server/share")] + [InlineData("//server/share/folder")] + [InlineData("//192.168.1.1/share")] + public void Unix_UNCPaths_Pass(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Linux); 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) + [InlineData("\\")] + [InlineData("\\home")] + public void Unix_Backslash_Fail(string value) { - var (isValid, _) = Validate(value); - Assert.True(isValid); + var (isValid, _) = Validate(value, OSPlatform.Linux); + Assert.False(isValid); } } - public class Relative_Fails + public class Relative { [Theory] [InlineData("subdir")] // simple name @@ -188,7 +126,7 @@ public class AbsolutePathAttributeTests [InlineData(".")] // current-dir but fundamentally not absolute public void RelativePath_Fails(string value) { - var (isValid, errorMessage) = Validate(value); + var (isValid, errorMessage) = Validate(value, OSPlatform.Linux); Assert.False(isValid); Assert.Equal("The Field field must be an absolute file path.", errorMessage); } diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index bc581bf1..d1d71f18 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using System.Runtime.InteropServices; using slskd.Validation; using Xunit; @@ -6,9 +7,9 @@ namespace slskd.Tests.Unit.Common.Validation; public class RelativePathAttributeTests { - private static (bool IsValid, string ErrorMessage) Validate(string value) + private static (bool IsValid, string ErrorMessage) Validate(string value, OSPlatform? os = null) { - var attribute = new RelativePathAttribute(); + var attribute = new RelativePathAttribute(os); var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; var result = attribute.GetValidationResult(value, context); return (result == null, result?.ErrorMessage); @@ -61,7 +62,7 @@ public class RelativePathAttributeTests [InlineData("משתמש/מוזיקה")] // Hebrew public void RelativePath_Passes(string value) { - var (isValid, _) = Validate(value); + var (isValid, _) = Validate(value, OSPlatform.Linux); Assert.True(isValid); } } @@ -97,7 +98,7 @@ public class RelativePathAttributeTests [InlineData("C:Music")] public void AbsolutePath_Fails(string value) { - var (isValid, errorMessage) = Validate(value); + var (isValid, errorMessage) = Validate(value, OSPlatform.Windows); Assert.False(isValid); Assert.Equal("The Field field must be a relative path.", errorMessage); } -- cgit v1.2.3 From 01836889040aa76883bf81eb0f4b900f6e7fc4be Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 May 2026 16:36:10 -0500 Subject: make CombineSafely() even safer --- src/slskd/Common/FileSafety.cs | 24 +++++- .../Common/FileSafety/CombineSafelyTests.cs | 95 ++++++++++++++++++++++ 2 files changed, 116 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index c024aa86..f67af8d5 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -81,6 +81,8 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } + var isWindows = os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows(); + foreach (var segment in segments) { // if any segment is rooted (leading slash), Path.Combine drops everyting up to that segment @@ -91,22 +93,38 @@ public static class FileSafety throw new ArgumentException($"Absolute paths are not permitted in segments: '{segment}'"); } + if (isWindows) + { + if (segment.Contains(':')) + { + throw new ArgumentException($"Colons are not permitted in segments: '{segment}'"); + } + + // on Windows, a segment beginning with a slash is considered 'drive rooted' and something like + // "\foo" translates to "C:\foo" when passed to Path.Combine() + if (segment.StartsWith('\\') || segment.StartsWith('/')) + { + throw new ArgumentException($"Drive-relative segments or those containing leading slashes 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}'"); + throw new ArgumentException($"Path traversal is not permitted in segments: '{segment}'"); } } var combined = Path.Combine(root, Path.Combine(segments)); - // not sure how we could possibly get here, but if we do, throw. + // this is a backstop to catch any condition we haven't thought of; it makes sure that the resulting + // path is actually rooted in the root we provided; if not the input was successful in traversal if (!Path.GetFullPath(combined).StartsWith(Path.GetFullPath(root))) { - throw new ArgumentException($"Path traversal detected in path {combined}, which is not allowed"); + throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } return combined; diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index dce61235..2d496c4b 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -51,6 +51,24 @@ public partial class FileSafetyTests Assert.EndsWith(Path.Combine("foo", "bar"), result); } + [Fact] + public void Throws_Given_Null_Segment() + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, "foo", null, "bar")); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + + [Fact] + public void Throws_Given_Null_Segments() + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, segments: null)); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + [Fact] public void SingleSegment_ReturnsBaseAndSegment() { @@ -116,6 +134,83 @@ public partial class FileSafetyTests Assert.Contains("Absolute", ex.Message); } + [Theory] + [InlineData("foo:bar")] + [InlineData("C:relative")] + [InlineData("sub/foo:bar")] + [InlineData("sub/foo/bar:qux")] + public void Throws_ArgumentException_Given_Colon_In_Segment_On_Windows(string segment) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Windows, segment)); + + Assert.NotNull(ex); + Assert.Contains("Colon", ex.Message); + } + + [Theory] + [InlineData("foo:bar")] + [InlineData("sub/foo:bar")] + [InlineData("sub/foo/bar:qux")] + public void Accepts_Colon_In_Segment_On_Linux(string segment) + { + var result = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Linux, segment)); + + Assert.Null(result); + } + + [Theory] + [InlineData("C:relative")] + public void Accepts_Colon_In_Segment_On_Linux_Hits_Backstop_On_Windows(string segment) + { + var result = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Linux, segment)); + + if (!OperatingSystem.IsWindows()) + { + Assert.Null(result); + } + else + { + // this test breaks when run on windows + // this is valid on linux (which we're trying to test for) + // but invalid on windows because it is a drive-relative path and it successfully traverses + Assert.NotNull(result); + Assert.IsType(result); + Assert.Contains("traversal detected", result.Message); + } + } + + [Theory] + [InlineData("/Music")] + [InlineData("\\Music")] + public void Throws_ArgumentException_Given_Leading_Slash_In_Segment_On_Windows(string segment) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Windows, segment)); + + Assert.NotNull(ex); + Assert.Contains("Drive-relative", ex.Message); + } + + [Theory] + [InlineData("\\Music")] + public void Accepts_Leading_Backslash_In_Segment_On_Linux(string segment) + { + var result = Record.Exception(() => FileSafety.CombineSafely(Base, OSPlatform.Linux, segment)); + + if (!OperatingSystem.IsWindows()) + { + Assert.Null(result); + } + else + { + // this test breaks when run on windows + // this is valid on linux (which we're trying to test for) + // but invalid on windows because it is a drive-relative path and it successfully traverses + Assert.NotNull(result); + Assert.IsType(result); + Assert.Contains("traversal detected", result.Message); + } + } + [Theory] // Bare traversal [InlineData("..")] -- cgit v1.2.3 From 643be1cf048878fdf6d96738205fbd86fa8dedc7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 23 May 2026 17:04:19 -0500 Subject: add additional guard clauses to FileService --- src/slskd/Files/FileService.cs | 57 ++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 55 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 4b281863..3b304d99 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -79,6 +79,17 @@ namespace slskd.Files { ArgumentException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + if (Path.GetFullPath(filename) != filename) + { + throw new ArgumentException("Only absolute paths may be specified", nameof(filename)); + } + + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to resolve file info for a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename); + throw new ArgumentException("Filenames containing traversal segments are not allowed", nameof(filename)); + } + FileInfo info; try @@ -153,11 +164,22 @@ namespace slskd.Files /// Thrown if a specified directory is restricted. public virtual async Task>> DeleteDirectoriesAsync(params string[] directories) { + if (directories is null or [] || directories.Any(directory => string.IsNullOrEmpty(directory))) + { + throw new ArgumentException("One or more directories are null or empty"); + } + if (directories.Any(directory => Path.GetFullPath(directory) != directory)) { throw new ArgumentException("Only absolute paths may be specified", nameof(directories)); } + if (directories.Any(directory => FileSafety.ContainsTraversalSegments(directory))) + { + Log.Warning("Suspicious attempt to delete a directory with a path containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested directories: {Directories}", string.Join(", ", directories)); + throw new ArgumentException("Directories containing traversal segments are not allowed", nameof(directories)); + } + if (directories.Any(directory => AllowedDirectories.Contains(directory))) { throw new ArgumentException("Deletion of application-controlled directory roots is not supported"); @@ -216,11 +238,22 @@ namespace slskd.Files /// Thrown if a specified file is restricted. public virtual async Task>> DeleteFilesAsync(params string[] files) { + if (files is null or [] || files.Any(file => string.IsNullOrWhiteSpace(file))) + { + throw new ArgumentException("One or more files are null or empty", nameof(files)); + } + if (files.Any(file => Path.GetFullPath(file) != file)) { throw new ArgumentException("Only absolute paths may be specified", nameof(files)); } + if (files.Any(file => FileSafety.ContainsTraversalSegments(file))) + { + Log.Warning("Suspicious attempt to delete a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file(s): {File}", string.Join(", ", files)); + throw new ArgumentException("Paths containing traversal segments are not allowed", nameof(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 + Path.DirectorySeparatorChar) || path == allowed); @@ -269,15 +302,23 @@ namespace slskd.Files /// Thrown if the specified root directory is restricted. public virtual async Task ListContentsAsync(string directory, EnumerationOptions enumerationOptions = null) { + ArgumentException.ThrowIfNullOrWhiteSpace(directory); + if (Path.GetFullPath(directory) != directory) { throw new ArgumentException("Only absolute paths may be specified", nameof(directory)); } + if (FileSafety.ContainsTraversalSegments(directory)) + { + Log.Warning("Suspicious attempt to list a directory with a path containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested directory: {Directory}", directory); + throw new ArgumentException("Paths containing traversal segments are not allowed", nameof(directory)); + } + // important! we must fully expand the path with GetFullPath() to resolve a given relative directory, like '..' - if (!AllowedDirectories.Any(allowed => directory.StartsWith(allowed))) + if (!AllowedDirectories.Any(allowed => directory.StartsWith(allowed + Path.DirectorySeparatorChar) || directory == allowed)) { - throw new UnauthorizedException($"Only application-controlled directories can be deleted"); + throw new UnauthorizedException($"Only application-controlled directories can be listed"); } if (!Directory.Exists(directory)) @@ -340,6 +381,12 @@ namespace slskd.Files { ArgumentNullException.ThrowIfNullOrWhiteSpace(filename, nameof(filename)); + if (FileSafety.ContainsTraversalSegments(filename)) + { + Log.Warning("Suspicious attempt to create a file with a filename containing unsafe path segments (one or more of path traversal characters '.' and '..'). Requested file: {File}", filename); + throw new ArgumentException("Filenames containing traversal segments are not allowed"); + } + var path = Path.GetDirectoryName(filename); UnixFileMode? unixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Permissions.File.Mode?.ToUnixFileMode(); @@ -411,6 +458,12 @@ namespace slskd.Files ArgumentNullException.ThrowIfNullOrWhiteSpace(sourceFilename, nameof(sourceFilename)); ArgumentNullException.ThrowIfNullOrWhiteSpace(destinationDirectory, nameof(destinationDirectory)); + if (FileSafety.ContainsTraversalSegments(sourceFilename) || FileSafety.ContainsTraversalSegments(destinationDirectory)) + { + Log.Warning("Suspicious attempt to move a file with either a source filename or destination directory name containing unsafe path segments (one or more of path traversal characters '.' and '..'). Source: {Source}, Destination: {Destination}", sourceFilename, destinationDirectory); + throw new ArgumentException("Filenames and directories containing traversal segments are not allowed"); + } + if (!File.Exists(sourceFilename)) { throw new FileNotFoundException($"The specified source file does not exist", fileName: sourceFilename); -- cgit v1.2.3 From c03c5087aa6ac70491363b7dff05909f7bc64fe0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 24 May 2026 12:52:16 -0500 Subject: rename 'incomplete' to 'partial', default to 'resume' (to match docs) --- config/slskd.example.yml | 2 +- docs/config.md | 4 ++-- src/slskd/Core/Options.cs | 6 +++--- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index e68baae2..1063e7f5 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -74,7 +74,7 @@ # slots: 500 # speed_limit: 1000 # retry: -# incomplete: resume # 'overwrite' or 'resume' +# partial: resume # 'overwrite' or 'resume' # attempts: 3 # delay: 5000 # initial time between retries, in milliseconds # max_delay: 60000 # maximum time between retries, in milliseconds diff --git a/docs/config.md b/docs/config.md index 14f1ae24..40d3a78a 100644 --- a/docs/config.md +++ b/docs/config.md @@ -362,14 +362,14 @@ transfers: Failed downloads can be retried automatically up to the configured number of attempts. If an attempt fails initially, the application delays the second attempt by the configured delay, and an exponential backoff is used to compute the delay for all subsequent events, up to the configured maximum delay. -By default, partial downloads are resumed based on the size of the incomplete file. Users can choose to always overwrite files if they wish. +By default, partial downloads are resumed based on the size of the file on disk. Users can choose to always overwrite files if they wish. **YAML** ```yaml transfers: download: retry: - incomplete: resume # 'overwrite' or 'resume' + partial: resume # 'overwrite' or 'resume' attempts: 3 delay: 5000 # initial time between retries, in milliseconds max_delay: 60000 # maximum time between retries, in milliseconds diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 83e534a1..bac86ea2 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1052,10 +1052,10 @@ namespace slskd public int MaxDelay { get; init; } = 60_000; /// - /// Gets the strategy for handling incomplete files upon retry. + /// Gets the strategy for handling partial files upon retry. /// - [Enum(typeof(RetryIncompleteStrategy))] - public string Incomplete { get; init; } = RetryIncompleteStrategy.Overwrite.ToString().ToLowerInvariant(); + [Enum(typeof(RetryPartialStrategy))] + public string Partial { get; init; } = RetryPartialStrategy.Resume.ToString().ToLowerInvariant(); } } -- cgit v1.2.3 From 8b27a264869dd51f3bb1ae27f208a3843d4c7df0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 24 May 2026 12:54:00 -0500 Subject: rename RetryIncompleteStrategy to RetryPartialStrategy --- .../Transfers/Types/RetryIncompleteStrategy.cs | 49 ---------------------- src/slskd/Transfers/Types/RetryPartialStrategy.cs | 49 ++++++++++++++++++++++ 2 files changed, 49 insertions(+), 49 deletions(-) delete mode 100644 src/slskd/Transfers/Types/RetryIncompleteStrategy.cs create mode 100644 src/slskd/Transfers/Types/RetryPartialStrategy.cs (limited to 'src') diff --git a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs b/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs deleted file mode 100644 index 9ac8d8e2..00000000 --- a/src/slskd/Transfers/Types/RetryIncompleteStrategy.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Transfers; - -/// -/// Strategy for retrying incomplete files. -/// -public enum RetryIncompleteStrategy -{ - /// - /// Overwrite the existing file. - /// - Overwrite = 0, - - /// - /// Resume the transfer using the size of the incomplete file as the initial offset. - /// - Resume = 1, -} \ No newline at end of file diff --git a/src/slskd/Transfers/Types/RetryPartialStrategy.cs b/src/slskd/Transfers/Types/RetryPartialStrategy.cs new file mode 100644 index 00000000..20868913 --- /dev/null +++ b/src/slskd/Transfers/Types/RetryPartialStrategy.cs @@ -0,0 +1,49 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers; + +/// +/// Strategy for retrying partial files. +/// +public enum RetryPartialStrategy +{ + /// + /// Overwrite the existing file. + /// + Overwrite = 0, + + /// + /// Resume the transfer using the size of the partial file as the initial offset. + /// + Resume = 1, +} \ No newline at end of file -- cgit v1.2.3 From 98b81975d0bf7a10fc834d33d5bfbb6532f75686 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 24 May 2026 13:10:02 -0500 Subject: update partial call sites --- src/slskd/Transfers/Downloads/DownloadService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 83e91ced..013e6a7a 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1061,14 +1061,14 @@ namespace slskd.Transfers.Downloads var completedTransfer = await Retry.Do(() => { var incompleteFileInfo = Files.ResolveFileInfo(incompleteFilename); - var incompleteStrategy = retryOptions.Incomplete.ToEnum(); + var incompleteStrategy = retryOptions.Partial.ToEnum(); var shouldResume = false; var startOffset = 0L; if (incompleteFileInfo.Exists && incompleteFileInfo.Length > 0) { - if (incompleteStrategy == RetryIncompleteStrategy.Resume) + if (incompleteStrategy == RetryPartialStrategy.Resume) { shouldResume = true; startOffset = incompleteFileInfo.Length; -- cgit v1.2.3 From 65178904483e4496c1140bee11b2fd4d79da121f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 25 May 2026 18:19:42 -0500 Subject: add ReplacePathTraversalSegments --- src/slskd/Common/CommonExtensions.cs | 18 +++++++++++++++++- 1 file changed, 17 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 5ff3e519..ce1b5afb 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -471,7 +471,7 @@ namespace slskd } /// - /// Replaces any occurrence of an invalid filename character with the specified . + /// Replaces any occurrence of an invalid filename character with the specified . /// /// The path to sanitize. /// The character with which to replace invalid characters. @@ -488,6 +488,22 @@ namespace slskd return sanitized; } + /// + /// Replaces any path traversal segments in the specified with the specified + /// . + /// + /// The path to sanitize. + /// The string with which to replace path traversal segments. + /// The sanitized path. + public static string ReplacePathTraversalSegments(this string path, string replacement = "_") + { + return string.Join(Path.DirectorySeparatorChar, + path + .LocalizePath() + .Split(Path.DirectorySeparatorChar) + .Select(s => s is "." or ".." ? replacement : s)); + } + /// /// Converts a ModelStateDictionary into a human-readable format. /// -- cgit v1.2.3 From def6a3a05f02a53b814821ab6b9692e89c2df693 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 May 2026 19:18:06 -0500 Subject: add sanitize functions to FileSafety --- src/slskd/Common/FileSafety.cs | 106 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index f67af8d5..aae14a25 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -36,12 +36,34 @@ using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; +using System.Text.RegularExpressions; /// /// Utility functions to help safely work with paths from untrusted sources. /// public static class FileSafety { + + /// + /// Invalid filename characters on Unix-like operating systems (Linux, OSX, FreeBSD, etc). + /// + public static readonly char[] InvalidFileNameCharactersOnUnix = ['\0', '/']; + + /// + /// Invalid filename characters on Windows. + /// + public static readonly char[] InvalidFileNameCharactersOnWindows = + [ + '\"', '<', '>', '|', '\0', + (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, + (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, + (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, + (char)31, ':', '*', '?', '\\', '/', + ]; + + private static readonly Regex DriveRootRegex = new(@"^[a-zA-Z]:[/\\]?", RegexOptions.Compiled); // C: or C:\ + private static readonly Regex UncRootRegex = new(@"^[/\\]{2}[^/\\]+[/\\]?", RegexOptions.Compiled); // \\server[\] or //server[/], any slash variants + /// /// An alternative to that disallows rooted segments in the second or /// subsequent position, and disallows segments containing path traversal characters "." and "..". @@ -193,4 +215,88 @@ public static class FileSafety /// An optional operating system override, for testing. /// True if the path is relative, false otherwise. public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); + + /// + /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). + /// + /// The path to convert. + /// An optional operating system override, for testing. + /// The converted path. + public static string LocalizePath(this string path, OSPlatform? os = null) + { + os ??= Compute.OSPlatform(); + + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + return path.Replace('\\', sep).Replace('/', sep); + } + + /// + /// Sanitizes the specified (or string intended to be used as or as part of a filename) + /// to make it suitable and safe on the local operating system by stripping all slashes (forward or back) and + /// and replacing any invalid characters with the specified . + /// + /// The filename (or string intended to be used as/part of one). + /// The character to substitute for invalid characters. + /// An optional operating system override, for testing. + /// The sanitized filename. + public static string SanitizeFilename(string filename, char replacement = '_', OSPlatform? os = null) + { + if (replacement is '/' or '\\') + { + throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); + } + + os ??= Compute.OSPlatform(); + + var characters = os.Value == OSPlatform.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; + + if (characters.Contains(replacement)) + { + throw new ArgumentException($"The provided replacement character '{replacement}' is invalid on {os}"); + } + + var sanitized = filename; + + foreach (var c in characters) + { + sanitized = sanitized.Replace(c, replacement); + } + + // regardless of which OS and what characters are disallowed on it, we don't allow slashes in filenames + // (or strings that will be used as filenames), otherwise we should/would have used SanitizePath() + return sanitized + .Replace('/', replacement) + .Replace('\\', replacement); + } + + /// + /// Sanitizes the specified to make it suitable and safe on the local operating system + /// by converting to the correct slashes, dropping a root (if present), replacing any invalid characters with + /// the specified , and by dropping any path traversal segments. + /// + /// The path. + /// The character to substitute for invalid characters. + /// An optional operating system override, for testing. + /// The sanitized path. + public static string SanitizePath(this string path, char replacement = '_', OSPlatform? os = null) + { + os ??= Compute.OSPlatform(); + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + // flip slashes the correct way + path = path.LocalizePath(os); + + // strip C:\ or //server, if present (regardless of slash variant, etc) + path = DriveRootRegex.Replace(path, string.Empty); + path = UncRootRegex.Replace(path, string.Empty); + + // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings + var segments = path + .Split(sep) + .Select(s => SanitizeFilename(s, replacement, os)) + .Select(s => s is "." or ".." ? replacement.ToString() : s); + + return string.Join(sep, segments); + } } \ No newline at end of file -- cgit v1.2.3 From 002a2295241bbbc3e823bc1aa18d64651a10ce74 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 May 2026 19:18:27 -0500 Subject: add compute.OSPlatform() --- src/slskd/Common/Compute.cs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index 8d7c1ceb..dc565806 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -33,6 +33,7 @@ namespace slskd { using System; + using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; @@ -64,5 +65,25 @@ namespace slskd using var sha256 = SHA256.Create(); return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty); } + + public static OSPlatform OSPlatform() + { + if (OperatingSystem.IsWindows()) + { + return System.Runtime.InteropServices.OSPlatform.Windows; + } + + if (OperatingSystem.IsMacOS()) + { + return System.Runtime.InteropServices.OSPlatform.OSX; + } + + if (OperatingSystem.IsFreeBSD()) + { + return System.Runtime.InteropServices.OSPlatform.FreeBSD; + } + + return System.Runtime.InteropServices.OSPlatform.Linux; + } } } \ No newline at end of file -- cgit v1.2.3 From e711d6ad8b52e7ee6454b20bce0fcdbe12aaae91 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 26 May 2026 19:25:10 -0500 Subject: add ExternalId to batch options --- src/slskd/Transfers/Types/BatchOptions.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/Types/BatchOptions.cs b/src/slskd/Transfers/Types/BatchOptions.cs index 6bacef8c..2ea22997 100644 --- a/src/slskd/Transfers/Types/BatchOptions.cs +++ b/src/slskd/Transfers/Types/BatchOptions.cs @@ -45,4 +45,9 @@ public record BatchOptions /// If specified, takes precedence over other configured placement rules. /// public string Destination { get; init; } + + /// + /// Gets an optional external ID for the batch. + /// + public string ExternalId { get; init; } } \ No newline at end of file -- cgit v1.2.3 From 89f2a6e19745f22a8f003556b743cbe87ec67cc8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 May 2026 21:43:50 -0500 Subject: strip soulseek qt prefixes too --- src/slskd/Common/FileSafety.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index aae14a25..06fd340d 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -63,6 +63,7 @@ public static class FileSafety private static readonly Regex DriveRootRegex = new(@"^[a-zA-Z]:[/\\]?", RegexOptions.Compiled); // C: or C:\ private static readonly Regex UncRootRegex = new(@"^[/\\]{2}[^/\\]+[/\\]?", RegexOptions.Compiled); // \\server[\] or //server[/], any slash variants + private static readonly Regex SoulseekQtRootRegex = new(@"^@@[a-zA-Z0-9]{5,}[\/\\]", RegexOptions.Compiled); // @@abcde[\|/], a Soulseek Qt share prefix /// /// An alternative to that disallows rooted segments in the second or @@ -291,6 +292,9 @@ public static class FileSafety path = DriveRootRegex.Replace(path, string.Empty); path = UncRootRegex.Replace(path, string.Empty); + // strip @@abcde prefixes used by SoulseekQt to obscure paths + path = SoulseekQtRootRegex.Replace(path, string.Empty); + // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path .Split(sep) -- cgit v1.2.3 From f785cdc0a88069f04e62a6dc968504d3fa8fd49b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 May 2026 21:56:49 -0500 Subject: add missing ExternalId to DTO --- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index c1b7d725..e569df30 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -110,4 +110,9 @@ public record EnqueueDownloadBatchOptions [NonTraversingPath] [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] public string Destination { get; init; } + + /// + /// An optional external ID for the batch. + /// + public string ExternalId { get; init; } } \ No newline at end of file -- cgit v1.2.3 From 65ab127c1b85b5c7023324a2c22b782d07f01f26 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 May 2026 21:58:48 -0500 Subject: remove deprecated extension method --- src/slskd/Common/CommonExtensions.cs | 24 +--- .../ReplaceInvalidFileNameCharactersTests.cs | 144 --------------------- 2 files changed, 3 insertions(+), 165 deletions(-) delete mode 100644 tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index ce1b5afb..4b327a1b 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -461,33 +461,15 @@ namespace slskd if (parts.Length == 1) { - return parts.First().ReplaceInvalidFileNameCharacters(); + return FileSafety.SanitizeFilename(parts.First()); } - var file = parts.Last().ReplaceInvalidFileNameCharacters(); - var directory = parts.Reverse().Skip(1).Take(1).Single().ReplaceInvalidFileNameCharacters(); + var file = FileSafety.SanitizeFilename(parts.Last()); + var directory = FileSafety.SanitizeFilename(parts.Reverse().Skip(1).Take(1).Single()); return FileSafety.CombineSafely(directory, file); } - /// - /// Replaces any occurrence of an invalid filename character with the specified . - /// - /// The path to sanitize. - /// The character with which to replace invalid characters. - /// The sanitized path. - public static string ReplaceInvalidFileNameCharacters(this string path, char replacement = '_') - { - var sanitized = path; - - foreach (var c in Path.GetInvalidFileNameChars()) - { - sanitized = sanitized.Replace(c, replacement); - } - - return sanitized; - } - /// /// Replaces any path traversal segments in the specified with the specified /// . diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs deleted file mode 100644 index eff24587..00000000 --- a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs +++ /dev/null @@ -1,144 +0,0 @@ -namespace slskd.Tests.Unit.Common.Extensions -{ - using System; - using System.IO; - using System.Linq; - using Xunit; - - public class ReplaceInvalidFileNameCharactersTests - { - [Fact] - public void Throws_NullReferenceException_Given_Null() - { - string path = null; - Assert.Throws(() => 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); - } - } -} -- cgit v1.2.3 From 953733c42b4f7556a8619c32da1ef897a0027ae9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 May 2026 21:59:07 -0500 Subject: use new SanitizeFilename --- src/slskd/Relay/API/Controllers/RelayController.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Relay/API/Controllers/RelayController.cs b/src/slskd/Relay/API/Controllers/RelayController.cs index fdc6dbe6..ddb8d0b0 100644 --- a/src/slskd/Relay/API/Controllers/RelayController.cs +++ b/src/slskd/Relay/API/Controllers/RelayController.cs @@ -345,7 +345,7 @@ namespace slskd.Relay } Directory.CreateDirectory(FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName)); - var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_{agentName.ReplaceInvalidFileNameCharacters()}_{Path.GetRandomFileName()}.db"); + var temp = FileSafety.CombineSafely(Path.GetTempPath(), Program.AppName, $"share_{FileSafety.SanitizeFilename(agentName)}_{Path.GetRandomFileName()}.db"); try { -- cgit v1.2.3 From 845da6c1c95ed18ec88c93a48f0a04c539f28bc3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 27 May 2026 21:59:45 -0500 Subject: wip --- config/slskd.example.yml | 7 +- src/slskd/Core/Options.cs | 50 ++ src/slskd/Transfers/Downloads/DownloadService.cs | 205 ++++++++- .../Transfers/Types/DestinationConflictStrategy.cs | 49 ++ .../DownloadService/DeriveDestinationTests.cs | 512 +++++++++++++++++++++ 5 files changed, 802 insertions(+), 21 deletions(-) create mode 100644 src/slskd/Transfers/Types/DestinationConflictStrategy.cs create mode 100644 tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs (limited to 'src') 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 @@ -1028,6 +1028,12 @@ namespace slskd [Validate] public RetryOptions Retry { get; init; } = new RetryOptions(); + /// + /// Gets download destination options. + /// + [Validate] + public DestinationOptions Destination { get; init; } = new DestinationOptions(); + /// /// Download retry options. /// @@ -1057,6 +1063,50 @@ namespace slskd [Enum(typeof(RetryPartialStrategy))] public string Partial { get; init; } = RetryPartialStrategy.Resume.ToString().ToLowerInvariant(); } + + /// + /// Download destination options. + /// + 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; } + + /// + /// Extended validation. + /// + /// + /// + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + 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; + } + } + } } /// 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; /// /// Manages downloads. @@ -67,6 +70,26 @@ namespace slskd.Transfers.Downloads /// void AddOrSupersede(Transfer transfer); + /// + /// Derives the destination subdirectory for the specified based on user and batch + /// configuration. + /// + /// + /// + /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments. + /// Otherwise, an instance of will be thrown as a backstop. + /// + /// + /// Empty segments may be present in the output, which more closely aligns with user intent. The + /// method drops them silently, so there's no functional impact. + /// + /// + /// The transfer. + /// The derived destination directory. + /// Thrown if the specified download doesn't exist. + /// Thrown if the derivation logic produces an absolute path, or one with traversal segments. + Task DeriveDestination(Transfer transfer); + /// /// Enqueues the requested list of . /// @@ -165,6 +188,7 @@ namespace slskd.Transfers.Downloads { public DownloadService( IBatchService batchService, + ISearchService searchService, IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory 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 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(); private IOptionsMonitor OptionsMonitor { get; } private EventBus EventBus { get; } + private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they @@ -707,6 +734,144 @@ namespace slskd.Transfers.Downloads } } + /// + /// Derives the destination subdirectory for the specified based on user and + /// batch configuration. + /// + /// + /// + /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments. + /// Otherwise, an instance of will be thrown as a backstop. + /// + /// + /// Empty segments may be present in the output, which more closely aligns with user intent. The + /// method drops them silently, so there's no functional impact. + /// + /// + /// The transfer. + /// The derived destination directory. + /// Thrown if the derivation logic produces an absolute path, or one with traversal segments. + public async Task 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( + 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; + } + /// /// Returns a list of all downloads matching the optional . /// @@ -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(); 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers; + +/// +/// Strategy for handling downloaded files with conflicting names. +/// +public enum DestinationConflictStrategy +{ + /// + /// Rename the new file by appending something. + /// + Rename = 0, + + /// + /// Overwrite the existing file. + /// + 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>().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(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>>())) + .ReturnsAsync(batch); + SearchService.Setup(s => s.FindAsync(It.IsAny>>(), It.IsAny())) + .ReturnsAsync(search); + } + + public Mock BatchService { get; } = new(); + public Mock SearchService { get; } = new(); + public TestOptionsMonitor OptionsMonitor { get; } + } +} -- cgit v1.2.3 From 34005f37c03e878c2a3286ca0223f921a66a5671 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 28 May 2026 19:10:37 -0500 Subject: tests --- src/slskd/Common/FileSafety.cs | 1 - .../Common/FileSafety/LocalizePathTests.cs | 16 ++++++++++++++- .../Common/FileSafety/SanitizeFilenameTests.cs | 24 ++++++++++++++++++++++ 3 files changed, 39 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 06fd340d..dc27a8b4 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -43,7 +43,6 @@ using System.Text.RegularExpressions; /// public static class FileSafety { - /// /// Invalid filename characters on Unix-like operating systems (Linux, OSX, FreeBSD, etc). /// diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index ed3e692f..2df3e18f 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -10,8 +10,15 @@ public partial class FileSafetyTests [Theory] [InlineData("foo/bar", "foo/bar")] [InlineData("foo\\bar", "foo/bar")] + [InlineData("foo/bar/baz", "foo/bar/baz")] [InlineData("foo\\bar/baz", "foo/bar/baz")] [InlineData("foo\\\\bar", "foo//bar")] + [InlineData("@@abcde\\foo\\bar\\", "@@abcde/foo/bar/")] + [InlineData("@@abcde/foo/bar/", "@@abcde/foo/bar/")] + [InlineData("\\\\server\\foo\\", "//server/foo/")] + [InlineData("//server/foo/", "//server/foo/")] + [InlineData("C:\\Windows\\foo", "C:/Windows/foo")] + [InlineData("C:/Windows/foo", "C:/Windows/foo")] [InlineData("", "")] public void Linux_NormalizesToForwardSlash(string input, string expected) { @@ -24,7 +31,14 @@ public partial class FileSafetyTests [InlineData("foo/bar", "foo\\bar")] [InlineData("foo\\bar", "foo\\bar")] [InlineData("foo/bar/baz", "foo\\bar\\baz")] + [InlineData("foo\\bar/baz", "foo\\bar\\baz")] [InlineData("foo//bar", "foo\\\\bar")] + [InlineData("@@abcde\\foo\\bar\\", "@@abcde\\foo\\bar\\")] + [InlineData("@@abcde/foo/bar/", "@@abcde\\foo\\bar\\")] + [InlineData("\\\\server\\foo\\", "\\\\server\\foo\\")] + [InlineData("//server/foo/", "\\\\server\\foo\\")] + [InlineData("C:\\Windows\\foo", "C:\\Windows\\foo")] + [InlineData("C:/Windows/foo", "C:\\Windows\\foo")] [InlineData("", "")] public void Windows_NormalizesToBackslash(string input, string expected) { @@ -38,7 +52,7 @@ public partial class FileSafetyTests { var result = "foo/bar".LocalizePath(); - Assert.NotNull(result); + Assert.False(string.IsNullOrEmpty(result)); } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs index 285fdffd..34e969d4 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs @@ -85,6 +85,18 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + [Theory] + [InlineData("/home/user/foo", "_home_user_foo")] + [InlineData("//server/share", "__server_share")] + [InlineData("C:\\Windows\\file.ext", "C:_Windows_file.ext")] + [InlineData("\\\\server\\share", "__server_share")] + public void Linux_Sanitizes_Full_Paths(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + [Fact] public void Linux_Uses_Custom_Replacement() { @@ -109,6 +121,18 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + [Theory] + [InlineData("/home/user/foo", "_home_user_foo")] + [InlineData("//server/share", "__server_share")] + [InlineData("C:\\Windows\\file.ext", "C__Windows_file.ext")] + [InlineData("\\\\server\\share", "__server_share")] + public void Windows_Sanitizes_Full_Paths(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Windows); + + Assert.Equal(expected, result); + } + [Fact] public void Windows_Replaces_ControlCharacters() { -- cgit v1.2.3 From 0e4af54cebd4adba3ef32d57f8dbc3920ad28228 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 28 May 2026 19:27:08 -0500 Subject: tests, strategy enum --- .../Transfers/Types/DestinationConflictStrategy.cs | 49 ++ .../DownloadService/DeriveDestinationTests.cs | 610 +++++++++++++++++++++ 2 files changed, 659 insertions(+) create mode 100644 src/slskd/Transfers/Types/DestinationConflictStrategy.cs create mode 100644 tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs (limited to 'src') 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 (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers; + +/// +/// Strategy for handling downloaded files with conflicting names. +/// +public enum DestinationConflictStrategy +{ + /// + /// Rename the new file by appending something. + /// + Rename = 0, + + /// + /// Overwrite the existing file. + /// + 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..4da05b24 --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -0,0 +1,610 @@ +namespace slskd.Tests.Unit.Transfers.Downloads; + +using System; +using System.IO; +using System.Linq.Expressions; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Moq; +using slskd.Search; +using slskd.Transfers; +using slskd.Transfers.Downloads; +using Xunit; + +public partial class DownloadServiceTests +{ + public class DeriveDestination + { + [Fact] + public async Task Explicit_Destination_Takes_Precedence_Over_Subdirectory_Pattern() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "explicit-dir" } }; + var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("explicit-dir", result); + } + + [Fact] + public async Task Explicit_Destination_Tokens_Are_Not_Expanded() + { + // explicit destination is sanitized but not token-substituted + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "{SOURCE_USERNAME}" } }; + var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("{SOURCE_USERNAME}", result); + } + + [Fact] + public async Task Explicit_Destination_Is_Always_Relative() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "/etc/passwd" } }; + var (service, _) = GetFixture("irrelevant", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.IsPathAbsolute(result)); + } + + [Fact] + public async Task Explicit_Destination_Traversal_Segments_Do_Not_Survive() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "../../../etc/passwd" } }; + var (service, _) = GetFixture("irrelevant", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task Explicit_Destination_Null_Byte_Replaced() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "down\0loads" } }; + var (service, _) = GetFixture("irrelevant", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("down_loads", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Is_Substituted() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Pattern_Match_Is_Case_Insensitive() + { + var (service, _) = GetFixture("{source_username}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Forward_Slash_Replaced_With_Underscore() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "al/ice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_ice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Backslash_Replaced_With_Underscore() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "al\\ice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_ice", result); + } + + [Fact] + public async Task SOURCE_USERNAME_Null_Byte_Replaced_With_Underscore() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "al\0ice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_ice", result); + } + + [Theory] + [InlineData("al\\..\\ice")] + [InlineData("al/../ice")] + [InlineData("al\\../ice")] + [InlineData("al/..\\ice")] + public async Task SOURCE_USERNAME_Traversal_Segment_Periods_Remains_After_Replacing_Slashes_With_Underscore(string username) + { + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = username, Filename = "@alice\\track.mp3" }); + + Assert.Equal("al_.._ice", result); + } + + [Fact] + public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Backslash() + { + var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" }); + + Assert.Equal("album", result); + } + + [Fact] + public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Forward_Slash() + { + var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice/Music/album/track.mp3" }); + + Assert.Equal("album", result); + } + + [Fact] + public async Task SOURCE_DIRECTORY_Is_Empty_If_File_Is_In_Root() + { + var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" }); + + Assert.Equal(string.Empty, result); + } + + [Fact] + public async Task SOURCE_PATH_Is_Full_Directory_Of_Remote_Filename() + { + var (service, _) = GetFixture("{SOURCE_PATH}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" }); + + Assert.Equal(Path.Combine("@alice", "Music", "album"), result); + } + + [Fact] + public async Task SOURCE_PATH_Is_Empty_If_File_Is_In_Root() + { + var (service, _) = GetFixture("{SOURCE_PATH}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" }); + + Assert.Equal(string.Empty, result); + } + + [Fact] + public async Task SOURCE_PATH_And_SOURCE_DIRECTORY_Match_If_File_Is_In_One_Subdirectory() + { + var (service, _) = GetFixture("{SOURCE_PATH}-{SOURCE_DIRECTORY}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("@alice-@alice", result); + } + + [Fact] + public async Task BATCH_ID_Is_Substituted_When_Batch_Exists() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId }; + var (service, _) = GetFixture("{BATCH_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal(batchId.ToString(), result); + } + + [Fact] + public async Task BATCH_ID_Is_Fallback_When_No_Batch() + { + var (service, _) = GetFixture("{BATCH_ID}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + Assert.Equal("unknown_batch_id", result); + } + + [Fact] + public async Task BATCH_ID_Is_Fallback_When_Batch_Id_Is_Empty_Guid() + { + var batch = new Batch { Id = Guid.Empty }; + var (service, _) = GetFixture("{BATCH_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = Guid.Empty }); + + Assert.Equal("unknown_batch_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Substituted_When_Batch_Has_External_Id() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "my-ext-id" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("my-ext-id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_No_Batch() + { + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Null() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = null } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Whitespace() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = " " } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Forward_Slash_In_Value_Replaced_With_Underscore() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo/bar" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Backslash_In_Value_Replaced_With_Underscore() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo\\bar" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Null_Byte_In_Value_Replaced_With_Underscore() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "foo\0bar" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Substituted_When_Search_Exists() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "some query" }; + var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal(searchId.ToString(), result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_No_Batch() + { + // no batch → SearchId is never consulted + var (service, _) = GetFixture("{SEARCH_ID}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_Batch_Has_No_SearchId() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = null }; + var (service, _) = GetFixture("{SEARCH_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_Search_Not_Found() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() }; + var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: null); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_ID_Is_Fallback_When_Search_ID_Is_Empty_Guid() + { + var searchId = Guid.Empty; + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "some query" }; + var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_id", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Substituted_When_Search_Exists() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo bar baz" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo bar baz", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_No_Search() + { + var (service, _) = GetFixture("{SEARCH_TEXT}"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Forward_Slash_In_Value_Replaced_With_Underscore() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo/bar" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task SEARCH_TEXT_Backlash_In_Value_Replaced_With_Underscore() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo\\bar" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task Batch_With_Null_Options_Falls_Through_To_Pattern() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = null }; + var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task Batch_With_Whitespace_Destination_Falls_Through_To_Pattern() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = " " } }; + var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("alice", result); + } + + [Fact] + public async Task Pattern_Forward_Slash_Separator_Preserved_In_Output() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}/downloads"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal(Path.Combine("alice", "downloads"), result); + } + + [Fact] + public async Task Pattern_Backslash_Separator_Preserved_In_Output() + { + var (service, _) = GetFixture("{SOURCE_USERNAME}\\downloads"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.Equal(Path.Combine("alice", "downloads"), result); + } + + [Fact] + public async Task Pattern_Output_Is_Always_Relative() + { + var (service, _) = GetFixture("/etc/passwd"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.False(FileSafety.IsPathAbsolute(result)); + } + + [Fact] + public async Task Pattern_Traversal_Segments_Do_Not_Survive() + { + var (service, _) = GetFixture("../../../etc/passwd"); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task Username_Containing_Traversal_Is_Safe() + { + // exact '..' in username must not produce a traversal segment in the final output + var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var result = await service.DeriveDestination(new Transfer { Username = "..", Filename = "@alice\\track.mp3" }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task SEARCH_TEXT_Null_Byte_In_Value_Replaced_With_Underscore() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "foo\0bar" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("foo_bar", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_Search_Not_Found() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: null); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_Batch_Has_No_SearchId() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = null }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Empty() + { + // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Whitespace() + { + // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = " " }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_search_text", result); + } + + [Fact] + public async Task SEARCH_TEXT_Traversal_Segments_Do_Not_Survive() + { + var searchId = Guid.NewGuid(); + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, SearchId = searchId }; + var search = new Search { Id = searchId, SearchText = "../evil" }; + var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_External_Id_Is_Empty_String() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.Equal("unknown_batch_external_id", result); + } + + [Fact] + public async Task BATCH_EXTERNAL_ID_Traversal_Segments_Do_Not_Survive() + { + var batchId = Guid.NewGuid(); + var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "../evil" } }; + var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); + + Assert.False(FileSafety.ContainsTraversalSegments(result)); + } + } + + private static (DownloadService service, Mocks mocks) GetFixture( + string subdirectory = "{SOURCE_USERNAME}", + Batch batch = null, + Search search = null) + { + var mocks = new Mocks(subdirectory, batch, search); + var service = new DownloadService( + mocks.BatchService.Object, + mocks.SearchService.Object, + mocks.OptionsMonitor, + null, + new Mock>().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(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>>())) + .ReturnsAsync(batch); + SearchService.Setup(s => s.FindAsync(It.IsAny>>(), It.IsAny())) + .ReturnsAsync(search); + } + + public Mock BatchService { get; } = new(); + public Mock SearchService { get; } = new(); + public TestOptionsMonitor OptionsMonitor { get; } + } +} -- cgit v1.2.3 From 040a31783e874c88e0cd35859253e29e33830ecf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 29 May 2026 19:08:58 -0500 Subject: add destination options --- config/slskd.example.yml | 7 +++++- src/slskd/Core/Options.cs | 63 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 69 insertions(+), 1 deletion(-) (limited to 'src') 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..8123404e 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1028,6 +1028,12 @@ namespace slskd [Validate] public RetryOptions Retry { get; init; } = new RetryOptions(); + /// + /// Gets download destination options. + /// + [Validate] + public DestinationOptions Destination { get; init; } = new DestinationOptions(); + /// /// Download retry options. /// @@ -1057,6 +1063,63 @@ namespace slskd [Enum(typeof(RetryPartialStrategy))] public string Partial { get; init; } = RetryPartialStrategy.Resume.ToString().ToLowerInvariant(); } + + /// + /// Download destination options. + /// + public class DestinationOptions + { + /// + /// Gets the destination subdirectory for the files in the batch. + /// + [RelativePath] + [NonTraversingPath] + [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] + public string Subdirectory { get; init; } = "{SOURCE_DIRECTORY}"; + + /// + /// Gets the strategy for handling conflicting filenames on disk. + /// + [Enum(typeof(DestinationConflictStrategy))] + public string Conflict { get; init; } = DestinationConflictStrategy.Rename.ToString().ToLowerInvariant(); + + /// + /// Gets the permissions to apply to downloaded files and directories. + /// + [Validate] + public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions(); + + /// + /// Download destination permission options. + /// + public class DestinationPermissionsOptions : IValidatableObject + { + /// + /// Gets the permissions to apply to newly created files. + /// + /// + /// Applicable to non-Windows operating systems, only. + /// + public string Mode { get; init; } + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + 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; + } + } + } } /// -- cgit v1.2.3 From 648ef46c787b0ebc96ae205a8b39b3cf5067dad2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 29 May 2026 19:11:13 -0500 Subject: implement subdirectory derivation --- src/slskd/Transfers/Downloads/DownloadService.cs | 208 ++++++++++++++++++++--- 1 file changed, 188 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 013e6a7a..b2435669 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; /// /// Manages downloads. @@ -67,6 +70,26 @@ namespace slskd.Transfers.Downloads /// void AddOrSupersede(Transfer transfer); + /// + /// Derives the destination subdirectory for the specified based on user and batch + /// configuration. + /// + /// + /// + /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments. + /// Otherwise, an instance of will be thrown as a backstop. + /// + /// + /// Empty segments may be present in the output, which more closely aligns with user intent. The + /// method drops them silently, so there's no functional impact. + /// + /// + /// The transfer. + /// The derived destination directory. + /// Thrown if the specified download doesn't exist. + /// Thrown if the derivation logic produces an absolute path, or one with traversal segments. + Task DeriveDestination(Transfer transfer); + /// /// Enqueues the requested list of . /// @@ -165,6 +188,7 @@ namespace slskd.Transfers.Downloads { public DownloadService( IBatchService batchService, + ISearchService searchService, IOptionsMonitor optionsMonitor, ISoulseekClient soulseekClient, IDbContextFactory 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 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(); private IOptionsMonitor OptionsMonitor { get; } private EventBus EventBus { get; } + private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they @@ -707,6 +734,144 @@ namespace slskd.Transfers.Downloads } } + /// + /// Derives the destination subdirectory for the specified based on user and + /// batch configuration. + /// + /// + /// + /// Output is guaranteed to be a localized, sanitized, relative path with no traversal segments. + /// Otherwise, an instance of will be thrown as a backstop. + /// + /// + /// Empty segments may be present in the output, which more closely aligns with user intent. The + /// method drops them silently, so there's no functional impact. + /// + /// + /// The transfer. + /// The derived destination directory. + /// Thrown if the derivation logic produces an absolute path, or one with traversal segments. + public async Task 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: string.IsNullOrWhiteSpace(search?.SearchText) ? "unknown_search_text" : search.SearchText, + replacement: '_'); + } + catch (Exception ex) + { + Log.Error(ex, "Failed fetch information for download {Id}: {Message}", transfer.Id, ex.Message); + throw; + } + + var args = new Dictionary( + 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; + } + /// /// Returns a list of all downloads matching the optional . /// @@ -1045,14 +1210,21 @@ 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), + FileSafety.SanitizePath(transfer.Filename))); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; @@ -1140,22 +1312,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(); Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory); @@ -1163,7 +1331,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); -- cgit v1.2.3 From a77a2d48c22b2287d8ad9125e0f9fa68f45def8b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 15:39:20 -0500 Subject: remove deprecated common extensions --- src/slskd/Common/CommonExtensions.cs | 28 +--------------------- src/slskd/Core/Options.cs | 8 +++---- src/slskd/Relay/RelayClient.cs | 2 +- .../Common/FileSafety/LocalizePathTests.cs | 6 ++--- 4 files changed, 9 insertions(+), 35 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index 4b327a1b..c37c1550 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -409,16 +409,6 @@ namespace slskd return path.Replace('/', '\\'); } - /// - /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). - /// - /// The path to convert. - /// The converted path. - public static string LocalizePath(this string path) - { - return path.Replace('\\', Path.DirectorySeparatorChar).Replace('/', Path.DirectorySeparatorChar); - } - /// /// , but for paths normalized to use backslashes. /// @@ -455,7 +445,7 @@ namespace slskd } // normalize path separators - var localizedRemoteFilename = remoteFilename.LocalizePath(); + var localizedRemoteFilename = FileSafety.LocalizePath(remoteFilename); var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar); @@ -470,22 +460,6 @@ namespace slskd return FileSafety.CombineSafely(directory, file); } - /// - /// Replaces any path traversal segments in the specified with the specified - /// . - /// - /// The path to sanitize. - /// The string with which to replace path traversal segments. - /// The sanitized path. - public static string ReplacePathTraversalSegments(this string path, string replacement = "_") - { - return string.Join(Path.DirectorySeparatorChar, - path - .LocalizePath() - .Split(Path.DirectorySeparatorChar) - .Select(s => s is "." or ".." ? replacement : s)); - } - /// /// Converts a ModelStateDictionary into a human-readable format. /// diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 8123404e..6600cf76 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -832,22 +832,22 @@ namespace slskd var directories = Directories ?? Enumerable.Empty(); - bool IsBlankPath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])$"); + bool IsBlankPath(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])$"); directories?.Where(share => IsBlankPath(share)).ToList() .ForEach(blank => results.Add(new ValidationResult($"Share {blank} does not specify a path"))); - bool IsRootMount(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])/$"); + bool IsRootMount(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])/$"); directories?.Where(share => IsRootMount(share)).ToList() .ForEach(blank => results.Add(new ValidationResult($"Share {blank} specifies a root mount, which is not supported."))); // starts with '/', 'X:', or '\\' - bool IsAbsolutePath(string share) => Regex.IsMatch(share.LocalizePath(), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); + bool IsAbsolutePath(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^(!|-){0,1}(\[.*\])?(\/|[a-zA-Z]:|\\\\).*$"); directories?.Where(share => !IsAbsolutePath(share)).ToList() .ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported."))); // contains /./ or /../ or \.\ or \..\ or ..\ or ../ or \.. or /.. // which is resolved by some OS and will cause weird, unintended side effects - bool ContainsTraversalSegments(string share) => Regex.IsMatch(share.LocalizePath(), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$"); + bool ContainsTraversalSegments(string share) => Regex.IsMatch(FileSafety.LocalizePath(share), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$"); directories?.Where(share => ContainsTraversalSegments(share)).ToList() .ForEach(badPath => results.Add(new ValidationResult($"Share {badPath} contains an unsafe path traversal segment."))); diff --git a/src/slskd/Relay/RelayClient.cs b/src/slskd/Relay/RelayClient.cs index 974ca71e..5c5f9d38 100644 --- a/src/slskd/Relay/RelayClient.cs +++ b/src/slskd/Relay/RelayClient.cs @@ -484,7 +484,7 @@ namespace slskd.Relay // if the controller is Windows and the agent is Linux or vice versa, we need to translate the filename to the // local OS or we're going to get funny results when we go to write the file - destinationFile = destinationFile.LocalizePath(); + destinationFile = FileSafety.LocalizePath(destinationFile); await Retry.Do(task: async () => { diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index 2df3e18f..160f2a72 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -22,7 +22,7 @@ public partial class FileSafetyTests [InlineData("", "")] public void Linux_NormalizesToForwardSlash(string input, string expected) { - var result = input.LocalizePath(OSPlatform.Linux); + var result = FileSafety.LocalizePath(input, OSPlatform.Linux); Assert.Equal(expected, result); } @@ -42,7 +42,7 @@ public partial class FileSafetyTests [InlineData("", "")] public void Windows_NormalizesToBackslash(string input, string expected) { - var result = input.LocalizePath(OSPlatform.Windows); + var result = FileSafety.LocalizePath(input, OSPlatform.Windows); Assert.Equal(expected, result); } @@ -50,7 +50,7 @@ public partial class FileSafetyTests [Fact] public void NullOs_UsesPlatformDefault_DoesNotThrow() { - var result = "foo/bar".LocalizePath(); + var result = FileSafety.LocalizePath("foo/bar"); Assert.False(string.IsNullOrEmpty(result)); } -- cgit v1.2.3 From ebf7c753f385c558cc1442609eaa17d2eb32e6da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 15:40:13 -0500 Subject: add get filename/directory name safely methods, overload sanitizefilename with sanitizePathRoot --- src/slskd/Common/FileSafety.cs | 63 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 63 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index dc27a8b4..93a91faa 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -216,6 +216,54 @@ public static class FileSafety /// True if the path is relative, false otherwise. public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); + /// + /// Returns the filename from the specified , properly + /// handling both forward and backslashes and removing invalid characters. + /// + /// The path from which to extract the filename. + /// An optional value indicating that invalid characters should not be replaced. + /// An optional operating system override, for testing. + /// The extracted filename. + /// Thrown if the specified path is null. + public static string GetFileNameSafely(string path, bool sanitize = true, OSPlatform? os = null) + { + ArgumentNullException.ThrowIfNull(path); + + return LocalizePath(path, os) + .Split(Path.DirectorySeparatorChar) + .TakeLast(1) + .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s) + .Single(); + } + + /// + /// Returns the full directory name from the specified , properly handling both + /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments and sanitizing + /// each of the remaining segments. + /// + /// The path from which to extract the directory name. + /// An optional value indicating that root segments should not be stripped. + /// An optional value indicating that path segments should not be sanitized. + /// An optional operating system override, for testing. + /// The directory name. + /// Thrown if the specified path is null. + public static string GetDirectoryNameSafely(string path, bool stripRoot = true, bool sanitize = true, OSPlatform? os = null) + { + ArgumentNullException.ThrowIfNull(path); + + var local = LocalizePath(path, os: os); + + if (stripRoot) + { + local = StripPathRoot(local); + } + + return string.Join(Path.DirectorySeparatorChar, local + .Split(Path.DirectorySeparatorChar) + .SkipLast(1) + .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s)); + } + /// /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). /// @@ -270,6 +318,21 @@ public static class FileSafety .Replace('\\', replacement); } + /// + /// Sanitizes the specified to make it suitable and safe on the local operating + /// system by stripping all slashes (forward or back) and replacing any invalid characters with the specified + /// . + /// + /// + /// This is an overload for that exists to improve understanding of intent at the + /// call site. + /// + /// The path segment. + /// The character to substitute for invalid characters. + /// An optional operating system override, for testing. + /// The sanitized path segment. + public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) => SanitizeFilename(segment, replacement, os); + /// /// Sanitizes the specified to make it suitable and safe on the local operating system /// by converting to the correct slashes, dropping a root (if present), replacing any invalid characters with -- cgit v1.2.3 From 062d282403cc03c3fdd4101742647be6a83d0329 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 15:40:29 -0500 Subject: extract StripPathRoot --- src/slskd/Common/FileSafety.cs | 23 ++++ .../Common/FileSafety/StripPathRootTests.cs | 150 +++++++++++++++++++++ 2 files changed, 173 insertions(+) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 93a91faa..a175ebbd 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -365,4 +365,27 @@ public static class FileSafety return string.Join(sep, segments); } + + /// + /// Removes the root of the specified , including Window's drive prefix (e.g. C:\), + /// UNC paths on any OS (e.g. \\server on Windows, //server on Linux), and drops the hashed prefix added by + /// Soulseek Qt to hide the path on disk (e.g. @@abcde). + /// + /// The path to strip. + /// An optional operating system override, for testing. + /// The path with the root stripped, if one was present. + public static string StripPathRoot(string path, OSPlatform? os = null) + { + // flip slashes the correct way + path = LocalizePath(path, os); + + // strip C:\ or //server, if present (regardless of slash variant) + path = DriveRootRegex.Replace(path, string.Empty); + path = UncRootRegex.Replace(path, string.Empty); + + // strip @@abcde prefixes used by SoulseekQt to obscure paths + path = SoulseekQtRootRegex.Replace(path, string.Empty); + + return path; + } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs new file mode 100644 index 00000000..f3638c9e --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs @@ -0,0 +1,150 @@ +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class StripPathRootTests + { + [Fact] + public void NullOs_UsesPlatformDefault_DoesNotThrow() + { + var result = FileSafety.StripPathRoot("foo/bar"); + + Assert.NotNull(result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "Music/Artist")] + [InlineData("C:/Music/Artist", "Music/Artist")] + [InlineData("D:\\path\\to\\file", "path/to/file")] + [InlineData("Z:\\", "")] + [InlineData("Z:/", "")] + [InlineData("Z:", "")] // bare drive letter, no separator + [InlineData("c:\\Music", "Music")] // lowercase drive letter + [InlineData("A:/single", "single")] + public void Linux_Strips_DriveRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "Music\\Artist")] + [InlineData("C:/Music/Artist", "Music\\Artist")] + [InlineData("D:\\path\\to\\file", "path\\to\\file")] + [InlineData("Z:\\", "")] + [InlineData("Z:", "")] + [InlineData("c:\\Music", "Music")] + public void Windows_Strips_DriveRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("//server/share/Music", "share/Music")] + [InlineData("//server/Music", "Music")] + [InlineData("//192.168.1.1/share/folder", "share/folder")] + [InlineData("//server", "")] // no path after server + public void Linux_Strips_UncRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\\\server\\share\\Music", "share\\Music")] + [InlineData("\\\\server\\Music", "Music")] + [InlineData("\\\\192.168.1.1\\share\\folder", "share\\folder")] + [InlineData("\\\\server", "")] // no path after server + public void Windows_Strips_UncRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde/Music/Artist", "Music/Artist")] + [InlineData("@@abcdefgh/Music", "Music")] + [InlineData("@@abcde\\Music\\Artist", "Music/Artist")] + public void Linux_Strips_SoulseekQtPrefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde\\Music\\Artist", "Music\\Artist")] + [InlineData("@@abcdefgh\\Music", "Music")] + [InlineData("@@abcde/Music/Artist", "Music\\Artist")] + public void Windows_Strips_SoulseekQtPrefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abc/Music")] // only 3 alphanumeric chars — does not match + [InlineData("@@abcd/Music")] // only 4 — does not match + public void DoesNotStrip_SoulseekQtPrefix_When_Prefix_Too_Short(string input) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.StartsWith("@@", result); + } + + [Theory] + [InlineData("Music/Artist", "Music/Artist")] + [InlineData("Artist/Album/song.flac", "Artist/Album/song.flac")] + [InlineData("just_a_filename.flac", "just_a_filename.flac")] + [InlineData("", "")] + [InlineData("foo", "foo")] + public void Linux_ReturnsUnchanged_Given_Relative_Path(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("Music\\Artist", "Music\\Artist")] + [InlineData("Artist\\Album\\song.flac", "Artist\\Album\\song.flac")] + [InlineData("just_a_filename.flac", "just_a_filename.flac")] + [InlineData("foo", "foo")] + public void Windows_ReturnsUnchanged_Given_Relative_Path(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("/home/user/Music", "/home/user/Music")] + [InlineData("/Music", "/Music")] + [InlineData("/single", "/single")] + public void Linux_ReturnsUnchanged_Given_Single_ForwardSlash_Prefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\Music", "\\Music")] + [InlineData("\\home\\user", "\\home\\user")] + public void Windows_ReturnsUnchanged_Given_Single_BackwardSlash_Prefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + } +} -- cgit v1.2.3 From 012b429f11d6c0247fa90a74c0367a112d45a84c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 16:00:35 -0500 Subject: add SanitizePathSegment --- src/slskd/Common/FileSafety.cs | 27 ++++-- .../Common/FileSafety/SanitizePathSegmentTests.cs | 99 ++++++++++++++++++++++ 2 files changed, 121 insertions(+), 5 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index a175ebbd..7e8c3516 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -323,15 +323,32 @@ public static class FileSafety /// system by stripping all slashes (forward or back) and replacing any invalid characters with the specified /// . /// - /// - /// This is an overload for that exists to improve understanding of intent at the - /// call site. - /// /// The path segment. /// The character to substitute for invalid characters. /// An optional operating system override, for testing. /// The sanitized path segment. - public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) => SanitizeFilename(segment, replacement, os); + public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) + { + var sanitized = SanitizeFilename(segment, replacement, os); + + // is is possible for the result of sanitization to produce path traversal strings, + // which would result in traversal when combined (or throw an error because of CombineSafely) + // this can happen either because the segment is already periods, or because the replacement + // character is a period and the input one or two invalid characters. + // if this happens we follow the principle of least surprise and return an empty string + // avoid using a period for replacement (don't let users choose) and we won't have this problem + if (sanitized is "." or "..") + { + if (replacement is '.') + { + return string.Empty; + } + + return replacement.ToString(); + } + + return sanitized; + } /// /// Sanitizes the specified to make it suitable and safe on the local operating system diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs new file mode 100644 index 00000000..72e6a21b --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -0,0 +1,99 @@ +using System; +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class SanitizePathSegmentTests + { + [Theory] + [InlineData('/')] + [InlineData('\\')] + public void Throws_Given_Slash_As_Replacement(char replacement) + { + var ex = Record.Exception(() => FileSafety.SanitizePathSegment("segment", replacement)); + + Assert.NotNull(ex); + Assert.IsType(ex); + Assert.Contains("invalid in filenames", ex.Message); + } + + [Theory] + [InlineData(".")] + [InlineData("..")] + public void Replaces_Traversal_Segments_With_Replacement(string input) + { + var s = FileSafety.SanitizePathSegment(input, '_'); + + Assert.Equal("_", s); + } + + [Theory] + [InlineData(".")] + [InlineData("..")] + public void Returns_Empty_String_When_Replacement_Is_Period_And_Result_Would_Be_Traversal(string input) + { + var s = FileSafety.SanitizePathSegment(input, '.'); + + Assert.Equal("", s); + } + + [Theory] + [InlineData("a.")] + [InlineData("..b")] + [InlineData("c..d")] + public void Preserves_Periods_In_Segment_If_Not_Traversal(string input) + { + var s = FileSafety.SanitizePathSegment(input, '_'); + + Assert.Equal(input, s); + } + + [Fact] + public void Respects_Replacement_Character() + { + var s = FileSafety.SanitizePathSegment("???", replacement: '!'); + + Assert.Equal("!!!", s); + } + + [Theory] + [InlineData("clean", "clean")] + [InlineData("Artist - Album", "Artist - Album")] + [InlineData("Ünïcödé", "Ünïcödé")] + [InlineData("пользователь", "пользователь")] + public void Linux_ReturnsUnchanged_Given_Safe_Segment(string input, string expected) + { + var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("has/slash", "has_slash")] + [InlineData("has\\backslash", "has_backslash")] + [InlineData("has/both\\types", "has_both_types")] + public void Linux_Replaces_Slashes(string input, string expected) + { + var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("file:name", "file_name")] + [InlineData("file*name", "file_name")] + [InlineData("file?name", "file_name")] + [InlineData("file\"name", "file_name")] + [InlineData("file/name", "file_name")] + [InlineData("file\\name", "file_name")] + public void Windows_Replaces_InvalidCharacters(string input, string expected) + { + var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Windows); + + Assert.Equal(expected, result); + } + } +} -- cgit v1.2.3 From 64db0b76b4a7f3242887d81b18414b8983a0d888 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 16:15:53 -0500 Subject: rename 'conflict' option to 'exists' --- config/slskd.example.yml | 2 +- src/slskd/Core/Options.cs | 6 +-- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +- .../Transfers/Types/DestinationConflictStrategy.cs | 49 ---------------------- .../Transfers/Types/DestinationExistsStrategy.cs | 49 ++++++++++++++++++++++ 5 files changed, 55 insertions(+), 55 deletions(-) delete mode 100644 src/slskd/Transfers/Types/DestinationConflictStrategy.cs create mode 100644 src/slskd/Transfers/Types/DestinationExistsStrategy.cs (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index d295b964..b66879e3 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -80,7 +80,7 @@ # max_delay: 60000 # maximum time between retries, in milliseconds # destination: # subdirectory: {SOURCE_DIRECTORY} -# conflict: rename # 'overwrite' or 'rename' +# exists: rename # 'overwrite' or 'rename' # permissions: # mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # groups: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 6600cf76..4e7dca7b 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1078,10 +1078,10 @@ namespace slskd public string Subdirectory { get; init; } = "{SOURCE_DIRECTORY}"; /// - /// Gets the strategy for handling conflicting filenames on disk. + /// Gets the strategy for handling existing files on disk. /// - [Enum(typeof(DestinationConflictStrategy))] - public string Conflict { get; init; } = DestinationConflictStrategy.Rename.ToString().ToLowerInvariant(); + [Enum(typeof(DestinationExistsStrategy))] + public string Exists { get; init; } = DestinationExistsStrategy.Rename.ToString().ToLowerInvariant(); /// /// Gets the permissions to apply to downloaded files and directories. diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index b2435669..d09bb71b 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1323,7 +1323,7 @@ namespace slskd.Transfers.Downloads var subdirectory = await DeriveDestination(transfer); var destinationDirectory = FileSafety.CombineSafely(OptionsMonitor.CurrentValue.Directories.Downloads, subdirectory); - var conflictStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Conflict.ToEnum(); + var existsStrategy = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Exists.ToEnum(); Log.Debug("Destination directory for {Filename}: {Destination}", transfer.Filename, destinationDirectory); @@ -1331,7 +1331,7 @@ namespace slskd.Transfers.Downloads sourceFilename: incompleteFilename, destinationDirectory: destinationDirectory, unixFileMode: unixFileMode, - overwrite: conflictStrategy == DestinationConflictStrategy.Overwrite, + overwrite: existsStrategy == DestinationExistsStrategy.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 deleted file mode 100644 index 27281a2d..00000000 --- a/src/slskd/Transfers/Types/DestinationConflictStrategy.cs +++ /dev/null @@ -1,49 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ 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 -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Transfers; - -/// -/// Strategy for handling downloaded files with conflicting names. -/// -public enum DestinationConflictStrategy -{ - /// - /// Rename the new file by appending something. - /// - Rename = 0, - - /// - /// Overwrite the existing file. - /// - Overwrite = 1, -} \ No newline at end of file diff --git a/src/slskd/Transfers/Types/DestinationExistsStrategy.cs b/src/slskd/Transfers/Types/DestinationExistsStrategy.cs new file mode 100644 index 00000000..18837563 --- /dev/null +++ b/src/slskd/Transfers/Types/DestinationExistsStrategy.cs @@ -0,0 +1,49 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Transfers; + +/// +/// Strategy for handling downloaded files when the destination file already exists. +/// +public enum DestinationExistsStrategy +{ + /// + /// Rename the new file by appending something to the file name. + /// + Rename = 0, + + /// + /// Overwrite the existing file. + /// + Overwrite = 1, +} \ No newline at end of file -- cgit v1.2.3 From ba3d4690e132a966567db40c8b778c5ed3922833 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 18:24:27 -0500 Subject: paths ending in a slash don't have a file --- src/slskd/Common/FileSafety.cs | 5 +++++ 1 file changed, 5 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 7e8c3516..6c1ce8b6 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -229,6 +229,11 @@ public static class FileSafety { ArgumentNullException.ThrowIfNull(path); + if (path.EndsWith('/') || path.EndsWith('\\')) + { + return null; + } + return LocalizePath(path, os) .Split(Path.DirectorySeparatorChar) .TakeLast(1) -- cgit v1.2.3 From b52215184538991dfe1012c1017437edeb2e7b70 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 18:24:50 -0500 Subject: remove the option to strip the root when getting directory --- src/slskd/Common/FileSafety.cs | 8 +------- 1 file changed, 1 insertion(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 6c1ce8b6..acbe273b 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -247,22 +247,16 @@ public static class FileSafety /// each of the remaining segments. /// /// The path from which to extract the directory name. - /// An optional value indicating that root segments should not be stripped. /// An optional value indicating that path segments should not be sanitized. /// An optional operating system override, for testing. /// The directory name. /// Thrown if the specified path is null. - public static string GetDirectoryNameSafely(string path, bool stripRoot = true, bool sanitize = true, OSPlatform? os = null) + public static string GetDirectoryNameSafely(string path, bool sanitize = true, OSPlatform? os = null) { ArgumentNullException.ThrowIfNull(path); var local = LocalizePath(path, os: os); - if (stripRoot) - { - local = StripPathRoot(local); - } - return string.Join(Path.DirectorySeparatorChar, local .Split(Path.DirectorySeparatorChar) .SkipLast(1) -- cgit v1.2.3 From 957dd89b04e941a17efb76dbfa439a2a0f5157ad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 18:34:27 -0500 Subject: more tests, make root stripping optional --- src/slskd/Common/FileSafety.cs | 22 +++-- .../FileSafety/GetDirectoryNameSafelyTests.cs | 90 ++++++++++++++++++++ .../Common/FileSafety/GetFileNameSafelyTests.cs | 96 ++++++++++++++++++++++ .../Common/FileSafety/SanitizePathTests.cs | 30 +++---- 4 files changed, 214 insertions(+), 24 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index acbe273b..dcdaa00a 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -269,7 +269,7 @@ public static class FileSafety /// The path to convert. /// An optional operating system override, for testing. /// The converted path. - public static string LocalizePath(this string path, OSPlatform? os = null) + public static string LocalizePath(string path, OSPlatform? os = null) { os ??= Compute.OSPlatform(); @@ -281,7 +281,7 @@ public static class FileSafety /// /// Sanitizes the specified (or string intended to be used as or as part of a filename) /// to make it suitable and safe on the local operating system by stripping all slashes (forward or back) and - /// and replacing any invalid characters with the specified . + /// replacing any invalid characters with the specified . /// /// The filename (or string intended to be used as/part of one). /// The character to substitute for invalid characters. @@ -356,22 +356,26 @@ public static class FileSafety /// /// The path. /// The character to substitute for invalid characters. + /// An optional value indicating whether to keep the path's root, if present. /// An optional operating system override, for testing. /// The sanitized path. - public static string SanitizePath(this string path, char replacement = '_', OSPlatform? os = null) + public static string SanitizePath(string path, char replacement = '_', bool retainRoot = false, OSPlatform? os = null) { os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; // flip slashes the correct way - path = path.LocalizePath(os); + path = LocalizePath(path, os); - // strip C:\ or //server, if present (regardless of slash variant, etc) - path = DriveRootRegex.Replace(path, string.Empty); - path = UncRootRegex.Replace(path, string.Empty); + if (!retainRoot) + { + // strip C:\ or //server, if present (regardless of slash variant, etc) + path = DriveRootRegex.Replace(path, string.Empty); + path = UncRootRegex.Replace(path, string.Empty); - // strip @@abcde prefixes used by SoulseekQt to obscure paths - path = SoulseekQtRootRegex.Replace(path, string.Empty); + // strip @@abcde prefixes used by SoulseekQt to obscure paths + path = SoulseekQtRootRegex.Replace(path, string.Empty); + } // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs new file mode 100644 index 00000000..fd78fcaa --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -0,0 +1,90 @@ +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class GetDirectoryNameSafelyTests + { + [Fact] + public void Throws_Given_Null() + { + var ex = Record.Exception(() => FileSafety.GetDirectoryNameSafely(null)); + + Assert.NotNull(ex); + } + + [Fact] + public void Returns_Empty_Given_Empty() + { + var result = FileSafety.GetDirectoryNameSafely(""); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("foo")] + [InlineData("foo.bar")] + public void Returns_Empty_Given_Bare_File(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("C:")] // bare drive letter — StripPathRoot removes it, nothing left + [InlineData("C:\\")] // drive root with trailing backslash + [InlineData("C:/")] // drive root with trailing forward slash + [InlineData("/")] // Unix-style root — no double-slash, not stripped; splits to ["", ""] + [InlineData("\\")] // single backslash root + [InlineData("//server")] // UNC root — StripPathRoot removes server, nothing left + [InlineData("\\\\server")] // UNC root, backslashes + public void Returns_Empty_Given_Root(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("foo\\bar", "foo")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "Music")] + [InlineData("C:/Music/song.flac", "Music")] + [InlineData("C:\\Music\\Artist\\song.flac", "Music\\Artist")] + [InlineData("//server/share/song.flac", "share")] + [InlineData("\\\\server\\share\\song.flac", "share")] + public void Returns_Directory_Given_Path_With_File(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Equal(expected, result); + } + + [Fact] + public void Sanitize_True_Replaces_InvalidCharacters_In_Segments() + { + var result = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: true); + + Assert.Equal("Music_\\Artist", result); + } + + [Fact] + public void Sanitize_False_Preserves_InvalidCharacters_In_Segments() + { + var result = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: false); + + Assert.Equal("Music*\\Artist", result); + } + + [Fact] + public void Default_Sanitize_Is_True() + { + var resultDefault = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac"); + var resultExplicit = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: true); + + Assert.Equal(resultExplicit, resultDefault); + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs new file mode 100644 index 00000000..a25da89b --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs @@ -0,0 +1,96 @@ +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class GetFileNameSafelyTests + { + [Fact] + public void Throws_Given_Null() + { + var ex = Record.Exception(() => FileSafety.GetFileNameSafely(null)); + + Assert.NotNull(ex); + } + + [Fact] + public void Returns_Empty_Given_Empty() + { + var result = FileSafety.GetFileNameSafely(""); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("/")] + [InlineData("\\")] + [InlineData("C:\\")] + [InlineData("C:/")] + [InlineData("//")] + [InlineData("\\\\")] + [InlineData("foo\\")] + [InlineData("foo//")] + [InlineData("C:\\foo//bar\\")] + [InlineData("C:/foo\\bar/")] + public void Returns_Empty_Given_Path_Ending_In_Separator(string input) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("//server", "server")] + [InlineData("\\\\server", "server")] + public void Returns_LastSegment_Given_UncRoot(string input, string expected) + { + // StripPathRoot is not called; the last segment of the localized + split path is returned + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo", "foo")] + [InlineData("foo.bar", "foo.bar")] + [InlineData("foo\\bar", "bar")] + [InlineData("foo/bar", "bar")] + [InlineData("C:\\Music\\song.flac", "song.flac")] + [InlineData("C:/Music/song.flac", "song.flac")] + [InlineData("Music\\Artist\\song.flac", "song.flac")] + [InlineData("//server/share/song.flac", "song.flac")] + [InlineData("\\\\server\\share\\song.flac", "song.flac")] + public void Returns_Filename_Given_Path_With_File(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(expected, result); + } + + [Fact] + public void Sanitize_True_Replaces_InvalidCharacters() + { + var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true); + + Assert.Equal("file_name.flac", result); + } + + [Fact] + public void Sanitize_False_Preserves_InvalidCharacters() + { + var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: false); + + Assert.Equal("file:name.flac", result); + } + + [Fact] + public void Default_Sanitize_Is_True() + { + var resultDefault = FileSafety.GetFileNameSafely("Music\\file:name.flac"); + var resultExplicit = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true); + + Assert.Equal(resultExplicit, resultDefault); + } + } +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index ea5b8538..2f712334 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -10,7 +10,7 @@ public partial class FileSafetyTests [Fact] public void NullOs_UsesPlatformDefault_DoesNotThrow() { - var result = "foo/bar".SanitizePath(); + var result = FileSafety.SanitizePath("foo/bar"); Assert.NotNull(result); } @@ -22,7 +22,7 @@ public partial class FileSafetyTests [InlineData("Ünïcödé/пользователь", "Ünïcödé/пользователь")] public void Linux_NormalizesSlashes(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -33,7 +33,7 @@ public partial class FileSafetyTests [InlineData("Artist/Album/song.flac", "Artist\\Album\\song.flac")] public void Windows_NormalizesSlashes(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -45,7 +45,7 @@ public partial class FileSafetyTests [InlineData("Z:\\", "")] public void Windows_Strips_DriveRoot(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -56,7 +56,7 @@ public partial class FileSafetyTests [InlineData("D:\\path", "path")] public void Linux_Strips_DriveRoot(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -67,7 +67,7 @@ public partial class FileSafetyTests [InlineData("\\\\192.168.1.1\\share\\folder", "share\\folder")] public void Windows_Strips_UncRoot(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -78,7 +78,7 @@ public partial class FileSafetyTests [InlineData("//192.168.1.1/share/folder", "share/folder")] public void Linux_Strips_UncRoot(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -89,7 +89,7 @@ public partial class FileSafetyTests [InlineData("@@abcde\\Music\\Artist", "Music/Artist")] public void Linux_Strips_SoulseekQtPrefix(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -100,7 +100,7 @@ public partial class FileSafetyTests [InlineData("@@abcde/Music/Artist", "Music\\Artist")] public void Windows_Strips_SoulseekQtPrefix(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -110,7 +110,7 @@ public partial class FileSafetyTests [InlineData("@@abcd/Music")] // only 4 — does not match public void DoesNotStrip_SoulseekQtPrefix_When_Prefix_Too_Short(string input) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.StartsWith("@@", result); } @@ -124,7 +124,7 @@ public partial class FileSafetyTests [InlineData("foo/.", "foo/_")] public void Linux_Replaces_TraversalSegments(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); Assert.Equal(expected, result); } @@ -135,7 +135,7 @@ public partial class FileSafetyTests [InlineData("..\\etc", "_\\etc")] public void Windows_Replaces_TraversalSegments(string input, string expected) { - var result = input.SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); Assert.Equal(expected, result); } @@ -143,7 +143,7 @@ public partial class FileSafetyTests [Fact] public void Linux_Replaces_InvalidFilenameChars_In_Segments() { - var result = "seg\0ment/file\0name".SanitizePath(os: OSPlatform.Linux); + var result = FileSafety.SanitizePath("seg\0ment/file\0name", os: OSPlatform.Linux); Assert.Equal("seg_ment/file_name", result); } @@ -151,7 +151,7 @@ public partial class FileSafetyTests [Fact] public void Windows_Replaces_InvalidFilenameChars_In_Segments() { - var result = "seg*ment\\file:name".SanitizePath(os: OSPlatform.Windows); + var result = FileSafety.SanitizePath("seg*ment\\file:name", os: OSPlatform.Windows); Assert.Equal("seg_ment\\file_name", result); } @@ -159,7 +159,7 @@ public partial class FileSafetyTests [Fact] public void Uses_Custom_Replacement() { - var result = "foo/../bar".SanitizePath(replacement: '-', os: OSPlatform.Linux); + var result = FileSafety.SanitizePath("foo/../bar", replacement: '-', os: OSPlatform.Linux); Assert.Equal("foo/-/bar", result); } -- cgit v1.2.3 From bebeb114426e717596b1cf485e358eae65cb08e0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 30 May 2026 18:35:15 -0500 Subject: use full sanitized path for incomplete files --- src/slskd/Transfers/Downloads/DownloadService.cs | 55 +++++++++++++++++------- 1 file changed, 39 insertions(+), 16 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index d09bb71b..ee7f2efd 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -802,11 +802,13 @@ namespace slskd.Transfers.Downloads 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('/', '\\'); + // full remote path, e.g. '@@abcd\Foo\Bar\Baz\Qux.ext' => '@@abcd\Foo\Bar\Baz' + // retains the path root, if there is one (Soulseek NS does this), which may not be what + // people want, so possibly revisit and add StripPathRoot() + source_path = (FileSafety.GetDirectoryNameSafely(filename) ?? string.Empty).TrimEnd('/', '\\'); // name of the remote parent directory, so using the example above, 'Baz' - source_directory = (Path.GetFileName(source_path) ?? string.Empty).TrimEnd('/', '\\'); + source_directory = (FileSafety.GetFileNameSafely(source_path) ?? string.Empty).TrimEnd('/', '\\'); batch_id = (batch?.Id ?? Guid.Empty) == Guid.Empty ? "unknown_batch_id" : batch.Id.ToString(); @@ -859,13 +861,13 @@ namespace slskd.Transfers.Downloads 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 }); + Log.Debug("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text }); // the only way to get here is through a regression in the logic above; if we are seeing this, ensure we are // properly sanitizing the final output to strip leading slashes and replace traversal segments if (FileSafety.IsPathAbsolute(destination) || FileSafety.ContainsTraversalSegments(destination)) { - Log.Error("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", 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 }); + Log.Error("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text }); throw new SlskdException("Derived a transfer destination that is either not relative or contains traversal segments; neither is allowed. Please report this on GitHub."); } @@ -1214,17 +1216,38 @@ namespace slskd.Transfers.Downloads ? 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. 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, - FileSafety.SanitizeFilename(transfer.Username), - FileSafety.SanitizePath(transfer.Filename))); + /* + store incomplete files under a username subdirectory to prevent collisions between users and to make + it safe to resume partial downloads without risking picking up an unrelated file. + + we're going to store the file as: + + /// + + so, a remote file 'C:\Music\Public_Domain\Foo\Bar\Baz.ext' from user 'FooBar' becomes: + + linux: incomplete/C:/FooBar/Music/Public_Domain/Foo/Bar/Baz.ext + windows: incomplete\C_\FooBar\Music\Public_Domain\Foo\Bar\Baz.ext + + slashes are normalized to the current OS and any invalid characters are replaced with an underscore, _. + this mitigates the risk of an improper partial resume to a great extent. + + if the remote file changes size between attempts, Soulseek.NET's DownloadAsync() will throw because + the size we send originates from the original file, and there will be a mismatch. + + the only remaining risk is in a case where the file contents have changed but the size remains the same. + the resulting file will be corrupted in that case, and there's nothing we can really do about it. users + that are concerned about this (extremely unlikely) case should configure slskd to always overwrite + partial files. + */ + var incompleteDirectory = OptionsMonitor.CurrentValue.Directories.Incomplete; + var sanitizedUsername = FileSafety.SanitizePathSegment(transfer.Username); + var sanitizedFilename = FileSafety.GetFileNameSafely(transfer.Filename, sanitize: true); + var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true); + + var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename); + + Log.Warning("Incomplete file for {Filename} from {Username} will be: {Filename}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; -- cgit v1.2.3 From 3003f80c16af1d551b9d6e484c566c7d69c061a9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:52:50 -0500 Subject: make slskqt regex slash optional --- src/slskd/Common/FileSafety.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index dcdaa00a..479f7834 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -62,7 +62,7 @@ public static class FileSafety private static readonly Regex DriveRootRegex = new(@"^[a-zA-Z]:[/\\]?", RegexOptions.Compiled); // C: or C:\ private static readonly Regex UncRootRegex = new(@"^[/\\]{2}[^/\\]+[/\\]?", RegexOptions.Compiled); // \\server[\] or //server[/], any slash variants - private static readonly Regex SoulseekQtRootRegex = new(@"^@@[a-zA-Z0-9]{5,}[\/\\]", RegexOptions.Compiled); // @@abcde[\|/], a Soulseek Qt share prefix + private static readonly Regex SoulseekQtRootRegex = new(@"^@@[a-zA-Z0-9]{5,}[\/\\]?", RegexOptions.Compiled); // @@abcde[\|/], a Soulseek Qt share prefix /// /// An alternative to that disallows rooted segments in the second or -- cgit v1.2.3 From 058b02ea093f4d7867441d055bef2b857eb98dd0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:54:01 -0500 Subject: always split by both slashes --- src/slskd/Common/FileSafety.cs | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 479f7834..ebd9a69c 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -130,7 +130,7 @@ public static class FileSafety } } - var parts = segment.Split(Path.DirectorySeparatorChar, '\\', '/'); + var parts = segment.Split('\\', '/'); // 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 @@ -234,8 +234,7 @@ public static class FileSafety return null; } - return LocalizePath(path, os) - .Split(Path.DirectorySeparatorChar) + var segments = localPath.Split('/', '\\'); .TakeLast(1) .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s) .Single(); @@ -258,7 +257,7 @@ public static class FileSafety var local = LocalizePath(path, os: os); return string.Join(Path.DirectorySeparatorChar, local - .Split(Path.DirectorySeparatorChar) + .Split('/', '\\') .SkipLast(1) .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s)); } @@ -379,7 +378,7 @@ public static class FileSafety // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path - .Split(sep) + .Split('/', '\\') .Select(s => SanitizeFilename(s, replacement, os)) .Select(s => s is "." or ".." ? replacement.ToString() : s); -- cgit v1.2.3 From 2926ef6ee1c9151d72ae9ab5d713630b299224ed Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:54:32 -0500 Subject: use method instead of inline --- src/slskd/Common/FileSafety.cs | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index ebd9a69c..011a7a70 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -369,11 +369,7 @@ public static class FileSafety if (!retainRoot) { // strip C:\ or //server, if present (regardless of slash variant, etc) - path = DriveRootRegex.Replace(path, string.Empty); - path = UncRootRegex.Replace(path, string.Empty); - - // strip @@abcde prefixes used by SoulseekQt to obscure paths - path = SoulseekQtRootRegex.Replace(path, string.Empty); + path = StripPathRoot(path); } // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings -- cgit v1.2.3 From 3e52de31aad47a3a333c64ef1b68f8abcf726fe8 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 14:55:07 -0500 Subject: fix GetFileNameSafely test cases --- src/slskd/Common/FileSafety.cs | 13 +++++++++---- 1 file changed, 9 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 011a7a70..9c8fac74 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -224,17 +224,22 @@ public static class FileSafety /// An optional value indicating that invalid characters should not be replaced. /// An optional operating system override, for testing. /// The extracted filename. - /// Thrown if the specified path is null. public static string GetFileNameSafely(string path, bool sanitize = true, OSPlatform? os = null) { - ArgumentNullException.ThrowIfNull(path); + if (path is null or "" || path.EndsWith('/') || path.EndsWith('\\')) + { + return null; + } - if (path.EndsWith('/') || path.EndsWith('\\')) + if (StripPathRoot(path, os) == string.Empty) { return null; } + var localPath = LocalizePath(path, os); var segments = localPath.Split('/', '\\'); + + return segments .TakeLast(1) .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s) .Single(); @@ -254,7 +259,7 @@ public static class FileSafety { ArgumentNullException.ThrowIfNull(path); - var local = LocalizePath(path, os: os); + var local = LocalizePath(path, os); return string.Join(Path.DirectorySeparatorChar, local .Split('/', '\\') -- cgit v1.2.3 From 046c60b817144b46d82c4311d166e6ba78062a90 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 17:48:57 -0500 Subject: i want to be done with this --- src/slskd/Common/FileSafety.cs | 60 ++++++-- .../Common/FileSafety/CombineSafelyTests.cs | 3 + .../FileSafety/GetDirectoryNameSafelyTests.cs | 151 +++++++++++++++++---- .../Common/FileSafety/SanitizePathSegmentTests.cs | 2 +- 4 files changed, 180 insertions(+), 36 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 9c8fac74..1fff4b08 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -241,7 +241,7 @@ public static class FileSafety return segments .TakeLast(1) - .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s) + .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s) .Single(); } @@ -251,20 +251,63 @@ public static class FileSafety /// each of the remaining segments. /// /// The path from which to extract the directory name. + /// An optional value indicating whether to keep the path's root, if present. /// An optional value indicating that path segments should not be sanitized. /// An optional operating system override, for testing. /// The directory name. /// Thrown if the specified path is null. - public static string GetDirectoryNameSafely(string path, bool sanitize = true, OSPlatform? os = null) + public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OSPlatform? os = null) { - ArgumentNullException.ThrowIfNull(path); + if (path is null or "") + { + return null; + } + + // a plain string is assumed to be a file. matches the behavior of the BCL method + if (!path.Contains('/') && !path.Contains('\\')) + { + return null; + } + + var isUNC = path.StartsWith("//") || path.StartsWith("\\\\"); + + os ??= Compute.OSPlatform(); + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + var local = LocalizePath(path, os) + .TrimEnd('/', '\\'); // treat file-less paths the same as files + + var unrooted = StripPathRoot(local, os); - var local = LocalizePath(path, os); + // were given a root; C:\, //server, @@abcde + if (unrooted is null or "") + { + return null; + } + + if (!retainRoot) + { + local = unrooted; + } - return string.Join(Path.DirectorySeparatorChar, local + // strip empty segments + var segments = local .Split('/', '\\') + .Where(s => s is not "") + .ToArray(); + + // we were given all slashes, a file in the root, or some other case where + // only a file or subdirectory remains; no parent directory + if (segments.Length <= 1) + { + return null; + } + + var newPath = string.Join(sep, segments .SkipLast(1) - .Select(s => sanitize == true ? SanitizePathSegment(s, os: os) : s)); + .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s)); + + return (retainRoot && isUNC) ? $"{sep}{sep}{newPath}" : newPath; } /// @@ -276,7 +319,6 @@ public static class FileSafety public static string LocalizePath(string path, OSPlatform? os = null) { os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; return path.Replace('\\', sep).Replace('/', sep); @@ -380,8 +422,8 @@ public static class FileSafety // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path .Split('/', '\\') - .Select(s => SanitizeFilename(s, replacement, os)) - .Select(s => s is "." or ".." ? replacement.ToString() : s); + .Where(s => s is not "") + .Select(s => SanitizePathSegment(s, replacement, os)); return string.Join(sep, segments); } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index 2d496c4b..0ffa0129 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -103,6 +103,9 @@ public partial class FileSafetyTests [InlineData("用户/音乐")] [InlineData("ユーザー/音楽")] [InlineData("사용자/음악")] + [InlineData("foo\\bar\\baz\\qux\\deeply\\nested")] + [InlineData("foo/bar/baz/qux/deeply/nested")] + [InlineData("foo/bar\\baz/qux\\deeply/nested")] public void Combines_Safe_Segments(string segment) { var result = FileSafety.CombineSafely(Base, segment); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs index fd78fcaa..07e4d485 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -1,3 +1,4 @@ +using System.Runtime.InteropServices; using Xunit; namespace slskd.Tests.Unit.Common; @@ -7,29 +8,29 @@ public partial class FileSafetyTests public class GetDirectoryNameSafelyTests { [Fact] - public void Throws_Given_Null() + public void Returns_Null_Given_Null() { - var ex = Record.Exception(() => FileSafety.GetDirectoryNameSafely(null)); + var result = FileSafety.GetDirectoryNameSafely(null); - Assert.NotNull(ex); + Assert.Null(result); } [Fact] - public void Returns_Empty_Given_Empty() + public void Returns_Null_Given_Empty() { var result = FileSafety.GetDirectoryNameSafely(""); - Assert.Equal(string.Empty, result); + Assert.Null(result); } [Theory] [InlineData("foo")] [InlineData("foo.bar")] - public void Returns_Empty_Given_Bare_File(string input) + public void Returns_Null_Given_Bare_File(string input) { var result = FileSafety.GetDirectoryNameSafely(input); - Assert.Equal(string.Empty, result); + Assert.Null(result); } [Theory] @@ -40,51 +41,149 @@ public partial class FileSafetyTests [InlineData("\\")] // single backslash root [InlineData("//server")] // UNC root — StripPathRoot removes server, nothing left [InlineData("\\\\server")] // UNC root, backslashes - public void Returns_Empty_Given_Root(string input) + public void Returns_Null_Given_Root(string input) { var result = FileSafety.GetDirectoryNameSafely(input); - Assert.Equal(string.Empty, result); + Assert.Null(result); + } + + [Fact] + public void Sanitizes_Path_When_Sanitize_True() + { + var result = FileSafety.GetDirectoryNameSafely("foo/b\0ar/baz", sanitize: true); + + Assert.DoesNotContain('\0', result); + } + + [Fact] + public void Does_Not_Sanitize_Path_When_Sanitize_False() + { + var result = FileSafety.GetDirectoryNameSafely("foo/b\0ar/baz", sanitize: false); + + Assert.Contains('\0', result); + } + + [Fact] + public void Sanitize_Defaults_To_True() + { + var result = FileSafety.GetDirectoryNameSafely("foo/b\0ar/baz"); + + Assert.DoesNotContain('\0', result); } [Theory] - [InlineData("foo\\bar", "foo")] + [InlineData("\\foo\\\\bar\\\\baz", "foo\\bar")] + [InlineData("/foo//bar//baz", "foo\\bar")] + public void Removes_Empty_Segments_And_Leading_Slashes_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\foo\\\\bar\\\\baz", "foo/bar")] + [InlineData("/foo//bar//baz", "foo/bar")] + public void Removes_Empty_Segments_And_Leading_Slashes_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o\\bar", "fo_o")] [InlineData("foo/bar", "foo")] [InlineData("C:\\Music\\song.flac", "Music")] [InlineData("C:/Music/song.flac", "Music")] - [InlineData("C:\\Music\\Artist\\song.flac", "Music\\Artist")] + [InlineData("C:\\M\0usic\\Artist\\song.flac", "M_usic/Artist")] + [InlineData("C:\\foo.txt", null)] [InlineData("//server/share/song.flac", "share")] [InlineData("\\\\server\\share\\song.flac", "share")] - public void Returns_Directory_Given_Path_With_File(string input, string expected) + [InlineData("@@abcde\\foo\\bar", "foo")] + public void Returns_Unrooted_Sanitized_Directory_Given_Path_With_File_Linux(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely(input); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Linux); Assert.Equal(expected, result); } - [Fact] - public void Sanitize_True_Replaces_InvalidCharacters_In_Segments() + [Theory] + [InlineData("fo\0o\\bar", "fo_o")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "Music")] + [InlineData("C:/Music/song.flac", "Music")] + [InlineData("C:\\M\0usic\\Artist\\song.flac", "M_usic\\Artist")] + [InlineData("C:\\foo.txt", null)] + [InlineData("//server/share/song.flac", "share")] + [InlineData("\\\\server\\share\\song.flac", "share")] + [InlineData("@@abcde\\foo\\bar", "foo")] + public void Returns_Unrooted_Sanitized_Directory_Given_Path_With_File_Windows(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: true); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Windows); - Assert.Equal("Music_\\Artist", result); + Assert.Equal(expected, result); } - [Fact] - public void Sanitize_False_Preserves_InvalidCharacters_In_Segments() + [Theory] + [InlineData("foo\\bar", "foo")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "C_\\Music")] + [InlineData("C:/Music/song.flac", "C_\\Music")] + [InlineData("C:\\Music\\Artist\\song.flac", "C_\\Music\\Artist")] + [InlineData("//server/share/song.flac", "\\\\server\\share")] + [InlineData("\\\\server\\share\\song.flac", "\\\\server\\share")] + [InlineData("@@abcde\\foo\\bar", "@@abcde\\foo")] + public void Retains_Path_Root_When_RetainRoot_True_Windows(string input, string expected) { - var result = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: false); + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Windows); - Assert.Equal("Music*\\Artist", result); + Assert.Equal(expected, result); } - [Fact] - public void Default_Sanitize_Is_True() + [Theory] + [InlineData("foo\\bar", "foo")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "C:/Music")] + [InlineData("C:/Music/song.flac", "C:/Music")] + [InlineData("C:\\Music\\Artist\\song.flac", "C:/Music/Artist")] + [InlineData("//server/share/song.flac", "//server/share")] + [InlineData("\\\\server\\share\\song.flac", "//server/share")] + [InlineData("@@abcde\\foo\\bar", "@@abcde/foo")] + public void Retains_Path_Root_When_RetainRoot_True_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Mu\0sic\\song.flac", "C:\\Mu\0sic")] + [InlineData("C:/Music/song.flac", "C:\\Music")] + [InlineData("//server/share/song.flac", "\\\\server\\share")] + [InlineData("\\\\serv?er\\share\\song.flac", "\\\\serv?er\\share")] + [InlineData("@@abcde\\fo:o\\bar", "@@abcde\\fo:o")] + [InlineData("@@abcde/fo*o/bar", "@@abcde\\fo*o")] + public void Returns_Rooted_Unsanitized_If_Directed_Windows(string input, string expected) { - var resultDefault = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac"); - var resultExplicit = FileSafety.GetDirectoryNameSafely("Music*\\Artist\\song.flac", sanitize: true); + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OSPlatform.Windows); - Assert.Equal(resultExplicit, resultDefault); + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Mu\0sic\\song.flac", "C:/Mu\0sic")] + [InlineData("C:/Music/song.flac", "C:/Music")] + [InlineData("//server/share/song.flac", "//server/share")] + [InlineData("\\\\serv?er\\share\\song.flac", "//serv?er/share")] + [InlineData("@@abcde\\fo:o\\bar", "@@abcde/fo:o")] + [InlineData("@@abcde/fo*o/bar", "@@abcde/fo*o")] + public void Returns_Rooted_Unsanitized_If_Directed_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs index 72e6a21b..27dcf925 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -54,7 +54,7 @@ public partial class FileSafetyTests [Fact] public void Respects_Replacement_Character() { - var s = FileSafety.SanitizePathSegment("???", replacement: '!'); + var s = FileSafety.SanitizePathSegment("\0\0\0", replacement: '!'); Assert.Equal("!!!", s); } -- cgit v1.2.3 From cc5d80202e6f5973a0ce1bbdb30635392aa07ada Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 19:15:08 -0500 Subject: tweak root handling --- src/slskd/Common/FileSafety.cs | 11 ++++++++--- 1 file changed, 8 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 1fff4b08..650c082b 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -247,7 +247,7 @@ public static class FileSafety /// /// Returns the full directory name from the specified , properly handling both - /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments and sanitizing + /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments, and sanitizing /// each of the remaining segments. /// /// The path from which to extract the directory name. @@ -269,7 +269,7 @@ public static class FileSafety return null; } - var isUNC = path.StartsWith("//") || path.StartsWith("\\\\"); + var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; @@ -307,7 +307,12 @@ public static class FileSafety .SkipLast(1) .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s)); - return (retainRoot && isUNC) ? $"{sep}{sep}{newPath}" : newPath; + if (retainRoot) + { + return new string(sep, leadingSlashCount) + newPath; + } + + return newPath; } /// -- cgit v1.2.3 From 18ecfac2d8dc2b5c768cc7cc2dc61fa23259417c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 31 May 2026 22:37:56 -0500 Subject: short circuit if a user has configured the root shortcut --- src/slskd/Transfers/Downloads/DownloadService.cs | 16 +++++++++++----- 1 file changed, 11 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index ee7f2efd..48c29b19 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -753,6 +753,16 @@ namespace slskd.Transfers.Downloads /// Thrown if the derivation logic produces an absolute path, or one with traversal segments. public async Task DeriveDestination(Transfer transfer) { + // validation should ensure this is a relative path and that it contains no traversal segments + // we accept any type of slash in the pattern and convert it to the correct variant for the local OS + var pattern = OptionsMonitor.CurrentValue.Transfers.Download.Destination.Subdirectory; + + // users can enter '{}' if they want the files to go directly into the root of the downloads directory + if (pattern.Equals("{}", StringComparison.OrdinalIgnoreCase)) + { + return string.Empty; + } + string source_username; string source_path; string source_directory; @@ -841,10 +851,6 @@ namespace slskd.Transfers.Downloads ["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( @@ -1247,7 +1253,7 @@ namespace slskd.Transfers.Downloads var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename); - Log.Warning("Incomplete file for {Filename} from {Username} will be: {Filename}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename); + Log.Debug("Incomplete file for {Filename} from {Username} will be: {IncompleteFilename}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename); Log.Debug("Invoking Soulseek DownloadAsync() for {Filename} from {Username}", transfer.Filename, transfer.Username); transfer.Attempts = 1; -- cgit v1.2.3 From 7239327610f020dcb9028a845709c79a5567869d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jun 2026 18:33:17 -0500 Subject: gracefully handle nulls --- src/slskd/Common/FileSafety.cs | 22 +++++++++++++++++++++- .../FileSafety/GetDirectoryNameSafelyTests.cs | 2 +- .../Common/FileSafety/LocalizePathTests.cs | 8 ++++++++ .../Common/FileSafety/SanitizeFilenameTests.cs | 8 ++++++++ .../Common/FileSafety/SanitizePathSegmentTests.cs | 8 ++++++++ .../Common/FileSafety/SanitizePathTests.cs | 9 +++++++++ .../Common/FileSafety/StripPathRootTests.cs | 8 ++++++++ 7 files changed, 63 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 650c082b..9819209f 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -323,6 +323,11 @@ public static class FileSafety /// The converted path. public static string LocalizePath(string path, OSPlatform? os = null) { + if (path is null) + { + return null; + } + os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; @@ -340,6 +345,11 @@ public static class FileSafety /// The sanitized filename. public static string SanitizeFilename(string filename, char replacement = '_', OSPlatform? os = null) { + if (filename is null) + { + return null; + } + if (replacement is '/' or '\\') { throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); @@ -412,6 +422,11 @@ public static class FileSafety /// The sanitized path. public static string SanitizePath(string path, char replacement = '_', bool retainRoot = false, OSPlatform? os = null) { + if (path is null) + { + return null; + } + os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; @@ -421,7 +436,7 @@ public static class FileSafety if (!retainRoot) { // strip C:\ or //server, if present (regardless of slash variant, etc) - path = StripPathRoot(path); + path = StripPathRoot(path, os); } // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings @@ -443,6 +458,11 @@ public static class FileSafety /// The path with the root stripped, if one was present. public static string StripPathRoot(string path, OSPlatform? os = null) { + if (path is null) + { + return null; + } + // flip slashes the correct way path = LocalizePath(path, os); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs index ff64e90d..3d89e9f5 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -112,7 +112,7 @@ public partial class FileSafetyTests [InlineData("\\\\server\\file.txt", "\\\\server")] [InlineData("@@abcde/file.txt", "@@abcde")] [InlineData("@@abcde\\file.txt", "@@abcde")] - public void Returns_Null_When_File_Is_Directly_In_Root_With_RetainRoot_True_Windows(string input, string expected) + public void Returns_Sanitized_Root_When_File_Is_Directly_In_Root_With_RetainRoot_True_Windows(string input, string expected) { var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Windows); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index 160f2a72..0b3eb81e 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -54,5 +54,13 @@ public partial class FileSafetyTests Assert.False(string.IsNullOrEmpty(result)); } + + [Fact] + public void Returns_Null_Given_Null_Path() + { + var result = FileSafety.LocalizePath(null); + + Assert.Null(result); + } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs index 34e969d4..c0334d9b 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs @@ -152,5 +152,13 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + + [Fact] + public void Returns_Null_Given_Null() + { + var result = FileSafety.SanitizeFilename(null); + + Assert.Null(result); + } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs index 27dcf925..d322179b 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -95,5 +95,13 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + + [Fact] + public void Returns_Null_Given_Null() + { + var result = FileSafety.SanitizePathSegment(null); + + Assert.Null(result); + } } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index 2f712334..92a9e62c 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -163,5 +163,14 @@ public partial class FileSafetyTests Assert.Equal("foo/-/bar", result); } + + [Fact] + public void Returns_Null_Given_Null_Path() + { + var result = FileSafety.SanitizePath(null); + + Assert.Null(result); + } + } } diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs index f3638c9e..1ec2021d 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs @@ -15,6 +15,14 @@ public partial class FileSafetyTests Assert.NotNull(result); } + [Fact] + public void Returns_Null_Given_Null_Path() + { + var result = FileSafety.StripPathRoot(null); + + Assert.Null(result); + } + [Theory] [InlineData("C:\\Music\\Artist", "Music/Artist")] [InlineData("C:/Music/Artist", "Music/Artist")] -- cgit v1.2.3 From 16271c5f89dd6b8a5af4690fc2813285ce797dad Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 1 Jun 2026 18:43:16 -0500 Subject: add leading slashes back when SanitizePath and retainRoot = true --- src/slskd/Common/FileSafety.cs | 13 ++- .../Common/FileSafety/SanitizePathTests.cs | 93 ++++++++++++++++++++++ 2 files changed, 105 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 9819209f..5a5d964e 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -309,6 +309,7 @@ public static class FileSafety if (retainRoot) { + // leading slashes are stripped of leading slashes by Split() so we must add them back return new string(sep, leadingSlashCount) + newPath; } @@ -427,6 +428,8 @@ public static class FileSafety return null; } + var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); + os ??= Compute.OSPlatform(); var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; @@ -445,7 +448,15 @@ public static class FileSafety .Where(s => s is not "") .Select(s => SanitizePathSegment(s, replacement, os)); - return string.Join(sep, segments); + var newPath = string.Join(sep, segments); + + if (retainRoot) + { + // leading slashes are stripped of leading slashes by Split() so we must add them back + return new string(sep, leadingSlashCount) + newPath; + } + + return newPath; } /// diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index 92a9e62c..f36e53de 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -1,3 +1,4 @@ +using System; using System.Runtime.InteropServices; using Xunit; @@ -172,5 +173,97 @@ public partial class FileSafetyTests Assert.Null(result); } + // --- retainRoot: true --- + // These verify that SanitizePath honours retainRoot. The UNC and single-slash absolute + // cases are EXPECTED TO FAIL: SanitizePath filters empty segments produced by splitting on + // leading slashes, so "//server/share" becomes "server/share" — the root is silently lost. + // Drive-letter and @@-prefix cases pass because they produce no empty segments. + + + [Theory] + [InlineData("C:/Music/Artist", "C:/Music/Artist")] + [InlineData("C:\\Music\\Artist", "C:/Music/Artist")] + public void Linux_RetainsDriveRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "C_\\Music\\Artist")] + [InlineData("C:/Music/Artist", "C_\\Music\\Artist")] + public void Windows_RetainsDriveRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde/Music/Artist", "@@abcde/Music/Artist")] + [InlineData("@@abcde\\Music\\Artist", "@@abcde/Music/Artist")] + public void Linux_RetainsSoulseekQtPrefix_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde\\Music\\Artist", "@@abcde\\Music\\Artist")] + [InlineData("@@abcde/Music/Artist", "@@abcde\\Music\\Artist")] + public void Windows_RetainsSoulseekQtPrefix_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("//server/share/Music", "//server/share/Music")] + [InlineData("//server/Music", "//server/Music")] + [InlineData("\\\\server\\share\\Music", "//server/share/Music")] + [InlineData("\\\\server\\Music", "//server/Music")] + public void Linux_RetainsUncRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("/absolute/Music", "/absolute/Music")] + [InlineData("/single", "/single")] + [InlineData("\\absolute\\Music", "/absolute/Music")] + [InlineData("\\single", "/single")] + public void Linux_RetainsAbsoluteRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\\\server\\share\\Music", "\\\\server\\share\\Music")] + [InlineData("\\\\server\\Music", "\\\\server\\Music")] + [InlineData("//server/share/Music", "\\\\server\\share\\Music")] + [InlineData("//server/Music", "\\\\server\\Music")] + public void Windows_RetainsUncRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\absolute\\Music", "\\absolute\\Music")] + [InlineData("/absolute/Music", "\\absolute\\Music")] + public void Windows_RetainsDriveRelativeRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } } } -- cgit v1.2.3 From 7c15337f80ec1e579f8725659657588a2d313911 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 2 Jun 2026 21:36:14 -0500 Subject: add Compute.OSPlatform() --- src/slskd/Common/Compute.cs | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) (limited to 'src') diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index 8d7c1ceb..dc565806 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -33,6 +33,7 @@ namespace slskd { using System; + using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Text; @@ -64,5 +65,25 @@ namespace slskd using var sha256 = SHA256.Create(); return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty); } + + public static OSPlatform OSPlatform() + { + if (OperatingSystem.IsWindows()) + { + return System.Runtime.InteropServices.OSPlatform.Windows; + } + + if (OperatingSystem.IsMacOS()) + { + return System.Runtime.InteropServices.OSPlatform.OSX; + } + + if (OperatingSystem.IsFreeBSD()) + { + return System.Runtime.InteropServices.OSPlatform.FreeBSD; + } + + return System.Runtime.InteropServices.OSPlatform.Linux; + } } } \ No newline at end of file -- cgit v1.2.3 From 3d76c437f63048c83b426a728ba37043115631f6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 2 Jun 2026 21:36:58 -0500 Subject: add comprehensive cross-platform path and filename handling functions --- src/slskd/Common/FileSafety.cs | 295 ++++++++++++++++++++- .../Common/FileSafety/CombineSafelyTests.cs | 3 + .../FileSafety/GetDirectoryNameSafelyTests.cs | 272 +++++++++++++++++++ .../Common/FileSafety/GetFileNameSafelyTests.cs | 114 ++++++++ .../Common/FileSafety/LocalizePathTests.cs | 66 +++++ .../Common/FileSafety/SanitizeFilenameTests.cs | 164 ++++++++++++ .../Common/FileSafety/SanitizePathSegmentTests.cs | 107 ++++++++ .../Common/FileSafety/SanitizePathTests.cs | 269 +++++++++++++++++++ .../Common/FileSafety/StripPathRootTests.cs | 158 +++++++++++ 9 files changed, 1447 insertions(+), 1 deletion(-) create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index f67af8d5..5a5d964e 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -36,12 +36,34 @@ using System; using System.IO; using System.Linq; using System.Runtime.InteropServices; +using System.Text.RegularExpressions; /// /// Utility functions to help safely work with paths from untrusted sources. /// public static class FileSafety { + /// + /// Invalid filename characters on Unix-like operating systems (Linux, OSX, FreeBSD, etc). + /// + public static readonly char[] InvalidFileNameCharactersOnUnix = ['\0', '/']; + + /// + /// Invalid filename characters on Windows. + /// + public static readonly char[] InvalidFileNameCharactersOnWindows = + [ + '\"', '<', '>', '|', '\0', + (char)1, (char)2, (char)3, (char)4, (char)5, (char)6, (char)7, (char)8, (char)9, (char)10, + (char)11, (char)12, (char)13, (char)14, (char)15, (char)16, (char)17, (char)18, (char)19, (char)20, + (char)21, (char)22, (char)23, (char)24, (char)25, (char)26, (char)27, (char)28, (char)29, (char)30, + (char)31, ':', '*', '?', '\\', '/', + ]; + + private static readonly Regex DriveRootRegex = new(@"^[a-zA-Z]:[/\\]?", RegexOptions.Compiled); // C: or C:\ + private static readonly Regex UncRootRegex = new(@"^[/\\]{2}[^/\\]+[/\\]?", RegexOptions.Compiled); // \\server[\] or //server[/], any slash variants + private static readonly Regex SoulseekQtRootRegex = new(@"^@@[a-zA-Z0-9]{5,}[\/\\]?", RegexOptions.Compiled); // @@abcde[\|/], a Soulseek Qt share prefix + /// /// An alternative to that disallows rooted segments in the second or /// subsequent position, and disallows segments containing path traversal characters "." and "..". @@ -108,7 +130,7 @@ public static class FileSafety } } - var parts = segment.Split(Path.DirectorySeparatorChar, '\\', '/'); + var parts = segment.Split('\\', '/'); // 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 @@ -193,4 +215,275 @@ public static class FileSafety /// An optional operating system override, for testing. /// True if the path is relative, false otherwise. public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); + + /// + /// Returns the filename from the specified , properly + /// handling both forward and backslashes and removing invalid characters. + /// + /// The path from which to extract the filename. + /// An optional value indicating that invalid characters should not be replaced. + /// An optional operating system override, for testing. + /// The extracted filename. + public static string GetFileNameSafely(string path, bool sanitize = true, OSPlatform? os = null) + { + if (path is null or "" || path.EndsWith('/') || path.EndsWith('\\')) + { + return null; + } + + if (StripPathRoot(path, os) == string.Empty) + { + return null; + } + + var localPath = LocalizePath(path, os); + var segments = localPath.Split('/', '\\'); + + return segments + .TakeLast(1) + .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s) + .Single(); + } + + /// + /// Returns the full directory name from the specified , properly handling both + /// forward and backslashes, removing Windows drive, UNC and Soulseek QT root segments, and sanitizing + /// each of the remaining segments. + /// + /// The path from which to extract the directory name. + /// An optional value indicating whether to keep the path's root, if present. + /// An optional value indicating that path segments should not be sanitized. + /// An optional operating system override, for testing. + /// The directory name. + /// Thrown if the specified path is null. + public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OSPlatform? os = null) + { + if (path is null or "") + { + return null; + } + + // a plain string is assumed to be a file. matches the behavior of the BCL method + if (!path.Contains('/') && !path.Contains('\\')) + { + return null; + } + + var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); + + os ??= Compute.OSPlatform(); + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + var local = LocalizePath(path, os) + .TrimEnd('/', '\\'); // treat file-less paths the same as files + + var unrooted = StripPathRoot(local, os); + + // were given a root; C:\, //server, @@abcde + if (unrooted is null or "") + { + return null; + } + + if (!retainRoot) + { + local = unrooted; + } + + // strip empty segments + var segments = local + .Split('/', '\\') + .Where(s => s is not "") + .ToArray(); + + // we were given all slashes, a file in the root, or some other case where + // only a file or subdirectory remains; no parent directory + if (segments.Length <= 1) + { + return null; + } + + var newPath = string.Join(sep, segments + .SkipLast(1) + .Select(s => sanitize ? SanitizePathSegment(s, os: os) : s)); + + if (retainRoot) + { + // leading slashes are stripped of leading slashes by Split() so we must add them back + return new string(sep, leadingSlashCount) + newPath; + } + + return newPath; + } + + /// + /// Converts the given path to the local format (normalizes path separators to Path.DirectorySeparatorChar). + /// + /// The path to convert. + /// An optional operating system override, for testing. + /// The converted path. + public static string LocalizePath(string path, OSPlatform? os = null) + { + if (path is null) + { + return null; + } + + os ??= Compute.OSPlatform(); + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + return path.Replace('\\', sep).Replace('/', sep); + } + + /// + /// Sanitizes the specified (or string intended to be used as or as part of a filename) + /// to make it suitable and safe on the local operating system by stripping all slashes (forward or back) and + /// replacing any invalid characters with the specified . + /// + /// The filename (or string intended to be used as/part of one). + /// The character to substitute for invalid characters. + /// An optional operating system override, for testing. + /// The sanitized filename. + public static string SanitizeFilename(string filename, char replacement = '_', OSPlatform? os = null) + { + if (filename is null) + { + return null; + } + + if (replacement is '/' or '\\') + { + throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); + } + + os ??= Compute.OSPlatform(); + + var characters = os.Value == OSPlatform.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; + + if (characters.Contains(replacement)) + { + throw new ArgumentException($"The provided replacement character '{replacement}' is invalid on {os}"); + } + + var sanitized = filename; + + foreach (var c in characters) + { + sanitized = sanitized.Replace(c, replacement); + } + + // regardless of which OS and what characters are disallowed on it, we don't allow slashes in filenames + // (or strings that will be used as filenames), otherwise we should/would have used SanitizePath() + return sanitized + .Replace('/', replacement) + .Replace('\\', replacement); + } + + /// + /// Sanitizes the specified to make it suitable and safe on the local operating + /// system by stripping all slashes (forward or back) and replacing any invalid characters with the specified + /// . + /// + /// The path segment. + /// The character to substitute for invalid characters. + /// An optional operating system override, for testing. + /// The sanitized path segment. + public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) + { + var sanitized = SanitizeFilename(segment, replacement, os); + + // is is possible for the result of sanitization to produce path traversal strings, + // which would result in traversal when combined (or throw an error because of CombineSafely) + // this can happen either because the segment is already periods, or because the replacement + // character is a period and the input one or two invalid characters. + // if this happens we follow the principle of least surprise and return an empty string + // avoid using a period for replacement (don't let users choose) and we won't have this problem + if (sanitized is "." or "..") + { + if (replacement is '.') + { + return string.Empty; + } + + return replacement.ToString(); + } + + return sanitized; + } + + /// + /// Sanitizes the specified to make it suitable and safe on the local operating system + /// by converting to the correct slashes, dropping a root (if present), replacing any invalid characters with + /// the specified , and by dropping any path traversal segments. + /// + /// The path. + /// The character to substitute for invalid characters. + /// An optional value indicating whether to keep the path's root, if present. + /// An optional operating system override, for testing. + /// The sanitized path. + public static string SanitizePath(string path, char replacement = '_', bool retainRoot = false, OSPlatform? os = null) + { + if (path is null) + { + return null; + } + + var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); + + os ??= Compute.OSPlatform(); + var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + + // flip slashes the correct way + path = LocalizePath(path, os); + + if (!retainRoot) + { + // strip C:\ or //server, if present (regardless of slash variant, etc) + path = StripPathRoot(path, os); + } + + // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings + var segments = path + .Split('/', '\\') + .Where(s => s is not "") + .Select(s => SanitizePathSegment(s, replacement, os)); + + var newPath = string.Join(sep, segments); + + if (retainRoot) + { + // leading slashes are stripped of leading slashes by Split() so we must add them back + return new string(sep, leadingSlashCount) + newPath; + } + + return newPath; + } + + /// + /// Removes the root of the specified , including Window's drive prefix (e.g. C:\), + /// UNC paths on any OS (e.g. \\server on Windows, //server on Linux), and drops the hashed prefix added by + /// Soulseek Qt to hide the path on disk (e.g. @@abcde). + /// + /// The path to strip. + /// An optional operating system override, for testing. + /// The path with the root stripped, if one was present. + public static string StripPathRoot(string path, OSPlatform? os = null) + { + if (path is null) + { + return null; + } + + // flip slashes the correct way + path = LocalizePath(path, os); + + // strip C:\ or //server, if present (regardless of slash variant) + path = DriveRootRegex.Replace(path, string.Empty); + path = UncRootRegex.Replace(path, string.Empty); + + // strip @@abcde prefixes used by SoulseekQt to obscure paths + path = SoulseekQtRootRegex.Replace(path, string.Empty); + + return path; + } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index 2d496c4b..0ffa0129 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -103,6 +103,9 @@ public partial class FileSafetyTests [InlineData("用户/音乐")] [InlineData("ユーザー/音楽")] [InlineData("사용자/음악")] + [InlineData("foo\\bar\\baz\\qux\\deeply\\nested")] + [InlineData("foo/bar/baz/qux/deeply/nested")] + [InlineData("foo/bar\\baz/qux\\deeply/nested")] public void Combines_Safe_Segments(string segment) { var result = FileSafety.CombineSafely(Base, segment); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs new file mode 100644 index 00000000..f60c4c9a --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -0,0 +1,272 @@ +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class GetDirectoryNameSafelyTests + { + [Fact] + public void Returns_Null_Given_Null() + { + var result = FileSafety.GetDirectoryNameSafely(null); + + Assert.Null(result); + } + + [Fact] + public void Returns_Null_Given_Empty() + { + var result = FileSafety.GetDirectoryNameSafely(""); + + Assert.Null(result); + } + + [Theory] + [InlineData("\\")] + [InlineData("\\\\")] + [InlineData("\\\\\\")] + [InlineData("/")] + [InlineData("//")] + [InlineData("///")] + [InlineData("/\\/\\\\//////\\")] + public void Returns_Null_Given_Only_Slashes(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Null(result); + } + + [Theory] + [InlineData("foo")] + [InlineData("foo.bar")] + public void Returns_Null_Given_Bare_File(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Null(result); + } + + [Theory] + [InlineData("C:")] + [InlineData("C:\\")] + [InlineData("C:/")] + [InlineData("/")] + [InlineData("\\")] + [InlineData("//server")] + [InlineData("\\\\server")] + public void Returns_Null_Given_Root(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input); + + Assert.Null(result); + } + + [Theory] + [InlineData("C:\\file.txt")] + [InlineData("C:/file.txt")] + [InlineData("//server/file.txt")] + [InlineData("\\\\server\\file.txt")] + [InlineData("@@abcde/file.txt")] + [InlineData("@@abcde\\file.txt")] + public void Returns_Null_When_File_Is_Directly_In_Root_With_RetainRoot_False_Linux(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, os: OSPlatform.Linux); + + Assert.Null(result); + } + + [Theory] + [InlineData("C:\\file.txt")] + [InlineData("C:/file.txt")] + [InlineData("//server/file.txt")] + [InlineData("\\\\server\\file.txt")] + [InlineData("@@abcde/file.txt")] + [InlineData("@@abcde\\file.txt")] + public void Returns_Null_When_File_Is_Directly_In_Root_With_RetainRoot_False_Windows(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, os: OSPlatform.Windows); + + Assert.Null(result); + } + + [Theory] + [InlineData("C:\\file.txt", "C:")] + [InlineData("C:/file.txt", "C:")] + [InlineData("//server/file.txt", "//server")] + [InlineData("\\\\server\\file.txt", "//server")] + [InlineData("@@abcde/file.txt", "@@abcde")] + [InlineData("@@abcde\\file.txt", "@@abcde")] + public void Returns_Root_When_File_Is_Directly_In_Root_With_RetainRoot_True_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\file.txt", "C_")] + [InlineData("C:/file.txt", "C_")] + [InlineData("//server/file.txt", "\\\\server")] + [InlineData("\\\\server\\file.txt", "\\\\server")] + [InlineData("@@abcde/file.txt", "@@abcde")] + [InlineData("@@abcde\\file.txt", "@@abcde")] + public void Returns_Sanitized_Root_When_File_Is_Directly_In_Root_With_RetainRoot_True_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Fact] + public void Sanitizes_Path_When_Sanitize_True() + { + var result = FileSafety.GetDirectoryNameSafely("foo/b\0ar/baz", sanitize: true); + + Assert.DoesNotContain('\0', result); + } + + [Fact] + public void Does_Not_Sanitize_Path_When_Sanitize_False() + { + var result = FileSafety.GetDirectoryNameSafely("foo/b\0ar/baz", sanitize: false); + + Assert.Contains('\0', result); + } + + [Fact] + public void Sanitize_Defaults_To_True() + { + var result = FileSafety.GetDirectoryNameSafely("foo/b\0ar/baz"); + + Assert.DoesNotContain('\0', result); + } + + [Theory] + [InlineData("\\foo\\\\bar\\\\baz", "foo\\bar")] + [InlineData("/foo//bar//baz", "foo\\bar")] + public void Removes_Empty_Segments_And_Leading_Slashes_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\foo\\\\bar\\\\baz", "foo/bar")] + [InlineData("/foo//bar//baz", "foo/bar")] + public void Removes_Empty_Segments_And_Leading_Slashes_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o\\bar", "fo_o")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "Music")] + [InlineData("C:/Music/song.flac", "Music")] + [InlineData("C:\\M\0usic\\Artist\\song.flac", "M_usic/Artist")] + [InlineData("C:\\foo.txt", null)] + [InlineData("//server/share/song.flac", "share")] + [InlineData("\\\\server\\share\\song.flac", "share")] + [InlineData("/abs\0olute/path", "abs_olute")] + [InlineData("\\abs\0olute\\path", "abs_olute")] + [InlineData("@@abcde\\foo\\bar", "foo")] + public void Returns_Unrooted_Sanitized_Directory_Given_Path_With_File_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o\\bar", "fo_o")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "Music")] + [InlineData("C:/Music/song.flac", "Music")] + [InlineData("C:\\M\0usic\\Artist\\song.flac", "M_usic\\Artist")] + [InlineData("C:\\foo.txt", null)] + [InlineData("//server/share/song.flac", "share")] + [InlineData("\\\\server\\share\\song.flac", "share")] + [InlineData("/abs\0olute/path", "abs_olute")] + [InlineData("\\abs\0olute\\path", "abs_olute")] + [InlineData("@@abcde\\foo\\bar", "foo")] + public void Returns_Unrooted_Sanitized_Directory_Given_Path_With_File_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: true, retainRoot: false, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo\\bar", "foo")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "C_\\Music")] + [InlineData("C:/Music/song.flac", "C_\\Music")] + [InlineData("C:\\Music\\Artist\\song.flac", "C_\\Music\\Artist")] + [InlineData("//server/share/song.flac", "\\\\server\\share")] + [InlineData("\\\\server\\share\\song.flac", "\\\\server\\share")] + [InlineData("/absolute/path", "\\absolute")] + [InlineData("\\absolute\\path", "\\absolute")] + [InlineData("@@abcde\\foo\\bar", "@@abcde\\foo")] + public void Retains_Path_Root_When_RetainRoot_True_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo\\bar", "foo")] + [InlineData("foo/bar", "foo")] + [InlineData("C:\\Music\\song.flac", "C:/Music")] + [InlineData("C:/Music/song.flac", "C:/Music")] + [InlineData("C:\\Music\\Artist\\song.flac", "C:/Music/Artist")] + [InlineData("//server/share/song.flac", "//server/share")] + [InlineData("\\\\server\\share\\song.flac", "//server/share")] + [InlineData("/absolute/path", "/absolute")] + [InlineData("\\absolute\\path", "/absolute")] + [InlineData("@@abcde\\foo\\bar", "@@abcde/foo")] + public void Retains_Path_Root_When_RetainRoot_True_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Mu\0sic\\song.flac", "C:\\Mu\0sic")] + [InlineData("C:/Music/song.flac", "C:\\Music")] + [InlineData("//server/share/song.flac", "\\\\server\\share")] + [InlineData("\\\\serv?er\\share\\song.flac", "\\\\serv?er\\share")] + [InlineData("/abs\0olute/path", "\\abs\0olute")] + [InlineData("\\abs\0olute\\path", "\\abs\0olute")] + [InlineData("@@abcde\\fo:o\\bar", "@@abcde\\fo:o")] + [InlineData("@@abcde/fo*o/bar", "@@abcde\\fo*o")] + public void Returns_Rooted_Unsanitized_If_Directed_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Mu\0sic\\song.flac", "C:/Mu\0sic")] + [InlineData("C:/Music/song.flac", "C:/Music")] + [InlineData("//server/share/song.flac", "//server/share")] + [InlineData("\\\\serv?er\\share\\song.flac", "//serv?er/share")] + [InlineData("/abs\0olute/path", "/abs\0olute")] + [InlineData("\\abs\0olute\\path", "/abs\0olute")] + [InlineData("@@abcde\\fo:o\\bar", "@@abcde/fo:o")] + [InlineData("@@abcde/fo*o/bar", "@@abcde/fo*o")] + public void Returns_Rooted_Unsanitized_If_Directed_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + } +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs new file mode 100644 index 00000000..93acaf42 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs @@ -0,0 +1,114 @@ +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class GetFileNameSafelyTests + { + [Fact] + public void Returns_Null_Given_Null() + { + var result = FileSafety.GetFileNameSafely(null); + + Assert.Null(result); + } + + [Fact] + public void Returns_Null_Given_Empty() + { + var result = FileSafety.GetFileNameSafely(""); + + Assert.Null(result); + } + + [Theory] + [InlineData("/")] + [InlineData("\\")] + [InlineData("C:\\")] + [InlineData("C:/")] + [InlineData("//")] + [InlineData("\\\\")] + [InlineData("foo\\")] + [InlineData("foo//")] + [InlineData("C:\\foo//bar\\")] + [InlineData("C:/foo\\bar/")] + public void Returns_Null_Given_Path_Ending_In_Separator(string input) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Null(result); + } + + [Theory] + [InlineData("//server")] + [InlineData("\\\\server")] + [InlineData("C:")] + [InlineData("@@abcde")] + public void Returns_Null_Given_Just_Rooted_Path(string input) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Null(result); + } + + [Theory] + [InlineData("foo", "foo")] + [InlineData("foo.bar", "foo.bar")] + [InlineData("foo\\bar", "bar")] + [InlineData("foo/bar", "bar")] + [InlineData("C:\\Music\\song.flac", "song.flac")] + [InlineData("C:/Music/song.flac", "song.flac")] + [InlineData("Music\\Artist\\song.flac", "song.flac")] + [InlineData("//server/share/song.flac", "song.flac")] + [InlineData("\\\\server\\share\\song.flac", "song.flac")] + public void Returns_Filename_Given_Path_With_File(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(expected, result); + } + + [Fact] + public void Sanitize_True_Replaces_InvalidCharacters_On_Windows() + { + var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true, os: OSPlatform.Windows); + + Assert.Equal("file_name.flac", result); + } + + [Fact] + public void Sanitize_True_Replaces_InvalidCharacters_On_Linux() + { + var result = FileSafety.GetFileNameSafely("Music\\file\0name.flac", sanitize: true, os: OSPlatform.Linux); + + Assert.Equal("file_name.flac", result); + } + + [Fact] + public void Sanitize_False_Preserves_InvalidCharacters_On_Windows() + { + var result = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: false, os: OSPlatform.Windows); + + Assert.Equal("file:name.flac", result); + } + + [Fact] + public void Sanitize_False_Preserves_InvalidCharacters_On_Linux() + { + var result = FileSafety.GetFileNameSafely("Music\\file\0name.flac", sanitize: false, os: OSPlatform.Linux); + + Assert.Equal("file\0name.flac", result); + } + + [Fact] + public void Default_Sanitize_Is_True() + { + var resultDefault = FileSafety.GetFileNameSafely("Music\\file:name.flac", os: OSPlatform.Windows); + var resultExplicit = FileSafety.GetFileNameSafely("Music\\file:name.flac", sanitize: true, os: OSPlatform.Windows); + + Assert.Equal(resultExplicit, resultDefault); + } + } +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs new file mode 100644 index 00000000..97a64d6c --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -0,0 +1,66 @@ +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class LocalizePathTests + { + [Theory] + [InlineData("foo/bar", "foo/bar")] + [InlineData("foo\\bar", "foo/bar")] + [InlineData("foo/bar/baz", "foo/bar/baz")] + [InlineData("foo\\bar/baz", "foo/bar/baz")] + [InlineData("foo\\\\bar", "foo//bar")] + [InlineData("@@abcde\\foo\\bar\\", "@@abcde/foo/bar/")] + [InlineData("@@abcde/foo/bar/", "@@abcde/foo/bar/")] + [InlineData("\\\\server\\foo\\", "//server/foo/")] + [InlineData("//server/foo/", "//server/foo/")] + [InlineData("C:\\Windows\\foo", "C:/Windows/foo")] + [InlineData("C:/Windows/foo", "C:/Windows/foo")] + [InlineData("", "")] + public void Linux_NormalizesToForwardSlash(string input, string expected) + { + var result = FileSafety.LocalizePath(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo/bar", "foo\\bar")] + [InlineData("foo\\bar", "foo\\bar")] + [InlineData("foo/bar/baz", "foo\\bar\\baz")] + [InlineData("foo\\bar/baz", "foo\\bar\\baz")] + [InlineData("foo//bar", "foo\\\\bar")] + [InlineData("@@abcde\\foo\\bar\\", "@@abcde\\foo\\bar\\")] + [InlineData("@@abcde/foo/bar/", "@@abcde\\foo\\bar\\")] + [InlineData("\\\\server\\foo\\", "\\\\server\\foo\\")] + [InlineData("//server/foo/", "\\\\server\\foo\\")] + [InlineData("C:\\Windows\\foo", "C:\\Windows\\foo")] + [InlineData("C:/Windows/foo", "C:\\Windows\\foo")] + [InlineData("", "")] + public void Windows_NormalizesToBackslash(string input, string expected) + { + var result = FileSafety.LocalizePath(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Fact] + public void NullOs_UsesPlatformDefault_DoesNotThrow() + { + var result = FileSafety.LocalizePath("foo/bar"); + + Assert.False(string.IsNullOrEmpty(result)); + } + + [Fact] + public void Returns_Null_Given_Null_Path() + { + var result = FileSafety.LocalizePath(null); + + Assert.Null(result); + } + } +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs new file mode 100644 index 00000000..618e691e --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs @@ -0,0 +1,164 @@ +using System; +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class SanitizeFilenameTests + { + [Theory] + [InlineData('/')] + [InlineData('\\')] + public void Throws_Given_Slash_As_Replacement(char replacement) + { + var ex = Record.Exception(() => FileSafety.SanitizeFilename("file", replacement)); + + Assert.NotNull(ex); + Assert.IsType(ex); + Assert.Contains("invalid in filenames", ex.Message); + } + + [Fact] + public void Throws_Given_OsInvalid_Replacement_On_Unix() + { + // '\0' is invalid on Unix but not caught by the slash guard + var ex = Record.Exception(() => FileSafety.SanitizeFilename("file", '\0', OSPlatform.Linux)); + + Assert.NotNull(ex); + Assert.IsType(ex); + Assert.Contains("invalid on", ex.Message); + } + + [Fact] + public void Throws_Given_OsInvalid_Replacement_On_Windows() + { + // '*' is invalid on Windows but not caught by the slash guard + var ex = Record.Exception(() => FileSafety.SanitizeFilename("file", '*', OSPlatform.Windows)); + + Assert.NotNull(ex); + Assert.IsType(ex); + Assert.Contains("invalid on", ex.Message); + } + + [Fact] + public void NullOs_UsesPlatformDefault_DoesNotThrow() + { + var result = FileSafety.SanitizeFilename("safe_file.flac"); + + Assert.NotNull(result); + } + + [Theory] + [InlineData("clean", "clean")] + [InlineData("file.flac", "file.flac")] + [InlineData("My Artist - My Album", "My Artist - My Album")] + [InlineData("Ünïcödé", "Ünïcödé")] + [InlineData("пользователь", "пользователь")] + public void Linux_ReturnsUnchanged_Given_Safe_Filename(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("file\0name", "file_name")] + [InlineData("\0leading", "_leading")] + [InlineData("trailing\0", "trailing_")] + public void Linux_Replaces_NullByte(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("has/slash", "has_slash")] + [InlineData("has\\backslash", "has_backslash")] + [InlineData("has/both\\types", "has_both_types")] + public void Linux_Replaces_Slashes(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("/home/user/foo", "_home_user_foo")] + [InlineData("//server/share", "__server_share")] + [InlineData("C:\\Windows\\file.ext", "C:_Windows_file.ext")] + [InlineData("\\\\server\\share", "__server_share")] + public void Linux_Sanitizes_Full_Paths(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Fact] + public void Linux_Uses_Custom_Replacement() + { + var result = FileSafety.SanitizeFilename("has/slash", '-', OSPlatform.Linux); + + Assert.Equal("has-slash", result); + } + + [Theory] + [InlineData("file\"name", "file_name")] + [InlineData("file", "file_name_")] + [InlineData("file|name", "file_name")] + [InlineData("file:name", "file_name")] + [InlineData("file*name", "file_name")] + [InlineData("file?name", "file_name")] + [InlineData("file\\name", "file_name")] + [InlineData("file/name", "file_name")] + public void Windows_Replaces_InvalidCharacters(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("/home/user/foo", "_home_user_foo")] + [InlineData("//server/share", "__server_share")] + [InlineData("C:\\Windows\\file.ext", "C__Windows_file.ext")] + [InlineData("\\\\server\\share", "__server_share")] + public void Windows_Sanitizes_Full_Paths(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Fact] + public void Windows_Replaces_ControlCharacters() + { + var input = "file\x01\x1fname"; + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Windows); + + Assert.Equal("file__name", result); + } + + [Theory] + [InlineData("clean", "clean")] + [InlineData("file.flac", "file.flac")] + [InlineData("My Artist", "My Artist")] + public void Windows_ReturnsUnchanged_Given_Safe_Filename(string input, string expected) + { + var result = FileSafety.SanitizeFilename(input, '_', OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Fact] + public void Returns_Null_Given_Null() + { + var result = FileSafety.SanitizeFilename(null); + + Assert.Null(result); + } + } +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs new file mode 100644 index 00000000..ecf5bdf9 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -0,0 +1,107 @@ +using System; +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class SanitizePathSegmentTests + { + [Theory] + [InlineData('/')] + [InlineData('\\')] + public void Throws_Given_Slash_As_Replacement(char replacement) + { + var ex = Record.Exception(() => FileSafety.SanitizePathSegment("segment", replacement)); + + Assert.NotNull(ex); + Assert.IsType(ex); + Assert.Contains("invalid in filenames", ex.Message); + } + + [Theory] + [InlineData(".")] + [InlineData("..")] + public void Replaces_Traversal_Segments_With_Replacement(string input) + { + var s = FileSafety.SanitizePathSegment(input, '_'); + + Assert.Equal("_", s); + } + + [Theory] + [InlineData(".")] + [InlineData("..")] + public void Returns_Empty_String_When_Replacement_Is_Period_And_Result_Would_Be_Traversal(string input) + { + var s = FileSafety.SanitizePathSegment(input, '.'); + + Assert.Equal("", s); + } + + [Theory] + [InlineData("a.")] + [InlineData("..b")] + [InlineData("c..d")] + public void Preserves_Periods_In_Segment_If_Not_Traversal(string input) + { + var s = FileSafety.SanitizePathSegment(input, '_'); + + Assert.Equal(input, s); + } + + [Fact] + public void Respects_Replacement_Character() + { + var s = FileSafety.SanitizePathSegment("\0\0\0", replacement: '!'); + + Assert.Equal("!!!", s); + } + + [Theory] + [InlineData("clean", "clean")] + [InlineData("Artist - Album", "Artist - Album")] + [InlineData("Ünïcödé", "Ünïcödé")] + [InlineData("пользователь", "пользователь")] + public void Linux_ReturnsUnchanged_Given_Safe_Segment(string input, string expected) + { + var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("has/slash", "has_slash")] + [InlineData("has\\backslash", "has_backslash")] + [InlineData("has/both\\types", "has_both_types")] + public void Linux_Replaces_Slashes(string input, string expected) + { + var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("file:name", "file_name")] + [InlineData("file*name", "file_name")] + [InlineData("file?name", "file_name")] + [InlineData("file\"name", "file_name")] + [InlineData("file/name", "file_name")] + [InlineData("file\\name", "file_name")] + public void Windows_Replaces_InvalidCharacters(string input, string expected) + { + var result = FileSafety.SanitizePathSegment(input, '_', OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Fact] + public void Returns_Null_Given_Null() + { + var result = FileSafety.SanitizePathSegment(null); + + Assert.Null(result); + } + } +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs new file mode 100644 index 00000000..5848b5f0 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -0,0 +1,269 @@ +using System; +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class SanitizePathTests + { + [Fact] + public void NullOs_UsesPlatformDefault_DoesNotThrow() + { + var result = FileSafety.SanitizePath("foo/bar"); + + Assert.NotNull(result); + } + + [Theory] + [InlineData("foo/bar", "foo/bar")] + [InlineData("foo\\bar", "foo/bar")] + [InlineData("Artist/Album/song.flac", "Artist/Album/song.flac")] + [InlineData("Ünïcödé/пользователь", "Ünïcödé/пользователь")] + public void Linux_NormalizesSlashes(string input, string expected) + { + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo/bar", "foo\\bar")] + [InlineData("foo\\bar", "foo\\bar")] + [InlineData("Artist/Album/song.flac", "Artist\\Album\\song.flac")] + public void Windows_NormalizesSlashes(string input, string expected) + { + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "Music\\Artist")] + [InlineData("C:/Music/Artist", "Music\\Artist")] + [InlineData("D:\\path\\to\\file", "path\\to\\file")] + [InlineData("Z:\\", "")] + public void Windows_Strips_DriveRoot(string input, string expected) + { + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "Music/Artist")] + [InlineData("C:/Music/Artist", "Music/Artist")] + [InlineData("D:\\path", "path")] + public void Linux_Strips_DriveRoot(string input, string expected) + { + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\\\server\\share\\Music", "share\\Music")] + [InlineData("\\\\server\\Music", "Music")] + [InlineData("\\\\192.168.1.1\\share\\folder", "share\\folder")] + public void Windows_Strips_UncRoot(string input, string expected) + { + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("//server/share/Music", "share/Music")] + [InlineData("//server/Music", "Music")] + [InlineData("//192.168.1.1/share/folder", "share/folder")] + public void Linux_Strips_UncRoot(string input, string expected) + { + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde/Music/Artist", "Music/Artist")] + [InlineData("@@abcdefgh/Music", "Music")] + [InlineData("@@abcde\\Music\\Artist", "Music/Artist")] + public void Linux_Strips_SoulseekQtPrefix(string input, string expected) + { + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde\\Music\\Artist", "Music\\Artist")] + [InlineData("@@abcdefgh\\Music", "Music")] + [InlineData("@@abcde/Music/Artist", "Music\\Artist")] + public void Windows_Strips_SoulseekQtPrefix(string input, string expected) + { + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abc/Music")] // only 3 alphanumeric chars — does not match + [InlineData("@@abcd/Music")] // only 4 — does not match + public void DoesNotStrip_SoulseekQtPrefix_When_Prefix_Too_Short(string input) + { + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); + + Assert.StartsWith("@@", result); + } + + [Theory] + [InlineData("foo/../bar", "foo/_/bar")] + [InlineData("foo/./bar", "foo/_/bar")] + [InlineData("../etc", "_/etc")] + [InlineData("./tmp", "_/tmp")] + [InlineData("foo/..", "foo/_")] + [InlineData("foo/.", "foo/_")] + public void Linux_Replaces_TraversalSegments(string input, string expected) + { + var result = FileSafety.SanitizePath(input, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo\\..\\bar", "foo\\_\\bar")] + [InlineData("foo\\.\\bar", "foo\\_\\bar")] + [InlineData("..\\etc", "_\\etc")] + public void Windows_Replaces_TraversalSegments(string input, string expected) + { + var result = FileSafety.SanitizePath(input, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Fact] + public void Linux_Replaces_InvalidFilenameChars_In_Segments() + { + var result = FileSafety.SanitizePath("seg\0ment/file\0name", os: OSPlatform.Linux); + + Assert.Equal("seg_ment/file_name", result); + } + + [Fact] + public void Windows_Replaces_InvalidFilenameChars_In_Segments() + { + var result = FileSafety.SanitizePath("seg*ment\\file:name", os: OSPlatform.Windows); + + Assert.Equal("seg_ment\\file_name", result); + } + + [Fact] + public void Uses_Custom_Replacement() + { + var result = FileSafety.SanitizePath("foo/../bar", replacement: '-', os: OSPlatform.Linux); + + Assert.Equal("foo/-/bar", result); + } + + [Fact] + public void Returns_Null_Given_Null_Path() + { + var result = FileSafety.SanitizePath(null); + + Assert.Null(result); + } + + // --- retainRoot: true --- + // These verify that SanitizePath honours retainRoot. The UNC and single-slash absolute + // cases are EXPECTED TO FAIL: SanitizePath filters empty segments produced by splitting on + // leading slashes, so "//server/share" becomes "server/share" — the root is silently lost. + // Drive-letter and @@-prefix cases pass because they produce no empty segments. + + + [Theory] + [InlineData("C:/Music/Artist", "C:/Music/Artist")] + [InlineData("C:\\Music\\Artist", "C:/Music/Artist")] + public void Linux_RetainsDriveRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "C_\\Music\\Artist")] + [InlineData("C:/Music/Artist", "C_\\Music\\Artist")] + public void Windows_RetainsDriveRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde/Music/Artist", "@@abcde/Music/Artist")] + [InlineData("@@abcde\\Music\\Artist", "@@abcde/Music/Artist")] + public void Linux_RetainsSoulseekQtPrefix_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde\\Music\\Artist", "@@abcde\\Music\\Artist")] + [InlineData("@@abcde/Music/Artist", "@@abcde\\Music\\Artist")] + public void Windows_RetainsSoulseekQtPrefix_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("//server/share/Music", "//server/share/Music")] + [InlineData("//server/Music", "//server/Music")] + [InlineData("\\\\server\\share\\Music", "//server/share/Music")] + [InlineData("\\\\server\\Music", "//server/Music")] + public void Linux_RetainsUncRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("/absolute/Music", "/absolute/Music")] + [InlineData("/single", "/single")] + [InlineData("\\absolute\\Music", "/absolute/Music")] + [InlineData("\\single", "/single")] + public void Linux_RetainsAbsoluteRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\\\server\\share\\Music", "\\\\server\\share\\Music")] + [InlineData("\\\\server\\Music", "\\\\server\\Music")] + [InlineData("//server/share/Music", "\\\\server\\share\\Music")] + [InlineData("//server/Music", "\\\\server\\Music")] + public void Windows_RetainsUncRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\absolute\\Music", "\\absolute\\Music")] + [InlineData("/absolute/Music", "\\absolute\\Music")] + public void Windows_RetainsDriveRelativeRoot_When_RetainRoot_True(string input, string expected) + { + var result = FileSafety.SanitizePath(input, retainRoot: true, os: OSPlatform.Windows); + + Assert.Equal(expected, result); + } + } +} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs new file mode 100644 index 00000000..a3641f8b --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs @@ -0,0 +1,158 @@ +using System.Runtime.InteropServices; +using Xunit; + +namespace slskd.Tests.Unit.Common; + +public partial class FileSafetyTests +{ + public class StripPathRootTests + { + [Fact] + public void NullOs_UsesPlatformDefault_DoesNotThrow() + { + var result = FileSafety.StripPathRoot("foo/bar"); + + Assert.NotNull(result); + } + + [Fact] + public void Returns_Null_Given_Null_Path() + { + var result = FileSafety.StripPathRoot(null); + + Assert.Null(result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "Music/Artist")] + [InlineData("C:/Music/Artist", "Music/Artist")] + [InlineData("D:\\path\\to\\file", "path/to/file")] + [InlineData("Z:\\", "")] + [InlineData("Z:/", "")] + [InlineData("Z:", "")] // bare drive letter, no separator + [InlineData("c:\\Music", "Music")] // lowercase drive letter + [InlineData("A:/single", "single")] + public void Linux_Strips_DriveRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("C:\\Music\\Artist", "Music\\Artist")] + [InlineData("C:/Music/Artist", "Music\\Artist")] + [InlineData("D:\\path\\to\\file", "path\\to\\file")] + [InlineData("Z:\\", "")] + [InlineData("Z:", "")] + [InlineData("c:\\Music", "Music")] + public void Windows_Strips_DriveRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("//server/share/Music", "share/Music")] + [InlineData("//server/Music", "Music")] + [InlineData("//192.168.1.1/share/folder", "share/folder")] + [InlineData("//server", "")] // no path after server + public void Linux_Strips_UncRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\\\server\\share\\Music", "share\\Music")] + [InlineData("\\\\server\\Music", "Music")] + [InlineData("\\\\192.168.1.1\\share\\folder", "share\\folder")] + [InlineData("\\\\server", "")] // no path after server + public void Windows_Strips_UncRoot(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde/Music/Artist", "Music/Artist")] + [InlineData("@@abcdefgh/Music", "Music")] + [InlineData("@@abcde\\Music\\Artist", "Music/Artist")] + public void Linux_Strips_SoulseekQtPrefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcde\\Music\\Artist", "Music\\Artist")] + [InlineData("@@abcdefgh\\Music", "Music")] + [InlineData("@@abcde/Music/Artist", "Music\\Artist")] + public void Windows_Strips_SoulseekQtPrefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abc/Music")] // only 3 alphanumeric chars — does not match + [InlineData("@@abcd/Music")] // only 4 — does not match + public void DoesNotStrip_SoulseekQtPrefix_When_Prefix_Too_Short(string input) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.StartsWith("@@", result); + } + + [Theory] + [InlineData("Music/Artist", "Music/Artist")] + [InlineData("Artist/Album/song.flac", "Artist/Album/song.flac")] + [InlineData("just_a_filename.flac", "just_a_filename.flac")] + [InlineData("", "")] + [InlineData("foo", "foo")] + public void Linux_ReturnsUnchanged_Given_Relative_Path(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("Music\\Artist", "Music\\Artist")] + [InlineData("Artist\\Album\\song.flac", "Artist\\Album\\song.flac")] + [InlineData("just_a_filename.flac", "just_a_filename.flac")] + [InlineData("foo", "foo")] + public void Windows_ReturnsUnchanged_Given_Relative_Path(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("/home/user/Music", "/home/user/Music")] + [InlineData("/Music", "/Music")] + [InlineData("/single", "/single")] + public void Linux_ReturnsUnchanged_Given_Single_ForwardSlash_Prefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("\\Music", "\\Music")] + [InlineData("\\home\\user", "\\home\\user")] + public void Windows_ReturnsUnchanged_Given_Single_BackwardSlash_Prefix(string input, string expected) + { + var result = FileSafety.StripPathRoot(input, OSPlatform.Windows); + + Assert.Equal(expected, result); + } + } +} \ No newline at end of file -- cgit v1.2.3 From 0a30f1080595a877d8c4b30f796e7055302de2cc Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 08:53:45 -0500 Subject: remove deprecated extension methods --- src/slskd/Common/CommonExtensions.cs | 46 ------ .../Extensions/ToLocalRelativeFilenameTests.cs | 160 --------------------- 2 files changed, 206 deletions(-) delete mode 100644 tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index c37c1550..95721163 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -381,21 +381,6 @@ namespace slskd .Build() .Deserialize(str); - /// - /// Converts a fully qualified remote filename to a local filename based in the provided - /// , swapping directory characters for those specific to the local OS, removing any - /// characters that are invalid for the local OS, and making the path relative to the remote store (including the - /// filename and the parent folder). - /// - /// The fully qualified remote filename to convert. - /// The base directory for the local filename. - /// The converted filename. - [Obsolete("Find something more intelligent to do instead of this")] - public static string ToLocalFilename(this string remoteFilename, string baseDirectory) - { - return FileSafety.CombineSafely(baseDirectory, remoteFilename.ToLocalRelativeFilename()); - } - /// /// Converts the given path to the normalized format (normalizes path separators to backslashes). /// @@ -429,37 +414,6 @@ namespace slskd return path.Split('\\').TakeLast(1).First(); } - /// - /// Converts a fully qualified remote filename to a local filename, swapping directory characters for those specific - /// to the local OS, removing any characters that are invalid for the local OS, and making the path relative to the - /// remote store (including the filename and the parent folder). - /// - /// The fully qualified remote filename to convert. - /// The converted filename. - [Obsolete("Find something more intelligent to do instead of this")] - public static string ToLocalRelativeFilename(this string remoteFilename) - { - if (string.IsNullOrWhiteSpace(remoteFilename)) - { - throw new ArgumentException($"Invalid remote filename; expected a non-whitespace value, received '{remoteFilename}'", nameof(remoteFilename)); - } - - // normalize path separators - var localizedRemoteFilename = FileSafety.LocalizePath(remoteFilename); - - var parts = localizedRemoteFilename.Split(Path.DirectorySeparatorChar); - - if (parts.Length == 1) - { - return FileSafety.SanitizeFilename(parts.First()); - } - - var file = FileSafety.SanitizeFilename(parts.Last()); - var directory = FileSafety.SanitizeFilename(parts.Reverse().Skip(1).Take(1).Single()); - - return FileSafety.CombineSafely(directory, file); - } - /// /// Converts a ModelStateDictionary into a human-readable format. /// diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs deleted file mode 100644 index 78539142..00000000 --- a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs +++ /dev/null @@ -1,160 +0,0 @@ -namespace slskd.Tests.Unit.Common.Extensions -{ - using System; - using System.IO; - using System.Linq; - using Xunit; - - public class ToLocalRelativeFilenameTests - { - [Theory] - [InlineData(null)] - [InlineData("")] - [InlineData("\t")] - public void Throws_ArgumentException_Given_Bad_Remote_Filename(string filename) - { - var ex = Record.Exception(() => filename.ToLocalRelativeFilename()); - - Assert.NotNull(ex); - Assert.IsType(ex); - } - - [Fact] - public void Returns_Last_Directory_And_Filename_From_Deep_Path() - { - var expected = "path" + Path.DirectorySeparatorChar + "file.ext"; - Assert.Equal(expected, @"deeply\nested\path\file.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Returns_Just_Filename_If_No_Directory_Given() - { - Assert.Equal("file.ext", "file.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Replaces_Invalid_Characters_In_Filename() - { - // Exclude backslash and forward slash — they act as segment separators in the input - // and would cause the dirty string to be split rather than treated as a filename. - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - var dirtyName = new string(invalidChars); - var result = $@"a\b\{dirtyName}".ToLocalRelativeFilename(); - var filename = Path.GetFileName(result); - - Assert.All(invalidChars, c => - Assert.False(filename.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in filename")); - } - - [Fact] - public void Replaces_Invalid_Characters_In_Directory() - { - // Directory segments are sanitized with ReplaceInvalidFileNameCharacters, so the full - // GetInvalidFileNameChars() set applies (excluding path separators, which split the input). - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - var dirtyName = new string(invalidChars); - var result = $@"a\{dirtyName}\file.ext".ToLocalRelativeFilename(); - var directory = Path.GetDirectoryName(result); - - Assert.All(invalidChars, c => - Assert.False(directory.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in directory")); - } - - [Fact] - public void Replaces_Each_Invalid_Filename_Character_Individually() - { - // Tests each invalid filename char in isolation so that failures identify the exact - // offending character rather than only reporting that something in a concatenated - // string was not replaced. - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - Assert.All(invalidChars, c => - { - var result = $@"a\b\prefix{c}suffix.ext".ToLocalRelativeFilename(); - var filename = Path.GetFileName(result); - Assert.False(filename.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in filename"); - }); - } - - [Fact] - public void Replaces_Each_Invalid_Filename_Character_In_Directory_Individually() - { - // Tests each invalid filename char in the directory segment in isolation so that - // failures identify the exact offending character. - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - Assert.All(invalidChars, c => - { - var result = $@"a\prefix{c}suffix\file.ext".ToLocalRelativeFilename(); - var directory = Path.GetDirectoryName(result); - Assert.False(directory.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in directory"); - }); - } - - [Fact] - public void Returns_Last_Directory_And_Filename_From_Two_Segment_Path() - { - var expected = "dir" + Path.DirectorySeparatorChar + "file.ext"; - Assert.Equal(expected, @"dir\file.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Handles_Forward_Slash_As_Segment_Separator() - { - // LocalizePath normalizes '/' to Path.DirectorySeparatorChar before splitting, - // so forward-slash paths must produce the same result as backslash paths. - var expected = "b" + Path.DirectorySeparatorChar + "c.ext"; - Assert.Equal(expected, "a/b/c.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Handles_Mixed_Slash_Separators() - { - var expected = "b" + Path.DirectorySeparatorChar + "c.ext"; - Assert.Equal(expected, @"a/b\c.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Preserves_Spaces_In_Filename() - { - // Spaces are valid in file names and must survive sanitization. - var expected = "dir" + Path.DirectorySeparatorChar + "file name.ext"; - Assert.Equal(expected, @"root\dir\file name.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Preserves_Spaces_In_Directory() - { - var expected = "my dir" + Path.DirectorySeparatorChar + "file.ext"; - Assert.Equal(expected, @"root\my dir\file.ext".ToLocalRelativeFilename()); - } - - [Fact] - public void Directory_Segment_Contains_No_Characters_Invalid_For_Directory_Names() - { - // All GetInvalidFileNameChars() (minus separators) must be absent from the directory - // segment. Directory segments are sanitized with ReplaceInvalidFileNameCharacters, so - // the full filename-invalid set applies. - var invalidChars = Path.GetInvalidFileNameChars() - .Where(c => c != '\\' && c != '/') - .ToArray(); - - Assert.All(invalidChars, c => - { - var result = $@"a\prefix{c}suffix\file.ext".ToLocalRelativeFilename(); - var directory = Path.GetDirectoryName(result); - Assert.False(directory.Contains(c), $"Character U+{(int)c:X4} is invalid for directory names but was not replaced"); - }); - } - } -} \ No newline at end of file -- cgit v1.2.3 From c89de5d4bcb56202a6879d752a685a7fc81d2920 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 08:57:19 -0500 Subject: temporarily back out destination permissions --- config/slskd.example.yml | 2 -- src/slskd/Core/Options.cs | 37 ------------------------ src/slskd/Transfers/Downloads/DownloadService.cs | 4 +-- 3 files changed, 2 insertions(+), 41 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index b66879e3..f616cd8a 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -81,8 +81,6 @@ # destination: # subdirectory: {SOURCE_DIRECTORY} # exists: 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 4e7dca7b..f2a78247 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1082,43 +1082,6 @@ namespace slskd /// [Enum(typeof(DestinationExistsStrategy))] public string Exists { get; init; } = DestinationExistsStrategy.Rename.ToString().ToLowerInvariant(); - - /// - /// Gets the permissions to apply to downloaded files and directories. - /// - [Validate] - public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions(); - - /// - /// Download destination permission options. - /// - public class DestinationPermissionsOptions : IValidatableObject - { - /// - /// Gets the permissions to apply to newly created files. - /// - /// - /// Applicable to non-Windows operating systems, only. - /// - public string Mode { get; init; } - - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - 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; - } - } } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 48c29b19..85de28b0 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1218,8 +1218,8 @@ namespace slskd.Transfers.Downloads }), disposeOutputStreamOnCompletion: true); - UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode) - ? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode.ToUnixFileMode() + UnixFileMode? unixFileMode = !string.IsNullOrEmpty(OptionsMonitor.CurrentValue.Permissions.File.Mode) + ? OptionsMonitor.CurrentValue.Permissions.File.Mode.ToUnixFileMode() : null; /* -- cgit v1.2.3 From e479f3a213d13cb8b165237a594bcb86b7462606 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 10:05:45 -0500 Subject: add informational log --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 85de28b0..9e240a7e 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1363,7 +1363,7 @@ namespace slskd.Transfers.Downloads overwrite: existsStrategy == DestinationExistsStrategy.Overwrite, deleteSourceDirectoryIfEmptyAfterMove: true); - Log.Debug("Moved file {Filename} to {Destination}", transfer.Filename, finalFilename); + Log.Information("Moved file {Filename} from {Username} from {Incomplete} to {Destination}", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, incompleteFilename, finalFilename); if (OptionsMonitor.CurrentValue.Relay.Enabled) { -- cgit v1.2.3 From e06999e5eec1616d93b34ffbab0eade617d1aaf6 Mon Sep 17 00:00:00 2001 From: "dependabot[bot]" <49699333+dependabot[bot]@users.noreply.github.com> Date: Wed, 3 Jun 2026 21:31:33 +0000 Subject: Bump launch-editor from 2.6.0 to 2.14.1 in /src/web Bumps [launch-editor](https://github.com/vitejs/launch-editor) from 2.6.0 to 2.14.1. - [Commits](https://github.com/vitejs/launch-editor/compare/v2.6.0...v2.14.1) --- updated-dependencies: - dependency-name: launch-editor dependency-version: 2.14.1 dependency-type: indirect ... Signed-off-by: dependabot[bot] --- src/web/package-lock.json | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) (limited to 'src') diff --git a/src/web/package-lock.json b/src/web/package-lock.json index 22d9c714..e64bc38d 100644 --- a/src/web/package-lock.json +++ b/src/web/package-lock.json @@ -14304,13 +14304,14 @@ } }, "node_modules/launch-editor": { - "version": "2.6.0", - "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.6.0.tgz", - "integrity": "sha512-JpDCcQnyAAzZZaZ7vEiSqL690w7dAEyLao+KC96zBplnYbJS7TYNjvM3M7y3dGz+v7aIsJk3hllWuc0kWAjyRQ==", + "version": "2.14.1", + "resolved": "https://registry.npmjs.org/launch-editor/-/launch-editor-2.14.1.tgz", + "integrity": "sha512-QWBrQsMpH7gPr965dsKD/3cKWiNoTjpATQf++Xq63N6sKRGMwlVXz41O1IZTMfZQgBctD/K5Zt06+/I6pP6+HA==", "dev": true, + "license": "MIT", "dependencies": { - "picocolors": "^1.0.0", - "shell-quote": "^1.7.3" + "picocolors": "^1.1.1", + "shell-quote": "^1.8.4" } }, "node_modules/less": { @@ -18840,10 +18841,14 @@ } }, "node_modules/shell-quote": { - "version": "1.8.1", - "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.1.tgz", - "integrity": "sha512-6j1W9l1iAs/4xYBI1SYOVZyFcCis9b4KCLQ8fgAGG07QvzaRLVVRQvAy85yNmmZSjYjg4MWh4gNvlPujU/5LpA==", + "version": "1.8.4", + "resolved": "https://registry.npmjs.org/shell-quote/-/shell-quote-1.8.4.tgz", + "integrity": "sha512-VsC6n6vz1ihYYyZZwX7YZSF5l5x36ca17OC+a69h94YqB7X6XLwf+5MOgynYir2SLFUbl8gIYvBo8K8RoNQ6bQ==", "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.4" + }, "funding": { "url": "https://github.com/sponsors/ljharb" } -- cgit v1.2.3 From 78561f600754241efdf06c0fcee5ffdbdccda1b6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 18:56:06 -0500 Subject: wip --- .../Common/Validation/AbsolutePathAttribute.cs | 36 +++++++++++++++++++--- .../Common/Validation/RelativePathAttribute.cs | 36 ++++++++++++++++++++-- src/slskd/Core/Options.cs | 8 ++--- 3 files changed, 69 insertions(+), 11 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index eb1c9069..8ee486c5 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -40,16 +40,19 @@ namespace slskd.Validation /// public class AbsolutePathAttribute : ValidationAttribute { - public AbsolutePathAttribute() + public AbsolutePathAttribute(bool platformAgnostic = false) { + PlatformAgnostic = platformAgnostic; } - public AbsolutePathAttribute(OSPlatform? os = null) + public AbsolutePathAttribute(bool platformAgnostic = false, OSPlatform? os = null) { + PlatformAgnostic = platformAgnostic; OS = os; } public OSPlatform? OS { get; } + public bool PlatformAgnostic { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { @@ -57,9 +60,34 @@ namespace slskd.Validation { var path = value.ToString(); - if (!FileSafety.IsPathAbsolute(path, os: OS)) + if (OS.HasValue) { - return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); + if (!FileSafety.IsPathAbsolute(path, os: OS)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); + } + } + else + { + if (!PlatformAgnostic) + { + if (!FileSafety.IsPathAbsolute(path, os: OS)) // this OS + { + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); + } + } + else + { + if (!FileSafety.IsPathAbsolute(path, os: OSPlatform.Linux)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); + } + + if (!FileSafety.IsPathAbsolute(path, os: OSPlatform.Windows)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); + } + } } } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index f465ba98..a3a3d435 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -40,8 +40,9 @@ namespace slskd.Validation /// public class RelativePathAttribute : ValidationAttribute { - public RelativePathAttribute() + public RelativePathAttribute(bool platformAgnostic = false) { + PlatformAgnostic = platformAgnostic; } public RelativePathAttribute(OSPlatform? os = null) @@ -50,15 +51,44 @@ namespace slskd.Validation } public OSPlatform? OS { get; } + public bool PlatformAgnostic { get; } + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && value is string str && !string.IsNullOrEmpty(str)) { var path = value.ToString(); - if (!FileSafety.IsPathRelative(path, os: OS)) + if (OS.HasValue) + { + // this can only be exercised via unit tests; OSPlatform can't be passeed as an attribute argument + // so, this takes precedent over PlatformAgnostic + if (!FileSafety.IsPathRelative(path, os: OS)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + } + } + else { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + if (!PlatformAgnostic) + { + if (!FileSafety.IsPathRelative(path, os: null)) // this OS + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + } + } + else + { + if (!FileSafety.IsPathRelative(path, os: OSPlatform.Linux)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + } + + if (!FileSafety.IsPathRelative(path, os: OSPlatform.Windows)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + } + } } } diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index f2a78247..9ad1a626 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -765,7 +765,7 @@ namespace slskd [Argument(default, "incomplete")] [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] - [AbsolutePath] + [AbsolutePath(platformAgnostic: true)] [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] @@ -777,7 +777,7 @@ namespace slskd [Argument('o', "downloads")] [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] - [AbsolutePath] + [AbsolutePath(platformAgnostic: true)] [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] @@ -1072,7 +1072,7 @@ namespace slskd /// /// Gets the destination subdirectory for the files in the batch. /// - [RelativePath] + [RelativePath(platformAgnostic: true)] [NonTraversingPath] [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] public string Subdirectory { get; init; } = "{SOURCE_DIRECTORY}"; @@ -2046,7 +2046,7 @@ namespace slskd [Argument(default, "http-socket")] [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] - [AbsolutePath] + [AbsolutePath(platformAgnostic: false)] [NonTraversingPath] [RequiresRestart] public string Socket { get; init; } -- cgit v1.2.3 From 70520ee0e09526cd86a4bdf6573cbc6f3af717da Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:10:50 -0500 Subject: add our own OperatingSystem enum because why not at this point --- src/slskd/Common/Compute.cs | 18 ++++------------ src/slskd/Common/OperatingSystem.cs | 42 +++++++++++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+), 14 deletions(-) create mode 100644 src/slskd/Common/OperatingSystem.cs (limited to 'src') diff --git a/src/slskd/Common/Compute.cs b/src/slskd/Common/Compute.cs index dc565806..d235a87c 100644 --- a/src/slskd/Common/Compute.cs +++ b/src/slskd/Common/Compute.cs @@ -66,24 +66,14 @@ namespace slskd return BitConverter.ToString(sha256.ComputeHash(Encoding.UTF8.GetBytes(str))).Replace("-", string.Empty); } - public static OSPlatform OSPlatform() + public static OperatingSystem OperatingSystem() { - if (OperatingSystem.IsWindows()) + if (System.OperatingSystem.IsWindows()) { - return System.Runtime.InteropServices.OSPlatform.Windows; + return slskd.OperatingSystem.Windows; } - if (OperatingSystem.IsMacOS()) - { - return System.Runtime.InteropServices.OSPlatform.OSX; - } - - if (OperatingSystem.IsFreeBSD()) - { - return System.Runtime.InteropServices.OSPlatform.FreeBSD; - } - - return System.Runtime.InteropServices.OSPlatform.Linux; + return slskd.OperatingSystem.Linux; } } } \ No newline at end of file diff --git a/src/slskd/Common/OperatingSystem.cs b/src/slskd/Common/OperatingSystem.cs new file mode 100644 index 00000000..97c205a6 --- /dev/null +++ b/src/slskd/Common/OperatingSystem.cs @@ -0,0 +1,42 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ 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 +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd; + +public enum OperatingSystem +{ + None = 0, + Current = 1, + Linux = 2, + Windows = 3, + Any = 4, +} \ No newline at end of file -- cgit v1.2.3 From 48f9412b8e9be15b36a2bd7335d6b7a8a0448421 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:17:24 -0500 Subject: so dumb --- src/slskd/Common/OperatingSystem.cs | 7 ++-- .../Common/Validation/AbsolutePathAttribute.cs | 39 +++++++++++++++++----- .../Common/Validation/RelativePathAttribute.cs | 39 ++++++++++++++++++---- 3 files changed, 67 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/OperatingSystem.cs b/src/slskd/Common/OperatingSystem.cs index 97c205a6..0c3dae2c 100644 --- a/src/slskd/Common/OperatingSystem.cs +++ b/src/slskd/Common/OperatingSystem.cs @@ -35,8 +35,9 @@ namespace slskd; public enum OperatingSystem { None = 0, - Current = 1, - Linux = 2, - Windows = 3, + Linux = 1, + Windows = 2, + Current = 3, Any = 4, + All = 5, } \ No newline at end of file diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index eb1c9069..9393e524 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -33,23 +33,24 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.Runtime.InteropServices; /// /// Validates that the specified path is absolute. /// public class AbsolutePathAttribute : ValidationAttribute { - public AbsolutePathAttribute() + public AbsolutePathAttribute(OperatingSystem os = OperatingSystem.Current) { - } + if (os != OperatingSystem.Current && os != OperatingSystem.Any && os != OperatingSystem.All) + { + throw new System.ArgumentException("OperatingSystem argument for AbsolutePathAttribute must be one of: Current, Any, All", nameof(os)); + } - public AbsolutePathAttribute(OSPlatform? os = null) - { OS = os; } - public OSPlatform? OS { get; } + public OperatingSystem? OS { get; } + private OperatingSystem? Injected { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) { @@ -57,9 +58,31 @@ namespace slskd.Validation { var path = value.ToString(); - if (!FileSafety.IsPathAbsolute(path, os: OS)) + // this property can only be set via reflection in a unit test; this is here only to make this testable + if (Injected.HasValue) + { + if (!FileSafety.IsPathAbsolute(path, os: Injected)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path."); + } + + return ValidationResult.Success; + } + + if (OS == OperatingSystem.Current) + { + if (!FileSafety.IsPathAbsolute(path, os: Compute.OperatingSystem())) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on the current operating system."); + } + + return ValidationResult.Success; + } + + // OS == OperatingSystem.All or .Any + if (!FileSafety.IsPathAbsolute(path, os: OperatingSystem.Linux) || !FileSafety.IsPathAbsolute(path, os: OperatingSystem.Windows)) { - return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); + return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on all operating systems."); } } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index f465ba98..755ea311 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -33,30 +33,55 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; - using System.Runtime.InteropServices; /// /// Validates that the specified path is relative. /// public class RelativePathAttribute : ValidationAttribute { - public RelativePathAttribute() + public RelativePathAttribute(OperatingSystem os = OperatingSystem.Current) { - } + if (os != OperatingSystem.Current && os != OperatingSystem.Any && os != OperatingSystem.All) + { + throw new System.ArgumentException("OperatingSystem argument for RelativePathAttribute must be one of: Current, Any, All", nameof(os)); + } - public RelativePathAttribute(OSPlatform? os = null) - { OS = os; } - public OSPlatform? OS { get; } + public OperatingSystem OS { get; } + + private OperatingSystem? Injected { get; } + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null && value is string str && !string.IsNullOrEmpty(str)) { var path = value.ToString(); - if (!FileSafety.IsPathRelative(path, os: OS)) + // this property can only be set via reflection in a unit test; this is here only to make this testable + if (Injected.HasValue) + { + if (!FileSafety.IsPathRelative(path, os: Injected)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system."); + } + + return ValidationResult.Success; + } + + if (OS == OperatingSystem.Current) + { + if (!FileSafety.IsPathRelative(path, os: Compute.OperatingSystem())) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); + } + + return ValidationResult.Success; + } + + // OS == OperatingSystem.All or .Any; + if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows)) { return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } -- cgit v1.2.3 From c0212d05af5a9ec22ff5c89a24ea4d5761a48482 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:17:49 -0500 Subject: pass os in attributes --- src/slskd/Core/Options.cs | 8 ++++---- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index f2a78247..e76f5d2f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -765,7 +765,7 @@ namespace slskd [Argument(default, "incomplete")] [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] - [AbsolutePath] + [AbsolutePath(OperatingSystem.Current)] [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] @@ -777,7 +777,7 @@ namespace slskd [Argument('o', "downloads")] [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] - [AbsolutePath] + [AbsolutePath(OperatingSystem.Current)] [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] @@ -1072,7 +1072,7 @@ namespace slskd /// /// Gets the destination subdirectory for the files in the batch. /// - [RelativePath] + [RelativePath(OperatingSystem.All)] [NonTraversingPath] [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] public string Subdirectory { get; init; } = "{SOURCE_DIRECTORY}"; @@ -2046,7 +2046,7 @@ namespace slskd [Argument(default, "http-socket")] [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] - [AbsolutePath] + [AbsolutePath(OperatingSystem.Current)] [NonTraversingPath] [RequiresRestart] public string Socket { get; init; } diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index e569df30..fe34bfec 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -106,7 +106,7 @@ public record EnqueueDownloadBatchOptions /// /// The destination directory for the files, relative to the configured download directory. /// - [RelativePath] + [RelativePath(OperatingSystem.All)] [NonTraversingPath] [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] public string Destination { get; init; } -- cgit v1.2.3 From 31a9b5918d49650564c4b59c8ae95a16412bef9c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:18:03 -0500 Subject: use OperatingSystem instead of the other thing --- src/slskd/Common/FileSafety.cs | 55 +++++++++++++++++++++++------------------- 1 file changed, 30 insertions(+), 25 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 5a5d964e..b72d3749 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -35,7 +35,6 @@ namespace slskd; using System; using System.IO; using System.Linq; -using System.Runtime.InteropServices; using System.Text.RegularExpressions; /// @@ -85,7 +84,7 @@ public static class FileSafety /// The combined path. /// Thrown if the root, list of segments, or one or more segments is null. /// Thrown if any of the specified segments is rooted, or if any contain path traversal characters. - public static string CombineSafely(string root, OSPlatform? os, params string[] segments) + public static string CombineSafely(string root, OperatingSystem? os, params string[] segments) { // ensure no inputs are null. matches the behavior of Path.Combine() if (string.IsNullOrWhiteSpace(root)) @@ -103,7 +102,7 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } - var isWindows = os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows(); + var isWindows = os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows(); foreach (var segment in segments) { @@ -170,15 +169,18 @@ public static class FileSafety /// The path to check. /// An optional operating system override, for testing. /// True if the path is absolute, false otherwise. - public static bool IsPathAbsolute(string path, OSPlatform? os = null) + public static bool IsPathAbsolute(string path, OperatingSystem? os = null) { if (string.IsNullOrEmpty(path)) { return false; } - if (os.HasValue ? os.Value == OSPlatform.Windows : OperatingSystem.IsWindows()) + Console.WriteLine($"IsPathAbsolute? path: {path}, os: {os}, iswindows? {System.OperatingSystem.IsWindows()}"); + + if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows()) { + Console.WriteLine("Windows!"); // Windows drive-letter path: X:\ or X:/ // X:foo is relative on windows if (path.Length >= 3 @@ -198,6 +200,8 @@ public static class FileSafety return false; } + Console.WriteLine("Linux!"); + // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with / if (path.StartsWith('/')) { @@ -214,7 +218,7 @@ public static class FileSafety /// The path to check. /// An optional operating system override, for testing. /// True if the path is relative, false otherwise. - public static bool IsPathRelative(string path, OSPlatform? os = null) => !IsPathAbsolute(path, os); + public static bool IsPathRelative(string path, OperatingSystem? os = null) => !IsPathAbsolute(path, os); /// /// Returns the filename from the specified , properly @@ -224,7 +228,7 @@ public static class FileSafety /// An optional value indicating that invalid characters should not be replaced. /// An optional operating system override, for testing. /// The extracted filename. - public static string GetFileNameSafely(string path, bool sanitize = true, OSPlatform? os = null) + public static string GetFileNameSafely(string path, bool sanitize = true, OperatingSystem? os = null) { if (path is null or "" || path.EndsWith('/') || path.EndsWith('\\')) { @@ -256,7 +260,7 @@ public static class FileSafety /// An optional operating system override, for testing. /// The directory name. /// Thrown if the specified path is null. - public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OSPlatform? os = null) + public static string GetDirectoryNameSafely(string path, bool retainRoot = false, bool sanitize = true, OperatingSystem? os = null) { if (path is null or "") { @@ -271,8 +275,8 @@ public static class FileSafety var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); - os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; var local = LocalizePath(path, os) .TrimEnd('/', '\\'); // treat file-less paths the same as files @@ -322,15 +326,15 @@ public static class FileSafety /// The path to convert. /// An optional operating system override, for testing. /// The converted path. - public static string LocalizePath(string path, OSPlatform? os = null) + public static string LocalizePath(string path, OperatingSystem? os = null) { if (path is null) { return null; } - os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; return path.Replace('\\', sep).Replace('/', sep); } @@ -344,7 +348,7 @@ public static class FileSafety /// The character to substitute for invalid characters. /// An optional operating system override, for testing. /// The sanitized filename. - public static string SanitizeFilename(string filename, char replacement = '_', OSPlatform? os = null) + public static string SanitizeFilename(string filename, char replacement = '_', OperatingSystem? os = null) { if (filename is null) { @@ -356,9 +360,9 @@ public static class FileSafety throw new ArgumentException($"The provided replacement character '{replacement}' is invalid in filenames"); } - os ??= Compute.OSPlatform(); + os ??= Compute.OperatingSystem(); - var characters = os.Value == OSPlatform.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; + var characters = os.Value == OperatingSystem.Windows ? InvalidFileNameCharactersOnWindows : InvalidFileNameCharactersOnUnix; if (characters.Contains(replacement)) { @@ -388,7 +392,7 @@ public static class FileSafety /// The character to substitute for invalid characters. /// An optional operating system override, for testing. /// The sanitized path segment. - public static string SanitizePathSegment(string segment, char replacement = '_', OSPlatform? os = null) + public static string SanitizePathSegment(string segment, char replacement = '_', OperatingSystem? os = null) { var sanitized = SanitizeFilename(segment, replacement, os); @@ -418,10 +422,10 @@ public static class FileSafety /// /// The path. /// The character to substitute for invalid characters. - /// An optional value indicating whether to keep the path's root, if present. + /// An optional value indicating whether to strip the path's root, if present. /// An optional operating system override, for testing. /// The sanitized path. - public static string SanitizePath(string path, char replacement = '_', bool retainRoot = false, OSPlatform? os = null) + public static string SanitizePath(string path, char replacement = '_', bool stripRoot = false, OperatingSystem? os = null) { if (path is null) { @@ -430,13 +434,13 @@ public static class FileSafety var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); - os ??= Compute.OSPlatform(); - var sep = os.Value == OSPlatform.Windows ? '\\' : '/'; + os ??= Compute.OperatingSystem(); + var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; // flip slashes the correct way path = LocalizePath(path, os); - if (!retainRoot) + if (stripRoot) { // strip C:\ or //server, if present (regardless of slash variant, etc) path = StripPathRoot(path, os); @@ -450,9 +454,10 @@ public static class FileSafety var newPath = string.Join(sep, segments); - if (retainRoot) + if (!stripRoot) { - // leading slashes are stripped of leading slashes by Split() so we must add them back + // leading slashes are stripped by Split() so we must add them back, + // unless we intended to strip the root return new string(sep, leadingSlashCount) + newPath; } @@ -467,7 +472,7 @@ public static class FileSafety /// The path to strip. /// An optional operating system override, for testing. /// The path with the root stripped, if one was present. - public static string StripPathRoot(string path, OSPlatform? os = null) + public static string StripPathRoot(string path, OperatingSystem? os = null) { if (path is null) { -- cgit v1.2.3 From 389ef5a3f0069df2a2560a32da8804cda78be16b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:18:46 -0500 Subject: now we have to disambiguate OperatingSystem --- src/slskd/Application.cs | 2 +- src/slskd/Common/Dumper.cs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Application.cs b/src/slskd/Application.cs index e3d212f7..2b9a1f93 100644 --- a/src/slskd/Application.cs +++ b/src/slskd/Application.cs @@ -551,7 +551,7 @@ namespace slskd { socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true); - if (OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive) + if (System.OperatingSystem.IsWindows() && OptionsAtStartup.Flags.LegacyWindowsTcpKeepalive) { return; } diff --git a/src/slskd/Common/Dumper.cs b/src/slskd/Common/Dumper.cs index f4367e61..27304873 100644 --- a/src/slskd/Common/Dumper.cs +++ b/src/slskd/Common/Dumper.cs @@ -84,7 +84,7 @@ namespace slskd await Download(url, BinFile); - if (!OperatingSystem.IsWindows()) + if (!System.OperatingSystem.IsWindows()) { await ExecAsync("/bin/sh", $"-c \"chmod +x {BinFile}\""); } @@ -139,15 +139,15 @@ namespace slskd string os = default; // seems like there should be a way to just retrieve this, but there is not as of .NET 6 - if (OperatingSystem.IsLinux()) + if (System.OperatingSystem.IsLinux()) { os = "linux"; } - else if (OperatingSystem.IsWindows()) + else if (System.OperatingSystem.IsWindows()) { os = "win"; } - else if (OperatingSystem.IsMacOS() || OperatingSystem.IsFreeBSD()) + else if (System.OperatingSystem.IsMacOS() || System.OperatingSystem.IsFreeBSD()) { os = "osx"; } -- cgit v1.2.3 From 9a08d5029880c2be008685990f0c83f221ec0e75 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 3 Jun 2026 23:19:21 -0500 Subject: specify replacement explicitly --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 9e240a7e..84753547 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -865,7 +865,7 @@ namespace slskd.Transfers.Downloads return match.Value; }); - destination = FileSafety.SanitizePath(destination); + destination = FileSafety.SanitizePath(destination, replacement: '_', stripRoot: false); Log.Debug("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text }); -- cgit v1.2.3 From e5d362836ce8892487864170abdc31fc032989c5 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 08:07:48 -0500 Subject: fix junk --- src/slskd/Common/FileSafety.cs | 5 ---- .../Common/Validation/RelativePathAttribute.cs | 31 ++-------------------- 2 files changed, 2 insertions(+), 34 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index b72d3749..a07de6d1 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -176,11 +176,8 @@ public static class FileSafety return false; } - Console.WriteLine($"IsPathAbsolute? path: {path}, os: {os}, iswindows? {System.OperatingSystem.IsWindows()}"); - if (os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows()) { - Console.WriteLine("Windows!"); // Windows drive-letter path: X:\ or X:/ // X:foo is relative on windows if (path.Length >= 3 @@ -200,8 +197,6 @@ public static class FileSafety return false; } - Console.WriteLine("Linux!"); - // Unix/Linux/macOS absolute paths and UNC paths with forward slashes start with / if (path.StartsWith('/')) { diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 62185a42..1bdbd4fb 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -83,38 +83,11 @@ namespace slskd.Validation // OS == OperatingSystem.All or .Any; if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows)) { - // this can only be exercised via unit tests; OSPlatform can't be passeed as an attribute argument - // so, this takes precedent over PlatformAgnostic - if (!FileSafety.IsPathRelative(path, os: OS)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - } - else - { - if (!PlatformAgnostic) - { - if (!FileSafety.IsPathRelative(path, os: null)) // this OS - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - } - else - { - if (!FileSafety.IsPathRelative(path, os: OSPlatform.Linux)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - - if (!FileSafety.IsPathRelative(path, os: OSPlatform.Windows)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); - } - } + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } } return ValidationResult.Success; } } -} +} \ No newline at end of file -- cgit v1.2.3 From 483e37f64def66cecb01a8c471d35e2937178960 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 18:07:07 -0500 Subject: change how property injection impacts path validation --- src/slskd/Common/Validation/AbsolutePathAttribute.cs | 13 +------------ src/slskd/Common/Validation/RelativePathAttribute.cs | 13 +------------ 2 files changed, 2 insertions(+), 24 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 9393e524..f2615315 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -58,20 +58,9 @@ namespace slskd.Validation { var path = value.ToString(); - // this property can only be set via reflection in a unit test; this is here only to make this testable - if (Injected.HasValue) - { - if (!FileSafety.IsPathAbsolute(path, os: Injected)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path."); - } - - return ValidationResult.Success; - } - if (OS == OperatingSystem.Current) { - if (!FileSafety.IsPathAbsolute(path, os: Compute.OperatingSystem())) + if (!FileSafety.IsPathAbsolute(path, os: Injected ?? Compute.OperatingSystem())) { return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute path on the current operating system."); } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index 1bdbd4fb..f691d4e5 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -59,20 +59,9 @@ namespace slskd.Validation { var path = value.ToString(); - // this property can only be set via reflection in a unit test; this is here only to make this testable - if (Injected.HasValue) - { - if (!FileSafety.IsPathRelative(path, os: Injected)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system."); - } - - return ValidationResult.Success; - } - if (OS == OperatingSystem.Current) { - if (!FileSafety.IsPathRelative(path, os: Compute.OperatingSystem())) + if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem())) { return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); } -- cgit v1.2.3 From fec423393232bc3b9b3a8b40ebeafb489c871e65 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 22:24:26 -0500 Subject: don't strip roots or restore slashes --- src/slskd/Common/FileSafety.cs | 22 +++------------------- 1 file changed, 3 insertions(+), 19 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index a07de6d1..73dd4b40 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -412,35 +412,26 @@ public static class FileSafety /// /// Sanitizes the specified to make it suitable and safe on the local operating system - /// by converting to the correct slashes, dropping a root (if present), replacing any invalid characters with - /// the specified , and by dropping any path traversal segments. + /// by converting to the correct slashes, replacing any invalid characters with the specified + /// , and by dropping any path traversal segments. /// /// The path. /// The character to substitute for invalid characters. - /// An optional value indicating whether to strip the path's root, if present. /// An optional operating system override, for testing. /// The sanitized path. - public static string SanitizePath(string path, char replacement = '_', bool stripRoot = false, OperatingSystem? os = null) + public static string SanitizePath(string path, char replacement = '_', OperatingSystem? os = null) { if (path is null) { return null; } - var leadingSlashCount = path.TakeWhile(c => c == '/' || c == '\\').Count(); - os ??= Compute.OperatingSystem(); var sep = os.Value == OperatingSystem.Windows ? '\\' : '/'; // flip slashes the correct way path = LocalizePath(path, os); - if (stripRoot) - { - // strip C:\ or //server, if present (regardless of slash variant, etc) - path = StripPathRoot(path, os); - } - // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings var segments = path .Split('/', '\\') @@ -449,13 +440,6 @@ public static class FileSafety var newPath = string.Join(sep, segments); - if (!stripRoot) - { - // leading slashes are stripped by Split() so we must add them back, - // unless we intended to strip the root - return new string(sep, leadingSlashCount) + newPath; - } - return newPath; } -- cgit v1.2.3 From 40913d2f6d2b6bd6ef41e4531c6dc62da1fe2b5d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 22:24:43 -0500 Subject: remove deprecated arg --- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 84753547..0f7805ba 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -865,7 +865,7 @@ namespace slskd.Transfers.Downloads return match.Value; }); - destination = FileSafety.SanitizePath(destination, replacement: '_', stripRoot: false); + destination = FileSafety.SanitizePath(destination, replacement: '_'); Log.Debug("Derived destination for download of {Filename} from {User}: {Destination} (id: {Id}, configuration: {Pattern}, args: {Args})", FileSafety.GetFileNameSafely(transfer.Filename), transfer.Username, destination, transfer.Id, pattern, new { source_username, source_path, source_directory, batch_id, batch_external_id, search_id, search_text }); -- cgit v1.2.3 From ee41b93605a380480a5f7d826e7ae0602cd52de1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 4 Jun 2026 22:52:37 -0500 Subject: wip --- src/slskd/Common/FileSafety.cs | 6 +- .../Common/FileSafety/CombineSafelyTests.cs | 38 +++++++++++ .../FileSafety/ContainsTraversalSegmentsTests.cs | 3 + .../FileSafety/GetDirectoryNameSafelyTests.cs | 79 ++++++++++++++++++++++ .../Common/FileSafety/GetFileNameSafelyTests.cs | 32 +++++++++ .../Common/FileSafety/IsPathTests.cs | 3 + .../Common/FileSafety/LocalizePathTests.cs | 4 ++ .../Common/FileSafety/SanitizeFilenameTests.cs | 16 +++++ .../Common/FileSafety/SanitizePathSegmentTests.cs | 1 + .../Common/FileSafety/SanitizePathTests.cs | 36 ++++++++++ .../Common/FileSafety/StripPathRootTests.cs | 18 +++++ 11 files changed, 234 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 73dd4b40..bf81da0e 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -432,11 +432,13 @@ public static class FileSafety // flip slashes the correct way path = LocalizePath(path, os); - // for each segment, drop nulls (created by double slashes), sanitize, and replace traversal strings + // for each segment, drop nulls (created by double slashes), sanitize, replace traversal strings, + // and drop any segments that sanitization reduced to empty (e.g. a single invalid char with '.' replacement) var segments = path .Split('/', '\\') .Where(s => s is not "") - .Select(s => SanitizePathSegment(s, replacement, os)); + .Select(s => SanitizePathSegment(s, replacement, os)) + .Where(s => s is not ""); var newPath = string.Join(sep, segments); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index ee5a69d8..c3b69b12 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -218,6 +218,44 @@ public partial class FileSafetyTests } } + [Fact] + public void Returns_Root_Given_Single_Empty_Segment() + { + var result = FileSafety.CombineSafely(Base, ""); + + Assert.Equal(Base, result); + } + + [Fact] + public void Returns_Root_Given_All_Empty_Segments() + { + var result = FileSafety.CombineSafely(Base, "", ""); + + Assert.Equal(Base, result); + } + + [Fact] + public void Handles_Root_With_Trailing_Separator() + { + var rootWithTrailing = Base + Path.DirectorySeparatorChar; + var result = FileSafety.CombineSafely(rootWithTrailing, "foo"); + + Assert.StartsWith(ExpectedStartsWith, result); + Assert.EndsWith("foo", result); + } + + [Theory] + [InlineData("./foo")] + [InlineData("../bar")] + [InlineData("foo/../bar")] + public void Throws_ArgumentException_Given_TraversingRoot_With_Os_Override(string root) + { + var ex = Record.Exception(() => FileSafety.CombineSafely(root, OperatingSystem.Linux, "segment")); + + Assert.NotNull(ex); + Assert.IsType(ex); + } + [Theory] // Bare traversal [InlineData("..")] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs index 205c87c2..f0b1a394 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/ContainsTraversalSegmentsTests.cs @@ -106,6 +106,9 @@ public partial class FileSafetyTests [InlineData("Ünïcödé/..hidden")] [InlineData("пользователь/...dir")] [InlineData("用户/..名前")] + // Segments that look like traversal but have surrounding whitespace — not exact matches + [InlineData(" . ")] + [InlineData(" .. ")] public void Path_DoesNotContainTraversal(string path) { Assert.False(FileSafety.ContainsTraversalSegments(path)); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs index 3ac48efd..eaeaa29f 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetDirectoryNameSafelyTests.cs @@ -45,6 +45,14 @@ public partial class FileSafetyTests Assert.Null(result); } + [Fact] + public void Returns_Null_Given_Whitespace_Only() + { + var result = FileSafety.GetDirectoryNameSafely(" "); + + Assert.Null(result); + } + [Theory] [InlineData("foo")] [InlineData("foo.bar")] @@ -192,6 +200,77 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + [Theory] + [InlineData("Artist/Album/", "Artist")] + [InlineData("Artist\\Album\\", "Artist")] + [InlineData("foo/bar/baz/", "foo/bar")] + public void Treats_Trailing_Slash_As_Directory_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("Artist/Album/", "Artist")] + [InlineData("Artist\\Album\\", "Artist")] + [InlineData("foo/bar/baz/", "foo\\bar")] + public void Treats_Trailing_Slash_As_Directory_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o/bar", "fo\0o")] + [InlineData("C:/Mu\0sic/song.flac", "Mu\0sic")] + public void Returns_Unrooted_Unsanitized_Directory_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, sanitize: false, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("fo\0o\\bar", "fo\0o")] + [InlineData("C:\\Mu\0sic\\song.flac", "Mu\0sic")] + public void Returns_Unrooted_Unsanitized_Directory_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, retainRoot: false, sanitize: false, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo/../bar/file.txt", "foo/../bar")] + [InlineData("../etc/file.txt", "../etc")] + public void Preserves_Traversal_Segments_When_Sanitize_False_Linux(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: false, os: OperatingSystem.Linux); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo\\..\\bar\\file.txt", "foo\\..\\bar")] + [InlineData("..\\etc\\file.txt", "..\\etc")] + public void Preserves_Traversal_Segments_When_Sanitize_False_Windows(string input, string expected) + { + var result = FileSafety.GetDirectoryNameSafely(input, sanitize: false, retainRoot: false, os: OperatingSystem.Windows); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("@@abcd/foo/bar/file.txt")] + public void Short_Qt_Prefix_Treated_As_Segment_Linux(string input) + { + var result = FileSafety.GetDirectoryNameSafely(input, os: OperatingSystem.Linux); + + Assert.StartsWith("@@abcd", result); + } + [Theory] [InlineData("fo\0o\\bar", "fo_o")] [InlineData("foo/bar", "foo")] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs index 2af5321e..59ba2b54 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/GetFileNameSafelyTests.cs @@ -138,6 +138,38 @@ public partial class FileSafetyTests Assert.Equal(input, result); } + [Theory] + [InlineData("foo/.")] + [InlineData("foo/..")] + [InlineData("foo\\..")] + public void Sanitize_True_Replaces_Traversal_As_Last_Path_Segment(string input) + { + var result = FileSafety.GetFileNameSafely(input, sanitize: true); + + Assert.Equal("_", result); + } + + [Theory] + [InlineData("foo/.", ".")] + [InlineData("foo/..", "..")] + [InlineData("foo\\..", "..")] + public void Sanitize_False_Preserves_Traversal_As_Last_Path_Segment(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input, sanitize: false); + + Assert.Equal(expected, result); + } + + [Theory] + [InlineData("foo//bar.flac", "bar.flac")] + [InlineData("foo\\\\bar.flac", "bar.flac")] + public void Returns_Filename_Given_Double_Separator(string input, string expected) + { + var result = FileSafety.GetFileNameSafely(input); + + Assert.Equal(expected, result); + } + [Theory] [InlineData("@@abcde/song.flac", "song.flac")] [InlineData("@@abcde\\song.flac", "song.flac")] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs index df81c8e2..771a1ea0 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/IsPathTests.cs @@ -22,6 +22,9 @@ public partial class FileSafetyTests [InlineData("C:\\Users\\Ünïcödé\\Music")] [InlineData("C:\\Users\\пользователь\\Музыка")] [InlineData("C:\\Users\\用户\\音乐")] + // lowercase drive letters + [InlineData("c:\\Music")] + [InlineData("a:/path")] // UNC paths (\\ prefix) [InlineData("\\\\server\\share")] [InlineData("\\\\server\\share\\folder")] diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs index a6909438..f0fc196c 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/LocalizePathTests.cs @@ -20,6 +20,8 @@ public partial class FileSafetyTests [InlineData("C:\\Windows\\foo", "C:/Windows/foo")] [InlineData("C:/Windows/foo", "C:/Windows/foo")] [InlineData("", "")] + [InlineData("/", "/")] + [InlineData("\\", "/")] public void Linux_NormalizesToForwardSlash(string input, string expected) { var result = FileSafety.LocalizePath(input, OperatingSystem.Linux); @@ -40,6 +42,8 @@ public partial class FileSafetyTests [InlineData("C:\\Windows\\foo", "C:\\Windows\\foo")] [InlineData("C:/Windows/foo", "C:\\Windows\\foo")] [InlineData("", "")] + [InlineData("/", "\\")] + [InlineData("\\", "\\")] public void Windows_NormalizesToBackslash(string input, string expected) { var result = FileSafety.LocalizePath(input, OperatingSystem.Windows); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs index 8985edd4..c53b95fc 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizeFilenameTests.cs @@ -153,6 +153,22 @@ public partial class FileSafetyTests Assert.Equal(expected, result); } + [Fact] + public void Linux_Accepts_Period_As_Replacement() + { + var result = FileSafety.SanitizeFilename("file\0name", '.', OperatingSystem.Linux); + + Assert.Equal("file.name", result); + } + + [Fact] + public void Windows_Accepts_Period_As_Replacement() + { + var result = FileSafety.SanitizeFilename("file*name", '.', OperatingSystem.Windows); + + Assert.Equal("file.name", result); + } + [Fact] public void Returns_Null_Given_Null() { diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs index 82a583c0..230c9a89 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathSegmentTests.cs @@ -123,6 +123,7 @@ public partial class FileSafetyTests [Theory] [InlineData("*")] [InlineData("*?")] + [InlineData("*.")] // one invalid char + one period → ".." public void Windows_Returns_EmptyString_When_Period_Replacement_Produces_Traversal(string input) { var result = FileSafety.SanitizePathSegment(input, replacement: '.', os: OperatingSystem.Windows); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs index 12ebdefa..61233e44 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/SanitizePathTests.cs @@ -129,5 +129,41 @@ public partial class FileSafetyTests Assert.False(result.StartsWith('/') || result.StartsWith('\\')); } + + [Fact] + public void Linux_NeverReturns_LeadingSlash_When_First_Segment_Sanitizes_To_Empty() + { + // '\0' replaced with '.' produces "." — SanitizePathSegment converts that to "" + // joining ["", "foo"] with '/' would yield "/foo" without a guard + var result = FileSafety.SanitizePath("\0/foo", replacement: '.', os: OperatingSystem.Linux); + + Assert.False(result.StartsWith('/') || result.StartsWith('\\')); + } + + [Theory] + [InlineData("../..")] + [InlineData("./.")] + public void Linux_Replaces_All_Traversal_Segments(string input) + { + var result = FileSafety.SanitizePath(input, os: OperatingSystem.Linux); + + Assert.Equal("_/_", result); + } + + [Fact] + public void Linux_Handles_SoulseekQt_Prefixed_Path() + { + var result = FileSafety.SanitizePath("@@abcde/foo/bar", os: OperatingSystem.Linux); + + Assert.Equal("@@abcde/foo/bar", result); + } + + [Fact] + public void Windows_Sanitizes_Colon_In_Drive_Like_Segment() + { + var result = FileSafety.SanitizePath("C:/Music/song.flac", os: OperatingSystem.Windows); + + Assert.Equal("C_\\Music\\song.flac", result); + } } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs index 469f5335..d547843b 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/StripPathRootTests.cs @@ -121,6 +121,24 @@ public partial class FileSafetyTests Assert.StartsWith("@@", result); } + [Fact] + public void Linux_Strips_Bare_SoulseekQtPrefix_Returning_Empty() + { + var result = FileSafety.StripPathRoot("@@abcde", OperatingSystem.Linux); + + Assert.Equal(string.Empty, result); + } + + [Theory] + [InlineData("/")] + [InlineData("//")] + public void Linux_ReturnsUnchanged_Given_Slash_Only_Path(string input) + { + var result = FileSafety.StripPathRoot(input, OperatingSystem.Linux); + + Assert.Equal(input, result); + } + [Theory] [InlineData("Music/Artist", "Music/Artist")] [InlineData("Artist/Album/song.flac", "Artist/Album/song.flac")] -- cgit v1.2.3 From 62134e78472a51ef0becff9c0850f635933ab506 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Jun 2026 19:16:57 -0500 Subject: stop using any Path.* method, because they are all fucked up and untestable --- src/slskd/Common/FileSafety.cs | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index bf81da0e..1634ca7a 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -102,7 +102,15 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } + root = LocalizePath(root, os).TrimEnd('/').TrimEnd('\\'); + + if (segments.Length == 0) + { + return root; + } + var isWindows = os.HasValue ? os.Value == OperatingSystem.Windows : System.OperatingSystem.IsWindows(); + var sep = isWindows ? '\\' : '/'; foreach (var segment in segments) { @@ -139,11 +147,17 @@ public static class FileSafety } } - var combined = Path.Combine(root, Path.Combine(segments)); + segments = [.. segments + .Where(s => !string.IsNullOrEmpty(s)) + .Select(s => LocalizePath(s))]; + + var combined = string.Join(sep, [root, .. segments]); // this is a backstop to catch any condition we haven't thought of; it makes sure that the resulting // path is actually rooted in the root we provided; if not the input was successful in traversal - if (!Path.GetFullPath(combined).StartsWith(Path.GetFullPath(root))) + var expectedPrefix = root + sep; + + if (combined != root && !combined.StartsWith(expectedPrefix)) { throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } -- cgit v1.2.3 From 5ed58b906b98c0f1b06147ed4db18c9bc2f1ffdf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Jun 2026 19:18:18 -0500 Subject: small tweaks --- src/slskd/Common/FileSafety.cs | 14 ++++++---- .../Common/Validation/AbsolutePathAttribute.cs | 2 +- .../Common/Validation/RelativePathAttribute.cs | 4 +-- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +-- .../Common/FileSafety/CombineSafelyTests.cs | 32 +++------------------- .../Validation/RelativePathAttributeTests.cs | 2 +- .../API/DTO/QueueDownloadBatchRequestTests.cs | 2 +- .../DownloadService/DeriveDestinationTests.cs | 2 -- 8 files changed, 19 insertions(+), 43 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 1634ca7a..bf8302d1 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -102,7 +102,7 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } - root = LocalizePath(root, os).TrimEnd('/').TrimEnd('\\'); + root = root.TrimEnd('/').TrimEnd('\\'); if (segments.Length == 0) { @@ -148,16 +148,18 @@ public static class FileSafety } segments = [.. segments - .Where(s => !string.IsNullOrEmpty(s)) - .Select(s => LocalizePath(s))]; + .Where(s => !string.IsNullOrEmpty(s))]; var combined = string.Join(sep, [root, .. segments]); + if (combined.TrimEnd('/').TrimEnd('\\') == root.TrimEnd('/').TrimEnd('\\')) + { + return combined; + } + // this is a backstop to catch any condition we haven't thought of; it makes sure that the resulting // path is actually rooted in the root we provided; if not the input was successful in traversal - var expectedPrefix = root + sep; - - if (combined != root && !combined.StartsWith(expectedPrefix)) + if (!combined.StartsWith($"{root}/") && !combined.StartsWith($"{root}\\")) { throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index f2615315..217a4eea 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -49,7 +49,7 @@ namespace slskd.Validation OS = os; } - public OperatingSystem? OS { get; } + public OperatingSystem OS { get; } private OperatingSystem? Injected { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index f691d4e5..ea2b627b 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -63,7 +63,7 @@ namespace slskd.Validation { if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem())) { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system."); } return ValidationResult.Success; @@ -72,7 +72,7 @@ namespace slskd.Validation // OS == OperatingSystem.All or .Any; if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows)) { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 0f7805ba..ad91ba2c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -815,7 +815,7 @@ namespace slskd.Transfers.Downloads // full remote path, e.g. '@@abcd\Foo\Bar\Baz\Qux.ext' => '@@abcd\Foo\Bar\Baz' // retains the path root, if there is one (Soulseek NS does this), which may not be what // people want, so possibly revisit and add StripPathRoot() - source_path = (FileSafety.GetDirectoryNameSafely(filename) ?? string.Empty).TrimEnd('/', '\\'); + source_path = (FileSafety.GetDirectoryNameSafely(filename, retainRoot: false) ?? string.Empty).TrimEnd('/', '\\'); // name of the remote parent directory, so using the example above, 'Baz' source_directory = (FileSafety.GetFileNameSafely(source_path) ?? string.Empty).TrimEnd('/', '\\'); @@ -1249,7 +1249,7 @@ namespace slskd.Transfers.Downloads var incompleteDirectory = OptionsMonitor.CurrentValue.Directories.Incomplete; var sanitizedUsername = FileSafety.SanitizePathSegment(transfer.Username); var sanitizedFilename = FileSafety.GetFileNameSafely(transfer.Filename, sanitize: true); - var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true); + var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true) ?? string.Empty; var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index c3b69b12..e40ce743 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -169,21 +169,9 @@ public partial class FileSafetyTests [InlineData("C:relative")] public void Accepts_Colon_In_Segment_On_Linux_Hits_Backstop_On_Windows(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!System.OperatingSystem.IsWindows()) - { - Assert.Null(result); - } - else - { - // this test breaks when run on windows - // this is valid on linux (which we're trying to test for) - // but invalid on windows because it is a drive-relative path and it successfully traverses - Assert.NotNull(result); - Assert.IsType(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/C:relative", result); } [Theory] @@ -201,21 +189,9 @@ public partial class FileSafetyTests [InlineData("\\Music")] public void Accepts_Leading_Backslash_In_Segment_On_Linux(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!System.OperatingSystem.IsWindows()) - { - Assert.Null(result); - } - else - { - // this test breaks when run on windows - // this is valid on linux (which we're trying to test for) - // but invalid on windows because it is a drive-relative path and it successfully traverses - Assert.NotNull(result); - Assert.IsType(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/\\Music", result); } [Fact] diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index 8d1c16b3..ea74f822 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -130,7 +130,7 @@ public class RelativePathAttributeTests // Note: the implementation uses the same message for Current as for Any/All. // "on all operating systems" is misleading here since Current only validates // against the current (or injected) OS. - Assert.Equal("The Field field must be a relative path on all operating systems.", msg); + Assert.Equal("The Field field must be a relative path on the current operating system.", msg); } [Fact] diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 4d4e4969..370a722d 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -285,7 +285,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + Assert.Equal("The Destination field must be a relative path on all operating systems.", results[0].ErrorMessage); } } diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs index 4da05b24..f35ff452 100644 --- a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -499,7 +499,6 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Empty() { - // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) var searchId = Guid.NewGuid(); var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; @@ -513,7 +512,6 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Whitespace() { - // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) var searchId = Guid.NewGuid(); var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; -- cgit v1.2.3 From 12cf9ad6b33ae29e9e7caea20b205fadd45798bf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 5 Jun 2026 19:18:18 -0500 Subject: small tweaks --- src/slskd/Common/FileSafety.cs | 14 ++++++---- .../Common/Validation/AbsolutePathAttribute.cs | 2 +- .../Common/Validation/RelativePathAttribute.cs | 4 +-- src/slskd/Transfers/Downloads/DownloadService.cs | 4 +-- .../Common/FileSafety/CombineSafelyTests.cs | 32 +++------------------- .../Validation/RelativePathAttributeTests.cs | 2 +- .../API/DTO/QueueDownloadBatchRequestTests.cs | 4 +-- .../DownloadService/DeriveDestinationTests.cs | 2 -- 8 files changed, 20 insertions(+), 44 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/FileSafety.cs b/src/slskd/Common/FileSafety.cs index 1634ca7a..bf8302d1 100644 --- a/src/slskd/Common/FileSafety.cs +++ b/src/slskd/Common/FileSafety.cs @@ -102,7 +102,7 @@ public static class FileSafety throw new ArgumentNullException(nameof(segments), $"One or more segments is null"); } - root = LocalizePath(root, os).TrimEnd('/').TrimEnd('\\'); + root = root.TrimEnd('/').TrimEnd('\\'); if (segments.Length == 0) { @@ -148,16 +148,18 @@ public static class FileSafety } segments = [.. segments - .Where(s => !string.IsNullOrEmpty(s)) - .Select(s => LocalizePath(s))]; + .Where(s => !string.IsNullOrEmpty(s))]; var combined = string.Join(sep, [root, .. segments]); + if (combined.TrimEnd('/').TrimEnd('\\') == root.TrimEnd('/').TrimEnd('\\')) + { + return combined; + } + // this is a backstop to catch any condition we haven't thought of; it makes sure that the resulting // path is actually rooted in the root we provided; if not the input was successful in traversal - var expectedPrefix = root + sep; - - if (combined != root && !combined.StartsWith(expectedPrefix)) + if (!combined.StartsWith($"{root}/") && !combined.StartsWith($"{root}\\")) { throw new ArgumentException($"Path traversal detected in combined path '{combined}', which is not allowed"); } diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index f2615315..217a4eea 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -49,7 +49,7 @@ namespace slskd.Validation OS = os; } - public OperatingSystem? OS { get; } + public OperatingSystem OS { get; } private OperatingSystem? Injected { get; } protected override ValidationResult IsValid(object value, ValidationContext validationContext) diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index f691d4e5..ea2b627b 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -63,7 +63,7 @@ namespace slskd.Validation { if (!FileSafety.IsPathRelative(path, os: Injected ?? Compute.OperatingSystem())) { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on the current operating system."); } return ValidationResult.Success; @@ -72,7 +72,7 @@ namespace slskd.Validation // OS == OperatingSystem.All or .Any; if (!FileSafety.IsPathRelative(path, os: OperatingSystem.Linux) || !FileSafety.IsPathRelative(path, os: OperatingSystem.Windows)) { - return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path on all operating systems."); } } diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index 0f7805ba..ad91ba2c 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -815,7 +815,7 @@ namespace slskd.Transfers.Downloads // full remote path, e.g. '@@abcd\Foo\Bar\Baz\Qux.ext' => '@@abcd\Foo\Bar\Baz' // retains the path root, if there is one (Soulseek NS does this), which may not be what // people want, so possibly revisit and add StripPathRoot() - source_path = (FileSafety.GetDirectoryNameSafely(filename) ?? string.Empty).TrimEnd('/', '\\'); + source_path = (FileSafety.GetDirectoryNameSafely(filename, retainRoot: false) ?? string.Empty).TrimEnd('/', '\\'); // name of the remote parent directory, so using the example above, 'Baz' source_directory = (FileSafety.GetFileNameSafely(source_path) ?? string.Empty).TrimEnd('/', '\\'); @@ -1249,7 +1249,7 @@ namespace slskd.Transfers.Downloads var incompleteDirectory = OptionsMonitor.CurrentValue.Directories.Incomplete; var sanitizedUsername = FileSafety.SanitizePathSegment(transfer.Username); var sanitizedFilename = FileSafety.GetFileNameSafely(transfer.Filename, sanitize: true); - var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true); + var sanitizedRemotePath = FileSafety.GetDirectoryNameSafely(transfer.Filename, sanitize: true) ?? string.Empty; var incompleteFilename = FileSafety.CombineSafely(incompleteDirectory, sanitizedUsername, sanitizedRemotePath, sanitizedFilename); diff --git a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs index c3b69b12..e40ce743 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafety/CombineSafelyTests.cs @@ -169,21 +169,9 @@ public partial class FileSafetyTests [InlineData("C:relative")] public void Accepts_Colon_In_Segment_On_Linux_Hits_Backstop_On_Windows(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!System.OperatingSystem.IsWindows()) - { - Assert.Null(result); - } - else - { - // this test breaks when run on windows - // this is valid on linux (which we're trying to test for) - // but invalid on windows because it is a drive-relative path and it successfully traverses - Assert.NotNull(result); - Assert.IsType(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/C:relative", result); } [Theory] @@ -201,21 +189,9 @@ public partial class FileSafetyTests [InlineData("\\Music")] public void Accepts_Leading_Backslash_In_Segment_On_Linux(string segment) { - var result = Record.Exception(() => FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment)); + var result = FileSafety.CombineSafely(Base, OperatingSystem.Linux, segment); - if (!System.OperatingSystem.IsWindows()) - { - Assert.Null(result); - } - else - { - // this test breaks when run on windows - // this is valid on linux (which we're trying to test for) - // but invalid on windows because it is a drive-relative path and it successfully traverses - Assert.NotNull(result); - Assert.IsType(result); - Assert.Contains("traversal detected", result.Message); - } + Assert.Equal($"{Base}/\\Music", result); } [Fact] diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index 8d1c16b3..ea74f822 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -130,7 +130,7 @@ public class RelativePathAttributeTests // Note: the implementation uses the same message for Current as for Any/All. // "on all operating systems" is misleading here since Current only validates // against the current (or injected) OS. - Assert.Equal("The Field field must be a relative path on all operating systems.", msg); + Assert.Equal("The Field field must be a relative path on the current operating system.", msg); } [Fact] diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 4d4e4969..f608467b 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -285,7 +285,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + Assert.Contains("must be a relative path", results[0].ErrorMessage); } } @@ -300,7 +300,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); + Assert.Contains("must be a relative path", results[0].ErrorMessage); } } diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs index 4da05b24..f35ff452 100644 --- a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -499,7 +499,6 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Empty() { - // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) var searchId = Guid.NewGuid(); var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; @@ -513,7 +512,6 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_Search_Text_Is_Whitespace() { - // fails until code uses IsNullOrWhiteSpace instead of ?? for search_text (parity with batch_external_id) var searchId = Guid.NewGuid(); var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; -- cgit v1.2.3 From d35ac4573e2ac5817af3a2b9a6025d41959b9caf Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 10:43:22 -0500 Subject: require dollar sign prefix for values to eliminate the need for single quotes --- config/slskd.example.yml | 2 +- src/slskd/Transfers/Downloads/DownloadService.cs | 2 +- .../DownloadService/DeriveDestinationTests.cs | 98 +++++++++++----------- 3 files changed, 51 insertions(+), 51 deletions(-) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index f616cd8a..46ef6ec1 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -79,7 +79,7 @@ # delay: 5000 # initial time between retries, in milliseconds # max_delay: 60000 # maximum time between retries, in milliseconds # destination: -# subdirectory: {SOURCE_DIRECTORY} +# subdirectory: ${SOURCE_DIRECTORY} # options: SOURCE_USERNAME, SOURCE_PATH, SOURCE_DIRECTORY, BATCH_ID, BATCH_EXTERNAL_ID, SEARCH_ID, SEARCH_TEXT # exists: rename # 'overwrite' or 'rename' # groups: # default: diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index ad91ba2c..c6892fc4 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -243,7 +243,7 @@ namespace slskd.Transfers.Downloads private ILogger Log { get; } = Serilog.Log.ForContext(); private IOptionsMonitor OptionsMonitor { get; } private EventBus EventBus { get; } - private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled); + private Regex SubdirectoryPatternTokenRegex { get; } = new Regex(@"\$\{([^\{\}]*)\}", RegexOptions.IgnoreCase | RegexOptions.Compiled); /// /// Allow only one enqueue operation for a given user at a time. Entries are added on the fly if they diff --git a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs index f35ff452..fcf3c45a 100644 --- a/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/Downloads/DownloadService/DeriveDestinationTests.cs @@ -20,7 +20,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = "explicit-dir" } }; - var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + 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); @@ -31,11 +31,11 @@ public partial class DownloadServiceTests { // 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 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); + Assert.Equal("${SOURCE_USERNAME}", result); } [Fact] @@ -74,7 +74,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_USERNAME_Is_Substituted() { - var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var (service, _) = GetFixture("${SOURCE_USERNAME}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal("alice", result); @@ -83,7 +83,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_USERNAME_Pattern_Match_Is_Case_Insensitive() { - var (service, _) = GetFixture("{source_username}"); + var (service, _) = GetFixture("${source_username}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal("alice", result); @@ -92,7 +92,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_USERNAME_Forward_Slash_Replaced_With_Underscore() { - var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var (service, _) = GetFixture("${SOURCE_USERNAME}"); var result = await service.DeriveDestination(new Transfer { Username = "al/ice", Filename = "@alice\\track.mp3" }); Assert.Equal("al_ice", result); @@ -101,7 +101,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_USERNAME_Backslash_Replaced_With_Underscore() { - var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var (service, _) = GetFixture("${SOURCE_USERNAME}"); var result = await service.DeriveDestination(new Transfer { Username = "al\\ice", Filename = "@alice\\track.mp3" }); Assert.Equal("al_ice", result); @@ -110,7 +110,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_USERNAME_Null_Byte_Replaced_With_Underscore() { - var (service, _) = GetFixture("{SOURCE_USERNAME}"); + var (service, _) = GetFixture("${SOURCE_USERNAME}"); var result = await service.DeriveDestination(new Transfer { Username = "al\0ice", Filename = "@alice\\track.mp3" }); Assert.Equal("al_ice", result); @@ -123,7 +123,7 @@ public partial class DownloadServiceTests [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 (service, _) = GetFixture("${SOURCE_USERNAME}"); var result = await service.DeriveDestination(new Transfer { Username = username, Filename = "@alice\\track.mp3" }); Assert.Equal("al_.._ice", result); @@ -132,7 +132,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Backslash() { - var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var (service, _) = GetFixture("${SOURCE_DIRECTORY}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\Music\\album\\track.mp3" }); Assert.Equal("album", result); @@ -141,7 +141,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_DIRECTORY_Is_Immediate_Parent_Of_Remote_Filename_Forward_Slash() { - var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var (service, _) = GetFixture("${SOURCE_DIRECTORY}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice/Music/album/track.mp3" }); Assert.Equal("album", result); @@ -150,7 +150,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_DIRECTORY_Is_Empty_If_File_Is_In_Root() { - var (service, _) = GetFixture("{SOURCE_DIRECTORY}"); + var (service, _) = GetFixture("${SOURCE_DIRECTORY}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" }); Assert.Equal(string.Empty, result); @@ -159,7 +159,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_PATH_Is_Full_Directory_Of_Remote_Filename() { - var (service, _) = GetFixture("{SOURCE_PATH}"); + 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); @@ -168,7 +168,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_PATH_Is_Empty_If_File_Is_In_Root() { - var (service, _) = GetFixture("{SOURCE_PATH}"); + var (service, _) = GetFixture("${SOURCE_PATH}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "track.mp3" }); Assert.Equal(string.Empty, result); @@ -177,7 +177,7 @@ public partial class DownloadServiceTests [Fact] public async Task SOURCE_PATH_And_SOURCE_DIRECTORY_Match_If_File_Is_In_One_Subdirectory() { - var (service, _) = GetFixture("{SOURCE_PATH}-{SOURCE_DIRECTORY}"); + 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); @@ -188,7 +188,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId }; - var (service, _) = GetFixture("{BATCH_ID}", batch: batch); + 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); @@ -197,7 +197,7 @@ public partial class DownloadServiceTests [Fact] public async Task BATCH_ID_Is_Fallback_When_No_Batch() { - var (service, _) = GetFixture("{BATCH_ID}"); + var (service, _) = GetFixture("${BATCH_ID}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal("unknown_batch_id", result); } @@ -206,7 +206,7 @@ public partial class DownloadServiceTests 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 (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); @@ -217,7 +217,7 @@ public partial class DownloadServiceTests { 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 (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); @@ -226,7 +226,7 @@ public partial class DownloadServiceTests [Fact] public async Task BATCH_EXTERNAL_ID_Is_Fallback_When_No_Batch() { - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}"); + 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); @@ -237,7 +237,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = null } }; - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + 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); @@ -248,7 +248,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = " " } }; - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + 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); @@ -259,7 +259,7 @@ public partial class DownloadServiceTests { 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 (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); @@ -270,7 +270,7 @@ public partial class DownloadServiceTests { 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 (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); @@ -281,7 +281,7 @@ public partial class DownloadServiceTests { 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 (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); @@ -294,7 +294,7 @@ public partial class DownloadServiceTests 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 (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); @@ -304,7 +304,7 @@ public partial class DownloadServiceTests public async Task SEARCH_ID_Is_Fallback_When_No_Batch() { // no batch → SearchId is never consulted - var (service, _) = GetFixture("{SEARCH_ID}"); + var (service, _) = GetFixture("${SEARCH_ID}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal("unknown_search_id", result); @@ -315,7 +315,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = null }; - var (service, _) = GetFixture("{SEARCH_ID}", batch: batch); + 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); @@ -326,7 +326,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() }; - var (service, _) = GetFixture("{SEARCH_ID}", batch: batch, search: null); + 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); @@ -339,7 +339,7 @@ public partial class DownloadServiceTests 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 (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); @@ -352,7 +352,7 @@ public partial class DownloadServiceTests 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 (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); @@ -361,7 +361,7 @@ public partial class DownloadServiceTests [Fact] public async Task SEARCH_TEXT_Is_Fallback_When_No_Search() { - var (service, _) = GetFixture("{SEARCH_TEXT}"); + var (service, _) = GetFixture("${SEARCH_TEXT}"); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3" }); Assert.Equal("unknown_search_text", result); @@ -374,7 +374,7 @@ public partial class DownloadServiceTests 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 (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); @@ -387,7 +387,7 @@ public partial class DownloadServiceTests 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 (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); @@ -398,7 +398,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = null }; - var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + 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); @@ -409,7 +409,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { Destination = " " } }; - var (service, _) = GetFixture("{SOURCE_USERNAME}", batch: batch); + 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); @@ -418,7 +418,7 @@ public partial class DownloadServiceTests [Fact] public async Task Pattern_Forward_Slash_Separator_Preserved_In_Output() { - var (service, _) = GetFixture("{SOURCE_USERNAME}/downloads"); + 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); @@ -427,7 +427,7 @@ public partial class DownloadServiceTests [Fact] public async Task Pattern_Backslash_Separator_Preserved_In_Output() { - var (service, _) = GetFixture("{SOURCE_USERNAME}\\downloads"); + 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); @@ -455,7 +455,7 @@ public partial class DownloadServiceTests 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 (service, _) = GetFixture("${SOURCE_USERNAME}"); var result = await service.DeriveDestination(new Transfer { Username = "..", Filename = "@alice\\track.mp3" }); Assert.False(FileSafety.ContainsTraversalSegments(result)); @@ -468,7 +468,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = "foo\0bar" }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var (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); @@ -479,7 +479,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = Guid.NewGuid() }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: null); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: null); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_search_text", result); @@ -490,7 +490,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = null }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_search_text", result); @@ -503,7 +503,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = "" }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_search_text", result); @@ -516,7 +516,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = " " }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.Equal("unknown_search_text", result); @@ -529,7 +529,7 @@ public partial class DownloadServiceTests var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, SearchId = searchId }; var search = new Search { Id = searchId, SearchText = "../evil" }; - var (service, _) = GetFixture("{SEARCH_TEXT}", batch: batch, search: search); + var (service, _) = GetFixture("${SEARCH_TEXT}", batch: batch, search: search); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.False(FileSafety.ContainsTraversalSegments(result)); @@ -540,7 +540,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "" } }; - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + 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); @@ -551,7 +551,7 @@ public partial class DownloadServiceTests { var batchId = Guid.NewGuid(); var batch = new Batch { Id = batchId, Options = new BatchOptions { ExternalId = "../evil" } }; - var (service, _) = GetFixture("{BATCH_EXTERNAL_ID}", batch: batch); + var (service, _) = GetFixture("${BATCH_EXTERNAL_ID}", batch: batch); var result = await service.DeriveDestination(new Transfer { Username = "alice", Filename = "@alice\\track.mp3", BatchId = batchId }); Assert.False(FileSafety.ContainsTraversalSegments(result)); @@ -559,7 +559,7 @@ public partial class DownloadServiceTests } private static (DownloadService service, Mocks mocks) GetFixture( - string subdirectory = "{SOURCE_USERNAME}", + string subdirectory = "${SOURCE_USERNAME}", Batch batch = null, Search search = null) { -- cgit v1.2.3 From 3740aaf2d59add87b87a88864ed459a94b925f5e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 18:47:26 -0500 Subject: add permissions to download.destination --- config/slskd.example.yml | 2 ++ src/slskd/Core/Options.cs | 37 +++++++++++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+) (limited to 'src') diff --git a/config/slskd.example.yml b/config/slskd.example.yml index 46ef6ec1..475ac65a 100644 --- a/config/slskd.example.yml +++ b/config/slskd.example.yml @@ -81,6 +81,8 @@ # destination: # subdirectory: ${SOURCE_DIRECTORY} # options: SOURCE_USERNAME, SOURCE_PATH, SOURCE_DIRECTORY, BATCH_ID, BATCH_EXTERNAL_ID, SEARCH_ID, SEARCH_TEXT # exists: rename # 'overwrite' or 'rename' +# permissions: +# mode: ~ # chmod syntax, e.g. 644, 777. does nothing on Windows. # groups: # default: # upload: diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e76f5d2f..6436a6d2 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1082,6 +1082,43 @@ namespace slskd /// [Enum(typeof(DestinationExistsStrategy))] public string Exists { get; init; } = DestinationExistsStrategy.Rename.ToString().ToLowerInvariant(); + + /// + /// Gets the permissions to apply to downloaded files and directories. + /// + [Validate] + public DestinationPermissionsOptions Permissions { get; init; } = new DestinationPermissionsOptions(); + + /// + /// Download destination permission options. + /// + public class DestinationPermissionsOptions : IValidatableObject + { + /// + /// Gets the permissions to apply to newly created files. + /// + /// + /// Applicable to non-Windows operating systems, only. + /// + public string Mode { get; init; } + + public IEnumerable Validate(ValidationContext validationContext) + { + var results = new List(); + + 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; + } + } } } -- cgit v1.2.3 From d2f1a0ca65b77cff7b5841df1bbaf3e3342c6df0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 18:49:09 -0500 Subject: deprecate old permissions and add a validation error to flag it --- src/slskd/Core/Options.cs | 12 +++++++----- 1 file changed, 7 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 6436a6d2..7fb70fbb 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -235,11 +235,8 @@ namespace slskd [Validate] public RelayOptions Relay { get; init; } = new RelayOptions(); - /// - /// Gets permission options. - /// - [Validate] - public PermissionsOptions Permissions { get; init; } = new PermissionsOptions(); + [Obsolete("temporary sentinel to warn users about breaking change. use Transfers.Download.Destination.Permissions instead.")] + public object Permissions { get; init; } = null; /// /// Gets directory options. @@ -364,6 +361,11 @@ namespace slskd { results.Add(new ValidationResult("The 'integration' key has been renamed to 'integrations'. Add an 's' to the end of the key to remove this error (no other changes were made)")); } + + if (Permissions is not null) + { + results.Add(new ValidationResult("The 'permissions' keys have been moved under a new 'destination' key under transfers -> download, and the behavior has changed. See https://github.com/slskd/slskd/pull/1756 for details")); + } #pragma warning restore CS0618 // Type or member is obsolete return results; -- cgit v1.2.3 From c1d14e53eab549922f02ae1adb811b2f5a7ec331 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 18:50:01 -0500 Subject: add missing $ --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index e76f5d2f..29d37806 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -1075,7 +1075,7 @@ namespace slskd [RelativePath(OperatingSystem.All)] [NonTraversingPath] [String(AllowNull = true, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1)] - public string Subdirectory { get; init; } = "{SOURCE_DIRECTORY}"; + public string Subdirectory { get; init; } = "${SOURCE_DIRECTORY}"; /// /// Gets the strategy for handling existing files on disk. -- cgit v1.2.3 From c1dd8157a683e2fb816ff0c5d06056cc0ac1e17a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 18:59:22 -0500 Subject: run chmod on directories --- src/slskd/Files/FileService.cs | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) (limited to 'src') diff --git a/src/slskd/Files/FileService.cs b/src/slskd/Files/FileService.cs index 3b304d99..62d17f20 100644 --- a/src/slskd/Files/FileService.cs +++ b/src/slskd/Files/FileService.cs @@ -389,13 +389,15 @@ namespace slskd.Files var path = Path.GetDirectoryName(filename); - UnixFileMode? unixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Permissions.File.Mode?.ToUnixFileMode(); + UnixFileMode? unixCreateMode = options?.UnixCreateMode ?? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode?.ToUnixFileMode(); if (!Directory.Exists(path)) { if (!OperatingSystem.IsWindows() && unixCreateMode.HasValue) { - Directory.CreateDirectory(path, unixCreateMode.Value.WithExecuteFlagsForEachReadFlag()); + var mode = unixCreateMode.Value.WithExecuteFlagsForEachReadFlag(); + Directory.CreateDirectory(path, unixCreateMode: mode); + File.SetUnixFileMode(path, mode: mode); } else { @@ -469,13 +471,15 @@ namespace slskd.Files throw new FileNotFoundException($"The specified source file does not exist", fileName: sourceFilename); } - UnixFileMode? unixCreateMode = unixFileMode ?? OptionsMonitor.CurrentValue.Permissions.File.Mode?.ToUnixFileMode(); + UnixFileMode? unixCreateMode = unixFileMode ?? OptionsMonitor.CurrentValue.Transfers.Download.Destination.Permissions.Mode?.ToUnixFileMode(); if (!Directory.Exists(destinationDirectory)) { if (!OperatingSystem.IsWindows() && unixCreateMode.HasValue) { - Directory.CreateDirectory(destinationDirectory, unixCreateMode.Value.WithExecuteFlagsForEachReadFlag()); + var mode = unixCreateMode.Value.WithExecuteFlagsForEachReadFlag(); + Directory.CreateDirectory(destinationDirectory, unixCreateMode: mode); + File.SetUnixFileMode(destinationDirectory, mode: mode); } else { -- cgit v1.2.3 From 0a5274bdeb39d8aa67161ff28382c2bab626f446 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 19:40:21 -0500 Subject: bump dependencies --- src/slskd/slskd.csproj | 40 ++++++++++++++++++++-------------------- 1 file changed, 20 insertions(+), 20 deletions(-) (limited to 'src') diff --git a/src/slskd/slskd.csproj b/src/slskd/slskd.csproj index cf825701..cb6a7d83 100644 --- a/src/slskd/slskd.csproj +++ b/src/slskd/slskd.csproj @@ -43,41 +43,41 @@ - - + + - - - - + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - - - + + + - + - - - - - - - - + + + + + + + + all runtime; build; native; contentfiles; analyzers; buildtransitive - + - + -- cgit v1.2.3 From ee655d70335939746a7c16f3bd9686c5e4cd2a88 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 19:42:08 -0500 Subject: update ref --- src/slskd/Transfers/Downloads/DownloadService.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Transfers/Downloads/DownloadService.cs b/src/slskd/Transfers/Downloads/DownloadService.cs index c6892fc4..7c794e55 100644 --- a/src/slskd/Transfers/Downloads/DownloadService.cs +++ b/src/slskd/Transfers/Downloads/DownloadService.cs @@ -1218,8 +1218,8 @@ namespace slskd.Transfers.Downloads }), disposeOutputStreamOnCompletion: true); - 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; /* -- cgit v1.2.3 From 596e6b9ee5a90384ee9c170986a9384fcd3e9f8f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 22:18:57 -0500 Subject: update imports --- src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs | 2 +- src/slskd/Program.cs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs index a7e7e0dc..760f7ba9 100644 --- a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs +++ b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs @@ -36,7 +36,7 @@ using System.Linq; using System.Reflection; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Formatters; -using Microsoft.OpenApi.Models; +using Microsoft.OpenApi; using Swashbuckle.AspNetCore.SwaggerGen; /// diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index d4baf276..22ad585a 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -62,7 +62,7 @@ namespace slskd using Microsoft.Extensions.FileProviders; using Microsoft.Extensions.FileProviders.Physical; using Microsoft.IdentityModel.Tokens; - using Microsoft.OpenApi.Models; + using Microsoft.OpenApi; using Prometheus.DotNetRuntime; using Prometheus.SystemMetrics; using Serilog; -- cgit v1.2.3 From 69360f579b1c0679a34263290af475bba8c4060d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 22:19:13 -0500 Subject: update loki config --- src/slskd/Program.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 22ad585a..9b7cd75e 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -67,6 +67,7 @@ namespace slskd using Prometheus.SystemMetrics; using Serilog; using Serilog.Events; + using Serilog.Formatting.Display; using Serilog.Sinks.Grafana.Loki; using Serilog.Sinks.SystemConsole.Themes; using slskd.Authentication; @@ -1236,7 +1237,7 @@ namespace slskd e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), config => config.GrafanaLoki( OptionsAtStartup.Logger.Loki ?? string.Empty, - outputTemplate: "[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")) + textFormatter: new MessageTemplateTextFormatter("[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))) .WriteTo.Sink(new DelegatingSink(logEvent => { string message = default; -- cgit v1.2.3 From e71eade0131b16c01f77637088c1e44ee07b3af6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 6 Jun 2026 22:40:41 -0500 Subject: conditional config of loki --- src/slskd/Program.cs | 12 +++++++++--- 1 file changed, 9 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 9b7cd75e..39c0d2ac 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1235,9 +1235,15 @@ namespace slskd retainedFileTimeLimit: TimeSpan.FromDays(OptionsAtStartup.Retention.Logs)))) .WriteTo.Conditional( e => !string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki), - config => config.GrafanaLoki( - OptionsAtStartup.Logger.Loki ?? string.Empty, - textFormatter: new MessageTemplateTextFormatter("[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}"))) + config => + { + if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) + { + config.GrafanaLoki( + OptionsAtStartup.Logger.Loki, + textFormatter: new MessageTemplateTextFormatter("[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")); + } + }) .WriteTo.Sink(new DelegatingSink(logEvent => { string message = default; -- cgit v1.2.3 From 0145a4d87ebe474aba82e2ad136eb9f5d652cc12 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Jun 2026 13:50:21 -0500 Subject: use the default message formatter for Loki (previous format prevented capture of properties) --- src/slskd/Program.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 39c0d2ac..9a2914ea 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -1008,6 +1008,7 @@ namespace slskd services.AddSwaggerGen(options => { options.DescribeAllParametersInCamelCase(); + options.CustomSchemaIds(type => type.FullName); options.SwaggerDoc("v0", new OpenApiInfo { Version = "v0", @@ -1217,6 +1218,7 @@ namespace slskd .MinimumLevel.Override("slskd.Authentication.PassthroughAuthenticationHandler", LogEventLevel.Warning) .MinimumLevel.Override("slskd.Authentication.ApiKeyAuthenticationHandler", LogEventLevel.Warning) .MinimumLevel.Override("Microsoft.EntityFrameworkCore.Database.Command", LogEventLevel.Warning) // bump this down to Information to show SQL + .Enrich.WithProperty("App", AppName) .Enrich.WithProperty("InstanceName", OptionsAtStartup.InstanceName) .Enrich.WithProperty("InvocationId", InvocationId) .Enrich.WithProperty("ProcessId", ProcessId) @@ -1239,9 +1241,7 @@ namespace slskd { if (!string.IsNullOrEmpty(OptionsAtStartup.Logger.Loki)) { - config.GrafanaLoki( - OptionsAtStartup.Logger.Loki, - textFormatter: new MessageTemplateTextFormatter("[{Timestamp:HH:mm:ss} {Level:u3}] {Message:lj}{NewLine}{Exception}")); + config.GrafanaLoki(OptionsAtStartup.Logger.Loki); } }) .WriteTo.Sink(new DelegatingSink(logEvent => -- cgit v1.2.3 From 1273205967f9427e6453b4064bdf549205ba106c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Jun 2026 15:07:44 -0500 Subject: resolve warnings about X509 API changes --- src/slskd/Common/Cryptography/X509.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Cryptography/X509.cs b/src/slskd/Common/Cryptography/X509.cs index bed224cf..b003decf 100644 --- a/src/slskd/Common/Cryptography/X509.cs +++ b/src/slskd/Common/Cryptography/X509.cs @@ -64,7 +64,7 @@ namespace slskd.Cryptography new DateTimeOffset(DateTime.UtcNow.AddDays(-1)), new DateTimeOffset(DateTime.UtcNow.AddDays(36500))); - return new X509Certificate2(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags); + return X509CertificateLoader.LoadPkcs12(certificate.Export(X509ContentType.Pkcs12, password), password, x509KeyStorageFlags); } /// @@ -80,7 +80,7 @@ namespace slskd.Cryptography try { - _ = new X509Certificate2(fileName, password); + _ = X509CertificateLoader.LoadPkcs12FromFile(fileName, password); return true; } catch (Exception ex) -- cgit v1.2.3 From 360e1c33739166b35f58f82acc8a9475cf8271a1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Jun 2026 15:22:09 -0500 Subject: fully deprecate old permissions objects --- src/slskd/Core/Options.cs | 51 ----------------- tests/slskd.Tests.Unit/Files/FileServiceTests.cs | 72 ++++++++++++++++++------ 2 files changed, 54 insertions(+), 69 deletions(-) (limited to 'src') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index f35a56df..d1062a2c 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -705,57 +705,6 @@ namespace slskd } } - /// - /// Permission options. - /// - public class PermissionsOptions - { - /// - /// Gets file permission options. - /// - [Validate] - public FileOptions File { get; init; } = new FileOptions(); - - /// - /// File permission options. - /// - public class FileOptions : IValidatableObject - { - /// - /// Gets the permissions to apply to newly created files. - /// - /// - /// Applicable to non-Windows operating systems, only. - /// - [Argument(default, "file-permission-mode")] - [EnvironmentVariable("FILE_PERMISSION_MODE")] - [Description("the permissions to apply to newly created files (chmod syntax, non-Windows only)")] - public string Mode { get; init; } - - /// - /// Extended validation. - /// - /// - /// - public IEnumerable Validate(ValidationContext validationContext) - { - var results = new List(); - - 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; - } - } - } - /// /// Directory options. /// diff --git a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs index 7bb0bfdd..d6c30316 100644 --- a/tests/slskd.Tests.Unit/Files/FileServiceTests.cs +++ b/tests/slskd.Tests.Unit/Files/FileServiceTests.cs @@ -155,11 +155,17 @@ namespace slskd.Tests.Unit.Files OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { - Permissions = new Options.PermissionsOptions + Transfers = new Options.TransfersOptions { - File = new Options.PermissionsOptions.FileOptions + Download = new Options.TransfersOptions.GlobalDownloadOptions { - Mode = mode, + Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions + { + Permissions = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions.DestinationPermissionsOptions + { + Mode = mode, + } + } } } }); @@ -204,11 +210,17 @@ namespace slskd.Tests.Unit.Files OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { - Permissions = new Options.PermissionsOptions + Transfers = new Options.TransfersOptions { - File = new Options.PermissionsOptions.FileOptions + Download = new Options.TransfersOptions.GlobalDownloadOptions { - Mode = mode, + Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions + { + Permissions = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions.DestinationPermissionsOptions + { + Mode = mode, + } + } } } }); @@ -262,11 +274,17 @@ namespace slskd.Tests.Unit.Files OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { - Permissions = new Options.PermissionsOptions + Transfers = new Options.TransfersOptions { - File = new Options.PermissionsOptions.FileOptions + Download = new Options.TransfersOptions.GlobalDownloadOptions { - Mode = mode, + Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions + { + Permissions = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions.DestinationPermissionsOptions + { + Mode = mode, + } + } } } }); @@ -316,11 +334,17 @@ namespace slskd.Tests.Unit.Files OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { - Permissions = new Options.PermissionsOptions + Transfers = new Options.TransfersOptions { - File = new Options.PermissionsOptions.FileOptions + Download = new Options.TransfersOptions.GlobalDownloadOptions { - Mode = mode, + Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions + { + Permissions = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions.DestinationPermissionsOptions + { + Mode = mode, + } + } } } }); @@ -367,11 +391,17 @@ namespace slskd.Tests.Unit.Files OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { - Permissions = new Options.PermissionsOptions + Transfers = new Options.TransfersOptions { - File = new Options.PermissionsOptions.FileOptions + Download = new Options.TransfersOptions.GlobalDownloadOptions { - Mode = optionsMode, + Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions + { + Permissions = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions.DestinationPermissionsOptions + { + Mode = optionsMode, + } + } } } }); @@ -401,11 +431,17 @@ namespace slskd.Tests.Unit.Files OptionsMonitorMock.Setup(o => o.CurrentValue).Returns(new Options { - Permissions = new Options.PermissionsOptions + Transfers = new Options.TransfersOptions { - File = new Options.PermissionsOptions.FileOptions + Download = new Options.TransfersOptions.GlobalDownloadOptions { - Mode = optionsMode, + Destination = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions + { + Permissions = new Options.TransfersOptions.GlobalDownloadOptions.DestinationOptions.DestinationPermissionsOptions + { + Mode = optionsMode, + } + } } } }); -- cgit v1.2.3