-
Notifications
You must be signed in to change notification settings - Fork 13
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Feature/8 sensitive data filter (#19)
* add SensitiveDataFilter, so that no user, login, or personal data will be leaked by logs * sensitiveDataFilter: add regex search * add sample creditCard data filter --------- Co-authored-by: Tomasz Dłuski <[email protected]> Co-authored-by: Matthias Güntert <[email protected]>
- Loading branch information
Showing
9 changed files
with
303 additions
and
6 deletions.
There are no files selected for viewing
This file contains 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 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 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
7 changes: 7 additions & 0 deletions
7
src/ApplicationInsightsRequestLogging/Filters/ISensitiveDataFilter.cs
This file contains 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,7 @@ | ||
namespace Azureblue.ApplicationInsights.RequestLogging | ||
{ | ||
public interface ISensitiveDataFilter | ||
{ | ||
string RemoveSensitiveData(string textOrJson); | ||
} | ||
} |
125 changes: 125 additions & 0 deletions
125
src/ApplicationInsightsRequestLogging/Filters/SensitiveDataFilter.cs
This file contains 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,125 @@ | ||
using System; | ||
using System.Collections.Generic; | ||
using System.Linq; | ||
using System.Text.Json; | ||
using System.Text.Json.Nodes; | ||
using System.Text.RegularExpressions; | ||
|
||
namespace Azureblue.ApplicationInsights.RequestLogging | ||
{ | ||
public class SensitiveDataFilter : ISensitiveDataFilter | ||
{ | ||
private const string SensitiveValueMask = "***MASKED***"; | ||
|
||
public readonly HashSet<string> _sensitiveDataPropertyKeys; | ||
private readonly IEnumerable<string> _regexesForSensitiveValues; | ||
|
||
|
||
public SensitiveDataFilter(BodyLoggerOptions options) : this(options.PropertyNamesWithSensitiveData, options.SensitiveDataRegexes) | ||
{ | ||
|
||
} | ||
|
||
public SensitiveDataFilter(IEnumerable<string> sensitiveDataPropertyKeys, IEnumerable<string> regexesForSensitiveValues) | ||
{ | ||
_sensitiveDataPropertyKeys = sensitiveDataPropertyKeys.Select(t => t.ToLowerInvariant()).ToHashSet(); | ||
_regexesForSensitiveValues = regexesForSensitiveValues; | ||
} | ||
|
||
public string RemoveSensitiveData(string textOrJson) | ||
{ | ||
try | ||
{ | ||
var json = JsonNode.Parse(textOrJson); | ||
if (json == null) return string.Empty; | ||
|
||
if (json is JsonValue jValue && TestIfContainsSensitiveData("", jValue.ToString(), _sensitiveDataPropertyKeys, _regexesForSensitiveValues)) | ||
{ | ||
return SensitiveValueMask; | ||
} | ||
RemoveIds(json); | ||
return json.ToJsonString(); | ||
} | ||
catch (JsonException) | ||
{ | ||
if (TestIfContainsSensitiveData("", textOrJson, _sensitiveDataPropertyKeys, _regexesForSensitiveValues)) | ||
{ | ||
return SensitiveValueMask; | ||
} | ||
return textOrJson; | ||
} | ||
} | ||
|
||
private void RemoveIds(JsonNode node) | ||
{ | ||
if (node is JsonObject jObject) | ||
{ | ||
RemoveIds(jObject); | ||
} | ||
else if (node is JsonArray jArray) | ||
{ | ||
RemoveFromArray(jArray); | ||
} | ||
} | ||
|
||
private void RemoveIds(JsonObject? jObject) | ||
{ | ||
if (jObject == null) throw new ArgumentNullException(nameof(jObject)); | ||
|
||
foreach (var jProperty in jObject.ToList()) | ||
{ | ||
if (jProperty.Value is JsonArray array) | ||
{ | ||
RemoveFromArray(array); | ||
} | ||
else if (jProperty.Value is JsonObject obj) | ||
{ | ||
RemoveIds(obj); | ||
} | ||
else if (jProperty.Value is JsonValue val | ||
&& TestIfContainsSensitiveData(jProperty.Key, val.ToString(), _sensitiveDataPropertyKeys, _regexesForSensitiveValues)) | ||
{ | ||
jObject[jProperty.Key] = SensitiveValueMask; | ||
} | ||
} | ||
} | ||
|
||
private void RemoveFromArray(JsonArray jArray) | ||
{ | ||
if (jArray == null) throw new ArgumentNullException(nameof(jArray)); | ||
|
||
foreach (var jNode in jArray.Where(v => v != null)) | ||
{ | ||
RemoveIds(jNode); | ||
Check warning on line 93 in src/ApplicationInsightsRequestLogging/Filters/SensitiveDataFilter.cs GitHub Actions / build
Check warning on line 93 in src/ApplicationInsightsRequestLogging/Filters/SensitiveDataFilter.cs GitHub Actions / build
Check warning on line 93 in src/ApplicationInsightsRequestLogging/Filters/SensitiveDataFilter.cs GitHub Actions / build (ubuntu-latest)
|
||
} | ||
} | ||
|
||
private bool TestIfContainsSensitiveData( | ||
string propertyName, | ||
string propertyValue, | ||
HashSet<string> sensitiveDataPropertyKeys, | ||
IEnumerable<string> regexesForSensitiveValues | ||
) | ||
{ | ||
var propertyNameToCompare = propertyName.ToLowerInvariant(); | ||
var sensitivePropertyName = sensitiveDataPropertyKeys.Contains(propertyNameToCompare) | ||
|| sensitiveDataPropertyKeys.Any(s => propertyNameToCompare.Contains(s)); | ||
|
||
if (sensitivePropertyName) | ||
{ | ||
return true; | ||
} | ||
|
||
foreach (var regex in regexesForSensitiveValues) | ||
{ | ||
if (Regex.IsMatch(propertyValue, regex)) | ||
{ | ||
return true; | ||
} | ||
} | ||
|
||
|
||
return false; | ||
} | ||
} | ||
} |
This file contains 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 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 |
---|---|---|
|
@@ -14,6 +14,7 @@ | |
using Microsoft.ApplicationInsights.DataContracts; | ||
using Moq; | ||
using Microsoft.Extensions.DependencyInjection; | ||
using System.Collections.Generic; | ||
|
||
namespace ApplicationInsightsRequestLoggingTests | ||
{ | ||
|
@@ -23,7 +24,7 @@ public class BodyLoggerMiddlewareTests | |
public void BodyLoggerMiddleware_Should_Throw_If_Ctor_Params_Null() | ||
{ | ||
// Arrange & Act | ||
var action = () => { var middleware = new BodyLoggerMiddleware(null, null, null); }; | ||
var action = () => { var middleware = new BodyLoggerMiddleware(null, null, null, null); }; | ||
|
||
// Assert | ||
action.Should().Throw<NullReferenceException>(); | ||
|
@@ -43,6 +44,7 @@ public async void BodyLoggerMiddleware_Should_Send_Data_To_AppInsights() | |
.ConfigureServices(services => | ||
{ | ||
services.AddTransient<IBodyReader, BodyReader>(); | ||
services.AddTransient<ISensitiveDataFilter, SensitiveDataFilter>(); | ||
services.AddSingleton(telemetryWriter.Object); | ||
services.AddTransient<BodyLoggerMiddleware>(); | ||
}) | ||
|
@@ -87,6 +89,7 @@ public async void BodyLoggerMiddleware_Should_Not_Send_Data_To_AppInsights_When_ | |
{ | ||
services.AddTransient<IBodyReader, BodyReader>(); | ||
services.AddSingleton(telemetryWriter.Object); | ||
services.AddTransient<ISensitiveDataFilter, SensitiveDataFilter>(); | ||
services.AddTransient<BodyLoggerMiddleware>(); | ||
}) | ||
.Configure(app => | ||
|
@@ -150,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() | ||
{ | ||
|
@@ -162,6 +207,7 @@ public async void BodyLoggerMiddleware_Should_Properly_Pass() | |
.ConfigureServices(services => | ||
{ | ||
services.AddAppInsightsHttpBodyLogging(); | ||
services.AddTransient<ISensitiveDataFilter, SensitiveDataFilter>(); | ||
}) | ||
.Configure(app => | ||
{ | ||
|
Oops, something went wrong.