Browse Source

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
pull/2549/head
pieroviano 2 months ago
parent
commit
6c6fab8a16
  1. 9
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  2. 8
      src/OpenIddict.Server.SystemNetHttp/OpenIddictServerSystemNetHttpHelpers.cs
  3. 4
      src/OpenIddict.Server/IOpenIddictServerIssuerResolver.cs
  4. 21
      src/OpenIddict.Server/OpenIddictServerConfiguration.cs
  5. 22
      src/OpenIddict.Server/OpenIddictServerHandlers.Authentication.cs
  6. 9
      src/OpenIddict.Server/OpenIddictServerHandlers.cs
  7. 43
      test/OpenIddict.Server.AspNetCore.IntegrationTests/OpenIddictServerAspNetCoreIssuerResolutionValidationTests.cs
  8. 14
      test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.IssuerResolution.cs
  9. 155
      test/OpenIddict.Server.IntegrationTests/OpenIddictServerIntegrationTests.RequestObjectReference.cs
  10. 125
      test/OpenIddict.Server.SystemNetHttp.Tests/OpenIddictServerSystemNetHttpRequestObjectFetcherTests.cs
  11. 61
      test/OpenIddict.Server.Tests/OpenIddictServerIssuerResolutionTests.cs

9
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -3204,6 +3204,9 @@ To register issuers, call 'services.AddOpenIddict().AddServer().AddIssuers()' or
<data name="ID2465" xml:space="preserve">
<value>The issuer of the current request couldn't be resolved.</value>
</data>
<data name="ID2466" xml:space="preserve">
<value>The '{0}' parameter must reference a pushed authorization request.</value>
</data>
<data name="ID4000" xml:space="preserve">
<value>The '{0}' parameter shouldn't be null or empty at this point.</value>
</data>
@ -4407,6 +4410,12 @@ This may indicate that the hashed entry is corrupted or malformed.</value>
<data name="ID6734" xml:space="preserve">
<value>The request object retrieved from '{RequestUri}' was rejected because it is not a valid UTF-8 string.</value>
</data>
<data name="ID6735" xml:space="preserve">
<value>The authorization request was rejected because the external request_uri '{RequestUri}' was used while pushed authorization requests are required.</value>
</data>
<data name="ID6736" xml:space="preserve">
<value>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.</value>
</data>
<data name="ID8000" xml:space="preserve">
<value>https://documentation.openiddict.com/errors/{0}</value>
</data>

8
src/OpenIddict.Server.SystemNetHttp/OpenIddictServerSystemNetHttpHelpers.cs

@ -17,7 +17,8 @@ public static class OpenIddictServerSystemNetHttpHelpers
/// <summary>
/// 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).
/// </summary>
/// <param name="address">The IP address.</param>
/// <returns><see langword="true"/> if the address is a public unicast address, <see langword="false"/> otherwise.</returns>
@ -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)

4
src/OpenIddict.Server/IOpenIddictServerIssuerResolver.cs

@ -13,6 +13,10 @@ namespace OpenIddict.Server;
/// <remarks>
/// 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.
/// </remarks>
public interface IOpenIddictServerIssuerResolver
{

21
src/OpenIddict.Server/OpenIddictServerConfiguration.cs

@ -451,6 +451,12 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions<OpenId
builder.AddError(SR.GetResourceString(SR.ID0924));
}
// Note: a missing issuer source would otherwise cause every request handled by the host to fail.
if (options.Issuers.Count is 0 && !HasIssuerResolver())
{
builder.AddError(SR.GetResourceString(SR.ID0929));
}
if (options.GrantTypes.Contains(GrantTypes.Ciba) ||
options.MtlsDeviceAuthorizationEndpointAliasUri is not null ||
options.MtlsIntrospectionEndpointAliasUri is not null ||
@ -898,5 +904,20 @@ public sealed class OpenIddictServerConfiguration : IPostConfigureOptions<OpenId
static bool TryValidateMtlsEndpointAlias(Uri? uri) => uri is null ||
(uri.IsAbsoluteUri && string.Equals(uri.Scheme, Uri.UriSchemeHttps, StringComparison.OrdinalIgnoreCase));
bool HasIssuerResolver()
{
try
{
return _provider.GetService<IOpenIddictServerIssuerResolver>() 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;
}
}
}
}

22
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)

9
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;
}
}

43
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<string> 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<IHost> CreateHostAsync(bool credentials)
private static async Task<IHost> 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<TenantCredentialsProvider>();
@ -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<OpenIddictServerCredentials?> 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);
}
}

14
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<InvalidOperationException>(
() => client.GetAsync("http://localhost/.well-known/openid-configuration"));
Assert.Equal(SR.GetResourceString(SR.ID0929), exception.Message);
}
[Fact]
public async Task IssuerResolution_IssuerSpecificCredentialsAreUsed()
{

155
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<HandleAuthorizationRequestContext>(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<HandleAuthorizationRequestContext>(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<HandleAuthorizationRequestContext>(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()
{

125
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<IPAddress>();
using var fetcher = new OpenIddictServerSystemNetHttpRequestObjectFetcher(
CreateOptions(), NullLogger<OpenIddictServerSystemNetHttpRequestObjectFetcher>.Instance);
CreateOptions(options => options.RemoteAddressFilter = address =>
{
addresses.Add(address);
return OpenIddictServerSystemNetHttpHelpers.IsPublicAddress(address);
}),
NullLogger<OpenIddictServerSystemNetHttpRequestObjectFetcher>.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<IPAddress>();
using var fetcher = new OpenIddictServerSystemNetHttpRequestObjectFetcher(
CreateOptions(options => options.RemoteAddressFilter = address =>
{
addresses.Add(address);
return OpenIddictServerSystemNetHttpHelpers.IsPublicAddress(address);
}),
NullLogger<OpenIddictServerSystemNetHttpRequestObjectFetcher>.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<IPAddress>();
using var fetcher = new OpenIddictServerSystemNetHttpRequestObjectFetcher(
CreateOptions(options =>
{
options.RequestObjectTimeout = TimeSpan.FromSeconds(10);
options.RemoteAddressFilter = address =>
{
addresses.Add(address);
return true;
};
}),
NullLogger<OpenIddictServerSystemNetHttpRequestObjectFetcher>.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]

61
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<IOpenIddictServerIssuerResolver, NullIssuerResolver>();
// 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<IOpenIddictServerIssuerResolver, NullIssuerResolver>();
// 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 ?? []];
}

Loading…
Cancel
Save