-
-
Notifications
You must be signed in to change notification settings - Fork 226
fix: Sentry capturing compressed bodies when RequestDecompression middleware is enabled #4315
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
1e9d22b
Fix Directory.Build.targets when using SentryNoMobile.slnf
jamescrosswell 75dec32
fix: Sentry capturing compressed bodies when RequestDecompression mid…
jamescrosswell 839fb37
Format code
getsentry-bot f3873ad
Update CHANGELOG.md
jamescrosswell ea688cf
Merge branch 'main' into request-decompression-middleware
jamescrosswell 1240694
Vendored in the RequestDecompressionMiddleware so we can catch any ex…
jamescrosswell 2ef850d
.
jamescrosswell ee1b9b9
Create RequestDecompressionMiddlewareTests.cs
jamescrosswell a4ec827
Update RequestDecompressionMiddlewareTests.cs
jamescrosswell 073c171
Decompression error test
jamescrosswell 19b5b33
Update RequestDecompressionMiddlewareTests.cs
jamescrosswell 4852747
Format code
getsentry-bot f0afcb5
Update CHANGELOG.md
jamescrosswell 9451236
Merge branch 'main' into request-decompression-middleware
jamescrosswell 1ce0a28
Update CHANGELOG.md
jamescrosswell 76ebf4f
Review feedback
jamescrosswell f2a411b
Update RequestDecompressionMiddlewareTests.cs
jamescrosswell a0b6f78
Format code
getsentry-bot 300248f
Merge branch 'main' into request-decompression-middleware
jamescrosswell File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
28 changes: 28 additions & 0 deletions
28
src/Sentry.AspNetCore/RequestDecompression/ATTRIBUTION.txt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,28 @@ | ||
| The code in this subdirectory has been adapted from | ||
| https://github.com/dotnet/aspnetcore | ||
|
|
||
| The original license is as follows: | ||
|
|
||
| The MIT License (MIT) | ||
|
|
||
| Copyright (c) .NET Foundation and Contributors | ||
|
|
||
| All rights reserved. | ||
|
|
||
| Permission is hereby granted, free of charge, to any person obtaining a copy | ||
| of this software and associated documentation files (the "Software"), to deal | ||
| in the Software without restriction, including without limitation the rights | ||
| to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
| copies of the Software, and to permit persons to whom the Software is | ||
| furnished to do so, subject to the following conditions: | ||
|
|
||
| The above copyright notice and this permission notice shall be included in all | ||
| copies or substantial portions of the Software. | ||
|
|
||
| THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
| IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
| FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
| AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
| LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
| OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE | ||
| SOFTWARE. |
107 changes: 107 additions & 0 deletions
107
src/Sentry.AspNetCore/RequestDecompression/RequestDecompressionMiddleware.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,107 @@ | ||
| // Adapted from: https://github.com/dotnet/aspnetcore/blob/c18e93a9a2e2949e1a9c880da16abf0837aa978f/src/Middleware/RequestDecompression/src/RequestDecompressionMiddleware.cs | ||
|
|
||
| // // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.AspNetCore.Http.Features; | ||
| using Microsoft.AspNetCore.Http.Metadata; | ||
| using Microsoft.AspNetCore.RequestDecompression; | ||
| using Microsoft.Extensions.Logging; | ||
|
|
||
| namespace Sentry.AspNetCore.RequestDecompression; | ||
|
|
||
| /// <summary> | ||
| /// Enables HTTP request decompression. | ||
| /// </summary> | ||
| internal sealed partial class RequestDecompressionMiddleware | ||
| { | ||
| private readonly RequestDelegate _next; | ||
| private readonly ILogger<RequestDecompressionMiddleware> _logger; | ||
| private readonly IRequestDecompressionProvider _provider; | ||
| private readonly IHub _hub; | ||
|
|
||
| /// <summary> | ||
| /// Initialize the request decompression middleware. | ||
| /// </summary> | ||
| /// <param name="next">The delegate representing the remaining middleware in the request pipeline.</param> | ||
| /// <param name="logger">The logger.</param> | ||
| /// <param name="provider">The <see cref="IRequestDecompressionProvider"/>.</param> | ||
| /// <param name="hub">The Sentry Hub</param> | ||
| public RequestDecompressionMiddleware( | ||
| RequestDelegate next, | ||
| ILogger<RequestDecompressionMiddleware> logger, | ||
| IRequestDecompressionProvider provider, | ||
| IHub hub) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(next); | ||
| ArgumentNullException.ThrowIfNull(logger); | ||
| ArgumentNullException.ThrowIfNull(provider); | ||
| ArgumentNullException.ThrowIfNull(hub); | ||
|
|
||
| _next = next; | ||
| _logger = logger; | ||
| _provider = provider; | ||
| _hub = hub; | ||
| } | ||
|
|
||
| /// <summary> | ||
| /// Invoke the middleware. | ||
| /// </summary> | ||
| /// <param name="context">The <see cref="HttpContext"/>.</param> | ||
| /// <returns>A task that represents the execution of this middleware.</returns> | ||
| public Task Invoke(HttpContext context) | ||
| { | ||
| Stream? decompressionStream = null; | ||
| try | ||
| { | ||
| decompressionStream = _provider.GetDecompressionStream(context); | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| HandleException(e); | ||
| } | ||
| return decompressionStream is null | ||
| ? _next(context) | ||
| : InvokeCore(context, decompressionStream); | ||
| } | ||
|
|
||
| private async Task InvokeCore(HttpContext context, Stream decompressionStream) | ||
| { | ||
| var request = context.Request.Body; | ||
| try | ||
| { | ||
| try | ||
| { | ||
| var sizeLimit = | ||
| context.GetEndpoint()?.Metadata?.GetMetadata<IRequestSizeLimitMetadata>()?.MaxRequestBodySize | ||
| ?? context.Features.Get<IHttpMaxRequestBodySizeFeature>()?.MaxRequestBodySize; | ||
|
|
||
| context.Request.Body = new SizeLimitedStream(decompressionStream, sizeLimit, static (long sizeLimit) => throw new BadHttpRequestException( | ||
| $"The decompressed request body is larger than the request body size limit {sizeLimit}.", | ||
| StatusCodes.Status413PayloadTooLarge)); | ||
| } | ||
| catch (Exception e) | ||
| { | ||
| HandleException(e); | ||
| } | ||
|
|
||
| await _next(context).ConfigureAwait(false); | ||
| } | ||
| finally | ||
| { | ||
| context.Request.Body = request; | ||
| await decompressionStream.DisposeAsync().ConfigureAwait(false); | ||
| } | ||
| } | ||
|
|
||
| private void HandleException(Exception e) | ||
| { | ||
| const string description = | ||
| "An exception was captured and then re-thrown, when attempting to decompress the request body." + | ||
| "The web server likely returned a 5xx error code as a result of this exception."; | ||
| e.SetSentryMechanism(nameof(RequestDecompressionMiddleware), description, handled: false); | ||
| _hub.CaptureException(e); | ||
| ExceptionDispatchInfo.Capture(e).Throw(); | ||
| } | ||
| } | ||
113 changes: 113 additions & 0 deletions
113
src/Sentry.AspNetCore/RequestDecompression/SizeLimitedStream.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| // Copied from: https://github.com/dotnet/aspnetcore/blob/c18e93a9a2e2949e1a9c880da16abf0837aa978f/src/Shared/SizeLimitedStream.cs | ||
| // The only changes are the namespace and the addition of this comment | ||
|
|
||
| // Licensed to the .NET Foundation under one or more agreements. | ||
| // The .NET Foundation licenses this file to you under the MIT license. | ||
|
|
||
| namespace Sentry.AspNetCore.RequestDecompression; | ||
|
|
||
| #nullable enable | ||
|
|
||
| internal sealed class SizeLimitedStream : Stream | ||
| { | ||
| private readonly Stream _innerStream; | ||
| private readonly long? _sizeLimit; | ||
| private readonly Action<long>? _handleSizeLimit; | ||
| private long _totalBytesRead; | ||
|
|
||
| public SizeLimitedStream(Stream innerStream, long? sizeLimit, Action<long>? handleSizeLimit = null) | ||
| { | ||
| ArgumentNullException.ThrowIfNull(innerStream); | ||
|
|
||
| _innerStream = innerStream; | ||
| _sizeLimit = sizeLimit; | ||
| _handleSizeLimit = handleSizeLimit; | ||
| } | ||
|
|
||
| public override bool CanRead => _innerStream.CanRead; | ||
|
|
||
| public override bool CanSeek => _innerStream.CanSeek; | ||
|
|
||
| public override bool CanWrite => _innerStream.CanWrite; | ||
|
|
||
| public override long Length => _innerStream.Length; | ||
|
|
||
| public override long Position | ||
| { | ||
| get | ||
| { | ||
| return _innerStream.Position; | ||
| } | ||
| set | ||
| { | ||
| _innerStream.Position = value; | ||
| } | ||
| } | ||
|
|
||
| public override void Flush() | ||
| { | ||
| _innerStream.Flush(); | ||
| } | ||
|
|
||
| public override int Read(byte[] buffer, int offset, int count) | ||
| { | ||
| var bytesRead = _innerStream.Read(buffer, offset, count); | ||
|
|
||
| _totalBytesRead += bytesRead; | ||
| if (_totalBytesRead > _sizeLimit) | ||
| { | ||
| if (_handleSizeLimit != null) | ||
| { | ||
| _handleSizeLimit(_sizeLimit.Value); | ||
| } | ||
| else | ||
| { | ||
| throw new InvalidOperationException("The maximum number of bytes have been read."); | ||
| } | ||
| } | ||
|
|
||
| return bytesRead; | ||
| } | ||
|
|
||
| public override long Seek(long offset, SeekOrigin origin) | ||
| { | ||
| return _innerStream.Seek(offset, origin); | ||
| } | ||
|
|
||
| public override void SetLength(long value) | ||
| { | ||
| _innerStream.SetLength(value); | ||
| } | ||
|
|
||
| public override void Write(byte[] buffer, int offset, int count) | ||
| { | ||
| _innerStream.Write(buffer, offset, count); | ||
| } | ||
|
|
||
| public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) | ||
| { | ||
| return ReadAsync(buffer.AsMemory(offset, count), cancellationToken).AsTask(); | ||
| } | ||
|
|
||
| public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) | ||
| { | ||
| #pragma warning disable CA2007 | ||
| var bytesRead = await _innerStream.ReadAsync(buffer, cancellationToken); | ||
| #pragma warning restore CA2007 | ||
|
|
||
| _totalBytesRead += bytesRead; | ||
| if (_totalBytesRead > _sizeLimit) | ||
| { | ||
| if (_handleSizeLimit != null) | ||
| { | ||
| _handleSizeLimit(_sizeLimit.Value); | ||
| } | ||
| else | ||
| { | ||
| throw new InvalidOperationException("The maximum number of bytes have been read."); | ||
| } | ||
| } | ||
|
|
||
| return bytesRead; | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.