diff options
| author | JP Dillingham <jp@dillingham.me> | 2026-01-12 09:40:48 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2026-01-12 09:40:48 -0600 |
| commit | f663c8a6bd3ac23676701f67a81286f83dac5b32 (patch) | |
| tree | 1927b1643b2a41946e4eac78519a495b8dc75357 /src | |
| parent | e3ee2eca180ec02b15001682bfed0a8f24d51d21 (diff) | |
| parent | c9d34650e95ae8e7bfa737dc65dfaf505c6b1551 (diff) | |
| download | slskd-f663c8a6bd3ac23676701f67a81286f83dac5b32.tar.gz | |
Merge branch 'master' into docs
Diffstat (limited to 'src')
| -rw-r--r-- | src/slskd/Common/CommonExtensions.cs | 1 | ||||
| -rw-r--r-- | src/slskd/Common/JsonConverters/TypeConverter.cs | 38 | ||||
| -rw-r--r-- | src/slskd/Common/Middleware/UrlEncodingModelBinder.cs | 144 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/Controllers/ConversationsController.cs | 12 | ||||
| -rw-r--r-- | src/slskd/Messaging/API/Controllers/RoomsController.cs | 14 | ||||
| -rw-r--r-- | src/slskd/Program.cs | 5 | ||||
| -rw-r--r-- | src/slskd/Telemetry/API/ReportsController.cs | 2 | ||||
| -rw-r--r-- | src/slskd/Transfers/API/Controllers/TransfersController.cs | 16 | ||||
| -rw-r--r-- | src/slskd/Users/API/Controllers/UsersController.cs | 12 |
9 files changed, 215 insertions, 29 deletions
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 file="TypeConverter.cs" company="slskd Team"> +// 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/. +// </copyright> + +namespace slskd; + +using System; +using System.Text.Json; +using System.Text.Json.Serialization; + +public class TypeConverter : JsonConverter<Type> +{ + 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 diff --git a/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs b/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs new file mode 100644 index 00000000..9592e75e --- /dev/null +++ b/src/slskd/Common/Middleware/UrlEncodingModelBinder.cs @@ -0,0 +1,144 @@ +// <copyright file="UrlEncodingModelBinder.cs" company="slskd Team"> +// 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/. +// </copyright> + +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; + +/// <summary> +/// Model binder for URL encoded strings. +/// +/// For this to work as intended, method parameters must: +/// +/// <list> +/// <item>Use Path binding (e.g [FromRoute])</item> +/// <item>Have a backing type of string</item> +/// <item>Be decorated with the [UrlEncoded] attribute</item> +/// </list> +/// +/// Most of this assumes the model binder is configured with <see cref="UrlEncodingModelBinderProvider"/>. +/// </summary> +public class UrlEncodingModelBinder : IModelBinder +{ + /// <inheritdoc/> + 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. '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 + 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 + { + 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; + + // 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<IHttpRequestFeature>()?.RawTarget ?? string.Empty; + + var request = bindingContext.HttpContext.Request; + var rawValue = new Uri($"{request.Scheme}://{request.Host}{rawUrl}").AbsolutePath // discard query string + .Split('/', StringSplitOptions.RemoveEmptyEntries) + .ElementAtOrDefault(index); + + if (rawValue is null) + { + bindingContext.ModelState.TryAddModelError(bindingContext.ModelName, "Could not extract URL encoded value from URL"); + return Task.CompletedTask; + } + + var decoded = Uri.UnescapeDataString(rawValue); + bindingContext.Result = ModelBindingResult.Success(decoded); + return Task.CompletedTask; + } + catch (Exception ex) + { + Console.Error.WriteLine(ex); + throw; + } + } +} + +/// <summary> +/// Model binding provider for URL encoded string binding via <see cref="UrlEncodingModelBinder"/>. +/// </summary> +public class UrlEncodingModelBinderProvider : IModelBinderProvider +{ + /// <summary> + /// Only use this binder if ALL of the following are true: + /// + /// <list> + /// <item>The binding source is Path (instead of Query, Form, Body, etc)</item> + /// <item>The target type is string</item> + /// <item>The target parameter has the [UrlEncoded] attribute</item> + /// </list> + /// </summary> + /// <param name="context">The model binder context.</param> + /// <returns>An instance of <see cref="UrlEncodingModelBinder"/>, or null if the conditions haven't been met.</returns> + 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)); + } +} + +/// <summary> +/// Indicates that the decorated parameter is a URL encoded string. +/// </summary> +[AttributeUsage(AttributeTargets.Parameter, AllowMultiple = false)] +public class UrlEncodedAttribute : Attribute +{ +}
\ No newline at end of file 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<IActionResult> Acknowledge([FromRoute] string username, [FromRoute] int id) + public async Task<IActionResult> 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<IActionResult> AcknowledgeAll([FromRoute] string username) + public async Task<IActionResult> 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<IActionResult> Close([FromRoute] string username) + public async Task<IActionResult> 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<IActionResult> GetByUsername([FromRoute] string username, [FromQuery] bool includeMessages = true) + public async Task<IActionResult> 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<PrivateMessage>), 200)] [ProducesResponseType(404)] - public async Task<IActionResult> GetMessagesByUsername([FromRoute] string username, [FromQuery] bool unAcknowledgedOnly = false) + public async Task<IActionResult> 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<IActionResult> Send([FromRoute] string username, [FromBody] string message) + public async Task<IActionResult> Send([FromRoute, UrlEncoded] string username, [FromBody] string message) { if (Program.IsRelayAgent) { 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<IActionResult> SendMessage([FromRoute] string roomName, [FromBody] string message) + public async Task<IActionResult> 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<IActionResult> SetTicker([FromRoute] string roomName, [FromBody] string message) + public async Task<IActionResult> 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<IActionResult> AddRoomMember([FromRoute] string roomName, [FromBody] string username) + public async Task<IActionResult> 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<UserData>), 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<RoomMessage>), 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<IActionResult> LeaveRoom([FromRoute] string roomName) + public async Task<IActionResult> LeaveRoom([FromRoute, UrlEncoded] string roomName) { if (Program.IsRelayAgent) { diff --git a/src/slskd/Program.cs b/src/slskd/Program.cs index 2b2d2840..d6873dc0 100644 --- a/src/slskd/Program.cs +++ b/src/slskd/Program.cs @@ -919,7 +919,10 @@ namespace slskd } services.AddRouting(options => options.LowercaseUrls = true); - services.AddControllers() + services.AddControllers(options => + { + options.ModelBinderProviders.Insert(0, new UrlEncodingModelBinderProvider()); + }) .ConfigureApiBehaviorOptions(options => { options.SuppressInferBindingSourcesForParameters = true; // explicit [FromRoute], etc 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 5d2fc274..443a1b44 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) { @@ -140,7 +140,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) { @@ -212,7 +212,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<IActionResult> EnqueueAsync([FromRoute, Required] string username, [FromBody] IEnumerable<QueueDownloadRequest> requests, CancellationToken cancellationToken = default) + public async Task<IActionResult> EnqueueAsync([FromRoute, UrlEncoded, Required] string username, [FromBody] IEnumerable<QueueDownloadRequest> 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) { @@ -283,7 +283,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) { @@ -315,7 +315,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) { @@ -350,7 +350,7 @@ namespace slskd.Transfers.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(API.Transfer), 200)] [ProducesResponseType(404)] - public async Task<IActionResult> GetPlaceInQueueAsync([FromRoute, Required] string username, [FromRoute, Required] string id) + public async Task<IActionResult> GetPlaceInQueueAsync([FromRoute, UrlEncoded, Required] string username, [FromRoute, Required] string id) { if (Program.IsRelayAgent) { @@ -419,7 +419,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) { @@ -457,7 +457,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<IActionResult> Endpoint([FromRoute, Required] string username) + public async Task<IActionResult> Endpoint([FromRoute, UrlEncoded, Required] string username) { if (Program.IsRelayAgent) { @@ -98,7 +98,7 @@ namespace slskd.Users.API [Authorize(Policy = AuthPolicy.Any)] [ProducesResponseType(typeof(IEnumerable<Directory>), 200)] [ProducesResponseType(404)] - public async Task<IActionResult> Browse([FromRoute, Required] string username) + public async Task<IActionResult> 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<Directory>), 200)] [ProducesResponseType(404)] - public async Task<IActionResult> Directory([FromRoute, Required] string username, [FromBody, Required] DirectoryContentsRequest request) + public async Task<IActionResult> 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<IActionResult> Info([FromRoute, Required] string username) + public async Task<IActionResult> 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<IActionResult> Status([FromRoute, Required] string username) + public async Task<IActionResult> Status([FromRoute, UrlEncoded, Required] string username) { if (Program.IsRelayAgent) { |
