Skip to content
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 8 additions & 2 deletions src/OpenTelemetry.Sampler.AWS/AWSXRaySamplerClient.cs
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ private void Dispose(bool disposing)

private async Task<string> DoRequestAsync(string endpoint, HttpRequestMessage request)
{
// 1 MB is well above any legitimate X-Ray sampling rules/targets
// response while still protecting against unbounded reads.
const int maxResponseSizeInBytes = 1024 * 1024;

try
{
var response = await this.httpClient.SendAsync(request).ConfigureAwait(false);
Expand All @@ -133,8 +137,10 @@ private async Task<string> DoRequestAsync(string endpoint, HttpRequestMessage re
return string.Empty;
}

var responseString = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
return responseString;
var stream = await response.Content.ReadAsStreamAsync().ConfigureAwait(false);
using var limitedStream = new LimitedStream(stream, maxResponseSizeInBytes);
using var reader = new StreamReader(limitedStream);
return await reader.ReadToEndAsync().ConfigureAwait(false);
Comment thread
normj marked this conversation as resolved.
}
catch (Exception ex)
{
Expand Down
2 changes: 2 additions & 0 deletions src/OpenTelemetry.Sampler.AWS/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@

* Updated OpenTelemetry core component version(s) to `1.15.2`.
([#4080](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/4080))
* Limit the max size read for response body getting the sampling rules to 1MB.
([#4100](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/4100))

## 0.1.0-alpha.7

Expand Down
99 changes: 99 additions & 0 deletions src/OpenTelemetry.Sampler.AWS/LimitedStream.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,99 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

namespace OpenTelemetry.Sampler.AWS;

/// <summary>
/// A read-only stream wrapper that throws <see cref="InvalidOperationException"/>
/// if the underlying stream exceeds a configured maximum number of bytes.
/// This protects against denial-of-service when reading from untrusted HTTP responses.
/// </summary>
internal sealed class LimitedStream : Stream
{
private readonly Stream innerStream;
private readonly long maxBytes;
private long totalBytesRead;

public LimitedStream(Stream innerStream, long maxBytes)
{
this.innerStream = innerStream ?? throw new ArgumentNullException(nameof(innerStream));
Comment thread
normj marked this conversation as resolved.
this.maxBytes = maxBytes;
}

public override bool CanRead => this.innerStream.CanRead;

public override bool CanSeek => false;

public override bool CanWrite => false;

public override long Length => throw new NotSupportedException();

public override long Position
{
get => throw new NotSupportedException();
set => throw new NotSupportedException();
}

public override int Read(byte[] buffer, int offset, int count)
{
var bytesRead = this.innerStream.Read(buffer, offset, count);
this.totalBytesRead += bytesRead;
if (this.totalBytesRead > this.maxBytes)
{
throw new InvalidOperationException(
$"Response exceeded the maximum allowed size of {this.maxBytes} bytes.");
}
Comment thread
normj marked this conversation as resolved.

return bytesRead;
}

public override async Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken)
{
#if NET
return await this.ReadAsync(buffer.AsMemory(offset, count), cancellationToken).ConfigureAwait(false);
#else
var bytesRead = await this.innerStream.ReadAsync(buffer, offset, count, cancellationToken).ConfigureAwait(false);
this.totalBytesRead += bytesRead;
if (this.totalBytesRead > this.maxBytes)
{
throw new InvalidOperationException(
$"Response exceeded the maximum allowed size of {this.maxBytes} bytes.");
}

return bytesRead;
#endif
}

#if NET
public override async ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default)
{
var bytesRead = await this.innerStream.ReadAsync(buffer, cancellationToken).ConfigureAwait(false);
this.totalBytesRead += bytesRead;
if (this.totalBytesRead > this.maxBytes)
{
throw new InvalidOperationException(
$"Response exceeded the maximum allowed size of {this.maxBytes} bytes.");
}

return bytesRead;
}
#endif

public override void Flush() => this.innerStream.Flush();

public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();

public override void SetLength(long value) => throw new NotSupportedException();

public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();

protected override void Dispose(bool disposing)
{
if (disposing)
{
this.innerStream.Dispose();
}

base.Dispose(disposing);
}
}
88 changes: 88 additions & 0 deletions test/OpenTelemetry.Sampler.AWS.Tests/TestLimitedStreamReader.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

using System.Text;
using Xunit;

namespace OpenTelemetry.Sampler.AWS.Tests;

public class TestLimitedStreamReader
{
[Fact]
public async Task ReadWithinLimitSucceeds()
{
var data = Encoding.UTF8.GetBytes("hello");
using var inner = new MemoryStream(data);
using var limited = new LimitedStream(inner, maxBytes: 1024);
using var reader = new StreamReader(limited);

var result = await reader.ReadToEndAsync();

Assert.Equal("hello", result);
}

[Fact]
public async Task ReadExactlyAtLimitSucceeds()
{
var data = Encoding.UTF8.GetBytes("12345");
using var inner = new MemoryStream(data);
using var limited = new LimitedStream(inner, maxBytes: 5);
using var reader = new StreamReader(limited);

var result = await reader.ReadToEndAsync();

Assert.Equal("12345", result);
}

[Fact]
public async Task ReadExceedingLimitThrows()
{
var data = Encoding.UTF8.GetBytes(new string('x', 2048));
using var inner = new MemoryStream(data);
using var limited = new LimitedStream(inner, maxBytes: 1024);
using var reader = new StreamReader(limited);

await Assert.ThrowsAsync<InvalidOperationException>(
() => reader.ReadToEndAsync());
}

[Fact]
public void SyncReadExceedingLimitThrows()
{
var data = Encoding.UTF8.GetBytes(new string('x', 2048));
using var inner = new MemoryStream(data);
using var limited = new LimitedStream(inner, maxBytes: 1024);

var buffer = new byte[2048];
Assert.Throws<InvalidOperationException>(
() => limited.Read(buffer, 0, buffer.Length));
}

[Fact]
public void CannotWrite()
{
using var inner = new MemoryStream();
using var limited = new LimitedStream(inner, maxBytes: 1024);

Assert.False(limited.CanWrite);
Assert.Throws<NotSupportedException>(
() => limited.Write(new byte[1], 0, 1));
}

[Fact]
public void CannotSeek()
{
using var inner = new MemoryStream();
using var limited = new LimitedStream(inner, maxBytes: 1024);

Assert.False(limited.CanSeek);
Assert.Throws<NotSupportedException>(
() => limited.Seek(0, SeekOrigin.Begin));
}

[Fact]
public void ThrowsOnNullInnerStream()
{
Assert.Throws<ArgumentNullException>(() => new LimitedStream(null!, maxBytes: 1024));
}
}
Loading