Files
scadaproj/ZB.MOM.WW.Telemetry/tests/ZB.MOM.WW.Telemetry.Serilog.Tests/RedactionTests.cs
T

91 lines
2.8 KiB
C#

using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using Serilog.Sinks.InMemory;
using ZB.MOM.WW.Telemetry;
using ZB.MOM.WW.Telemetry.Serilog;
namespace ZB.MOM.WW.Telemetry.Serilog.Tests;
public sealed class RedactionTests
{
private const string Masked = "***";
private sealed class FakeRedactor : ILogRedactor
{
public void Redact(IDictionary<string, object?> properties)
{
if (properties.ContainsKey("apiKey"))
{
properties["apiKey"] = Masked;
}
}
}
private static string? ScalarOrNull(LogEvent logEvent, string propertyName) =>
logEvent.Properties.TryGetValue(propertyName, out var value) && value is ScalarValue scalar
? scalar.Value?.ToString()
: null;
[Fact]
public void Registered_redactor_masks_sensitive_property()
{
var serviceProvider = new ServiceCollection()
.AddSingleton<ILogRedactor>(new FakeRedactor())
.BuildServiceProvider();
var sink = new InMemorySink();
var options = new ZbTelemetryOptions { ServiceName = "mxgateway" };
var loggerConfig = new LoggerConfiguration();
ZbSerilogConfig.Apply(loggerConfig, options, serviceProvider);
using Logger logger = loggerConfig.WriteTo.Sink(sink).CreateLogger();
logger.Information("authenticating {apiKey}", "mxgw_secret");
var logEvent = Assert.Single(sink.LogEvents);
Assert.Equal(Masked, ScalarOrNull(logEvent, "apiKey"));
}
[Fact]
public void No_redactor_registered_is_a_no_op()
{
var serviceProvider = new ServiceCollection().BuildServiceProvider();
var sink = new InMemorySink();
var options = new ZbTelemetryOptions { ServiceName = "mxgateway" };
var loggerConfig = new LoggerConfiguration();
ZbSerilogConfig.Apply(loggerConfig, options, serviceProvider);
using Logger logger = loggerConfig.WriteTo.Sink(sink).CreateLogger();
logger.Information("authenticating {apiKey}", "mxgw_secret");
var logEvent = Assert.Single(sink.LogEvents);
Assert.Equal("mxgw_secret", ScalarOrNull(logEvent, "apiKey"));
}
[Fact]
public void AddZbSerilog_with_otlp_options_builds_without_error()
{
var builder = Host.CreateApplicationBuilder();
builder.AddZbSerilog(o =>
{
o.ServiceName = "mxgateway";
o.SiteId = "s1";
o.NodeRole = "central";
o.Exporter = ZbExporter.Otlp;
o.OtlpEndpoint = "http://localhost:4317";
});
using var host = builder.Build();
var logger = host.Services.GetRequiredService<ILogger>();
logger.Information("otlp wiring smoke test");
}
}