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

Bypass of Health/Readiness Probes #118

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions samples/3.1/MvcSample/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,8 @@ public void ConfigureServices(IServiceCollection services)
options.RequestHeader = "My-Custom-Correlation-Id";
options.ResponseHeader = "X-Correlation-Id";
options.UpdateTraceIdentifier = false;
options.ExcludeHealthProbes = true;
options.EndpointExclusion.Add("notThisEndPoint");
});

// Example of registering a custom correlation ID provider
Expand Down
2 changes: 1 addition & 1 deletion samples/3.1/MvcSampleTests/MvcSampleTests.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<TargetFramework>net6.0</TargetFramework>

<IsPackable>false</IsPackable>
</PropertyGroup>
Expand Down
2 changes: 1 addition & 1 deletion src/CorrelationId/CorrelationId.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<TargetFramework>netstandard2.1</TargetFramework>
<GeneratePackageOnBuild>False</GeneratePackageOnBuild>
<Authors>Steve Gordon</Authors>
<Company>Steve Gordon | www.stevejgordon.co.uk</Company>
Expand Down
26 changes: 26 additions & 0 deletions src/CorrelationId/CorrelationIdMiddleware.cs
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,8 @@ public CorrelationIdMiddleware(RequestDelegate next, ILogger<CorrelationIdMiddle
/// <param name="correlationContextFactory">The <see cref="ICorrelationContextFactory"/> which can create a <see cref="CorrelationContext"/>.</param>
public async Task Invoke(HttpContext context, ICorrelationContextFactory correlationContextFactory)
{
await HealthCheckProcess(context);

Log.CorrelationIdProcessingBegin(_logger);

if (_correlationIdProvider is null)
Expand Down Expand Up @@ -128,6 +130,30 @@ public async Task Invoke(HttpContext context, ICorrelationContextFactory correla
Log.DisposingCorrelationContext(_logger);
correlationContextFactory.Dispose();
}

private async Task HealthCheckProcess(HttpContext context)
{
if (_options.ExcludeHealthProbes && context.Request.Path.HasValue)
{
if (Uri.TryCreate(context.Request.Path.Value, UriKind.Absolute, out Uri uriRawPath))
{
var uriPath = uriRawPath.PathAndQuery.Contains('?')
? uriRawPath.PathAndQuery.Split('?')[0]
: uriRawPath.PathAndQuery;

if (_options.EndpointExclusion.Exists(_ => uriPath.Contains(_, StringComparison.OrdinalIgnoreCase)))
{
await _next(context);
}
}

if (_options.EndpointExclusion.Exists(_ =>
context.Request.Path.Value.Contains(_, StringComparison.OrdinalIgnoreCase)))
{
await _next(context);
}
}
}

private static bool RequiresGenerationOfCorrelationId(bool idInHeader, StringValues idFromHeader) =>
!idInHeader || StringValues.IsNullOrEmpty(idFromHeader);
Expand Down
16 changes: 16 additions & 0 deletions src/CorrelationId/CorrelationIdOptions.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
using System;
using System.Collections.Generic;
using CorrelationId.Abstractions;

namespace CorrelationId
Expand Down Expand Up @@ -86,5 +87,20 @@ public class CorrelationIdOptions
/// When set, this function will be used instead of the registered <see cref="ICorrelationIdProvider"/>.
/// </summary>
public Func<string> CorrelationIdGenerator { get; set; }
/// <summary>
/// <para>
/// Controls whether the CorrelationId or TraceIdentifier is generated for Health Check probes.
/// </para>
/// <para>Default: false</para>
/// </summary>
public bool ExcludeHealthProbes { get; set; } = true;

/// <summary>
/// <para>
/// Default Health Check and metric probe names.
/// </para>
/// <para>Defaults: "ready", "live", "health", "metric", "management"</para>
/// </summary>
public List<string> EndpointExclusion { get; set; } = new List<string> { "ready", "live", "health", "metric", "management" };
}
}
2 changes: 1 addition & 1 deletion test/CorrelationId.Tests/CorrelationId.Tests.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<TargetFramework>net6.0</TargetFramework>
<LangVersion>8</LangVersion>
</PropertyGroup>

Expand Down
112 changes: 112 additions & 0 deletions test/CorrelationId.Tests/CorrelationIdMiddlewareTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,118 @@ namespace CorrelationId.Tests
{
public class CorrelationIdMiddlewareTests
{
[Theory]
[InlineData("/health/ready?edata=test")]
[InlineData("/health/ready")]
[InlineData("/health/live")]
[InlineData("/management/bundle")]
[InlineData("/metrics")]
[InlineData("/health")]
public async Task DoesNotThrow_WhenHealthCheckProbeIsIncluded(string targetEndpoint)
{
Exception exception = null;

var builder = new WebHostBuilder()
.Configure(app =>
{
app.Use(async (ctx, next) =>
{
try
{
await next.Invoke();
}
catch (Exception e)
{
exception = e;
}
});

app.UseCorrelationId();
})
.ConfigureServices(sc => sc.AddDefaultCorrelationId(options =>
{
options.ExcludeHealthProbes = false;
}));

using var server = new TestServer(builder);

await server.CreateClient().GetAsync(targetEndpoint);

Assert.Null(exception);
}

[Theory]
[InlineData("/health/ready?edata=test")]
[InlineData("/health/ready")]
[InlineData("/health/live")]
[InlineData("/management/bundle")]
[InlineData("/metrics")]
[InlineData("/health")]
public async Task DoesNotThrow_WhenHealthCheckProbeIsExcluded(string targetEndpoint)
{
Exception exception = null;

var builder = new WebHostBuilder()
.Configure(app =>
{
app.Use(async (ctx, next) =>
{
try
{
await next.Invoke();
}
catch (Exception e)
{
exception = e;
}
});

app.UseCorrelationId();
})
.ConfigureServices(sc => sc.AddDefaultCorrelationId());

using var server = new TestServer(builder);

await server.CreateClient().GetAsync(targetEndpoint);

Assert.Null(exception);
}

[Fact]
public async Task DoesNotThrow_WhenHealthCheckProbeIsExcludedWithCustomEndpoint()
{
Exception exception = null;
var customEndpoint = "notThisEndpoint";

var builder = new WebHostBuilder()
.Configure(app =>
{
app.Use(async (ctx, next) =>
{
try
{
await next.Invoke();
}
catch (Exception e)
{
exception = e;
}
});

app.UseCorrelationId();
})
.ConfigureServices(sc => sc.AddDefaultCorrelationId(options =>
{
options.EndpointExclusion.Add(customEndpoint);
}));

using var server = new TestServer(builder);

await server.CreateClient().GetAsync($"/{customEndpoint}");

Assert.Null(exception);
}

[Fact]
public async Task Throws_WhenCorrelationIdProviderIsNotRegistered()
{
Expand Down