diff --git a/src/Open.IdentityServer/src/Stores/Default/ServerSessionTicketStore.cs b/src/Open.IdentityServer/src/Stores/Default/ServerSessionTicketStore.cs index 67ea97bc0..5353590ad 100644 --- a/src/Open.IdentityServer/src/Stores/Default/ServerSessionTicketStore.cs +++ b/src/Open.IdentityServer/src/Stores/Default/ServerSessionTicketStore.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Linq; using System.Security.Claims; +using System.Security.Cryptography; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -113,7 +114,7 @@ await persistedGrantStore.RemoveAllAsync(new PersistedGrantFilter existingSession.Scheme = ticket.AuthenticationScheme; existingSession.SubjectId = ticket.Principal.GetSubjectId(); existingSession.SessionId = ticket.Properties.GetSessionId(); - existingSession.DisplayName = ticket.Principal.FindFirstValue(JwtClaimTypes.Name); + existingSession.DisplayName = GetDisplayNameValue(ticket.Principal); existingSession.Renewed = issued; existingSession.Expires = ticket.Properties.ExpiresUtc?.UtcDateTime; existingSession.Data = ToProtectedDataString(ticket); @@ -224,10 +225,8 @@ private async Task StoreNewSession(string key, Authentication { ticket.Properties.Items[JwtClaimTypes.Issuer] = issuerUri; } - - string? displayName = string.IsNullOrWhiteSpace(options.ServerSideSessions.UserDisplayNameClaimType) - ? null - : ticket.Principal.FindFirstValue(options.ServerSideSessions.UserDisplayNameClaimType); + + string? displayName = GetDisplayNameValue(ticket.Principal); var issued = ticket.Properties.IssuedUtc?.UtcDateTime ?? timeProvider.GetUtcNow().UtcDateTime; ServerSideSession serverSideSession = new ServerSideSession @@ -248,6 +247,13 @@ private async Task StoreNewSession(string key, Authentication return serverSideSession; } + private string? GetDisplayNameValue(ClaimsPrincipal principal) + { + return string.IsNullOrWhiteSpace(options.ServerSideSessions.UserDisplayNameClaimType) + ? null + : principal.FindFirstValue(options.ServerSideSessions.UserDisplayNameClaimType); + } + private string ToProtectedDataString(AuthenticationTicket ticket) { string serializedTicket = JsonSerializer.Serialize(ticket.ToSerializableObj()); @@ -277,12 +283,25 @@ private string ToProtectedDataString(AuthenticationTicket ticket) logger.LogError("failed retrieving '{SessionKey}', deserialisation failed, incorrect version '{VersionOrNull}'", existingSession.Key, dataProtectedSessionData?.Version); return null; } - - string unprotectedData = dataProtector.Unprotect(dataProtectedSessionData.Payload); - SerializedAuthenticationTicket? serializedAuthTicket = - JsonSerializer.Deserialize(unprotectedData); + try + { + string unprotectedData = dataProtector.Unprotect(dataProtectedSessionData.Payload); + + SerializedAuthenticationTicket? serializedAuthTicket = + JsonSerializer.Deserialize(unprotectedData); - return serializedAuthTicket?.ToAuthTicket(existingSession); + return serializedAuthTicket?.ToAuthTicket(existingSession); + } + catch (CryptographicException cryptException) + { + logger.LogError(cryptException, "failed to unprotect auth ticket data '{SessionKey}'", existingSession.Key); + return null; + } + catch (JsonException jsonException) + { + logger.LogError(jsonException, "failed deserialising unprotected auth ticket data '{SessionKey}'", existingSession.Key); + return null; + } } } \ No newline at end of file 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 a901251c9..a5cb61791 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 @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Security.Claims; using System.Text.Json; using System.Threading; using System.Threading.Tasks; @@ -13,6 +14,7 @@ using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.DataProtection; using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.Logging; using Microsoft.Extensions.Time.Testing; using Moq; using Open.IdentityServer.Configuration; @@ -97,7 +99,7 @@ public async Task StoreAsync_WhenOptionalValuesNotProvided_ShouldUseCorrectDefau ServerSideSession? createdSessionModel = null; Mock.Get(serverServerSideSessionStore) .Setup(x => x.CreateSession(It.IsAny())) - .Callback((session) => { createdSessionModel = session; }); + .Callback(session => { createdSessionModel = session; }); ServerSessionTicketStore sut = CreateSut(); @@ -139,7 +141,7 @@ public async Task StoreAsync_WhenIssuedUtcNotProvided_ShouldSetCreatedAndRenewed ServerSideSession? createdSessionModel = null; Mock.Get(serverServerSideSessionStore) .Setup(x => x.CreateSession(It.IsAny())) - .Callback((session) => { createdSessionModel = session; }); + .Callback(session => { createdSessionModel = session; }); // every read moves the clock on, so separate reads give different times fakeTimeProvider.AutoAdvanceAmount = TimeSpan.FromSeconds(1); @@ -168,7 +170,7 @@ public async Task StoreAsync_WhenOptionalValuesProvided_ShouldUseThem() ServerSideSession? createdSessionModel = null; Mock.Get(serverServerSideSessionStore) .Setup(x => x.CreateSession(It.IsAny())) - .Callback((session) => { createdSessionModel = session; }); + .Callback(session => { createdSessionModel = session; }); ServerSessionTicketStore sut = CreateSut(); @@ -221,7 +223,7 @@ public async Task StoreAsync_WhenDisplayNameClaimSet_ShouldUseClaimValueIfSet(st ServerSideSession? createdSessionModel = null; Mock.Get(serverServerSideSessionStore) .Setup(x => x.CreateSession(It.IsAny())) - .Callback((session) => { createdSessionModel = session; }); + .Callback(session => { createdSessionModel = session; }); ServerSessionTicketStore sut = CreateSut(); @@ -254,6 +256,50 @@ public async Task StoreAsync_WhenDisplayNameClaimSet_ShouldUseClaimValueIfSet(st dataProtector.ValidateProtectedData(actualPayload, expectedJson); } + [Fact] + public async Task RenewAsync_WhenDisplayNameClaimSet_ShouldUseValueAsDeterminedByClaim() + { + const string fakeDisplayNameClaimType = "alias"; + const string fakeDisplayNameClaimValue = "jsmith232"; + fakeOptions.ServerSideSessions.UserDisplayNameClaimType = fakeDisplayNameClaimType; + + 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(); + + Claim[] claims = [ + new(fakeDisplayNameClaimType, fakeDisplayNameClaimValue) + ]; + + AuthenticationTicket authenticationTicket = ServerSessionTestGenerators.GenerateAuthenticationTicket(authScheme, subjectId, sessionId, claims: claims); + + Mock.Get(serverServerSideSessionStore) + .Setup(x => x.GetSession(existingSession.Key)) + .ReturnsAsync(existingSession); + + ServerSideSession? createdSessionModel = null; + Mock.Get(serverServerSideSessionStore) + .Setup(x => x.UpdateSession(It.IsAny())) + .Callback(session => { createdSessionModel = session; }); + + ServerSessionTicketStore sut = CreateSut(); + + await sut.RenewAsync(existingSession.Key, authenticationTicket); + + createdSessionModel.Should().NotBeNull(); + createdSessionModel.DisplayName.Should().Be(fakeDisplayNameClaimValue); + } + [Fact] public async Task RenewAsync_WhenOptionalValuesNotProvided_ShouldUseCorrectDefaults() { @@ -280,7 +326,7 @@ public async Task RenewAsync_WhenOptionalValuesNotProvided_ShouldUseCorrectDefau ServerSideSession? createdSessionModel = null; Mock.Get(serverServerSideSessionStore) .Setup(x => x.UpdateSession(It.IsAny())) - .Callback((session) => { createdSessionModel = session; }); + .Callback(session => { createdSessionModel = session; }); ServerSessionTicketStore sut = CreateSut(); @@ -390,6 +436,8 @@ public async Task RenewAsync_WhenSessionOverwrittenWithoutIssuedUtc_ShouldSetCre [Fact] public async Task RenewAsync_WhenOptionalValuesProvided_ShouldUseThem() { + fakeOptions.ServerSideSessions.UserDisplayNameClaimType = JwtClaimTypes.Name; + ServerSideSession existingSession = new ServerSideSession { Key = Guid.NewGuid().ToString(), Scheme = "AuthScheme", SessionId = Guid.NewGuid().ToString(), @@ -417,7 +465,7 @@ public async Task RenewAsync_WhenOptionalValuesProvided_ShouldUseThem() ServerSideSession? updatedSessionModel = null; Mock.Get(serverServerSideSessionStore) .Setup(x => x.UpdateSession(It.IsAny())) - .Callback((session) => { updatedSessionModel = session; }); + .Callback(session => { updatedSessionModel = session; }); ServerSessionTicketStore sut = CreateSut(); @@ -457,7 +505,7 @@ public async Task RenewAsync_WhenNoExistingSessionWithKey_ShouldCreateNewSession ServerSideSession? createdSessionModel = null; Mock.Get(serverServerSideSessionStore) .Setup(x => x.CreateSession(It.IsAny())) - .Callback((session) => { createdSessionModel = session; }); + .Callback(session => { createdSessionModel = session; }); ServerSessionTicketStore sut = CreateSut(); @@ -515,7 +563,30 @@ public async Task RetrieveAsync_WhenNoSessionStoredForKey_ShouldReturnNull() [Theory] [InlineData("{invalid.json}")] [InlineData("{\"Version\": 2, Payload: \"SOMEDATA\"}")] - public async Task RetrieveAsync_WhenSessionDataDeserialisationFails_ShouldReturnNull(string data) + public async Task RetrieveAsync_WhenSessionDataDeserialisationFails_ShouldReturnNull(string malformedData) + { + 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 = malformedData, + }; + + Mock.Get(serverServerSideSessionStore) + .Setup(x => x.GetSession(existingSession.Key)) + .ReturnsAsync(existingSession); + + ServerSessionTicketStore sut = CreateSut(); + AuthenticationTicket? actual = await sut.RetrieveAsync(existingSession.Key); + + actual.Should().BeNull(); + } + + [Fact] + public async Task RetrieveAsync_WhenUnprotectPayloadFails_ShouldReturnNull() { ServerSideSession existingSession = new ServerSideSession { @@ -524,9 +595,38 @@ public async Task RetrieveAsync_WhenSessionDataDeserialisationFails_ShouldReturn 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 = data + Data = GenerateFakeProtectedData("FAKE_DATA"), }; + Mock.Get(dataProtector.dataProtector) + .Setup(x => x.Unprotect(It.IsAny())) + .Throws(new Exception("Fake Error")); + + Mock.Get(serverServerSideSessionStore) + .Setup(x => x.GetSession(existingSession.Key)) + .ReturnsAsync(existingSession); + + ServerSessionTicketStore sut = CreateSut(); + AuthenticationTicket? actual = await sut.RetrieveAsync(existingSession.Key); + + actual.Should().BeNull(); + logger.VerifyLog(LogLevel.Error); + } + + [Theory] + [InlineData("{invalid.json}")] + public async Task RetrieveAsync_WhenUnprotectedPayloadIsInvalidJson_ShouldReturnNull(string invalidJson) + { + 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 = GenerateFakeProtectedData(invalidJson), + }; + Mock.Get(serverServerSideSessionStore) .Setup(x => x.GetSession(existingSession.Key)) .ReturnsAsync(existingSession); @@ -535,6 +635,7 @@ public async Task RetrieveAsync_WhenSessionDataDeserialisationFails_ShouldReturn AuthenticationTicket? actual = await sut.RetrieveAsync(existingSession.Key); actual.Should().BeNull(); + logger.VerifyLog(LogLevel.Error); } [Fact] @@ -597,6 +698,107 @@ public async Task RemoveAsync_ShouldCallServerSideSessionStoreDelete() .Verify(x => x.DeleteSession(keyId)); } + [Theory] + [InlineData("{invalid.json}")] + [InlineData("{\"Version\": 2, Payload: \"SOMEDATA\"}")] + public async Task + RemoveAsync_WhenSessionStillExists_AndSessionDataDeserialisationFails_ShouldStoreExpiredSessionAndNullTicketOnHttpContext_AndRemove_AndLogError(string malformedData) + { + string keyId = Guid.NewGuid().ToString(); + ServerSideSession existingSession = new ServerSideSession + { + Key = keyId, Scheme = "AuthScheme", SessionId = "session_id", + SubjectId = Guid.NewGuid().ToString(), DisplayName = "bob", + 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 = malformedData, + }; + + Mock.Get(serverServerSideSessionStore) + .Setup(x => x.GetSession(keyId)) + .ReturnsAsync(existingSession); + + ServerSessionTicketStore sut = CreateSut(); + await sut.RemoveAsync(keyId); + + fakeHttpContext.Items.Should().ContainKey("idsvr:SessionExpired"); + fakeHttpContext.Items.Should().ContainKey("idsvr:TicketExpired"); + fakeHttpContext.Items["idsvr:SessionExpired"].Should().Be(existingSession); + fakeHttpContext.Items["idsvr:TicketExpired"].Should().BeNull(); + + Mock.Get(serverServerSideSessionStore) + .Verify(x => x.DeleteSession(keyId)); + logger.VerifyLog(LogLevel.Error); + } + + [Fact] + public async Task RemoveAsync_WhenSessionStillExists_AndUnprotectTicketFails_ShouldStoreExpiredSessionAndNullTicketOnHttpContext_AndRemove_AndLogError() + { + string keyId = Guid.NewGuid().ToString(); + ServerSideSession existingSession = new ServerSideSession + { + Key = keyId, Scheme = "AuthScheme", SessionId = "session_id", + SubjectId = Guid.NewGuid().ToString(), DisplayName = "bob", + 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 = GenerateFakeProtectedData("FAKE_DATA"), + }; + + Mock.Get(dataProtector.dataProtector) + .Setup(x => x.Unprotect(It.IsAny())) + .Throws(new Exception("Fake Error")); + + Mock.Get(serverServerSideSessionStore) + .Setup(x => x.GetSession(keyId)) + .ReturnsAsync(existingSession); + + ServerSessionTicketStore sut = CreateSut(); + await sut.RemoveAsync(keyId); + + fakeHttpContext.Items.Should().ContainKey("idsvr:SessionExpired"); + fakeHttpContext.Items.Should().ContainKey("idsvr:TicketExpired"); + fakeHttpContext.Items["idsvr:SessionExpired"].Should().Be(existingSession); + fakeHttpContext.Items["idsvr:TicketExpired"].Should().BeNull(); + + Mock.Get(serverServerSideSessionStore) + .Verify(x => x.DeleteSession(keyId)); + logger.VerifyLog(LogLevel.Error); + } + + [Theory] + [InlineData("{invalid.json}")] + public async Task RemoveAsync_WhenSessionStillExists_AndProtectedJsonMalformedTicket_ShouldStoreExpiredSessionAndNullTicketOnHttpContext_AndRemove_AndLogError(string malformedJson) + { + string keyId = Guid.NewGuid().ToString(); + ServerSideSession existingSession = new ServerSideSession + { + Key = keyId, Scheme = "AuthScheme", SessionId = "session_id", + SubjectId = Guid.NewGuid().ToString(), DisplayName = "bob", + 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 = GenerateFakeProtectedData(malformedJson), + }; + + Mock.Get(serverServerSideSessionStore) + .Setup(x => x.GetSession(keyId)) + .ReturnsAsync(existingSession); + + ServerSessionTicketStore sut = CreateSut(); + await sut.RemoveAsync(keyId); + + fakeHttpContext.Items.Should().ContainKey("idsvr:SessionExpired"); + fakeHttpContext.Items.Should().ContainKey("idsvr:TicketExpired"); + fakeHttpContext.Items["idsvr:SessionExpired"].Should().Be(existingSession); + fakeHttpContext.Items["idsvr:TicketExpired"].Should().BeNull(); + + Mock.Get(serverServerSideSessionStore) + .Verify(x => x.DeleteSession(keyId)); + logger.VerifyLog(LogLevel.Error); + } + [Fact] public async Task RemoveAsync_WhenSessionStillExists_ShouldStoreExpiredSessionAndTicketOnHttpContext_AndRemove() { @@ -787,7 +989,7 @@ public async Task FilterServerAuthenticationTickets_WhenQueryProvided_ShouldCall ServerSessionTicketStore sut = CreateSut(); QueryResult actual = - (await sut.FilterServerAuthenticationTickets(fakeQuery, TestContext.Current.CancellationToken)); + await sut.FilterServerAuthenticationTickets(fakeQuery, TestContext.Current.CancellationToken); actual.Should().NotBeNull(); actual.Should().BeEquivalentTo(fakeResult, cnf => cnf.Excluding(x => x.Results)); @@ -856,11 +1058,16 @@ private ServerSideSession GenerateSerialisedData( } private string GenerateFakeProtectedData(SerializedAuthenticationTicket serializedAuthenticationTicket) + { + return GenerateFakeProtectedData(JsonSerializer.Serialize(serializedAuthenticationTicket, + ServerSessionTicketStore.JsonSettings)); + } + + private string GenerateFakeProtectedData(string serializedJson) { DataProtectedSessionData sessionData = new DataProtectedSessionData { - Payload = dataProtector.GenerateFakeProtectedData(JsonSerializer.Serialize(serializedAuthenticationTicket, - ServerSessionTicketStore.JsonSettings)) + Payload = dataProtector.GenerateFakeProtectedData(serializedJson) }; return JsonSerializer.Serialize(sessionData, ServerSessionTicketStore.JsonSettings); diff --git a/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Utilities/Generators/ServerSessionTestGenerators.cs b/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Utilities/Generators/ServerSessionTestGenerators.cs index 1b421c663..5d663cd64 100644 --- a/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Utilities/Generators/ServerSessionTestGenerators.cs +++ b/src/Open.IdentityServer/test/Open.IdentityServer.UnitTests/Utilities/Generators/ServerSessionTestGenerators.cs @@ -3,6 +3,8 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Security.Claims; using Microsoft.AspNetCore.Authentication; using Open.IdentityServer.Extensions; using Open.IdentityServer.Models; @@ -21,7 +23,8 @@ public static AuthenticationTicket GenerateAuthenticationTicket( DateTimeOffset? issuedUtc = null, DateTimeOffset? expiresUtc = null, string? issuer = null, - string[]? clientIds = null) + string[]? clientIds = null, + Claim[]? claims = null) { IdentityServerUser user = new(subjectId); AuthenticationProperties properties = new(); @@ -32,6 +35,11 @@ public static AuthenticationTicket GenerateAuthenticationTicket( properties.IssuedUtc = issuedUtc; properties.ExpiresUtc = expiresUtc; + foreach (var claim in claims ?? []) + { + user.AdditionalClaims.Add(claim); + } + foreach (var clientId in clientIds ?? []) { properties.AddClientId(clientId);