Merge fix/review-2026-12-phase0 (2026-12-02 review fix plan)

This commit is contained in:
Joseph Doherty
2026-12-03 10:18:42 -05:00
35 changed files with 2261 additions and 76 deletions
+12 -4
View File
@@ -104,7 +104,12 @@ library:
it after writing the cache entry (set-then-recheck); a revoke that lands while a
verification is still in flight in the inner library therefore discards that
verification's repopulation instead of re-caching the just-revoked identity for a
full TTL (SEC-34). The short TTL remains the backstop for two bounded-staleness
full TTL (SEC-34). The same revoke/rotate/delete also calls
`ApiKeyStreamRegistry.Revoke(keyId)`, which ends every streaming call the key
already has open (SEC-004): a streaming call is authenticated once, at open, so
evicting the cache alone left an open `StreamEvents`, `StreamAlarms` or
`WatchDeployEvents` delivering data until the client disconnected. See
[Authorization](./Authorization.md#streaming-calls-and-revocation). The short TTL remains the backstop for two bounded-staleness
windows it cannot close directly: (1) out-of-band mutations (a direct DB edit, or a
revoke run by the separate `apikey` CLI process, whose in-memory cache is not the
running gateway's cache); and (2) a key whose `ExpiresUtc` passes while cached keeps
@@ -141,7 +146,7 @@ Failures are never cached — a wrong secret always reaches the store — so the
failure path is shielded by `ApiKeyFailureLimiter` instead, consulted before
`VerifyAsync` runs. It counts failures over one sliding
`MxGateway:Security:ApiKeyFailureWindowSeconds` window in two layers: a composite
`(transport peer, key id)` partition capped at `ApiKeyFailureLimit`, and a
`(remote IP, key id)` partition capped at `ApiKeyFailureLimit`, and a
per-key-id aggregate across all peers capped at `ApiKeyFailureAggregateLimit`. The
key id never partitions on its own — it is public, so an attacker-supplied one
would otherwise let any peer throttle a key it does not hold — and it joins the
@@ -153,8 +158,11 @@ the cross-peer aggregate: its failures still feed and consult the key-id aggrega
whose own cardinality is bounded by the configured LRU cap. An over-limit state admits one probe per
`ApiKeyFailureProbeIntervalSeconds` through to the real verifier and refuses
everything else with `ResourceExhausted` before the store read, so a legitimate
holder presenting the correct secret always reaches the constant-time compare and
resets both layers; the counter's LRU eviction (`ApiKeyFailureTrackedPeers`)
holder presenting the correct secret always reaches the constant-time compare. A
success clears the caller's own partition and exempts its address from the key's
aggregate for one window, but leaves the aggregate itself to decay, and a cached
success skips the limiter altogether (see [Authorization](./Authorization.md));
the counter's LRU eviction (`ApiKeyFailureTrackedPeers`)
prefers expired windows and will not drop an over-limit partition below a 2x
overshoot ceiling, so the memory bound cannot be turned into a way to clear an
active block. See [Authorization](./Authorization.md) for the enforcement path.
+70 -6
View File
@@ -96,13 +96,35 @@ The status codes are deliberately distinct: `Unauthenticated` signals "we do not
Before the verification store read, the helper asks a cheap in-process failure counter (`ApiKeyFailureLimiter`) whether the attempt may proceed, so online guessing of API-key secrets cannot spend a SQLite read (and, in a naive design, a cache miss) per attempt. The counter has two layers over one sliding `ApiKeyFailureWindowSeconds` window:
- **Composite `(transport peer, key id)` partitions.** Reaching `MxGateway:Security:ApiKeyFailureLimit` failures binds the throttle to the address that produced them. The key id alone is never the partition: key ids are not secret — they ride in every token and are listed on the dashboard — so keying on them let any network peer deny a key to its legitimate holder. The key id joins the partition only after a token-shape check (literal `mxgw` prefix, at least three non-empty `_` segments, key id of at most 64 characters), and one address may mint at most 32 key-id partitions before the overflow collapses onto that address's fallback partition.
- **Composite `(remote IP, key id)` partitions.** Reaching `MxGateway:Security:ApiKeyFailureLimit` failures binds the throttle to the address that produced them. The address is the client's IP with the source port stripped (`ApiKeyThrottlePeer`): the port is ephemeral, and keying on it made every new TCP connection a fresh partition, so a client could send `limit - 1` bad secrets, reconnect, and repeat without ever being throttled (SEC-001). The gRPC interceptor (parsing `ServerCallContext.Peer`) and the `/metrics` handler (`Connection.RemoteIpAddress`) normalise through the same helper, with IPv4-mapped IPv6 reduced to IPv4, so a failure on either surface counts against the same partition. The key id alone is never the partition: key ids are not secret — they ride in every token and are listed on the dashboard — so keying on them let any network peer deny a key to its legitimate holder. The key id joins the partition only after a token-shape check (literal `mxgw` prefix, at least three non-empty `_` segments, key id of at most 64 characters), and one address may mint at most 32 key-id partitions before the overflow collapses onto that address's fallback partition.
- **A per-key-id aggregate** across all peers (`ApiKeyFailureAggregateLimit`, default 30), which bounds a distributed or source-rotating sprayer that never trips any single partition.
An over-limit state is a valve, not a wall: one request per `ApiKeyFailureProbeIntervalSeconds` (default 5 s) is admitted through to the real verifier, and everything else is refused with `StatusCode.ResourceExhausted` before the store read. The slot is claimed atomically, so a burst arriving together at an interval boundary still yields exactly one admission, and a slot claimed for a request that a later layer then refuses is handed back under a per-state version stamp — never by timestamp comparison, which collides whenever a concurrent failure re-arms the same state on the same clock tick. A successful verification resets both layers — which is why the reset path stays reachable while a key is under active spray. One exception: when the caller's key id was collapsed into its address's shared fallback partition by the per-peer cap, a success clears the key's aggregate but leaves that shared partition alone, since it also holds failures contributed by other key ids from the same address. The tracked partitions form a bounded LRU (`ApiKeyFailureTrackedPeers`) whose eviction prefers fully expired windows and never removes an over-limit partition below a 2x transient overshoot ceiling, so the cap bounds memory without becoming a reset button for an active block. `ResourceExhausted` reveals only that throttling is in effect, not whether any particular secret was valid, preserving the opaque-failure property. Refusals increment `mxgateway.auth.throttled`, tagged `stage=peer|aggregate` and nothing else — `/metrics` is anonymous by default (`MxGateway:Metrics:RequireAuthentication` is opt-in), so neither key ids nor peer addresses may appear there.
An over-limit state is a valve, not a wall: one request per `ApiKeyFailureProbeIntervalSeconds` (default 5 s) is admitted through to the real verifier, and everything else is refused with `StatusCode.ResourceExhausted` before the store read. The slot is claimed atomically, so a burst arriving together at an interval boundary still yields exactly one admission, and a slot claimed for a request that a later layer then refuses is handed back under a per-state version stamp — never by timestamp comparison, which collides whenever a concurrent failure re-arms the same state on the same clock tick. A successful verification clears the caller's own `(remote IP, key id)` partition and marks that pair verified for one window; it does **not** clear the key id's cross-peer aggregate, which decays by window expiry only (SEC-003). Clearing the aggregate on success meant a key in steady use — many successful calls a second — never accumulated one, so a sprayer guessing that key id from other addresses was bounded by neither layer. When the caller's key id was collapsed into its address's shared fallback partition by the per-peer cap, a success leaves that shared partition alone too, since it also holds failures contributed by other key ids from the same address.
Two rules keep the holder of the correct secret from being denied by a spray against its public key id (SEC-002). First, the interceptor (and the `/metrics` handler) consult the verification cache **before** the limiter: a cached success (`IApiKeyVerificationCache`, implemented by `CachingApiKeyVerifier`) is proof of the correct token and costs no store read — the only thing the limiter protects — so it skips the limiter entirely. Second, on a cache miss, an address that verified the key inside the window skips the aggregate layer, so the holder does not have to win the probe slot against the sprayer once its cache entry expires. Neither path is reachable without the correct secret; a new address presenting the correct secret while the aggregate is tripped still goes through the probe slot once, then is exempt. The tracked partitions form a bounded LRU (`ApiKeyFailureTrackedPeers`) whose eviction prefers fully expired windows and never removes an over-limit partition below a 2x transient overshoot ceiling, so the cap bounds memory without becoming a reset button for an active block. `ResourceExhausted` reveals only that throttling is in effect, not whether any particular secret was valid, preserving the opaque-failure property. Refusals increment `mxgateway.auth.throttled`, tagged `stage=peer|aggregate` and nothing else — `/metrics` is anonymous by default (`MxGateway:Metrics:RequireAuthentication` is opt-in), so neither key ids nor peer addresses may appear there.
The dashboard login surface is throttled independently: `POST /auth/login` carries a fixed-window ASP.NET Core rate-limiter policy keyed per remote IP (`MxGateway:Security:LoginRateLimit*`), rejecting a burst with HTTP 429 before the LDAP bind is relayed to the directory. See [GatewayConfiguration](./GatewayConfiguration.md#security-options).
### Streaming calls and revocation
A streaming call is authenticated once, when it opens. To keep a revoked key from
holding a stream open indefinitely (SEC-004), the interceptor registers every
streaming call (server, client and duplex) in `ApiKeyStreamRegistry` under the
caller's key id, and hands the handler a `RevocableServerCallContext`: the real call
context with a cancellation token that also fires when the key is revoked. The
dashboard API Keys page calls `ApiKeyStreamRegistry.Revoke(keyId)` on Revoke, Rotate
and Delete, right after it evicts the verification cache. The handler stops on its
token as it would for a client cancel, and the interceptor reports the end of the
call as `Unauthenticated` — the status a new call with that key now gets — whatever
status the handler mapped its cancellation to. Rotate ends the key's streams too,
since they were opened with the secret the rotation retires; the client reconnects
with the new secret. Unary calls are not tracked: they complete within the command
timeout.
Only revocations made inside the gateway process reach the registry. A key revoked
by the separate `apikey` CLI process keeps its open streams until they reconnect,
the same out-of-band window its verification-cache entry has.
## Scope Resolution
`GatewayGrpcScopeResolver` is a stateless singleton that switches on the runtime request type. Top-level RPC requests map directly:
@@ -249,10 +271,26 @@ page create dialog (see
[Gateway Dashboard Design](./GatewayDashboardDesign.md#api-keys-page)). The
dashboard API Keys page also renders each key's effective constraints.
The service checks read constraints for `AddItem`, `AddItem2`, `AddItemBulk`,
`SubscribeBulk`, `AdviseItemBulk`, and `ReadBulk`. It checks write constraints
for `Write`, `Write2`, `WriteSecured`, `WriteSecured2`, `WriteBulk`,
`Write2Bulk`, `WriteSecuredBulk`, and `WriteSecured2Bulk`. Bulk commands run
The service checks read constraints for `AddItem`, `AddItem2`,
`AddBufferedItem`, `AddItemBulk`, `SubscribeBulk`, `AdviseItemBulk`, and
`ReadBulk`. It checks write constraints for `Write`, `Write2`, `WriteSecured`,
`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`,
`WriteBulkConstraintPlan`, `SubscribeBulkConstraintPlan`), which preserves the
caller's input order: each entry is evaluated against the constraint surface,
@@ -277,6 +315,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
+2 -2
View File
@@ -458,9 +458,9 @@ model requires otherwise.
| `MxGateway:Security:ApiKeyLastUsedCoalesceSeconds` | `60` | Coalescing window, in seconds, for the `last_used_utc` write. The library verifier writes `last_used` on every successful verification; this bounds the write to at most one per key per window, so a hammered key does not churn the WAL. `0` forwards every write. Must be zero or greater. |
| `MxGateway:Security:LoginRateLimitPermitLimit` | `10` | Maximum `POST /auth/login` attempts permitted per remote IP within `LoginRateLimitWindowSeconds` before requests are rejected with HTTP 429. Throttles LDAP credential stuffing before the bind is relayed to the directory. Must be greater than zero. |
| `MxGateway:Security:LoginRateLimitWindowSeconds` | `60` | Fixed-window length, in seconds, for the per-IP login rate limit. Must be greater than zero. |
| `MxGateway:Security:ApiKeyFailureLimit` | `10` | Failed API-key verifications, per `(transport peer, key id)` partition, within `ApiKeyFailureWindowSeconds` that trip the in-process short-circuit. Once tripped, the gRPC auth path rejects further attempts from that partition with `ResourceExhausted` **before** the store read — except for the probe admitted every `ApiKeyFailureProbeIntervalSeconds` — and a successful verification resets the partition. The partition always includes the sender's transport address: key ids are public (they ride in every token and are listed on the dashboard), so keying on the key id alone let any peer deny a key to its legitimate holder. Must be greater than zero. |
| `MxGateway:Security:ApiKeyFailureLimit` | `10` | Failed API-key verifications, per `(remote IP, key id)` partition (the source port is not part of it), within `ApiKeyFailureWindowSeconds` that trip the in-process short-circuit. Once tripped, the gRPC auth path rejects further attempts from that partition with `ResourceExhausted` **before** the store read — except for the probe admitted every `ApiKeyFailureProbeIntervalSeconds` — and a successful verification resets the partition. The partition always includes the sender's transport address: key ids are public (they ride in every token and are listed on the dashboard), so keying on the key id alone let any peer deny a key to its legitimate holder. Must be greater than zero. |
| `MxGateway:Security:ApiKeyFailureWindowSeconds` | `60` | Sliding-window length, in seconds, over which API-key verification failures are counted, for both the per-partition and the per-key-id aggregate layer. Must be greater than zero. |
| `MxGateway:Security:ApiKeyFailureAggregateLimit` | `30` | Failed verifications for one key id counted across **all** transport peers within `ApiKeyFailureWindowSeconds` before that key id enters probe mode. This second layer bounds a distributed or source-rotating sprayer that never trips any single `(peer, key id)` partition. `0` disables the aggregate layer, leaving only per-partition counting. Must be zero or greater. |
| `MxGateway:Security:ApiKeyFailureAggregateLimit` | `30` | Failed verifications for one key id counted across **all** transport peers within `ApiKeyFailureWindowSeconds` before that key id enters probe mode. This second layer bounds a distributed or source-rotating sprayer that never trips any single `(remote IP, key id)` partition. A successful verification does not clear it (it decays by window); addresses that verified the key inside the window, and cached verifications, are exempt so the holder is never locked out. `0` disables the aggregate layer, leaving only per-partition counting. Must be zero or greater. |
| `MxGateway:Security:ApiKeyFailureProbeIntervalSeconds` | `5` | Minimum interval, in seconds, between probe admissions for an over-limit partition or key-id aggregate. An over-limit state is a valve rather than a wall: one request per interval reaches the real verifier — exactly one, even when a burst arrives together at the interval boundary — so the holder of the correct secret always gets through and clears the state, while everything else is still refused before the store read. `0` blocks absolutely instead — **not recommended**, because an unauthenticated peer can then deny the key to its holder for the whole window. Must be zero or greater. |
| `MxGateway:Security:AuditRetentionDays` | `90` | Days of canonical audit history kept in the `audit_event` table. The audit drain sweeps once at startup and hourly thereafter, deleting rows older than this window; without it the table grows without bound inside the same SQLite file the authentication hot path reads. Rows whose timestamp SQLite cannot parse are never swept. Must be greater than zero — retention can be widened but not switched off. |
| `MxGateway:Security:ApiKeyFailureTrackedPeers` | `4096` | Maximum distinct partitions tracked by the failure counter (a bounded LRU) so a spray of unique tokens cannot grow memory without limit. It cannot be used to flush an active block either: only a validly shaped `mxgw_<keyId>_<secret>` token mints a key-id partition (everything else lands on the sender's transport-peer partition), each address may mint at most 32 key-id partitions before the overflow collapses onto that address's fallback partition, and eviction prefers fully expired windows, never removing an over-limit partition until the map exceeds twice this cap. Must be greater than zero. |
+38 -3
View File
@@ -627,6 +627,15 @@ policy `AlarmsHub` carries — the two read one central monitor and must not dis
may see it — and the side rail hides the Alarms link for callers the policy denies. What a
permitted caller sees is galaxy-wide and not tag-scoped; see "Alarm-feed visibility".
The attribute is enforced on both routes into the page. A full HTTP request meets endpoint
authorization. An in-circuit navigation (an in-page link, or `Blazor.navigateTo` from the
console) issues no HTTP request, so `Routes.razor` renders pages through `AuthorizeRouteView`,
which evaluates the page's `[Authorize]` attribute against the circuit's principal and renders a
"Not Authorized" panel instead. Before DSH-001 (#243) the router used a plain `RouteView`, so an
anonymous-localhost caller could reach this page, and a Viewer could reach the mounted Secrets
page (`/admin/secrets`, `secrets:manage`) and its secret-metadata list, by navigating inside an
existing circuit.
### Live data source
Both the Browse subscription panel and the Alarms page read live MXAccess data
@@ -720,6 +729,9 @@ anonymous localhost session shows the same read-only view.
old one. Active keys only — rotating a revoked key would un-revoke it, so
the button is not shown on revoked rows.
- **Revoke** marks a key revoked; a revoked key cannot be un-revoked.
Revoke, Rotate and Delete also end every streaming gRPC call the key
already has open (`ApiKeyStreamRegistry`, SEC-004); the client sees
`Unauthenticated`.
- **Delete** permanently removes a key row from the auth database, but only
when the key is already revoked. `IApiKeyAdminStore.DeleteAsync` rejects
active keys (returns false) so the revoke event lands in the audit log
@@ -817,8 +829,10 @@ they do not use.
The in-process page feeds carry no authentication of their own, and need none:
`MapRazorComponents<App>()` applies `RequireAuthorization(ViewerPolicy)` to the
component endpoints, so a page can only run inside a circuit whose principal is
already an authorized Viewer. The hub-token flow below therefore covers only the
remote hub surface.
already an authorized Viewer. Pages with a stricter `[Authorize]` attribute (Alarms,
the mounted Secrets page) are re-checked by `AuthorizeRouteView` on every in-circuit
navigation, because that navigation never reaches the endpoint. The hub-token flow
below therefore covers only the remote hub surface.
Neither policy scopes a Viewer to particular sessions — that is
`IDashboardSessionAcl`'s job (SEC-25 / TST-15), consulted by both subscribe seams:
@@ -962,15 +976,36 @@ dashboard mints short-lived bearer tokens for the connection:
it must never be request-logged (see the remarks on
`HubTokenAuthenticationHandler`).
4. `HubTokenAuthenticationHandler` validates the protected payload and
rebuilds the `ClaimsPrincipal` with the carried roles.
rebuilds the `ClaimsPrincipal` with the carried roles, and stamps the
token's expiry on the authentication ticket (`ExpiresUtc`).
5. The hubs' `[Authorize(Policy = HubClientsPolicy)]` accepts the resulting
identity.
6. Every hub is mapped with `CloseOnAuthenticationExpiration`, so SignalR closes
the connection when that ticket expires (DSH-006). Before this, the 5-minute
lifetime bounded only the handshake: an open socket kept the roles and tag
grants it connected with for as long as it stayed up, and each later
`SubscribeSession` on it was decided from those frozen claims. A
cookie-authenticated hub connection closes at the cookie ticket's expiry the
same way. The client reconnects with a freshly minted token.
There is no in-repo hub client: the helper that once wrapped `HubConnectionBuilder`
for a circuit was deleted when the pages moved to the in-process seams. An external
client re-fetches `/hubs/token` on every (re)connect itself, which is what makes the
short 5-minute lifetime transparent.
Blazor circuits have the same capture-once problem — a circuit takes its principal
from the HTTP request that started it and an open tab sends no further requests — so
the dashboard replaces the default `ServerAuthenticationStateProvider` with
`DashboardRevalidatingAuthenticationStateProvider` (DSH-006). Every minute it signs
the circuit out (anonymous state) when the circuit is older than the cookie's 8-hour
idle lifetime, or when the principal holds a role that its LDAP group claims no
longer map to under the current `Dashboard:GroupToRole`. Pages under
`AuthorizeRouteView` then re-render as not authorized, and admin actions, which read
the provider at action time, are refused. A change to the user's LDAP group
membership and a sign-out in another tab are not observable there (no server-side
session, no password to re-bind with); they take effect at the age limit or on
reconnect. The `DisableLogin` dev bypass is never signed out.
Caveat — logout does not revoke outstanding tokens. Logout clears the dashboard
cookie, but hub bearer tokens are self-contained, data-protection-encrypted, and
carry no server-side revocation state (no jti denylist). A token captured before
+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.