From 7b0dce6b5f25427b2d2695f143bd6c8dd15fd3e3 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 7 Dec 2025 19:25:08 -0600 Subject: rough in solution from github issues --- src/slskd/Common/Middleware/RouteUnsafeBinder.cs | 82 ++++++++++++++++++++++++ src/slskd/Program.cs | 5 +- 2 files changed, 86 insertions(+), 1 deletion(-) create mode 100644 src/slskd/Common/Middleware/RouteUnsafeBinder.cs (limited to 'src') diff --git a/src/slskd/Common/Middleware/RouteUnsafeBinder.cs b/src/slskd/Common/Middleware/RouteUnsafeBinder.cs new file mode 100644 index 00000000..7a5f5b99 --- /dev/null +++ b/src/slskd/Common/Middleware/RouteUnsafeBinder.cs @@ -0,0 +1,82 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; +using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; + +namespace slskd; + +public class RouteUnsafeBinder : IModelBinder +{ + public Task BindModelAsync(ModelBindingContext bindingContext) + { + ArgumentNullException.ThrowIfNull(bindingContext); + + var modelName = bindingContext.ModelName; + + // make sure the param we want was extracted in the standard method + // this will be the partially-decoded value that we're looking to avoid using here + if (!bindingContext.ActionContext.RouteData.Values.ContainsKey(modelName)) + throw new NotSupportedException(); + + // wrap the param in curly braces so we can look for it in the [Route(...)] path + var templateToMatch = $"{{{modelName}}}"; + + // if this is null then the developer forgot the [Route(...)] attribute + var request = bindingContext.HttpContext.Request; + var template = (bindingContext.ActionContext.ActionDescriptor.AttributeRouteInfo?.Template) + ?? throw new NotSupportedException(); + + // get the raw url that was called + var rawTarget = bindingContext.HttpContext.Features.Get()?.RawTarget + ?? throw new NotSupportedException(); + // strip the query string + var path = new Uri($"{request.Scheme}://{request.Host}{rawTarget}").AbsolutePath; + + // go through route template and find which segment we need to extract by index + var index = template + .Split('/', StringSplitOptions.RemoveEmptyEntries) + .Select((segment, index) => new { segment, index }) + .SingleOrDefault(iter => + iter.segment.Equals(templateToMatch, StringComparison.OrdinalIgnoreCase)) + ?.index; + + var segments = path.ToString().Split('/', StringSplitOptions.RemoveEmptyEntries); + + if (index.HasValue) + { + // extract and decode the target path segment + var rawUrlSegment = segments[index.Value]; + var decoded = Uri.UnescapeDataString(rawUrlSegment); + + Console.WriteLine($"decoded {decoded} from {rawUrlSegment}"); + bindingContext.Result = ModelBindingResult.Success(decoded); + } + else + { + // can't think of any scenarios where we'd hit this + throw new NotSupportedException(); + } + + return Task.CompletedTask; + } +} + +public class FromRouteUnsafeModelBinder : IModelBinderProvider +{ + public IModelBinder? GetBinder(ModelBinderProviderContext context) + { + if (context.Metadata is not DefaultModelMetadata metadata) return null; + var attribs = metadata.Attributes.ParameterAttributes; + return attribs == null + ? null + // handle all [FromRoute] string parameters + : attribs.Any(pa => pa.GetType() == typeof(FromRouteAttribute)) + && metadata.ModelType == typeof(string) + ? new BinderTypeModelBinder(typeof(RouteUnsafeBinder)) + : null; + } +} \ No newline at end of file diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index aa320961..2d35f2a5 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -847,7 +847,10 @@ namespace slskd } services.AddRouting(options => options.LowercaseUrls = true); - services.AddControllers() + services.AddControllers(options => + { + options.ModelBinderProviders.Insert(0, new FromRouteUnsafeModelBinder()); + }) .ConfigureApiBehaviorOptions(options => { options.SuppressInferBindingSourcesForParameters = true; // explicit [FromRoute], etc -- cgit v1.2.3 From 42c01f5626df717cd7c3cb45765572ad60573551 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Jan 2026 17:38:14 -0600 Subject: rename and tweak --- src/slskd/Common/Middleware/RouteUnsafeBinder.cs | 82 -------------- .../Common/Middleware/UrlEncodingModelBinder.cs | 119 +++++++++++++++++++++ 2 files changed, 119 insertions(+), 82 deletions(-) delete mode 100644 src/slskd/Common/Middleware/RouteUnsafeBinder.cs create mode 100644 src/slskd/Common/Middleware/UrlEncodingModelBinder.cs (limited to 'src') diff --git a/src/slskd/Common/Middleware/RouteUnsafeBinder.cs b/src/slskd/Common/Middleware/RouteUnsafeBinder.cs deleted file mode 100644 index 7a5f5b99..00000000 --- a/src/slskd/Common/Middleware/RouteUnsafeBinder.cs +++ /dev/null @@ -1,82 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.AspNetCore.Http.Features; -using Microsoft.AspNetCore.Mvc; -using Microsoft.AspNetCore.Mvc.ModelBinding; -using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; -using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; - -namespace slskd; - -public class RouteUnsafeBinder : IModelBinder -{ - public Task BindModelAsync(ModelBindingContext bindingContext) - { - ArgumentNullException.ThrowIfNull(bindingContext); - - var modelName = bindingContext.ModelName; - - // make sure the param we want was extracted in the standard method - // this will be the partially-decoded value that we're looking to avoid using here - if (!bindingContext.ActionContext.RouteData.Values.ContainsKey(modelName)) - throw new NotSupportedException(); - - // wrap the param in curly braces so we can look for it in the [Route(...)] path - var templateToMatch = $"{{{modelName}}}"; - - // if this is null then the developer forgot the [Route(...)] attribute - var request = bindingContext.HttpContext.Request; - var template = (bindingContext.ActionContext.ActionDescriptor.AttributeRouteInfo?.Template) - ?? throw new NotSupportedException(); - - // get the raw url that was called - var rawTarget = bindingContext.HttpContext.Features.Get()?.RawTarget - ?? throw new NotSupportedException(); - // strip the query string - var path = new Uri($"{request.Scheme}://{request.Host}{rawTarget}").AbsolutePath; - - // go through route template and find which segment we need to extract by index - var index = template - .Split('/', StringSplitOptions.RemoveEmptyEntries) - .Select((segment, index) => new { segment, index }) - .SingleOrDefault(iter => - iter.segment.Equals(templateToMatch, StringComparison.OrdinalIgnoreCase)) - ?.index; - - var segments = path.ToString().Split('/', StringSplitOptions.RemoveEmptyEntries); - - if (index.HasValue) - { - // extract and decode the target path segment - var rawUrlSegment = segments[index.Value]; - var decoded = Uri.UnescapeDataString(rawUrlSegment); - - Console.WriteLine($"decoded {decoded} from {rawUrlSegment}"); - bindingContext.Result = ModelBindingResult.Success(decoded); - } - else - { - // can't think of any scenarios where we'd hit this - throw new NotSupportedException(); - } - - return Task.CompletedTask; - } -} - -public class FromRouteUnsafeModelBinder : IModelBinderProvider -{ - public IModelBinder? GetBinder(ModelBinderProviderContext context) - { - if (context.Metadata is not DefaultModelMetadata metadata) return null; - var attribs = metadata.Attributes.ParameterAttributes; - return attribs == null - ? null - // handle all [FromRoute] string parameters - : attribs.Any(pa => pa.GetType() == typeof(FromRouteAttribute)) - && metadata.ModelType == typeof(string) - ? new BinderTypeModelBinder(typeof(RouteUnsafeBinder)) - : null; - } -} \ No newline at end of file diff --git a/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs b/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs new file mode 100644 index 00000000..2c6f341f --- /dev/null +++ b/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs @@ -0,0 +1,119 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// 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, either version 3 of the License, or +// (at your option) any later version. +// +// 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/. +// + +namespace slskd; + +using System; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.AspNetCore.Mvc.ModelBinding; +using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; +using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; + +/// +/// Model binder for URL encoded strings. +/// +/// For this to work as intended, method parameters must: +/// +/// +/// Use either Path binding (e.g [FromRoute]) +/// Have a backing type of string +/// Be decorated with the [UrlEncoded] attribute +/// +/// +/// Most of this assumes the model binder is configured with . +/// +public class UrlEncodingModelBinder : IModelBinder +{ + /// + public Task BindModelAsync(ModelBindingContext bindingContext) + { + try + { + // get the raw value that was passed, if any + var potentiallyUrlEncodedResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); + + if (potentiallyUrlEncodedResult == ValueProviderResult.None) + { + return Task.CompletedTask; + } + + var value = potentiallyUrlEncodedResult.FirstValue; + + if (string.IsNullOrEmpty(value)) + { + return Task.CompletedTask; + } + + // a value was provided; decode it + var decodedValue = Uri.UnescapeDataString(value); + + bindingContext.Result = ModelBindingResult.Success(decodedValue); + return Task.CompletedTask; + } + catch (Exception ex) + { + Console.Error.WriteLine(ex); + throw; + } + } +} + +/// +/// Model binding provider for URL encoded string binding via . +/// +public class UrlEncodingModelBinderProvider : IModelBinderProvider +{ + /// + /// Only use this binder if ALL of the following are true: + /// + /// + /// The binding source is Path (instead of Query, Form, Body, etc) + /// The target type is string + /// The target parameter has the [UrlEncoded] attribute + /// + /// + /// The model binder context. + /// An instance of , or null if the conditions haven't been met. + public IModelBinder GetBinder(ModelBinderProviderContext context) + { + if (context.BindingInfo.BindingSource != BindingSource.Path) + { + return null; + } + + if (context.Metadata is not DefaultModelMetadata metadata || metadata.ModelType != typeof(string)) + { + return null; + } + + if (!metadata.Attributes.ParameterAttributes?.Any(a => a.GetType() == typeof(UrlEncodedAttribute)) ?? true) + { + return null; + } + + return new BinderTypeModelBinder(typeof(UrlEncodingModelBinder)); + } +} + +/// +/// Indicates that the decorated parameter is a URL encoded string. +/// +[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] +public class UrlEncodedAttribute : Attribute +{ +} \ No newline at end of file -- cgit v1.2.3 From 41bf492f6e1c699abfc53e40a43ec011b16b6f61 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Jan 2026 17:38:38 -0600 Subject: add type converter for serialization --- src/slskd/Common/CommonExtensions.cs | 1 + src/slskd/Common/JsonConverters/TypeConverter.cs | 38 ++++++++++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 src/slskd/Common/JsonConverters/TypeConverter.cs (limited to 'src') diff --git a/src/slskd/Common/CommonExtensions.cs b/src/slskd/Common/CommonExtensions.cs index ec76b745..815c0eb4 100644 --- a/src/slskd/Common/CommonExtensions.cs +++ b/src/slskd/Common/CommonExtensions.cs @@ -490,6 +490,7 @@ namespace slskd var options = new JsonSerializerOptions(); options.Converters.Add(new IPAddressConverter()); options.Converters.Add(new JsonStringEnumConverter()); + options.Converters.Add(new TypeConverter()); options.PropertyNamingPolicy = JsonNamingPolicy.CamelCase; options.DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull; return options; diff --git a/src/slskd/Common/JsonConverters/TypeConverter.cs b/src/slskd/Common/JsonConverters/TypeConverter.cs new file mode 100644 index 00000000..cb946667 --- /dev/null +++ b/src/slskd/Common/JsonConverters/TypeConverter.cs @@ -0,0 +1,38 @@ +// +// Copyright (c) slskd Team. All rights reserved. +// +// 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, either version 3 of the License, or +// (at your option) any later version. +// +// 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/. +// + +namespace slskd; + +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +public class TypeConverter : JsonConverter +{ + public override bool CanConvert(Type typeToConvert) => typeToConvert == typeof(Type); + + public override Type Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) + { + var typeName = reader.GetString(); + return typeName is null ? null : Type.GetType(typeName); + } + + public override void Write(Utf8JsonWriter writer, Type value, JsonSerializerOptions options) + { + writer.WriteStringValue(value.AssemblyQualifiedName); + } +} \ No newline at end of file -- cgit v1.2.3 From 08d7dfcc81026a0e1f99a2af6b079fc1dbaae99c Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Jan 2026 17:38:47 -0600 Subject: add provider --- src/slskd/Program.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'src') diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 2d35f2a5..b9ca4d36 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -849,7 +849,7 @@ namespace slskd services.AddRouting(options => options.LowercaseUrls = true); services.AddControllers(options => { - options.ModelBinderProviders.Insert(0, new FromRouteUnsafeModelBinder()); + options.ModelBinderProviders.Insert(0, new UrlEncodingModelBinderProvider()); }) .ConfigureApiBehaviorOptions(options => { -- cgit v1.2.3 From 7a49f4d20c3cacf417e30ec367641baf7e1e9c21 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Jan 2026 17:39:00 -0600 Subject: add attributes to conversations controller --- .../Messaging/API/Controllers/ConversationsController.cs | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) (limited to 'src') diff --git a/src/slskd/Messaging/API/Controllers/ConversationsController.cs b/src/slskd/Messaging/API/Controllers/ConversationsController.cs index c8a57bd4..6c647272 100644 --- a/src/slskd/Messaging/API/Controllers/ConversationsController.cs +++ b/src/slskd/Messaging/API/Controllers/ConversationsController.cs @@ -70,7 +70,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(404)] - public async Task Acknowledge([FromRoute] string username, [FromRoute] int id) + public async Task Acknowledge([FromRoute, UrlEncoded] string username, [FromRoute] int id) { if (Program.IsRelayAgent) { @@ -100,7 +100,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] [ProducesResponseType(404)] - public async Task AcknowledgeAll([FromRoute] string username) + public async Task AcknowledgeAll([FromRoute, UrlEncoded] string username) { if (Program.IsRelayAgent) { @@ -129,7 +129,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(404)] [ProducesResponseType(204)] - public async Task Close([FromRoute] string username) + public async Task Close([FromRoute, UrlEncoded] string username) { if (Program.IsRelayAgent) { @@ -185,7 +185,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Conversation), 200)] [ProducesResponseType(404)] - public async Task GetByUsername([FromRoute] string username, [FromQuery] bool includeMessages = true) + public async Task GetByUsername([FromRoute, UrlEncoded] string username, [FromQuery] bool includeMessages = true) { if (Program.IsRelayAgent) { @@ -206,7 +206,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(List), 200)] [ProducesResponseType(404)] - public async Task GetMessagesByUsername([FromRoute] string username, [FromQuery] bool unAcknowledgedOnly = false) + public async Task GetMessagesByUsername([FromRoute, UrlEncoded] string username, [FromQuery] bool unAcknowledgedOnly = false) { if (Program.IsRelayAgent) { @@ -242,7 +242,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(201)] [ProducesResponseType(400)] - public async Task Send([FromRoute] string username, [FromBody] string message) + public async Task Send([FromRoute, UrlEncoded] string username, [FromBody] string message) { if (Program.IsRelayAgent) { -- cgit v1.2.3 From c0aa546d0ba0fd427c587d8cf695280c20109b17 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sat, 10 Jan 2026 17:40:51 -0600 Subject: fix rooms --- src/slskd/Messaging/API/Controllers/RoomsController.cs | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) (limited to 'src') diff --git a/src/slskd/Messaging/API/Controllers/RoomsController.cs b/src/slskd/Messaging/API/Controllers/RoomsController.cs index 2ba62a10..64c8b938 100644 --- a/src/slskd/Messaging/API/Controllers/RoomsController.cs +++ b/src/slskd/Messaging/API/Controllers/RoomsController.cs @@ -88,7 +88,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Room), 200)] [ProducesResponseType(404)] - public IActionResult GetByRoomName([FromRoute] string roomName) + public IActionResult GetByRoomName([FromRoute, UrlEncoded] string roomName) { if (Program.IsRelayAgent) { @@ -115,7 +115,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(201)] [ProducesResponseType(404)] - public async Task SendMessage([FromRoute] string roomName, [FromBody] string message) + public async Task SendMessage([FromRoute, UrlEncoded] string roomName, [FromBody] string message) { if (Program.IsRelayAgent) { @@ -143,7 +143,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(201)] [ProducesResponseType(404)] - public async Task SetTicker([FromRoute] string roomName, [FromBody] string message) + public async Task SetTicker([FromRoute, UrlEncoded] string roomName, [FromBody] string message) { if (Program.IsRelayAgent) { @@ -171,7 +171,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(201)] [ProducesResponseType(404)] - public async Task AddRoomMember([FromRoute] string roomName, [FromBody] string username) + public async Task AddRoomMember([FromRoute, UrlEncoded] string roomName, [FromBody] string username) { if (Program.IsRelayAgent) { @@ -198,7 +198,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IList), 200)] [ProducesResponseType(404)] - public IActionResult GetUsersByRoomName([FromRoute] string roomName) + public IActionResult GetUsersByRoomName([FromRoute, UrlEncoded] string roomName) { if (Program.IsRelayAgent) { @@ -227,7 +227,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IList), 200)] [ProducesResponseType(404)] - public IActionResult GetMessagesByRoomName([FromRoute] string roomName) + public IActionResult GetMessagesByRoomName([FromRoute, UrlEncoded] string roomName) { if (Program.IsRelayAgent) { @@ -327,7 +327,7 @@ namespace slskd.Messaging.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(204)] [ProducesResponseType(404)] - public async Task LeaveRoom([FromRoute] string roomName) + public async Task LeaveRoom([FromRoute, UrlEncoded] string roomName) { if (Program.IsRelayAgent) { -- cgit v1.2.3 From 8849d78cbe7057dacad9c00c471691af8e367cd9 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Jan 2026 15:46:51 -0600 Subject: mark additional endpoints --- src/slskd/Telemetry/API/ReportsController.cs | 2 +- .../Transfers/API/Controllers/TransfersController.cs | 16 ++++++++-------- src/slskd/Users/API/Controllers/UsersController.cs | 12 ++++++------ 3 files changed, 15 insertions(+), 15 deletions(-) (limited to 'src') diff --git a/src/slskd/Telemetry/API/ReportsController.cs b/src/slskd/Telemetry/API/ReportsController.cs index da088800..677a93ed 100644 --- a/src/slskd/Telemetry/API/ReportsController.cs +++ b/src/slskd/Telemetry/API/ReportsController.cs @@ -285,7 +285,7 @@ public class ReportsController : ControllerBase [ProducesResponseType(typeof(string), 400)] [ProducesResponseType(typeof(string), 500)] public IActionResult GetUserDetails( - [FromRoute] string username, + [FromRoute, UrlEncoded] string username, [FromQuery] DateTime? start = null, [FromQuery] DateTime? end = null) { diff --git a/src/slskd/Transfers/API/Controllers/TransfersController.cs b/src/slskd/Transfers/API/Controllers/TransfersController.cs index 6be11b2d..068d1174 100644 --- a/src/slskd/Transfers/API/Controllers/TransfersController.cs +++ b/src/slskd/Transfers/API/Controllers/TransfersController.cs @@ -71,7 +71,7 @@ namespace slskd.Transfers.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(204)] [ProducesResponseType(404)] - public IActionResult CancelDownloadAsync([FromRoute, Required] string username, [FromRoute, Required] string id, [FromQuery] bool remove = false) + public IActionResult CancelDownloadAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id, [FromQuery] bool remove = false) { if (Program.IsRelayAgent) { @@ -138,7 +138,7 @@ namespace slskd.Transfers.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(204)] [ProducesResponseType(404)] - public IActionResult CancelUpload([FromRoute, Required] string username, [FromRoute, Required] string id, [FromQuery] bool remove = false) + public IActionResult CancelUpload([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id, [FromQuery] bool remove = false) { if (Program.IsRelayAgent) { @@ -210,7 +210,7 @@ namespace slskd.Transfers.API [ProducesResponseType(typeof(string), 500)] #pragma warning disable CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) #pragma warning disable SA1611 // Element parameters should be documented - public async Task EnqueueAsync([FromRoute, Required] string username, [FromBody] IEnumerable requests, CancellationToken cancellationToken = default) + public async Task EnqueueAsync([FromRoute, UrlEncoded, Required] string username, [FromBody] IEnumerable requests, CancellationToken cancellationToken = default) #pragma warning restore SA1611 // Element parameters should be documented #pragma warning restore CS1573 // Parameter has no matching param tag in the XML comment (but other parameters do) { @@ -281,7 +281,7 @@ namespace slskd.Transfers.API [HttpGet("downloads/{username}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] - public IActionResult GetDownloadsAsync([FromRoute, Required] string username) + public IActionResult GetDownloadsAsync([FromRoute, UrlEncoded, Required] string username) { if (Program.IsRelayAgent) { @@ -313,7 +313,7 @@ namespace slskd.Transfers.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(API.Transfer), 200)] [ProducesResponseType(404)] - public IActionResult GetDownload([FromRoute, Required] string username, [FromRoute, Required] string id) + public IActionResult GetDownload([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) { if (Program.IsRelayAgent) { @@ -348,7 +348,7 @@ namespace slskd.Transfers.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(API.Transfer), 200)] [ProducesResponseType(404)] - public async Task GetPlaceInQueueAsync([FromRoute, Required] string username, [FromRoute, Required] string id) + public async Task GetPlaceInQueueAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) { if (Program.IsRelayAgent) { @@ -417,7 +417,7 @@ namespace slskd.Transfers.API [HttpGet("uploads/{username}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required] string username) + public IActionResult GetUploads([FromRoute, UrlEncoded, Required] string username) { if (Program.IsRelayAgent) { @@ -455,7 +455,7 @@ namespace slskd.Transfers.API [HttpGet("uploads/{username}/{id}")] [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(200)] - public IActionResult GetUploads([FromRoute, Required] string username, [FromRoute, Required] string id) + public IActionResult GetUploads([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) { if (Program.IsRelayAgent) { diff --git a/src/slskd/Users/API/Controllers/UsersController.cs b/src/slskd/Users/API/Controllers/UsersController.cs index 821baa9b..f83dd840 100644 --- a/src/slskd/Users/API/Controllers/UsersController.cs +++ b/src/slskd/Users/API/Controllers/UsersController.cs @@ -71,7 +71,7 @@ namespace slskd.Users.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IPEndPoint), 200)] [ProducesResponseType(404)] - public async Task Endpoint([FromRoute, Required] string username) + public async Task Endpoint([FromRoute, UrlEncoded, Required] string username) { if (Program.IsRelayAgent) { @@ -98,7 +98,7 @@ namespace slskd.Users.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IEnumerable), 200)] [ProducesResponseType(404)] - public async Task Browse([FromRoute, Required] string username) + public async Task Browse([FromRoute, UrlEncoded, Required] string username) { if (Program.IsRelayAgent) { @@ -132,7 +132,7 @@ namespace slskd.Users.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(decimal), 200)] [ProducesResponseType(404)] - public IActionResult BrowseStatus([FromRoute, Required] string username) + public IActionResult BrowseStatus([FromRoute, UrlEncoded, Required] string username) { if (Program.IsRelayAgent) { @@ -157,7 +157,7 @@ namespace slskd.Users.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IEnumerable), 200)] [ProducesResponseType(404)] - public async Task Directory([FromRoute, Required] string username, [FromBody, Required] DirectoryContentsRequest request) + public async Task Directory([FromRoute, UrlEncoded, Required] string username, [FromBody, Required] DirectoryContentsRequest request) { if (Program.IsRelayAgent) { @@ -192,7 +192,7 @@ namespace slskd.Users.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Info), 200)] [ProducesResponseType(404)] - public async Task Info([FromRoute, Required] string username) + public async Task Info([FromRoute, UrlEncoded, Required] string username) { if (Program.IsRelayAgent) { @@ -219,7 +219,7 @@ namespace slskd.Users.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(Status), 200)] [ProducesResponseType(404)] - public async Task Status([FromRoute, Required] string username) + public async Task Status([FromRoute, UrlEncoded, Required] string username) { if (Program.IsRelayAgent) { -- cgit v1.2.3 From e7e0cdaf762b10027e8417ebc985d621ddb87eca Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Sun, 11 Jan 2026 18:44:04 -0600 Subject: use raw url, before any decoding --- .../Common/Middleware/UrlEncodingModelBinder.cs | 49 ++++++++++++++++------ 1 file changed, 37 insertions(+), 12 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs b/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs index 2c6f341f..9ec52302 100644 --- a/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs +++ b/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs @@ -20,6 +20,7 @@ namespace slskd; using System; using System.Linq; using System.Threading.Tasks; +using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Mvc.ModelBinding; using Microsoft.AspNetCore.Mvc.ModelBinding.Binders; using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; @@ -42,27 +43,51 @@ public class UrlEncodingModelBinder : IModelBinder /// public Task BindModelAsync(ModelBindingContext bindingContext) { + /* + given the information in the provided ModelBindingContext, + + 1. determine which 'model' (named route parameter) we're trying to bind a value for (e.g. 'foo') + 2. from the full route template (e.g. api/v{version:apiVersion}/foo/{bar}), determine the index of + the model we are looking for in the template, segmented by forward slashes (e.g. 3rd in example above) + 3. from the raw, unmanipulated request URL, extract the Nth forward-slash-separated value; this will be our + url encoded value as provided by the client + 4. decode this value and assign it to ModelBindingContext.Result + + + template: api/v{version:apiVersion}/foo/{bar} + model: bar + index: 3 + raw url: api/v0/foo/hello%20world + raw value: 'hello%20world' (3rd index in split string) + result: 'hello world' + */ try { - // get the raw value that was passed, if any - var potentiallyUrlEncodedResult = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); + var model = $"{{{bindingContext.ModelName}}}"; + var template = bindingContext.ActionContext.ActionDescriptor.AttributeRouteInfo?.Template ?? string.Empty; + var index = template + .Split('/', StringSplitOptions.RemoveEmptyEntries) + .Select((segment, index) => new { Segment = segment, Index = index }) + .Single(x => x.Segment.Equals(model, StringComparison.OrdinalIgnoreCase)).Index; - if (potentiallyUrlEncodedResult == ValueProviderResult.None) - { - return Task.CompletedTask; - } + // get the raw URL, *before* any sort of processing or default url-decoding is applied + // this is necessary to avoid double-decoding issues; using HttpContext.Request.Path gives us + // a value that's already had one pass of url decoding applied + var rawUrl = bindingContext.HttpContext.Features.Get()?.RawTarget ?? string.Empty; - var value = potentiallyUrlEncodedResult.FirstValue; + var request = bindingContext.HttpContext.Request; + var rawValue = new Uri($"{request.Scheme}://{request.Host}{rawUrl}").AbsolutePath // discard query string + .Split('/', StringSplitOptions.RemoveEmptyEntries) + .ElementAtOrDefault(index); - if (string.IsNullOrEmpty(value)) + if (rawValue is null) { + bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, "Could not extract URL encoded value from URL"); return Task.CompletedTask; } - // a value was provided; decode it - var decodedValue = Uri.UnescapeDataString(value); - - bindingContext.Result = ModelBindingResult.Success(decodedValue); + var decoded = Uri.UnescapeDataString(rawValue); + bindingContext.Result = ModelBindingResult.Success(decoded); return Task.CompletedTask; } catch (Exception ex) -- cgit v1.2.3 From c313134d97b441d9abaaf363bb83a4ceff66746d Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Mon, 12 Jan 2026 08:57:27 -0600 Subject: docs --- src/slskd/Common/Middleware/UrlEncodingModelBinder.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs b/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs index 9ec52302..9592e75e 100644 --- a/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs +++ b/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs @@ -31,7 +31,7 @@ using Microsoft.AspNetCore.Mvc.ModelBinding.Metadata; /// For this to work as intended, method parameters must: /// /// -/// Use either Path binding (e.g [FromRoute]) +/// Use Path binding (e.g [FromRoute]) /// Have a backing type of string /// Be decorated with the [UrlEncoded] attribute /// @@ -46,7 +46,7 @@ public class UrlEncodingModelBinder : IModelBinder /* given the information in the provided ModelBindingContext, - 1. determine which 'model' (named route parameter) we're trying to bind a value for (e.g. 'foo') + 1. determine which 'model' (named route parameter) we're trying to bind a value for (e.g. 'bar') 2. from the full route template (e.g. api/v{version:apiVersion}/foo/{bar}), determine the index of the model we are looking for in the template, segmented by forward slashes (e.g. 3rd in example above) 3. from the raw, unmanipulated request URL, extract the Nth forward-slash-separated value; this will be our -- cgit v1.2.3