diff --git a/OpenIddict.slnx b/OpenIddict.slnx index a82e216d..3dde8d62 100644 --- a/OpenIddict.slnx +++ b/OpenIddict.slnx @@ -88,6 +88,7 @@ + @@ -107,6 +108,7 @@ + diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx index debb0713..2f79a0b6 100644 --- a/src/OpenIddict.Abstractions/OpenIddictResources.resx +++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx @@ -3288,6 +3288,15 @@ This may indicate that the hashed entry is corrupted or malformed. A non-fatal error occurred while pruning sessions from the database. + + An invalid JSON payload was returned by the remote HTTP server ({ContentType}, {ContentLength} bytes). Note: sensitive payload logging can be enabled to include the raw payload in the logs. + + + A generic {StatusCode} response was returned by the remote HTTP server ({ContentType}, {ContentLength} bytes). Note: sensitive payload logging can be enabled to include the raw payload in the logs. + + + An unsupported {StatusCode} response was returned by the remote HTTP server ({ContentType}, {ContentLength} bytes). Note: sensitive payload logging can be enabled to include the raw payload in the logs. + https://documentation.openiddict.com/errors/{0} diff --git a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpBuilder.cs b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpBuilder.cs index ff6b83fb..dc24d047 100644 --- a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpBuilder.cs +++ b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpBuilder.cs @@ -256,6 +256,16 @@ public sealed class OpenIddictClientSystemNetHttpBuilder } #endif + /// + /// Enables logging the raw payloads of the HTTP responses returned by the remote + /// server when an invalid or unexpected response is received. Since raw payloads + /// may contain sensitive data (e.g access tokens or refresh tokens), this option + /// should only be enabled in development environments. + /// + /// The instance. + public OpenIddictClientSystemNetHttpBuilder EnableSensitivePayloadLogging() + => Configure(options => options.EnableSensitivePayloadLogging = true); + /// /// Sets the product information used in the "User-Agent" header that is attached /// to the backchannel HTTP requests sent to the authorization server. diff --git a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs index ce017923..b7ba28ff 100644 --- a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs +++ b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs @@ -684,6 +684,11 @@ public static partial class OpenIddictClientSystemNetHttpHandlers /// public sealed class ExtractJsonHttpResponse : IOpenIddictClientHandler where TContext : BaseExternalContext { + private readonly IOptionsMonitor _options; + + public ExtractJsonHttpResponse(IOptionsMonitor options) + => _options = options ?? throw new ArgumentNullException(nameof(options)); + /// /// Gets the default descriptor definition assigned to this handler. /// @@ -738,8 +743,19 @@ public static partial class OpenIddictClientSystemNetHttpHandlers // a server error occurs while the JSON response is being generated and returned to the client. catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception)) { - context.Logger.LogError(6183, exception, SR.GetResourceString(SR.ID6183), - await response.Content.ReadAsStringAsync(context.CancellationToken)); + // Note: the raw payload is only logged if sensitive payload logging was explicitly + // enabled, as it may contain sensitive data (e.g access tokens or refresh tokens). + if (_options.CurrentValue.EnableSensitivePayloadLogging) + { + context.Logger.LogError(6183, exception, SR.GetResourceString(SR.ID6183), + await response.Content.ReadAsStringAsync(context.CancellationToken)); + } + + else + { + context.Logger.LogError(6183, exception, SR.GetResourceString(SR.ID6301), + response.Content.Headers.ContentType, response.Content.Headers.ContentLength); + } context.Reject( error: Errors.ServerError, @@ -934,6 +950,11 @@ public static partial class OpenIddictClientSystemNetHttpHandlers /// public sealed class ValidateHttpResponse : IOpenIddictClientHandler where TContext : BaseExternalContext { + private readonly IOptionsMonitor _options; + + public ValidateHttpResponse(IOptionsMonitor options) + => _options = options ?? throw new ArgumentNullException(nameof(options)); + /// /// Gets the default descriptor definition assigned to this handler. /// @@ -959,8 +980,19 @@ public static partial class OpenIddictClientSystemNetHttpHandlers // error could be extracted from the payload or from the WWW-Authenticate header. if (!response.IsSuccessStatusCode && string.IsNullOrEmpty(context.Transaction.Response?.Error)) { - context.Logger.LogError(6184, SR.GetResourceString(SR.ID6184), response.StatusCode, - await response.Content.ReadAsStringAsync(context.CancellationToken)); + // Note: the raw payload is only logged if sensitive payload logging was explicitly + // enabled, as it may contain sensitive data (e.g access tokens or refresh tokens). + if (_options.CurrentValue.EnableSensitivePayloadLogging) + { + context.Logger.LogError(6184, SR.GetResourceString(SR.ID6184), response.StatusCode, + await response.Content.ReadAsStringAsync(context.CancellationToken)); + } + + else + { + context.Logger.LogError(6184, SR.GetResourceString(SR.ID6302), response.StatusCode, + response.Content.Headers.ContentType, response.Content.Headers.ContentLength); + } context.Reject( error: (int) response.StatusCode switch @@ -983,8 +1015,19 @@ public static partial class OpenIddictClientSystemNetHttpHandlers // (e.g because an unsupported content type was returned), return a generic error. if (context.Transaction.Response is null) { - context.Logger.LogError(6185, SR.GetResourceString(SR.ID6185), response.StatusCode, - response.Content.Headers.ContentType, await response.Content.ReadAsStringAsync(context.CancellationToken)); + // Note: the raw payload is only logged if sensitive payload logging was explicitly + // enabled, as it may contain sensitive data (e.g access tokens or refresh tokens). + if (_options.CurrentValue.EnableSensitivePayloadLogging) + { + context.Logger.LogError(6185, SR.GetResourceString(SR.ID6185), response.StatusCode, + response.Content.Headers.ContentType, await response.Content.ReadAsStringAsync(context.CancellationToken)); + } + + else + { + context.Logger.LogError(6185, SR.GetResourceString(SR.ID6303), response.StatusCode, + response.Content.Headers.ContentType, response.Content.Headers.ContentLength); + } context.Reject( error: Errors.ServerError, diff --git a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpOptions.cs b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpOptions.cs index de8935be..859cf9dc 100644 --- a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpOptions.cs +++ b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpOptions.cs @@ -69,6 +69,16 @@ public sealed class OpenIddictClientSystemNetHttpOptions /// public ProductInfoHeaderValue? ProductInformation { get; set; } + /// + /// Gets or sets a boolean indicating whether the raw payloads of the HTTP responses returned by + /// the remote server should be included in the logs when an invalid or unexpected response is received. + /// + /// + /// Note: raw payloads may contain sensitive data (e.g access tokens or refresh tokens). + /// As such, this option should only be enabled in development environments. + /// + public bool EnableSensitivePayloadLogging { get; set; } + /// /// Gets the user-defined actions used to amend the /// instances created by the OpenIddict client/System.Net.Http integration. diff --git a/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpBuilder.cs b/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpBuilder.cs index 26fc46d7..6e6fd839 100644 --- a/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpBuilder.cs +++ b/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpBuilder.cs @@ -164,6 +164,16 @@ public sealed class OpenIddictValidationSystemNetHttpBuilder } #endif + /// + /// Enables logging the raw payloads of the HTTP responses returned by the remote + /// server when an invalid or unexpected response is received. Since raw payloads + /// may contain sensitive data (e.g access tokens or refresh tokens), this option + /// should only be enabled in development environments. + /// + /// The instance. + public OpenIddictValidationSystemNetHttpBuilder EnableSensitivePayloadLogging() + => Configure(options => options.EnableSensitivePayloadLogging = true); + /// /// Sets the product information used in the "User-Agent" header that is attached /// to the backchannel HTTP requests sent to the authorization server. diff --git a/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpHandlers.cs b/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpHandlers.cs index bd5fe405..78e1f460 100644 --- a/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpHandlers.cs +++ b/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpHandlers.cs @@ -680,6 +680,11 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers /// public sealed class ExtractJsonHttpResponse : IOpenIddictValidationHandler where TContext : BaseExternalContext { + private readonly IOptionsMonitor _options; + + public ExtractJsonHttpResponse(IOptionsMonitor options) + => _options = options ?? throw new ArgumentNullException(nameof(options)); + /// /// Gets the default descriptor definition assigned to this handler. /// @@ -734,8 +739,19 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers // a server error occurs while the JSON response is being generated and returned to the client. catch (Exception exception) when (!OpenIddictHelpers.IsFatal(exception)) { - context.Logger.LogError(6183, exception, SR.GetResourceString(SR.ID6183), - await response.Content.ReadAsStringAsync(context.CancellationToken)); + // Note: the raw payload is only logged if sensitive payload logging was explicitly + // enabled, as it may contain sensitive data (e.g access tokens or refresh tokens). + if (_options.CurrentValue.EnableSensitivePayloadLogging) + { + context.Logger.LogError(6183, exception, SR.GetResourceString(SR.ID6183), + await response.Content.ReadAsStringAsync(context.CancellationToken)); + } + + else + { + context.Logger.LogError(6183, exception, SR.GetResourceString(SR.ID6301), + response.Content.Headers.ContentType, response.Content.Headers.ContentLength); + } context.Reject( error: Errors.ServerError, @@ -887,6 +903,11 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers /// public sealed class ValidateHttpResponse : IOpenIddictValidationHandler where TContext : BaseExternalContext { + private readonly IOptionsMonitor _options; + + public ValidateHttpResponse(IOptionsMonitor options) + => _options = options ?? throw new ArgumentNullException(nameof(options)); + /// /// Gets the default descriptor definition assigned to this handler. /// @@ -912,8 +933,19 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers // error could be extracted from the payload or from the WWW-Authenticate header. if (!response.IsSuccessStatusCode && string.IsNullOrEmpty(context.Transaction.Response?.Error)) { - context.Logger.LogError(6184, SR.GetResourceString(SR.ID6184), response.StatusCode, - await response.Content.ReadAsStringAsync(context.CancellationToken)); + // Note: the raw payload is only logged if sensitive payload logging was explicitly + // enabled, as it may contain sensitive data (e.g access tokens or refresh tokens). + if (_options.CurrentValue.EnableSensitivePayloadLogging) + { + context.Logger.LogError(6184, SR.GetResourceString(SR.ID6184), response.StatusCode, + await response.Content.ReadAsStringAsync(context.CancellationToken)); + } + + else + { + context.Logger.LogError(6184, SR.GetResourceString(SR.ID6302), response.StatusCode, + response.Content.Headers.ContentType, response.Content.Headers.ContentLength); + } context.Reject( error: (int) response.StatusCode switch @@ -936,8 +968,19 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers // (e.g because an unsupported content type was returned), return a generic error. if (context.Transaction.Response is null) { - context.Logger.LogError(6185, SR.GetResourceString(SR.ID6185), response.StatusCode, - response.Content.Headers.ContentType, await response.Content.ReadAsStringAsync(context.CancellationToken)); + // Note: the raw payload is only logged if sensitive payload logging was explicitly + // enabled, as it may contain sensitive data (e.g access tokens or refresh tokens). + if (_options.CurrentValue.EnableSensitivePayloadLogging) + { + context.Logger.LogError(6185, SR.GetResourceString(SR.ID6185), response.StatusCode, + response.Content.Headers.ContentType, await response.Content.ReadAsStringAsync(context.CancellationToken)); + } + + else + { + context.Logger.LogError(6185, SR.GetResourceString(SR.ID6303), response.StatusCode, + response.Content.Headers.ContentType, response.Content.Headers.ContentLength); + } context.Reject( error: Errors.ServerError, diff --git a/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpOptions.cs b/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpOptions.cs index ff754e9b..43cdc4fe 100644 --- a/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpOptions.cs +++ b/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpOptions.cs @@ -69,6 +69,16 @@ public sealed class OpenIddictValidationSystemNetHttpOptions /// public ProductInfoHeaderValue? ProductInformation { get; set; } + /// + /// Gets or sets a boolean indicating whether the raw payloads of the HTTP responses returned by + /// the remote server should be included in the logs when an invalid or unexpected response is received. + /// + /// + /// Note: raw payloads may contain sensitive data (e.g access tokens or refresh tokens). + /// As such, this option should only be enabled in development environments. + /// + public bool EnableSensitivePayloadLogging { get; set; } + /// /// Gets the user-defined actions used to amend the /// instances created by the OpenIddict validation/System.Net.Http integration. diff --git a/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddict.Client.SystemNetHttp.Tests.csproj b/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddict.Client.SystemNetHttp.Tests.csproj new file mode 100644 index 00000000..ef60d9ee --- /dev/null +++ b/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddict.Client.SystemNetHttp.Tests.csproj @@ -0,0 +1,26 @@ + + + + $(NetFrameworkTargetFrameworks);$(NetCoreTargetFrameworks) + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpBuilderTests.cs b/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpBuilderTests.cs new file mode 100644 index 00000000..a120bdc3 --- /dev/null +++ b/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpBuilderTests.cs @@ -0,0 +1,69 @@ +/* + * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) + * See https://github.com/openiddict/openiddict-core for more information concerning + * the license and the contributors participating to this project. + */ + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Xunit; + +namespace OpenIddict.Client.SystemNetHttp.Tests; + +public class OpenIddictClientSystemNetHttpBuilderTests +{ + [Fact] + public void Constructor_ThrowsAnExceptionForNullServices() + { + // Arrange + var services = (IServiceCollection) null!; + + // Act and assert + var exception = Assert.Throws(() => new OpenIddictClientSystemNetHttpBuilder(services)); + + Assert.Equal("services", exception.ParamName); + } + + [Fact] + public void EnableSensitivePayloadLogging_IsDisabledByDefault() + { + // Arrange + var services = CreateServices(); + CreateBuilder(services); + + // Act + var options = GetOptions(services); + + // Assert + Assert.False(options.EnableSensitivePayloadLogging); + } + + [Fact] + public void EnableSensitivePayloadLogging_SetsSensitivePayloadLoggingEnabled() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.EnableSensitivePayloadLogging(); + + var options = GetOptions(services); + + // Assert + Assert.True(options.EnableSensitivePayloadLogging); + } + + private static IServiceCollection CreateServices() + => new ServiceCollection().AddOptions(); + + private static OpenIddictClientSystemNetHttpBuilder CreateBuilder(IServiceCollection services) + => new(services); + + private static OpenIddictClientSystemNetHttpOptions GetOptions(IServiceCollection services) + { + var provider = services.BuildServiceProvider(); + var options = provider.GetRequiredService>(); + return options.Value; + } +} diff --git a/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpHandlersTests.cs b/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpHandlersTests.cs new file mode 100644 index 00000000..eae44414 --- /dev/null +++ b/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpHandlersTests.cs @@ -0,0 +1,143 @@ +/* + * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) + * See https://github.com/openiddict/openiddict-core for more information concerning + * the license and the contributors participating to this project. + */ + +using System.Globalization; +using System.Net; +using System.Net.Http; +using System.Text; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Moq; +using Xunit; +using static OpenIddict.Client.OpenIddictClientEvents; +using static OpenIddict.Client.SystemNetHttp.OpenIddictClientSystemNetHttpHandlers; + +namespace OpenIddict.Client.SystemNetHttp.Tests; + +public class OpenIddictClientSystemNetHttpHandlersTests +{ + private const string Payload = "SENSITIVE_PAYLOAD"; + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ExtractJsonHttpResponse_OnlyLogsPayloadWhenSensitivePayloadLoggingIsEnabled(bool enabled) + { + // Arrange + var logger = new Mock>(); + + using var response = new HttpResponseMessage(HttpStatusCode.OK) + { + // Note: the payload is deliberately malformed to trigger the JSON deserialization error. + Content = new StringContent("{\"access_token\":\"" + Payload + "\"", Encoding.UTF8, "application/json") + }; + + var context = new PrepareDeviceAuthorizationRequestContext(CreateTransaction(logger.Object, response)); + var handler = new ExtractJsonHttpResponse(CreateOptions(enabled)); + + // Act + await handler.HandleAsync(context); + + // Assert + Assert.True(context.IsRejected); + Assert.Equal(Errors.ServerError, context.Error); + + logger.Verify(logger => logger.Log( + LogLevel.Error, + It.Is(id => id.Id == 6183), + It.Is((state, type) => Convert.ToString(state, CultureInfo.InvariantCulture)!.Contains(Payload) == enabled), + It.IsAny(), + It.IsAny>()), Times.Once()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ValidateHttpResponse_OnlyLogsPayloadOfGenericErrorsWhenSensitivePayloadLoggingIsEnabled(bool enabled) + { + // Arrange + var logger = new Mock>(); + + using var response = new HttpResponseMessage(HttpStatusCode.InternalServerError) + { + Content = new StringContent(Payload, Encoding.UTF8, "text/plain") + }; + + var context = new PrepareDeviceAuthorizationRequestContext(CreateTransaction(logger.Object, response)); + var handler = new ValidateHttpResponse(CreateOptions(enabled)); + + // Act + await handler.HandleAsync(context); + + // Assert + Assert.True(context.IsRejected); + Assert.Equal(Errors.ServerError, context.Error); + + logger.Verify(logger => logger.Log( + LogLevel.Error, + It.Is(id => id.Id == 6184), + It.Is((state, type) => Convert.ToString(state, CultureInfo.InvariantCulture)!.Contains(Payload) == enabled), + It.IsAny(), + It.IsAny>()), Times.Once()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ValidateHttpResponse_OnlyLogsPayloadOfUnsupportedResponsesWhenSensitivePayloadLoggingIsEnabled(bool enabled) + { + // Arrange + var logger = new Mock>(); + + using var response = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(Payload, Encoding.UTF8, "text/plain") + }; + + var context = new PrepareDeviceAuthorizationRequestContext(CreateTransaction(logger.Object, response)); + var handler = new ValidateHttpResponse(CreateOptions(enabled)); + + // Act + await handler.HandleAsync(context); + + // Assert + Assert.True(context.IsRejected); + Assert.Equal(Errors.ServerError, context.Error); + + logger.Verify(logger => logger.Log( + LogLevel.Error, + It.Is(id => id.Id == 6185), + It.Is((state, type) => Convert.ToString(state, CultureInfo.InvariantCulture)!.Contains(Payload) == enabled), + It.IsAny(), + It.IsAny>()), Times.Once()); + } + + private static IOptionsMonitor CreateOptions(bool enabled) + => Mock.Of>(monitor => + monitor.CurrentValue == new OpenIddictClientSystemNetHttpOptions + { + EnableSensitivePayloadLogging = enabled + }); + + private static OpenIddictClientTransaction CreateTransaction( + ILogger logger, HttpResponseMessage response) + { + var services = new ServiceCollection(); + services.AddSingleton(logger); + + var transaction = new OpenIddictClientTransaction + { + CancellationToken = CancellationToken.None, + Options = new OpenIddictClientOptions(), + ServiceProvider = services.BuildServiceProvider() + }; + + transaction.Properties[typeof(HttpResponseMessage).FullName!] = response; + + return transaction; + } +} diff --git a/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddict.Validation.SystemNetHttp.Tests.csproj b/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddict.Validation.SystemNetHttp.Tests.csproj new file mode 100644 index 00000000..da3f80a9 --- /dev/null +++ b/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddict.Validation.SystemNetHttp.Tests.csproj @@ -0,0 +1,26 @@ + + + + $(NetFrameworkTargetFrameworks);$(NetCoreTargetFrameworks) + + + + + + + + + + + + + + + + + + + + + + diff --git a/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpBuilderTests.cs b/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpBuilderTests.cs new file mode 100644 index 00000000..ea78f68c --- /dev/null +++ b/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpBuilderTests.cs @@ -0,0 +1,69 @@ +/* + * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) + * See https://github.com/openiddict/openiddict-core for more information concerning + * the license and the contributors participating to this project. + */ + +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Options; +using Xunit; + +namespace OpenIddict.Validation.SystemNetHttp.Tests; + +public class OpenIddictValidationSystemNetHttpBuilderTests +{ + [Fact] + public void Constructor_ThrowsAnExceptionForNullServices() + { + // Arrange + var services = (IServiceCollection) null!; + + // Act and assert + var exception = Assert.Throws(() => new OpenIddictValidationSystemNetHttpBuilder(services)); + + Assert.Equal("services", exception.ParamName); + } + + [Fact] + public void EnableSensitivePayloadLogging_IsDisabledByDefault() + { + // Arrange + var services = CreateServices(); + CreateBuilder(services); + + // Act + var options = GetOptions(services); + + // Assert + Assert.False(options.EnableSensitivePayloadLogging); + } + + [Fact] + public void EnableSensitivePayloadLogging_SetsSensitivePayloadLoggingEnabled() + { + // Arrange + var services = CreateServices(); + var builder = CreateBuilder(services); + + // Act + builder.EnableSensitivePayloadLogging(); + + var options = GetOptions(services); + + // Assert + Assert.True(options.EnableSensitivePayloadLogging); + } + + private static IServiceCollection CreateServices() + => new ServiceCollection().AddOptions(); + + private static OpenIddictValidationSystemNetHttpBuilder CreateBuilder(IServiceCollection services) + => new(services); + + private static OpenIddictValidationSystemNetHttpOptions GetOptions(IServiceCollection services) + { + var provider = services.BuildServiceProvider(); + var options = provider.GetRequiredService>(); + return options.Value; + } +} diff --git a/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpHandlersTests.cs b/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpHandlersTests.cs new file mode 100644 index 00000000..3ed652f7 --- /dev/null +++ b/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpHandlersTests.cs @@ -0,0 +1,143 @@ +/* + * Licensed under the Apache License, Version 2.0 (http://www.apache.org/licenses/LICENSE-2.0) + * See https://github.com/openiddict/openiddict-core for more information concerning + * the license and the contributors participating to this project. + */ + +using System.Globalization; +using System.Net; +using System.Net.Http; +using System.Text; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Moq; +using Xunit; +using static OpenIddict.Validation.OpenIddictValidationEvents; +using static OpenIddict.Validation.SystemNetHttp.OpenIddictValidationSystemNetHttpHandlers; + +namespace OpenIddict.Validation.SystemNetHttp.Tests; + +public class OpenIddictValidationSystemNetHttpHandlersTests +{ + private const string Payload = "SENSITIVE_PAYLOAD"; + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ExtractJsonHttpResponse_OnlyLogsPayloadWhenSensitivePayloadLoggingIsEnabled(bool enabled) + { + // Arrange + var logger = new Mock>(); + + using var response = new HttpResponseMessage(HttpStatusCode.OK) + { + // Note: the payload is deliberately malformed to trigger the JSON deserialization error. + Content = new StringContent("{\"access_token\":\"" + Payload + "\"", Encoding.UTF8, "application/json") + }; + + var context = new PrepareConfigurationRequestContext(CreateTransaction(logger.Object, response)); + var handler = new ExtractJsonHttpResponse(CreateOptions(enabled)); + + // Act + await handler.HandleAsync(context); + + // Assert + Assert.True(context.IsRejected); + Assert.Equal(Errors.ServerError, context.Error); + + logger.Verify(logger => logger.Log( + LogLevel.Error, + It.Is(id => id.Id == 6183), + It.Is((state, type) => Convert.ToString(state, CultureInfo.InvariantCulture)!.Contains(Payload) == enabled), + It.IsAny(), + It.IsAny>()), Times.Once()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ValidateHttpResponse_OnlyLogsPayloadOfGenericErrorsWhenSensitivePayloadLoggingIsEnabled(bool enabled) + { + // Arrange + var logger = new Mock>(); + + using var response = new HttpResponseMessage(HttpStatusCode.InternalServerError) + { + Content = new StringContent(Payload, Encoding.UTF8, "text/plain") + }; + + var context = new PrepareConfigurationRequestContext(CreateTransaction(logger.Object, response)); + var handler = new ValidateHttpResponse(CreateOptions(enabled)); + + // Act + await handler.HandleAsync(context); + + // Assert + Assert.True(context.IsRejected); + Assert.Equal(Errors.ServerError, context.Error); + + logger.Verify(logger => logger.Log( + LogLevel.Error, + It.Is(id => id.Id == 6184), + It.Is((state, type) => Convert.ToString(state, CultureInfo.InvariantCulture)!.Contains(Payload) == enabled), + It.IsAny(), + It.IsAny>()), Times.Once()); + } + + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ValidateHttpResponse_OnlyLogsPayloadOfUnsupportedResponsesWhenSensitivePayloadLoggingIsEnabled(bool enabled) + { + // Arrange + var logger = new Mock>(); + + using var response = new HttpResponseMessage(HttpStatusCode.OK) + { + Content = new StringContent(Payload, Encoding.UTF8, "text/plain") + }; + + var context = new PrepareConfigurationRequestContext(CreateTransaction(logger.Object, response)); + var handler = new ValidateHttpResponse(CreateOptions(enabled)); + + // Act + await handler.HandleAsync(context); + + // Assert + Assert.True(context.IsRejected); + Assert.Equal(Errors.ServerError, context.Error); + + logger.Verify(logger => logger.Log( + LogLevel.Error, + It.Is(id => id.Id == 6185), + It.Is((state, type) => Convert.ToString(state, CultureInfo.InvariantCulture)!.Contains(Payload) == enabled), + It.IsAny(), + It.IsAny>()), Times.Once()); + } + + private static IOptionsMonitor CreateOptions(bool enabled) + => Mock.Of>(monitor => + monitor.CurrentValue == new OpenIddictValidationSystemNetHttpOptions + { + EnableSensitivePayloadLogging = enabled + }); + + private static OpenIddictValidationTransaction CreateTransaction( + ILogger logger, HttpResponseMessage response) + { + var services = new ServiceCollection(); + services.AddSingleton(logger); + + var transaction = new OpenIddictValidationTransaction + { + CancellationToken = CancellationToken.None, + Options = new OpenIddictValidationOptions(), + ServiceProvider = services.BuildServiceProvider() + }; + + transaction.Properties[typeof(HttpResponseMessage).FullName!] = response; + + return transaction; + } +}