feat(grpc-data): A1 — condition_key derivation (HKDF+HMAC) and DataConnections:ConditionKeySecret validation

This commit is contained in:
Joseph Doherty
2026-11-24 09:18:08 -05:00
parent 696f029349
commit 6584c8535a
4 changed files with 142 additions and 1 deletions
@@ -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);
/// <summary>
/// A1 (§5.2/§6): the per-origin-cluster secret the <c>condition_key</c> is derived from. Supply it as a
/// <c>${secret:…}</c> reference or the <c>DataConnections__ConditionKeySecret</c> 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).
/// </summary>
public string? ConditionKeySecret { get; set; }
}
@@ -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;
}
}
@@ -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<DataWriteDispatchFence>()));
// 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<DataConnectionProcessIdentity>();
@@ -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<LocalCatalogCoordinator>(sp) };
})
{
Logger = LoggerFor<LocalCatalogCoordinator>(sp),
ConditionKeys = ReportConditionKeys(sp.GetRequiredService<ConditionKeys>(), LoggerFor<LocalCatalogCoordinator>(sp))
};
});
services.AddSingleton(sp => new PartitionedSampleHub(options.Hub, sp.GetRequiredService<TimeProvider>()));
services.AddSingleton(sp => new SourceSamplePublisher(sp.GetRequiredService<PartitionedSampleHub>(),
@@ -261,6 +267,13 @@ public static class DataConnectionRegistration
return options;
}
/// <summary>A1 fail-closed diagnostic: an origin without a condition-key secret says so once, when its catalog starts.</summary>
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<T>(IServiceProvider sp) =>
(Microsoft.Extensions.Logging.ILogger?)sp.GetService<Microsoft.Extensions.Logging.ILoggerFactory>()?.CreateLogger<T>()
?? Microsoft.Extensions.Logging.Abstractions.NullLogger.Instance;
@@ -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;
/// <summary>
/// A1 (§5.2 "Dedupe key", N3, m-T6): mints the opaque <c>condition_key</c> an origin puts on every condition record.
/// <para>
/// <c>condition_key = base64url(HMAC-SHA256(K, upper(originClusterId) ‖ 0x00 ‖ realm ‖ ConditionId))</c>, with
/// <c>K = HKDF-SHA256(DataConnections:ConditionKeySecret, info = "otopcua/condition-key/v1")</c>. 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.
/// </para>
/// <para>
/// 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 <c>${secret:}</c>), 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 <c>Metadata.stable_source_id</c>, #916).
/// </para>
/// <para>
/// Without a secret the origin advertises no <c>conditions</c> capability (fail closed): <see cref="IsAvailable"/>
/// is false and <see cref="UnavailableReason"/> is the diagnostic. A present but unusable secret is a configuration
/// error (<see cref="SecretProblem"/>, enforced by the host's DataConnections options validator).
/// </para>
/// </summary>
public sealed class ConditionKeys
{
/// <summary>The configuration key, for diagnostics.</summary>
public const string ConfigurationKey = "DataConnections:ConditionKeySecret";
/// <summary>Minimum secret length in UTF-8 bytes (256 bits of input keying material).</summary>
public const int MinimumSecretBytes = 32;
/// <summary>HKDF <c>info</c>: versions the derivation, so a future scheme cannot collide with this one.</summary>
public const string DerivationInfo = "otopcua/condition-key/v1";
/// <summary>The fail-closed diagnostic when no secret is provisioned.</summary>
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;
}
/// <summary>An instance that never derives (no secret).</summary>
public static ConditionKeys Unavailable { get; } = new(null, NotProvisionedReason);
/// <summary>Whether a secret is provisioned and keys can be derived.</summary>
public bool IsAvailable => _key is not null;
/// <summary>Why <see cref="IsAvailable"/> is false; null when available.</summary>
public string? UnavailableReason { get; }
/// <summary>True when a secret value is configured at all (null/empty means "not provisioned", never an error).</summary>
public static bool IsProvisioned(string? secret) => !string.IsNullOrEmpty(secret);
/// <summary>
/// The configuration error for a PROVISIONED but unusable secret, or null (absent or valid). Never echoes the value.
/// </summary>
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;
}
/// <summary>
/// Builds the deriver from the configured secret: <see cref="Unavailable"/> when absent; throws
/// <see cref="ArgumentException"/> (without the value) when provisioned but unusable.
/// </summary>
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); }
}
/// <summary>The key for one origin condition; throws when <see cref="IsAvailable"/> is false.</summary>
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;
}
}