Skip to content
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 @@ -6,6 +6,11 @@
"Upload": false,
"Download": false,
"Print": false,
"Masking": {
"Level": "Full",
"UseStandardRules": true,
"Rules": []
},
"LocalFile": {
"Enabled": false,
"Directory": "",
Expand Down
5 changes: 5 additions & 0 deletions BrowserGuard.Tests/Configuration/testconfig/02_strict.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
"Upload": true,
"Download": true,
"Print": true,
"Masking": {
"Level": "Full",
"UseStandardRules": true,
"Rules": []
},
"LocalFile": {
"Enabled": true,
"Directory": "C:\\BrowserGuardTest\\NetLog\\%MACHINENAME%",
Expand Down
241 changes: 241 additions & 0 deletions BrowserGuard.Tests/NetLogger/NetLogMaskerTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,241 @@
/*
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.

Copyright (c) 2026 ClearCode Inc.
*/

using System;
using System.IO;
using System.Linq;
using System.Text.Json;
using BrowserGuard.Common;
using BrowserGuard.Configuration;
using BrowserGuard.NetLogger;
using BrowserGuard.UploadFileBridge;
using Xunit;

namespace BrowserGuard.Tests.NetLogger
{
public class NetLogMaskerTests
{
static NetLogMasker Masker(string level = "Full", params NetLogMaskRuleConfig[] rules) =>
new(new NetLogMaskingConfig { Level = level, Rules = rules });

static NetLogMaskRuleConfig Rule(string pattern, string scope = "Part") =>
new() { Pattern = pattern, Scope = scope };

[Theory]
[InlineData("card 4111 1111 1111 1111.", "card ***.")]
[InlineData("card 4111 1111 1111 1112.", "card 4111 1111 1111 1112.")]
[InlineData("id 1234-5678-9018", "id ***")]
[InlineData("id 1234-5678-9010", "id 1234-5678-9010")]
[InlineData("Quote for taro@example.co.jp (090-1234-5678) - Mail", "Quote for *** (***) - Mail")]
[InlineData("+81 90 1234 5678", "***")]
[InlineData("03-1234-5678", "***")]
[InlineData("https://example.com/?password=abc&x=1", "https://example.com/?password=***&x=1")]
[InlineData("https://example.com/?access_token=abc#top", "https://example.com/?access_token=***")]
[InlineData("https://taro:pw@example.com/", "https://taro:***@example.com/")]
[InlineData("Authorization: Bearer abcdefgh", "Authorization: Bearer ***")]
public void MasksWhatLooksConfidential(string text, string expected) =>
Assert.Equal(expected, Masker().Apply(text));

[Theory]
[InlineData("https://example.com/a%20b?q=%E6%9D%B1%E4%BA%AC+x&n=10")]
[InlineData("C++ 100% の資料.pdf")]
[InlineData(@"C:\Users\taro\Downloads\report.xlsx")]
[InlineData("")]
public void LeavesTheRestAlone(string text) =>
Assert.Equal(text, Masker().Apply(text));

[Theory]
[InlineData("https://e.com/?m=taro%40example.com&x=1", "https://e.com/?m=***&x=1")]
[InlineData("https://e.com/?m=taro%2540example.com&x=1", "https://e.com/?m=***&x=1")]
[InlineData("https://e.com/?c=4111+1111+1111+1111&x=1", "https://e.com/?c=***&x=1")]
[InlineData("https://e.com/?t=+81%2090%201234%205678&x=1", "https://e.com/?t=***&x=1")]
[InlineData("https://e.com/?u=https%3A%2F%2Fa%2F%3Ftoken%3Dabc&x=1", "https://e.com/?u=***&x=1")]
// Only seen across two components, so there is no part to point at.
[InlineData("https://e.com/?pass%77ord=abc", "***")]
public void SeesThroughPercentEncoding(string text, string expected) =>
Assert.Equal(expected, Masker().Apply(text));

[Theory]
[InlineData("taro@example.com", "taro@example.com")]
[InlineData("EX-123456", "EX-123456")]
[InlineData("?token=abc", "?token=***")]
public void MasksOnlySecretsWhenLight(string text, string expected) =>
Assert.Equal(expected, Masker("light", Rule("EX-??????")).Apply(text));

[Theory]
[InlineData("Ligh")]
[InlineData("")]
[InlineData(null)]
public void ReadsAnUnknownLevelAsFull(string? level) =>
Assert.Equal("***", Masker(level!).Apply("taro@example.com"));

[Fact]
public void CanLeaveTheStandardRulesOut()
{
var masker = new NetLogMasker(new NetLogMaskingConfig { UseStandardRules = false });

Assert.Equal("taro@example.com", masker.Apply("taro@example.com"));
Assert.Equal("token=***", masker.Apply("token=abc"));
}

[Theory]
[InlineData("regex:EX-[0-9]{6}", "Part", "see ex-123456 now", "see *** now")]
[InlineData("EX-??", "Part", "see EX-12 now", "see *** now")]
[InlineData("a.b", "Part", "axb a.b", "axb ***")]
[InlineData("*社外秘*", "Whole", "資料(社外秘).pdf", "***")]
[InlineData("*社外秘*", "Whole", "https://e.com/%E7%A4%BE%E5%A4%96%E7%A7%98.pdf", "***")]
[InlineData("社外秘", "Whole", "資料(社外秘).pdf", "資料(社外秘).pdf")]
[InlineData("社外秘", "Part", "https://e.com/%E7%A4%BE%E5%A4%96%E7%A7%98.pdf?a=1", "https://e.com/***?a=1")]
[InlineData("regex:(?<=[?&](code|sig)=)[^&#]+", "Part", "https://e.com/?sig=a%2Bb&x=1", "https://e.com/?sig=***&x=1")]
[InlineData("", "Part", "plain", "plain")]
public void AppliesTheRulesOfTheOrganisation(
string pattern, string scope, string text, string expected) =>
Assert.Equal(expected, Masker("Full", Rule(pattern, scope)).Apply(text));

[Fact]
public void MasksEverythingWhenARuleIsBroken() =>
Assert.Equal("***", Masker("Full", Rule("regex:(")).Apply("plain"));

[Fact]
public void MasksEverythingWhenARuleTakesTooLong() =>
Assert.Equal("***", Masker("Full", Rule("regex:^(a+)+$")).Apply(new string('a', 60) + "!"));

[Fact]
public void CutsWhatIsTooLongToCheck()
{
var masked = Masker().Apply(new string('x', NetLogMasker.MaxLength) + "token=abc");

Assert.EndsWith("x***", masked);
Assert.True(masked.Length <= NetLogMasker.MaxLength);
}

// The standard rules must get through the longest text in time, or
// ordinary pages would come out masked as a whole.
[Theory]
[InlineData("x")]
[InlineData("1")]
[InlineData("%41")]
[InlineData("a%20+")]
[InlineData("a.")]
public void KeepsUpWithTheLongestText(string unit)
{
var text = "https://e.com/" + string.Concat(Enumerable.Repeat(unit, 8000 / unit.Length));

Assert.StartsWith("https://", Masker().Apply(text));
}

[Fact]
public void MasksEveryTextOfAnEntryButNotWhatIdentifiesIt()
{
var entry = """
{"operation":"browsing","timestamp":"2026-07-01 10:00:00","name":"taro@example.com",
"extra":{"list":["token=abc",1,null,true]},"broken":"\ud800"}
""";

Assert.Null(NetLogEntry.Compact(entry, out var line, Masker()));

var root = JsonDocument.Parse(line).RootElement;
Assert.Equal("browsing", root.GetProperty("operation").GetString());
Assert.Equal("2026-07-01 10:00:00", root.GetProperty("timestamp").GetString());
Assert.Equal("***", root.GetProperty("name").GetString());
Assert.Equal("""["token=***",1,null,true]""", root.GetProperty("extra").GetProperty("list").GetRawText());
Assert.Equal("***", root.GetProperty("broken").GetString());
Assert.Equal(NetLogIdentity.Account, root.GetProperty("user").GetString());
}

[Fact]
public void ReadsTheConfiguration()
{
var config = ConfigLoader.ParseConf("""
{"NetLogger":{"Masking":{"Level":"Light","UseStandardRules":false,
"Rules":[{"Pattern":"EX-*","Scope":"Whole"}]}}}
""").NetLogger.Masking;

Assert.Equal("Light", config.Level);
Assert.False(config.UseStandardRules);
Assert.Equal("EX-*", Assert.Single(config.Rules).Pattern);
Assert.Equal("Whole", config.Rules[0].Scope);
}

// Leaving the group out, or emptying it, must not turn it off.
[Theory]
[InlineData("{}")]
[InlineData("""{"NetLogger":{"Masking":null}}""")]
[InlineData("""{"NetLogger":{"Masking":{"Level":null,"Rules":null}}}""")]
[InlineData("""{"NetLogger":{"Masking":{"Rules":[null]}}}""")]
public void MasksUnlessToldOtherwise(string json)
{
var masker = new NetLogMasker(ConfigLoader.ParseConf(json).NetLogger.Masking);

Assert.Equal("***", masker.Apply("taro@example.com"));
}

// Both the copy on this machine and what waits for the collector: the
// endpoint answers nothing, so the entry ends up in the spool.
[Fact]
public void NothingUnmaskedReachesTheDisk()
{
var directory = Path.Combine(Path.GetTempPath(), "browserguard-masker-" + Guid.NewGuid().ToString("N"));
try
{
var config = new NetLoggerConfig
{
Enabled = true,
LocalFile = new() { Enabled = true, Directory = directory },
Sender = new()
{
Enabled = true,
Endpoint = "http://127.0.0.1:1/",
Spool = new() { Enabled = true },
},
};
using (var recorder = new NetLogRecorder(() => config))
{
Assert.Null(recorder.Record(
"""{"operation":"browsing","url":"https://e.com/?password=hunter2"}"""));
}

var written = Directory.GetFiles(directory).Select(File.ReadAllText).ToArray();
Assert.Equal(2, written.Length);
Assert.All(written, text => Assert.Contains("password=***", text));
Assert.All(written, text => Assert.DoesNotContain("hunter2", text));
}
finally
{
try { Directory.Delete(directory, true); } catch { }
}
}

[Fact]
public void MasksTheDiagnosticLogOfTheFileBridge()
{
var directory = Path.Combine(Path.GetTempPath(), "browserguard-masker-" + Guid.NewGuid().ToString("N"));
try
{
var logger = new Logger(directory);
FileBridge.Copy(
new UploadFileBridgeConfig
{
Enabled = true,
Destination = directory,
BlockedUrls = new[] { "example" },
},
@"C:\tmp\a.txt", "https://example.com/?token=hunter2", DateTime.Now,
logger, Masker().Apply);

var text = File.ReadAllText(Path.Combine(directory, "BrowserGuard.log"));
Assert.Contains("token=***", text);
Assert.DoesNotContain("hunter2", text);
}
finally
{
try { Directory.Delete(directory, true); } catch { }
}
}
}
}
5 changes: 5 additions & 0 deletions BrowserGuard/BrowserGuard.sample.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,11 @@
"Upload": false,
"Download": false,
"Print": false,
"Masking": {
"Level": "Full",
"UseStandardRules": true,
"Rules": []
},
"LocalFile": {
"Enabled": true,
"Directory": "%LOCALAPPDATA%\\Chronos\\BrowserGuard\\NetLog",
Expand Down
5 changes: 4 additions & 1 deletion BrowserGuard/Host/Handlers/UploadFileBridgeHandler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,8 +59,11 @@ internal UploadFileBridgeHandler(NetLogRecorder recorder, Logger? logger = null)
}

var now = DateTime.Now;
// The diagnostic log names the file and the URL too, so it is
// masked as the entries are.
var masker = new NetLogMasker(config.Value.NetLogger?.Masking, logger);
var failure = FileBridge.Copy(
config.Value.UploadFileBridge, upload.File, upload.Url, now, logger);
config.Value.UploadFileBridge, upload.File, upload.Url, now, logger, masker.Apply);
if (failure is not null)
{
RecordFailure(upload, failure, now);
Expand Down
61 changes: 59 additions & 2 deletions BrowserGuard/NetLogger/NetLogEntry.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ internal static string UploadFileBridgeFailed(

// null when the entry is usable, and `line` holds it. Otherwise the
// reason it cannot be used.
internal static string? Compact(string entry, out string line)
internal static string? Compact(
string entry, out string line, NetLogMasker? masker = null)
{
line = "";
try
Expand Down Expand Up @@ -85,7 +86,15 @@ internal static string UploadFileBridgeFailed(
{
continue;
}
property.WriteTo(writer);
if (masker is null ||
property.NameEquals("operation") ||
property.NameEquals("timestamp"))
{
property.WriteTo(writer);
continue;
}
writer.WritePropertyName(property.Name);
WriteMasked(writer, property.Value, masker);
}
writer.WriteString(HostProperty, NetLogIdentity.Host);
writer.WriteString(UserProperty, NetLogIdentity.Account);
Expand All @@ -105,5 +114,53 @@ internal static string UploadFileBridgeFailed(
return $"entry is not valid JSON: {ex.Message}";
}
}

// Every text is masked, however deep, so that a field added to the
// entries later is covered without having to be listed here.
private static void WriteMasked(
Utf8JsonWriter writer, JsonElement value, NetLogMasker masker)
{
switch (value.ValueKind)
{
case JsonValueKind.String:
writer.WriteStringValue(MaskText(value, masker));
break;
case JsonValueKind.Object:
writer.WriteStartObject();
foreach (var property in value.EnumerateObject())
{
writer.WritePropertyName(property.Name);
WriteMasked(writer, property.Value, masker);
}
writer.WriteEndObject();
break;
case JsonValueKind.Array:
writer.WriteStartArray();
foreach (var item in value.EnumerateArray())
{
WriteMasked(writer, item, masker);
}
writer.WriteEndArray();
break;
default:
value.WriteTo(writer);
break;
}
}

private static string MaskText(JsonElement value, NetLogMasker masker)
{
string text;
try
{
text = value.GetString() ?? "";
}
catch (InvalidOperationException)
{
// Half of a surrogate pair: it cannot be read, so not checked.
return NetLogMasker.Mask;
}
return masker.Apply(text);
}
}
}
Loading
Loading