# Server Dashboard — bug and performance review (2026-12-02) Scope: `src/ZB.MOM.WW.MxGateway.Server/Dashboard/` at HEAD `54367e74`. Read-only review; no source was modified and nothing was built or run. Other code was read only to confirm a finding. All paths below are relative to `src/ZB.MOM.WW.MxGateway.Server/` unless they start with `src/`. ## Summary | ID | Severity | Category | Confidence | Title | |---|---|---|---|---| | DSH-001 | High | Bug (security) | Confirmed | `/alarms` `AlarmsPolicy` is bypassed by in-circuit navigation (plain `RouteView`) | | DSH-002 | High | Bug | Confirmed path / Plausible trigger | Live-read failure orphans the dashboard session and its x86 worker for the full 30-minute lease | | DSH-003 | Medium | Performance | Confirmed | Every snapshot tick runs the full health-check set (Galaxy SQL ping included); a slow check stalls the tick and reports `Unknown` | | DSH-004 | Medium | Performance | Confirmed code / Plausible magnitude | Session-details event pump renders once per wake with no time coalescing | | DSH-005 | Medium | Bug | Confirmed | `/hubs/alarms` clients that connect after the publisher subscribed never receive the active-alarm snapshot | | DSH-006 | Medium | Bug (security) | Confirmed | Hub-token and cookie lifetimes are not enforced on live hub connections or circuits | | DSH-007 | Low | Bug | Plausible | Cancelled Browse read can leave tags advised on the worker but untracked | | DSH-008 | Low | Performance | Confirmed | `NativeDialog` makes a JS interop call on every parent render once it has been opened | | DSH-009 | Low | Performance | Confirmed | `AlarmsHubPublisher` has no idle gate | | DSH-010 | Low | Performance | Confirmed | Alarms page re-sorts and re-renders every 3 s even when nothing changed | Areas read and found sound (no finding): `DashboardSessionAcl` decision order and fallback arm, `EventsHubViewerRegistry` counting, `DashboardEventBroadcaster` pump/teardown locking, `DashboardSnapshotFeed` generation handling, `HubTokenService` mint/validate (anonymous principals mint a token that never validates), `/hubs/token` scheme restriction, page disposal of timers and `CancellationTokenSource`s. --- ## DSH-001 — `/alarms` `AlarmsPolicy` is bypassed by in-circuit navigation - **Severity:** High — **Category:** Bug (security) — **Confidence:** Confirmed (code reading; not exercised in a browser) - **Locations:** - `Dashboard/Components/Routes.razor:4` — ``, not `AuthorizeRouteView` - `Dashboard/Components/App.razor:13` — `` (global interactive routing) - `Dashboard/Components/Pages/AlarmsPage.razor:12` — `[Authorize(Policy = AlarmsPolicy)]` is the only gate; `OnInitialized` (212–216) starts the poll and feed loops unconditionally - `Dashboard/DashboardEndpointRouteBuilderExtensions.cs:135-138` — endpoint-level `RequireAuthorization(ViewerPolicy)` - `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/AlarmFeedAuthorizationTests.cs:144-159` — asserts endpoint metadata only **Description.** The page attribute is enforced by endpoint routing on a full HTTP request to `/alarms`. With the router rendered interactively, a navigation that starts inside an existing circuit never issues an HTTP request for the page: the in-circuit `Router` resolves the route and `RouteView` renders it. `RouteView` does not evaluate `[Authorize]`; only `AuthorizeRouteView` does. `AlarmsPage` has no in-component check, and `IDashboardLiveDataService.QueryAlarmsAsync` / `IGatewayAlarmService.StreamAsync` take no principal. **Failure scenario.** Anonymous localhost (`AllowAnonymousLocalhost=true`, the default) or any caller under `Authentication:Mode=Disabled` loads `/` — allowed by `ViewerPolicy`. The nav link is hidden (`MainLayout.razor:18-22`), but the caller runs `Blazor.navigateTo('/alarms')` in the console, or clicks any in-page anchor pointing at `/alarms`. The circuit renders `AlarmsPage` and the galaxy-wide alarm list is displayed. This is exactly the audience the contract says "do not receive it at all". **Related.** `/admin/secrets` (shared `ZB.MOM.WW.Secrets.Ui` page) relies on the same attribute mechanism, so a Viewer can reach it the same way. Its mutating and reveal controls are separately wrapped in `AuthorizeView` in the library source, so the exposure there appears limited to the list itself. Not verified against the packaged 1.0.1 build. **Suggested fix.** Switch `Routes.razor` to `AuthorizeRouteView` with a `NotAuthorized` fragment. Check that anonymous localhost still passes `ViewerPolicy` in-circuit, since `DashboardAuthorizationHandler` reads `IHttpContextAccessor`. As defense in depth, have `AlarmsPage` call `IAuthorizationService.AuthorizeAsync(user, AlarmsPolicy)` before starting its loops. **Test idea.** bUnit: render `Routes` with an unauthenticated `AuthenticationState`, navigate the `NavigationManager` to `/alarms`, assert `AlarmsPage` is not instantiated and `IGatewayAlarmService.StreamAsync` is never called. --- ## DSH-002 — Live-read failure orphans the dashboard session and worker - **Severity:** High — **Category:** Bug — **Confidence:** Confirmed code path; trigger frequency Plausible - **Locations:** - `Dashboard/DashboardLiveDataService.cs:179-184` — catch-all calls `InvalidateSession()` - `Dashboard/DashboardLiveDataService.cs:541-546` — `InvalidateSession` nulls `_session` without closing it - `Dashboard/DashboardLiveDataService.cs:482-497` — `EnsureReadyAsync` closes the old session only when `_session` is still non-null - `Sessions/GatewaySession.cs:2276-2282` — a bulk reply with non-Ok `ProtocolStatus` throws `SessionManagerException` while the session stays Ready - `Configuration/SessionOptions.cs:13,21,80` — `MaxSessions=64`, `DefaultLeaseSeconds=1800`, `UnattachedSessionGraceSeconds=0` (sweep disabled) **Description.** Any non-cancellation exception in `ReadAsync` drops the reference to the dashboard's session. If the session did not fault (command timeout, non-Ok protocol status on a bulk subscribe or read, transient `SessionNotReady`), it stays in the registry as Ready with a live x86 worker and up to 256 advised tags. Nothing references it, so the fault sweep does not apply and the unattached-grace sweep is off by default; it lives until the 30-minute lease expires. The next Browse poll opens a new session and worker. **Failure scenario.** An operator has a Browse page open with watched tags. The worker answers a bulk read with a non-Ok protocol status, or a command times out, repeatedly. The page polls every 2 s (`BrowsePage.razor:603`); each failing poll opens a fresh session and leaks the previous one. Within minutes the registry reaches `MaxSessions` and `OpenSession` is refused for real gRPC clients (OtOpcUa, ScadaBridge) for up to 30 minutes, with dozens of orphan worker processes still pumping events. **Suggested fix.** In the catch block, capture the session id before invalidating and call `CloseQuietlyAsync` on it (still under `_gate`). Consider not invalidating on per-command failures that leave the session Ready. **Test idea.** Fake `ISessionManager` whose session throws `SessionManagerException` from `ReadBulkAsync`; call `ReadAsync` twice; assert `CloseSessionAsync` was called for the first session id and at most one session is open. --- ## DSH-003 — Snapshot tick runs every health check; a slow check stalls the tick - **Severity:** Medium — **Category:** Performance — **Confidence:** Confirmed - **Locations:** - `Dashboard/DashboardSnapshotService.cs:193-194, 215-216` — both refreshes awaited before every `yield return GetSnapshot()` - `Dashboard/DashboardSnapshotService.cs:230-265` — `RefreshGatewayStatusAsync` runs `HealthCheckService.CheckHealthAsync` with a 2 s bound (`:27`) - `Diagnostics/GatewayHealthCheckExtensions.cs:21-39` — registered checks: SQLite open + `SELECT 1`, worker exe, Galaxy SQL `TestConnectionAsync`, sessions - `Diagnostics/GalaxySqlHealthCheck.cs` — own timeout 5 s - `Dashboard/Hubs/DashboardSnapshotHub.cs:52` — one more full evaluation per hub connect **Description.** While any dashboard page or `/hubs/snapshot` client is open, each snapshot tick (default 1 s) performs a Galaxy SQL round trip and a SQLite connection open. The page feed and the hub publisher each run their own enumeration, so with both audiences present it is up to two evaluations per second (the zero-timeout gate only skips overlapping ones). The evaluation is inline in the tick, so the snapshot cadence is coupled to the slowest check. **Failure scenario.** Galaxy SQL becomes slow or unreachable (connect takes more than 2 s). Each tick now blocks for the 2 s bound before yielding, so every dashboard page updates roughly every 3 s instead of every 1 s. Because the 2 s outer bound is shorter than the check's own 5 s timeout, the check never gets to report `Unhealthy`: the outer cancellation propagates out of `CheckHealthAsync` and the status is written as `Unknown` (`:255-259`), which hides the actual cause. In steady state the cost is a 1–2 Hz SQL ping against the Galaxy Repository server for as long as a browser tab is open. **Suggested fix.** Decouple status from the tick: refresh on its own slower interval (for example 10–15 s, like `ApiKeySummaryRefreshInterval`) in a background task, and have the tick read the cached value. Make the outer bound at least the longest per-check timeout. **Test idea.** Fake `HealthCheckService` that delays 5 s; drive `WatchSnapshotsAsync` with a fake `TimeProvider`; assert snapshots keep arriving at the configured interval and that the health service is invoked at most once per refresh interval. --- ## DSH-004 — Session-details event pump renders once per wake - **Severity:** Medium — **Category:** Performance — **Confidence:** Confirmed (code); magnitude Plausible - **Locations:** `Dashboard/Components/Pages/SessionDetailsPage.razor:363-408` (pump), `:143-153` (unkeyed row loop) **Description.** `PumpEventsAsync` wakes on `WaitToReadAsync`, drains whatever is queued, and dispatches `StateHasChanged`. Draining coalesces only events that arrived during the previous render dispatch; there is no minimum interval between renders. New events are prepended with `AddFirst` and the rows have no `@key`, so every render diffs all 50 rows as changed. **Failure scenario.** An operator opens the details page of a session delivering about 240 events/s (the rate recorded for vd03). The pump issues on the order of 100+ renders per second for that circuit, each a 50-row, 5-column diff serialized to the browser, on top of the 1 Hz snapshot render. Several operators on busy sessions multiply this. The server-side cost lands on the gateway process that is also running the event pipeline. **Suggested fix.** Coalesce by time: after a batch is applied, wait a fixed interval (for example 250 ms) before the next read, or drive rendering from a `PeriodicTimer` that drains the channel. Add `@key="evt.WorkerSequence"` to the row. **Test idea.** bUnit with a fake subscription: write 1,000 events over one simulated second; assert the component's render count stays below a small bound and the final 50 rows are the newest 50. --- ## DSH-005 — Late `/hubs/alarms` clients never get the active-alarm snapshot - **Severity:** Medium — **Category:** Bug — **Confidence:** Confirmed - **Locations:** `Dashboard/Hubs/AlarmsHub.cs:40-44`; `Dashboard/Hubs/AlarmsHubPublisher.cs:104-128` **Description.** The publisher holds one monitor subscription for the process lifetime. The monitor primes that subscription with the active-alarm snapshot once, at subscribe time, and the publisher group-sends it to whoever is connected at that moment — normally nobody, since it starts with the host. `AlarmsHub.OnConnectedAsync` only joins the group; it sends no reset, snapshot, provider status or truncation status, and the hub exposes no method to request them. **Failure scenario.** The gateway starts with 40 active alarms. Ten minutes later an external consumer connects to `/hubs/alarms`. It receives only subsequent transitions; the 40 standing alarms, the current provider-degraded state and the truncation flag never arrive unless the publisher happens to resubscribe. The client shows an empty or partial alarm list indefinitely. **Suggested fix.** In `OnConnectedAsync`, send the caller a `ResetMessage` followed by the current snapshot and status frames (redacted by the same rule), built from `IGatewayAlarmService.CurrentAlarms` / state, before adding it to the group. **Test idea.** Start the publisher against a fake alarm service with two active alarms, then connect a hub client; assert it receives a reset plus two `active_alarm` frames without any new transition being raised. --- ## DSH-006 — Auth lifetimes are not enforced on live connections - **Severity:** Medium — **Category:** Bug (security) — **Confidence:** Confirmed (by absence; repo-wide search finds no `CloseOnAuthenticationExpiration` and no revalidating `AuthenticationStateProvider`) - **Locations:** - `Dashboard/HubTokenService.cs:48` — 5-minute lifetime, described as the bound on stale roles and tag grants - `Dashboard/HubTokenAuthenticationHandler.cs:57-58` — ticket carries no expiry - `Dashboard/DashboardServiceCollectionExtensions.cs:113-117` — `AddSignalR()` and `AddCascadingAuthenticationState()` with defaults - `Dashboard/Hubs/EventsHub.cs:66` and `Dashboard/DashboardSessionAcl.cs:141-151` — ACL evaluated against `Context.User`, which is fixed at connect - `Dashboard/Components/Pages/SessionDetailsPage.razor:287-290`, `SessionsPage.razor:184-187` — admin actions re-read the circuit's fixed authentication state **Description.** The token and cookie lifetimes bound only the handshake. A WebSocket hub connection opened with a valid token keeps its principal for as long as the socket stays up, and each later `SubscribeSession` on it is decided from the role and tag claims frozen at connect. The "re-resolved on every subscribe" rule therefore re-resolves nothing on this seam after the first five minutes. Blazor circuits behave the same way: the authentication state is captured at circuit start and is never revalidated, and a circuit with an open tab issues no HTTP requests, so cookie expiry or sign-out elsewhere does not end it. **Failure scenario.** (a) A user with a tag grant mints a hub token, opens `/hubs/events`, and keeps the socket open. Their LDAP group is removed and they sign out. Hours later the same connection calls `SubscribeSession` for a newly opened tagged session and is admitted on the stale tag claims. (b) An Administrator leaves a Sessions tab open, signs out in another tab (or is removed from the admin group). The open tab can still Close sessions, Kill workers and manage API keys, because `CanManage` sees the circuit's original Admin principal. **Suggested fix.** Stamp `ExpiresUtc` on the hub-token ticket and set `CloseOnAuthenticationExpiration = true` for the hub endpoints, so token-authenticated connections must reconnect with a fresh token. For circuits, register a `RevalidatingServerAuthenticationStateProvider` that re-checks the cookie/session on an interval, or at minimum tracks sign-out. **Test idea.** Integration test with a short token lifetime: connect to `/hubs/events`, advance past expiry, assert the connection is closed or that `SubscribeSession` is refused. bUnit: flip the authentication state to signed-out and assert `ConfirmPendingAsync` is denied. --- ## DSH-007 — Cancelled Browse read can leave untracked advises - **Severity:** Low — **Category:** Bug — **Confidence:** Plausible - **Locations:** `Dashboard/DashboardLiveDataService.cs:152-155` (subscribe, then track), `:179` (cancellation deliberately not caught); `Dashboard/Components/Pages/BrowsePage.razor:677, 709` (page token cancels in-flight reads on dispose) **Description.** If the caller's token fires after the bulk subscribe command was sent to the worker but before `TrackSubscribed` runs, the tags are advised on the worker with no entry in `_subscribed`. The session is not invalidated on cancellation, so those advises are never unadvised and do not count against `MaxSubscribedTags`. A later read of the same tags subscribes them again. **Failure scenario.** An operator adds several tags and navigates away from Browse while the first read is in flight. The shared dashboard worker keeps those items advised, and keeps emitting data-change events for them, for the life of the dashboard session. Repeating this grows the standing advise set past its documented cap. **Suggested fix.** Run the subscribe-and-track step under a token that is not the caller's (or under `CancellationToken.None` with the existing command timeout), and only observe the caller's token before and after it. **Test idea.** Fake session whose `SubscribeBulkAsync` completes the worker-side subscribe and then observes cancellation; cancel mid-call; assert a subsequent read does not re-subscribe, or that an unadvise was issued. --- ## DSH-008 — `NativeDialog` JS interop on every render after first use - **Severity:** Low — **Category:** Performance — **Confidence:** Confirmed - **Locations:** `Dashboard/Components/Shared/NativeDialog.razor:56-87`; hosts at `SessionsPage.razor:30`, `SessionDetailsPage.razor:64`, `WorkersPage.razor:30`, `ApiKeysPage.razor:43,54` **Description.** `OnAfterRenderAsync` calls `close` whenever the dialog is not open and the JS module is loaded, and `update` whenever it is open, with no check that anything changed. The host pages re-render on every snapshot tick, and the dialog receives a `RenderFragment` and an `EventCallback`, so it re-renders with them. **Failure scenario.** An Administrator opens and dismisses one confirm dialog on the Sessions page. From then on that tab makes one JS interop round trip per second for as long as it stays open; an open create-key dialog does the same with `update`. **Suggested fix.** Track the last state sent to JS (`open`/`closed`, `IsBusy`, generation) and skip the interop call when it is unchanged. **Test idea.** bUnit with a JS interop mock: open then close the dialog, re-render the parent ten times, assert no further `close` invocations. --- ## DSH-009 — `AlarmsHubPublisher` has no idle gate - **Severity:** Low — **Category:** Performance — **Confidence:** Confirmed - **Locations:** `Dashboard/Hubs/AlarmsHubPublisher.cs:104-128, 196-218` **Description.** Unlike the snapshot publisher (connection counter) and the events broadcaster (viewer registry), the alarm publisher always holds a monitor subscription, deep-clones each transition or active-alarm message for redaction (the default), and performs a group send, even when no hub client is connected. Server-rendered pages do not use this hub, so in most deployments the group is permanently empty. **Failure scenario.** A site with a chatty alarm provider and no external hub consumer pays a protobuf clone and a SignalR group send per alarm message, plus a full snapshot replay on every resubscribe, for output nobody receives. **Suggested fix.** Count `AlarmsHub` connections and skip the clone and send when the count is zero. This combines naturally with DSH-005: once connections are primed individually, the publisher can stay unsubscribed while idle. **Test idea.** Run the publisher with a fake feed and zero connections; assert no `SendAsync` on the hub context and no clone (the source message instance count is unchanged). --- ## DSH-010 — Alarms page recomputes and re-renders every 3 s regardless of change - **Severity:** Low — **Category:** Performance — **Confidence:** Confirmed - **Locations:** `Dashboard/Components/Pages/AlarmsPage.razor:406-423`; `Dashboard/DashboardLiveDataService.cs:196-198`; `Dashboard/DashboardAlarmView.cs` (`Filtered`, `Areas`) **Description.** Each open Alarms page projects the whole `CurrentAlarms` set into new `DashboardActiveAlarm` objects every 3 s, replaces its list, and increments `_alarmGeneration` unconditionally. That invalidates the memoized filter and area views, so the filter, two-key sort and distinct-area pass rerun and the whole table re-renders even when no alarm changed. The work is per circuit. **Failure scenario.** With a few thousand active alarms and several operators on the page, the gateway allocates and sorts the full set per viewer every 3 s and pushes a full-table diff each time, while the alarm state is static. **Suggested fix.** Bump the generation only when the result differs (compare count plus a cheap per-alarm signature, or expose a change sequence from the alarm service and skip the poll when it has not advanced). **Test idea.** Poll twice with an unchanged fake alarm set; assert `DashboardAlarmView.FilterComputations` stays at 1.