fix(grpc): owner-scope Invoke and CloseSession like StreamEvents (SES-002, #241)
A foreign API key holding the matching scope could Invoke(DrainEvents) another key's session (dequeuing its events), write through it, or close it. Invoke and CloseSession now apply the same ordinal owner compare as the StreamEvents attach and return PermissionDenied. No admin override (D2): operators use the dashboard, which calls ISessionManager directly.
This commit is contained in:
@@ -83,6 +83,14 @@ public sealed class MxAccessGatewayService(
|
||||
try
|
||||
{
|
||||
requestValidator.ValidateCloseSession(request);
|
||||
|
||||
// Owner-scoped close: only the key that opened the session may close it. An unknown id
|
||||
// falls through so the session manager reports SessionNotFound exactly as before.
|
||||
if (sessionManager.TryGetSession(request.SessionId, out GatewaySession? session) && session is not null)
|
||||
{
|
||||
EnsureOwner(session);
|
||||
}
|
||||
|
||||
SessionCloseResult result = await sessionManager
|
||||
.CloseSessionAsync(request.SessionId, context.CancellationToken)
|
||||
.ConfigureAwait(false);
|
||||
@@ -115,6 +123,7 @@ public sealed class MxAccessGatewayService(
|
||||
// would duplicate InvokeAsync's fault mapping (SessionNotFound / state checks / metrics)
|
||||
// at a second entry point — deliberately not worth it until a profile says otherwise.
|
||||
GatewaySession session = ResolveSession(request.SessionId);
|
||||
EnsureOwner(session);
|
||||
MxCommand command = request.Command;
|
||||
BulkConstraintPlan? bulkConstraintPlan = await ApplyConstraintsAsync(
|
||||
session,
|
||||
@@ -335,6 +344,25 @@ public sealed class MxAccessGatewayService(
|
||||
return session;
|
||||
}
|
||||
|
||||
// Owner-scoped session RPCs (security control, SES-002): Invoke and CloseSession act on a
|
||||
// session only for the API key that opened it — the same ordinal compare EventStreamService
|
||||
// applies to StreamEvents attach. Possessing the matching scope and knowing a session id is
|
||||
// not enough; without this, an events:read key could DrainEvents another key's queue, and an
|
||||
// invoke:write key could write through another key's session. There is deliberately no admin
|
||||
// override: operators close or kill any session from the dashboard, which calls
|
||||
// ISessionManager directly and never passes through here. A null owner (session opened with
|
||||
// authentication disabled) matches only a null caller key.
|
||||
private void EnsureOwner(GatewaySession session)
|
||||
{
|
||||
string? callerKeyId = identityAccessor.Current?.KeyId;
|
||||
if (!string.Equals(session.OwnerKeyId, callerKeyId, StringComparison.Ordinal))
|
||||
{
|
||||
throw new SessionManagerException(
|
||||
SessionManagerErrorCode.PermissionDenied,
|
||||
$"Session {session.SessionId} is owned by a different API key; session RPCs are owner-scoped.");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<BulkConstraintPlan?> ApplyConstraintsAsync(
|
||||
GatewaySession session,
|
||||
MxCommand command,
|
||||
|
||||
@@ -722,6 +722,127 @@ public sealed class MxAccessGatewayServiceTests
|
||||
Assert.Equal(expectedReason, exception.Trailers.GetValue(ResourceExhaustedReasons.TrailerKey));
|
||||
}
|
||||
|
||||
// === Owner-scoped session RPCs (SES-002, #241) ===
|
||||
|
||||
/// <summary>
|
||||
/// A foreign key — even one holding <c>admin</c> — cannot drain, write through or close
|
||||
/// another key's session: each call is refused with <c>PermissionDenied</c> before the
|
||||
/// session manager is reached, and the owner's session stays <c>Ready</c>.
|
||||
/// </summary>
|
||||
/// <param name="foreignScope">Scope the foreign key holds.</param>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Theory]
|
||||
[InlineData(GatewayScopes.EventsRead)]
|
||||
[InlineData(GatewayScopes.Admin)]
|
||||
public async Task SessionRpcs_FromForeignKey_ThrowPermissionDeniedAndLeaveSessionReady(string foreignScope)
|
||||
{
|
||||
GatewayRequestIdentityAccessor identityAccessor = new();
|
||||
FakeSessionManager sessionManager = new() { ResolveOnlySeededSessions = true };
|
||||
GatewaySession ownedSession = CreateOwnedSession("session-owned", ownerKeyId: "key-a");
|
||||
sessionManager.SeedSession(ownedSession);
|
||||
MxAccessGatewayService service = CreateService(sessionManager, identityAccessor);
|
||||
|
||||
using IDisposable identityScope = identityAccessor.Push(CreateIdentity("key-b", foreignScope));
|
||||
|
||||
MxCommandRequest drain = new()
|
||||
{
|
||||
SessionId = "session-owned",
|
||||
Command = new MxCommand { Kind = MxCommandKind.DrainEvents, DrainEvents = new DrainEventsCommand() },
|
||||
};
|
||||
MxCommandRequest write = new()
|
||||
{
|
||||
SessionId = "session-owned",
|
||||
Command = new MxCommand
|
||||
{
|
||||
Kind = MxCommandKind.Write,
|
||||
Write = new WriteCommand { ServerHandle = 1, ItemHandle = 2, Value = new MxValue { StringValue = "v" } },
|
||||
},
|
||||
};
|
||||
|
||||
RpcException drainException = await Assert.ThrowsAsync<RpcException>(
|
||||
async () => await service.Invoke(drain, new TestServerCallContext()));
|
||||
RpcException writeException = await Assert.ThrowsAsync<RpcException>(
|
||||
async () => await service.Invoke(write, new TestServerCallContext()));
|
||||
RpcException closeException = await Assert.ThrowsAsync<RpcException>(
|
||||
async () => await service.CloseSession(
|
||||
new CloseSessionRequest { SessionId = "session-owned" },
|
||||
new TestServerCallContext()));
|
||||
|
||||
Assert.Equal(StatusCode.PermissionDenied, drainException.StatusCode);
|
||||
Assert.Equal(StatusCode.PermissionDenied, writeException.StatusCode);
|
||||
Assert.Equal(StatusCode.PermissionDenied, closeException.StatusCode);
|
||||
Assert.Equal(0, sessionManager.InvokeCount);
|
||||
Assert.Equal(0, sessionManager.CloseCount);
|
||||
Assert.Equal(SessionState.Ready, ownedSession.State);
|
||||
}
|
||||
|
||||
/// <summary>The owning key still reaches Invoke and CloseSession on its own session.</summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task SessionRpcs_FromOwnerKey_ReachSessionManager()
|
||||
{
|
||||
GatewayRequestIdentityAccessor identityAccessor = new();
|
||||
FakeSessionManager sessionManager = new() { ResolveOnlySeededSessions = true };
|
||||
sessionManager.SeedSession(CreateOwnedSession("session-owned", ownerKeyId: "key-a"));
|
||||
MxAccessGatewayService service = CreateService(sessionManager, identityAccessor);
|
||||
|
||||
using IDisposable identityScope = identityAccessor.Push(CreateIdentity("key-a", GatewayScopes.InvokeRead));
|
||||
|
||||
await service.Invoke(CreatePingRequest("session-owned"), new TestServerCallContext());
|
||||
CloseSessionReply reply = await service.CloseSession(
|
||||
new CloseSessionRequest { SessionId = "session-owned" },
|
||||
new TestServerCallContext());
|
||||
|
||||
Assert.Equal(1, sessionManager.InvokeCount);
|
||||
Assert.Equal(1, sessionManager.CloseCount);
|
||||
Assert.Equal("session-owned", reply.SessionId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The owner compare is ordinal: a key id that differs only by case is a different key.
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task Invoke_FromKeyDifferingOnlyByCase_ThrowsPermissionDenied()
|
||||
{
|
||||
GatewayRequestIdentityAccessor identityAccessor = new();
|
||||
FakeSessionManager sessionManager = new() { ResolveOnlySeededSessions = true };
|
||||
sessionManager.SeedSession(CreateOwnedSession("session-owned", ownerKeyId: "key-a"));
|
||||
MxAccessGatewayService service = CreateService(sessionManager, identityAccessor);
|
||||
|
||||
using IDisposable identityScope = identityAccessor.Push(CreateIdentity("KEY-A", GatewayScopes.InvokeRead));
|
||||
|
||||
RpcException exception = await Assert.ThrowsAsync<RpcException>(
|
||||
async () => await service.Invoke(CreatePingRequest("session-owned"), new TestServerCallContext()));
|
||||
|
||||
Assert.Equal(StatusCode.PermissionDenied, exception.StatusCode);
|
||||
Assert.Equal(0, sessionManager.InvokeCount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// An authenticated key cannot act on a session opened with authentication disabled (a
|
||||
/// <see langword="null"/> owner matches only a <see langword="null"/> caller).
|
||||
/// </summary>
|
||||
/// <returns>A task that represents the asynchronous operation.</returns>
|
||||
[Fact]
|
||||
public async Task CloseSession_OnUnownedSessionFromAuthenticatedKey_ThrowsPermissionDenied()
|
||||
{
|
||||
GatewayRequestIdentityAccessor identityAccessor = new();
|
||||
FakeSessionManager sessionManager = new() { ResolveOnlySeededSessions = true };
|
||||
sessionManager.SeedSession(CreateOwnedSession("session-unowned", ownerKeyId: null));
|
||||
MxAccessGatewayService service = CreateService(sessionManager, identityAccessor);
|
||||
|
||||
using IDisposable identityScope = identityAccessor.Push(CreateIdentity("key-b", GatewayScopes.SessionClose));
|
||||
|
||||
RpcException exception = await Assert.ThrowsAsync<RpcException>(
|
||||
async () => await service.CloseSession(
|
||||
new CloseSessionRequest { SessionId = "session-unowned" },
|
||||
new TestServerCallContext()));
|
||||
|
||||
Assert.Equal(StatusCode.PermissionDenied, exception.StatusCode);
|
||||
Assert.Equal(0, sessionManager.CloseCount);
|
||||
}
|
||||
|
||||
private static MxAccessGatewayService CreateService(
|
||||
FakeSessionManager sessionManager,
|
||||
IGatewayRequestIdentityAccessor? identityAccessor = null,
|
||||
@@ -752,6 +873,37 @@ public sealed class MxAccessGatewayServiceTests
|
||||
Scopes: new HashSet<string>(StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
private static ApiKeyIdentity CreateIdentity(string keyId, string scope)
|
||||
{
|
||||
return new ApiKeyIdentity(
|
||||
KeyId: keyId,
|
||||
KeyPrefix: $"mxgw_{keyId}",
|
||||
DisplayName: keyId,
|
||||
Scopes: new HashSet<string>([scope], StringComparer.Ordinal));
|
||||
}
|
||||
|
||||
private static GatewaySession CreateOwnedSession(string sessionId, string? ownerKeyId)
|
||||
{
|
||||
GatewaySession session = new(
|
||||
sessionId,
|
||||
GatewayContractInfo.DefaultBackendName,
|
||||
"pipe",
|
||||
"nonce",
|
||||
"Owner Key",
|
||||
ownerKeyId,
|
||||
"operator-session",
|
||||
"client-correlation",
|
||||
TimeSpan.FromSeconds(7),
|
||||
TimeSpan.FromSeconds(30),
|
||||
TimeSpan.FromSeconds(10),
|
||||
TimeSpan.FromMinutes(5),
|
||||
DateTimeOffset.UtcNow);
|
||||
session.AttachWorkerClient(new FakeWorkerClient(1234));
|
||||
session.MarkReady();
|
||||
|
||||
return session;
|
||||
}
|
||||
|
||||
private static GatewaySession CreateSession(
|
||||
string sessionId,
|
||||
int processId)
|
||||
@@ -860,6 +1012,9 @@ public sealed class MxAccessGatewayServiceTests
|
||||
/// <summary>The number of times InvokeAsync was called.</summary>
|
||||
public int InvokeCount { get; private set; }
|
||||
|
||||
/// <summary>The number of times CloseSessionAsync was called.</summary>
|
||||
public int CloseCount { get; private set; }
|
||||
|
||||
/// <summary>The events the fake event stream service replays for this manager.</summary>
|
||||
public List<WorkerEvent> Events { get; } = [];
|
||||
|
||||
@@ -940,6 +1095,7 @@ public sealed class MxAccessGatewayServiceTests
|
||||
string sessionId,
|
||||
CancellationToken cancellationToken)
|
||||
{
|
||||
CloseCount++;
|
||||
return Task.FromResult(new SessionCloseResult(sessionId, SessionState.Closed, AlreadyClosed: false));
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user