using Microsoft.Extensions.Logging; using ZB.MOM.WW.MxGateway.Client; using ZB.MOM.WW.MxGateway.Contracts.Proto; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; /// /// Production backed by the session-less /// MxGatewayClient.AcknowledgeAlarmAsync RPC. The gateway routes acknowledgement /// through its always-on central alarm monitor, so no worker session is involved. /// /// /// /// Operator-authenticated ack (mxaccessgw 488649c+, lmxopcua#749). The gateway runs /// AuthenticateUser with operator_user/operator_domain/operator_password /// and writes the comment to <alarm>.AckMsg as that user, so the request always /// carries a real Galaxy account — never an empty operator_user, which the gateway rejects. /// /// /// The password never leaves the request. It is not logged, and every message this type /// builds from gateway output is scrubbed of it (the gateway contract already keeps it out of /// ProtocolStatus.Message; the scrub is defence in depth). The 0.3.0 client redacts it from /// its own MxGatewayExceptions. /// /// /// A non-OK means the gateway never reached MXAccess (transport / /// dispatch / validation failure) and is surfaced as a thrown exception. A non-zero native ack /// return code (hresult — now the AuthenticateUser HRESULT or the AckMsg write status) /// means MXAccess rejected the ack (a wrong password, an account without ack permission, a failed /// AckMsg write). It is logged and thrown as a /// (lmxopcua#760): the host then reverts the OPC UA condition to unacknowledged instead of leaving it /// claiming an ack Galaxy never recorded, and the operator can retry. A refusal, not a fault — the /// gateway answered — so it neither retries nor counts toward the resilience breaker (a mis-keyed /// account must not open the breaker for every correctly-configured caller). /// /// internal sealed class GatewayGalaxyAlarmAcknowledger : IGalaxyAlarmAcknowledger { /// Placeholder substituted for the password wherever gateway text is echoed. internal const string Redacted = "***"; private readonly MxGatewayClient _client; private readonly ILogger _logger; /// Initializes a new instance of the class. /// The MX gateway client used to send acknowledgments. /// A logger for diagnostic output. public GatewayGalaxyAlarmAcknowledger(MxGatewayClient client, ILogger logger) { _client = client ?? throw new ArgumentNullException(nameof(client)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); } /// public async Task AcknowledgeAsync( string alarmFullReference, string comment, GalaxyAckCredential credential, CancellationToken cancellationToken) { var request = BuildRequest(alarmFullReference, comment, credential); AcknowledgeAlarmReply reply; try { reply = await _client.AcknowledgeAlarmAsync(request, cancellationToken).ConfigureAwait(false); } catch (Exception ex) when (ex is not OperationCanceledException && credential.Password.Length > 0 && ContainsSecret(ex, credential.Password)) { // Defence in depth over the client's own redaction: never let an exception that echoes the // password escape into the actor's warning log. throw new InvalidOperationException( $"Galaxy AcknowledgeAlarm for '{alarmFullReference}' failed at the gateway ({ex.GetType().Name}); " + "details withheld because they echoed the operator credential."); } EvaluateReply(reply, alarmFullReference, credential, _logger); } /// Maps an acknowledge onto the gateway request. Pure — pinned by unit tests. /// The alarm reference. /// The ack comment. /// The Galaxy account to acknowledge as. /// The request. internal static AcknowledgeAlarmRequest BuildRequest( string alarmFullReference, string comment, GalaxyAckCredential credential) { ArgumentException.ThrowIfNullOrEmpty(alarmFullReference); ArgumentNullException.ThrowIfNull(credential); return new AcknowledgeAlarmRequest { ClientCorrelationId = Guid.NewGuid().ToString("N"), AlarmFullReference = alarmFullReference, Comment = comment ?? string.Empty, OperatorUser = credential.User, OperatorDomain = credential.Domain, OperatorPassword = credential.Password, }; } /// /// Applies the reply semantics: non-OK protocol status throws; a non-zero native code warns and throws a /// (lmxopcua#760). /// Every message is scrubbed of the password. /// /// The gateway reply. /// The alarm reference. /// The credential the request carried. /// The logger. internal static void EvaluateReply( AcknowledgeAlarmReply reply, string alarmFullReference, GalaxyAckCredential credential, ILogger logger) { // Protocol status — the gateway failed before MXAccess saw the ack. This is a // hard failure: the operator's request was not delivered at all. if (reply.ProtocolStatus is { } proto && proto.Code != ProtocolStatusCode.Ok) { throw new InvalidOperationException( $"Galaxy AcknowledgeAlarm for '{alarmFullReference}' as '{credential.DisplayName}' failed at the gateway: " + $"{proto.Code} {Scrub(proto.Message, credential.Password)}"); } // hresult is the authoritative native ack return code (0 = success) — the AuthenticateUser HRESULT // or the AckMsg write status. It is absent only on a worker protocol violation; with an OK protocol // status a missing value is treated as success. if (reply.HasHresult && reply.Hresult != 0) { logger.LogWarning( "Galaxy AcknowledgeAlarm for {AlarmRef} as {GalaxyUser} returned native ack failure code {Hresult}.", alarmFullReference, credential.DisplayName, reply.Hresult); throw new DriverOperationRefusedException( $"MXAccess rejected the Galaxy acknowledge of '{alarmFullReference}' as '{credential.DisplayName}' " + $"(native code 0x{reply.Hresult:X8}); check the account's password and Galaxy acknowledge permission."); } } /// Replaces every occurrence of in . /// Text that may echo the secret. /// The secret; empty means nothing to scrub. /// The scrubbed text. internal static string Scrub(string? text, string secret) => string.IsNullOrEmpty(text) || string.IsNullOrEmpty(secret) ? text ?? string.Empty : text.Replace(secret, Redacted, StringComparison.Ordinal); private static bool ContainsSecret(Exception ex, string secret) { for (var e = ex; e is not null; e = e.InnerException) { if (e.Message.Contains(secret, StringComparison.Ordinal)) return true; } return false; } }