diff --git a/docs/manual/index.md b/docs/manual/index.md index c749cb1b..4b4a99d5 100644 --- a/docs/manual/index.md +++ b/docs/manual/index.md @@ -62,7 +62,7 @@ You are handing Lumina the keys to your files, so it is built to deserve that tr - **Locked down by default.** The API authenticates every request, and only endpoints explicitly marked as public can be reached without signing in. Accounts, roles, fine grained permissions and policies decide who may reach which library or content, and sensitive endpoints are rate limited per client IP. - **Secrets stay secret.** A production deployment must supply its own signing and encryption keys, and the server refuses to start without them. - **Themes and plugins are treated as untrusted.** Theme packs are validated, their template and asset paths are normalized and confined to the pack, and their archive size, expanded size and entry count are capped. A plugin archive has its directory components stripped, so it cannot write outside the plugin directory, but it has no size or entry limit. Templates render through a small engine that cannot execute code, and a broken theme falls back to the built-in rendering. Themes can still ship their own JavaScript, so only install code from sources you trust. -- **Nothing phones home.** Lumina itself makes no outbound connections on its own. It reaches the internet only when your configuration tells it to, for example when you enable a metadata provider. Part of what it fetches on your behalf is guarded: artwork downloads reject literal loopback, private, link local and carrier grade NAT addresses, and follow redirects only to public HTTPS hosts. That guard is not a hard boundary, though. It does not resolve host names, so a name that points at an internal address can still get through, and the metadata calls a provider makes go out through the provider's own client, without that guard at all. Some providers add a check of their own: the MusicBrainz provider refuses a base address that is not public unless you turn on its `Allow LAN/Private Base URL` setting, which exists for pointing it at a self hosted instance. Enabling a web provider is trusting it to make requests from your server. Everything the client loads, from stylesheets and scripts to images, fonts and icons, is served from your own server, so using the client pings no third party that could note where you are or what you are looking at. One exception ships switched on, and it is worth knowing about: a book can carry its own styles, and those styles can make the browser load resources from outside servers, which those servers could observe. Lumina keeps a book's styles by default because it looks better, so a book from an untrusted source can leak your location this way. The `Preserve book styles` setting (see [Managing Libraries](managing-libraries/index.md)) turns it off, stripping the styles and closing that door, at the cost of the book's original look. +- **Nothing phones home.** Lumina itself makes no outbound connections on its own. It reaches the internet only when your configuration tells it to, for example when you enable a metadata provider. Everything it fetches on your behalf is guarded: before any provider request leaves the server, the host name is resolved, and the request is refused when any address it resolves to is loopback, private, link local, carrier grade NAT or otherwise internal. Provider requests are made directly, never through an outbound HTTP proxy, so the connection is made to the very address that was checked, and a name that changes its answer between the check and the connection cannot slip through. The same guard covers the metadata and artwork calls of the providers, and redirects are followed only to public HTTPS hosts, checking every hop. The single exception is one you opt into, and it covers every request the MusicBrainz provider sends to the base address you configure, including redirects that stay on that host and that may use plain HTTP when the base address itself does: the provider accepts a base address that is not public only when you turn on its `Allow LAN/Private Base URL` setting, which exists for pointing it at a self hosted instance. It does not extend to any other host, and the link local and cloud metadata ranges stay blocked even then. Enabling a web provider is still trusting it to make requests from your server. Everything the client loads, from stylesheets and scripts to images, fonts and icons, is served from your own server, so using the client pings no third party that could note where you are or what you are looking at. One exception ships switched on, and it is worth knowing about: a book can carry its own styles, and those styles can make the browser load resources from outside servers, which those servers could observe. Lumina keeps a book's styles by default because it looks better, so a book from an untrusted source can leak your location this way. The `Preserve book styles` setting (see [Managing Libraries](managing-libraries/index.md)) turns it off, stripping the styles and closing that door, at the cost of the book's original look. - **It is tested, a lot.** Do not take any of this on faith. The project is covered by more than 10,000 tests, including a dedicated security suite, because Lumina puts stability and security ahead of moving fast. ## Documentation, diagrams and comments diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Common/DependencyInjection/CoverArtArchiveServices.cs b/plugins/Lumina.Plugins.CoverArtArchive/Common/DependencyInjection/CoverArtArchiveServices.cs index aa1899b3..065c8289 100644 --- a/plugins/Lumina.Plugins.CoverArtArchive/Common/DependencyInjection/CoverArtArchiveServices.cs +++ b/plugins/Lumina.Plugins.CoverArtArchive/Common/DependencyInjection/CoverArtArchiveServices.cs @@ -8,7 +8,6 @@ using Lumina.Plugins.CoverArtArchive.Core.Settings; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; -using System.Net.Http; #endregion namespace Lumina.Plugins.CoverArtArchive.Common.DependencyInjection; @@ -46,12 +45,9 @@ internal static class CoverArtArchiveServices // is fetched only once during a run. services.TryAddSingleton(); - // Automatic redirects are disabled on purpose: the metadata endpoints answer with a temporary redirect to the Internet Archive, and the client - // follows that redirect itself, checking every hop against CoverArtArchiveHosts. Letting the primary handler follow redirects automatically - // would make it follow whatever Location the response carries, which is server controlled, and would bypass that host check, which is the SSRF - // control here; the base URL being a constant does not make the redirect target trustworthy. - services.AddHttpClient() - .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); + // The client follows the redirects of the Cover Art Archive itself, confined to the hosts the archive may delegate its responses to, so it opts out of the + // host redirect handling. The host still validates and pins the address of every request and confirms that it is public. + services.AddHttpClient(); // Register the artwork provider as a keyed by pluginId transient service, so it can be resolved specifically among other IArtworkProvider implementations. services.AddKeyedTransient(pluginId); diff --git a/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveHttpClient.cs b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveHttpClient.cs index 08cde755..2c93e390 100644 --- a/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveHttpClient.cs +++ b/plugins/Lumina.Plugins.CoverArtArchive/Core/Api/CoverArtArchiveHttpClient.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Http; using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; using Lumina.Plugins.CoverArtArchive.Common.Models.DTO.Settings; using Lumina.Plugins.CoverArtArchive.Core.Settings; @@ -118,8 +119,8 @@ internal sealed class CoverArtArchiveHttpClient Uri requestUri = new(new Uri(BASE_URL, UriKind.Absolute), relativeUrl); - // The metadata endpoints answer with a temporary redirect to the Internet Archive, so the redirect is followed explicitly, which keeps the - // automatic redirects disabled and confines the following to the hosts the Cover Art Archive is allowed to delegate its responses to. + // The metadata endpoints answer with a temporary redirect to the Internet Archive, so the redirect is followed explicitly, which keeps the automatic + // redirects disabled, opts out of the host redirect handling, and confines the following to the hosts the Cover Art Archive may delegate its responses to. for (int redirectCount = 0; redirectCount <= MAXIMUM_REDIRECT_COUNT; redirectCount++) { HttpResponseMessage response = await SendWithRetriesAsync(settings, requestUri, cancellationToken).ConfigureAwait(false); @@ -164,10 +165,14 @@ internal sealed class CoverArtArchiveHttpClient { HttpRequestMessage request = new(HttpMethod.Get, requestUri); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + // The client follows the redirects itself, confined to the hosts the Cover Art Archive may delegate its responses to, so it opts out of the + // host redirect handling and receives the redirect response instead. + request.Options.Set(OutboundRequestOptions.FollowRedirects, false); response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); } - catch (HttpRequestException) when (!isLastAttempt) + catch (HttpRequestException exception) when (!isLastAttempt && !IsPolicyRejection(exception)) { + // A rejection by the host outbound address policy is deterministic and is reported as ConfigurationLimitExceeded, so it is not retried. await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false); continue; } @@ -238,6 +243,22 @@ internal sealed class CoverArtArchiveHttpClient return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt)); } + /// + /// Determines whether the provided exception, or one of its inner exceptions, reports a rejection by the host outbound address policy. + /// + /// The exception to inspect. + /// when the exception chain contains a policy rejection, otherwise . + /// + /// SocketsHttpHandler wraps an exception thrown by the connect callback in an HttpRequestException with the ConnectionError error, so the policy rejection is only visible on the inner exception. + /// + private static bool IsPolicyRejection(HttpRequestException exception) + { + for (Exception? currentException = exception; currentException is not null; currentException = currentException.InnerException) + if (currentException is HttpRequestException httpRequestException && httpRequestException.HttpRequestError == HttpRequestError.ConfigurationLimitExceeded) + return true; + return false; + } + /// /// Applies the request headers configured in the onto the underlying HTTP client, unless they are already set. /// diff --git a/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs b/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs index f4364382..46a7edbb 100644 --- a/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs +++ b/plugins/Lumina.Plugins.MusicBrainz/Common/DependencyInjection/MusicBrainzServices.cs @@ -8,7 +8,6 @@ using Lumina.Plugins.MusicBrainz.Core.Settings; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using System; -using System.Net.Http; #endregion namespace Lumina.Plugins.MusicBrainz.Common.DependencyInjection; @@ -45,9 +44,9 @@ internal static class MusicBrainzServices // The response cache is process-wide, so that an entity shared by many items, like a release shared by all its tracks, is fetched only once. services.TryAddSingleton(); - // Redirects are not followed, so the configurable base URL cannot be used to reach an internal address through a redirect from a mirror. - services.AddHttpClient() - .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }); + // The host creates the primary handler of the outbound clients, which disables automatic redirects and connects only to addresses validated to be + // public. The client follows the redirects itself, confined to the configured host, so the configurable base URL cannot be used to reach an internal address. + services.AddHttpClient(); // Register the metadata providers as keyed by pluginId transient services, so they can be resolved specifically among other IMetadataProvider implementations. // A single plugin exposes one provider per entity type, because the metadata contract is typed to a single lookup and metadata pair. diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs index 70407049..cd77112c 100644 --- a/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Api/MusicBrainzHttpClient.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Http; using Lumina.Plugins.MusicBrainz.Common.Models.Contracts.Responses; using Lumina.Plugins.MusicBrainz.Common.Models.DTO.Settings; using Lumina.Plugins.MusicBrainz.Core.Settings; @@ -34,6 +35,9 @@ internal sealed class MusicBrainzHttpClient // Transient failures and rate limiting are retried with an exponential backoff, so a single hiccup does not mark an item as failed to enrich. private const int MAXIMUM_ATTEMPT_COUNT = 4; + // The redirects of a self hosted mirror are followed explicitly, so the host redirect policy can be opted out of and only the same host can be reached. + private const int MAXIMUM_REDIRECT_COUNT = 5; + /// /// Initializes a new instance of the class. /// @@ -222,15 +226,55 @@ internal sealed class MusicBrainzHttpClient } /// - /// Sends a GET request to the MusicBrainz web service, throttled to respect the configured minimum request interval unless the configured - /// base URL is not the real MusicBrainz service, in which case no rate limit is imposed. Transient failures, rate limiting and transport - /// exceptions are retried, preferring the delay requested by the web service when it is provided. + /// Sends a GET request to the MusicBrainz web service, following its redirects explicitly so they are confined to the configured host, and throttled to + /// respect the configured minimum request interval unless the configured base URL is not the real MusicBrainz service, in which case no rate limit is imposed. + /// Transient failures, rate limiting and transport exceptions are retried, preferring the delay requested by the web service when it is provided. /// /// The settings that configure the MusicBrainz web service requests. /// The URL of the resource, relative to the base address. /// Cancellation token that can be used to stop the execution. /// The HTTP response message for the request. + /// The service redirected the request to a host or a scheme that is not allowed, or too many times. private async Task SendAsync(MusicBrainzSettingsDto settings, string relativeUrl, CancellationToken cancellationToken) + { + Uri baseUri = new(settings.BaseUrl, UriKind.Absolute); + // The permission to reach a private address is scoped to the host of the configured base URL, so a mirror cannot redirect the request to another + // private host, and the link local and cloud metadata ranges stay blocked even when the permission is granted. + string? allowedPrivateHost = settings.DoesAllowPrivateBaseUrl ? baseUri.IdnHost : null; + Uri requestUri = BuildRequestUri(settings.BaseUrl, relativeUrl); + + for (int redirectCount = 0; redirectCount <= MAXIMUM_REDIRECT_COUNT; redirectCount++) + { + HttpResponseMessage response = await SendWithRetriesAsync(settings, requestUri, allowedPrivateHost, cancellationToken).ConfigureAwait(false); + + if (!IsRedirect(response.StatusCode) || response.Headers.Location is null) + return response; + + Uri? redirectUri = ResolveRedirect(requestUri, response.Headers.Location); + // The response of a redirect is not returned, so it must be disposed here to release its connection. + response.Dispose(); + + // A redirect is followed only to the configured host, and never from HTTPS to HTTP, so a compromised or misbehaving mirror cannot redirect the + // request to any other host, while a plain HTTP self hosted mirror keeps working across the redirects of its reverse proxy. + if (redirectUri is null || !IsAllowedRedirect(baseUri, redirectUri)) + throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, "The MusicBrainz service redirected the request to a disallowed target."); + + requestUri = redirectUri; + } + + throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, "The MusicBrainz service redirected the request too many times."); + } + + /// + /// Sends a GET request to the provided URI, throttled to respect the configured minimum request interval. Transient failures and rate limiting are retried, + /// so a single hiccup does not surface as a failed resolution. + /// + /// The settings that configure the MusicBrainz web service requests. + /// The absolute URI of the resource to request. + /// The host that may be private, or when no such permission was granted. + /// Cancellation token that can be used to stop the execution. + /// The HTTP response message for the request. + private async Task SendWithRetriesAsync(MusicBrainzSettingsDto settings, Uri requestUri, string? allowedPrivateHost, CancellationToken cancellationToken) { EnsureRequestHeaders(settings); // The rate limit is enforced by the MusicBrainz web service itself, so it is only observed when the requests actually reach it; a self hosted @@ -248,12 +292,17 @@ internal sealed class MusicBrainzHttpClient HttpResponseMessage response; try { - HttpRequestMessage request = new(HttpMethod.Get, BuildRequestUri(settings.BaseUrl, relativeUrl)); + HttpRequestMessage request = new(HttpMethod.Get, requestUri); request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + // The client follows the redirects itself, confined to the configured host, so it opts out of the host redirect handling. + request.Options.Set(OutboundRequestOptions.FollowRedirects, false); + if (allowedPrivateHost is not null && string.Equals(requestUri.IdnHost, allowedPrivateHost, StringComparison.OrdinalIgnoreCase)) + request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, allowedPrivateHost); response = await _httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancellationToken).ConfigureAwait(false); } - catch (HttpRequestException) when (!isLastAttempt) + catch (HttpRequestException exception) when (!isLastAttempt && !IsPolicyRejection(exception)) { + // A rejection by the host outbound address policy is deterministic and is reported as ConfigurationLimitExceeded, so it is not retried. await Task.Delay(GetRetryDelay(attempt, null), cancellationToken).ConfigureAwait(false); continue; } @@ -271,6 +320,42 @@ internal sealed class MusicBrainzHttpClient } } + /// + /// Determines whether the provided status code is a redirect. + /// + /// The status code to check. + /// when the status code is a redirect, otherwise . + private static bool IsRedirect(HttpStatusCode statusCode) + { + return statusCode is HttpStatusCode.MovedPermanently or HttpStatusCode.Found or HttpStatusCode.SeeOther + or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect; + } + + /// + /// Resolves the location of a redirect against the URI of the request it was returned for. + /// + /// The URI of the request the redirect was returned for. + /// The location of the redirect. + /// The absolute URI of the redirect, or when it could not be resolved. + private static Uri? ResolveRedirect(Uri requestUri, Uri location) + { + if (location.IsAbsoluteUri) + return location; + return Uri.TryCreate(requestUri, location, out Uri? resolvedUri) ? resolvedUri : null; + } + + /// + /// Determines whether the provided redirect target may be followed: it must stay on the host of the configured base address, and it may not downgrade an HTTPS base address to plain HTTP. + /// + /// The URI of the configured base address. + /// The URI of the redirect target. + /// when the redirect may be followed, otherwise . + private static bool IsAllowedRedirect(Uri baseUri, Uri redirectUri) + { + bool isSchemeAllowed = redirectUri.Scheme == Uri.UriSchemeHttps || (baseUri.Scheme == Uri.UriSchemeHttp && redirectUri.Scheme == Uri.UriSchemeHttp); + return isSchemeAllowed && string.Equals(baseUri.IdnHost, redirectUri.IdnHost, StringComparison.OrdinalIgnoreCase); + } + /// /// Gets the delay to wait before the next attempt, preferring the delay requested by the MusicBrainz web service when it is provided. /// @@ -293,6 +378,22 @@ internal sealed class MusicBrainzHttpClient return TimeSpan.FromMilliseconds(250 * Math.Pow(2, attempt)); } + /// + /// Determines whether the provided exception, or one of its inner exceptions, reports a rejection by the host outbound address policy. + /// + /// The exception to inspect. + /// when the exception chain contains a policy rejection, otherwise . + /// + /// SocketsHttpHandler wraps an exception thrown by the connect callback in an HttpRequestException with the ConnectionError error, so the policy rejection is only visible on the inner exception. + /// + private static bool IsPolicyRejection(HttpRequestException exception) + { + for (Exception? currentException = exception; currentException is not null; currentException = currentException.InnerException) + if (currentException is HttpRequestException httpRequestException && httpRequestException.HttpRequestError == HttpRequestError.ConfigurationLimitExceeded) + return true; + return false; + } + /// /// Determines whether the provided base URL points to the real MusicBrainz web service, which is the only one whose rate limit is observed. /// diff --git a/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs index 5a667f17..09583d56 100644 --- a/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs +++ b/plugins/Lumina.Plugins.MusicBrainz/Core/Settings/MusicBrainzSettingsProvider.cs @@ -130,17 +130,20 @@ internal sealed class MusicBrainzSettingsProvider /// The host of the persisted base URL. /// when the host is public, otherwise . /// - /// A host name is accepted as is, because it cannot be classified without resolving it, which is deliberately not done here. - /// A private or local host is accepted when is enabled, which supports self hosted - /// mirrors on a local network. + /// A host name is accepted as is, because it cannot be classified without resolving it, which is deliberately not done here. The host that runs the plugin + /// resolves it again when the request is sent, and rejects it when any address it resolves to is private, unless + /// enabled the private base address. That permission applies only to the host of the configured base address, so a redirect to another private host is still + /// rejected, and the link local and cloud metadata ranges are always rejected. Enabling the setting supports self hosted mirrors on a local network. + /// The address classification matches the one the host applies to a resolved address, so the settings layer does not accept a base URL that the host later + /// rejects. /// private static bool IsPublicHost(string host) { if (string.IsNullOrWhiteSpace(host)) return false; - // Uri.Host surrounds an IPv6 literal with brackets, which IPAddress.TryParse does not accept. - string normalizedHost = host.Trim('[', ']'); + // Uri.Host surrounds an IPv6 literal with brackets, which IPAddress.TryParse does not accept, and a fully qualified name may end with a dot. + string normalizedHost = host.Trim('[', ']').TrimEnd('.'); if (string.Equals(normalizedHost, "localhost", StringComparison.OrdinalIgnoreCase)) return false; @@ -153,32 +156,64 @@ internal sealed class MusicBrainzSettingsProvider if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) return false; - if (address.AddressFamily == AddressFamily.InterNetwork) - { - byte[] octets = address.GetAddressBytes(); - // The unspecified, private, loopback, link local and carrier grade NAT ranges are rejected, as they are the common targets of an SSRF. - return octets[0] switch - { - 0 => false, - 10 => false, - 100 when octets[1] is >= 64 and <= 127 => false, - 127 => false, - 169 when octets[1] == 254 => false, - 172 when octets[1] is >= 16 and <= 31 => false, - 192 when octets[1] == 168 => false, - _ => true - }; - } + // IPv4-mapped IPv6 addresses were converted to IPv4 above, so the family split never sees one. + return address.AddressFamily == AddressFamily.InterNetwork + ? IsPublicIPv4Address(address) + : IsPublicIPv6Address(address); + } - if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal) + /// + /// Determines whether the provided IPv4 address is public. + /// + /// The IPv4 address to check. + /// when the address is public, otherwise . + private static bool IsPublicIPv4Address(IPAddress address) + { + byte[] octets = address.GetAddressBytes(); + return octets[0] switch + { + 0 => false, // The 0.0.0.0/8 "this network" range. + 10 => false, // The 10.0.0.0/8 private range. + 100 when octets[1] is >= 64 and <= 127 => false, // The 100.64.0.0/10 carrier grade NAT range. + 127 => false, // The 127.0.0.0/8 loopback range. + 169 when octets[1] == 254 => false, // The 169.254.0.0/16 link local range, including the cloud metadata endpoints. + 172 when octets[1] is >= 16 and <= 31 => false, // The 172.16.0.0/12 private range. + 192 when octets[1] == 168 => false, // The 192.168.0.0/16 private range. + 192 when octets[1] == 0 && (octets[2] is 0 or 2) => false, // The IETF protocol assignments and TEST-NET-1 documentation ranges. + 198 when octets[1] is >= 18 and <= 19 => false, // The 198.18.0.0/15 benchmarking range. + 198 when octets[1] == 51 && octets[2] == 100 => false, // The TEST-NET-2 documentation range. + 203 when octets[1] == 0 && octets[2] == 113 => false, // The TEST-NET-3 documentation range. + >= 224 => false, // The multicast range, the reserved range, and the broadcast address. + _ => true + }; + } + + /// + /// Determines whether the provided IPv6 address is public. + /// + /// The IPv6 address to check. + /// when the address is public, otherwise . + private static bool IsPublicIPv6Address(IPAddress address) + { + if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal || address.IsIPv6Multicast || address.IsIPv6Teredo || address.IsIPv6UniqueLocal) return false; byte[] addressBytes = address.GetAddressBytes(); - // The fc00::/7 unique local range is rejected, matching the private IPv4 ranges. - if ((addressBytes[0] & 0xFE) == 0xFC) + // The ::/96 IPv4 compatible and ::ffff:0:0/96 IPv4 translated ranges embed an IPv4 address, and the mapped form is already converted to IPv4, so no + // address with an all zero first eighty bits is public. + if (addressBytes[0] == 0 && addressBytes[1] == 0 && addressBytes[2] == 0 && addressBytes[3] == 0 && + addressBytes[4] == 0 && addressBytes[5] == 0 && addressBytes[6] == 0 && addressBytes[7] == 0 && + addressBytes[8] == 0 && addressBytes[9] == 0) return false; - return true; + return addressBytes[0] switch + { + 0x00 when addressBytes[1] == 0x64 && addressBytes[2] == 0xFF && addressBytes[3] == 0x9B => false, // The 64:ff9b::/96 NAT64 prefix, which can map to private IPv4 addresses. + 0x01 when addressBytes[1] == 0x00 && addressBytes[2] == 0x00 && addressBytes[3] == 0x00 => false, // The 100::/64 discard only range. + 0x20 when addressBytes[1] == 0x01 && addressBytes[2] == 0x0D && addressBytes[3] == 0xB8 => false, // The 2001:db8::/32 documentation range. + 0x20 when addressBytes[1] == 0x02 => false, // The 2002::/16 6to4 range. + _ => true + }; } /// diff --git a/src/Lumina.Domain.SharedKernel/Common/Enums/Networking/OutboundRequestRejectionReason.cs b/src/Lumina.Domain.SharedKernel/Common/Enums/Networking/OutboundRequestRejectionReason.cs new file mode 100644 index 00000000..4c003e83 --- /dev/null +++ b/src/Lumina.Domain.SharedKernel/Common/Enums/Networking/OutboundRequestRejectionReason.cs @@ -0,0 +1,47 @@ +namespace Lumina.Domain.SharedKernel.Common.Enums.Networking; + +/// +/// Enumeration for the reasons an outbound request was rejected by the host address policy. +/// +public enum OutboundRequestRejectionReason +{ + /// + /// The request was not rejected. + /// + None, + + /// + /// The host name could not be resolved. + /// + HostCouldNotBeResolved, + + /// + /// The host resolved to an address that is not public and was not explicitly allowed. + /// + AddressNotAllowed, + + /// + /// The host resolved to a link local or cloud metadata address, which is never allowed. + /// + LinkLocalOrMetadataAddress, + + /// + /// The redirect target is not an HTTPS URL. + /// + RedirectSchemeNotHttps, + + /// + /// The redirect target could not be resolved from the location of the response. + /// + RedirectTargetInvalid, + + /// + /// The request was redirected too many times. + /// + TooManyRedirects, + + /// + /// The outbound request has no absolute URI, so its host cannot be validated. + /// + RequestHasNoAbsoluteUri +} diff --git a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs index 591ca71f..5c2f7436 100644 --- a/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs +++ b/src/Lumina.Infrastructure/Common/DependencyInjection/InfrastructureLayerServices.cs @@ -139,11 +139,23 @@ public static class InfrastructureLayerServices services.AddSingleton(); - // Artwork downloads: the remote artwork of any provider is downloaded through a client that follows redirects only to public HTTPS hosts, - // so a URL returned by a provider, or a redirect it points at, can never reach a private, loopback or link local address of the host. - services.AddHttpClient(NamedHttpClients.ARTWORK_DOWNLOAD) - .ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler { AllowAutoRedirect = false }) - .AddHttpMessageHandler(() => new PublicHostRedirectHandler()); + // Every outbound HTTP client of the host is guarded, including the clients the provider plugins register: the host of every request is resolved and + // must be public, the connection is made to the validated address itself, so a URL chosen by a provider, or a name that resolves to an internal + // address, can never make the host reach a private, loopback or link local address, and redirects are followed only to public HTTPS hosts. + services.AddSingleton(); + services.ConfigureHttpClientDefaults(httpClientBuilder => httpClientBuilder + .ConfigurePrimaryHttpMessageHandler(serviceProvider => PublicHostConnectionGuard.CreatePrimaryHandler( + serviceProvider.GetRequiredService(), + serviceProvider.GetRequiredService().CreateLogger(nameof(PublicHostConnectionGuard)))) + .AddHttpMessageHandler(serviceProvider => new PublicHostValidationHandler( + serviceProvider.GetRequiredService(), + serviceProvider.GetRequiredService>())) + .AddHttpMessageHandler(serviceProvider => new PublicHostRedirectHandler( + serviceProvider.GetRequiredService(), + serviceProvider.GetRequiredService>()))); + + // Artwork downloads: the remote artwork of any provider is downloaded through the same guarded client pipeline, and is stored by the artwork services below. + services.AddHttpClient(NamedHttpClients.ARTWORK_DOWNLOAD); // Book artwork: stores the artwork of the books into the internal media directory. services.AddScoped(); diff --git a/src/Lumina.Infrastructure/Common/Networking/NamedHttpClients.cs b/src/Lumina.Infrastructure/Common/Networking/NamedHttpClients.cs index 926e983d..b70a468d 100644 --- a/src/Lumina.Infrastructure/Common/Networking/NamedHttpClients.cs +++ b/src/Lumina.Infrastructure/Common/Networking/NamedHttpClients.cs @@ -6,7 +6,7 @@ namespace Lumina.Infrastructure.Common.Networking; internal static class NamedHttpClients { /// - /// The name of the HTTP client used to download remote artwork, whose redirects are followed only to public hosts. + /// The name of the HTTP client used to download remote artwork, which is guarded like every other outbound client of the host. /// internal const string ARTWORK_DOWNLOAD = "artwork-download"; } diff --git a/src/Lumina.Infrastructure/Common/Networking/PublicHostConnectionGuard.cs b/src/Lumina.Infrastructure/Common/Networking/PublicHostConnectionGuard.cs new file mode 100644 index 00000000..67c9b77a --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Networking/PublicHostConnectionGuard.cs @@ -0,0 +1,213 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Http; +using Microsoft.Extensions.Logging; +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Common.Networking; + +/// +/// Creates the primary message handler used by the outbound HTTP clients, whose connect callback resolves each host and connects only to an address that was +/// checked to be public, so that a name that changes its answer between the check and the connection cannot make the host reach an internal address. +/// +internal static class PublicHostConnectionGuard +{ + private const int ATTEMPT_STAGGER_IN_MILLISECONDS = 250; + + /// + /// Creates the primary message handler of an outbound HTTP client, which follows no redirects and validates the address it connects to. + /// + /// The validator that decides whether a host is public. + /// The logger that records the rejected connections. + /// The primary message handler of the client. + /// + /// Automatic redirects are disabled because a redirect is a server controlled instruction, which the clients that follow one validate hop by hop instead. + /// Proxy use is disabled as well, because a proxy would make the connection to an address other than the target of the request, which could not be pinned to + /// the address that was checked. Every connection is therefore direct, so the connect callback is the sole and authoritative address check. + /// + public static SocketsHttpHandler CreatePrimaryHandler(PublicHostValidator publicHostValidator, ILogger logger) + { + return new SocketsHttpHandler + { + // Redirects are handled by PublicHostRedirectHandler, which validates every hop. The primary handler must not follow one on its own. + AllowAutoRedirect = false, + // A proxy would connect to an address other than the validated target, so the guard requires direct connections. + UseProxy = false, + ConnectCallback = (connectionContext, cancellationToken) => ConnectAsync( + publicHostValidator, + connectionContext.DnsEndPoint.Host, + connectionContext.DnsEndPoint.Port, + connectionContext.InitialRequestMessage, + logger, + cancellationToken) + }; + } + + /// + /// Resolves the host and connects to the first of its validated addresses that accepts the connection. + /// + /// The validator that decides whether a host is public. + /// The host to connect to. + /// The port to connect to. + /// The request that triggered the connection, when it is known. + /// The logger that records the rejected connections. + /// Cancellation token that can be used to stop the execution. + /// The stream of the established connection. + /// The host could not be resolved. + /// The host resolves to an address that is not allowed, or none of its addresses accepts the connection. + internal static async ValueTask ConnectAsync( + PublicHostValidator publicHostValidator, + string host, + int port, + HttpRequestMessage? request, + ILogger logger, + CancellationToken cancellationToken) + { + try + { + // Resolve and validate the addresses before any socket is opened, so the connection can only target a checked endpoint. + IReadOnlyList endPoints = await publicHostValidator.ResolveEndPointsAsync(host, port, GetAllowedPrivateHost(request), cancellationToken).ConfigureAwait(false); + return await ConnectToFirstEndPointAsync(endPoints, cancellationToken).ConfigureAwait(false); + } + catch (PublicHostRejectedException exception) + { + // The address policy refused the target. This is deterministic, so it is logged as a rejection rather than as a transport failure. + logger.LogWarning("Rejected the outbound connection to the host '{Host}' because {RejectionReason}. The connection was not made.", host, exception.RejectionReason); + throw; + } + catch (PublicHostResolutionException) + { + // The host name could not be resolved. This is reported separately from a policy rejection because it can be transient. + logger.LogWarning("Could not resolve the outbound host '{Host}'. The connection was not made.", host); + throw; + } + } + + /// + /// Gets the single host the request was explicitly allowed to reach private or local addresses on, which is how a user opted into a provider that runs on the + /// local network, like a self hosted MusicBrainz instance. + /// + /// The request that triggered the connection, when it is known. + /// The host that may be private, or when no such permission was granted. + private static string? GetAllowedPrivateHost(HttpRequestMessage? request) + { + if (request is not null && request.Options.TryGetValue(OutboundRequestOptions.AllowedPrivateHost, out string? allowedPrivateHost)) + return allowedPrivateHost; + return null; + } + + /// + /// Connects to the first endpoint that accepts the connection, starting the next address shortly after the previous one, instead of waiting for it to fail, + /// so an address that silently drops the connection cannot delay the others by the operating system timeout. + /// + /// The validated endpoints of the host. + /// Cancellation token that can be used to stop the execution. + /// The stream of the established connection. + /// None of the endpoints accepts the connection. + private static async ValueTask ConnectToFirstEndPointAsync(IReadOnlyList endPoints, CancellationToken cancellationToken) + { + // Every attempt shares this token, so the winner can cancel the attempts that are still running, while the caller keeps the ability to cancel all of them. + using CancellationTokenSource attemptCancellation = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken); + List> attempts = []; + + // Each address starts a little later than the previous one, so a blackholed address cannot delay the next one by the whole operating system timeout. + for (int index = 0; index < endPoints.Count; index++) + attempts.Add(ConnectToEndPointAsync(endPoints[index], index, attemptCancellation.Token)); + + Exception? lastException = null; + try + { + // The first attempt that succeeds wins. A failed attempt is removed and the loop keeps waiting for the remaining ones. + while (attempts.Count > 0) + { + Task completedAttempt = await Task.WhenAny(attempts).ConfigureAwait(false); + // Remove the completed attempt before the cleanup below, so only the attempts that are still running are disposed there. + attempts.Remove(completedAttempt); + try + { + Stream stream = await completedAttempt.ConfigureAwait(false); + // A connection was established. Cancel and dispose every attempt that lost the race before returning the winner's stream. + attemptCancellation.Cancel(); + await DisposeUnusedAttemptsAsync(attempts).ConfigureAwait(false); + attempts.Clear(); + return stream; + } + catch (Exception exception) when (exception is SocketException or OperationCanceledException) + { + // One unreachable address must not stop the next one from being tried, but a cancellation of the whole request must propagate. + if (cancellationToken.IsCancellationRequested) + throw; + lastException = exception; + } + } + } + finally + { + // An unexpected exception, or a cancellation, must not leave the other attempts running or their sockets open. + if (attempts.Count > 0) + { + attemptCancellation.Cancel(); + await DisposeUnusedAttemptsAsync(attempts).ConfigureAwait(false); + } + } + + // Every validated address was tried and none of them accepted the connection. + throw new HttpRequestException("None of the validated addresses of the host accepted the connection.", lastException); + } + + /// + /// Connects to a single endpoint, after waiting for its position in the staggered attempts. + /// + /// The endpoint to connect to. + /// The zero based position of the attempt among the endpoints of the host. + /// Cancellation token that can be used to stop the execution. + /// The stream of the established connection. + private static async Task ConnectToEndPointAsync(IPEndPoint endPoint, int attemptIndex, CancellationToken cancellationToken) + { + // The first address connects immediately. Each later address waits for its turn in the stagger, giving the earlier address a short head start. + if (attemptIndex > 0) + await Task.Delay(ATTEMPT_STAGGER_IN_MILLISECONDS * attemptIndex, cancellationToken).ConfigureAwait(false); + + Socket socket = new(endPoint.AddressFamily, SocketType.Stream, ProtocolType.Tcp) { NoDelay = true }; + try + { + await socket.ConnectAsync(endPoint, cancellationToken).ConfigureAwait(false); + return new NetworkStream(socket, ownsSocket: true); + } + catch + { + // Whether the attempt failed or was canceled by a winner, its socket must be released before the exception continues. + socket.Dispose(); + throw; + } + } + + /// + /// Disposes the connections established by the attempts that lost the race, and observes their failures so no exception is left unhandled. + /// + /// The attempts that are no longer needed. + /// A task that completes when every attempt was observed. + private static async Task DisposeUnusedAttemptsAsync(List> attempts) + { + foreach (Task attempt in attempts) + { + try + { + // A losing attempt can still have connected just before it was canceled, so its stream must be disposed too. + Stream stream = await attempt.ConfigureAwait(false); + stream.Dispose(); + } + catch + { + // The attempt failed or was canceled, so it has no stream to dispose. Its exception is expected and must not mask the winner. + } + } + } +} diff --git a/src/Lumina.Infrastructure/Common/Networking/PublicHostRedirectHandler.cs b/src/Lumina.Infrastructure/Common/Networking/PublicHostRedirectHandler.cs index a72b0354..8e4eeaf3 100644 --- a/src/Lumina.Infrastructure/Common/Networking/PublicHostRedirectHandler.cs +++ b/src/Lumina.Infrastructure/Common/Networking/PublicHostRedirectHandler.cs @@ -1,4 +1,7 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Networking; +using Lumina.Plugins.Contracts.Common.Http; +using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Net; @@ -10,10 +13,15 @@ using System.Threading.Tasks; namespace Lumina.Infrastructure.Common.Networking; /// -/// Message handler that validates the host of the initial request, and follows the redirects of the response only to public HTTPS hosts, so that -/// neither the URL emitted by a provider nor a server controlled redirect can make the host issue a request to a private, loopback, link local or -/// otherwise internal address. It is provider agnostic: it protects every download that is routed through the client it is attached to. +/// Message handler that follows the redirects of a bodyless request only to public HTTPS hosts, so that a server controlled redirect cannot make the host issue a +/// request to a private, loopback, link local or otherwise internal address. It is provider agnostic: it protects every request of the clients it is attached to. /// +/// +/// The host of the initial request is validated by , which runs before this handler. The host of every redirect is +/// validated here, because the requests created to follow a redirect are sent below the validation handler and never reach it. Their connections are still +/// validated by the connect callback of the outbound client. A client with its own redirect policy disables the redirect handling of the host through +/// and receives the redirect response instead. +/// internal sealed class PublicHostRedirectHandler : DelegatingHandler { /// @@ -21,20 +29,56 @@ internal sealed class PublicHostRedirectHandler : DelegatingHandler /// private const int MAXIMUM_REDIRECT_COUNT = 5; + private readonly PublicHostValidator _publicHostValidator; + private readonly ILogger _logger; + + // Headers that describe a single connection rather than the request, so they must never be replayed on the connection made for a redirect. + private static readonly HashSet s_hopByHopHeaders = new(StringComparer.OrdinalIgnoreCase) + { + "Connection", + "Keep-Alive", + "Proxy-Authenticate", + "Proxy-Authorization", + "Proxy-Connection", + "TE", + "Trailer", + "Transfer-Encoding", + "Upgrade" + }; + + // Headers that belong to the origin of the request, so they must not be forwarded when a redirect points at another origin. + private static readonly HashSet s_crossOriginHeaders = new(StringComparer.OrdinalIgnoreCase) + { + "Authorization", + "Cookie", + "Cookie2", + "Host" + }; + /// - /// Sends the request, validating that its host is public, and following its redirects only to public HTTPS hosts. + /// Initializes a new instance of the class. + /// + /// The validator that decides whether a host is public. + /// The logger that records the rejected redirects. + public PublicHostRedirectHandler(PublicHostValidator publicHostValidator, ILogger logger) + { + _publicHostValidator = publicHostValidator; + _logger = logger; + } + + /// + /// Sends the request, following its redirects only to public HTTPS hosts. /// /// The request to send. /// Cancellation token that can be used to stop the execution. /// The final response of the request. + /// A redirect target could not be resolved. + /// A redirect points to a host or a scheme that is not allowed, or too many redirects are followed. protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { - // The sink is provider agnostic, so the initial request is validated too, not only the redirects, so a provider that emits an internal URL - // cannot make the host fetch a private, loopback or link local address before any redirect is even involved. - Uri? initialUri = request.RequestUri; - string initialHost = initialUri is { IsAbsoluteUri: true } ? initialUri.Host : string.Empty; - if (initialUri is not { IsAbsoluteUri: true } || !PublicHostValidator.IsPublicHost(initialHost)) - throw new HttpRequestException($"The request was sent to the disallowed host '{initialHost}'."); + // A client with its own redirect policy opts out, so that this handler never consumes a redirect it cannot validate against that policy. + if (!ShouldFollowRedirects(request)) + return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); HttpRequestMessage currentRequest = request; // The requests created here to follow a redirect are owned by this handler, so they are disposed once the sending is complete. @@ -48,7 +92,7 @@ internal sealed class PublicHostRedirectHandler : DelegatingHandler HttpResponseMessage response = await base.SendAsync(currentRequest, cancellationToken).ConfigureAwait(false); - if (!IsRedirect(response.StatusCode) || response.Headers.Location is null) + if (!IsRedirect(response.StatusCode) || response.Headers.Location is null || !IsFollowableMethod(currentRequest.Method)) return response; Uri? redirectUri = ResolveRedirect(requestUri, response.Headers.Location); @@ -56,14 +100,29 @@ internal sealed class PublicHostRedirectHandler : DelegatingHandler response.Dispose(); if (redirectCount >= MAXIMUM_REDIRECT_COUNT) - throw new HttpRequestException("The request was redirected too many times."); + throw Reject(requestUri.IdnHost, OutboundRequestRejectionReason.TooManyRedirects); + + if (redirectUri is null) + throw Reject(requestUri.IdnHost, OutboundRequestRejectionReason.RedirectTargetInvalid); // Only public HTTPS targets are followed, so a redirect can never reach a private, loopback, link local or other internal address, - // nor downgrade the transfer back to an unencrypted one. - if (redirectUri is null || redirectUri.Scheme != Uri.UriSchemeHttps || !PublicHostValidator.IsPublicHost(redirectUri.Host)) - throw new HttpRequestException($"The request was redirected to the disallowed host '{redirectUri?.Host}'."); + // nor downgrade the transfer back to an unencrypted one. A request that was explicitly allowed to reach private endpoints keeps that + // permission only for the host it was granted for. + if (redirectUri.Scheme != Uri.UriSchemeHttps) + throw Reject(redirectUri.IdnHost, OutboundRequestRejectionReason.RedirectSchemeNotHttps); - HttpRequestMessage redirectRequest = CloneRequest(currentRequest, redirectUri); + PublicHostValidationResult result = await _publicHostValidator.ValidateHostAsync(redirectUri.IdnHost, GetAllowedPrivateHost(currentRequest), cancellationToken).ConfigureAwait(false); + if (!result.IsAllowed) + { + if (result.RejectionReason == OutboundRequestRejectionReason.HostCouldNotBeResolved) + { + _logger.LogWarning("Could not resolve the outbound redirect host '{Host}'. The request was not sent.", redirectUri.IdnHost); + throw new PublicHostResolutionException(redirectUri.IdnHost); + } + throw Reject(redirectUri.IdnHost, result.RejectionReason); + } + + HttpRequestMessage redirectRequest = CloneRequest(currentRequest, requestUri, redirectUri); redirectRequests.Add(redirectRequest); currentRequest = redirectRequest; } @@ -75,6 +134,41 @@ internal sealed class PublicHostRedirectHandler : DelegatingHandler } } + /// + /// Logs and creates the exception that reports a redirect rejected by the outbound address policy. + /// + /// The host the redirect points at, or the host of the request when the redirect has no usable target. + /// The reason the redirect was rejected. + /// The exception that reports the rejection. + private PublicHostRejectedException Reject(string host, OutboundRequestRejectionReason rejectionReason) + { + _logger.LogWarning("Rejected the outbound redirect to the host '{Host}' because {RejectionReason}. The request was not sent.", host, rejectionReason); + return new PublicHostRejectedException(host, rejectionReason); + } + + /// + /// Determines whether the host should follow the redirects of the provided request, which is the default, unless the client opted out to apply its own policy. + /// + /// The request to check. + /// when the host should follow the redirects, otherwise . + private static bool ShouldFollowRedirects(HttpRequestMessage request) + { + return !request.Options.TryGetValue(OutboundRequestOptions.FollowRedirects, out bool shouldFollowRedirects) || shouldFollowRedirects; + } + + /// + /// Gets the single host the request was explicitly allowed to reach private or local addresses on, which is how a user opted into a provider that runs on the + /// local network, like a self hosted MusicBrainz instance. + /// + /// The request to check. + /// The host that may be private, or when no such permission was granted. + private static string? GetAllowedPrivateHost(HttpRequestMessage request) + { + if (request.Options.TryGetValue(OutboundRequestOptions.AllowedPrivateHost, out string? allowedPrivateHost)) + return allowedPrivateHost; + return null; + } + /// /// Determines whether the provided status code is a redirect. /// @@ -86,6 +180,29 @@ internal sealed class PublicHostRedirectHandler : DelegatingHandler or HttpStatusCode.TemporaryRedirect or HttpStatusCode.PermanentRedirect; } + /// + /// Determines whether the redirect of a request with the provided method can be followed without replaying a body. + /// + /// The method of the request that was redirected. + /// when the method has no body and its redirect can be followed, otherwise . + private static bool IsFollowableMethod(HttpMethod method) + { + return HttpMethod.Get.Equals(method) || HttpMethod.Head.Equals(method); + } + + /// + /// Determines whether the provided URIs share a scheme, a host and a port, which makes them the same origin. + /// + /// The first URI to compare. + /// The second URI to compare. + /// when both URIs have the same origin, otherwise . + private static bool IsSameOrigin(Uri first, Uri second) + { + return string.Equals(first.Scheme, second.Scheme, StringComparison.OrdinalIgnoreCase) && + string.Equals(first.IdnHost, second.IdnHost, StringComparison.OrdinalIgnoreCase) && + first.Port == second.Port; + } + /// /// Resolves the location of a redirect against the URI of the request it was returned for. /// @@ -100,21 +217,37 @@ internal sealed class PublicHostRedirectHandler : DelegatingHandler } /// - /// Creates the request used to follow a redirect to , carrying over the method and the headers of - /// . It is meant for the bodyless GET downloads this handler is registered for. + /// Creates the request used to follow a redirect to , carrying over the method, the safe headers, and the private host permission + /// of . It is meant for the bodyless requests this handler follows. /// /// The request that is being redirected. - /// The URI of the redirect target. + /// The URI of the request the redirect was returned for. + /// The URI of the redirect target. /// The request used to follow the redirect. - private static HttpRequestMessage CloneRequest(HttpRequestMessage request, Uri requestUri) + /// + /// The credentials of the request, and the headers that describe its origin, are forwarded only when the redirect stays on the same origin, matching the + /// behavior of the built in redirect handling. The hop by hop headers are never forwarded, because they only apply to the connection that is being replaced. + /// + private static HttpRequestMessage CloneRequest(HttpRequestMessage request, Uri requestUri, Uri redirectUri) { - HttpRequestMessage redirectRequest = new(request.Method, requestUri) + HttpRequestMessage redirectRequest = new(request.Method, redirectUri) { Version = request.Version, VersionPolicy = request.VersionPolicy }; + bool isSameOrigin = IsSameOrigin(requestUri, redirectUri); foreach (KeyValuePair> header in request.Headers) + { + if (s_hopByHopHeaders.Contains(header.Key)) + continue; + if (!isSameOrigin && s_crossOriginHeaders.Contains(header.Key)) + continue; redirectRequest.Headers.TryAddWithoutValidation(header.Key, header.Value); + } + if (!isSameOrigin) + redirectRequest.Headers.Host = null; + if (request.Options.TryGetValue(OutboundRequestOptions.AllowedPrivateHost, out string? allowedPrivateHost)) + redirectRequest.Options.Set(OutboundRequestOptions.AllowedPrivateHost, allowedPrivateHost); return redirectRequest; } } diff --git a/src/Lumina.Infrastructure/Common/Networking/PublicHostRejectedException.cs b/src/Lumina.Infrastructure/Common/Networking/PublicHostRejectedException.cs new file mode 100644 index 00000000..c6051917 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Networking/PublicHostRejectedException.cs @@ -0,0 +1,53 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Networking; +using System.Net.Http; +#endregion + +namespace Lumina.Infrastructure.Common.Networking; + +/// +/// The exception thrown when an outbound request is rejected by the host address policy. +/// +/// +/// The error is used because it is a deterministic configuration error, which tells the provider clients +/// that the request must not be retried, unlike a transient transport failure. When the exception is thrown by the connect callback, SocketsHttpHandler wraps it in +/// an whose error is and whose inner exception is this one, so consumers inspect +/// the exception chain to recognize the policy rejection. +/// +internal sealed class PublicHostRejectedException : HttpRequestException +{ + /// + /// Gets the reason the host was rejected. + /// + public OutboundRequestRejectionReason RejectionReason { get; } + + /// + /// Initializes a new instance of the class. + /// + /// The host that was rejected. + /// The reason the host was rejected. + public PublicHostRejectedException(string host, OutboundRequestRejectionReason rejectionReason) + : base(HttpRequestError.ConfigurationLimitExceeded, BuildMessage(host, rejectionReason)) + { + RejectionReason = rejectionReason; + } + + /// + /// Builds the message of the exception, which names the host but never the resolved address, so an internal address does not reach the logs. + /// + /// The host that was rejected. + /// The reason the host was rejected. + /// The message of the exception. + private static string BuildMessage(string host, OutboundRequestRejectionReason rejectionReason) + { + return rejectionReason switch + { + OutboundRequestRejectionReason.LinkLocalOrMetadataAddress => $"The host '{host}' resolved to a link local or cloud metadata address, which is not allowed.", + OutboundRequestRejectionReason.RedirectSchemeNotHttps => $"The request to the host '{host}' was redirected to a target that is not an HTTPS URL.", + OutboundRequestRejectionReason.RedirectTargetInvalid => $"The request to the host '{host}' was redirected to a target that could not be resolved.", + OutboundRequestRejectionReason.TooManyRedirects => $"The request to the host '{host}' was redirected too many times.", + OutboundRequestRejectionReason.RequestHasNoAbsoluteUri => "The outbound request has no absolute URI, so its host could not be validated.", + _ => $"The host '{host}' points at an address that is not allowed." + }; + } +} diff --git a/src/Lumina.Infrastructure/Common/Networking/PublicHostResolutionException.cs b/src/Lumina.Infrastructure/Common/Networking/PublicHostResolutionException.cs new file mode 100644 index 00000000..ec47a435 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Networking/PublicHostResolutionException.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System; +using System.Net.Http; +#endregion + +namespace Lumina.Infrastructure.Common.Networking; + +/// +/// The exception thrown when the host of an outbound request cannot be resolved. +/// +/// +/// The error tells the provider clients that the failure is transient and may be retried, unlike a rejection +/// by the host address policy. When the exception is thrown by the connect callback, SocketsHttpHandler wraps it in an whose +/// error is and whose inner exception is this one, so consumers inspect the exception chain to distinguish it from a policy rejection. +/// +internal sealed class PublicHostResolutionException : HttpRequestException +{ + /// + /// Initializes a new instance of the class. + /// + /// The host that could not be resolved. + /// The exception that caused the resolution failure, when one is available. + public PublicHostResolutionException(string host, Exception? innerException = null) + : base(HttpRequestError.NameResolutionError, $"The host '{host}' could not be resolved.", innerException) + { + } +} diff --git a/src/Lumina.Infrastructure/Common/Networking/PublicHostValidationHandler.cs b/src/Lumina.Infrastructure/Common/Networking/PublicHostValidationHandler.cs new file mode 100644 index 00000000..bb19477d --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Networking/PublicHostValidationHandler.cs @@ -0,0 +1,78 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Networking; +using Lumina.Plugins.Contracts.Common.Http; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.Common.Networking; + +/// +/// Message handler that validates the host of the outbound requests it sees, resolving it and rejecting it when it is not public, so that a URL chosen by a provider +/// can never make the host issue a request to a private, loopback, link local or otherwise internal address. +/// +/// +/// The handler runs for the initial request of the clients it is attached to. A request that is created by a redirect handler is sent below this handler, so it +/// is validated by that redirect handler instead, and every connection is validated again by the connect callback installed alongside this handler. +/// +internal sealed class PublicHostValidationHandler : DelegatingHandler +{ + private readonly PublicHostValidator _publicHostValidator; + private readonly ILogger _logger; + + /// + /// Initializes a new instance of the class. + /// + /// The validator that decides whether a host is public. + /// The logger that records the rejected requests. + public PublicHostValidationHandler(PublicHostValidator publicHostValidator, ILogger logger) + { + _publicHostValidator = publicHostValidator; + _logger = logger; + } + + /// + /// Sends the request, after validating that its host is public. + /// + /// The request to send. + /// Cancellation token that can be used to stop the execution. + /// The response of the request. + /// The host of the request could not be resolved. + /// The host of the request is not public, or the request has no absolute URI. + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + if (request.RequestUri is not { IsAbsoluteUri: true } requestUri) + { + _logger.LogWarning("Rejected an outbound request that has no absolute URI, because its host could not be validated."); + throw new PublicHostRejectedException(string.Empty, OutboundRequestRejectionReason.RequestHasNoAbsoluteUri); + } + + PublicHostValidationResult result = await _publicHostValidator.ValidateHostAsync(requestUri.IdnHost, GetAllowedPrivateHost(request), cancellationToken).ConfigureAwait(false); + if (result.IsAllowed) + return await base.SendAsync(request, cancellationToken).ConfigureAwait(false); + + if (result.RejectionReason == OutboundRequestRejectionReason.HostCouldNotBeResolved) + { + _logger.LogWarning("Could not resolve the outbound host '{Host}'. The request was not sent.", requestUri.IdnHost); + throw new PublicHostResolutionException(requestUri.IdnHost); + } + + _logger.LogWarning("Rejected the outbound request to the host '{Host}' because {RejectionReason}. The request was not sent.", requestUri.IdnHost, result.RejectionReason); + throw new PublicHostRejectedException(requestUri.IdnHost, result.RejectionReason); + } + + /// + /// Gets the single host the request was explicitly allowed to reach private or local addresses on, which is how a user opted into a provider that runs on the + /// local network, like a self hosted MusicBrainz instance. + /// + /// The request to check. + /// The host that may be private, or when no such permission was granted. + private static string? GetAllowedPrivateHost(HttpRequestMessage request) + { + if (request.Options.TryGetValue(OutboundRequestOptions.AllowedPrivateHost, out string? allowedPrivateHost)) + return allowedPrivateHost; + return null; + } +} diff --git a/src/Lumina.Infrastructure/Common/Networking/PublicHostValidationResult.cs b/src/Lumina.Infrastructure/Common/Networking/PublicHostValidationResult.cs new file mode 100644 index 00000000..e4e7bd33 --- /dev/null +++ b/src/Lumina.Infrastructure/Common/Networking/PublicHostValidationResult.cs @@ -0,0 +1,31 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Networking; +#endregion + +namespace Lumina.Infrastructure.Common.Networking; + +/// +/// Represents the outcome of validating a host against the outbound address policy. +/// +/// Whether the host may be reached. +/// The reason the host may not be reached, or when it may. +internal readonly record struct PublicHostValidationResult( + bool IsAllowed, + OutboundRequestRejectionReason RejectionReason +) +{ + /// + /// Gets the result of a host that passed the validation. + /// + public static PublicHostValidationResult Allowed => new(true, OutboundRequestRejectionReason.None); + + /// + /// Creates the result of a host that failed the validation. + /// + /// The reason the host may not be reached. + /// The result of the rejected host. + public static PublicHostValidationResult Rejected(OutboundRequestRejectionReason rejectionReason) + { + return new(false, rejectionReason); + } +} diff --git a/src/Lumina.Infrastructure/Common/Networking/PublicHostValidator.cs b/src/Lumina.Infrastructure/Common/Networking/PublicHostValidator.cs index 4f0ce059..9d6e5078 100644 --- a/src/Lumina.Infrastructure/Common/Networking/PublicHostValidator.cs +++ b/src/Lumina.Infrastructure/Common/Networking/PublicHostValidator.cs @@ -1,7 +1,14 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Networking; using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.Globalization; +using System.Linq; using System.Net; using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; #endregion namespace Lumina.Infrastructure.Common.Networking; @@ -9,60 +16,444 @@ namespace Lumina.Infrastructure.Common.Networking; /// /// Determines whether a host is public, so that a request can never be sent to a private, loopback, link local or otherwise internal address. /// -internal static class PublicHostValidator +internal sealed class PublicHostValidator { + // A resolution is reused briefly, so the validation of a request and the connection that follows it do not resolve the same host twice. A negative result + // is kept for a much shorter time, so a temporary resolution failure does not keep a host unusable for long. The cache is bounded, so a provider that emits + // many distinct host names cannot make it grow without limit. + private const int CACHED_ADDRESS_LIFETIME_IN_SECONDS = 60; + private const int CACHED_ADDRESS_FAILURE_LIFETIME_IN_SECONDS = 5; + private const int MAXIMUM_CACHED_HOST_COUNT = 1024; + + private readonly Func> _hostAddressResolver; + private readonly ConcurrentDictionary _addressesCache = new(StringComparer.Ordinal); + /// - /// Determines whether the provided host is a public host. + /// Initializes a new instance of the class, resolving host names through the operating system resolver. /// - /// The host to check. - /// when the host is public, otherwise . - /// - /// A host name is accepted as is, because it cannot be classified without resolving it, which is deliberately not done here. An IP literal is accepted - /// only when it is a public address, so the unspecified, private, loopback, link local and carrier grade NAT ranges are all rejected. - /// - public static bool IsPublicHost(string host) + public PublicHostValidator() + : this(Dns.GetHostAddressesAsync) { + } + + /// + /// Initializes a new instance of the class, resolving host names through the provided resolver. + /// + /// The resolver used to resolve host names, so the resolution can be replaced when the validator is tested. + internal PublicHostValidator(Func> hostAddressResolver) + { + _hostAddressResolver = hostAddressResolver; + } + + /// + /// Validates whether the provided host may be reached, resolving it when it is a host name. + /// + /// The host to validate. + /// The single host that was explicitly allowed to reach private or local addresses, or when no such permission was granted. + /// Cancellation token that can be used to stop the execution. + /// The outcome of the validation, with the reason of a rejection when the host may not be reached. + /// + /// A host name is accepted only when every address it resolves to is public, so a name that points at an internal address, or that mixes public and internal + /// addresses, is rejected. A name that cannot be resolved is rejected as well, because a request to it could not be checked before it is sent. When the + /// host is the one explicitly allowed to be private, its private addresses are accepted too, except the link local and cloud metadata ranges. + /// + public async Task ValidateHostAsync(string host, string? allowedPrivateHost, CancellationToken cancellationToken) + { + // A host that is missing or blank cannot be classified, so it is rejected instead of being treated as public. if (string.IsNullOrWhiteSpace(host)) - return false; + return PublicHostValidationResult.Rejected(OutboundRequestRejectionReason.AddressNotAllowed); - // Uri.Host surrounds an IPv6 literal with brackets, which IPAddress.TryParse does not accept. - string normalizedHost = host.Trim('[', ']'); + string normalizedHost = NormalizeHost(host); + // localhost always resolves to loopback, so it is allowed only when it is the host the user explicitly opted into. if (string.Equals(normalizedHost, "localhost", StringComparison.OrdinalIgnoreCase)) - return false; + return allowedPrivateHost is not null && IsSameHost(normalizedHost, allowedPrivateHost) + ? PublicHostValidationResult.Allowed + : PublicHostValidationResult.Rejected(OutboundRequestRejectionReason.AddressNotAllowed); - if (!IPAddress.TryParse(normalizedHost, out IPAddress? address)) - return true; + // An IP literal needs no DNS resolution, so it can be classified directly. + if (IPAddress.TryParse(normalizedHost, out IPAddress? literalAddress)) + return EvaluateAddress(host, literalAddress, allowedPrivateHost); + IPAddress[] addresses = await ResolveAddressesAsync(normalizedHost, cancellationToken).ConfigureAwait(false); + // A name that cannot be resolved is rejected, because the address it would connect to could not be checked first. + if (addresses.Length == 0) + return PublicHostValidationResult.Rejected(OutboundRequestRejectionReason.HostCouldNotBeResolved); + + // Every address must be allowed, so a name that resolves to any internal address cannot be used to reach it by retrying the request. + foreach (IPAddress address in addresses) + { + PublicHostValidationResult result = EvaluateAddress(host, address, allowedPrivateHost); + if (!result.IsAllowed) + return result; + } + + return PublicHostValidationResult.Allowed; + } + + /// + /// Resolves the endpoint the provided host and port identify, rejecting the host when any address it resolves to is not public and not explicitly allowed. + /// + /// The host to resolve. + /// The port the resolved addresses are paired with. + /// The single host that was explicitly allowed to reach private or local addresses, or when no such permission was granted. + /// Cancellation token that can be used to stop the execution. + /// The endpoints the host resolves to, with the duplicate addresses removed. + /// The host cannot be resolved. + /// The host resolves to an address that is neither public nor allowed. + public async Task> ResolveEndPointsAsync(string host, int port, string? allowedPrivateHost, CancellationToken cancellationToken) + { + string normalizedHost = NormalizeHost(host); + List endPoints = []; + + // An IP literal needs no DNS resolution; it is validated and paired with the port directly. + if (IPAddress.TryParse(normalizedHost, out IPAddress? literalAddress)) + { + AddEndPoint(endPoints, literalAddress, port, host, allowedPrivateHost); + return endPoints; + } + + IPAddress[] addresses = await ResolveAddressesAsync(normalizedHost, cancellationToken).ConfigureAwait(false); + + // An empty result means there is no address to connect to, which is reported as a resolution failure rather than as an empty list. + if (addresses.Length == 0) + throw new PublicHostResolutionException(host); + + // Every address is validated before it is added, so the caller can only connect to endpoints that passed the policy. + foreach (IPAddress address in addresses) + AddEndPoint(endPoints, address, port, host, allowedPrivateHost); + + return endPoints; + } + + /// + /// Determines whether the provided address is public. + /// + /// The address to check. + /// when the address is public, otherwise . + /// + /// The loopback, unspecified, private, link local, carrier grade NAT, multicast, reserved and documentation ranges are all rejected, for both address families. + /// + public static bool IsPublicAddress(IPAddress address) + { + // An IPv4-mapped address is an IPv4 address in disguise. Classifying it as IPv4 keeps both spellings under the same policy. if (address.IsIPv4MappedToIPv6) address = address.MapToIPv4(); + // The loopback and unspecified addresses can never be a remote public peer. if (IPAddress.IsLoopback(address) || address.Equals(IPAddress.Any) || address.Equals(IPAddress.IPv6Any)) return false; + // The two families have different range tables, so each one has its own classifier. + return address.AddressFamily == AddressFamily.InterNetwork + ? IsPublicIPv4Address(address) + : IsPublicIPv6Address(address); + } + + /// + /// Normalizes the provided host, removing the brackets of an IPv6 literal and the trailing dot of a fully qualified name. + /// + /// The host to normalize. + /// The normalized host. + private static string NormalizeHost(string host) + { + // Uri.Host keeps the brackets around an IPv6 literal and may keep the trailing dot of a fully qualified name. Neither spelling changes the host. + return host.Trim('[', ']').TrimEnd('.'); + } + + /// + /// Resolves the addresses of the provided host, reusing a recent resolution when one is cached. + /// + /// The host to resolve. + /// Cancellation token that can be used to stop the execution. + /// The addresses the host resolves to, or an empty collection when it cannot be resolved. + /// + /// A cached resolution cannot open a hole in the guard, because every cached address is validated again before it is used, and the connection is made to + /// the validated address itself. A resolution failure is cached only briefly, so a temporary failure does not keep a host unusable for long. + /// + private async Task ResolveAddressesAsync(string host, CancellationToken cancellationToken) + { + DateTimeOffset now = DateTimeOffset.UtcNow; + // The cache key ignores case, a trailing dot and the IDN spelling, so every spelling of the same name shares one entry. + string cacheKey = NormalizeHostForComparison(host); + // A cached positive result avoids a second DNS lookup between the validation handler and the connect callback. + if (_addressesCache.TryGetValue(cacheKey, out CachedAddresses? cachedAddresses) && cachedAddresses.ExpiresOnUtc > now) + return cachedAddresses.Addresses; + + IPAddress[] addresses; + DateTimeOffset expiresOnUtc; + try + { + addresses = await _hostAddressResolver(host, cancellationToken).ConfigureAwait(false); + // A successful lookup is cached longer than a failure. An empty result is a failure too, because there is no address to connect to. + expiresOnUtc = now.AddSeconds(addresses.Length > 0 ? CACHED_ADDRESS_LIFETIME_IN_SECONDS : CACHED_ADDRESS_FAILURE_LIFETIME_IN_SECONDS); + } + catch (Exception exception) when (exception is SocketException or ArgumentException) + { + // A temporary DNS failure is cached only briefly, so the host becomes usable again quickly. Cancellation is not caught on purpose. + addresses = []; + expiresOnUtc = now.AddSeconds(CACHED_ADDRESS_FAILURE_LIFETIME_IN_SECONDS); + } + + // The cache is bounded. When it is full, expired entries are pruned first; if it is still full, this result is simply not cached. + if (_addressesCache.Count >= MAXIMUM_CACHED_HOST_COUNT) + RemoveExpiredCacheEntries(); + if (_addressesCache.Count < MAXIMUM_CACHED_HOST_COUNT) + _addressesCache[cacheKey] = new CachedAddresses(addresses, expiresOnUtc); + + return addresses; + } + + /// + /// Removes the cached resolutions whose lifetime expired, so the cache stays within its size limit. + /// + private void RemoveExpiredCacheEntries() + { + DateTimeOffset now = DateTimeOffset.UtcNow; + // The entries are removed one by one, because a concurrent dictionary cannot be cleared safely while it is being enumerated. + foreach (KeyValuePair cachedAddress in _addressesCache) + if (cachedAddress.Value.ExpiresOnUtc <= now) + _addressesCache.TryRemove(cachedAddress.Key, out _); + } + + /// + /// Adds the endpoint of the provided address to , unless the address is a duplicate or it is neither public nor allowed. + /// + /// The endpoints collected so far. + /// The address to add. + /// The port the address is paired with. + /// The host the address was resolved from. + /// The single host that was explicitly allowed to reach private or local addresses, when one was allowed. + /// The address is neither public nor allowed. + private static void AddEndPoint(List endPoints, IPAddress address, int port, string host, string? allowedPrivateHost) + { + // Mapped addresses are stored and compared in their IPv4 form, so the same endpoint is not added twice under two spellings. + if (address.IsIPv4MappedToIPv6) + address = address.MapToIPv4(); + + // The exception names the host but never the address, so an internal address does not reach the logs or the caller. + if (!IsAddressAllowed(host, address, allowedPrivateHost)) + throw new PublicHostRejectedException(host, GetRejectionReason(host, address, allowedPrivateHost)); + + // A host that resolves to the same address twice is only tried once. + if (!endPoints.Any(endPoint => endPoint.Address.Equals(address))) + endPoints.Add(new IPEndPoint(address, port)); + } + + /// + /// Evaluates the provided address against the outbound address policy. + /// + /// The host the address was resolved from. + /// The address to evaluate. + /// The single host that was explicitly allowed to reach private or local addresses, when one was allowed. + /// The outcome of the evaluation, with the reason of a rejection when the address may not be used. + private static PublicHostValidationResult EvaluateAddress(string host, IPAddress address, string? allowedPrivateHost) + { + if (IsAddressAllowed(host, address, allowedPrivateHost)) + return PublicHostValidationResult.Allowed; + return PublicHostValidationResult.Rejected(GetRejectionReason(host, address, allowedPrivateHost)); + } + + /// + /// Gets the reason the provided address was rejected, without exposing the address itself. + /// + /// The host the address was resolved from. + /// The rejected address. + /// The single host that was explicitly allowed to reach private or local addresses, when one was allowed. + /// The reason the address was rejected. + private static OutboundRequestRejectionReason GetRejectionReason(string host, IPAddress address, string? allowedPrivateHost) + { + // A link local or metadata address gets its own reason, so logs can distinguish it from a generic private address refusal. + if (allowedPrivateHost is not null && IsSameHost(host, allowedPrivateHost) && IsLinkLocalOrMetadataAddress(address)) + return OutboundRequestRejectionReason.LinkLocalOrMetadataAddress; + return OutboundRequestRejectionReason.AddressNotAllowed; + } + + /// + /// Determines whether the provided address is a link local or a cloud metadata address, which stay rejected even when the host is explicitly allowed to be private. + /// + /// The address to check. + /// when the address is a link local or cloud metadata address, otherwise . + private static bool IsLinkLocalOrMetadataAddress(IPAddress address) + { + if (address.IsIPv4MappedToIPv6) + address = address.MapToIPv4(); + + if (address.AddressFamily == AddressFamily.InterNetwork) + { + byte[] octets = address.GetAddressBytes(); + // 169.254.0.0/16 covers the common cloud metadata endpoints, and 100.100.100.200 is the Alibaba Cloud metadata endpoint. + return (octets[0] == 169 && octets[1] == 254) || (octets[0] == 100 && octets[1] == 100 && octets[2] == 100 && octets[3] == 200); + } + + // The IPv6 link local range covers the common metadata endpoints, but the AWS endpoint lives in a unique local range. + return address.IsIPv6LinkLocal || IsAwsMetadataAddress(address); + } + + /// + /// Determines whether the provided address is the IPv6 endpoint of the AWS instance metadata service, which lives in a unique local range and is therefore + /// not covered by the link local check. + /// + /// The address to check. + /// when the address is the AWS metadata endpoint, otherwise . + private static bool IsAwsMetadataAddress(IPAddress address) + { + if (address.AddressFamily != AddressFamily.InterNetworkV6) + return false; + + byte[] addressBytes = address.GetAddressBytes(); + // The AWS IMDSv6 endpoint is fd00:ec2::254, inside the fd00:ec2::/64 prefix. + return addressBytes[0] == 0xFD && addressBytes[1] == 0x00 && addressBytes[2] == 0x0E && addressBytes[3] == 0xC2 && + addressBytes[4] == 0 && addressBytes[5] == 0 && addressBytes[6] == 0 && addressBytes[7] == 0; + } + + /// + /// Determines whether the provided address may be used by the host, either because it is public, or because it is private and the host is the one explicitly allowed to be private. + /// + /// The host the address was resolved from. + /// The address to check. + /// The single host that was explicitly allowed to reach private or local addresses, when one was allowed. + /// when the address may be used, otherwise . + private static bool IsAddressAllowed(string host, IPAddress address, string? allowedPrivateHost) + { + // A public address is always allowed. + if (IsPublicAddress(address)) + return true; + + // A private address is allowed only for the single host the user opted into, never for another host a redirect might point at. + return allowedPrivateHost is not null && + IsSameHost(host, allowedPrivateHost) && + IsAllowedPrivateAddress(address); + } + + /// + /// Determines whether the provided host is the host that was explicitly allowed to reach private or local addresses. + /// + /// The host to check. + /// The host that was explicitly allowed to reach private or local addresses. + /// when the two hosts name the same host, otherwise . + /// + /// The comparison converts internationalized names to their punycode spelling, so the Unicode spelling a URI keeps is matched against the punycode spelling the connection authority uses. + /// + private static bool IsSameHost(string host, string allowedPrivateHost) + { + // Both sides go through the same normalization, so case, a trailing dot and the IDN spelling do not affect the comparison. + return string.Equals(NormalizeHostForComparison(host), NormalizeHostForComparison(allowedPrivateHost), StringComparison.OrdinalIgnoreCase); + } + + /// + /// Normalizes the provided host for comparison, using the punycode spelling of internationalized names. + /// + /// The host to normalize. + /// The normalized host. + private static string NormalizeHostForComparison(string host) + { + string normalizedHost = NormalizeHost(host); + // An IP literal is compared in its canonical text form, which is how both address families are represented. + if (IPAddress.TryParse(normalizedHost, out IPAddress? address)) + return address.ToString(); + try + { + // An internationalized name is compared in punycode, because that is the spelling the connection authority uses. + return new IdnMapping().GetAscii(normalizedHost).ToLowerInvariant(); + } + catch (ArgumentException) + { + // A malformed name cannot be converted. It is compared as lowercased text and will fail resolution later anyway. + return normalizedHost.ToLowerInvariant(); + } + } + + /// + /// Determines whether the provided non public address is a private or local address that a user may explicitly allow, which excludes the link local and cloud + /// metadata ranges even when such a permission was granted. + /// + /// The address to check. + /// when the address is a private address a user may allow, otherwise . + private static bool IsAllowedPrivateAddress(IPAddress address) + { + // This is the only place where a non public address becomes reachable. The accepted ranges are deliberately narrow. + if (address.IsIPv4MappedToIPv6) + address = address.MapToIPv4(); + if (address.AddressFamily == AddressFamily.InterNetwork) { byte[] octets = address.GetAddressBytes(); return octets[0] switch { - 0 => false, - 10 => false, - 100 when octets[1] is >= 64 and <= 127 => false, - 127 => false, - 169 when octets[1] == 254 => false, - 172 when octets[1] is >= 16 and <= 31 => false, - 192 when octets[1] == 168 => false, - _ => true + 10 => true, // The 10.0.0.0/8 private range. + 100 when octets[1] is >= 64 and <= 127 => !(octets[1] == 100 && octets[2] == 100 && octets[3] == 200), // Carrier grade NAT, except the Alibaba Cloud metadata endpoint. + 127 => true, // The loopback range, for a self hosted instance on the same machine. + 172 when octets[1] is >= 16 and <= 31 => true, // The 172.16.0.0/12 private range. + 192 when octets[1] == 168 => true, // The 192.168.0.0/16 private range. + _ => false }; } - if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal) + // Only the IPv6 loopback and unique local ranges can be allowed, except the AWS metadata endpoint, which lives in a unique local range but is never allowed. + return IPAddress.IsLoopback(address) || (address.IsIPv6UniqueLocal && !IsAwsMetadataAddress(address)); + } + + /// + /// Determines whether the provided IPv4 address is public. + /// + /// The IPv4 address to check. + /// when the address is public, otherwise . + private static bool IsPublicIPv4Address(IPAddress address) + { + // Each listed case is a range that must never be reached. Everything not listed is public. + byte[] octets = address.GetAddressBytes(); + return octets[0] switch + { + 0 => false, // The 0.0.0.0/8 "this network" range. + 10 => false, // The 10.0.0.0/8 private range. + 100 when octets[1] is >= 64 and <= 127 => false, // The 100.64.0.0/10 carrier grade NAT range. + 127 => false, // The 127.0.0.0/8 loopback range. + 169 when octets[1] == 254 => false, // The 169.254.0.0/16 link local range, including the cloud metadata endpoints. + 172 when octets[1] is >= 16 and <= 31 => false, // The 172.16.0.0/12 private range. + 192 when octets[1] == 168 => false, // The 192.168.0.0/16 private range. + 192 when octets[1] == 0 && (octets[2] is 0 or 2) => false, // The IETF protocol assignments and TEST-NET-1 documentation ranges. + 198 when octets[1] is >= 18 and <= 19 => false, // The 198.18.0.0/15 benchmarking range. + 198 when octets[1] == 51 && octets[2] == 100 => false, // The TEST-NET-2 documentation range. + 203 when octets[1] == 0 && octets[2] == 113 => false, // The TEST-NET-3 documentation range. + >= 224 => false, // The multicast range, the reserved range, and the broadcast address. + _ => true + }; + } + + /// + /// Determines whether the provided IPv6 address is public. + /// + /// The IPv6 address to check. + /// when the address is public, otherwise . + private static bool IsPublicIPv6Address(IPAddress address) + { + // Link local, site local, multicast, Teredo and unique local addresses are all internal, deprecated, multicast or transition ranges. + if (address.IsIPv6LinkLocal || address.IsIPv6SiteLocal || address.IsIPv6Multicast || address.IsIPv6Teredo || address.IsIPv6UniqueLocal) return false; byte[] addressBytes = address.GetAddressBytes(); - // The fc00::/7 unique local range is rejected, matching the private IPv4 ranges. - if ((addressBytes[0] & 0xFE) == 0xFC) + // The ::/96 IPv4 compatible and ::ffff:0:0/96 IPv4 translated ranges embed an IPv4 address, and the mapped form was already converted to IPv4, so no + // address with an all zero first eighty bits is public. + if (addressBytes[0] == 0 && addressBytes[1] == 0 && addressBytes[2] == 0 && addressBytes[3] == 0 && + addressBytes[4] == 0 && addressBytes[5] == 0 && addressBytes[6] == 0 && addressBytes[7] == 0 && + addressBytes[8] == 0 && addressBytes[9] == 0) return false; - return true; + // NAT64, the discard only range, the documentation range and 6to4 are not public destinations either. + return addressBytes[0] switch + { + 0x00 when addressBytes[1] == 0x64 && addressBytes[2] == 0xFF && addressBytes[3] == 0x9B => false, // The 64:ff9b::/96 NAT64 prefix, which can map to private IPv4 addresses. + 0x01 when addressBytes[1] == 0x00 && addressBytes[2] == 0x00 && addressBytes[3] == 0x00 => false, // The 100::/64 discard only range. + 0x20 when addressBytes[1] == 0x01 && addressBytes[2] == 0x0D && addressBytes[3] == 0xB8 => false, // The 2001:db8::/32 documentation range. + 0x20 when addressBytes[1] == 0x02 => false, // The 2002::/16 6to4 range. + _ => true + }; } + + /// + /// A resolved set of addresses, together with the time after which it must be resolved again. + /// + /// The addresses the host resolved to. + /// The time after which the resolution must be repeated. + private sealed record CachedAddresses(IPAddress[] Addresses, DateTimeOffset ExpiresOnUtc); } diff --git a/src/Lumina.Plugins.Contracts/Common/Http/OutboundRequestOptions.cs b/src/Lumina.Plugins.Contracts/Common/Http/OutboundRequestOptions.cs new file mode 100644 index 00000000..8ab9ee03 --- /dev/null +++ b/src/Lumina.Plugins.Contracts/Common/Http/OutboundRequestOptions.cs @@ -0,0 +1,27 @@ +#region ========================================================================= USING ===================================================================================== +using System.Net.Http; +#endregion + +namespace Lumina.Plugins.Contracts.Common.Http; + +/// +/// Options that a request may set to control how the host establishes the connection it is sent through. +/// +public static class OutboundRequestOptions +{ + /// + /// Gets the option that names the single host a request is allowed to reach private or local addresses on. A provider sets it only when the user + /// explicitly enabled a private base address for it, so the permission applies to that host alone and not to any other host a redirect could point at. + /// + /// + /// Even on the allowed host, the link local and cloud metadata ranges are never reachable, and only the private, loopback and carrier grade NAT ranges are + /// accepted, so enabling a private base address cannot be turned into a request to an unrelated internal service. + /// + public static HttpRequestOptionsKey AllowedPrivateHost { get; } = new(nameof(AllowedPrivateHost)); + + /// + /// Gets the option that disables the redirect handling of the host for a request whose client follows redirects itself. The host follows redirects by + /// default, and a client that sets this option receives the redirect response and applies its own policy instead. + /// + public static HttpRequestOptionsKey FollowRedirects { get; } = new(nameof(FollowRedirects)); +} diff --git a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs index 812750c8..7bd384dc 100644 --- a/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs +++ b/tests/SecurityTests/Lumina.Presentation.Api.SecurityTests/Core/MediaLibrary/Artwork/BookArtworkServiceSecurityTests.cs @@ -18,6 +18,8 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using NSubstitute; using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Sockets; #endregion namespace Lumina.Presentation.Api.SecurityTests.Core.MediaLibrary.Artwork; @@ -65,6 +67,55 @@ public class BookArtworkServiceSecurityTests _sut = scope.ServiceProvider.GetRequiredService(); } + [Theory] + [InlineData("http://169.254.169.254/latest/meta-data/")] // The link local cloud metadata endpoint. + [InlineData("http://10.0.0.5/cover.jpg")] // A private class A address. + [InlineData("http://[::1]/cover.jpg")] // The IPv6 loopback address. + public async Task SaveBookArtworkAsync_WhenRemoteArtworkPointsAtAPrivateAddress_ShouldNotDownloadIt(string remoteUrl) + { + // Arrange + using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10)); + + // Act + Result result = await _sut.SaveBookArtworkAsync( + Guid.NewGuid(), + Guid.NewGuid(), + "Library", + "Author", + "Title", + _artworkDtoFixture.Create(remoteUrl: remoteUrl), + cancellationTokenSource.Token); + + // Assert + Assert.True(result.IsFailure); + Assert.Equal(Errors.FileSystemManagement.FileNotFound, result.FirstError); + } + + [Fact] + public async Task SaveBookArtworkAsync_WhenRemoteArtworkPointsAtTheLoopbackAddress_ShouldNotConnectToIt() + { + // Arrange + using TcpListener listener = new(IPAddress.Loopback, 0); + listener.Start(); + int port = ((IPEndPoint)listener.LocalEndpoint).Port; + using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10)); + + // Act + Result result = await _sut.SaveBookArtworkAsync( + Guid.NewGuid(), + Guid.NewGuid(), + "Library", + "Author", + "Title", + _artworkDtoFixture.Create(remoteUrl: $"http://127.0.0.1:{port}/cover.jpg"), + cancellationTokenSource.Token); + + // Assert + // The real dependency injection container must reject the address before any connection is made, so nothing reaches the listener. + Assert.True(result.IsFailure); + Assert.False(listener.Pending()); + } + [Fact] public async Task SaveBookArtworkAsync_WhenLocalArtworkIsAReparsePoint_ShouldRejectIt() { diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs index 7da33091..ac0a8951 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/DependencyInjection/InfrastructureLayerServicesTests.cs @@ -12,6 +12,7 @@ using Lumina.Domain.Common.Events; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Cancellation; using Lumina.Domain.Core.BoundedContexts.LibraryManagementBoundedContext.LibraryScanAggregate.Services.Queue; using Lumina.Infrastructure.Common.DependencyInjection; +using Lumina.Infrastructure.Common.Networking; using Lumina.Infrastructure.Core.Authorization.Policies.ConsumptionActivity; using Lumina.Infrastructure.Core.MediaLibrary.AudioLibrary.MusicLibrary.Playback; using Lumina.Infrastructure.Core.Security; @@ -20,8 +21,10 @@ using Lumina.Plugins.Contracts.Core.Plugins; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; +using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Net.Http; #endregion namespace Lumina.Infrastructure.UnitTests.Common.DependencyInjection; @@ -73,6 +76,27 @@ public class InfrastructureLayerServicesTests Assert.Contains(services, descriptor => descriptor.ServiceType == typeof(IValidator)); } + [Fact] + public void AddInfrastructureLayerServices_WhenCalled_ShouldGuardEveryOutboundHttpClientWithThePublicHostChecks() + { + // Arrange + IServiceCollection services = new ServiceCollection(); + IConfiguration configuration = CreateConfiguration(); + services.AddInfrastructureLayerServices(configuration); + // A plugin registers its typed client after the infrastructure layer, so the defaults must reach it too. + services.AddHttpClient("plugin-client"); + using ServiceProvider serviceProvider = services.BuildServiceProvider(); + IHttpMessageHandlerFactory httpMessageHandlerFactory = serviceProvider.GetRequiredService(); + + // Act + using HttpMessageHandler pluginClientHandler = httpMessageHandlerFactory.CreateHandler("plugin-client"); + using HttpMessageHandler artworkClientHandler = httpMessageHandlerFactory.CreateHandler(NamedHttpClients.ARTWORK_DOWNLOAD); + + // Assert + AssertUsesThePublicHostGuards(pluginClientHandler); + AssertUsesThePublicHostGuards(artworkClientHandler); + } + /// /// Creates an in-memory configuration pointing the plugins directory to a non-existent folder, so no plugin assemblies are loaded. /// @@ -85,4 +109,52 @@ public class InfrastructureLayerServicesTests }; return new ConfigurationBuilder().AddInMemoryCollection(configurationValues).Build(); } + + /// + /// Asserts that the provided handler pipeline validates the host of every request, follows redirects only to public HTTPS hosts, and connects only to an + /// address checked to be public. + /// + /// The handler pipeline to check. + private static void AssertUsesThePublicHostGuards(HttpMessageHandler handler) + { + List delegatingHandlers = GetDelegatingHandlers(handler); + int validationIndex = delegatingHandlers.FindIndex(delegatingHandler => delegatingHandler is PublicHostValidationHandler); + int redirectIndex = delegatingHandlers.FindIndex(delegatingHandler => delegatingHandler is PublicHostRedirectHandler); + // The validation handler must run before the redirect handler, because the redirect handler follows a redirect below the validation handler. + Assert.True(validationIndex >= 0, "The public host validation handler must be part of the outbound pipeline."); + Assert.True(redirectIndex > validationIndex, "The public host validation handler must run before the public host redirect handler."); + SocketsHttpHandler primaryHandler = Assert.IsType(GetPrimaryHandler(handler)); + Assert.False(primaryHandler.AllowAutoRedirect); + Assert.NotNull(primaryHandler.ConnectCallback); + } + + /// + /// Gets the delegating handlers of the provided handler pipeline, from the outermost to the innermost one. + /// + /// The handler pipeline to walk. + /// The delegating handlers of the pipeline. + private static List GetDelegatingHandlers(HttpMessageHandler handler) + { + List delegatingHandlers = []; + HttpMessageHandler currentHandler = handler; + while (currentHandler is DelegatingHandler delegatingHandler) + { + delegatingHandlers.Add(delegatingHandler); + currentHandler = delegatingHandler.InnerHandler ?? throw new InvalidOperationException("The delegating handler has no inner handler."); + } + return delegatingHandlers; + } + + /// + /// Gets the primary, non delegating handler of the provided handler pipeline. + /// + /// The handler pipeline to walk. + /// The primary handler of the pipeline. + private static HttpMessageHandler GetPrimaryHandler(HttpMessageHandler handler) + { + HttpMessageHandler currentHandler = handler; + while (currentHandler is DelegatingHandler delegatingHandler) + currentHandler = delegatingHandler.InnerHandler ?? throw new InvalidOperationException("The delegating handler has no inner handler."); + return currentHandler; + } } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostConnectionGuardTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostConnectionGuardTests.cs new file mode 100644 index 00000000..66475cf9 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostConnectionGuardTests.cs @@ -0,0 +1,275 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Networking; +using Lumina.Infrastructure.Common.Networking; +using Lumina.Plugins.Contracts.Common.Http; +using Microsoft.Extensions.Logging.Abstractions; +using System; +using System.Diagnostics.CodeAnalysis; +using System.IO; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Networking; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PublicHostConnectionGuardTests +{ + private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34"); + + [Fact] + public void CreatePrimaryHandler_WhenCalled_ShouldDisableAutomaticRedirectsAndInstallTheConnectGuard() + { + // Arrange + PublicHostValidator publicHostValidator = CreateValidator(host => [s_publicAddress]); + + // Act + using SocketsHttpHandler handler = PublicHostConnectionGuard.CreatePrimaryHandler(publicHostValidator, NullLogger.Instance); + + // Assert + Assert.False(handler.AllowAutoRedirect); + Assert.False(handler.UseProxy); + Assert.NotNull(handler.ConnectCallback); + // The callback behavior itself is covered by CreatePrimaryHandler_WhenARequestConnects_ShouldUseTheAllowedPrivateHostOfTheInitialRequest. + } + + [Fact] + public async Task ConnectAsync_WhenTheHostResolvesToOnePrivateAddress_ShouldThrowWithoutConnecting() + { + // Arrange + PublicHostValidator publicHostValidator = CreateValidator(host => [s_publicAddress, IPAddress.Parse("10.0.0.5")]); + + // Act + Task Act() + { + return PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "mixed.example.com", 443, request: null, NullLogger.Instance, CancellationToken.None).AsTask(); + } + + // Assert + PublicHostRejectedException exception = await Assert.ThrowsAsync(Act); + Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason); + } + + [Fact] + public async Task ConnectAsync_WhenTheRequestUriHasAUnicodeIdnHostAndTheConnectionUsesThePunycodeHost_ShouldValidateTheResolvedAddress() + { + // Arrange + // Uri.Host keeps the Unicode spelling of an internationalized name, while the connection authority uses its punycode spelling. The two must never be + // compared to decide whether a connection goes to a proxy, because an attacker controlled name could otherwise skip the address check. + PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]); + using HttpRequestMessage request = new(HttpMethod.Get, "https://bücher.example/cover.jpg"); + + // Act + Task Act() + { + return PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "xn--bcher-kva.example", 1, request, NullLogger.Instance, CancellationToken.None).AsTask(); + } + + // Assert + PublicHostRejectedException exception = await Assert.ThrowsAsync(Act); + Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason); + Assert.DoesNotContain("127.0.0.1", exception.Message); + } + + [Fact] + public async Task ConnectAsync_WhenAnotherHostResolvesToAPrivateAddress_ShouldThrowWithoutConnecting() + { + // Arrange + PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]); + using HttpRequestMessage request = new(HttpMethod.Get, "http://other.internal.example.com/cover.jpg"); + request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "internal.example.com"); + + // Act + Task Act() + { + return PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "other.internal.example.com", 443, request, NullLogger.Instance, CancellationToken.None).AsTask(); + } + + // Assert + PublicHostRejectedException exception = await Assert.ThrowsAsync(Act); + Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason); + } + + [Fact] + public async Task ConnectAsync_WhenTheAllowedPrivateHostResolvesToTheLinkLocalMetadataAddress_ShouldThrowWithoutConnecting() + { + // Arrange + PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Parse("169.254.169.254")]); + using HttpRequestMessage request = new(HttpMethod.Get, "http://internal.example.com/cover.jpg"); + request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "internal.example.com"); + + // Act + Task Act() + { + return PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "internal.example.com", 443, request, NullLogger.Instance, CancellationToken.None).AsTask(); + } + + // Assert + PublicHostRejectedException exception = await Assert.ThrowsAsync(Act); + Assert.Equal(OutboundRequestRejectionReason.LinkLocalOrMetadataAddress, exception.RejectionReason); + } + + [Fact] + public async Task ConnectAsync_WhenTheFirstAddressIsUnreachable_ShouldConnectToTheNextAddress() + { + // Arrange + using TcpListener listener = new(IPAddress.Loopback, 0); + listener.Start(); + int port = ((IPEndPoint)listener.LocalEndpoint).Port; + // 10.0.0.1 is a private address that no test service listens on, so the loopback address wins the staggered race. + PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Parse("10.0.0.1"), IPAddress.Loopback]); + using HttpRequestMessage request = new(HttpMethod.Get, "http://mixed.example.com/cover.jpg"); + request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "mixed.example.com"); + using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10)); + + // Act + Task connectTask = PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "mixed.example.com", port, request, NullLogger.Instance, CancellationToken.None).AsTask(); + (TcpClient acceptedClient, Stream stream) = await AcceptConnectionAsync(listener, connectTask, cancellationTokenSource); + using (acceptedClient) + using (stream) + { + // Assert + Assert.True(stream.CanWrite); + } + } + + [Fact] + public async Task CreatePrimaryHandler_WhenTheConnectPolicyRejectsTheAddress_ShouldWrapThePolicyRejectionAsAConnectionError() + { + // Arrange + PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]); + using SocketsHttpHandler handler = PublicHostConnectionGuard.CreatePrimaryHandler(publicHostValidator, NullLogger.Instance); + using HttpClient client = new(handler); + using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10)); + + // Act + Task Act() + { + return client.GetAsync("http://internal.example.com/", cancellationTokenSource.Token); + } + + // Assert + HttpRequestException exception = await Assert.ThrowsAsync(Act); + Assert.Equal(HttpRequestError.ConnectionError, exception.HttpRequestError); + PublicHostRejectedException innerException = Assert.IsType(exception.InnerException); + Assert.Equal(HttpRequestError.ConfigurationLimitExceeded, innerException.HttpRequestError); + Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, innerException.RejectionReason); + } + + [Fact] + public async Task CreatePrimaryHandler_WhenARequestConnects_ShouldUseTheAllowedPrivateHostOfTheInitialRequest() + { + // Arrange + using TcpListener listener = new(IPAddress.Loopback, 0); + listener.Start(); + int port = ((IPEndPoint)listener.LocalEndpoint).Port; + PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]); + using SocketsHttpHandler handler = PublicHostConnectionGuard.CreatePrimaryHandler(publicHostValidator, NullLogger.Instance); + using HttpClient client = new(handler); + using HttpRequestMessage request = new(HttpMethod.Get, $"http://internal.example.com:{port}/"); + request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "internal.example.com"); + using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10)); + + // Act + Task requestTask = client.SendAsync(request, cancellationTokenSource.Token); + Task acceptTask = listener.AcceptTcpClientAsync(cancellationTokenSource.Token).AsTask(); + try + { + Task firstCompletedTask = await Task.WhenAny(requestTask, acceptTask); + // Await the request first when it completed, so a failure to connect surfaces its own exception instead of the accept timeout. + if (firstCompletedTask == requestTask) + await requestTask; + + using TcpClient acceptedClient = await acceptTask; + using NetworkStream stream = acceptedClient.GetStream(); + byte[] responseBytes = Encoding.ASCII.GetBytes("HTTP/1.1 200 OK\r\nContent-Length: 0\r\nConnection: close\r\n\r\n"); + await stream.WriteAsync(responseBytes, cancellationTokenSource.Token); + using HttpResponseMessage response = await requestTask; + + // Assert + // The connect callback resolved the host through the validator and read the allowed private host from the initial request message, because + // without that option the loopback address would have been rejected and the connection would never have been accepted. + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + } + finally + { + cancellationTokenSource.Cancel(); + } + } + + [Fact] + public async Task ConnectAsync_WhenTheRequestAllowsPrivateEndPoints_ShouldConnectToThePrivateAddress() + { + // Arrange + using TcpListener listener = new(IPAddress.Loopback, 0); + listener.Start(); + int port = ((IPEndPoint)listener.LocalEndpoint).Port; + PublicHostValidator publicHostValidator = CreateValidator(host => [IPAddress.Loopback]); + using HttpRequestMessage request = new(HttpMethod.Get, "http://internal.example.com/cover.jpg"); + request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "internal.example.com"); + using CancellationTokenSource cancellationTokenSource = new(TimeSpan.FromSeconds(10)); + + // Act + Task connectTask = PublicHostConnectionGuard.ConnectAsync(publicHostValidator, "internal.example.com", port, request, NullLogger.Instance, CancellationToken.None).AsTask(); + (TcpClient acceptedClient, Stream stream) = await AcceptConnectionAsync(listener, connectTask, cancellationTokenSource); + using (acceptedClient) + using (stream) + { + // Assert + Assert.True(stream.CanWrite); + } + } + + /// + /// Accepts the connection made by , surfacing a connection failure instead of waiting for the accept timeout. + /// + /// The listener that accepts the connection. + /// The task that establishes the connection. + /// The cancellation token source that bounds the accept. + /// The accepted client and the established stream. + private static async Task<(TcpClient AcceptedClient, Stream Stream)> AcceptConnectionAsync(TcpListener listener, Task connectTask, CancellationTokenSource cancellationTokenSource) + { + Task acceptTask = listener.AcceptTcpClientAsync(cancellationTokenSource.Token).AsTask(); + try + { + Task firstCompletedTask = await Task.WhenAny(connectTask, acceptTask).ConfigureAwait(false); + // Await the connect task first when it completed, so a failure to connect surfaces its own exception instead of the accept timeout. + if (firstCompletedTask == connectTask) + await connectTask.ConfigureAwait(false); + + TcpClient acceptedClient = await acceptTask.ConfigureAwait(false); + Stream stream = await connectTask.ConfigureAwait(false); + return (acceptedClient, stream); + } + catch + { + cancellationTokenSource.Cancel(); + try + { + await acceptTask.ConfigureAwait(false); + } + catch + { + // The accept was canceled because the connection failed; its exception must not mask the connection failure. + } + throw; + } + } + + /// + /// Creates a whose host name resolution is replaced by the provided resolver. + /// + /// The resolver that produces the addresses of a host name. + /// The created validator. + private static PublicHostValidator CreateValidator(Func addressResolver) + { + return new PublicHostValidator((host, cancellationToken) => Task.FromResult(addressResolver(host))); + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostRedirectHandlerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostRedirectHandlerTests.cs index 1c95cd60..31e5575b 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostRedirectHandlerTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostRedirectHandlerTests.cs @@ -1,10 +1,14 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Networking; using Lumina.Infrastructure.Common.Networking; +using Lumina.Plugins.Contracts.Common.Http; +using Microsoft.Extensions.Logging.Abstractions; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Net; using System.Net.Http; +using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; #endregion @@ -17,48 +21,12 @@ namespace Lumina.Infrastructure.UnitTests.Common.Networking; [ExcludeFromCodeCoverage] public class PublicHostRedirectHandlerTests { - [Fact] - public async Task SendAsync_WhenTheInitialRequestHostIsPublic_ShouldSendTheRequest() - { - // Arrange - StubHttpMessageHandler innerHandler = new((request, callIndex) => new HttpResponseMessage(HttpStatusCode.OK)); - using HttpClient client = CreateClient(innerHandler); + private const string PRIVATE_HOST = "internal.example.com"; - // Act - HttpResponseMessage response = await client.GetAsync("https://example.com/cover.jpg"); - - // Assert - Assert.Equal(HttpStatusCode.OK, response.StatusCode); - Assert.Equal(1, innerHandler.CallCount); - } - - [Theory] - [InlineData("http://127.0.0.1/cover.jpg")] // The IPv4 loopback address. - [InlineData("http://localhost/cover.jpg")] // The loopback host name. - [InlineData("http://[::1]/cover.jpg")] // The IPv6 loopback address. - [InlineData("http://169.254.169.254/latest/meta-data/")] // The link local cloud metadata endpoint. - [InlineData("http://10.0.0.5/cover.jpg")] // A private class A address. - [InlineData("http://172.16.0.1/cover.jpg")] // A private class B address. - [InlineData("http://192.168.1.10/cover.jpg")] // A private class C address. - public async Task SendAsync_WhenTheInitialRequestHostIsPrivateOrLocal_ShouldThrowAndNotSendTheRequest(string url) - { - // Arrange - StubHttpMessageHandler innerHandler = new((request, callIndex) => new HttpResponseMessage(HttpStatusCode.OK)); - using HttpClient client = CreateClient(innerHandler); - - // Act - Task Act() - { - return client.GetAsync(url); - } - - // Assert - await Assert.ThrowsAsync(Act); - Assert.Equal(0, innerHandler.CallCount); - } + private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34"); [Fact] - public async Task SendAsync_WhenTheInitialRequestRedirectsToAPublicHttpsHost_ShouldFollowIt() + public async Task SendAsync_WhenTheResponseRedirectsToAPublicHttpsHost_ShouldFollowIt() { // Arrange StubHttpMessageHandler innerHandler = new((request, callIndex) => @@ -82,6 +50,29 @@ public class PublicHostRedirectHandlerTests Assert.Equal("archive.org", innerHandler.Requests[1].RequestUri!.Host); } + [Fact] + public async Task SendAsync_WhenTheResponseRedirectsToAPrivateHostName_ShouldThrow() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri($"https://{PRIVATE_HOST}/index.json"); + return redirect; + }); + using HttpClient client = CreateClient(innerHandler); + + // Act + Task Act() + { + return client.GetAsync("https://coverartarchive.org/release/1"); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(1, innerHandler.CallCount); + } + [Theory] [InlineData("http://archive.org/index.json")] // A downgrade of a trusted host to plain HTTP. [InlineData("https://127.0.0.1/index.json")] // The IPv4 loopback address. @@ -89,7 +80,7 @@ public class PublicHostRedirectHandlerTests [InlineData("https://169.254.169.254/latest/meta-data/")] // The link local cloud metadata endpoint. [InlineData("https://10.0.0.5/index.json")] // A private class A address. [InlineData("https://192.168.1.10/index.json")] // A private class C address. - public async Task SendAsync_WhenTheInitialRequestRedirectsToADisallowedTarget_ShouldThrow(string location) + public async Task SendAsync_WhenTheResponseRedirectsToADisallowedTarget_ShouldThrow(string location) { // Arrange StubHttpMessageHandler innerHandler = new((request, callIndex) => @@ -107,7 +98,55 @@ public class PublicHostRedirectHandlerTests } // Assert - await Assert.ThrowsAsync(Act); + await Assert.ThrowsAsync(Act); + Assert.Equal(1, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenTheRequestAllowsPrivateEndPointsAndRedirectsToAPrivateHost_ShouldFollowIt() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + if (callIndex == 1) + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri($"https://{PRIVATE_HOST}/index.json"); + return redirect; + } + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using HttpClient client = CreateClient(innerHandler); + using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/start"); + request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST); + + // Act + using HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(2, innerHandler.CallCount); + Assert.Equal(PRIVATE_HOST, innerHandler.Requests[1].RequestUri!.Host); + } + + [Fact] + public async Task SendAsync_WhenARequestWithABodyIsRedirected_ShouldReturnTheRedirectResponseWithoutFollowingIt() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("https://archive.org/index.json"); + return redirect; + }); + using HttpClient client = CreateClient(innerHandler); + using HttpRequestMessage request = new(HttpMethod.Post, "https://coverartarchive.org/release/1"); + + // Act + using HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.TemporaryRedirect, response.StatusCode); Assert.Equal(1, innerHandler.CallCount); } @@ -130,11 +169,207 @@ public class PublicHostRedirectHandlerTests } // Assert - await Assert.ThrowsAsync(Act); + await Assert.ThrowsAsync(Act); // The initial request plus the maximum number of followed redirects are sent before the loop is detected. Assert.Equal(6, innerHandler.CallCount); } + [Fact] + public async Task SendAsync_WhenTheRequestDisablesRedirectFollowing_ShouldReturnTheRedirectResponseWithoutFollowingIt() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("https://archive.org/index.json"); + return redirect; + }); + using HttpClient client = CreateClient(innerHandler); + using HttpRequestMessage request = new(HttpMethod.Get, "https://coverartarchive.org/release/1"); + request.Options.Set(OutboundRequestOptions.FollowRedirects, false); + + // Act + using HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.TemporaryRedirect, response.StatusCode); + Assert.Equal("https://archive.org/index.json", response.Headers.Location!.AbsoluteUri); + Assert.Equal(1, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenTheRedirectPointsAtAnotherPrivateHostThanTheAllowedOne_ShouldThrow() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("https://another.internal.example.com/index.json"); + return redirect; + }); + using HttpClient client = CreateClient(innerHandler); + using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/start"); + request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST); + + // Act + Task Act() + { + return client.SendAsync(request); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(1, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenARedirectCrossesOrigins_ShouldNotForwardCredentialsOrHopByHopHeaders() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + if (callIndex == 1) + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("https://archive.org/index.json"); + return redirect; + } + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using HttpClient client = CreateClient(innerHandler); + using HttpRequestMessage request = new(HttpMethod.Get, "https://coverartarchive.org/start"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "secret"); + request.Headers.TryAddWithoutValidation("Cookie", "session=secret"); + request.Headers.TryAddWithoutValidation("Proxy-Authorization", "Basic secret"); + request.Headers.Host = "coverartarchive.org"; + request.Headers.TryAddWithoutValidation("Connection", "keep-alive"); + request.Headers.TryAddWithoutValidation("Keep-Alive", "timeout=5"); + request.Headers.TryAddWithoutValidation("TE", "trailers"); + request.Headers.TryAddWithoutValidation("Upgrade", "h2c"); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + + // Act + using HttpResponseMessage response = await client.SendAsync(request); + + // Assert + HttpRequestMessage redirectedRequest = innerHandler.Requests[1]; + Assert.Null(redirectedRequest.Headers.Authorization); + Assert.False(redirectedRequest.Headers.Contains("Cookie")); + Assert.False(redirectedRequest.Headers.Contains("Proxy-Authorization")); + Assert.Null(redirectedRequest.Headers.Host); + Assert.False(redirectedRequest.Headers.Contains("Connection")); + Assert.False(redirectedRequest.Headers.Contains("Keep-Alive")); + Assert.False(redirectedRequest.Headers.Contains("TE")); + Assert.False(redirectedRequest.Headers.Contains("Upgrade")); + Assert.Contains("application/json", redirectedRequest.Headers.Accept.ToString()); + } + + [Fact] + public async Task SendAsync_WhenARedirectStaysOnTheSameOrigin_ShouldKeepCredentialsButDropHopByHopHeaders() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + if (callIndex == 1) + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("https://coverartarchive.org/index.json"); + return redirect; + } + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using HttpClient client = CreateClient(innerHandler); + using HttpRequestMessage request = new(HttpMethod.Get, "https://coverartarchive.org/start"); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", "secret"); + request.Headers.TryAddWithoutValidation("Cookie", "session=secret"); + request.Headers.TryAddWithoutValidation("Connection", "keep-alive"); + + // Act + using HttpResponseMessage response = await client.SendAsync(request); + + // Assert + HttpRequestMessage redirectedRequest = innerHandler.Requests[1]; + Assert.Equal("Bearer secret", redirectedRequest.Headers.Authorization!.ToString()); + string cookieHeader = Assert.Single(redirectedRequest.Headers.GetValues("Cookie")); + Assert.Equal("session=secret", cookieHeader); + Assert.False(redirectedRequest.Headers.Contains("Connection")); + } + + [Fact] + public async Task SendAsync_WhenAHeadRequestIsRedirected_ShouldFollowIt() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + if (callIndex == 1) + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("https://archive.org/index.json"); + return redirect; + } + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using HttpClient client = CreateClient(innerHandler); + using HttpRequestMessage request = new(HttpMethod.Head, "https://coverartarchive.org/release/1"); + + // Act + using HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(2, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenAnAllowedPrivateHostRedirectsToItselfAcrossMultipleHops_ShouldKeepThePermission() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + if (callIndex <= 2) + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri(callIndex == 1 ? $"https://{PRIVATE_HOST}/second" : $"https://{PRIVATE_HOST}/third"); + return redirect; + } + return new HttpResponseMessage(HttpStatusCode.OK); + }); + using HttpClient client = CreateClient(innerHandler); + using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/start"); + request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST); + + // Act + using HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(3, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenTheResponseRedirectsToPlainHttp_ShouldThrowAPublicHostRejectedException() + { + // Arrange + StubHttpMessageHandler innerHandler = new((request, callIndex) => + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri("http://archive.org/index.json"); + return redirect; + }); + using HttpClient client = CreateClient(innerHandler); + + // Act + Task Act() + { + return client.GetAsync("https://coverartarchive.org/release/1"); + } + + // Assert + PublicHostRejectedException exception = await Assert.ThrowsAsync(Act); + Assert.Equal(OutboundRequestRejectionReason.RedirectSchemeNotHttps, exception.RejectionReason); + Assert.Equal(1, innerHandler.CallCount); + } + /// /// Creates an whose requests are sent through the handler under test, wrapping the provided inner handler. /// @@ -142,7 +377,9 @@ public class PublicHostRedirectHandlerTests /// The created client. private static HttpClient CreateClient(HttpMessageHandler innerHandler) { - PublicHostRedirectHandler handler = new() { InnerHandler = innerHandler }; + PublicHostValidator publicHostValidator = new((host, cancellationToken) => + Task.FromResult(host.Contains("internal.example.com", StringComparison.OrdinalIgnoreCase) ? [IPAddress.Parse("10.0.0.5")] : [s_publicAddress])); + PublicHostRedirectHandler handler = new(publicHostValidator, NullLogger.Instance) { InnerHandler = innerHandler }; return new HttpClient(handler); } diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidationHandlerTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidationHandlerTests.cs new file mode 100644 index 00000000..277e2909 --- /dev/null +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidationHandlerTests.cs @@ -0,0 +1,239 @@ +#region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Networking; +using Lumina.Infrastructure.Common.Networking; +using Lumina.Plugins.Contracts.Common.Http; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Logging.Abstractions; +using NSubstitute; +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; +#endregion + +namespace Lumina.Infrastructure.UnitTests.Common.Networking; + +/// +/// Contains unit tests for the class. +/// +[ExcludeFromCodeCoverage] +public class PublicHostValidationHandlerTests +{ + private const string PRIVATE_HOST = "internal.example.com"; + + private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34"); + + [Fact] + public async Task SendAsync_WhenTheHostIsPublic_ShouldSendTheRequest() + { + // Arrange + StubHttpMessageHandler innerHandler = new(); + using HttpClient client = CreateClient(innerHandler); + + // Act + using HttpResponseMessage response = await client.GetAsync("https://example.com/cover.jpg"); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(1, innerHandler.CallCount); + } + + [Theory] + [InlineData("http://127.0.0.1/cover.jpg")] // The IPv4 loopback address. + [InlineData("http://localhost/cover.jpg")] // The loopback host name. + [InlineData("http://[::1]/cover.jpg")] // The IPv6 loopback address. + [InlineData("http://169.254.169.254/latest/meta-data/")] // The link local cloud metadata endpoint. + [InlineData("http://10.0.0.5/cover.jpg")] // A private class A address. + [InlineData("http://172.16.0.1/cover.jpg")] // A private class B address. + [InlineData("http://192.168.1.10/cover.jpg")] // A private class C address. + public async Task SendAsync_WhenTheHostIsPrivateOrLocal_ShouldThrowAndNotSendTheRequest(string url) + { + // Arrange + StubHttpMessageHandler innerHandler = new(); + using HttpClient client = CreateClient(innerHandler); + + // Act + Task Act() + { + return client.GetAsync(url); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(0, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenTheHostNameResolvesToOnePrivateAddress_ShouldThrowAndNotSendTheRequest() + { + // Arrange + StubHttpMessageHandler innerHandler = new(); + using HttpClient client = CreateClient(innerHandler); + + // Act + Task Act() + { + return client.GetAsync($"https://{PRIVATE_HOST}/cover.jpg"); + } + + // Assert + PublicHostRejectedException exception = await Assert.ThrowsAsync(Act); + Assert.Equal(OutboundRequestRejectionReason.AddressNotAllowed, exception.RejectionReason); + Assert.Contains(PRIVATE_HOST, exception.Message); + Assert.DoesNotContain("10.0.0.5", exception.Message); + Assert.Equal(0, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenTheHostCannotBeResolved_ShouldThrowAPublicHostResolutionException() + { + // Arrange + StubHttpMessageHandler innerHandler = new(); + PublicHostValidator validator = new((host, cancellationToken) => throw new SocketException((int)SocketError.HostNotFound)); + PublicHostValidationHandler handler = new(validator, NullLogger.Instance) { InnerHandler = innerHandler }; + using HttpClient client = new(handler); + + // Act + Task Act() + { + return client.GetAsync("https://missing.example.com/cover.jpg"); + } + + // Assert + PublicHostResolutionException exception = await Assert.ThrowsAsync(Act); + Assert.Equal(HttpRequestError.NameResolutionError, exception.HttpRequestError); + Assert.Equal(0, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenTheHostIsRejected_ShouldLogAWarning() + { + // Arrange + ILogger mockLogger = Substitute.For>(); + StubHttpMessageHandler innerHandler = new(); + PublicHostValidationHandler handler = new(CreateValidator(), mockLogger) { InnerHandler = innerHandler }; + using HttpClient client = new(handler); + + // Act + Task Act() + { + return client.GetAsync($"https://{PRIVATE_HOST}/cover.jpg"); + } + + // Assert + await Assert.ThrowsAsync(Act); + mockLogger.Received(1).Log( + LogLevel.Warning, + Arg.Any(), + Arg.Any(), + Arg.Any(), + Arg.Any>()); + } + + [Fact] + public async Task SendAsync_WhenTheRequestAllowsPrivateEndPointsForTheHost_ShouldSendTheRequest() + { + // Arrange + StubHttpMessageHandler innerHandler = new(); + using HttpClient client = CreateClient(innerHandler); + using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/cover.jpg"); + request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, PRIVATE_HOST); + + // Act + using HttpResponseMessage response = await client.SendAsync(request); + + // Assert + Assert.Equal(HttpStatusCode.OK, response.StatusCode); + Assert.Equal(1, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenTheRequestAllowsPrivateEndPointsForAnotherHost_ShouldThrowAndNotSendTheRequest() + { + // Arrange + StubHttpMessageHandler innerHandler = new(); + using HttpClient client = CreateClient(innerHandler); + using HttpRequestMessage request = new(HttpMethod.Get, $"https://{PRIVATE_HOST}/cover.jpg"); + request.Options.Set(OutboundRequestOptions.AllowedPrivateHost, "another.internal.example.com"); + + // Act + Task Act() + { + return client.SendAsync(request); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(0, innerHandler.CallCount); + } + + [Fact] + public async Task SendAsync_WhenTheRequestHasNoAbsoluteUri_ShouldThrowAndNotSendTheRequest() + { + // Arrange + StubHttpMessageHandler innerHandler = new(); + PublicHostValidationHandler handler = new(CreateValidator(), NullLogger.Instance) { InnerHandler = innerHandler }; + using HttpMessageInvoker invoker = new(handler); + + // Act + Task Act() + { + return invoker.SendAsync(new HttpRequestMessage(HttpMethod.Get, "/relative"), CancellationToken.None); + } + + // Assert + PublicHostRejectedException exception = await Assert.ThrowsAsync(Act); + Assert.Equal(OutboundRequestRejectionReason.RequestHasNoAbsoluteUri, exception.RejectionReason); + Assert.Equal(0, innerHandler.CallCount); + } + + /// + /// Creates an whose requests are sent through the handler under test, wrapping the provided inner handler. + /// + /// The handler that answers the requests that reach the network. + /// The created client. + private static HttpClient CreateClient(HttpMessageHandler innerHandler) + { + PublicHostValidationHandler handler = new(CreateValidator(), NullLogger.Instance) { InnerHandler = innerHandler }; + return new HttpClient(handler); + } + + /// + /// Creates a that classifies as private and every other host name as public. + /// + /// The created validator. + private static PublicHostValidator CreateValidator() + { + return new PublicHostValidator((host, cancellationToken) => + Task.FromResult(string.Equals(host, PRIVATE_HOST, StringComparison.OrdinalIgnoreCase) ? [IPAddress.Parse("10.0.0.5")] : [s_publicAddress])); + } + + /// + /// Test HTTP message handler that answers every request with a successful response and records how many requests were sent to it. + /// + [ExcludeFromCodeCoverage] + private sealed class StubHttpMessageHandler : HttpMessageHandler + { + private int _callCount; + + /// + /// Gets the number of requests that were sent through the handler. + /// + public int CallCount => _callCount; + + /// + /// Sends the provided request, producing a successful response. + /// + /// The request to send. + /// Cancellation token that can be used to stop the execution. + /// The response produced for the request. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + Interlocked.Increment(ref _callCount); + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK)); + } + } +} diff --git a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidatorTests.cs b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidatorTests.cs index a77fbf48..3616bcf4 100644 --- a/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidatorTests.cs +++ b/tests/UnitTests/Lumina.Infrastructure.UnitTests/Common/Networking/PublicHostValidatorTests.cs @@ -1,6 +1,14 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Domain.SharedKernel.Common.Enums.Networking; using Lumina.Infrastructure.Common.Networking; +using System; +using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Net; +using System.Net.Http; +using System.Net.Sockets; +using System.Threading; +using System.Threading.Tasks; #endregion namespace Lumina.Infrastructure.UnitTests.Common.Networking; @@ -11,21 +19,28 @@ namespace Lumina.Infrastructure.UnitTests.Common.Networking; [ExcludeFromCodeCoverage] public class PublicHostValidatorTests { + private static readonly IPAddress s_publicAddress = IPAddress.Parse("93.184.216.34"); + [Theory] - [InlineData("coverartarchive.org")] // A public host name. - [InlineData("example.com")] // A public host name. [InlineData("8.8.8.8")] // A public IPv4 address. [InlineData("1.1.1.1")] // A public IPv4 address. [InlineData("172.15.0.1")] // The address just below the private class B range. [InlineData("172.32.0.1")] // The address just above the private class B range. + [InlineData("100.63.255.255")] // The address just below the carrier grade NAT range. + [InlineData("100.128.0.1")] // The address just above the carrier grade NAT range. [InlineData("2606:4700:4700::1111")] // A public IPv6 address. - public void IsPublicHost_WhenTheHostIsPublic_ShouldReturnTrue(string host) + [InlineData("[2606:4700:4700::1111]")] // A public IPv6 address, bracketed like a URI host. + [InlineData("::ffff:93.184.216.34")] // An IPv4-mapped public IPv4 address. + public async Task ValidateHostAsync_WhenTheHostIsAPublicAddress_ShouldReturnTrue(string host) { + // Arrange + PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved.")); + // Act - bool result = PublicHostValidator.IsPublicHost(host); + PublicHostValidationResult result = await sut.ValidateHostAsync(host, allowedPrivateHost: null, CancellationToken.None); // Assert - Assert.True(result); + Assert.True(result.IsAllowed); } [Theory] @@ -40,19 +55,448 @@ public class PublicHostValidatorTests [InlineData("[::]")] // The unspecified IPv6 address. [InlineData("169.254.169.254")] // The link local cloud metadata endpoint. [InlineData("10.0.0.5")] // A private class A address. + [InlineData("::ffff:10.0.0.5")] // A private class A address, in its IPv4-mapped IPv6 form. [InlineData("172.16.0.1")] // The lower bound of the private class B range. [InlineData("172.31.255.255")] // The upper bound of the private class B range. [InlineData("192.168.1.10")] // A private class C address. [InlineData("100.64.0.1")] // The lower bound of the carrier grade NAT range. [InlineData("100.127.255.255")] // The upper bound of the carrier grade NAT range. + [InlineData("192.0.2.10")] // The TEST-NET-1 documentation range. + [InlineData("198.18.0.1")] // The benchmarking range. + [InlineData("198.51.100.10")] // The TEST-NET-2 documentation range. + [InlineData("203.0.113.10")] // The TEST-NET-3 documentation range. + [InlineData("224.0.0.1")] // The multicast range. + [InlineData("240.0.0.1")] // The reserved range. + [InlineData("255.255.255.255")] // The broadcast address. [InlineData("fc00::1")] // The IPv6 unique local range. + [InlineData("fd00:ec2::254")] // The AWS IMDSv6 endpoint, which lives in a unique local range. [InlineData("fe80::1")] // The IPv6 link local range. - public void IsPublicHost_WhenTheHostIsPrivateOrLocal_ShouldReturnFalse(string host) + [InlineData("2001:db8::1")] // The IPv6 documentation range. + [InlineData("::127.0.0.1")] // An IPv4 compatible IPv6 address. + [InlineData("64:ff9b:1::1")] // The local use NAT64 prefix. + [InlineData("2002::1")] // The IPv6 6to4 range. + [InlineData("64:ff9b::1")] // The IPv6 NAT64 prefix. + [InlineData("100::1")] // The IPv6 discard only range. + [InlineData("ff02::1")] // The IPv6 multicast range. + public async Task ValidateHostAsync_WhenTheHostIsPrivateOrLocal_ShouldReturnFalse(string host) { + // Arrange + PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved.")); + // Act - bool result = PublicHostValidator.IsPublicHost(host); + PublicHostValidationResult result = await sut.ValidateHostAsync(host, allowedPrivateHost: null, CancellationToken.None); // Assert - Assert.False(result); + Assert.False(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheAllowedPrivateHostIsAnIPv4MappedPrivateAddress_ShouldReturnTrue() + { + // Arrange + PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved.")); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("::ffff:10.0.0.5", allowedPrivateHost: "::ffff:10.0.0.5", CancellationToken.None); + + // Assert + Assert.True(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheHostNameResolvesToPublicAddresses_ShouldReturnTrue() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [s_publicAddress, IPAddress.Parse("93.184.216.35")]); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None); + + // Assert + Assert.True(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheHostNameResolvesToOnePrivateAddress_ShouldReturnFalse() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: null, CancellationToken.None); + + // Assert + Assert.False(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheHostNameResolvesToBothPublicAndPrivateAddresses_ShouldReturnFalse() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [s_publicAddress, IPAddress.Parse("192.168.1.10")]); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("mixed.example.com", allowedPrivateHost: null, CancellationToken.None); + + // Assert + Assert.False(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheHostNameCannotBeResolved_ShouldReturnFalse() + { + // Arrange + PublicHostValidator sut = CreateValidator(_ => throw new SocketException((int)SocketError.HostNotFound)); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("missing.example.com", allowedPrivateHost: null, CancellationToken.None); + + // Assert + Assert.False(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheHostNameIsMalformed_ShouldReturnFalse() + { + // Arrange + PublicHostValidator sut = CreateValidator(_ => throw new ArgumentException("The host is malformed.")); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("malformed host", allowedPrivateHost: null, CancellationToken.None); + + // Assert + Assert.False(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheHostNameResolvesToNoAddress_ShouldReturnFalse() + { + // Arrange + PublicHostValidator sut = CreateValidator(_ => []); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("empty.example.com", allowedPrivateHost: null, CancellationToken.None); + + // Assert + Assert.False(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenCancellationIsRequested_ShouldThrowOperationCanceledException() + { + // Arrange + PublicHostValidator sut = CreateValidator(_ => throw new OperationCanceledException()); + using CancellationTokenSource cancellationTokenSource = new(); + cancellationTokenSource.Cancel(); + + // Act + Task Act() + { + return sut.ValidateHostAsync("example.com", allowedPrivateHost: null, cancellationTokenSource.Token); + } + + // Assert + await Assert.ThrowsAnyAsync(Act); + } + + [Fact] + public async Task ResolveEndPointsAsync_WhenThePublicHostNameResolvesToAddresses_ShouldReturnTheirEndPoints() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [s_publicAddress, s_publicAddress]); + IPAddress expectedAddress = s_publicAddress; + + // Act + IReadOnlyList result = await sut.ResolveEndPointsAsync("example.com", 443, allowedPrivateHost: null, CancellationToken.None); + + // Assert + IPEndPoint endPoint = Assert.Single(result); + Assert.Equal(expectedAddress, endPoint.Address); + Assert.Equal(443, endPoint.Port); + } + + [Fact] + public async Task ResolveEndPointsAsync_WhenTheHostNameResolvesToOnePrivateAddress_ShouldThrow() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [s_publicAddress, IPAddress.Parse("10.0.0.5")]); + + // Act + Task Act() + { + return sut.ResolveEndPointsAsync("mixed.example.com", 80, allowedPrivateHost: null, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task ResolveEndPointsAsync_WhenTheHostIsAnIPv4MappedIPv6Address_ShouldReturnItsIPv4EndPoint() + { + // Arrange + PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("An IP literal must not be resolved.")); + IPAddress expectedAddress = IPAddress.Parse("93.184.216.34"); + + // Act + IReadOnlyList result = await sut.ResolveEndPointsAsync("::ffff:93.184.216.34", 443, allowedPrivateHost: null, CancellationToken.None); + + // Assert + IPEndPoint endPoint = Assert.Single(result); + Assert.Equal(expectedAddress, endPoint.Address); + Assert.Equal(443, endPoint.Port); + } + + [Fact] + public async Task ResolveEndPointsAsync_WhenTheHostCannotBeResolved_ShouldThrow() + { + // Arrange + PublicHostValidator sut = CreateValidator(_ => throw new SocketException((int)SocketError.HostNotFound)); + + // Act + Task Act() + { + return sut.ResolveEndPointsAsync("missing.example.com", 443, allowedPrivateHost: null, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task ResolveEndPointsAsync_WhenTheHostNameResolvesToNoAddress_ShouldThrow() + { + // Arrange + PublicHostValidator sut = CreateValidator(_ => []); + + // Act + Task Act() + { + return sut.ResolveEndPointsAsync("empty.example.com", 443, allowedPrivateHost: null, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToAPrivateAddress_ShouldReturnTrue() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None); + + // Assert + Assert.True(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenAnotherHostResolvesToOnePrivateAddress_ShouldReturnFalse() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("other.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None); + + // Assert + Assert.False(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheAllowedPrivateHostIsLocalhost_ShouldReturnTrue() + { + // Arrange + PublicHostValidator sut = CreateValidator(_ => throw new InvalidOperationException("The loopback host name must not be resolved.")); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("localhost", allowedPrivateHost: "localhost", CancellationToken.None); + + // Assert + Assert.True(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheAllowedPrivateHostIsAnIdnNameAndTheConnectionUsesItsPunycodeSpelling_ShouldReturnTrue() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("192.168.1.10")]); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("xn--bcher-kva.example", allowedPrivateHost: "bücher.example", CancellationToken.None); + + // Assert + Assert.True(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToTheLinkLocalMetadataAddress_ShouldReturnFalse() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("169.254.169.254")]); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None); + + // Assert + Assert.False(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToAnIPv6UniqueLocalAddress_ShouldReturnTrue() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("fc00::1")]); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None); + + // Assert + Assert.True(result.IsAllowed); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToTheAwsMetadataAddress_ShouldReturnFalse() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("fd00:ec2::254")]); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None); + + // Assert + Assert.False(result.IsAllowed); + Assert.Equal(OutboundRequestRejectionReason.LinkLocalOrMetadataAddress, result.RejectionReason); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheAllowedPrivateHostResolvesToTheAlibabaMetadataAddress_ShouldReturnFalse() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("100.100.100.200")]); + + // Act + PublicHostValidationResult result = await sut.ValidateHostAsync("internal.example.com", allowedPrivateHost: "internal.example.com", CancellationToken.None); + + // Assert + Assert.False(result.IsAllowed); + } + + [Fact] + public async Task ResolveEndPointsAsync_WhenTheAllowedPrivateHostResolvesToAPrivateAddress_ShouldReturnItsEndPoint() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]); + IPAddress expectedAddress = IPAddress.Parse("10.0.0.5"); + + // Act + IReadOnlyList result = await sut.ResolveEndPointsAsync("internal.example.com", 8080, allowedPrivateHost: "internal.example.com", CancellationToken.None); + + // Assert + IPEndPoint endPoint = Assert.Single(result); + Assert.Equal(expectedAddress, endPoint.Address); + Assert.Equal(8080, endPoint.Port); + } + + [Fact] + public async Task ResolveEndPointsAsync_WhenAnotherHostResolvesToAPrivateAddress_ShouldThrow() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("10.0.0.5")]); + + // Act + Task Act() + { + return sut.ResolveEndPointsAsync("other.example.com", 443, allowedPrivateHost: "internal.example.com", CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + } + + [Fact] + public async Task ResolveEndPointsAsync_WhenTheAllowedPrivateHostResolvesToTheLinkLocalMetadataAddress_ShouldThrow() + { + // Arrange + PublicHostValidator sut = CreateValidator(host => [IPAddress.Parse("169.254.169.254")]); + + // Act + Task Act() + { + return sut.ResolveEndPointsAsync("internal.example.com", 443, allowedPrivateHost: "internal.example.com", CancellationToken.None); + } + + // Assert + PublicHostRejectedException exception = await Assert.ThrowsAsync(Act); + Assert.Equal(OutboundRequestRejectionReason.LinkLocalOrMetadataAddress, exception.RejectionReason); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheSameHostIsCheckedTwice_ShouldResolveItOnlyOnce() + { + // Arrange + int resolutionCount = 0; + PublicHostValidator sut = new((host, cancellationToken) => + { + resolutionCount++; + return Task.FromResult([s_publicAddress]); + }); + + // Act + await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None); + await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None); + + // Assert + Assert.Equal(1, resolutionCount); + } + + [Fact] + public async Task ResolveEndPointsAsync_WhenTheHostWasAlreadyChecked_ShouldReuseTheResolution() + { + // Arrange + int resolutionCount = 0; + PublicHostValidator sut = new((host, cancellationToken) => + { + resolutionCount++; + return Task.FromResult([s_publicAddress]); + }); + + // Act + await sut.ValidateHostAsync("example.com", allowedPrivateHost: null, CancellationToken.None); + await sut.ResolveEndPointsAsync("example.com", 443, allowedPrivateHost: null, CancellationToken.None); + + // Assert + Assert.Equal(1, resolutionCount); + } + + [Fact] + public async Task ValidateHostAsync_WhenTheHostCannotBeResolvedTwice_ShouldCacheTheFailureBriefly() + { + // Arrange + int resolutionCount = 0; + PublicHostValidator sut = new((host, cancellationToken) => + { + resolutionCount++; + throw new SocketException((int)SocketError.HostNotFound); + }); + + // Act + await sut.ValidateHostAsync("missing.example.com", allowedPrivateHost: null, CancellationToken.None); + await sut.ValidateHostAsync("missing.example.com", allowedPrivateHost: null, CancellationToken.None); + + // Assert + Assert.Equal(1, resolutionCount); + } + + /// + /// Creates a whose host name resolution is replaced by the provided resolver. + /// + /// The resolver that produces the addresses of a host name. + /// The created validator. + private static PublicHostValidator CreateValidator(Func addressResolver) + { + return new PublicHostValidator((host, cancellationToken) => Task.FromResult(addressResolver(host))); } } diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/DependencyInjection/CoverArtArchiveServicesTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/DependencyInjection/CoverArtArchiveServicesTests.cs index 9daac4bb..810b4aed 100644 --- a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/DependencyInjection/CoverArtArchiveServicesTests.cs +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Common/DependencyInjection/CoverArtArchiveServicesTests.cs @@ -129,22 +129,23 @@ public class CoverArtArchiveServicesTests } [Fact] - public void AddCoverArtArchiveArtworkProvider_WhenTheClientIsResolved_ShouldDisableAutomaticRedirectsOnItsPrimaryHandler() + public void AddCoverArtArchiveArtworkProvider_WhenTheHostConfiguresHttpClientDefaults_ShouldKeepThePrimaryHandlerOfTheHost() { // Arrange ServiceCollection services = new(); + StubPrimaryHttpMessageHandler hostPrimaryHandler = new(); + services.ConfigureHttpClientDefaults(builder => builder.ConfigurePrimaryHttpMessageHandler(() => hostPrimaryHandler)); services.AddCoverArtArchiveArtworkProvider(pluginId: Guid.NewGuid()); ServiceProvider serviceProvider = services.BuildServiceProvider(); using (IServiceScope scope = serviceProvider.CreateScope()) { // Act CoverArtArchiveHttpClient client = scope.ServiceProvider.GetRequiredService(); - HttpClientHandler primaryHandler = GetPrimaryHandler(client); // Assert - // Automatic redirects must stay disabled on the primary handler, otherwise it would follow a server controlled redirect on its own, - // before the client can check the target host against the Cover Art Archive and the Internet Archive, bypassing that control. - Assert.False(primaryHandler.AllowAutoRedirect); + // The host owns the primary handler, because it is what disables automatic redirects and connects only to addresses validated to be public. + // The plugin must not replace it, otherwise it would follow a server controlled redirect on its own and bypass the guard of the host. + Assert.Same(hostPrimaryHandler, GetPrimaryHandler(client)); } } @@ -170,14 +171,14 @@ public class CoverArtArchiveServicesTests /// Gets the primary HTTP message handler of the provided client, unwrapping the delegating handlers built by the HTTP client factory around it. /// /// The client whose primary handler is retrieved. - /// The primary HTTP client handler of the client. - private static HttpClientHandler GetPrimaryHandler(CoverArtArchiveHttpClient client) + /// The primary HTTP message handler of the client. + private static HttpMessageHandler GetPrimaryHandler(CoverArtArchiveHttpClient client) { HttpClient httpClient = (HttpClient)GetFieldOfType(client, typeof(HttpClient))!; HttpMessageHandler? handler = (HttpMessageHandler?)GetFieldOfType(httpClient, typeof(HttpMessageHandler)); while (handler is DelegatingHandler delegatingHandler) handler = delegatingHandler.InnerHandler; - return Assert.IsType(handler); + return handler ?? throw new InvalidOperationException("The HTTP client has no primary handler."); } /// @@ -202,4 +203,23 @@ public class CoverArtArchiveServicesTests } throw new InvalidOperationException($"No field assignable to {fieldType} was found on {instance.GetType()} or its base types."); } + + /// + /// Primary HTTP message handler that identifies the handler the host configured, so a test can verify that the plugin does not replace it. + /// + [ExcludeFromCodeCoverage] + private sealed class StubPrimaryHttpMessageHandler : HttpMessageHandler + { + /// + /// Sends the provided request. The tests never send a request through this handler. + /// + /// The request to send. + /// Cancellation token that can be used to stop the execution. + /// The response of the request. + /// Always thrown, because this handler only identifies the handler configured by the host. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + throw new NotSupportedException(); + } + } } diff --git a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveHttpClientTests.cs b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveHttpClientTests.cs index 3fceffd8..865356e1 100644 --- a/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveHttpClientTests.cs +++ b/tests/UnitTests/Lumina.Plugins.CoverArtArchive.UnitTests/Core/Api/CoverArtArchiveHttpClientTests.cs @@ -1,4 +1,5 @@ #region ========================================================================= USING ===================================================================================== +using Lumina.Plugins.Contracts.Common.Http; using Lumina.Plugins.CoverArtArchive.Common.Models.Contracts.Responses; using Lumina.Plugins.CoverArtArchive.Core; using Lumina.Plugins.CoverArtArchive.Core.Api; @@ -54,6 +55,20 @@ public class CoverArtArchiveHttpClientTests Assert.Equal("coverartarchive.org", handler.Requests[0].RequestUri!.Host); } + [Fact] + public async Task GetReleaseArtworkAsync_WhenCalled_ShouldOptOutOfTheHostRedirectHandling() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient(); + + // Act + await client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + + // Assert + Assert.True(handler.Requests[0].Options.TryGetValue(OutboundRequestOptions.FollowRedirects, out bool shouldFollowRedirects)); + Assert.False(shouldFollowRedirects); + } + [Fact] public async Task GetReleaseGroupArtworkAsync_WhenTheReleaseGroupHasArtwork_ShouldDeserializeIt() { @@ -298,6 +313,43 @@ public class CoverArtArchiveHttpClientTests Assert.Equal(2, handler.CallCount); } + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheHostRejectsTheRequest_ShouldNotRetry() + { + // Arrange + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient( + (request, callIndex) => throw new HttpRequestException(HttpRequestError.ConfigurationLimitExceeded, "Rejected.")); + + // Act + Task Act() + { + return client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(1, handler.CallCount); + } + + [Fact] + public async Task GetReleaseArtworkAsync_WhenTheConnectPolicyWrapsTheRejection_ShouldNotRetry() + { + // Arrange + HttpRequestException rejection = new(HttpRequestError.ConfigurationLimitExceeded, "Rejected."); + (CoverArtArchiveHttpClient client, StubHttpMessageHandler handler) = CreateClient( + (request, callIndex) => throw new HttpRequestException(HttpRequestError.ConnectionError, "Connection error.", rejection)); + + // Act + Task Act() + { + return client.GetReleaseArtworkAsync(s_releaseId, CancellationToken.None); + } + + // Assert + await Assert.ThrowsAsync(Act); + Assert.Equal(1, handler.CallCount); + } + [Fact] public async Task GetReleaseArtworkAsync_WhenEveryAttemptFails_ShouldThrowAfterExhaustingTheRetries() { diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs index cb5dca74..87834201 100644 --- a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Common/DependencyInjection/MusicBrainzServicesTests.cs @@ -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(); + + // 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)); } + + /// + /// Gets the primary HTTP message handler of the provided client, unwrapping the delegating handlers built by the HTTP client factory around it. + /// + /// The client whose primary handler is retrieved. + /// The primary HTTP message handler of the client. + 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."); + } + + /// + /// Gets the value of the first field, declared on the provided or any of its base types, whose type is assignable to + /// , without relying on the field name, so the test keeps working across runtime versions. + /// + /// The instance whose field is read. + /// The type the field must be assignable to. + /// The value of the found field. + /// Thrown when no field assignable to is found. + 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."); + } + + /// + /// Primary HTTP message handler that identifies the handler the host configured, so a test can verify that the plugin does not replace it. + /// + [ExcludeFromCodeCoverage] + private sealed class StubPrimaryHttpMessageHandler : HttpMessageHandler + { + /// + /// Sends the provided request. The tests never send a request through this handler. + /// + /// The request to send. + /// Cancellation token that can be used to stop the execution. + /// The response of the request. + /// Always thrown, because this handler only identifies the handler configured by the host. + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + throw new NotSupportedException(); + } + } } diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzHttpClientTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzHttpClientTests.cs index 7625a4ad..3f02b0bc 100644 --- a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzHttpClientTests.cs +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Api/MusicBrainzHttpClientTests.cs @@ -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(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(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(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(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(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 /// The minimum request interval configured for the client. /// Optional. The factory that produces the response of a request. /// Optional. The contact email configured for the client. + /// Optional. Whether the base URL may point at a private or local host. /// The created client, its stub handler and the underlying HTTP client. private (MusicBrainzHttpClient Client, StubHttpMessageHandler Handler, HttpClient HttpClient) CreateClient( string baseUrl, TimeSpan minimumRequestInterval, Func? 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 /// The base URL of the MusicBrainz web service the client points to. /// The minimum request interval configured for the client. /// Optional. The contact email configured for the client. + /// Optional. Whether the base URL may point at a private or local host. /// The created client. - 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") }; } + + /// + /// Creates a temporary redirect response to the provided location. + /// + /// The absolute location of the redirect target. + /// The created response. + private static HttpResponseMessage Redirect(string location) + { + HttpResponseMessage redirect = new(HttpStatusCode.TemporaryRedirect); + redirect.Headers.Location = new Uri(location); + return redirect; + } } diff --git a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Settings/MusicBrainzSettingsProviderTests.cs b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Settings/MusicBrainzSettingsProviderTests.cs index 6b04da68..528e85b8 100644 --- a/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Settings/MusicBrainzSettingsProviderTests.cs +++ b/tests/UnitTests/Lumina.Plugins.MusicBrainz.UnitTests/Core/Settings/MusicBrainzSettingsProviderTests.cs @@ -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(); + mockStore.GetSettingsAsync(Arg.Any(), Arg.Any()).Returns( + new Dictionary { [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() {