From 3abaadcd87383c22bc380d6c2fd9b05e38e7d353 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 30 Apr 2026 23:43:50 -0500 Subject: remove StartOffset from Transfers table (unused) --- ...Z2026_04_30_DropTransferStartOffsetMigration.cs | 101 +++++++++++++++++++++ 1 file changed, 101 insertions(+) create mode 100644 src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs new file mode 100644 index 00000000..4fb25b1f --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2026_04_30_DropTransferStartOffsetMigration.cs @@ -0,0 +1,101 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Migrations; + +using System; +using System.Linq; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Updates the Transfers table to drop the unused StartOffset column. +/// +public class Z2026_04_30_DropTransferStartOffsetMigration : IMigration +{ + public Z2026_04_30_DropTransferStartOffsetMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + + var columns = schema["Transfers"]; + + if (columns.Any(c => c.Name == "StartOffset")) + { + return true; + } + + return false; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_04_30_DropTransferStartOffsetMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } + + Log.Information("> Dropping StartOffset column from the Transfers table..."); + + Exec("ALTER TABLE Transfers DROP COLUMN StartOffset;"); + + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} -- cgit v1.2.3 From a4f0bd664849652893dea35055a186eeab25b06b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 6 May 2026 19:18:32 -0500 Subject: stub migration for batches table --- .../Z2026_05_06_AddBatchesTableMigration.cs | 107 +++++++++++++++++++++ 1 file changed, 107 insertions(+) create mode 100644 src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs new file mode 100644 index 00000000..89d718ef --- /dev/null +++ b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs @@ -0,0 +1,107 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Migrations; + +using System; +using Microsoft.Data.Sqlite; +using Serilog; + +/// +/// Creates the Batches table in the Transfers database. +/// +public class Z2026_05_06_AddBatchesTableMigration : IMigration +{ + public Z2026_05_06_AddBatchesTableMigration(ConnectionStringDictionary connectionStrings) + { + ConnectionString = connectionStrings[Database.Transfers]; + } + + private ILogger Log { get; } = Serilog.Log.ForContext(); + private string ConnectionString { get; } + + public bool NeedsToBeApplied() + { + var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); + + if (schema.ContainsKey("Batches")) + { + return false; + } + + return true; + } + + public void Apply() + { + if (!NeedsToBeApplied()) + { + Log.Information("> Migration {Name} is not necessary or has already been applied", nameof(Z2026_05_06_AddBatchesTableMigration)); + return; + } + + using var connection = new SqliteConnection(ConnectionString); + connection.Open(); + + using var transaction = connection.BeginTransaction(); + + try + { + void Exec(string sql) + { + using var command = new SqliteCommand(sql, connection, transaction); + command.ExecuteNonQuery(); + } + + Log.Information("> Creating the Batches table..."); + + Exec(@" + CREATE TABLE Batches ( + Id TEXT NOT NULL, + SearchId TEXT, + Username TEXT, + Direction INTEGER NOT NULL, + CreatedAt TEXT NOT NULL, + Options TEXT, + CONSTRAINT PK_Batches PRIMARY KEY(Id) + );"); + + transaction.Commit(); + Log.Information("> Done!"); + } + catch (Exception) + { + transaction.Rollback(); + throw; + } + } +} -- cgit v1.2.3 From 8948664a68875ea4b68a5a5ba61628f985926c2f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 6 May 2026 19:30:54 -0500 Subject: tweak migration --- .../Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs index 89d718ef..fe124680 100644 --- a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs @@ -86,15 +86,16 @@ public class Z2026_05_06_AddBatchesTableMigration : IMigration Exec(@" CREATE TABLE Batches ( - Id TEXT NOT NULL, - SearchId TEXT, - Username TEXT, + Id TEXT NOT NULL CONSTRAINT PK_Batches PRIMARY KEY, + SearchId TEXT NULL, + Username TEXT NULL, Direction INTEGER NOT NULL, CreatedAt TEXT NOT NULL, - Options TEXT, - CONSTRAINT PK_Batches PRIMARY KEY(Id) + Options TEXT NULL );"); + Exec(@"CREATE INDEX IDX_Batches_SearchId ON Batches (SearchId);"); + transaction.Commit(); Log.Information("> Done!"); } -- cgit v1.2.3 From f77b8a40a242d00f72882aff33fe4a4c00fdc06a Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 6 May 2026 19:32:02 -0500 Subject: remove nulls --- .../Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs index fe124680..be56bfed 100644 --- a/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z2026_05_06_AddBatchesTableMigration.cs @@ -87,11 +87,11 @@ public class Z2026_05_06_AddBatchesTableMigration : IMigration Exec(@" CREATE TABLE Batches ( Id TEXT NOT NULL CONSTRAINT PK_Batches PRIMARY KEY, - SearchId TEXT NULL, - Username TEXT NULL, + SearchId TEXT, + Username TEXT, Direction INTEGER NOT NULL, CreatedAt TEXT NOT NULL, - Options TEXT NULL + Options TEXT );"); Exec(@"CREATE INDEX IDX_Batches_SearchId ON Batches (SearchId);"); -- cgit v1.2.3 From 1bd12fee8216e31f5c13ac0cf07e5fd42f26e8e2 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Wed, 6 May 2026 19:32:37 -0500 Subject: wire up migration --- src/slskd/Core/Data/Migrator.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 7289b070..61d64e76 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -60,6 +60,7 @@ public class Migrator { nameof(Z2025_07_26_PrivateMessageWasReplayedMigration), new Z2025_07_26_PrivateMessageWasReplayedMigration(connectionStrings: Databases) }, { nameof(Z2025_12_28_AdditionalTransferIndexesMigration), new Z2025_12_28_AdditionalTransferIndexesMigration(connectionStrings: Databases) }, { nameof(Z2026_02_17_TransferAttemptsAndBatchIdMigration), new Z2026_02_17_TransferAttemptsAndBatchIdMigration(connectionStrings: Databases) }, + { nameof(Z2026_05_06_AddBatchesTableMigration), new Z2026_05_06_AddBatchesTableMigration(connectionStrings: Databases) }, }; } -- cgit v1.2.3 From fb600f5b90e6c313635687414b50869bf86ab653 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 7 May 2026 17:13:28 -0500 Subject: add a validator for relative paths --- .../Common/Validation/AbsoluteFilePathAttribute.cs | 58 ----------------- .../Common/Validation/AbsolutePathAttribute.cs | 58 +++++++++++++++++ .../Common/Validation/RelativePathAttribute.cs | 72 ++++++++++++++++++++++ src/slskd/Core/Options.cs | 2 +- 4 files changed, 131 insertions(+), 59 deletions(-) delete mode 100644 src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs create mode 100644 src/slskd/Common/Validation/AbsolutePathAttribute.cs create mode 100644 src/slskd/Common/Validation/RelativePathAttribute.cs (limited to 'src/slskd/Core') diff --git a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs b/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs deleted file mode 100644 index 8f87e479..00000000 --- a/src/slskd/Common/Validation/AbsoluteFilePathAttribute.cs +++ /dev/null @@ -1,58 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ Copyright (c) JP Dillingham. -// │ -// │ This program is free software: you can redistribute it and/or modify -// │ it under the terms of the GNU Affero General Public License as published -// │ by the Free Software Foundation, version 3. -// │ -// │ This program is distributed in the hope that it will be useful, -// │ but WITHOUT ANY WARRANTY; without even the implied warranty of -// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// │ GNU Affero General Public License for more details. -// │ -// │ You should have received a copy of the GNU Affero General Public License -// │ along with this program. If not, see https://www.gnu.org/licenses/. -// │ -// │ This program is distributed with Additional Terms pursuant to Section 7 -// │ of the AGPLv3. See the LICENSE file in the root directory of this -// │ project for the complete terms and conditions. -// │ -// │ https://slskd.org -// │ -// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ -// │ SPDX-FileCopyrightText: JP Dillingham -// │ SPDX-License-Identifier: AGPL-3.0-only -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Validation -{ - using System.ComponentModel.DataAnnotations; - using System.IO; - - /// - /// Validates that the specified path is absolute. - /// - public class AbsoluteFilePathAttribute : ValidationAttribute - { - protected override ValidationResult IsValid(object value, ValidationContext validationContext) - { - if (value != null) - { - var filePath = value.ToString(); - - if (!string.IsNullOrEmpty(filePath) && !Path.IsPathRooted(filePath)) - { - return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); - } - } - - return ValidationResult.Success; - } - } -} \ No newline at end of file diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs new file mode 100644 index 00000000..ef6db8ca --- /dev/null +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -0,0 +1,58 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation +{ + using System.ComponentModel.DataAnnotations; + using System.IO; + + /// + /// Validates that the specified path is absolute. + /// + public class AbsolutePathAttribute : ValidationAttribute + { + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value != null) + { + var filePath = value.ToString(); + + if (!string.IsNullOrEmpty(filePath) && !Path.IsPathRooted(filePath)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must specify an absolute file path."); + } + } + + return ValidationResult.Success; + } + } +} \ No newline at end of file diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs new file mode 100644 index 00000000..05f7630d --- /dev/null +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -0,0 +1,72 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation +{ + using System; + using System.ComponentModel.DataAnnotations; + using System.IO; + + /// + /// Validates that the specified path is relative and contains no path traversal segments. + /// + public class RelativePathAttribute : ValidationAttribute + { + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value != null) + { + var path = value.ToString(); + + if (!string.IsNullOrEmpty(path)) + { + if (Path.IsPathRooted(path)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); + } + + // use a dummy absolute base to normalize the path; GetFullPath resolves all .. and . segments + var dummyBase = Path.GetTempPath().TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar) + + Path.DirectorySeparatorChar; + var combined = Path.GetFullPath(Path.Combine(dummyBase, path)); + + if (!combined.StartsWith(dummyBase, StringComparison.OrdinalIgnoreCase)) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain path traversal segments."); + } + } + } + + return ValidationResult.Success; + } + } +} diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 8cc369af..1ca5b84a 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2010,7 +2010,7 @@ namespace slskd [Argument(default, "http-socket")] [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] - [AbsoluteFilePath] + [AbsolutePath] [RequiresRestart] public string Socket { get; init; } -- cgit v1.2.3 From 0e9d1a75eb3e954829e86f20c7f64724d21e780e Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 19:00:59 -0500 Subject: mark incomplete/downloads as absolute --- src/slskd/Core/Options.cs | 2 ++ 1 file changed, 2 insertions(+) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 1ca5b84a..21f2c75f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -765,6 +765,7 @@ namespace slskd [Argument(default, "incomplete")] [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] + [AbsolutePath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory; @@ -775,6 +776,7 @@ namespace slskd [Argument('o', "downloads")] [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] + [AbsolutePath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; -- cgit v1.2.3 From 9f68821f91a643c872a7023d6abf2c2f7cb60474 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 19:03:12 -0500 Subject: disallow path traversal characters as aliases --- src/slskd/Core/Options.cs | 4 ++++ 1 file changed, 4 insertions(+) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 21f2c75f..9fe8270b 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -880,6 +880,10 @@ namespace slskd { results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; aliases may not contain path separators '/' or '\\'")); } + else if (share.Alias == "." || share.Alias == "..") + { + results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; aliases may not be path traversal characters '.' or '..'")); + } } return results; -- cgit v1.2.3 From e73ccbe4b6bd35449e88e261aa6bfb869952517c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 9 May 2026 19:04:10 -0500 Subject: mark contentpath relative --- src/slskd/Core/Options.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 9fe8270b..7c391959 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -2043,6 +2043,7 @@ namespace slskd [EnvironmentVariable("CONTENT_PATH")] [Description("path to static web content")] [StringLength(255, MinimumLength = 1)] + [RelativePath] [DirectoryExists(relativeToApplicationDirectory: true)] [RequiresRestart] public string ContentPath { get; init; } = "wwwroot"; -- cgit v1.2.3 From 298539af4b3d49733073bedd68862973596b9b00 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 12 May 2026 18:59:16 -0500 Subject: add DisallowedCharacters attribute, ensure no slashes in instance/agent name --- .../Validation/DisallowedCharactersAttribute.cs | 71 ++++++ src/slskd/Core/Options.cs | 2 + .../DisallowedCharactersAttributeTests.cs | 254 +++++++++++++++++++++ 3 files changed, 327 insertions(+) create mode 100644 src/slskd/Common/Validation/DisallowedCharactersAttribute.cs create mode 100644 tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs (limited to 'src/slskd/Core') diff --git a/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs new file mode 100644 index 00000000..90ed3d81 --- /dev/null +++ b/src/slskd/Common/Validation/DisallowedCharactersAttribute.cs @@ -0,0 +1,71 @@ +// +// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ +// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ +// █__ --█ █__ --█ ◄█ - █ +// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ +// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ +// │ Copyright (c) JP Dillingham. +// │ +// │ This program is free software: you can redistribute it and/or modify +// │ it under the terms of the GNU Affero General Public License as published +// │ by the Free Software Foundation, version 3. +// │ +// │ This program is distributed in the hope that it will be useful, +// │ but WITHOUT ANY WARRANTY; without even the implied warranty of +// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// │ GNU Affero General Public License for more details. +// │ +// │ You should have received a copy of the GNU Affero General Public License +// │ along with this program. If not, see https://www.gnu.org/licenses/. +// │ +// │ This program is distributed with Additional Terms pursuant to Section 7 +// │ of the AGPLv3. See the LICENSE file in the root directory of this +// │ project for the complete terms and conditions. +// │ +// │ https://slskd.org +// │ +// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ +// │ SPDX-FileCopyrightText: JP Dillingham +// │ SPDX-License-Identifier: AGPL-3.0-only +// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ +// + +namespace slskd.Validation; + +using System.ComponentModel.DataAnnotations; +using System.Linq; + +/// +/// Validates that the value does not contain any of the characters. +/// +public class DisallowedCharactersAttribute : ValidationAttribute +{ + public DisallowedCharactersAttribute(params char[] disallowed) + { + Disallowed = disallowed; + } + + /// + /// Gets or sets a value indicating whether character matching is case-insensitive. Defaults to . + /// + public bool IgnoreCase { get; set; } = true; + + private char[] Disallowed { get; } + + protected override ValidationResult IsValid(object value, ValidationContext validationContext) + { + if (value is not null and string str) + { + var invalid = IgnoreCase + ? str.Where(c => Disallowed.Any(d => char.ToUpperInvariant(c) == char.ToUpperInvariant(d))) + : str.Where(c => Disallowed.Contains(c)); + + if (invalid.Any()) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more disallowed characters: {string.Join(", ", invalid.Select(c => $"'{c}'"))}"); + } + } + + return ValidationResult.Success; + } +} \ No newline at end of file diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 7c391959..90a72f7d 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -198,6 +198,7 @@ namespace slskd [Argument('i', "instance-name")] [EnvironmentVariable("INSTANCE_NAME")] [Description("optional; a unique name for this instance")] + [DisallowedCharacters('/', '\\')] [RequiresRestart] public string InstanceName { get; init; } = "default"; @@ -654,6 +655,7 @@ namespace slskd [Description("the name for this agent")] [StringLength(255, MinimumLength = 1)] [NotNullOrWhiteSpace] + [DisallowedCharacters('/', '\\')] [Secret] public string InstanceName { get; init; } diff --git a/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs new file mode 100644 index 00000000..4654fd25 --- /dev/null +++ b/tests/slskd.Tests.Unit/Common/Validation/DisallowedCharactersAttributeTests.cs @@ -0,0 +1,254 @@ +using System.ComponentModel.DataAnnotations; +using slskd.Validation; +using Xunit; + +namespace slskd.Tests.Unit.Common.Validation; + +public class DisallowedCharactersAttributeTests +{ + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) + { + var attribute = new DisallowedCharactersAttribute(disallowed) { IgnoreCase = ignoreCase }; + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(value, context); + return (result == null, result?.ErrorMessage); + } + + // null and empty pass — [Required] handles presence; this attribute only checks content + [Fact] + public void Null_Passes() + { + var (isValid, _) = Validate(null, ['!']); + Assert.True(isValid); + } + + [Fact] + public void EmptyString_Passes() + { + var (isValid, _) = Validate(string.Empty, ['!']); + Assert.True(isValid); + } + + public class Passes + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) + => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase); + + // Punctuation has no case variants — IgnoreCase must not affect the result either way + [Theory] + [InlineData(true)] + [InlineData(false)] + public void NoDisallowedCharsPresent_Passes_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello", ['!', '@'], ignoreCase); + Assert.True(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void EmptyDisallowedSet_Passes_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello!@#", [], ignoreCase); + Assert.True(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Unicode_AllowedChars_Pass_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("пользователь/音楽", ['!', '@'], ignoreCase); + Assert.True(isValid); + } + + [Fact] + public void NonString_Passes() + { + var attribute = new DisallowedCharactersAttribute('!'); + var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; + var result = attribute.GetValidationResult(42, context); + Assert.Equal(ValidationResult.Success, result); + } + + // IgnoreCase = false only: a disallowed letter in one case does not block the other case + [Fact] + public void CaseSensitive_LowerCaseDisallowed_DoesNotBlock_UpperCase() + { + var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o'], ignoreCase: false); + Assert.True(isValid); + } + + [Fact] + public void CaseSensitive_UpperCaseDisallowed_DoesNotBlock_LowerCase() + { + var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O'], ignoreCase: false); + Assert.True(isValid); + } + } + + public class Fails + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) + => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase); + + // Punctuation has no case variants — IgnoreCase must not affect the result either way + [Theory] + [InlineData(true)] + [InlineData(false)] + public void SingleDisallowedChar_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello!", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DisallowedCharAtStart_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("!hello", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DisallowedCharAtEnd_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello!", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DisallowedCharInMiddle_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hel!lo", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void OneOfMultipleDisallowedCharsPresent_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("hello!", ['!', '@', '#'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void MultipleDisallowedCharsAllPresent_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("h!e@l#lo", ['!', '@', '#'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void DisallowedCharRepeated_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("he!lo!", ['!'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void AllCharsDisallowed_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("!@#", ['!', '@', '#'], ignoreCase); + Assert.False(isValid); + } + + [Theory] + [InlineData(true)] + [InlineData(false)] + public void Unicode_DisallowedChar_Fails_Regardless_Of_IgnoreCase(bool ignoreCase) + { + var (isValid, _) = Validate("пользователь", ['е'], ignoreCase); + Assert.False(isValid); + } + + // IgnoreCase = true only: a disallowed letter blocks its other-case equivalent + [Fact] + public void IgnoreCase_LowerCaseDisallowed_Blocks_UpperCase() + { + var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o'], ignoreCase: true); + Assert.False(isValid); + } + + [Fact] + public void IgnoreCase_UpperCaseDisallowed_Blocks_LowerCase() + { + var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O'], ignoreCase: true); + Assert.False(isValid); + } + + [Fact] + public void CaseSensitive_ExactMatch_Fails() + { + var (isValid, _) = Validate("hello", ['h'], ignoreCase: false); + Assert.False(isValid); + } + } + + public class ErrorMessage_Contains + { + private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed, bool ignoreCase = true) + => DisallowedCharactersAttributeTests.Validate(value, disallowed, ignoreCase); + + [Fact] + public void DisplayName() + { + var (_, errorMessage) = Validate("hello!", ['!']); + Assert.Contains("Field", errorMessage); + } + + [Fact] + public void TheDisallowedChar() + { + var (_, errorMessage) = Validate("hello!", ['!']); + Assert.Contains("'!'", errorMessage); + } + + [Fact] + public void AllPresentDisallowedChars() + { + var (_, errorMessage) = Validate("h!@l", ['!', '@']); + Assert.Contains("'!'", errorMessage); + Assert.Contains("'@'", errorMessage); + } + + [Fact] + public void EachOccurrenceOfRepeatedChar() + { + // "he!lo!" has two '!' — both occurrences are listed + var (_, errorMessage) = Validate("he!lo!", ['!']); + Assert.Equal(2, errorMessage.Split("'!'").Length - 1); + } + + [Fact] + public void OnlyCharsActuallyPresent_NotAllDisallowedChars() + { + // '@' is disallowed but not in the value — must not appear in the message + var (_, errorMessage) = Validate("hello!", ['!', '@']); + Assert.Contains("'!'", errorMessage); + Assert.DoesNotContain("'@'", errorMessage); + } + + [Fact] + public void IgnoreCase_ShowsActualChar_NotDisallowedChar() + { + // 'a' is disallowed (lowercase); value contains 'A' (uppercase). + // The message reports what the user supplied ('A'), not the disallowed definition ('a'). + var (_, errorMessage) = Validate("A", ['a'], ignoreCase: true); + Assert.Contains("'A'", errorMessage); + Assert.DoesNotContain("'a'", errorMessage); + } + } +} -- cgit v1.2.3 From f13782644f835162186d1630809ee8508600cf9b Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 19:01:05 -0500 Subject: wire up missed migration --- src/slskd/Core/Data/Migrator.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Data/Migrator.cs b/src/slskd/Core/Data/Migrator.cs index 61d64e76..d53d7c8c 100644 --- a/src/slskd/Core/Data/Migrator.cs +++ b/src/slskd/Core/Data/Migrator.cs @@ -60,6 +60,7 @@ public class Migrator { nameof(Z2025_07_26_PrivateMessageWasReplayedMigration), new Z2025_07_26_PrivateMessageWasReplayedMigration(connectionStrings: Databases) }, { nameof(Z2025_12_28_AdditionalTransferIndexesMigration), new Z2025_12_28_AdditionalTransferIndexesMigration(connectionStrings: Databases) }, { nameof(Z2026_02_17_TransferAttemptsAndBatchIdMigration), new Z2026_02_17_TransferAttemptsAndBatchIdMigration(connectionStrings: Databases) }, + { nameof(Z2026_04_30_DropTransferStartOffsetMigration), new Z2026_04_30_DropTransferStartOffsetMigration(connectionStrings: Databases) }, { nameof(Z2026_05_06_AddBatchesTableMigration), new Z2026_05_06_AddBatchesTableMigration(connectionStrings: Databases) }, }; } -- cgit v1.2.3 From 38cdbb2a30358a509fd1c080747c4ad8101cd344 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Thu, 14 May 2026 19:02:41 -0500 Subject: revert option tweaks --- src/slskd/Core/Options.cs | 5 ----- 1 file changed, 5 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 90a72f7d..51b3cab1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -882,10 +882,6 @@ namespace slskd { results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; aliases may not contain path separators '/' or '\\'")); } - else if (share.Alias == "." || share.Alias == "..") - { - results.Add(new ValidationResult($"Share '{share.Raw}' is invalid; aliases may not be path traversal characters '.' or '..'")); - } } return results; @@ -2045,7 +2041,6 @@ namespace slskd [EnvironmentVariable("CONTENT_PATH")] [Description("path to static web content")] [StringLength(255, MinimumLength = 1)] - [RelativePath] [DirectoryExists(relativeToApplicationDirectory: true)] [RequiresRestart] public string ContentPath { get; init; } = "wwwroot"; -- cgit v1.2.3 From d4c06cba98911c1fdad4ba65a6450180c0df9684 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Fri, 15 May 2026 19:03:04 -0500 Subject: tweaks --- src/slskd/Common/Validation/GuidAttribute.cs | 2 +- .../Z2026_05_06_AddBatchesTableMigration.cs | 2 +- .../API/Controllers/TransfersController.cs | 41 +++++++++++++++------- .../Transfers/API/DTO/QueueDownloadBatchRequest.cs | 4 +-- 4 files changed, 32 insertions(+), 17 deletions(-) (limited to 'src/slskd/Core') 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 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/Core') diff --git a/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs index 6c5810c5..1a155f18 100644 --- a/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs +++ b/src/slskd/Core/Data/Migrations/Z2025_04_01_TransferStateMigration.cs @@ -69,7 +69,10 @@ public class Z2025_04_01_TransferStateMigration : IMigration var schema = SchemaInspector.GetDatabaseSchema(ConnectionString); var txfers = schema["Transfers"]; +#pragma warning disable CS0618 // Type or member is obsolete return !txfers.Any(c => c.Name == nameof(Transfer.StateDescription)); +#pragma warning restore CS0618 // Type or member is obsolete + } public void Apply() diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 05a913bd..77f7e7a9 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -37,6 +37,9 @@ using slskd.Validation; namespace slskd.Transfers.API; +/// +/// Enqueue a batch of downloads. +/// public record QueueDownloadBatchRequest { /// @@ -75,6 +78,9 @@ public record QueueDownloadBatchRequest public EnqueueDownloadBatchOptions Options { get; init; } = new(); } +/// +/// An item in a download batch. +/// public record EnqueueDownloadBatchItem { /// @@ -88,10 +94,14 @@ public record EnqueueDownloadBatchItem /// /// The file size. /// + [Required] [Range(0, long.MaxValue)] - public long Size { get; init; } + public long? Size { get; init; } } +/// +/// Download batch options. +/// public record EnqueueDownloadBatchOptions { /// @@ -99,5 +109,6 @@ public record EnqueueDownloadBatchOptions /// [RelativePath] [NonTraversingPath] + [MinLength(1)] public string Destination { get; init; } } \ No newline at end of file diff --git a/src/slskd/Transfers/API/DTO/Transfer.cs b/src/slskd/Transfers/API/DTO/Transfer.cs deleted file mode 100644 index 949f15d4..00000000 --- a/src/slskd/Transfers/API/DTO/Transfer.cs +++ /dev/null @@ -1,169 +0,0 @@ -// -// ▄▄▄▄ ▄▄▄▄ ▄▄▄▄ -// ▄▄▄▄▄▄█ █▄▄▄▄▄█ █▄▄▄▄▄█ █ -// █__ --█ █__ --█ ◄█ - █ -// █▄▄▄▄▄█▄▄█▄▄▄▄▄█▄▄█▄▄█▄▄▄▄▄█ -// ┍━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ ━━━━ ━ ━┉ ┉ ┉ -// │ Copyright (c) JP Dillingham. -// │ -// │ This program is free software: you can redistribute it and/or modify -// │ it under the terms of the GNU Affero General Public License as published -// │ by the Free Software Foundation, version 3. -// │ -// │ This program is distributed in the hope that it will be useful, -// │ but WITHOUT ANY WARRANTY; without even the implied warranty of -// │ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -// │ GNU Affero General Public License for more details. -// │ -// │ You should have received a copy of the GNU Affero General Public License -// │ along with this program. If not, see https://www.gnu.org/licenses/. -// │ -// │ This program is distributed with Additional Terms pursuant to Section 7 -// │ of the AGPLv3. See the LICENSE file in the root directory of this -// │ project for the complete terms and conditions. -// │ -// │ https://slskd.org -// │ -// ├╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ╌ ╌╌╌╌ ╌ -// │ SPDX-FileCopyrightText: JP Dillingham -// │ SPDX-License-Identifier: AGPL-3.0-only -// ╰───────────────────────────────────────────╶──── ─ ─── ─ ── ──┈ ┈ -// - -namespace slskd.Transfers.API -{ - using System; - using System.Net; - using Soulseek; - - /// - /// A single file transfer. - /// - public class Transfer - { - /// - /// Gets the current average transfer speed. - /// - public double AverageSpeed { get; set; } - - /// - /// Gets the number of remaining bytes to be transferred. - /// - public long BytesRemaining { get; set; } - - /// - /// Gets the total number of bytes transferred. - /// - public long BytesTransferred { get; set; } - - /// - /// Gets the transfer direction. - /// - public TransferDirection Direction { get; set; } - - /// - /// Gets the current duration of the transfer, if it has been started. - /// - public double? ElapsedTime { get; set; } - - /// - /// Gets the UTC time at which the transfer transitioned into the state. - /// - public DateTime? EndTime { get; set; } - - /// - /// Gets the filename of the file to be transferred. - /// - public string Filename { get; set; } - - /// - /// Gets the transfer id. - /// - public string Id => Compute.Sha1Hash(Filename); - - /// - /// Gets the ip endpoint of the remote transfer connection, if one has been established. - /// - public IPEndPoint IPEndPoint { get; set; } - - /// - /// Gets the current progress in percent. - /// - public double PercentComplete { get; set; } - - /// - /// Gets the current place in queue, if it has been fetched. - /// - public int? PlaceInQueue { get; set; } - - /// - /// Gets the projected remaining duration of the transfer. - /// - public double? RemainingTime { get; set; } - - /// - /// Gets the remote unique token for the transfer. - /// - public int? RemoteToken { get; set; } - - /// - /// Gets the size of the file to be transferred, in bytes. - /// - public long Size { get; set; } - - /// - /// Gets the starting offset of the transfer, in bytes. - /// - public long StartOffset { get; set; } - - /// - /// Gets the UTC time at which the transfer transitioned into the state. - /// - public DateTime? StartTime { get; set; } - - /// - /// Gets the state of the transfer. - /// - public TransferStates State { get; set; } - - /// - /// Gets the unique token for the transfer. - /// - public int Token { get; set; } - - /// - /// Gets the username of the peer to or from which the file is to be transferred. - /// - public string Username { get; set; } - - /// - /// Gets the Exception that caused the failure of the transfer, if applicable. - /// - public string Exception { get; set; } - - public static Transfer FromSoulseekTransfer(Soulseek.Transfer transfer) - { - return new Transfer() - { - AverageSpeed = transfer.AverageSpeed, - BytesRemaining = transfer.BytesRemaining, - BytesTransferred = transfer.BytesTransferred, - Direction = transfer.Direction, - ElapsedTime = transfer.ElapsedTime?.TotalMilliseconds, - EndTime = transfer.EndTime, - Filename = transfer.Filename, - IPEndPoint = transfer.IPEndPoint, - PercentComplete = transfer.PercentComplete, - RemainingTime = transfer.RemainingTime?.TotalMilliseconds, - RemoteToken = transfer.RemoteToken, - Size = transfer.Size, - StartOffset = transfer.StartOffset, - StartTime = transfer.StartTime, - State = transfer.State, - Token = transfer.Token, - Username = transfer.Username, - Exception = transfer.Exception?.Message, - }; - } - } -} \ No newline at end of file diff --git a/src/slskd/Transfers/TransfersDbContext.cs b/src/slskd/Transfers/TransfersDbContext.cs index 13d0984d..b25e7663 100644 --- a/src/slskd/Transfers/TransfersDbContext.cs +++ b/src/slskd/Transfers/TransfersDbContext.cs @@ -50,11 +50,17 @@ namespace slskd.Transfers public override int SaveChanges(bool acceptAllChangesOnSuccess) { // this is absolutely NOT IDEAL and will accellerate the move away from EF + // we have to do this to store both the integer and the string value in the database + // well, we don't *HAVE* to, but storing the string allows external apps to understand transfer history + // and not need to work out the flags. storing the integer allows us to use bitwise operations in queries, + // which is the main driver for this. foreach (var entry in ChangeTracker.Entries()) { if (entry.State == EntityState.Added || entry.State == EntityState.Modified) { +#pragma warning disable CS0618 // Type or member is obsolete entry.Entity.StateDescription = entry.Entity.State.ToString(); +#pragma warning restore CS0618 // Type or member is obsolete } } diff --git a/src/slskd/Transfers/Types/Transfer.cs b/src/slskd/Transfers/Types/Transfer.cs index 8d1afa25..d33a5efc 100644 --- a/src/slskd/Transfers/Types/Transfer.cs +++ b/src/slskd/Transfers/Types/Transfer.cs @@ -90,6 +90,8 @@ public class Transfer /// and especially **DO NOT** set the value. The getter and setter can't be protected because /// EF Core needs them to be public. /// + [Obsolete("Use State isntead; this is a hack for EF")] + [JsonIgnore] public string StateDescription { get; set; } /// @@ -160,7 +162,6 @@ public class Transfer /// /// Gets or sets a value indicating whether the Transfer has been removed from the UI. /// - [JsonIgnore] public bool Removed { get; set; } [NotMapped] -- cgit v1.2.3 From 772df82d0faf98f00fc8cc2ee59051e386eaa998 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 16 May 2026 18:52:44 -0500 Subject: remove disallowed character validation from instancename --- src/slskd/Core/Options.cs | 2 -- 1 file changed, 2 deletions(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 51b3cab1..21f2c75f 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -198,7 +198,6 @@ namespace slskd [Argument('i', "instance-name")] [EnvironmentVariable("INSTANCE_NAME")] [Description("optional; a unique name for this instance")] - [DisallowedCharacters('/', '\\')] [RequiresRestart] public string InstanceName { get; init; } = "default"; @@ -655,7 +654,6 @@ namespace slskd [Description("the name for this agent")] [StringLength(255, MinimumLength = 1)] [NotNullOrWhiteSpace] - [DisallowedCharacters('/', '\\')] [Secret] public string InstanceName { get; init; } -- cgit v1.2.3 From 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/Core') diff --git a/src/slskd/Common/Validation/AbsolutePathAttribute.cs b/src/slskd/Common/Validation/AbsolutePathAttribute.cs index 4c9f5e53..1999220f 100644 --- a/src/slskd/Common/Validation/AbsolutePathAttribute.cs +++ b/src/slskd/Common/Validation/AbsolutePathAttribute.cs @@ -49,12 +49,6 @@ namespace slskd.Validation { return new ValidationResult($"The {validationContext.DisplayName} field must be an absolute file path."); } - - // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here - if (FileSafety.ContainsTraversalSegments(path)) - { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); - } } return ValidationResult.Success; diff --git a/src/slskd/Common/Validation/GuidAttribute.cs b/src/slskd/Common/Validation/GuidAttribute.cs index 5728b8f6..f61527a4 100644 --- a/src/slskd/Common/Validation/GuidAttribute.cs +++ b/src/slskd/Common/Validation/GuidAttribute.cs @@ -32,6 +32,8 @@ namespace slskd.Validation { + using System; + using System.ComponentModel.DataAnnotations; /// @@ -39,6 +41,13 @@ namespace slskd.Validation /// public class GuidAttribute : ValidationAttribute { + public GuidAttribute(bool allowEmpty = false) + { + AllowEmpty = allowEmpty; + } + + public bool AllowEmpty { get; } + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value is null) @@ -46,8 +55,23 @@ namespace slskd.Validation return ValidationResult.Success; } - if (value is string str && System.Guid.TryParse(str, out _)) + if (value is Guid guid) { + if (!AllowEmpty && guid == Guid.Empty) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID"); + } + + return ValidationResult.Success; + } + + if (value is string str && Guid.TryParse(str, out guid)) + { + if (!AllowEmpty && guid == Guid.Empty) + { + return new ValidationResult($"The {validationContext.DisplayName} field must not contain an empty GUID/UUID"); + } + return ValidationResult.Success; } diff --git a/src/slskd/Common/Validation/RelativePathAttribute.cs b/src/slskd/Common/Validation/RelativePathAttribute.cs index e8865554..64e418b1 100644 --- a/src/slskd/Common/Validation/RelativePathAttribute.cs +++ b/src/slskd/Common/Validation/RelativePathAttribute.cs @@ -49,12 +49,6 @@ namespace slskd.Validation { return new ValidationResult($"The {validationContext.DisplayName} field must be a relative path."); } - - // unrelated to absolute/relative check; we disallow traversal segments across the board so check while we're here - if (FileSafety.ContainsTraversalSegments(path)) - { - return new ValidationResult($"The {validationContext.DisplayName} field contains one or more unsafe path traversal segments ('.' or '..')"); - } } return ValidationResult.Success; diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 21f2c75f..3d9c8fb2 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -766,6 +766,7 @@ namespace slskd [EnvironmentVariable("INCOMPLETE_DIR")] [Description("path where incomplete downloads are saved")] [AbsolutePath] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Incomplete { get; init; } = Program.DefaultIncompleteDirectory; @@ -777,6 +778,7 @@ namespace slskd [EnvironmentVariable("DOWNLOADS_DIR")] [Description("path where downloaded files are saved")] [AbsolutePath] + [NonTraversingPath] [DirectoryExists(ensureWriteable: true)] [RequiresRestart] public string Downloads { get; init; } = Program.DefaultDownloadsDirectory; @@ -2013,6 +2015,7 @@ namespace slskd [EnvironmentVariable("HTTP_SOCKET")] [Description("HTTP listen unix domain socket (UDS) path for web UI")] [AbsolutePath] + [NonTraversingPath] [RequiresRestart] public string Socket { get; init; } diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 01dd61bd..3191e3a8 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -385,7 +385,7 @@ namespace slskd.Transfers.API if (failed.Count > 0) { - Log.Warning("Failed to enqueue {Count} of {Total} files for {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, batchId, failed); + Log.Warning("Failed to enqueue {Count} of {Total} files from {Username}; transfers already queued, in progress, or an error occurred (batch Id: {BatchId}). Failues: {Failures}", failed.Count, request.Files.Count, request.Username, batchId, failed); } // the returned batch will have whatever Transfers were successfully inserted attached (via Include()) @@ -488,7 +488,7 @@ namespace slskd.Transfers.API if (!Guid.TryParse(id, out var guid)) { - return BadRequest(); + return BadRequest($"The specified id {id} is not a valid GUID/UUID"); } try diff --git a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs index 53f5290f..c1b7d725 100644 --- a/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs +++ b/src/slskd/Transfers/API/DTO/QueueDownloadBatchRequest.cs @@ -61,8 +61,7 @@ public record QueueDownloadBatchRequest /// The username of the user from which to download. /// [Required] - [NotNullOrWhiteSpace] - [StringLength(maximumLength: 500)] + [String(AllowNull = false, AllowEmpty = false, AllowWhiteSpace = false, MinimumLength = 1, MaximumLength = 500)] public string Username { get; init; } /// diff --git a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs index 53e25ac6..bc8601c5 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/AbsolutePathAttributeTests.cs @@ -171,39 +171,6 @@ public class AbsolutePathAttributeTests } } - // Paths containing . or .. segments, which are valid directory names in isolation - // but indicate traversal or ambiguity and must be rejected regardless of whether - // the path is otherwise absolute or relative. - public class Traversal_Fails - { - [Theory] - // Windows-style traversal - [InlineData("C:\\Music\\..\\Windows")] // traversal to sibling via backslash - [InlineData("C:\\Music\\.\\Artist")] // current-dir segment via backslash - [InlineData("C:/Music/../Windows")] // traversal via forward slash - [InlineData("C:/Music/./Artist")] // current-dir via forward slash - [InlineData("C:\\..")] // traversal at drive root - [InlineData("D:\\a\\b\\..\\c")] // traversal deep in path - // Unix-style traversal - [InlineData("/../etc")] // traversal at Unix root - [InlineData("/home/user/../etc")] // traversal to sibling on Unix - [InlineData("/home/user/./Music")] // current-dir on Unix - [InlineData("/home/../../etc")] // double traversal on Unix - // UNC traversal (backslash) - [InlineData("\\\\server\\..\\Windows")] // traversal past UNC server - [InlineData("\\\\server\\share\\..\\other")] // traversal within UNC share - [InlineData("\\\\server\\share\\.\\folder")] // current-dir within UNC share - // UNC traversal (forward slash) - [InlineData("//server/../share")] // traversal past server, forward slash - [InlineData("//server/share/../other")] // traversal within share, forward slash - public void TraversalSegment_Fails(string value) - { - var (isValid, errorMessage) = Validate(value); - Assert.False(isValid); - Assert.Contains("traversal segments", errorMessage); - } - } - public class Relative_Fails { [Theory] diff --git a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs index e574c130..a26bb160 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/GuidAttributeTests.cs @@ -1,3 +1,4 @@ +using System; using System.ComponentModel.DataAnnotations; using slskd.Validation; using Xunit; @@ -6,9 +7,9 @@ namespace slskd.Tests.Unit.Common.Validation; public class GuidAttributeTests { - private static (bool IsValid, string ErrorMessage) Validate(object value) + private static (bool IsValid, string ErrorMessage) Validate(object value, bool allowEmpty = false) { - var attribute = new GuidAttribute(); + var attribute = new GuidAttribute(allowEmpty); var context = new ValidationContext(new object()) { DisplayName = "Field", MemberName = "Field" }; var result = attribute.GetValidationResult(value, context); return (result == null, result?.ErrorMessage); @@ -22,53 +23,84 @@ public class GuidAttributeTests Assert.True(isValid); } - public class Passes + [Fact] + public void Empty_String_Fails_If_AllowEmpty_False() + { + var (isValid, message) = Validate("00000000-0000-0000-0000-000000000000", allowEmpty: false); + Assert.False(isValid); + Assert.Contains("empty", message); + } + + [Fact] + public void Empty_Guid_Fails_If_AllowEmpty_False() { - [Theory] - [InlineData("d3b07384-d9a0-4b9b-abcd-012345678901")] // lowercase with hyphens - [InlineData("D3B07384-D9A0-4B9B-ABCD-012345678901")] // uppercase with hyphens - [InlineData("d3b07384d9a04b9babcd012345678901")] // no hyphens (N format) - [InlineData("{d3b07384-d9a0-4b9b-abcd-012345678901}")] // braces format - [InlineData("(d3b07384-d9a0-4b9b-abcd-012345678901)")] // parentheses format - [InlineData("00000000-0000-0000-0000-000000000000")] // all zeros - [InlineData("ffffffff-ffff-ffff-ffff-ffffffffffff")] // all f's - public void ValidGuidString_Passes(string value) - { - var (isValid, _) = Validate(value); - Assert.True(isValid); - } + var (isValid, message) = Validate(Guid.Empty, allowEmpty: false); + Assert.False(isValid); + Assert.Contains("empty", message); } - public class Fails + [Fact] + public void AllowEmpty_Guid_Defaults_False() { - [Fact] - public void EmptyString_Fails() - { - var (isValid, errorMessage) = Validate(string.Empty); - Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); - } + var (isValid, message) = Validate(Guid.Empty); + Assert.False(isValid); + Assert.Contains("empty", message); + } - [Theory] - [InlineData("not-a-guid")] // arbitrary string - [InlineData("d3b07384-d9a0-4b9b-abcd")] // too short - [InlineData("d3b07384-d9a0-4b9b-abcd-01234567890Z")] // invalid character Z - [InlineData("d3b07384-d9a0-4b9b-abcd-0123456789012")] // one char too long - [InlineData("g3b07384-d9a0-4b9b-abcd-012345678901")] // invalid hex char g - [InlineData("d3b07384 d9a0 4b9b abcd 012345678901")] // spaces instead of hyphens - public void InvalidGuidString_Fails(string value) - { - var (isValid, errorMessage) = Validate(value); - Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); - } + [Fact] + public void AllowEmpty_String_Defaults_False() + { + var (isValid, message) = Validate(Guid.Empty.ToString()); + Assert.False(isValid); + Assert.Contains("empty", message); + } + + [Fact] + public void Empty_String_Passes_If_AllowEmpty_True() + { + var (isValid, _) = Validate(Guid.Empty.ToString(), allowEmpty: true); + Assert.True(isValid); + } - [Fact] - public void NonStringValue_Fails() - { - var (isValid, errorMessage) = Validate(42); - Assert.False(isValid); - Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); - } + [Fact] + public void Empty_Guid_Passes_If_AllowEmpty_True() + { + var (isValid, _) = Validate(Guid.Empty, allowEmpty: true); + Assert.True(isValid); + } + + [Theory] + [InlineData("d3b07384-d9a0-4b9b-abcd-012345678901")] // lowercase with hyphens + [InlineData("D3B07384-D9A0-4B9B-ABCD-012345678901")] // uppercase with hyphens + [InlineData("d3b07384d9a04b9babcd012345678901")] // no hyphens (N format) + [InlineData("{d3b07384-d9a0-4b9b-abcd-012345678901}")] // braces format + [InlineData("(d3b07384-d9a0-4b9b-abcd-012345678901)")] // parentheses format + [InlineData("ffffffff-ffff-ffff-ffff-ffffffffffff")] // all f's + public void ValidGuidString_Passes(string value) + { + var (isValid, _) = Validate(value); + Assert.True(isValid); + } + + [Theory] + [InlineData("not-a-guid")] // arbitrary string + [InlineData("d3b07384-d9a0-4b9b-abcd")] // too short + [InlineData("d3b07384-d9a0-4b9b-abcd-01234567890Z")] // invalid character Z + [InlineData("d3b07384-d9a0-4b9b-abcd-0123456789012")] // one char too long + [InlineData("g3b07384-d9a0-4b9b-abcd-012345678901")] // invalid hex char g + [InlineData("d3b07384 d9a0 4b9b abcd 012345678901")] // spaces instead of hyphens + public void InvalidGuidString_Fails(string value) + { + var (isValid, errorMessage) = Validate(value); + Assert.False(isValid); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); + } + + [Fact] + public void NonStringValue_Fails() + { + var (isValid, errorMessage) = Validate(42); + Assert.False(isValid); + Assert.Equal("The Field field must be a valid GUID/UUID", errorMessage); } } diff --git a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs index 1692bceb..bc581bf1 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/RelativePathAttributeTests.cs @@ -66,32 +66,6 @@ public class RelativePathAttributeTests } } - public class Traversal_Fails - { - [Theory] - [InlineData("..")] // bare traversal - [InlineData(".")] // bare current-dir - [InlineData("../music")] // traversal prefix, forward slash - [InlineData("./music")] // current-dir prefix - [InlineData("music/../other")] // traversal in middle - [InlineData("music/./other")] // current-dir in middle - [InlineData("sub/../../escape")] // double traversal - [InlineData("music\\..")] // traversal via backslash - [InlineData("music\\.")] // current-dir via backslash - [InlineData("music/dir/..")] // traversal at end - [InlineData("a/b/c/../../d")] // multi-level traversal - [InlineData("Ünïcödé/../escape")] // latin extended with traversal - [InlineData("пользователь/../etc")] // Cyrillic with traversal - [InlineData("用户/音乐/../../escape")] // Chinese with deep traversal - [InlineData("ユーザー\\..\\escape")] // Japanese with backslash traversal - public void TraversalSegment_Fails(string value) - { - var (isValid, errorMessage) = Validate(value); - Assert.False(isValid); - Assert.Contains("traversal segments", errorMessage); - } - } - public class Absolute_Fails { [Theory] diff --git a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs index 71e6ce8b..dbc82736 100644 --- a/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs +++ b/tests/slskd.Tests.Unit/Common/Validation/StringAttributeTests.cs @@ -17,49 +17,119 @@ public class StringAttributeTests return (result == null, result?.ErrorMessage); } - // empty string passes all default checks — [Required] handles presence - [Fact] - public void EmptyString_Passes() + public class Null { - var (isValid, _) = Validate(string.Empty); - Assert.True(isValid); + [Fact] + public void Passes_When_AllowNull() + { + var (isValid, message) = Validate(null, a => a.AllowNull = true); + Assert.True(isValid); + } + + [Fact] + public void Fails_When_Not_AllowNull() + { + var (isValid, message) = Validate(null, a => a.AllowNull = false); + Assert.False(isValid); + Assert.Contains("must not be null", message); + } + + [Fact] + public void NonNull_Passes_Regardless() + { + var (isValid, message) = Validate("foo", a => a.AllowNull = true); + Assert.True(isValid); + + var (isValid2, message2) = Validate("foo", a => a.AllowNull = false); + Assert.True(isValid); + } } - public class DisallowedCharacters + public class Empty { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => StringAttributeTests.Validate(value, a => a.DisallowedCharacters = disallowed); + [Fact] + public void Empty_Passes_When_AllowEmpty_Is_True() + { + var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = true); + Assert.True(isValid); + } - public class Passes + [Fact] + public void Empty_Fails_When_AllowEmpty_Is_False() + { + var (isValid, message) = Validate(string.Empty, a => a.AllowEmpty = false); + Assert.False(isValid); + Assert.Contains("at least one character", message); + } + + [Fact] + public void NonEmpty_Passes_Regardless() + { + var (isValid, _) = Validate("hello", a => a.AllowEmpty = false); + Assert.True(isValid); + + var (isValid2, _) = Validate("hello", a => a.AllowEmpty = true); + Assert.True(isValid); + } + } + + public class WhiteSpace + { + [Fact] + public void WhiteSpace_Passes_When_AllowWhiteSpace_Is_True() + { + var (isValid, _) = Validate(" ", a => a.AllowWhiteSpace = true); + Assert.True(isValid); + } + + [Fact] + public void WhiteSpace_Fails_When_AllowWhiteSpace_Is_False() + { + var (isValid, message) = Validate(" ", a => a.AllowWhiteSpace = false); + Assert.False(isValid); + Assert.Contains("whitespace", message); + } + + [Fact] + public void NonWhiteSpace_Passes_Regardless() { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => DisallowedCharacters.Validate(value, disallowed); + var (isValid, _) = Validate("hello", a => a.AllowWhiteSpace = false); + Assert.True(isValid); + var (isValid2, _) = Validate("hello", a => a.AllowWhiteSpace = true); + Assert.True(isValid); + } + } + + public class DisallowedCharacters + { + public class Passes + { [Fact] public void EmptyString_Passes() { - var (isValid, _) = Validate(string.Empty, ['!']); + var (isValid, _) = Validate(string.Empty, a => a.DisallowedCharacters = ['!']); Assert.True(isValid); } [Fact] public void NoDisallowedCharsPresent_Passes() { - var (isValid, _) = Validate("hello", ['!', '@']); + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['!', '@']); Assert.True(isValid); } [Fact] public void EmptyDisallowedSet_Passes() { - var (isValid, _) = Validate("hello!@#", []); + var (isValid, _) = Validate("hello!@#", a => a.DisallowedCharacters = []); Assert.True(isValid); } [Fact] public void Unicode_AllowedChars_Pass() { - var (isValid, _) = Validate("пользователь/音楽", ['!', '@']); + var (isValid, _) = Validate("пользователь/音楽", a => a.DisallowedCharacters = ['!', '@']); Assert.True(isValid); } @@ -68,76 +138,73 @@ public class StringAttributeTests [Fact] public void LowerCaseDisallowed_DoesNotBlock_Different_UpperCaseLetter() { - var (isValid, _) = Validate("B", ['a']); + var (isValid, _) = Validate("B", a => a.DisallowedCharacters = ['a']); Assert.True(isValid); } } public class Fails { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => DisallowedCharacters.Validate(value, disallowed); - [Fact] public void SingleDisallowedChar_Fails() { - var (isValid, _) = Validate("hello!", ['!']); + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void DisallowedCharAtStart_Fails() { - var (isValid, _) = Validate("!hello", ['!']); + var (isValid, _) = Validate("!hello", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void DisallowedCharAtEnd_Fails() { - var (isValid, _) = Validate("hello!", ['!']); + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void DisallowedCharInMiddle_Fails() { - var (isValid, _) = Validate("hel!lo", ['!']); + var (isValid, _) = Validate("hel!lo", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void OneOfMultipleDisallowedCharsPresent_Fails() { - var (isValid, _) = Validate("hello!", ['!', '@', '#']); + var (isValid, _) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@', '#']); Assert.False(isValid); } [Fact] public void MultipleDisallowedCharsAllPresent_Fails() { - var (isValid, _) = Validate("h!e@l#lo", ['!', '@', '#']); + var (isValid, _) = Validate("h!e@l#lo", a => a.DisallowedCharacters = ['!', '@', '#']); Assert.False(isValid); } [Fact] public void DisallowedCharRepeated_Fails() { - var (isValid, _) = Validate("he!lo!", ['!']); + var (isValid, _) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']); Assert.False(isValid); } [Fact] public void AllCharsDisallowed_Fails() { - var (isValid, _) = Validate("!@#", ['!', '@', '#']); + var (isValid, _) = Validate("!@#", a => a.DisallowedCharacters = ['!', '@', '#']); Assert.False(isValid); } [Fact] public void Unicode_DisallowedChar_Fails() { - var (isValid, _) = Validate("пользователь", ['е']); + var (isValid, _) = Validate("пользователь", a => a.DisallowedCharacters = ['е']); Assert.False(isValid); } @@ -145,41 +212,38 @@ public class StringAttributeTests [Fact] public void LowerCaseDisallowed_Blocks_UpperCase() { - var (isValid, _) = Validate("HELLO", ['h', 'e', 'l', 'o']); + var (isValid, _) = Validate("HELLO", a => a.DisallowedCharacters = ['h', 'e', 'l', 'o']); Assert.False(isValid); } [Fact] public void UpperCaseDisallowed_Blocks_LowerCase() { - var (isValid, _) = Validate("hello", ['H', 'E', 'L', 'O']); + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['H', 'E', 'L', 'O']); Assert.False(isValid); } [Fact] public void ExactMatch_Fails() { - var (isValid, _) = Validate("hello", ['h']); + var (isValid, _) = Validate("hello", a => a.DisallowedCharacters = ['h']); Assert.False(isValid); } } public class ErrorMessage_Contains { - private static (bool IsValid, string ErrorMessage) Validate(string value, char[] disallowed) - => DisallowedCharacters.Validate(value, disallowed); - [Fact] public void TheDisallowedChar() { - var (_, errorMessage) = Validate("hello!", ['!']); + var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!']); Assert.Contains("'!'", errorMessage); } [Fact] public void AllPresentDisallowedChars() { - var (_, errorMessage) = Validate("h!@l", ['!', '@']); + var (_, errorMessage) = Validate("h!@l", a => a.DisallowedCharacters = ['!', '@']); Assert.Contains("'!'", errorMessage); Assert.Contains("'@'", errorMessage); } @@ -188,7 +252,7 @@ public class StringAttributeTests public void EachOccurrenceOfRepeatedChar() { // "he!lo!" has two '!' — both occurrences are listed - var (_, errorMessage) = Validate("he!lo!", ['!']); + var (_, errorMessage) = Validate("he!lo!", a => a.DisallowedCharacters = ['!']); Assert.Equal(2, errorMessage.Split("'!'").Length - 1); } @@ -196,7 +260,7 @@ public class StringAttributeTests public void OnlyCharsActuallyPresent_NotAllDisallowedChars() { // '@' is disallowed but not in the value — must not appear in the message - var (_, errorMessage) = Validate("hello!", ['!', '@']); + var (_, errorMessage) = Validate("hello!", a => a.DisallowedCharacters = ['!', '@']); Assert.Contains("'!'", errorMessage); Assert.DoesNotContain("'@'", errorMessage); } @@ -206,159 +270,15 @@ public class StringAttributeTests { // 'a' is disallowed (lowercase); value contains 'A' (uppercase). // The message reports what the user supplied ('A'), not the disallowed definition ('a'). - var (_, errorMessage) = Validate("A", ['a']); + var (_, errorMessage) = Validate("A", a => a.DisallowedCharacters = ['a']); Assert.Contains("'A'", errorMessage); Assert.DoesNotContain("'a'", errorMessage); } } } - // ----------------------------------------------------------------------- - // AllowNull - // ----------------------------------------------------------------------- - public class AllowNull - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - - [Fact] - public void Null_Passes_When_AllowNull_Is_True() - { - var (isValid, _) = Validate(null); - Assert.True(isValid); - } - - [Fact] - public void Null_Fails_When_AllowNull_Is_False() - { - var (isValid, _) = Validate(null, a => a.AllowNull = false); - Assert.False(isValid); - } - - [Fact] - public void NonNull_Passes_When_AllowNull_Is_False() - { - var (isValid, _) = Validate("hello", a => a.AllowNull = false); - Assert.True(isValid); - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => AllowNull.Validate(value, configure); - - [Fact] - public void Null_Keyword() - { - var (_, message) = Validate(null, a => a.AllowNull = false); - Assert.Contains("null", message); - } - } - } - - // ----------------------------------------------------------------------- - // AllowEmpty - // ----------------------------------------------------------------------- - public class AllowEmpty - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - - [Fact] - public void Empty_Passes_When_AllowEmpty_Is_True() - { - var (isValid, _) = Validate(string.Empty); - Assert.True(isValid); - } - - [Fact] - public void Empty_Fails_When_AllowEmpty_Is_False() - { - var (isValid, _) = Validate(string.Empty, a => a.AllowEmpty = false); - Assert.False(isValid); - } - - [Fact] - public void NonEmpty_Passes_When_AllowEmpty_Is_False() - { - var (isValid, _) = Validate("hello", a => a.AllowEmpty = false); - Assert.True(isValid); - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => AllowEmpty.Validate(value, configure); - - [Fact] - public void Character_Keyword() - { - var (_, message) = Validate(string.Empty, a => a.AllowEmpty = false); - Assert.Contains("character", message); - } - } - } - - // ----------------------------------------------------------------------- - // AllowWhiteSpace - // ----------------------------------------------------------------------- - public class AllowWhiteSpace - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - - [Fact] - public void WhiteSpace_Passes_When_AllowWhiteSpace_Is_True() - { - var (isValid, _) = Validate(" "); - Assert.True(isValid); - } - - [Fact] - public void WhiteSpace_Fails_When_AllowWhiteSpace_Is_False() - { - var (isValid, _) = Validate(" ", a => a.AllowWhiteSpace = false); - Assert.False(isValid); - } - - [Fact] - public void NonWhiteSpace_Passes_When_AllowWhiteSpace_Is_False() - { - var (isValid, _) = Validate("hello", a => a.AllowWhiteSpace = false); - Assert.True(isValid); - } - - // IsNullOrWhiteSpace("") is true, so empty string also fails the whitespace check - // when AllowEmpty=true (default) and AllowWhiteSpace=false - [Fact] - public void EmptyString_Fails_When_AllowWhiteSpace_Is_False_And_AllowEmpty_Is_True() - { - var (isValid, _) = Validate(string.Empty, a => a.AllowWhiteSpace = false); - Assert.False(isValid); - } - - public class ErrorMessage_Contains - { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => AllowWhiteSpace.Validate(value, configure); - - [Fact] - public void Whitespace_Keyword() - { - var (_, message) = Validate(" ", a => a.AllowWhiteSpace = false); - Assert.Contains("whitespace", message); - } - } - } - - // ----------------------------------------------------------------------- - // Length (MinimumLength / MaximumLength) - // ----------------------------------------------------------------------- public class Length { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - [Fact] public void Within_Range_Passes() { @@ -396,9 +316,6 @@ public class StringAttributeTests public class ErrorMessage_Contains { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => Length.Validate(value, configure); - [Fact] public void MinimumLength_Value() { @@ -415,16 +332,8 @@ public class StringAttributeTests } } - // ----------------------------------------------------------------------- - // Pattern - // ----------------------------------------------------------------------- - // The Pattern check fails validation when the value *matches* the regex — - // Pattern acts as a "disallowed pattern" rather than a "required pattern". public class Pattern { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - [Fact] public void NullPattern_Passes() { @@ -449,9 +358,6 @@ public class StringAttributeTests public class ErrorMessage_Contains { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => Pattern.Validate(value, configure); - [Fact] public void RegularExpression_Keyword() { @@ -461,16 +367,8 @@ public class StringAttributeTests } } - // ----------------------------------------------------------------------- - // Check ordering - // ----------------------------------------------------------------------- - // Validation checks run in declaration order; when a value violates multiple - // conditions the error from the first check in code is the one returned. public class CheckOrdering { - private static (bool IsValid, string ErrorMessage) Validate(string value, Action configure = null) - => StringAttributeTests.Validate(value, configure); - // AllowNull is checked before AllowEmpty: // null with both disabled returns the null error, not the empty error. [Fact] diff --git a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs index 2440291c..a9f30129 100644 --- a/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs +++ b/tests/slskd.Tests.Unit/Transfers/API/DTO/QueueDownloadBatchRequestTests.cs @@ -141,7 +141,7 @@ public class QueueDownloadBatchRequestTests var (isValid, results) = Validate(ValidRequest() with { Username = new string('a', 501) }); Assert.False(isValid); Assert.Single(results); - Assert.Equal("The field Username must be a string with a minimum length of 1 and a maximum length of 500.", results[0].ErrorMessage); + Assert.Contains("between 1 and 500 characters", results[0].ErrorMessage); } } -- cgit v1.2.3 From 97104a235b705bc1b8151a4a0b244efbf875b866 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 15:25:59 -0500 Subject: add regex to block shares with path traversal segments --- src/slskd/Core/Options.cs | 6 ++++++ 1 file changed, 6 insertions(+) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index 3d9c8fb2..f952f014 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -845,6 +845,12 @@ namespace slskd directories?.Where(share => !IsAbsolutePath(share)).ToList() .ForEach(relativePath => results.Add(new ValidationResult($"Share {relativePath} contains a relative path; only absolute paths are supported."))); + // contains /./ or /../ or \.\ or \..\ or ..\ or ../ or \.. or /.. + // which is resolved by some OS and will cause weird, unintended side effects + bool ContainsTraversalSegments(string share) => Regex.IsMatch(share.LocalizePath(), @"^\.+[\/\\]?|[\/\\]\.+[\/\\]|[\/\\]\.+$"); + directories?.Where(share => ContainsTraversalSegments(share)).ToList() + .ForEach(badPath => results.Add(new ValidationResult($"Share {badPath} contains an unsafe path traversal segment."))); + (string Raw, string Alias, string Path) Digest(string share) { var matches = Regex.Matches(share, @"^(!|-){0,1}\[(.*)\](.*)$"); -- cgit v1.2.3 From 6f0d9682fde688cf1fd8d3f330aca71616f28a9f Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 17 May 2026 17:02:27 -0500 Subject: capture alias up to the first closing square bracket --- src/slskd/Core/Options.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src/slskd/Core') diff --git a/src/slskd/Core/Options.cs b/src/slskd/Core/Options.cs index f952f014..83e534a1 100644 --- a/src/slskd/Core/Options.cs +++ b/src/slskd/Core/Options.cs @@ -853,7 +853,7 @@ namespace slskd (string Raw, string Alias, string Path) Digest(string share) { - var matches = Regex.Matches(share, @"^(!|-){0,1}\[(.*)\](.*)$"); + var matches = Regex.Matches(share, @"^(!|-){0,1}\[([^\]]*)\](.*)$"); if (matches.Any()) { -- cgit v1.2.3