using System.Text.RegularExpressions; using ZB.MOM.WW.OtOpcUa.Commons.OpcUa; using ZB.MOM.WW.OtOpcUa.Commons.Types; using ZB.MOM.WW.OtOpcUa.Configuration.Entities; using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; namespace ZB.MOM.WW.OtOpcUa.Configuration.Validation; /// Validates deployed data-service configuration without resolving consumer-side secrets. public static class DataConnectionValidator { private const DataOperations KnownOperations = DataOperations.Browse | DataOperations.Metadata | DataOperations.Read | DataOperations.Write | DataOperations.Subscribe; private static readonly StringComparer Ids = StringComparer.OrdinalIgnoreCase; public static IReadOnlyList Validate(DraftSnapshot draft) { ArgumentNullException.ThrowIfNull(draft); var errors = new List(); void Add(string code, string id, string message) => errors.Add(new(code, message, id)); bool Same(string? a, string? b) => Ids.Equals(a, b); bool ValidOps(DataOperations operations) => operations != DataOperations.None && (operations & ~KnownOperations) == 0; bool NodesValid(IEnumerable ids, string owner) { var list = ids.ToList(); return list.Count > 0 && list.All(x => !string.IsNullOrWhiteSpace(x)) && list.Distinct(Ids).Count() == list.Count && list.All(id => draft.ClusterNodes.Any(n => Same(n.NodeId, id) && Same(n.ClusterId, owner) && n.Enabled)); } bool ValidSegment(string? value, DataRealm realm) => realm == DataRealm.Uns ? UnsSegment.IsValid(value) : value is not null && value.Length <= 128 && RawPaths.ValidateSegment(value) is null; bool ValidEndpoint(string endpoint) => Uri.TryCreate(endpoint, UriKind.Absolute, out var uri) && uri.Scheme == Uri.UriSchemeHttps && string.IsNullOrEmpty(uri.UserInfo) && string.IsNullOrEmpty(uri.Query) && string.IsNullOrEmpty(uri.Fragment); bool ValidSecretReference(string? reference) => reference is not null && Regex.IsMatch(reference, @"\Asecret:data/[A-Za-z0-9][A-Za-z0-9._/-]*\z", RegexOptions.CultureInvariant) && !reference.Contains("..", StringComparison.Ordinal); void DuplicateIds(IEnumerable ids, string kind) { foreach (var duplicate in ids.Where(id => !string.IsNullOrWhiteSpace(id)) .GroupBy(id => id, Ids).Where(group => group.Count() > 1)) { Add("DataLogicalIdDuplicate", duplicate.Key, $"Duplicate {kind} logical ID."); } } DuplicateIds(draft.DataConnections.Select(x => x.DataConnectionId), "connection"); DuplicateIds(draft.DataExports.Select(x => x.DataExportId), "export"); DuplicateIds(draft.RemoteNamespaceMappings.Select(x => x.RemoteNamespaceMappingId), "mapping"); foreach (var connection in draft.DataConnections) { var id = connection.DataConnectionId; if ((connection.Enabled && connection.Endpoints.Count == 0) || connection.Endpoints.Any(endpoint => !string.IsNullOrWhiteSpace(endpoint) ? !ValidEndpoint(endpoint) : connection.Enabled)) { Add("DataConnectionEndpointInvalid", id, "Endpoints must be absolute HTTPS URIs without credentials, query or fragment."); } if ((connection.Enabled || !string.IsNullOrWhiteSpace(connection.SecretReference)) && (!ValidSecretReference(connection.SecretReference) || ((connection.Enabled || !string.IsNullOrWhiteSpace(connection.SecretScopeClusterId)) && !Same(connection.SecretScopeClusterId, connection.ClusterId)))) { Add("DataConnectionSecretReferenceInvalid", id, "A cluster-scoped data secret reference is required."); } } foreach (var connection in draft.DataConnections.Where(x => x.Enabled)) { var id = connection.DataConnectionId; if (string.IsNullOrWhiteSpace(id) || string.IsNullOrWhiteSpace(connection.ClusterId) || connection.Revision <= 0 || string.IsNullOrWhiteSpace(connection.ExpectedClusterId) || !Enum.IsDefined(connection.TargetMode) || connection.TargetMode == DataTargetMode.Unspecified || !Enum.IsDefined(connection.Consistency) || connection.Consistency == DataConsistency.Unspecified) Add("DataConnectionIdentityInvalid", id, "Connection identity, target mode and consistency are required."); if (!NodesValid(connection.ConsumerNodeIds, connection.ClusterId)) Add("DataConnectionConsumerScopeInvalid", id, "Consumers must be distinct enabled nodes owned by the connection cluster."); if (connection.TargetMode == DataTargetMode.Node) { if (string.IsNullOrWhiteSpace(connection.ExpectedNodeId) || connection.EligibleTargetNodeIds.Count != 0) Add("DataConnectionTargetInvalid", id, "Node targets require one expected node and no cluster target set."); if (Same(connection.ClusterId, connection.ExpectedClusterId) && connection.ConsumerNodeIds.Any(n => Same(n, connection.ExpectedNodeId))) Add("DataConnectionSelfRoute", id, "A consumer cannot target itself."); if (Same(connection.ClusterId, connection.ExpectedClusterId) && !draft.ClusterNodes.Any(n => Same(n.ClusterId, connection.ClusterId) && Same(n.NodeId, connection.ExpectedNodeId))) Add("DataConnectionTargetInvalid", id, "Same-cluster target node must exist in the declared cluster."); } else if (connection.TargetMode == DataTargetMode.Cluster) { if (connection.ExpectedNodeId is not null || connection.EligibleTargetNodeIds.Count == 0 || connection.EligibleTargetNodeIds.Any(string.IsNullOrWhiteSpace) || connection.EligibleTargetNodeIds.Distinct(Ids).Count() != connection.EligibleTargetNodeIds.Count) Add("DataConnectionTargetInvalid", id, "Cluster targets require a distinct nonempty eligible node set."); if (Same(connection.ClusterId, connection.ExpectedClusterId) && connection.ConsumerNodeIds.Any(consumer => !connection.EligibleTargetNodeIds.Any(target => !Same(target, consumer)))) Add("DataConnectionSelfRoute", id, "Each consumer requires an eligible nonself target."); if (Same(connection.ClusterId, connection.ExpectedClusterId) && connection.EligibleTargetNodeIds.Any(target => !draft.ClusterNodes.Any(n => Same(n.ClusterId, connection.ClusterId) && Same(n.NodeId, target) && n.Enabled && !n.MaintenanceMode))) Add("DataConnectionTargetInvalid", id, "Same-cluster eligible targets must be enabled and out of maintenance."); } if (!ValidOps(connection.AllowedOperations)) Add("DataConnectionOperationsInvalid", id, "Connection operations must be a supported nonempty subset."); if (connection.TimeoutMilliseconds <= 0 || connection.MaxBatchItems <= 0 || connection.MaxPageItems <= 0 || connection.MaxMessageBytes <= 0 || connection.MaxStreams <= 0 || connection.MaxMonitoredItems <= 0 || connection.MaxPendingBytes <= 0) Add("DataConnectionLimitInvalid", id, "Connection limits must be positive."); } // Resolve local entity ownership through existing trees. Projected mappings are never valid parents or exports. string? Owner(string kind, string entityId) => kind switch { "Cluster" => draft.ServerClusters.FirstOrDefault(x => Same(x.ClusterId, entityId))?.ClusterId, "RawFolder" => draft.RawFolders.FirstOrDefault(x => Same(x.RawFolderId, entityId))?.ClusterId, "RawDriver" => draft.DriverInstances.FirstOrDefault(x => Same(x.DriverInstanceId, entityId))?.ClusterId, "RawDevice" => DeviceOwner(entityId), "RawTagGroup" => draft.TagGroups.FirstOrDefault(x => Same(x.TagGroupId, entityId)) is { } group ? DeviceOwner(group.DeviceId) : null, "RawTag" => draft.Tags.FirstOrDefault(x => Same(x.TagId, entityId)) is { } tag ? DeviceOwner(tag.DeviceId) : null, "UnsArea" => draft.UnsAreas.FirstOrDefault(x => Same(x.UnsAreaId, entityId))?.ClusterId, "UnsLine" => LineOwner(entityId), "Equipment" => draft.Equipment.FirstOrDefault(x => Same(x.EquipmentId, entityId)) is { } equipment ? LineOwner(equipment.UnsLineId) : null, "UnsTagReference" => draft.UnsTagReferences.FirstOrDefault(x => Same(x.UnsTagReferenceId, entityId)) is { } reference ? EquipmentOwner(reference.EquipmentId) : null, "VirtualTag" => draft.VirtualTags.FirstOrDefault(x => Same(x.VirtualTagId, entityId)) is { } virtualTag ? EquipmentOwner(virtualTag.EquipmentId) : null, _ => null }; string? DeviceOwner(string deviceId) { var device = draft.Devices.FirstOrDefault(x => Same(x.DeviceId, deviceId)); return device is null ? null : draft.DriverInstances.FirstOrDefault(x => Same(x.DriverInstanceId, device.DriverInstanceId))?.ClusterId; } string? EquipmentOwner(string equipmentId) { var equipment = draft.Equipment.FirstOrDefault(x => Same(x.EquipmentId, equipmentId)); return equipment is null ? null : LineOwner(equipment.UnsLineId); } string? LineOwner(string lineId) { var line = draft.UnsLines.FirstOrDefault(x => Same(x.UnsLineId, lineId)); return line is null ? null : draft.UnsAreas.FirstOrDefault(x => Same(x.UnsAreaId, line.UnsAreaId))?.ClusterId; } bool KindInRealm(string kind, DataRealm realm) => kind == "Cluster" || (realm switch { DataRealm.Raw => kind is "RawFolder" or "RawDriver" or "RawDevice" or "RawTagGroup" or "RawTag", DataRealm.Uns => kind is "UnsArea" or "UnsLine" or "Equipment" or "UnsTagReference" or "VirtualTag", _ => false }); bool LocalCollision(RemoteNamespaceMapping m) { var name = m.BranchName; bool Name(string? candidate) => string.Equals(candidate, name, StringComparison.Ordinal); return m.LocalParentKind switch { "Cluster" when m.Realm == DataRealm.Raw => draft.RawFolders.Any(x => Same(x.ClusterId, m.ClusterId) && x.ParentRawFolderId is null && Name(x.Name)) || draft.DriverInstances.Any(x => Same(x.ClusterId, m.ClusterId) && x.RawFolderId is null && Name(x.Name)), "Cluster" => draft.UnsAreas.Any(x => Same(x.ClusterId, m.ClusterId) && Name(x.Name)), "RawFolder" => draft.RawFolders.Any(x => Same(x.ParentRawFolderId, m.LocalParentId) && Name(x.Name)) || draft.DriverInstances.Any(x => Same(x.RawFolderId, m.LocalParentId) && Name(x.Name)), "RawDriver" => draft.Devices.Any(x => Same(x.DriverInstanceId, m.LocalParentId) && Name(x.Name)), "RawDevice" => draft.TagGroups.Any(x => Same(x.DeviceId, m.LocalParentId) && x.ParentTagGroupId is null && Name(x.Name)) || draft.Tags.Any(x => Same(x.DeviceId, m.LocalParentId) && x.TagGroupId is null && Name(x.Name)), "RawTagGroup" => draft.TagGroups.Any(x => Same(x.ParentTagGroupId, m.LocalParentId) && Name(x.Name)) || draft.Tags.Any(x => Same(x.TagGroupId, m.LocalParentId) && Name(x.Name)), "UnsArea" => draft.UnsLines.Any(x => Same(x.UnsAreaId, m.LocalParentId) && Name(x.Name)), "UnsLine" => draft.Equipment.Any(x => Same(x.UnsLineId, m.LocalParentId) && Name(x.Name)), "Equipment" => draft.VirtualTags.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.ScriptedAlarms.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.Name)) || draft.UnsTagReferences.Any(x => Same(x.EquipmentId, m.LocalParentId) && Name(x.DisplayNameOverride ?? draft.Tags.FirstOrDefault(t => Same(t.TagId, x.TagId))?.Name)), _ => false }; } bool RootIsAncestor(RemoteNamespaceMapping mapping) { var kind = mapping.LocalParentKind; var current = mapping.LocalParentId; var seen = new HashSet(Ids); while (!string.IsNullOrEmpty(current) && seen.Add(kind + ":" + current)) { if (Same(current, mapping.RemoteRootEntityId)) return true; switch (kind) { case "RawFolder": var folder = draft.RawFolders.FirstOrDefault(x => Same(x.RawFolderId, current)); if (folder is null) return false; current = folder.ParentRawFolderId ?? folder.ClusterId; kind = folder.ParentRawFolderId is null ? "Cluster" : "RawFolder"; break; case "RawDriver": var driver = draft.DriverInstances.FirstOrDefault(x => Same(x.DriverInstanceId, current)); if (driver is null) return false; current = driver.RawFolderId ?? driver.ClusterId; kind = driver.RawFolderId is null ? "Cluster" : "RawFolder"; break; case "RawDevice": current = draft.Devices.FirstOrDefault(x => Same(x.DeviceId, current))?.DriverInstanceId ?? ""; kind = "RawDriver"; break; case "RawTagGroup": var group = draft.TagGroups.FirstOrDefault(x => Same(x.TagGroupId, current)); if (group is null) return false; current = group.ParentTagGroupId ?? group.DeviceId; kind = group.ParentTagGroupId is null ? "RawDevice" : "RawTagGroup"; break; case "Equipment": current = draft.Equipment.FirstOrDefault(x => Same(x.EquipmentId, current))?.UnsLineId ?? ""; kind = "UnsLine"; break; case "UnsLine": current = draft.UnsLines.FirstOrDefault(x => Same(x.UnsLineId, current))?.UnsAreaId ?? ""; kind = "UnsArea"; break; case "UnsArea": current = draft.UnsAreas.FirstOrDefault(x => Same(x.UnsAreaId, current))?.ClusterId ?? ""; kind = "Cluster"; break; default: return false; } } return false; } foreach (var mapping in draft.RemoteNamespaceMappings.Where(x => x.Enabled)) { var id = mapping.RemoteNamespaceMappingId; var connection = draft.DataConnections.FirstOrDefault(x => Same(x.DataConnectionId, mapping.DataConnectionId)); if (string.IsNullOrWhiteSpace(id) || mapping.Revision <= 0 || connection is null || !connection.Enabled || !Same(connection.ClusterId, mapping.ClusterId)) Add("DataMappingConnectionInvalid", id, "An enabled mapping requires an enabled connection owned by the same cluster."); if (!NodesValid(mapping.ConsumerNodeIds, mapping.ClusterId) || connection is null || mapping.ConsumerNodeIds.Any(n => !connection.ConsumerNodeIds.Contains(n, Ids))) Add("DataMappingConsumerScopeInvalid", id, "Mapping consumers must be a nonempty subset of connection consumers."); if (!Enum.IsDefined(mapping.Realm) || mapping.Realm == DataRealm.Unspecified || mapping.Realm != mapping.RemoteRealm) Add("DataMappingRealmMismatch", id, "Local and remote realms must be the same supported realm."); if (!KindInRealm(mapping.LocalParentKind, mapping.Realm) || mapping.LocalParentKind is "RawTag" or "UnsTagReference" or "VirtualTag" || !Same(Owner(mapping.LocalParentKind, mapping.LocalParentId), mapping.ClusterId)) Add("DataMappingParentInvalid", id, "Mapping parent must be a local entity in the selected realm and cluster."); if (!ValidSegment(mapping.BranchName, mapping.Realm)) Add("DataMappingNameInvalid", id, "Mapping branch name must be a valid realm segment."); var expectedNamespaceUri = mapping.RemoteRealm switch { DataRealm.Raw => V3NodeIds.RawNamespaceUri, DataRealm.Uns => V3NodeIds.UnsNamespaceUri, _ => null }; if (string.IsNullOrWhiteSpace(mapping.RemoteRootEntityId) || expectedNamespaceUri is null || !string.Equals(mapping.RemoteNamespaceUri, expectedNamespaceUri, StringComparison.Ordinal) || string.IsNullOrWhiteSpace(mapping.RemoteIdentifierKind) || string.IsNullOrWhiteSpace(mapping.RemoteIdentifier)) Add("DataMappingRootInvalid", id, "A stable remote entity and canonical address are required."); if (mapping.ExpectedValueKind is { } valueKind && (!Enum.IsDefined(valueKind) || valueKind == DataValueKind.Unspecified || (valueKind == DataValueKind.Array && (mapping.ExpectedArrayElementKind is not { } elementKind || !DataValue.IsSupportedArrayElementKind(elementKind))) || (valueKind != DataValueKind.Array && mapping.ExpectedArrayElementKind is not null)) || (mapping.ExpectedValueKind is null && mapping.ExpectedArrayElementKind is not null)) Add("DataMappingTypeInvalid", id, "Expected leaf value and array element types must be supported and consistent."); if (connection is not null && draft.RemoteNamespaceMappings.Any(other => Same(other.ClusterId, connection.ExpectedClusterId) && Same(other.RemoteNamespaceMappingId, mapping.RemoteRootEntityId))) Add("DataMappingProjectionLoop", id, "Projected mappings cannot be re-exported or mounted as roots."); if (connection is not null && Same(connection.ExpectedClusterId, mapping.ClusterId) && RootIsAncestor(mapping)) Add("DataMappingProjectionLoop", id, "A root cannot be mounted under itself."); if (LocalCollision(mapping) || draft.RemoteNamespaceMappings.Any(other => !ReferenceEquals(other, mapping) && other.Enabled && Same(other.ClusterId, mapping.ClusterId) && other.Realm == mapping.Realm && Same(other.LocalParentKind, mapping.LocalParentKind) && Same(other.LocalParentId, mapping.LocalParentId) && string.Equals(other.BranchName, mapping.BranchName, StringComparison.Ordinal))) Add("DataMappingNameCollision", id, "A mapping branch collides with an existing sibling."); if (!ValidOps(mapping.AllowedOperations) || connection is null || (mapping.AllowedOperations & ~connection.AllowedOperations) != 0 || (mapping.AllowedOperations.HasFlag(DataOperations.Write) && !mapping.WriteThrough)) Add("DataMappingOperationsInvalid", id, "Mapping operations must be permitted by the connection and write-through policy."); if (mapping.MaxProjectionNodes <= 0 || mapping.MaxProjectionDepth <= 0 || mapping.MetadataLeaseMilliseconds <= 0 || mapping.StaleTimeoutMilliseconds <= 0 || mapping.SamplingIntervalMilliseconds <= 0 || mapping.PublishingIntervalMilliseconds <= 0) Add("DataMappingLimitInvalid", id, "Mapping limits and intervals must be positive and the metadata lease bounded."); } foreach (var export in draft.DataExports.Where(x => x.Enabled)) { var id = export.DataExportId; if (string.IsNullOrWhiteSpace(id) || export.Revision <= 0 || string.IsNullOrWhiteSpace(export.PrincipalId) || !Enum.IsDefined(export.Realm) || export.Realm == DataRealm.Unspecified || !KindInRealm(export.RootKind, export.Realm) || !Same(Owner(export.RootKind, export.RootEntityId), export.ClusterId)) Add("DataExportRootInvalid", id, "Export requires a named principal and an origin-local root in its realm."); if (!ValidOps(export.AllowedOperations)) Add("DataExportOperationsInvalid", id, "Export operations must be a supported nonempty subset."); if (export.MaxBatchItems <= 0 || export.MaxPageItems <= 0 || export.MaxMonitoredItems <= 0 || export.MaxStreams <= 0) Add("DataExportLimitInvalid", id, "Export limits must be positive."); } return errors; } }