Fix all baseline code-review findings across the six shared libraries

Resolves the 35 findings from the 2026-06-01 baseline (commit 26ba1c7),
test-first for every behavioral change. +51 tests (331 -> 382 passing, 0 failed).

- Telemetry-001 (HIGH): RedactionEnricher now honours property removal, so a
  redactor that drops a key actually scrubs the secret from the event.
- Auth: LDAP validator ValidateOnStart; API-key verify no longer fails on a
  best-effort MarkUsed write or a corrupt scopes column (fail-closed); LDAP cert
  validation hook; KeyPrefix persistence aligned; README algorithm corrected.
- Health: Akka checks return Degraded (not throw) when the cluster isn't up yet;
  GrpcDependencyHealthCheck catch-all; null 'description' rendered; composite
  endpoint builder; XML docs shipped.
- Audit: CompositeAuditWriter no longer re-throws OperationCanceledException;
  TruncatingAuditRedactor over-redact scrubs Target + safe negative max; options
  record; XML docs shipped.
- Configuration: TryAddEnumerable idempotent registration; consistent port
  quoting; strict invariant port parsing; XML docs + README packaged.
- Theme: mobile toggle is now CSS-only (no Bootstrap JS); token/CSS hygiene;
  XML docs on the public parameter surface.

Shared-contract/spec docs updated where the code was the source of truth
(observability service.instance.id, MapZbMetrics, redactor reach). All changes
additive/back-compatible at v0.1.0. code-reviews bookkeeping follows separately.
This commit is contained in:
Joseph Doherty
2026-06-01 11:22:14 -04:00
parent 26ba1c7215
commit 544a6ddb77
72 changed files with 1539 additions and 191 deletions
@@ -11,6 +11,20 @@ public interface ILogRedactor
/// <summary>
/// Inspects and mutates the supplied log-event <paramref name="properties"/> in place — remove
/// or replace any sensitive values. Called on every log event before it reaches any sink.
/// Both removing a key (the property is dropped from the event) and replacing its value are
/// honoured by <see cref="RedactionEnricher"/>.
/// <para>
/// <b>Reach — scalar top-level properties only.</b> Each entry's value is the unwrapped scalar
/// of a Serilog <c>ScalarValue</c> property (so simple string/number/etc. properties such as
/// <c>{apiKey}</c> can be read and masked directly). <b>Destructured / structured properties are
/// not unwrapped:</b> a <c>{@Object}</c> property arrives as the raw Serilog
/// <c>StructureValue</c> wrapper (and a sequence/dictionary as <c>SequenceValue</c>/
/// <c>DictionaryValue</c>). A redactor can therefore replace or remove the <i>whole</i>
/// top-level property, but it cannot reach a field <i>nested inside</i> a destructured object to
/// mask it selectively. To protect a sensitive field of a logged object, do not destructure it
/// (log the field as its own scalar property), or remove/replace the entire structured property
/// by key.
/// </para>
/// </summary>
/// <param name="properties">The mutable property dictionary for the current log event.</param>
void Redact(IDictionary<string, object?> properties);
@@ -30,8 +30,18 @@ public sealed class RedactionEnricher : ILogEventEnricher
}
/// <summary>
/// Hands the log event's scalar properties to the registered <see cref="ILogRedactor"/> and
/// writes back any values the redactor changed. No-op when no redactor is registered.
/// Hands the log event's properties to the registered <see cref="ILogRedactor"/> and reconciles
/// the result back onto the event: values the redactor changed are rewritten via
/// <c>AddOrUpdateProperty</c>, and keys the redactor removed are deleted via
/// <c>RemovePropertyIfPresent</c>. No-op when no redactor is registered or the event carries no
/// properties.
/// <para>
/// The redactor sees the unwrapped value of each <see cref="ScalarValue"/> property; structured
/// values (<see cref="StructureValue"/> from <c>{@Object}</c>, <see cref="SequenceValue"/>,
/// <see cref="DictionaryValue"/>) are passed through as their raw Serilog wrapper. A redactor can
/// therefore replace or remove a whole structured top-level property, but cannot reach a field
/// nested inside one — see <see cref="ILogRedactor"/> for the seam's documented reach.
/// </para>
/// </summary>
/// <param name="logEvent">The log event to redact.</param>
/// <param name="propertyFactory">Factory used to materialize replacement properties.</param>
@@ -46,6 +56,12 @@ public sealed class RedactionEnricher : ILogEventEnricher
return;
}
// Hot path: an event with no properties has nothing to redact — skip the snapshot copy.
if (logEvent.Properties.Count == 0)
{
return;
}
var snapshot = new Dictionary<string, object?>(logEvent.Properties.Count);
foreach (var property in logEvent.Properties)
{
@@ -54,6 +70,10 @@ public sealed class RedactionEnricher : ILogEventEnricher
: property.Value;
}
// Capture the original key set so we can honour deletions: any key the redactor drops from
// the snapshot must be removed from the event (not silently retained).
var originalKeys = new HashSet<string>(snapshot.Keys, StringComparer.Ordinal);
redactor.Redact(snapshot);
foreach (var entry in snapshot)
@@ -64,6 +84,16 @@ public sealed class RedactionEnricher : ILogEventEnricher
propertyFactory.CreateProperty(entry.Key, entry.Value));
}
}
// Reconcile removals: a redactor that deleted a key from the snapshot (e.g.
// properties.Remove("apiKey")) means that property must not reach any sink.
foreach (var key in originalKeys)
{
if (!snapshot.ContainsKey(key))
{
logEvent.RemovePropertyIfPresent(key);
}
}
}
private ILogRedactor? ResolveRedactor() => _redactor.Value;
@@ -115,38 +115,13 @@ internal static class ZbSerilogConfig
}
/// <summary>
/// Builds the OTLP Resource-attribute map mirroring <c>ZbResource</c>. Null/empty optional
/// attributes are omitted, matching the shared Resource's omission rules. The
/// <c>service.instance.id</c> is sourced from <see cref="ZbResource.InstanceId"/> — the
/// same deterministic <c>MachineName:ProcessId</c> value used by the OTel SDK path — so
/// all three signals carry an identical instance identifier. Internal so it can be asserted
/// by the test assembly without being part of the public NuGet API.
/// Builds the OTLP log-sink Resource-attribute map. This is <em>not</em> a parallel
/// implementation: it is derived directly from <see cref="ZbResource.BuildAttributes"/> — the
/// single source of truth shared with the OTel SDK metrics/traces pipeline — so the log sink can
/// never drift from metrics and traces. Returned as a fresh mutable copy because the
/// Serilog OpenTelemetry sink takes ownership of the dictionary it is handed. Internal so it can
/// be asserted by the test assembly without being part of the public NuGet API.
/// </summary>
internal static IDictionary<string, object> BuildResourceAttributes(ZbTelemetryOptions options)
{
var attributes = new Dictionary<string, object>
{
["service.name"] = options.ServiceName,
["service.namespace"] = options.ServiceNamespace,
["service.instance.id"] = ZbResource.InstanceId,
["host.name"] = Environment.MachineName,
};
if (!string.IsNullOrEmpty(options.ServiceVersion))
{
attributes["service.version"] = options.ServiceVersion;
}
if (!string.IsNullOrEmpty(options.SiteId))
{
attributes["site.id"] = options.SiteId;
}
if (!string.IsNullOrEmpty(options.NodeRole))
{
attributes["node.role"] = options.NodeRole;
}
return attributes;
}
internal static IDictionary<string, object> BuildResourceAttributes(ZbTelemetryOptions options) =>
new Dictionary<string, object>(ZbResource.BuildAttributes(options), StringComparer.Ordinal);
}
@@ -65,6 +65,10 @@ public static class ZbSerilogExtensions
var options = new ZbTelemetryOptions();
configure(options);
// Fail fast on a malformed OTLP endpoint with a clear, named message — same validation the
// core AddZbTelemetry path uses — instead of a late error when the OTel log sink builds.
ZbTelemetryOptionsValidator.Validate(options, nameof(configure));
// Register the application logger in DI only. preserveStaticLogger: true ensures
// AddSerilog does NOT freeze or replace Log.Logger — critical for multi-host
// processes (integration tests etc.) where AddZbSerilog may be called more than once.
@@ -20,6 +20,17 @@
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<!-- The Serilog companion package reuses the internal options validator (single fail-fast
path); its tests assert it too. -->
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>ZB.MOM.WW.Telemetry.Serilog</_Parameter1>
</AssemblyAttribute>
<AssemblyAttribute Include="System.Runtime.CompilerServices.InternalsVisibleTo">
<_Parameter1>ZB.MOM.WW.Telemetry.Serilog.Tests</_Parameter1>
</AssemblyAttribute>
</ItemGroup>
<ItemGroup>
<PackageReference Include="OpenTelemetry.Extensions.Hosting" />
<PackageReference Include="OpenTelemetry.Exporter.Prometheus.AspNetCore" />
@@ -9,8 +9,10 @@ namespace ZB.MOM.WW.Telemetry;
public static class ZbMetricsEndpointExtensions
{
/// <summary>
/// Mounts the Prometheus <c>/metrics</c> endpoint. Only valid when
/// <see cref="ZbTelemetryOptions.Exporter"/> = <see cref="ZbExporter.Prometheus"/>.
/// Mounts the Prometheus <c>/metrics</c> endpoint. Valid under <em>any</em>
/// <see cref="ZbTelemetryOptions.Exporter"/> value: the Prometheus exporter is always wired by
/// <c>AddZbTelemetry</c>, and OTLP (<see cref="ZbExporter.Otlp"/>) is only an additive overlay —
/// so <c>/metrics</c> serves scrape data even when <c>Exporter = ZbExporter.Otlp</c>.
/// Call after <c>app.UseRouting()</c>.
/// </summary>
/// <param name="endpoints">The endpoint route builder.</param>
@@ -31,34 +31,55 @@ public static class ZbResource
Configure(ResourceBuilder.CreateDefault(), options);
/// <summary>
/// Applies the shared ZB.MOM.WW Resource attributes to an existing <see cref="ResourceBuilder"/>.
/// Internal seam so the <c>AddZbTelemetry</c> pipeline produces a Resource identical to
/// <see cref="Build"/>.
/// The single source of truth for the shared ZB.MOM.WW Resource attribute set. Every consumer
/// of the Resource — the OTel SDK metrics/traces pipeline (<see cref="Configure"/>) and the
/// Serilog OTLP log sink — derives its attributes from this one map, so logs can never drift
/// from metrics/traces. Required attributes (<c>service.name</c>, <c>service.namespace</c>,
/// <c>service.instance.id</c>, <c>host.name</c>) are always present; optional ones
/// (<c>service.version</c>, <c>site.id</c>, <c>node.role</c>) are included only when the
/// corresponding option is non-null/non-empty, matching the Resource's omission rules.
/// </summary>
internal static ResourceBuilder Configure(ResourceBuilder builder, ZbTelemetryOptions options)
/// <param name="options">The telemetry options describing the service identity.</param>
/// <returns>The canonical attribute map carried by all three signals.</returns>
public static IReadOnlyDictionary<string, object> BuildAttributes(ZbTelemetryOptions options)
{
builder.AddService(
serviceName: options.ServiceName,
serviceNamespace: options.ServiceNamespace,
serviceVersion: options.ServiceVersion,
autoGenerateServiceInstanceId: false,
serviceInstanceId: InstanceId);
ArgumentNullException.ThrowIfNull(options);
var attributes = new List<KeyValuePair<string, object>>
var attributes = new Dictionary<string, object>(StringComparer.Ordinal)
{
new("host.name", System.Environment.MachineName),
["service.name"] = options.ServiceName,
["service.namespace"] = options.ServiceNamespace,
["service.instance.id"] = InstanceId,
["host.name"] = System.Environment.MachineName,
};
if (!string.IsNullOrEmpty(options.ServiceVersion))
{
attributes["service.version"] = options.ServiceVersion;
}
if (!string.IsNullOrEmpty(options.SiteId))
{
attributes.Add(new("site.id", options.SiteId));
attributes["site.id"] = options.SiteId;
}
if (!string.IsNullOrEmpty(options.NodeRole))
{
attributes.Add(new("node.role", options.NodeRole));
attributes["node.role"] = options.NodeRole;
}
return attributes;
}
/// <summary>
/// Applies the shared ZB.MOM.WW Resource attributes to an existing <see cref="ResourceBuilder"/>.
/// Internal seam so the <c>AddZbTelemetry</c> pipeline produces a Resource identical to
/// <see cref="Build"/>. Derives every attribute from <see cref="BuildAttributes"/> — the same
/// canonical map the Serilog OTLP log sink uses — so all three signals agree.
/// </summary>
internal static ResourceBuilder Configure(ResourceBuilder builder, ZbTelemetryOptions options)
{
var attributes = BuildAttributes(options);
builder.AddAttributes(attributes);
return builder;
}
@@ -101,6 +101,7 @@ public static class ZbTelemetryExtensions
"ZbTelemetryOptions.ServiceName is required (e.g. \"otopcua\").",
nameof(configure));
}
ZbTelemetryOptionsValidator.Validate(options, nameof(configure));
return options;
}
@@ -0,0 +1,44 @@
namespace ZB.MOM.WW.Telemetry;
/// <summary>
/// Eager, fail-fast validation of <see cref="ZbTelemetryOptions"/> shared by the core
/// <c>AddZbTelemetry</c> path and the Serilog <c>AddZbSerilog</c> path, so a malformed value is
/// reported once, clearly, and with the offending option named — rather than surfacing late as a
/// bare <see cref="UriFormatException"/> deep inside exporter construction at host-build time.
/// </summary>
internal static class ZbTelemetryOptionsValidator
{
/// <summary>
/// Validates the OTLP configuration. When <see cref="ZbTelemetryOptions.Exporter"/> is
/// <see cref="ZbExporter.Otlp"/>, <see cref="ZbTelemetryOptions.OtlpEndpoint"/> must be a
/// non-empty, well-formed absolute URI. Throws an <see cref="ArgumentException"/> (naming the
/// option) otherwise. No-op for the Prometheus exporter — a stray endpoint is ignored there.
/// </summary>
/// <param name="options">The populated telemetry options to validate.</param>
/// <param name="paramName">The originating parameter name for the thrown exception.</param>
public static void Validate(ZbTelemetryOptions options, string paramName)
{
ArgumentNullException.ThrowIfNull(options);
if (options.Exporter != ZbExporter.Otlp)
{
return;
}
if (string.IsNullOrWhiteSpace(options.OtlpEndpoint))
{
throw new ArgumentException(
"ZbTelemetryOptions.OtlpEndpoint is required when Exporter = ZbExporter.Otlp " +
"(e.g. \"http://collector:4317\").",
paramName);
}
if (!Uri.TryCreate(options.OtlpEndpoint, UriKind.Absolute, out _))
{
throw new ArgumentException(
$"ZbTelemetryOptions.OtlpEndpoint is not a well-formed absolute URI: " +
$"'{options.OtlpEndpoint}' (expected e.g. \"http://collector:4317\").",
paramName);
}
}
}