From 714647b1faecf291afac73a44451505a80b52dbd Mon Sep 17 00:00:00 2001
From: Manuel Menegazzo <65919883+m3nax@users.noreply.github.com>
Date: Mon, 2 Nov 2026 13:26:43 +0100
Subject: [PATCH] Update the `System.Net.Http` integrations to support
restricting the allowed decompression algorithms
---
.gitignore | 1 +
.../OpenIddictResources.resx | 3 +
.../OpenIddictClientSystemNetHttpBuilder.cs | 10 ++
.../OpenIddictClientSystemNetHttpHandlers.cs | 51 +++++++-
.../OpenIddictClientSystemNetHttpOptions.cs | 12 ++
...penIddictValidationSystemNetHttpBuilder.cs | 10 ++
...enIddictValidationSystemNetHttpHandlers.cs | 51 +++++++-
...penIddictValidationSystemNetHttpOptions.cs | 12 ++
...enIddictClientSystemNetHttpBuilderTests.cs | 41 +++++++
...nIddictClientSystemNetHttpHandlersTests.cs | 110 ++++++++++++++++++
...dictValidationSystemNetHttpBuilderTests.cs | 41 +++++++
...ictValidationSystemNetHttpHandlersTests.cs | 110 ++++++++++++++++++
12 files changed, 448 insertions(+), 4 deletions(-)
diff --git a/.gitignore b/.gitignore
index 4d05dfe3..2c4188f6 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,6 +11,7 @@ target/
# User-specific files
*.suo
*.user
+*.lutconfig
*.sln.docstates
project.lock.json
_references.js
diff --git a/src/OpenIddict.Abstractions/OpenIddictResources.resx b/src/OpenIddict.Abstractions/OpenIddictResources.resx
index 2f79a0b6..8e9fda74 100644
--- a/src/OpenIddict.Abstractions/OpenIddictResources.resx
+++ b/src/OpenIddict.Abstractions/OpenIddictResources.resx
@@ -2415,6 +2415,9 @@ To use a custom policy relying on the system store, set 'OpenIddictServerOptions
The session associated with the token is no longer valid.
+
+ The remote server returned a content encoding that is not allowed by the configured decompression methods.
+
The '{0}' parameter shouldn't be null or empty at this point.
diff --git a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpBuilder.cs b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpBuilder.cs
index dc24d047..1d7ba028 100644
--- a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpBuilder.cs
+++ b/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);
+ ///
+ /// 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.
+ ///
+ /// The allowed decompression methods.
+ /// The instance.
+ public OpenIddictClientSystemNetHttpBuilder SetAllowedDecompressionMethods(DecompressionMethods methods)
+ => Configure(options => options.AllowedDecompressionMethods = methods);
+
///
/// 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 b7ba28ff..bf230764 100644
--- a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpHandlers.cs
+++ b/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
///
public sealed class DecompressResponseContent : IOpenIddictClientHandler where TContext : BaseExternalContext
{
+ private readonly IOptionsMonitor _options;
+
+ public DecompressResponseContent(IOptionsMonitor options)
+ => _options = options ?? throw new ArgumentNullException(nameof(options));
+
///
/// Gets the default descriptor definition assigned to this handler.
///
@@ -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));
diff --git a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpOptions.cs b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpOptions.cs
index 859cf9dc..c9162bfd 100644
--- a/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpOptions.cs
+++ b/src/OpenIddict.Client.SystemNetHttp/OpenIddictClientSystemNetHttpOptions.cs
@@ -79,6 +79,18 @@ public sealed class OpenIddictClientSystemNetHttpOptions
///
public bool EnableSensitivePayloadLogging { get; set; }
+ ///
+ /// 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.
+ ///
+ ///
+ /// 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.
+ ///
+ public DecompressionMethods AllowedDecompressionMethods { get; set; } = ~DecompressionMethods.None;
+
///
/// 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 6e6fd839..c64830ac 100644
--- a/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpBuilder.cs
+++ b/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);
+ ///
+ /// 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.
+ ///
+ /// The allowed decompression methods.
+ /// The instance.
+ public OpenIddictValidationSystemNetHttpBuilder SetAllowedDecompressionMethods(DecompressionMethods methods)
+ => Configure(options => options.AllowedDecompressionMethods = methods);
+
///
/// 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 78e1f460..09e248aa 100644
--- a/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpHandlers.cs
+++ b/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
///
public sealed class DecompressResponseContent : IOpenIddictValidationHandler where TContext : BaseExternalContext
{
+ private readonly IOptionsMonitor _options;
+
+ public DecompressResponseContent(IOptionsMonitor options)
+ => _options = options ?? throw new ArgumentNullException(nameof(options));
+
///
/// Gets the default descriptor definition assigned to this handler.
///
@@ -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));
diff --git a/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpOptions.cs b/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpOptions.cs
index 43cdc4fe..a9913568 100644
--- a/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpOptions.cs
+++ b/src/OpenIddict.Validation.SystemNetHttp/OpenIddictValidationSystemNetHttpOptions.cs
@@ -79,6 +79,18 @@ public sealed class OpenIddictValidationSystemNetHttpOptions
///
public bool EnableSensitivePayloadLogging { get; set; }
+ ///
+ /// 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.
+ ///
+ ///
+ /// 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.
+ ///
+ public DecompressionMethods AllowedDecompressionMethods { get; set; } = ~DecompressionMethods.None;
+
///
/// 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/OpenIddictClientSystemNetHttpBuilderTests.cs b/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpBuilderTests.cs
index a120bdc3..79e9dee0 100644
--- a/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpBuilderTests.cs
+++ b/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();
diff --git a/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpHandlersTests.cs b/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpHandlersTests.cs
index eae44414..04e0a1e6 100644
--- a/test/OpenIddict.Client.SystemNetHttp.Tests/OpenIddictClientSystemNetHttpHandlersTests.cs
+++ b/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 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>(), response));
+ var handler = new DecompressResponseContent(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>(), response));
+
+ // Note: all the methods except the one used to encode the response are allowed.
+ var handler = new DecompressResponseContent(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>(), response));
+ var handler = new DecompressResponseContent(
+ 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>()), 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 CreateOptions(bool enabled)
=> Mock.Of>(monitor =>
monitor.CurrentValue == new OpenIddictClientSystemNetHttpOptions
@@ -123,6 +226,13 @@ public class OpenIddictClientSystemNetHttpHandlersTests
EnableSensitivePayloadLogging = enabled
});
+ private static IOptionsMonitor CreateOptions(DecompressionMethods methods)
+ => Mock.Of>(monitor =>
+ monitor.CurrentValue == new OpenIddictClientSystemNetHttpOptions
+ {
+ AllowedDecompressionMethods = methods
+ });
+
private static OpenIddictClientTransaction CreateTransaction(
ILogger logger, HttpResponseMessage response)
{
diff --git a/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpBuilderTests.cs b/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpBuilderTests.cs
index ea78f68c..defcd8b1 100644
--- a/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpBuilderTests.cs
+++ b/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();
diff --git a/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpHandlersTests.cs b/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpHandlersTests.cs
index 3ed652f7..8ce4d82f 100644
--- a/test/OpenIddict.Validation.SystemNetHttp.Tests/OpenIddictValidationSystemNetHttpHandlersTests.cs
+++ b/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 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>(), response));
+ var handler = new DecompressResponseContent(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>(), response));
+
+ // Note: all the methods except the one used to encode the response are allowed.
+ var handler = new DecompressResponseContent(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>(), response));
+ var handler = new DecompressResponseContent(
+ 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>()), 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 CreateOptions(bool enabled)
=> Mock.Of>(monitor =>
monitor.CurrentValue == new OpenIddictValidationSystemNetHttpOptions
@@ -123,6 +226,13 @@ public class OpenIddictValidationSystemNetHttpHandlersTests
EnableSensitivePayloadLogging = enabled
});
+ private static IOptionsMonitor CreateOptions(DecompressionMethods methods)
+ => Mock.Of>(monitor =>
+ monitor.CurrentValue == new OpenIddictValidationSystemNetHttpOptions
+ {
+ AllowedDecompressionMethods = methods
+ });
+
private static OpenIddictValidationTransaction CreateTransaction(
ILogger logger, HttpResponseMessage response)
{