diff --git a/.claude/rules/drivers.md b/.claude/rules/drivers.md index 0bfe87bf2..5b44d4008 100644 --- a/.claude/rules/drivers.md +++ b/.claude/rules/drivers.md @@ -228,7 +228,12 @@ host logger factory (wired in `DriverFactoryBootstrap`; the FOCAS and TwinCAT fa design). The caller rides `WriteCaller` → `RouteNodeWrite`/`WriteAttribute.Caller` → `ICallerAwareWritable`; a gRPC data-connection write carries the connection's principal + key id from its `DataWriteAdmission` + `WriteCaller.Origin = DataConnection` (#1074), honoured only with the default-OFF `MxAccess.SecuredWritesOverDataConnections` (a forwarded write runs as the - LINK key's identity); `Origin` is stamped at the receiving seam, `Unspecified` ⇒ no identity. Not live-gated. `docs/drivers/Galaxy.md` §Secured writes. + LINK key's identity) AND the origin export's default-OFF `DataExport.AllowSecuredWrites` (#1084 — without it + `DriverInstanceActor.RichCaller` returns null, no caller reaches the driver); `Origin` is stamped at the receiving seam, + `Unspecified` ⇒ no identity. gRPC outcomes (#1091): Galaxy is `ICallerAwareWriteOutcomeCapability` — a refusal is + `DriverConfirmedFailure` + `BadUserAccessDenied` (`GalaxyWriteOutcomes`), not `OutcomeUnknown`; rich-write precedence = + caller-aware outcome (caller present) → outcome → `ICallerAwareWritable` (caller present) → `IWritable`. Both caller-aware + interfaces are OTOPCUA0001-guarded. Not live-gated. `docs/drivers/Galaxy.md` §Secured writes. - **No driver-side history (#655):** `IHistoryProvider`, `DriverCapability.HistoryRead`, `HistoryReadStatusException` and the OpcUaClient history passthrough are deleted — nothing ever dispatched HistoryRead to a driver; it is served only by the server-wide `IHistorianDataSource`. `isHistorized` on an OpcUaClient tag means OtOpcUa records it, not that upstream diff --git a/docs/DataConnections.md b/docs/DataConnections.md index 68d7860b1..ece6da156 100644 --- a/docs/DataConnections.md +++ b/docs/DataConnections.md @@ -14,7 +14,7 @@ The deployed configuration uses three entities: | Entity | Operator choices | |---|---| | `DataConnection` | Owning cluster, explicit consumer nodes, expected remote cluster/node, Node or Cluster target, endpoint set, consistency, secret reference, operation subset and finite call limits. | -| `DataExport` | Origin-owned Raw or UNS root, authenticated peer principal, operation grants and export limits. | +| `DataExport` | Origin-owned Raw or UNS root, authenticated peer principal, operation grants, export limits and the default-off identity opt-ins `AllowGalaxyServiceAck` and `AllowSecuredWrites` (#1084, migration `AddDataExportAllowSecuredWrites`). | | `RemoteNamespaceMapping` | Connection, consumer subset, local parent and branch name, same-realm remote root/address, operations, optional write-through, projection limits and freshness settings. | New connections, exports and mappings are disabled by default; write-through also defaults off. @@ -799,16 +799,30 @@ not see these bits; see "Mixed versions" above. `otopcua/apikeys//galaxy-ack-user` and `…/galaxy-ack-password` in the **origin's** secrets store; without them the #765 preflight refuses `BadUserAccessDenied`. -**Galaxy secured writes over a data connection (#1074) — opt-in, default off.** A write carries the connection's -principal, API key id and `Origin = DataConnection` to the driver. A Galaxy driver in `MxAccess.SecuredWrites = -ApiKeyIdentity` mode still refuses a SecuredWrite from a data connection (`BadUserAccessDenied`, before the wire, as -before) unless it also sets `MxAccess.SecuredWritesOverDataConnections = true`. Then it writes as the **connection key's** -Galaxy identity (the same `galaxy-ack-*` secrets as above; no fallback account). ⚠️ For a forwarding consumer cluster that -key is the link's service key, so every consumer-side client allowed to write the projected node would write secured -attributes as it. Unlike `AllowGalaxyServiceAck` there is no export-level switch; the driver option, the export's Write -grant and the origin ACL are the gates. A refused secured write reaches the caller as `OutcomeUnknown`, because the -Galaxy driver reports through the legacy write path. See -[Galaxy § Secured writes](drivers/Galaxy.md#secured-writes-under-the-callers-galaxy-identity-1017). +**Galaxy secured writes over a data connection (#1074, #1084) — two opt-ins, both default off.** A SecuredWrite +attribute written through a data connection runs as the **connection key's** Galaxy identity (the same `galaxy-ack-*` +secrets as above; no fallback account) only when BOTH hold: + +| Gate | Where | Default | Without it | +|---|---|---|---| +| **`DataExport.AllowSecuredWrites`** (#1084; AdminUI export editor "Allow secured writes under this peer's key identity") | origin ConfigDb, per export; valid only with `Write` (validator code `DataExportSecuredWriteInvalid`, authoring, deploy gate and deployed row) | `false` | the origin dispatches the write to the driver with **no caller** — it is still admitted on the Write grant, but a caller-aware driver refuses an identity-bearing write exactly as an anonymous one | +| **`MxAccess.SecuredWritesOverDataConnections`** (#1074) | Galaxy driver config (with `SecuredWrites = ApiKeyIdentity`) | `false` | the driver refuses a caller whose `Origin = DataConnection` | + +- The export flag counts only on an export of the connection's principal that grants `Write` AND whose root contains the + node (`LocalExportCatalog.AllowsSecuredWrite`); any one such export suffices, as for every grant. The origin decides it + when it admits the write, from the same catalog generation (`DataWriteAdmission.AllowsSecuredWrite`) — never from the + request — and the dispatch gate's commit re-checks that generation, so a deploy that clears it reaches the next write. +- Why two switches: the driver option applies to every connection that can write the driver's nodes, including a + **forwarding consumer cluster**, whose link key stands for every consumer-side client allowed to write the projected + node. The export flag scopes the delegation to one peer principal and one root. Turn it on for a direct client (e.g. + ScadaBridge with its own key); leave it off on an export to another OtOpcUa cluster unless delegating to the link's + identity is intended. +- The remaining gates are unchanged: the export's Write grant, the origin ACL for the connection's principal and, on a + consumer, its own write grants. +- **A refusal is reported definitively (#1091):** the Galaxy driver reports gRPC writes through `IWriteOutcomeCapability` + (+ the caller-aware `ICallerAwareWriteOutcomeCapability`), so a refused secured write is `DriverConfirmedFailure` + + `BadUserAccessDenied` (it used to be `OutcomeUnknown`). See + [Galaxy § Secured writes](drivers/Galaxy.md#secured-writes-under-the-callers-galaxy-identity-1017). ### Condition methods (`CallConditionMethod`) diff --git a/docs/drivers/Galaxy.md b/docs/drivers/Galaxy.md index 391a96fb2..f790f03b2 100644 --- a/docs/drivers/Galaxy.md +++ b/docs/drivers/Galaxy.md @@ -224,6 +224,12 @@ from the transport's `DataAuthenticatedContext` (never from the request payload) at the commit point — plus `Origin = DataConnection`. The OPC UA node manager stamps `Origin = OpcUaSession`. The runtime sets the origin from where it RECEIVED the write; nothing parses it out of the principal or key. No wire change. +**…and the origin's export must opt in too (#1084): `DataExport.AllowSecuredWrites`** (default `false`, valid only with +`Write`; AdminUI export editor "Allow secured writes under this peer's key identity"). The origin decides at admission +whether an export of the connection's principal that grants Write on the node opts in; if none does, the runtime hands +the driver **no caller** (`DriverInstanceActor.RichCaller` returns null) and the write takes the caller-less path — so the +driver option alone is not enough. See [DataConnections § Galaxy secured writes](../DataConnections.md). + The driver gives a caller an identity source only when `SecuredWrites = ApiKeyIdentity` **and** the origin is allowed: | Origin | Identity source | @@ -232,7 +238,7 @@ The driver gives a caller an identity source only when `SecuredWrites = ApiKeyId | `DataConnection` | only with `MxAccess.SecuredWritesOverDataConnections = true` (default `false`; AdminUI "Also for gRPC data-connection writes") | | `Unspecified` (the `WriteCaller` default) | never — fail closed, so a future call site that forgets to say where a write came from gets nothing | -**Off (default):** a SecuredWrite arriving over a data connection is refused exactly as before #1074 — no identity +**Off (default — either switch):** a SecuredWrite arriving over a data connection is refused exactly as before #1074 — no identity lookup, the writer's local `BadUserAccessDenied`, nothing on the wire — even when the same key writes it successfully over OPC UA. **On:** it runs as the connection key's own `/api-keys` Galaxy identity, as an OPC UA session with that key would; no identity (or a broken one) ⇒ refused. The option is ignored in `Refuse` mode. Read before turning it on: @@ -244,9 +250,17 @@ would; no identity (or a broken one) ⇒ refused. The option is ignored in `Refu names the link's account, not the person. The remaining gates are the export's Write grant, the origin ACL for the service principal and the consumer's own write grants. A direct client (e.g. ScadaBridge with its own key) is the case the option is meant for; do not map an identity to a link's service key you do not want to delegate. -- **A refusal is not reported as one over gRPC.** The Galaxy driver is a plain `IWritable` (no - `IWriteOutcomeCapability`), so the rich write path reports any non-Good result, `BadUserAccessDenied` included, as - `OutcomeUnknown` — the same as every legacy driver's Bad (pre-existing; #1074 follow-up). +- **The forwarded-write case is why the export flag exists (#1084):** set `AllowSecuredWrites` on the export for a direct + client's principal and leave it off on an export to another OtOpcUa cluster's link unless delegating to it is intended. +- **gRPC write outcomes are definite where they can be (#1091).** The driver implements `IWriteOutcomeCapability` and the + caller-aware `ICallerAwareWriteOutcomeCapability` (`DriverInstanceActor.RunRichWriteAsync` precedence: caller-aware + outcome overload when the write carries a caller → plain outcome overload → `ICallerAwareWritable` → `IWritable`; the OPC + UA path is unchanged). `GalaxyWriteOutcomes` maps each result: `BadUserAccessDenied` (every secured/verified refusal, a + failed `AuthenticateUser`, a gateway `PermissionDenied`, MXAccess's access verdicts) and the `OnWriteComplete` verdicts + `BadNotWritable` / `BadTypeMismatch` / `BadOutOfRange` / `BadConfigurationError` ⇒ `DriverConfirmedFailure` with that + status; Good ⇒ `AcceptedUnconfirmed` (the writer cannot tell a confirmed Good from the provisional one an empty statuses + array produces); everything else (`BadCommunicationError`, `BadTimeout`, Uncertain, …) ⇒ `OutcomeUnknown`. Before + #1091 every non-Good result was `OutcomeUnknown`. **The wire sequence** (`GatewayGalaxyDataWriter.WriteSecuredOneAsync`): the writer's own item handle for the secured path (separate from the raw path's supervisory-advised handle — MXAccess allows one advise mode per handle), plain @@ -275,8 +289,9 @@ wrong password ⇒ `BadUserAccessDenied` naming the user, password absent from e attribute's permission ⇒ `BadUserAccessDenied` (1016); a VerifiedWrite attribute ⇒ `BadUserAccessDenied` with no gateway traffic; a raw (FreeAccess) write on the same attribute's object still commits (the two handles coexist); a gateway reconnect re-adds + re-advises the secured handle; the same write over a gRPC data connection with that -key ⇒ `BadUserAccessDenied`-refused (reported `OutcomeUnknown`, nothing in the gateway log) until -`SecuredWritesOverDataConnections = true`, then it commits as the mapped user (#1074). +key ⇒ `BadUserAccessDenied`-refused (reported `DriverConfirmedFailure`, #1091; nothing in the gateway log) until BOTH +`SecuredWritesOverDataConnections = true` and the origin export's `AllowSecuredWrites = true` (#1084) — check each alone +still refuses — then it commits as the mapped user (#1074). Full per-field descriptions live in `Config/GalaxyDriverOptions.cs`. The full JSON skeleton is reproduced in [docs/v2/driver-specs.md §1](../v2/driver-specs.md). diff --git a/docs/security.md b/docs/security.md index 5b86a8c2f..6ff3eaec2 100644 --- a/docs/security.md +++ b/docs/security.md @@ -1401,7 +1401,7 @@ public enum NodePermissions : int } ``` -The three Write tiers map to Galaxy's v1 `SecurityClassification` — `FreeAccess`/`Operate` → `WriteOperate`, `Tune` → `WriteTune`, `Configure` → `WriteConfigure`. `VerifiedWrite` / `ViewOnly` classifications remain read-only from OPC UA regardless of grant; `SecuredWrite` is too unless the Galaxy driver opts in to `MxAccess.SecuredWrites = ApiKeyIdentity`, which writes it as the calling OPC UA session's key's own Galaxy identity (#1017). A secured write arriving over a **gRPC data connection** needs a second, default-off opt-in, `MxAccess.SecuredWritesOverDataConnections` (#1074); without it such a write is refused `BadUserAccessDenied` before the wire, as before. ⚠️ With it on, the identity is the **connection's** key — and a consumer OtOpcUa cluster forwarding its OPC UA clients' writes (projected-node write-through) presents its link's service key, so every consumer-side client allowed to write the projected node writes secured attributes as that key's Galaxy identity (the audit names the link's account, not the person). The driver tells the planes apart by `WriteCaller.Origin`, stamped by the runtime at the receiving seam (an unstated origin gets no identity). See [Galaxy § Secured writes](drivers/Galaxy.md#secured-writes-under-the-callers-galaxy-identity-1017). +The three Write tiers map to Galaxy's v1 `SecurityClassification` — `FreeAccess`/`Operate` → `WriteOperate`, `Tune` → `WriteTune`, `Configure` → `WriteConfigure`. `VerifiedWrite` / `ViewOnly` classifications remain read-only from OPC UA regardless of grant; `SecuredWrite` is too unless the Galaxy driver opts in to `MxAccess.SecuredWrites = ApiKeyIdentity`, which writes it as the calling OPC UA session's key's own Galaxy identity (#1017). A secured write arriving over a **gRPC data connection** needs two more default-off opt-ins: the driver's `MxAccess.SecuredWritesOverDataConnections` (#1074) AND, on the origin, the `DataExport.AllowSecuredWrites` of an export that grants the connection's principal `Write` on the node (#1084). Without the export flag the origin hands the driver no caller at all; without the driver option the driver refuses a data-connection caller; either way the write is refused `BadUserAccessDenied` before the wire and reported to the gRPC caller as a definite failure (#1091). ⚠️ With both on, the identity is the **connection's** key — and a consumer OtOpcUa cluster forwarding its OPC UA clients' writes (projected-node write-through) presents its link's service key, so every consumer-side client allowed to write the projected node writes secured attributes as that key's Galaxy identity (the audit names the link's account, not the person). That is why the export flag exists: it scopes the delegation to one peer and one root, so leave it off on an export to another OtOpcUa cluster unless that delegation is intended. The driver tells the planes apart by `WriteCaller.Origin`, stamped by the runtime at the receiving seam (an unstated origin gets no identity). See [Galaxy § Secured writes](drivers/Galaxy.md#secured-writes-under-the-callers-galaxy-identity-1017). `HistoryUpdate` (bit 12) is a **separate** permission from `HistoryRead` so a read-only grant cannot also authorize OPC UA HistoryUpdate operations. `TriePermissionEvaluator` maps `OpcUaOperation.HistoryUpdate` to this bit. It is **not** included in any composite bundle (`ReadOnly` / `Operator` / `Engineer` / `Admin`) — it must be granted explicitly, and it is offered as its own checkbox in the AdminUI ACL editor (`AclEdit.razor`). The HistoryUpdate service itself is now implemented (SQL Server historian backend only) — see the next section. diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataExport.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataExport.cs index 0a5ec06cc..fe27e115f 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataExport.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Entities/DataExport.cs @@ -31,5 +31,13 @@ public sealed class DataExport /// A2 (used by A2b): per-export opt-in for remote acknowledgement of Galaxy conditions, which execute as the /// origin's service identity (plan §5.6, Q2). Valid only with AlarmAcknowledge. public bool AllowGalaxyServiceAck { get; set; } + /// + /// #1084: per-export opt-in for writes that act under the connection key's own identity (Galaxy SecuredWrite attributes, + /// written as the key's /api-keys Galaxy account). Without it the origin hands the driver NO caller for a write + /// admitted through this export, so a caller-aware driver refuses an identity-bearing write exactly as it would an + /// anonymous one — even with the driver's own MxAccess.SecuredWritesOverDataConnections on. Both are needed. + /// Valid only with Write. Default false (fail closed). + /// + public bool AllowSecuredWrites { get; set; } public byte[] RowVersion { get; set; } = []; } diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261204193604_AddDataExportAllowSecuredWrites.Designer.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261204193604_AddDataExportAllowSecuredWrites.Designer.cs new file mode 100644 index 000000000..0c8ba5085 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261204193604_AddDataExportAllowSecuredWrites.Designer.cs @@ -0,0 +1,1984 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Metadata; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using ZB.MOM.WW.OtOpcUa.Configuration; + +#nullable disable + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations +{ + [DbContext(typeof(OtOpcUaConfigDbContext))] + [Migration("20261204193604_AddDataExportAllowSecuredWrites")] + partial class AddDataExportAllowSecuredWrites + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "10.0.7") + .HasAnnotation("Relational:MaxIdentifierLength", 128); + + SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder); + + modelBuilder.Entity("Microsoft.AspNetCore.DataProtection.EntityFrameworkCore.DataProtectionKey", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("int"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("Id")); + + b.Property("FriendlyName") + .HasColumnType("nvarchar(max)"); + + b.Property("Xml") + .HasColumnType("nvarchar(max)"); + + b.HasKey("Id"); + + b.ToTable("DataProtectionKeys", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ApiKey", b => + { + b.Property("ApiKeyRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ApiKeyId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedUtc") + .HasColumnType("datetime2"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("ExpiresUtc") + .HasColumnType("datetime2"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Principal") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SecretHash") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.HasKey("ApiKeyRowId"); + + b.HasIndex("ApiKeyId") + .IsUnique() + .HasDatabaseName("UX_ApiKey_ApiKeyId"); + + b.HasIndex("Principal") + .HasDatabaseName("IX_ApiKey_Principal"); + + b.ToTable("ApiKey", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => + { + b.Property("NodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("AkkaPort") + .ValueGeneratedOnAdd() + .HasColumnType("int") + .HasDefaultValue(4053); + + b.Property("ApplicationUri") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("DashboardPort") + .HasColumnType("int"); + + b.Property("DriverConfigOverridesJson") + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("GrpcPort") + .HasColumnType("int"); + + b.Property("Host") + .IsRequired() + .HasMaxLength(255) + .HasColumnType("nvarchar(255)"); + + b.Property("LastSeenAt") + .HasColumnType("datetime2(3)"); + + b.Property("MaintenanceMode") + .HasColumnType("bit"); + + b.Property("OpcUaPort") + .HasColumnType("int"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ServiceLevelBase") + .HasColumnType("tinyint"); + + b.HasKey("NodeId"); + + b.HasIndex("ApplicationUri") + .IsUnique() + .HasDatabaseName("UX_ClusterNode_ApplicationUri"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_ClusterNode_ClusterId"); + + b.ToTable("ClusterNode", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNodeCredential", b => + { + b.Property("CredentialId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Kind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("NodeId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RotatedAt") + .HasColumnType("datetime2(3)"); + + b.Property("Value") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.HasKey("CredentialId"); + + b.HasIndex("Kind", "Value") + .IsUnique() + .HasDatabaseName("UX_ClusterNodeCredential_Value") + .HasFilter("[Enabled] = 1"); + + b.HasIndex("NodeId", "Enabled") + .HasDatabaseName("IX_ClusterNodeCredential_NodeId"); + + b.ToTable("ClusterNodeCredential", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ConfigAuditLog", b => + { + b.Property("AuditId") + .ValueGeneratedOnAdd() + .HasColumnType("bigint"); + + SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property("AuditId")); + + b.Property("ClusterId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CorrelationId") + .HasColumnType("uniqueidentifier"); + + b.Property("DetailsJson") + .HasColumnType("nvarchar(max)"); + + b.Property("EventId") + .HasColumnType("uniqueidentifier"); + + b.Property("EventType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("GenerationId") + .HasColumnType("bigint"); + + b.Property("NodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Outcome") + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("Principal") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Timestamp") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.HasKey("AuditId"); + + b.HasIndex("EventId") + .IsUnique() + .HasDatabaseName("UX_ConfigAuditLog_EventId") + .HasFilter("[EventId] IS NOT NULL"); + + b.HasIndex("GenerationId") + .HasDatabaseName("IX_ConfigAuditLog_Generation") + .HasFilter("[GenerationId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Timestamp") + .IsDescending(false, true) + .HasDatabaseName("IX_ConfigAuditLog_Cluster_Time"); + + b.ToTable("ConfigAuditLog", null, t => + { + t.HasCheckConstraint("CK_ConfigAuditLog_DetailsJson_IsJson", "DetailsJson IS NULL OR ISJSON(DetailsJson) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ConfigEdit", b => + { + b.Property("EditId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("EditedAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("EditedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("EntityId") + .HasColumnType("uniqueidentifier"); + + b.Property("EntityType") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ExecutionId") + .HasColumnType("uniqueidentifier"); + + b.Property("FieldsJson") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("SourceNode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("EditId"); + + b.HasIndex("EditedAtUtc") + .HasDatabaseName("IX_ConfigEdit_EditedAt"); + + b.HasIndex("ExecutionId") + .HasDatabaseName("IX_ConfigEdit_Execution") + .HasFilter("[ExecutionId] IS NOT NULL"); + + b.HasIndex("EntityType", "EntityId") + .HasDatabaseName("IX_ConfigEdit_Entity"); + + b.ToTable("ConfigEdit", null, t => + { + t.HasCheckConstraint("CK_ConfigEdit_FieldsJson_IsJson", "ISJSON(FieldsJson) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection", b => + { + b.Property("DataConnectionRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Consistency") + .HasColumnType("int"); + + b.PrimitiveCollection("ConsumerNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DataConnectionId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.PrimitiveCollection("EligibleTargetNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.PrimitiveCollection("Endpoints") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("ExpectedClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ExpectedNodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("HistoryTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("MaxBatchItems") + .HasColumnType("int"); + + b.Property("MaxMessageBytes") + .HasColumnType("int"); + + b.Property("MaxMonitoredItems") + .HasColumnType("int"); + + b.Property("MaxPageItems") + .HasColumnType("int"); + + b.Property("MaxPendingBytes") + .HasColumnType("bigint"); + + b.Property("MaxStreams") + .HasColumnType("int"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SecretReference") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("SecretScopeClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TargetMode") + .HasColumnType("int"); + + b.Property("TimeoutMilliseconds") + .HasColumnType("int"); + + b.HasKey("DataConnectionRowId"); + + b.HasIndex("ClusterId"); + + b.HasIndex("DataConnectionId") + .IsUnique() + .HasFilter("[DataConnectionId] IS NOT NULL"); + + b.ToTable("DataConnection", null, t => + { + t.HasCheckConstraint("CK_DataConnection_Limits", "[Revision] > 0 AND [TimeoutMilliseconds] > 0 AND [MaxBatchItems] > 0 AND [MaxPageItems] > 0 AND [MaxMessageBytes] > 0 AND [MaxStreams] > 0 AND [MaxMonitoredItems] > 0 AND [MaxPendingBytes] > 0 AND [HistoryTimeoutMilliseconds] > 0"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnectionScopeState", b => + { + b.Property("Id") + .HasColumnType("int"); + + b.Property("Fingerprint") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScopeVersion") + .HasColumnType("bigint"); + + b.HasKey("Id"); + + b.ToTable("DataConnectionScopeState", null, t => + { + t.HasCheckConstraint("CK_DataConnectionScopeState_Singleton", "[Id] = 1 AND [ScopeVersion] >= 0"); + }); + + b.HasData( + new + { + Id = 1, + ScopeVersion = 0L + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataExport", b => + { + b.Property("DataExportRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowGalaxyServiceAck") + .HasColumnType("bit"); + + b.Property("AllowSecuredWrites") + .HasColumnType("bit"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DataExportId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("MaxBatchItems") + .HasColumnType("int"); + + b.Property("MaxConcurrentHistoryReads") + .HasColumnType("int"); + + b.Property("MaxConditions") + .HasColumnType("int"); + + b.Property("MaxHistoryResponseBytes") + .HasColumnType("int"); + + b.Property("MaxHistoryValuesPerPage") + .HasColumnType("int"); + + b.Property("MaxMonitoredItems") + .HasColumnType("int"); + + b.Property("MaxPageItems") + .HasColumnType("int"); + + b.Property("MaxStreams") + .HasColumnType("int"); + + b.Property("PrincipalId") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Realm") + .HasColumnType("int"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RootEntityId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RootKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("DataExportRowId"); + + b.HasIndex("ClusterId"); + + b.HasIndex("DataExportId") + .IsUnique() + .HasFilter("[DataExportId] IS NOT NULL"); + + b.ToTable("DataExport", null, t => + { + t.HasCheckConstraint("CK_DataExport_Limits", "[Revision] > 0 AND [MaxBatchItems] > 0 AND [MaxPageItems] > 0 AND [MaxMonitoredItems] > 0 AND [MaxStreams] > 0 AND [MaxConcurrentHistoryReads] > 0 AND [MaxHistoryValuesPerPage] > 0 AND [MaxHistoryResponseBytes] > 0 AND [MaxConditions] > 0"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Deployment", b => + { + b.Property("DeploymentId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ArtifactBlob") + .IsRequired() + .HasColumnType("varbinary(max)"); + + b.Property("CreatedAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("FailureReason") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RevisionHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SealedAtUtc") + .HasColumnType("datetime2(3)"); + + b.Property("Status") + .HasColumnType("int"); + + b.HasKey("DeploymentId"); + + b.HasIndex("CreatedAtUtc") + .HasDatabaseName("IX_Deployment_CreatedAt"); + + b.HasIndex("Status") + .HasDatabaseName("IX_Deployment_Status"); + + b.ToTable("Deployment", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Device", b => + { + b.Property("DeviceRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DeviceConfig") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DeviceId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DriverInstanceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("DeviceRowId"); + + b.HasIndex("DeviceId") + .IsUnique() + .HasDatabaseName("UX_Device_LogicalId") + .HasFilter("[DeviceId] IS NOT NULL"); + + b.HasIndex("DriverInstanceId") + .HasDatabaseName("IX_Device_Driver"); + + b.HasIndex("DriverInstanceId", "Name") + .IsUnique() + .HasDatabaseName("UX_Device_Driver_Name"); + + b.ToTable("Device", null, t => + { + t.HasCheckConstraint("CK_Device_DeviceConfig_IsJson", "ISJSON(DeviceConfig) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DriverInstance", b => + { + b.Property("DriverInstanceRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DriverConfig") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DriverInstanceId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DriverType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RawFolderId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ResilienceConfig") + .HasColumnType("nvarchar(max)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("DriverInstanceRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_DriverInstance_Cluster"); + + b.HasIndex("DriverInstanceId") + .IsUnique() + .HasDatabaseName("UX_DriverInstance_LogicalId") + .HasFilter("[DriverInstanceId] IS NOT NULL"); + + b.HasIndex("RawFolderId") + .HasDatabaseName("IX_DriverInstance_RawFolder"); + + b.HasIndex("ClusterId", "Name") + .IsUnique() + .HasDatabaseName("UX_DriverInstance_ClusterRoot_Name") + .HasFilter("[RawFolderId] IS NULL"); + + b.HasIndex("ClusterId", "RawFolderId", "Name") + .IsUnique() + .HasDatabaseName("UX_DriverInstance_Folder_Name") + .HasFilter("[RawFolderId] IS NOT NULL"); + + b.ToTable("DriverInstance", null, t => + { + t.HasCheckConstraint("CK_DriverInstance_DriverConfig_IsJson", "ISJSON(DriverConfig) = 1"); + + t.HasCheckConstraint("CK_DriverInstance_ResilienceConfig_IsJson", "ResilienceConfig IS NULL OR ISJSON(ResilienceConfig) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Equipment", b => + { + b.Property("EquipmentRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AssetLocation") + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("DeviceManualUri") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("EquipmentClassRef") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("EquipmentId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("EquipmentUuid") + .HasColumnType("uniqueidentifier"); + + b.Property("HardwareRevision") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("MachineCode") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Manufacturer") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ManufacturerUri") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Model") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SAPID") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SerialNumber") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SoftwareRevision") + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("UnsLineId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("YearOfConstruction") + .HasColumnType("smallint"); + + b.Property("ZTag") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("EquipmentRowId"); + + b.HasIndex("EquipmentId") + .IsUnique() + .HasDatabaseName("UX_Equipment_LogicalId") + .HasFilter("[EquipmentId] IS NOT NULL"); + + b.HasIndex("EquipmentUuid") + .IsUnique() + .HasDatabaseName("UX_Equipment_Uuid"); + + b.HasIndex("MachineCode") + .HasDatabaseName("IX_Equipment_MachineCode"); + + b.HasIndex("SAPID") + .IsUnique() + .HasDatabaseName("UX_Equipment_SAPID") + .HasFilter("[SAPID] IS NOT NULL AND [SAPID] <> N''"); + + b.HasIndex("UnsLineId") + .HasDatabaseName("IX_Equipment_Line"); + + b.HasIndex("ZTag") + .IsUnique() + .HasDatabaseName("UX_Equipment_ZTag") + .HasFilter("[ZTag] IS NOT NULL AND [ZTag] <> N''"); + + b.HasIndex("UnsLineId", "Name") + .IsUnique() + .HasDatabaseName("UX_Equipment_LinePath"); + + b.ToTable("Equipment", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.LdapGroupRoleMapping", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier"); + + b.Property("ClusterId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedAtUtc") + .HasColumnType("datetime2(3)"); + + b.Property("IsSystemWide") + .HasColumnType("bit"); + + b.Property("LdapGroup") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("Role") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("Id"); + + b.HasIndex("ClusterId"); + + b.HasIndex("LdapGroup") + .HasDatabaseName("IX_LdapGroupRoleMapping_Group"); + + b.HasIndex("LdapGroup", "ClusterId") + .IsUnique() + .HasDatabaseName("UX_LdapGroupRoleMapping_Group_Cluster"); + + b.ToTable("LdapGroupRoleMapping", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.NodeAcl", b => + { + b.Property("NodeAclRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("NodeAclId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("PermissionFlags") + .HasColumnType("int"); + + b.Property("Principal") + .IsRequired() + .HasMaxLength(256) + .HasColumnType("nvarchar(256)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScopeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ScopeKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("NodeAclRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_NodeAcl_Cluster"); + + b.HasIndex("NodeAclId") + .IsUnique() + .HasDatabaseName("UX_NodeAcl_LogicalId") + .HasFilter("[NodeAclId] IS NOT NULL"); + + b.HasIndex("Principal") + .HasDatabaseName("IX_NodeAcl_Principal"); + + b.HasIndex("ScopeKind", "ScopeId") + .HasDatabaseName("IX_NodeAcl_Scope") + .HasFilter("[ScopeId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Principal", "ScopeKind", "ScopeId") + .IsUnique() + .HasDatabaseName("UX_NodeAcl_PrincipalScope"); + + b.ToTable("NodeAcl", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.NodeDeploymentState", b => + { + b.Property("NodeId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("DeploymentId") + .HasColumnType("uniqueidentifier"); + + b.Property("AppliedAtUtc") + .HasColumnType("datetime2(3)"); + + b.Property("FailureReason") + .HasMaxLength(2048) + .HasColumnType("nvarchar(2048)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("StartedAtUtc") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("Status") + .HasColumnType("int"); + + b.HasKey("NodeId", "DeploymentId"); + + b.HasIndex("DeploymentId") + .HasDatabaseName("IX_NodeDeploymentState_Deployment"); + + b.HasIndex("Status") + .HasDatabaseName("IX_NodeDeploymentState_Status"); + + b.ToTable("NodeDeploymentState", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.PollGroup", b => + { + b.Property("PollGroupRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DriverInstanceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("IntervalMs") + .HasColumnType("int"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PollGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.HasKey("PollGroupRowId"); + + b.HasIndex("DriverInstanceId") + .HasDatabaseName("IX_PollGroup_Driver"); + + b.HasIndex("PollGroupId") + .IsUnique() + .HasDatabaseName("UX_PollGroup_LogicalId") + .HasFilter("[PollGroupId] IS NOT NULL"); + + b.ToTable("PollGroup", null, t => + { + t.HasCheckConstraint("CK_PollGroup_IntervalMs_Min", "IntervalMs >= 50"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RawFolder", b => + { + b.Property("RawFolderRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ParentRawFolderId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RawFolderId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.HasKey("RawFolderRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_RawFolder_Cluster"); + + b.HasIndex("RawFolderId") + .IsUnique() + .HasDatabaseName("UX_RawFolder_LogicalId") + .HasFilter("[RawFolderId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Name") + .IsUnique() + .HasDatabaseName("UX_RawFolder_ClusterRoot_Name") + .HasFilter("[ParentRawFolderId] IS NULL"); + + b.HasIndex("ClusterId", "ParentRawFolderId", "Name") + .IsUnique() + .HasDatabaseName("UX_RawFolder_Parent_Name") + .HasFilter("[ParentRawFolderId] IS NOT NULL"); + + b.ToTable("RawFolder", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping", b => + { + b.Property("RemoteNamespaceMappingRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AllowedOperations") + .HasColumnType("int"); + + b.Property("BranchName") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("ConditionMethodTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("ConditionSnapshotTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("ConditionStaleTimeoutMilliseconds") + .HasColumnType("int"); + + b.PrimitiveCollection("ConsumerNodeIds") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("DataConnectionId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("ExpectedArrayElementKind") + .HasColumnType("int"); + + b.Property("ExpectedValueKind") + .HasColumnType("int"); + + b.Property("LocalParentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("LocalParentKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("MaxConditions") + .HasColumnType("int"); + + b.Property("MaxHistoryAssemblyBytesPerRequest") + .HasColumnType("int"); + + b.Property("MaxProjectionDepth") + .HasColumnType("int"); + + b.Property("MaxProjectionNodes") + .HasColumnType("int"); + + b.Property("MetadataLeaseMilliseconds") + .HasColumnType("int"); + + b.Property("PublishingIntervalMilliseconds") + .HasColumnType("int"); + + b.Property("Realm") + .HasColumnType("int"); + + b.Property("RemoteIdentifier") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RemoteIdentifierKind") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("RemoteNamespaceMappingId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RemoteNamespaceUri") + .IsRequired() + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RemoteRealm") + .HasColumnType("int"); + + b.Property("RemoteRootEntityId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Revision") + .HasColumnType("bigint"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SamplingIntervalMilliseconds") + .HasColumnType("int"); + + b.Property("StaleTimeoutMilliseconds") + .HasColumnType("int"); + + b.Property("WriteThrough") + .HasColumnType("bit"); + + b.HasKey("RemoteNamespaceMappingRowId"); + + b.HasIndex("RemoteNamespaceMappingId") + .IsUnique() + .HasFilter("[RemoteNamespaceMappingId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Realm", "LocalParentKind", "LocalParentId", "BranchName") + .IsUnique(); + + b.ToTable("RemoteNamespaceMapping", null, t => + { + t.HasCheckConstraint("CK_RemoteNamespaceMapping_Limits", "[Revision] > 0 AND [MaxProjectionNodes] > 0 AND [MaxProjectionDepth] > 0 AND [MetadataLeaseMilliseconds] > 0 AND [StaleTimeoutMilliseconds] > 0 AND [SamplingIntervalMilliseconds] > 0 AND [PublishingIntervalMilliseconds] > 0 AND [MaxHistoryAssemblyBytesPerRequest] > 0 AND [MaxConditions] > 0 AND [ConditionStaleTimeoutMilliseconds] > 0 AND [ConditionMethodTimeoutMilliseconds] > 0 AND [ConditionSnapshotTimeoutMilliseconds] > 0"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", b => + { + b.Property("ScriptRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("Language") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScriptId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("SourceCode") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("SourceHash") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("ScriptRowId"); + + b.HasAlternateKey("ScriptId") + .HasName("UX_Script_LogicalId"); + + b.HasIndex("SourceHash") + .HasDatabaseName("IX_Script_SourceHash"); + + b.ToTable("Script", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ScriptedAlarm", b => + { + b.Property("ScriptedAlarmRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AlarmType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("EquipmentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("HistorizeToAveva") + .HasColumnType("bit"); + + b.Property("MessageTemplate") + .IsRequired() + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PredicateScriptId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Retain") + .HasColumnType("bit"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScriptedAlarmId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Severity") + .HasColumnType("int"); + + b.HasKey("ScriptedAlarmRowId"); + + b.HasIndex("PredicateScriptId") + .HasDatabaseName("IX_ScriptedAlarm_Script"); + + b.HasIndex("ScriptedAlarmId") + .IsUnique() + .HasDatabaseName("UX_ScriptedAlarm_LogicalId") + .HasFilter("[ScriptedAlarmId] IS NOT NULL"); + + b.HasIndex("EquipmentId", "Name") + .IsUnique() + .HasDatabaseName("UX_ScriptedAlarm_EquipmentPath"); + + b.ToTable("ScriptedAlarm", null, t => + { + t.HasCheckConstraint("CK_ScriptedAlarm_AlarmType", "AlarmType IN ('AlarmCondition','LimitAlarm','OffNormalAlarm','DiscreteAlarm')"); + + t.HasCheckConstraint("CK_ScriptedAlarm_Severity_Range", "Severity BETWEEN 1 AND 1000"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", b => + { + b.Property("ClusterId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("datetime2(3)") + .HasDefaultValueSql("SYSUTCDATETIME()"); + + b.Property("CreatedBy") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("Enterprise") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("ModifiedAt") + .HasColumnType("datetime2(3)"); + + b.Property("ModifiedBy") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("NodeCount") + .HasColumnType("tinyint"); + + b.Property("Notes") + .HasMaxLength(1024) + .HasColumnType("nvarchar(1024)"); + + b.Property("RedundancyMode") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("Site") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.HasKey("ClusterId"); + + b.HasIndex("Name") + .IsUnique() + .HasDatabaseName("UX_ServerCluster_Name"); + + b.HasIndex("Site") + .HasDatabaseName("IX_ServerCluster_Site"); + + b.ToTable("ServerCluster", null, t => + { + t.HasCheckConstraint("CK_ServerCluster_RedundancyMode_NodeCount", "((NodeCount = 1 AND RedundancyMode = 'None') OR (NodeCount = 2 AND RedundancyMode IN ('Warm', 'Hot')))"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Tag", b => + { + b.Property("TagRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("AccessLevel") + .IsRequired() + .HasMaxLength(16) + .HasColumnType("nvarchar(16)"); + + b.Property("DataType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("DeviceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("PollGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("TagConfig") + .IsRequired() + .HasColumnType("nvarchar(max)"); + + b.Property("TagGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TagId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("WriteIdempotent") + .HasColumnType("bit"); + + b.HasKey("TagRowId"); + + b.HasIndex("TagId") + .IsUnique() + .HasDatabaseName("UX_Tag_LogicalId") + .HasFilter("[TagId] IS NOT NULL"); + + b.HasIndex("DeviceId", "Name") + .IsUnique() + .HasDatabaseName("UX_Tag_Device_Name") + .HasFilter("[TagGroupId] IS NULL"); + + b.HasIndex("DeviceId", "TagGroupId") + .HasDatabaseName("IX_Tag_Device"); + + b.HasIndex("DeviceId", "TagGroupId", "Name") + .IsUnique() + .HasDatabaseName("UX_Tag_Group_Name") + .HasFilter("[TagGroupId] IS NOT NULL"); + + b.ToTable("Tag", null, t => + { + t.HasCheckConstraint("CK_Tag_TagConfig_IsJson", "ISJSON(TagConfig) = 1"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.TagGroup", b => + { + b.Property("TagGroupRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DeviceId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("ParentTagGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("TagGroupId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("TagGroupRowId"); + + b.HasIndex("DeviceId") + .HasDatabaseName("IX_TagGroup_Device"); + + b.HasIndex("TagGroupId") + .IsUnique() + .HasDatabaseName("UX_TagGroup_LogicalId") + .HasFilter("[TagGroupId] IS NOT NULL"); + + b.HasIndex("DeviceId", "Name") + .IsUnique() + .HasDatabaseName("UX_TagGroup_DeviceRoot_Name") + .HasFilter("[ParentTagGroupId] IS NULL"); + + b.HasIndex("DeviceId", "ParentTagGroupId", "Name") + .IsUnique() + .HasDatabaseName("UX_TagGroup_Parent_Name") + .HasFilter("[ParentTagGroupId] IS NOT NULL"); + + b.ToTable("TagGroup", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsArea", b => + { + b.Property("UnsAreaRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ClusterId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("UnsAreaId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("UnsAreaRowId"); + + b.HasIndex("ClusterId") + .HasDatabaseName("IX_UnsArea_Cluster"); + + b.HasIndex("UnsAreaId") + .IsUnique() + .HasDatabaseName("UX_UnsArea_LogicalId") + .HasFilter("[UnsAreaId] IS NOT NULL"); + + b.HasIndex("ClusterId", "Name") + .IsUnique() + .HasDatabaseName("UX_UnsArea_ClusterName"); + + b.ToTable("UnsArea", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsLine", b => + { + b.Property("UnsLineRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Notes") + .HasMaxLength(512) + .HasColumnType("nvarchar(512)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("UnsAreaId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("UnsLineId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("UnsLineRowId"); + + b.HasIndex("UnsAreaId") + .HasDatabaseName("IX_UnsLine_Area"); + + b.HasIndex("UnsLineId") + .IsUnique() + .HasDatabaseName("UX_UnsLine_LogicalId") + .HasFilter("[UnsLineId] IS NOT NULL"); + + b.HasIndex("UnsAreaId", "Name") + .IsUnique() + .HasDatabaseName("UX_UnsLine_AreaName"); + + b.ToTable("UnsLine", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsTagReference", b => + { + b.Property("UnsTagReferenceRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("DisplayNameOverride") + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("EquipmentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("SortOrder") + .HasColumnType("int"); + + b.Property("TagId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("UnsTagReferenceId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("UnsTagReferenceRowId"); + + b.HasIndex("EquipmentId") + .HasDatabaseName("IX_UnsTagReference_Equipment"); + + b.HasIndex("TagId") + .HasDatabaseName("IX_UnsTagReference_Tag"); + + b.HasIndex("UnsTagReferenceId") + .IsUnique() + .HasDatabaseName("UX_UnsTagReference_LogicalId") + .HasFilter("[UnsTagReferenceId] IS NOT NULL"); + + b.HasIndex("EquipmentId", "TagId") + .IsUnique() + .HasDatabaseName("UX_UnsTagReference_Equip_Tag"); + + b.ToTable("UnsTagReference", (string)null); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.VirtualTag", b => + { + b.Property("VirtualTagRowId") + .ValueGeneratedOnAdd() + .HasColumnType("uniqueidentifier") + .HasDefaultValueSql("NEWSEQUENTIALID()"); + + b.Property("ChangeTriggered") + .HasColumnType("bit"); + + b.Property("DataType") + .IsRequired() + .HasMaxLength(32) + .HasColumnType("nvarchar(32)"); + + b.Property("Enabled") + .HasColumnType("bit"); + + b.Property("EquipmentId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("Historize") + .HasColumnType("bit"); + + b.Property("Name") + .IsRequired() + .HasMaxLength(128) + .HasColumnType("nvarchar(128)"); + + b.Property("RowVersion") + .IsConcurrencyToken() + .IsRequired() + .ValueGeneratedOnAddOrUpdate() + .HasColumnType("rowversion"); + + b.Property("ScriptId") + .IsRequired() + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.Property("TimerIntervalMs") + .HasColumnType("int"); + + b.Property("VirtualTagId") + .HasMaxLength(64) + .HasColumnType("nvarchar(64)"); + + b.HasKey("VirtualTagRowId"); + + b.HasIndex("ScriptId") + .HasDatabaseName("IX_VirtualTag_Script"); + + b.HasIndex("VirtualTagId") + .IsUnique() + .HasDatabaseName("UX_VirtualTag_LogicalId") + .HasFilter("[VirtualTagId] IS NOT NULL"); + + b.HasIndex("EquipmentId", "Name") + .IsUnique() + .HasDatabaseName("UX_VirtualTag_EquipmentPath"); + + b.ToTable("VirtualTag", null, t => + { + t.HasCheckConstraint("CK_VirtualTag_TimerInterval_Min", "TimerIntervalMs IS NULL OR TimerIntervalMs >= 50"); + + t.HasCheckConstraint("CK_VirtualTag_Trigger_AtLeastOne", "ChangeTriggered = 1 OR TimerIntervalMs IS NOT NULL"); + }); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany("Nodes") + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNodeCredential", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", "Node") + .WithMany("Credentials") + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Node"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataConnection", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DataExport", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.DriverInstance", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.LdapGroupRoleMapping", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Cascade); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.NodeDeploymentState", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Deployment", "Deployment") + .WithMany() + .HasForeignKey("DeploymentId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", "Node") + .WithMany() + .HasForeignKey("NodeId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Deployment"); + + b.Navigation("Node"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RawFolder", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany("RawFolders") + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.RemoteNamespaceMapping", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", null) + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ScriptedAlarm", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", null) + .WithMany() + .HasForeignKey("PredicateScriptId") + .HasPrincipalKey("ScriptId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("FK_ScriptedAlarm_Script"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.UnsArea", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", "Cluster") + .WithMany() + .HasForeignKey("ClusterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Cluster"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.VirtualTag", b => + { + b.HasOne("ZB.MOM.WW.OtOpcUa.Configuration.Entities.Script", null) + .WithMany() + .HasForeignKey("ScriptId") + .HasPrincipalKey("ScriptId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired() + .HasConstraintName("FK_VirtualTag_Script"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ClusterNode", b => + { + b.Navigation("Credentials"); + }); + + modelBuilder.Entity("ZB.MOM.WW.OtOpcUa.Configuration.Entities.ServerCluster", b => + { + b.Navigation("Nodes"); + + b.Navigation("RawFolders"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261204193604_AddDataExportAllowSecuredWrites.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261204193604_AddDataExportAllowSecuredWrites.cs new file mode 100644 index 000000000..5b15124f9 --- /dev/null +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/20261204193604_AddDataExportAllowSecuredWrites.cs @@ -0,0 +1,32 @@ +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations +{ + /// + public partial class AddDataExportAllowSecuredWrites : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + // #1084: the export-level opt-in for secured (caller-identity) writes over a data connection. Non-null with a + // false default, so every existing export keeps refusing them and no row needs a backfill. No check constraint: + // "only with Write" is a validator rule (DataExportSecuredWriteInvalid), like AllowGalaxyServiceAck's. + migrationBuilder.AddColumn( + name: "AllowSecuredWrites", + table: "DataExport", + type: "bit", + nullable: false, + defaultValue: false); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropColumn( + name: "AllowSecuredWrites", + table: "DataExport"); + } + } +} diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs index fb8a8b17d..b5f6874de 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Migrations/OtOpcUaConfigDbContextModelSnapshot.cs @@ -500,6 +500,9 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Migrations b.Property("AllowGalaxyServiceAck") .HasColumnType("bit"); + b.Property("AllowSecuredWrites") + .HasColumnType("bit"); + b.Property("AllowedOperations") .HasColumnType("int"); diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs index 662755223..e049bd415 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Configuration/Validation/DataConnectionValidator.cs @@ -349,6 +349,10 @@ public static class DataConnectionValidator // must stay false; a deployed row from a newer central that carries both is tolerated (the flag is inert here). if (export.AllowGalaxyServiceAck && !export.AllowedOperations.HasFlag(DataOperations.AlarmAcknowledge)) Add("DataExportGalaxyAckInvalid", id, "Galaxy service acknowledgement can be allowed only on an export that grants AlarmAcknowledge."); + // #1084: the secured-write (caller-identity) opt-in qualifies the Write grant and means nothing without it. Checked + // at authoring, at the deploy gate and on a deployed row alike (a deployed row breaking it fails closed). + if (export.AllowSecuredWrites && !export.AllowedOperations.HasFlag(DataOperations.Write)) + Add("DataExportSecuredWriteInvalid", id, "Secured writes can be allowed only on an export that grants Write."); // #942: an alarm-bearing tag is never a value (#917: an unsupported value node, hidden from Browse; #896: no UNS // variable), and its condition placements sit under the tag's folder / the referencing equipment, never under the // tag. So an export rooted at the tag (RawTag) grants nothing at all, and one rooted at a reference to it diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs index d5c6b9aa8..afb6a491b 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/DataConnections/IDataServices.cs @@ -29,10 +29,16 @@ public sealed record WriteItem(string CorrelationId, string OperationId, DataVie /// recheck the original key's current principal and credential version against authority and its /// original expiry even when the epoch is unchanged. ApiKeyId and CredentialVersion are non-secret /// identifiers, never the bearer credential. +/// +/// (#1084): whether an export covering the node opts in to secured (caller-identity) +/// writes (DataExport.AllowSecuredWrites). Only then does the runtime hand the driver the connection's caller; false +/// (the default — fail closed) dispatches the write with no caller, so a caller-aware driver refuses an identity-bearing +/// write exactly as it would an anonymous one. +/// /// public sealed record DataWriteAdmission(string PrincipalId, DataView View, long AuthorityEpoch, long CatalogRevision, string ServingIncarnation, string DriverIncarnation, string OperationId, long MonotonicExpiry, - string ApiKeyId, DateTimeOffset? CredentialExpiresUtc, string CredentialVersion) + string ApiKeyId, DateTimeOffset? CredentialExpiresUtc, string CredentialVersion, bool AllowsSecuredWrite = false) { public void Validate() { diff --git a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ICallerAwareWritable.cs b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ICallerAwareWritable.cs index bd2c4cefb..b10ad8200 100644 --- a/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ICallerAwareWritable.cs +++ b/src/Core/ZB.MOM.WW.OtOpcUa.Core.Abstractions/ICallerAwareWritable.cs @@ -39,8 +39,9 @@ public enum WriteCallerOrigin /// attributes, written under the calling API key's Galaxy account). The runtime calls this overload instead /// of whenever the write carries a . Both data planes /// supply one: an OPC UA write from its session, a gRPC data-connection write from the connection's authenticated -/// key (#1074) — except through IWriteOutcomeCapability, which takes precedence on the gRPC path and carries -/// no caller. It must keep +/// key (#1074), and only when the origin export opts in (DataExport.AllowSecuredWrites, #1084). On the gRPC path +/// a driver that also implements IWriteOutcomeCapability is called through that instead — with a caller, through +/// ICallerAwareWriteOutcomeCapability (#1091). It must keep /// every other behaviour of ; a caller the driver cannot map is refused /// per write (e.g. BadUserAccessDenied), never silently written under another identity. /// diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs index 49eec7271..735389c84 100644 --- a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/GalaxyDriver.cs @@ -4,6 +4,7 @@ using Microsoft.Extensions.Logging.Abstractions; using ZB.MOM.WW.MxGateway.Client; using ZB.MOM.WW.MxGateway.Contracts.Proto; using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Browse; using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config; using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Health; @@ -38,7 +39,7 @@ namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy; /// /// public sealed class GalaxyDriver - : IDriver, ITagDiscovery, IReadable, IWritable, ICallerAwareWritable, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmInitialStateSignal, IAlarmAcknowledgePreflight, IAlarmAcknowledgeConfirmation, ISkippedTagReporter, IDisposable, IAsyncDisposable + : IDriver, ITagDiscovery, IReadable, IWritable, ICallerAwareWritable, ICallerAwareWriteOutcomeCapability, ISubscribable, IRediscoverable, IHostConnectivityProbe, IAlarmSource, IAlarmInitialStateSignal, IAlarmAcknowledgePreflight, IAlarmAcknowledgeConfirmation, ISkippedTagReporter, IDisposable, IAsyncDisposable { /// Authored tags this driver could not dial — a TagConfig with no usable /// attributeRef has no MXAccess address to bind. @@ -2438,6 +2439,42 @@ public sealed class GalaxyDriver dialledWrites, attributeRef => ResolveSecurity(ToRawPath(attributeRef)), securedCredential, cancellationToken); } + // ===== IWriteOutcomeCapability (#1091) — the gRPC data-connection write path ===== + + /// + /// #1091 — reported as explicit outcomes for + /// the gRPC data-connection write path (): a refusal is a definite + /// carrying its status (a refused secured write ⇒ + /// BadUserAccessDenied), where the legacy path reported every non-Good result as OutcomeUnknown. + /// + /// Pairs of full reference (RawPath) + value. + /// Cancellation token. + /// One outcome per request, in order. + public Task> WriteWithOutcomesAsync( + IReadOnlyList writes, CancellationToken cancellationToken) + => WithOutcomesAsync(writes, caller: null, cancellationToken); + + /// + /// #1091 — (the caller's Galaxy + /// identity for SecuredWrite attributes, under the same origin rules) reported as explicit outcomes. + /// + /// Pairs of full reference (RawPath) + value. + /// Who issued the write. + /// Cancellation token. + /// One outcome per request, in order. + public Task> WriteWithOutcomesAsync( + IReadOnlyList writes, WriteCaller caller, CancellationToken cancellationToken) + => WithOutcomesAsync(writes, caller ?? throw new ArgumentNullException(nameof(caller)), cancellationToken); + + private async Task> WithOutcomesAsync( + IReadOnlyList writes, WriteCaller? caller, CancellationToken cancellationToken) + { + var results = await WriteCoreAsync(writes, caller, cancellationToken).ConfigureAwait(false); + var outcomes = new DataWriteOutcome[results.Count]; + for (var i = 0; i < results.Count; i++) outcomes[i] = GalaxyWriteOutcomes.From(results[i]); + return outcomes; + } + /// /// #1074 — which data planes a SecuredWrite may run under the caller's identity on. An OPC UA session always /// (the #1017 opt-in alone); a gRPC data connection only with MxAccess.SecuredWritesOverDataConnections diff --git a/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyWriteOutcomes.cs b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyWriteOutcomes.cs new file mode 100644 index 000000000..a4e636b9e --- /dev/null +++ b/src/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy/Runtime/GalaxyWriteOutcomes.cs @@ -0,0 +1,47 @@ +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; + +/// +/// #1091 — how a Galaxy reads as a gRPC data-connection . Only a +/// status that can arise solely from a definite verdict is reported as one; everything ambiguous stays +/// , because a caller treats a definite failure as "the value did not change". +/// +/// +/// +/// Good ⇒ (as the legacy path reported it): the writer +/// reports a provisional Good off an EMPTY gateway statuses array (the completion wait timed out), which the result +/// cannot tell apart from a confirmed one. +/// Definite refusals ⇒ with the status: +/// BadUserAccessDenied — a local secured/verified-write refusal (no identity, origin not allowed, identity +/// unresolvable), a failed AuthenticateUser (no WriteSecured sent), the gateway refusing the caller +/// (PermissionDenied/Unauthenticated, nothing executed) or MXAccess's own access verdict (1008/1012/ +/// 1013/1016/1017); and the MXAccess OnWriteComplete verdicts BadNotWritable, BadTypeMismatch, +/// BadOutOfRange and BadConfigurationError, which no transport/exception path of the writer produces. +/// Everything else ⇒ with the status: +/// BadCommunicationError (protocol failure, exception, failed advise), BadTimeout, Uncertain +/// (Pending/Warning), BadInternalError, generic Bad and any other code. +/// +/// +internal static class GalaxyWriteOutcomes +{ + /// Maps one write result. + /// The writer's result. + /// The data-connection outcome. + public static DataWriteOutcome From(WriteResult result) + { + ArgumentNullException.ThrowIfNull(result); + var status = result.StatusCode; + if (status == StatusCodeMap.Good) return new(DataWriteState.AcceptedUnconfirmed, status, null); + return status switch + { + StatusCodeMap.BadUserAccessDenied => new(DataWriteState.DriverConfirmedFailure, status, "Write refused: access denied."), + StatusCodeMap.BadNotWritable => new(DataWriteState.DriverConfirmedFailure, status, "Write refused: not writable."), + StatusCodeMap.BadTypeMismatch => new(DataWriteState.DriverConfirmedFailure, status, "Write refused: type mismatch."), + StatusCodeMap.BadOutOfRange => new(DataWriteState.DriverConfirmedFailure, status, "Write refused: out of range."), + StatusCodeMap.BadConfigurationError => new(DataWriteState.DriverConfirmedFailure, status, "Write refused: configuration error."), + _ => new(DataWriteState.OutcomeUnknown, status, "Write outcome unknown."), + }; + } +} diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor index 6f14d2e01..feb4b291b 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor +++ b/src/Server/ZB.MOM.WW.OtOpcUa.AdminUI/Components/Pages/Clusters/ClusterDataConnections.razor @@ -123,6 +123,7 @@ else
Larger answers are sent in bounded chunks.
A remote AlarmSubscribe scope with more conditions than this is refused (ConditionCapacity) before anything is imported.
Galaxy-sourced alarms are acknowledged under this peer's API-key Galaxy ack identity (provision otopcua/apikeys/<keyId>/galaxy-ack-user and …/galaxy-ack-password on this cluster). Requires AlarmAcknowledge.
+
Galaxy SecuredWrite attributes written through this export run as this peer's API-key Galaxy identity (the same otopcua/apikeys/<keyId>/galaxy-ack-* secrets). Also needs the Galaxy driver's "Also for gRPC data-connection writes". If the peer is another OtOpcUa cluster, every client it forwards writes for writes as that one identity. Requires Write.
@Actions(e, e.DataExportRowId != Guid.Empty) } diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs index b31a8958d..2dde0016c 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/DataConnections/DataWriteExecutor.cs @@ -144,7 +144,10 @@ internal sealed class DataWriteExecutor(DataAuthenticatedContext context, Func nodes, IEnumerable exports, int maximumNodes = 100_000, @@ -100,7 +100,9 @@ public sealed partial class LocalExportCatalog export.AllowedOperations & DataOperationSets.Understood, export.MaxBatchItems, export.MaxPageItems, export.MaxMonitoredItems, export.MaxStreams, export.MaxConcurrentHistoryReads, export.MaxHistoryValuesPerPage, export.MaxHistoryResponseBytes, export.MaxConditions, // A2b (§6, Q2): the Galaxy service-ack opt-in counts only with the AlarmAcknowledge grant it qualifies. - export.AllowGalaxyServiceAck && (export.AllowedOperations & DataOperations.AlarmAcknowledge) != 0)); + export.AllowGalaxyServiceAck && (export.AllowedOperations & DataOperations.AlarmAcknowledge) != 0, + // #1084: the secured-write (caller-identity) opt-in counts only with the Write grant it qualifies. + export.AllowSecuredWrites && (export.AllowedOperations & DataOperations.Write) != 0)); if (UnknownOperationDrops.Unknown(export.AllowedOperations) is var unknown && unknown != DataOperations.None) dropped[export.DataExportId] = unknown; } @@ -201,6 +203,25 @@ public sealed partial class LocalExportCatalog return false; } + /// + /// #1084: whether holds an export of the node's realm that grants Write on it AND opts in to + /// secured writes (DataExport.AllowSecuredWrites) — i.e. a write admitted for this node may carry the connection's + /// caller to a caller-aware driver (Galaxy SecuredWrite under the key's Galaxy identity). Any one such export suffices, + /// exactly as for ; with none the write is still admitted (on the Write grant) but goes to the + /// driver without a caller, so an identity-bearing write is refused there. + /// + internal bool AllowsSecuredWrite(string principal, LocalDataNode node) + { + ArgumentNullException.ThrowIfNull(node); + foreach (var rule in _exports) + { + if (!rule.SecuredWrites || !string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase) + || rule.Realm != node.Metadata.View.Realm || (rule.Operations & DataOperations.Write) == 0) continue; + if (rule.WholeRealm || IsAncestor(rule.Root!, node.Metadata.View)) return true; + } + return false; + } + internal string SubscriptionExportScope(string principal, LocalDataNode node) { var ids = _exports.Where(rule => string.Equals(principal, rule.Principal, StringComparison.OrdinalIgnoreCase) && diff --git a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs index 810abcdbf..f98f3b294 100644 --- a/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs +++ b/src/Server/ZB.MOM.WW.OtOpcUa.Runtime/Drivers/DriverInstanceActor.cs @@ -1510,14 +1510,18 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers { // #1074: a gRPC data-connection write carries its caller like an OPC UA write does (#1017) — // the admission's principal + API key id, bound from the authenticated transport context - // (never from the request payload) and re-checked by the dispatch gate's commit above. A - // caller-aware driver (Galaxy SecuredWrite under the key's Galaxy identity) gets it; every - // other driver is unchanged. No driver is both IWriteOutcomeCapability and - // ICallerAwareWritable today; one that were would need a caller-aware outcome overload. - if (driver is IWriteOutcomeCapability rich) + // (never from the request payload) and re-checked by the dispatch gate's commit above. #1084: + // only when an export covering the node opts in (AllowsSecuredWrite); otherwise there is no + // caller and a caller-aware driver gets the caller-less call (identity-bearing writes refused). + // Precedence (#1091): the explicit-outcome path wins over the legacy one, and within each the + // caller-aware overload is used whenever there is a caller. + var caller = RichCaller(msg.Ticket.Proof.Admission); + if (caller is not null && driver is ICallerAwareWriteOutcomeCapability richCaller) + _ = ObserveRichDriver(richCaller.WriteWithOutcomesAsync(request, caller, ct), physical); + else if (driver is IWriteOutcomeCapability rich) _ = ObserveRichDriver(rich.WriteWithOutcomesAsync(request, ct), physical); - else if (driver is ICallerAwareWritable callerAware) - _ = ObserveLegacyDriver(callerAware.WriteAsync(request, RichCaller(msg.Ticket.Proof.Admission), ct), physical); + else if (caller is not null && driver is ICallerAwareWritable callerAware) + _ = ObserveLegacyDriver(callerAware.WriteAsync(request, caller, ct), physical); else _ = ObserveLegacyDriver(((IWritable)driver).WriteAsync(request, ct), physical); } @@ -1583,11 +1587,17 @@ public sealed class DriverInstanceActor : ReceiveActor, IWithTimers /// Both are mandatory on an admission () and carry no secret. Marked /// so a driver can hold this plane to its own opt-in (Galaxy /// MxAccess.SecuredWritesOverDataConnections, default off). + /// + /// #1084: null unless the admission says an export covering the node opts in to secured writes + /// (DataExport.AllowSecuredWrites, default off). The driver option alone is therefore not enough: a + /// forwarding consumer cluster's link gets no caller identity unless the origin's export for it says so. + /// ///
- internal static WriteCaller RichCaller(DataWriteAdmission admission) => - new(string.IsNullOrWhiteSpace(admission.PrincipalId) ? null : admission.PrincipalId, - string.IsNullOrWhiteSpace(admission.ApiKeyId) ? null : admission.ApiKeyId, - WriteCallerOrigin.DataConnection); + internal static WriteCaller? RichCaller(DataWriteAdmission admission) => + !admission.AllowsSecuredWrite ? null + : new(string.IsNullOrWhiteSpace(admission.PrincipalId) ? null : admission.PrincipalId, + string.IsNullOrWhiteSpace(admission.ApiKeyId) ? null : admission.ApiKeyId, + WriteCallerOrigin.DataConnection); private static async Task ObserveRichDriver(Task> task, TaskCompletionSource physical) diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataSecuredWriteExportConfigurationTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataSecuredWriteExportConfigurationTests.cs new file mode 100644 index 000000000..92e7ac7f6 --- /dev/null +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/DataConnections/GrpcDataSecuredWriteExportConfigurationTests.cs @@ -0,0 +1,60 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Configuration.Entities; +using ZB.MOM.WW.OtOpcUa.Configuration.Validation; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; + +namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests.DataConnections; + +/// +/// #1084: — the export-level opt-in a secured (caller-identity) write over a data +/// connection needs on top of the driver's own MxAccess.SecuredWritesOverDataConnections. Default off, valid only with +/// the Write grant it qualifies, added by a default-false column. +/// +[Trait("Category", "Unit"), Trait("Feature", "GrpcData")] +public sealed class GrpcDataSecuredWriteExportConfigurationTests +{ + [Fact] + public void A_new_export_does_not_allow_secured_writes() + { + new DataExport().AllowSecuredWrites.ShouldBeFalse("fail closed: the opt-in defaults off"); + } + + [Fact] + public void AllowSecuredWrites_is_valid_only_with_Write_at_authoring_and_on_a_deployed_row() + { + var draft = GrpcDataReservedOperationAuthoringTests.Snapshot(DataOperations.Browse | DataOperations.Read); + DataConnectionValidator.Validate(draft).ShouldNotContain(x => x.Code == "DataExportSecuredWriteInvalid"); + draft.DataExports[0].AllowSecuredWrites = true; + DataConnectionValidator.Validate(draft).ShouldContain(x => x.Code == "DataExportSecuredWriteInvalid" && x.Context == "export"); + DataConnectionValidator.ValidateDeployed(draft).ShouldContain(x => x.Code == "DataExportSecuredWriteInvalid" && x.Context == "export"); + // With the Write grant the flag authors and deploys cleanly. + draft.DataExports[0].AllowedOperations = DataOperations.Browse | DataOperations.Read | DataOperations.Write; + DataConnectionValidator.Validate(draft).ShouldNotContain(x => x.Code == "DataExportSecuredWriteInvalid"); + DataConnectionValidator.ValidateDeployed(draft).ShouldNotContain(x => x.Code == "DataExportSecuredWriteInvalid"); + // A disabled export is not validated (it grants nothing either way). + draft.DataExports[0].AllowedOperations = DataOperations.Read; + draft.DataExports[0].Enabled = false; + DataConnectionValidator.Validate(draft).ShouldNotContain(x => x.Code == "DataExportSecuredWriteInvalid"); + } + + [Fact] + public void Migration_adds_a_default_false_column_reversibly_and_no_constraint() + { + using var db = new OtOpcUaConfigDbContext(new DbContextOptionsBuilder() + .UseSqlServer("Server=127.0.0.1,1;Database=design;Integrated Security=true;TrustServerCertificate=true").Options); + var migrations = db.Database.GetMigrations().ToArray(); + var index = Array.FindIndex(migrations, x => x.EndsWith("_AddDataExportAllowSecuredWrites", StringComparison.Ordinal)); + index.ShouldBeGreaterThan(0); + var migrator = db.GetService(); + var up = migrator.GenerateScript(migrations[index - 1], migrations[index]); + up.ShouldContain("ALTER TABLE [DataExport] ADD [AllowSecuredWrites] bit NOT NULL DEFAULT CAST(0 AS bit)"); + up.ShouldNotContain("CHECK", Case.Sensitive, "no constraint, so the upgrade preflight needs no MigrationPreChecks twin"); + var down = migrator.GenerateScript(migrations[index], migrations[index - 1]); + down.ShouldContain("DROP COLUMN [AllowSecuredWrites]"); + db.Database.HasPendingModelChanges().ShouldBeFalse(); + } +} diff --git a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ScriptForeignKeysAndExternalIdUniquenessMigrationTests.cs b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ScriptForeignKeysAndExternalIdUniquenessMigrationTests.cs index 32cfb7ba6..66f22b6af 100644 --- a/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ScriptForeignKeysAndExternalIdUniquenessMigrationTests.cs +++ b/tests/Core/ZB.MOM.WW.OtOpcUa.Configuration.Tests/ScriptForeignKeysAndExternalIdUniquenessMigrationTests.cs @@ -16,6 +16,8 @@ namespace ZB.MOM.WW.OtOpcUa.Configuration.Tests; public sealed class ScriptForeignKeysAndExternalIdUniquenessMigrationTests { private const string Previous = "20261203154217_ConfigurationGapsIndexesAndRowVersions"; + // Migrate up to THIS migration, not the latest: a later migration must not change what these tests assert (#1084 added one). + private const string This = "20261203200204_ScriptForeignKeysAndExternalIdUniqueness"; private static Equipment NewEquipment(string? zTag = null, string? sapId = null) { @@ -50,7 +52,7 @@ public sealed class ScriptForeignKeysAndExternalIdUniquenessMigrationTests scratch.Execute( "INSERT ExternalIdReservation (Kind, Value, EquipmentUuid, ClusterId, FirstPublishedBy) VALUES ('ZTag', 'ZT-9', NEWID(), 'c', 't')"); - var ex = Should.Throw(() => scratch.MigrateTo()); + var ex = Should.Throw(() => scratch.MigrateTo(This)); ex.Number.ShouldBe(51049); ex.Message.ShouldContain("VT-dangling->SC-gone"); @@ -88,7 +90,7 @@ public sealed class ScriptForeignKeysAndExternalIdUniquenessMigrationTests db.SaveChanges(); } - Should.NotThrow(() => scratch.MigrateTo()); + Should.NotThrow(() => scratch.MigrateTo(This)); scratch.LastAppliedMigration().ShouldEndWith("_ScriptForeignKeysAndExternalIdUniqueness"); scratch.Scalar("SELECT COUNT(*) FROM sys.foreign_keys WHERE name IN ('FK_VirtualTag_Script', 'FK_ScriptedAlarm_Script')").ShouldBe(2); diff --git a/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverWriteOutcomeTests.cs b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverWriteOutcomeTests.cs new file mode 100644 index 000000000..fb696ee17 --- /dev/null +++ b/tests/Drivers/ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests/Runtime/GalaxyDriverWriteOutcomeTests.cs @@ -0,0 +1,124 @@ +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Config; +using ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime; + +namespace ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Tests.Runtime; + +/// +/// #1091 — the Galaxy driver reports gRPC data-connection writes through (and its +/// caller-aware overload), so a refused secured write is a definite + +/// BadUserAccessDenied instead of the legacy path's OutcomeUnknown; only verdict-only statuses are definite. +/// +public sealed class GalaxyDriverWriteOutcomeTests +{ + [Theory] + [InlineData(StatusCodeMap.Good, DataWriteState.AcceptedUnconfirmed)] + [InlineData(StatusCodeMap.BadUserAccessDenied, DataWriteState.DriverConfirmedFailure)] + [InlineData(StatusCodeMap.BadNotWritable, DataWriteState.DriverConfirmedFailure)] + [InlineData(StatusCodeMap.BadTypeMismatch, DataWriteState.DriverConfirmedFailure)] + [InlineData(StatusCodeMap.BadOutOfRange, DataWriteState.DriverConfirmedFailure)] + [InlineData(StatusCodeMap.BadConfigurationError, DataWriteState.DriverConfirmedFailure)] + [InlineData(StatusCodeMap.BadCommunicationError, DataWriteState.OutcomeUnknown)] + [InlineData(StatusCodeMap.BadTimeout, DataWriteState.OutcomeUnknown)] + [InlineData(StatusCodeMap.BadInternalError, DataWriteState.OutcomeUnknown)] + [InlineData(StatusCodeMap.BadOutOfService, DataWriteState.OutcomeUnknown)] + [InlineData(StatusCodeMap.Uncertain, DataWriteState.OutcomeUnknown)] + [InlineData(StatusCodeMap.Bad, DataWriteState.OutcomeUnknown)] + public void A_write_result_maps_to_a_definite_outcome_only_for_a_verdict_status(uint status, DataWriteState expected) + { + var outcome = GalaxyWriteOutcomes.From(new WriteResult(status)); + outcome.State.ShouldBe(expected); + outcome.StatusCode.ShouldBe(status, "the status rides the outcome unchanged"); + } + + [Fact] + public async Task A_secured_write_with_no_caller_is_reported_as_a_definite_access_refusal() + { + var (driver, writer) = Build(overDataConnections: true); + + var outcomes = await driver.WriteWithOutcomesAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], + TestContext.Current.CancellationToken); + + var outcome = outcomes.ShouldHaveSingleItem(); + outcome.State.ShouldBe(DataWriteState.DriverConfirmedFailure); + outcome.StatusCode.ShouldBe(StatusCodeMap.BadUserAccessDenied); + writer.Sources.ShouldHaveSingleItem().ShouldBeNull("no caller ⇒ no identity source"); + } + + [Fact] + public async Task The_caller_overload_follows_the_same_origin_rules_as_the_legacy_one() + { + var (driver, writer) = Build(overDataConnections: false); + var caller = new WriteCaller("svc-mes", "0a1b2c3d4e5f6071", WriteCallerOrigin.DataConnection); + + var refused = await driver.WriteWithOutcomesAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], caller, + TestContext.Current.CancellationToken); + refused.ShouldHaveSingleItem().State.ShouldBe(DataWriteState.DriverConfirmedFailure, + "a data-connection caller gets no identity without MxAccess.SecuredWritesOverDataConnections"); + + var (optedIn, optedInWriter) = Build(overDataConnections: true); + var written = await optedIn.WriteWithOutcomesAsync([new WriteRequest("Plant/Tank1/SP", 1.0)], caller, + TestContext.Current.CancellationToken); + written.ShouldHaveSingleItem().State.ShouldBe(DataWriteState.AcceptedUnconfirmed); + optedInWriter.Sources.ShouldHaveSingleItem().ShouldNotBeNull("positive control: the opted-in driver writes as the key"); + writer.Sources.ShouldHaveSingleItem().ShouldBeNull(); + } + + [Fact] + public async Task Outcomes_keep_request_order_for_a_mixed_batch() + { + var (driver, _) = Build(overDataConnections: true, statuses: [StatusCodeMap.Good, StatusCodeMap.BadCommunicationError, StatusCodeMap.BadNotWritable]); + + var outcomes = await driver.WriteWithOutcomesAsync( + [new WriteRequest("Plant/Tank1/SP", 1.0), new WriteRequest("Plant/Tank1/SP", 2.0), new WriteRequest("Plant/Tank1/SP", 3.0)], + TestContext.Current.CancellationToken); + + outcomes.Select(o => o.State).ShouldBe( + [DataWriteState.AcceptedUnconfirmed, DataWriteState.OutcomeUnknown, DataWriteState.DriverConfirmedFailure]); + } + + private static (GalaxyDriver Driver, SecuredWriter Writer) Build(bool overDataConnections, uint[]? statuses = null) + { + var writer = new SecuredWriter(statuses); + var options = new GalaxyDriverOptions( + new GalaxyGatewayOptions("https://mxgw.test:5001", "key"), + new GalaxyMxAccessOptions("OtOpcUa-A") + { + SecuredWrites = GalaxySecuredWriteMode.ApiKeyIdentity, + SecuredWritesOverDataConnections = overDataConnections, + }, + new GalaxyRepositoryOptions(WatchDeployEvents: false), + new GalaxyReconnectOptions()) + { + RawTags = [new RawTagEntry("Plant/Tank1/SP", """{"attributeRef":"Tank1.SP"}""", false)], + }; + return (new GalaxyDriver("g", options, hierarchySource: null, dataWriter: writer, + ackCredentialResolver: FixedAckCredentialResolver.Fallback()), writer); + } + + /// Like the real writer for a SecuredWrite tag: refuses BadUserAccessDenied without an identity source; + /// with one (or with canned ) answers per request. + private sealed class SecuredWriter(uint[]? statuses) : IGalaxyDataWriter + { + public List>?> Sources { get; } = []; + + public Task> WriteAsync(IReadOnlyList writes, + Func securityResolver, CancellationToken cancellationToken) + => ((IGalaxyDataWriter)this).WriteAsync(writes, securityResolver, null, cancellationToken); + + Task> IGalaxyDataWriter.WriteAsync(IReadOnlyList writes, + Func securityResolver, + Func>? securedCredential, CancellationToken cancellationToken) + { + Sources.Add(securedCredential); + return Task.FromResult>(statuses is not null + ? [.. statuses.Select(s => new WriteResult(s))] + : [.. writes.Select(_ => new WriteResult(securedCredential is null ? StatusCodeMap.BadUserAccessDenied : StatusCodeMap.Good))]); + } + + public void InvalidateHandleCaches() { } + } +} diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/DataConnectionRootPickerTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/DataConnectionRootPickerTests.cs index 1d42578e1..800e21d12 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/DataConnectionRootPickerTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.AdminUI.Tests/Pages/DataConnectionRootPickerTests.cs @@ -54,6 +54,8 @@ public sealed class DataConnectionRootPickerTests : BunitContext protected override object? Invoke(System.Reflection.MethodInfo? method, object?[]? args) => throw new NotSupportedException("Node-pick mode must not call " + method?.Name); } + private string? _dbName; + private IRenderedComponent>> RenderPage() { Services.RemoveAll(); @@ -62,7 +64,7 @@ public sealed class DataConnectionRootPickerTests : BunitContext Services.AddCascadingAuthenticationState(); Services.AddSingleton(new PrincipalState()); Services.AddSingleton(new NoDiagnostics()); - var name = RawTreeTestDb.SeedFresh(); + var name = _dbName = RawTreeTestDb.SeedFresh(); using (var db = RawTreeTestDb.CreateNamed(name)) { db.UnsAreas.Add(new UnsArea { UnsAreaId = "AREA-1", ClusterId = Cluster, Name = "Packaging" }); @@ -138,6 +140,27 @@ public sealed class DataConnectionRootPickerTests : BunitContext cut.WaitForAssertion(() => cut.Find("#remote-root").GetAttribute("value").ShouldBe("AREA-OTHER")); } + /// #1084: the export editor's secured-write opt-in is offered only with the Write grant and is saved to the row. + [Fact] + public void Export_SecuredWritesCheckbox_RequiresWrite_AndIsSaved() + { + var cut = RenderPage(); + cut.WaitForElement("button:contains('New export')").Click(); + cut.WaitForElement("#export-secured-writes").HasAttribute("disabled").ShouldBeTrue("a new export has no Write grant"); + cut.Find("#export-id").Change("EXP-SW"); + cut.Find("#principal").Change("peer-principal"); + cut.Find("#export-root-id").Change("RawDevice|" + RawTreeTestDb.FolderedDeviceId); + cut.FindAll("fieldset label").Single(l => l.TextContent.Trim() == "Write").QuerySelector("input")!.Change(true); + cut.WaitForAssertion(() => cut.Find("#export-secured-writes").HasAttribute("disabled").ShouldBeFalse()); + cut.Find("#export-secured-writes").Change(true); + cut.Find("button:contains('Save draft')").Click(); + cut.WaitForAssertion(() => cut.Markup.ShouldContain("Draft saved")); + using var db = RawTreeTestDb.CreateNamed(_dbName!); + var saved = db.DataExports.Single(x => x.DataExportId == "EXP-SW"); + saved.AllowSecuredWrites.ShouldBeTrue(); + saved.AllowedOperations.HasFlag(ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections.DataOperations.Write).ShouldBeTrue(); + } + [Fact] public void Cancel_LeavesTheFieldUnchanged() { diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs index 055bf81a9..13890d86d 100644 --- a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataDriverOutcomeTests.cs @@ -22,7 +22,7 @@ using ZB.MOM.WW.OtOpcUa.Runtime.Tests.Harness; namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; [Trait("Category", "Unit"), Trait("Feature", "GrpcData"), Trait("Phase", "P05")] -public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase +public sealed partial class GrpcDataDriverOutcomeTests : RuntimeActorTestBase { private static readonly TimeSpan Timeout = TimeSpan.FromSeconds(10); @@ -318,13 +318,14 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase /// carrying the ADMITTED principal + API key id (bound from the authenticated /// transport context), exactly as an OPC UA write carries its session's (#1017). Before the fix the rich path /// always called the caller-less , so a Galaxy SecuredWrite was refused. + /// #1084: only for a write whose admitting export opts in to secured writes. /// [Fact] public async Task Rich_write_hands_a_caller_aware_driver_the_admitted_principal_and_key() { var driver = new CallerRecordingDriver(); var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1))); - var (ticket, claim) = NewWrite("caller", 1); + var (ticket, claim) = NewWrite("caller", 1, securedWrites: true); var result = await actor.Ask(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken); @@ -334,6 +335,51 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase driver.Calls.ShouldBe(0, "the caller-less overload must not be used when the driver can act on the caller"); } + /// + /// #1084 fail closed: an admission whose export does NOT opt in to secured writes hands a caller-aware driver no + /// caller at all — the caller-less overload runs, so an identity-bearing write is refused exactly as an anonymous one. + /// + [Fact] + public async Task Rich_write_without_the_export_opt_in_reaches_a_caller_aware_driver_without_a_caller() + { + var driver = new CallerRecordingDriver(); + var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1))); + var (ticket, claim) = NewWrite("no-export-opt-in", 1); + + var result = await actor.Ask(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), + Timeout, TestContext.Current.CancellationToken); + + result.State.ShouldBe(DataWriteState.AcceptedUnconfirmed); + driver.Callers.ShouldBeEmpty("no caller identity without the export's opt-in"); + driver.Calls.ShouldBe(1); + } + + /// + /// #1091 precedence: a driver with the explicit-outcome capability AND a caller-aware outcome overload gets the + /// caller-aware overload when the write carries a caller, the plain outcome overload when it does not — never the + /// legacy path either way, and its outcome is reported as the driver gave it. + /// + [Fact] + public async Task Rich_write_to_a_caller_aware_outcome_driver_uses_the_caller_overload_only_with_a_caller() + { + var driver = new CallerRecordingRichDriver(); + var actor = Connect(driver, new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1))); + + var (withTicket, withClaim) = NewWrite("rich-caller", 1, securedWrites: true); + var with = await actor.Ask(new DriverInstanceActor.WriteAttributeWithOutcome(withTicket, withClaim), + Timeout, TestContext.Current.CancellationToken); + var (withoutTicket, withoutClaim) = NewWrite("rich-no-caller", 2); + var without = await actor.Ask(new DriverInstanceActor.WriteAttributeWithOutcome(withoutTicket, withoutClaim), + Timeout, TestContext.Current.CancellationToken); + + with.State.ShouldBe(DataWriteState.DriverConfirmedFailure); + with.StatusCode.ShouldBe(0x801F0000u); + without.State.ShouldBe(DataWriteState.DriverConfirmedSuccess); + driver.Callers.ShouldBe([new WriteCaller("peer", "key", WriteCallerOrigin.DataConnection)]); + driver.CallerlessOutcomeCalls.ShouldBe(1); + driver.Calls.ShouldBe(0, "the legacy IWritable path is never used by an outcome-capable driver"); + } + /// /// #1074 — both data planes hand the driver the same caller shape: an OPC UA write's /// (caller from the session, #1017) and a gRPC data-connection @@ -352,7 +398,7 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase Caller: new WriteCaller("peer", "key", WriteCallerOrigin.OpcUaSession)), Timeout, TestContext.Current.CancellationToken); opcUa.Success.ShouldBeTrue(opcUa.Reason); - var (ticket, claim) = NewWrite("parity", 2); + var (ticket, claim) = NewWrite("parity", 2, securedWrites: true); var grpc = await actor.Ask(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken); grpc.State.ShouldBe(DataWriteState.AcceptedUnconfirmed); @@ -376,7 +422,7 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase var galaxy = new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver("driver", GalaxyOptions(overDataConnections: true), hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver); var actor = Connect(new GalaxyWriteHost(galaxy), new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1))); - var (ticket, claim) = NewWrite("galaxy", 5, driverReference: "Plant/Tank1/SP"); + var (ticket, claim) = NewWrite("galaxy", 5, driverReference: "Plant/Tank1/SP", securedWrites: true); var result = await actor.Ask(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken); @@ -388,9 +434,11 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase /// /// #1074 default: the same write to a Galaxy driver in ApiKeyIdentity mode WITHOUT - /// SecuredWritesOverDataConnections is refused exactly as before #1074 — no identity is resolved, the - /// writer refuses the SecuredWrite BadUserAccessDenied locally, and the gRPC caller sees the same outcome as - /// before (the legacy path's OutcomeUnknown). The OPC UA plane on the same driver still writes (control). + /// SecuredWritesOverDataConnections is refused exactly as before #1074 — no identity is resolved and the + /// writer refuses the SecuredWrite BadUserAccessDenied locally — even though the export opts in (#1084: both + /// are needed). #1091: the gRPC caller now hears that refusal definitively (DriverConfirmedFailure + + /// BadUserAccessDenied; it used to be OutcomeUnknown). The OPC UA plane on the same driver still writes + /// (control). /// [Fact] public async Task Rich_write_to_a_Galaxy_driver_without_the_data_connection_opt_in_is_refused_as_before() @@ -400,12 +448,13 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase var galaxy = new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver("driver", GalaxyOptions(overDataConnections: false), hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver); var actor = Connect(new GalaxyWriteHost(galaxy), new RecordingGate(), new LateWriteObserver(1, TimeSpan.FromMinutes(1))); - var (ticket, claim) = NewWrite("galaxy-off", 5, driverReference: "Plant/Tank1/SP"); + var (ticket, claim) = NewWrite("galaxy-off", 5, driverReference: "Plant/Tank1/SP", securedWrites: true); var result = await actor.Ask(new DriverInstanceActor.WriteAttributeWithOutcome(ticket, claim), Timeout, TestContext.Current.CancellationToken); - result.State.ShouldBe(DataWriteState.OutcomeUnknown, "the pre-#1074 report of a refused legacy write"); + result.State.ShouldBe(DataWriteState.DriverConfirmedFailure, "#1091: a refused secured write is a definite failure"); + result.StatusCode.ShouldBe(0x801F0000u, "BadUserAccessDenied"); writer.Refusals.ShouldBe(1); writer.ResolvedUsers.ShouldBeEmpty(); resolver.SecuredWriteKeyIds.ShouldBeEmpty("no identity is looked up for a data-connection write while opted out"); @@ -677,12 +726,13 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase } private static (WriteAdmissionTicket Ticket, WriteClaim Claim) NewWrite(string operation, int value, - string driverReference = "plant/tag", string driverInstanceId = "driver") + string driverReference = "plant/tag", string driverInstanceId = "driver", bool securedWrites = false) { var now = TimeProvider.System.GetTimestamp(); var view = new DataView(new("cluster", "urn:raw", "string", "plant/tag"), DataRealm.Raw, null, 0, "plant/tag"); var admission = new DataWriteAdmission("peer", view, 1, 1, "serving", "driver-incarnation", operation, - now + 60 * TimeProvider.System.TimestampFrequency, "key", DateTimeOffset.UtcNow.AddMinutes(1), "key-version"); + now + 60 * TimeProvider.System.TimestampFrequency, "key", DateTimeOffset.UtcNow.AddMinutes(1), "key-version", + AllowsSecuredWrite: securedWrites); var scope = new FrozenWriteScope("cluster", NodeHierarchyKind.Raw, ImmutableArray.Create("plant", "tag")); var proof = new WriteRouteProof(admission, scope, "RawTag", "tag", null, driverInstanceId, driverReference, 1, 1); var ticket = new WriteAdmissionTicket(proof, DataValue.FromScalar(DataValueKind.Int32, value), now); @@ -738,9 +788,31 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase } } + private sealed class CallerRecordingRichDriver : LegacyDriver, ICallerAwareWriteOutcomeCapability + { + private readonly Lock _gate = new(); + private readonly List _callers = []; + private int _callerless; + public IReadOnlyList Callers { get { lock (_gate) return [.. _callers]; } } + public int CallerlessOutcomeCalls => Volatile.Read(ref _callerless); + public Task> WriteWithOutcomesAsync(IReadOnlyList writes, + CancellationToken cancellationToken) + { + Interlocked.Increment(ref _callerless); + return Task.FromResult>([new(DataWriteState.DriverConfirmedSuccess, 0, null)]); + } + public Task> WriteWithOutcomesAsync(IReadOnlyList writes, WriteCaller caller, + CancellationToken cancellationToken) + { + lock (_gate) _callers.Add(caller); + return Task.FromResult>([new(DataWriteState.DriverConfirmedFailure, 0x801F0000u, "denied")]); + } + } + /// Hosts a real 's write surface without its /// gateway lifecycle (initialize would dial mxaccessgw). - private sealed class GalaxyWriteHost(ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver galaxy) : IDriver, ICallerAwareWritable + private sealed class GalaxyWriteHost(ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver galaxy) + : IDriver, ICallerAwareWritable, ICallerAwareWriteOutcomeCapability { public string DriverInstanceId => "driver"; public string DriverType => "Galaxy"; @@ -753,6 +825,10 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase => galaxy.WriteAsync(writes, cancellationToken); public Task> WriteAsync(IReadOnlyList writes, WriteCaller caller, CancellationToken cancellationToken) => ((ICallerAwareWritable)galaxy).WriteAsync(writes, caller, cancellationToken); + public Task> WriteWithOutcomesAsync(IReadOnlyList writes, + CancellationToken cancellationToken) => galaxy.WriteWithOutcomesAsync(writes, cancellationToken); + public Task> WriteWithOutcomesAsync(IReadOnlyList writes, WriteCaller caller, + CancellationToken cancellationToken) => galaxy.WriteWithOutcomesAsync(writes, caller, cancellationToken); #pragma warning restore OTOPCUA0001 } @@ -793,7 +869,7 @@ public sealed class GrpcDataDriverOutcomeTests : RuntimeActorTestBase string? apiKeyId, CancellationToken cancellationToken) { SecuredWriteKeyIds.Add(apiKeyId); - return Task.FromResult(apiKeyId == "key" + return Task.FromResult(apiKeyId is "key" or "peer-key" ? ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.GalaxyAckCredentialResolution.Resolved( new("mes-writer", "PLANT", "pw", ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.GalaxyAckCredentialSource.ApiKey)) : ZB.MOM.WW.OtOpcUa.Driver.Galaxy.Runtime.GalaxyAckCredentialResolution.Refused("no key identity")); diff --git a/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSecuredWriteExportTests.cs b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSecuredWriteExportTests.cs new file mode 100644 index 000000000..31b183510 --- /dev/null +++ b/tests/Server/ZB.MOM.WW.OtOpcUa.Runtime.Tests/DataConnections/GrpcDataSecuredWriteExportTests.cs @@ -0,0 +1,175 @@ +using System.Text; +using System.Text.Json.Nodes; +using Akka.Actor; +using Shouldly; +using Xunit; +using ZB.MOM.WW.OtOpcUa.Core.Abstractions.DataConnections; +using ZB.MOM.WW.OtOpcUa.Core.Authorization; +using ZB.MOM.WW.OtOpcUa.Runtime.DataConnections; +using ZB.MOM.WW.OtOpcUa.Runtime.Drivers; +using ZB.MOM.WW.OtOpcUa.Runtime.Redundancy; + +namespace ZB.MOM.WW.OtOpcUa.Runtime.Tests.DataConnections; + +/// +/// #1084 — a secured (caller-identity) write over a gRPC data connection needs BOTH the origin export's opt-in +/// (DataExport.AllowSecuredWrites) AND the Galaxy driver's MxAccess.SecuredWritesOverDataConnections. +/// Driven end to end through the runtime write path: a deployed artifact → the compiled export catalog → the real +/// executor (admission) → the real → the +/// behind the real dispatch gate → a real GalaxyDriver (#1091 outcomes). +/// +public sealed partial class GrpcDataDriverOutcomeTests +{ + [Theory] + [InlineData(true, true)] + [InlineData(false, true)] + [InlineData(true, false)] + public async Task A_secured_write_over_a_data_connection_needs_both_the_export_opt_in_and_the_driver_option( + bool exportOptIn, bool driverOption) + { + var ct = TestContext.Current.CancellationToken; + var clock = TimeProvider.System; + var fence = new DataWriteDispatchFence(); + var authority = new DataPlaneAuthorityState(fence); + var activation = new CatalogActivation(fence); + var role = new RedundancyRoleView(fence); + role.PublishPrimaryRole(true); + var serving = new ServingIdentity("node-a", "serving", "Primary", 0, 0); + var coordinator = new LocalCatalogCoordinator(activation, authority, () => serving); + var bytes = SecuredWriteArtifact(exportOptIn); + var attempt = coordinator.BeginAttempt("catalog-revision"); + coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, "node-a")).ShouldBeTrue(); + using (var parsed = DeploymentArtifact.Open(bytes)) + coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot("node-a")!, "node-a").ShouldBeTrue(); + coordinator.Complete(attempt, true).ShouldBeTrue(); + var catalog = coordinator.Current.ShouldNotBeNull(); + var node = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag"); + var key = authority.Current.FindUsableKey("peer-key", clock.GetUtcNow().UtcDateTime).ShouldNotBeNull(); + + var limits = new DataLimits(100, 100, 1_000_000, 100, 10, 1_000_000, + TimeSpan.FromSeconds(15), TimeSpan.FromHours(1), TimeSpan.FromMinutes(1)); + var capabilities = new DataCapabilitiesProvider("cluster", () => coordinator.Current!.Serving, () => true, limits); + var policy = new DataOperationPolicy(authority, new TriePermissionEvaluator(authority.Tries, clock), clock); + var bounds = new DriverWriteBounds(TimeSpan.FromSeconds(5)); + var runtime = new DataWriteRuntime(coordinator, activation, authority, policy, capabilities, role, clock, bounds, + "serving", 16, 16_384, 16_384, 4, TimeSpan.FromMinutes(1)); + + var writer = new GalaxyIdentityRecordingWriter(); + var resolver = new KeyIdentityResolver(); + var galaxy = new ZB.MOM.WW.OtOpcUa.Driver.Galaxy.GalaxyDriver("driver", GalaxyOptions(driverOption), + hierarchySource: null, dataWriter: writer, ackCredentialResolver: resolver); + var actor = Connect(new GalaxyWriteHost(galaxy), runtime.Gate, runtime.Observer, writeClock: clock, + writeRouteState: runtime.Routes); + var incarnation = runtime.Routes.CurrentDriverIncarnation("driver").ShouldNotBeNull(); + runtime.Routes.Publish(node.Metadata.View, "driver", "Plant/Tank1/SP", incarnation); + var host = Sys.ActorOf(Props.Create(() => new RichRouteForwarder(actor))); + + var context = new DataAuthenticatedContext("peer", "peer-key", DataCallerIdentity.CredentialVersionFor(key), + null, catalog.AuthorityEpoch); + var results = await runtime.ForCaller(context, () => host).WriteAsync(new WriteBatch( + [new WriteItem("c1", "secured-op", node.Metadata.View, DataValue.FromScalar(DataValueKind.Int32, 7), + catalog.Serving.CatalogEpoch, "serving", TimeSpan.FromSeconds(30))], + new DataBudget(TimeSpan.FromSeconds(30), 8, 64_000)), ct); + var outcome = results.ShouldHaveSingleItem().Outcome; + + if (exportOptIn && driverOption) + { + outcome.State.ShouldBe(DataWriteState.AcceptedUnconfirmed, outcome.Diagnostic); + writer.ResolvedUsers.ShouldBe(["mes-writer"], "the secured write ran as the connection key's own Galaxy identity"); + resolver.SecuredWriteKeyIds.ShouldBe(["peer-key"]); + } + else + { + outcome.State.ShouldBe(DataWriteState.DriverConfirmedFailure, outcome.Diagnostic); + outcome.StatusCode.ShouldBe(0x801F0000u, "BadUserAccessDenied, reported definitively (#1091)"); + writer.Refusals.ShouldBe(1); + writer.ResolvedUsers.ShouldBeEmpty(); + resolver.SecuredWriteKeyIds.ShouldBeEmpty("no identity is looked up unless both opt-ins are set"); + } + } + + /// #1084: the opt-in is per export and per root — only an export of the principal that grants Write AND opts in, + /// and whose root contains the node, lets a write carry the caller; another principal's export never does. + [Fact] + public void Only_an_opted_in_Write_export_whose_root_contains_the_node_allows_a_secured_write() + { + var root = JsonNode.Parse(SecuredWriteArtifact(exportOptIn: false))!.AsObject(); + root["Devices"]!.AsArray().Add(JsonNode.Parse("""{"DeviceId":"device2","DriverInstanceId":"driver","Name":"Other","DeviceConfig":"{}","Enabled":true}""")); + root["Tags"]!.AsArray().Add(JsonNode.Parse("""{"TagId":"tag2","DeviceId":"device2","Name":"Level","DataType":"Int32","AccessLevel":1,"TagConfig":"{}"}""")); + root["DataExports"]!.AsArray().Add(JsonNode.Parse(""" + {"DataExportId":"device-only","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"RawDevice","RootEntityId":"device", + "PrincipalId":"peer","AllowedOperations":8,"AllowSecuredWrites":true} + """)); + root["DataExports"]!.AsArray().Add(JsonNode.Parse(""" + {"DataExportId":"other-principal","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster", + "PrincipalId":"other","AllowedOperations":12,"AllowSecuredWrites":true} + """)); + var catalog = Compile(Encoding.UTF8.GetBytes(root.ToJsonString())); + var inside = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag"); + var outside = catalog.Nodes.Single(n => n.EntityKind == "RawTag" && n.EntityId == "tag2"); + + catalog.AllowsSecuredWrite("peer", inside).ShouldBeTrue("the device-rooted export opts in and contains the tag"); + catalog.AllowsSecuredWrite("peer", outside).ShouldBeFalse("only the whole-realm export without the opt-in covers it"); + catalog.AllowsExport("peer", outside, DataOperations.Write).ShouldBeTrue("the write itself is still admitted"); + catalog.AllowsSecuredWrite("PEER", inside).ShouldBeTrue("principals compare case-insensitively, as for every grant"); + catalog.AllowsSecuredWrite("stranger", inside).ShouldBeFalse(); + } + + /// #1084: the flag rides the artifact; on a deployed row without the Write grant it fails closed. + [Fact] + public void AllowSecuredWrites_rides_the_artifact_and_without_Write_fails_the_row_closed() + { + using (var parsed = DeploymentArtifact.Open(SecuredWriteArtifact(exportOptIn: true))) + parsed.ParseDataExports("node-a").ShouldHaveSingleItem().AllowSecuredWrites.ShouldBeTrue(); + var root = JsonNode.Parse(SecuredWriteArtifact(exportOptIn: true))!.AsObject(); + root["DataExports"]![0]!["AllowedOperations"] = (int)(DataOperations.Browse | DataOperations.Read); + using var bad = DeploymentArtifact.Open(Encoding.UTF8.GetBytes(root.ToJsonString())); + Should.Throw(() => bad.ParseDataExports("node-a")); + using var old = DeploymentArtifact.Open(SecuredWriteArtifact(exportOptIn: null)); + old.ParseDataExports("node-a").ShouldHaveSingleItem().AllowSecuredWrites.ShouldBeFalse("a pre-#1084 artifact grants none"); + } + + private static LocalExportCatalog Compile(byte[] bytes) + { + var fence = new DataWriteDispatchFence(); + var authority = new DataPlaneAuthorityState(fence); + var coordinator = new LocalCatalogCoordinator(new CatalogActivation(fence), authority, + () => new ServingIdentity("node-a", "serving", "Primary", 0, 0)); + var attempt = coordinator.BeginAttempt("catalog-revision"); + coordinator.InstallAuthority(attempt, DeploymentArtifact.ParseDataPlaneAuthority(bytes, "node-a")).ShouldBeTrue(); + using (var parsed = DeploymentArtifact.Open(bytes)) + coordinator.Stage(attempt, parsed.ParseLocalCatalogSnapshot("node-a")!, "node-a").ShouldBeTrue(); + coordinator.Complete(attempt, true).ShouldBeTrue(); + return coordinator.Current.ShouldNotBeNull(); + } + + /// The export's AllowSecuredWrites; null omits the field (a pre-#1084 artifact). + private static byte[] SecuredWriteArtifact(bool? exportOptIn) + { + var root = JsonNode.Parse(""" + { + "Clusters":[{"ClusterId":"cluster","Name":"Cluster","Enterprise":"ent","Site":"site","CreatedBy":"test","RedundancyMode":0,"Enabled":true}], + "Nodes":[{"NodeId":"node-a","ClusterId":"cluster","Host":"node-a","ApplicationUri":"urn:node-a","CreatedBy":"test","Enabled":true,"MaintenanceMode":false}], + "ApiKeys":[{"ApiKeyId":"peer-key","Name":"peer-key","SecretHash":"hash","Principal":"peer","Enabled":true}], + "NodeAcls":[{"NodeAclId":"acl","ClusterId":"cluster","Principal":"peer","ScopeKind":0,"PermissionFlags":16}], + "RawFolders":[{"RawFolderId":"folder","ClusterId":"cluster","Name":"Plant"}], + "DriverInstances":[{"DriverInstanceId":"driver","ClusterId":"cluster","RawFolderId":"folder","Name":"Driver","DriverType":"Modbus","DriverConfig":"{}","Enabled":true}], + "Devices":[{"DeviceId":"device","DriverInstanceId":"driver","Name":"Device","DeviceConfig":"{}","Enabled":true}], + "Tags":[{"TagId":"tag","DeviceId":"device","Name":"Speed","DataType":"Int32","AccessLevel":1,"TagConfig":"{}"}], + "TagGroups":[],"UnsAreas":[],"UnsLines":[],"Equipment":[],"UnsTagReferences":[],"VirtualTags":[], + "DataConnections":[],"RemoteNamespaceMappings":[], + "DataExports":[{"DataExportId":"raw","ClusterId":"cluster","Enabled":true,"Realm":1,"RootKind":"Cluster","RootEntityId":"cluster","PrincipalId":"peer","AllowedOperations":8}] + } + """)!.AsObject(); + if (exportOptIn is { } optIn) root["DataExports"]![0]!["AllowSecuredWrites"] = optIn; + return Encoding.UTF8.GetBytes(root.ToJsonString()); + } + + /// Stands in for 's rich-write routing: hands the routed write to the one child. + private sealed class RichRouteForwarder : ReceiveActor + { + public RichRouteForwarder(IActorRef child) => + Receive(msg => + child.Forward(new DriverInstanceActor.WriteAttributeWithOutcome(msg.Ticket, msg.Claim))); + } +}