Browse Source

Add an option to control whether raw HTTP response payloads are logged by the System.Net.Http integrations

pull/2570/head
Manuel Menegazzo 4 weeks ago
committed by GitHub
parent
commit
7af81eb95b
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 2
      OpenIddict.slnx
  2. 9
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  3. 10
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpBuilder.cs
  4. 55
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
  5. 10
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpOptions.cs
  6. 10
      src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpBuilder.cs
  7. 55
      src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpHandlers.cs
  8. 10
      src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpOptions.cs
  9. 26
      test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddict.Client.SystemNetHttp.Tests.csproj
  10. 69
      test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpBuilderTests.cs
  11. 143
      test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpHandlersTests.cs
  12. 26
      test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddict.Validation.SystemNetHttp.Tests.csproj
  13. 69
      test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpBuilderTests.cs
  14. 143
      test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpHandlersTests.cs

2
OpenIddict.slnx

@ -88,6 +88,7 @@
<Project Path="test/OpenIddict.Client.Owin.IntegrationTests/OpenIddict.Client.Owin.IntegrationTests.csproj" />
<Project Path="test/OpenIddict.Client.Owin.Tests/OpenIddict.Client.Owin.Tests.csproj" Id="d57775bf-7b38-48f5-b15c-d48916de9166" />
<Project Path="test/OpenIddict.Client.SystemIntegration.Tests/OpenIddict.Client.SystemIntegration.Tests.csproj" Id="0d37c331-021f-4158-89e3-139c00731497" />
<Project Path="test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddict.Client.SystemNetHttp.Tests.csproj" />
<Project Path="test/OpenIddict.Client.Tests/OpenIddict.Client.Tests.csproj" Id="69998197-05ae-4259-adbf-d98fc9a51d88" />
<Project Path="test/OpenIddict.Client.WebIntegration.Tests/OpenIddict.Client.WebIntegration.Tests.csproj" Id="9a65c61e-f5ac-40da-9703-a8c2d6479185" />
<Project Path="test/OpenIddict.Core.Tests/OpenIddict.Core.Tests.csproj" />
@ -107,6 +108,7 @@
<Project Path="test/OpenIddict.Validation.IntegrationTests/OpenIddict.Validation.IntegrationTests.csproj" />
<Project Path="test/OpenIddict.Validation.Owin.IntegrationTests/OpenIddict.Validation.Owin.IntegrationTests.csproj" />
<Project Path="test/OpenIddict.Validation.Owin.Tests/OpenIddict.Validation.Owin.Tests.csproj" Id="6c6f2b51-8319-4c93-bf80-36db6a7ce9eb" />
<Project Path="test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddict.Validation.SystemNetHttp.Tests.csproj" />
<Project Path="test/OpenIddict.Validation.Tests/OpenIddict.Validation.Tests.csproj" Id="8a9f3177-84c8-4098-bbe2-f9fdda866c43" />
</Folder>

9
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -3288,6 +3288,15 @@ This may indicate that the hashed entry is corrupted or malformed.</value>
<data name="ID6300" xml:space="preserve">
<value>A non-fatal error occurred while pruning sessions from the database.</value>
</data>
<data name="ID6301" xml:space="preserve">
<value>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.</value>
</data>
<data name="ID6302" xml:space="preserve">
<value>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.</value>
</data>
<data name="ID6303" xml:space="preserve">
<value>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.</value>
</data>
<data name="ID8000" xml:space="preserve">
<value>https://documentation.openiddict.com/errors/{0}</value>
</data>

10
src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpBuilder.cs

@ -256,6 +256,16 @@ public sealed class OpenIddictClientSystemNetHttpBuilder
}
#endif
/// <summary>
/// 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.
/// </summary>
/// <returns>The <see cref="OpenIddictClientSystemNetHttpBuilder"/> instance.</returns>
public OpenIddictClientSystemNetHttpBuilder EnableSensitivePayloadLogging()
=> Configure(options => options.EnableSensitivePayloadLogging = true);
/// <summary>
/// Sets the product information used in the "User-Agent" header that is attached
/// to the backchannel HTTP requests sent to the authorization server.

