Browse Source

Update the `System.Net.Http` integrations to support restricting the allowed decompression algorithms

pull/2574/head
Manuel Menegazzo 3 weeks ago
committed by GitHub
parent
commit
714647b1fa
No known key found for this signature in database GPG Key ID: B5690EEEBB952194
  1. 1
      .gitignore
  2. 3
      src/OpenIddict.Abstractions/OpenIddictResources.resx
  3. 10
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpBuilder.cs
  4. 51
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
  5. 12
      src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpOptions.cs
  6. 10
      src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpBuilder.cs
  7. 51
      src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpHandlers.cs
  8. 12
      src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpOptions.cs
  9. 41
      test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpBuilderTests.cs
  10. 110
      test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpHandlersTests.cs
  11. 41
      test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpBuilderTests.cs
  12. 110
      test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpHandlersTests.cs

1
.gitignore

@ -11,6 +11,7 @@ target/
# User-specific files
*.suo
*.user
*.lutconfig
*.sln.docstates
project.lock.json
_references.js

3
src/OpenIddict.Abstractions/OpenIddictResources.resx

@ -2415,6 +2415,9 @@ To use a custom policy relying on the system store, set 'OpenIddictServerOptions
<data name="ID2210" xml:space="preserve">
<value>The session associated with the token is no longer valid.</value>
</data>
<data name="ID2211" xml:space="preserve">
<value>The remote server returned a content encoding that is not allowed by the configured decompression methods.</value>
</data>
<data name="ID4000" xml:space="preserve">
<value>The '{0}' parameter shouldn't be null or empty at this point.</value>
</data>

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

@ -6,6 +6,7 @@
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mail;
@ -266,6 +267,15 @@ public sealed class OpenIddictClientSystemNetHttpBuilder
public OpenIddictClientSystemNetHttpBuilder EnableSensitivePayloadLogging()
=> Configure(options => options.EnableSensitivePayloadLogging = true);
/// <summary>
/// Sets the decompression methods the OpenIddict client/System.Net.Http integration is
/// allowed to use to decode the compressed HTTP responses returned by the remote server.
/// </summary>
/// <param name="methods">The allowed decompression methods.</param>
/// <returns>The <see cref="OpenIddictClientSystemNetHttpBuilder"/> instance.</returns>
public OpenIddictClientSystemNetHttpBuilder SetAllowedDecompressionMethods(DecompressionMethods methods)
=> Configure(options => options.AllowedDecompressionMethods = methods);
/// <summary>
/// Sets the product information used in the "User-Agent" header that is attached
/// to the backchannel HTTP requests sent to the authorization server.

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

