From 2d8d5a3d6fcda1580e5668544af3f313531bfc2f Mon Sep 17 00:00:00 2001 From: Joseph Doherty Date: Tue, 17 Nov 2026 11:21:00 -0500 Subject: [PATCH] fix(auth): end a cookie session whose roles drop to zero on refresh (#144) The mid-session refresh ended a session only when the directory returned no groups (or the user was gone/disabled/ambiguous). A user still in some groups but in no mapped one, or whose DB mappings were all revoked, kept a signed-in, role-less session that could read the bare-[Authorize] pages. CookieSessionValidator now rejects when the re-map yields zero roles, on ordinary and fail-closed paths. A mapper fault keeps its existing policy (keep grants; fail closed when asked). Docs: Component-Security "No role, no login" (incl. the HTTP Basic gap left as a follow-up), Component-CentralUI, CLAUDE.md. Claude-Session: https://claude.ai/code/session_01GT67AFKC45MBz1wPZnVbX8 --- CLAUDE.md | 1 + docs/requirements/Component-CentralUI.md | 1 + docs/requirements/Component-Security.md | 19 +++++-- .../CookieSessionValidator.cs | 19 ++++++- .../ServiceCollectionExtensions.cs | 2 +- .../CookieSessionValidatorTests.cs | 50 ++++++++++++++++--- .../DirectoryGroupRefreshTests.cs | 41 ++++++++++++++- 7 files changed, 119 insertions(+), 14 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index b46485c6..a20a6c3d 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -195,6 +195,7 @@ spec for each is `docs/requirements/Component-.md`, and `README.md` carrie - Authentication: direct LDAP bind (username/password), no Kerberos/NTLM. LDAPS/StartTLS required. - Two session models: the **UI** uses an HttpOnly/Secure cookie carrying a data-protected claims ticket (no embedded JWT; shared Data Protection keys; 30-minute idle timeout, DB-only role re-map every 15 min); the **CLI/API** exchanges credentials once per invocation at `POST /auth/token` for a 15-minute HS256 **bearer** JWT (`JwtSigningKey`, >= 32 bytes, shared by both centrals; `management_bearer: true` capability flag; Basic stays as fallback). Bearer roles are authoritative until expiry (revocation lag <= `JwtExpiryMinutes`; rotating the key kills every token). Cookies are the correct transport for Blazor Server (SignalR circuits). Spec: `Component-Security.md`. - LDAP failure: new logins fail; active sessions continue with current roles. +- **No role, no login (ScadaBridge#144, 2026-11-17).** `/auth/login` and `/auth/token` refuse a bind whose groups map to zero roles (or whose role mapping throws) with the exact bad-password response + a throttle failure; the reason is logged server-side only. A cookie session whose refresh maps to zero roles is ended (`CookieSessionValidator` → Reject). HTTP Basic on the management surfaces is not covered yet (follow-up). Spec: `Component-Security.md` *No role, no login*. - Load balancer in front of central UI; cookie-embedded JWT + shared Data Protection keys for failover transparency. - Two-person MxGateway secured writes (M7): two new global roles — `Operator` (initiates) + `Verifier` (approves) — added alongside the canonical `Administrator`/`Designer`/`Deployer`/`Viewer`, with `RequireOperator`/`RequireVerifier` policies. An Operator submits a secured write from the Central UI Secured Writes page (`/operations/secured-writes`); it stays a `Pending` `PendingSecuredWrite` row until a *distinct* Verifier approves it (no-self-approval enforced server-side in the ManagementActor, plus a compare-and-swap race guard). Approval relays a `WriteTagRequest` to the site MxGateway; MxGateway-protocol connections only; each lifecycle event (submit/approve/reject/execute) emits a best-effort `AuditChannel.SecuredWrite` / `AuditKind.SecuredWrite*` central-direct-write row sharing the row id as `CorrelationId`. (SecuredWrite audit rows stamp `SourceNode` via `ICentralAuditWriter`/`INodeIdentityProvider`.) Pending secured writes expire server-side after a configurable TTL (`ManagementServiceOptions.SecuredWritePendingTtl`, default 24 h): an overdue `Pending` row is CAS'd to `Expired` (never relayed) — enforced at approve/reject and swept opportunistically on list (arch-review S2, `AuditKind.SecuredWriteExpire`). - **Inbound API key store — per node by default, shared on central pairs (2026-09-02, register row 108).** The shared `ZB.MOM.WW.Auth.ApiKeys` library stores inbound keys in **SQLite per node** unless `ScadaBridge:InboundApi:ApiKeyStore:Provider=SqlServer`, which points both central nodes at the same `zbauth` schema in the configuration database (library `ZB.MOM.WW.Auth.ApiKeys.SqlServer` 0.3.0) — under `SqlServer`, create/revoke/rotate/scope changes are cluster-wide immediately; a node's existing SQLite file is imported once at boot (insert-where-absent, safe on both nodes of a pair) and renamed `*.imported`. Central pairs **MUST** run `Provider=SqlServer` — a clustered Central left on `Sqlite` boots fine but `StartupValidator` logs a Warning, because a failover otherwise 401s every inbound client until keys are re-issued on the survivor. Both docker rigs (`docker/`, `docker-env2/`) run `SqlServer`; QA (`vq03`/`vq04`) runs `SqlServer` for both inbound keys and secrets since 2026-10-22 (deployment record `2026-10-22-wonder-app-vq03-vq04-3808b49f.md`); DEV (`vd03`, single node — not production) is not switched. The boot import's `*.imported` rename needs the importer's pooled SQLite handle released first — Windows refuses to rename an open file (fixed `6ed6800b`; pre-fix Windows builds need the manual rename in the runbook). Design: `docs/plans/2026-09-02-inbound-api-key-shared-store-design.md`; runbook: `docs/operations/inbound-api-key-reissue.md` → *Central pairs*. diff --git a/docs/requirements/Component-CentralUI.md b/docs/requirements/Component-CentralUI.md index b7f8274b..9f9cdcd4 100644 --- a/docs/requirements/Component-CentralUI.md +++ b/docs/requirements/Component-CentralUI.md @@ -25,6 +25,7 @@ Central cluster only. Sites have no user interface. ## Review hardening (2026-09-09) - Cookie login validates an antiforgery token before reading credentials or calling LDAP; the login form supplies the token. The JSON token endpoint retains its non-cookie client contract. +- Cookie login and the token endpoint refuse a bind whose groups map to no role, or whose role mapping fails, exactly as for a bad password (ScadaBridge#144; see `Component-Security.md` *No role, no login*). This is what makes the two bare-`[Authorize]` pages (`/`, `/monitoring/health`) safe. - Manual failover goes through a scoped `AuthorizedManualFailoverService` that refreshes the circuit's Administrator grant before calling the host singleton. The component's visibility policy is an additional presentation guard. - Flow Debugger method-entry Live runs are unavailable to a site-scoped Deployer (Gitea #55): the *Inbound API method* entry is disabled with the reason as a tooltip and an inline note, the page starts on script entry, a `?methodId=` drill-in or a stored method choice is ignored, and the server refuses the command regardless. Script entry on a permitted instance and Replay stay available. - Flow Debugger retry/discard validates the current Deployer grant and resolves site scope inside its service. Scoped callers cannot relay an unknown site. Refresh merges preserve Replay's event ordering and append only rows known exclusively to the live run. diff --git a/docs/requirements/Component-Security.md b/docs/requirements/Component-Security.md index e7623150..b4513096 100644 --- a/docs/requirements/Component-Security.md +++ b/docs/requirements/Component-Security.md @@ -32,6 +32,17 @@ Central cluster. Sites do not have user-facing interfaces and do not perform ind Set in a local or docker-dev environment via the environment variable `ScadaBridge__Security__Auth__DisableLogin=true`. Note that `ScadaBridge:Security:Auth` is a child sub-section nested inside `ScadaBridge:Security`. +## No role, no login (ScadaBridge#144) + +A successful LDAP bind is **not** enough to sign in: the user's groups must map to **at least one** ScadaBridge role. This is the family standard (scadaproj NAM AD cutover plan §3.2), and it matters once the LDAP search base is domain-wide — without it, any directory user could sign in role-less and read the bare-`[Authorize]` pages (`/` and `/monitoring/health`). + +- **Both sign-in endpoints refuse.** `POST /auth/login` and `POST /auth/token` refuse a bind whose groups map to **zero roles**, and a bind whose **role mapping throws** (e.g. the configuration database is unreachable). +- **Indistinguishable from a bad password.** The client gets exactly the bad-credentials response — `/auth/login` redirects to `/login?error=Invalid username or password.` with no session cookie; `/auth/token` answers `401` `{ error: "Invalid username or password.", code: "AUTH_FAILED" }` with no token. The refusal also **counts as a login-throttle failure**, so the throttle cannot be used to tell "right password, no role" from "wrong password". +- **Logged server-side only.** Each refusal is logged at Warning (category `ZB.MOM.WW.ScadaBridge.CentralUI.Auth.AuthEndpoints`) with the endpoint, the username and the reason (no mapped role, with the group count; or the mapping exception). There is no login audit event in the Audit Log — sign-in success and failure are not audited today — so the log line is the record. +- **Sessions end the same way.** A cookie session whose groups map to zero roles on a refresh is ended (see *Cookie session lifecycle*). +- **HTTP Basic is not covered yet.** `ManagementAuthenticator`'s Basic branch (`POST /management`, the audit REST endpoints, the debug-stream hub) still authenticates a zero-role bind. Role-gated commands deny it, but the read-only management queries that `ManagementActor.GetRequiredRoles` opens to *any authenticated user* answer it. Closing that is a follow-up to ScadaBridge#144. +- Under the dev/test `DisableLogin` flag none of this runs: the auto-login identity holds every role. + ## Session Management ### Interactive sessions — cookie claims ticket @@ -41,7 +52,7 @@ Set in a local or docker-dev environment via the environment variable `ScadaBrid - Both central nodes share the ASP.NET Data Protection key ring, so either node can read a cookie the other issued. ### CLI / API sessions — bearer JWT (`POST /auth/token`) -- `POST /auth/token` (form `username`/`password`) performs the LDAP bind (login-throttled), maps the groups to roles and site scope, and returns a short-lived **HS256 JWT** signed with `SecurityOptions.JwtSigningKey`, shared by both central nodes: `{ access_token, token_type: "Bearer", expires_in, management_bearer: true, username, display_name, roles }`. +- `POST /auth/token` (form `username`/`password`) performs the LDAP bind (login-throttled), maps the groups to roles and site scope (zero roles, or a mapping fault, is refused as a bad password — *No role, no login* above), and returns a short-lived **HS256 JWT** signed with `SecurityOptions.JwtSigningKey`, shared by both central nodes: `{ access_token, token_type: "Bearer", expires_in, management_bearer: true, username, display_name, roles }`. - **JWT claims**: display name, username, roles, and for a site-scoped Deployer the permitted site IDs (no site claims = system-wide, the same normalisation the Basic path uses). Issuer and audience are both fixed to `scadabridge-central`. Lifetime is `JwtExpiryMinutes` (default **15**). - `ManagementAuthenticator` accepts `Authorization: Bearer ` alongside HTTP Basic on every CLI-facing surface: `POST /management`, the audit REST endpoints, and the debug-stream hub (`/hubs/debug-stream`, token in the `Authorization` header of the negotiate request and WebSocket upgrade). Validation checks the HS256 signature, issuer, audience and lifetime (30 s clock skew for node-to-node drift; `nbf` is back-dated by the same skew so a peer whose clock lags the issuer accepts a fresh token after failover); unsigned (`alg=none`) or other-algorithm tokens are rejected, and a failure is a plain `401 AUTH_FAILED` (no LDAP bind, so it does not feed the login throttle). The token is never logged. - **Roles and scope inside a valid token are authoritative for its lifetime**: a bearer request performs no LDAP bind and no role re-map. A role revocation therefore reaches a bearer caller when its token expires (≤ `JwtExpiryMinutes`); rotating `JwtSigningKey` invalidates every outstanding token immediately. @@ -52,15 +63,15 @@ Set in a local or docker-dev environment via the environment variable `ScadaBrid ### Cookie session lifecycle - **Idle timeout**: Configurable, default **30 minutes**. Without eligible activity within the idle window, the session is rejected and the user must re-login. Passive `/auth/ping`, activity prevalidation, and Blazor transport requests preserve the activity anchor and suppress sliding renewal; the activity endpoint renews only after authentication and antiforgery validation. Tracked via a `LastActivity` last-activity timestamp claim. The cookie's `ExpireTimeSpan` is set to the idle timeout and `SlidingExpiration` renews it on activity, so the cookie window and the explicit `OnValidatePrincipal` idle check use the **same** value and cannot contradict each other. -- **Role-mapping refresh (DB)**: Configurable, default **15 minutes** (`SecurityOptions.RoleRefreshThresholdMinutes`). At login the session stores the user's raw LDAP groups (one `zb:group` claim each) plus a `zb:lastrolerefresh` anchor. Once the anchor is older than the threshold, `OnValidatePrincipal` re-runs the **DB-backed** `RoleMapper` on the session's groups (the stored ones, or the ones just re-read from the directory — see the next item), rebuilds the role/scope claims via the shared claim-builder, advances the anchor, and re-issues the cookie. Central role-mapping (DB) changes — including a **revoked** mapping that drops the user's roles, and changed site-scope rules — take effect within this window. Ordinary HTTP validation uses this threshold. A live circuit refreshes mappings in fresh scopes on authentication-state reads — display reads (`GetAuthenticationStateAsync`) at most once per `CookieAuthenticationStateProvider.NonAuthoritativeRefreshInterval` (10 s) per circuit — and mutation entrypoints (`GetAuthoritativeStateAsync`) require a successful current mapping before every dispatch. +- **Role-mapping refresh (DB)**: Configurable, default **15 minutes** (`SecurityOptions.RoleRefreshThresholdMinutes`). At login the session stores the user's raw LDAP groups (one `zb:group` claim each) plus a `zb:lastrolerefresh` anchor. Once the anchor is older than the threshold, `OnValidatePrincipal` re-runs the **DB-backed** `RoleMapper` on the session's groups (the stored ones, or the ones just re-read from the directory — see the next item), rebuilds the role/scope claims via the shared claim-builder, advances the anchor, and re-issues the cookie. Central role-mapping (DB) changes — including a **revoked** mapping that drops some of the user's roles, and changed site-scope rules — take effect within this window. A refresh under which the user's groups map to **no role at all** ends the session (HTTP rejects the principal and clears the cookie; a circuit's state becomes anonymous), on ordinary and fail-closed validation alike, because a new login would be refused (ScadaBridge#144). A mapping **fault** is not this case: it keeps the current grants on ordinary validation and fails closed on authoritative checks (see *Session Validation*). Ordinary HTTP validation uses this threshold. A live circuit refreshes mappings in fresh scopes on authentication-state reads — display reads (`GetAuthenticationStateAsync`) at most once per `CookieAuthenticationStateProvider.NonAuthoritativeRefreshInterval` (10 s) per circuit — and mutation entrypoints (`GetAuthoritativeStateAsync`) require a successful current mapping before every dispatch. - **Directory group re-query (ScadaBridge#46)**: Configurable, default **on, every 15 minutes** (`SecurityOptions.LdapGroupRefresh`: `Enabled` = `true`, `IntervalMinutes` = `15`, `CacheSeconds` = `60`; config `ScadaBridge:Security:LdapGroupRefresh:*`). Login also stamps a `zb:lastgrouprefresh` anchor. Once it is older than `IntervalMinutes`, the next validation — HTTP `OnValidatePrincipal`, a circuit display read or an authoritative mutation check — re-reads the user's groups from the directory through the shared library's passwordless `ILdapGroupLookup` (Auth `0.5.0`; it binds as the configured **service account**, never the user), replaces the stored `zb:group` claims, re-runs the role mapping, and advances the anchor. A directory group removal or addition therefore reaches an open session — browser and circuit — within the interval, without re-login. Its cadence is independent of `RoleRefreshThresholdMinutes` and of the 10 s circuit refresh: a circuit queries the directory at most once per interval. One user's answer is reused on a node for `CacheSeconds`, so the cookie path and every circuit of that user cost one directory query. A cookie issued before this feature (no anchor) is due on its first validation. - - **Outcome policy.** *Directory unavailable* (connect/TLS, service-account bind or search failed on every endpoint, including `FallbackServers`) **keeps the stored groups and roles** and logs a warning — on every path, including the fail-closed authoritative check — and the anchor still advances, so an outage costs one attempt per interval rather than one per request (availability first, consistent with *LDAP Connection Failure* below). Any answer under which a **new login would now be refused for a user-side reason** — account **not found** (deleted/renamed), **disabled** (AD `userAccountControl`), **ambiguous** (two entries), or found with **no groups** — **ends the session** on every path: HTTP rejects the principal and clears the cookie (the user lands on `/login`), and a circuit's state becomes anonymous so the next gate denies. Ending the session (rather than leaving a signed-in, role-less session) is chosen because it is what the login path would decide and it cannot be mistaken for a working account. *Not supported* (LDAP configured with `BindMode = User`, i.e. no service account) or LDAP disabled keeps the stored groups; the feature is then inert and logs that once. + - **Outcome policy.** *Directory unavailable* (connect/TLS, service-account bind or search failed on every endpoint, including `FallbackServers`) **keeps the stored groups and roles** and logs a warning — on every path, including the fail-closed authoritative check — and the anchor still advances, so an outage costs one attempt per interval rather than one per request (availability first, consistent with *LDAP Connection Failure* below). Any answer under which a **new login would now be refused for a user-side reason** — account **not found** (deleted/renamed), **disabled** (AD `userAccountControl`), **ambiguous** (two entries), or found with **no groups** — **ends the session** on every path (and so does a directory answer whose groups all map to **no role**, through the zero-role rule of the DB re-map above — ScadaBridge#144): HTTP rejects the principal and clears the cookie (the user lands on `/login`), and a circuit's state becomes anonymous so the next gate denies. Ending the session (rather than leaving a signed-in, role-less session) is chosen because it is what the login path would decide and it cannot be mistaken for a working account. *Not supported* (LDAP configured with `BindMode = User`, i.e. no service account) or LDAP disabled keeps the stored groups; the feature is then inert and logs that once. - **Off switches.** `LdapGroupRefresh:Enabled = false` restores the pre-#46 behaviour (stored groups until next login). Under `ScadaBridge:Security:Auth:DisableLogin` no cookie validation runs at all, so no directory query is made. Bearer tokens and HTTP Basic are unaffected: a token's claims are authoritative for its lifetime, and Basic binds per request. - **Role-mapping cache**: `RoleMapper` reads the LDAP-group→role table and the scope rules of every Deployer mapping through a process-wide `RoleMappingCache` snapshot (`SecurityOptions.RoleMappingCacheSeconds`, default **30**; `0` disables). One refresh loads the whole table plus all Deployer scope rules, so a cache hit costs no database round-trip — previously every Basic-authenticated management request and every circuit auth-state read issued `GetAllMappingsAsync` plus one `GetScopeRulesForMappingAsync` per matched Deployer mapping. Without an explicit invalidation a mapping or scope-rule change is therefore visible on every node within the TTL. `RoleMappingCache.Invalidate()` discards the calling node's snapshot so its next mapping re-reads the database (a refresh started before an invalidation is never published over it); the Management Service's mapping/scope-rule handlers also publish `RoleMappingsInvalidated` on the central cache-invalidation topic, so the peer central node discards its snapshot too (audit D1, ScadaBridge#100 item 3) and the TTL is only the fallback. `RoleMappingCacheSeconds = 0` bypasses the snapshot and reads only the matched mappings' scope rules per call. #### Session Validation (`OnValidatePrincipal`) - The cookie principal is built at login by a **single shared claim-builder** (`SessionClaimBuilder`). The `OnValidatePrincipal` role-refresh path rebuilds the principal through the **same** builder, so the login and refresh claim shapes cannot drift. -- **Failure policy**: ordinary cookie validation and display-state refresh retain existing grants on a mapping lookup error. Authoritative circuit mutation checks fail closed on the same error, so a mutation cannot proceed using grants that could not be refreshed. Idle timeout rejects the principal. +- **Failure policy**: ordinary cookie validation and display-state refresh retain existing grants on a mapping lookup error. Authoritative circuit mutation checks fail closed on the same error, so a mutation cannot proceed using grants that could not be refreshed. Idle timeout rejects the principal, and so does a successful refresh that maps the user to no role (ScadaBridge#144). > **Directory group-membership changes (resolved by ScadaBridge#46).** Earlier builds re-mapped > only the **stored** groups mid-session, so a directory group change waited for the next login; diff --git a/src/ZB.MOM.WW.ScadaBridge.Security/CookieSessionValidator.cs b/src/ZB.MOM.WW.ScadaBridge.Security/CookieSessionValidator.cs index bf54c74e..edb2289e 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Security/CookieSessionValidator.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Security/CookieSessionValidator.cs @@ -37,7 +37,7 @@ public enum SessionValidationAction /// Leave the principal as-is (no idle timeout, no refresh due, or a refresh error we swallow). Keep, - /// The session is idle-timed-out, or the directory says the user can no longer sign in; reject + sign out. + /// The session is idle-timed-out, the directory says the user can no longer sign in, or the user's groups now map to no role; reject + sign out. Reject, /// The role mapping was refreshed; replace the principal. The HTTP adapter decides whether renewal is appropriate. @@ -66,7 +66,9 @@ public enum SessionValidationAction /// = 15): when the elapsed time since /// exceeds the threshold, the stored groups are re-mapped and the principal is rebuilt via /// (identical shape to /auth/login). If the DB -/// mapping revoked the user's roles, the rebuilt principal reflects the loss. +/// mapping revoked some of the user's roles, the rebuilt principal reflects the loss; if it revoked +/// ALL of them, the session ends () — the same +/// "no role, no login" rule /auth/login applies (ScadaBridge#144). /// /// /// Directory group re-query (ScadaBridge#46): when the session's @@ -251,6 +253,19 @@ public sealed class CookieSessionValidator // Re-run the DB-backed mapping on the (possibly just re-read) groups. var mapping = await _roleMapper.MapAsync(groups, ct).ConfigureAwait(false); + + // No role, no session (ScadaBridge#144): a login whose groups map to no role is refused, so a + // session whose groups now map to no role ends the same way — on the DB-only re-map and after + // a directory re-query alike. A mapper FAULT is not this case: it throws above and the failure + // policy in ValidateAsync applies (keep on ordinary validation, propagate when fail-closed). + if (mapping.Roles is not { Count: > 0 }) + { + _logger.LogWarning( + "Cookie session for {Username} ended: its {GroupCount} group(s) now map to no ScadaBridge role (a new sign-in would be refused).", + username, groups.Count); + return SessionValidationResult.Reject; + } + var scope = mapping.Scope is RoleMappingResult mapped ? mapped : new RoleMappingResult(mapping.Roles, [], IsSystemWideDeployment: false); diff --git a/src/ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs b/src/ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs index 19a7ba76..3c2c87c6 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Security/ServiceCollectionExtensions.cs @@ -254,7 +254,7 @@ public static class ServiceCollectionExtensions /// adapter. It resolves the request-scoped , /// asks it for a decision, and applies it to the cookie context: /// - /// → + sign out (idle timeout, or the directory reports the user gone/disabled/ambiguous/group-less — ScadaBridge#46). + /// → + sign out (idle timeout, the directory reports the user gone/disabled/ambiguous/group-less — ScadaBridge#46, or the user's groups now map to no role — ScadaBridge#144). /// → + renewal only for non-passive requests (role mapping refreshed). /// → no-op (no refresh due, or a swallowed refresh fault). /// diff --git a/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs index cacd78cc..f79c4400 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs @@ -214,10 +214,17 @@ public class CookieSessionValidatorTests Assert.Equal(clock.GetUtcNow(), refreshedAt); } - /// Verifies that a user whose group was revoked loses the roles on refresh. + /// + /// Verifies that a user whose every role mapping was revoked has the session ENDED on refresh + /// (ScadaBridge#144: no role, no login — and so no role-less session either). Before #144 the + /// session was replaced with a role-less principal that could still read bare-[Authorize] pages. + /// + /// Whether the caller is an authoritative (fail-closed) check. /// A task that represents the asynchronous operation. - [Fact] - public async Task ValidateAsync_RevokedGroupUser_LosesRolesOnRefresh() + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task ValidateAsync_RevokedGroupUser_RefreshToZeroRoles_EndsTheSession(bool failClosed) { var clock = new TestTimeProvider(Start); var principal = Session(Start, ["SCADA-Admins"], @@ -227,13 +234,44 @@ public class CookieSessionValidatorTests var mapper = new FakeGroupRoleMapper(new RoleMappingResult([], [], IsSystemWideDeployment: false)); var sut = CreateValidator(mapper, clock); + clock.Advance(TimeSpan.FromMinutes(16)); + var result = await sut.ValidateAsync(principal, failClosed: failClosed); + + Assert.Equal(SessionValidationAction.Reject, result.Action); + Assert.Null(result.Principal); + Assert.Equal(1, mapper.CallCount); + } + + /// A forced (circuit) refresh to zero roles ends the session too, before the threshold. + /// A task that represents the asynchronous operation. + [Fact] + public async Task ValidateAsync_ForcedRefreshToZeroRoles_EndsTheSession() + { + var clock = new TestTimeProvider(Start); + var principal = Session(Start, ["SCADA-Admins"], + new RoleMappingResult([Roles.Administrator], [], true)); + var sut = CreateValidator(new FakeGroupRoleMapper(new RoleMappingResult([], [], false)), clock); + + var result = await sut.ValidateAsync(principal, recordActivity: false, forceRefresh: true); + + Assert.Equal(SessionValidationAction.Reject, result.Action); + } + + /// A refresh that keeps one role still replaces the principal (the zero-role rule is not over-broad). + /// A task that represents the asynchronous operation. + [Fact] + public async Task ValidateAsync_RefreshToOneRole_KeepsTheSession() + { + var clock = new TestTimeProvider(Start); + var principal = Session(Start, ["SCADA-Admins"], + new RoleMappingResult([Roles.Administrator], [], true)); + var sut = CreateValidator(new FakeGroupRoleMapper(new RoleMappingResult([Roles.Viewer], [], false)), clock); + clock.Advance(TimeSpan.FromMinutes(16)); var result = await sut.ValidateAsync(principal); Assert.Equal(SessionValidationAction.Replace, result.Action); - // The user has lost ALL roles mid-session — every authorization policy will now deny. - Assert.Empty(result.Principal!.FindAll(JwtTokenService.RoleClaimType)); - Assert.Empty(result.Principal.FindAll(JwtTokenService.SiteIdClaimType)); + Assert.Equal([Roles.Viewer], result.Principal!.FindAll(JwtTokenService.RoleClaimType).Select(c => c.Value)); } /// Verifies that validation does not refresh roles before the refresh threshold. diff --git a/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/DirectoryGroupRefreshTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/DirectoryGroupRefreshTests.cs index 8e68476e..53198d46 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/DirectoryGroupRefreshTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/DirectoryGroupRefreshTests.cs @@ -27,6 +27,9 @@ public class DirectoryGroupRefreshTests } /// Maps each group to a role by name (Admins→Administrator, Designers→Designer, else Viewer). + // A group that maps to no ScadaBridge role (e.g. "Domain Users" under a domain-wide search base). + private const string UnmappedGroup = "Domain Users"; + private sealed class NamingMapper : IGroupRoleMapper { public int Calls { get; private set; } @@ -40,8 +43,9 @@ public class DirectoryGroupRefreshTests { "SCADA-Admins" => Roles.Administrator, "SCADA-Designers" => Roles.Designer, + UnmappedGroup => null, _ => Roles.Viewer, - }).Distinct().ToList(); + }).OfType().Distinct().ToList(); var result = new RoleMappingResult(roles, [], IsSystemWideDeployment: true); return Task.FromResult(new GroupRoleMapping(roles, Scope: result)); } @@ -255,6 +259,41 @@ public class DirectoryGroupRefreshTests Assert.Equal(SessionValidationAction.Reject, result.Action); } + /// + /// ScadaBridge#144: the directory still answers with groups, but none of them maps to a role + /// (the user was removed from every mapped AD group and keeps only e.g. "Domain Users"). Before + /// #144 this kept a signed-in, role-less session; a new login would now be refused, so the + /// session ends — on ordinary validation and on the fail-closed authoritative path. + /// + [Theory] + [InlineData(false)] + [InlineData(true)] + public async Task FoundWithOnlyUnmappedGroups_EndsTheSession(bool failClosed) + { + var rig = Build(); + rig.Lookup.Answer = _ => FoundWith(UnmappedGroup); + rig.Clock.Advance(TimeSpan.FromMinutes(16)); + + var result = await rig.Sut.ValidateAsync(Login(["SCADA-Admins"]), forceRefresh: failClosed, failClosed: failClosed); + + Assert.Equal(SessionValidationAction.Reject, result.Action); + Assert.Equal([UnmappedGroup], rig.Mapper.LastGroups); + } + + /// A directory answer that keeps one mapped group alongside unmapped ones keeps the session. + [Fact] + public async Task FoundWithOneMappedGroup_KeepsTheSession() + { + var rig = Build(); + rig.Lookup.Answer = _ => FoundWith(UnmappedGroup, "SCADA-Designers"); + rig.Clock.Advance(TimeSpan.FromMinutes(16)); + + var result = await rig.Sut.ValidateAsync(Login(["SCADA-Admins"])); + + Assert.Equal(SessionValidationAction.Replace, result.Action); + Assert.Equal([Roles.Designer], RolesOf(result.Principal!)); + } + [Theory] [InlineData(LdapGroupLookupStatus.NotSupported)] [InlineData(LdapGroupLookupStatus.ProviderDisabled)]