fix(security): remember an unchanged passive-request role refresh per session instead of re-issuing the cookie (SEC-1, WP7 task 7.6)

The first attempt (renew the cookie on a passive Replace) contradicted the documented rule that passive requests never re-issue the cookie and was reverted; the per-session anchor record in SessionActivityTracker honours it.
This commit is contained in:
Joseph Doherty
2026-12-03 10:02:42 -05:00
parent 0a62f33ab5
commit 6dd6c50e6f
4 changed files with 122 additions and 3 deletions
+1 -1
View File
@@ -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) ### 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.
@@ -285,6 +285,17 @@ public sealed class CookieSessionValidator
identity.AddClaim(new Claim(JwtTokenService.LastActivityClaimType, lastActivity)); identity.AddClaim(new Claim(JwtTokenService.LastActivityClaimType, lastActivity));
} }
else _activity?.Record(rebuilt, now); 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); return SessionValidationResult.Replace(rebuilt);
} }
@@ -304,9 +315,25 @@ public sealed class CookieSessionValidator
return false; return false;
var anchor = ReadAnchor(principal, JwtTokenService.LastGroupRefreshClaimType); 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; 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<string> 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) private static DateTimeOffset? ReadAnchor(ClaimsPrincipal principal, string claimType)
=> principal.FindFirst(claimType) is { } claim && DateTimeOffset.TryParse(claim.Value, out var value) ? value : null; => 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) public bool IsRoleRefreshDue(ClaimsPrincipal principal, DateTimeOffset now)
{ {
var claim = principal.FindFirst(JwtTokenService.LastRoleRefreshClaimType); 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 true;
} }
return (now - lastRefresh).TotalMinutes > _options.RoleRefreshThresholdMinutes; return (now - lastRefresh.Value).TotalMinutes > _options.RoleRefreshThresholdMinutes;
} }
} }
@@ -14,6 +14,7 @@ public sealed class SessionActivityTracker
private const int Capacity = 10_000; private const int Capacity = 10_000;
private readonly object _sync = new(); private readonly object _sync = new();
private readonly Dictionary<string, DateTimeOffset> _activity = new(StringComparer.Ordinal); private readonly Dictionary<string, DateTimeOffset> _activity = new(StringComparer.Ordinal);
private readonly Dictionary<string, (DateTimeOffset Role, DateTimeOffset Group)> _refreshes = new(StringComparer.Ordinal);
/// <summary>Returns the newer of the protected cookie anchor and this node's observed activity.</summary> /// <summary>Returns the newer of the protected cookie anchor and this node's observed activity.</summary>
/// <param name="principal">The principal whose session activity is queried.</param> /// <param name="principal">The principal whose session activity is queried.</param>
@@ -42,4 +43,40 @@ public sealed class SessionActivityTracker
_activity[id] = now; _activity[id] = now;
} }
} }
/// <summary>
/// Returns the refresh anchors this node recorded for the principal's session, or
/// <see langword="null"/> when none (SEC-1). They supersede the older anchors in the cookie.
/// </summary>
/// <param name="principal">The principal whose session is queried.</param>
/// <returns>The recorded role and group refresh instants, if any.</returns>
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;
}
/// <summary>
/// Records that a role/group refresh ran for the session without changing its grants. A passive
/// request (<c>/auth/ping</c>, <c>/_blazor</c>) 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.
/// </summary>
/// <param name="principal">The principal whose session is recorded.</param>
/// <param name="role">The role-refresh anchor now in effect.</param>
/// <param name="group">The group-refresh anchor now in effect.</param>
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);
}
}
} }
@@ -257,6 +257,58 @@ public class CookieSessionValidatorTests
Assert.Equal(SessionValidationAction.Reject, result.Action); Assert.Equal(SessionValidationAction.Reject, result.Action);
} }
private static CookieSessionValidator CreateTrackedValidator(
IGroupRoleMapper<string> mapper, TimeProvider clock, SessionActivityTracker tracker) =>
new(mapper, Microsoft.Extensions.Options.Options.Create(Options()), clock,
NullLogger<CookieSessionValidator>.Instance, tracker);
/// <summary>
/// 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.
/// </summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>A passive refresh that CHANGED the grants is not remembered: it is re-derived until a non-passive request persists it.</summary>
/// <returns>A task that represents the asynchronous operation.</returns>
[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);
}
/// <summary>A refresh that keeps one role still replaces the principal (the zero-role rule is not over-broad).</summary> /// <summary>A refresh that keeps one role still replaces the principal (the zero-role rule is not over-broad).</summary>
/// <returns>A task that represents the asynchronous operation.</returns> /// <returns>A task that represents the asynchronous operation.</returns>
[Fact] [Fact]