Skip to content

Commit

Permalink
Added test: BodyLoggerMiddleware_Should_Redact_Password.
Browse files Browse the repository at this point in the history
  • Loading branch information
ColinNg committed Feb 13, 2024
1 parent 6131757 commit 9c8fc01
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ public BodyLoggerOptions()
/// Controls storage of client IP addresses https://learn.microsoft.com/en-us/azure/azure-monitor/app/ip-collection?tabs=net
/// </summary>
public bool DisableIpMasking { get; set; } = false;

public List<string> PropertyNamesWithSensitiveData { get; set; } = new List<string>()
{
"password",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
using Microsoft.ApplicationInsights.DataContracts;
using Moq;
using Microsoft.Extensions.DependencyInjection;
using System.Collections.Generic;

namespace ApplicationInsightsRequestLoggingTests
{
Expand Down Expand Up @@ -152,6 +153,48 @@ public async void BodyLoggerMiddleware_Should_Leave_Body_intact()
body.Should().Be("Hello from client");
}

[Fact]
public async void BodyLoggerMiddleware_Should_Redact_Password()
{
// Arrange
var telemetryWriter = new Mock<ITelemetryWriter>();

using var host = await new HostBuilder()
.ConfigureWebHost(webBuilder =>
{
webBuilder
.UseTestServer()
.ConfigureServices(services =>
{
services.AddTransient<IBodyReader, BodyReader>();
services.AddTransient<ISensitiveDataFilter>(provider =>
{
return new SensitiveDataFilter(new List<string>() { "password" }, new List<string>());
});
services.AddSingleton(telemetryWriter.Object);
services.AddTransient<BodyLoggerMiddleware>();
})
.Configure(app =>
{
app.UseMiddleware<BodyLoggerMiddleware>();
app.Run(async context =>
{
// Send request body back in response body
context.Response.StatusCode = StatusCodes.Status400BadRequest;
await context.Request.Body.CopyToAsync(context.Response.Body);
});
});
})
.StartAsync();

// Act
var response = await host.GetTestClient().PostAsync("/", new StringContent("{\"email\":\"[email protected]\",\"password\":\"P@ssw0rd!\"}"));

// Assert
telemetryWriter.Verify(x => x.Write(It.IsAny<HttpContext>(), "RequestBody", "{\"email\":\"[email protected]\",\"password\":\"***MASKED***\"}"), Times.Once);
telemetryWriter.Verify(x => x.Write(It.IsAny<HttpContext>(), "ResponseBody", "{\"email\":\"[email protected]\",\"password\":\"***MASKED***\"}"), Times.Once);
}

[Fact]
public async void BodyLoggerMiddleware_Should_Properly_Pass()
{
Expand Down

0 comments on commit 9c8fc01

Please sign in to comment.