diff --git a/docs/requirements/Component-Security.md b/docs/requirements/Component-Security.md index 7e9270a6..f2ec6597 100644 --- a/docs/requirements/Component-Security.md +++ b/docs/requirements/Component-Security.md @@ -234,4 +234,4 @@ To blunt online password-spray and brute-force against the directory, every LDAP ### Passive traffic and circuit refresh (2026-09-09) -`/auth/ping`, `/auth/activity`, and Blazor transport validation do not advance inactivity timestamps or trigger sliding renewal. The explicit activity endpoint validates antiforgery before renewing the cookie and recording activity by protected session ID. A bounded process-local tracker lets a live circuit observe successful activity renewal. Role refresh preserves the session ID and activity timestamp; current circuit mutation checks re-map stored groups with fail-closed lookup behavior. Display-only auth-state reads reuse the circuit's last revalidation for up to 10 s (review 2026-10-21 07/P-3), so an idle timeout or a revoked grant can show on a read-only surface for at most that long; it never reaches a mutation. +`/auth/ping`, `/auth/activity`, and Blazor transport validation do not advance inactivity timestamps or trigger sliding renewal. The explicit activity endpoint validates antiforgery before renewing the cookie and recording activity by protected session ID. A bounded process-local tracker lets a live circuit observe successful activity renewal. Role refresh preserves the session ID and activity timestamp; a refresh done on a passive request cannot re-issue the cookie, so when it changed no grant the node remembers it per session in the bounded activity tracker and the next ping does not repeat the role re-map / directory query (a refresh that DID change grants is re-derived until a non-passive request persists it, so stale cookie roles never outlive it); current circuit mutation checks re-map stored groups with fail-closed lookup behavior. Display-only auth-state reads reuse the circuit's last revalidation for up to 10 s (review 2026-10-21 07/P-3), so an idle timeout or a revoked grant can show on a read-only surface for at most that long; it never reaches a mutation. diff --git a/src/ZB.MOM.WW.ScadaBridge.Security/CookieSessionValidator.cs b/src/ZB.MOM.WW.ScadaBridge.Security/CookieSessionValidator.cs index edb2289e..89e89413 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Security/CookieSessionValidator.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Security/CookieSessionValidator.cs @@ -285,6 +285,17 @@ public sealed class CookieSessionValidator identity.AddClaim(new Claim(JwtTokenService.LastActivityClaimType, lastActivity)); } else _activity?.Record(rebuilt, now); + + // SEC-1: a passive request cannot persist the rebuilt ticket, so remember on this node that the + // refresh ran - but only when it changed nothing, so a changed grant keeps being re-derived + // until a non-passive request writes it into the cookie. + if (!recordActivity && _activity is not null && SameGrants(principal, rebuilt)) + { + var roleAnchor = ReadAnchor(rebuilt, JwtTokenService.LastRoleRefreshClaimType) ?? now; + var groupAnchor2 = ReadAnchor(rebuilt, JwtTokenService.LastGroupRefreshClaimType) ?? now; + _activity.RecordRefresh(principal, roleAnchor, groupAnchor2); + } + return SessionValidationResult.Replace(rebuilt); } @@ -304,9 +315,25 @@ public sealed class CookieSessionValidator return false; var anchor = ReadAnchor(principal, JwtTokenService.LastGroupRefreshClaimType); + if (_activity?.LastRefreshes(principal) is { } seen && (anchor is null || seen.Group > anchor)) + anchor = seen.Group; return anchor is null || now - anchor.Value >= _directory.Interval; } + // True when two principals carry the same grant claims (roles, groups, scope, identity), ignoring + // the refresh/activity timestamps and the session id. + private static bool SameGrants(ClaimsPrincipal before, ClaimsPrincipal after) + { + static HashSet Grants(ClaimsPrincipal p) => p.Claims + .Where(c => c.Type is not (JwtTokenService.LastActivityClaimType + or JwtTokenService.LastRoleRefreshClaimType + or JwtTokenService.LastGroupRefreshClaimType + or SessionActivityTracker.SessionIdClaim)) + .Select(c => c.Type + "\u0000" + c.Value) + .ToHashSet(StringComparer.Ordinal); + return Grants(before).SetEquals(Grants(after)); + } + private static DateTimeOffset? ReadAnchor(ClaimsPrincipal principal, string claimType) => principal.FindFirst(claimType) is { } claim && DateTimeOffset.TryParse(claim.Value, out var value) ? value : null; @@ -321,11 +348,14 @@ public sealed class CookieSessionValidator public bool IsRoleRefreshDue(ClaimsPrincipal principal, DateTimeOffset now) { var claim = principal.FindFirst(JwtTokenService.LastRoleRefreshClaimType); - if (claim is null || !DateTimeOffset.TryParse(claim.Value, out var lastRefresh)) + DateTimeOffset? lastRefresh = claim is not null && DateTimeOffset.TryParse(claim.Value, out var parsed) ? parsed : null; + if (_activity?.LastRefreshes(principal) is { } seen && (lastRefresh is null || seen.Role > lastRefresh)) + lastRefresh = seen.Role; + if (lastRefresh is null) { return true; } - return (now - lastRefresh).TotalMinutes > _options.RoleRefreshThresholdMinutes; + return (now - lastRefresh.Value).TotalMinutes > _options.RoleRefreshThresholdMinutes; } } diff --git a/src/ZB.MOM.WW.ScadaBridge.Security/SessionActivityTracker.cs b/src/ZB.MOM.WW.ScadaBridge.Security/SessionActivityTracker.cs index 5f9ebdbf..c16cf525 100644 --- a/src/ZB.MOM.WW.ScadaBridge.Security/SessionActivityTracker.cs +++ b/src/ZB.MOM.WW.ScadaBridge.Security/SessionActivityTracker.cs @@ -14,6 +14,7 @@ public sealed class SessionActivityTracker private const int Capacity = 10_000; private readonly object _sync = new(); private readonly Dictionary _activity = new(StringComparer.Ordinal); + private readonly Dictionary _refreshes = new(StringComparer.Ordinal); /// Returns the newer of the protected cookie anchor and this node's observed activity. /// The principal whose session activity is queried. @@ -42,4 +43,40 @@ public sealed class SessionActivityTracker _activity[id] = now; } } + + /// + /// Returns the refresh anchors this node recorded for the principal's session, or + /// when none (SEC-1). They supersede the older anchors in the cookie. + /// + /// The principal whose session is queried. + /// The recorded role and group refresh instants, if any. + public (DateTimeOffset Role, DateTimeOffset Group)? LastRefreshes(ClaimsPrincipal principal) + { + var id = principal.FindFirst(SessionIdClaim)?.Value; + if (id is null) return null; + lock (_sync) + return _refreshes.TryGetValue(id, out var seen) ? seen : null; + } + + /// + /// Records that a role/group refresh ran for the session without changing its grants. A passive + /// request (/auth/ping, /_blazor) never re-issues the cookie, so without this the old + /// anchors in the cookie made every later ping repeat the refresh (SEC-1). Only an UNCHANGED outcome + /// may be recorded: a changed one must keep being re-derived until a non-passive request persists it + /// in the cookie, otherwise the stale cookie roles would outlive the refresh. + /// + /// The principal whose session is recorded. + /// The role-refresh anchor now in effect. + /// The group-refresh anchor now in effect. + public void RecordRefresh(ClaimsPrincipal principal, DateTimeOffset role, DateTimeOffset group) + { + var id = principal.FindFirst(SessionIdClaim)?.Value; + if (id is null || principal.Identity?.IsAuthenticated != true) return; + lock (_sync) + { + if (!_refreshes.ContainsKey(id) && _refreshes.Count >= Capacity) + _refreshes.Remove(_refreshes.MinBy(p => p.Value.Role).Key); + _refreshes[id] = (role, group); + } + } } diff --git a/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs b/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs index f79c4400..8ea4b553 100644 --- a/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs +++ b/tests/ZB.MOM.WW.ScadaBridge.Security.Tests/CookieSessionValidatorTests.cs @@ -257,6 +257,58 @@ public class CookieSessionValidatorTests Assert.Equal(SessionValidationAction.Reject, result.Action); } + private static CookieSessionValidator CreateTrackedValidator( + IGroupRoleMapper mapper, TimeProvider clock, SessionActivityTracker tracker) => + new(mapper, Microsoft.Extensions.Options.Options.Create(Options()), clock, + NullLogger.Instance, tracker); + + /// + /// SEC-1: a passive request cannot write the cookie, so an UNCHANGED role refresh is remembered on the + /// node; the next ping (still carrying the old cookie anchors) must not repeat the re-map. + /// + /// A task that represents the asynchronous operation. + [Fact] + public async Task ValidateAsync_PassiveUnchangedRefresh_IsNotRepeatedOnTheNextPing() + { + var clock = new TestTimeProvider(Start); + var mapping = new RoleMappingResult([Roles.Administrator], [], true); + var mapper = new FakeGroupRoleMapper(mapping); + var sut = CreateTrackedValidator(mapper, clock, new SessionActivityTracker()); + var cookie = Session(Start, ["SCADA-Admins"], mapping); // the ticket never changes: passive requests cannot re-issue it + + clock.Advance(TimeSpan.FromMinutes(16)); + var first = await sut.ValidateAsync(cookie, recordActivity: false); + var second = await sut.ValidateAsync(cookie, recordActivity: false); + clock.Advance(TimeSpan.FromMinutes(14)); // 30 min since login, 14 since the remembered refresh + var third = await sut.ValidateAsync(cookie, recordActivity: false); + + Assert.Equal(SessionValidationAction.Replace, first.Action); + Assert.Equal(SessionValidationAction.Keep, second.Action); + Assert.Equal(1, mapper.CallCount); + Assert.Equal(SessionValidationAction.Keep, third.Action); + Assert.Equal(1, mapper.CallCount); + } + + /// A passive refresh that CHANGED the grants is not remembered: it is re-derived until a non-passive request persists it. + /// A task that represents the asynchronous operation. + [Fact] + public async Task ValidateAsync_PassiveChangedRefresh_KeepsBeingRederived() + { + var clock = new TestTimeProvider(Start); + var mapper = new FakeGroupRoleMapper(new RoleMappingResult([Roles.Viewer], [], false)); + var sut = CreateTrackedValidator(mapper, clock, new SessionActivityTracker()); + var cookie = Session(Start, ["SCADA-Admins"], new RoleMappingResult([Roles.Administrator], [], true)); + + clock.Advance(TimeSpan.FromMinutes(16)); + var first = await sut.ValidateAsync(cookie, recordActivity: false); + var second = await sut.ValidateAsync(cookie, recordActivity: false); + + Assert.Equal(SessionValidationAction.Replace, first.Action); + Assert.Equal(SessionValidationAction.Replace, second.Action); + Assert.Equal([Roles.Viewer], second.Principal!.FindAll(JwtTokenService.RoleClaimType).Select(c => c.Value)); + Assert.Equal(2, mapper.CallCount); + } + /// 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]