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:
@@ -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<MxAccessGatewayService> logger,
|
||||
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 />
|
||||
public override async Task<OpenSessionReply> 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,
|
||||
|
||||
@@ -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) ===
|
||||
|
||||
/// <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 ===
|
||||
|
||||
private static MxAccessGatewayService CreateService(
|
||||
|
||||
Reference in New Issue
Block a user