@ -8,6 +8,7 @@ using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
@ -542,6 +543,11 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
/// </summary>
public sealed class DecompressResponseContent<TContext> : IOpenIddictClientHandler<TContext> where TContext : BaseExternalContext
{
private readonly IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> _options;
public DecompressResponseContent(IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> options)
=> _options = options ?? throw new ArgumentNullException(nameof(options));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
@ -606,8 +612,15 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
Stream? stream = null;
// Note: the algorithms that were not explicitly allowed are rejected even if they are natively
// supported by the runtime (e.g to prevent using a decoder affected by a known vulnerability).
//
// ~DecompressionMethods.None (which is equivalent to .All) has all the bits set and can be
// used to bypass the individual checks and allow all the algorithms supported by OpenIddict.
var methods = _options.CurrentValue.AllowedDecompressionMethods;
// Iterate the returned encodings and wrap the response stream using the specified algorithm.
// If one of the returned algorithms cannot be recognized, immediately return an error.
// If one of the returned algorithms cannot be recognized or is not allowed, immediately return an error.
foreach (var encoding in response.Content.Headers.ContentEncoding.Reverse())
{
if (string.Equals(encoding, ContentEncodings.Identity, StringComparison.OrdinalIgnoreCase))
@ -617,11 +630,25 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
if (string.Equals(encoding, ContentEncodings.Gzip, StringComparison.OrdinalIgnoreCase))
{
if (!methods.HasFlag(DecompressionMethods.GZip))
{
context.Reject(
error: Errors.ServerError,
description: SR.GetResourceString(SR.ID2211),
uri: SR.FormatID8000(SR.ID2211));
return;
}
stream ??= await response.Content.ReadAsStreamAsync().WaitAsync(context.CancellationToken);
stream = new GZipStream(stream, CompressionMode.Decompress);
}
#if NET
// Note: Deflate and Brotli are deliberately not supported on .NET Framework, even if they are
// explicitly allowed via the options: the HTTP "deflate" content coding requires a zlib-framed
// stream that DeflateStream cannot decode (ZLibStream is only available on .NET 6.0 and higher)
// and BrotliStream is not available. In this case, such responses are rejected as unsupported.
// Note: some server implementations are known to incorrectly implement the "Deflate" compression
// algorithm and don't wrap the compressed data in a ZLib frame as required by the specifications.
//
@ -631,12 +658,32 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
// For more information, read https://www.rfc-editor.org/rfc/rfc9110.html#name-deflate-coding.
else if (string.Equals(encoding, ContentEncodings.Deflate, StringComparison.OrdinalIgnoreCase))
{
if (!methods.HasFlag(DecompressionMethods.Deflate))
{
context.Reject(
error: Errors.ServerError,
description: SR.GetResourceString(SR.ID2211),
uri: SR.FormatID8000(SR.ID2211));
return;
}
stream ??= await response.Content.ReadAsStreamAsync().WaitAsync(context.CancellationToken);
stream = new ZLibStream(stream, CompressionMode.Decompress);
}
else if (string.Equals(encoding, ContentEncodings.Brotli, StringComparison.OrdinalIgnoreCase))
{
if (!methods.HasFlag(DecompressionMethods.Brotli))
{
context.Reject(
error: Errors.ServerError,
description: SR.GetResourceString(SR.ID2211),
uri: SR.FormatID8000(SR.ID2211));
return;
}
stream ??= await response.Content.ReadAsStreamAsync().WaitAsync(context.CancellationToken);
stream = new BrotliStream(stream, CompressionMode.Decompress);
}
@ -1003,7 +1050,7 @@ public static partial class OpenIddictClientSystemNetHttpHandlers
429 => Errors.SlowDown,
500 => Errors.ServerError,
503 => Errors.TemporarilyUnavailable,
_ => Errors.ServerError
_ => Errors.ServerError
},
description: SR.FormatID2161((int) response.StatusCode),
uri: SR.FormatID8000(SR.ID2161));

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

@ -79,6 +79,18 @@ public sealed class OpenIddictClientSystemNetHttpOptions
/// </remarks>
public bool EnableSensitivePayloadLogging { get; set; }
/// <summary>
/// Gets or sets the decompression methods the OpenIddict client/System.Net.Http integration
/// is allowed to use to decode the compressed HTTP responses returned by the remote server.
/// </summary>
/// <remarks>
/// Note: while HTTP compression is never opted-in by default, encoded responses returned by servers
/// that enforce content compression are still decoded. This property can be used to exclude specific
/// algorithms (e.g to mitigate a vulnerability affecting one of the decoders used by the runtime).
/// By default, all the algorithms supported by OpenIddict are allowed.
/// </remarks>
public DecompressionMethods AllowedDecompressionMethods { get; set; } = ~DecompressionMethods.None;
/// <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

@ -6,6 +6,7 @@
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Mail;
@ -174,6 +175,15 @@ public sealed class OpenIddictValidationSystemNetHttpBuilder
public OpenIddictValidationSystemNetHttpBuilder EnableSensitivePayloadLogging()
=> Configure(options => options.EnableSensitivePayloadLogging = true);
/// <summary>
/// Sets the decompression methods the OpenIddict validation/System.Net.Http integration is
/// allowed to use to decode the compressed HTTP responses returned by the remote server.
/// </summary>
/// <param name="methods">The allowed decompression methods.</param>
/// <returns>The <see cref="OpenIddictValidationSystemNetHttpBuilder"/> instance.</returns>
public OpenIddictValidationSystemNetHttpBuilder SetAllowedDecompressionMethods(DecompressionMethods methods)
=> Configure(options => options.AllowedDecompressionMethods = methods);
/// <summary>
/// Sets the product information used in the "User-Agent" header that is attached
/// to the backchannel HTTP requests sent to the authorization server.

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

