diff --git a/CLAUDE.md b/CLAUDE.md index e267c8b3..d5a7f45a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -176,9 +176,9 @@ 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. +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`, and close a connection when its ticket expires (`CloseOnAuthenticationExpiration`); Blazor circuits are re-validated every minute (`DashboardRevalidatingAuthenticationStateProvider`: signed out past the cookie's 8-hour idle life or when a held role is no longer granted by `GroupToRole`); `/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. ## Process / Platform Notes diff --git a/docs/Authentication.md b/docs/Authentication.md index 0e77d1f4..5c0b2d3a 100644 --- a/docs/Authentication.md +++ b/docs/Authentication.md @@ -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. diff --git a/docs/Authorization.md b/docs/Authorization.md index 204b9f79..59439b54 100644 --- a/docs/Authorization.md +++ b/docs/Authorization.md @@ -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: 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/GatewayConfiguration.md b/docs/GatewayConfiguration.md index 076705f4..e54a7e34 100644 --- a/docs/GatewayConfiguration.md +++ b/docs/GatewayConfiguration.md @@ -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__` 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. | diff --git a/docs/GatewayDashboardDesign.md b/docs/GatewayDashboardDesign.md index 40e36bd4..402a50be 100644 --- a/docs/GatewayDashboardDesign.md +++ b/docs/GatewayDashboardDesign.md @@ -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()` 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 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/Dashboard/Components/Routes.razor b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Routes.razor index c5296533..f76a13fd 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Routes.razor +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/Components/Routes.razor @@ -1,7 +1,27 @@ +@* AuthorizeRouteView, not RouteView (DSH-001): the router is interactive, so a navigation that + starts inside a circuit never issues an HTTP request and never meets endpoint authorization. + Only AuthorizeRouteView evaluates a page's [Authorize] attribute on that path — the Alarms page + (AlarmsPolicy) and the shared Secrets page (secrets:manage) both rely on it. Pages without an + attribute are rendered as before; the endpoint ViewerPolicy still gates the initial request. *@ - + + + Dashboard - Not Authorized +
+

Not Authorized

