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(+) 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 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(+) 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(-) 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(-) 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(+) 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(-) 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(+) 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 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(-) 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(-) 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(-) 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(-) 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(-) 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(+) 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(-) 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(-) 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 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(-) 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(-) 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(-) 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 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(-) 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 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 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(+) 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(-) 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(-) 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(-) 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(-) 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 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(-) 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(-) 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(-) 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 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(-) 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(-) 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(-) 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(+) 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 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 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(-) 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(+) 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(-) 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 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 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(-) 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 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(-) 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(-) 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(-) 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(+) 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(-) 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 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(-) 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(-) 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(+) 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(+) 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(+) 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 6a6de665cd23a651a5fdb8df37034b0b07c93c98 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 11:32:13 -0500 Subject: ensure traversal segments fail --- .../API/DTO/QueueDownloadBatchRequestTests.cs | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 1f12d787..9fa4d304 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -241,9 +241,11 @@ public class QueueDownloadBatchRequestTests } [Theory] - [InlineData("C:\\Music")] - [InlineData("/music")] - [InlineData("\\\\server\\share")] + [InlineData("C:\\Music")] // Windows absolute + [InlineData("C:/Music")] // Windows absolute, forward slash + [InlineData("/music")] // Unix absolute + [InlineData("/home/user/Music")] // Unix absolute, deep + [InlineData("\\\\server\\share")] // UNC public void AbsolutePath_Fails(string value) { var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); @@ -251,5 +253,19 @@ public class QueueDownloadBatchRequestTests Assert.Single(results); Assert.Equal("The Destination field must be a relative path.", results[0].ErrorMessage); } + + [Theory] + [InlineData("../escape")] // traversal prefix + [InlineData("./music")] // current-dir prefix + [InlineData("music/../other")] // traversal in middle + [InlineData("sub/../../escape")] // double traversal + [InlineData("music\\..")] // traversal via backslash + public void TraversalSegment_Fails(string value) + { + var (isValid, results) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.False(isValid); + Assert.Single(results); + Assert.Contains("traversal segments", results[0].ErrorMessage); + } } } -- 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 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(-) 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 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 fadc47b83a1d510ec10417010fba57fe39fb099b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 17:51:53 -0500 Subject: more tests for ToLocalRelativeFilename --- .../Extensions/ToLocalRelativeFilenameTests.cs | 141 ++++++++++++++++++--- 1 file changed, 124 insertions(+), 17 deletions(-) diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs index 1012ddfa..2df21dd1 100644 --- a/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs +++ b/tests/slskd.Tests.Unit/Common/Extensions/ToLocalRelativeFilenameTests.cs @@ -1,6 +1,8 @@ namespace slskd.Tests.Unit.Common.Extensions { using System; + using System.IO; + using System.Linq; using Xunit; public class ToLocalRelativeFilenameTests @@ -18,36 +20,141 @@ namespace slskd.Tests.Unit.Common.Extensions } [Fact] - public void Returns_Localized_Filename_And_Parent_Directory() + public void Returns_Last_Directory_And_Filename_From_Deep_Path() { - if (Environment.OSVersion.Platform == PlatformID.Win32NT) + var expected = "path" + Path.DirectorySeparatorChar + "file.ext"; + Assert.Equal(expected, @"deeply\nested\path\file.ext".ToLocalRelativeFilename()); + } + + [Fact] + public void Returns_Just_Filename_If_No_Directory_Given() + { + Assert.Equal("file.ext", "file.ext".ToLocalRelativeFilename()); + } + + [Fact] + public void Replaces_Invalid_Characters_In_Filename() + { + // Exclude backslash and forward slash — they act as segment separators in the input + // and would cause the dirty string to be split rather than treated as a filename. + var invalidChars = Path.GetInvalidFileNameChars() + .Where(c => c != '\\' && c != '/') + .ToArray(); + + var dirtyName = new string(invalidChars); + var result = $@"a\b\{dirtyName}".ToLocalRelativeFilename(); + var filename = Path.GetFileName(result); + + Assert.All(invalidChars, c => + Assert.False(filename.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in filename")); + } + + [Fact] + public void Replaces_Invalid_Characters_In_Directory() + { + // Directory segments are sanitized with ReplaceInvalidFileNameCharacters, so the full + // GetInvalidFileNameChars() set applies (excluding path separators, which split the input). + var invalidChars = Path.GetInvalidFileNameChars() + .Where(c => c != '\\' && c != '/') + .ToArray(); + + var dirtyName = new string(invalidChars); + var result = $@"a\{dirtyName}\file.ext".ToLocalRelativeFilename(); + var directory = Path.GetDirectoryName(result); + + Assert.All(invalidChars, c => + Assert.False(directory.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in directory")); + } + + [Fact] + public void Replaces_Each_Invalid_Filename_Character_Individually() + { + // Tests each invalid filename char in isolation so that failures identify the exact + // offending character rather than only reporting that something in a concatenated + // string was not replaced. + var invalidChars = Path.GetInvalidFileNameChars() + .Where(c => c != '\\' && c != '/') + .ToArray(); + + Assert.All(invalidChars, c => { - Assert.Equal(@"path\file.ext", "deeply/nested/path/file.ext".ToLocalRelativeFilename()); - } - else + var result = $@"a\b\prefix{c}suffix.ext".ToLocalRelativeFilename(); + var filename = Path.GetFileName(result); + Assert.False(filename.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in filename"); + }); + } + + [Fact] + public void Replaces_Each_Invalid_Filename_Character_In_Directory_Individually() + { + // Tests each invalid filename char in the directory segment in isolation so that + // failures identify the exact offending character. + var invalidChars = Path.GetInvalidFileNameChars() + .Where(c => c != '\\' && c != '/') + .ToArray(); + + Assert.All(invalidChars, c => { - Assert.Equal(@"path/file.ext", @"C:\deeply\nested\path\file.ext".ToLocalRelativeFilename()); - } + var result = $@"a\prefix{c}suffix\file.ext".ToLocalRelativeFilename(); + var directory = Path.GetDirectoryName(result); + Assert.False(directory.Contains(c), $"Invalid character U+{(int)c:X4} was not replaced in directory"); + }); + } + [Fact] + public void Returns_Last_Directory_And_Filename_From_Two_Segment_Path() + { + var expected = "dir" + Path.DirectorySeparatorChar + "file.ext"; + Assert.Equal(expected, @"dir\file.ext".ToLocalRelativeFilename()); } [Fact] - public void Returns_Just_File_If_Only_File_Given() + public void Handles_Forward_Slash_As_Segment_Separator() { - Assert.Equal("file.ext", "file.ext".ToLocalRelativeFilename()); + // LocalizePath normalizes '/' to Path.DirectorySeparatorChar before splitting, + // so forward-slash paths must produce the same result as backslash paths. + var expected = "b" + Path.DirectorySeparatorChar + "c.ext"; + Assert.Equal(expected, "a/b/c.ext".ToLocalRelativeFilename()); } [Fact] - public void Removes_Invalid_Characters_From_Path_And_Filename() + public void Handles_Mixed_Slash_Separators() { - if (Environment.OSVersion.Platform == PlatformID.Win32NT) - { - Assert.Equal(@"p_a_t_h\fi_le.ext", @"p?a|tle.ext".ToLocalRelativeFilename()); - } - else + var expected = "b" + Path.DirectorySeparatorChar + "c.ext"; + Assert.Equal(expected, @"a/b\c.ext".ToLocalRelativeFilename()); + } + + [Fact] + public void Preserves_Spaces_In_Filename() + { + // Spaces are valid in file names and must survive sanitization. + var expected = "dir" + Path.DirectorySeparatorChar + "file name.ext"; + Assert.Equal(expected, @"root\dir\file name.ext".ToLocalRelativeFilename()); + } + + [Fact] + public void Preserves_Spaces_In_Directory() + { + var expected = "my dir" + Path.DirectorySeparatorChar + "file.ext"; + Assert.Equal(expected, @"root\my dir\file.ext".ToLocalRelativeFilename()); + } + + [Fact] + public void Directory_Segment_Contains_No_Characters_Invalid_For_Directory_Names() + { + // All GetInvalidFileNameChars() (minus separators) must be absent from the directory + // segment. Directory segments are sanitized with ReplaceInvalidFileNameCharacters, so + // the full filename-invalid set applies. + var invalidChars = Path.GetInvalidFileNameChars() + .Where(c => c != '\\' && c != '/') + .ToArray(); + + Assert.All(invalidChars, c => { - Assert.Equal(@"_", $"{'\0'}".ToLocalRelativeFilename()); - } + var result = $@"a\prefix{c}suffix\file.ext".ToLocalRelativeFilename(); + var directory = Path.GetDirectoryName(result); + Assert.False(directory.Contains(c), $"Character U+{(int)c:X4} is invalid for directory names but was not replaced"); + }); } } } -- 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(+) 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(-) 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(-) 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(-) 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 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(-) 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(-) 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(-) 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 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(+) 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(-) 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 9039fd194f1f9cac0a6de54a68c17dead2eb65d7 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 May 2026 09:32:13 -0500 Subject: add tests for GuidAttribute --- .../Common/Validation/GuidAttributeTests.cs | 74 ++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs diff --git a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs new file mode 100644 index 00000000..85522c18 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs @@ -0,0 +1,74 @@ +using System.ComponentModel.DataAnnotations; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class GuidAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(object value) + { + var attribute = new GuidAttribute(); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); + } + + // null is allowed; [Required] dictates whether the field must be defined + [Fact] + public void Null_Passes() + { + var (isValid, _) = Validate(null); + Assert.True(isValid); + } + + public class Passes + { + [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); + } + } + + public class Fails + { + [Fact] + public void EmptyString_Fails() + { + var (isValid, errorMessage) = Validate(string.Empty); + Assert.False(isValid); + Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + } + + [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/UUIDv4", errorMessage); + } + + [Fact] + public void NonStringValue_Fails() + { + var (isValid, errorMessage) = Validate(42); + Assert.False(isValid); + Assert.Equal("The Field field must be a valid GUID/UUIDv4", errorMessage); + } + } +} -- 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(-) 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(-) 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 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 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(-) 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 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(-) 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 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(-) 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 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(-) 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(-) 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(-) 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(-) 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(-) 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(+) 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(-) 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 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 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 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(+) 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(-) 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(+) 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 338ed57cd52806e3684ccaedd1f19f5eafd4123a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 15:40:21 -0500 Subject: add/adjust tests --- .../ReplaceInvalidFileNameCharactersTests.cs | 2 +- tests/slskd.Tests.Unit/Common/FileSafetyTests.cs | 2 +- .../Validation/AbsolutePathAttributeTests.cs | 33 -- .../DisallowedCharactersAttributeTests.cs | 254 ------------- .../Common/Validation/GuidAttributeTests.cs | 106 ++++++ .../Validation/NonTraversingPathAttributeTests.cs | 94 +++++ .../Validation/RelativePathAttributeTests.cs | 26 -- .../Common/Validation/StringAttributeTests.cs | 422 +++++++++++++++++++++ 8 files changed, 624 insertions(+), 315 deletions(-) delete mode 100644 tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/NonTraversingPathAttributeTests.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs diff --git a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs index f6264661..eff24587 100644 --- a/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs +++ b/tests/slskd.Tests.Unit/Common/Extensions/ReplaceInvalidFileNameCharactersTests.cs @@ -141,4 +141,4 @@ namespace slskd.Tests.Unit.Common.Extensions Assert.EndsWith("after", result); } } -} \ No newline at end of file +} diff --git a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs index ae1efccf..a37e9e74 100644 --- a/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs +++ b/tests/slskd.Tests.Unit/Common/FileSafetyTests.cs @@ -542,4 +542,4 @@ public class FileSafetyTests Assert.NotNull(result); } } -} \ No newline at end of file +} diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs index 5013ec3a..10d62bc9 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/DisallowedCharactersAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs deleted file mode 100644 index f430c181..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); - } - } -} \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs new file mode 100644 index 00000000..f44b1f57 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs @@ -0,0 +1,106 @@ +using System; +using System.ComponentModel.DataAnnotations; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class GuidAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(object value, bool allowEmpty = false) + { + 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); + } + + // null is allowed; [Required] dictates whether the field must be defined + [Fact] + public void Null_Passes() + { + var (isValid, _) = Validate(null); + Assert.True(isValid); + } + + [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() + { + var (isValid, message) = Validate(Guid.Empty, allowEmpty: false); + Assert.False(isValid); + Assert.Contains("empty", message); + } + + [Fact] + public void AllowEmpty_Guid_Defaults_False() + { + var (isValid, message) = Validate(Guid.Empty); + Assert.False(isValid); + Assert.Contains("empty", message); + } + + [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 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); + } +} \ 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..b70d2603 --- /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); + } + } +} \ 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 index 647bc05f..0006d91d 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 new file mode 100644 index 00000000..e344798f --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs @@ -0,0 +1,422 @@ +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); + } + + public class Null + { + [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 Empty + { + [Fact] + public void Empty_Passes_When_AllowEmpty_Is_True() + { + var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = true); + Assert.True(isValid); + } + + [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() + { + 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, a => a.DisallowedCharacters = ['!']); + Assert.True(isValid); + } + + [Fact] + public void NoDisallowedCharsPresent_Passes() + { + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['!', '@']); + Assert.True(isValid); + } + + [Fact] + public void EmptyDisallowedSet_Passes() + { + var (isValid, _) = Validate("hello!@#", a => a.DisallowedCharacters = []); + Assert.True(isValid); + } + + [Fact] + public void Unicode_AllowedChars_Pass() + { + var (isValid, _) = Validate("пользователь/音楽", a => a.DisallowedCharacters = ['!', '@']); + 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 => a.DisallowedCharacters = ['a']); + Assert.True(isValid); + } + } + + public class Fails + { + [Fact] + public void SingleDisallowedChar_Fails() + { + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']); + Assert.False(isValid); + } + + [Fact] + public void DisallowedCharAtStart_Fails() + { + var (isValid, _) = Validate("!hello", a => a.DisallowedCharacters = ['!']); + Assert.False(isValid); + } + + [Fact] + public void DisallowedCharAtEnd_Fails() + { + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']); + Assert.False(isValid); + } + + [Fact] + public void DisallowedCharInMiddle_Fails() + { + var (isValid, _) = Validate("hel!lo", a => a.DisallowedCharacters = ['!']); + Assert.False(isValid); + } + + [Fact] + public void OneOfMultipleDisallowedCharsPresent_Fails() + { + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@', '#']); + Assert.False(isValid); + } + + [Fact] + public void MultipleDisallowedCharsAllPresent_Fails() + { + var (isValid, _) = Validate("h!e@l#lo", a => a.DisallowedCharacters = ['!', '@', '#']); + Assert.False(isValid); + } + + [Fact] + public void DisallowedCharRepeated_Fails() + { + var (isValid, _) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']); + Assert.False(isValid); + } + + [Fact] + public void AllCharsDisallowed_Fails() + { + var (isValid, _) = Validate("!@#", a => a.DisallowedCharacters = ['!', '@', '#']); + Assert.False(isValid); + } + + [Fact] + public void Unicode_DisallowedChar_Fails() + { + var (isValid, _) = Validate("пользователь", a => a.DisallowedCharacters = ['е']); + Assert.False(isValid); + } + + // character matching is always case-insensitive + [Fact] + public void LowerCaseDisallowed_Blocks_UpperCase() + { + var (isValid, _) = Validate("HELLO", a => a.DisallowedCharacters = ['h', 'e', 'l', 'o']); + Assert.False(isValid); + } + + [Fact] + public void UpperCaseDisallowed_Blocks_LowerCase() + { + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['H', 'E', 'L', 'O']); + Assert.False(isValid); + } + + [Fact] + public void ExactMatch_Fails() + { + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['h']); + Assert.False(isValid); + } + } + + public class ErrorMessage_Contains + { + [Fact] + public void TheDisallowedChar() + { + var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!']); + Assert.Contains("'!'", errorMessage); + } + + [Fact] + public void AllPresentDisallowedChars() + { + var (_, errorMessage) = Validate("h!@l", a => a.DisallowedCharacters = ['!', '@']); + Assert.Contains("'!'", errorMessage); + Assert.Contains("'@'", errorMessage); + } + + [Fact] + public void EachOccurrenceOfRepeatedChar() + { + // "he!lo!" has two '!' — both occurrences are listed + var (_, errorMessage) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']); + 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!", a => a.DisallowedCharacters = ['!', '@']); + 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 => a.DisallowedCharacters = ['a']); + Assert.Contains("'A'", errorMessage); + Assert.DoesNotContain("'a'", errorMessage); + } + } + } + + public class Length + { + [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 + { + [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); + } + } + } + + public class Pattern + { + [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 + { + [Fact] + public void RegularExpression_Keyword() + { + var (_, message) = Validate("hello1", a => a.Pattern = new Regex("[0-9]")); + Assert.Contains("regular expression", message); + } + } + } + + public class CheckOrdering + { + // 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); + } + } +} \ No newline at end of file -- 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(-) 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 3c799f205ce56e250883efd1deda798b758bb788 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 17:39:43 -0500 Subject: add test for greedy bracket change --- .../Core/Options/SharesOptionsTests.cs | 37 ++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs diff --git a/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs b/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs new file mode 100644 index 00000000..35ff53e6 --- /dev/null +++ b/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using Xunit; +using static slskd.Options; + +namespace slskd.Tests.Unit.Core.Options; + +public class SharesOptionsTests +{ + private static List Validate(SharesOptions options) + { + var context = new ValidationContext(options); + var results = new List(); + Validator.TryValidateObject(options, context, results, validateAllProperties: true); + return results; + } + + public class Directories + { + public class Digest + { + [Fact] + public void Alias_Uses_First_Closing_Bracket_When_Path_Contains_Brackets() + { + // [foo]/bar/[baz]/ should digest to alias "foo" and path "/bar/[baz]" + var options = new SharesOptions + { + Directories = [@"[foo]/bar/[baz]/"] + }; + + var results = Validate(options); + + Assert.DoesNotContain(results, r => r.ErrorMessage?.Contains("aliases may not contain path separators") == true); + } + } + } +} -- cgit v1.2.3 From f402e6f074b49d2344ba6d839f58298b87971f40 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 17:42:34 -0500 Subject: leave some notes --- tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs b/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs index 35ff53e6..7eacb95d 100644 --- a/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs +++ b/tests/slskd.Tests.Unit/Core/Options/SharesOptionsTests.cs @@ -28,6 +28,9 @@ public class SharesOptionsTests Directories = [@"[foo]/bar/[baz]/"] }; + // todo: fix this so that it fully validates on all platforms; currently this fails + // validation on Windows and would fail on Linux if i were to use backslashes + // the assertion for the alias proves we have fixed an aliasing bug so it's fine for now var results = Validate(options); Assert.DoesNotContain(results, r => r.ErrorMessage?.Contains("aliases may not contain path separators") == true); -- 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(-) 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