diff --git a/identity-server/src/IdentityServer/Validation/Default/TokenRequestValidator.cs b/identity-server/src/IdentityServer/Validation/Default/TokenRequestValidator.cs index 5d326b6b7..2c90e1aea 100644 --- a/identity-server/src/IdentityServer/Validation/Default/TokenRequestValidator.cs +++ b/identity-server/src/IdentityServer/Validation/Default/TokenRequestValidator.cs @@ -216,15 +216,15 @@ public async Task ValidateRequestAsync(TokenReques private async Task ValidateProofToken(TokenRequestValidationContext context) { - // can't allow both both at once - if (context.ClientCertificate != null && context.DPoPProofToken.IsPresent()) - { - LogError("Only one confirmation mechanism is allowed at a time."); - return Invalid(OidcConstants.TokenErrors.InvalidRequest, "Only one confirmation mechanism is allowed at a time"); - } // mTLS client cert processing - if (context.ClientCertificate != null) + // + // If both a dpop proof and client certificate are present, we use the + // proof token for sender-constraining the token. DPoP takes precedence + // because that's the only sensible interpretation of the client's + // request. DPoP can only be used for sender constraining the token, + // but client certificates can also be used as client authentication. + if (context.ClientCertificate != null && context.DPoPProofToken.IsMissing()) { if (_options.MutualTls.AlwaysEmitConfirmationClaim && _validatedRequest.Confirmation.IsMissing()) { diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/IdentityServerPipeline.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/IdentityServerPipeline.cs index f62c0dc40..2b2bb97b2 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Common/IdentityServerPipeline.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/IdentityServerPipeline.cs @@ -4,6 +4,7 @@ using System.Net; using System.Security.Claims; +using System.Security.Cryptography.X509Certificates; using System.Text.Json; using Duende.IdentityModel.Client; using Duende.IdentityServer; @@ -17,6 +18,7 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.TestHost; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; @@ -39,6 +41,7 @@ public class IdentityServerPipeline public const string AuthorizeEndpoint = BaseUrl + "/connect/authorize"; public const string BackchannelAuthenticationEndpoint = BaseUrl + "/connect/ciba"; public const string TokenEndpoint = BaseUrl + "/connect/token"; + public const string TokenMtlsEndpoint = BaseUrl + "/connect/mtls/token"; public const string RevocationEndpoint = BaseUrl + "/connect/revocation"; public const string UserInfoEndpoint = BaseUrl + "/connect/userinfo"; public const string IntrospectionEndpoint = BaseUrl + "/connect/introspect"; @@ -47,6 +50,7 @@ public class IdentityServerPipeline public const string CheckSessionEndpoint = BaseUrl + "/connect/checksession"; public const string ParEndpoint = BaseUrl + "/connect/par"; + public const string FederatedSignOutPath = "/signout-oidc"; public const string FederatedSignOutUrl = BaseUrl + FederatedSignOutPath; @@ -63,6 +67,10 @@ public class IdentityServerPipeline public BrowserClient BrowserClient { get; set; } public HttpClient BackChannelClient { get; set; } + // mTLS support + public X509Certificate2 ClientCertificate { get; set; } + public HttpClient MtlsBackChannelClient { get; set; } + public MockMessageHandler BackChannelMessageHandler { get; set; } = new MockMessageHandler(); public MockMessageHandler JwtRequestMessageHandler { get; set; } = new MockMessageHandler(); @@ -107,6 +115,9 @@ public void Initialize(string basePath = null, bool enableLogging = false) BrowserClient = new BrowserClient(new BrowserHandler(Handler)); BackChannelClient = new HttpClient(Handler); + + // Initialize mTLS client (will be null until a certificate is set) + UpdateMtlsClient(); } public void ConfigureServices(IServiceCollection services) @@ -120,6 +131,11 @@ public void ConfigureServices(IServiceCollection services) scheme.DisplayName = "External"; scheme.HandlerType = typeof(MockExternalAuthenticationHandler); }); + opts.AddScheme("Certificate", scheme => + { + scheme.DisplayName = "Certificate"; + scheme.HandlerType = typeof(MockCertificateAuthenticationHandler); + }); }); services.AddTransient(svcs => { @@ -143,6 +159,8 @@ public void ConfigureServices(IServiceCollection services) }; options.KeyManagement.Enabled = false; + options.MutualTls.Enabled = true; + Options = options; }) .AddInMemoryClients(Clients) @@ -150,7 +168,8 @@ public void ConfigureServices(IServiceCollection services) .AddInMemoryApiResources(ApiResources) .AddInMemoryApiScopes(ApiScopes) .AddTestUsers(Users) - .AddDeveloperSigningCredential(persistKey: false); + .AddDeveloperSigningCredential(persistKey: false) + .AddMutualTlsSecretValidators(); services.AddHttpClient(IdentityServerConstants.HttpClients.BackChannelLogoutHttpClient) .AddHttpMessageHandler(() => BackChannelMessageHandler); @@ -167,6 +186,9 @@ public void ConfigureApp(IApplicationBuilder app) OnPreConfigure(app); + // Add mTLS test middleware before IdentityServer middleware + app.UseMiddleware(); + app.UseIdentityServer(); // UI endpoints @@ -463,6 +485,40 @@ public string CreateAuthorizeUrl( public T Resolve() => // create throw-away scope ApplicationServices.CreateScope().ServiceProvider.GetRequiredService(); + + /* mTLS helpers */ + public void SetClientCertificate(X509Certificate2 certificate) + { + ClientCertificate = certificate; + UpdateMtlsClient(); + } + + private void UpdateMtlsClient() + { + MtlsBackChannelClient?.Dispose(); + + if (ClientCertificate != null) + { + var mtlsHandler = new MtlsMessageHandler(Handler, ClientCertificate); + MtlsBackChannelClient = new HttpClient(mtlsHandler) + { + BaseAddress = new Uri(BaseUrl) + }; + } + else + { + MtlsBackChannelClient = null; + } + } + + public HttpClient GetMtlsClient() + { + if (MtlsBackChannelClient == null) + { + throw new InvalidOperationException("No client certificate has been set. Call SetClientCertificate() first."); + } + return MtlsBackChannelClient; + } } public class MockMessageHandler : DelegatingHandler @@ -522,3 +578,30 @@ public async Task HandleRequestAsync() public Task SignOutAsync(AuthenticationProperties properties) => Task.CompletedTask; } + +public class MockCertificateAuthenticationHandler : IAuthenticationHandler +{ + private HttpContext _context; + private string _scheme; + + public Task AuthenticateAsync() + { + if (_context?.Features.Get() is { ClientCertificate: not null }) + { + return Task.FromResult(AuthenticateResult.Success(new AuthenticationTicket( + new ClaimsPrincipal(new ClaimsIdentity([])), _scheme))); + } + return Task.FromResult(AuthenticateResult.Fail("No client certificate set.")); + } + + public Task InitializeAsync(AuthenticationScheme scheme, HttpContext context) + { + _scheme = scheme.Name; + _context = context; + return Task.CompletedTask; + } + + public Task ChallengeAsync(AuthenticationProperties properties) => Task.CompletedTask; + + public Task ForbidAsync(AuthenticationProperties properties) => Task.CompletedTask; +} diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsMessageHandler.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsMessageHandler.cs new file mode 100644 index 000000000..6002acb77 --- /dev/null +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsMessageHandler.cs @@ -0,0 +1,31 @@ +// Copyright (c) Duende Software. All rights reserved. +// See LICENSE in the project root for license information. + + +using System.Security.Cryptography.X509Certificates; + +namespace IntegrationTests.Common; + +/// +/// Message handler that injects a client certificate into the HTTP request for testing mTLS scenarios +/// +public class MtlsMessageHandler : DelegatingHandler +{ + private readonly X509Certificate2 _clientCertificate; + + public MtlsMessageHandler(HttpMessageHandler innerHandler, X509Certificate2 clientCertificate) + : base(innerHandler) => _clientCertificate = clientCertificate; + + protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) + { + // Add the client certificate as a base64 encoded header for the test middleware to pick up + if (_clientCertificate != null) + { + var certBytes = _clientCertificate.Export(X509ContentType.Cert); + var certBase64 = Convert.ToBase64String(certBytes); + request.Headers.Add("X-Test-Client-Certificate", certBase64); + } + + return await base.SendAsync(request, cancellationToken); + } +} diff --git a/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsTestMiddleware.cs b/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsTestMiddleware.cs new file mode 100644 index 000000000..9a7b90492 --- /dev/null +++ b/identity-server/test/IdentityServer.IntegrationTests/Common/MtlsTestMiddleware.cs @@ -0,0 +1,76 @@ +// Copyright (c) Duende Software. All rights reserved. +// See LICENSE in the project root for license information. + + +using System.Security.Cryptography.X509Certificates; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; + +namespace IntegrationTests.Common; + +/// +/// Middleware for testing mTLS scenarios by injecting client certificates from request properties +/// +public class MtlsTestMiddleware +{ + private readonly RequestDelegate _next; + + public MtlsTestMiddleware(RequestDelegate next) => _next = next; + + public async Task InvokeAsync(HttpContext context) + { + // Check if the request has a client certificate in its properties + if (context.Request.HttpContext.Features.Get() is IHttpRequestFeature requestFeature) + { + // Try to get the certificate from request properties (injected by MtlsMessageHandler) + if (context.Features.Get() == null) + { + // Look for certificate in request headers or properties + // This is a simplified approach for testing - in real scenarios the certificate + // would be part of the TLS handshake + var cert = GetClientCertificateFromRequest(context); + if (cert != null) + { + // Create a custom feature to hold the client certificate + var tlsFeature = new TlsConnectionFeature { ClientCertificate = cert }; + context.Features.Set(tlsFeature); + } + } + } + + await _next(context); + } + + private static X509Certificate2 GetClientCertificateFromRequest(HttpContext context) + { + // For testing purposes, we'll try to get the certificate from a custom header + // This simulates what would normally be provided by the TLS layer + if (context.Request.Headers.TryGetValue("X-Test-Client-Certificate", out var certHeader)) + { + try + { + var certBytes = Convert.FromBase64String(certHeader.First()); +#pragma warning disable SYSLIB0057 // Type or member is obsolete + return new X509Certificate2(certBytes); +#pragma warning restore SYSLIB0057 // Type or member is obsolete + } + catch + { + // Ignore invalid certificate data + } + } + + return null; + } +} + +/// +/// Custom implementation of ITlsConnectionFeature for testing +/// +public class TlsConnectionFeature : ITlsConnectionFeature +{ + public X509Certificate2 ClientCertificate { get; set; } + + public Task GetClientCertificateAsync(CancellationToken cancellationToken) + => Task.FromResult(ClientCertificate); +} diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/DPoPTokenEndpointTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/DPoPTokenEndpointTests.cs index 51a8f577f..ca620ddc1 100644 --- a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/DPoPTokenEndpointTests.cs +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/DPoPTokenEndpointTests.cs @@ -73,7 +73,7 @@ public async Task valid_dpop_request_should_return_bound_access_token() [Trait("Category", Category)] public async Task valid_dpop_request_with_unusual_but_valid_proof_token_should_return_bound_access_token() { - // The point here is to have an array in the payload, to exercise + // The point here is to have an array in the payload, to exercise // the json serialization Payload.Add("key_ops", new string[] { "sign", "verify" }); var request = CreateClientCredentialsTokenRequest(); @@ -448,6 +448,59 @@ public async Task all_supported_signing_algorithms_should_work(string alg, KeyTy var jkt = GetJKTFromAccessToken(response); jkt.ShouldBe(JKT); } + + [Fact] + [Trait("Category", Category)] + public async Task mtls_and_dpop_request_should_succeed() + { + var clientId = "mtls_dpop_client"; + var clientCert = TestCert.Load(); + + // Add a client that requires mTLS and supports DPoP + var client = new Client + { + ClientId = clientId, + ClientSecrets = + { + new Secret + { + Type = IdentityServerConstants.SecretTypes.X509CertificateThumbprint, + Value = clientCert.Thumbprint + } + }, + AllowedGrantTypes = GrantTypes.ClientCredentials, + AllowedScopes = { "scope1" }, + RequireDPoP = true + }; + + Pipeline.Clients.Add(client); + Pipeline.Initialize(); + + // Set the client certificate in the pipeline + Pipeline.SetClientCertificate(clientCert); + + // Act - Make a client credentials request using mTLS and DPoP + var tokenClient = Pipeline.GetMtlsClient(); + + var formParams = new Dictionary + { + { "grant_type", "client_credentials" }, + { "client_id", clientId }, + { "scope", "scope1" } + }; + + var form = new FormUrlEncodedContent(formParams); + tokenClient.DefaultRequestHeaders.Add("DPoP", CreateDPoPProofToken()); + + var response = await tokenClient.PostAsync(IdentityServerPipeline.TokenMtlsEndpoint, form); + + // Assert + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var json = await response.Content.ReadAsStringAsync(); + json.ShouldContain("access_token"); + json.ShouldContain("\"token_type\":\"DPoP\""); + } } public class ParModes : TheoryData diff --git a/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/MtlsTokenEndpointTests.cs b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/MtlsTokenEndpointTests.cs new file mode 100644 index 000000000..34232f44c --- /dev/null +++ b/identity-server/test/IdentityServer.IntegrationTests/Endpoints/Token/MtlsTokenEndpointTests.cs @@ -0,0 +1,124 @@ +// Copyright (c) Duende Software. All rights reserved. +// See LICENSE in the project root for license information. + + +using Duende.IdentityServer; +using Duende.IdentityServer.Models; +using IntegrationTests.Common; + +namespace IntegrationTests.Endpoints.Token; + +public class MtlsTokenEndpointTests +{ + private const string Category = "mTLS Token endpoint"; + + private IdentityServerPipeline _pipeline = new IdentityServerPipeline(); + + [Fact] + [Trait("Category", Category)] + public async Task client_credentials_request_with_client_certificate_should_succeed() + { + // Arrange + var clientId = "mtls_client"; + + // Load a test certificate + var clientCert = TestCert.Load(); + + // Add a client that requires mTLS (client certificate) + var client = new Client + { + ClientId = clientId, + ClientSecrets = + { + new Secret + { + Type = IdentityServerConstants.SecretTypes.X509CertificateThumbprint, + Value = clientCert.Thumbprint + } + }, + AllowedGrantTypes = GrantTypes.ClientCredentials, + AllowedScopes = { "scope1" } + }; + + _pipeline.Clients.Add(client); + _pipeline.ApiScopes.Add(new ApiScope("scope1")); + _pipeline.Initialize(); + + // Set the client certificate in the pipeline + _pipeline.SetClientCertificate(clientCert); + + // Act - Make a client credentials request using mTLS client + var tokenClient = _pipeline.GetMtlsClient(); + + var formParams = new Dictionary + { + { "grant_type", "client_credentials" }, + { "client_id", clientId }, + { "scope", "scope1" } + }; + + var form = new FormUrlEncodedContent(formParams); + var response = await tokenClient.PostAsync(IdentityServerPipeline.TokenMtlsEndpoint, form); + + // Assert + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var json = await response.Content.ReadAsStringAsync(); + json.ShouldContain("access_token"); + json.ShouldContain("\"token_type\":\"Bearer\""); + } + + [Fact] + [Trait("Category", Category)] + public async Task client_credentials_request_without_client_certificate_should_still_work_with_secret() + { + // Arrange + var clientId = "regular_client"; + var clientSecret = "secret"; + + var client = new Client + { + ClientId = clientId, + ClientSecrets = { new Secret(clientSecret.Sha256()) }, + AllowedGrantTypes = GrantTypes.ClientCredentials, + AllowedScopes = { "scope1" } + }; + + _pipeline.Clients.Add(client); + _pipeline.ApiScopes.Add(new ApiScope("scope1")); + _pipeline.Initialize(); + + // Act - Make a client credentials request using regular client (no mTLS) + var tokenClient = _pipeline.BrowserClient; + + var formParams = new Dictionary + { + { "grant_type", "client_credentials" }, + { "client_id", clientId }, + { "client_secret", clientSecret }, + { "scope", "scope1" } + }; + + var form = new FormUrlEncodedContent(formParams); + var response = await tokenClient.PostAsync(IdentityServerPipeline.TokenEndpoint, form); + + // Assert + response.StatusCode.ShouldBe(System.Net.HttpStatusCode.OK); + + var json = await response.Content.ReadAsStringAsync(); + json.ShouldContain("access_token"); + json.ShouldContain("\"token_type\":\"Bearer\""); + } + + [Fact] + [Trait("Category", Category)] + public void infrastructure_should_reject_mtls_client_request_when_no_certificate_set() + { + // Arrange + _pipeline.Initialize(); + + // Act & Assert - Trying to get mTLS client without setting certificate should throw + var action = () => _pipeline.GetMtlsClient(); + action.ShouldThrow("No client certificate has been set. Call SetClientCertificate() first."); + } +}