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 --- .../Common/Middleware/UrlEncodingModelBinder.cs | 119 +++++++++++++++++++++ 1 file changed, 119 insertions(+) create mode 100644 src/slskd/Common/Middleware/UrlEncodingModelBinder.cs (limited to 'src/slskd/Common/Middleware/UrlEncodingModelBinder.cs') 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 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/slskd/Common/Middleware/UrlEncodingModelBinder.cs') 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/slskd/Common/Middleware/UrlEncodingModelBinder.cs') 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