diff --git a/CLAUDE.md b/CLAUDE.md index e267c8b3..d0996ee9 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -176,7 +176,7 @@ External analysis sources referenced by design docs: Gateway gRPC clients authenticate with an API key in metadata: `authorization: Bearer mxgw__`. Keys are stored hashed (with a peppered SHA) in a gateway-owned SQLite DB (default `C:\ProgramData\MxGateway\gateway-auth.db`). Scopes (`session:open`, `session:close`, `invoke:read`, `invoke:write`, `invoke:secure`, `events:read`, `metadata:read`, `admin`) gate specific RPCs; missing → `Unauthenticated`, insufficient → `PermissionDenied`. The `apikey` subcommand on the server exe manages keys; see `src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/`. -Session event streaming is **owner-scoped**: the API key that opened a session is recorded on the session, and every `StreamEvents` attach/reattach is rejected with `PermissionDenied` unless the caller's key id matches the owner. Possessing the `events:read` scope and knowing a session id is not sufficient — this closes the reconnect/fan-out trust boundary (detach-grace and replay retention are on by default) so an `events:read`-scoped key cannot attach to another key's retained session. +Session RPCs are **owner-scoped**: the API key that opened a session is recorded on the session, and every `StreamEvents` attach/reattach, `Invoke` (every command kind, `DrainEvents` included) and `CloseSession` is rejected with `PermissionDenied` unless the caller's key id matches the owner (strict ordinal compare, **no `admin` override** — operators close or kill other keys' sessions from the dashboard, which calls `ISessionManager` directly). Possessing the matching scope and knowing a session id is not sufficient — this closes the reconnect/fan-out trust boundary (detach-grace and replay retention are on by default) so an `events:read`-scoped key cannot attach to, drain, write through or close another key's session. Dashboard auth is LDAP-backed (separate from the gRPC API-key model). `/login` binds against `MxGateway:Ldap` and maps the user's LDAP groups to `Admin` or `Viewer` via `MxGateway:Dashboard:GroupToRole`, then issues an HTTP-only secure cookie named `__Host-MxGatewayDashboard` when `Dashboard:RequireHttpsCookie` is true (default) and no `Dashboard:CookieName` override is set, else the plain `MxGatewayDashboard` (the `__Host-` prefix requires a Secure cookie). SignalR hubs at `/hubs/{snapshot,alarms,events}` accept either the cookie or a 5-minute bearer minted at `/hubs/token`; `/hubs/alarms` and the `/alarms` page additionally require a **real authenticated dashboard role** (`MxGateway.Dashboard.Alarms`, a requirement type the environment-bypass handler does not handle), because the alarm feed is gateway-central with no per-session provenance and so cannot be tag-scoped — its metadata stays galaxy-wide for authenticated Viewers, but anonymous localhost and `Authentication:Mode=Disabled` do not receive it at all. Dashboard event visibility is **tag-scoped per session** (`IDashboardSessionAcl`, gating both the events hub and the session-details page's in-process subscribe): an Administrator sees every session, while any other caller sees a session only when its tags — inherited from the owning API key's `apikey --dashboard-tags`, never from the client's request — intersect the tags their LDAP groups grant via `Dashboard:GroupToTag`. That grant is **re-resolved from the caller's LDAP group claims against current options on every subscribe** (not read from the tag claims stamped at login, which would outlive a config-revoked grant for the cookie's 8-hour sliding life); login-stamped tag claims are the fallback only for a principal carrying no group claims — i.e. the hub-token principal, whose grant the mint already re-resolved. Untagged sessions follow `Dashboard:UntaggedSessionVisibility` (default `AdminOnly`), and a principal with neither claim kind (anonymous localhost included) is an empty-grant Viewer. `Dashboard:AllowAnonymousLocalhost` (default `true`) grants **read-only** loopback access — it satisfies the Viewer requirement but never the Admin-only requirement, so anonymous localhost can view the dashboard but not reach API-key CRUD, session Close/Kill, or the alarm feed (`Authentication:Mode=Disabled` is scoped the same way). `Dashboard:DisableLogin` (default `false`) auto-authenticates every dashboard request — including remote browsers — as `Dashboard:AutoLoginUser` (default `multi-role`) with both Admin and Viewer roles; dev/test only, never enable in production. diff --git a/docs/Authorization.md b/docs/Authorization.md index 204b9f79..03827c04 100644 --- a/docs/Authorization.md +++ b/docs/Authorization.md @@ -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: diff --git a/docs/DesignDecisions.md b/docs/DesignDecisions.md index 3a82cbb6..340bb5c6 100644 --- a/docs/DesignDecisions.md +++ b/docs/DesignDecisions.md @@ -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 diff --git a/docs/Grpc.md b/docs/Grpc.md index b2c07582..5c0870df 100644 --- a/docs/Grpc.md +++ b/docs/Grpc.md @@ -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. diff --git a/docs/Sessions.md b/docs/Sessions.md index acea2952..35fafa55 100644 --- a/docs/Sessions.md +++ b/docs/Sessions.md @@ -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. diff --git a/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs b/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs index dcb509fd..63455c46 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs @@ -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 ApplyConstraintsAsync( GatewaySession session, MxCommand command, diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceTests.cs index 5bf444b5..2c8cd3d8 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceTests.cs @@ -722,6 +722,127 @@ public sealed class MxAccessGatewayServiceTests Assert.Equal(expectedReason, exception.Trailers.GetValue(ResourceExhaustedReasons.TrailerKey)); } + // === Owner-scoped session RPCs (SES-002, #241) === + + /// + /// A foreign key — even one holding admin — cannot drain, write through or close + /// another key's session: each call is refused with PermissionDenied before the + /// session manager is reached, and the owner's session stays Ready. + /// + /// Scope the foreign key holds. + /// A task that represents the asynchronous operation. + [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( + async () => await service.Invoke(drain, new TestServerCallContext())); + RpcException writeException = await Assert.ThrowsAsync( + async () => await service.Invoke(write, new TestServerCallContext())); + RpcException closeException = await Assert.ThrowsAsync( + 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); + } + + /// The owning key still reaches Invoke and CloseSession on its own session. + /// A task that represents the asynchronous operation. + [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); + } + + /// + /// The owner compare is ordinal: a key id that differs only by case is a different key. + /// + /// A task that represents the asynchronous operation. + [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( + async () => await service.Invoke(CreatePingRequest("session-owned"), new TestServerCallContext())); + + Assert.Equal(StatusCode.PermissionDenied, exception.StatusCode); + Assert.Equal(0, sessionManager.InvokeCount); + } + + /// + /// An authenticated key cannot act on a session opened with authentication disabled (a + /// owner matches only a caller). + /// + /// A task that represents the asynchronous operation. + [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( + 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(StringComparer.Ordinal)); } + private static ApiKeyIdentity CreateIdentity(string keyId, string scope) + { + return new ApiKeyIdentity( + KeyId: keyId, + KeyPrefix: $"mxgw_{keyId}", + DisplayName: keyId, + Scopes: new HashSet([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 /// The number of times InvokeAsync was called. public int InvokeCount { get; private set; } + /// The number of times CloseSessionAsync was called. + public int CloseCount { get; private set; } + /// The events the fake event stream service replays for this manager. public List 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)); }