Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public async Task RenewAsync(string key, AuthenticationTicket ticket)

if (existingSession == null)
{
await StoreNewSession(key, ticket);
logger.NoTicketFoundInStore(key);
return;
}

Expand All @@ -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);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
#nullable enable

using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using AwesomeAssertions;
using IdentityServer.IntegrationTests.Common;
Expand All @@ -12,7 +13,7 @@

namespace Open.IdentityServer.IntegrationTests.Endpoints.Login;

public class LoginServerSideSessionTests: ServerSideSessionTests
public class LoginServerSideSessionTests : ServerSideSessionTests
{
private const string Category = nameof(LoginServerSideSessionTests);

Expand All @@ -37,30 +38,42 @@ public async Task Login_ShouldCreateSessionInServerStore()

[Fact]
[Trait("Category", Category)]
public async Task Login_WhenUserChanges_ShouldUpdateSessionInServerStore()
public async Task Login_WhenUserChanges_ShouldRemoveExistingSession()
{
sessionStore.Should().NotBeNull();

await _mockPipeline.LoginAsync("bob");

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]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -259,22 +259,22 @@ 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;

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),
Data = "EXISTING_PROTEXTEDDAAT",
};

const string authScheme = "FakeAuthScheme";
string subjectId = Guid.NewGuid().ToString();
string sessionId = Guid.NewGuid().ToString();

Claim[] claims = [
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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),
Expand All @@ -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))
Expand All @@ -397,7 +398,7 @@ public async Task RenewAsync_WhenSessionOverwritten_ShouldExpirePreviousGrants()
.Verify(x => x.UpdateSession(
It.Is<ServerSideSession>(sessions =>
sessions.SessionId == newSessionId &&
sessions.SubjectId == newSubjectId &&
sessions.SubjectId == existingSubjectId &&
sessions.Created == FakeNow.AddMinutes(1) &&
sessions.Expires == null
)));
Expand All @@ -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))
Expand Down Expand Up @@ -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);
Expand Down Expand Up @@ -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<ServerSideSession>()))
.Callback<ServerSideSession>(session => { createdSessionModel = session; });
.Setup(x => x.GetSession(existingSession.Key))
.ReturnsAsync(existingSession);

ServerSideSession? updatedSessionModel = null;
Mock.Get(serverServerSideSessionStore)
.Setup(x => x.UpdateSession(It.IsAny<ServerSideSession>()))
.Callback<ServerSideSession>((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<ServerSideSession>()), Times.Never());
}

[Theory]
Expand Down
Loading