Path: redb-identity/tests/redb.Identity.Tests/Cookies/SessionCookieRotationTests.cs Snapshot: redb-identity, development snapshot 2026-12-06. This is the development state of the public mirrors; it may differ from the published packages. License: Apache-2.0. Repository: https://github.com/redbase-app/redb-identity Page: https://redbase.app/src/dev-2026-12-06/redb-identity/tests/redb.Identity.Tests/Cookies/SessionCookieRotationTests.cs ---- using System.Net; using AwesomeAssertions; using redb.Identity.Tests.Infrastructure; using Xunit; namespace redb.Identity.Tests.Cookies; /// /// G10 / C7 — session-fixation defence via per-login cookie value rotation. /// /// In redb.Identity the session cookie is an encrypted DataProtection ticket built /// by SessionTicketService.Protect(userId, sessionId, username) where /// sessionId is freshly generated by SessionService.CreateAsync on every /// successful login (see LoginProcessor.Process) and again on every successful /// MFA verify (see MfaVerifyProcessor.Process). DataProtection adds a random /// nonce to the ciphertext, so even if userId+sessionId were identical the cookie /// value would differ — but they are not identical, because each login produces a /// new SessionProps row. /// /// /// The C7 spec calls for "session-id rotation" — in this implementation that means /// the entire opaque cookie value MUST change between two successive logins from /// the same client. These tests assert exactly that: an attacker pre-seeding a /// cookie value cannot have it survive across a login. /// /// [Collection("ProductionHttp")] public sealed class SessionCookieRotationTests { private readonly ProductionHttpFixture _fx; public SessionCookieRotationTests(ProductionHttpFixture fx) => _fx = fx; [Fact] public async Task Login_IssuesFreshSessionCookie_OnEachSuccessfulLogin() { var first = await DoLoginAndExtractSessionCookieAsync(); var second = await DoLoginAndExtractSessionCookieAsync(); first.Should().NotBeNullOrEmpty("login response must Set-Cookie the session ticket"); second.Should().NotBeNullOrEmpty(); second.Should().NotBe(first, "C7 / session-fixation: each successful /login must emit a new opaque " + "session cookie value. The encrypted ticket binds a freshly-created " + "SessionProps row (new sessionId), so two logins back-to-back must " + "produce two distinct cookies — otherwise an attacker could pre-fix " + "the cookie on the victim and ride the post-login session."); } [Fact] public async Task Login_OverridesPreSeededAttackerCookie() { // Simulate session-fixation: attacker plants a cookie value on the victim // BEFORE login; after login the value MUST be a fresh server-issued one, // not the attacker's seed. const string attackerCookieValue = "ATTACKER-FIXED-COOKIE-DOES-NOT-DECRYPT"; var cookies = new CookieContainer(); cookies.Add(new Uri(_fx.BaseUrl), new Cookie( "redb.identity.session", attackerCookieValue) { Path = "/" }); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookies, UseCookies = true, }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; var resp = await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, })); resp.IsSuccessStatusCode.Should().BeTrue(); var setCookie = ExtractSessionSetCookie(resp); setCookie.Should().NotBeNullOrEmpty("login must Set-Cookie a fresh session ticket"); setCookie.Should().NotContain(attackerCookieValue, "session-fixation: server-issued cookie must NOT echo the attacker's seed"); // Independently verify by walking the CookieContainer: post-login the // stored cookie value must not equal the seed. var stored = cookies.GetCookies(new Uri(_fx.BaseUrl))["redb.identity.session"]; stored.Should().NotBeNull(); stored!.Value.Should().NotBe(attackerCookieValue, "the cookie jar after login must hold the new server-issued ticket"); } [Fact] public async Task Logout_ClearsSessionCookie() { var cookies = new CookieContainer(); using var handler = new HttpClientHandler { AllowAutoRedirect = false, CookieContainer = cookies, UseCookies = true, }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, })); // Pre-condition: session cookie present and non-empty var preLogout = cookies.GetCookies(new Uri(_fx.BaseUrl))["redb.identity.session"]; preLogout.Should().NotBeNull(); preLogout!.Value.Should().NotBeNullOrEmpty(); // No id_token_hint: the OP asks the browser to confirm first; LogoutFlow posts the page's state back. var logoutResp = await LogoutFlow.ConfirmAsync(client, await client.PostAsync("/connect/logout", new FormUrlEncodedContent([]))); // The Set-Cookie on the logout response must clear the session cookie. // CookieContainer treats Max-Age=0 / Expires in past as deletion; check // that the cookie value is now empty (server explicitly cleared) OR the // CookieContainer no longer holds it. var rawSetCookies = string.Join("; ", logoutResp.Headers.TryGetValues("Set-Cookie", out var sc) ? sc : []); rawSetCookies.Should().Contain("redb.identity.session", "logout must emit Set-Cookie targeting the session cookie name"); rawSetCookies.Should().MatchRegex("(?i)(max-age=0|expires=)", "logout must clear the cookie via Max-Age=0 or a past Expires date"); } // ─────────────── helpers ─────────────── private async Task DoLoginAndExtractSessionCookieAsync() { using var handler = new HttpClientHandler { AllowAutoRedirect = false, UseCookies = false }; using var client = new HttpClient(handler) { BaseAddress = new Uri(_fx.BaseUrl) }; var resp = await client.PostAsync("/login", new FormUrlEncodedContent(new Dictionary { ["username"] = ProductionHttpFixture.TestUsername, ["password"] = ProductionHttpFixture.TestPassword, })); resp.IsSuccessStatusCode.Should().BeTrue(); return ExtractSessionSetCookie(resp); } private static string? ExtractSessionSetCookie(HttpResponseMessage resp) { if (!resp.Headers.TryGetValues("Set-Cookie", out var values)) return null; foreach (var v in values) { // Header format: "redb.identity.session=; Path=/; ...". var idx = v.IndexOf("redb.identity.session=", StringComparison.Ordinal); if (idx < 0) continue; var tail = v[(idx + "redb.identity.session=".Length)..]; var semi = tail.IndexOf(';'); return semi >= 0 ? tail[..semi] : tail; } return null; } }