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
+26
View File
@@ -277,6 +277,32 @@ that drops on full, so per-item events let a single low-privilege key flush
every other pending audit record with one large bulk command. Secured values
and raw credentials are never logged.
## Session Ownership
Scopes say what verbs a key may use; they do not say whose sessions it may use
them on. Every session-scoped RPC is therefore also **owner-scoped**.
`OpenSession` records the caller's key id as `GatewaySession.OwnerKeyId`, and
`StreamEvents`, `Invoke` (every command kind) and `CloseSession` refuse a caller
whose key id differs with `PermissionDenied`, before the session manager or the
worker is reached. The compare is ordinal, and a `null` owner (a session opened
with authentication disabled) matches only a `null` caller key.
`MxAccessGatewayService.EnsureOwner` holds the check for `Invoke` and
`CloseSession`; `EventStreamService` holds the same check for the stream attach.
Without the owner rule, knowing a session id plus a matching scope would be
enough. Session ids appear on the dashboard Sessions pages and in logs, so an
`events:read` key could call `Invoke(DrainEvents)` on another key's session and
dequeue its events (which the owner's stream then never sees), and an
`invoke:write` key could write through it.
There is **no `admin` override**: an `admin`-scoped key is refused like any
other foreign key. Operators close or kill other keys' sessions from the
dashboard, which calls `ISessionManager` directly. Internal callers (the alarm
monitor, the dashboard live read) go through `ISessionManager` as well and are
not affected. The session-less alarm RPCs (`AcknowledgeAlarm`, `StreamAlarms`,
`QueryActiveAlarms`) and the Galaxy Repository RPCs have no session and so no
owner to check.
## Scope Catalog
`GatewayScopes` is the single source of truth for scope strings. Every entry is currently mapped by either the resolver or another security component:
+15 -1
View File
@@ -94,7 +94,21 @@ the caller's key id matches the owner. Gating on the `events:read` scope alone w
rejected: it would let any `events:read`-scoped key that learned a session id
attach to another key's retained session and receive its replayed and live data. The check
runs before any subscriber is attached, so a foreign key never touches the
replay ring. Admin-scope override is deferred.
replay ring.
Decision (2026-12-03, SES-002 / #241): the owner rule covers every
session-scoped RPC, not just the stream. `Invoke` (every command kind) and
`CloseSession` apply the same ordinal compare as `StreamEvents` and return
`PermissionDenied` to a foreign key before the session manager is reached.
Owner-scoping only the stream left `Invoke(DrainEvents)` — which needs only
`events:read` and dequeues from the same worker queue the event pump drains — as
a way to read another key's events, and let a foreign key write through, or
close, a session it did not open. There is **no admin override**: an
`admin`-scoped key is refused like any other foreign key. Operators close or
kill any session from the dashboard, which calls `ISessionManager` directly and
does not pass through the gRPC owner check; a gRPC override would be a separate,
explicit, audited feature. Internal callers (the alarm monitor, the dashboard)
use `ISessionManager` directly and are unaffected.
## Event Subscribers
+1 -1
View File
@@ -333,7 +333,7 @@ While the gateway is stopping, clients see three different outcomes. An in-fligh
The pipeline has four stages:
1. The session is resolved via `sessionManager.TryGetSession`. A miss raises `SessionManagerException(SessionNotFound)` so the handler reports `StatusCode.NotFound`.
2. The attach is owner-scoped: the caller's API key id must match the key that opened the session, or the call fails with `PermissionDenied` before anything is attached or delivered.
2. The attach is owner-scoped: the caller's API key id must match the key that opened the session, or the call fails with `PermissionDenied` before anything is attached or delivered. `Invoke` and `CloseSession` apply the same check (see [Authorization](./Authorization.md#session-ownership)).
3. The call registers a subscriber on the distributor. A fresh stream (`after_worker_sequence == 0`) uses `session.AttachEventSubscriber(...)`. A resume uses `session.AttachEventSubscriberWithReplay(...)`, which snapshots the replay ring for events newer than the cursor and registers the live subscriber under one lock, so the replay-to-live handoff has no gap and no duplicate. In single-subscriber mode (the default) a second attach fails with `EventSubscriberAlreadyActive`; with `Sessions:AllowMultipleEventSubscribers` enabled, an attach beyond `MaxEventSubscribersPerSession` fails with `EventSubscriberLimitReached`. Both map to `ResourceExhausted`. The lease is released in the `finally` block, so the subscriber slot is freed even when the client cancels mid-stream.
4. The call yields events from the lease's bounded channel (capacity `Events:QueueCapacity`). When the request set `emit_stream_attached` it first yields the StreamAttached sentinel — after step 3, so the client's receipt of it proves the subscriber is registered (see [Sessions](./Sessions.md#attach-acknowledgement)). On a resume it then yields a `ReplayGap` sentinel when the cursor predates the oldest retained event, then the replayed batch, then live events filtered to sequences above the last replayed one. Per-session ordering is preserved end-to-end, because the pump is the single writer to each subscriber channel and writes in `WorkerSequence` order.
+2 -2
View File
@@ -165,7 +165,7 @@ public sealed record SessionCloseResult(
| `SessionLimitExceeded` | `MaxSessions` is in use. |
| `OpenFailed` | `OpenSessionAsync` failed; the inner exception carries the cause. A caller-cancelled open and an open refused because the gateway is stopping do not use this code. |
| `CloseFailed` | A close started but did not complete cleanly — the worker's graceful shutdown and the kill fall-back both failed (or a kill threw); the session is removed and faulted. A shutdown failure whose kill succeeded is a successful close, not this. |
| `PermissionDenied` | The caller may not perform the operation on this session (for example, attaching `StreamEvents` to a session opened by a different API key). |
| `PermissionDenied` | The caller may not perform the operation on this session (for example, attaching `StreamEvents`, calling `Invoke` or calling `CloseSession` on a session opened by a different API key). |
| `GatewayStopping` | The gateway is stopping and refuses new sessions (see [Shutdown Coordination](#shutdown-coordination)). Maps to gRPC `Unavailable`; not recorded as a fault. |
## Lifecycle
@@ -282,7 +282,7 @@ Four deliberate limits keep the rule from catching legitimate sessions. It appli
A client that drops mid-stream reconnects by re-issuing `StreamEvents` with `StreamEventsRequest.after_worker_sequence` set to the last `worker_sequence` it observed. A non-zero `after_worker_sequence` means *resume*; `0` means *fresh stream* and behaves exactly as a first-time subscribe — no replay, no sentinel.
**Owner-scoped attach (security control).** `OpenSession` records the caller's API key id on the session as `GatewaySession.OwnerKeyId`. Every `StreamEvents` attach and reattach is owner-checked: `EventStreamService.StreamEventsAsync` compares the caller's key id (threaded from `GatewayGrpcAuthorizationInterceptor` via `MxAccessGatewayService.StreamEvents`) to the session owner and throws `SessionManagerException(PermissionDenied)` — surfaced as gRPC `PermissionDenied` — when they differ, before any subscriber is attached and before any replayed or live event is delivered. Possessing the `events:read` scope and knowing a session id is not enough. This is what makes the default-on detach-grace and replay-retention windows safe: without the check, any `events:read`-scoped key that learned a session id could attach to another key's retained session and receive its replayed and live data. A `null` owner (session opened with authentication disabled) matches only a `null` caller key.
**Owner-scoped attach (security control).** `OpenSession` records the caller's API key id on the session as `GatewaySession.OwnerKeyId`. Every `StreamEvents` attach and reattach is owner-checked: `EventStreamService.StreamEventsAsync` compares the caller's key id (threaded from `GatewayGrpcAuthorizationInterceptor` via `MxAccessGatewayService.StreamEvents`) to the session owner and throws `SessionManagerException(PermissionDenied)` — surfaced as gRPC `PermissionDenied` — when they differ, before any subscriber is attached and before any replayed or live event is delivered. Possessing the `events:read` scope and knowing a session id is not enough. This is what makes the default-on detach-grace and replay-retention windows safe: without the check, any `events:read`-scoped key that learned a session id could attach to another key's retained session and receive its replayed and live data. A `null` owner (session opened with authentication disabled) matches only a `null` caller key. `MxAccessGatewayService.Invoke` (every command kind, `DrainEvents` included) and `CloseSession` apply the same ordinal owner check through `EnsureOwner`, so a foreign key can neither drain, write through nor close the session. There is no `admin` override; see [Design Decisions](./DesignDecisions.md).
On a resume, `EventStreamService.StreamEventsAsync` attaches through `GatewaySession.AttachEventSubscriberWithReplay`, which calls `SessionEventDistributor.RegisterWithReplay`. That method snapshots the session's replay ring for events newer than `after_worker_sequence` **and** registers the live subscriber inside a single `_replayLock` critical section. This atomicity is what makes the replay→live handoff free of gaps and duplicates: the pump appends each event to the replay ring (under `_replayLock`) before fanning it to subscriber channels, so relative to that one critical section every event is either in the replay snapshot or fanned into the freshly-registered live channel — never both observably, never neither.