From 97e4d96afaa419ea3a0ffe5ab4cc25d4e479e849 Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Thu, 3 Dec 2026 09:41:50 -0500 Subject: [PATCH] fix(grpc): check AddBufferedItem read constraints; fail closed on unclassified command kinds (SES-003, #242) AddBufferedItem carries an item_definition but fell into the default branch of ApplyConstraintsAsync, so a read-constrained key could add and advise an out-of-scope tag. It now runs EnforceReadTagAsync. The switch also fails closed: kinds are explicitly classified as constraint-checked or tag-free, any other kind is refused with PermissionDenied and an audited denial, and a test enumerates MxCommandKind so a new kind must be classified. --- docs/Authorization.md | 24 +++- .../Grpc/MxAccessGatewayService.cs | 83 +++++++++++ .../MxAccessGatewayServiceConstraintTests.cs | 134 ++++++++++++++++++ 3 files changed, 237 insertions(+), 4 deletions(-) diff --git a/docs/Authorization.md b/docs/Authorization.md index 03827c04..40d5e385 100644 --- a/docs/Authorization.md +++ b/docs/Authorization.md @@ -249,10 +249,26 @@ page create dialog (see [Gateway Dashboard Design](./GatewayDashboardDesign.md#api-keys-page)). The dashboard API Keys page also renders each key's effective constraints. -The service checks read constraints for `AddItem`, `AddItem2`, `AddItemBulk`, -`SubscribeBulk`, `AdviseItemBulk`, and `ReadBulk`. It checks write constraints -for `Write`, `Write2`, `WriteSecured`, `WriteSecured2`, `WriteBulk`, -`Write2Bulk`, `WriteSecuredBulk`, and `WriteSecured2Bulk`. Bulk commands run +The service checks read constraints for `AddItem`, `AddItem2`, +`AddBufferedItem`, `AddItemBulk`, `SubscribeBulk`, `AdviseItemBulk`, and +`ReadBulk`. It checks write constraints for `Write`, `Write2`, `WriteSecured`, +`WriteSecured2`, `WriteBulk`, `Write2Bulk`, `WriteSecuredBulk`, and +`WriteSecured2Bulk`. Handle-only commands (`Advise`, `RemoveItem`, the +un-advise and remove bulks) and commands with no tag at all (`Register`, +`Ping`, `DrainEvents`, ...) are on an explicit no-tag allow-list +(`MxAccessGatewayService.UnconstrainedCommandKinds`); single `Advise` relies on +the add that produced the handle having been checked. + +The command-kind switch fails closed. A kind that is on neither the checked list +(`ConstrainedCommandKinds`) nor the allow-list is refused with +`PermissionDenied` and one audited `constraint-denied` event, for every key, +constrained or not. Today that covers the gateway-internal alarm kinds +(`SubscribeAlarms`, `UpdateAlarmWatchList`, `AcknowledgeAlarmByName`, ...), +which the gateway's alarm monitor sends through `ISessionManager` and which the +public `Invoke` could only ever deliver without a payload, and any kind added +to the contract later. A unit test enumerates `MxCommandKind` and fails until a +new kind is classified, so a new tag-bearing kind cannot reach the worker +unchecked the way `AddBufferedItem` once did (SES-003). Bulk commands run through `BulkConstraintPlan` (`ReadBulkConstraintPlan`, `WriteBulkConstraintPlan`, `SubscribeBulkConstraintPlan`), which preserves the caller's input order: each entry is evaluated against the constraint surface, diff --git a/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs b/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs index 63455c46..01a51c2d 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs @@ -1,3 +1,4 @@ +using System.Collections.Frozen; using System.Diagnostics; using Grpc.Core; using Google.Protobuf.WellKnownTypes; @@ -24,6 +25,60 @@ public sealed class MxAccessGatewayService( ILogger logger, IGatewayAlarmService alarmService) : MxAccessGateway.MxAccessGatewayBase { + /// + /// Command kinds checks against the caller's read or + /// write constraints because their payload names a tag address or an item handle that maps + /// back to one. + /// + internal static readonly FrozenSet ConstrainedCommandKinds = new[] + { + MxCommandKind.AddItem, + MxCommandKind.AddItem2, + MxCommandKind.AddBufferedItem, + MxCommandKind.AddItemBulk, + MxCommandKind.SubscribeBulk, + MxCommandKind.AdviseItemBulk, + MxCommandKind.ReadBulk, + MxCommandKind.Write, + MxCommandKind.Write2, + MxCommandKind.WriteSecured, + MxCommandKind.WriteSecured2, + MxCommandKind.WriteBulk, + MxCommandKind.Write2Bulk, + MxCommandKind.WriteSecuredBulk, + MxCommandKind.WriteSecured2Bulk, + }.ToFrozenSet(); + + /// + /// Command kinds that carry no tag address, so they pass + /// without a constraint check. Handle-only commands (Advise, RemoveItem, ...) + /// belong here because the add that produced the handle was checked. Any kind in neither + /// set is refused with PermissionDenied, so a new tag-bearing kind cannot slip + /// through unchecked; the enum-coverage test fails until it is classified. + /// + internal static readonly FrozenSet UnconstrainedCommandKinds = new[] + { + MxCommandKind.Register, + MxCommandKind.Unregister, + MxCommandKind.RemoveItem, + MxCommandKind.Advise, + MxCommandKind.UnAdvise, + MxCommandKind.AdviseSupervisory, + MxCommandKind.SetBufferedUpdateInterval, + MxCommandKind.Suspend, + MxCommandKind.Activate, + MxCommandKind.AuthenticateUser, + MxCommandKind.ArchestraUserToId, + MxCommandKind.RemoveItemBulk, + MxCommandKind.UnAdviseItemBulk, + MxCommandKind.UnsubscribeBulk, + MxCommandKind.Ping, + MxCommandKind.GetSessionState, + MxCommandKind.GetWorkerInfo, + MxCommandKind.DrainEvents, + MxCommandKind.ShutdownWorker, + }.ToFrozenSet(); + /// public override async Task OpenSession( OpenSessionRequest request, @@ -380,6 +435,10 @@ public sealed class MxAccessGatewayService( await EnforceReadTagAsync(identity, command.Kind, command.AddItem2.ItemDefinition, correlationId, cancellationToken) .ConfigureAwait(false); return null; + case MxCommandKind.AddBufferedItem: + await EnforceReadTagAsync(identity, command.Kind, command.AddBufferedItem.ItemDefinition, correlationId, cancellationToken) + .ConfigureAwait(false); + return null; case MxCommandKind.AddItemBulk: return await FilterTagBulkAsync( identity, @@ -506,10 +565,34 @@ public sealed class MxAccessGatewayService( .ConfigureAwait(false); return null; default: + if (UnconstrainedCommandKinds.Contains(command.Kind)) + { + return null; + } + + // Fail closed: a kind that is neither checked above nor on the no-tag allow-list + // (a gateway-internal alarm kind, or a kind added to the contract after this + // switch) may carry a tag address the API-key constraints never saw. + await RefuseUnconstrainedCommandAsync(identity, command.Kind, correlationId, cancellationToken) + .ConfigureAwait(false); return null; } } + private async Task RefuseUnconstrainedCommandAsync( + ApiKeyIdentity? identity, + MxCommandKind commandKind, + string? correlationId, + CancellationToken cancellationToken) + { + ConstraintFailure failure = new( + "command-kind", + $"Command kind {commandKind} is not accepted on Invoke: it has no API-key constraint check."); + await constraintEnforcer.RecordDenialAsync(identity, commandKind.ToString(), commandKind.ToString(), failure, correlationId, cancellationToken) + .ConfigureAwait(false); + throw new RpcException(new Status(StatusCode.PermissionDenied, failure.Message)); + } + private async Task EnforceReadTagAsync( ApiKeyIdentity? identity, MxCommandKind commandKind, diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceConstraintTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceConstraintTests.cs index 59593846..fbf947c9 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceConstraintTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceConstraintTests.cs @@ -689,6 +689,140 @@ public sealed class MxAccessGatewayServiceConstraintTests Assert.Equal("Secret.Tag", enforcer.RecordedDenials[0].Target); } + // === AddBufferedItem and the fail-closed command-kind switch (SES-003) === + + /// + /// AddBufferedItem names a tag like the other adds, so an out-of-scope tag is + /// refused with , the denial is audited, and the + /// worker never sees the command. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Invoke_AddBufferedItem_WithDeniedTag_ThrowsPermissionDeniedAndDoesNotCallWorker() + { + PredicateConstraintEnforcer enforcer = new() + { + DenyTag = tag => tag == "AreaB.Tank.Level", + }; + FakeSessionManager sessionManager = CreateSessionManagerWithSeed(); + MxAccessGatewayService service = CreateService(sessionManager, enforcer); + + MxCommandRequest request = new() + { + SessionId = SessionId, + ClientCorrelationId = "corr-buffered", + Command = new MxCommand + { + Kind = MxCommandKind.AddBufferedItem, + AddBufferedItem = new AddBufferedItemCommand { ServerHandle = 7, ItemDefinition = "AreaB.Tank.Level" }, + }, + }; + + RpcException exception = await Assert.ThrowsAsync( + async () => await service.Invoke(request, new TestServerCallContext())); + + Assert.Equal(StatusCode.PermissionDenied, exception.StatusCode); + Assert.Equal(0, sessionManager.InvokeCount); + (string commandKind, string target, string? correlationId) = Assert.Single(enforcer.RecordedDenials); + Assert.Equal(nameof(MxCommandKind.AddBufferedItem), commandKind); + Assert.Equal("AreaB.Tank.Level", target); + Assert.Equal("corr-buffered", correlationId); + } + + /// An in-scope AddBufferedItem still reaches the worker. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Invoke_AddBufferedItem_WithAllowedTag_ReachesWorker() + { + PredicateConstraintEnforcer enforcer = new() + { + DenyTag = tag => tag == "AreaB.Tank.Level", + }; + FakeSessionManager sessionManager = CreateSessionManagerWithSeed(); + MxAccessGatewayService service = CreateService(sessionManager, enforcer); + + await service.Invoke( + new MxCommandRequest + { + SessionId = SessionId, + Command = new MxCommand + { + Kind = MxCommandKind.AddBufferedItem, + AddBufferedItem = new AddBufferedItemCommand { ServerHandle = 7, ItemDefinition = "AreaA.Tank.Level" }, + }, + }, + new TestServerCallContext()); + + Assert.Equal(1, sessionManager.InvokeCount); + Assert.Empty(enforcer.RecordedDenials); + } + + /// + /// Every is classified exactly once: constraint-checked, + /// on the no-tag allow-list, or one of the gateway-internal alarm kinds the switch + /// refuses. A new contract value fails this test until someone decides whether it + /// carries a tag; at runtime an unclassified kind is refused, not passed through. + /// + [Fact] + public void EveryCommandKind_IsClassifiedExactlyOnceForConstraintEnforcement() + { + HashSet refusedOnInvoke = + [ + MxCommandKind.SubscribeAlarms, + MxCommandKind.UnsubscribeAlarms, + MxCommandKind.AcknowledgeAlarm, + MxCommandKind.QueryActiveAlarms, + MxCommandKind.AcknowledgeAlarmByName, + MxCommandKind.UpdateAlarmWatchList, + ]; + + foreach (MxCommandKind kind in Enum.GetValues()) + { + if (kind == MxCommandKind.Unspecified) + { + continue; + } + + int classifications = + (MxAccessGatewayService.ConstrainedCommandKinds.Contains(kind) ? 1 : 0) + + (MxAccessGatewayService.UnconstrainedCommandKinds.Contains(kind) ? 1 : 0) + + (refusedOnInvoke.Contains(kind) ? 1 : 0); + Assert.True(classifications == 1, $"MxCommandKind.{kind} is classified {classifications} times; expected exactly once."); + } + } + + /// + /// A kind on neither list — a gateway-internal alarm kind, or a value the switch has never + /// seen — is refused with and an audited denial + /// even for an unconstrained key, and never reaches the worker. + /// + /// Numeric value. + /// A task that represents the asynchronous operation. + [Theory] + [InlineData((int)MxCommandKind.SubscribeAlarms)] + [InlineData((int)MxCommandKind.UpdateAlarmWatchList)] + [InlineData((int)MxCommandKind.AcknowledgeAlarmByName)] + [InlineData(999)] + public async Task Invoke_UnclassifiedCommandKind_FailsClosed(int kindValue) + { + PredicateConstraintEnforcer enforcer = new(); + FakeSessionManager sessionManager = CreateSessionManagerWithSeed(); + MxAccessGatewayService service = CreateService(sessionManager, enforcer); + + RpcException exception = await Assert.ThrowsAsync( + async () => await service.Invoke( + new MxCommandRequest + { + SessionId = SessionId, + Command = new MxCommand { Kind = (MxCommandKind)kindValue }, + }, + new TestServerCallContext())); + + Assert.Equal(StatusCode.PermissionDenied, exception.StatusCode); + Assert.Equal(0, sessionManager.InvokeCount); + Assert.Single(enforcer.RecordedDenials); + } + // === Helpers === private static MxAccessGatewayService CreateService(