Skip to content
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

Prevent access to HttpContext throught HttpContextAccessor in TryRefreshAsync #432

Merged
merged 14 commits into from
Jul 27, 2023
Merged
Show file tree
Hide file tree
Changes from all 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
Expand Up @@ -3,7 +3,9 @@
//
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.Azure.AppConfiguration.AspNetCore
Expand All @@ -13,7 +15,11 @@ namespace Microsoft.Azure.AppConfiguration.AspNetCore
/// </summary>
internal class AzureAppConfigurationRefreshMiddleware
{
// The minimum refresh interval on the configuration provider is 1 second, so refreshing more often is unnecessary
private static readonly long MinimumRefreshInterval = TimeSpan.FromSeconds(1).Ticks;
private readonly RequestDelegate _next;
private long _refreshReadyTime = DateTimeOffset.UtcNow.Ticks;

public IEnumerable<IConfigurationRefresher> Refreshers { get; }
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Can you add a new-line before Refreshers to separate properties vs fields.


public AzureAppConfigurationRefreshMiddleware(RequestDelegate next, IConfigurationRefresherProvider refresherProvider)
Expand All @@ -24,9 +30,23 @@ public AzureAppConfigurationRefreshMiddleware(RequestDelegate next, IConfigurati

public async Task InvokeAsync(HttpContext context)
{
foreach (var refresher in Refreshers)
long utcNow = DateTimeOffset.UtcNow.Ticks;

long refreshReadyTime = Interlocked.Read(ref _refreshReadyTime);

if (refreshReadyTime <= utcNow &&
Interlocked.CompareExchange(ref _refreshReadyTime, utcNow + MinimumRefreshInterval, refreshReadyTime) == refreshReadyTime)
{
_ = refresher.TryRefreshAsync();
//
// Configuration refresh is meant to execute as an isolated background task.
// To prevent access of request-based resources, such as HttpContext, we suppress the execution context within the refresh operation.
using (AsyncFlowControl flowControl = ExecutionContext.SuppressFlow())
{
foreach (IConfigurationRefresher refresher in Refreshers)
{
_ = Task.Run(() => refresher.TryRefreshAsync());
}
}
}

// Call the next delegate/middleware in the pipeline
Expand Down
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.
//

using Microsoft.Azure.Functions.Worker;
using Microsoft.Azure.Functions.Worker.Middleware;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;

namespace Microsoft.Azure.AppConfiguration.Functions.Worker
Expand All @@ -15,6 +16,10 @@ namespace Microsoft.Azure.AppConfiguration.Functions.Worker
/// </summary>
internal class AzureAppConfigurationRefreshMiddleware : IFunctionsWorkerMiddleware
{
// The minimum refresh interval on the configuration provider is 1 second, so refreshing more often is unnecessary
private static readonly long MinimumRefreshInterval = TimeSpan.FromSeconds(1).Ticks;
private long _refreshReadyTime = DateTimeOffset.UtcNow.Ticks;

private IEnumerable<IConfigurationRefresher> Refreshers { get; }

public AzureAppConfigurationRefreshMiddleware(IConfigurationRefresherProvider refresherProvider)
Expand All @@ -24,9 +29,23 @@ public AzureAppConfigurationRefreshMiddleware(IConfigurationRefresherProvider re

public async Task Invoke(FunctionContext context, FunctionExecutionDelegate next)
{
foreach (IConfigurationRefresher refresher in Refreshers)
long utcNow = DateTimeOffset.UtcNow.Ticks;

long refreshReadyTime = Interlocked.Read(ref _refreshReadyTime);

if (refreshReadyTime <= utcNow &&
Interlocked.CompareExchange(ref _refreshReadyTime, utcNow + MinimumRefreshInterval, refreshReadyTime) == refreshReadyTime)
{
_ = refresher.TryRefreshAsync();
//
// Configuration refresh is meant to execute as an isolated background task.
// To prevent access of request-based resources, such as HttpContext, we suppress the execution context within the refresh operation.
using (AsyncFlowControl flowControl = ExecutionContext.SuppressFlow())
{
foreach (IConfigurationRefresher refresher in Refreshers)
{
_ = Task.Run(() => refresher.TryRefreshAsync());
}
}
}

await next(context).ConfigureAwait(false);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,19 +6,26 @@
using Microsoft.Azure.Functions.Worker.Middleware;
using Microsoft.Extensions.Configuration.AzureAppConfiguration;
using Moq;
using System;
using System.Threading;
using System.Threading.Tasks;
using Xunit;

namespace Tests.AzureAppConfiguration.Functions.Worker
{
public class RefreshMiddlewareTests
{
[Fact]
public void RefreshMiddlewareTests_MiddlewareConstructorRetrievesIConfigurationRefresher()
public async Task RefreshMiddlewareTests_MiddlewareConstructorRetrievesIConfigurationRefresher()
{
// Arrange
var mockRefresher = new Mock<IConfigurationRefresher>(MockBehavior.Strict);
mockRefresher.Setup(provider => provider.TryRefreshAsync(It.IsAny<CancellationToken>())).ReturnsAsync(true);

int callCount = 0;

mockRefresher.Setup(provider => provider.TryRefreshAsync(It.IsAny<CancellationToken>()))
.Callback(() => Interlocked.Increment(ref callCount))
.ReturnsAsync(true);

var mockRefresherProvider = new Mock<IConfigurationRefresherProvider>(MockBehavior.Strict);
mockRefresherProvider.SetupGet(provider => provider.Refreshers).Returns(new IConfigurationRefresher[] { mockRefresher.Object });
Expand All @@ -30,16 +37,28 @@ public void RefreshMiddlewareTests_MiddlewareConstructorRetrievesIConfigurationR
var middleware = new AzureAppConfigurationRefreshMiddleware(mockRefresherProvider.Object);
_ = middleware.Invoke(mockContext.Object, mockFunctionExecutionDelegate.Object);

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));

while (callCount < 1)
{
await Task.Delay(TimeSpan.FromSeconds(1), cts.Token);
}

// Assert
mockRefresher.Verify(refresher => refresher.TryRefreshAsync(It.IsAny<CancellationToken>()), Times.Once);
}

[Fact]
public void RefreshMiddlewareTests_MiddlewareConstructorRetrievesMultipleIConfigurationRefreshers()
public async Task RefreshMiddlewareTests_MiddlewareConstructorRetrievesMultipleIConfigurationRefreshers()
{
// Arrange
var mockRefresher = new Mock<IConfigurationRefresher>(MockBehavior.Strict);
mockRefresher.Setup(provider => provider.TryRefreshAsync(It.IsAny<CancellationToken>())).ReturnsAsync(true);

int callCount = 0;

mockRefresher.Setup(provider => provider.TryRefreshAsync(It.IsAny<CancellationToken>()))
.Callback(() => Interlocked.Increment(ref callCount))
.ReturnsAsync(true);

var mockRefresherProvider = new Mock<IConfigurationRefresherProvider>(MockBehavior.Strict);
mockRefresherProvider.SetupGet(provider => provider.Refreshers).Returns(new IConfigurationRefresher[] { mockRefresher.Object, mockRefresher.Object });
Expand All @@ -51,6 +70,13 @@ public void RefreshMiddlewareTests_MiddlewareConstructorRetrievesMultipleIConfig
var middleware = new AzureAppConfigurationRefreshMiddleware(mockRefresherProvider.Object);
_ = middleware.Invoke(mockContext.Object, mockFunctionExecutionDelegate.Object);

using var cts = new CancellationTokenSource(TimeSpan.FromSeconds(10));

while (callCount < 2)
{
await Task.Delay(TimeSpan.FromSeconds(1), cts.Token);
}

// Assert
mockRefresher.Verify(refresher => refresher.TryRefreshAsync(It.IsAny<CancellationToken>()), Times.Exactly(2));
}
Expand Down