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

This commit is contained in:
Joseph Doherty
2026-12-03 10:18:42 -05:00
35 changed files with 2261 additions and 76 deletions
+2 -2
View File
@@ -176,9 +176,9 @@ External analysis sources referenced by design docs:
Gateway gRPC clients authenticate with an API key in metadata: `authorization: Bearer mxgw_<key-id>_<secret>`. 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
+12 -4
View File
@@ -104,7 +104,12 @@ library:
it after writing the cache entry (set-then-recheck); a revoke that lands while a
verification is still in flight in the inner library therefore discards that
verification's repopulation instead of re-caching the just-revoked identity for a
full TTL (SEC-34). The short TTL remains the backstop for two bounded-staleness
full TTL (SEC-34). The same revoke/rotate/delete also calls
`ApiKeyStreamRegistry.Revoke(keyId)`, which ends every streaming call the key
already has open (SEC-004): a streaming call is authenticated once, at open, so
evicting the cache alone left an open `StreamEvents`, `StreamAlarms` or
`WatchDeployEvents` delivering data until the client disconnected. See
[Authorization](./Authorization.md#streaming-calls-and-revocation). The short TTL remains the backstop for two bounded-staleness
windows it cannot close directly: (1) out-of-band mutations (a direct DB edit, or a
revoke run by the separate `apikey` CLI process, whose in-memory cache is not the
running gateway's cache); and (2) a key whose `ExpiresUtc` passes while cached keeps
@@ -141,7 +146,7 @@ Failures are never cached — a wrong secret always reaches the store — so the
failure path is shielded by `ApiKeyFailureLimiter` instead, consulted before
`VerifyAsync` runs. It counts failures over one sliding
`MxGateway:Security:ApiKeyFailureWindowSeconds` window in two layers: a composite
`(transport peer, key id)` partition capped at `ApiKeyFailureLimit`, and a
`(remote IP, key id)` partition capped at `ApiKeyFailureLimit`, and a
per-key-id aggregate across all peers capped at `ApiKeyFailureAggregateLimit`. The
key id never partitions on its own — it is public, so an attacker-supplied one
would otherwise let any peer throttle a key it does not hold — and it joins the
@@ -153,8 +158,11 @@ the cross-peer aggregate: its failures still feed and consult the key-id aggrega
whose own cardinality is bounded by the configured LRU cap. An over-limit state admits one probe per
`ApiKeyFailureProbeIntervalSeconds` through to the real verifier and refuses
everything else with `ResourceExhausted` before the store read, so a legitimate
holder presenting the correct secret always reaches the constant-time compare and
resets both layers; the counter's LRU eviction (`ApiKeyFailureTrackedPeers`)
holder presenting the correct secret always reaches the constant-time compare. A
success clears the caller's own partition and exempts its address from the key's
aggregate for one window, but leaves the aggregate itself to decay, and a cached
success skips the limiter altogether (see [Authorization](./Authorization.md));
the counter's LRU eviction (`ApiKeyFailureTrackedPeers`)
prefers expired windows and will not drop an over-limit partition below a 2x
overshoot ceiling, so the memory bound cannot be turned into a way to clear an
active block. See [Authorization](./Authorization.md) for the enforcement path.
+70 -6
View File
@@ -96,13 +96,35 @@ The status codes are deliberately distinct: `Unauthenticated` signals "we do not
Before the verification store read, the helper asks a cheap in-process failure counter (`ApiKeyFailureLimiter`) whether the attempt may proceed, so online guessing of API-key secrets cannot spend a SQLite read (and, in a naive design, a cache miss) per attempt. The counter has two layers over one sliding `ApiKeyFailureWindowSeconds` window:
- **Composite `(transport peer, key id)` partitions.** Reaching `MxGateway:Security:ApiKeyFailureLimit` failures binds the throttle to the address that produced them. The key id alone is never the partition: key ids are not secret — they ride in every token and are listed on the dashboard — so keying on them let any network peer deny a key to its legitimate holder. The key id joins the partition only after a token-shape check (literal `mxgw` prefix, at least three non-empty `_` segments, key id of at most 64 characters), and one address may mint at most 32 key-id partitions before the overflow collapses onto that address's fallback partition.
- **Composite `(remote IP, key id)` partitions.** Reaching `MxGateway:Security:ApiKeyFailureLimit` failures binds the throttle to the address that produced them. The address is the client's IP with the source port stripped (`ApiKeyThrottlePeer`): the port is ephemeral, and keying on it made every new TCP connection a fresh partition, so a client could send `limit - 1` bad secrets, reconnect, and repeat without ever being throttled (SEC-001). The gRPC interceptor (parsing `ServerCallContext.Peer`) and the `/metrics` handler (`Connection.RemoteIpAddress`) normalise through the same helper, with IPv4-mapped IPv6 reduced to IPv4, so a failure on either surface counts against the same partition. The key id alone is never the partition: key ids are not secret — they ride in every token and are listed on the dashboard — so keying on them let any network peer deny a key to its legitimate holder. The key id joins the partition only after a token-shape check (literal `mxgw` prefix, at least three non-empty `_` segments, key id of at most 64 characters), and one address may mint at most 32 key-id partitions before the overflow collapses onto that address's fallback partition.
- **A per-key-id aggregate** across all peers (`ApiKeyFailureAggregateLimit`, default 30), which bounds a distributed or source-rotating sprayer that never trips any single partition.
An over-limit state is a valve, not a wall: one request per `ApiKeyFailureProbeIntervalSeconds` (default 5 s) is admitted through to the real verifier, and everything else is refused with `StatusCode.ResourceExhausted` before the store read. The slot is claimed atomically, so a burst arriving together at an interval boundary still yields exactly one admission, and a slot claimed for a request that a later layer then refuses is handed back under a per-state version stamp — never by timestamp comparison, which collides whenever a concurrent failure re-arms the same state on the same clock tick. A successful verification resets both layers — which is why the reset path stays reachable while a key is under active spray. One exception: when the caller's key id was collapsed into its address's shared fallback partition by the per-peer cap, a success clears the key's aggregate but leaves that shared partition alone, since it also holds failures contributed by other key ids from the same address. The tracked partitions form a bounded LRU (`ApiKeyFailureTrackedPeers`) whose eviction prefers fully expired windows and never removes an over-limit partition below a 2x transient overshoot ceiling, so the cap bounds memory without becoming a reset button for an active block. `ResourceExhausted` reveals only that throttling is in effect, not whether any particular secret was valid, preserving the opaque-failure property. Refusals increment `mxgateway.auth.throttled`, tagged `stage=peer|aggregate` and nothing else — `/metrics` is anonymous by default (`MxGateway:Metrics:RequireAuthentication` is opt-in), so neither key ids nor peer addresses may appear there.
An over-limit state is a valve, not a wall: one request per `ApiKeyFailureProbeIntervalSeconds` (default 5 s) is admitted through to the real verifier, and everything else is refused with `StatusCode.ResourceExhausted` before the store read. The slot is claimed atomically, so a burst arriving together at an interval boundary still yields exactly one admission, and a slot claimed for a request that a later layer then refuses is handed back under a per-state version stamp — never by timestamp comparison, which collides whenever a concurrent failure re-arms the same state on the same clock tick. A successful verification clears the caller's own `(remote IP, key id)` partition and marks that pair verified for one window; it does **not** clear the key id's cross-peer aggregate, which decays by window expiry only (SEC-003). Clearing the aggregate on success meant a key in steady use — many successful calls a second — never accumulated one, so a sprayer guessing that key id from other addresses was bounded by neither layer. When the caller's key id was collapsed into its address's shared fallback partition by the per-peer cap, a success leaves that shared partition alone too, since it also holds failures contributed by other key ids from the same address.
Two rules keep the holder of the correct secret from being denied by a spray against its public key id (SEC-002). First, the interceptor (and the `/metrics` handler) consult the verification cache **before** the limiter: a cached success (`IApiKeyVerificationCache`, implemented by `CachingApiKeyVerifier`) is proof of the correct token and costs no store read — the only thing the limiter protects — so it skips the limiter entirely. Second, on a cache miss, an address that verified the key inside the window skips the aggregate layer, so the holder does not have to win the probe slot against the sprayer once its cache entry expires. Neither path is reachable without the correct secret; a new address presenting the correct secret while the aggregate is tripped still goes through the probe slot once, then is exempt. The tracked partitions form a bounded LRU (`ApiKeyFailureTrackedPeers`) whose eviction prefers fully expired windows and never removes an over-limit partition below a 2x transient overshoot ceiling, so the cap bounds memory without becoming a reset button for an active block. `ResourceExhausted` reveals only that throttling is in effect, not whether any particular secret was valid, preserving the opaque-failure property. Refusals increment `mxgateway.auth.throttled`, tagged `stage=peer|aggregate` and nothing else — `/metrics` is anonymous by default (`MxGateway:Metrics:RequireAuthentication` is opt-in), so neither key ids nor peer addresses may appear there.
The dashboard login surface is throttled independently: `POST /auth/login` carries a fixed-window ASP.NET Core rate-limiter policy keyed per remote IP (`MxGateway:Security:LoginRateLimit*`), rejecting a burst with HTTP 429 before the LDAP bind is relayed to the directory. See [GatewayConfiguration](./GatewayConfiguration.md#security-options).
### Streaming calls and revocation
A streaming call is authenticated once, when it opens. To keep a revoked key from
holding a stream open indefinitely (SEC-004), the interceptor registers every
streaming call (server, client and duplex) in `ApiKeyStreamRegistry` under the
caller's key id, and hands the handler a `RevocableServerCallContext`: the real call
context with a cancellation token that also fires when the key is revoked. The
dashboard API Keys page calls `ApiKeyStreamRegistry.Revoke(keyId)` on Revoke, Rotate
and Delete, right after it evicts the verification cache. The handler stops on its
token as it would for a client cancel, and the interceptor reports the end of the
call as `Unauthenticated` — the status a new call with that key now gets — whatever
status the handler mapped its cancellation to. Rotate ends the key's streams too,
since they were opened with the secret the rotation retires; the client reconnects
with the new secret. Unary calls are not tracked: they complete within the command
timeout.
Only revocations made inside the gateway process reach the registry. A key revoked
by the separate `apikey` CLI process keeps its open streams until they reconnect,
the same out-of-band window its verification-cache entry has.
## Scope Resolution
`GatewayGrpcScopeResolver` is a stateless singleton that switches on the runtime request type. Top-level RPC requests map directly:
@@ -249,10 +271,26 @@ page create dialog (see
[Gateway Dashboard Design](./GatewayDashboardDesign.md#api-keys-page)). The
dashboard API Keys page also renders each key's effective constraints.
The service checks read constraints for `AddItem`, `AddItem2`, `AddItemBulk`,
`SubscribeBulk`, `AdviseItemBulk`, and `ReadBulk`. It checks write constraints
for `Write`, `Write2`, `WriteSecured`, `WriteSecured2`, `WriteBulk`,
`Write2Bulk`, `WriteSecuredBulk`, and `WriteSecured2Bulk`. Bulk commands run
The service checks read constraints for `AddItem`, `AddItem2`,
`AddBufferedItem`, `AddItemBulk`, `SubscribeBulk`, `AdviseItemBulk`, and
`ReadBulk`. It checks write constraints for `Write`, `Write2`, `WriteSecured`,
`WriteSecured2`, `WriteBulk`, `Write2Bulk`, `WriteSecuredBulk`, and
`WriteSecured2Bulk`. Handle-only commands (`Advise`, `RemoveItem`, the
un-advise and remove bulks) and commands with no tag at all (`Register`,
`Ping`, `DrainEvents`, ...) are on an explicit no-tag allow-list
(`MxAccessGatewayService.UnconstrainedCommandKinds`); single `Advise` relies on
the add that produced the handle having been checked.
The command-kind switch fails closed. A kind that is on neither the checked list
(`ConstrainedCommandKinds`) nor the allow-list is refused with
`PermissionDenied` and one audited `constraint-denied` event, for every key,
constrained or not. Today that covers the gateway-internal alarm kinds
(`SubscribeAlarms`, `UpdateAlarmWatchList`, `AcknowledgeAlarmByName`, ...),
which the gateway's alarm monitor sends through `ISessionManager` and which the
public `Invoke` could only ever deliver without a payload, and any kind added
to the contract later. A unit test enumerates `MxCommandKind` and fails until a
new kind is classified, so a new tag-bearing kind cannot reach the worker
unchecked the way `AddBufferedItem` once did (SES-003). Bulk commands run
through `BulkConstraintPlan` (`ReadBulkConstraintPlan`,
`WriteBulkConstraintPlan`, `SubscribeBulkConstraintPlan`), which preserves the
caller's input order: each entry is evaluated against the constraint surface,
@@ -277,6 +315,32 @@ that drops on full, so per-item events let a single low-privilege key flush
every other pending audit record with one large bulk command. Secured values
and raw credentials are never logged.
## Session Ownership
Scopes say what verbs a key may use; they do not say whose sessions it may use
them on. Every session-scoped RPC is therefore also **owner-scoped**.
`OpenSession` records the caller's key id as `GatewaySession.OwnerKeyId`, and
`StreamEvents`, `Invoke` (every command kind) and `CloseSession` refuse a caller
whose key id differs with `PermissionDenied`, before the session manager or the
worker is reached. The compare is ordinal, and a `null` owner (a session opened
with authentication disabled) matches only a `null` caller key.
`MxAccessGatewayService.EnsureOwner` holds the check for `Invoke` and
`CloseSession`; `EventStreamService` holds the same check for the stream attach.
Without the owner rule, knowing a session id plus a matching scope would be
enough. Session ids appear on the dashboard Sessions pages and in logs, so an
`events:read` key could call `Invoke(DrainEvents)` on another key's session and
dequeue its events (which the owner's stream then never sees), and an
`invoke:write` key could write through it.
There is **no `admin` override**: an `admin`-scoped key is refused like any
other foreign key. Operators close or kill other keys' sessions from the
dashboard, which calls `ISessionManager` directly. Internal callers (the alarm
monitor, the dashboard live read) go through `ISessionManager` as well and are
not affected. The session-less alarm RPCs (`AcknowledgeAlarm`, `StreamAlarms`,
`QueryActiveAlarms`) and the Galaxy Repository RPCs have no session and so no
owner to check.
## Scope Catalog
`GatewayScopes` is the single source of truth for scope strings. Every entry is currently mapped by either the resolver or another security component:
+15 -1
View File
@@ -94,7 +94,21 @@ the caller's key id matches the owner. Gating on the `events:read` scope alone w
rejected: it would let any `events:read`-scoped key that learned a session id
attach to another key's retained session and receive its replayed and live data. The check
runs before any subscriber is attached, so a foreign key never touches the
replay ring. Admin-scope override is deferred.
replay ring.
Decision (2026-12-03, SES-002 / #241): the owner rule covers every
session-scoped RPC, not just the stream. `Invoke` (every command kind) and
`CloseSession` apply the same ordinal compare as `StreamEvents` and return
`PermissionDenied` to a foreign key before the session manager is reached.
Owner-scoping only the stream left `Invoke(DrainEvents)` — which needs only
`events:read` and dequeues from the same worker queue the event pump drains — as
a way to read another key's events, and let a foreign key write through, or
close, a session it did not open. There is **no admin override**: an
`admin`-scoped key is refused like any other foreign key. Operators close or
kill any session from the dashboard, which calls `ISessionManager` directly and
does not pass through the gRPC owner check; a gRPC override would be a separate,
explicit, audited feature. Internal callers (the alarm monitor, the dashboard)
use `ISessionManager` directly and are unaffected.
## Event Subscribers
+2 -2
View File
@@ -458,9 +458,9 @@ model requires otherwise.
| `MxGateway:Security:ApiKeyLastUsedCoalesceSeconds` | `60` | Coalescing window, in seconds, for the `last_used_utc` write. The library verifier writes `last_used` on every successful verification; this bounds the write to at most one per key per window, so a hammered key does not churn the WAL. `0` forwards every write. Must be zero or greater. |
| `MxGateway:Security:LoginRateLimitPermitLimit` | `10` | Maximum `POST /auth/login` attempts permitted per remote IP within `LoginRateLimitWindowSeconds` before requests are rejected with HTTP 429. Throttles LDAP credential stuffing before the bind is relayed to the directory. Must be greater than zero. |
| `MxGateway:Security:LoginRateLimitWindowSeconds` | `60` | Fixed-window length, in seconds, for the per-IP login rate limit. Must be greater than zero. |
| `MxGateway:Security:ApiKeyFailureLimit` | `10` | Failed API-key verifications, per `(transport peer, key id)` partition, within `ApiKeyFailureWindowSeconds` that trip the in-process short-circuit. Once tripped, the gRPC auth path rejects further attempts from that partition with `ResourceExhausted` **before** the store read — except for the probe admitted every `ApiKeyFailureProbeIntervalSeconds` — and a successful verification resets the partition. The partition always includes the sender's transport address: key ids are public (they ride in every token and are listed on the dashboard), so keying on the key id alone let any peer deny a key to its legitimate holder. Must be greater than zero. |
| `MxGateway:Security:ApiKeyFailureLimit` | `10` | Failed API-key verifications, per `(remote IP, key id)` partition (the source port is not part of it), within `ApiKeyFailureWindowSeconds` that trip the in-process short-circuit. Once tripped, the gRPC auth path rejects further attempts from that partition with `ResourceExhausted` **before** the store read — except for the probe admitted every `ApiKeyFailureProbeIntervalSeconds` — and a successful verification resets the partition. The partition always includes the sender's transport address: key ids are public (they ride in every token and are listed on the dashboard), so keying on the key id alone let any peer deny a key to its legitimate holder. Must be greater than zero. |
| `MxGateway:Security:ApiKeyFailureWindowSeconds` | `60` | Sliding-window length, in seconds, over which API-key verification failures are counted, for both the per-partition and the per-key-id aggregate layer. Must be greater than zero. |
| `MxGateway:Security:ApiKeyFailureAggregateLimit` | `30` | Failed verifications for one key id counted across **all** transport peers within `ApiKeyFailureWindowSeconds` before that key id enters probe mode. This second layer bounds a distributed or source-rotating sprayer that never trips any single `(peer, key id)` partition. `0` disables the aggregate layer, leaving only per-partition counting. Must be zero or greater. |
| `MxGateway:Security:ApiKeyFailureAggregateLimit` | `30` | Failed verifications for one key id counted across **all** transport peers within `ApiKeyFailureWindowSeconds` before that key id enters probe mode. This second layer bounds a distributed or source-rotating sprayer that never trips any single `(remote IP, key id)` partition. A successful verification does not clear it (it decays by window); addresses that verified the key inside the window, and cached verifications, are exempt so the holder is never locked out. `0` disables the aggregate layer, leaving only per-partition counting. Must be zero or greater. |
| `MxGateway:Security:ApiKeyFailureProbeIntervalSeconds` | `5` | Minimum interval, in seconds, between probe admissions for an over-limit partition or key-id aggregate. An over-limit state is a valve rather than a wall: one request per interval reaches the real verifier — exactly one, even when a burst arrives together at the interval boundary — so the holder of the correct secret always gets through and clears the state, while everything else is still refused before the store read. `0` blocks absolutely instead — **not recommended**, because an unauthenticated peer can then deny the key to its holder for the whole window. Must be zero or greater. |
| `MxGateway:Security:AuditRetentionDays` | `90` | Days of canonical audit history kept in the `audit_event` table. The audit drain sweeps once at startup and hourly thereafter, deleting rows older than this window; without it the table grows without bound inside the same SQLite file the authentication hot path reads. Rows whose timestamp SQLite cannot parse are never swept. Must be greater than zero — retention can be widened but not switched off. |
| `MxGateway:Security:ApiKeyFailureTrackedPeers` | `4096` | Maximum distinct partitions tracked by the failure counter (a bounded LRU) so a spray of unique tokens cannot grow memory without limit. It cannot be used to flush an active block either: only a validly shaped `mxgw_<keyId>_<secret>` token mints a key-id partition (everything else lands on the sender's transport-peer partition), each address may mint at most 32 key-id partitions before the overflow collapses onto that address's fallback partition, and eviction prefers fully expired windows, never removing an over-limit partition until the map exceeds twice this cap. Must be greater than zero. |
+38 -3
View File
@@ -627,6 +627,15 @@ policy `AlarmsHub` carries — the two read one central monitor and must not dis
may see it — and the side rail hides the Alarms link for callers the policy denies. What a
permitted caller sees is galaxy-wide and not tag-scoped; see "Alarm-feed visibility".
The attribute is enforced on both routes into the page. A full HTTP request meets endpoint
authorization. An in-circuit navigation (an in-page link, or `Blazor.navigateTo` from the
console) issues no HTTP request, so `Routes.razor` renders pages through `AuthorizeRouteView`,
which evaluates the page's `[Authorize]` attribute against the circuit's principal and renders a
"Not Authorized" panel instead. Before DSH-001 (#243) the router used a plain `RouteView`, so an
anonymous-localhost caller could reach this page, and a Viewer could reach the mounted Secrets
page (`/admin/secrets`, `secrets:manage`) and its secret-metadata list, by navigating inside an
existing circuit.
### Live data source
Both the Browse subscription panel and the Alarms page read live MXAccess data
@@ -720,6 +729,9 @@ anonymous localhost session shows the same read-only view.
old one. Active keys only — rotating a revoked key would un-revoke it, so
the button is not shown on revoked rows.
- **Revoke** marks a key revoked; a revoked key cannot be un-revoked.
Revoke, Rotate and Delete also end every streaming gRPC call the key
already has open (`ApiKeyStreamRegistry`, SEC-004); the client sees
`Unauthenticated`.
- **Delete** permanently removes a key row from the auth database, but only
when the key is already revoked. `IApiKeyAdminStore.DeleteAsync` rejects
active keys (returns false) so the revoke event lands in the audit log
@@ -817,8 +829,10 @@ they do not use.
The in-process page feeds carry no authentication of their own, and need none:
`MapRazorComponents<App>()` applies `RequireAuthorization(ViewerPolicy)` to the
component endpoints, so a page can only run inside a circuit whose principal is
already an authorized Viewer. The hub-token flow below therefore covers only the
remote hub surface.
already an authorized Viewer. Pages with a stricter `[Authorize]` attribute (Alarms,
the mounted Secrets page) are re-checked by `AuthorizeRouteView` on every in-circuit
navigation, because that navigation never reaches the endpoint. The hub-token flow
below therefore covers only the remote hub surface.
Neither policy scopes a Viewer to particular sessions — that is
`IDashboardSessionAcl`'s job (SEC-25 / TST-15), consulted by both subscribe seams:
@@ -962,15 +976,36 @@ dashboard mints short-lived bearer tokens for the connection:
it must never be request-logged (see the remarks on
`HubTokenAuthenticationHandler`).
4. `HubTokenAuthenticationHandler` validates the protected payload and
rebuilds the `ClaimsPrincipal` with the carried roles.
rebuilds the `ClaimsPrincipal` with the carried roles, and stamps the
token's expiry on the authentication ticket (`ExpiresUtc`).
5. The hubs' `[Authorize(Policy = HubClientsPolicy)]` accepts the resulting
identity.
6. Every hub is mapped with `CloseOnAuthenticationExpiration`, so SignalR closes
the connection when that ticket expires (DSH-006). Before this, the 5-minute
lifetime bounded only the handshake: an open socket kept the roles and tag
grants it connected with for as long as it stayed up, and each later
`SubscribeSession` on it was decided from those frozen claims. A
cookie-authenticated hub connection closes at the cookie ticket's expiry the
same way. The client reconnects with a freshly minted token.
There is no in-repo hub client: the helper that once wrapped `HubConnectionBuilder`
for a circuit was deleted when the pages moved to the in-process seams. An external
client re-fetches `/hubs/token` on every (re)connect itself, which is what makes the
short 5-minute lifetime transparent.
Blazor circuits have the same capture-once problem — a circuit takes its principal
from the HTTP request that started it and an open tab sends no further requests — so
the dashboard replaces the default `ServerAuthenticationStateProvider` with
`DashboardRevalidatingAuthenticationStateProvider` (DSH-006). Every minute it signs
the circuit out (anonymous state) when the circuit is older than the cookie's 8-hour
idle lifetime, or when the principal holds a role that its LDAP group claims no
longer map to under the current `Dashboard:GroupToRole`. Pages under
`AuthorizeRouteView` then re-render as not authorized, and admin actions, which read
the provider at action time, are refused. A change to the user's LDAP group
membership and a sign-out in another tab are not observable there (no server-side
session, no password to re-bind with); they take effect at the age limit or on
reconnect. The `DisableLogin` dev bypass is never signed out.
Caveat — logout does not revoke outstanding tokens. Logout clears the dashboard
cookie, but hub bearer tokens are self-contained, data-protection-encrypted, and
carry no server-side revocation state (no jti denylist). A token captured before
+1 -1
View File
@@ -333,7 +333,7 @@ While the gateway is stopping, clients see three different outcomes. An in-fligh
The pipeline has four stages:
1. The session is resolved via `sessionManager.TryGetSession`. A miss raises `SessionManagerException(SessionNotFound)` so the handler reports `StatusCode.NotFound`.
2. The attach is owner-scoped: the caller's API key id must match the key that opened the session, or the call fails with `PermissionDenied` before anything is attached or delivered.
2. The attach is owner-scoped: the caller's API key id must match the key that opened the session, or the call fails with `PermissionDenied` before anything is attached or delivered. `Invoke` and `CloseSession` apply the same check (see [Authorization](./Authorization.md#session-ownership)).
3. The call registers a subscriber on the distributor. A fresh stream (`after_worker_sequence == 0`) uses `session.AttachEventSubscriber(...)`. A resume uses `session.AttachEventSubscriberWithReplay(...)`, which snapshots the replay ring for events newer than the cursor and registers the live subscriber under one lock, so the replay-to-live handoff has no gap and no duplicate. In single-subscriber mode (the default) a second attach fails with `EventSubscriberAlreadyActive`; with `Sessions:AllowMultipleEventSubscribers` enabled, an attach beyond `MaxEventSubscribersPerSession` fails with `EventSubscriberLimitReached`. Both map to `ResourceExhausted`. The lease is released in the `finally` block, so the subscriber slot is freed even when the client cancels mid-stream.
4. The call yields events from the lease's bounded channel (capacity `Events:QueueCapacity`). When the request set `emit_stream_attached` it first yields the StreamAttached sentinel — after step 3, so the client's receipt of it proves the subscriber is registered (see [Sessions](./Sessions.md#attach-acknowledgement)). On a resume it then yields a `ReplayGap` sentinel when the cursor predates the oldest retained event, then the replayed batch, then live events filtered to sequences above the last replayed one. Per-session ordering is preserved end-to-end, because the pump is the single writer to each subscriber channel and writes in `WorkerSequence` order.
+2 -2
View File
@@ -165,7 +165,7 @@ public sealed record SessionCloseResult(
| `SessionLimitExceeded` | `MaxSessions` is in use. |
| `OpenFailed` | `OpenSessionAsync` failed; the inner exception carries the cause. A caller-cancelled open and an open refused because the gateway is stopping do not use this code. |
| `CloseFailed` | A close started but did not complete cleanly — the worker's graceful shutdown and the kill fall-back both failed (or a kill threw); the session is removed and faulted. A shutdown failure whose kill succeeded is a successful close, not this. |
| `PermissionDenied` | The caller may not perform the operation on this session (for example, attaching `StreamEvents` to a session opened by a different API key). |
| `PermissionDenied` | The caller may not perform the operation on this session (for example, attaching `StreamEvents`, calling `Invoke` or calling `CloseSession` on a session opened by a different API key). |
| `GatewayStopping` | The gateway is stopping and refuses new sessions (see [Shutdown Coordination](#shutdown-coordination)). Maps to gRPC `Unavailable`; not recorded as a fault. |
## Lifecycle
@@ -282,7 +282,7 @@ Four deliberate limits keep the rule from catching legitimate sessions. It appli
A client that drops mid-stream reconnects by re-issuing `StreamEvents` with `StreamEventsRequest.after_worker_sequence` set to the last `worker_sequence` it observed. A non-zero `after_worker_sequence` means *resume*; `0` means *fresh stream* and behaves exactly as a first-time subscribe — no replay, no sentinel.
**Owner-scoped attach (security control).** `OpenSession` records the caller's API key id on the session as `GatewaySession.OwnerKeyId`. Every `StreamEvents` attach and reattach is owner-checked: `EventStreamService.StreamEventsAsync` compares the caller's key id (threaded from `GatewayGrpcAuthorizationInterceptor` via `MxAccessGatewayService.StreamEvents`) to the session owner and throws `SessionManagerException(PermissionDenied)` — surfaced as gRPC `PermissionDenied` — when they differ, before any subscriber is attached and before any replayed or live event is delivered. Possessing the `events:read` scope and knowing a session id is not enough. This is what makes the default-on detach-grace and replay-retention windows safe: without the check, any `events:read`-scoped key that learned a session id could attach to another key's retained session and receive its replayed and live data. A `null` owner (session opened with authentication disabled) matches only a `null` caller key.
**Owner-scoped attach (security control).** `OpenSession` records the caller's API key id on the session as `GatewaySession.OwnerKeyId`. Every `StreamEvents` attach and reattach is owner-checked: `EventStreamService.StreamEventsAsync` compares the caller's key id (threaded from `GatewayGrpcAuthorizationInterceptor` via `MxAccessGatewayService.StreamEvents`) to the session owner and throws `SessionManagerException(PermissionDenied)` — surfaced as gRPC `PermissionDenied` — when they differ, before any subscriber is attached and before any replayed or live event is delivered. Possessing the `events:read` scope and knowing a session id is not enough. This is what makes the default-on detach-grace and replay-retention windows safe: without the check, any `events:read`-scoped key that learned a session id could attach to another key's retained session and receive its replayed and live data. A `null` owner (session opened with authentication disabled) matches only a `null` caller key. `MxAccessGatewayService.Invoke` (every command kind, `DrainEvents` included) and `CloseSession` apply the same ordinal owner check through `EnsureOwner`, so a foreign key can neither drain, write through nor close the session. There is no `admin` override; see [Design Decisions](./DesignDecisions.md).
On a resume, `EventStreamService.StreamEventsAsync` attaches through `GatewaySession.AttachEventSubscriberWithReplay`, which calls `SessionEventDistributor.RegisterWithReplay`. That method snapshots the session's replay ring for events newer than `after_worker_sequence` **and** registers the live subscriber inside a single `_replayLock` critical section. This atomicity is what makes the replay→live handoff free of gaps and duplicates: the pump appends each event to the replay ring (under `_replayLock`) before fanning it to subscriber channels, so relative to that one critical section every event is either in the replay snapshot or fanned into the freshly-registered live channel — never both observably, never neither.
@@ -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. *@
<Router AppAssembly="@typeof(Routes).Assembly"
AdditionalAssemblies="new[]{ typeof(ZB.MOM.WW.Secrets.Ui.SecretsPage).Assembly }">
<Found Context="routeData">
<RouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)" />
<AuthorizeRouteView RouteData="@routeData" DefaultLayout="@typeof(MainLayout)">
<NotAuthorized>
<PageTitle>Dashboard - Not Authorized</PageTitle>
<section class="dashboard-section">
<h1 class="h4 mb-3">Not Authorized</h1>
@if (context.User.Identity?.IsAuthenticated == true)
{
<p class="mb-0">Your dashboard role does not grant access to this page.</p>
}
else
{
<p class="mb-0">This page requires a signed-in dashboard role. <a href="/login">Sign in</a></p>
}
</section>
</NotAuthorized>
</AuthorizeRouteView>
<FocusOnNavigate RouteData="@routeData" Selector="h1" />
</Found>
<NotFound>
@@ -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,
@@ -45,6 +45,13 @@ public static class DashboardAuthenticationDefaults
/// </summary>
public const string AlarmsPolicy = "MxGateway.Dashboard.Alarms";
/// <summary>
/// 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
/// <see cref="DashboardRevalidatingAuthenticationStateProvider"/> signs it out at this age.
/// </summary>
public static readonly TimeSpan CookieIdleTimeout = TimeSpan.FromHours(8);
public const string LdapGroupClaimType = "mxgateway:ldap_group";
public const string KeyPrefixClaimType = "mxgateway:key_prefix";
@@ -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<DashboardSnapshotHub>("/hubs/snapshot");
endpoints.MapHub<AlarmsHub>("/hubs/alarms");
endpoints.MapHub<EventsHub>("/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<DashboardSnapshotHub>("/hubs/snapshot", CloseOnAuthenticationExpiration);
endpoints.MapHub<AlarmsHub>("/hubs/alarms", CloseOnAuthenticationExpiration);
endpoints.MapHub<EventsHub>("/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<IResult> PostLoginAsync(
HttpContext httpContext,
IAntiforgery antiforgery,
@@ -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;
/// <summary>
/// Re-checks a Blazor circuit's sign-in on a timer and signs the circuit out when it no longer
/// holds (DSH-006).
/// </summary>
/// <remarks>
/// <para>
/// 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
/// <see cref="RevalidationInterval"/> this provider re-evaluates two things it can know without the
/// user's password:
/// </para>
/// <list type="bullet">
/// <item><description>
/// <b>Age.</b> A circuit older than the cookie's idle lifetime
/// (<see cref="DashboardAuthenticationDefaults.CookieIdleTimeout"/>) is signed out; the circuit
/// could not have renewed the cookie, so the sign-in it holds has lapsed.
/// </description></item>
/// <item><description>
/// <b>Roles.</b> The principal's LDAP group claims are re-mapped through the current
/// <c>MxGateway:Dashboard:GroupToRole</c>; 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.
/// </description></item>
/// </list>
/// <para>
/// When either check fails the circuit's state becomes anonymous: pages under
/// <c>AuthorizeRouteView</c> 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 <c>Dashboard:DisableLogin</c> dev bypass and unauthenticated principals are
/// never signed out.
/// </para>
/// </remarks>
public sealed class DashboardRevalidatingAuthenticationStateProvider : RevalidatingServerAuthenticationStateProvider
{
private readonly IOptionsMonitor<GatewayOptions> _options;
private readonly TimeProvider _timeProvider;
private readonly DateTimeOffset _circuitStartedAt;
/// <summary>Initializes a new instance of the <see cref="DashboardRevalidatingAuthenticationStateProvider"/> class.</summary>
/// <param name="loggerFactory">Logger factory for the revalidation loop.</param>
/// <param name="options">Gateway options, read fresh on every revalidation.</param>
/// <param name="timeProvider">Clock; the system clock when not registered.</param>
public DashboardRevalidatingAuthenticationStateProvider(
ILoggerFactory loggerFactory,
IOptionsMonitor<GatewayOptions> options,
TimeProvider? timeProvider = null)
: base(loggerFactory)
{
ArgumentNullException.ThrowIfNull(options);
_options = options;
_timeProvider = timeProvider ?? TimeProvider.System;
_circuitStartedAt = _timeProvider.GetUtcNow();
}
/// <inheritdoc />
protected override TimeSpan RevalidationInterval => TimeSpan.FromMinutes(1);
/// <summary>Decides whether the circuit's principal is still signed in. Internal for tests.</summary>
/// <param name="user">The circuit's current principal.</param>
/// <returns><see langword="true"/> to keep the sign-in; <see langword="false"/> to sign out.</returns>
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<string> 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;
}
/// <inheritdoc />
protected override Task<bool> ValidateAuthenticationStateAsync(
AuthenticationState authenticationState,
CancellationToken cancellationToken) =>
Task.FromResult(IsStillValid(authenticationState.User));
}
@@ -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<AuthenticationStateProvider, DashboardRevalidatingAuthenticationStateProvider>();
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
@@ -48,14 +48,19 @@ public sealed class HubTokenAuthenticationHandler : AuthenticationHandler<Authen
return Task.FromResult(AuthenticateResult.NoResult());
}
System.Security.Claims.ClaimsPrincipal? principal = _tokens.Validate(token);
System.Security.Claims.ClaimsPrincipal? principal = _tokens.Validate(token, out DateTimeOffset expiresUtc);
if (principal is null)
{
return Task.FromResult(AuthenticateResult.Fail("Invalid or expired hub token."));
}
// The ticket carries the token's expiry so the hubs, mapped with
// CloseOnAuthenticationExpiration, close a token-authenticated connection when its token
// lapses (DSH-006). Without it 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.
AuthenticationProperties properties = new() { ExpiresUtc = expiresUtc };
return Task.FromResult(AuthenticateResult.Success(
new AuthenticationTicket(principal, Scheme.Name)));
new AuthenticationTicket(principal, properties, Scheme.Name)));
}
private string? ExtractToken()
@@ -100,8 +100,19 @@ public sealed class HubTokenService
/// <summary>Validates a token and returns the equivalent claims principal; null when invalid or expired.</summary>
/// <param name="token">The token string to validate.</param>
/// <returns>The reconstructed <see cref="ClaimsPrincipal"/>, or <see langword="null"/> when the token is missing, invalid, or expired.</returns>
public ClaimsPrincipal? Validate(string? token)
public ClaimsPrincipal? Validate(string? token) => Validate(token, out _);
/// <summary>
/// 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
/// <c>CloseOnAuthenticationExpiration</c> ends the connection when the token lapses (DSH-006).
/// </summary>
/// <param name="token">The token string to validate.</param>
/// <param name="expiresUtc">The token's expiry when valid; otherwise <see langword="default"/>.</param>
/// <returns>The reconstructed <see cref="ClaimsPrincipal"/>, or <see langword="null"/>.</returns>
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<HubTokenPayload>(_protector.Unprotect(token));
HubTokenPayload? payload = JsonSerializer.Deserialize<HubTokenPayload>(
_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)
@@ -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<MxAccessGatewayService> logger,
IGatewayAlarmService alarmService) : MxAccessGateway.MxAccessGatewayBase
{
/// <summary>
/// Command kinds <see cref="ApplyConstraintsAsync"/> 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.
/// </summary>
internal static readonly FrozenSet<MxCommandKind> 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();
/// <summary>
/// Command kinds that carry no tag address, so they pass <see cref="ApplyConstraintsAsync"/>
/// without a constraint check. Handle-only commands (<c>Advise</c>, <c>RemoveItem</c>, ...)
/// belong here because the add that produced the handle was checked. Any kind in neither
/// set is refused with <c>PermissionDenied</c>, so a new tag-bearing kind cannot slip
/// through unchecked; the enum-coverage test fails until it is classified.
/// </summary>
internal static readonly FrozenSet<MxCommandKind> 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();
/// <inheritdoc />
public override async Task<OpenSessionReply> 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<BulkConstraintPlan?> 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,
@@ -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);
}
/// <summary>
/// Read-only access to cached successful verifications, consulted by the auth surfaces before the
/// failure limiter (SEC-002).
/// </summary>
/// <remarks>
/// A hit means the presented token — key id <em>and</em> 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.
/// </remarks>
public interface IApiKeyVerificationCache
{
/// <summary>Returns a cached successful verification for the header, if one is within TTL.</summary>
/// <param name="authorizationHeader">The raw <c>authorization</c> header value.</param>
/// <param name="verification">The cached successful verification, when found.</param>
/// <returns><see langword="true"/> on a cache hit.</returns>
bool TryGetCachedSuccess(string? authorizationHeader, [NotNullWhen(true)] out ApiKeyVerification? verification);
}
/// <summary>
/// An <see cref="IApiKeyVerifier"/> decorator that caches successful verifications for a short,
/// configurable TTL (<see cref="SecurityOptions.ApiKeyVerificationCacheSeconds"/>), keyed on a
@@ -72,7 +92,7 @@ public interface IApiKeyCacheInvalidator
/// live cache rather than to every token ever verified.
/// </para>
/// </remarks>
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);
}
/// <inheritdoc />
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<ApiKeyVerification> VerifyMissAsync(
@@ -21,9 +21,14 @@ namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
/// <para>
/// An over-limit state is a valve, not a wall: at most one request per
/// <see cref="SecurityOptions.ApiKeyFailureProbeIntervalSeconds"/> 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 <c>(address, key id)</c> partition
/// and marks that pair as verified for one window; it does <em>not</em> 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.
/// </para>
/// <para>
/// The tracked partition set is a bounded LRU (<see cref="SecurityOptions.ApiKeyFailureTrackedPeers"/>).
@@ -71,6 +76,11 @@ public sealed class ApiKeyFailureLimiter
private readonly ConcurrentDictionary<string, WindowState> _aggregates = new(StringComparer.Ordinal);
private readonly ConcurrentDictionary<string, PeerKeyIds> _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<string, long> _verified = new(StringComparer.Ordinal);
/// <summary>Initializes a new instance of the <see cref="ApiKeyFailureLimiter"/> class.</summary>
/// <param name="security">Security options carrying the failure-limit knobs.</param>
/// <param name="clock">The time provider.</param>
@@ -115,6 +125,9 @@ public sealed class ApiKeyFailureLimiter
/// <summary>Gets the number of tracked per-key-id aggregates. Test seam.</summary>
internal int TrackedAggregateCount => _aggregates.Count;
/// <summary>Gets the number of tracked verified <c>(address, key id)</c> marks. Test seam.</summary>
internal int VerifiedMarkCount => _verified.Count;
/// <summary>
/// Test seam invoked between a probe claim and its compensating release; <see langword="null"/>
/// 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);
}
/// <summary>Clears both limiter layers for the partition after a successful verification.</summary>
/// <summary>
/// Records a successful verification: clears the caller's own partition and marks the
/// <c>(address, key id)</c> pair verified. The key id's cross-peer aggregate is left to decay.
/// </summary>
/// <param name="partition">The throttle partition derived from the request.</param>
public void Reset(ApiKeyThrottlePartition partition) => Reset(partition, PartitionResolution.Unresolved);
/// <summary>
/// Clears both limiter layers for the partition after a successful verification, reusing the
/// storage key <see cref="Check(ApiKeyThrottlePartition, out PartitionResolution)"/> already
/// resolved for this request.
/// Records a successful verification, reusing the storage key
/// <see cref="Check(ApiKeyThrottlePartition, out PartitionResolution)"/> already resolved for
/// this request.
/// </summary>
/// <param name="partition">The throttle partition derived from the request.</param>
/// <param name="resolution">
@@ -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<string, long> 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;
}
/// <summary>Returns whether the partition currently has tracked failure state. Test seam.</summary>
/// <param name="partition">The throttle partition to look up.</param>
/// <returns><see langword="true"/> when the partition has a tracked window.</returns>
@@ -0,0 +1,152 @@
using System.Collections.Concurrent;
namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
/// <summary>
/// Tracks the streaming gRPC calls each API key has open, so revoking, rotating or deleting the key
/// ends them (SEC-004).
/// </summary>
/// <remarks>
/// <para>
/// A streaming call is authenticated once, when it opens. Evicting the verification cache on
/// revoke stops new calls but leaves an open <c>StreamEvents</c>, <c>StreamAlarms</c> or
/// <c>WatchDeployEvents</c> 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 <see cref="Revoke"/>; the interceptor then
/// reports the end of the call as <c>Unauthenticated</c>.
/// </para>
/// <para>
/// Only revocations made through this gateway process reach the registry (the dashboard API Keys
/// page). The separate <c>apikey</c> 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).
/// </para>
/// </remarks>
public sealed class ApiKeyStreamRegistry
{
private readonly ConcurrentDictionary<string, ConcurrentDictionary<Registration, byte>> _byKeyId =
new(StringComparer.OrdinalIgnoreCase);
/// <summary>Gets the number of open streaming calls registered for a key id. Test seam.</summary>
/// <param name="keyId">The key id.</param>
/// <returns>The open registration count.</returns>
internal int CountFor(string keyId) =>
_byKeyId.TryGetValue(keyId, out ConcurrentDictionary<Registration, byte>? set) ? set.Count : 0;
/// <summary>
/// Registers a streaming call. Dispose the returned registration when the call ends.
/// </summary>
/// <param name="keyId">The authenticated caller's key id.</param>
/// <param name="callCancellation">The call's own cancellation token, linked into the registration's.</param>
/// <returns>The registration whose <see cref="Registration.Token"/> the handler must observe.</returns>
public Registration Register(string keyId, CancellationToken callCancellation)
{
ArgumentException.ThrowIfNullOrEmpty(keyId);
Registration registration = new(this, keyId, callCancellation);
while (true)
{
ConcurrentDictionary<Registration, byte> 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<Registration, byte>? current)
&& ReferenceEquals(current, set))
{
return registration;
}
set.TryRemove(registration, out _);
}
}
/// <summary>Ends every open streaming call registered for the key id.</summary>
/// <param name="keyId">The revoked, rotated or deleted key id.</param>
/// <returns>The number of calls that were cancelled.</returns>
public int Revoke(string keyId)
{
if (string.IsNullOrEmpty(keyId) || !_byKeyId.TryGetValue(keyId, out ConcurrentDictionary<Registration, byte>? 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<Registration, byte>? set)
&& set.TryRemove(registration, out _)
&& set.IsEmpty)
{
_byKeyId.TryRemove(new KeyValuePair<string, ConcurrentDictionary<Registration, byte>>(registration.KeyId, set));
}
}
/// <summary>One open streaming call.</summary>
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);
}
/// <summary>Gets the key id the call authenticated with.</summary>
public string KeyId { get; }
/// <summary>Gets the token that fires when the call is cancelled or its key is revoked.</summary>
public CancellationToken Token => _cancellation.Token;
/// <summary>Gets a value indicating whether the key was revoked while the call was open.</summary>
public bool IsRevoked => Volatile.Read(ref _revoked) == 1;
/// <inheritdoc />
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;
}
}
}
@@ -11,6 +11,9 @@ namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
/// <see cref="GatewayGrpcAuthorizationInterceptor"/> (literal <c>mxgw</c> prefix, at least three
/// non-empty underscore segments, bounded key-id length) so junk tokens cannot mint partitions.
/// </remarks>
/// <param name="TransportPeer">The gRPC transport peer address (<c>ServerCallContext.Peer</c>).</param>
/// <param name="TransportPeer">
/// The client's remote IP with no port, as produced by <see cref="ApiKeyThrottlePeer"/>. The
/// source port is excluded because it changes with every connection (SEC-001).
/// </param>
/// <param name="KeyId">The key id claimed by a validly shaped token, or <see langword="null"/>.</param>
public readonly record struct ApiKeyThrottlePartition(string TransportPeer, string? KeyId);
@@ -0,0 +1,76 @@
using System.Net;
namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
/// <summary>
/// Derives the address half of an <see cref="ApiKeyThrottlePartition"/>: the client's remote IP
/// with no source port, in one canonical form shared by the gRPC interceptor and the
/// <c>/metrics</c> handler.
/// </summary>
/// <remarks>
/// 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
/// <c>limit - 1</c> 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.
/// </remarks>
public static class ApiKeyThrottlePeer
{
private const string Ipv4Prefix = "ipv4:";
private const string Ipv6Prefix = "ipv6:[";
/// <summary>
/// Extracts the remote IP from a Grpc.AspNetCore peer string (<c>ipv4:1.2.3.4:5678</c> or
/// <c>ipv6:[::1]:5678</c>). A peer in any other form (<c>unknown</c>, a Unix socket) is returned
/// unchanged, since it carries no port to strip.
/// </summary>
/// <param name="grpcPeer">The value of <c>ServerCallContext.Peer</c>.</param>
/// <returns>The canonical address string.</returns>
public static string FromGrpcPeer(string grpcPeer)
{
ArgumentNullException.ThrowIfNull(grpcPeer);
ReadOnlySpan<char> address;
if (grpcPeer.StartsWith(Ipv4Prefix, StringComparison.Ordinal))
{
ReadOnlySpan<char> rest = grpcPeer.AsSpan(Ipv4Prefix.Length);
int portSeparator = rest.LastIndexOf(':');
address = portSeparator > 0 ? rest[..portSeparator] : rest;
}
else if (grpcPeer.StartsWith(Ipv6Prefix, StringComparison.Ordinal))
{
ReadOnlySpan<char> 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;
}
/// <summary>
/// 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.
/// </summary>
/// <param name="remoteIpAddress">The connection's remote address, or <see langword="null"/>.</param>
/// <returns>The canonical address string, or <c>unknown</c>.</returns>
public static string FromRemoteIp(IPAddress? remoteIpAddress)
{
if (remoteIpAddress is null)
{
return "unknown";
}
return remoteIpAddress.IsIPv4MappedToIPv6
? remoteIpAddress.MapToIPv4().ToString()
: remoteIpAddress.ToString();
}
}
@@ -18,12 +18,19 @@ public sealed class GatewayGrpcAuthorizationInterceptor(
IGatewayRequestIdentityAccessor identityAccessor,
IOptions<GatewayOptions> 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;
/// <inheritdoc />
public override async Task<TResponse> UnaryServerHandler<TRequest, TResponse>(
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<ServerCallContext, Task> 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_<keyId>_<secret>: the key id is the second underscore-delimited segment (the
@@ -26,6 +26,7 @@ public static class GrpcAuthorizationServiceCollectionExtensions
sp.GetRequiredService<IConfiguration>().GetSection(SecurityOptions.SectionName).Get<SecurityOptions>()
?? new SecurityOptions(),
sp.GetService<TimeProvider>() ?? TimeProvider.System));
services.AddSingleton<ApiKeyStreamRegistry>();
services.AddSingleton<GatewayGrpcAuthorizationInterceptor>();
services
.AddOptions<global::Grpc.AspNetCore.Server.GrpcServiceOptions>()
@@ -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 <c>429</c>, mirroring the gRPC
/// <c>ResourceExhausted</c>. 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 <see cref="ApiKeyThrottlePeer"/>, so the two surfaces share both limiter
/// layers. A cached successful verification skips the limiter here as it does on gRPC (SEC-002).
/// </remarks>
public sealed class MetricsAuthenticationHandler(
IOptionsMonitor<AuthenticationSchemeOptions> options,
@@ -50,6 +51,8 @@ public sealed class MetricsAuthenticationHandler(
GatewayMetrics metrics)
: AuthenticationHandler<AuthenticationSchemeOptions>(options, logger, encoder)
{
private readonly IApiKeyVerificationCache? _verificationCache = apiKeyVerifier as IApiKeyVerificationCache;
private bool _throttled;
/// <inheritdoc />
@@ -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<Claim> claims = [new Claim(ClaimTypes.Name, verification.Identity.KeyId)];
private AuthenticateResult Authenticated(ApiKeyVerification verification)
{
List<Claim> claims = [new Claim(ClaimTypes.Name, verification.Identity!.KeyId)];
foreach (string scope in verification.Identity.Scopes)
{
claims.Add(new Claim(MetricsAuthorizationDefaults.ScopeClaimType, scope));
@@ -0,0 +1,84 @@
using Grpc.Core;
namespace ZB.MOM.WW.MxGateway.Server.Security.Authorization;
/// <summary>
/// A <see cref="ServerCallContext"/> 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 <see cref="ServerCallContext.CancellationToken"/>, so they end a revoked stream
/// without knowing about revocation.
/// </summary>
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.
}
}
/// <inheritdoc />
protected override string MethodCore => _inner.Method;
/// <inheritdoc />
protected override string HostCore => _inner.Host;
/// <inheritdoc />
protected override string PeerCore => _inner.Peer;
/// <inheritdoc />
protected override DateTime DeadlineCore => _inner.Deadline;
/// <inheritdoc />
protected override Metadata RequestHeadersCore => _inner.RequestHeaders;
/// <inheritdoc />
protected override CancellationToken CancellationTokenCore => _cancellationToken;
/// <inheritdoc />
protected override Metadata ResponseTrailersCore => _inner.ResponseTrailers;
/// <inheritdoc />
protected override Status StatusCore
{
get => _inner.Status;
set => _inner.Status = value;
}
/// <inheritdoc />
protected override WriteOptions? WriteOptionsCore
{
get => _inner.WriteOptions;
set => _inner.WriteOptions = value;
}
/// <inheritdoc />
protected override AuthContext AuthContextCore => _inner.AuthContext;
/// <inheritdoc />
protected override IDictionary<object, object> UserStateCore => _inner.UserState;
/// <inheritdoc />
protected override ContextPropagationToken CreatePropagationTokenCore(ContextPropagationOptions? options) =>
_inner.CreatePropagationToken(options);
/// <inheritdoc />
protected override Task WriteResponseHeadersAsyncCore(Metadata responseHeaders) =>
_inner.WriteResponseHeadersAsync(responseHeaders);
}
@@ -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;
/// <summary>
/// Proves the dashboard router enforces page <c>[Authorize]</c> attributes on in-circuit
/// navigation (DSH-001, #243).
/// </summary>
/// <remarks>
/// <para>
/// A page's <c>[Authorize]</c> 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 <c>Blazor.navigateTo</c> from the console) never issues
/// an HTTP request: the in-circuit <c>Router</c> resolves the route and renders it. A plain
/// <c>RouteView</c> does not evaluate <c>[Authorize]</c>; <c>AuthorizeRouteView</c> does.
/// </para>
/// <para>
/// These tests render the production <see cref="Routes"/> component, park it on a page that has
/// no attribute, then call <see cref="NavigationManager.NavigateTo(string, bool)"/> — the same
/// <c>LocationChanged</c> 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.
/// </para>
/// <para>
/// The shared <c>ZB.MOM.WW.Secrets.Ui</c> page is not rendered for real: under the static
/// <see cref="HtmlRenderer"/> 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 <see cref="SecretsPage"/>, so "activated" means
/// exactly "the router decided to render the page".
/// </para>
/// </remarks>
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";
/// <summary>
/// A Viewer is not granted <c>secrets:manage</c>. Navigating in-circuit to
/// <c>/admin/secrets</c> must render the not-authorized content and must not list secrets.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
}
/// <summary>
/// Control for the Viewer case: an Administrator satisfies <c>secrets:manage</c>, 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
}
/// <summary>
/// Anonymous localhost passes the endpoint <c>ViewerPolicy</c> but never the Alarms policy.
/// In-circuit navigation to <c>/alarms</c> must not render the galaxy-wide alarm list or
/// start its poll loop.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
}
/// <summary>
/// Control for the anonymous case: an authenticated Viewer holds a real dashboard role and so
/// satisfies the Alarms policy; the page renders and polls.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<RouteHarness> 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<IAuthorizationHandler, AuthenticatedDashboardRoleHandler>();
services.AddCascadingAuthenticationState();
services.AddSingleton<AuthenticationStateProvider>(new StubAuthenticationStateProvider(roles));
services.AddSingleton<NavigationManager, InCircuitNavigationManager>();
services.AddSingleton<INavigationInterception, NoOpNavigationInterception>();
services.AddSingleton<IScrollToLocationHash, NoOpScrollToLocationHash>();
services.AddSingleton<IJSRuntime, NoOpJsRuntime>();
services.AddSingleton<IComponentActivator>(activator);
services.AddSingleton<IDashboardLiveDataService>(liveData);
services.AddSingleton<IGatewayAlarmService>(new FakeGatewayAlarmService());
services.AddSingleton<IOptions<GatewayOptions>>(
Options.Create(new GatewayOptions { Alarms = new AlarmsOptions { Enabled = true } }));
ServiceProvider provider = services.BuildServiceProvider();
HtmlRenderer renderer = new(provider, provider.GetRequiredService<ILoggerFactory>());
HtmlRootComponent root = await renderer.Dispatcher.InvokeAsync(
() => renderer.RenderComponentAsync<Routes>());
return new RouteHarness(provider, renderer, root, activator, liveData);
}
public async Task<string> NavigateAsync(string path)
{
NavigationManager navigation = _provider.GetRequiredService<NavigationManager>();
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
{
/// <inheritdoc />
public override Task<AuthenticationState> 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
{
/// <summary>Initializes the manager on the attribute-free start path.</summary>
public InCircuitNavigationManager() => Initialize("https://localhost/", $"https://localhost{StartPath}");
/// <inheritdoc />
protected override void NavigateToCore(string uri, NavigationOptions options)
{
Uri = ToAbsoluteUri(uri).ToString();
NotifyLocationChanged(isInterceptedLink: false);
}
}
private sealed class NoOpNavigationInterception : INavigationInterception
{
/// <inheritdoc />
public Task EnableNavigationInterceptionAsync() => Task.CompletedTask;
}
private sealed class NoOpScrollToLocationHash : IScrollToLocationHash
{
/// <inheritdoc />
public Task RefreshScrollPositionForHash(string locationAbsolute) => Task.CompletedTask;
}
private sealed class NoOpJsRuntime : IJSRuntime
{
/// <inheritdoc />
public ValueTask<TValue> InvokeAsync<TValue>(string identifier, object?[]? args) => default;
/// <inheritdoc />
public ValueTask<TValue> InvokeAsync<TValue>(
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<DashboardLiveReadResult> ReadAsync(
IReadOnlyCollection<string> tagAddresses,
CancellationToken cancellationToken) =>
Task.FromResult(DashboardLiveReadResult.Empty);
public async Task<DashboardAlarmQueryResult> 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);
/// <inheritdoc />
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
{
/// <inheritdoc />
protected override void BuildRenderTree(Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder builder)
{
builder.AddMarkupContent(0, $"<p>{SecretsPageMarker}</p>");
}
}
}
@@ -335,7 +335,31 @@ public sealed class DashboardApiKeyManagementServiceTests : IDisposable
Assert.Equal("API key pepper is not configured.", result.Message);
}
private DashboardApiKeyManagementService CreateService(ServiceProvider services)
/// <summary>
/// SEC-004: revoking a key on the dashboard ends the streaming calls that key already has
/// open, not only future calls.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<IApiKeyAdminStore>(),
services.GetRequiredService<ZB.MOM.WW.Auth.ApiKeys.IApiKeyPepperProvider>(),
services.GetRequiredService<ZB.MOM.WW.Audit.IAuditWriter>(),
new HttpContextAccessor { HttpContext = httpContext });
new HttpContextAccessor { HttpContext = httpContext },
streamRegistry: streamRegistry);
}
private ServiceProvider BuildServices(string? pepper = "test-pepper")
@@ -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;
/// <summary>
/// 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.
/// </summary>
public sealed class DashboardAuthLifetimeTests
{
private const string AdminGroup = "GwAdmin";
private const string ViewerGroup = "GwViewer";
/// <summary>
/// The hub-token ticket carries the token's expiry, which is what SignalR's
/// CloseOnAuthenticationExpiration closes the connection on.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<AuthenticationSchemeOptions>(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));
}
/// <summary>
/// Every dashboard hub closes a connection whose authentication has expired. The dispatcher
/// options ride on each hub's negotiate endpoint.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task EveryHub_ClosesOnAuthenticationExpiration()
{
await using WebApplication app = TestGatewayHost.Build([]);
List<RouteEndpoint> hubEndpoints = ((IEndpointRouteBuilder)app).DataSources
.SelectMany(source => source.Endpoints)
.OfType<RouteEndpoint>()
.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<HttpConnectionDispatcherOptions>()?.CloseOnAuthenticationExpiration));
}
/// <summary>Circuits get the revalidating provider, not the capture-once default.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[Fact]
public async Task Circuits_UseTheRevalidatingAuthenticationStateProvider()
{
await using WebApplication app = TestGatewayHost.Build([]);
await using AsyncServiceScope scope = app.Services.CreateAsyncScope();
Assert.IsType<DashboardRevalidatingAuthenticationStateProvider>(
scope.ServiceProvider.GetRequiredService<AuthenticationStateProvider>());
}
/// <summary>An Administrator whose admin group is withdrawn from GroupToRole is signed out.</summary>
[Fact]
public void Revalidation_WhenAdminGrantWithdrawn_SignsOut()
{
GatewayOptions options = OptionsWithRoles(includeAdmin: true);
StaticOptionsMonitor<GatewayOptions> 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));
}
/// <summary>A circuit older than the cookie's idle lifetime is signed out.</summary>
[Fact]
public void Revalidation_PastCookieIdleTimeout_SignsOut()
{
StaticOptionsMonitor<GatewayOptions> 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));
}
/// <summary>
/// Principals with nothing to revoke stay as they are: anonymous localhost, and the
/// DisableLogin dev bypass however old the circuit.
/// </summary>
[Fact]
public void Revalidation_AnonymousAndDisableLogin_AreNeverSignedOut()
{
StaticOptionsMonitor<GatewayOptions> 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<string, string> 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<Claim> 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>(T value) : IOptionsMonitor<T>
{
public T CurrentValue { get; set; } = value;
public T Get(string? name) => CurrentValue;
public IDisposable? OnChange(Action<T, string?> listener) => null;
}
}
@@ -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) ===
/// <summary>
/// <c>AddBufferedItem</c> names a tag like the other adds, so an out-of-scope tag is
/// refused with <see cref="StatusCode.PermissionDenied"/>, the denial is audited, and the
/// worker never sees the command.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<RpcException>(
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);
}
/// <summary>An in-scope <c>AddBufferedItem</c> still reaches the worker.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>
/// Every <see cref="MxCommandKind"/> 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.
/// </summary>
[Fact]
public void EveryCommandKind_IsClassifiedExactlyOnceForConstraintEnforcement()
{
HashSet<MxCommandKind> refusedOnInvoke =
[
MxCommandKind.SubscribeAlarms,
MxCommandKind.UnsubscribeAlarms,
MxCommandKind.AcknowledgeAlarm,
MxCommandKind.QueryActiveAlarms,
MxCommandKind.AcknowledgeAlarmByName,
MxCommandKind.UpdateAlarmWatchList,
];
foreach (MxCommandKind kind in Enum.GetValues<MxCommandKind>())
{
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.");
}
}
/// <summary>
/// A kind on neither list — a gateway-internal alarm kind, or a value the switch has never
/// seen — is refused with <see cref="StatusCode.PermissionDenied"/> and an audited denial
/// even for an unconstrained key, and never reaches the worker.
/// </summary>
/// <param name="kindValue">Numeric <see cref="MxCommandKind"/> value.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<RpcException>(
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(
@@ -722,6 +722,127 @@ public sealed class MxAccessGatewayServiceTests
Assert.Equal(expectedReason, exception.Trailers.GetValue(ResourceExhaustedReasons.TrailerKey));
}
// === Owner-scoped session RPCs (SES-002, #241) ===
/// <summary>
/// A foreign key — even one holding <c>admin</c> — cannot drain, write through or close
/// another key's session: each call is refused with <c>PermissionDenied</c> before the
/// session manager is reached, and the owner's session stays <c>Ready</c>.
/// </summary>
/// <param name="foreignScope">Scope the foreign key holds.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<RpcException>(
async () => await service.Invoke(drain, new TestServerCallContext()));
RpcException writeException = await Assert.ThrowsAsync<RpcException>(
async () => await service.Invoke(write, new TestServerCallContext()));
RpcException closeException = await Assert.ThrowsAsync<RpcException>(
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);
}
/// <summary>The owning key still reaches Invoke and CloseSession on its own session.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>
/// The owner compare is ordinal: a key id that differs only by case is a different key.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<RpcException>(
async () => await service.Invoke(CreatePingRequest("session-owned"), new TestServerCallContext()));
Assert.Equal(StatusCode.PermissionDenied, exception.StatusCode);
Assert.Equal(0, sessionManager.InvokeCount);
}
/// <summary>
/// An authenticated key cannot act on a session opened with authentication disabled (a
/// <see langword="null"/> owner matches only a <see langword="null"/> caller).
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<RpcException>(
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<string>(StringComparer.Ordinal));
}
private static ApiKeyIdentity CreateIdentity(string keyId, string scope)
{
return new ApiKeyIdentity(
KeyId: keyId,
KeyPrefix: $"mxgw_{keyId}",
DisplayName: keyId,
Scopes: new HashSet<string>([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
/// <summary>The number of times InvokeAsync was called.</summary>
public int InvokeCount { get; private set; }
/// <summary>The number of times CloseSessionAsync was called.</summary>
public int CloseCount { get; private set; }
/// <summary>The events the fake event stream service replays for this manager.</summary>
public List<WorkerEvent> 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));
}
@@ -313,18 +313,21 @@ public sealed class ApiKeyFailureLimiterTests
Assert.Equal(ApiKeyThrottleDecision.ThrottledByPeer, limiter.Check(partition));
}
/// <summary>A successful verification clears both the composite partition and the key aggregate.</summary>
/// <summary>
/// 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).
/// </summary>
[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")));
}
/// <summary>
/// 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.
/// </summary>
[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));
}
/// <summary>
/// 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.
/// </summary>
[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));
}
/// <summary>
@@ -0,0 +1,50 @@
using System.Net;
using ZB.MOM.WW.MxGateway.Server.Security.Authorization;
namespace ZB.MOM.WW.MxGateway.Tests.Security.Authorization;
/// <summary>
/// Pins the address normalisation shared by the gRPC interceptor and the <c>/metrics</c> handler
/// (SEC-001): the source port never reaches the limiter partition, and both surfaces produce the
/// same string for the same client.
/// </summary>
public sealed class ApiKeyThrottlePeerTests
{
/// <summary>Strips the port from each Grpc.AspNetCore peer form.</summary>
/// <param name="grpcPeer">The <c>ServerCallContext.Peer</c> value.</param>
/// <param name="expected">The expected address.</param>
[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));
}
/// <summary>A peer with no address/port shape is kept verbatim rather than guessed at.</summary>
/// <param name="grpcPeer">The <c>ServerCallContext.Peer</c> value.</param>
[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));
}
/// <summary>
/// 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.
/// </summary>
[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));
}
}
@@ -406,6 +406,287 @@ public sealed class GatewayGrpcAuthorizationInterceptorTests
Assert.Equal(3, verifier.CallCount);
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<StatusCode> 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<RpcException>(
() => 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);
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<RpcException>(
() => 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);
}
/// <summary>
/// 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.
/// </summary>
/// <param name="holderPeer">Address the holder calls from after the spray.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<RpcException>(
() => interceptor.UnaryServerHandler(
new OpenSessionRequest(),
ContextWithAuthorization("Bearer mxgw_operator01_guess", $"ipv4:203.0.113.{peer}:5000"),
(_, _) => Task.FromResult(new OpenSessionReply())));
}
RpcException sprayer = await Assert.ThrowsAsync<RpcException>(
() => 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);
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<RpcException>(
() => 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);
}
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<RpcException>(
() => 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<RpcException>(
() => 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);
}
/// <summary>
/// SEC-004: revoking a key mid-stream ends the open streaming call with
/// <see cref="StatusCode.Unauthenticated"/>, whatever status the handler maps its cancellation
/// to, and releases the registration.
/// </summary>
/// <param name="handlerMapsCancellation">Whether the handler converts its cancellation to an RpcException(Cancelled), as the gateway services do.</param>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<MxEvent>(),
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<RpcException>(() => call.WaitAsync(TimeSpan.FromSeconds(10)));
Assert.Equal(StatusCode.Unauthenticated, exception.StatusCode);
Assert.Equal(0, registry.CountFor("operator01"));
}
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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<MxEvent>(),
ContextWithAuthorization("Bearer mxgw_operator01_secret", HolderPeer),
(_, _, context) =>
{
seenPeer = context.Peer;
return Task.CompletedTask;
});
Assert.Equal(HolderPeer, seenPeer);
Assert.Equal(0, registry.CountFor("operator01"));
}
/// <summary>
/// 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)));
}
/// <summary>
@@ -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;
/// <summary>Gets the number of verifications performed.</summary>
public int CallCount => Volatile.Read(ref _callCount);
/// <inheritdoc />
public Task<ApiKeyVerification> 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
{
/// <summary>Gets whether the verifier was called.</summary>
@@ -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;
/// <summary>
/// The context handed to streaming handlers (SEC-004) must behave as the real call context in
/// every respect except its cancellation token.
/// </summary>
public sealed class RevocableServerCallContextTests
{
/// <summary>Metadata, status, trailers, user state and the HttpContext all pass through.</summary>
[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);
}
}