4563940792
User decision: save, Test Connect, live browse and the deploy gate keep refusing out-of-namespace credential references, but an ALREADY-DEPLOYED driver must not fault at the upgrade restart or (Galaxy) at the next gateway reconnect, since ReopenAsync re-resolves Gateway.ApiKeySecretRef. - LegacyCredentialReferenceTracker (Core.Abstractions): the one, deprecated, call-site-chosen compatibility path. Running Galaxy (InitializeAsync, ReopenAsync, ack fallback) and OpcUaClient (session open) pass it and keep the pre-#815 semantics (case-insensitive prefixes, Galaxy file:, OpcUaClient literal pass-through) with a rate-limited Warning (driver/field/allowed form, never the value) and a credential-compat:<field> diagnostics entry (both drivers now implement IDriverDiagnostics). Browsers and probes pass none and stay hard-fail; Heidenhain has none. - Deploy-gate message names the migration. - Upgrade preflight: CredentialReferencePreflightService (admin nodes, once after ApplicationStarted, ConfigDb only, resolves nothing) logs a Warning per Draft row / Deployed-artifact finding; the /raw banner shows them plus Running drivers reporting warn-only use (driver-health diagnostics). - docs/security.md: exact replacement table (incl. the old form default env:MX_API_KEY, file:, un-namespaced secret:, casing changes), the ReopenAsync reconnect behaviour, the warn-only window and its removal. Co-Authored-By: Claude <noreply@anthropic.com>
207 lines
11 KiB
C#
207 lines
11 KiB
C#
using Microsoft.Extensions.Logging;
|
|
using ZB.MOM.WW.OtOpcUa.Core.Abstractions;
|
|
using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config;
|
|
using ZB.MOM.WW.Secrets.Abstractions;
|
|
|
|
namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime;
|
|
|
|
/// <summary>
|
|
/// Production <see cref="IGalaxyAckCredentialResolver"/>: the API key's own Galaxy ack identity
|
|
/// (Secrets store, <see cref="GalaxyAckIdentitySecrets"/>) → the driver's fallback account
|
|
/// (<see cref="GalaxyAlarmAckOptions"/>) → refused.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// Resolves on every acknowledge rather than caching, so rotating a password or remapping a key takes
|
|
/// effect on the next ack; the Secrets resolver caches decrypted values itself. Nothing here logs a
|
|
/// password: log lines and refusal reasons name only users, key ids and secret NAMES.
|
|
/// </remarks>
|
|
internal sealed class GalaxyAckCredentialResolver : IGalaxyAckCredentialResolver
|
|
{
|
|
private readonly string _driverInstanceId;
|
|
private readonly GalaxyAlarmAckOptions _options;
|
|
private readonly ISecretResolver _secrets;
|
|
private readonly ILogger _logger;
|
|
private readonly Func<string, string?>? _environment;
|
|
private readonly LegacyCredentialReferenceTracker? _legacy;
|
|
|
|
/// <summary>Initializes a new instance of the <see cref="GalaxyAckCredentialResolver"/> class.</summary>
|
|
/// <param name="driverInstanceId">The owning driver instance id (for messages).</param>
|
|
/// <param name="options">The driver's ack-credential options.</param>
|
|
/// <param name="secrets">The shared secret resolver.</param>
|
|
/// <param name="logger">Logger; never receives a secret.</param>
|
|
/// <param name="environment">Environment reader (tests); null ⇒ the process environment.</param>
|
|
/// <param name="legacy">⚠️ #815 warn-only compatibility tracker of the running driver (deprecated); null ⇒ hard-fail.</param>
|
|
public GalaxyAckCredentialResolver(
|
|
string driverInstanceId, GalaxyAlarmAckOptions? options, ISecretResolver secrets, ILogger logger,
|
|
Func<string, string?>? environment = null, LegacyCredentialReferenceTracker? legacy = null)
|
|
{
|
|
_environment = environment;
|
|
_legacy = legacy;
|
|
_driverInstanceId = driverInstanceId;
|
|
_options = options ?? new GalaxyAlarmAckOptions();
|
|
_secrets = secrets ?? throw new ArgumentNullException(nameof(secrets));
|
|
_logger = logger ?? throw new ArgumentNullException(nameof(logger));
|
|
}
|
|
|
|
/// <inheritdoc />
|
|
public async Task<GalaxyAckCredentialResolution> ResolveAsync(string? apiKeyId, CancellationToken cancellationToken)
|
|
{
|
|
string? keyNote = null;
|
|
if (!string.IsNullOrWhiteSpace(apiKeyId))
|
|
{
|
|
var keyResult = await ResolveKeyIdentityAsync(apiKeyId, cancellationToken).ConfigureAwait(false);
|
|
if (keyResult.Credential is not null) return keyResult;
|
|
// A key whose identity is half-configured (user without password, unreadable secret) is
|
|
// refused outright — silently acknowledging as the fallback account would record the wrong
|
|
// operator for a key the administrator explicitly mapped.
|
|
if (keyResult.RefusalReason is not null) return keyResult;
|
|
keyNote = $"API key '{apiKeyId}' has no Galaxy ack identity";
|
|
}
|
|
|
|
if (_options.HasFallback)
|
|
{
|
|
return await ResolveFallbackAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
return GalaxyAckCredentialResolution.Refused(
|
|
$"{keyNote ?? "the session is anonymous (no API key)"} and Galaxy driver '{_driverInstanceId}' has no " +
|
|
"AlarmAck.FallbackUser configured; the acknowledge was not sent. Map a Galaxy ack identity to the key " +
|
|
"in AdminUI /api-keys or configure the driver's fallback ack account.");
|
|
}
|
|
|
|
// Returns Resolved, Refused (mapped but broken), or (null, null) = "no identity mapped".
|
|
private async Task<GalaxyAckCredentialResolution> ResolveKeyIdentityAsync(string apiKeyId, CancellationToken ct)
|
|
{
|
|
string userName, passwordName;
|
|
try
|
|
{
|
|
userName = GalaxyAckIdentitySecrets.UserSecretName(apiKeyId);
|
|
passwordName = GalaxyAckIdentitySecrets.PasswordSecretName(apiKeyId);
|
|
}
|
|
catch (ArgumentException)
|
|
{
|
|
return GalaxyAckCredentialResolution.Refused($"API key id '{apiKeyId}' is malformed; the acknowledge was not sent.");
|
|
}
|
|
|
|
string? identity;
|
|
string? password;
|
|
try
|
|
{
|
|
identity = await _secrets.GetAsync(new SecretName(userName), ct).ConfigureAwait(false);
|
|
if (string.IsNullOrWhiteSpace(identity)) return new GalaxyAckCredentialResolution(null, null);
|
|
password = await _secrets.GetAsync(new SecretName(passwordName), ct).ConfigureAwait(false);
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
// The exception type only — a secrets-layer message is not ours to vouch for.
|
|
_logger.LogWarning(
|
|
"Galaxy driver {DriverInstanceId}: reading the Galaxy ack identity of API key {ApiKeyId} failed ({ExceptionType})",
|
|
_driverInstanceId, apiKeyId, ex.GetType().Name);
|
|
return GalaxyAckCredentialResolution.Refused(
|
|
$"the Galaxy ack identity of API key '{apiKeyId}' could not be read from the Secrets store; the acknowledge was not sent.");
|
|
}
|
|
|
|
if (password is null)
|
|
{
|
|
return GalaxyAckCredentialResolution.Refused(
|
|
$"API key '{apiKeyId}' has a Galaxy ack user but no password secret '{passwordName}'; the acknowledge was not sent.");
|
|
}
|
|
|
|
var (user, domain) = GalaxyAckIdentitySecrets.ParseIdentity(identity);
|
|
if (user.Length == 0)
|
|
{
|
|
return GalaxyAckCredentialResolution.Refused(
|
|
$"API key '{apiKeyId}' has a malformed Galaxy ack user secret '{userName}'; the acknowledge was not sent.");
|
|
}
|
|
|
|
return GalaxyAckCredentialResolution.Resolved(
|
|
new GalaxyAckCredential(user, domain, password, GalaxyAckCredentialSource.ApiKey));
|
|
}
|
|
|
|
private async Task<GalaxyAckCredentialResolution> ResolveFallbackAsync(CancellationToken ct)
|
|
{
|
|
var reference = _options.FallbackPasswordSecretRef;
|
|
if (string.IsNullOrWhiteSpace(reference))
|
|
{
|
|
return GalaxyAckCredentialResolution.Refused(
|
|
$"Galaxy driver '{_driverInstanceId}' has AlarmAck.FallbackUser but no AlarmAck.FallbackPasswordSecretRef; the acknowledge was not sent.");
|
|
}
|
|
|
|
try
|
|
{
|
|
var password = await ResolvePasswordRefAsync(reference.Trim(), ct).ConfigureAwait(false);
|
|
if (password is null)
|
|
{
|
|
return GalaxyAckCredentialResolution.Refused(
|
|
$"Galaxy driver '{_driverInstanceId}' fallback ack password reference '{DescribeRef(reference)}' did not resolve; the acknowledge was not sent.");
|
|
}
|
|
|
|
return GalaxyAckCredentialResolution.Resolved(new GalaxyAckCredential(
|
|
_options.FallbackUser!, _options.FallbackDomain, password, GalaxyAckCredentialSource.Fallback));
|
|
}
|
|
catch (Exception ex) when (ex is not OperationCanceledException)
|
|
{
|
|
_logger.LogWarning(
|
|
"Galaxy driver {DriverInstanceId}: resolving the fallback ack password reference {Reference} failed ({ExceptionType})",
|
|
_driverInstanceId, DescribeRef(reference), ex.GetType().Name);
|
|
return GalaxyAckCredentialResolution.Refused(
|
|
$"Galaxy driver '{_driverInstanceId}' fallback ack password reference '{DescribeRef(reference)}' could not be resolved; the acknowledge was not sent.");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Resolves the fallback password reference through the shared lmxopcua#815 resolver: <c>secret:galaxy/NAME</c>
|
|
/// (or <c>secret:otopcua/galaxy/NAME</c>, <c>${secret:…}</c>), <c>env:OTOPCUA_GALAXY_NAME</c> /
|
|
/// <c>env:GALAXY_MXGW_NAME</c>, or <c>dev:VALUE</c>; returns null when the referenced value is absent; throws
|
|
/// <see cref="CredentialReferenceException"/> — before any store/environment read — for a bare literal, a
|
|
/// <c>file:</c> reference, or a reference outside the Galaxy namespace (the password is sent to the
|
|
/// operator-authored gateway endpoint, so it must never be able to name another subsystem's secret).
|
|
/// </summary>
|
|
internal async Task<string?> ResolvePasswordRefAsync(string reference, CancellationToken ct)
|
|
{
|
|
if (_legacy is not null
|
|
&& CredentialReferences.Parse(reference, DriverCredentialPolicy.GalaxyScope, out _) == CredentialReferenceKind.OutOfScope)
|
|
{
|
|
_legacy.Report("AlarmAck.FallbackPasswordSecretRef");
|
|
return await LegacyResolvePasswordRefAsync(reference, ct).ConfigureAwait(false);
|
|
}
|
|
|
|
var resolved = await CredentialReferences.ResolveOrNullAsync(
|
|
reference,
|
|
DriverCredentialPolicy.GalaxyScope,
|
|
"AlarmAck.FallbackPasswordSecretRef",
|
|
DriverCredentialPolicy.GalaxyAckPasswordField.Literals,
|
|
async (name, c) => await _secrets.GetAsync(new SecretName(name), c).ConfigureAwait(false),
|
|
_environment,
|
|
ct).ConfigureAwait(false);
|
|
return resolved is not null && reference.StartsWith(CredentialReferences.DevPrefix, StringComparison.OrdinalIgnoreCase)
|
|
? resolved[CredentialReferences.DevPrefix.Length..]
|
|
: resolved;
|
|
}
|
|
|
|
/// <summary>
|
|
/// ⚠️ DEPRECATED (lmxopcua#815 warn-only compatibility; delete in the hard-fail release): the pre-#815 resolver,
|
|
/// verbatim. Reached ONLY for an out-of-namespace reference in an already-deployed, running driver.
|
|
/// </summary>
|
|
private async Task<string?> LegacyResolvePasswordRefAsync(string reference, CancellationToken ct)
|
|
{
|
|
if (reference.StartsWith("${secret:", StringComparison.OrdinalIgnoreCase) && reference.EndsWith('}'))
|
|
reference = "secret:" + reference["${secret:".Length..^1];
|
|
if (reference.StartsWith("secret:", StringComparison.OrdinalIgnoreCase))
|
|
return await _secrets.GetAsync(new SecretName(reference["secret:".Length..]), ct).ConfigureAwait(false);
|
|
if (reference.StartsWith("env:", StringComparison.OrdinalIgnoreCase))
|
|
return (_environment ?? Environment.GetEnvironmentVariable)(reference[4..]);
|
|
if (reference.StartsWith("file:", StringComparison.OrdinalIgnoreCase))
|
|
{
|
|
var path = reference[5..];
|
|
return File.Exists(path) ? (await File.ReadAllTextAsync(path, ct).ConfigureAwait(false)).TrimEnd('\r', '\n') : null;
|
|
}
|
|
|
|
if (reference.StartsWith("dev:", StringComparison.OrdinalIgnoreCase)) return reference[4..];
|
|
throw new FormatException("AlarmAck.FallbackPasswordSecretRef must be a secret:/env:/dev: reference, not a literal.");
|
|
}
|
|
|
|
// Safe-to-print form of a reference: the kind + name for secret/env/file, never the dev: value or a literal.
|
|
internal static string DescribeRef(string reference) => CredentialReferences.Describe(reference);
|
|
}
|