55
src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs

@ -684,6 +684,11 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
/// </summary>
public sealed class ExtractJsonHttpResponse<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
private readonly IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> _options;
public ExtractJsonHttpResponse(IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> options)
=> _options = options ?? throw new ArgumentNullException(nameof(options));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
@ -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
/// </summary>
public sealed class ValidateHttpResponse<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
private readonly IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> _options;
public ValidateHttpResponse(IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> options)
=> _options = options ?? throw new ArgumentNullException(nameof(options));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
@ -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,

10
src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpOptions.cs

@ -69,6 +69,16 @@ public sealed class OpenIddictClientSystemNetHttpOptions
/// </summary>
public ProductInfoHeaderValue? ProductInformation { get; set; }
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public bool EnableSensitivePayloadLogging { get; set; }
/// <summary>
/// Gets the user-defined actions used to amend the <see cref="HttpClient"/>
/// instances created by the OpenIddict client/System.Net.Http integration.

10
src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpBuilder.cs

@ -164,6 +164,16 @@ public sealed class OpenIddictValidationSystemNetHttpBuilder
}
#endif
/// <summary>
/// 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.
/// </summary>
/// <returns>The <see cref="OpenIddictValidationSystemNetHttpBuilder"/> instance.</returns>
public OpenIddictValidationSystemNetHttpBuilder EnableSensitivePayloadLogging()
=> Configure(options => options.EnableSensitivePayloadLogging = true);
/// <summary>
/// Sets the product information used in the "User-Agent" header that is attached
/// to the backchannel HTTP requests sent to the authorization server.

55
src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpHandlers.cs

@ -680,6 +680,11 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
/// </summary>
public sealed class ExtractJsonHttpResponse<TContext> : IOpenIddictValidationHandler<TContext> where TContext : BaseExternalContext
{
private readonly IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions> _options;
public ExtractJsonHttpResponse(IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions> options)
=> _options = options ?? throw new ArgumentNullException(nameof(options));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
@ -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
/// </summary>
public sealed class ValidateHttpResponse<TContext> : IOpenIddictValidationHandler<TContext> where TContext : BaseExternalContext
{
private readonly IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions> _options;
public ValidateHttpResponse(IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions> options)
=> _options = options ?? throw new ArgumentNullException(nameof(options));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
@ -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,

10
src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpOptions.cs

@ -69,6 +69,16 @@ public sealed class OpenIddictValidationSystemNetHttpOptions
/// </summary>
public ProductInfoHeaderValue? ProductInformation { get; set; }
/// <summary>
/// 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.
/// </summary>
/// <remarks>
/// 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.
/// </remarks>
public bool EnableSensitivePayloadLogging { get; set; }
/// <summary>
/// Gets the user-defined actions used to amend the <see cref="HttpClient"/>
/// instances created by the OpenIddict validation/System.Net.Http integration.

26
test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddict.Client.SystemNetHttp.Tests.csproj

@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetFrameworkTargetFrameworks);$(NetCoreTargetFrameworks)</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\OpenIddict.Client.SystemNetHttp\OpenIddict.Client.SystemNetHttp.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Moq" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' ">
<Reference Include="System.Net.Http" />
</ItemGroup>
<ItemGroup>
<Using Include="OpenIddict.Abstractions" />
<Using Include="OpenIddict.Abstractions.OpenIddictConstants" Static="true" />
<Using Include="OpenIddict.Abstractions.OpenIddictResources" Alias="SR" />
</ItemGroup>
</Project>

69
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<ArgumentNullException>(() => 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<IOptions<OpenIddictClientSystemNetHttpOptions>>();
return options.Value;
}
}

