From 3371921f4897dbff370c91b3171df4f953bfe21f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 3 May 2026 18:44:35 -0500 Subject: move destination to options --- src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src/slskd/Transfers/API/DTO') 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 16aeb34e118ee2d4770bcace3aa06a7615a2eae6 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 4 May 2026 22:13:44 -0500 Subject: tweak dto --- .../API/DTO/EnqueueDownloadBatchRequest.cs | 63 --------------- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 93 ++++++++++++++++++++++ 2 files changed, 93 insertions(+), 63 deletions(-) delete mode 100644 src/slskd/Transfers/API/DTO/EnqueueDownloadBatchRequest.cs create mode 100644 src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs (limited to 'src/slskd/Transfers/API/DTO') 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 eec45b7ddaa7fb33cc3831af4d4c849a5c39ca40 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 4 May 2026 22:28:01 -0500 Subject: size is a long, not an int --- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Transfers/API/DTO') 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 3afb1123087a03e15c23a75602b8f91094964e79 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:15:49 -0500 Subject: destination must be relative (to the configured download directory) --- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/slskd/Transfers/API/DTO') 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 b3041a9daffa98a0acda701e5e6b26345a185bde Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 12:41:23 -0500 Subject: add validation and tests for batch request DTO --- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 7 +- .../API/DTO/QueueDownloadBatchRequestTests.cs | 212 +++++++++++++++++++++ 2 files changed, 217 insertions(+), 2 deletions(-) create mode 100644 tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs (limited to 'src/slskd/Transfers/API/DTO') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 4a1d32f1..6d08f8f3 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -45,12 +45,14 @@ public record QueueDownloadBatchRequest /// /// If not supplied, one will be randomly generated. /// - public Guid? Id { get; init; } = Guid.NewGuid(); + [Guid] + public string Id { get; init; } /// /// The ID of the associated Search, if applicable. /// - public Guid? SearchId { get; init; } + [Guid] + public string SearchId { get; init; } /// /// The username of the user from which to download. @@ -76,6 +78,7 @@ public record EnqueueDownloadBatchItem /// The name of the file. /// [Required] + [StringLength(int.MaxValue, MinimumLength = 1)] public string Filename { get; set; } /// diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs new file mode 100644 index 00000000..3863c649 --- /dev/null +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -0,0 +1,212 @@ +using System.Collections.Generic; +using System.ComponentModel.DataAnnotations; +using slskd.Transfers.API; +using Xunit; + +namespace slskd.Tests.Unit.Transfers.API.DTO; + +public class QueueDownloadBatchRequestTests +{ + private static (bool IsValid, List Results) Validate(object obj) + { + var results = new List(); + var isValid = Validator.TryValidateObject(obj, new ValidationContext(obj), results, validateAllProperties: true); + return (isValid, results); + } + + private static QueueDownloadBatchRequest ValidRequest() => new() + { + Username = "testuser", + }; + + public class Id_Field + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Passes() + { + var (isValid, _) = Validate(ValidRequest() with { Id = null }); + Assert.True(isValid); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("not-a-guid")] + [InlineData("b5bde3d1-4aba-4d64-b64a")] + public void NonGuid_Fails(string value) + { + var (isValid, _) = Validate(ValidRequest() with { Id = value }); + Assert.False(isValid); + } + + [Theory] + [InlineData("b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b")] + [InlineData("B5BDE3D14ABA4D64B64A7A00A3CE5E1B")] + [InlineData("{b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b}")] + public void ValidGuid_Passes(string value) + { + var (isValid, _) = Validate(ValidRequest() with { Id = value }); + Assert.True(isValid); + } + } + + public class SearchId_Field + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Passes() + { + var (isValid, _) = Validate(ValidRequest() with { SearchId = null }); + Assert.True(isValid); + } + + [Theory] + [InlineData("")] + [InlineData(" ")] + [InlineData("not-a-guid")] + [InlineData("b5bde3d1-4aba-4d64-b64a")] + public void NonGuid_Fails(string value) + { + var (isValid, _) = Validate(ValidRequest() with { SearchId = value }); + Assert.False(isValid); + } + + [Theory] + [InlineData("b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b")] + [InlineData("B5BDE3D14ABA4D64B64A7A00A3CE5E1B")] + [InlineData("{b5bde3d1-4aba-4d64-b64a-7a00a3ce5e1b}")] + public void ValidGuid_Passes(string value) + { + var (isValid, _) = Validate(ValidRequest() with { SearchId = value }); + Assert.True(isValid); + } + } + + public class Username_Field + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Fails() + { + var (isValid, _) = Validate(ValidRequest() with { Username = null }); + Assert.False(isValid); + } + + [Fact] + public void Empty_Fails() + { + var (isValid, _) = Validate(ValidRequest() with { Username = "" }); + Assert.False(isValid); + } + + [Fact] + public void OneChar_Passes() + { + var (isValid, _) = Validate(ValidRequest() with { Username = "a" }); + Assert.True(isValid); + } + + [Fact] + public void FiveHundredChars_Passes() + { + var (isValid, _) = Validate(ValidRequest() with { Username = new string('a', 500) }); + Assert.True(isValid); + } + + [Fact] + public void FiveHundredOneChars_Fails() + { + var (isValid, _) = Validate(ValidRequest() with { Username = new string('a', 501) }); + Assert.False(isValid); + } + } + + public class Files_Item + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void NullFilename_Fails() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); + Assert.False(isValid); + } + + [Fact] + public void EmptyFilename_Fails() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); + Assert.False(isValid); + } + + [Fact] + public void ValidFilename_Passes() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 }); + Assert.True(isValid); + } + + [Fact] + public void NegativeSize_Fails() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = -1 }); + Assert.False(isValid); + } + + [Fact] + public void ZeroSize_Passes() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 0 }); + Assert.True(isValid); + } + + [Fact] + public void PositiveSize_Passes() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 1 }); + Assert.True(isValid); + } + } + + public class Options_Destination + { + private static (bool IsValid, List Results) Validate(object obj) + => QueueDownloadBatchRequestTests.Validate(obj); + + [Fact] + public void Omitted_Passes() + { + var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = null }); + Assert.True(isValid); + } + + [Theory] + [InlineData("subdir")] + [InlineData("sub/dir")] + [InlineData("sub\\dir")] + [InlineData("Artist\\Album")] + public void RelativePath_Passes(string value) + { + var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.True(isValid); + } + + [Theory] + [InlineData("C:\\Music")] + [InlineData("/music")] + [InlineData("\\\\server\\share")] + public void AbsolutePath_Fails(string value) + { + var (isValid, _) = Validate(new EnqueueDownloadBatchOptions { Destination = value }); + Assert.False(isValid); + } + } +} -- cgit v1.2.3 From c86fbec378b42dbd5ae6133c8ac706669f5709bb Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 12:59:32 -0500 Subject: require at least 1 file --- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 2 + .../API/DTO/QueueDownloadBatchRequestTests.cs | 61 ++++++++++++++++++---- 2 files changed, 54 insertions(+), 9 deletions(-) (limited to 'src/slskd/Transfers/API/DTO') 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 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/DTO') 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 8dc86c07d7e3c0ad82ad8e1c1c64b26a460774ac Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 14:54:14 -0500 Subject: tweak validation on batch request --- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 7 +++- .../API/DTO/QueueDownloadBatchRequestTests.cs | 47 ++++++++++++++++++---- 2 files changed, 45 insertions(+), 9 deletions(-) (limited to 'src/slskd/Transfers/API/DTO') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index fe539ce7..05a913bd 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -58,7 +58,8 @@ public record QueueDownloadBatchRequest /// The username of the user from which to download. /// [Required] - [StringLength(500, MinimumLength = 1)] + [NotNullOrWhiteSpace] + [StringLength(maximumLength: 500)] public string Username { get; init; } /// @@ -80,7 +81,8 @@ public record EnqueueDownloadBatchItem /// The name of the file. /// [Required] - [StringLength(int.MaxValue, MinimumLength = 1)] + [NotNullOrWhiteSpace] + [NonTraversingPath] public string Filename { get; init; } /// @@ -96,5 +98,6 @@ public record EnqueueDownloadBatchOptions /// The destination directory for the files, relative to the configured download directory. /// [RelativePath] + [NonTraversingPath] public string Destination { get; init; } } \ No newline at end of file diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 019e8cd5..2440291c 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -102,8 +102,7 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(ValidRequest() with { Username = null }); Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Username field is required.", results[0].ErrorMessage); + Assert.Contains(results, r => r.ErrorMessage == "The Username field is required."); } [Fact] @@ -111,8 +110,15 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(ValidRequest() with { Username = "" }); Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Username field is required.", results[0].ErrorMessage); + Assert.Contains(results, r => r.ErrorMessage == "The Username field is required."); + } + + [Fact] + public void Whitespace_Fails() + { + var (isValid, results) = Validate(ValidRequest() with { Username = " " }); + Assert.False(isValid); + Assert.Contains(results, r => r.ErrorMessage == "The Username field is required."); } [Fact] @@ -173,8 +179,7 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = null, Size = 0 }); Assert.False(isValid); - Assert.Single(results); - Assert.Equal("The Filename field is required.", results[0].ErrorMessage); + Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); } [Fact] @@ -182,7 +187,14 @@ public class QueueDownloadBatchRequestTests { var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = "", Size = 0 }); Assert.False(isValid); - Assert.Single(results); + Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); + } + + [Fact] + public void WhitespaceFilename_Fails() + { + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = " ", Size = 0 }); + Assert.False(isValid); Assert.Contains(results, r => r.ErrorMessage == "The Filename field is required."); } @@ -215,6 +227,27 @@ public class QueueDownloadBatchRequestTests var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = "music.mp3", Size = 1 }); Assert.True(isValid); } + + [Theory] + [InlineData("@foo/bar/../baz/file.mp3")] + [InlineData("@foo/bar/./baz/file.mp3")] + [InlineData("@foo\\bar\\..\\baz\\file.mp3")] + public void TraversalSegmentInFilename_Fails(string value) + { + var (isValid, results) = Validate(new EnqueueDownloadBatchItem { Filename = value, Size = 0 }); + Assert.False(isValid); + Assert.Contains(results, r => r.ErrorMessage != null && r.ErrorMessage.Contains("traversal segments")); + } + + [Theory] + [InlineData("@foo/bar/baz/file.mp3")] + [InlineData("@foo/bar/baz/file..ext")] + [InlineData("@foo\\bar\\baz\\file.mp3")] + public void NonTraversalFilename_Passes(string value) + { + var (isValid, _) = Validate(new EnqueueDownloadBatchItem { Filename = value, Size = 0 }); + Assert.True(isValid); + } } public class Options_Destination -- cgit v1.2.3 From b59d4b6b9b497c9c9c767e11da2af30dfd41983a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 14:54:22 -0500 Subject: add response --- .../API/DTO/QueueDownloadBatchResponse.cs | 41 ++++++++++++++++++++++ 1 file changed, 41 insertions(+) create mode 100644 src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs (limited to 'src/slskd/Transfers/API/DTO') 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 147aad8cca088734587c144434044a02d9ec7a96 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 17:40:44 -0500 Subject: tweak endpoint, docs, annotation. obsolete StateDescription to avoid usage --- .../Z2025_04_01_TransferStateMigration.cs | 3 + .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 13 +- src/slskd/Transfers/API/DTO/Transfer.cs | 169 --------------------- src/slskd/Transfers/TransfersDbContext.cs | 6 + src/slskd/Transfers/Types/Transfer.cs | 3 +- 5 files changed, 23 insertions(+), 171 deletions(-) delete mode 100644 src/slskd/Transfers/API/DTO/Transfer.cs (limited to 'src/slskd/Transfers/API/DTO') 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 21167d26a62add9ba54c50faa9b93970a478d27b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 18:53:38 -0500 Subject: failures as objects to avoid dictionary keys containing crap --- src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) (limited to 'src/slskd/Transfers/API/DTO') diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs index 8e134c29..84b570bc 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchResponse.cs @@ -37,5 +37,11 @@ namespace slskd.Transfers.API; public record QueueDownloadBatchResponse { public Batch Batch { get; init; } - public Dictionary Failures { get; init; } = []; + public IReadOnlyCollection Failures { get; init; } = []; +} + +public record QueueDownloadBatchResponseFailure +{ + public string Filename { get; init; } + public string Message { get; init; } } -- cgit v1.2.3 From aee67635e0c1048b890bc98812678086407d3b92 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 18:54:15 -0500 Subject: readonly fils, validatie destination --- src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src/slskd/Transfers/API/DTO') 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 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/DTO') 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