@ -8,6 +8,7 @@ using System.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
@ -538,6 +539,11 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
/// </summary>
public sealed class DecompressResponseContent<TContext> : IOpenIddictValidationHandler<TContext> where TContext : BaseExternalContext
{
private readonly IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions> _options;
public DecompressResponseContent(IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions> options)
=> _options = options ?? throw new ArgumentNullException(nameof(options));
/// <summary>
/// Gets the default descriptor definition assigned to this handler.
/// </summary>
@ -602,8 +608,15 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
Stream? stream = null;
// Note: the algorithms that were not explicitly allowed are rejected even if they are natively
// supported by the runtime (e.g to prevent using a decoder affected by a known vulnerability).
//
// ~DecompressionMethods.None (which is equivalent to .All) has all the bits set and can be
// used to bypass the individual checks and allow all the algorithms supported by OpenIddict.
var methods = _options.CurrentValue.AllowedDecompressionMethods;
// Iterate the returned encodings and wrap the response stream using the specified algorithm.
// If one of the returned algorithms cannot be recognized, immediately return an error.
// If one of the returned algorithms cannot be recognized or is not allowed, immediately return an error.
foreach (var encoding in response.Content.Headers.ContentEncoding.Reverse())
{
if (string.Equals(encoding, ContentEncodings.Identity, StringComparison.OrdinalIgnoreCase))
@ -613,11 +626,25 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
if (string.Equals(encoding, ContentEncodings.Gzip, StringComparison.OrdinalIgnoreCase))
{
if (!methods.HasFlag(DecompressionMethods.GZip))
{
context.Reject(
error: Errors.ServerError,
description: SR.GetResourceString(SR.ID2211),
uri: SR.FormatID8000(SR.ID2211));
return;
}
stream ??= await response.Content.ReadAsStreamAsync().WaitAsync(context.CancellationToken);
stream = new GZipStream(stream, CompressionMode.Decompress);
}
#if NET
// Note: Deflate and Brotli are deliberately not supported on .NET Framework, even if they are
// explicitly allowed via the options: the HTTP "deflate" content coding requires a zlib-framed
// stream that DeflateStream cannot decode (ZLibStream is only available on .NET 6.0 and higher)
// and BrotliStream is not available. In this case, such responses are rejected as unsupported.
// Note: some server implementations are known to incorrectly implement the "Deflate" compression
// algorithm and don't wrap the compressed data in a ZLib frame as required by the specifications.
//
@ -627,12 +654,32 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
// For more information, read https://www.rfc-editor.org/rfc/rfc9110.html#name-deflate-coding.
else if (string.Equals(encoding, ContentEncodings.Deflate, StringComparison.OrdinalIgnoreCase))
{
if (!methods.HasFlag(DecompressionMethods.Deflate))
{
context.Reject(
error: Errors.ServerError,
description: SR.GetResourceString(SR.ID2211),
uri: SR.FormatID8000(SR.ID2211));
return;
}
stream ??= await response.Content.ReadAsStreamAsync().WaitAsync(context.CancellationToken);
stream = new ZLibStream(stream, CompressionMode.Decompress);
}
else if (string.Equals(encoding, ContentEncodings.Brotli, StringComparison.OrdinalIgnoreCase))
{
if (!methods.HasFlag(DecompressionMethods.Brotli))
{
context.Reject(
error: Errors.ServerError,
description: SR.GetResourceString(SR.ID2211),
uri: SR.FormatID8000(SR.ID2211));
return;
}
stream ??= await response.Content.ReadAsStreamAsync().WaitAsync(context.CancellationToken);
stream = new BrotliStream(stream, CompressionMode.Decompress);
}
@ -956,7 +1003,7 @@ public static partial class OpenIddictValidationSystemNetHttpHandlers
429 => Errors.SlowDown,
500 => Errors.ServerError,
503 => Errors.TemporarilyUnavailable,
_ => Errors.ServerError
_ => Errors.ServerError
},
description: SR.FormatID2161((int) response.StatusCode),
uri: SR.FormatID8000(SR.ID2161));

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

