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.
This commit is contained in:
+20
-4
@@ -249,10 +249,26 @@ page create dialog (see
|
|||||||
[Gateway Dashboard Design](./GatewayDashboardDesign.md#api-keys-page)). The
|
[Gateway Dashboard Design](./GatewayDashboardDesign.md#api-keys-page)). The
|
||||||
dashboard API Keys page also renders each key's effective constraints.
|
dashboard API Keys page also renders each key's effective constraints.
|
||||||
|
|
||||||
The service checks read constraints for `AddItem`, `AddItem2`, `AddItemBulk`,
|
The service checks read constraints for `AddItem`, `AddItem2`,
|
||||||
`SubscribeBulk`, `AdviseItemBulk`, and `ReadBulk`. It checks write constraints
|
`AddBufferedItem`, `AddItemBulk`, `SubscribeBulk`, `AdviseItemBulk`, and
|
||||||
for `Write`, `Write2`, `WriteSecured`, `WriteSecured2`, `WriteBulk`,
|
`ReadBulk`. It checks write constraints for `Write`, `Write2`, `WriteSecured`,
|
||||||
`Write2Bulk`, `WriteSecuredBulk`, and `WriteSecured2Bulk`. Bulk commands run
|
`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`,
|
through `BulkConstraintPlan` (`ReadBulkConstraintPlan`,
|
||||||
`WriteBulkConstraintPlan`, `SubscribeBulkConstraintPlan`), which preserves the
|
`WriteBulkConstraintPlan`, `SubscribeBulkConstraintPlan`), which preserves the
|
||||||
caller's input order: each entry is evaluated against the constraint surface,
|
caller's input order: each entry is evaluated against the constraint surface,
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
using System.Collections.Frozen;
|
||||||
using System.Diagnostics;
|
using System.Diagnostics;
|
||||||
using Grpc.Core;
|
using Grpc.Core;
|
||||||
using Google.Protobuf.WellKnownTypes;
|
using Google.Protobuf.WellKnownTypes;
|
||||||
@@ -24,6 +25,60 @@ public sealed class MxAccessGatewayService(
|
|||||||
ILogger<MxAccessGatewayService> logger,
|
ILogger<MxAccessGatewayService> logger,
|
||||||
IGatewayAlarmService alarmService) : MxAccessGateway.MxAccessGatewayBase
|
IGatewayAlarmService alarmService) : MxAccessGateway.MxAccessGatewayBase
|
||||||
{
|
{
|
||||||
|
/// <summary>
|
||||||
|
/// Command kinds <see cref="ApplyConstraintsAsync"/> 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.
|
||||||
|
/// </summary>
|
||||||
|
internal static readonly FrozenSet<MxCommandKind> 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();
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Command kinds that carry no tag address, so they pass <see cref="ApplyConstraintsAsync"/>
|
||||||
|
/// without a constraint check. Handle-only commands (<c>Advise</c>, <c>RemoveItem</c>, ...)
|
||||||
|
/// belong here because the add that produced the handle was checked. Any kind in neither
|
||||||
|
/// set is refused with <c>PermissionDenied</c>, so a new tag-bearing kind cannot slip
|
||||||
|
/// through unchecked; the enum-coverage test fails until it is classified.
|
||||||
|
/// </summary>
|
||||||
|
internal static readonly FrozenSet<MxCommandKind> 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();
|
||||||
|
|
||||||
/// <inheritdoc />
|
/// <inheritdoc />
|
||||||
public override async Task<OpenSessionReply> OpenSession(
|
public override async Task<OpenSessionReply> OpenSession(
|
||||||
OpenSessionRequest request,
|
OpenSessionRequest request,
|
||||||
@@ -380,6 +435,10 @@ public sealed class MxAccessGatewayService(
|
|||||||
await EnforceReadTagAsync(identity, command.Kind, command.AddItem2.ItemDefinition, correlationId, cancellationToken)
|
await EnforceReadTagAsync(identity, command.Kind, command.AddItem2.ItemDefinition, correlationId, cancellationToken)
|
||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
return null;
|
return null;
|
||||||
|
case MxCommandKind.AddBufferedItem:
|
||||||
|
await EnforceReadTagAsync(identity, command.Kind, command.AddBufferedItem.ItemDefinition, correlationId, cancellationToken)
|
||||||
|
.ConfigureAwait(false);
|
||||||
|
return null;
|
||||||
case MxCommandKind.AddItemBulk:
|
case MxCommandKind.AddItemBulk:
|
||||||
return await FilterTagBulkAsync(
|
return await FilterTagBulkAsync(
|
||||||
identity,
|
identity,
|
||||||
@@ -506,10 +565,34 @@ public sealed class MxAccessGatewayService(
|
|||||||
.ConfigureAwait(false);
|
.ConfigureAwait(false);
|
||||||
return null;
|
return null;
|
||||||
default:
|
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;
|
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(
|
private async Task EnforceReadTagAsync(
|
||||||
ApiKeyIdentity? identity,
|
ApiKeyIdentity? identity,
|
||||||
MxCommandKind commandKind,
|
MxCommandKind commandKind,
|
||||||
|
|||||||
@@ -689,6 +689,140 @@ public sealed class MxAccessGatewayServiceConstraintTests
|
|||||||
Assert.Equal("Secret.Tag", enforcer.RecordedDenials[0].Target);
|
Assert.Equal("Secret.Tag", enforcer.RecordedDenials[0].Target);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// === AddBufferedItem and the fail-closed command-kind switch (SES-003) ===
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// <c>AddBufferedItem</c> names a tag like the other adds, so an out-of-scope tag is
|
||||||
|
/// refused with <see cref="StatusCode.PermissionDenied"/>, the denial is audited, and the
|
||||||
|
/// worker never sees the command.
|
||||||
|
/// </summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[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<RpcException>(
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>An in-scope <c>AddBufferedItem</c> still reaches the worker.</summary>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// Every <see cref="MxCommandKind"/> 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.
|
||||||
|
/// </summary>
|
||||||
|
[Fact]
|
||||||
|
public void EveryCommandKind_IsClassifiedExactlyOnceForConstraintEnforcement()
|
||||||
|
{
|
||||||
|
HashSet<MxCommandKind> refusedOnInvoke =
|
||||||
|
[
|
||||||
|
MxCommandKind.SubscribeAlarms,
|
||||||
|
MxCommandKind.UnsubscribeAlarms,
|
||||||
|
MxCommandKind.AcknowledgeAlarm,
|
||||||
|
MxCommandKind.QueryActiveAlarms,
|
||||||
|
MxCommandKind.AcknowledgeAlarmByName,
|
||||||
|
MxCommandKind.UpdateAlarmWatchList,
|
||||||
|
];
|
||||||
|
|
||||||
|
foreach (MxCommandKind kind in Enum.GetValues<MxCommandKind>())
|
||||||
|
{
|
||||||
|
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.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// <summary>
|
||||||
|
/// A kind on neither list — a gateway-internal alarm kind, or a value the switch has never
|
||||||
|
/// seen — is refused with <see cref="StatusCode.PermissionDenied"/> and an audited denial
|
||||||
|
/// even for an unconstrained key, and never reaches the worker.
|
||||||
|
/// </summary>
|
||||||
|
/// <param name="kindValue">Numeric <see cref="MxCommandKind"/> value.</param>
|
||||||
|
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||||
|
[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<RpcException>(
|
||||||
|
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 ===
|
// === Helpers ===
|
||||||
|
|
||||||
private static MxAccessGatewayService CreateService(
|
private static MxAccessGatewayService CreateService(
|
||||||
|
|||||||
Reference in New Issue
Block a user