mirror of
https://github.com/BinaryAlley/Nemera.git
synced 2026-12-03 18:21:10 +00:00
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:
1 parent
ecdb39cc6a
commit
24af00579c
28 files changed
+2977
-162
No files matched your search
+156
-3
@@ -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;
|
||||
}
|
||||
}
|
||||
+31
@@ -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()
|
||||
{
|
||||
|
||||
Reference in new issue
Block a user