@ -79,6 +79,18 @@ public sealed class OpenIddictValidationSystemNetHttpOptions
/// </remarks>
public bool EnableSensitivePayloadLogging { get; set; }
/// <summary>
/// Gets or sets the decompression methods the OpenIddict validation/System.Net.Http integration
/// is allowed to use to decode the compressed HTTP responses returned by the remote server.
/// </summary>
/// <remarks>
/// Note: while HTTP compression is never opted-in by default, encoded responses returned by servers
/// that enforce content compression are still decoded. This property can be used to exclude specific
/// algorithms (e.g to mitigate a vulnerability affecting one of the decoders used by the runtime).
/// By default, all the algorithms supported by OpenIddict are allowed.
/// </remarks>
public DecompressionMethods AllowedDecompressionMethods { get; set; } = ~DecompressionMethods.None;
/// <summary>
/// Gets the user-defined actions used to amend the <see cref="HttpClient"/>
/// instances created by the OpenIddict validation/System.Net.Http integration.

41
test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpBuilderTests.cs

@ -4,6 +4,7 @@
* the license and the contributors participating to this project.
*/
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Xunit;
@ -54,6 +55,46 @@ public class OpenIddictClientSystemNetHttpBuilderTests
Assert.True(options.EnableSensitivePayloadLogging);
}
[Fact]
public void SetAllowedDecompressionMethods_AllSupportedMethodsAreAllowedByDefault()
{
// Arrange
var services = CreateServices();
CreateBuilder(services);
// Act
var options = GetOptions(services);
// Assert
Assert.Equal(~DecompressionMethods.None, options.AllowedDecompressionMethods);
}
[Theory]
[InlineData(DecompressionMethods.None)]
[InlineData(DecompressionMethods.GZip)]
[InlineData(DecompressionMethods.Deflate)]
[InlineData(DecompressionMethods.GZip | DecompressionMethods.Deflate)]
#if NET
[InlineData(DecompressionMethods.Brotli)]
[InlineData(DecompressionMethods.GZip | DecompressionMethods.Brotli)]
[InlineData(DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli)]
[InlineData(~DecompressionMethods.None)]
#endif
public void SetAllowedDecompressionMethods_SetsAllowedDecompressionMethods(DecompressionMethods methods)
{
// Arrange
var services = CreateServices();
var builder = CreateBuilder(services);
// Act
builder.SetAllowedDecompressionMethods(methods);
var options = GetOptions(services);
// Assert
Assert.Equal(methods, options.AllowedDecompressionMethods);
}
private static IServiceCollection CreateServices()
=> new ServiceCollection().AddOptions();

110
test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpHandlersTests.cs

