From 5748eb5fe1991b61944a2e31516ab8f353b3149a Mon Sep 17 00:00:00 2001 From: James Britton Date: Mon, 9 Nov 2026 15:48:05 +0000 Subject: [PATCH] fix: renew deletes session when subjectId changes, and also doesn't create session when existing session is missing --- .../Default/ServerSessionTicketStore.cs | 11 ++- .../src/Stores/Default/StoreLogMessages.cs | 6 ++ .../Login/LoginServerSideSessionTests.cs | 33 ++++--- .../Default/ServerSessionTicketStoreTests.cs | 89 +++++++++++-------- 4 files changed, 91 insertions(+), 48 deletions(-) diff --git a/src/Open.IdentityServer/src/Stores/Default/ServerSessionTicketStore.cs b/src/Open.IdentityServer/src/Stores/Default/ServerSessionTicketStore.cs index 5353590ad..0dc02f72c 100644 --- a/src/Open.IdentityServer/src/Stores/Default/ServerSessionTicketStore.cs +++ b/src/Open.IdentityServer/src/Stores/Default/ServerSessionTicketStore.cs @@ -89,7 +89,7 @@ public async Task RenewAsync(string key, AuthenticationTicket ticket) if (existingSession == null) { - await StoreNewSession(key, ticket); + logger.NoTicketFoundInStore(key); return; } @@ -108,6 +108,15 @@ await persistedGrantStore.RemoveAllAsync(new PersistedGrantFilter existingSession.Created = issued; } + + var inputSubject = ticket.Principal.GetSubjectId(); + + if (existingSession.SubjectId != inputSubject) + { + logger.SessionUserChangeDetectedRemovingSession(key, existingSession.SubjectId, inputSubject); + await serverServerSideSessionStore.DeleteSession(key); + return; + } logger.RenewingTicketInStore(key, ticket.Properties.ExpiresUtc); diff --git a/src/Open.IdentityServer/src/Stores/Default/StoreLogMessages.cs b/src/Open.IdentityServer/src/Stores/Default/StoreLogMessages.cs index 8fabf3a98..be7a0393c 100644 --- a/src/Open.IdentityServer/src/Stores/Default/StoreLogMessages.cs +++ b/src/Open.IdentityServer/src/Stores/Default/StoreLogMessages.cs @@ -55,4 +55,10 @@ internal static partial class Log EventName = nameof(SessionOverwriteRevokingGrants), Message = "Session overwrite detected for key {key}, subject {subjectId} and session {sessionId}, revoking grants")] internal static partial void SessionOverwriteRevokingGrants(this ILogger logger, string key, string subjectId, string sessionId); + + [LoggerMessage( + LogLevel.Debug, + EventName = nameof(SessionUserChangeDetectedRemovingSession), + Message = "Session user change detected for key {key}, old subject {oldSubject} and new session {newSubject}, removing session")] + internal static partial void SessionUserChangeDetectedRemovingSession(this ILogger logger, string key, string oldSubject, string newSubject); } \ No newline at end of file diff --git a/src/Open.IdentityServer/test/Open.IdentityServer.IntegrationTests/Endpoints/Login/LoginServerSideSessionTests.cs b/src/Open.IdentityServer/test/Open.IdentityServer.IntegrationTests/Endpoints/Login/LoginServerSideSessionTests.cs index aba231fba..e9eddbe23 100644 --- a/src/Open.IdentityServer/test/Open.IdentityServer.IntegrationTests/Endpoints/Login/LoginServerSideSessionTests.cs +++ b/src/Open.IdentityServer/test/Open.IdentityServer.IntegrationTests/Endpoints/Login/LoginServerSideSessionTests.cs @@ -4,6 +4,7 @@ #nullable enable using System.Net; +using System.Net.Http; using System.Threading.Tasks; using AwesomeAssertions; using IdentityServer.IntegrationTests.Common; @@ -12,7 +13,7 @@ namespace Open.IdentityServer.IntegrationTests.Endpoints.Login; -public class LoginServerSideSessionTests: ServerSideSessionTests +public class LoginServerSideSessionTests : ServerSideSessionTests { private const string Category = nameof(LoginServerSideSessionTests); @@ -37,7 +38,7 @@ public async Task Login_ShouldCreateSessionInServerStore() [Fact] [Trait("Category", Category)] - public async Task Login_WhenUserChanges_ShouldUpdateSessionInServerStore() + public async Task Login_WhenUserChanges_ShouldRemoveExistingSession() { sessionStore.Should().NotBeNull(); @@ -45,22 +46,34 @@ public async Task Login_WhenUserChanges_ShouldUpdateSessionInServerStore() Cookie originalSessionCookie = _mockPipeline.GetSessionCookie(); - var authKey = _mockPipeline.GetTicketStoreKeyFromAuthCookie(); - authKey.Should().NotBeNull(); + var originalAuthKey = _mockPipeline.GetTicketStoreKeyFromAuthCookie(); + originalAuthKey.Should().NotBeNull(); - var originalSession = await sessionStore.GetSession(authKey); + var originalSession = await sessionStore.GetSession(originalAuthKey); originalSession.Should().NotBeNull(); originalSession.SessionId.Should().Be(originalSessionCookie.Value); originalSession.SubjectId.Should().Be("bob"); await _mockPipeline.LoginAsync("alice"); - Cookie newSessionCookie = _mockPipeline.GetSessionCookie(); + var newAuthKey = _mockPipeline.GetTicketStoreKeyFromAuthCookie(); + newAuthKey.Should().Be(originalAuthKey); + + var updatedSession = await sessionStore.GetSession(originalAuthKey); + updatedSession.Should().BeNull(); + + _mockPipeline.LoginWasCalled = false; + + var authorizeUrl = _mockPipeline.CreateAuthorizeUrl( + clientId: "client1", + responseType: "code", + scope: "openid", + redirectUri: "https://client1/callback"); + + await _mockPipeline.BrowserClient!.GetAsync( + authorizeUrl, TestContext.Current.CancellationToken); - var updatedSession = await sessionStore.GetSession(authKey); - updatedSession.Should().NotBeNull(); - updatedSession.SessionId.Should().Be(newSessionCookie.Value); - updatedSession.SubjectId.Should().Be("alice"); + _mockPipeline.LoginWasCalled.Should().BeTrue(); } [Fact] diff --git a/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Stores/Default/ServerSessionTicketStoreTests.cs b/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Stores/Default/ServerSessionTicketStoreTests.cs index a5cb61791..b18c8930b 100644 --- a/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Stores/Default/ServerSessionTicketStoreTests.cs +++ b/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Stores/Default/ServerSessionTicketStoreTests.cs @@ -259,6 +259,7 @@ public async Task StoreAsync_WhenDisplayNameClaimSet_ShouldUseClaimValueIfSet(st [Fact] public async Task RenewAsync_WhenDisplayNameClaimSet_ShouldUseValueAsDeterminedByClaim() { + string subjectId = Guid.NewGuid().ToString(); const string fakeDisplayNameClaimType = "alias"; const string fakeDisplayNameClaimValue = "jsmith232"; fakeOptions.ServerSideSessions.UserDisplayNameClaimType = fakeDisplayNameClaimType; @@ -266,7 +267,7 @@ public async Task RenewAsync_WhenDisplayNameClaimSet_ShouldUseValueAsDeterminedB ServerSideSession existingSession = new ServerSideSession { Key = Guid.NewGuid().ToString(), Scheme = "AuthScheme", SessionId = Guid.NewGuid().ToString(), - SubjectId = Guid.NewGuid().ToString(), DisplayName = "John Doe", + SubjectId = subjectId, DisplayName = "John Doe", Created = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc), Renewed = new DateTime(2026, 1, 2, 12, 0, 0, DateTimeKind.Utc), Expires = new DateTime(2026, 1, 31, 12, 0, 0, DateTimeKind.Utc), @@ -274,7 +275,6 @@ public async Task RenewAsync_WhenDisplayNameClaimSet_ShouldUseValueAsDeterminedB }; const string authScheme = "FakeAuthScheme"; - string subjectId = Guid.NewGuid().ToString(); string sessionId = Guid.NewGuid().ToString(); Claim[] claims = [ @@ -314,7 +314,7 @@ public async Task RenewAsync_WhenOptionalValuesNotProvided_ShouldUseCorrectDefau }; const string authScheme = "FakeAuthScheme"; - string subjectId = Guid.NewGuid().ToString(); + string subjectId = existingSession.SubjectId; string sessionId = Guid.NewGuid().ToString(); AuthenticationTicket authenticationTicket = ServerSessionTestGenerators.GenerateAuthenticationTicket(authScheme, subjectId, sessionId); @@ -357,12 +357,13 @@ public async Task RenewAsync_WhenOptionalValuesNotProvided_ShouldUseCorrectDefau [Fact] public async Task RenewAsync_WhenSessionOverwritten_ShouldExpirePreviousGrants() { + string existingSubjectId = "subject_id"; ServerSideSession existingSession = new ServerSideSession { Key = Guid.NewGuid().ToString(), Scheme = "AuthScheme", SessionId = "session_id", - SubjectId = "subject_id", + SubjectId = existingSubjectId, DisplayName = "John Doe", Created = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc), Renewed = new DateTime(2026, 1, 2, 12, 0, 0, DateTimeKind.Utc), @@ -371,10 +372,10 @@ public async Task RenewAsync_WhenSessionOverwritten_ShouldExpirePreviousGrants() }; const string authScheme = "FakeAuthScheme"; - string newSubjectId = Guid.NewGuid().ToString(); + string subjectId = existingSession.SubjectId; string newSessionId = Guid.NewGuid().ToString(); - AuthenticationTicket authenticationTicket = ServerSessionTestGenerators.GenerateAuthenticationTicket(authScheme, newSubjectId, newSessionId); + AuthenticationTicket authenticationTicket = ServerSessionTestGenerators.GenerateAuthenticationTicket(authScheme, existingSubjectId, newSessionId); Mock.Get(serverServerSideSessionStore) .Setup(x => x.GetSession(existingSession.Key)) @@ -397,7 +398,7 @@ public async Task RenewAsync_WhenSessionOverwritten_ShouldExpirePreviousGrants() .Verify(x => x.UpdateSession( It.Is(sessions => sessions.SessionId == newSessionId && - sessions.SubjectId == newSubjectId && + sessions.SubjectId == existingSubjectId && sessions.Created == FakeNow.AddMinutes(1) && sessions.Expires == null ))); @@ -417,7 +418,7 @@ public async Task RenewAsync_WhenSessionOverwrittenWithoutIssuedUtc_ShouldSetCre }; AuthenticationTicket authenticationTicket = ServerSessionTestGenerators.GenerateAuthenticationTicket( - "FakeAuthScheme", Guid.NewGuid().ToString(), Guid.NewGuid().ToString()); + "FakeAuthScheme", "subject_id", Guid.NewGuid().ToString()); Mock.Get(serverServerSideSessionStore) .Setup(x => x.GetSession(existingSession.Key)) @@ -449,7 +450,7 @@ public async Task RenewAsync_WhenOptionalValuesProvided_ShouldUseThem() }; const string authScheme = "FakeAuthScheme"; - string subjectId = Guid.NewGuid().ToString(); + string subjectId = existingSession.SubjectId; string sessionId = Guid.NewGuid().ToString(); const string displayName = "Fake User"; DateTime issuedUtc = new(2026, 02, 19, 12, 0, 0, DateTimeKind.Utc); @@ -492,49 +493,63 @@ public async Task RenewAsync_WhenOptionalValuesProvided_ShouldUseThem() ServerSessionTicketStore.JsonSettings); dataProtector.ValidateProtectedData(actualPayload, expectedJson); } - + [Fact] - public async Task RenewAsync_WhenNoExistingSessionWithKey_ShouldCreateNewSession() + public async Task RenewAsync_WhenSubjectIdChanges_ShouldDeleteSession() { + ServerSideSession existingSession = new ServerSideSession + { + Key = Guid.NewGuid().ToString(), Scheme = "AuthScheme", SessionId = Guid.NewGuid().ToString(), + SubjectId = Guid.NewGuid().ToString(), DisplayName = "John Doe", + Created = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc), + Renewed = new DateTime(2026, 1, 2, 12, 0, 0, DateTimeKind.Utc), + Expires = new DateTime(2026, 1, 31, 12, 0, 0, DateTimeKind.Utc), + Data = "EXISTING_PROTEXTEDDAAT", + }; + const string authScheme = "FakeAuthScheme"; string subjectId = Guid.NewGuid().ToString(); string sessionId = Guid.NewGuid().ToString(); + const string displayName = "Fake User"; + DateTime issuedUtc = new(2026, 02, 19, 12, 0, 0, DateTimeKind.Utc); + DateTime expiresUtc = new(2026, 02, 19, 12, 0, 0, DateTimeKind.Utc); - AuthenticationTicket authenticationTicket = ServerSessionTestGenerators.GenerateAuthenticationTicket(authScheme, subjectId, sessionId); + AuthenticationTicket authenticationTicket = + ServerSessionTestGenerators.GenerateAuthenticationTicket(authScheme, subjectId, sessionId, displayName, issuedUtc, expiresUtc); - ServerSideSession? createdSessionModel = null; Mock.Get(serverServerSideSessionStore) - .Setup(x => x.CreateSession(It.IsAny())) - .Callback(session => { createdSessionModel = session; }); + .Setup(x => x.GetSession(existingSession.Key)) + .ReturnsAsync(existingSession); + + ServerSideSession? updatedSessionModel = null; + Mock.Get(serverServerSideSessionStore) + .Setup(x => x.UpdateSession(It.IsAny())) + .Callback((session) => { updatedSessionModel = session; }); ServerSessionTicketStore sut = CreateSut(); - - const string nonExistent = "NonExistentSession"; - await sut.RenewAsync(nonExistent, authenticationTicket); - createdSessionModel.Should().NotBeNull(); - createdSessionModel.Key.Should().NotBeNullOrWhiteSpace(); - createdSessionModel.Key.Should().Be(nonExistent); - createdSessionModel.Scheme.Should().Be(authScheme); - createdSessionModel.SessionId.Should().Be(sessionId); - createdSessionModel.SubjectId.Should().Be(subjectId); - createdSessionModel.DisplayName.Should().BeNull(); - createdSessionModel.Created.Should().Be(FakeNow); - createdSessionModel.Renewed.Should().Be(FakeNow); - createdSessionModel.Expires.Should().BeNull(); + await sut.RenewAsync(existingSession.Key, authenticationTicket); - var jsonElement = JsonElement.Parse(createdSessionModel.Data); + Mock.Get(serverServerSideSessionStore) + .Verify(x => x.DeleteSession(existingSession.Key)); + } + + [Fact] + public async Task RenewAsync_WhenNoExistingSessionWithKey_ShouldNotCreateSession() + { + const string authScheme = "FakeAuthScheme"; + string subjectId = Guid.NewGuid().ToString(); + string sessionId = Guid.NewGuid().ToString(); - jsonElement.GetProperty("Version").GetInt32().Should().Be(1); - var actualPayload = jsonElement.GetProperty("Payload").GetString(); - actualPayload.Should().NotBeNull(); + AuthenticationTicket authenticationTicket = ServerSessionTestGenerators.GenerateAuthenticationTicket(authScheme, subjectId, sessionId); - var expectedAuthTicket = authenticationTicket.Clone(); - expectedAuthTicket.Properties.Items[JwtClaimTypes.Issuer] = FakeIssuer; + ServerSessionTicketStore sut = CreateSut(); - string expectedJson = JsonSerializer.Serialize(expectedAuthTicket.ToSerializableObj(), - ServerSessionTicketStore.JsonSettings); - dataProtector.ValidateProtectedData(actualPayload, expectedJson); + const string nonExistent = "NonExistentSession"; + await sut.RenewAsync(nonExistent, authenticationTicket); + + Mock.Get(serverServerSideSessionStore) + .Verify(x => x.CreateSession(It.IsAny()), Times.Never()); } [Theory]