+ @if (context.User.Identity?.IsAuthenticated == true) + { +

Your dashboard role does not grant access to this page.

+ } + else + { +

This page requires a signed-in dashboard role. Sign in

+ } +
+
+
diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardApiKeyManagementService.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardApiKeyManagementService.cs index 41e773bc..070b53b4 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardApiKeyManagementService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardApiKeyManagementService.cs @@ -18,7 +18,8 @@ public sealed class DashboardApiKeyManagementService( IApiKeyPepperProvider pepperProvider, IAuditWriter auditWriter, IHttpContextAccessor httpContextAccessor, - IApiKeyCacheInvalidator? cacheInvalidator = null) : IDashboardApiKeyManagementService + IApiKeyCacheInvalidator? cacheInvalidator = null, + ApiKeyStreamRegistry? streamRegistry = null) : IDashboardApiKeyManagementService { private const string UnauthorizedMessage = "Sign in with an authorized LDAP account to manage API keys."; private const string PepperNotConfiguredMessage = "API key pepper is not configured."; @@ -108,6 +109,10 @@ public sealed class DashboardApiKeyManagementService( cacheInvalidator?.Invalidate(normalizedKeyId); + // The cache eviction stops new calls; this ends the streams the key already has open + // (SEC-004), which were authenticated once at open and would otherwise keep delivering. + streamRegistry?.Revoke(normalizedKeyId); + await WriteDashboardAuditAsync( user, normalizedKeyId, @@ -151,6 +156,10 @@ public sealed class DashboardApiKeyManagementService( cacheInvalidator?.Invalidate(normalizedKeyId); + // The cache eviction stops new calls; this ends the streams the key already has open + // (SEC-004), which were authenticated once at open and would otherwise keep delivering. + streamRegistry?.Revoke(normalizedKeyId); + bool succeeded = rotated.Token is not null; await WriteDashboardAuditAsync( @@ -192,6 +201,10 @@ public sealed class DashboardApiKeyManagementService( cacheInvalidator?.Invalidate(normalizedKeyId); + // The cache eviction stops new calls; this ends the streams the key already has open + // (SEC-004), which were authenticated once at open and would otherwise keep delivering. + streamRegistry?.Revoke(normalizedKeyId); + await WriteDashboardAuditAsync( user, normalizedKeyId, diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAuthenticationDefaults.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAuthenticationDefaults.cs index 407a1876..6fd364fa 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAuthenticationDefaults.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAuthenticationDefaults.cs @@ -45,6 +45,13 @@ public static class DashboardAuthenticationDefaults /// public const string AlarmsPolicy = "MxGateway.Dashboard.Alarms"; + /// + /// Sliding idle lifetime of the dashboard login cookie. Also the longest a Blazor circuit keeps + /// its sign-in: the circuit issues no HTTP requests, so it cannot renew the cookie, and + /// signs it out at this age. + /// + public static readonly TimeSpan CookieIdleTimeout = TimeSpan.FromHours(8); + public const string LdapGroupClaimType = "mxgateway:ldap_group"; public const string KeyPrefixClaimType = "mxgateway:key_prefix"; diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardEndpointRouteBuilderExtensions.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardEndpointRouteBuilderExtensions.cs index 28f83581..93389986 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardEndpointRouteBuilderExtensions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardEndpointRouteBuilderExtensions.cs @@ -109,9 +109,14 @@ public static class DashboardEndpointRouteBuilderExtensions // events use HubClientsPolicy; AlarmsHub uses AlarmsPolicy, which additionally requires a // real authenticated dashboard role — see AlarmsHub for why the alarm feed is // gated harder than the session-scoped ones. - endpoints.MapHub("/hubs/snapshot"); - endpoints.MapHub("/hubs/alarms"); - endpoints.MapHub("/hubs/events"); + // CloseOnAuthenticationExpiration (DSH-006): a hub connection authenticates once, at the + // handshake, and keeps that principal for as long as the socket stays up. Closing it when + // the ticket expires — the hub token's 5 minutes, or the cookie ticket's expiry — makes a + // long-lived connection re-authenticate, so a revoked role or tag grant cannot outlive it. + // Remote clients already re-fetch /hubs/token on every (re)connect. + endpoints.MapHub("/hubs/snapshot", CloseOnAuthenticationExpiration); + endpoints.MapHub("/hubs/alarms", CloseOnAuthenticationExpiration); + endpoints.MapHub("/hubs/events", CloseOnAuthenticationExpiration); // Bearer-token mint endpoint. The cookie-authenticated browser hits // this from JS before opening a hub connection; the hub then accepts @@ -140,6 +145,11 @@ public static class DashboardEndpointRouteBuilderExtensions return endpoints; } + // Applied to every dashboard hub; internal so a test can assert the options each hub gets. + internal static void CloseOnAuthenticationExpiration( + Microsoft.AspNetCore.Http.Connections.HttpConnectionDispatcherOptions options) => + options.CloseOnAuthenticationExpiration = true; + private static async Task PostLoginAsync( HttpContext httpContext, IAntiforgery antiforgery, diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardRevalidatingAuthenticationStateProvider.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardRevalidatingAuthenticationStateProvider.cs new file mode 100644 index 00000000..afeac8e8 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardRevalidatingAuthenticationStateProvider.cs @@ -0,0 +1,116 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.Components.Server; +using Microsoft.Extensions.Options; +using ZB.MOM.WW.MxGateway.Server.Configuration; + +namespace ZB.MOM.WW.MxGateway.Server.Dashboard; + +/// +/// Re-checks a Blazor circuit's sign-in on a timer and signs the circuit out when it no longer +/// holds (DSH-006). +/// +/// +/// +/// A circuit captures its principal once, at circuit start, and an open tab issues no further HTTP +/// requests, so neither cookie expiry nor a configuration change ever reached it: an Administrator +/// tab left open could still close sessions, kill workers and manage API keys hours later. Every +/// this provider re-evaluates two things it can know without the +/// user's password: +/// +/// +/// +/// Age. A circuit older than the cookie's idle lifetime +/// () is signed out; the circuit +/// could not have renewed the cookie, so the sign-in it holds has lapsed. +/// +/// +/// Roles. The principal's LDAP group claims are re-mapped through the current +/// MxGateway:Dashboard:GroupToRole; if a role the principal carries is no longer granted, the +/// circuit is signed out. This is the same re-resolution the session ACL applies to tag grants. +/// +/// +/// +/// When either check fails the circuit's state becomes anonymous: pages under +/// AuthorizeRouteView 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 here (the gateway keeps no server-side session and +/// cannot re-bind without the password); they take effect when the circuit reaches the age limit or +/// reconnects. The Dashboard:DisableLogin dev bypass and unauthenticated principals are +/// never signed out. +/// +/// +public sealed class DashboardRevalidatingAuthenticationStateProvider : RevalidatingServerAuthenticationStateProvider +{ + private readonly IOptionsMonitor _options; + private readonly TimeProvider _timeProvider; + private readonly DateTimeOffset _circuitStartedAt; + + /// Initializes a new instance of the class. + /// Logger factory for the revalidation loop. + /// Gateway options, read fresh on every revalidation. + /// Clock; the system clock when not registered. + public DashboardRevalidatingAuthenticationStateProvider( + ILoggerFactory loggerFactory, + IOptionsMonitor options, + TimeProvider? timeProvider = null) + : base(loggerFactory) + { + ArgumentNullException.ThrowIfNull(options); + _options = options; + _timeProvider = timeProvider ?? TimeProvider.System; + _circuitStartedAt = _timeProvider.GetUtcNow(); + } + + /// + protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(1); + + /// Decides whether the circuit's principal is still signed in. Internal for tests. + /// The circuit's current principal. + /// to keep the sign-in; to sign out. + internal bool IsStillValid(ClaimsPrincipal user) + { + if (user.Identity?.IsAuthenticated != true) + { + return true; + } + + GatewayOptions options = _options.CurrentValue; + if (options.Dashboard.DisableLogin) + { + return true; + } + + if (_timeProvider.GetUtcNow() - _circuitStartedAt >= DashboardAuthenticationDefaults.CookieIdleTimeout) + { + return false; + } + + string[] groups = [.. user.FindAll(DashboardAuthenticationDefaults.LdapGroupClaimType).Select(claim => claim.Value)]; + if (groups.Length == 0) + { + // Nothing to re-resolve from (a principal minted without LDAP groups); the age check + // above is the bound. + return true; + } + + IReadOnlyList grantedRoles = DashboardGroupRoleMapping.MapGroupsToRoles( + groups, + options.Dashboard.GroupToRole); + foreach (Claim role in user.FindAll(ClaimTypes.Role)) + { + if (!grantedRoles.Contains(role.Value, StringComparer.Ordinal)) + { + return false; + } + } + + return true; + } + + /// + protected override Task ValidateAuthenticationStateAsync( + AuthenticationState authenticationState, + CancellationToken cancellationToken) => + Task.FromResult(IsStillValid(authenticationState.User)); +} diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs index 7a9e3ec1..7ac053fb 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs @@ -1,6 +1,7 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components.Authorization; using Microsoft.AspNetCore.Components.Server.Circuits; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection.Extensions; @@ -114,6 +115,10 @@ public static class DashboardServiceCollectionExtensions services.AddRazorComponents() .AddInteractiveServerComponents(circuit => circuit.DisconnectedCircuitRetentionPeriod = DisconnectedCircuitRetention); + // Registered after AddInteractiveServerComponents so it replaces the default + // ServerAuthenticationStateProvider: a circuit's sign-in is otherwise captured once at + // circuit start and never revisited (DSH-006). + services.AddScoped(); services.AddSignalR(); // DEV/TEST ONLY. Read directly from configuration here because authentication scheme @@ -154,7 +159,7 @@ public static class DashboardServiceCollectionExtensions // ExpireTimeSpan) via the shared ZbCookieDefaults.Apply. requireHttps is set to // its default (true / Always) here and overridden per-environment by the // PostConfigure below; the 8-hour idle timeout is preserved (not the 30-min default). - ZbCookieDefaults.Apply(cookieOptions, requireHttps: true, idleTimeout: TimeSpan.FromHours(8)); + ZbCookieDefaults.Apply(cookieOptions, requireHttps: true, idleTimeout: DashboardAuthenticationDefaults.CookieIdleTimeout); // Cookie name, path, and redirect paths are MxGateway-specific — set after Apply // so they are never overwritten by the shared helper (Apply intentionally skips name). // This is the canonical default; it is overridden per-environment from diff --git a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/HubTokenAuthenticationHandler.cs b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/HubTokenAuthenticationHandler.cs index 0a5622e0..697e4a9d 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Dashboard/HubTokenAuthenticationHandler.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Dashboard/HubTokenAuthenticationHandler.cs @@ -48,14 +48,19 @@ public sealed class HubTokenAuthenticationHandler : AuthenticationHandlerValidates a token and returns the equivalent claims principal; null when invalid or expired. /// The token string to validate. /// The reconstructed , or when the token is missing, invalid, or expired. - public ClaimsPrincipal? Validate(string? token) + public ClaimsPrincipal? Validate(string? token) => Validate(token, out _); + + /// + /// Validates a token and returns the equivalent claims principal and the token's expiry; null + /// when invalid or expired. The expiry is stamped on the hub authentication ticket so SignalR's + /// CloseOnAuthenticationExpiration ends the connection when the token lapses (DSH-006). + /// + /// The token string to validate. + /// The token's expiry when valid; otherwise . + /// The reconstructed , or . + public ClaimsPrincipal? Validate(string? token, out DateTimeOffset expiresUtc) { + expiresUtc = default; if (string.IsNullOrEmpty(token)) { return null; @@ -109,7 +120,8 @@ public sealed class HubTokenService try { - HubTokenPayload? payload = JsonSerializer.Deserialize(_protector.Unprotect(token)); + HubTokenPayload? payload = JsonSerializer.Deserialize( + _protector.Unprotect(token, out DateTimeOffset expiration)); if (payload is null) { return null; @@ -149,6 +161,7 @@ public sealed class HubTokenService DashboardAuthenticationDefaults.HubAuthenticationScheme, ClaimTypes.Name, ClaimTypes.Role); + expiresUtc = expiration; return new ClaimsPrincipal(identity); } catch (Exception ex) when (ex is CryptographicException or JsonException) diff --git a/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs b/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs index dcb509fd..01a51c2d 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Grpc/MxAccessGatewayService.cs @@ -1,3 +1,4 @@ +using System.Collections.Frozen; using System.Diagnostics; using Grpc.Core; using Google.Protobuf.WellKnownTypes; @@ -24,6 +25,60 @@ public sealed class MxAccessGatewayService( ILogger logger, IGatewayAlarmService alarmService) : MxAccessGateway.MxAccessGatewayBase { + /// + /// Command kinds checks against the caller's read or + /// write constraints because their payload names a tag address or an item handle that maps + /// back to one. + /// + internal static readonly FrozenSet ConstrainedCommandKinds = new[] + { + MxCommandKind.AddItem, + MxCommandKind.AddItem2, + MxCommandKind.AddBufferedItem, + MxCommandKind.AddItemBulk, + MxCommandKind.SubscribeBulk, + MxCommandKind.AdviseItemBulk, + MxCommandKind.ReadBulk, + MxCommandKind.Write, + MxCommandKind.Write2, + MxCommandKind.WriteSecured, + MxCommandKind.WriteSecured2, + MxCommandKind.WriteBulk, + MxCommandKind.Write2Bulk, + MxCommandKind.WriteSecuredBulk, + MxCommandKind.WriteSecured2Bulk, + }.ToFrozenSet(); + + /// + /// Command kinds that carry no tag address, so they pass + /// without a constraint check. Handle-only commands (Advise, RemoveItem, ...) + /// belong here because the add that produced the handle was checked. Any kind in neither + /// set is refused with PermissionDenied, so a new tag-bearing kind cannot slip + /// through unchecked; the enum-coverage test fails until it is classified. + /// + internal static readonly FrozenSet UnconstrainedCommandKinds = new[] + { + MxCommandKind.Register, + MxCommandKind.Unregister, + MxCommandKind.RemoveItem, + MxCommandKind.Advise, + MxCommandKind.UnAdvise, + MxCommandKind.AdviseSupervisory, + MxCommandKind.SetBufferedUpdateInterval, + MxCommandKind.Suspend, + MxCommandKind.Activate, + MxCommandKind.AuthenticateUser, + MxCommandKind.ArchestraUserToId, + MxCommandKind.RemoveItemBulk, + MxCommandKind.UnAdviseItemBulk, + MxCommandKind.UnsubscribeBulk, + MxCommandKind.Ping, + MxCommandKind.GetSessionState, + MxCommandKind.GetWorkerInfo, + MxCommandKind.DrainEvents, + MxCommandKind.ShutdownWorker, + }.ToFrozenSet(); + /// public override async Task OpenSession( OpenSessionRequest request, @@ -83,6 +138,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 +178,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 +399,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, @@ -352,6 +435,10 @@ public sealed class MxAccessGatewayService( await EnforceReadTagAsync(identity, command.Kind, command.AddItem2.ItemDefinition, correlationId, cancellationToken) .ConfigureAwait(false); return null; + case MxCommandKind.AddBufferedItem: + await EnforceReadTagAsync(identity, command.Kind, command.AddBufferedItem.ItemDefinition, correlationId, cancellationToken) + .ConfigureAwait(false); + return null; case MxCommandKind.AddItemBulk: return await FilterTagBulkAsync( identity, @@ -478,10 +565,34 @@ public sealed class MxAccessGatewayService( .ConfigureAwait(false); return null; default: + if (UnconstrainedCommandKinds.Contains(command.Kind)) + { + return null; + } + + // Fail closed: a kind that is neither checked above nor on the no-tag allow-list + // (a gateway-internal alarm kind, or a kind added to the contract after this + // switch) may carry a tag address the API-key constraints never saw. + await RefuseUnconstrainedCommandAsync(identity, command.Kind, correlationId, cancellationToken) + .ConfigureAwait(false); return null; } } + private async Task RefuseUnconstrainedCommandAsync( + ApiKeyIdentity? identity, + MxCommandKind commandKind, + string? correlationId, + CancellationToken cancellationToken) + { + ConstraintFailure failure = new( + "command-kind", + $"Command kind {commandKind} is not accepted on Invoke: it has no API-key constraint check."); + await constraintEnforcer.RecordDenialAsync(identity, commandKind.ToString(), commandKind.ToString(), failure, correlationId, cancellationToken) + .ConfigureAwait(false); + throw new RpcException(new Status(StatusCode.PermissionDenied, failure.Message)); + } + private async Task EnforceReadTagAsync( ApiKeyIdentity? identity, MxCommandKind commandKind, diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs index 113516a8..bb1b2741 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authentication/CachingApiKeyVerifier.cs @@ -1,4 +1,5 @@ using System.Collections.Concurrent; +using System.Diagnostics.CodeAnalysis; using System.Security.Cryptography; using System.Text; using Microsoft.Extensions.Caching.Memory; @@ -19,6 +20,25 @@ public interface IApiKeyCacheInvalidator void Invalidate(string keyId); } +/// +/// Read-only access to cached successful verifications, consulted by the auth surfaces before the +/// failure limiter (SEC-002). +/// +/// +/// A hit means the presented token — key id and secret — hashed to an entry that a real +/// verification stored within the TTL. It costs no store read, which is the only thing the failure +/// limiter protects, so a hit bypasses the limiter: a spray of bad secrets against a public key id +/// can then never deny the key to the client holding the correct one. +/// +public interface IApiKeyVerificationCache +{ + /// Returns a cached successful verification for the header, if one is within TTL. + /// The raw authorization header value. + /// The cached successful verification, when found. + /// on a cache hit. + bool TryGetCachedSuccess(string? authorizationHeader, [NotNullWhen(true)] out ApiKeyVerification? verification); +} + /// /// An decorator that caches successful verifications for a short, /// configurable TTL (), keyed on a @@ -72,7 +92,7 @@ public interface IApiKeyCacheInvalidator /// live cache rather than to every token ever verified. /// /// -public sealed class CachingApiKeyVerifier : IApiKeyVerifier, IApiKeyCacheInvalidator +public sealed class CachingApiKeyVerifier : IApiKeyVerifier, IApiKeyCacheInvalidator, IApiKeyVerificationCache { private const string CacheKeyPrefix = "mxgw:apikeyverif:"; private const string TokenPrefix = "mxgw"; @@ -217,6 +237,22 @@ public sealed class CachingApiKeyVerifier : IApiKeyVerifier, IApiKeyCacheInvalid return await verification.WaitAsync(ct).ConfigureAwait(false); } + /// + public bool TryGetCachedSuccess(string? authorizationHeader, [NotNullWhen(true)] out ApiKeyVerification? verification) + { + if (_ttl > TimeSpan.Zero + && TryComputeCacheKey(authorizationHeader, out string cacheKey) + && _cache.TryGetValue(cacheKey, out ApiKeyVerification? cached) + && cached is not null) + { + verification = cached; + return true; + } + + verification = null; + return false; + } + // The shared body of one single-flight miss. Not bound to any caller's token: a caller that // gives up must not cancel the verification other callers are waiting on. private async Task VerifyMissAsync( diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs index 7fbc8875..684dc0f4 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyFailureLimiter.cs @@ -21,9 +21,14 @@ namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization; /// /// An over-limit state is a valve, not a wall: at most one request per /// is admitted through to the real -/// verifier, and a successful verification resets both layers. The reset path therefore stays -/// reachable while throttled — the earlier design keyed solely on the attacker-supplied key id and -/// rejected before verification, so the legitimate holder could never clear the block. +/// verifier. A successful verification clears the caller's own (address, key id) partition +/// and marks that pair as verified for one window; it does not clear the key id's +/// cross-peer aggregate (SEC-003), which decays by window expiry only — otherwise every call from +/// a key in steady use would wipe the aggregate and a sprayer would never be bounded by it. The +/// verified mark is what keeps the holder from being denied by a spray against its public key id +/// (SEC-002): an address that verified the key inside the window skips the aggregate layer, and the +/// interceptor serves a cached verification without consulting the limiter at all. Neither path is +/// reachable without the correct secret. /// /// /// The tracked partition set is a bounded LRU (). @@ -71,6 +76,11 @@ public sealed class ApiKeyFailureLimiter private readonly ConcurrentDictionary _aggregates = new(StringComparer.Ordinal); private readonly ConcurrentDictionary _peerKeyIds = new(StringComparer.Ordinal); + // Composite (address, key id) -> ticks of the last successful verification from that address. + // Only a correct secret writes here, so it is bounded by legitimate traffic, and it is pruned to + // the same partition cap on the success path. + private readonly ConcurrentDictionary _verified = new(StringComparer.Ordinal); + /// Initializes a new instance of the class. /// Security options carrying the failure-limit knobs. /// The time provider. @@ -115,6 +125,9 @@ public sealed class ApiKeyFailureLimiter /// Gets the number of tracked per-key-id aggregates. Test seam. internal int TrackedAggregateCount => _aggregates.Count; + /// Gets the number of tracked verified (address, key id) marks. Test seam. + internal int VerifiedMarkCount => _verified.Count; + /// /// Test seam invoked between a probe claim and its compensating release; /// in production, where it costs one null check on the already-refused path. @@ -166,7 +179,9 @@ public sealed class ApiKeyFailureLimiter } bool peerOver = peerState is not null && IsOverLimit(peerState, now, _limit); - bool aggregateOver = aggregateState is not null && IsOverLimit(aggregateState, now, _aggregateLimit); + bool aggregateOver = aggregateState is not null + && IsOverLimit(aggregateState, now, _aggregateLimit) + && !IsRecentlyVerified(peer, partition.KeyId!, now); if (!peerOver && !aggregateOver) { return ApiKeyThrottleDecision.Allowed; @@ -239,14 +254,17 @@ public sealed class ApiKeyFailureLimiter EvictIfOverCapacity(_aggregates, now, _aggregateLimit, releaseKeyIds: false); } - /// Clears both limiter layers for the partition after a successful verification. + /// + /// Records a successful verification: clears the caller's own partition and marks the + /// (address, key id) pair verified. The key id's cross-peer aggregate is left to decay. + /// /// The throttle partition derived from the request. public void Reset(ApiKeyThrottlePartition partition) => Reset(partition, PartitionResolution.Unresolved); /// - /// Clears both limiter layers for the partition after a successful verification, reusing the - /// storage key already - /// resolved for this request. + /// Records a successful verification, reusing the storage key + /// already resolved for + /// this request. /// /// The throttle partition derived from the request. /// @@ -272,15 +290,42 @@ public sealed class ApiKeyFailureLimiter RemovePartition(partitionKey); } - // The aggregate is cleared on the presented key id even when the composite partition - // collapsed to the fallback: a verified secret is proof the key is not under successful - // attack, and clearing is what makes the block recoverable. - if (partition.KeyId is not null) + // The aggregate is deliberately NOT cleared (SEC-003). A key in steady use succeeds many + // times a second, so clearing it on success meant it never accumulated and a sprayer guessing + // the same key id from other addresses was bounded by neither layer. It decays by window. + // Instead the verifying address is marked, so the aggregate cannot lock the holder out. + if (partition.KeyId is not null && _aggregateLimit > 0 && _limit > 0) { - _aggregates.TryRemove(partition.KeyId, out _); + MarkVerified(peer, partition.KeyId, _clock.GetUtcNow().UtcTicks); } } + private void MarkVerified(string peer, string keyId, long now) + { + _verified[Composite(peer, keyId)] = now; + if (_verified.Count <= _maxPartitions) + { + return; + } + + // Over the cap: drop marks that have aged out of the window. If legitimate traffic alone + // still exceeds the cap the map overshoots; it is written only by correct secrets. + foreach (KeyValuePair entry in _verified) + { + if (now - entry.Value >= _windowTicks) + { + _verified.TryRemove(entry); + } + } + } + + private bool IsRecentlyVerified(string peer, string keyId, long now) + { + return !_verified.IsEmpty + && _verified.TryGetValue(Composite(peer, keyId), out long verifiedAt) + && now - verifiedAt < _windowTicks; + } + /// Returns whether the partition currently has tracked failure state. Test seam. /// The throttle partition to look up. /// when the partition has a tracked window. diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyStreamRegistry.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyStreamRegistry.cs new file mode 100644 index 00000000..07999ae4 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyStreamRegistry.cs @@ -0,0 +1,152 @@ +using System.Collections.Concurrent; + +namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization; + +/// +/// Tracks the streaming gRPC calls each API key has open, so revoking, rotating or deleting the key +/// ends them (SEC-004). +/// +/// +/// +/// A streaming call is authenticated once, when it opens. Evicting the verification cache on +/// revoke stops new calls but leaves an open StreamEvents, StreamAlarms or +/// WatchDeployEvents delivering data until the client disconnects. The authorization +/// interceptor registers every streaming call here under the caller's key id and hands the handler +/// a call context whose cancellation token also fires on ; the interceptor then +/// reports the end of the call as Unauthenticated. +/// +/// +/// Only revocations made through this gateway process reach the registry (the dashboard API Keys +/// page). The separate apikey CLI process cannot signal it, so a key revoked there ends its +/// open streams only when they reconnect — the same bounded window its cache eviction has. +/// Key ids compare ordinal-ignore-case, matching the verification cache (mxaccessgw#173). +/// +/// +public sealed class ApiKeyStreamRegistry +{ + private readonly ConcurrentDictionary> _byKeyId = + new(StringComparer.OrdinalIgnoreCase); + + /// Gets the number of open streaming calls registered for a key id. Test seam. + /// The key id. + /// The open registration count. + internal int CountFor(string keyId) => + _byKeyId.TryGetValue(keyId, out ConcurrentDictionary? set) ? set.Count : 0; + + /// + /// Registers a streaming call. Dispose the returned registration when the call ends. + /// + /// The authenticated caller's key id. + /// The call's own cancellation token, linked into the registration's. + /// The registration whose the handler must observe. + public Registration Register(string keyId, CancellationToken callCancellation) + { + ArgumentException.ThrowIfNullOrEmpty(keyId); + + Registration registration = new(this, keyId, callCancellation); + while (true) + { + ConcurrentDictionary set = _byKeyId.GetOrAdd(keyId, static _ => new()); + set[registration] = 0; + + // Lost a race with the last registration of this key id removing an empty set: re-add + // into whatever set is current so a later Revoke can still find this call. + if (_byKeyId.TryGetValue(keyId, out ConcurrentDictionary? current) + && ReferenceEquals(current, set)) + { + return registration; + } + + set.TryRemove(registration, out _); + } + } + + /// Ends every open streaming call registered for the key id. + /// The revoked, rotated or deleted key id. + /// The number of calls that were cancelled. + public int Revoke(string keyId) + { + if (string.IsNullOrEmpty(keyId) || !_byKeyId.TryGetValue(keyId, out ConcurrentDictionary? set)) + { + return 0; + } + + int cancelled = 0; + foreach (Registration registration in set.Keys) + { + if (registration.MarkRevoked()) + { + cancelled++; + } + } + + return cancelled; + } + + private void Unregister(Registration registration) + { + if (_byKeyId.TryGetValue(registration.KeyId, out ConcurrentDictionary? set) + && set.TryRemove(registration, out _) + && set.IsEmpty) + { + _byKeyId.TryRemove(new KeyValuePair>(registration.KeyId, set)); + } + } + + /// One open streaming call. + public sealed class Registration : IDisposable + { + private readonly ApiKeyStreamRegistry _owner; + private readonly CancellationTokenSource _cancellation; + private int _revoked; + private int _disposed; + + internal Registration(ApiKeyStreamRegistry owner, string keyId, CancellationToken callCancellation) + { + _owner = owner; + KeyId = keyId; + _cancellation = CancellationTokenSource.CreateLinkedTokenSource(callCancellation); + } + + /// Gets the key id the call authenticated with. + public string KeyId { get; } + + /// Gets the token that fires when the call is cancelled or its key is revoked. + public CancellationToken Token => _cancellation.Token; + + /// Gets a value indicating whether the key was revoked while the call was open. + public bool IsRevoked => Volatile.Read(ref _revoked) == 1; + + /// + public void Dispose() + { + if (Interlocked.Exchange(ref _disposed, 1) == 1) + { + return; + } + + _owner.Unregister(this); + _cancellation.Dispose(); + } + + internal bool MarkRevoked() + { + if (Interlocked.Exchange(ref _revoked, 1) == 1 || Volatile.Read(ref _disposed) == 1) + { + return false; + } + + try + { + _cancellation.Cancel(); + } + catch (ObjectDisposedException) + { + // The call ended between the checks above and the cancel; nothing left to stop. + return false; + } + + return true; + } + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePartition.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePartition.cs index 05dbe244..bdd73c38 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePartition.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePartition.cs @@ -11,6 +11,9 @@ namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization; /// (literal mxgw prefix, at least three /// non-empty underscore segments, bounded key-id length) so junk tokens cannot mint partitions. /// -/// The gRPC transport peer address (ServerCallContext.Peer). +/// +/// The client's remote IP with no port, as produced by . The +/// source port is excluded because it changes with every connection (SEC-001). +/// /// The key id claimed by a validly shaped token, or . public readonly record struct ApiKeyThrottlePartition(string TransportPeer, string? KeyId); diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePeer.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePeer.cs new file mode 100644 index 00000000..d20c24a7 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/ApiKeyThrottlePeer.cs @@ -0,0 +1,76 @@ +using System.Net; + +namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization; + +/// +/// Derives the address half of an : the client's remote IP +/// with no source port, in one canonical form shared by the gRPC interceptor and the +/// /metrics handler. +/// +/// +/// The port must not be part of the partition (SEC-001). It is the client's ephemeral source port, +/// so keying on it made every new TCP connection a fresh partition: an attacker could send +/// limit - 1 bad secrets, reconnect, and repeat without ever being throttled, and each +/// connection minted a tracked partition. Both auth surfaces normalise through this type so a +/// failure on one counts against the same address on the other. +/// +public static class ApiKeyThrottlePeer +{ + private const string Ipv4Prefix = "ipv4:"; + private const string Ipv6Prefix = "ipv6:["; + + /// + /// Extracts the remote IP from a Grpc.AspNetCore peer string (ipv4:1.2.3.4:5678 or + /// ipv6:[::1]:5678). A peer in any other form (unknown, a Unix socket) is returned + /// unchanged, since it carries no port to strip. + /// + /// The value of ServerCallContext.Peer. + /// The canonical address string. + public static string FromGrpcPeer(string grpcPeer) + { + ArgumentNullException.ThrowIfNull(grpcPeer); + + ReadOnlySpan address; + if (grpcPeer.StartsWith(Ipv4Prefix, StringComparison.Ordinal)) + { + ReadOnlySpan rest = grpcPeer.AsSpan(Ipv4Prefix.Length); + int portSeparator = rest.LastIndexOf(':'); + address = portSeparator > 0 ? rest[..portSeparator] : rest; + } + else if (grpcPeer.StartsWith(Ipv6Prefix, StringComparison.Ordinal)) + { + ReadOnlySpan rest = grpcPeer.AsSpan(Ipv6Prefix.Length); + int close = rest.IndexOf(']'); + if (close <= 0) + { + return grpcPeer; + } + + address = rest[..close]; + } + else + { + return grpcPeer; + } + + return IPAddress.TryParse(address, out IPAddress? parsed) ? FromRemoteIp(parsed) : grpcPeer; + } + + /// + /// Formats an HTTP connection's remote IP. An IPv4-mapped IPv6 address is reduced to IPv4 so a + /// dual-stack listener does not split one client across two partitions. + /// + /// The connection's remote address, or . + /// The canonical address string, or unknown. + public static string FromRemoteIp(IPAddress? remoteIpAddress) + { + if (remoteIpAddress is null) + { + return "unknown"; + } + + return remoteIpAddress.IsIPv4MappedToIPv6 + ? remoteIpAddress.MapToIPv4().ToString() + : remoteIpAddress.ToString(); + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs index 730c2e2e..5bb2a2e6 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GatewayGrpcAuthorizationInterceptor.cs @@ -18,12 +18,19 @@ public sealed class GatewayGrpcAuthorizationInterceptor( IGatewayRequestIdentityAccessor identityAccessor, IOptions options, ApiKeyFailureLimiter failureLimiter, - GatewayMetrics metrics) : Interceptor + GatewayMetrics metrics, + ApiKeyStreamRegistry? streamRegistry = null) : Interceptor { + private const string RevokedMessage = "The API key was revoked while the call was open."; + // Generated key ids are far shorter; the cap only exists to stop an invented "key id" of // arbitrary length from becoming a limiter partition. private const int MaxKeyIdLength = 64; + // The production verifier is the caching decorator; a test double that is not a cache simply + // always takes the limiter path. + private readonly IApiKeyVerificationCache? _verificationCache = apiKeyVerifier as IApiKeyVerificationCache; + /// public override async Task UnaryServerHandler( TRequest request, @@ -55,7 +62,11 @@ public sealed class GatewayGrpcAuthorizationInterceptor( IDisposable? identityScope = identity is null ? null : identityAccessor.Push(identity); using (identityScope) { - await continuation(request, responseStream, context).ConfigureAwait(false); + await RunRevocableAsync( + identity, + context, + revocableContext => continuation(request, responseStream, revocableContext)) + .ConfigureAwait(false); } } @@ -77,7 +88,13 @@ public sealed class GatewayGrpcAuthorizationInterceptor( IDisposable? identityScope = identity is null ? null : identityAccessor.Push(identity); using (identityScope) { - return await continuation(requestStream, context).ConfigureAwait(false); + TResponse response = default!; + await RunRevocableAsync( + identity, + context, + async revocableContext => response = await continuation(requestStream, revocableContext).ConfigureAwait(false)) + .ConfigureAwait(false); + return response; } } @@ -93,7 +110,43 @@ public sealed class GatewayGrpcAuthorizationInterceptor( IDisposable? identityScope = identity is null ? null : identityAccessor.Push(identity); using (identityScope) { - await continuation(requestStream, responseStream, context).ConfigureAwait(false); + await RunRevocableAsync( + identity, + context, + revocableContext => continuation(requestStream, responseStream, revocableContext)) + .ConfigureAwait(false); + } + } + + // Runs a streaming handler registered under the caller's key id (SEC-004). The handler sees a + // call context whose cancellation token also fires when the key is revoked, rotated or deleted + // through this process, so an open stream ends instead of outliving its credential. However the + // handler then finishes — its own Cancelled mapping, a normal return — a revoked call is + // reported as Unauthenticated, the status a fresh call with the same key would get. + private async Task RunRevocableAsync( + ApiKeyIdentity? identity, + ServerCallContext context, + Func handler) + { + if (identity is null || streamRegistry is null) + { + await handler(context).ConfigureAwait(false); + return; + } + + using ApiKeyStreamRegistry.Registration registration = streamRegistry.Register(identity.KeyId, context.CancellationToken); + try + { + await handler(new RevocableServerCallContext(context, registration.Token)).ConfigureAwait(false); + } + catch (Exception) when (registration.IsRevoked) + { + throw new RpcException(new Status(StatusCode.Unauthenticated, RevokedMessage)); + } + + if (registration.IsRevoked) + { + throw new RpcException(new Status(StatusCode.Unauthenticated, RevokedMessage)); } } @@ -112,6 +165,15 @@ public sealed class GatewayGrpcAuthorizationInterceptor( string? authorizationHeader = context.RequestHeaders.GetValue("authorization"); + // A cached successful verification is proof of the correct secret and costs no store read, + // so it skips the failure limiter entirely (SEC-002): a spray of bad secrets against this + // key id, from anywhere, cannot deny the key to the client that holds it. + if (_verificationCache is not null + && _verificationCache.TryGetCachedSuccess(authorizationHeader, out ApiKeyVerification? cached)) + { + return AuthorizeVerifiedIdentity(cached, requiredScope); + } + // Short-circuit a partition that has already failed too many times inside the sliding window // BEFORE the verification store read, so online guessing cannot spend a SQLite read per // attempt. The partition is the composite (transport peer, key id) — never the key id alone, @@ -150,13 +212,19 @@ public sealed class GatewayGrpcAuthorizationInterceptor( "Missing or invalid API key.")); } - // Successful authentication clears both limiter layers, so a legitimate client that - // fat-fingered a few attempts is not penalised once it recovers — and, because the check - // above admits a probe rather than blocking absolutely, this reset stays reachable while the - // key is under an active spray. + // Successful authentication clears this caller's own partition, so a legitimate client that + // fat-fingered a few attempts is not penalised once it recovers, and marks the address as + // verified for the key id so the cross-peer aggregate cannot lock it out. It leaves the + // aggregate itself to decay by window (SEC-003): clearing it on every success meant a key in + // steady use never accumulated one. failureLimiter.Reset(throttlePartition, throttleResolution); - ApiKeyIdentity identity = GatewayApiKeyIdentityMapper.ToGatewayIdentity(verification.Identity); + return AuthorizeVerifiedIdentity(verification, requiredScope); + } + + private static ApiKeyIdentity AuthorizeVerifiedIdentity(ApiKeyVerification verification, string requiredScope) + { + ApiKeyIdentity identity = GatewayApiKeyIdentityMapper.ToGatewayIdentity(verification.Identity!); if (!identity.Scopes.Contains(requiredScope)) { @@ -168,14 +236,17 @@ public sealed class GatewayGrpcAuthorizationInterceptor( return identity; } - // Resolves the failure-limiter partition: always the transport peer, plus the presented key id - // when — and only when — the token is validly shaped. Both halves are unauthenticated input, so - // the peer half is what keeps a throttle bound to the address that earned it. + // Resolves the failure-limiter partition: always the remote IP (port stripped — the source port + // changes per connection, SEC-001), plus the presented key id when — and only when — the token + // is validly shaped. Both halves are unauthenticated input, so the address half is what keeps a + // throttle bound to the address that earned it. private static ApiKeyThrottlePartition ResolveThrottlePartition( string? authorizationHeader, ServerCallContext context) { - return new ApiKeyThrottlePartition(context.Peer, TryResolveKeyId(authorizationHeader)); + return new ApiKeyThrottlePartition( + ApiKeyThrottlePeer.FromGrpcPeer(context.Peer), + TryResolveKeyId(authorizationHeader)); } // Token shape mxgw__: the key id is the second underscore-delimited segment (the diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GrpcAuthorizationServiceCollectionExtensions.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GrpcAuthorizationServiceCollectionExtensions.cs index 62e4d9af..7a535d63 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GrpcAuthorizationServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/GrpcAuthorizationServiceCollectionExtensions.cs @@ -26,6 +26,7 @@ public static class GrpcAuthorizationServiceCollectionExtensions sp.GetRequiredService().GetSection(SecurityOptions.SectionName).Get() ?? new SecurityOptions(), sp.GetService() ?? TimeProvider.System)); + services.AddSingleton(); services.AddSingleton(); services .AddOptions() diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/MetricsAuthorization.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/MetricsAuthorization.cs index d9ed334f..eaf8d94d 100644 --- a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/MetricsAuthorization.cs +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/MetricsAuthorization.cs @@ -7,6 +7,7 @@ using ZB.MOM.WW.Auth.Abstractions.ApiKeys; using ZB.MOM.WW.MxGateway.Server.Configuration; using ZB.MOM.WW.MxGateway.Server.Dashboard; using ZB.MOM.WW.MxGateway.Server.Metrics; +using ZB.MOM.WW.MxGateway.Server.Security.Authentication; namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization; @@ -35,9 +36,9 @@ public static class MetricsAuthorizationDefaults /// cookie scheme on the policy directly would turn an anonymous scrape into a 302 redirect to the /// login page. A throttled key partition answers 429, mirroring the gRPC /// ResourceExhausted. Failure reasons are never echoed to the caller and the presented -/// secret is never logged. The limiter's per-peer partition here is the remote IP, whereas the gRPC -/// interceptor's is the gRPC peer string (address and port, i.e. per connection), so the two paths -/// share only the per-key-id aggregate layer. +/// secret is never logged. Both this handler and the gRPC interceptor partition the limiter on the +/// remote IP through , so the two surfaces share both limiter +/// layers. A cached successful verification skips the limiter here as it does on gRPC (SEC-002). /// public sealed class MetricsAuthenticationHandler( IOptionsMonitor options, @@ -50,6 +51,8 @@ public sealed class MetricsAuthenticationHandler( GatewayMetrics metrics) : AuthenticationHandler(options, logger, encoder) { + private readonly IApiKeyVerificationCache? _verificationCache = apiKeyVerifier as IApiKeyVerificationCache; + private bool _throttled; /// @@ -61,10 +64,18 @@ public sealed class MetricsAuthenticationHandler( return await AuthenticateDashboardCookieAsync().ConfigureAwait(false); } + // Same order as the gRPC interceptor: a cached success (correct secret, no store read) + // skips the limiter, so a spray against the key id cannot deny the scraper that holds it. + if (_verificationCache is not null + && _verificationCache.TryGetCachedSuccess(authorizationHeader, out ApiKeyVerification? cached)) + { + return Authenticated(cached); + } + // Same throttle as the gRPC interceptor: checked before the store read so online guessing // against /metrics cannot spend a verification per attempt or bypass the gRPC limiter. ApiKeyThrottlePartition partition = new( - Context.Connection.RemoteIpAddress?.ToString() ?? "unknown", + ApiKeyThrottlePeer.FromRemoteIp(Context.Connection.RemoteIpAddress), GatewayGrpcAuthorizationInterceptor.TryResolveKeyId(authorizationHeader)); ApiKeyThrottleDecision decision = failureLimiter.Check( partition, @@ -86,8 +97,12 @@ public sealed class MetricsAuthenticationHandler( } failureLimiter.Reset(partition, resolution); + return Authenticated(verification); + } - List claims = [new Claim(ClaimTypes.Name, verification.Identity.KeyId)]; + private AuthenticateResult Authenticated(ApiKeyVerification verification) + { + List claims = [new Claim(ClaimTypes.Name, verification.Identity!.KeyId)]; foreach (string scope in verification.Identity.Scopes) { claims.Add(new Claim(MetricsAuthorizationDefaults.ScopeClaimType, scope)); diff --git a/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/RevocableServerCallContext.cs b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/RevocableServerCallContext.cs new file mode 100644 index 00000000..37677449 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Server/Security/Authorization/RevocableServerCallContext.cs @@ -0,0 +1,84 @@ +using Grpc.Core; + +namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization; + +/// +/// A that forwards everything to the real call context except its +/// cancellation token, which also fires when the caller's API key is revoked (SEC-004). Handlers +/// already stop on , so they end a revoked stream +/// without knowing about revocation. +/// +internal sealed class RevocableServerCallContext : ServerCallContext +{ + // Grpc.AspNetCore's GetHttpContext() falls back to this user-state key for a ServerCallContext + // that is not its own type; seeding it keeps that extension working through the wrapper. + private const string HttpContextUserStateKey = "__HttpContext"; + + private readonly ServerCallContext _inner; + private readonly CancellationToken _cancellationToken; + + public RevocableServerCallContext(ServerCallContext inner, CancellationToken cancellationToken) + { + _inner = inner; + _cancellationToken = cancellationToken; + + try + { + HttpContext httpContext = inner.GetHttpContext(); + inner.UserState.TryAdd(HttpContextUserStateKey, httpContext); + } + catch (InvalidOperationException) + { + // Not hosted by ASP.NET Core (unit tests); nothing to forward. + } + } + + /// + protected override string MethodCore => _inner.Method; + + /// + protected override string HostCore => _inner.Host; + + /// + protected override string PeerCore => _inner.Peer; + + /// + protected override DateTime DeadlineCore => _inner.Deadline; + + /// + protected override Metadata RequestHeadersCore => _inner.RequestHeaders; + + /// + protected override CancellationToken CancellationTokenCore => _cancellationToken; + + /// + protected override Metadata ResponseTrailersCore => _inner.ResponseTrailers; + + /// + protected override Status StatusCore + { + get => _inner.Status; + set => _inner.Status = value; + } + + /// + protected override WriteOptions? WriteOptionsCore + { + get => _inner.WriteOptions; + set => _inner.WriteOptions = value; + } + + /// + protected override AuthContext AuthContextCore => _inner.AuthContext; + + /// + protected override IDictionary UserStateCore => _inner.UserState; + + /// + protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) => + _inner.CreatePropagationToken(options); + + /// + protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) => + _inner.WriteResponseHeadersAsync(responseHeaders); +} diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/DashboardRouteAuthorizationTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/DashboardRouteAuthorizationTests.cs new file mode 100644 index 00000000..3215758c --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Dashboard/DashboardRouteAuthorizationTests.cs @@ -0,0 +1,335 @@ +using System.Security.Claims; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Components; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.Components.Routing; +using Microsoft.AspNetCore.Components.Web; +using Microsoft.AspNetCore.Components.Web.HtmlRendering; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using Microsoft.JSInterop; +using ZB.MOM.WW.Auth.AspNetCore; +using ZB.MOM.WW.MxGateway.Server.Alarms; +using ZB.MOM.WW.MxGateway.Server.Configuration; +using ZB.MOM.WW.MxGateway.Server.Dashboard; +using ZB.MOM.WW.MxGateway.Server.Dashboard.Components; +using ZB.MOM.WW.MxGateway.Tests.TestSupport; +using ZB.MOM.WW.Secrets.Ui; + +namespace ZB.MOM.WW.MxGateway.Tests.Dashboard; + +/// +/// Proves the dashboard router enforces page [Authorize] attributes on in-circuit +/// navigation (DSH-001, #243). +/// +/// +/// +/// A page's [Authorize] attribute is enforced by endpoint routing only on a full HTTP +/// request. The dashboard router is interactive, so a navigation that starts inside an existing +/// circuit (a click on an in-page link, or Blazor.navigateTo from the console) never issues +/// an HTTP request: the in-circuit Router resolves the route and renders it. A plain +/// RouteView does not evaluate [Authorize]; AuthorizeRouteView does. +/// +/// +/// These tests render the production component, park it on a page that has +/// no attribute, then call — the same +/// LocationChanged path an in-circuit navigation drives. Each negative test asserts both +/// that the gated page's markup is absent and that its data source was never called, so a page +/// that rendered and then threw cannot pass for a gate. +/// +/// +/// The shared ZB.MOM.WW.Secrets.Ui page is not rendered for real: under the static +/// its Theme-based markup overflows the HTML writer's stack in this +/// harness, and its internals are not what is under test. A component activator substitutes a +/// marker component when the router activates , so "activated" means +/// exactly "the router decided to render the page". +/// +/// +public sealed class DashboardRouteAuthorizationTests +{ + private const string StartPath = "/route-authorization-test-start"; + private const string SecretsPageMarker = "secrets-page-activated"; + private const string AlarmsPageMarker = "Active Alarms"; + private const string NotAuthorizedMarker = "Not Authorized"; + + /// + /// A Viewer is not granted secrets:manage. Navigating in-circuit to + /// /admin/secrets must render the not-authorized content and must not list secrets. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Viewer_InCircuitNavigationToSecrets_IsNotAuthorized() + { + RouteHarness harness = await RouteHarness.StartAsync(DashboardRoles.Viewer); + await using (harness.ConfigureAwait(false)) + { + string html = await harness.NavigateAsync("/admin/secrets"); + + Assert.DoesNotContain(SecretsPageMarker, html, StringComparison.Ordinal); + Assert.Contains(NotAuthorizedMarker, html, StringComparison.Ordinal); + Assert.Equal(0, harness.Activator.SecretsPageActivations); + } + } + + /// + /// Control for the Viewer case: an Administrator satisfies secrets:manage, so the same + /// in-circuit navigation renders the page and lists secrets. Without this, a router that + /// rendered nothing at all would pass the negative test. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Administrator_InCircuitNavigationToSecrets_RendersPage() + { + RouteHarness harness = await RouteHarness.StartAsync(DashboardRoles.Admin); + await using (harness.ConfigureAwait(false)) + { + string html = await harness.NavigateAsync("/admin/secrets"); + + Assert.Contains(SecretsPageMarker, html, StringComparison.Ordinal); + Assert.DoesNotContain(NotAuthorizedMarker, html, StringComparison.Ordinal); + Assert.Equal(1, harness.Activator.SecretsPageActivations); + } + } + + /// + /// Anonymous localhost passes the endpoint ViewerPolicy but never the Alarms policy. + /// In-circuit navigation to /alarms must not render the galaxy-wide alarm list or + /// start its poll loop. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Anonymous_InCircuitNavigationToAlarms_IsNotAuthorized() + { + RouteHarness harness = await RouteHarness.StartAsync(); + await using (harness.ConfigureAwait(false)) + { + string html = await harness.NavigateAsync("/alarms"); + + Assert.DoesNotContain(AlarmsPageMarker, html, StringComparison.Ordinal); + Assert.Contains(NotAuthorizedMarker, html, StringComparison.Ordinal); + Assert.Equal(0, harness.LiveData.AlarmQueries); + } + } + + /// + /// Control for the anonymous case: an authenticated Viewer holds a real dashboard role and so + /// satisfies the Alarms policy; the page renders and polls. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Viewer_InCircuitNavigationToAlarms_RendersPage() + { + RouteHarness harness = await RouteHarness.StartAsync(DashboardRoles.Viewer); + await using (harness.ConfigureAwait(false)) + { + string html = await harness.NavigateAsync("/alarms"); + + Assert.Contains(AlarmsPageMarker, html, StringComparison.Ordinal); + Assert.DoesNotContain(NotAuthorizedMarker, html, StringComparison.Ordinal); + Assert.True(harness.LiveData.AlarmQueries >= 1); + } + } + + // Owns the service provider, the renderer and the rendered Routes root for one test. + private sealed class RouteHarness : IAsyncDisposable + { + private readonly ServiceProvider _provider; + private readonly HtmlRenderer _renderer; + private readonly HtmlRootComponent _root; + + private RouteHarness( + ServiceProvider provider, + HtmlRenderer renderer, + HtmlRootComponent root, + SecretsPageSubstitutingActivator activator, + CountingLiveDataService liveData) + { + _provider = provider; + _renderer = renderer; + _root = root; + Activator = activator; + LiveData = liveData; + } + + public SecretsPageSubstitutingActivator Activator { get; } + + public CountingLiveDataService LiveData { get; } + + public static async Task StartAsync(params string[] roles) + { + SecretsPageSubstitutingActivator activator = new(); + CountingLiveDataService liveData = new(); + + ServiceCollection services = new(); + services.AddLogging(); + services.AddAuthorization(options => + { + options.AddSecretsAuthorization(); + options.AddPolicy( + DashboardAuthenticationDefaults.AlarmsPolicy, + policy => policy.AddRequirements(AuthenticatedDashboardRoleRequirement.AnyDashboardRole)); + }); + services.AddSingleton(); + services.AddCascadingAuthenticationState(); + services.AddSingleton(new StubAuthenticationStateProvider(roles)); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(); + services.AddSingleton(activator); + services.AddSingleton(liveData); + services.AddSingleton(new FakeGatewayAlarmService()); + services.AddSingleton>( + Options.Create(new GatewayOptions { Alarms = new AlarmsOptions { Enabled = true } })); + + ServiceProvider provider = services.BuildServiceProvider(); + HtmlRenderer renderer = new(provider, provider.GetRequiredService()); + HtmlRootComponent root = await renderer.Dispatcher.InvokeAsync( + () => renderer.RenderComponentAsync()); + + return new RouteHarness(provider, renderer, root, activator, liveData); + } + + public async Task NavigateAsync(string path) + { + NavigationManager navigation = _provider.GetRequiredService(); + await _renderer.Dispatcher.InvokeAsync(() => navigation.NavigateTo(path)); + + // The router re-renders asynchronously after LocationChanged; wait for the start + // page's not-found content to be replaced before reading the markup. + string html = string.Empty; + await Eventually.WaitUntilAsync( + async () => + { + html = await _renderer.Dispatcher.InvokeAsync(_root.ToHtmlString); + return !html.Contains("The requested dashboard page does not exist", StringComparison.Ordinal); + }, + TimeSpan.FromSeconds(10), + $"the router to leave the start page after navigating to {path}"); + return html; + } + + public async ValueTask DisposeAsync() + { + await _renderer.DisposeAsync(); + await _provider.DisposeAsync(); + } + } + + // A principal with an authentication type and role claims, or an unauthenticated one when no + // roles are given (the anonymous-localhost shape). + private sealed class StubAuthenticationStateProvider(string[] roles) : AuthenticationStateProvider + { + /// + public override Task GetAuthenticationStateAsync() + { + ClaimsIdentity identity = roles.Length == 0 + ? new ClaimsIdentity() + : new ClaimsIdentity( + roles.Select(role => new Claim(ZbClaimTypes.Role, role)), + authenticationType: "Test", + nameType: ZbClaimTypes.Name, + roleType: ZbClaimTypes.Role); + + return Task.FromResult(new AuthenticationState(new ClaimsPrincipal(identity))); + } + } + + // Navigation stays in process: NavigateTo updates the URI and raises LocationChanged, which + // is exactly what an in-circuit navigation does — no HTTP request, so no endpoint authorization. + private sealed class InCircuitNavigationManager : NavigationManager + { + /// Initializes the manager on the attribute-free start path. + public InCircuitNavigationManager() => Initialize("https://localhost/", $"https://localhost{StartPath}"); + + /// + protected override void NavigateToCore(string uri, NavigationOptions options) + { + Uri = ToAbsoluteUri(uri).ToString(); + NotifyLocationChanged(isInterceptedLink: false); + } + } + + private sealed class NoOpNavigationInterception : INavigationInterception + { + /// + public Task EnableNavigationInterceptionAsync() => Task.CompletedTask; + } + + private sealed class NoOpScrollToLocationHash : IScrollToLocationHash + { + /// + public Task RefreshScrollPositionForHash(string locationAbsolute) => Task.CompletedTask; + } + + private sealed class NoOpJsRuntime : IJSRuntime + { + /// + public ValueTask InvokeAsync(string identifier, object?[]? args) => default; + + /// + public ValueTask InvokeAsync( + string identifier, + CancellationToken cancellationToken, + object?[]? args) => default; + } + + // Answers the Alarms page's poll with an empty result and counts the calls; a non-zero count + // means the page initialized and started its galaxy-wide alarm loop. + private sealed class CountingLiveDataService : IDashboardLiveDataService + { + private int _alarmQueries; + + public int AlarmQueries => Volatile.Read(ref _alarmQueries); + + public Task ReadAsync( + IReadOnlyCollection tagAddresses, + CancellationToken cancellationToken) => + Task.FromResult(DashboardLiveReadResult.Empty); + + public async Task QueryAlarmsAsync(CancellationToken cancellationToken) + { + if (Interlocked.Increment(ref _alarmQueries) > 1) + { + await Task.Delay(Timeout.Infinite, cancellationToken).ConfigureAwait(false); + } + + return new DashboardAlarmQueryResult( + Alarms: [], + Error: null, + WorkerProcessId: null, + SnapshotTruncated: false); + } + } + + // Activates components normally, except SecretsPage, which it counts and replaces with a + // marker. Renderer resolves IComponentActivator from the service provider. + private sealed class SecretsPageSubstitutingActivator : IComponentActivator + { + private int _secretsPageActivations; + + public int SecretsPageActivations => Volatile.Read(ref _secretsPageActivations); + + /// + public IComponent CreateInstance(Type componentType) + { + if (componentType == typeof(SecretsPage)) + { + Interlocked.Increment(ref _secretsPageActivations); + return new SecretsPageStandIn(); + } + + return (IComponent)System.Activator.CreateInstance(componentType)!; + } + } + + private sealed class SecretsPageStandIn : ComponentBase + { + /// + protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder) + { + builder.AddMarkupContent(0, $"

{SecretsPageMarker}

"); + } + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardApiKeyManagementServiceTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardApiKeyManagementServiceTests.cs index 4aecc340..abee5740 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardApiKeyManagementServiceTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardApiKeyManagementServiceTests.cs @@ -335,7 +335,31 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable Assert.Equal("API key pepper is not configured.", result.Message); } - private DashboardApiKeyManagementService CreateService(ServiceProvider services) + /// + /// SEC-004: revoking a key on the dashboard ends the streaming calls that key already has + /// open, not only future calls. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RevokeAsync_AuthorizedUser_CancelsTheKeysOpenStreams() + { + await using ServiceProvider services = BuildServices(); + ApiKeyStreamRegistry registry = new(); + DashboardApiKeyManagementService service = CreateService(services, registry); + await service.CreateAsync(CreateAuthorizedUser(), CreateRequest(), CancellationToken.None); + using ApiKeyStreamRegistry.Registration revoked = registry.Register("operator01", CancellationToken.None); + using ApiKeyStreamRegistry.Registration other = registry.Register("operator02", CancellationToken.None); + + await service.RevokeAsync(CreateAuthorizedUser(), "operator01", CancellationToken.None); + + Assert.True(revoked.IsRevoked); + Assert.True(revoked.Token.IsCancellationRequested); + Assert.False(other.Token.IsCancellationRequested); + } + + private DashboardApiKeyManagementService CreateService( + ServiceProvider services, + ApiKeyStreamRegistry? streamRegistry = null) { DefaultHttpContext httpContext = new(); httpContext.Connection.RemoteIpAddress = System.Net.IPAddress.Loopback; @@ -346,7 +370,8 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable services.GetRequiredService(), services.GetRequiredService(), services.GetRequiredService(), - new HttpContextAccessor { HttpContext = httpContext }); + new HttpContextAccessor { HttpContext = httpContext }, + streamRegistry: streamRegistry); } private ServiceProvider BuildServices(string? pepper = "test-pepper") diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardAuthLifetimeTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardAuthLifetimeTests.cs new file mode 100644 index 00000000..15ff4f62 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardAuthLifetimeTests.cs @@ -0,0 +1,189 @@ +using System.Security.Claims; +using System.Text.Encodings.Web; +using Microsoft.AspNetCore.Authentication; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Components.Authorization; +using Microsoft.AspNetCore.DataProtection; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Connections; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Microsoft.Extensions.Time.Testing; +using ZB.MOM.WW.MxGateway.Server.Configuration; +using ZB.MOM.WW.MxGateway.Server.Dashboard; +using ZB.MOM.WW.MxGateway.Tests.TestSupport; + +namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Dashboard; + +/// +/// DSH-006: authentication lifetimes are enforced on live dashboard connections, not only at the +/// handshake — hub connections close when their ticket expires, and Blazor circuits are signed out +/// when their sign-in lapses or a role grant is withdrawn. +/// +public sealed class DashboardAuthLifetimeTests +{ + private const string AdminGroup = "GwAdmin"; + private const string ViewerGroup = "GwViewer"; + + /// + /// The hub-token ticket carries the token's expiry, which is what SignalR's + /// CloseOnAuthenticationExpiration closes the connection on. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task HubTokenTicket_CarriesTheTokenExpiry() + { + HubTokenService tokens = new( + new EphemeralDataProtectionProvider(), + Options.Create(new GatewayOptions())); + string token = tokens.Issue(Principal("alice", DashboardRoles.Viewer), TimeSpan.FromMinutes(5)); + DefaultHttpContext httpContext = new(); + httpContext.Request.Headers.Authorization = $"Bearer {token}"; + + HubTokenAuthenticationHandler handler = new( + new StaticOptionsMonitor(new AuthenticationSchemeOptions()), + NullLoggerFactory.Instance, + UrlEncoder.Default, + tokens); + await handler.InitializeAsync( + new AuthenticationScheme( + DashboardAuthenticationDefaults.HubAuthenticationScheme, + displayName: null, + typeof(HubTokenAuthenticationHandler)), + httpContext); + + AuthenticateResult result = await handler.AuthenticateAsync(); + + Assert.True(result.Succeeded); + DateTimeOffset? expires = result.Properties?.ExpiresUtc; + Assert.NotNull(expires); + Assert.InRange( + expires.Value, + DateTimeOffset.UtcNow.AddMinutes(4), + DateTimeOffset.UtcNow.AddMinutes(6)); + } + + /// + /// Every dashboard hub closes a connection whose authentication has expired. The dispatcher + /// options ride on each hub's negotiate endpoint. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task EveryHub_ClosesOnAuthenticationExpiration() + { + await using WebApplication app = TestGatewayHost.Build([]); + List hubEndpoints = ((IEndpointRouteBuilder)app).DataSources + .SelectMany(source => source.Endpoints) + .OfType() + .Where(endpoint => endpoint.RoutePattern.RawText + is "/hubs/snapshot/negotiate" or "/hubs/alarms/negotiate" or "/hubs/events/negotiate") + .ToList(); + + Assert.Equal(3, hubEndpoints.Count); + Assert.All( + hubEndpoints, + endpoint => Assert.True(endpoint.Metadata.GetMetadata()?.CloseOnAuthenticationExpiration)); + } + + /// Circuits get the revalidating provider, not the capture-once default. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Circuits_UseTheRevalidatingAuthenticationStateProvider() + { + await using WebApplication app = TestGatewayHost.Build([]); + await using AsyncServiceScope scope = app.Services.CreateAsyncScope(); + + Assert.IsType( + scope.ServiceProvider.GetRequiredService()); + } + + /// An Administrator whose admin group is withdrawn from GroupToRole is signed out. + [Fact] + public void Revalidation_WhenAdminGrantWithdrawn_SignsOut() + { + GatewayOptions options = OptionsWithRoles(includeAdmin: true); + StaticOptionsMonitor monitor = new(options); + FakeTimeProvider clock = new(DateTimeOffset.UnixEpoch); + using DashboardRevalidatingAuthenticationStateProvider provider = new(NullLoggerFactory.Instance, monitor, clock); + ClaimsPrincipal admin = Principal("alice", DashboardRoles.Admin, groups: [AdminGroup]); + + Assert.True(provider.IsStillValid(admin)); + + monitor.CurrentValue = OptionsWithRoles(includeAdmin: false); + + Assert.False(provider.IsStillValid(admin)); + } + + /// A circuit older than the cookie's idle lifetime is signed out. + [Fact] + public void Revalidation_PastCookieIdleTimeout_SignsOut() + { + StaticOptionsMonitor monitor = new(OptionsWithRoles(includeAdmin: true)); + FakeTimeProvider clock = new(DateTimeOffset.UnixEpoch); + using DashboardRevalidatingAuthenticationStateProvider provider = new(NullLoggerFactory.Instance, monitor, clock); + ClaimsPrincipal viewer = Principal("bob", DashboardRoles.Viewer, groups: [ViewerGroup]); + + clock.Advance(DashboardAuthenticationDefaults.CookieIdleTimeout - TimeSpan.FromMinutes(1)); + Assert.True(provider.IsStillValid(viewer)); + + clock.Advance(TimeSpan.FromMinutes(1)); + Assert.False(provider.IsStillValid(viewer)); + } + + /// + /// Principals with nothing to revoke stay as they are: anonymous localhost, and the + /// DisableLogin dev bypass however old the circuit. + /// + [Fact] + public void Revalidation_AnonymousAndDisableLogin_AreNeverSignedOut() + { + StaticOptionsMonitor monitor = new(new GatewayOptions + { + Dashboard = new DashboardOptions { DisableLogin = true }, + }); + FakeTimeProvider clock = new(DateTimeOffset.UnixEpoch); + using DashboardRevalidatingAuthenticationStateProvider provider = new(NullLoggerFactory.Instance, monitor, clock); + + clock.Advance(DashboardAuthenticationDefaults.CookieIdleTimeout * 2); + + Assert.True(provider.IsStillValid(new ClaimsPrincipal(new ClaimsIdentity()))); + Assert.True(provider.IsStillValid(Principal("multi-role", DashboardRoles.Admin))); + } + + private static GatewayOptions OptionsWithRoles(bool includeAdmin) + { + Dictionary groupToRole = new(StringComparer.OrdinalIgnoreCase) + { + [ViewerGroup] = DashboardRoles.Viewer, + }; + if (includeAdmin) + { + groupToRole[AdminGroup] = DashboardRoles.Admin; + } + + return new GatewayOptions { Dashboard = new DashboardOptions { GroupToRole = groupToRole } }; + } + + private static ClaimsPrincipal Principal(string name, string role, string[]? groups = null) + { + List claims = + [ + new(ClaimTypes.Name, name), + new(ClaimTypes.NameIdentifier, name), + new(ClaimTypes.Role, role), + ]; + claims.AddRange((groups ?? []).Select(group => new Claim(DashboardAuthenticationDefaults.LdapGroupClaimType, group))); + return new ClaimsPrincipal(new ClaimsIdentity(claims, "Test", ClaimTypes.Name, ClaimTypes.Role)); + } + + private sealed class StaticOptionsMonitor(T value) : IOptionsMonitor + { + public T CurrentValue { get; set; } = value; + + public T Get(string? name) => CurrentValue; + + public IDisposable? OnChange(Action listener) => null; + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceConstraintTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceConstraintTests.cs index 59593846..fbf947c9 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceConstraintTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Gateway/Grpc/MxAccessGatewayServiceConstraintTests.cs @@ -689,6 +689,140 @@ public sealed class MxAccessGatewayServiceConstraintTests Assert.Equal("Secret.Tag", enforcer.RecordedDenials[0].Target); } + // === AddBufferedItem and the fail-closed command-kind switch (SES-003) === + + /// + /// AddBufferedItem names a tag like the other adds, so an out-of-scope tag is + /// refused with , the denial is audited, and the + /// worker never sees the command. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Invoke_AddBufferedItem_WithDeniedTag_ThrowsPermissionDeniedAndDoesNotCallWorker() + { + PredicateConstraintEnforcer enforcer = new() + { + DenyTag = tag => tag == "AreaB.Tank.Level", + }; + FakeSessionManager sessionManager = CreateSessionManagerWithSeed(); + MxAccessGatewayService service = CreateService(sessionManager, enforcer); + + MxCommandRequest request = new() + { + SessionId = SessionId, + ClientCorrelationId = "corr-buffered", + Command = new MxCommand + { + Kind = MxCommandKind.AddBufferedItem, + AddBufferedItem = new AddBufferedItemCommand { ServerHandle = 7, ItemDefinition = "AreaB.Tank.Level" }, + }, + }; + + RpcException exception = await Assert.ThrowsAsync( + async () => await service.Invoke(request, new TestServerCallContext())); + + Assert.Equal(StatusCode.PermissionDenied, exception.StatusCode); + Assert.Equal(0, sessionManager.InvokeCount); + (string commandKind, string target, string? correlationId) = Assert.Single(enforcer.RecordedDenials); + Assert.Equal(nameof(MxCommandKind.AddBufferedItem), commandKind); + Assert.Equal("AreaB.Tank.Level", target); + Assert.Equal("corr-buffered", correlationId); + } + + /// An in-scope AddBufferedItem still reaches the worker. + /// A task that represents the asynchronous operation. + [Fact] + public async Task Invoke_AddBufferedItem_WithAllowedTag_ReachesWorker() + { + PredicateConstraintEnforcer enforcer = new() + { + DenyTag = tag => tag == "AreaB.Tank.Level", + }; + FakeSessionManager sessionManager = CreateSessionManagerWithSeed(); + MxAccessGatewayService service = CreateService(sessionManager, enforcer); + + await service.Invoke( + new MxCommandRequest + { + SessionId = SessionId, + Command = new MxCommand + { + Kind = MxCommandKind.AddBufferedItem, + AddBufferedItem = new AddBufferedItemCommand { ServerHandle = 7, ItemDefinition = "AreaA.Tank.Level" }, + }, + }, + new TestServerCallContext()); + + Assert.Equal(1, sessionManager.InvokeCount); + Assert.Empty(enforcer.RecordedDenials); + } + + /// + /// Every is classified exactly once: constraint-checked, + /// on the no-tag allow-list, or one of the gateway-internal alarm kinds the switch + /// refuses. A new contract value fails this test until someone decides whether it + /// carries a tag; at runtime an unclassified kind is refused, not passed through. + /// + [Fact] + public void EveryCommandKind_IsClassifiedExactlyOnceForConstraintEnforcement() + { + HashSet refusedOnInvoke = + [ + MxCommandKind.SubscribeAlarms, + MxCommandKind.UnsubscribeAlarms, + MxCommandKind.AcknowledgeAlarm, + MxCommandKind.QueryActiveAlarms, + MxCommandKind.AcknowledgeAlarmByName, + MxCommandKind.UpdateAlarmWatchList, + ]; + + foreach (MxCommandKind kind in Enum.GetValues()) + { + if (kind == MxCommandKind.Unspecified) + { + continue; + } + + int classifications = + (MxAccessGatewayService.ConstrainedCommandKinds.Contains(kind) ? 1 : 0) + + (MxAccessGatewayService.UnconstrainedCommandKinds.Contains(kind) ? 1 : 0) + + (refusedOnInvoke.Contains(kind) ? 1 : 0); + Assert.True(classifications == 1, $"MxCommandKind.{kind} is classified {classifications} times; expected exactly once."); + } + } + + /// + /// A kind on neither list — a gateway-internal alarm kind, or a value the switch has never + /// seen — is refused with and an audited denial + /// even for an unconstrained key, and never reaches the worker. + /// + /// Numeric value. + /// A task that represents the asynchronous operation. + [Theory] + [InlineData((int)MxCommandKind.SubscribeAlarms)] + [InlineData((int)MxCommandKind.UpdateAlarmWatchList)] + [InlineData((int)MxCommandKind.AcknowledgeAlarmByName)] + [InlineData(999)] + public async Task Invoke_UnclassifiedCommandKind_FailsClosed(int kindValue) + { + PredicateConstraintEnforcer enforcer = new(); + FakeSessionManager sessionManager = CreateSessionManagerWithSeed(); + MxAccessGatewayService service = CreateService(sessionManager, enforcer); + + RpcException exception = await Assert.ThrowsAsync( + async () => await service.Invoke( + new MxCommandRequest + { + SessionId = SessionId, + Command = new MxCommand { Kind = (MxCommandKind)kindValue }, + }, + new TestServerCallContext())); + + Assert.Equal(StatusCode.PermissionDenied, exception.StatusCode); + Assert.Equal(0, sessionManager.InvokeCount); + Assert.Single(enforcer.RecordedDenials); + } + // === Helpers === private static MxAccessGatewayService CreateService( 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)); } diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs index 17b05d57..d9d66524 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyFailureLimiterTests.cs @@ -313,18 +313,21 @@ public sealed class ApiKeyFailureLimiterTests Assert.Equal(ApiKeyThrottleDecision.ThrottledByPeer, limiter.Check(partition)); } - /// A successful verification clears both the composite partition and the key aggregate. + /// + /// A successful verification clears the caller's own partition and exempts that address from + /// the key's aggregate, but leaves the aggregate in place for every other address (SEC-003). + /// [Fact] - public void Reset_ClearsCompositeAndAggregateLayers() + public void Reset_ClearsOwnPartitionAndLeavesAggregateForOtherAddresses() { ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch); ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 3, aggregateLimit: 5); - ApiKeyThrottlePartition partition = new("ipv4:10.0.0.1:1", "victim"); + ApiKeyThrottlePartition partition = new("10.0.0.1", "victim"); RecordFailures(limiter, partition, 3); for (int peer = 1; peer < 3; peer++) { - limiter.RecordFailure(new ApiKeyThrottlePartition($"ipv4:10.0.1.{peer}:1", "victim")); + limiter.RecordFailure(new ApiKeyThrottlePartition($"10.0.1.{peer}", "victim")); } Assert.Equal(ApiKeyThrottleDecision.ThrottledByPeer, limiter.Check(partition)); @@ -332,10 +335,56 @@ public sealed class ApiKeyFailureLimiterTests limiter.Reset(partition); Assert.Equal(ApiKeyThrottleDecision.Allowed, limiter.Check(partition)); - Assert.Equal(0, limiter.TrackedAggregateCount); + Assert.Equal(1, limiter.TrackedAggregateCount); Assert.Equal( - ApiKeyThrottleDecision.Allowed, - limiter.Check(new ApiKeyThrottlePartition("ipv4:10.0.9.9:1", "victim"))); + ApiKeyThrottleDecision.ThrottledByAggregate, + limiter.Check(new ApiKeyThrottlePartition("10.0.9.9", "victim"))); + } + + /// + /// SEC-003: a key in steady use from its holder still accrues cross-peer failures. One success + /// between every failure used to wipe the aggregate, so it never reached its limit. + /// + [Fact] + public void Aggregate_InterleavedWithHolderSuccesses_StillTrips() + { + ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch); + ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10, aggregateLimit: 30); + ApiKeyThrottlePartition holder = new("198.51.100.4", "victim"); + + for (int i = 0; i < 30; i++) + { + limiter.RecordFailure(new ApiKeyThrottlePartition($"203.0.113.{i}", "victim")); + Assert.NotEqual(ApiKeyThrottleDecision.ThrottledByAggregate, limiter.Check(holder)); + limiter.Reset(holder); + } + + Assert.Equal( + ApiKeyThrottleDecision.ThrottledByAggregate, + limiter.Check(new ApiKeyThrottlePartition("203.0.113.200", "victim"))); + Assert.Equal(ApiKeyThrottleDecision.Allowed, limiter.Check(holder)); + } + + /// + /// The verified exemption lasts one window: once it ages out, an address with no fresh success + /// is subject to a still-tripped aggregate like any other. + /// + [Fact] + public void VerifiedExemption_ExpiresWithTheWindow() + { + ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch); + ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10, aggregateLimit: 3); + ApiKeyThrottlePartition holder = new("198.51.100.4", "victim"); + + limiter.Reset(holder); + clock.Advance(Window); + + for (int i = 0; i < 3; i++) + { + limiter.RecordFailure(new ApiKeyThrottlePartition($"203.0.113.{i}", "victim")); + } + + Assert.Equal(ApiKeyThrottleDecision.ThrottledByAggregate, limiter.Check(holder)); } /// diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyThrottlePeerTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyThrottlePeerTests.cs new file mode 100644 index 00000000..81da4808 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/ApiKeyThrottlePeerTests.cs @@ -0,0 +1,50 @@ +using System.Net; +using ZB.MOM.WW.MxGateway.Server.Security.Authorization; + +namespace ZB.MOM.WW.MxGateway.Tests.Security.Authorization; + +/// +/// Pins the address normalisation shared by the gRPC interceptor and the /metrics handler +/// (SEC-001): the source port never reaches the limiter partition, and both surfaces produce the +/// same string for the same client. +/// +public sealed class ApiKeyThrottlePeerTests +{ + /// Strips the port from each Grpc.AspNetCore peer form. + /// The ServerCallContext.Peer value. + /// The expected address. + [Theory] + [InlineData("ipv4:203.0.113.7:40001", "203.0.113.7")] + [InlineData("ipv4:127.0.0.1:5000", "127.0.0.1")] + [InlineData("ipv6:[::1]:5000", "::1")] + [InlineData("ipv6:[2001:db8::7]:40001", "2001:db8::7")] + [InlineData("ipv6:[::ffff:203.0.113.7]:40001", "203.0.113.7")] + public void FromGrpcPeer_StripsPort(string grpcPeer, string expected) + { + Assert.Equal(expected, ApiKeyThrottlePeer.FromGrpcPeer(grpcPeer)); + } + + /// A peer with no address/port shape is kept verbatim rather than guessed at. + /// The ServerCallContext.Peer value. + [Theory] + [InlineData("unknown")] + [InlineData("unix:/tmp/mxgw.sock")] + [InlineData("ipv6:[not-an-address]:1")] + public void FromGrpcPeer_KeepsUnrecognisedForms(string grpcPeer) + { + Assert.Equal(grpcPeer, ApiKeyThrottlePeer.FromGrpcPeer(grpcPeer)); + } + + /// + /// The gRPC and HTTP surfaces agree, so a failure counted on one is charged to the same + /// partition on the other — including an IPv4 client seen through a dual-stack listener. + /// + [Fact] + public void FromRemoteIp_MatchesGrpcPeerForm() + { + Assert.Equal( + ApiKeyThrottlePeer.FromGrpcPeer("ipv4:203.0.113.7:40001"), + ApiKeyThrottlePeer.FromRemoteIp(IPAddress.Parse("::ffff:203.0.113.7"))); + Assert.Equal("unknown", ApiKeyThrottlePeer.FromRemoteIp(null)); + } +} diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs index 64828fe8..d7e30348 100644 --- a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/GatewayGrpcAuthorizationInterceptorTests.cs @@ -406,6 +406,287 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests Assert.Equal(3, verifier.CallCount); } + /// + /// SEC-001: the partition is the remote IP, not the TCP connection. Failures from two + /// connections of one address (different ephemeral source ports) share one partition, so + /// reconnecting does not reset the count: nine failures on each connection trip the limit of + /// ten and the eleventh attempt overall is throttled without reaching the verifier. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task Failures_FromSameAddressOnDifferentSourcePorts_ShareOnePartition() + { + CountingFailureVerifier verifier = new(Failure(ApiKeyFailure.SecretMismatch)); + ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch); + ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10); + GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor( + verifier, + new GatewayRequestIdentityAccessor(), + failureLimiter: limiter); + + List statuses = []; + foreach (string peer in new[] { "ipv4:203.0.113.7:40001", "ipv4:203.0.113.7:40002" }) + { + for (int attempt = 0; attempt < 9; attempt++) + { + RpcException failure = await Assert.ThrowsAsync( + () => interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer mxgw_operator01_bad-secret", peer), + (_, _) => Task.FromResult(new OpenSessionReply()))); + statuses.Add(failure.StatusCode); + } + } + + Assert.All(statuses.Take(10), status => Assert.Equal(StatusCode.Unauthenticated, status)); + Assert.Equal(StatusCode.ResourceExhausted, statuses[10]); + Assert.Equal(10, verifier.CallCount); + Assert.Equal(1, limiter.TrackedPartitionCount); + } + + /// + /// SEC-001, junk-token path: tokens with no key id fall back to the address partition, and that + /// partition must also survive a reconnect, or junk spraying would never be throttled. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task JunkTokens_FromSameAddressOnDifferentSourcePorts_AreThrottled() + { + CountingFailureVerifier verifier = new(Failure(ApiKeyFailure.MissingOrMalformed)); + ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch); + ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 3); + GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor( + verifier, + new GatewayRequestIdentityAccessor(), + failureLimiter: limiter); + + StatusCode last = StatusCode.OK; + for (int port = 50000; port < 50004; port++) + { + RpcException failure = await Assert.ThrowsAsync( + () => interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer garbage", $"ipv6:[2001:db8::7]:{port}"), + (_, _) => Task.FromResult(new OpenSessionReply()))); + last = failure.StatusCode; + } + + Assert.Equal(StatusCode.ResourceExhausted, last); + Assert.Equal(3, verifier.CallCount); + } + + /// + /// SEC-002: a holder whose verification is cached is never refused by a spray against its key + /// id. Thirty bad secrets from thirty addresses trip the aggregate; the holder's next call — + /// inside the cache TTL and inside the probe interval — is served from the cache without + /// consulting the limiter, even from an address that never verified before. + /// + /// Address the holder calls from after the spray. + /// A task that represents the asynchronous operation. + [Theory] + [InlineData(HolderPeer)] + [InlineData("ipv4:192.0.2.55:41000")] + public async Task CachedHolder_AfterAggregateSpray_IsNotThrottled(string holderPeer) + { + ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch); + ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10, aggregateLimit: 30); + SecretMatchingVerifier inner = new("correct"); + using Microsoft.Extensions.Caching.Memory.MemoryCache cache = new(new Microsoft.Extensions.Caching.Memory.MemoryCacheOptions()); + CachingApiKeyVerifier verifier = new(inner, cache, TimeSpan.FromMinutes(5)); + GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor( + verifier, + new GatewayRequestIdentityAccessor(), + failureLimiter: limiter); + + await interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer mxgw_operator01_correct", HolderPeer), + (_, _) => Task.FromResult(new OpenSessionReply())); + + for (int peer = 0; peer < 30; peer++) + { + await Assert.ThrowsAsync( + () => interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer mxgw_operator01_guess", $"ipv4:203.0.113.{peer}:5000"), + (_, _) => Task.FromResult(new OpenSessionReply()))); + } + + RpcException sprayer = await Assert.ThrowsAsync( + () => interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer mxgw_operator01_guess", "ipv4:203.0.113.250:5000"), + (_, _) => Task.FromResult(new OpenSessionReply()))); + Assert.Equal(StatusCode.ResourceExhausted, sprayer.StatusCode); + + int innerCallsBefore = inner.CallCount; + OpenSessionReply reply = await interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer mxgw_operator01_correct", holderPeer), + (_, _) => Task.FromResult(new OpenSessionReply { SessionId = "session-1" })); + + Assert.Equal("session-1", reply.SessionId); + Assert.Equal(innerCallsBefore, inner.CallCount); + } + + /// + /// SEC-002 without a cache hit (TTL expired, or a non-caching verifier): an address that + /// verified the key inside the window is exempt from the tripped aggregate, so it still reaches + /// the verifier instead of competing with the sprayer for the probe slot. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task RecentlyVerifiedHolder_OnCacheMiss_IsExemptFromTrippedAggregate() + { + ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch); + ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10, aggregateLimit: 30); + SecretMatchingVerifier verifier = new("correct"); + GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor( + verifier, + new GatewayRequestIdentityAccessor(), + failureLimiter: limiter); + + await interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer mxgw_operator01_correct", HolderPeer), + (_, _) => Task.FromResult(new OpenSessionReply())); + + for (int peer = 0; peer < 31; peer++) + { + await Assert.ThrowsAsync( + () => interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer mxgw_operator01_guess", $"ipv4:203.0.113.{peer}:5000"), + (_, _) => Task.FromResult(new OpenSessionReply()))); + } + + for (int call = 0; call < 3; call++) + { + OpenSessionReply reply = await interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer mxgw_operator01_correct", "ipv4:198.51.100.4:6000"), + (_, _) => Task.FromResult(new OpenSessionReply { SessionId = "session-1" })); + Assert.Equal("session-1", reply.SessionId); + } + } + + /// + /// SEC-003 end to end: one holder success between every bad guess no longer wipes the + /// aggregate, so after thirty guesses from thirty addresses a new address is throttled. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ActiveKey_InterleavedWithSpray_StillAccruesAggregate() + { + ManualTimeProvider clock = new(DateTimeOffset.UnixEpoch); + ApiKeyFailureLimiter limiter = CreateLimiter(clock, limit: 10, aggregateLimit: 30); + SecretMatchingVerifier verifier = new("correct"); + GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor( + verifier, + new GatewayRequestIdentityAccessor(), + failureLimiter: limiter); + + for (int peer = 0; peer < 30; peer++) + { + await interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer mxgw_operator01_correct", HolderPeer), + (_, _) => Task.FromResult(new OpenSessionReply())); + await Assert.ThrowsAsync( + () => interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer mxgw_operator01_guess", $"ipv4:203.0.113.{peer}:5000"), + (_, _) => Task.FromResult(new OpenSessionReply()))); + } + + int verifierCallsBefore = verifier.CallCount; + RpcException throttled = await Assert.ThrowsAsync( + () => interceptor.UnaryServerHandler( + new OpenSessionRequest(), + ContextWithAuthorization("Bearer mxgw_operator01_guess", "ipv4:203.0.113.250:5000"), + (_, _) => Task.FromResult(new OpenSessionReply()))); + + Assert.Equal(StatusCode.ResourceExhausted, throttled.StatusCode); + Assert.Equal(verifierCallsBefore, verifier.CallCount); + } + + /// + /// SEC-004: revoking a key mid-stream ends the open streaming call with + /// , whatever status the handler maps its cancellation + /// to, and releases the registration. + /// + /// Whether the handler converts its cancellation to an RpcException(Cancelled), as the gateway services do. + /// A task that represents the asynchronous operation. + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task RevokeKey_MidStream_EndsStreamWithUnauthenticated(bool handlerMapsCancellation) + { + ApiKeyStreamRegistry registry = new(); + GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor( + new FakeApiKeyVerifier(SuccessWithScopes(GatewayScopes.EventsRead)), + new GatewayRequestIdentityAccessor(), + streamRegistry: registry); + TaskCompletionSource streaming = new(TaskCreationOptions.RunContinuationsAsynchronously); + + Task call = interceptor.ServerStreamingServerHandler( + new StreamEventsRequest { SessionId = "session-1" }, + new RecordingServerStreamWriter(), + ContextWithAuthorization("Bearer mxgw_operator01_secret"), + async (_, _, context) => + { + streaming.SetResult(); + try + { + await Task.Delay(Timeout.Infinite, context.CancellationToken); + } + catch (OperationCanceledException) when (handlerMapsCancellation) + { + throw new RpcException(new Status(StatusCode.Cancelled, "gRPC request was canceled.")); + } + }); + + await streaming.Task.WaitAsync(TimeSpan.FromSeconds(10)); + Assert.Equal(1, registry.CountFor("operator01")); + + Assert.Equal(0, registry.Revoke("someone-else")); + Assert.False(call.IsCompleted); + Assert.Equal(1, registry.Revoke("operator01")); + + RpcException exception = await Assert.ThrowsAsync(() => call.WaitAsync(TimeSpan.FromSeconds(10))); + Assert.Equal(StatusCode.Unauthenticated, exception.StatusCode); + Assert.Equal(0, registry.CountFor("operator01")); + } + + /// + /// A stream that ends on its own is not reported as revoked, and the handler sees the real + /// call's metadata through the revocable context. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task StreamingCall_WithoutRevocation_CompletesNormallyAndUnregisters() + { + ApiKeyStreamRegistry registry = new(); + GatewayGrpcAuthorizationInterceptor interceptor = CreateInterceptor( + new FakeApiKeyVerifier(SuccessWithScopes(GatewayScopes.EventsRead)), + new GatewayRequestIdentityAccessor(), + streamRegistry: registry); + string? seenPeer = null; + + await interceptor.ServerStreamingServerHandler( + new StreamEventsRequest { SessionId = "session-1" }, + new RecordingServerStreamWriter(), + ContextWithAuthorization("Bearer mxgw_operator01_secret", HolderPeer), + (_, _, context) => + { + seenPeer = context.Peer; + return Task.CompletedTask; + }); + + Assert.Equal(HolderPeer, seenPeer); + Assert.Equal(0, registry.CountFor("operator01")); + } + /// /// Lockout inversion: an attacker who floods failures for a victim's key id from its /// own address must not deny that key to the legitimate holder. The holder presents the correct @@ -609,7 +890,7 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests } Assert.Equal(1, limiter.TrackedPartitionCount); - Assert.True(limiter.IsTracked(new ApiKeyThrottlePartition(AttackerPeer, KeyId: null))); + Assert.True(limiter.IsTracked(new ApiKeyThrottlePartition(ApiKeyThrottlePeer.FromGrpcPeer(AttackerPeer), KeyId: null))); } /// @@ -882,7 +1163,8 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests IApiKeyVerifier apiKeyVerifier, IGatewayRequestIdentityAccessor identityAccessor, AuthenticationMode authenticationMode = AuthenticationMode.ApiKey, - ApiKeyFailureLimiter? failureLimiter = null) + ApiKeyFailureLimiter? failureLimiter = null, + ApiKeyStreamRegistry? streamRegistry = null) { return new GatewayGrpcAuthorizationInterceptor( apiKeyVerifier, @@ -896,7 +1178,8 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests } }), failureLimiter ?? CreateLimiter(TimeProvider.System, limit: 1000), - new GatewayMetrics()); + new GatewayMetrics(), + streamRegistry); } private static ApiKeyFailureLimiter CreateLimiter( @@ -1055,6 +1338,26 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests } } + // Succeeds (with session:open) only for a token whose secret is the configured one; every + // other token fails as a secret mismatch. Counts calls so a test can tell a cache hit or a + // throttle from a real verification. + private sealed class SecretMatchingVerifier(string correctSecret) : IApiKeyVerifier + { + private int _callCount; + + /// Gets the number of verifications performed. + public int CallCount => Volatile.Read(ref _callCount); + + /// + public Task VerifyAsync(string authorizationHeader, CancellationToken ct) + { + Interlocked.Increment(ref _callCount); + return Task.FromResult(authorizationHeader.EndsWith("_" + correctSecret, StringComparison.Ordinal) + ? SuccessWithScopes(GatewayScopes.SessionOpen) + : Failure(ApiKeyFailure.SecretMismatch)); + } + } + private sealed class FakeApiKeyVerifier(ApiKeyVerification result) : IApiKeyVerifier { /// Gets whether the verifier was called. diff --git a/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/RevocableServerCallContextTests.cs b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/RevocableServerCallContextTests.cs new file mode 100644 index 00000000..ecfe51a8 --- /dev/null +++ b/src/ZB.MOM.WW.MxGateway.Tests/Security/Authorization/RevocableServerCallContextTests.cs @@ -0,0 +1,40 @@ +using Grpc.Core; +using Microsoft.AspNetCore.Http; +using ZB.MOM.WW.MxGateway.Server.Security.Authorization; +using ZB.MOM.WW.MxGateway.Tests.TestSupport; + +namespace ZB.MOM.WW.MxGateway.Tests.Security.Authorization; + +/// +/// The context handed to streaming handlers (SEC-004) must behave as the real call context in +/// every respect except its cancellation token. +/// +public sealed class RevocableServerCallContextTests +{ + /// Metadata, status, trailers, user state and the HttpContext all pass through. + [Fact] + public void Wrapper_ForwardsEverythingButCancellation() + { + DefaultHttpContext httpContext = new(); + TestServerCallContext inner = new( + [new Metadata.Entry("x-test", "1")], + peer: "ipv4:192.0.2.1:5000"); + inner.UserState["__HttpContext"] = httpContext; + using CancellationTokenSource revocation = new(); + + RevocableServerCallContext wrapper = new(inner, revocation.Token); + wrapper.Status = new Status(StatusCode.Unauthenticated, "revoked"); + wrapper.ResponseTrailers.Add("x-trailer", "2"); + + Assert.Equal("ipv4:192.0.2.1:5000", wrapper.Peer); + Assert.Equal("1", wrapper.RequestHeaders.GetValue("x-test")); + Assert.Equal(StatusCode.Unauthenticated, inner.Status.StatusCode); + Assert.Equal("2", inner.ResponseTrailers.GetValue("x-trailer")); + Assert.Same(httpContext, wrapper.GetHttpContext()); + + Assert.False(wrapper.CancellationToken.IsCancellationRequested); + revocation.Cancel(); + Assert.True(wrapper.CancellationToken.IsCancellationRequested); + Assert.False(inner.CancellationToken.IsCancellationRequested); + } +}