Hardens outbound host validation against SSRF

- resolves host names and validates every address, with a connect callback that pins the checked address

- applies the guard to every outbound HTTP client, with distinct rejection and resolution failures and warning logs

- scopes the MusicBrainz private base URL permission to the configured host and blocks link local and cloud metadata endpoints

- keeps provider redirects bounded and strips credentials and hop-by-hop headers on cross-origin redirects

- adds unit, security, and end-to-end coverage, and updates the manual
This commit is contained in:
BinaryAlley committed 2026-11-18 10:51:41 +02:00
1 parent ecdb39cc6a
commit 24af00579c
28 files changed
+2977 -162

No files matched your search

@@ -2,13 +2,14 @@
using Lumina.Plugins.Contracts.Core.Metadata;
using Lumina.Plugins.MusicBrainz.Common.DependencyInjection;
using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings;
using Lumina.Plugins.MusicBrainz.Core;
using Lumina.Plugins.MusicBrainz.Core.Api;
using Lumina.Plugins.MusicBrainz.Core.Settings;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net.Http;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
#endregion
@@ -127,6 +128,26 @@ public class MusicBrainzServicesTests
}
}
[Fact]
public void AddMusicBrainzMetadataProviders_WhenTheHostConfiguresHttpClientDefaults_ShouldKeepThePrimaryHandlerOfTheHost()
{
// Arrange
ServiceCollection services = new();
StubPrimaryHttpMessageHandler hostPrimaryHandler = new();
services.ConfigureHttpClientDefaults(builder => builder.ConfigurePrimaryHttpMessageHandler(() => hostPrimaryHandler));
services.AddMusicBrainzMetadataProviders(pluginId: Guid.NewGuid());
ServiceProvider serviceProvider = services.BuildServiceProvider();
using (IServiceScope scope = serviceProvider.CreateScope())
{
// Act
MusicBrainzHttpClient client = scope.ServiceProvider.GetRequiredService<MusicBrainzHttpClient>();
// Assert
// The host owns the primary handler, because it is what validates and pins the address of every connection. The plugin must not replace it.
Assert.Same(hostPrimaryHandler, GetPrimaryHandler(client));
}
}
[Fact]
public void AddMusicBrainzMetadataProviders_WhenCalledTwice_ShouldNotDuplicateTheTryAddServices()
{
@@ -144,4 +165,60 @@ public class MusicBrainzServicesTests
Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzResponseCache));
Assert.Single(services, descriptor => descriptor.ServiceType == typeof(MusicBrainzSettingsProvider));
}
/// <summary>
/// Gets the primary HTTP message handler of the provided client, unwrapping the delegating handlers built by the HTTP client factory around it.
/// </summary>
/// <param name="client">The client whose primary handler is retrieved.</param>
/// <returns>The primary HTTP message handler of the client.</returns>
private static HttpMessageHandler GetPrimaryHandler(MusicBrainzHttpClient client)
{
HttpClient httpClient = (HttpClient)GetFieldOfType(client, typeof(HttpClient))!;
HttpMessageHandler? handler = (HttpMessageHandler?)GetFieldOfType(httpClient, typeof(HttpMessageHandler));
while (handler is DelegatingHandler delegatingHandler)
handler = delegatingHandler.InnerHandler;
return handler ?? throw new InvalidOperationException("The HTTP client has no primary handler.");
}
/// <summary>
/// Gets the value of the first field, declared on the provided <paramref name="instance"/> or any of its base types, whose type is assignable to
/// <paramref name="fieldType"/>, without relying on the field name, so the test keeps working across runtime versions.
/// </summary>
/// <param name="instance">The instance whose field is read.</param>
/// <param name="fieldType">The type the field must be assignable to.</param>
/// <returns>The value of the found field.</returns>
/// <exception cref="InvalidOperationException">Thrown when no field assignable to <paramref name="fieldType"/> is found.</exception>
private static object GetFieldOfType(object instance, Type fieldType)
{
Type? type = instance.GetType();
while (type is not null)
{
FieldInfo? field = type
.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly)
.FirstOrDefault(candidate => fieldType.IsAssignableFrom(candidate.FieldType));
if (field is not null)
return field.GetValue(instance)!;
type = type.BaseType;
}
throw new InvalidOperationException($"No field assignable to {fieldType} was found on {instance.GetType()} or its base types.");
}
/// <summary>
/// Primary HTTP message handler that identifies the handler the host configured, so a test can verify that the plugin does not replace it.
/// </summary>
[ExcludeFromCodeCoverage]
private sealed class StubPrimaryHttpMessageHandler : HttpMessageHandler
{
/// <summary>
/// Sends the provided request. The tests never send a request through this handler.
/// </summary>
/// <param name="request">The request to send.</param>
/// <param name="cancellationToken">Cancellation token that can be used to stop the execution.</param>
/// <returns>The response of the request.</returns>
/// <exception cref="NotSupportedException">Always thrown, because this handler only identifies the handler configured by the host.</exception>
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
throw new NotSupportedException();
}
}
}
@@ -1,4 +1,5 @@
#region ========================================================================= USING =====================================================================================
using Lumina.Plugins.Contracts.Common.Http;
using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses;
using Lumina.Plugins.MusicBrainz.Core;
using Lumina.Plugins.MusicBrainz.Core.Api;
@@ -181,6 +182,115 @@ public class MusicBrainzHttpClientTests
Assert.Equal(2, handler.CallCount);
}
[Fact]
public async Task GetRecordingAsync_WhenTheServiceRedirectsToTheSameHost_ShouldFollowIt()
{
// Arrange
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero,
(request, callIndex) => callIndex == 1 ? Redirect("http://localhost/ws/2/redirected") : Json(RECORDING_JSON));
// Act
MusicBrainzRecordingResponse? result = await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.NotNull(result);
Assert.Equal(2, handler.CallCount);
Assert.True(handler.Requests[1].Options.TryGetValue(OutboundRequestOptions.FollowRedirects, out bool shouldFollowRedirects));
Assert.False(shouldFollowRedirects);
}
[Fact]
public async Task GetRecordingAsync_WhenTheServiceRedirectsToAnotherHost_ShouldThrowWithoutFollowingIt()
{
// Arrange
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero,
(request, callIndex) => Redirect("http://other.example/ws/2/redirected"));
// Act
Task Act()
{
return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<HttpRequestException>(Act);
Assert.Equal(1, handler.CallCount);
}
[Fact]
public async Task GetRecordingAsync_WhenTheServiceDowngradesHttpsToPlainHttp_ShouldThrowWithoutFollowingIt()
{
// Arrange
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("https://musicbrainz.org/ws/2/", TimeSpan.Zero,
(request, callIndex) => Redirect("http://musicbrainz.org/ws/2/redirected"));
// Act
Task Act()
{
return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<HttpRequestException>(Act);
Assert.Equal(1, handler.CallCount);
}
[Fact]
public async Task GetRecordingAsync_WhenTheServiceRedirectsTooManyTimes_ShouldThrow()
{
// Arrange
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero,
(request, callIndex) => Redirect("http://localhost/ws/2/loop"));
// Act
Task Act()
{
return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<HttpRequestException>(Act);
// The initial request plus the maximum number of followed redirects are sent before the loop is detected.
Assert.Equal(6, handler.CallCount);
}
[Fact]
public async Task GetRecordingAsync_WhenTheHostRejectsTheRequest_ShouldNotRetry()
{
// Arrange
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero,
(request, callIndex) => throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, "Rejected."));
// Act
Task Act()
{
return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<HttpRequestException>(Act);
Assert.Equal(1, handler.CallCount);
}
[Fact]
public async Task GetRecordingAsync_WhenTheConnectPolicyWrapsTheRejection_ShouldNotRetry()
{
// Arrange
HttpRequestException rejection = new(HttpRequestError.ConfigurationLimitExceeded, "Rejected.");
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero,
(request, callIndex) => throw new HttpRequestException(HttpRequestError.ConnectionError, "Connection error.", rejection));
// Act
Task Act()
{
return client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
}
// Assert
await Assert.ThrowsAsync<HttpRequestException>(Act);
Assert.Equal(1, handler.CallCount);
}
[Fact]
public async Task GetRecordingAsync_WhenEveryAttemptFails_ShouldThrowAfterExhaustingTheRetries()
{
@@ -243,6 +353,33 @@ public class MusicBrainzHttpClientTests
Assert.Equal("Custom/9.9", handler.Requests[0].Headers.UserAgent.ToString());
}
[Fact]
public async Task GetRecordingAsync_WhenAPrivateBaseUrlIsAllowed_ShouldScopeThePermissionToTheBaseHost()
{
// Arrange
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, doesAllowPrivateBaseUrl: true);
// Act
await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.True(handler.Requests[0].Options.TryGetValue(OutboundRequestOptions.AllowedPrivateHost, out string? allowedPrivateHost));
Assert.Equal("localhost", allowedPrivateHost);
}
[Fact]
public async Task GetRecordingAsync_WhenAPrivateBaseUrlIsNotAllowed_ShouldNotAllowTheRequestToReachPrivateEndPoints()
{
// Arrange
(MusicBrainzHttpClient client, StubHttpMessageHandler handler, _) = CreateClient("http://localhost/", TimeSpan.Zero, doesAllowPrivateBaseUrl: false);
// Act
await client.GetRecordingAsync(Guid.NewGuid(), CancellationToken.None);
// Assert
Assert.False(handler.Requests[0].Options.TryGetValue(OutboundRequestOptions.AllowedPrivateHost, out string? _));
}
[Fact]
public async Task GetArtistAsync_WhenTheArtistExists_ShouldDeserializeIt()
{
@@ -532,16 +669,18 @@ public class MusicBrainzHttpClientTests
/// <param name="minimumRequestInterval">The minimum request interval configured for the client.</param>
/// <param name="responseFactory">Optional. The factory that produces the response of a request.</param>
/// <param name="contactEmail">Optional. The contact email configured for the client.</param>
/// <param name="doesAllowPrivateBaseUrl">Optional. Whether the base URL may point at a private or local host.</param>
/// <returns>The created client, its stub handler and the underlying HTTP client.</returns>
private (MusicBrainzHttpClient Client, StubHttpMessageHandler Handler, HttpClient HttpClient) CreateClient(
string baseUrl,
TimeSpan minimumRequestInterval,
Func<HttpRequestMessage, int, HttpResponseMessage>? responseFactory = null,
string? contactEmail = null)
string? contactEmail = null,
bool? doesAllowPrivateBaseUrl = null)
{
StubHttpMessageHandler handler = new(responseFactory ?? ((request, callIndex) => Json(RECORDING_JSON)));
HttpClient httpClient = new(handler);
MusicBrainzHttpClient client = CreateMusicBrainzHttpClient(httpClient, baseUrl, minimumRequestInterval, contactEmail);
MusicBrainzHttpClient client = CreateMusicBrainzHttpClient(httpClient, baseUrl, minimumRequestInterval, contactEmail, doesAllowPrivateBaseUrl);
return (client, handler, httpClient);
}
@@ -552,11 +691,13 @@ public class MusicBrainzHttpClientTests
/// <param name="baseUrl">The base URL of the MusicBrainz web service the client points to.</param>
/// <param name="minimumRequestInterval">The minimum request interval configured for the client.</param>
/// <param name="contactEmail">Optional. The contact email configured for the client.</param>
/// <param name="doesAllowPrivateBaseUrl">Optional. Whether the base URL may point at a private or local host.</param>
/// <returns>The created client.</returns>
private MusicBrainzHttpClient CreateMusicBrainzHttpClient(HttpClient httpClient, string baseUrl, TimeSpan minimumRequestInterval, string? contactEmail)
private MusicBrainzHttpClient CreateMusicBrainzHttpClient(HttpClient httpClient, string baseUrl, TimeSpan minimumRequestInterval, string? contactEmail, bool? doesAllowPrivateBaseUrl = null)
{
MusicBrainzSettingsProvider settingsProvider = new(null, MusicBrainzPlugin.s_pluginId, _musicBrainzSettingsDtoFixture.Create(
baseUrl: baseUrl,
doesAllowPrivateBaseUrl: doesAllowPrivateBaseUrl,
userAgent: "Lumina-Test/1.0",
contactEmail: contactEmail,
includeContactEmail: contactEmail is not null,
@@ -575,4 +716,16 @@ public class MusicBrainzHttpClientTests
{
return new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(json, Encoding.UTF8, "application/json") };
}
/// <summary>
/// Creates a temporary redirect response to the provided location.
/// </summary>
/// <param name="location">The absolute location of the redirect target.</param>
/// <returns>The created response.</returns>
private static HttpResponseMessage Redirect(string location)
{
HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect);
redirect.Headers.Location = new Uri(location);
return redirect;
}
}
@@ -111,13 +111,27 @@ public class MusicBrainzSettingsProviderTests
[Theory]
[InlineData("http://127.0.0.1/ws/2/")] // IPv4 loopback.
[InlineData("http://localhost/ws/2/")] // Loopback host name.
[InlineData("http://localhost./ws/2/")] // Loopback host name with a trailing dot.
[InlineData("http://[::1]/ws/2/")] // IPv6 loopback.
[InlineData("http://169.254.169.254/latest/meta-data/")] // Link local cloud metadata endpoint.
[InlineData("http://10.0.0.5/ws/2/")] // Private class A range.
[InlineData("http://172.16.0.1/ws/2/")] // Private class B range.
[InlineData("http://[::ffff:10.0.0.5]/ws/2/")] // An IPv4-mapped private address.
[InlineData("http://192.168.1.10/ws/2/")] // Private class C range.
[InlineData("http://0.0.0.0/ws/2/")] // Unspecified address.
[InlineData("http://[fc00::1]/ws/2/")] // IPv6 unique local range.
[InlineData("http://[fd00:ec2::254]/ws/2/")] // The AWS IMDSv6 endpoint, which lives in a unique local range.
[InlineData("http://198.18.0.1/ws/2/")] // IPv4 benchmarking range.
[InlineData("http://198.51.100.10/ws/2/")] // TEST-NET-2 documentation range.
[InlineData("http://203.0.113.10/ws/2/")] // TEST-NET-3 documentation range.
[InlineData("http://224.0.0.1/ws/2/")] // IPv4 multicast range.
[InlineData("http://[ff02::1]/ws/2/")] // IPv6 multicast range.
[InlineData("http://[2001:db8::1]/ws/2/")] // IPv6 documentation range.
[InlineData("http://[::127.0.0.1]/ws/2/")] // IPv4 compatible IPv6 address.
[InlineData("http://[64:ff9b:1::1]/ws/2/")] // Local use NAT64 prefix.
[InlineData("http://[2002::1]/ws/2/")] // IPv6 6to4 range.
[InlineData("http://[64:ff9b::1]/ws/2/")] // IPv6 NAT64 prefix.
[InlineData("http://[100::1]/ws/2/")] // IPv6 discard only range.
public async Task GetAsync_WhenThePersistedBaseUrlPointsAtALocalOrPrivateHost_ShouldKeepTheDefaultBaseUrl(string baseUrl)
{
// Arrange
@@ -137,6 +151,7 @@ public class MusicBrainzSettingsProviderTests
[InlineData("http://192.168.1.10/ws/2/")] // Private class C range, a typical self hosted mirror.
[InlineData("http://localhost/ws/2/")] // Loopback host name.
[InlineData("http://[fc00::1]/ws/2/")] // IPv6 unique local range.
[InlineData("http://[::ffff:10.0.0.5]/ws/2/")] // An IPv4-mapped private address.
public async Task GetAsync_WhenPrivateBaseUrlsAreExplicitlyAllowed_ShouldApplyThem(string baseUrl)
{
// Arrange
@@ -193,6 +208,22 @@ public class MusicBrainzSettingsProviderTests
Assert.Equal("http://mirror.example/ws/2/", result.BaseUrl);
}
[Fact]
public async Task GetAsync_WhenThePersistedBaseUrlIsAnIPv4MappedPublicAddress_ShouldApplyIt()
{
// Arrange
IPluginSettingsStore mockStore = Substitute.For<IPluginSettingsStore>();
mockStore.GetSettingsAsync(Arg.Any<Guid>(), Arg.Any<CancellationToken>()).Returns(
new Dictionary<string, string> { [MusicBrainzSettingsKeys.BASE_URL] = "http://[::ffff:93.184.216.34]/ws/2/" });
MusicBrainzSettingsProvider sut = new(mockStore, Guid.NewGuid(), CreateDefaults());
// Act
MusicBrainzSettingsDto result = await sut.GetAsync(CancellationToken.None);
// Assert
Assert.Equal("http://[::ffff:93.184.216.34]/ws/2/", result.BaseUrl);
}
[Fact]
public async Task GetAsync_WhenThePersistedBaseUrlIsNull_ShouldKeepTheDefaultBaseUrl()
{