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:
Joseph Doherty
2026-12-03 09:40:41 -05:00
parent d12fd4f5a0
commit cf00f6fc86
7 changed files with 229 additions and 5 deletions
@@ -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,