143
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<ILogger<OpenIddictClientDispatcher>>();
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<PrepareDeviceAuthorizationRequestContext>(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<EventId>(id => id.Id == 6183),
It.Is<It.IsAnyType>((state, type) => Convert.ToString(state, CultureInfo.InvariantCulture)!.Contains(Payload) == enabled),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ValidateHttpResponse_OnlyLogsPayloadOfGenericErrorsWhenSensitivePayloadLoggingIsEnabled(bool enabled)
{
// Arrange
var logger = new Mock<ILogger<OpenIddictClientDispatcher>>();
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<PrepareDeviceAuthorizationRequestContext>(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<EventId>(id => id.Id == 6184),
It.Is<It.IsAnyType>((state, type) => Convert.ToString(state, CultureInfo.InvariantCulture)!.Contains(Payload) == enabled),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ValidateHttpResponse_OnlyLogsPayloadOfUnsupportedResponsesWhenSensitivePayloadLoggingIsEnabled(bool enabled)
{
// Arrange
var logger = new Mock<ILogger<OpenIddictClientDispatcher>>();
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<PrepareDeviceAuthorizationRequestContext>(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<EventId>(id => id.Id == 6185),
It.Is<It.IsAnyType>((state, type) => Convert.ToString(state, CultureInfo.InvariantCulture)!.Contains(Payload) == enabled),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once());
}
private static IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> CreateOptions(bool enabled)
=> Mock.Of<IOptionsMonitor<OpenIddictClientSystemNetHttpOptions>>(monitor =>
monitor.CurrentValue == new OpenIddictClientSystemNetHttpOptions
{
EnableSensitivePayloadLogging = enabled
});
private static OpenIddictClientTransaction CreateTransaction(
ILogger<OpenIddictClientDispatcher> 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;
}
}

26
test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddict.Validation.SystemNetHttp.Tests.csproj

@ -0,0 +1,26 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>$(NetFrameworkTargetFrameworks);$(NetCoreTargetFrameworks)</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\OpenIddict.Validation.SystemNetHttp\OpenIddict.Validation.SystemNetHttp.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Extensions.DependencyInjection" />
<PackageReference Include="Moq" />
</ItemGroup>
<ItemGroup Condition=" '$(TargetFrameworkIdentifier)' == '.NETFramework' ">
<Reference Include="System.Net.Http" />
</ItemGroup>
<ItemGroup>
<Using Include="OpenIddict.Abstractions" />
<Using Include="OpenIddict.Abstractions.OpenIddictConstants" Static="true" />
<Using Include="OpenIddict.Abstractions.OpenIddictResources" Alias="SR" />
</ItemGroup>
</Project>

69
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<ArgumentNullException>(() => 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<IOptions<OpenIddictValidationSystemNetHttpOptions>>();
return options.Value;
}
}

143
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<ILogger<OpenIddictValidationDispatcher>>();
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<PrepareConfigurationRequestContext>(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<EventId>(id => id.Id == 6183),
It.Is<It.IsAnyType>((state, type) => Convert.ToString(state, CultureInfo.InvariantCulture)!.Contains(Payload) == enabled),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ValidateHttpResponse_OnlyLogsPayloadOfGenericErrorsWhenSensitivePayloadLoggingIsEnabled(bool enabled)
{
// Arrange
var logger = new Mock<ILogger<OpenIddictValidationDispatcher>>();
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<PrepareConfigurationRequestContext>(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<EventId>(id => id.Id == 6184),
It.Is<It.IsAnyType>((state, type) => Convert.ToString(state, CultureInfo.InvariantCulture)!.Contains(Payload) == enabled),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task ValidateHttpResponse_OnlyLogsPayloadOfUnsupportedResponsesWhenSensitivePayloadLoggingIsEnabled(bool enabled)
{
// Arrange
var logger = new Mock<ILogger<OpenIddictValidationDispatcher>>();
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<PrepareConfigurationRequestContext>(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<EventId>(id => id.Id == 6185),
It.Is<It.IsAnyType>((state, type) => Convert.ToString(state, CultureInfo.InvariantCulture)!.Contains(Payload) == enabled),
It.IsAny<Exception>(),
It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once());
}
private static IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions> CreateOptions(bool enabled)
=> Mock.Of<IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions>>(monitor =>
monitor.CurrentValue == new OpenIddictValidationSystemNetHttpOptions
{
EnableSensitivePayloadLogging = enabled
});
private static OpenIddictValidationTransaction CreateTransaction(
ILogger<OpenIddictValidationDispatcher> 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;
}
}
Loading…
Cancel
Save