fix(mtconnect): redact the Agent URI everywhere it is shown (R06:T-8)

The driver logged and surfaced the raw AgentUri (which may carry user:pass@) as
HostName (the /hosts key), in ~20 log lines and in exception messages that reach
DriverHealth.LastError, and the client's request-URI messages (timeouts, stream
end, not-a-stream, framing) embedded it too - while the Test-Connect probe
deliberately redacted it. New MTConnectUriRedaction (user-info, and for the
configured string its query, removed; a clean URI is unchanged so host keys do
not move); the driver computes its display form once per options document.

Refs #743

Claude-Session: https://claude.ai/code/session_01Ub9hGmYLQvn9XETzw7CMsT
This commit is contained in:
Joseph Doherty
2026-10-22 16:00:40 -04:00
parent d4b9fa1c29
commit d67634cc4f
7 changed files with 263 additions and 33 deletions
@@ -1002,7 +1002,7 @@ public sealed partial class MTConnectDriver
_logger.LogWarning(
ex,
"MTConnect driver {DriverInstanceId} could not write {Count} DataItem(s) ({DataItemIds}) on device '{DeviceName}' to {AgentUri}.",
_driverInstanceId, batch.Count, string.Join(", ", batch.Select(w => w.DataItemId)), device, options.AgentUri);
_driverInstanceId, batch.Count, string.Join(", ", batch.Select(w => w.DataItemId)), device, AgentDisplay(options));
foreach (var write in batch)
{
@@ -1029,7 +1029,7 @@ public sealed partial class MTConnectDriver
{
_logger.LogWarning(
"MTConnect driver {DriverInstanceId}: {AgentUri} refused the write of '{Value}' to DataItem '{DataItemId}' on device '{DeviceName}' — {AgentError}. Check the Agent's AllowPut / AllowPutFrom settings and that the DataItem exists.",
_driverInstanceId, options.AgentUri, batch[0].Text, batch[0].DataItemId, device, outcome.AgentError);
_driverInstanceId, AgentDisplay(options), batch[0].Text, batch[0].DataItemId, device, outcome.AgentError);
results[batch[0].Slot] = new WriteResult(BadCommunicationError);
return;
@@ -1370,7 +1370,7 @@ public sealed partial class MTConnectDriver
// downstream). Its data items are unreachable either way.
_logger.LogWarning(
"MTConnect driver {DriverInstanceId} skipped a device in {AgentUri}'s /probe model that declares neither a name nor an id; it cannot be given a browse path.",
_driverInstanceId, options.AgentUri);
_driverInstanceId, AgentDisplay(options));
continue;
}
@@ -1388,7 +1388,7 @@ public sealed partial class MTConnectDriver
{
_logger.LogWarning(
"MTConnect driver {DriverInstanceId} is scoped to device '{DeviceScope}', but {AgentUri}'s /probe model declares no device with that name or id ({DeclaredCount} declared). The browse is empty because the scope matched nothing, not because the Agent has nothing.",
_driverInstanceId, deviceScope, options.AgentUri, model.Devices.Count);
_driverInstanceId, deviceScope, AgentDisplay(options), model.Devices.Count);
return;
}
@@ -1398,7 +1398,7 @@ public sealed partial class MTConnectDriver
_driverInstanceId,
devices,
variables,
options.AgentUri,
AgentDisplay(options),
deviceScope is null or "" ? string.Empty : $" (scoped to '{deviceScope}')");
}
@@ -1568,7 +1568,33 @@ public sealed partial class MTConnectDriver
/// <c>host:port</c> convention: several MTConnect drivers in one server disambiguate on the
/// Admin dashboard by endpoint rather than by driver-instance id.
/// </summary>
public string HostName => Volatile.Read(ref _options).AgentUri;
public string HostName => AgentDisplay(Volatile.Read(ref _options));
/// <summary>
/// R06:T-8 — the redacted display form of <paramref name="options"/>' <c>AgentUri</c> (no <c>user:pass@</c>),
/// used for <see cref="HostName"/>, every log line and every message that can reach health text. Computed once
/// per options document and cached by reference.
/// </summary>
/// <param name="options">The options whose Agent is being named.</param>
/// <returns>The display form; identical to the configured value when it carries no credentials.</returns>
private string AgentDisplay(MTConnectDriverOptions options)
{
var cached = Volatile.Read(ref _agentDisplay);
if (cached is not null && ReferenceEquals(cached.Options, options))
{
return cached.Display;
}
var fresh = new AgentDisplayCache(options, MTConnectUriRedaction.Redact(options.AgentUri));
Volatile.Write(ref _agentDisplay, fresh);
return fresh.Display;
}
/// <summary>The last computed <see cref="AgentDisplay"/>, keyed by the options instance it was computed for.</summary>
private AgentDisplayCache? _agentDisplay;
private sealed record AgentDisplayCache(MTConnectDriverOptions Options, string Display);
/// <inheritdoc />
// One entry, always — an Agent is a single host, and the driver knows of it whether or not
@@ -1691,7 +1717,7 @@ public sealed partial class MTConnectDriver
_logger.LogDebug(
ex,
"MTConnect driver {DriverInstanceId} could not reach {AgentUri} on its connectivity probe.",
_driverInstanceId, options.AgentUri);
_driverInstanceId, AgentDisplay(options));
}
TransitionHostTo(reachable ? HostState.Running : HostState.Stopped);
@@ -1702,7 +1728,7 @@ public sealed partial class MTConnectDriver
_logger.LogError(
ex,
"MTConnect driver {DriverInstanceId} stopped its connectivity probe on an unexpected fault; host status for {AgentUri} will not be updated until the driver is re-initialized.",
_driverInstanceId, options.AgentUri);
_driverInstanceId, AgentDisplay(options));
}
}
@@ -1870,7 +1896,7 @@ public sealed partial class MTConnectDriver
_logger.LogInformation(
"MTConnect driver {DriverInstanceId} dropped its cached /probe device model for {AgentUri} and raised rediscovery: agent instanceId is now {InstanceId}.",
_driverInstanceId, options.AgentUri, instanceId);
_driverInstanceId, AgentDisplay(options), instanceId);
try
{
@@ -1993,7 +2019,7 @@ public sealed partial class MTConnectDriver
// that is not running; without this, the resubscribe returns a handle, the caller is
// told SubscriptionEstablished, and the next successful read reports a perfectly green
// driver over a subscription that can never deliver a value.
var agentUri = Volatile.Read(ref _options).AgentUri;
var agentUri = AgentDisplay(Volatile.Read(ref _options));
_streamDegraded = true;
Degrade($"The MTConnect Agent at '{agentUri}' does not serve a framed /sample stream; subscriptions cannot deliver until the driver is re-initialized.");
@@ -2167,7 +2193,7 @@ public sealed partial class MTConnectDriver
_logger.LogError(
outcome.Error,
"MTConnect driver {DriverInstanceId} cannot stream /sample from {AgentUri}: the endpoint did not answer with a framed multipart stream. Subscriptions stay registered but will receive no updates until the driver is re-initialized; check for a proxy or load balancer in front of the Agent.",
_driverInstanceId, options.AgentUri);
_driverInstanceId, AgentDisplay(options));
return;
@@ -2205,7 +2231,7 @@ public sealed partial class MTConnectDriver
_logger.LogWarning(
outcome.Error,
"MTConnect driver {DriverInstanceId} lost the /sample stream from {AgentUri}; reconnecting from sequence {Cursor} (attempt {Attempt}, delivered={Delivered}).",
_driverInstanceId, options.AgentUri, cursor, attempt, outcome.DeliveredAny);
_driverInstanceId, AgentDisplay(options), cursor, attempt, outcome.DeliveredAny);
break;
}
@@ -2296,7 +2322,7 @@ public sealed partial class MTConnectDriver
{
_logger.LogWarning(
"MTConnect driver {DriverInstanceId} saw {AgentUri} restart (instanceId {Previous} -> {Current}); dropping every held observation and re-baselining.",
_driverInstanceId, options.AgentUri, instanceId, chunk.InstanceId);
_driverInstanceId, AgentDisplay(options), instanceId, chunk.InstanceId);
// Dropped BEFORE the re-baseline, and the subscribers are told: if the /current
// then fails, holding stale values from a dead device model would be worse than
@@ -2318,7 +2344,7 @@ public sealed partial class MTConnectDriver
{
_logger.LogWarning(
"MTConnect driver {DriverInstanceId} fell out of {AgentUri}'s buffer (expected sequence {Expected}, oldest retained {FirstSequence}); re-baselining from /current.",
_driverInstanceId, options.AgentUri, expected, chunk.FirstSequence);
_driverInstanceId, AgentDisplay(options), expected, chunk.FirstSequence);
return await RebaselineAsync(client, options, expected, instanceId, delivered, generation, ct)
.ConfigureAwait(false);
@@ -2364,7 +2390,7 @@ public sealed partial class MTConnectDriver
instanceId,
delivered,
new MTConnectStreamEndedException(
MTConnectStreamEndReason.ConnectionClosed, options.AgentUri, 0));
MTConnectStreamEndReason.ConnectionClosed, AgentDisplay(options), 0));
}
catch (OperationCanceledException) when (ct.IsCancellationRequested)
{
@@ -2384,7 +2410,7 @@ public sealed partial class MTConnectDriver
_logger.LogWarning(
ex,
"MTConnect driver {DriverInstanceId} could not resume {AgentUri}'s /sample stream at sequence {Cursor} (the Agent rejected it as out of range); re-baselining from /current.",
_driverInstanceId, options.AgentUri, cursor);
_driverInstanceId, AgentDisplay(options), cursor);
return await RebaselineAsync(client, options, expected, instanceId, delivered, generation, ct)
.ConfigureAwait(false);
@@ -2440,7 +2466,7 @@ public sealed partial class MTConnectDriver
_logger.LogInformation(
"MTConnect driver {DriverInstanceId} re-baselined from {AgentUri}'s /current ({ObservationCount} observation(s), agent instanceId {InstanceId}) and resumes /sample from sequence {NextSequence}.",
_driverInstanceId,
options.AgentUri,
AgentDisplay(options),
current.Observations.Count,
current.InstanceId,
current.NextSequence);
@@ -3040,7 +3066,7 @@ public sealed partial class MTConnectDriver
_logger.LogInformation(
"MTConnect driver {DriverInstanceId} initialized against {AgentUri}{DeviceScope}: {DeviceCount} device(s), {ObservationCount} primed observation(s), agent instanceId {InstanceId}.",
_driverInstanceId,
options.AgentUri,
AgentDisplay(options),
options.DeviceName is null ? string.Empty : $"/{options.DeviceName}",
probe.Devices.Count,
index.Count,
@@ -3072,7 +3098,7 @@ public sealed partial class MTConnectDriver
_logger.LogError(
ex,
"MTConnect driver {DriverInstanceId} failed to initialize against {AgentUri}; the driver is Faulted and serves no values.",
_driverInstanceId, options.AgentUri);
_driverInstanceId, AgentDisplay(options));
throw;
}
@@ -3376,7 +3402,7 @@ public sealed partial class MTConnectDriver
{
// A bare "A task was canceled" names neither the Agent nor the request that stalled.
throw new TimeoutException(
$"MTConnect {request} request for driver '{_driverInstanceId}' against '{Volatile.Read(ref _options).AgentUri}' did not complete within {timeoutMs} ms.");
$"MTConnect {request} request for driver '{_driverInstanceId}' against '{AgentDisplay(Volatile.Read(ref _options))}' did not complete within {timeoutMs} ms.");
}
}
@@ -3413,7 +3439,7 @@ public sealed partial class MTConnectDriver
_logger.LogWarning(
ex,
"MTConnect driver {DriverInstanceId} could not read /current from {AgentUri}; the batch is reported Bad.",
_driverInstanceId, Volatile.Read(ref _options).AgentUri);
_driverInstanceId, AgentDisplay(Volatile.Read(ref _options)));
}
/// <summary>Publishes <see cref="DriverState.Degraded"/> without downgrading a Faulted driver.</summary>