Skip to content
Open
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
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft. All rights reserved.
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System;
Expand Down Expand Up @@ -28,6 +28,8 @@ internal class MicrosoftEntraAccessKey : IAccessKey

private const int GetMicrosoftEntraTokenMaxRetryTimes = 3;

private const int MaxResponseContentLength = 1024 * 1024; // 1 MB cap to protect against oversized responses.

private readonly object _lock = new object();

private volatile TaskCompletionSource<bool> _updateTaskSource;
Expand Down Expand Up @@ -215,7 +217,7 @@ private static async Task ThrowExceptionOnResponseFailureAsync(HttpRequestMessag
return;
}

var content = await response.Content.ReadAsStringAsync();
var content = await ReadAsStringWithLimitAsync(response.Content);

#if NET5_0_OR_GREATER
var innerException = new HttpRequestException(
Expand Down Expand Up @@ -261,7 +263,7 @@ private async Task HandleHttpResponseAsync(HttpResponseMessage response)
return;
}

var content = await response.Content.ReadAsStringAsync();
var content = await ReadAsStringWithLimitAsync(response.Content);
var obj = JsonSerializer.Deserialize<AccessKeyResponse>(content) ?? throw new AzureSignalRException("Access key response is not expected.");

if (string.IsNullOrEmpty(obj.KeyId))
Expand All @@ -274,4 +276,23 @@ private async Task HandleHttpResponseAsync(HttpResponseMessage response)
}
UpdateAccessKey(obj.KeyId, obj.AccessKey);
}

private static async Task<string> ReadAsStringWithLimitAsync(HttpContent content)
{
if (content.Headers.ContentLength is long length && length > MaxResponseContentLength)
{
throw new AzureSignalRException($"Response content length {length} exceeds the maximum allowed size of {MaxResponseContentLength} bytes.");
}

try
{
await content.LoadIntoBufferAsync(MaxResponseContentLength);
}
catch (HttpRequestException ex)
{
throw new AzureSignalRException($"Response content exceeds the maximum allowed size of {MaxResponseContentLength} bytes.", ex);
}

return await content.ReadAsStringAsync();
}
}
Loading