-
Notifications
You must be signed in to change notification settings - Fork 0
fix(service-defaults): security trio — middleware order, JWT, error t… #25
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
4 commits
Select commit
Hold shift + click to select a range
3e4de55
fix(service-defaults): security trio — middleware order, JWT, error t…
emeraldleaf 6e2d45c
fix(service-defaults): place CorrelationIdMiddleware between Auth and…
emeraldleaf 53af8a6
Merge branch 'main' into fix/service-defaults-security-trio
emeraldleaf 27b8a93
test(service-defaults): unit tests for JWT options + GlobalExceptionH…
emeraldleaf 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
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
100 changes: 100 additions & 0 deletions
100
tests/OrderService.Tests.Unit/Application/GlobalExceptionHandlerTests.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,100 @@ | ||
| using System.Diagnostics; | ||
| using System.Text.Json; | ||
| using AwesomeAssertions; | ||
| using Microsoft.AspNetCore.Http; | ||
| using Microsoft.Extensions.Logging; | ||
| using NextAurora.ServiceDefaults; | ||
| using NSubstitute; | ||
|
|
||
| namespace OrderService.Tests.Unit.Application; | ||
|
|
||
| /// <summary> | ||
| /// Tests for <see cref="GlobalExceptionHandler"/> — specifically the recent change | ||
| /// that switched the response <c>traceId</c> from <c>Activity.Current?.Id</c> (full | ||
| /// W3C traceparent with span ID) to <c>Activity.Current?.TraceId.ToString()</c> | ||
| /// (trace component only). The span-ID leak is a CWE-200 information disclosure | ||
| /// of server-side handler call structure; tests pin the correct shape. | ||
| /// </summary> | ||
| public class GlobalExceptionHandlerTests | ||
| { | ||
| private readonly ILogger<GlobalExceptionHandler> _logger = | ||
| Substitute.For<ILogger<GlobalExceptionHandler>>(); | ||
|
|
||
| [Fact] | ||
| public async Task TryHandleAsync_WhenActivityIsActive_ReturnsTraceIdOnly_NotFullActivityId() | ||
| { | ||
| using var activity = new Activity("test"); | ||
| activity.Start(); | ||
| var (sut, httpContext, responseStream) = BuildSut(); | ||
|
|
||
| var handled = await sut.TryHandleAsync( | ||
| httpContext, new InvalidOperationException("boom"), CancellationToken.None); | ||
|
|
||
| handled.Should().BeTrue(); | ||
| var traceIdInResponse = await ExtractTraceIdAsync(responseStream); | ||
|
|
||
| // The response traceId must be the trace component only (32 hex chars), NOT | ||
| // Activity.Id which is the full W3C traceparent "00-<trace>-<span>-<flags>" | ||
| // and leaks span information. | ||
| traceIdInResponse.Should().Be(activity.TraceId.ToString()); | ||
| traceIdInResponse.Should().NotBe(activity.Id); | ||
| traceIdInResponse.Should().NotContain("-", | ||
| "the W3C traceparent format uses hyphens to separate version/trace/span/flags; the bare trace component has none"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task TryHandleAsync_WhenNoActivity_FallsBackToHttpContextTraceIdentifier() | ||
| { | ||
| // Belt-and-suspenders: ensure no Activity is leaking from a previous test. | ||
| // Activity.Current is an AsyncLocal; in xunit a class's tests run sequentially | ||
| // so the `using` in the prior test should have stopped its activity, but | ||
| // assert here to be explicit. | ||
| Activity.Current.Should().BeNull(); | ||
|
|
||
| var (sut, httpContext, responseStream) = BuildSut(); | ||
| httpContext.TraceIdentifier = "fallback-trace-from-aspnetcore"; | ||
|
|
||
| await sut.TryHandleAsync( | ||
| httpContext, new InvalidOperationException("boom"), CancellationToken.None); | ||
|
|
||
| var traceIdInResponse = await ExtractTraceIdAsync(responseStream); | ||
| traceIdInResponse.Should().Be("fallback-trace-from-aspnetcore"); | ||
| } | ||
|
|
||
| [Fact] | ||
| public async Task TryHandleAsync_AlwaysReturnsProblemDetailsWithGenericDetail_NeverExceptionMessage() | ||
| { | ||
| // Defense against information disclosure: the response must never include the | ||
| // raw exception message (which can leak SQL fragments, file paths, stack | ||
| // traces, etc.). Per CLAUDE.md "Security Requirements — Error Handling". | ||
| var (sut, httpContext, responseStream) = BuildSut(); | ||
| var sensitiveException = new InvalidOperationException( | ||
| "SELECT * FROM Users WHERE Password = 'super-secret-leaked-via-error'"); | ||
|
|
||
| await sut.TryHandleAsync(httpContext, sensitiveException, CancellationToken.None); | ||
|
|
||
| responseStream.Position = 0; | ||
| using var reader = new StreamReader(responseStream); | ||
| var body = await reader.ReadToEndAsync(); | ||
| body.Should().NotContain("super-secret-leaked-via-error"); | ||
| body.Should().NotContain("SELECT * FROM"); | ||
| } | ||
|
|
||
| private (GlobalExceptionHandler sut, DefaultHttpContext context, MemoryStream responseStream) BuildSut() | ||
| { | ||
| var sut = new GlobalExceptionHandler(_logger); | ||
| var httpContext = new DefaultHttpContext(); | ||
| var responseStream = new MemoryStream(); | ||
| httpContext.Response.Body = responseStream; | ||
| return (sut, httpContext, responseStream); | ||
| } | ||
|
|
||
| private static async Task<string?> ExtractTraceIdAsync(MemoryStream responseStream) | ||
| { | ||
| responseStream.Position = 0; | ||
| using var reader = new StreamReader(responseStream); | ||
| var body = await reader.ReadToEndAsync(); | ||
| var problem = JsonSerializer.Deserialize<JsonElement>(body); | ||
| return problem.GetProperty("traceId").GetString(); | ||
| } | ||
| } |
78 changes: 78 additions & 0 deletions
78
tests/OrderService.Tests.Unit/Application/ServiceDefaultsJwtTests.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,78 @@ | ||
| using AwesomeAssertions; | ||
| using Microsoft.AspNetCore.Authentication.JwtBearer; | ||
| using Microsoft.Extensions.Configuration; | ||
| using Microsoft.Extensions.DependencyInjection; | ||
| using Microsoft.Extensions.Hosting; | ||
| using Microsoft.Extensions.Options; | ||
|
|
||
| namespace OrderService.Tests.Unit.Application; | ||
|
|
||
| /// <summary> | ||
| /// Tests for the JWT Bearer options configured in | ||
| /// <c>NextAurora.ServiceDefaults.Extensions.AddDefaultAuthentication</c> — pins the | ||
| /// security-hardened defaults (explicit signing-key validation + tight ClockSkew) | ||
| /// so a future config change can't silently weaken them. | ||
| /// </summary> | ||
| public class ServiceDefaultsJwtTests | ||
| { | ||
| [Fact] | ||
| public void AddServiceDefaults_WhenAuthorityConfigured_SetsExplicitSigningKeyValidation() | ||
| { | ||
| using var host = BuildHostWithAuthority(); | ||
| var options = host.Services | ||
| .GetRequiredService<IOptionsMonitor<JwtBearerOptions>>() | ||
| .Get(JwtBearerDefaults.AuthenticationScheme); | ||
|
|
||
| // Without this, JWT Bearer's implicit default still validates (via JWKS), but | ||
| // making it explicit makes the security posture auditable + prevents a future | ||
| // config refactor from accidentally disabling signature validation. | ||
| options.TokenValidationParameters.ValidateIssuerSigningKey.Should().BeTrue(); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void AddServiceDefaults_WhenAuthorityConfigured_SetsTightClockSkew() | ||
| { | ||
| using var host = BuildHostWithAuthority(); | ||
| var options = host.Services | ||
| .GetRequiredService<IOptionsMonitor<JwtBearerOptions>>() | ||
| .Get(JwtBearerDefaults.AuthenticationScheme); | ||
|
|
||
| // Default ClockSkew is 5 minutes — revoked/expired tokens stay accepted for | ||
| // 5 extra minutes, material on typical 15-minute access-token lifetimes. We | ||
| // pin 30 seconds: covers inter-server clock drift without giving attackers a | ||
| // long replay window. | ||
| options.TokenValidationParameters.ClockSkew.Should().Be(TimeSpan.FromSeconds(30)); | ||
| } | ||
|
|
||
| [Fact] | ||
| public void AddServiceDefaults_WhenAuthorityConfigured_RetainsCoreValidations() | ||
| { | ||
| // Defense against a refactor that drops one of the foundational validations. | ||
| // ValidateAudience/Issuer/Lifetime were already on; this test pins them. | ||
| using var host = BuildHostWithAuthority(); | ||
| var options = host.Services | ||
| .GetRequiredService<IOptionsMonitor<JwtBearerOptions>>() | ||
| .Get(JwtBearerDefaults.AuthenticationScheme); | ||
|
|
||
| options.TokenValidationParameters.ValidateAudience.Should().BeTrue(); | ||
| options.TokenValidationParameters.ValidateIssuer.Should().BeTrue(); | ||
| options.TokenValidationParameters.ValidateLifetime.Should().BeTrue(); | ||
| } | ||
|
|
||
| private static IHost BuildHostWithAuthority() | ||
| { | ||
| var builder = Host.CreateApplicationBuilder(); | ||
|
|
||
| // AddDefaultAuthentication branches on whether an authority is configured. | ||
| // With one, it wires AddJwtBearer with the TokenValidationParameters we're | ||
| // testing. Without one, it registers no-op auth and the JwtBearerOptions | ||
| // doesn't get configured. | ||
| builder.Configuration.AddInMemoryCollection(new Dictionary<string, string?>(StringComparer.Ordinal) | ||
| { | ||
| ["Keycloak:Url"] = "https://example.keycloak.test/realms/nextaurora", | ||
| }); | ||
|
|
||
| builder.AddServiceDefaults(); | ||
| return builder.Build(); | ||
| } | ||
| } |
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.