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;
///
/// Production : the API key's own Galaxy ack identity
/// (Secrets store, ) → the driver's fallback account
/// () → refused.
///
///
/// 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.
///
internal sealed class GalaxyAckCredentialResolver : IGalaxyAckCredentialResolver
{
private readonly string _driverInstanceId;
private readonly GalaxyAlarmAckOptions _options;
private readonly ISecretResolver _secrets;
private readonly ILogger _logger;
private readonly Func? _environment;
private readonly LegacyCredentialReferenceTracker? _legacy;
/// Initializes a new instance of the class.
/// The owning driver instance id (for messages).
/// The driver's ack-credential options.
/// The shared secret resolver.
/// Logger; never receives a secret.
/// Environment reader (tests); null ⇒ the process environment.
/// ⚠️ #815 warn-only compatibility tracker of the running driver (deprecated); null ⇒ hard-fail.
public GalaxyAckCredentialResolver(
string driverInstanceId, GalaxyAlarmAckOptions? options, ISecretResolver secrets, ILogger logger,
Func? 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));
}
///
public async Task 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 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 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.");
}
}
///
/// Resolves the fallback password reference through the shared lmxopcua#815 resolver: secret:galaxy/NAME
/// (or secret:otopcua/galaxy/NAME, ${secret:…}), env:OTOPCUA_GALAXY_NAME /
/// env:GALAXY_MXGW_NAME, or dev:VALUE; returns null when the referenced value is absent; throws
/// — before any store/environment read — for a bare literal, a
/// file: 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).
///
internal async Task 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;
}
///
/// ⚠️ 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.
///
private async Task 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);
}