From f12d89de3381c59393444b602e762ae5d8146984 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 25 Apr 2026 19:11:42 -0500 Subject: wip --- .../API/Controllers/TransfersController.cs | 60 ++++++++++++++++++++++ 1 file changed, 60 insertions(+) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') 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 59e2e9de29de2dea134c5fbaf3a518b2fe0d82b2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 26 Apr 2026 19:23:58 -0500 Subject: wip transferscontroller --- .../API/Controllers/TransfersController.cs | 118 ++++++++++----------- 1 file changed, 59 insertions(+), 59 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') 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 89b6bdc087db0fc442492fcc52d0ca7d68e415aa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:48:24 -0500 Subject: rough in batch endpoints --- .../API/Controllers/TransfersController.cs | 173 +++++++++++++-------- 1 file changed, 112 insertions(+), 61 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') 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 22cc518863f5f2f0169e5fcbd83a91ebda15a5ef Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 4 May 2026 22:14:03 -0500 Subject: finish endpoint --- .../API/Controllers/TransfersController.cs | 44 ++++++++++++++++------ 1 file changed, 33 insertions(+), 11 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') 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 a61917f50b3874640b1bcd3c536a5ca4f38f10e0 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:16:19 -0500 Subject: handle conflicts/PK violations, validate more properties --- .../API/Controllers/TransfersController.cs | 9 +++++-- src/slskd/Transfers/Downloads/BatchService.cs | 28 ++++++++++++++++++---- 2 files changed, 30 insertions(+), 7 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') 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 f70c670e1dfbc6e6642365f57ba138501a8826fa Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 12:33:24 -0500 Subject: parse guids from strings --- .../API/Controllers/TransfersController.cs | 23 +++++++++++++++++----- 1 file changed, 18 insertions(+), 5 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') 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 7cd70a730b6cd57952f2e233378cd6bb244f56b1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 10 May 2026 18:51:35 -0500 Subject: block downloads of files with traversal segments --- .../Transfers/API/Controllers/TransfersController.cs | 17 ++++++++++++++++- src/slskd/Transfers/Downloads/DownloadService.cs | 5 +++++ 2 files changed, 21 insertions(+), 1 deletion(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') 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 d4c06cba98911c1fdad4ba65a6450180c0df9684 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 May 2026 19:03:04 -0500 Subject: tweaks --- src/slskd/Common/Validation/GuidAttribute.cs | 2 +- .../Z2026_05_06_AddBatchesTableMigration.cs | 2 +- .../API/Controllers/TransfersController.cs | 41 +++++++++++++++------- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 4 +-- 4 files changed, 32 insertions(+), 17 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Common/Validation/GuidAttribute.cs b/src/slskd/Common/Validation/GuidAttribute.cs index 9139ffef..5728b8f6 100644 --- a/src/slskd/Common/Validation/GuidAttribute.cs +++ b/src/slskd/Common/Validation/GuidAttribute.cs @@ -51,7 +51,7 @@ namespace slskd.Validation return ValidationResult.Success; } - return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUIDv4"); + return new ValidationResult($"The {validationContext.DisplayName} field must be a valid GUID/UUID"); } } } diff --git a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs index be56bfed..9b373f71 100644 --- a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs @@ -46,7 +46,7 @@ public class Z2026_05_06_AddBatchesTableMigration : IMigration ConnectionString = connectionStrings[Database.Transfers]; } - private ILogger Log { get; } = Serilog.Log.ForContext(); + private ILogger Log { get; } = Serilog.Log.ForContext(); private string ConnectionString { get; } public bool NeedsToBeApplied() diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 1d748f35..4fcb8d5a 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -287,11 +287,22 @@ namespace slskd.Transfers.API } } + /// + /// Enqueues a batch of downloads. + /// + /// The batch details. + /// + /// One or more downloads were successfully enqueued. + /// The request succeeded, but all downloads were already enqueued. + /// An unexpected error was encountered. [HttpPost("downloads/batches")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(201)] + [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 403)] + [ProducesResponseType(typeof(string), 409)] + [ProducesResponseType(typeof(string), 429)] [ProducesResponseType(typeof(string), 500)] public async Task EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request) { @@ -310,22 +321,22 @@ namespace slskd.Transfers.API return BadRequest("At least one file is required"); } - if (request.Files.Any( - r => r is null - || string.IsNullOrWhiteSpace(r.Filename) - || r.Size < 0)) + if (request.Files.Any(r => r is null)) { - return BadRequest("One or more files in the request are invalid"); + return BadRequest("One or more files in the request are null"); } - if (request.Files.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) + if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count) { - return BadRequest("One or more files in the request contain a dangerous path traversal segment"); + return BadRequest("Two or more files in the request are repeated"); } - if (request.Files.DistinctBy(f => f.Filename).Count() != request.Files.Count) + // a user would have to deliberately fake this, as no OS and no client are capable of scanning + // such a file into configured shares + if (request.Files.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) { - return BadRequest("One or more files in the request are duplicates"); + Log.Warning("Attempt to enqueue one or more files containing unsafe path segments from user {Username} (one or more of path traversal characters '.' and '..')", request.Username); + return BadRequest("One or more files in the request contain an unsafe path traversal segment"); } Guid? batchId; @@ -343,6 +354,8 @@ namespace slskd.Transfers.API return BadRequest("One or more provided identifiers is not a valid GUID/UUIDv4"); } + batchId ??= Guid.NewGuid(); + if (!DownloadRequestLimiter.Wait(0)) { return StatusCode(429, "Only one concurrent operation is permitted. Wait until the previous request completes"); @@ -357,9 +370,10 @@ namespace slskd.Transfers.API throw new UserOfflineException($"User {request.Username} appears to be offline"); } + // throws DuplicateException if a record already exists await Transfers.Downloads.Batches.CreateAsync(new() { - Id = batchId ?? Guid.NewGuid(), + Id = batchId.Value, SearchId = searchId, Username = request.Username, Options = new() @@ -377,12 +391,13 @@ namespace slskd.Transfers.API if (failed.Count > 0) { - Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already in progress", failed.Count, request.Files.Count); + Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already queued or in progress", failed.Count, request.Files.Count); } - // the returned batch will have whatever Transfers were successfully inserted attached + // the returned batch will have whatever Transfers were successfully inserted attached (via Include()) var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == batchId); + // all of the files were already queued; list of transfers should be empty if (batch.Transfers.Count == 0) { return Ok(batch); @@ -393,7 +408,7 @@ namespace slskd.Transfers.API catch (DuplicateException ex) { Log.Error(ex, "Failed to enqueue {Count} files for {Username}: A Batch with ID {BatchId} already exists", request.Files.Count, request.Username, request.Id); - return Conflict(); + return Conflict($"A batch with ID {batchId} already exists"); } catch (Exception ex) { diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 823a4e40..fe539ce7 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -81,13 +81,13 @@ public record EnqueueDownloadBatchItem /// [Required] [StringLength(int.MaxValue, MinimumLength = 1)] - public string Filename { get; set; } + public string Filename { get; init; } /// /// The file size. /// [Range(0, long.MaxValue)] - public long Size { get; set; } + public long Size { get; init; } } public record EnqueueDownloadBatchOptions -- cgit v1.2.3 From c2055a762d3d5df2ac26845ca7a45a292cc6b6e1 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 May 2026 22:04:37 -0500 Subject: fix tests --- src/slskd/Transfers/API/Controllers/TransfersController.cs | 2 +- tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs | 6 +++--- .../Transfers/API/DTO/QueueDownloadBatchRequestTests.cs | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') 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 5d16f6f9cccf72c29b8bbf206c851005e3375d79 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 19:02:40 -0500 Subject: wip --- .../API/Controllers/TransfersController.cs | 84 +++++++++++++--------- 1 file changed, 50 insertions(+), 34 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index ee3dfe2d..01dd61bd 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -42,6 +42,7 @@ namespace slskd.Transfers.API using System.Threading.Tasks; using Asp.Versioning; using Microsoft.AspNetCore.Authorization; + using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Serilog; using slskd.Users; @@ -292,18 +293,24 @@ namespace slskd.Transfers.API /// /// The batch details. /// - /// One or more downloads were successfully enqueued. - /// The request succeeded, but all downloads were already enqueued. + /// All downloads were successfully enqueued. + /// The request succeeded, but all downloads failed to be enqueued. + /// Some downloads were successfully enqueued, while some failed. + /// Bad request. + /// The request was forbidden. + /// A batch with the same ID already exists. + /// Request throttled. /// An unexpected error was encountered. [HttpPost("downloads/batches")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(200)] - [ProducesResponseType(201)] - [ProducesResponseType(typeof(string), 400)] - [ProducesResponseType(typeof(string), 403)] - [ProducesResponseType(typeof(string), 409)] - [ProducesResponseType(typeof(string), 429)] - [ProducesResponseType(typeof(string), 500)] + [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status201Created)] + [ProducesResponseType(typeof(QueueDownloadBatchResponse), StatusCodes.Status207MultiStatus)] + [ProducesResponseType(typeof(string), StatusCodes.Status400BadRequest)] + [ProducesResponseType(typeof(string), StatusCodes.Status403Forbidden)] + [ProducesResponseType(typeof(string), StatusCodes.Status409Conflict)] + [ProducesResponseType(typeof(string), StatusCodes.Status429TooManyRequests)] + [ProducesResponseType(typeof(string), StatusCodes.Status500InternalServerError)] public async Task EnqueueBatchAsync([FromBody] QueueDownloadBatchRequest request) { if (Program.IsRelayAgent) @@ -316,11 +323,6 @@ namespace slskd.Transfers.API return BadRequest(ModelState.GetReadableString()); } - if ((request.Files?.Count ?? 0) == 0) - { - return BadRequest("At least one file is required"); - } - if (request.Files.Any(r => r is null)) { return BadRequest("One or more files in the request are null"); @@ -331,18 +333,9 @@ namespace slskd.Transfers.API return BadRequest("Two or more files in the request are repeated"); } - // a user would have to deliberately fake this, as no OS and no client are capable of scanning - // such a file into configured shares - if (request.Files.Any(r => FileSafety.ContainsTraversalSegments(r.Filename))) - { - Log.Warning("Attempt to enqueue one or more files containing unsafe path segments from user {Username} (one or more of path traversal characters '.' and '..')", request.Username); - return BadRequest("One or more files in the request contain an unsafe path traversal segment"); - } - Guid? batchId; Guid? searchId; - // validation rules should prevent any problems here, but we have a backstop just in case try { batchId = string.IsNullOrWhiteSpace(request.Id) ? null : Guid.Parse(request.Id); @@ -383,27 +376,50 @@ namespace slskd.Transfers.API }); // Transfer records will have been inserted before this returns, unless they were rejected - // because they were already in progress, in which case they will show up in 'failed' + // because they were already in progress, in which case they will show up in 'failed'. or maybe they + // failed with an error. either way this complicates the return code var (enqueued, failed) = await Transfers.Downloads.EnqueueAsync( username: request.Username, - files: request.Files.Select(r => (r.Filename, r.Size)), + files: request.Files.Select(r => (r.Filename, r.Size.Value)), batchId: batchId); if (failed.Count > 0) { - Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already queued or in progress", failed.Count, request.Files.Count); + Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, batchId, failed); } // the returned batch will have whatever Transfers were successfully inserted attached (via Include()) + // failed transfers MAY or MAY NOT have an associated database record. if they do, it should have been + // properly finalized and marked as a failure var batch = await Transfers.Downloads.Batches.FindAsync(b => b.Id == batchId); - // all of the files were already queued; list of transfers should be empty - if (batch.Transfers.Count == 0) + var response = new QueueDownloadBatchResponse + { + Batch = batch, + Failures = failed.Select(f => new QueueDownloadBatchResponseFailure { Filename = f.Filename, Message = f.Message }).ToList(), + }; + + // basically a no-op, but we did create the batch record (and it's useless, but it's there) + // there's nothing to process asynchronously, so we'll return 200. 204 makes more sense to me, + // but it doesn't allow a body and without it the caller will never know the id unless they supplied it + if (response.Failures.Count == request.Files.Count) { - return Ok(batch); + return StatusCode(StatusCodes.Status200OK, response); } - return StatusCode(201, batch); + // if at least one (but not all) failed, we're in a weird state so send the most appropriate status code + // along with the batch and list of failures; the caller will have to pick through it and decide what to do + if (response.Failures.Count > 0) + { + return StatusCode(StatusCodes.Status207MultiStatus, response); + } + + // everything passed and we are now (or will eventually be) downloading asynchronously + return StatusCode(StatusCodes.Status201Created, response); + } + catch (UserOfflineException ex) + { + return StatusCode(StatusCodes.Status404NotFound, ex.Message); } catch (DuplicateException ex) { @@ -412,8 +428,8 @@ namespace slskd.Transfers.API } catch (Exception ex) { - Log.Error(ex, "Failed to enqueue {Count} files for {Username}: {Message}", request.Files.Count, request.Username, ex.Message); - return StatusCode(500, ex.Message); + Log.Error(ex, "Failed to enqueue {Count} files for {Username} (batch Id: {BatchId}): {Message}", request.Files.Count, request.Username, batchId, ex.Message); + return StatusCode(StatusCodes.Status500InternalServerError, ex.Message); } finally { @@ -532,7 +548,7 @@ namespace slskd.Transfers.API [HttpGet("downloads/{username}/{id}")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(API.Transfer), 200)] + [ProducesResponseType(typeof(Transfer), 200)] [ProducesResponseType(404)] public IActionResult GetDownload([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) { @@ -567,7 +583,7 @@ namespace slskd.Transfers.API /// The specified download was not found. [HttpGet("downloads/{username}/{id}/position")] [Authorize(Policy = AuthPolicy.Any)] - [ProducesResponseType(typeof(API.Transfer), 200)] + [ProducesResponseType(typeof(Transfer), 200)] [ProducesResponseType(404)] public async Task GetPlaceInQueueAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) { -- cgit v1.2.3 From 946333991d4f06aa139e9659952b2ce2ca9e988d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 13:40:48 -0500 Subject: mess with tests and validation --- .../Common/Validation/AbsolutePathAttribute.cs | 6 - src/slskd/Common/Validation/GuidAttribute.cs | 26 +- .../Common/Validation/RelativePathAttribute.cs | 6 - src/slskd/Core/Options.cs | 3 + .../API/Controllers/TransfersController.cs | 4 +- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 3 +- .../Validation/AbsolutePathAttributeTests.cs | 33 --- .../Common/Validation/GuidAttributeTests.cs | 120 +++++--- .../Validation/RelativePathAttributeTests.cs | 26 -- .../Common/Validation/StringAttributeTests.cs | 308 +++++++-------------- .../API/DTO/QueueDownloadBatchRequestTests.cs | 2 +- 11 files changed, 211 insertions(+), 326 deletions(-) (limited to 'src/slskd/Transfers/API/Controllers/TransfersController.cs') 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