Compare commits
10 Commits
c446bef64f
...
ca443b1903
| Author | SHA1 | Date | |
|---|---|---|---|
| ca443b1903 | |||
| 7a2da4d8b6 | |||
| a0b21ca225 | |||
| 3690e4c2ca | |||
| 1d652b24c6 | |||
| ee1423db7a | |||
| 4993057ed5 | |||
| 073252d7a6 | |||
| a894717319 | |||
| 0856cd4f93 |
@@ -116,7 +116,7 @@ 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`, `invoke`, `event`, `metadata`, `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/`.
|
||||
|
||||
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 `__Host-MxGatewayDashboard` cookie. SignalR hubs at `/hubs/{snapshot,alarms,events}` accept either the cookie or a 30-minute bearer minted at `/hubs/token`. `Dashboard:AllowAnonymousLocalhost` bypasses auth on loopback when enabled.
|
||||
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 `__Host-MxGatewayDashboard` cookie. SignalR hubs at `/hubs/{snapshot,alarms,events}` accept either the cookie or a 30-minute bearer minted at `/hubs/token`. `Dashboard:AllowAnonymousLocalhost` bypasses auth on loopback when enabled. `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
|
||||
|
||||
|
||||
@@ -171,6 +171,8 @@ events (a "gap") and must re-snapshot; whatever is still retained is replayed.
|
||||
| `MxGateway:Dashboard:RecentSessionLimit` | `200` | Maximum number of session summaries projected into each dashboard snapshot. |
|
||||
| `MxGateway:Dashboard:ShowTagValues` | `false` | Reserved display control for tag values. The dashboard does not show full tag values by default. |
|
||||
| `MxGateway:Dashboard:GroupToRole` | _(empty)_ | LDAP group → dashboard role mapping. Keys are LDAP group names (short CN or full DN — leading-RDN match). Values must be `Admin` (read/write, API-key CRUD) or `Viewer` (read-only). A user whose LDAP groups don't intersect this map cannot sign in; with no mapping at all, only the loopback bypass admits anyone. |
|
||||
| `MxGateway:Dashboard:DisableLogin` | `false` | Dev/test only. When `true`, replaces the cookie authentication handler with `DashboardAutoLoginAuthenticationHandler`, which auto-authenticates every dashboard request — including requests from remote browsers, not just loopback — as `AutoLoginUser` holding both `Administrator` and `Viewer` roles. No login form, LDAP bind, or cookie is involved. A loud one-time startup warning is logged. Differs from `AllowAnonymousLocalhost`: `DisableLogin` mints a real authenticated principal (so role-gated write affordances appear), whereas `AllowAnonymousLocalhost` satisfies the authorization requirement on loopback only without minting a principal (write affordances stay hidden). Never enable in production. |
|
||||
| `MxGateway:Dashboard:AutoLoginUser` | `(null)` | Username stamped on the synthetic principal when `DisableLogin` is `true`. Default `(null)` — a null or blank value falls back to `multi-role`. Has no effect when `DisableLogin` is `false`. |
|
||||
|
||||
`SnapshotIntervalMilliseconds` must be greater than zero. `RecentFaultLimit`
|
||||
and `RecentSessionLimit` must be greater than or equal to zero.
|
||||
|
||||
@@ -442,6 +442,37 @@ authorizes every request, and `MxGateway:Dashboard:AllowAnonymousLocalhost`
|
||||
requests always require an authenticated principal carrying at least the
|
||||
Viewer role.
|
||||
|
||||
### DisableLogin dev bypass
|
||||
|
||||
`MxGateway:Dashboard:DisableLogin` (default `false`) is a third bypass for
|
||||
dev and test environments where LDAP is unavailable or irrelevant.
|
||||
|
||||
When the flag is `true`, the `DashboardAuthenticator`-backed cookie handler is
|
||||
replaced by `DashboardAutoLoginAuthenticationHandler`, registered under the
|
||||
same scheme name (`MxGateway.Dashboard`). The handler auto-authenticates every
|
||||
incoming request — including requests from remote browsers, not just loopback —
|
||||
as a principal for `MxGateway:Dashboard:AutoLoginUser` (default `multi-role`)
|
||||
holding both the `Administrator` and `Viewer` role claims.
|
||||
|
||||
The same-scheme-name swap is intentional: every authorization policy
|
||||
(`MxGateway.Dashboard.Viewer`, `MxGateway.Dashboard.Admin`,
|
||||
`MxGateway.Dashboard.HubClients`) resolves the `MxGateway.Dashboard` scheme,
|
||||
so the handler replacement requires zero changes to policies, Razor page
|
||||
attributes, or hub authorization attributes. `UseAuthentication()` stamps the
|
||||
principal on `HttpContext.User` for the full HTTP pipeline, the Blazor circuit,
|
||||
and the SignalR hubs uniformly — there is no separate path for each surface.
|
||||
|
||||
This differs from `AllowAnonymousLocalhost`: that flag satisfies the Viewer
|
||||
authorization requirement on loopback without minting an authenticated
|
||||
principal, so role-gated write affordances (Admin-only API-key CRUD, Close/Kill
|
||||
controls) stay hidden. `DisableLogin` mints a real multi-role principal, so
|
||||
those affordances appear — which is the point for dev scenarios where a
|
||||
developer needs the full Admin surface without standing up LDAP.
|
||||
|
||||
A loud one-time startup warning is logged when `DisableLogin` is `true`. The
|
||||
gRPC API-key authentication path is untouched; only the dashboard cookie
|
||||
surface is affected. Never enable in production.
|
||||
|
||||
### Hub bearer flow
|
||||
|
||||
SignalR connections cannot reuse the `__Host-` cookie when the JS client
|
||||
|
||||
@@ -0,0 +1,141 @@
|
||||
# Dashboard "Disable Login" Dev Flag — Design
|
||||
|
||||
**Date:** 2026-06-16
|
||||
**Status:** Approved (brainstorming) — ready for implementation plan.
|
||||
|
||||
## Goal
|
||||
|
||||
A config flag that **disables login in the gateway dashboard**. When enabled, every
|
||||
request is auto-authenticated as a fixed dev user (default **`multi-role`**) holding
|
||||
**both** dashboard roles (`Administrator` + `Viewer`), so no login form, cookie, or LDAP
|
||||
bind is involved and the whole UI behaves as a signed-in multi-role admin. Default
|
||||
**off**. Mirrors the sister project OtOpcUa's `Security:Auth:DisableLogin` feature.
|
||||
|
||||
## Why / scope
|
||||
|
||||
Speeds up dashboard testing against the remote dev boxes (10.100.0.48, wonder) with no
|
||||
sign-in round-trip and no GLAuth dependency. Scope is the **dashboard cookie web surface
|
||||
only** — the gRPC API-key auth path (`authorization: Bearer mxgw_…`) and its scopes are a
|
||||
separate auth model and are **untouched**.
|
||||
|
||||
## Background (current dashboard auth, verified)
|
||||
|
||||
- Dashboard auth is a **single cookie scheme** `MxGateway.Dashboard` registered in
|
||||
`Dashboard/DashboardServiceCollectionExtensions.cs::AddGatewayDashboard`
|
||||
(`AddAuthentication("MxGateway.Dashboard").AddCookie(...)`), plus a bearer scheme
|
||||
`MxGateway.Dashboard.HubToken` (`HubTokenAuthenticationHandler`) for SignalR hubs.
|
||||
- Real login: `/login` → `DashboardAuthenticator.AuthenticateAsync` → shared
|
||||
`ILdapAuthService` bind/search → `IGroupRoleMapper<string>` → `CreatePrincipal` builds a
|
||||
`ClaimsPrincipal` (`ZbClaimTypes.Name`/`Username`/`DisplayName` + one `ZbClaimTypes.Role`
|
||||
per role + `LdapGroupClaimType` group claims; identity authType = the cookie scheme,
|
||||
nameType = `ZbClaimTypes.Name`, roleType = `ZbClaimTypes.Role`) → cookie sign-in.
|
||||
- Authorization: a custom `DashboardAuthorizationHandler` evaluates
|
||||
`DashboardAuthorizationRequirement`. Policies: `ViewerPolicy` (AnyDashboardRole),
|
||||
`AdminPolicy` (AdminOnly), `HubClientsPolicy` (cookie **or** hub-token scheme,
|
||||
AnyDashboardRole).
|
||||
- Roles: exactly two — `DashboardRoles.Admin` (`"Administrator"`) and
|
||||
`DashboardRoles.Viewer` (`"Viewer"`).
|
||||
- **Existing escapes (important):** `DashboardAuthorizationHandler` already short-circuits
|
||||
when `Authentication.Mode == Disabled` or when `Dashboard.AllowAnonymousLocalhost`
|
||||
(default **true**) and the request is loopback. **But both only `context.Succeed(...)`
|
||||
the authorization requirement — they do not mint an authenticated principal.** So
|
||||
`HttpContext.User.Identity.IsAuthenticated` stays false, `Identity.Name` is null, and
|
||||
role-gated `AuthorizeView` write affordances stay **hidden**. That is precisely why they
|
||||
do not deliver the "logged-in multi-role admin" experience this feature needs.
|
||||
|
||||
## Approach (chosen: always-authenticating handler under the cookie scheme name)
|
||||
|
||||
When the flag is **on**, **replace the `.AddCookie(...)` registration with a custom
|
||||
`AuthenticationHandler` registered under the *same* scheme name**
|
||||
(`DashboardAuthenticationDefaults.AuthenticationScheme` = `"MxGateway.Dashboard"`). Its
|
||||
`HandleAuthenticateAsync` **always returns `AuthenticateResult.Success`** with the fixed
|
||||
dev principal (configured username, both roles), shaped identically to what
|
||||
`DashboardAuthenticator.CreatePrincipal` produces. `UseAuthentication()` stamps that
|
||||
principal on `HttpContext.User` for **every** request.
|
||||
|
||||
Registering under the cookie scheme name (not a new name) is the load-bearing detail: the
|
||||
`ViewerPolicy`, `AdminPolicy`, and `HubClientsPolicy` all resolve through that scheme via
|
||||
`DashboardAuthorizationHandler`'s role check, so they pass with **no policy or page
|
||||
changes**. The HTTP pipeline (Razor pages, admin endpoints), the Blazor circuit
|
||||
(`AuthorizeView`, `[CascadingParameter] AuthenticationState`), and the SignalR hubs are
|
||||
all covered by the single `HttpContext.User` seam. Because the handler authenticates every
|
||||
request, the feature is inherently **global** (all clients, including remote browsers) —
|
||||
the agreed scope.
|
||||
|
||||
`SignInAsync`/`SignOutAsync` are no-ops (no cookie to write or clear; the next request
|
||||
re-authenticates through the handler).
|
||||
|
||||
**Alternatives rejected:** (2) mint the principal inside the existing
|
||||
`DashboardAuthorizationHandler` bypass branches — authorization runs after authentication,
|
||||
so `HttpContext.User` is set too late for the Blazor auth state, and two seams must agree
|
||||
(this is essentially today's half-feature); (3) a pipeline middleware plus a stubbed
|
||||
`AuthenticationStateProvider` — two components to keep in sync, and a page request still
|
||||
302s to `/login` unless `HttpContext.User` is also set.
|
||||
|
||||
## Components
|
||||
|
||||
### 1. Config surface — two new fields on `DashboardOptions` (`MxGateway:Dashboard:*`)
|
||||
- `DisableLogin` (bool, default **false**).
|
||||
- `AutoLoginUser` (string, default **`"multi-role"`** — this project's GLAuth
|
||||
Administrator test user). Used as `Name`/`Username`/`DisplayName` of the minted
|
||||
principal; blank falls back to `"multi-role"`.
|
||||
|
||||
"All permissions" = principal minted with **both** `DashboardRoles.Admin` and
|
||||
`DashboardRoles.Viewer`.
|
||||
|
||||
### 2. `DashboardAutoLoginAuthenticationHandler`
|
||||
`AuthenticationHandler<AuthenticationSchemeOptions>` implementing
|
||||
`IAuthenticationSignInHandler`. Mirrors OtOpcUa's `AutoLoginAuthenticationHandler`, adapted
|
||||
to this project's claim shape (`ZbClaimTypes.*`, `DashboardRoles.*`). Always `Success`;
|
||||
SignIn/SignOut no-ops.
|
||||
|
||||
### 3. Wiring in `AddGatewayDashboard`
|
||||
Read `MxGateway:Dashboard:DisableLogin` directly from `IConfiguration` at registration
|
||||
time (the same idiom OtOpcUa uses, since scheme registration precedes options binding).
|
||||
- On → `AddScheme<AuthenticationSchemeOptions, DashboardAutoLoginAuthenticationHandler>(
|
||||
"MxGateway.Dashboard", _ => {})` in place of `AddCookie`; the `HubToken` scheme stays
|
||||
registered unchanged.
|
||||
- Off → existing `AddCookie(...)` path unchanged.
|
||||
|
||||
### 4. Safety
|
||||
- Default **off**.
|
||||
- A **loud one-time startup `LogWarning`** ("DASHBOARD LOGIN DISABLED
|
||||
(MxGateway:Dashboard:DisableLogin=true) — every request authenticated as '{user}' with
|
||||
full permissions (Administrator, Viewer). Dev/test only; never enable in production.")
|
||||
via the same options `PostConfigure<ILoggerFactory>` idiom OtOpcUa uses.
|
||||
- The existing `AllowAnonymousLocalhost` / `Authentication.Mode == Disabled` escapes are
|
||||
left untouched — `DisableLogin` is orthogonal (it changes *authentication*, minting a
|
||||
principal, not authorization bypass); when it is on the authorization handler's normal
|
||||
role-check branch succeeds, so the bypass branches simply do not matter.
|
||||
|
||||
## Error handling / edge cases
|
||||
|
||||
- Blank `AutoLoginUser` → falls back to `"multi-role"` (handler never mints a nameless
|
||||
principal).
|
||||
- `/login` still renders when the flag is on but is pointless (the user is already
|
||||
authenticated); `POST /login`'s `SignInAsync` is a no-op. `/logout` is likewise a no-op.
|
||||
No redirect added (YAGNI).
|
||||
- No interaction with the gRPC API-key path — that auth is entirely separate.
|
||||
|
||||
## Testing
|
||||
|
||||
- **Handler unit test:** `HandleAuthenticateAsync` returns `Success`;
|
||||
`principal.Identity.IsAuthenticated`, `Identity.Name == AutoLoginUser`,
|
||||
`IsInRole("Administrator")` && `IsInRole("Viewer")`; blank-user fallback.
|
||||
- **Wiring / integration (`WebApplicationFactory`):** with `DisableLogin=true`, an
|
||||
`AdminPolicy`-gated endpoint returns 200 with **no** cookie, and a `/hubs/*` negotiate
|
||||
authorizes; the startup warning is emitted.
|
||||
- **Regression:** with the flag off (default), the real cookie handler is still registered
|
||||
and existing dashboard auth tests pass.
|
||||
|
||||
## Docs to update in the same change
|
||||
|
||||
- `docs/GatewayConfiguration.md` — new `MxGateway:Dashboard:DisableLogin` /
|
||||
`AutoLoginUser` options.
|
||||
- The dashboard design doc (`docs/GatewayDashboardDesign.md`).
|
||||
- The CLAUDE.md dashboard-auth note (alongside the `AllowAnonymousLocalhost` mention).
|
||||
|
||||
## Scope / verification
|
||||
|
||||
Gateway-server-side only (.NET 10, x64) — builds and tests entirely on macOS. No worker,
|
||||
no `.proto`, no client, no gRPC changes.
|
||||
@@ -0,0 +1,447 @@
|
||||
# Dashboard "Disable Login" Dev Flag — Implementation Plan
|
||||
|
||||
> **For Claude:** REQUIRED SUB-SKILL: Use superpowers-extended-cc:executing-plans to implement this plan task-by-task.
|
||||
|
||||
**Goal:** Add a `MxGateway:Dashboard:DisableLogin` config flag that, when on, auto-authenticates every dashboard request as a fixed dev user (default `multi-role`) holding both dashboard roles — no login form, cookie, or LDAP bind.
|
||||
|
||||
**Architecture:** When the flag is on, the dashboard's `AddCookie(...)` registration is replaced by a custom `AuthenticationHandler` registered **under the same scheme name** (`MxGateway.Dashboard`) whose `HandleAuthenticateAsync` always succeeds with a multi-role principal. `UseAuthentication()` stamps that principal on `HttpContext.User` for every request, so every policy (Viewer/Admin/HubClients), the Blazor circuit, and the SignalR hubs see a signed-in admin with **zero policy or page changes**. Mirrors the sister project OtOpcUa's `Security:Auth:DisableLogin`.
|
||||
|
||||
**Tech Stack:** .NET 10 (x64) gateway server; ASP.NET Core authentication/authorization; xUnit. Server-side only — no worker, no `.proto`, no clients, no gRPC API-key changes. Builds and tests entirely on macOS.
|
||||
|
||||
**Design doc:** `docs/plans/2026-06-16-dashboard-disable-login-design.md`
|
||||
|
||||
**Key existing files (verified):**
|
||||
- `src/ZB.MOM.WW.MxGateway.Server/Configuration/DashboardOptions.cs` — options bound from `MxGateway:Dashboard`.
|
||||
- `src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs::AddGatewayDashboard` — auth scheme + policy wiring.
|
||||
- `src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAuthenticationDefaults.cs` — scheme/policy name constants (`AuthenticationScheme = "MxGateway.Dashboard"`, `AdminPolicy`, `ViewerPolicy`).
|
||||
- `src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardRoles.cs` — `Admin = "Administrator"`, `Viewer = "Viewer"`.
|
||||
- `src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAuthenticator.cs::CreatePrincipal` — the claim shape to mirror (`ZbClaimTypes.Name/Username/DisplayName` + `ZbClaimTypes.Role` per role; identity authType = scheme, nameType = `ZbClaimTypes.Name`, roleType = `ZbClaimTypes.Role`).
|
||||
- `ZbClaimTypes` (from `ZB.MOM.WW.Auth.AspNetCore`): `Name` (= `ClaimTypes.Name`), `Role` (= `ClaimTypes.Role`), `Username` (`"zb:username"`), `DisplayName` (`"zb:displayname"`).
|
||||
- `src/ZB.MOM.WW.MxGateway.Server/Properties/AssemblyInfo.cs` — `InternalsVisibleTo("ZB.MOM.WW.MxGateway.Tests")` (so `internal` members are test-visible).
|
||||
|
||||
**Test conventions (verified):** no Moq/NSubstitute — hand-written stubs only. Integration-style tests build the real app with `GatewayApplication.Build(["--MxGateway:Dashboard:Key=value"])` and resolve services from `app.Services` (see `DashboardCookieOptionsTests`, `DashboardHubsRegistrationTests`). Run filtered tests only (per standing guidance), with `MSBUILDDISABLENODEREUSE=1`.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Config fields on `DashboardOptions`
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~3 min
|
||||
**Parallelizable with:** none (Tasks 2/3 depend on these fields)
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.MxGateway.Server/Configuration/DashboardOptions.cs`
|
||||
- Test: `src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsTests.cs`
|
||||
|
||||
**Step 1: Write the failing test** — add to `GatewayOptionsTests.cs`:
|
||||
|
||||
```csharp
|
||||
[Fact]
|
||||
public void DashboardOptions_DisableLogin_DefaultsToFalse()
|
||||
{
|
||||
Assert.False(new DashboardOptions().DisableLogin);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DashboardOptions_AutoLoginUser_DefaultsToNull()
|
||||
{
|
||||
Assert.Null(new DashboardOptions().AutoLoginUser);
|
||||
}
|
||||
```
|
||||
|
||||
(If `GatewayOptionsTests` lacks `using ZB.MOM.WW.MxGateway.Server.Configuration;`, add it.)
|
||||
|
||||
**Step 2: Run it, expect FAIL** (compile error: no such members)
|
||||
|
||||
Run: `MSBUILDDISABLENODEREUSE=1 dotnet test src/ZB.MOM.WW.MxGateway.Tests/ZB.MOM.WW.MxGateway.Tests.csproj --filter "FullyQualifiedName~GatewayOptionsTests.DashboardOptions"`
|
||||
|
||||
**Step 3: Add the two `init` properties** to `DashboardOptions.cs` (place near `AllowAnonymousLocalhost`):
|
||||
|
||||
```csharp
|
||||
/// <summary>
|
||||
/// DEV/TEST ONLY. When true, the dashboard bypasses the login form entirely and
|
||||
/// auto-authenticates EVERY request as <see cref="AutoLoginUser"/> holding both
|
||||
/// dashboard roles (Administrator + Viewer). No cookie, no LDAP bind. Default false.
|
||||
/// Unlike <see cref="AllowAnonymousLocalhost"/> (which only succeeds the authorization
|
||||
/// requirement without authenticating), this mints a real principal, so the UI behaves
|
||||
/// as a signed-in admin and applies to all clients (not just loopback). Never enable in
|
||||
/// production. See docs/plans/2026-06-16-dashboard-disable-login-design.md.
|
||||
/// </summary>
|
||||
public bool DisableLogin { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Username minted for the auto-login principal when <see cref="DisableLogin"/> is true.
|
||||
/// Null/blank falls back to the GLAuth Administrator test user <c>multi-role</c>.
|
||||
/// </summary>
|
||||
public string? AutoLoginUser { get; init; }
|
||||
```
|
||||
|
||||
**Step 4: Run the test, expect PASS.**
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ZB.MOM.WW.MxGateway.Server/Configuration/DashboardOptions.cs src/ZB.MOM.WW.MxGateway.Tests/Configuration/GatewayOptionsTests.cs
|
||||
git commit -m "feat(dashboard): add DisableLogin + AutoLoginUser options (default off)"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: `DashboardAutoLoginAuthenticationHandler` + unit tests
|
||||
|
||||
**Classification:** high-risk (security/auth code)
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** Task 4
|
||||
|
||||
**Files:**
|
||||
- Create: `src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAutoLoginAuthenticationHandler.cs`
|
||||
- Test: `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardAutoLoginAuthenticationHandlerTests.cs`
|
||||
|
||||
**Step 1: Write the failing test** (`DashboardAutoLoginAuthenticationHandlerTests.cs`):
|
||||
|
||||
```csharp
|
||||
using System.Security.Claims;
|
||||
using ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Dashboard;
|
||||
|
||||
public sealed class DashboardAutoLoginAuthenticationHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public void CreatePrincipal_MintsAuthenticatedMultiRoleUser()
|
||||
{
|
||||
ClaimsPrincipal principal = DashboardAutoLoginAuthenticationHandler.CreatePrincipal("multi-role");
|
||||
|
||||
Assert.True(principal.Identity!.IsAuthenticated);
|
||||
Assert.Equal("multi-role", principal.Identity!.Name);
|
||||
Assert.True(principal.IsInRole(DashboardRoles.Admin));
|
||||
Assert.True(principal.IsInRole(DashboardRoles.Viewer));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void CreatePrincipal_BlankUser_FallsBackToDefault(string? user)
|
||||
{
|
||||
ClaimsPrincipal principal = DashboardAutoLoginAuthenticationHandler.CreatePrincipal(user);
|
||||
|
||||
Assert.Equal(DashboardAutoLoginAuthenticationHandler.DefaultUser, principal.Identity!.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreatePrincipal_TrimsUser()
|
||||
{
|
||||
ClaimsPrincipal principal = DashboardAutoLoginAuthenticationHandler.CreatePrincipal(" multi-role ");
|
||||
|
||||
Assert.Equal("multi-role", principal.Identity!.Name);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 2: Run it, expect FAIL** (type does not exist).
|
||||
|
||||
Run: `MSBUILDDISABLENODEREUSE=1 dotnet test src/ZB.MOM.WW.MxGateway.Tests/ZB.MOM.WW.MxGateway.Tests.csproj --filter "FullyQualifiedName~DashboardAutoLoginAuthenticationHandlerTests"`
|
||||
|
||||
**Step 3: Implement** `DashboardAutoLoginAuthenticationHandler.cs`:
|
||||
|
||||
```csharp
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Auth.AspNetCore;
|
||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||
|
||||
/// <summary>
|
||||
/// Authentication handler used ONLY when <c>MxGateway:Dashboard:DisableLogin</c> is true.
|
||||
/// Registered under the dashboard cookie scheme name
|
||||
/// (<see cref="DashboardAuthenticationDefaults.AuthenticationScheme"/>), it authenticates
|
||||
/// EVERY request as the configured dev user with both dashboard roles — no credential check,
|
||||
/// no cookie, no LDAP bind. The minted principal mirrors the shape the real login
|
||||
/// (<see cref="DashboardAuthenticator"/>) produces, so policies and the UI cannot tell it
|
||||
/// apart. DEV/TEST ONLY; never enable in production.
|
||||
/// </summary>
|
||||
public sealed class DashboardAutoLoginAuthenticationHandler
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>, IAuthenticationSignInHandler
|
||||
{
|
||||
/// <summary>Username used when <c>AutoLoginUser</c> is null or blank.</summary>
|
||||
public const string DefaultUser = "multi-role";
|
||||
|
||||
private readonly string _user;
|
||||
|
||||
/// <summary>Initializes the handler with scheme plumbing and the dashboard options.</summary>
|
||||
/// <param name="options">The per-scheme authentication options monitor.</param>
|
||||
/// <param name="logger">The logger factory the base handler uses.</param>
|
||||
/// <param name="encoder">The URL encoder the base handler uses.</param>
|
||||
/// <param name="gatewayOptions">Gateway options carrying the dashboard auto-login user.</param>
|
||||
public DashboardAutoLoginAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
IOptions<GatewayOptions> gatewayOptions)
|
||||
: base(options, logger, encoder)
|
||||
=> _user = gatewayOptions.Value.Dashboard.AutoLoginUser ?? DefaultUser;
|
||||
|
||||
/// <summary>No-op: auto-login writes no cookie, so a sign-in has nothing to persist.</summary>
|
||||
/// <param name="user">Ignored.</param>
|
||||
/// <param name="properties">Ignored.</param>
|
||||
/// <returns>A completed task.</returns>
|
||||
public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties) => Task.CompletedTask;
|
||||
|
||||
/// <summary>No-op: there is no auth cookie to clear; the next request re-authenticates.</summary>
|
||||
/// <param name="properties">Ignored.</param>
|
||||
/// <returns>A completed task.</returns>
|
||||
public Task SignOutAsync(AuthenticationProperties? properties) => Task.CompletedTask;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
ClaimsPrincipal principal = CreatePrincipal(_user);
|
||||
AuthenticationTicket ticket = new(principal, Scheme.Name);
|
||||
|
||||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the multi-role dev principal. Null/blank <paramref name="user"/> falls back to
|
||||
/// <see cref="DefaultUser"/>. Claim shape mirrors <see cref="DashboardAuthenticator"/>.
|
||||
/// </summary>
|
||||
/// <param name="user">The configured auto-login username (may be null/blank).</param>
|
||||
/// <returns>An authenticated principal holding both dashboard roles.</returns>
|
||||
internal static ClaimsPrincipal CreatePrincipal(string? user)
|
||||
{
|
||||
string name = string.IsNullOrWhiteSpace(user) ? DefaultUser : user.Trim();
|
||||
|
||||
Claim[] claims =
|
||||
[
|
||||
new Claim(ClaimTypes.NameIdentifier, name),
|
||||
new Claim(ZbClaimTypes.Username, name),
|
||||
new Claim(ZbClaimTypes.Name, name),
|
||||
new Claim(ZbClaimTypes.DisplayName, name),
|
||||
new Claim(ZbClaimTypes.Role, DashboardRoles.Admin),
|
||||
new Claim(ZbClaimTypes.Role, DashboardRoles.Viewer),
|
||||
];
|
||||
|
||||
ClaimsIdentity identity = new(
|
||||
claims,
|
||||
DashboardAuthenticationDefaults.AuthenticationScheme,
|
||||
ZbClaimTypes.Name,
|
||||
ZbClaimTypes.Role);
|
||||
|
||||
return new ClaimsPrincipal(identity);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Step 4: Run the test, expect PASS.**
|
||||
|
||||
**Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardAutoLoginAuthenticationHandler.cs src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardAutoLoginAuthenticationHandlerTests.cs
|
||||
git commit -m "feat(dashboard): add auto-login auth handler for DisableLogin mode"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Wire the scheme swap + startup warning + wiring/authorization tests
|
||||
|
||||
**Classification:** high-risk (security wiring)
|
||||
**Estimated implement time:** ~5 min
|
||||
**Parallelizable with:** none (depends on Task 2's handler)
|
||||
|
||||
**Files:**
|
||||
- Modify: `src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs`
|
||||
- Test: `src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardDisableLoginTests.cs` (create)
|
||||
|
||||
**Step 1: Write the failing tests** (`DashboardDisableLoginTests.cs`):
|
||||
|
||||
```csharp
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZB.MOM.WW.MxGateway.Server;
|
||||
using ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Dashboard;
|
||||
|
||||
public sealed class DashboardDisableLoginTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task DisableLoginOff_CookieSchemeUsesCookieHandler()
|
||||
{
|
||||
await using WebApplication app = GatewayApplication.Build([]);
|
||||
IAuthenticationSchemeProvider provider =
|
||||
app.Services.GetRequiredService<IAuthenticationSchemeProvider>();
|
||||
|
||||
AuthenticationScheme? scheme = await provider.GetSchemeAsync(
|
||||
DashboardAuthenticationDefaults.AuthenticationScheme);
|
||||
|
||||
Assert.NotNull(scheme);
|
||||
Assert.Equal(typeof(CookieAuthenticationHandler), scheme!.HandlerType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisableLoginOn_CookieSchemeUsesAutoLoginHandler()
|
||||
{
|
||||
await using WebApplication app = GatewayApplication.Build(
|
||||
["--MxGateway:Dashboard:DisableLogin=true"]);
|
||||
IAuthenticationSchemeProvider provider =
|
||||
app.Services.GetRequiredService<IAuthenticationSchemeProvider>();
|
||||
|
||||
AuthenticationScheme? scheme = await provider.GetSchemeAsync(
|
||||
DashboardAuthenticationDefaults.AuthenticationScheme);
|
||||
|
||||
Assert.NotNull(scheme);
|
||||
Assert.Equal(typeof(DashboardAutoLoginAuthenticationHandler), scheme!.HandlerType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisableLoginOn_AutoLoginPrincipalSatisfiesAdminAndViewerPolicies()
|
||||
{
|
||||
await using WebApplication app = GatewayApplication.Build(
|
||||
["--MxGateway:Dashboard:DisableLogin=true"]);
|
||||
IAuthorizationService authorization =
|
||||
app.Services.GetRequiredService<IAuthorizationService>();
|
||||
ClaimsPrincipal user = DashboardAutoLoginAuthenticationHandler.CreatePrincipal("multi-role");
|
||||
|
||||
Assert.True((await authorization.AuthorizeAsync(
|
||||
user, resource: null, DashboardAuthenticationDefaults.AdminPolicy)).Succeeded);
|
||||
Assert.True((await authorization.AuthorizeAsync(
|
||||
user, resource: null, DashboardAuthenticationDefaults.ViewerPolicy)).Succeeded);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> Note: `AuthorizeAsync` invokes the real `DashboardAuthorizationHandler` against the minted
|
||||
> principal — its role-check branch succeeds independent of `HttpContext` (loopback check
|
||||
> returns false with no request, and `Authentication.Mode` defaults to `ApiKey`), so this
|
||||
> proves the policies pass purely on the minted roles.
|
||||
|
||||
**Step 2: Run them, expect FAIL** (the `DisableLoginOn_*` tests fail — handler not yet wired; cookie handler still registered).
|
||||
|
||||
Run: `MSBUILDDISABLENODEREUSE=1 dotnet test src/ZB.MOM.WW.MxGateway.Tests/ZB.MOM.WW.MxGateway.Tests.csproj --filter "FullyQualifiedName~DashboardDisableLoginTests"`
|
||||
|
||||
**Step 3: Rewire `AddGatewayDashboard`.** In `DashboardServiceCollectionExtensions.cs`, replace the current authentication-builder block:
|
||||
|
||||
```csharp
|
||||
services
|
||||
.AddAuthentication(DashboardAuthenticationDefaults.AuthenticationScheme)
|
||||
.AddCookie(DashboardAuthenticationDefaults.AuthenticationScheme, cookieOptions =>
|
||||
{
|
||||
// ... existing cookie config ...
|
||||
})
|
||||
.AddScheme<AuthenticationSchemeOptions, HubTokenAuthenticationHandler>(
|
||||
DashboardAuthenticationDefaults.HubAuthenticationScheme,
|
||||
_ => { });
|
||||
```
|
||||
|
||||
with:
|
||||
|
||||
```csharp
|
||||
// DEV/TEST ONLY. Read directly from configuration here because authentication scheme
|
||||
// registration runs before options binding. Key mirrors DashboardOptions.DisableLogin.
|
||||
bool disableLogin = configuration.GetValue<bool>("MxGateway:Dashboard:DisableLogin");
|
||||
|
||||
AuthenticationBuilder authentication =
|
||||
services.AddAuthentication(DashboardAuthenticationDefaults.AuthenticationScheme);
|
||||
|
||||
if (disableLogin)
|
||||
{
|
||||
// Register an always-authenticating handler UNDER the cookie scheme name, so the
|
||||
// Viewer/Admin/HubClients policies (which all resolve this scheme) authenticate
|
||||
// through it as the multi-role dev user — zero policy or page changes.
|
||||
authentication.AddScheme<AuthenticationSchemeOptions, DashboardAutoLoginAuthenticationHandler>(
|
||||
DashboardAuthenticationDefaults.AuthenticationScheme,
|
||||
_ => { });
|
||||
|
||||
// Loud, once-at-startup warning (emitted when GatewayOptions is first resolved).
|
||||
services.AddOptions<GatewayOptions>().PostConfigure<ILoggerFactory>((gatewayOptions, loggerFactory) =>
|
||||
loggerFactory
|
||||
.CreateLogger("ZB.MOM.WW.MxGateway.Server.Dashboard.DisableLogin")
|
||||
.LogWarning(
|
||||
"DASHBOARD LOGIN DISABLED (MxGateway:Dashboard:DisableLogin=true) — every request is "
|
||||
+ "authenticated as '{User}' with full permissions ({Roles}). Dev/test only; never "
|
||||
+ "enable in production.",
|
||||
gatewayOptions.Dashboard.AutoLoginUser ?? DashboardAutoLoginAuthenticationHandler.DefaultUser,
|
||||
$"{DashboardRoles.Admin}, {DashboardRoles.Viewer}"));
|
||||
}
|
||||
else
|
||||
{
|
||||
authentication.AddCookie(DashboardAuthenticationDefaults.AuthenticationScheme, cookieOptions =>
|
||||
{
|
||||
// ... MOVE the existing cookie config body here unchanged ...
|
||||
});
|
||||
}
|
||||
|
||||
authentication.AddScheme<AuthenticationSchemeOptions, HubTokenAuthenticationHandler>(
|
||||
DashboardAuthenticationDefaults.HubAuthenticationScheme,
|
||||
_ => { });
|
||||
```
|
||||
|
||||
Notes for the implementer:
|
||||
- Keep the existing `services.AddOptions<CookieAuthenticationOptions>(scheme).Configure(...)` block (RequireHttpsCookie / cookie-name) as-is. When `disableLogin` is on it configures an options object no handler reads — harmless dead config; not worth guarding.
|
||||
- Required usings should already be present (`Microsoft.AspNetCore.Authentication`, `Microsoft.Extensions.Configuration`, `Microsoft.Extensions.Logging`, the `Configuration` namespace for `GatewayOptions`). Add any that are missing.
|
||||
- `configuration.GetValue<bool>` defaults to `false` when the key is absent — preserves default-off.
|
||||
|
||||
**Step 4: Run the tests, expect PASS** (all three).
|
||||
|
||||
**Step 5: Run the broader dashboard auth tests to confirm no regression:**
|
||||
|
||||
Run: `MSBUILDDISABLENODEREUSE=1 dotnet test src/ZB.MOM.WW.MxGateway.Tests/ZB.MOM.WW.MxGateway.Tests.csproj --filter "FullyQualifiedName~Dashboard"`
|
||||
Expected: all pass (existing `DashboardCookieOptionsTests`, `DashboardHubsRegistrationTests`, etc., still green — they build with the flag off).
|
||||
|
||||
> The startup warning is verified by inspection / manual run (`dotnet run … --MxGateway:Dashboard:DisableLogin=true` logs the warning once). It is not asserted automatically — capturing a startup log line would require injecting a log provider the `Build` harness does not expose, and the warning is a safety nicety, not core behavior.
|
||||
|
||||
**Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add src/ZB.MOM.WW.MxGateway.Server/Dashboard/DashboardServiceCollectionExtensions.cs src/ZB.MOM.WW.MxGateway.Tests/Gateway/Dashboard/DashboardDisableLoginTests.cs
|
||||
git commit -m "feat(dashboard): swap to auto-login handler when DisableLogin is set"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Documentation
|
||||
|
||||
**Classification:** small
|
||||
**Estimated implement time:** ~3 min
|
||||
**Parallelizable with:** Task 2 (disjoint files — docs vs src/test)
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/GatewayConfiguration.md`
|
||||
- Modify: `docs/GatewayDashboardDesign.md`
|
||||
- Modify: `CLAUDE.md`
|
||||
|
||||
**Step 1:** In `docs/GatewayConfiguration.md`, add `MxGateway:Dashboard:DisableLogin` (bool, default `false`) and `MxGateway:Dashboard:AutoLoginUser` (string, default `multi-role`) to the dashboard options section. Describe: dev/test only; auto-authenticates every request as `AutoLoginUser` with both roles; applies to all clients (not just loopback); never enable in production. Note it differs from `AllowAnonymousLocalhost` (which only bypasses authorization without minting a principal).
|
||||
|
||||
**Step 2:** In `docs/GatewayDashboardDesign.md`, document the auth-scheme swap: when the flag is on, the cookie handler is replaced by `DashboardAutoLoginAuthenticationHandler` under the same scheme name; explain *why* (every policy resolves that scheme, so no policy/page changes), and that it is dev/test only with a loud startup warning.
|
||||
|
||||
**Step 3:** In `CLAUDE.md`, in the Authentication section near the `Dashboard:AllowAnonymousLocalhost` sentence, add one sentence: `MxGateway:Dashboard:DisableLogin` (default off) auto-authenticates every dashboard request as `AutoLoginUser` (default `multi-role`) with all roles — dev/test only.
|
||||
|
||||
**Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add docs/GatewayConfiguration.md docs/GatewayDashboardDesign.md CLAUDE.md
|
||||
git commit -m "docs: document dashboard DisableLogin / AutoLoginUser dev flag"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Verification (after all tasks)
|
||||
|
||||
```bash
|
||||
MSBUILDDISABLENODEREUSE=1 dotnet test src/ZB.MOM.WW.MxGateway.Tests/ZB.MOM.WW.MxGateway.Tests.csproj \
|
||||
--filter "FullyQualifiedName~Dashboard|FullyQualifiedName~GatewayOptions"
|
||||
```
|
||||
|
||||
Expected: all dashboard + options tests pass. (Known macOS-only failures `OrphanWorkerTerminatorTests` ×2 and the parallel-load `SqliteAuthStoreTests` TLS temp-file test are unrelated and out of this filter.)
|
||||
|
||||
Then `superpowers-extended-cc:finishing-a-development-branch` to merge/push.
|
||||
@@ -0,0 +1,10 @@
|
||||
{
|
||||
"planPath": "docs/plans/2026-06-16-dashboard-disable-login.md",
|
||||
"tasks": [
|
||||
{"id": 136, "subject": "Task 1: Config fields on DashboardOptions", "status": "completed"},
|
||||
{"id": 137, "subject": "Task 2: DashboardAutoLoginAuthenticationHandler + unit tests", "status": "completed", "blockedBy": [136]},
|
||||
{"id": 138, "subject": "Task 3: Wire scheme swap + startup warning + wiring/authorization tests", "status": "completed", "blockedBy": [137]},
|
||||
{"id": 139, "subject": "Task 4: Documentation", "status": "completed", "blockedBy": [136]}
|
||||
],
|
||||
"lastUpdated": "2026-06-16"
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
# Saved Task List — Session Resilience Epic
|
||||
|
||||
> Snapshot taken 2026-06-16, before switching to the dashboard disable-login feature.
|
||||
> This is the in-flight epic from `docs/plans/2026-06-15-session-resilience.md`.
|
||||
|
||||
## How to resume
|
||||
|
||||
```
|
||||
/superpowers-extended-cc:executing-plans docs/plans/2026-06-15-session-resilience.md
|
||||
```
|
||||
|
||||
The authoritative resume state lives in
|
||||
`docs/plans/2026-06-15-session-resilience.md.tasks.json` (tasks 1–12 completed,
|
||||
13–28 pending). This file is just a human-readable mirror.
|
||||
|
||||
## Status
|
||||
|
||||
**12 of 28 tasks complete** (Phases 1–2 + reconnect core of Phase 3). All completed
|
||||
work is merged to `main` (commit `c446bef`, pushed to origin).
|
||||
|
||||
### Completed — Phase 1 (Foundation)
|
||||
- ✅ Task 1 (#108): Add OwnerKeyId to the session
|
||||
- ✅ Task 2 (#109): SessionEventDistributor skeleton
|
||||
- ✅ Task 3 (#110): Bounded replay ring buffer
|
||||
- ✅ Task 4 (#111): Rewire AttachEventSubscriber + EventStreamService onto distributor
|
||||
- ✅ Task 5 (#112): Per-subscriber backpressure isolation
|
||||
- ✅ Task 6 (#113): Dashboard broadcaster becomes a distributor subscriber
|
||||
|
||||
### Completed — Phase 2 (Multi-subscriber fan-out)
|
||||
- ✅ Task 7 (#114): Remove validator block + add subscriber cap option
|
||||
- ✅ Task 8 (#115): Subscriber-lease collection + cap enforcement
|
||||
- ✅ Task 9 (#116): Multi-subscriber end-to-end test (FakeWorkerHarness)
|
||||
|
||||
### Completed — Phase 3 (Reconnect core)
|
||||
- ✅ Task 10 (#117): Proto — ReplayGap signal
|
||||
- ✅ Task 11 (#118): Detach-grace session retention
|
||||
- ✅ Task 12 (#119): Replay-on-reconnect + emit ReplayGap
|
||||
|
||||
### Pending — Phase 3 finish
|
||||
- ⏳ Task 13 (#120): Owner re-validation on reconnect — blockedBy 12, 1
|
||||
- ⏳ Task 14 (#121): Client ReplayGap handling — all 5 clients — blockedBy 10
|
||||
- Carry the per-language presence-check idiom note for `optional` message fields.
|
||||
- ⏳ Task 15 (#122): Reconnect integration test (fake worker) — blockedBy 12
|
||||
|
||||
### Pending — Phase 4 (Per-session dashboard ACL)
|
||||
- ⏳ Task 16 (#123): gRPC session-owner gate + all-sessions admin scope — blockedBy 9, 1
|
||||
- ⏳ Task 17 (#124): Session Tag + dashboard group-to-tag config — blockedBy 9
|
||||
- ⏳ Task 18 (#125): EventsHub per-session ACL + hub-token tag claim — blockedBy 17
|
||||
- Open decision: Viewer default (admin-sees-all vs strict per-session).
|
||||
- ⏳ Task 19 (#126): ACL tests incl. live LDAP users — blockedBy 18
|
||||
|
||||
### Pending — Phase 5 (Orphan-worker reattach)
|
||||
- ⏳ Task 20 (#127): Stable gateway-instance id + stable pipe naming — blockedBy 19
|
||||
- ⏳ Task 21 (#128): Adoption manifest store (SQLite) — blockedBy 20
|
||||
- ⏳ Task 22 (#129): Proto — worker adopt/reconnect frame — blockedBy 21
|
||||
- ⏳ Task 23 (#130): Worker phone-home reconnect loop + self-terminate — blockedBy 22 (net48/x86, windev)
|
||||
- ⏳ Task 24 (#131): Gateway adoption — re-open pipes, nonce-validate, reject impostors — blockedBy 23
|
||||
- ⏳ Task 25 (#132): Resync adopted worker + ReplayGap to subscribers — blockedBy 24, 12
|
||||
- ⏳ Task 26 (#133): EnableOrphanReattach flag (default off) + terminator fallback — blockedBy 24
|
||||
- ⏳ Task 27 (#134): Gateway-restart reattach round-trip (WINDEV + live worker) — blockedBy 25, 26
|
||||
- ⏳ Task 28 (#135): Documented-rule reversals + stillpending refresh — blockedBy 27
|
||||
|
||||
## Notes
|
||||
- Phase 5 reverses the documented "Gateway restart does not reattach orphan workers"
|
||||
rule (CLAUDE.md) — this was explicitly approved during design.
|
||||
- Two deferred follow-ups noted earlier: dashboard visibility of `DetachedAtUtc` on
|
||||
`DashboardSessionSummary`.
|
||||
- Worker (net48/x86) tasks build/test on windev; everything else builds on macOS.
|
||||
@@ -8,6 +8,23 @@ public sealed class DashboardOptions
|
||||
/// <summary>Gets whether anonymous localhost access to dashboard is allowed.</summary>
|
||||
public bool AllowAnonymousLocalhost { get; init; } = true;
|
||||
|
||||
/// <summary>
|
||||
/// DEV/TEST ONLY. When true, the dashboard bypasses the login form entirely and
|
||||
/// auto-authenticates EVERY request as <see cref="AutoLoginUser"/> holding both
|
||||
/// dashboard roles (Administrator + Viewer). No cookie, no LDAP bind. Default false.
|
||||
/// Unlike <see cref="AllowAnonymousLocalhost"/> (which only succeeds the authorization
|
||||
/// requirement without authenticating), this mints a real principal, so the UI behaves
|
||||
/// as a signed-in admin and applies to all clients (not just loopback). Never enable in
|
||||
/// production. See docs/plans/2026-06-16-dashboard-disable-login-design.md.
|
||||
/// </summary>
|
||||
public bool DisableLogin { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// Username minted for the auto-login principal when <see cref="DisableLogin"/> is true.
|
||||
/// Null/blank falls back to the GLAuth Administrator test user <c>multi-role</c>.
|
||||
/// </summary>
|
||||
public string? AutoLoginUser { get; init; }
|
||||
|
||||
/// <summary>
|
||||
/// When true (default), the dashboard auth cookie is restricted to HTTPS
|
||||
/// requests via <see cref="Microsoft.AspNetCore.Http.CookieSecurePolicy.Always"/>.
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
using System.Security.Claims;
|
||||
using System.Text.Encodings.Web;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Auth.AspNetCore;
|
||||
using ZB.MOM.WW.MxGateway.Server.Configuration;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||
|
||||
/// <summary>
|
||||
/// Authentication handler used ONLY when <c>MxGateway:Dashboard:DisableLogin</c> is true.
|
||||
/// Registered under the dashboard cookie scheme name
|
||||
/// (<see cref="DashboardAuthenticationDefaults.AuthenticationScheme"/>), it authenticates
|
||||
/// EVERY request as the configured dev user with both dashboard roles — no credential check,
|
||||
/// no cookie, no LDAP bind. The minted principal mirrors the shape the real login
|
||||
/// (<see cref="DashboardAuthenticator"/>) produces, so policies and the UI cannot tell it
|
||||
/// apart. DEV/TEST ONLY; never enable in production.
|
||||
/// </summary>
|
||||
public sealed class DashboardAutoLoginAuthenticationHandler
|
||||
: AuthenticationHandler<AuthenticationSchemeOptions>, IAuthenticationSignInHandler
|
||||
{
|
||||
/// <summary>Username used when <c>AutoLoginUser</c> is null or blank.</summary>
|
||||
public const string DefaultUser = "multi-role";
|
||||
|
||||
private readonly string _user;
|
||||
|
||||
/// <summary>Initializes the handler with scheme plumbing and the dashboard options.</summary>
|
||||
/// <param name="options">The per-scheme authentication options monitor.</param>
|
||||
/// <param name="logger">The logger factory the base handler uses.</param>
|
||||
/// <param name="encoder">The URL encoder the base handler uses.</param>
|
||||
/// <param name="gatewayOptions">Gateway options carrying the dashboard auto-login user.</param>
|
||||
public DashboardAutoLoginAuthenticationHandler(
|
||||
IOptionsMonitor<AuthenticationSchemeOptions> options,
|
||||
ILoggerFactory logger,
|
||||
UrlEncoder encoder,
|
||||
IOptions<GatewayOptions> gatewayOptions)
|
||||
: base(options, logger, encoder)
|
||||
{
|
||||
string? configured = gatewayOptions.Value.Dashboard.AutoLoginUser;
|
||||
_user = string.IsNullOrWhiteSpace(configured) ? DefaultUser : configured.Trim();
|
||||
}
|
||||
|
||||
/// <summary>No-op: auto-login writes no cookie, so a sign-in has nothing to persist.</summary>
|
||||
/// <param name="user">Ignored.</param>
|
||||
/// <param name="properties">Ignored.</param>
|
||||
/// <returns>A completed task.</returns>
|
||||
public Task SignInAsync(ClaimsPrincipal user, AuthenticationProperties? properties) => Task.CompletedTask;
|
||||
|
||||
/// <summary>No-op: there is no auth cookie to clear; the next request re-authenticates.</summary>
|
||||
/// <param name="properties">Ignored.</param>
|
||||
/// <returns>A completed task.</returns>
|
||||
public Task SignOutAsync(AuthenticationProperties? properties) => Task.CompletedTask;
|
||||
|
||||
/// <inheritdoc />
|
||||
protected override Task<AuthenticateResult> HandleAuthenticateAsync()
|
||||
{
|
||||
ClaimsPrincipal principal = CreatePrincipal(_user);
|
||||
AuthenticationTicket ticket = new(principal, Scheme.Name);
|
||||
|
||||
return Task.FromResult(AuthenticateResult.Success(ticket));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Builds the multi-role dev principal. Null/blank <paramref name="user"/> falls back to
|
||||
/// <see cref="DefaultUser"/>. The authorization-relevant claim shape mirrors
|
||||
/// <see cref="DashboardAuthenticator"/>; LDAP group claims (<c>LdapGroupClaimType</c>) are
|
||||
/// intentionally omitted because auto-login has no real LDAP context.
|
||||
/// </summary>
|
||||
/// <param name="user">The configured auto-login username (may be null/blank).</param>
|
||||
/// <returns>An authenticated principal holding both dashboard roles.</returns>
|
||||
internal static ClaimsPrincipal CreatePrincipal(string? user)
|
||||
{
|
||||
string name = string.IsNullOrWhiteSpace(user) ? DefaultUser : user.Trim();
|
||||
|
||||
// LdapGroupClaimType claims are omitted — no LDAP groups exist in the auto-login context.
|
||||
Claim[] claims =
|
||||
[
|
||||
new Claim(ClaimTypes.NameIdentifier, name),
|
||||
new Claim(ZbClaimTypes.Username, name),
|
||||
new Claim(ZbClaimTypes.Name, name),
|
||||
new Claim(ZbClaimTypes.DisplayName, name),
|
||||
new Claim(ZbClaimTypes.Role, DashboardRoles.Admin),
|
||||
new Claim(ZbClaimTypes.Role, DashboardRoles.Viewer),
|
||||
];
|
||||
|
||||
ClaimsIdentity identity = new(
|
||||
claims,
|
||||
DashboardAuthenticationDefaults.AuthenticationScheme,
|
||||
ZbClaimTypes.Name,
|
||||
ZbClaimTypes.Role);
|
||||
|
||||
return new ClaimsPrincipal(identity);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.Extensions.Configuration;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Microsoft.Extensions.Options;
|
||||
using ZB.MOM.WW.Auth.Abstractions.Roles;
|
||||
using ZB.MOM.WW.Auth.AspNetCore;
|
||||
@@ -21,7 +22,8 @@ public static class DashboardServiceCollectionExtensions
|
||||
/// <param name="services">Service collection to register services.</param>
|
||||
/// <param name="configuration">
|
||||
/// Application configuration, used to bind the shared LDAP provider's options
|
||||
/// from the <c>MxGateway:Ldap</c> section.
|
||||
/// from the <c>MxGateway:Ldap</c> section. Also read to select the dashboard
|
||||
/// authentication scheme via the <c>MxGateway:Dashboard:DisableLogin</c> dev flag.
|
||||
/// </param>
|
||||
public static IServiceCollection AddGatewayDashboard(
|
||||
this IServiceCollection services,
|
||||
@@ -55,9 +57,39 @@ public static class DashboardServiceCollectionExtensions
|
||||
.AddInteractiveServerComponents();
|
||||
services.AddSignalR();
|
||||
|
||||
services
|
||||
.AddAuthentication(DashboardAuthenticationDefaults.AuthenticationScheme)
|
||||
.AddCookie(DashboardAuthenticationDefaults.AuthenticationScheme, cookieOptions =>
|
||||
// DEV/TEST ONLY. Read directly from configuration here because authentication scheme
|
||||
// registration runs before options binding. Key mirrors DashboardOptions.DisableLogin.
|
||||
bool disableLogin = configuration.GetValue<bool>("MxGateway:Dashboard:DisableLogin");
|
||||
|
||||
AuthenticationBuilder authentication =
|
||||
services.AddAuthentication(DashboardAuthenticationDefaults.AuthenticationScheme);
|
||||
|
||||
if (disableLogin)
|
||||
{
|
||||
// Register an always-authenticating handler UNDER the cookie scheme name, so the
|
||||
// Viewer/Admin/HubClients policies (which all resolve this scheme) authenticate
|
||||
// through it as the multi-role dev user — zero policy or page changes.
|
||||
authentication.AddScheme<AuthenticationSchemeOptions, DashboardAutoLoginAuthenticationHandler>(
|
||||
DashboardAuthenticationDefaults.AuthenticationScheme,
|
||||
_ => { });
|
||||
|
||||
// Loud warning, emitted on first resolution of GatewayOptions (i.e. on the first
|
||||
// request/options access, not guaranteed at process start). Dev-only safety notice.
|
||||
services.AddOptions<GatewayOptions>().PostConfigure<ILoggerFactory>((gatewayOptions, loggerFactory) =>
|
||||
loggerFactory
|
||||
.CreateLogger("ZB.MOM.WW.MxGateway.Server.Dashboard.DisableLogin")
|
||||
.LogWarning(
|
||||
"DASHBOARD LOGIN DISABLED (MxGateway:Dashboard:DisableLogin=true) — every request is "
|
||||
+ "authenticated as '{User}' with full permissions ({Roles}). Dev/test only; never "
|
||||
+ "enable in production.",
|
||||
string.IsNullOrWhiteSpace(gatewayOptions.Dashboard.AutoLoginUser)
|
||||
? DashboardAutoLoginAuthenticationHandler.DefaultUser
|
||||
: gatewayOptions.Dashboard.AutoLoginUser!.Trim(),
|
||||
$"{DashboardRoles.Admin}, {DashboardRoles.Viewer}"));
|
||||
}
|
||||
else
|
||||
{
|
||||
authentication.AddCookie(DashboardAuthenticationDefaults.AuthenticationScheme, cookieOptions =>
|
||||
{
|
||||
// Hardened defaults (HttpOnly, SameSite=Strict, SecurePolicy, SlidingExpiration,
|
||||
// ExpireTimeSpan) via the shared ZbCookieDefaults.Apply. requireHttps is set to
|
||||
@@ -73,10 +105,12 @@ public static class DashboardServiceCollectionExtensions
|
||||
cookieOptions.LoginPath = "/login";
|
||||
cookieOptions.LogoutPath = "/logout";
|
||||
cookieOptions.AccessDeniedPath = "/denied";
|
||||
})
|
||||
.AddScheme<AuthenticationSchemeOptions, HubTokenAuthenticationHandler>(
|
||||
DashboardAuthenticationDefaults.HubAuthenticationScheme,
|
||||
_ => { });
|
||||
});
|
||||
}
|
||||
|
||||
authentication.AddScheme<AuthenticationSchemeOptions, HubTokenAuthenticationHandler>(
|
||||
DashboardAuthenticationDefaults.HubAuthenticationScheme,
|
||||
_ => { });
|
||||
|
||||
// Honour DashboardOptions.RequireHttpsCookie (default true / Always; set false for dev
|
||||
// HTTP deployments → SameAsRequest) and the optional per-environment cookie-name
|
||||
|
||||
@@ -121,6 +121,18 @@ public sealed class GatewayOptionsTests
|
||||
StringComparison.Ordinal);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DashboardOptions_DisableLogin_DefaultsToFalse()
|
||||
{
|
||||
Assert.False(new DashboardOptions().DisableLogin);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void DashboardOptions_AutoLoginUser_DefaultsToNull()
|
||||
{
|
||||
Assert.Null(new DashboardOptions().AutoLoginUser);
|
||||
}
|
||||
|
||||
private static GatewayOptions BindOptions(IReadOnlyDictionary<string, string?> configurationValues)
|
||||
{
|
||||
using ServiceProvider services = BuildServices(configurationValues);
|
||||
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
using System.Security.Claims;
|
||||
using ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Dashboard;
|
||||
|
||||
public sealed class DashboardAutoLoginAuthenticationHandlerTests
|
||||
{
|
||||
[Fact]
|
||||
public void CreatePrincipal_MintsAuthenticatedMultiRoleUser()
|
||||
{
|
||||
ClaimsPrincipal principal = DashboardAutoLoginAuthenticationHandler.CreatePrincipal("multi-role");
|
||||
|
||||
Assert.True(principal.Identity!.IsAuthenticated);
|
||||
Assert.Equal("multi-role", principal.Identity!.Name);
|
||||
Assert.True(principal.IsInRole(DashboardRoles.Admin));
|
||||
Assert.True(principal.IsInRole(DashboardRoles.Viewer));
|
||||
}
|
||||
|
||||
[Theory]
|
||||
[InlineData(null)]
|
||||
[InlineData("")]
|
||||
[InlineData(" ")]
|
||||
public void CreatePrincipal_BlankUser_FallsBackToDefault(string? user)
|
||||
{
|
||||
ClaimsPrincipal principal = DashboardAutoLoginAuthenticationHandler.CreatePrincipal(user);
|
||||
|
||||
Assert.Equal(DashboardAutoLoginAuthenticationHandler.DefaultUser, principal.Identity!.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreatePrincipal_TrimsUser()
|
||||
{
|
||||
ClaimsPrincipal principal = DashboardAutoLoginAuthenticationHandler.CreatePrincipal(" multi-role ");
|
||||
|
||||
Assert.Equal("multi-role", principal.Identity!.Name);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void CreatePrincipal_CustomUser_PreservesNameAndRoles()
|
||||
{
|
||||
ClaimsPrincipal principal = DashboardAutoLoginAuthenticationHandler.CreatePrincipal("gw-viewer");
|
||||
|
||||
Assert.Equal("gw-viewer", principal.Identity!.Name);
|
||||
Assert.True(principal.IsInRole(DashboardRoles.Admin));
|
||||
Assert.True(principal.IsInRole(DashboardRoles.Viewer));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
using System.Security.Claims;
|
||||
using Microsoft.AspNetCore.Authentication;
|
||||
using Microsoft.AspNetCore.Authentication.Cookies;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Builder;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using ZB.MOM.WW.MxGateway.Server;
|
||||
using ZB.MOM.WW.MxGateway.Server.Dashboard;
|
||||
|
||||
namespace ZB.MOM.WW.MxGateway.Tests.Gateway.Dashboard;
|
||||
|
||||
public sealed class DashboardDisableLoginTests
|
||||
{
|
||||
[Fact]
|
||||
public async Task DisableLoginOff_CookieSchemeUsesCookieHandler()
|
||||
{
|
||||
await using WebApplication app = GatewayApplication.Build([]);
|
||||
IAuthenticationSchemeProvider provider =
|
||||
app.Services.GetRequiredService<IAuthenticationSchemeProvider>();
|
||||
|
||||
AuthenticationScheme? scheme = await provider.GetSchemeAsync(
|
||||
DashboardAuthenticationDefaults.AuthenticationScheme);
|
||||
|
||||
Assert.NotNull(scheme);
|
||||
Assert.Equal(typeof(CookieAuthenticationHandler), scheme!.HandlerType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisableLoginOn_CookieSchemeUsesAutoLoginHandler()
|
||||
{
|
||||
await using WebApplication app = GatewayApplication.Build(
|
||||
["--MxGateway:Dashboard:DisableLogin=true"]);
|
||||
IAuthenticationSchemeProvider provider =
|
||||
app.Services.GetRequiredService<IAuthenticationSchemeProvider>();
|
||||
|
||||
AuthenticationScheme? scheme = await provider.GetSchemeAsync(
|
||||
DashboardAuthenticationDefaults.AuthenticationScheme);
|
||||
|
||||
Assert.NotNull(scheme);
|
||||
Assert.Equal(typeof(DashboardAutoLoginAuthenticationHandler), scheme!.HandlerType);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task DisableLoginOn_AutoLoginPrincipalSatisfiesAdminAndViewerPolicies()
|
||||
{
|
||||
await using WebApplication app = GatewayApplication.Build(
|
||||
["--MxGateway:Dashboard:DisableLogin=true"]);
|
||||
IAuthorizationService authorization =
|
||||
app.Services.GetRequiredService<IAuthorizationService>();
|
||||
ClaimsPrincipal user = DashboardAutoLoginAuthenticationHandler.CreatePrincipal("multi-role");
|
||||
|
||||
Assert.True((await authorization.AuthorizeAsync(
|
||||
user, resource: null, DashboardAuthenticationDefaults.AdminPolicy)).Succeeded);
|
||||
Assert.True((await authorization.AuthorizeAsync(
|
||||
user, resource: null, DashboardAuthenticationDefaults.ViewerPolicy)).Succeeded);
|
||||
Assert.True((await authorization.AuthorizeAsync(
|
||||
user, resource: null, DashboardAuthenticationDefaults.HubClientsPolicy)).Succeeded);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user