@ -5,6 +5,7 @@
*/
using System.Globalization;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Text;
@ -14,6 +15,7 @@ using Microsoft.Extensions.Options;
using Moq;
using Xunit;
using static OpenIddict.Client.OpenIddictClientEvents;
using static OpenIddict.Client.SystemNetHttp.OpenIddictClientSystemNetHttpConstants;
using static OpenIddict.Client.SystemNetHttp.OpenIddictClientSystemNetHttpHandlers;
namespace OpenIddict.Client.SystemNetHttp.Tests;
@ -22,6 +24,79 @@ public class OpenIddictClientSystemNetHttpHandlersTests
{
private const string Payload = "SENSITIVE_PAYLOAD";
public static TheoryData<string, DecompressionMethods> SupportedEncodings => new()
{
{ ContentEncodings.Gzip, DecompressionMethods.GZip },
#if NET
{ ContentEncodings.Deflate, DecompressionMethods.Deflate },
{ ContentEncodings.Brotli, DecompressionMethods.Brotli }
#endif
};
[Theory]
[MemberData(nameof(SupportedEncodings))]
public async Task DecompressResponseContent_DecompressesContentWhenMethodIsAllowed(string encoding, DecompressionMethods method)
{
// Arrange
using var response = CreateCompressedResponse(encoding);
var context = new PrepareDeviceAuthorizationRequestContext(
CreateTransaction(Mock.Of<ILogger<OpenIddictClientDispatcher>>(), response));
var handler = new DecompressResponseContent<PrepareDeviceAuthorizationRequestContext>(CreateOptions(method));
// Act
await handler.HandleAsync(context);
// Assert
Assert.False(context.IsRejected);
Assert.Empty(response.Content.Headers.ContentEncoding);
Assert.Equal(Payload, await response.Content.ReadAsStringAsync());
}
[Theory]
[MemberData(nameof(SupportedEncodings))]
public async Task DecompressResponseContent_RejectsContentWhenMethodIsNotAllowed(string encoding, DecompressionMethods method)
{
// Arrange
using var response = CreateCompressedResponse(encoding);
var context = new PrepareDeviceAuthorizationRequestContext(
CreateTransaction(Mock.Of<ILogger<OpenIddictClientDispatcher>>(), response));
// Note: all the methods except the one used to encode the response are allowed.
var handler = new DecompressResponseContent<PrepareDeviceAuthorizationRequestContext>(CreateOptions(~method));
// Act
await handler.HandleAsync(context);
// Assert
Assert.True(context.IsRejected);
Assert.Equal(Errors.ServerError, context.Error);
Assert.Equal(SR.GetResourceString(SR.ID2211), context.ErrorDescription);
}
[Theory]
[MemberData(nameof(SupportedEncodings))]
public async Task DecompressResponseContent_DecompressesContentWhenAllMethodsAreAllowed(string encoding, DecompressionMethods method)
{
// Arrange
using var response = CreateCompressedResponse(encoding);
var context = new PrepareDeviceAuthorizationRequestContext(
CreateTransaction(Mock.Of<ILogger<OpenIddictClientDispatcher>>(), response));
var handler = new DecompressResponseContent<PrepareDeviceAuthorizationRequestContext>(
CreateOptions(~DecompressionMethods.None));
// Act
await handler.HandleAsync(context);
// Assert
Assert.True((~DecompressionMethods.None).HasFlag(method));
Assert.False(context.IsRejected);
Assert.Empty(response.Content.Headers.ContentEncoding);
Assert.Equal(Payload, await response.Content.ReadAsStringAsync());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
@ -116,6 +191,34 @@ public class OpenIddictClientSystemNetHttpHandlersTests
It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once());
}
private static HttpResponseMessage CreateCompressedResponse(string encoding)
{
using var buffer = new MemoryStream();
using (Stream stream = encoding switch
{
ContentEncodings.Gzip => new GZipStream(buffer, CompressionMode.Compress, leaveOpen: true),
#if NET
ContentEncodings.Deflate => new ZLibStream(buffer, CompressionMode.Compress, leaveOpen: true),
ContentEncodings.Brotli => new BrotliStream(buffer, CompressionMode.Compress, leaveOpen: true),
#endif
_ => throw new ArgumentOutOfRangeException(nameof(encoding))
})
{
var bytes = Encoding.UTF8.GetBytes(Payload);
stream.Write(bytes, 0, bytes.Length);
}
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(buffer.ToArray())
};
response.Content.Headers.ContentEncoding.Add(encoding);
return response;
}
private static IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> CreateOptions(bool enabled)
=> Mock.Of<IOptionsMonitor<OpenIddictClientSystemNetHttpOptions>>(monitor =>
monitor.CurrentValue == new OpenIddictClientSystemNetHttpOptions
@ -123,6 +226,13 @@ public class OpenIddictClientSystemNetHttpHandlersTests
EnableSensitivePayloadLogging = enabled
});
private static IOptionsMonitor<OpenIddictClientSystemNetHttpOptions> CreateOptions(DecompressionMethods methods)
=> Mock.Of<IOptionsMonitor<OpenIddictClientSystemNetHttpOptions>>(monitor =>
monitor.CurrentValue == new OpenIddictClientSystemNetHttpOptions
{
AllowedDecompressionMethods = methods
});
private static OpenIddictClientTransaction CreateTransaction(
ILogger<OpenIddictClientDispatcher> logger, HttpResponseMessage response)
{

41
test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpBuilderTests.cs

@ -4,6 +4,7 @@
* the license and the contributors participating to this project.
*/
using System.Net;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using Xunit;
@ -54,6 +55,46 @@ public class OpenIddictValidationSystemNetHttpBuilderTests
Assert.True(options.EnableSensitivePayloadLogging);
}
[Fact]
public void SetAllowedDecompressionMethods_AllSupportedMethodsAreAllowedByDefault()
{
// Arrange
var services = CreateServices();
CreateBuilder(services);
// Act
var options = GetOptions(services);
// Assert
Assert.Equal(~DecompressionMethods.None, options.AllowedDecompressionMethods);
}
[Theory]
[InlineData(DecompressionMethods.None)]
[InlineData(DecompressionMethods.GZip)]
[InlineData(DecompressionMethods.Deflate)]
[InlineData(DecompressionMethods.GZip | DecompressionMethods.Deflate)]
#if NET
[InlineData(DecompressionMethods.Brotli)]
[InlineData(DecompressionMethods.GZip | DecompressionMethods.Brotli)]
[InlineData(DecompressionMethods.GZip | DecompressionMethods.Deflate | DecompressionMethods.Brotli)]
[InlineData(~DecompressionMethods.None)]
#endif
public void SetAllowedDecompressionMethods_SetsAllowedDecompressionMethods(DecompressionMethods methods)
{
// Arrange
var services = CreateServices();
var builder = CreateBuilder(services);
// Act
builder.SetAllowedDecompressionMethods(methods);
var options = GetOptions(services);
// Assert
Assert.Equal(methods, options.AllowedDecompressionMethods);
}
private static IServiceCollection CreateServices()
=> new ServiceCollection().AddOptions();

