From 6c6fab8a16df72e680476a965d5fbaeec3cab0ae Mon Sep 17 00:00:00 2001 From: pieroviano Date: Tue, 15 Sep 2026 02:50:25 +0300 Subject: [PATCH] Harden JAR by reference and multi-issuer hosting after review - Reject external request_uri values when pushed authorization requests are globally required - Compute the request_uri fragment hash on the untrimmed request object - Treat local-use NAT64, benchmarking, ORCHID, 3fff::/20 and 5f00::/16 IPv6 ranges as non-public - Report a missing issuer source as a startup configuration error - Document and log issuers that can't match the request URI - Prove SSRF filtering and per-issuer signing keys with dedicated tests --- .../OpenIddictResources.resx | 9 + .../OpenIddictServerSystemNetHttpHelpers.cs | 8 +- .../IOpenIddictServerIssuerResolver.cs | 4 + .../OpenIddictServerConfiguration.cs | 21 +++ ...OpenIddictServerHandlers.Authentication.cs | 22 ++- .../OpenIddictServerHandlers.cs | 9 + ...pNetCoreIssuerResolutionValidationTests.cs | 43 ++++- ...ServerIntegrationTests.IssuerResolution.cs | 14 -- ...IntegrationTests.RequestObjectReference.cs | 155 ++++++++++++++++++ ...rSystemNetHttpRequestObjectFetcherTests.cs | 125 +++++++++++++- .../OpenIddictServerIssuerResolutionTests.cs | 61 ++++++- 11 files changed, 438 insertions(+), 33 deletions(-) diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx index b1ea3bd5..91c2cf4a 100644 --- a/src/OpenIddict.Abstractions/OpenIddictResources.resx +++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx @@ -3204,6 +3204,9 @@ To register issuers, call 'services.AddOpenIddict().AddServer().AddIssuers()' or The issuer of the current request couldn't be resolved. + + The '{0}' parameter must reference a pushed authorization request. + The '{0}' parameter shouldn't be null or empty at this point. @@ -4407,6 +4410,12 @@ This may indicate that the hashed entry is corrupted or malformed. The request object retrieved from '{RequestUri}' was rejected because it is not a valid UTF-8 string. + + The authorization request was rejected because the external request_uri '{RequestUri}' was used while pushed authorization requests are required. + + + The issuer '{Issuer}' resolved for the request '{RequestUri}' doesn't share the scheme, host and port of the request URI or the request is not located under the issuer path: no endpoint can be matched. + https://documentation.openiddict.com/errors/{0} diff --git a/src/OpenIddict.Server.SystemNetHttp/OpenIddictServerSystemNetHttpHelpers.cs b/src/OpenIddict.Server.SystemNetHttp/OpenIddictServerSystemNetHttpHelpers.cs index a38ce48c..fe45a5d3 100644 --- a/src/OpenIddict.Server.SystemNetHttp/OpenIddictServerSystemNetHttpHelpers.cs +++ b/src/OpenIddict.Server.SystemNetHttp/OpenIddictServerSystemNetHttpHelpers.cs @@ -17,7 +17,8 @@ public static class OpenIddictServerSystemNetHttpHelpers /// /// Determines whether the specified address is a public unicast address, i.e an address that is not part of /// the unspecified, loopback, private (RFC 1918, RFC 4193), shared (RFC 6598), link-local (RFC 3927, RFC 4291), - /// documentation (RFC 5737, RFC 3849), benchmarking (RFC 2544), multicast or reserved ranges (RFC 6890). + /// documentation (RFC 5737, RFC 3849, RFC 9637), benchmarking (RFC 2544, RFC 5180), local-use NAT64 (RFC 8215), + /// ORCHID (RFC 7343), multicast or reserved ranges (RFC 6890). /// /// The IP address. /// if the address is a public unicast address, otherwise. @@ -77,9 +78,14 @@ public static class OpenIddictServerSystemNetHttpHelpers return bytes switch { [0, 0x64, 0xff, 0x9b, 0, 0, 0, 0, 0, 0, 0, 0, ..] => IsPublicIPv4Address(bytes.AsSpan(12, 4)), // 64:ff9b::/96 (NAT64) + [0, 0x64, 0xff, 0x9b, 0, 0x01, ..] => false, // 64:ff9b:1::/48 (local-use NAT64, RFC 8215) [0x20, 0x02, ..] => IsPublicIPv4Address(bytes.AsSpan(2, 4)), // 2002::/16 (6to4) [0x20, 0x01, 0x00, 0x00, ..] => false, // 2001::/32 (Teredo) + [0x20, 0x01, 0x00, 0x02, 0x00, 0x00, ..] => false, // 2001:2::/48 (benchmarking, RFC 5180) + [0x20, 0x01, 0x00, >= 0x10 and <= 0x2f, ..] => false, // 2001:10::/28 and 2001:20::/28 (ORCHID, RFC 4843 and RFC 7343) [0x20, 0x01, 0x0d, 0xb8, ..] => false, // 2001:db8::/32 (documentation) + [0x3f, 0xff, >= 0x00 and <= 0x0f, ..] => false, // 3fff::/20 (documentation, RFC 9637) + [0x5f, 0x00, ..] => false, // 5f00::/16 (segment routing SIDs, RFC 9602) [0x01, 0x00, 0, 0, 0, 0, 0, 0, ..] => false, // 100::/64 (discard-only) [>= 0xfc and <= 0xfd, ..] => false, // fc00::/7 (unique local) [0xfe, >= 0x80, ..] => false, // fe80::/10 (link-local) and fec0::/10 (site-local) diff --git a/src/OpenIddict.Server/IOpenIddictServerIssuerResolver.cs b/src/OpenIddict.Server/IOpenIddictServerIssuerResolver.cs index 933414d1..a67a9664 100644 --- a/src/OpenIddict.Server/IOpenIddictServerIssuerResolver.cs +++ b/src/OpenIddict.Server/IOpenIddictServerIssuerResolver.cs @@ -13,6 +13,10 @@ namespace OpenIddict.Server; /// /// The resolved issuer is used as the base URI of the request: relative endpoint URIs are resolved relatively /// to it, the discovery document advertises it and tokens are issued for and validated against it. +/// As such, the returned issuer must share the scheme, host and port of the request URI and the request path +/// must be located under the issuer path, otherwise no endpoint is matched. When the server is hosted behind +/// a reverse proxy, the forwarded headers must be applied (e.g using the ASP.NET Core forwarded headers +/// middleware) before OpenIddict processes the request so that the request URI reflects the public address. /// public interface IOpenIddictServerIssuerResolver { diff --git a/src/OpenIddict.Server/OpenIddictServerConfiguration.cs b/src/OpenIddict.Server/OpenIddictServerConfiguration.cs index 037cb49b..0cdeab94 100644 --- a/src/OpenIddict.Server/OpenIddictServerConfiguration.cs +++ b/src/OpenIddict.Server/OpenIddictServerConfiguration.cs @@ -451,6 +451,12 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions uri is null || (uri.IsAbsoluteUri && string.Equals(uri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase)); + + bool HasIssuerResolver() + { + try + { + return _provider.GetService() is not null; + } + + // Note: resolvers registered with a scoped lifetime can't be resolved from the root + // provider when scope validation is enabled: in this case, assume a resolver exists. + catch (InvalidOperationException) + { + return true; + } + } } } diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.cs index 396e11c3..ac2df4f8 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.cs @@ -580,6 +580,21 @@ public static partial class OpenIddictServerHandlers return ValueTask.CompletedTask; } + // When pushed authorization requests are globally required, the authorization server + // only accepts authorization request data via the pushed authorization endpoint + // (RFC 9126, section 5): external request_uri values MUST be rejected in this case. + if (context.Options.RequirePushedAuthorizationRequests) + { + context.Logger.LogInformation(6735, SR.GetResourceString(SR.ID6735), context.Request.RequestUri); + + context.Reject( + error: Errors.InvalidRequestUri, + description: SR.FormatID2466(Parameters.RequestUri), + uri: SR.FormatID8000(SR.ID2466)); + + return ValueTask.CompletedTask; + } + if (!IsValidExternalRequestUri(context.Request.RequestUri)) { context.Logger.LogInformation(6720, SR.GetResourceString(SR.ID6720), context.Request.RequestUri); @@ -748,9 +763,7 @@ public static partial class OpenIddictServerHandlers content = null; } - content = content?.Trim(); - - if (string.IsNullOrEmpty(content)) + if (string.IsNullOrWhiteSpace(content)) { context.Logger.LogInformation(6723, SR.GetResourceString(SR.ID6723), uri); @@ -765,6 +778,7 @@ public static partial class OpenIddictServerHandlers // If the contents of the referenced resource can change, OpenID Connect Core (section 6.2) // recommends including the base64url-encoded SHA-256 hash of the resource as the URI fragment. // When the fragment has the shape of such a hash, ensure it matches the retrieved request object. + // Note: the hash is computed over the file contents as returned by the fetcher (i.e before trimming). if (uri.Fragment is { Length: 44 } fragment && TryDecodeHash(fragment[1..]) is byte[] hash && !hash.AsSpan().SequenceEqual(SHA256.HashData(Encoding.UTF8.GetBytes(content)))) { @@ -780,7 +794,7 @@ public static partial class OpenIddictServerHandlers // Attach the request object as if it had been sent by value: the request_uri is removed // so that it is not mistaken for a request token generated by OpenIddict later in the pipeline. - context.Request.Request = content; + context.Request.Request = content.Trim(); context.Request.RequestUri = null; static byte[]? TryDecodeHash(string value) diff --git a/src/OpenIddict.Server/OpenIddictServerHandlers.cs b/src/OpenIddict.Server/OpenIddictServerHandlers.cs index 8922d12c..d67cde8b 100644 --- a/src/OpenIddict.Server/OpenIddictServerHandlers.cs +++ b/src/OpenIddict.Server/OpenIddictServerHandlers.cs @@ -200,6 +200,15 @@ public static partial class OpenIddictServerHandlers context.Logger.LogDebug(6725, SR.GetResourceString(SR.ID6725), issuer, context.RequestUri); + // Note: since the resolved issuer is used as the base URI, endpoints can only be matched if the request URI + // shares the scheme, host and port of the issuer and is located under its path. When this is not the case + // (e.g when the application is behind a reverse proxy that doesn't flow the forwarded headers), log a message + // to help diagnose why no endpoint is matched. + if (OpenIddictServerIssuerResolution.MatchIssuer([issuer], context.RequestUri) is null) + { + context.Logger.LogDebug(6736, SR.GetResourceString(SR.ID6736), issuer, context.RequestUri); + } + context.BaseUri = issuer; } } diff --git a/test/OpenIddict.Server.AspNetCore.IntegrationTests/OpenIddictServerAspNetCoreIssuerResolutionValidationTests.cs b/test/OpenIddict.Server.AspNetCore.IntegrationTests/OpenIddictServerAspNetCoreIssuerResolutionValidationTests.cs index 9430b569..ed7a3ea3 100644 --- a/test/OpenIddict.Server.AspNetCore.IntegrationTests/OpenIddictServerAspNetCoreIssuerResolutionValidationTests.cs +++ b/test/OpenIddict.Server.AspNetCore.IntegrationTests/OpenIddictServerAspNetCoreIssuerResolutionValidationTests.cs @@ -69,6 +69,31 @@ public class OpenIddictServerAspNetCoreIssuerResolutionValidationTests Assert.Equal(status, response.StatusCode); } + [Theory] + [InlineData(false, HttpStatusCode.OK)] + [InlineData(true, HttpStatusCode.Unauthorized)] + public async Task Validation_TokenWithCorrectIssuerSignedWithAnotherIssuerKeyIsRejected( + bool credentials, HttpStatusCode status) + { + // Arrange + var toggle = new CredentialsSwitch { Enabled = false }; + + using var host = await CreateHostAsync(credentials: true, encryption: false, toggle); + using var client = host.GetTestClient(); + + // Note: while the issuer-specific credentials are disabled, the token issued for tenant2 carries + // the correct "iss" claim but is signed using the default signing key (i.e the key of tenant1). + var token = await GetAccessTokenAsync(client, "tenant2"); + + toggle.Enabled = credentials; + + // Act + using var response = await CallApiAsync(client, "tenant2", token); + + // Assert + Assert.Equal(status, response.StatusCode); + } + private static async Task GetAccessTokenAsync(HttpClient client, string tenant) { using var response = await client.PostAsync($"http://localhost/{tenant}/connect/token", new FormUrlEncodedContent( @@ -94,13 +119,15 @@ public class OpenIddictServerAspNetCoreIssuerResolutionValidationTests return await client.SendAsync(request); } - private static async Task CreateHostAsync(bool credentials) + private static async Task CreateHostAsync(bool credentials, bool encryption = true, CredentialsSwitch? toggle = null) { var builder = new HostBuilder(); builder.UseEnvironment("Testing"); builder.ConfigureServices(services => { + services.AddSingleton(toggle ?? new CredentialsSwitch { Enabled = true }); + services.AddOpenIddict() .AddServer(options => { @@ -117,6 +144,11 @@ public class OpenIddictServerAspNetCoreIssuerResolutionValidationTests options.UseAspNetCore() .DisableTransportSecurityRequirement(); + if (!encryption) + { + options.DisableAccessTokenEncryption(); + } + if (credentials) { options.SetIssuerCredentialsProvider(); @@ -171,7 +203,12 @@ public class OpenIddictServerAspNetCoreIssuerResolutionValidationTests return await builder.StartAsync(); } - private sealed class TenantCredentialsProvider : IOpenIddictServerIssuerCredentialsProvider + private sealed class CredentialsSwitch + { + public bool Enabled { get; set; } + } + + private sealed class TenantCredentialsProvider(CredentialsSwitch toggle) : IOpenIddictServerIssuerCredentialsProvider { private static readonly SigningCredentials Credentials = new( new RsaSecurityKey(RSA.Create(keySizeInBits: 2048)) { KeyId = "tenant2" }, SecurityAlgorithms.RsaSha256); @@ -182,7 +219,7 @@ public class OpenIddictServerAspNetCoreIssuerResolutionValidationTests public ValueTask GetCredentialsAsync( Uri issuer, IServiceProvider provider, CancellationToken cancellationToken) - => new(issuer.AbsoluteUri is "http://localhost/tenant2/" ? + => new(toggle.Enabled && issuer.AbsoluteUri is "http://localhost/tenant2/" ? new OpenIddictServerCredentials([Credentials], [Encryption]) : null); } } diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.IssuerResolution.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.IssuerResolution.cs index 047e57fb..aae78c96 100644 --- a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.IssuerResolution.cs +++ b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.IssuerResolution.cs @@ -244,20 +244,6 @@ public abstract partial class OpenIddictServerIntegrationTests Assert.Equal(SR.GetResourceString(SR.ID0925), exception.Message); } - [Fact] - public async Task IssuerResolution_MissingIssuerSourceCausesAnException() - { - // Arrange - await using var server = await CreateServerAsync(options => ConfigureIssuerResolution(options)); - await using var client = await server.CreateClientAsync(); - - // Act and assert - var exception = await Assert.ThrowsAsync( - () => client.GetAsync("http://localhost/.well-known/openid-configuration")); - - Assert.Equal(SR.GetResourceString(SR.ID0929), exception.Message); - } - [Fact] public async Task IssuerResolution_IssuerSpecificCredentialsAreUsed() { diff --git a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.RequestObjectReference.cs b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.RequestObjectReference.cs index f3dcc1a9..dc76fb3d 100644 --- a/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.RequestObjectReference.cs +++ b/test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.RequestObjectReference.cs @@ -243,6 +243,161 @@ public abstract partial class OpenIddictServerIntegrationTests Assert.NotNull(response.AccessToken); } + [Fact] + public async Task ValidateAuthorizationRequest_FragmentHashIsComputedOnUntrimmedContents() + { + // Arrange + var token = CreateRequestObject(new(StringComparer.Ordinal) + { + [Parameters.Nonce] = "n-0S6_WzA2Mj", + [Parameters.RedirectUri] = "http://www.fabrikam.com/path", + [Parameters.ResponseType] = ResponseTypes.Token + }) + "\n"; + + await using var server = await CreateServerAsync(options => + { + ConfigureRequestObjectReferenceServer(options, _ => token); + + options.AddEventHandler(builder => + builder.UseInlineHandler(context => + { + context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")) + .SetClaim(Claims.Subject, "Bob le Magnifique"); + + return ValueTask.CompletedTask; + })); + }); + + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/authorize", new OpenIddictRequest + { + ClientId = "Fabrikam", + RequestUri = ExternalRequestUri + "#" + Base64Url.EncodeToString(SHA256.HashData(Encoding.UTF8.GetBytes(token))) + }); + + // Assert + Assert.Null(response.Error); + Assert.NotNull(response.AccessToken); + } + + [Fact] + public async Task ValidateAuthorizationRequest_ExternalRequestUriIsRejectedWhenPushedAuthorizationRequestsAreRequired() + { + // Arrange + var fetched = false; + + await using var server = await CreateServerAsync(options => + { + ConfigureRequestObjectReferenceServer(options, _ => + { + fetched = true; + + return CreateRequestObject(new(StringComparer.Ordinal) + { + [Parameters.Nonce] = "n-0S6_WzA2Mj", + [Parameters.RedirectUri] = "http://www.fabrikam.com/path", + [Parameters.ResponseType] = ResponseTypes.Token + }); + }); + + options.RequirePushedAuthorizationRequests(); + + options.AddEventHandler(builder => + builder.UseInlineHandler(context => + { + context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")) + .SetClaim(Claims.Subject, "Bob le Magnifique"); + + return ValueTask.CompletedTask; + })); + }); + + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/authorize", new OpenIddictRequest + { + ClientId = "Fabrikam", + RequestUri = ExternalRequestUri + }); + + // Assert + Assert.Equal(Errors.InvalidRequestUri, response.Error); + Assert.Equal(SR.FormatID2466(Parameters.RequestUri), response.ErrorDescription); + Assert.Equal(SR.FormatID8000(SR.ID2466), response.ErrorUri); + Assert.Null(response.AccessToken); + Assert.False(fetched); + } + + [Fact] + public async Task ValidateAuthorizationRequest_ReferencedRequestObjectSatisfiesSignedRequestObjectsRequirement() + { + // Arrange + await using var server = await CreateServerAsync(options => + { + ConfigureRequestObjectReferenceServer(options, _ => CreateRequestObject(new(StringComparer.Ordinal) + { + [Parameters.Nonce] = "n-0S6_WzA2Mj", + [Parameters.RedirectUri] = "http://www.fabrikam.com/path", + [Parameters.ResponseType] = ResponseTypes.Token + })); + + options.RequireSignedRequestObjects(); + + options.AddEventHandler(builder => + builder.UseInlineHandler(context => + { + context.Principal = new ClaimsPrincipal(new ClaimsIdentity("Bearer")) + .SetClaim(Claims.Subject, "Bob le Magnifique"); + + return ValueTask.CompletedTask; + })); + }); + + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/authorize", new OpenIddictRequest + { + ClientId = "Fabrikam", + RequestUri = ExternalRequestUri + }); + + // Assert + Assert.Null(response.Error); + Assert.NotNull(response.AccessToken); + } + + [Fact] + public async Task ValidateAuthorizationRequest_UnsignedReferencedRequestObjectIsRejectedWhenSignedRequestObjectsAreRequired() + { + // Arrange + await using var server = await CreateServerAsync(options => + { + ConfigureRequestObjectReferenceServer(options, _ => CreateRequestObject(new(StringComparer.Ordinal) + { + [Parameters.ResponseType] = ResponseTypes.Token + }, unsigned: true)); + + options.RequireSignedRequestObjects(); + }); + + await using var client = await server.CreateClientAsync(); + + // Act + var response = await client.PostAsync("/connect/authorize", new OpenIddictRequest + { + ClientId = "Fabrikam", + RequestUri = ExternalRequestUri + }); + + // Assert + Assert.Equal(Errors.InvalidRequestObject, response.Error); + Assert.Equal(SR.GetResourceString(SR.ID2211), response.ErrorDescription); + } + [Fact] public async Task ValidateAuthorizationRequest_ThrowsAnExceptionWhenNoFetcherIsRegistered() { diff --git a/test/OpenIddict.Server.SystemNetHttp.Tests/OpenIddictServerSystemNetHttpRequestObjectFetcherTests.cs b/test/OpenIddict.Server.SystemNetHttp.Tests/OpenIddictServerSystemNetHttpRequestObjectFetcherTests.cs index d670e6b3..d912eefa 100644 --- a/test/OpenIddict.Server.SystemNetHttp.Tests/OpenIddictServerSystemNetHttpRequestObjectFetcherTests.cs +++ b/test/OpenIddict.Server.SystemNetHttp.Tests/OpenIddictServerSystemNetHttpRequestObjectFetcherTests.cs @@ -4,10 +4,12 @@ * the license and the contributors participating to this project. */ +using System.Collections.Concurrent; using System.Globalization; using System.Net; using System.Net.Http; using System.Net.Http.Headers; +using System.Net.Sockets; using System.Text; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging.Abstractions; @@ -44,6 +46,15 @@ public class OpenIddictServerSystemNetHttpRequestObjectFetcherTests [InlineData("fd12:3456::1", false)] [InlineData("fe80::1", false)] [InlineData("ff02::1", false)] + [InlineData("64:ff9b:1::a00:1", false)] + [InlineData("2001:2::1", false)] + [InlineData("2001:10::1", false)] + [InlineData("2001:20::1", false)] + [InlineData("2001:2f::1", false)] + [InlineData("3fff::1", false)] + [InlineData("5f00::1", false)] + [InlineData("2001:30::1", true)] + [InlineData("2001:4860:4860::8888", true)] [InlineData("8.8.8.8", true)] [InlineData("172.32.0.1", true)] [InlineData("100.128.0.1", true)] @@ -295,19 +306,115 @@ public class OpenIddictServerSystemNetHttpRequestObjectFetcherTests } [Theory] - [InlineData("https://127.0.0.1/request_objects/1")] - [InlineData("https://[::1]/request_objects/1")] - [InlineData("https://10.0.0.1/request_objects/1")] - [InlineData("https://169.254.169.254/latest/meta-data")] - [InlineData("https://localhost/request_objects/1")] - public async Task FetchAsync_RejectsDisallowedRemoteAddresses(string uri) + [InlineData("10.0.0.1")] + [InlineData("169.254.169.254")] + [InlineData("[::1]")] + public async Task FetchAsync_RejectsDisallowedRemoteAddressesUsingFilter(string host) { // Arrange + var addresses = new ConcurrentBag(); + using var fetcher = new OpenIddictServerSystemNetHttpRequestObjectFetcher( - CreateOptions(), NullLogger.Instance); + CreateOptions(options => options.RemoteAddressFilter = address => + { + addresses.Add(address); + return OpenIddictServerSystemNetHttpHelpers.IsPublicAddress(address); + }), + NullLogger.Instance); - // Act and assert - Assert.Null(await fetcher.FetchAsync(new Uri(uri, UriKind.Absolute), CancellationToken.None)); + // Act + var result = await fetcher.FetchAsync(new Uri($"https://{host}/request_objects/1", UriKind.Absolute), CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.Contains(IPAddress.Parse(host.Trim('[', ']')), addresses); + } + + [Theory] + [InlineData("127.0.0.1")] + [InlineData("localhost")] + public async Task FetchAsync_DoesNotConnectToDisallowedRemoteAddresses(string host) + { + // Arrange + var listener = TcpListener.Create(0); + listener.Start(); + + try + { + var port = ((IPEndPoint) listener.LocalEndpoint).Port.ToString(CultureInfo.InvariantCulture); + var addresses = new ConcurrentBag(); + + using var fetcher = new OpenIddictServerSystemNetHttpRequestObjectFetcher( + CreateOptions(options => options.RemoteAddressFilter = address => + { + addresses.Add(address); + return OpenIddictServerSystemNetHttpHelpers.IsPublicAddress(address); + }), + NullLogger.Instance); + + // Act + var result = await fetcher.FetchAsync(new Uri($"https://{host}:{port}/request_objects/1", UriKind.Absolute), CancellationToken.None); + + // Assert + Assert.Null(result); + Assert.NotEmpty(addresses); + Assert.All(addresses, address => Assert.True(IPAddress.IsLoopback(address))); + Assert.False(listener.Pending()); + } + + finally + { + listener.Stop(); + } + } + + [Fact] + public async Task FetchAsync_ConnectsToRemoteAddressesAllowedByFilter() + { + // Arrange + var listener = new TcpListener(IPAddress.Loopback, 0); + listener.Start(); + + try + { + var port = ((IPEndPoint) listener.LocalEndpoint).Port.ToString(CultureInfo.InvariantCulture); + var addresses = new ConcurrentBag(); + + using var fetcher = new OpenIddictServerSystemNetHttpRequestObjectFetcher( + CreateOptions(options => + { + options.RequestObjectTimeout = TimeSpan.FromSeconds(10); + options.RemoteAddressFilter = address => + { + addresses.Add(address); + return true; + }; + }), + NullLogger.Instance); + + // Act + var task = fetcher.FetchAsync(new Uri($"https://127.0.0.1:{port}/request_objects/1", UriKind.Absolute), CancellationToken.None).AsTask(); + var accept = listener.AcceptTcpClientAsync(); + + // Assert +#if NET + var delay = Task.Delay(TimeSpan.FromSeconds(10), TimeProvider.System); +#else + var delay = TimeProvider.System.Delay(TimeSpan.FromSeconds(10)); +#endif + Assert.Same(accept, await Task.WhenAny(accept, delay)); + + // Close the connection without completing the TLS handshake. + (await accept).Dispose(); + + Assert.Null(await task); + Assert.Contains(IPAddress.Loopback, addresses); + } + + finally + { + listener.Stop(); + } } [Fact] diff --git a/test/OpenIddict.Server.Tests/OpenIddictServerIssuerResolutionTests.cs b/test/OpenIddict.Server.Tests/OpenIddictServerIssuerResolutionTests.cs index dc2d48b4..43da47cc 100644 --- a/test/OpenIddict.Server.Tests/OpenIddictServerIssuerResolutionTests.cs +++ b/test/OpenIddict.Server.Tests/OpenIddictServerIssuerResolutionTests.cs @@ -181,15 +181,72 @@ public class OpenIddictServerIssuerResolutionTests => Assert.False(OpenIddictServerIssuerResolution.IsIssuedBy( new ClaimsPrincipal(new ClaimsIdentity()), new Uri("https://contoso.com/"))); + [Fact] + public void Validate_ReturnsAnErrorWhenNoIssuerSourceIsConfigured() + { + // Arrange + var options = CreateOptions(); + + // Act + var failures = Validate(options); + + // Assert + Assert.Contains(SR.GetResourceString(SR.ID0929), failures, StringComparer.Ordinal); + } + + [Fact] + public void Validate_DoesNotReturnAnErrorWhenIssuersAreRegistered() + { + // Arrange + var options = CreateOptions(); + options.Issuers.Add(new Uri("https://contoso.com/")); + + // Act + var failures = Validate(options); + + // Assert + Assert.DoesNotContain(SR.GetResourceString(SR.ID0929), failures, StringComparer.Ordinal); + } + + [Fact] + public void Validate_DoesNotReturnAnErrorWhenCustomResolverIsRegistered() + { + // Arrange + var options = CreateOptions(); + var services = new ServiceCollection(); + services.AddSingleton(); + + // Act + var failures = Validate(options, services.BuildServiceProvider()); + + // Assert + Assert.DoesNotContain(SR.GetResourceString(SR.ID0929), failures, StringComparer.Ordinal); + } + + [Fact] + public void Validate_DoesNotReturnAnErrorWhenScopedResolverIsRegistered() + { + // Arrange + var options = CreateOptions(); + var services = new ServiceCollection(); + services.AddScoped(); + + // Act + var failures = Validate(options, services.BuildServiceProvider(validateScopes: true)); + + // Assert + Assert.DoesNotContain(SR.GetResourceString(SR.ID0929), failures, StringComparer.Ordinal); + } + private static OpenIddictServerOptions CreateOptions() => new() { EnableIssuerResolution = true, TimeProvider = TimeProvider.System }; - private static string[] Validate(OpenIddictServerOptions options) + private static string[] Validate(OpenIddictServerOptions options, IServiceProvider? provider = null) { - var configuration = new OpenIddictServerConfiguration(new ServiceCollection().BuildServiceProvider()); + var configuration = new OpenIddictServerConfiguration(provider ?? new ServiceCollection().BuildServiceProvider()); return [.. configuration.Validate(name: null, options).Failures ?? []]; }