using System.Security.Cryptography; using System.Text; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; /// /// A1 (§5.2 "Dedupe key", N3, m-T6): mints the opaque condition_key an origin puts on every condition record. /// /// condition_key = base64url(HMAC-SHA256(K, upper(originClusterId) ‖ 0x00 ‖ realm ‖ ConditionId)), with /// K = HKDF-SHA256(DataConnections:ConditionKeySecret, info = "otopcua/condition-key/v1"). The realm byte /// (1 = Raw, 2 = Uns — the node manager's condition realm key) is an A1 addition to the plan's formula: a native /// ConditionId is a RawPath and a scripted one a ScriptedAlarmId, and nothing stops the two spaces from sharing a /// string, so the realm keeps two distinct conditions from sharing a key. /// /// /// The key depends only on the secret, the origin cluster and the condition: it is stable across restarts, /// failover and re-deploys, identical on both pair members (the secret is a per-cluster ${secret:}), and /// equal across every listing and principal (m-T6), so a consumer dedupes a condition's Raw and UNS placements. /// Being keyed, it cannot be dictionary-reversed from guessable RawPaths, and it carries no RawPath or driver id /// (unlike Metadata.stable_source_id, #916). /// /// /// Without a secret the origin advertises no conditions capability (fail closed): /// is false and is the diagnostic. A present but unusable secret is a configuration /// error (, enforced by the host's DataConnections options validator). /// /// public sealed class ConditionKeys { /// The configuration key, for diagnostics. public const string ConfigurationKey = "DataConnections:ConditionKeySecret"; /// Minimum secret length in UTF-8 bytes (256 bits of input keying material). public const int MinimumSecretBytes = 32; /// HKDF info: versions the derivation, so a future scheme cannot collide with this one. public const string DerivationInfo = "otopcua/condition-key/v1"; /// The fail-closed diagnostic when no secret is provisioned. public const string NotProvisionedReason = ConfigurationKey + " is not provisioned; this origin does not advertise the conditions capability."; private readonly byte[]? _key; private ConditionKeys(byte[]? key, string? unavailableReason) { _key = key; UnavailableReason = unavailableReason; } /// An instance that never derives (no secret). public static ConditionKeys Unavailable { get; } = new(null, NotProvisionedReason); /// Whether a secret is provisioned and keys can be derived. public bool IsAvailable => _key is not null; /// Why is false; null when available. public string? UnavailableReason { get; } /// True when a secret value is configured at all (null/empty means "not provisioned", never an error). public static bool IsProvisioned(string? secret) => !string.IsNullOrEmpty(secret); /// /// The configuration error for a PROVISIONED but unusable secret, or null (absent or valid). Never echoes the value. /// public static string? SecretProblem(string? secret) { if (!IsProvisioned(secret)) return null; if (secret!.Contains("${secret:", StringComparison.OrdinalIgnoreCase)) return ConfigurationKey + " still holds an unexpanded ${secret:} reference."; if (string.IsNullOrWhiteSpace(secret) || secret.Any(char.IsControl)) return ConfigurationKey + " must not be blank or contain control characters."; if (Encoding.UTF8.GetByteCount(secret) < MinimumSecretBytes) return $"{ConfigurationKey} must be at least {MinimumSecretBytes} bytes; generate a random per-cluster secret."; return null; } /// /// Builds the deriver from the configured secret: when absent; throws /// (without the value) when provisioned but unusable. /// public static ConditionKeys FromSecret(string? secret) { if (!IsProvisioned(secret)) return Unavailable; if (SecretProblem(secret) is { } problem) throw new ArgumentException(problem, nameof(secret)); var material = Encoding.UTF8.GetBytes(secret!); try { return new(HKDF.DeriveKey(HashAlgorithmName.SHA256, material, 32, salt: [], info: Encoding.UTF8.GetBytes(DerivationInfo)), null); } finally { CryptographicOperations.ZeroMemory(material); } } /// The key for one origin condition; throws when is false. public string Derive(string originClusterId, AddressSpaceRealm realm, string conditionId) { if (_key is null) throw new InvalidOperationException(UnavailableReason); ArgumentException.ThrowIfNullOrWhiteSpace(originClusterId); ArgumentException.ThrowIfNullOrEmpty(conditionId); if (originClusterId.Contains('\0')) throw new ArgumentException("Cluster ids cannot contain NUL.", nameof(originClusterId)); if (realm is not (AddressSpaceRealm.Raw or AddressSpaceRealm.Uns)) throw new ArgumentOutOfRangeException(nameof(realm)); var cluster = Encoding.UTF8.GetBytes(originClusterId.ToUpperInvariant()); var condition = Encoding.UTF8.GetBytes(conditionId); var message = new byte[cluster.Length + 2 + condition.Length]; cluster.CopyTo(message, 0); message[cluster.Length] = 0; message[cluster.Length + 1] = realm == AddressSpaceRealm.Raw ? (byte)1 : (byte)2; condition.CopyTo(message, cluster.Length + 2); var key = Convert.ToBase64String(HMACSHA256.HashData(_key, message)).TrimEnd('=').Replace('+', '-').Replace('/', '_'); System.Diagnostics.Debug.Assert(ImportedConditionIds.IsWellFormedConditionKey(key)); return key; } }