110
test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpHandlersTests.cs

@ -5,6 +5,7 @@
*/
using System.Globalization;
using System.IO.Compression;
using System.Net;
using System.Net.Http;
using System.Text;
@ -14,6 +15,7 @@ using Microsoft.Extensions.Options;
using Moq;
using Xunit;
using static OpenIddict.Validation.OpenIddictValidationEvents;
using static OpenIddict.Validation.SystemNetHttp.OpenIddictValidationSystemNetHttpConstants;
using static OpenIddict.Validation.SystemNetHttp.OpenIddictValidationSystemNetHttpHandlers;
namespace OpenIddict.Validation.SystemNetHttp.Tests;
@ -22,6 +24,79 @@ public class OpenIddictValidationSystemNetHttpHandlersTests
{
private const string Payload = "SENSITIVE_PAYLOAD";
public static TheoryData<string, DecompressionMethods> SupportedEncodings => new()
{
{ ContentEncodings.Gzip, DecompressionMethods.GZip },
#if NET
{ ContentEncodings.Deflate, DecompressionMethods.Deflate },
{ ContentEncodings.Brotli, DecompressionMethods.Brotli }
#endif
};
[Theory]
[MemberData(nameof(SupportedEncodings))]
public async Task DecompressResponseContent_DecompressesContentWhenMethodIsAllowed(string encoding, DecompressionMethods method)
{
// Arrange
using var response = CreateCompressedResponse(encoding);
var context = new PrepareConfigurationRequestContext(
CreateTransaction(Mock.Of<ILogger<OpenIddictValidationDispatcher>>(), response));
var handler = new DecompressResponseContent<PrepareConfigurationRequestContext>(CreateOptions(method));
// Act
await handler.HandleAsync(context);
// Assert
Assert.False(context.IsRejected);
Assert.Empty(response.Content.Headers.ContentEncoding);
Assert.Equal(Payload, await response.Content.ReadAsStringAsync());
}
[Theory]
[MemberData(nameof(SupportedEncodings))]
public async Task DecompressResponseContent_RejectsContentWhenMethodIsNotAllowed(string encoding, DecompressionMethods method)
{
// Arrange
using var response = CreateCompressedResponse(encoding);
var context = new PrepareConfigurationRequestContext(
CreateTransaction(Mock.Of<ILogger<OpenIddictValidationDispatcher>>(), response));
// Note: all the methods except the one used to encode the response are allowed.
var handler = new DecompressResponseContent<PrepareConfigurationRequestContext>(CreateOptions(~method));
// Act
await handler.HandleAsync(context);
// Assert
Assert.True(context.IsRejected);
Assert.Equal(Errors.ServerError, context.Error);
Assert.Equal(SR.GetResourceString(SR.ID2211), context.ErrorDescription);
}
[Theory]
[MemberData(nameof(SupportedEncodings))]
public async Task DecompressResponseContent_DecompressesContentWhenAllMethodsAreAllowed(string encoding, DecompressionMethods method)
{
// Arrange
using var response = CreateCompressedResponse(encoding);
var context = new PrepareConfigurationRequestContext(
CreateTransaction(Mock.Of<ILogger<OpenIddictValidationDispatcher>>(), response));
var handler = new DecompressResponseContent<PrepareConfigurationRequestContext>(
CreateOptions(~DecompressionMethods.None));
// Act
await handler.HandleAsync(context);
// Assert
Assert.True((~DecompressionMethods.None).HasFlag(method));
Assert.False(context.IsRejected);
Assert.Empty(response.Content.Headers.ContentEncoding);
Assert.Equal(Payload, await response.Content.ReadAsStringAsync());
}
[Theory]
[InlineData(false)]
[InlineData(true)]
@ -116,6 +191,34 @@ public class OpenIddictValidationSystemNetHttpHandlersTests
It.IsAny<Func<It.IsAnyType, Exception?, string>>()), Times.Once());
}
private static HttpResponseMessage CreateCompressedResponse(string encoding)
{
using var buffer = new MemoryStream();
using (Stream stream = encoding switch
{
ContentEncodings.Gzip => new GZipStream(buffer, CompressionMode.Compress, leaveOpen: true),
#if NET
ContentEncodings.Deflate => new ZLibStream(buffer, CompressionMode.Compress, leaveOpen: true),
ContentEncodings.Brotli => new BrotliStream(buffer, CompressionMode.Compress, leaveOpen: true),
#endif
_ => throw new ArgumentOutOfRangeException(nameof(encoding))
})
{
var bytes = Encoding.UTF8.GetBytes(Payload);
stream.Write(bytes, 0, bytes.Length);
}
var response = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(buffer.ToArray())
};
response.Content.Headers.ContentEncoding.Add(encoding);
return response;
}
private static IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions> CreateOptions(bool enabled)
=> Mock.Of<IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions>>(monitor =>
monitor.CurrentValue == new OpenIddictValidationSystemNetHttpOptions
@ -123,6 +226,13 @@ public class OpenIddictValidationSystemNetHttpHandlersTests
EnableSensitivePayloadLogging = enabled
});
private static IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions> CreateOptions(DecompressionMethods methods)
=> Mock.Of<IOptionsMonitor<OpenIddictValidationSystemNetHttpOptions>>(monitor =>
monitor.CurrentValue == new OpenIddictValidationSystemNetHttpOptions
{
AllowedDecompressionMethods = methods
});
private static OpenIddictValidationTransaction CreateTransaction(
ILogger<OpenIddictValidationDispatcher> logger, HttpResponseMessage response)
{

Loading…
Cancel
Save