diff options
| author | JP Dillingham <jp@dillingham.me> | 2025-12-13 16:59:51 -0600 |
|---|---|---|
| committer | GitHub <noreply@github.com> | 2025-12-13 16:59:51 -0600 |
| commit | 1d27718843b0d62afa8a52847eadcbdbcbf44b98 (patch) | |
| tree | bc6d2bd7fd959d0740a68b5b35a3baf8f1de31c0 /src/slskd/Common | |
| parent | 6dbedb038a152a22dd9ee4b04a41a8b3ffde5d1f (diff) | |
| parent | 54584b8edd08f704427355d59323163086102207 (diff) | |
| download | slskd-1d27718843b0d62afa8a52847eadcbdbcbf44b98.tar.gz | |
Merge branch 'master' into copilot/add-sort-directories-files
Diffstat (limited to 'src/slskd/Common')
3 files changed, 136 insertions, 5 deletions
diff --git a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs index 1aaa4a4f..e2733442 100644 --- a/src/slskd/Common/Authentication/ApiKeyAuthentication.cs +++ b/src/slskd/Common/Authentication/ApiKeyAuthentication.cs @@ -15,6 +15,7 @@ // along with this program. If not, see https://www.gnu.org/licenses/. // </copyright> +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace slskd.Authentication @@ -24,7 +25,7 @@ namespace slskd.Authentication using System.Text.Encodings.Web; using System.Threading.Tasks; using Microsoft.AspNetCore.Authentication; - using Microsoft.Extensions.Logging; + using Serilog; /// <summary> /// API key authentication. @@ -51,7 +52,7 @@ namespace slskd.Authentication /// <param name="urlEncoder">A url encoder.</param> public ApiKeyAuthenticationHandler( IOptionsMonitor<ApiKeyAuthenticationOptions> apiKeyOptionsMonitor, - ISecurityService securityService, + SecurityService securityService, ILoggerFactory logger, UrlEncoder urlEncoder) : base(apiKeyOptionsMonitor, logger, urlEncoder) @@ -59,7 +60,8 @@ namespace slskd.Authentication Security = securityService; } - private ISecurityService Security { get; } + private ILogger Log { get; } = Serilog.Log.ForContext<ApiKeyAuthenticationHandler>(); + private SecurityService Security { get; } /// <summary> /// Authenticates via API key. @@ -86,6 +88,7 @@ namespace slskd.Authentication } catch (Exception ex) { + Log.Warning("Unauthorized request from IP address {IP}: {Message}", Request.HttpContext.Connection.RemoteIpAddress, ex.Message); return AuthenticateResult.Fail(ex); } } diff --git a/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs new file mode 100644 index 00000000..db5c4baa --- /dev/null +++ b/src/slskd/Common/OpenAPI/ContentNegotiationOperationFilter.cs @@ -0,0 +1,100 @@ +// <copyright file="ContentNegotiationOperationFilter.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.Linq; +using System.Reflection; +using Microsoft.AspNetCore.Mvc; +using Microsoft.AspNetCore.Mvc.Formatters; +using Microsoft.OpenApi.Models; +using Swashbuckle.AspNetCore.SwaggerGen; + +/// <summary> +/// OpenAPI operation filter that properly handles content negotiation with different response schemas. +/// </summary> +public class ContentNegotiationOperationFilter : IOperationFilter +{ + public void Apply(OpenApiOperation operation, OperationFilterContext context) + { + // check to see if the current operation is decorated with [Produces], which is what enables content negotiation + var producesAttribute = context.MethodInfo + .GetCustomAttributes(typeof(ProducesAttribute), false) + .Cast<ProducesAttribute>() + .FirstOrDefault(); + + if (producesAttribute == null || producesAttribute.ContentTypes.Count == 0) + { + return; + } + + // next, get all of the [ProducesResponseType] attributes, if any + var producesResponseTypeAttributes = context.MethodInfo + .GetCustomAttributes(typeof(ProducesResponseTypeAttribute), false) + .Cast<ProducesResponseTypeAttribute>() + .ToList(); + + if (producesResponseTypeAttributes.Count == 0) + { + return; + } + + // map over the list of status codes; we need to (attempt to) perform this mapping for each status code and each + // content type listed in [Produces] + foreach (var statusCodeGroup in producesResponseTypeAttributes.GroupBy(x => x.StatusCode)) + { + foreach (var contentType in producesAttribute.ContentTypes) + { + // find the first [ProducesResponseType] that contains this content type in its list of content types + var attribute = statusCodeGroup.FirstOrDefault(x => GetContentTypes(x).Contains(contentType)); + + if (attribute is not null) + { + var response = operation.Responses[statusCodeGroup.Key.ToString()]; + response.Content[contentType] = new OpenApiMediaType + { + Schema = context.SchemaGenerator.GenerateSchema(attribute.Type, context.SchemaRepository), + }; + } + } + } + } + + /// <summary> + /// Extracts the value of the _contentTypes field of <see cref="ProducesResponseTypeAttribute"/>. + /// + /// This is necessary because Microsoft didn't see fit to bless us with the ability to retrieve the content types + /// we specifify along with our [ProducesResponseType] attributes. + /// + /// It will most likely break at some point. + /// </summary> + /// <param name="attribute">The attribute from which to extract the _contentTypes field.</param> + /// <returns>The value of the extracted field.</returns> + private MediaTypeCollection GetContentTypes(ProducesResponseTypeAttribute attribute) + { + var contentTypesField = typeof(ProducesResponseTypeAttribute).GetField("_contentTypes", BindingFlags.NonPublic | BindingFlags.Instance); + + MediaTypeCollection value = (MediaTypeCollection)contentTypesField.GetValue(attribute); + + if (value is null) + { + return []; + } + + return value; + } +} diff --git a/src/slskd/Common/Validation/IPAddressAttribute.cs b/src/slskd/Common/Validation/IPAddressAttribute.cs index 6e53df57..b9075808 100644 --- a/src/slskd/Common/Validation/IPAddressAttribute.cs +++ b/src/slskd/Common/Validation/IPAddressAttribute.cs @@ -18,6 +18,7 @@ namespace slskd.Validation { using System.ComponentModel.DataAnnotations; + using System.Linq; using System.Net; /// <summary> @@ -25,6 +26,13 @@ namespace slskd.Validation /// </summary> public class IPAddressAttribute : ValidationAttribute { + public IPAddressAttribute(bool allowCommaSeparatedValues = false) + { + AllowCommaSeparatedValues = allowCommaSeparatedValues; + } + + private bool AllowCommaSeparatedValues { get; set; } + protected override ValidationResult IsValid(object value, ValidationContext validationContext) { if (value != null) @@ -36,9 +44,29 @@ namespace slskd.Validation return fail; } - if (!IPAddress.TryParse(valueAsString, out _)) + if (!valueAsString.Contains(',')) { - return fail; + if (!IPAddress.TryParse(valueAsString, out _)) + { + return fail; + } + } + else + { + if (!AllowCommaSeparatedValues) + { + return new ValidationResult($"The {validationContext.DisplayName} field accepts a single value only (a comma separated list was specified)"); + } + + var values = valueAsString.Split(',').Select(v => v.Trim()); + + foreach (var currentValue in values) + { + if (!IPAddress.TryParse(currentValue, out _)) + { + return new ValidationResult($"The {validationContext.DisplayName} field contains one or more invalid IPv4 or IPv6 IP addresses."); + } + } } } |
