From 6584c8535a472eba847ed5e82051bfb91beaced7 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 24 Nov 2026 09:18:08 -0500 Subject: [PATCH] =?UTF-8?q?feat(grpc-data):=20A1=20=E2=80=94=20condition?= =?UTF-8?q?=5Fkey=20derivation=20(HKDF+HMAC)=20and=20DataConnections:Condi?= =?UTF-8?q?tionKeySecret=20validation?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../Configuration/DataConnectionOptions.cs | 8 ++ .../DataConnectionOptionsValidator.cs | 4 + .../DataConnectionRegistration.cs | 15 ++- .../DataConnections/ConditionKeys.cs | 116 ++++++++++++++++++ 4 files changed, 142 insertions(+), 1 deletion(-) create mode 100644 src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionKeys.cs diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs index ea8dd1a99..00458e0e2 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptions.cs @@ -27,4 +27,12 @@ public sealed class DataConnectionOptions public string? CredentialBundlePath { get; set; } public string? TrustBundlePath { get; set; } public TimeSpan BundleRefreshInterval { get; set; } = TimeSpan.FromSeconds(1); + /// + /// A1 (§5.2/§6): the per-origin-cluster secret the condition_key is derived from. Supply it as a + /// ${secret:…} reference or the DataConnections__ConditionKeySecret environment variable, identical on + /// both pair members — never a committed literal. Absent ⇒ the origin advertises no conditions capability (fail + /// closed, with a diagnostic); present but shorter than 32 bytes ⇒ a startup error. Rotating it changes every + /// imported condition's NodeId on the consumers (a planned operation). + /// + public string? ConditionKeySecret { get; set; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptionsValidator.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptionsValidator.cs index 9683dc89a..96ddb03cf 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptionsValidator.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionOptionsValidator.cs @@ -39,6 +39,10 @@ public sealed class DataConnectionOptionsValidator(IHostEnvironment environment) if (options.UnaryTimeout <= TimeSpan.Zero || options.UnaryTimeout > TimeSpan.FromMinutes(5) || options.StreamCommandTimeout <= TimeSpan.Zero || options.StreamCommandTimeout > TimeSpan.FromMinutes(1)) errors.Add("Unary and stream-command timeouts must be finite and within supported limits."); + // A1: an absent condition-key secret is NOT an error (the origin just never advertises conditions); a provisioned + // one that is too short, blank or still an unexpanded ${secret:} reference is. + if (ZB.MOM.WW.OtOpcUa.Runtime.DataConnections.ConditionKeys.SecretProblem(options.ConditionKeySecret) is { } secretProblem) + errors.Add(secretProblem); return errors; } } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs index 1a6b07330..ca680e696 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Host/Configuration/DataConnectionRegistration.cs @@ -46,6 +46,8 @@ public static class DataConnectionRegistration return new DataConnectionProcessIdentity(role.ClusterId, role.LocalNode.Value, Guid.NewGuid().ToString("N")); }); services.AddSingleton(sp => new CatalogActivation(sp.GetRequiredService())); + // A1: the condition-key deriver (validated above; absent secret ⇒ Unavailable, conditions never advertised). + services.AddSingleton(_ => ConditionKeys.FromSecret(options.ConditionKeySecret)); services.AddSingleton(sp => { var identity = sp.GetRequiredService(); @@ -58,7 +60,11 @@ public static class DataConnectionRegistration var state = CaptureReadRole(role, warm); var servingRole = settings.IsWarm && state.WarmRole != WarmRole.Active ? "Standby" : state.Role; return new(identity.NodeId, identity.Incarnation, servingRole, 0, 0, state.Generation); - }) { Logger = LoggerFor(sp) }; + }) + { + Logger = LoggerFor(sp), + ConditionKeys = ReportConditionKeys(sp.GetRequiredService(), LoggerFor(sp)) + }; }); services.AddSingleton(sp => new PartitionedSampleHub(options.Hub, sp.GetRequiredService())); services.AddSingleton(sp => new SourceSamplePublisher(sp.GetRequiredService(), @@ -261,6 +267,13 @@ public static class DataConnectionRegistration return options; } + /// A1 fail-closed diagnostic: an origin without a condition-key secret says so once, when its catalog starts. + private static ConditionKeys ReportConditionKeys(ConditionKeys keys, Microsoft.Extensions.Logging.ILogger logger) + { + if (!keys.IsAvailable) + Microsoft.Extensions.Logging.LoggerExtensions.LogInformation(logger, "{Reason}", keys.UnavailableReason); + return keys; + } private static Microsoft.Extensions.Logging.ILogger LoggerFor(IServiceProvider sp) => (Microsoft.Extensions.Logging.ILogger?)sp.GetService()?.CreateLogger() ?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance; diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionKeys.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionKeys.cs new file mode 100644 index 000000000..2ce9ca776 --- /dev/null +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/ConditionKeys.cs @@ -0,0 +1,116 @@ +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; + } +}