From 1403e3a76ae4f8c0c03c7c2f2939d21f7ebb023b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Can=20Karag=C3=B6z?= Date: Mon, 30 Nov 2026 23:54:10 +0300 Subject: [PATCH 1/6] feat(product): Support SemiHybrid Auth Mode --- .../Contracts/Session/IssuedSession.cs | 11 +-- .../Session/SessionCredentialPurpose.cs | 18 +++++ .../Domain/Session/UAuthSession.cs | 34 ++++++--- .../Flows/Login/LoginOrchestrator.cs | 6 +- .../Issuers/UAuthSessionIssuer.cs | 43 ++++++++--- .../Issuers/UAuthTokenIssuer.cs | 8 +- .../Services/UAuthSessionValidator.cs | 7 ++ .../Data/UAuthSessionsModelBuilder.cs | 5 ++ .../Mappers/SessionProjectionMapper.cs | 10 ++- .../Projections/SessionProjection.cs | 1 + .../Server/UAuthSessionValidatorTests.cs | 75 +++++++++++++++++++ 11 files changed, 187 insertions(+), 31 deletions(-) create mode 100644 src/CodeBeam.UltimateAuth.Core/Domain/Session/SessionCredentialPurpose.cs diff --git a/src/CodeBeam.UltimateAuth.Core/Contracts/Session/IssuedSession.cs b/src/CodeBeam.UltimateAuth.Core/Contracts/Session/IssuedSession.cs index 6a76788b..90ced686 100644 --- a/src/CodeBeam.UltimateAuth.Core/Contracts/Session/IssuedSession.cs +++ b/src/CodeBeam.UltimateAuth.Core/Contracts/Session/IssuedSession.cs @@ -13,13 +13,10 @@ public sealed class IssuedSession public required UAuthSession Session { get; init; } /// - /// Opaque session identifier returned to the client. + /// Populated only for opaque credential sessions. + /// Metadata-only sessions never expose an opaque grant. /// - public required string OpaqueSessionId { get; init; } + public string? OpaqueSessionId { get; init; } - /// - /// Indicates whether this issuance is metadata-only - /// (used in SemiHybrid mode). - /// - public bool IsMetadataOnly { get; init; } + public bool IsMetadataOnly => Session.IsMetadataOnly; } diff --git a/src/CodeBeam.UltimateAuth.Core/Domain/Session/SessionCredentialPurpose.cs b/src/CodeBeam.UltimateAuth.Core/Domain/Session/SessionCredentialPurpose.cs new file mode 100644 index 00000000..7aecc82e --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Core/Domain/Session/SessionCredentialPurpose.cs @@ -0,0 +1,18 @@ +namespace CodeBeam.UltimateAuth.Core.Domain; + +/// +/// Defines whether a persisted session can authenticate an opaque credential or only represents JWT lineage. +/// +public enum SessionCredentialPurpose +{ + /// + /// The session ID is an opaque authentication credential. + /// + Opaque = 0, + + /// + /// The session ID is a non-secret correlation identifier. + /// It cannot authenticate an opaque request. + /// + MetadataOnly = 1 +} diff --git a/src/CodeBeam.UltimateAuth.Core/Domain/Session/UAuthSession.cs b/src/CodeBeam.UltimateAuth.Core/Domain/Session/UAuthSession.cs index ba3ef2c7..5a71277e 100644 --- a/src/CodeBeam.UltimateAuth.Core/Domain/Session/UAuthSession.cs +++ b/src/CodeBeam.UltimateAuth.Core/Domain/Session/UAuthSession.cs @@ -19,6 +19,11 @@ public sealed class UAuthSession : IVersionedEntity public SessionMetadata Metadata { get; } public long Version { get; set; } + public SessionCredentialPurpose CredentialPurpose { get; } + + public bool IsOpaqueCredential => CredentialPurpose == SessionCredentialPurpose.Opaque; + public bool IsMetadataOnly => CredentialPurpose == SessionCredentialPurpose.MetadataOnly; + public bool IsRevoked => RevokedAt != null; private UAuthSession( @@ -33,7 +38,8 @@ private UAuthSession( DeviceContext device, ClaimsSnapshot claims, SessionMetadata metadata, - long version) + long version, + SessionCredentialPurpose credentialPurpose) { SessionId = sessionId; Tenant = tenant; @@ -47,6 +53,7 @@ private UAuthSession( Claims = claims; Metadata = metadata; Version = version; + CredentialPurpose = credentialPurpose; } public static UAuthSession Create( @@ -59,8 +66,12 @@ public static UAuthSession Create( long securityVersion, DeviceContext device, ClaimsSnapshot? claims, - SessionMetadata metadata) + SessionMetadata metadata, + SessionCredentialPurpose credentialPurpose = SessionCredentialPurpose.Opaque) { + if (!Enum.IsDefined(credentialPurpose)) + throw new ArgumentOutOfRangeException(nameof(credentialPurpose)); + return new( sessionId, tenant, @@ -73,8 +84,8 @@ public static UAuthSession Create( device: device, claims: claims ?? ClaimsSnapshot.Empty, metadata: metadata, - version: 0 - ); + credentialPurpose: credentialPurpose, + version: 0); } public UAuthSession Revoke(DateTimeOffset at) @@ -94,7 +105,8 @@ public UAuthSession Revoke(DateTimeOffset at) Device, Claims, Metadata, - Version + 1 + Version + 1, + credentialPurpose: CredentialPurpose ); } @@ -110,7 +122,8 @@ internal static UAuthSession FromProjection( DeviceContext device, ClaimsSnapshot claims, SessionMetadata metadata, - long version) + long version, + SessionCredentialPurpose credentialPurpose) { return new UAuthSession( sessionId, @@ -124,7 +137,8 @@ internal static UAuthSession FromProjection( device, claims, metadata, - version + version, + credentialPurpose ); } @@ -156,7 +170,8 @@ public UAuthSession ExtendExpiration(DateTimeOffset expiresAt) Device, Claims, Metadata, - Version + 1 + Version + 1, + credentialPurpose: CredentialPurpose ); } @@ -177,7 +192,8 @@ public UAuthSession WithChain(SessionChainId chainId) device: Device, claims: Claims, metadata: Metadata, - version: Version + 1 + version: Version + 1, + credentialPurpose: CredentialPurpose ); } } diff --git a/src/CodeBeam.UltimateAuth.Server/Flows/Login/LoginOrchestrator.cs b/src/CodeBeam.UltimateAuth.Server/Flows/Login/LoginOrchestrator.cs index 964916c9..e4f07ad3 100644 --- a/src/CodeBeam.UltimateAuth.Server/Flows/Login/LoginOrchestrator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Flows/Login/LoginOrchestrator.cs @@ -79,9 +79,11 @@ public async Task LoginAsync(AuthFlowContext flow, LoginRequest req if (request.CredentialType != CredentialType.Password) throw new UAuthValidationException("unsupported_credential_type"); - if (flow.EffectiveMode == UAuthMode.PureJwt && loginExecution.Mode == LoginExecutionMode.Commit && !request.RequestTokens) + if (flow.EffectiveMode is UAuthMode.PureJwt or UAuthMode.SemiHybrid && + loginExecution.Mode == LoginExecutionMode.Commit && + !request.RequestTokens) { - throw new UAuthValidationException("pure_jwt_requires_token_delivery"); + throw new UAuthValidationException("jwt_mode_requires_token_delivery"); } var now = _clock.UtcNow; diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs index 1a8e31a0..8e3b726b 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs @@ -34,10 +34,34 @@ public async Task IssueSessionAsync(SessionIssuanceContext contex var sessionOptions = context.SessionOptions; var now = context.Now; - var opaqueSessionId = _opaqueGenerator.Generate(); - if (!AuthSessionId.TryCreate(opaqueSessionId, out AuthSessionId sessionId)) - throw new InvalidCastException("Can't create opaque id."); + var purpose = context.Mode switch + { + UAuthMode.PureOpaque or UAuthMode.Hybrid + => SessionCredentialPurpose.Opaque, + + UAuthMode.SemiHybrid + => SessionCredentialPurpose.MetadataOnly, + + UAuthMode.PureJwt + => throw new InvalidOperationException("PureJwt does not create sessions."), + + _ => throw new InvalidOperationException($"Unsupported auth mode: {context.Mode}") + }; + + var rawSessionId = purpose switch + { + SessionCredentialPurpose.Opaque => _opaqueGenerator.Generate(), + SessionCredentialPurpose.MetadataOnly => + _opaqueGenerator.Generate(), + + _ => throw new InvalidOperationException("Unsupported session credential purpose.") + }; + + if (!AuthSessionId.TryCreate(rawSessionId, out AuthSessionId sessionId)) + { + throw new InvalidOperationException("Could not generate session identifier."); + } var absoluteExpiresAt = sessionOptions.MaxLifetime is { } max ? now.Add(max) @@ -214,7 +238,8 @@ context.Device.DeviceId is not DeviceId incomingDeviceId || securityVersion: root.SecurityVersion, device: sessionDevice, claims: context.Claims, - metadata: context.Metadata); + metadata: context.Metadata, + credentialPurpose: purpose); await kernel.CreateSessionAsync(session, innerCt); var updatedChain = chain.AttachSession(session.SessionId, now); @@ -223,8 +248,7 @@ context.Device.DeviceId is not DeviceId incomingDeviceId || return new IssuedSession { Session = session, - OpaqueSessionId = opaqueSessionId, - IsMetadataOnly = context.Mode == UAuthMode.SemiHybrid + OpaqueSessionId = purpose == SessionCredentialPurpose.Opaque ? rawSessionId : null }; } @@ -297,16 +321,15 @@ await kernel.ExecuteAsync(async _ => securityVersion: root.SecurityVersion, device: context.Device, claims: context.Claims, - metadata: context.Metadata - ); + metadata: context.Metadata, + credentialPurpose: oldSession.CredentialPurpose); var newSession = newSessionUnbound.WithChain(chain.ChainId); issued = new IssuedSession { Session = newSession, - OpaqueSessionId = opaqueSessionId, - IsMetadataOnly = context.Mode == UAuthMode.SemiHybrid + OpaqueSessionId = newSession.IsOpaqueCredential ? opaqueSessionId : null }; await kernel.CreateSessionAsync(newSession); diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthTokenIssuer.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthTokenIssuer.cs index 48e8f79d..76266da5 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthTokenIssuer.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthTokenIssuer.cs @@ -42,9 +42,15 @@ public Task IssueAccessTokenAsync(AuthFlowContext flow, TokenIssuan UAuthMode.PureOpaque or UAuthMode.Hybrid => Task.FromResult(IssueOpaqueAccessToken(expires, context.SessionId)), - UAuthMode.SemiHybrid => + UAuthMode.SemiHybrid + when context.SessionId is not null && + context.SessionChainId is not null && + context.DeviceId is not null => Task.FromResult(IssueJwtAccessToken(context, tokens, expires)), + UAuthMode.SemiHybrid => + throw new InvalidOperationException("SemiHybrid JWT requires a session, chain and device binding."), + UAuthMode.PureJwt when context.SessionId is null && context.SessionChainId is null && diff --git a/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs b/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs index ad9617f0..69292f62 100644 --- a/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs @@ -26,6 +26,13 @@ public async Task ValidateSessionAsync(SessionValidatio var kernel = _storeFactory.Create(context.Tenant); var session = await kernel.GetSessionAsync(context.SessionId, ct); + if (session is null) + return SessionValidationResult.Invalid(SessionState.NotFound, sessionId: context.SessionId); + + // Metadata-only identifiers are not opaque credentials. + if (!session.IsOpaqueCredential) + return SessionValidationResult.Invalid(SessionState.NotFound, sessionId: context.SessionId); + if (session is null) return SessionValidationResult.Invalid(SessionState.NotFound, sessionId: context.SessionId); diff --git a/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Data/UAuthSessionsModelBuilder.cs b/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Data/UAuthSessionsModelBuilder.cs index 3e0a462f..494e7d4e 100644 --- a/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Data/UAuthSessionsModelBuilder.cs +++ b/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Data/UAuthSessionsModelBuilder.cs @@ -154,6 +154,11 @@ private static void ConfigureSessions(ModelBuilder b) .HasConversion(new JsonValueConverter()) .IsRequired(); + e.Property(x => x.CredentialPurpose) + .HasConversion() + .HasDefaultValue(SessionCredentialPurpose.Opaque) + .IsRequired(); + e.HasIndex(x => new { x.Tenant, x.SessionId }).IsUnique(); e.HasIndex(x => new { x.Tenant, x.ChainId }); e.HasIndex(x => new { x.Tenant, x.ChainId, x.RevokedAt }); diff --git a/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Mappers/SessionProjectionMapper.cs b/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Mappers/SessionProjectionMapper.cs index be5f5413..760aeb84 100644 --- a/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Mappers/SessionProjectionMapper.cs +++ b/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Mappers/SessionProjectionMapper.cs @@ -18,7 +18,8 @@ public static UAuthSession ToDomain(this SessionProjection p) p.Device, p.Claims, p.Metadata, - p.Version + p.Version, + p.CredentialPurpose ); } @@ -39,7 +40,8 @@ public static SessionProjection ToProjection(this UAuthSession s) Device = s.Device, Claims = s.Claims, Metadata = s.Metadata, - Version = s.Version + Version = s.Version, + CredentialPurpose = s.CredentialPurpose, }; } @@ -51,6 +53,10 @@ public static void UpdateProjection(this UAuthSession source, SessionProjection target.Device = source.Device; target.Claims = source.Claims; target.Metadata = source.Metadata; + + if (target.CredentialPurpose != source.CredentialPurpose) + throw new InvalidOperationException("Session credential purpose cannot be changed."); + // Version store-owned } } diff --git a/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Projections/SessionProjection.cs b/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Projections/SessionProjection.cs index 7860d578..9adcfc02 100644 --- a/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Projections/SessionProjection.cs +++ b/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Projections/SessionProjection.cs @@ -23,6 +23,7 @@ public sealed class SessionProjection public SessionMetadata Metadata { get; set; } = SessionMetadata.Empty; public long Version { get; set; } + public SessionCredentialPurpose CredentialPurpose { get; set; } = SessionCredentialPurpose.Opaque; public bool IsRevoked => RevokedAt != null; } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthSessionValidatorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthSessionValidatorTests.cs index e7a39459..40a5e331 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthSessionValidatorTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthSessionValidatorTests.cs @@ -555,6 +555,81 @@ public async Task ValidateSessionAsync_PropagatesCancellationToken() Times.Once); } + [Fact] + public async Task ValidateSessionAsync_MetadataOnlySession_ReturnsNotFound() + { + var fixture = CreateFixture(); + + var metadataSession = UAuthSession.Create( + sessionId: fixture.Session.SessionId, + tenant: fixture.Tenant, + userKey: fixture.User, + chainId: fixture.Chain.ChainId, + now: Now.AddMinutes(-5), + expiresAt: Now.AddMinutes(30), + securityVersion: fixture.Root.SecurityVersion, + device: fixture.Session.Device, + claims: ClaimsSnapshot.Empty, + metadata: SessionMetadata.Empty, + credentialPurpose: SessionCredentialPurpose.MetadataOnly); + + fixture.Store + .Setup(x => x.GetSessionAsync( + metadataSession.SessionId, + It.IsAny())) + .ReturnsAsync(metadataSession); + + var result = await fixture.Sut.ValidateSessionAsync( + fixture.Context, + TestContext.Current.CancellationToken); + + result.IsValid.Should().BeFalse(); + result.State.Should().Be(SessionState.NotFound); + + fixture.Store.Verify( + x => x.GetChainAsync( + It.IsAny(), + It.IsAny()), + Times.Never); + + fixture.ClaimsProvider.Verify( + x => x.GetClaimsAsync( + It.IsAny(), + It.IsAny(), + It.IsAny()), + Times.Never); + } + + [Fact] + public void MetadataOnlySession_PreservesPurpose_AfterMutation() + { + var now = new DateTimeOffset( + 2026, 11, 30, 12, 0, 0, TimeSpan.Zero); + + var session = UAuthSession.Create( + sessionId: AuthSessionId.Parse("metadata_session_identifier_1234567890"), + tenant: TenantKey.Single, + userKey: UserKey.FromString("user-1"), + chainId: SessionChainId.New(), + now: now, + expiresAt: now.AddHours(1), + securityVersion: 0, + device: DeviceContext.Anonymous(), + claims: ClaimsSnapshot.Empty, + metadata: SessionMetadata.Empty, + credentialPurpose: SessionCredentialPurpose.MetadataOnly); + + session.IsMetadataOnly.Should().BeTrue(); + + session.ExtendExpiration(now.AddHours(2)) + .CredentialPurpose.Should() + .Be(SessionCredentialPurpose.MetadataOnly); + + session.Revoke(now.AddMinutes(10)) + .CredentialPurpose.Should() + .Be(SessionCredentialPurpose.MetadataOnly); + } + // --------------------------------------------------------------------- // Setup // --------------------------------------------------------------------- From ff41b1d238afb9f7e494d26bf3b2eca43f47cb48 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Can=20Karag=C3=B6z?= Date: Tue, 1 Dec 2026 12:01:33 +0300 Subject: [PATCH 2/6] Login Implementation --- .../Auth/Context/AuthFlowContextFactory.cs | 6 +- .../AspNetCore/UAuthAuthenticationHandler.cs | 50 ++----- .../UAuthResourceAuthenticationHandler.cs | 60 ++------ .../UAuthJwtPrincipalFactory.cs | 70 +++++++++ .../Endpoints/ValidateEndpointHandler.cs | 21 +-- .../Extensions/ServiceCollectionExtensions.cs | 47 +++--- .../Flows/Login/LoginOrchestrator.cs | 33 ++++- .../Flows/Refresh/RefreshResponsePolicy.cs | 7 +- .../Infrastructure/Token/JwtPayloadGuard.cs | 11 ++ .../Infrastructure/User/UAuthUserAccessor.cs | 2 +- .../Options/Defaults/ConfigureDefaults.cs | 5 +- .../UAuthResourceApiOptionsValidator.cs | 21 +-- .../Services/UAuthSessionValidator.cs | 3 - .../Server/UAuthJwtPrincipalFactoryTests.cs | 137 ++++++++++++++++++ 14 files changed, 313 insertions(+), 160 deletions(-) create mode 100644 src/CodeBeam.UltimateAuth.Server/Authentication/UAuthJwtPrincipalFactory.cs create mode 100644 tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthJwtPrincipalFactoryTests.cs diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowContextFactory.cs b/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowContextFactory.cs index 1bc012d2..94e65947 100644 --- a/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowContextFactory.cs +++ b/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowContextFactory.cs @@ -70,10 +70,10 @@ public async ValueTask CreateAsync(HttpContext ctx, AuthFlowTyp bool isAuthenticated; UserKey? userKey; - if (effectiveMode == UAuthMode.PureJwt) + if (effectiveMode is UAuthMode.PureJwt or UAuthMode.SemiHybrid) { - // The UserMiddleware has already populated this snapshot from the cryptographically authenticated JWT principal. - // No session validation is performed for PureJwt. + // Identity is established by the UltimateAuth JWT scheme. + // No implicit session or lineage validation. isAuthenticated = user?.IsAuthenticated == true; userKey = isAuthenticated ? user?.UserId : null; } diff --git a/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthAuthenticationHandler.cs b/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthAuthenticationHandler.cs index b62d6e9d..19d4c7c9 100644 --- a/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthAuthenticationHandler.cs +++ b/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthAuthenticationHandler.cs @@ -71,15 +71,17 @@ protected override async Task HandleAuthenticateAsync() var credential = await _transportCredentialResolver.ResolveAsync(Context, mode, response); - if (mode == UAuthMode.PureJwt) + if (mode is UAuthMode.PureJwt or UAuthMode.SemiHybrid) { if (credential is null) return AuthenticateResult.NoResult(); if (credential.Kind != TransportCredentialKind.AccessToken) - return AuthenticateResult.Fail("PureJwt requires an access token."); + { + return AuthenticateResult.Fail("JWT authentication requires an access token."); + } - return await AuthenticateJwtAsync(credential.Value, tenant, effective.Options.Session.DeviceMismatchBehavior); + return await AuthenticateJwtAsync(credential.Value, tenant, mode, effective.Options.Session.DeviceMismatchBehavior); } if (credential is null) @@ -167,36 +169,13 @@ protected override Task HandleForbiddenAsync(AuthenticationProperties properties return Task.CompletedTask; } - private async Task AuthenticateJwtAsync(string token, TenantKey tenant, DeviceMismatchBehavior mismatchBehavior) + private async Task AuthenticateJwtAsync(string token, TenantKey tenant, UAuthMode mode, DeviceMismatchBehavior mismatchBehavior) { var validated = await _jwtValidator.ValidateAsync(token, tenant, Context.RequestAborted); if (validated is null) - return AuthenticateResult.Fail("Invalid JWT access token."); - - // PureJwt credentials must not carry framework session identity. - if (validated.Claims.Any(x => x.Type == "sid")) - { - return AuthenticateResult.Fail("Session-bound JWT is not valid in PureJwt mode."); - } - - var deviceClaims = validated.Claims - .Where(x => x.Type == "device_id") - .ToArray(); - - if (deviceClaims.Length != 1 || !DeviceId.TryCreate(deviceClaims[0].Value, out var tokenDeviceId)) - { - return AuthenticateResult.Fail("PureJwt requires a valid device binding."); - } - - if (mismatchBehavior == DeviceMismatchBehavior.AllowAndRebind) { - return AuthenticateResult.Fail("Device rebinding is not supported in PureJwt."); - } - - if (mismatchBehavior is not (DeviceMismatchBehavior.Reject or DeviceMismatchBehavior.Allow)) - { - return AuthenticateResult.Fail("Unsupported device mismatch behavior."); + return AuthenticateResult.Fail("Invalid JWT access token."); } DeviceId? requestDeviceId = null; @@ -211,22 +190,11 @@ private async Task AuthenticateJwtAsync(string token, Tenant } } - if (!PureJwtDevicePolicy.IsAllowed(mismatchBehavior, tokenDeviceId, requestDeviceId)) + if (!UAuthJwtPrincipalFactory.TryCreate(validated, mode, mismatchBehavior, requestDeviceId, Scheme.Name, out var principal) || principal is null) { - return AuthenticateResult.Fail("JWT device mismatch."); + return AuthenticateResult.Fail("JWT identity does not satisfy authentication mode."); } - var claims = validated.Claims.ToList(); - - // Use the cryptographically validated subject, not an untrusted request header or client-provided identifier. - claims.RemoveAll(x => x.Type == ClaimTypes.NameIdentifier); - - claims.Add(new Claim(ClaimTypes.NameIdentifier, validated.Subject)); - - var identity = new ClaimsIdentity(claims, Scheme.Name, ClaimTypes.NameIdentifier, ClaimTypes.Role); - - var principal = new ClaimsPrincipal(identity); - RateLimiting.UAuthRateLimitPolicy.SetValidatedActor(Context, tenant.Value, validated.Subject); return AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name)); diff --git a/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthResourceAuthenticationHandler.cs b/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthResourceAuthenticationHandler.cs index 3d465f41..5366576d 100644 --- a/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthResourceAuthenticationHandler.cs +++ b/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthResourceAuthenticationHandler.cs @@ -3,7 +3,6 @@ using CodeBeam.UltimateAuth.Core.Defaults; using CodeBeam.UltimateAuth.Core.Domain; using CodeBeam.UltimateAuth.Core.MultiTenancy; -using CodeBeam.UltimateAuth.Core.Options; using CodeBeam.UltimateAuth.Server.Abstractions; using CodeBeam.UltimateAuth.Server.Auth; using CodeBeam.UltimateAuth.Server.Domain; @@ -55,9 +54,10 @@ public UAuthResourceAuthenticationHandler( protected override async Task HandleAuthenticateAsync() { var tenant = Context.GetTenant(); + var mode = _modeProvider.Mode; - return _modeProvider.Mode == UAuthMode.PureJwt - ? await AuthenticatePureJwtAsync(tenant) + return mode is UAuthMode.PureJwt or UAuthMode.SemiHybrid + ? await AuthenticateJwtAsync(tenant, mode) : await AuthenticateSessionAsync(tenant); } @@ -126,7 +126,7 @@ private async Task AuthenticateSessionAsync(TenantKey tenant return AuthenticateResult.Success(new AuthenticationTicket(new ClaimsPrincipal(identity), Scheme.Name)); } - private async Task AuthenticatePureJwtAsync(CodeBeam.UltimateAuth.Core.MultiTenancy.TenantKey tenant) + private async Task AuthenticateJwtAsync(TenantKey tenant, UAuthMode mode) { var accessDelivery = new EffectiveGrantDelivery( GrantKind.AccessToken, @@ -145,52 +145,25 @@ private async Task AuthenticatePureJwtAsync(CodeBeam.Ultimat EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), EffectiveRedirectResponse.Disabled); - var credential = await _credentialResolver.ResolveAsync( - Context, - UAuthMode.PureJwt, - response); + var credential = await _credentialResolver.ResolveAsync(Context, mode, response); if (credential is null) return AuthenticateResult.NoResult(); if (credential.Kind != TransportCredentialKind.AccessToken) - return AuthenticateResult.Fail("PureJwt requires an access token."); + { + return AuthenticateResult.Fail("JWT authentication requires an access token."); + } var validator = _services.GetRequiredService(); - var validated = await validator.ValidateAsync( - credential.Value, - tenant, - Context.RequestAborted); + var validated = await validator.ValidateAsync(credential.Value, tenant, Context.RequestAborted); if (validated is null) return AuthenticateResult.Fail("Invalid JWT access token."); - // PureJwt must never carry a framework session identity. - if (validated.Claims.Any(x => x.Type == "sid")) - { - return AuthenticateResult.Fail("Session-bound JWT is not valid in PureJwt mode."); - } - - var deviceClaims = validated.Claims.Where(x => x.Type == "device_id").ToArray(); - - if (deviceClaims.Length != 1 || !DeviceId.TryCreate(deviceClaims[0].Value, out var tokenDeviceId)) - { - return AuthenticateResult.Fail("PureJwt requires a valid device binding."); - } - var mismatchBehavior = _resourceOptions.Auth.Device.MismatchBehavior; - if (mismatchBehavior == DeviceMismatchBehavior.AllowAndRebind) - { - return AuthenticateResult.Fail("Device rebinding is not supported in PureJwt."); - } - - if (mismatchBehavior is not (DeviceMismatchBehavior.Reject or DeviceMismatchBehavior.Allow)) - { - return AuthenticateResult.Fail("Unsupported device mismatch behavior."); - } - DeviceId? requestDeviceId = null; if (mismatchBehavior == DeviceMismatchBehavior.Reject) @@ -203,22 +176,11 @@ private async Task AuthenticatePureJwtAsync(CodeBeam.Ultimat } } - if (!PureJwtDevicePolicy.IsAllowed(mismatchBehavior, tokenDeviceId, requestDeviceId)) + if (!UAuthJwtPrincipalFactory.TryCreate(validated, mode, mismatchBehavior, requestDeviceId, Scheme.Name, out var principal) || principal is null) { - return AuthenticateResult.Fail("JWT device mismatch."); + return AuthenticateResult.Fail("JWT identity does not satisfy authentication mode."); } - var claims = validated.Claims.ToList(); - - // The identity must come from the validated JWT subject. - claims.RemoveAll(x => x.Type == ClaimTypes.NameIdentifier); - - claims.Add(new Claim(ClaimTypes.NameIdentifier, validated.Subject)); - - var identity = new ClaimsIdentity(claims, Scheme.Name, ClaimTypes.NameIdentifier, ClaimTypes.Role); - - var principal = new ClaimsPrincipal(identity); - return AuthenticateResult.Success(new AuthenticationTicket(principal, Scheme.Name)); } } diff --git a/src/CodeBeam.UltimateAuth.Server/Authentication/UAuthJwtPrincipalFactory.cs b/src/CodeBeam.UltimateAuth.Server/Authentication/UAuthJwtPrincipalFactory.cs new file mode 100644 index 00000000..25ccbb42 --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/Authentication/UAuthJwtPrincipalFactory.cs @@ -0,0 +1,70 @@ +using System.Security.Claims; +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Server.Contracts; + +namespace CodeBeam.UltimateAuth.Server.Authentication; + +internal static class UAuthJwtPrincipalFactory +{ + public static bool TryCreate( + ValidatedJwtIdentity validated, + UAuthMode mode, + DeviceMismatchBehavior mismatchBehavior, + DeviceId? requestDeviceId, + string scheme, + out ClaimsPrincipal? principal) + { + principal = null; + + if (mode is not (UAuthMode.PureJwt or UAuthMode.SemiHybrid)) + return false; + + if (mismatchBehavior is not (DeviceMismatchBehavior.Reject or DeviceMismatchBehavior.Allow)) + { + return false; + } + + if (!UserKey.TryParse(validated.Subject, null, out _)) + { + return false; + } + + var sessionClaims = validated.Claims.Where(x => x.Type == "sid").ToArray(); + + if (mode == UAuthMode.PureJwt) + { + if (sessionClaims.Length != 0) + return false; + } + else + { + if (sessionClaims.Length != 1 || !AuthSessionId.TryCreate(sessionClaims[0].Value, out _)) + { + return false; + } + } + + var deviceClaims = validated.Claims.Where(x => x.Type == "device_id").ToArray(); + + if (deviceClaims.Length != 1 || !DeviceId.TryCreate(deviceClaims[0].Value, out var tokenDeviceId)) + { + return false; + } + + if (!PureJwtDevicePolicy.IsAllowed(mismatchBehavior, tokenDeviceId, requestDeviceId)) + { + return false; + } + + // Framework identity cannot be overridden by application-supplied NameIdentifier claims. + var claims = validated.Claims.Where(x => x.Type != ClaimTypes.NameIdentifier).ToList(); + + claims.Add(new Claim(ClaimTypes.NameIdentifier, validated.Subject)); + + var identity = new ClaimsIdentity(claims, scheme, ClaimTypes.NameIdentifier, ClaimTypes.Role); + + principal = new ClaimsPrincipal(identity); + return true; + } +} diff --git a/src/CodeBeam.UltimateAuth.Server/Endpoints/ValidateEndpointHandler.cs b/src/CodeBeam.UltimateAuth.Server/Endpoints/ValidateEndpointHandler.cs index 1573959e..4e096cea 100644 --- a/src/CodeBeam.UltimateAuth.Server/Endpoints/ValidateEndpointHandler.cs +++ b/src/CodeBeam.UltimateAuth.Server/Endpoints/ValidateEndpointHandler.cs @@ -37,9 +37,9 @@ public async Task ValidateAsync(HttpContext context, CancellationToken { var auth = _authContext.Current; - if (auth.EffectiveMode == UAuthMode.PureJwt) + if (auth.EffectiveMode is UAuthMode.PureJwt or UAuthMode.SemiHybrid) { - return await ValidatePureJwtAsync(context); + return await ValidateJwtAsync(context); } var credential = await _credentialResolver.ResolveAsync(context, auth.EffectiveMode, auth.Response); @@ -141,11 +141,9 @@ public async Task ValidateAsync(HttpContext context, CancellationToken ); } - private static async Task ValidatePureJwtAsync( - HttpContext context) + private static async Task ValidateJwtAsync(HttpContext context) { - var result = await context.AuthenticateAsync( - UAuthConstants.SchemeDefaults.GlobalScheme); + var result = await context.AuthenticateAsync(UAuthConstants.SchemeDefaults.GlobalScheme); if (result.None) { @@ -157,8 +155,7 @@ private static async Task ValidatePureJwtAsync( statusCode: StatusCodes.Status401Unauthorized); } - if (!result.Succeeded || - result.Principal?.Identity?.IsAuthenticated != true) + if (!result.Succeeded || result.Principal?.Identity?.IsAuthenticated != true) { return Results.Json( new AuthValidationResult @@ -170,8 +167,7 @@ private static async Task ValidatePureJwtAsync( var principal = result.Principal; - var subject = principal - .FindFirst(ClaimTypes.NameIdentifier)?.Value; + var subject = principal.FindFirst(ClaimTypes.NameIdentifier)?.Value; if (!UserKey.TryParse(subject, null, out var userKey)) { @@ -183,10 +179,7 @@ private static async Task ValidatePureJwtAsync( statusCode: StatusCodes.Status401Unauthorized); } - var snapshot = PureJwtSnapshotFactory.Create( - principal, - userKey, - context.GetTenant()); + var snapshot = PureJwtSnapshotFactory.Create(principal, userKey, context.GetTenant()); return Results.Ok(new AuthValidationResult { diff --git a/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs b/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs index 14190aa6..81ae5578 100644 --- a/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs +++ b/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs @@ -7,7 +7,6 @@ using CodeBeam.UltimateAuth.Core.Extensions; using CodeBeam.UltimateAuth.Core.Infrastructure; using CodeBeam.UltimateAuth.Core.MultiTenancy; -using CodeBeam.UltimateAuth.Core.Options; using CodeBeam.UltimateAuth.Core.Runtime; using CodeBeam.UltimateAuth.Credentials; using CodeBeam.UltimateAuth.Credentials.Extensions; @@ -39,13 +38,10 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Cors.Infrastructure; using Microsoft.AspNetCore.Http; -using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.DependencyInjection.Extensions; using Microsoft.Extensions.Hosting; -using Microsoft.Extensions.Hosting.Internal; using Microsoft.Extensions.Options; -using Microsoft.IdentityModel.Tokens; namespace CodeBeam.UltimateAuth.Server.Extensions; @@ -82,6 +78,26 @@ public static IServiceCollection AddUltimateAuthServer(this IServiceCollection s return services; } + public static IServiceCollection AddUAuthHub(this IServiceCollection services, Action? configure = null) + { + services.PostConfigure(options => + { + configure?.Invoke(options.Hub); + }); + + services.TryAddSingleton(); + + services.TryAddScoped(); + services.TryAddScoped(); + services.TryAddScoped(); + + services.AddCors(); + + services.TryAddEnumerable(ServiceDescriptor.Singleton, UAuthHubCorsOptionsSetup>()); + + return services; + } + public static IServiceCollection AddUltimateAuthResourceApi(this IServiceCollection services, Action? configure = null, Action? configurePolicies = null) { ArgumentNullException.ThrowIfNull(services); @@ -468,27 +484,6 @@ internal static IServiceCollection AddAuthorizationInternal(IServiceCollection s return services; } - - public static IServiceCollection AddUAuthHub(this IServiceCollection services, Action? configure = null) - { - services.PostConfigure(options => - { - configure?.Invoke(options.Hub); - }); - - services.TryAddSingleton(); - - services.TryAddScoped(); - services.TryAddScoped(); - services.TryAddScoped(); - - services.AddCors(); - - services.TryAddEnumerable(ServiceDescriptor.Singleton, UAuthHubCorsOptionsSetup>()); - - return services; - } - private static IServiceCollection AddUltimateAuthResourceInternal(this IServiceCollection services) { // Resource API Specific @@ -573,7 +568,7 @@ private static IServiceCollection AddUltimateAuthResourceInternal(this IServiceC { var mode = sp.GetRequiredService().Mode; - if (mode == UAuthMode.PureJwt) + if (mode is UAuthMode.PureJwt or UAuthMode.SemiHybrid) return; var options = sp.GetRequiredService>().Value; diff --git a/src/CodeBeam.UltimateAuth.Server/Flows/Login/LoginOrchestrator.cs b/src/CodeBeam.UltimateAuth.Server/Flows/Login/LoginOrchestrator.cs index e4f07ad3..0801676d 100644 --- a/src/CodeBeam.UltimateAuth.Server/Flows/Login/LoginOrchestrator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Flows/Login/LoginOrchestrator.cs @@ -12,6 +12,7 @@ using CodeBeam.UltimateAuth.Server.Infrastructure; using CodeBeam.UltimateAuth.Users; using CodeBeam.UltimateAuth.Users.Contracts; +using static System.Runtime.InteropServices.JavaScript.JSType; // TODO: Identifier-based throttling, Exponential lockout @@ -333,17 +334,37 @@ public async Task LoginAsync(AuthFlowContext flow, LoginRequest req if (request.RequestTokens) { + var identifiers = flow.EffectiveMode == UAuthMode.SemiHybrid + ? await _primaryIdentifiers.GetAsync(flow.Tenant, userKey.Value, ct) + : null; + + var profile = flow.EffectiveMode == UAuthMode.SemiHybrid + ? await _userProfiles.GetAsync(flow.Tenant, userKey.Value, ProfileKey.Default, ct) + : null; + var tokenContext = new TokenIssuanceContext { Tenant = flow.Tenant, UserKey = userKey.Value, SessionId = issuedSession.Session.SessionId, SessionChainId = issuedSession.Session.ChainId, - Claims = claims + DeviceId = deviceId, + Claims = claims, + + PrimaryUserName = identifiers?.UserName, + DisplayName = profile?.DisplayName, + TimeZone = profile?.TimeZone, + AuthenticatedAt = now }; var accessToken = await _tokens.IssueAccessTokenAsync(flow, tokenContext, ct); + if (flow.EffectiveMode == UAuthMode.SemiHybrid && accessToken.Format != TokenFormat.Jwt) + { + throw new InvalidOperationException( + "SemiHybrid must issue a JWT access token."); + } + var refreshIssuance = await _tokens.IssueRefreshTokenAsync(flow, tokenContext, RefreshTokenPersistence.Persist, ct); tokens = new AuthTokens @@ -355,6 +376,16 @@ public async Task LoginAsync(AuthFlowContext flow, LoginRequest req await _events.DispatchAsync(new UserLoggedInContext(flow.Tenant, userKey.Value, now, flow.Device, issuedSession.Session.SessionId)); + if (flow.EffectiveMode == UAuthMode.SemiHybrid) + { + if (tokens?.AccessToken?.Format != TokenFormat.Jwt) + { + throw new InvalidOperationException("SemiHybrid login requires a JWT."); + } + + return LoginResult.Success(tokens); + } + return LoginResult.Success(issuedSession.Session.SessionId, tokens); } diff --git a/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/RefreshResponsePolicy.cs b/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/RefreshResponsePolicy.cs index 4b8c24e6..a1f6f186 100644 --- a/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/RefreshResponsePolicy.cs +++ b/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/RefreshResponsePolicy.cs @@ -1,6 +1,5 @@ using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; -using CodeBeam.UltimateAuth.Core.Options; using CodeBeam.UltimateAuth.Server.Auth; namespace CodeBeam.UltimateAuth.Server.Flows; @@ -12,18 +11,14 @@ public GrantKind SelectPrimary(AuthFlowContext flow, RefreshFlowRequest request, if (flow.EffectiveMode == UAuthMode.PureOpaque) return GrantKind.Session; - if (flow.EffectiveMode == UAuthMode.PureJwt) + if (flow.EffectiveMode is UAuthMode.PureJwt or UAuthMode.SemiHybrid) return GrantKind.AccessToken; if (!string.IsNullOrWhiteSpace(request.RefreshToken) && request.SessionId == null) - { return GrantKind.AccessToken; - } if (request.SessionId != null) - { return GrantKind.Session; - } if (flow.ApplicationProfile == UAuthApplicationProfile.Api) return GrantKind.AccessToken; diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Token/JwtPayloadGuard.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Token/JwtPayloadGuard.cs index d552597f..633da423 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Token/JwtPayloadGuard.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Token/JwtPayloadGuard.cs @@ -70,6 +70,17 @@ public static bool IsValid(string token) } } + if (property.Name is "sid" or "device_id") + { + if (property.Value.ValueKind != JsonValueKind.String) + return false; + + if (string.IsNullOrWhiteSpace(property.Value.GetString())) + { + return false; + } + } + if (property.Name is "exp" or "nbf" or "iat") { if (property.Value.ValueKind != JsonValueKind.Number || !property.Value.TryGetInt64(out _)) diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/User/UAuthUserAccessor.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/User/UAuthUserAccessor.cs index 95771ab7..9fdc66fe 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/User/UAuthUserAccessor.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/User/UAuthUserAccessor.cs @@ -37,7 +37,7 @@ public async Task ResolveAsync(HttpContext context) var profile = await _applicationProfileReader.ReadAsync(context); var mode = _effectiveOptions.GetEffective(context, profile).Mode; - if (mode == UAuthMode.PureJwt) + if (mode is UAuthMode.PureJwt or UAuthMode.SemiHybrid) { await ResolveJwtAsync(context); return; diff --git a/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs b/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs index 5bbe055c..53d9ec03 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs @@ -2,6 +2,7 @@ namespace CodeBeam.UltimateAuth.Server.Options; +// TODO: Check this class that it must not prevent the user from setting their own defaults. It should only set defaults for properties that are not set by the user. internal static class ConfigureDefaults { internal static void ApplyModeDefaults(UAuthMode effectiveMode, UAuthServerOptions options) @@ -59,7 +60,6 @@ private static void ApplyHybridDefaults(UAuthServerOptions options) token.IssueOpaque = true; cookie.Session.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); - cookie.RefreshToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); } @@ -73,7 +73,8 @@ private static void ApplySemiHybridDefaults(UAuthServerOptions options) session.TouchInterval = null; token.IssueJwt = true; - token.IssueOpaque = true; + token.IssueOpaque = false; + token.IssueRefresh = true; token.AddJwtIdClaim = true; cookie.AccessToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); diff --git a/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthResourceApiOptionsValidator.cs b/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthResourceApiOptionsValidator.cs index 91cf0a45..d34dc883 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthResourceApiOptionsValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthResourceApiOptionsValidator.cs @@ -97,13 +97,11 @@ public ValidateOptionsResult Validate(string? name, UAuthResourceApiOptions opti if (!Enum.IsDefined(auth.Device.MismatchBehavior)) errors.Add("Auth.Device.MismatchBehavior is invalid."); - if (mode == UAuthMode.PureJwt && auth.Device.MismatchBehavior == DeviceMismatchBehavior.AllowAndRebind) - { - errors.Add("PureJwt does not support device rebinding."); - } + if (mode is UAuthMode.PureJwt or UAuthMode.SemiHybrid && auth.Device.MismatchBehavior == DeviceMismatchBehavior.AllowAndRebind) + errors.Add("JWT authentication modes do not support device rebinding."); } - if (mode == UAuthMode.PureJwt) + if (mode is UAuthMode.PureJwt or UAuthMode.SemiHybrid) { if (auth.Jwt is null) { @@ -128,22 +126,17 @@ public ValidateOptionsResult Validate(string? name, UAuthResourceApiOptions opti errors.Add("Auth.Jwt.ClockSkew cannot be negative."); if (auth.Jwt.MaximumTokenSizeInBytes <= 0) - errors.Add( - "Auth.Jwt.MaximumTokenSizeInBytes must be positive."); + errors.Add("Auth.Jwt.MaximumTokenSizeInBytes must be positive."); } } - if (mode != UAuthMode.PureJwt) + if (mode is UAuthMode.PureOpaque or UAuthMode.Hybrid) { if (string.IsNullOrWhiteSpace(options.Hub?.BaseUrl)) { - errors.Add( - "Hub.BaseUrl is required for remote session validation."); + errors.Add("Hub.BaseUrl is required for remote session validation."); } - else if (!Uri.TryCreate( - options.Hub.BaseUrl, - UriKind.Absolute, - out var uri) || + else if (!Uri.TryCreate(options.Hub.BaseUrl, UriKind.Absolute, out var uri) || (uri.Scheme != Uri.UriSchemeHttps && uri.Scheme != Uri.UriSchemeHttp)) { diff --git a/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs b/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs index 69292f62..d9033689 100644 --- a/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs @@ -33,9 +33,6 @@ public async Task ValidateSessionAsync(SessionValidatio if (!session.IsOpaqueCredential) return SessionValidationResult.Invalid(SessionState.NotFound, sessionId: context.SessionId); - if (session is null) - return SessionValidationResult.Invalid(SessionState.NotFound, sessionId: context.SessionId); - var state = session.GetState(context.Now); if (state != SessionState.Active) return SessionValidationResult.Invalid(state, session.UserKey, session.SessionId, session.ChainId); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthJwtPrincipalFactoryTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthJwtPrincipalFactoryTests.cs new file mode 100644 index 00000000..ab7ec6ff --- /dev/null +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthJwtPrincipalFactoryTests.cs @@ -0,0 +1,137 @@ +using System.Security.Claims; +using AwesomeAssertions; +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Server.Authentication; +using CodeBeam.UltimateAuth.Server.Contracts; + +namespace CodeBeam.UltimateAuth.Tests.Unit.Server; + +public sealed class UAuthJwtPrincipalFactoryTests +{ + private const string SessionId = "metadata-session-identifier-1234567890"; + + private static readonly DeviceId Device = DeviceId.Create("test-device-1234567890"); + + [Theory] + [InlineData(UAuthMode.PureJwt, false, true)] + [InlineData(UAuthMode.PureJwt, true, false)] + [InlineData(UAuthMode.SemiHybrid, false, false)] + [InlineData(UAuthMode.SemiHybrid, true, true)] + public void TryCreate_EnforcesSessionClaimByMode(UAuthMode mode, bool includeSession, bool expected) + { + var token = CreateIdentity(includeSession); + + var success = UAuthJwtPrincipalFactory.TryCreate( + token, + mode, + DeviceMismatchBehavior.Reject, + Device, + "UltimateAuth", + out var principal); + + success.Should().Be(expected); + + if (expected) + { + principal.Should().NotBeNull(); + principal!.Identity!.IsAuthenticated + .Should().BeTrue(); + } + else + { + principal.Should().BeNull(); + } + } + + [Fact] + public void SemiHybrid_DuplicateSid_IsRejected() + { + var token = CreateIdentity(true) with + { + Claims = + [ + new Claim("sub", "user-123"), + new Claim("tenant", "single"), + new Claim("sid", SessionId), + new Claim("sid", SessionId), + new Claim("device_id", Device.Value) + ] + }; + + var success = UAuthJwtPrincipalFactory.TryCreate( + token, + UAuthMode.SemiHybrid, + DeviceMismatchBehavior.Allow, + null, + "UltimateAuth", + out _); + + success.Should().BeFalse(); + } + + [Fact] + public void SemiHybrid_DeviceMismatch_IsRejected() + { + var success = UAuthJwtPrincipalFactory.TryCreate( + CreateIdentity(true), + UAuthMode.SemiHybrid, + DeviceMismatchBehavior.Reject, + DeviceId.Create("another-device-1234567890"), + "UltimateAuth", + out _); + + success.Should().BeFalse(); + } + + [Fact] + public void SemiHybrid_DoesNotRequireDeviceHeader_WhenAllowed() + { + var success = UAuthJwtPrincipalFactory.TryCreate( + CreateIdentity(true), + UAuthMode.SemiHybrid, + DeviceMismatchBehavior.Allow, + null, + "UltimateAuth", + out _); + + success.Should().BeTrue(); + } + + [Fact] + public void SemiHybrid_RejectsDeviceRebinding() + { + var success = UAuthJwtPrincipalFactory.TryCreate( + CreateIdentity(true), + UAuthMode.SemiHybrid, + DeviceMismatchBehavior.AllowAndRebind, + Device, + "UltimateAuth", + out _); + + success.Should().BeFalse(); + } + + private static ValidatedJwtIdentity CreateIdentity(bool includeSession) + { + var claims = new List + { + new("sub", "user-123"), + new("tenant", "single"), + new("device_id", Device.Value) + }; + + if (includeSession) + claims.Add(new Claim("sid", SessionId)); + + return new ValidatedJwtIdentity + { + Subject = "user-123", + TenantId = "single", + Issuer = "https://issuer.example.com", + Audience = "test-audience", + ExpiresAt = DateTimeOffset.UtcNow.AddMinutes(5), + Claims = claims + }; + } +} From daa0ea29f79c41642af2cf8b6c5cf551cd55776f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Can=20Karag=C3=B6z?= Date: Tue, 1 Dec 2026 18:30:19 +0300 Subject: [PATCH 3/6] Refresh & Lineage Validation --- .../UAuthRefreshTokenValidator.cs | 3 + .../Abstractions/ISessionLineageValidator.cs | 9 ++ .../Extensions/ServiceCollectionExtensions.cs | 11 +- .../Services/RefreshFlowService.cs | 47 +------- .../Services/RefreshTokenRotationService.cs | 106 ++++++++++++++---- .../Services/SessionLineageValidator.cs | 95 ++++++++++++++++ .../Services/UAuthSessionValidator.cs | 75 +++---------- 7 files changed, 216 insertions(+), 130 deletions(-) create mode 100644 src/CodeBeam.UltimateAuth.Server/Abstractions/ISessionLineageValidator.cs create mode 100644 src/CodeBeam.UltimateAuth.Server/Services/SessionLineageValidator.cs diff --git a/src/CodeBeam.UltimateAuth.Core/Infrastructure/UAuthRefreshTokenValidator.cs b/src/CodeBeam.UltimateAuth.Core/Infrastructure/UAuthRefreshTokenValidator.cs index 67140f1f..afd62cdc 100644 --- a/src/CodeBeam.UltimateAuth.Core/Infrastructure/UAuthRefreshTokenValidator.cs +++ b/src/CodeBeam.UltimateAuth.Core/Infrastructure/UAuthRefreshTokenValidator.cs @@ -26,6 +26,9 @@ public async Task ValidateAsync(RefreshTokenValida if (stored is null) return RefreshTokenValidationResult.NotFound(); + if (stored.Tenant != context.Tenant) + return RefreshTokenValidationResult.Invalid(); + if (stored.IsExpired(context.Now)) return RefreshTokenValidationResult.Expired(stored); diff --git a/src/CodeBeam.UltimateAuth.Server/Abstractions/ISessionLineageValidator.cs b/src/CodeBeam.UltimateAuth.Server/Abstractions/ISessionLineageValidator.cs new file mode 100644 index 00000000..2ecd84f4 --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/Abstractions/ISessionLineageValidator.cs @@ -0,0 +1,9 @@ +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; + +namespace CodeBeam.UltimateAuth.Server.Abstractions; + +internal interface ISessionLineageValidator +{ + Task ValidateAsync(SessionValidationContext context, SessionCredentialPurpose expectedPurpose, CancellationToken ct = default); +} diff --git a/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs b/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs index 81ae5578..cbca9ae3 100644 --- a/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs +++ b/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs @@ -292,6 +292,7 @@ private static IServiceCollection AddUltimateAuthServerInternal(this IServiceCol services.TryAddScoped(); services.TryAddScoped(); + services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); @@ -300,14 +301,10 @@ private static IServiceCollection AddUltimateAuthServerInternal(this IServiceCol services.TryAddSingleton>(sp => { - var serverOptions = - sp.GetRequiredService>().Value; - - var signingProvider = - sp.GetRequiredService(); + var serverOptions = sp.GetRequiredService>().Value; + var signingProvider = sp.GetRequiredService(); - var signingKey = signingProvider.Resolve( - serverOptions.Token.KeyId); + var signingKey = signingProvider.Resolve(serverOptions.Token.KeyId); return Microsoft.Extensions.Options.Options.Create( new UAuthJwtValidationOptions diff --git a/src/CodeBeam.UltimateAuth.Server/Services/RefreshFlowService.cs b/src/CodeBeam.UltimateAuth.Server/Services/RefreshFlowService.cs index 62597a33..830ffc37 100644 --- a/src/CodeBeam.UltimateAuth.Server/Services/RefreshFlowService.cs +++ b/src/CodeBeam.UltimateAuth.Server/Services/RefreshFlowService.cs @@ -32,15 +32,12 @@ public async Task RefreshAsync(AuthFlowContext flow, RefreshF UAuthMode.PureOpaque => await HandleSessionOnlyAsync(flow, request, ct), - UAuthMode.PureJwt => + UAuthMode.PureJwt or UAuthMode.SemiHybrid => await HandleTokenOnlyAsync(flow, request, ct), UAuthMode.Hybrid => await HandleHybridAsync(flow, request, ct), - UAuthMode.SemiHybrid => - await HandleSemiHybridAsync(flow, request, ct), - _ => RefreshFlowResult.ReauthRequired() }; } @@ -164,46 +161,4 @@ private async Task HandleHybridAsync(AuthFlowContext flow, Re accessToken: rotation.Result.AccessToken, refreshToken: rotation.Result.RefreshToken); } - - private async Task HandleSemiHybridAsync(AuthFlowContext flow, RefreshFlowRequest request, CancellationToken ct) - { - if (request.SessionId is null || string.IsNullOrWhiteSpace(request.RefreshToken)) - return RefreshFlowResult.ReauthRequired(); - - var now = _clock.UtcNow; - - var validation = await _sessionValidator.ValidateSessionAsync( - new SessionValidationContext - { - Tenant = flow.Tenant, - SessionId = request.SessionId.Value, - Now = now, - Device = request.Device, - SessionOptions = flow.Options.Session - }, - ct); - - if (!validation.IsValid) - return RefreshFlowResult.ReauthRequired(); - - var rotation = await _tokenRotation.RotateAsync( - flow, - new RefreshTokenRotationContext - { - RefreshToken = request.RefreshToken!, - Now = now, - Device = request.Device, - ExpectedSessionId = request.SessionId.Value - }, - ct); - - if (!rotation.Result.IsSuccess) - return RefreshFlowResult.ReauthRequired(); - - return RefreshFlowResult.Success( - outcome: RefreshOutcome.Rotated, - sessionId: request.SessionId.Value, - accessToken: rotation.Result.AccessToken, - refreshToken: rotation.Result.RefreshToken); - } } diff --git a/src/CodeBeam.UltimateAuth.Server/Services/RefreshTokenRotationService.cs b/src/CodeBeam.UltimateAuth.Server/Services/RefreshTokenRotationService.cs index 2c326267..c3a67cf2 100644 --- a/src/CodeBeam.UltimateAuth.Server/Services/RefreshTokenRotationService.cs +++ b/src/CodeBeam.UltimateAuth.Server/Services/RefreshTokenRotationService.cs @@ -10,7 +10,7 @@ namespace CodeBeam.UltimateAuth.Server.Services; -public sealed class RefreshTokenRotationService : IRefreshTokenRotationService +internal sealed class RefreshTokenRotationService : IRefreshTokenRotationService { private readonly IRefreshTokenValidator _validator; private readonly IRefreshTokenStoreFactory _storeFactory; @@ -18,9 +18,10 @@ public sealed class RefreshTokenRotationService : IRefreshTokenRotationService private readonly IUserClaimsProvider _claimsProvider; private readonly IPrimaryUserIdentifierProvider _primaryIdentifiers; private readonly IUserProfileSnapshotProvider _userProfiles; + private readonly ISessionLineageValidator _lineageValidator; - public RefreshTokenRotationService(IRefreshTokenValidator validator, IRefreshTokenStoreFactory storeFactory, ITokenIssuer tokenIssuer, IUserClaimsProvider claimsProvider, IPrimaryUserIdentifierProvider primaryIdentifiers, IUserProfileSnapshotProvider userProfiles) + public RefreshTokenRotationService(IRefreshTokenValidator validator, IRefreshTokenStoreFactory storeFactory, ITokenIssuer tokenIssuer, IUserClaimsProvider claimsProvider, IPrimaryUserIdentifierProvider primaryIdentifiers, IUserProfileSnapshotProvider userProfiles, ISessionLineageValidator lineageValidator) { _validator = validator; _storeFactory = storeFactory; @@ -28,6 +29,7 @@ public RefreshTokenRotationService(IRefreshTokenValidator validator, IRefreshTok _claimsProvider = claimsProvider; _primaryIdentifiers = primaryIdentifiers; _userProfiles = userProfiles; + _lineageValidator = lineageValidator; } // TODO: Handle reuse detection and make flow knows situation, but don't make security branch. @@ -70,23 +72,18 @@ validation.UserKey is not UserKey userKey || var isPureJwt = flow.EffectiveMode == UAuthMode.PureJwt; - // Enforce mode-specific refresh token structure. - if (isPureJwt) - { - if (validation.SessionId is not null || - validation.SessionChainId is not null || - validation.DeviceId is null) - { - return Failed(); - } - } - else if (validation.SessionId is null) + if (validation.Tenant != flow.Tenant) + return Failed(); + + if (validation.RefreshChainId is not { } refreshChainId || refreshChainId.Value == Guid.Empty) { return Failed(); } - if (validation.RefreshChainId is not { } refreshChainId || refreshChainId.Value == Guid.Empty) + if (!await ValidateModeBindingAsync(flow, context, validation, ct)) + { return Failed(); + } var store = _storeFactory.Create(validation.Tenant); @@ -98,10 +95,7 @@ validation.SessionChainId is not null || var tokenContext = new TokenIssuanceContext { - Tenant = flow.Options.MultiTenant.Enabled - ? validation.Tenant - : TenantKey.Single, - + Tenant = validation.Tenant, UserKey = userKey, SessionId = validation.SessionId, SessionChainId = validation.SessionChainId, @@ -123,8 +117,32 @@ validation.SessionChainId is not null || var accessToken = await _tokenIssuer.IssueAccessTokenAsync(flow, tokenContext, ct); - // Consume the old token and persist its replacement - // within the same store execution scope. + if (flow.EffectiveMode is UAuthMode.PureJwt or UAuthMode.SemiHybrid) + { + if (accessToken.Format != TokenFormat.Jwt) + { + throw new InvalidOperationException("JWT authentication modes must issue JWT access tokens."); + } + } + + if (validation.State == RefreshTokenValidationState.Consumed) + { + if (validation.Tenant != flow.Tenant || !await ValidateModeBindingAsync(flow, context, validation, ct)) + { + return Failed(); + } + + var window = flow.Options.Token.RefreshTokenConcurrentRequestWindow; + + if (!IsLikelyConcurrentRequest(validation, context.Now, window)) + { + await HandleReplayAsync(validation, context.Now, ct); + } + + return Failed(); + } + + // Consume the old token and persist its replacement within the same store execution scope. var consumed = await store.ExecuteAsync( async transactionCt => { @@ -204,6 +222,54 @@ await store.ExecuteAsync( ct); } + private async Task ValidateModeBindingAsync(AuthFlowContext flow, RefreshTokenRotationContext context, RefreshTokenValidationResult validation, CancellationToken ct) + { + switch (flow.EffectiveMode) + { + case UAuthMode.PureJwt: + return validation.SessionId is null && + validation.SessionChainId is null && + validation.DeviceId is not null; + + case UAuthMode.Hybrid: + return validation.SessionId is not null && context.ExpectedSessionId == validation.SessionId; + + case UAuthMode.SemiHybrid: + if (validation.SessionId is not AuthSessionId sessionId || + validation.SessionChainId is not SessionChainId chainId || + validation.UserKey is not UserKey userKey || + validation.DeviceId is not DeviceId deviceId) + { + return false; + } + + if (context.Device.DeviceId != deviceId) + return false; + + var lineage = await _lineageValidator.ValidateAsync( + new SessionValidationContext + { + Tenant = flow.Tenant, + SessionId = sessionId, + Now = context.Now, + Device = context.Device, + SessionOptions = flow.Options.Session + }, + SessionCredentialPurpose.MetadataOnly, + ct); + + return lineage.IsValid && + lineage.Tenant == flow.Tenant && + lineage.UserKey == userKey && + lineage.SessionId == sessionId && + lineage.ChainId == chainId && + lineage.BoundDeviceId == deviceId; + + default: + return false; + } + } + private static bool IsLikelyConcurrentRequest(RefreshTokenValidationResult validation, DateTimeOffset now, TimeSpan window) { if (validation.State != RefreshTokenValidationState.Consumed) diff --git a/src/CodeBeam.UltimateAuth.Server/Services/SessionLineageValidator.cs b/src/CodeBeam.UltimateAuth.Server/Services/SessionLineageValidator.cs new file mode 100644 index 00000000..9a51646a --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/Services/SessionLineageValidator.cs @@ -0,0 +1,95 @@ +using CodeBeam.UltimateAuth.Core.Abstractions; +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Server.Abstractions; + +namespace CodeBeam.UltimateAuth.Server.Services; + +internal sealed class SessionLineageValidator : ISessionLineageValidator +{ + private readonly ISessionStoreFactory _storeFactory; + + public SessionLineageValidator(ISessionStoreFactory storeFactory) + { + _storeFactory = storeFactory; + } + + public async Task ValidateAsync(SessionValidationContext context, SessionCredentialPurpose expectedPurpose, CancellationToken ct = default) + { + var options = context.SessionOptions + ?? throw new InvalidOperationException("Session options are required for lineage validation."); + + var store = _storeFactory.Create(context.Tenant); + + var session = await store.GetSessionAsync(context.SessionId, ct); + + if (session is null || session.CredentialPurpose != expectedPurpose) + { + return SessionValidationResult.Invalid(SessionState.NotFound, sessionId: context.SessionId); + } + + if (session.Tenant != context.Tenant || session.SessionId != context.SessionId) + { + return SessionValidationResult.Invalid(SessionState.SecurityMismatch); + } + + var state = session.GetState(context.Now); + + if (state != SessionState.Active) + { + return SessionValidationResult.Invalid(state, session.UserKey, session.SessionId, session.ChainId); + } + + var chain = await store.GetChainAsync(session.ChainId, ct); + + if (chain is null || chain.IsRevoked) + { + return SessionValidationResult.Invalid(SessionState.Revoked, session.UserKey, session.SessionId, session.ChainId); + } + + var chainState = chain.GetState(context.Now, options.IdleTimeout); + + if (chainState != SessionState.Active) + { + return SessionValidationResult.Invalid(chainState, session.UserKey, session.SessionId, session.ChainId); + } + + if (chain.ChainId != session.ChainId || chain.Tenant != context.Tenant || chain.UserKey != session.UserKey) + { + return SessionValidationResult.Invalid(SessionState.SecurityMismatch); + } + + var root = await store.GetActiveRootByUserAsync(session.UserKey, ct); + + if (root is null || root.IsRevoked) + { + return SessionValidationResult.Invalid(SessionState.Revoked); + } + + if (root.RootId != chain.RootId || + root.Tenant != context.Tenant || + root.UserKey != session.UserKey || + root.SecurityVersion != session.SecurityVersionAtCreation) + { + return SessionValidationResult.Invalid(SessionState.SecurityMismatch); + } + + var deviceMismatch = + !chain.Device.HasDeviceId || + !context.Device.HasDeviceId || + !Equals(chain.Device.DeviceId, context.Device.DeviceId); + + var requireDeviceMatch = + expectedPurpose == SessionCredentialPurpose.MetadataOnly || + options.DeviceMismatchBehavior == DeviceMismatchBehavior.Reject; + + // TODO: Implement device mismatch behavior based on options, e.g., allow, reject or rebind. + if (deviceMismatch && requireDeviceMatch) + { + return SessionValidationResult.Invalid(SessionState.DeviceMismatch, session.UserKey, session.SessionId, chain.ChainId, root.RootId); + } + + return SessionValidationResult.Active(context.Tenant, session.UserKey, session.SessionId, chain.ChainId, root.RootId, + ClaimsSnapshot.Empty, session.CreatedAt, chain.Device.DeviceId); + } +} diff --git a/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs b/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs index d9033689..fc3cb6dd 100644 --- a/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs @@ -1,78 +1,39 @@ using CodeBeam.UltimateAuth.Core; -using CodeBeam.UltimateAuth.Core.Abstractions; using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Server.Abstractions; namespace CodeBeam.UltimateAuth.Server.Services; internal sealed class UAuthSessionValidator : ISessionValidator { - private readonly ISessionStoreFactory _storeFactory; + private readonly ISessionLineageValidator _lineageValidator; private readonly IUserClaimsProvider _claimsProvider; - public UAuthSessionValidator(ISessionStoreFactory storeFactory, IUserClaimsProvider claimsProvider) + public UAuthSessionValidator(ISessionLineageValidator lineageValidator, IUserClaimsProvider claimsProvider) { - _storeFactory = storeFactory; + _lineageValidator = lineageValidator; _claimsProvider = claimsProvider; } - // Validate runs before AuthFlowContext is set, do not call _authFlow here. - - // TODO: Add GetSessionAggregate store method to 1 call instead of 3 calls of root chain session public async Task ValidateSessionAsync(SessionValidationContext context, CancellationToken ct = default) { - var options = context.SessionOptions ?? throw new InvalidOperationException("Session options are required for local session validation."); - - var kernel = _storeFactory.Create(context.Tenant); - var session = await kernel.GetSessionAsync(context.SessionId, ct); - - if (session is null) - return SessionValidationResult.Invalid(SessionState.NotFound, sessionId: context.SessionId); - - // Metadata-only identifiers are not opaque credentials. - if (!session.IsOpaqueCredential) - return SessionValidationResult.Invalid(SessionState.NotFound, sessionId: context.SessionId); - - var state = session.GetState(context.Now); - if (state != SessionState.Active) - return SessionValidationResult.Invalid(state, session.UserKey, session.SessionId, session.ChainId); - - var chain = await kernel.GetChainAsync(session.ChainId, ct); - if (chain is null || chain.IsRevoked) - return SessionValidationResult.Invalid(SessionState.Revoked, session.UserKey, session.SessionId, session.ChainId); - - var chainState = chain.GetState(context.Now, options.IdleTimeout); - if (chainState != SessionState.Active) - return SessionValidationResult.Invalid(chainState, chain.UserKey, session.SessionId, chain.ChainId); - - //if (chain.ActiveSessionId != session.SessionId) - // return SessionValidationResult.Invalid(SessionState.SecurityMismatch, chain.UserKey, session.SessionId, chain.ChainId); - - if (chain.ChainId != session.ChainId) - return SessionValidationResult.Invalid(SessionState.SecurityMismatch, chain.UserKey, session.SessionId, chain.ChainId); - - if (chain.Tenant != context.Tenant) - return SessionValidationResult.Invalid(SessionState.SecurityMismatch, chain.UserKey, session.SessionId, chain.ChainId); - - var root = await kernel.GetActiveRootByUserAsync(session.UserKey, ct); - if (root is null || root.IsRevoked) - return SessionValidationResult.Invalid(SessionState.Revoked, chain.UserKey, session.SessionId, chain.ChainId, root?.RootId); - - if (chain.RootId != root.RootId) - return SessionValidationResult.Invalid(SessionState.SecurityMismatch, chain.UserKey, session.SessionId, chain.ChainId, root.RootId); - - if (session.SecurityVersionAtCreation != root.SecurityVersion) - return SessionValidationResult.Invalid(SessionState.SecurityMismatch, session.UserKey, session.SessionId, session.ChainId, root.RootId); - - // TODO: Implement device mismatch behavior based on options, e.g., allow, reject or rebind. - var deviceMismatch = !chain.Device.HasDeviceId || !context.Device.HasDeviceId || !Equals(chain.Device.DeviceId, context.Device.DeviceId); - - if (deviceMismatch && options.DeviceMismatchBehavior == DeviceMismatchBehavior.Reject) + var result = await _lineageValidator.ValidateAsync(context, SessionCredentialPurpose.Opaque, ct); + + if (!result.IsValid || + result.UserKey is not UserKey userKey || + result.SessionId is not AuthSessionId sessionId || + result.ChainId is not SessionChainId chainId || + result.RootId is not SessionRootId rootId || + result.AuthenticatedAt is not DateTimeOffset authenticatedAt) { - return SessionValidationResult.Invalid(SessionState.DeviceMismatch, chain.UserKey, session.SessionId, chain.ChainId, root.RootId); + return result.IsValid + ? SessionValidationResult.Invalid(SessionState.Invalid) + : result; } - var claims = await _claimsProvider.GetClaimsAsync(context.Tenant, session.UserKey, ct); - return SessionValidationResult.Active(context.Tenant, session.UserKey, session.SessionId, session.ChainId, root.RootId, claims, session.CreatedAt, chain.Device.DeviceId); + var claims = await _claimsProvider.GetClaimsAsync(context.Tenant, userKey, ct); + + return SessionValidationResult.Active(context.Tenant, userKey, sessionId, chainId, rootId, claims, authenticatedAt, result.BoundDeviceId, result.UserStatus); } } From e32bc0b508073f397aefc444a68aed7f944a335c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Can=20Karag=C3=B6z?= Date: Tue, 1 Dec 2026 20:04:18 +0300 Subject: [PATCH 4/6] Options Refactoring --- .../Options/UAuthSessionOptions.cs | 99 +++++-------------- .../Options/UAuthTokenOptions.cs | 43 ++++---- .../Issuers/UAuthTokenIssuer.cs | 10 +- .../Options/Defaults/ConfigureDefaults.cs | 28 +----- .../Options/UAuthServerOptions.cs | 15 +-- 5 files changed, 63 insertions(+), 132 deletions(-) rename src/{CodeBeam.UltimateAuth.Server => CodeBeam.UltimateAuth.Core}/Options/UAuthTokenOptions.cs (71%) diff --git a/src/CodeBeam.UltimateAuth.Core/Options/UAuthSessionOptions.cs b/src/CodeBeam.UltimateAuth.Core/Options/UAuthSessionOptions.cs index 1514da03..aeb8d2a8 100644 --- a/src/CodeBeam.UltimateAuth.Core/Options/UAuthSessionOptions.cs +++ b/src/CodeBeam.UltimateAuth.Core/Options/UAuthSessionOptions.cs @@ -4,7 +4,6 @@ namespace CodeBeam.UltimateAuth.Core.Options; // TODO: Add rotate on refresh (especially for Hybrid). Default behavior should be single session in chain for Hybrid, but can be configured. // And add RotateAsync method. -// Implement all options. /// /// Defines configuration settings that control the lifecycle, security behavior, and device constraints of UltimateAuth @@ -14,10 +13,7 @@ namespace CodeBeam.UltimateAuth.Core.Options; /// public sealed class UAuthSessionOptions { - /// - /// The standard lifetime of a session before it expires. - /// This is the duration added during login or refresh. - /// + [Obsolete("Use Token.SessionIdLifetime instead. This property has no effect and will be removed in a future version.")] public TimeSpan Lifetime { get; set; } = TimeSpan.FromDays(7); /// @@ -40,82 +36,42 @@ public sealed class UAuthSessionOptions /// public TimeSpan? IdleTimeout { get; set; } + // TODO: Implement this option on PureJwt mode. /// /// Minimum interval between LastSeenAt updates. /// Prevents excessive writes under high traffic. /// public TimeSpan? TouchInterval { get; set; } = TimeSpan.FromMinutes(5); - /// - /// Maximum number of device session chains a single user may have. - /// Set to zero to indicate no user-level chain limit. - /// - /// NOTE: - /// Enforcement is not active in v0.0.1. - /// This option is reserved for future security policies. - /// - public int MaxChainsPerUser { get; set; } = 0; - /// /// Maximum number of session rotations within a single chain. /// Used for cleanup, replay protection, and analytics. /// public int MaxSessionsPerChain { get; set; } = 100; - /// - /// Optional limit on the number of session chains allowed per platform - /// (e.g. "web" = 1, "mobile" = 1). - /// - /// NOTE: - /// Enforcement is not active in v0.0.1. - /// This option is reserved for future security policies. - /// - public Dictionary? MaxChainsPerPlatform { get; set; } - - /// - /// Defines platform categories that map multiple platforms - /// into a single abstract group (e.g. mobile: [ "ios", "android", "tablet" ]). - /// - /// NOTE: - /// Enforcement is not active in v0.0.1. - /// This option is reserved for future security policies. - /// - public Dictionary? PlatformCategories { get; set; } - - /// - /// Limits how many session chains can exist per platform category - /// (e.g. mobile = 1, desktop = 2). - /// - /// NOTE: - /// Enforcement is not active in v0.0.1. - /// This option is reserved for future security policies. - /// - public Dictionary? MaxChainsPerCategory { get; set; } - - /// - /// Enables binding sessions to the user's IP address. - /// When enabled, IP mismatches can invalidate a session. - /// - /// NOTE: - /// Enforcement is not active in v0.0.1. - /// This option is reserved for future security policies. - /// - public bool EnableIpBinding { get; set; } = false; - - /// - /// Enables binding sessions to the user's User-Agent header. - /// When enabled, UA mismatches can invalidate a session. - /// - /// NOTE: - /// Enforcement is not active in v0.0.1. - /// This option is reserved for future security policies. - /// - public bool EnableUserAgentBinding { get; set; } = false; + // TODO: Implement these. + ///// + ///// Enables binding sessions to the user's IP address. + ///// When enabled, IP mismatches can invalidate a session. + ///// + ///// NOTE: + ///// Enforcement is not active in v0.0.1. + ///// This option is reserved for future security policies. + ///// + //public bool EnableIpBinding { get; set; } = false; + + ///// + ///// Enables binding sessions to the user's User-Agent header. + ///// When enabled, UA mismatches can invalidate a session. + ///// + ///// NOTE: + ///// Enforcement is not active in v0.0.1. + ///// This option is reserved for future security policies. + ///// + //public bool EnableUserAgentBinding { get; set; } = false; /// - /// NOTE: - /// Enforcement is not active in v0.0.1. - /// This option is reserved for future security policies. + /// Gets or sets the behavior when an authentication session is used by a mismatched device. /// public DeviceMismatchBehavior DeviceMismatchBehavior { get; set; } = DeviceMismatchBehavior.Reject; @@ -123,16 +79,11 @@ public sealed class UAuthSessionOptions { SlidingExpiration = SlidingExpiration, IdleTimeout = IdleTimeout, - Lifetime = Lifetime, MaxLifetime = MaxLifetime, TouchInterval = TouchInterval, DeviceMismatchBehavior = DeviceMismatchBehavior, - MaxChainsPerUser = MaxChainsPerUser, MaxSessionsPerChain = MaxSessionsPerChain, - MaxChainsPerPlatform = MaxChainsPerPlatform is null ? null : new Dictionary(MaxChainsPerPlatform), - MaxChainsPerCategory = MaxChainsPerCategory is null ? null : new Dictionary(MaxChainsPerCategory), - PlatformCategories = PlatformCategories is null ? null : PlatformCategories.ToDictionary(kvp => kvp.Key, kvp => kvp.Value.ToArray()), - EnableIpBinding = EnableIpBinding, - EnableUserAgentBinding = EnableUserAgentBinding + //EnableIpBinding = EnableIpBinding, + //EnableUserAgentBinding = EnableUserAgentBinding }; } diff --git a/src/CodeBeam.UltimateAuth.Server/Options/UAuthTokenOptions.cs b/src/CodeBeam.UltimateAuth.Core/Options/UAuthTokenOptions.cs similarity index 71% rename from src/CodeBeam.UltimateAuth.Server/Options/UAuthTokenOptions.cs rename to src/CodeBeam.UltimateAuth.Core/Options/UAuthTokenOptions.cs index 84b5e583..c6545ec2 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/UAuthTokenOptions.cs +++ b/src/CodeBeam.UltimateAuth.Core/Options/UAuthTokenOptions.cs @@ -1,4 +1,4 @@ -namespace CodeBeam.UltimateAuth.Server.Options; +namespace CodeBeam.UltimateAuth.Core.Options; /// /// Configuration settings for access and refresh token behavior @@ -7,28 +7,39 @@ /// public sealed class UAuthTokenOptions { - /// - /// Determines whether JWT-format access tokens should be issued. - /// Recommended for APIs that rely on claims-based authorization. - /// + [Obsolete("Credential format is determined by the authentication mode.")] public bool IssueJwt { get; set; } = true; - /// - /// Determines whether opaque tokens (session-id based) should be issued. - /// Useful for high-security APIs where token introspection is required. - /// + [Obsolete("Credential format is determined by the authentication mode.")] public bool IssueOpaque { get; set; } = true; - public bool IssueRefresh { get; set; } = true; + [Obsolete("Use IssueRefreshToken instead.")] + public bool IssueRefresh + { + get => IssueRefreshToken; + set => IssueRefreshToken = value; + } + + [Obsolete("JWT ID claims are generated automatically.")] + public bool AddJwtIdClaim { get; set; } = true; + + public bool IssueRefreshToken { get; set; } = true; + + /// + /// Lifetime of a session identified by a session ID. + /// Applies to both opaque and metadata-only sessions. Has no effect on PureJwt mode, which does not use session IDs. + /// + public TimeSpan SessionIdLifetime { get; set; } = TimeSpan.FromDays(7); /// /// Lifetime of access tokens (JWT or opaque). - /// Short lifetimes improve security but require more frequent refreshes. + /// Short lifetimes improve security but require more frequent refreshes. Has no effect on PureOpaque mode, which uses session id instead of access tokens. /// public TimeSpan AccessTokenLifetime { get; set; } = TimeSpan.FromMinutes(10); /// /// Lifetime of refresh tokens, used in PKCE or session rotation flows. + /// Has no effect on PureOpaque mode, which does not use refresh tokens. /// public TimeSpan RefreshTokenLifetime { get; set; } = TimeSpan.FromDays(7); @@ -58,12 +69,6 @@ public sealed class UAuthTokenOptions /// public string Audience { get; set; } = "UAuthClient"; - /// - /// If true, adds a unique 'jti' (JWT ID) claim to each issued JWT. - /// Useful for token replay detection and advanced auditing. - /// - public bool AddJwtIdClaim { get; set; } = false; - /// /// Optional key identifier to select signing key. /// If null, default key will be used. @@ -72,15 +77,11 @@ public sealed class UAuthTokenOptions internal UAuthTokenOptions Clone() => new() { - IssueOpaque = IssueOpaque, - IssueJwt = IssueJwt, - IssueRefresh = IssueRefresh, AccessTokenLifetime = AccessTokenLifetime, RefreshTokenLifetime = RefreshTokenLifetime, OpaqueIdBytes = OpaqueIdBytes, Issuer = Issuer, Audience = Audience, - AddJwtIdClaim = AddJwtIdClaim, KeyId = KeyId, RefreshTokenConcurrentRequestWindow = RefreshTokenConcurrentRequestWindow }; diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthTokenIssuer.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthTokenIssuer.cs index 76266da5..b777a553 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthTokenIssuer.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthTokenIssuer.cs @@ -2,9 +2,9 @@ using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Defaults; using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Core.Options; using CodeBeam.UltimateAuth.Server.Abstractions; using CodeBeam.UltimateAuth.Server.Auth; -using CodeBeam.UltimateAuth.Server.Options; namespace CodeBeam.UltimateAuth.Server.Infrastructure; @@ -67,7 +67,7 @@ context.SessionChainId is null && public async Task IssueRefreshTokenAsync(AuthFlowContext flow, TokenIssuanceContext context, RefreshTokenPersistence persistence, CancellationToken ct = default) { - if (flow.EffectiveMode == UAuthMode.PureOpaque || !flow.Options.Token.IssueRefresh) + if (flow.EffectiveMode == UAuthMode.PureOpaque || !flow.Options.Token.IssueRefreshToken) { return null; } @@ -172,8 +172,7 @@ UAuthJwtProfileClaims.AuthenticatedAt or : values.ToArray(); } - // UltimateAuth-owned identity/security claims must never be overridable - // by caller-provided claims. + // UltimateAuth-owned identity/security claims must never be overridable by caller-provided claims. claims["sub"] = context.UserKey.Value; claims["tenant"] = context.Tenant.Value; @@ -211,8 +210,7 @@ UAuthJwtProfileClaims.AuthenticatedAt or else claims.Remove("sid"); - if (tokens.AddJwtIdClaim) - claims["jti"] = _opaqueGenerator.GenerateJwtId(); + claims["jti"] = _opaqueGenerator.GenerateJwtId(); var descriptor = new UAuthJwtTokenDescriptor { diff --git a/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs b/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs index 53d9ec03..d6c07c4f 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs @@ -38,12 +38,9 @@ private static void ApplyPureOpaqueDefaults(UAuthServerOptions options) session.IdleTimeout ??= TimeSpan.FromDays(7); session.TouchInterval ??= TimeSpan.FromDays(1); - session.MaxLifetime ??= null; - token.IssueJwt = false; - token.IssueOpaque = false; - token.IssueRefresh = false; + token.IssueRefreshToken = false; cookie.Session.Lifetime.IdleBuffer = TimeSpan.FromDays(2); } @@ -54,11 +51,6 @@ private static void ApplyHybridDefaults(UAuthServerOptions options) var token = options.Token; var cookie = options.Cookie; - session.TouchInterval = null; - - token.IssueJwt = true; - token.IssueOpaque = true; - cookie.Session.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); cookie.RefreshToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); } @@ -69,13 +61,7 @@ private static void ApplySemiHybridDefaults(UAuthServerOptions options) var token = options.Token; var cookie = options.Cookie; - session.SlidingExpiration = false; - session.TouchInterval = null; - - token.IssueJwt = true; - token.IssueOpaque = false; - token.IssueRefresh = true; - token.AddJwtIdClaim = true; + token.IssueRefreshToken = true; cookie.AccessToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); cookie.RefreshToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); @@ -87,19 +73,11 @@ private static void ApplyPureJwtDefaults(UAuthServerOptions options) var token = options.Token; var cookie = options.Cookie; - // PureJwt does not use server-side sessions. - session.SlidingExpiration = false; session.TouchInterval = null; - session.IdleTimeout = null; - session.MaxLifetime = null; - token.IssueJwt = true; - token.IssueOpaque = false; - token.IssueRefresh = true; - token.AddJwtIdClaim = true; + token.IssueRefreshToken = true; cookie.AccessToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); - cookie.RefreshToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); } } diff --git a/src/CodeBeam.UltimateAuth.Server/Options/UAuthServerOptions.cs b/src/CodeBeam.UltimateAuth.Server/Options/UAuthServerOptions.cs index 7f2e8b52..d6fd0c08 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/UAuthServerOptions.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/UAuthServerOptions.cs @@ -15,7 +15,6 @@ namespace CodeBeam.UltimateAuth.Server.Options; /// public sealed class UAuthServerOptions { - // ------------------------------------------------------- // CORE OPTION COMPOSITION // (Server must NOT duplicate Core options) @@ -26,6 +25,11 @@ public sealed class UAuthServerOptions /// public UAuthSessionOptions Session { get; set; } = new(); + /// + /// Token issuing behavior (lifetimes, refresh policies). + /// + public UAuthTokenOptions Token { get; set; } = new(); + /// /// Multi-tenancy behavior (resolver, normalization, etc.) Fully defined in Core. /// @@ -45,15 +49,14 @@ public sealed class UAuthServerOptions // SERVER-ONLY BEHAVIOR // ------------------------------------------------------- - public UAuthLoginOptions Login { get; set; } = new(); - /// - /// Token issuing behavior (lifetimes, refresh policies). + /// Gets or sets the server login options. /// - public UAuthTokenOptions Token { get; set; } = new(); + /// This property is used only in server-side authentication behavior. + public UAuthLoginOptions Login { get; set; } = new(); /// - /// PKCE configuration (required for WASM). + /// PKCE configuration (required for client applications like WASM). /// public UAuthPkceOptions Pkce { get; set; } = new(); From 461457afd9c137593c7de3afdef5f3d69a57a4d2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Can=20Karag=C3=B6z?= Date: Tue, 1 Dec 2026 21:07:44 +0300 Subject: [PATCH 5/6] Arrange New Options Design --- .../LabSessionDiagnosticsPolicyService.cs | 3 +- .../Session/SessionIssuanceContext.cs | 1 + .../Session/SessionRotationContext.cs | 1 + .../Contracts/Token/TokenIssuanceContext.cs | 1 + .../Flows/Login/LoginOrchestrator.cs | 8 +- .../Issuers/UAuthSessionIssuer.cs | 17 ++- .../Options/Defaults/ConfigureDefaults.cs | 6 - .../Validators/UAuthServerOptionsValidator.cs | 4 +- .../UAuthServerSessionOptionsValidator.cs | 22 ++-- .../UAuthServerTokenOptionsValidator.cs | 41 ++++--- .../Services/RefreshFlowService.cs | 4 +- .../Services/RefreshTokenRotationService.cs | 2 +- .../Services/SessionLineageValidator.cs | 19 ++- .../DeviceLimitPostgresTests.cs | 5 +- .../RefreshTests.cs | 8 +- .../SessionSlidingExpirationTests.cs | 8 +- .../EffectiveServerOptionsProviderTests.cs | 47 +------- .../Server/LoginOrchestratorTests.cs | 2 +- .../RefreshTokenRotationServiceTests.cs | 45 +++++-- .../Server/ServerOptionsValidatorTests.cs | 110 +++++++++--------- .../Server/UAuthSessionValidatorTests.cs | 8 +- .../Sessions/DeviceLimitAdmissionTests.cs | 7 +- .../Sessions/UAuthSessionIssuerTests.cs | 36 +++--- .../Tokens/UAuthTokenIssuerTests.cs | 23 ++-- 24 files changed, 212 insertions(+), 216 deletions(-) diff --git a/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Services/LabSessionDiagnosticsPolicyService.cs b/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Services/LabSessionDiagnosticsPolicyService.cs index 592fb970..ac9ce64b 100644 --- a/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Services/LabSessionDiagnosticsPolicyService.cs +++ b/apps/identity-lab/CodeBeam.UltimateAuth.IdentityLab/Services/LabSessionDiagnosticsPolicyService.cs @@ -25,10 +25,11 @@ public sealed class LabSessionDiagnosticsPolicyService(IOptions /// Optional chain identifier. diff --git a/src/CodeBeam.UltimateAuth.Core/Contracts/Session/SessionRotationContext.cs b/src/CodeBeam.UltimateAuth.Core/Contracts/Session/SessionRotationContext.cs index 9543328d..44b74831 100644 --- a/src/CodeBeam.UltimateAuth.Core/Contracts/Session/SessionRotationContext.cs +++ b/src/CodeBeam.UltimateAuth.Core/Contracts/Session/SessionRotationContext.cs @@ -15,4 +15,5 @@ public sealed record SessionRotationContext public required SessionMetadata Metadata { get; init; } = SessionMetadata.Empty; public required UAuthMode Mode { get; init; } public required UAuthSessionOptions SessionOptions { get; init; } + public required UAuthTokenOptions TokenOptions { get; init; } } diff --git a/src/CodeBeam.UltimateAuth.Core/Contracts/Token/TokenIssuanceContext.cs b/src/CodeBeam.UltimateAuth.Core/Contracts/Token/TokenIssuanceContext.cs index ec3da9f2..dbb3aed6 100644 --- a/src/CodeBeam.UltimateAuth.Core/Contracts/Token/TokenIssuanceContext.cs +++ b/src/CodeBeam.UltimateAuth.Core/Contracts/Token/TokenIssuanceContext.cs @@ -1,5 +1,6 @@ using CodeBeam.UltimateAuth.Core.Domain; using CodeBeam.UltimateAuth.Core.MultiTenancy; +using CodeBeam.UltimateAuth.Core.Options; namespace CodeBeam.UltimateAuth.Core.Contracts; diff --git a/src/CodeBeam.UltimateAuth.Server/Flows/Login/LoginOrchestrator.cs b/src/CodeBeam.UltimateAuth.Server/Flows/Login/LoginOrchestrator.cs index 0801676d..c684d2ac 100644 --- a/src/CodeBeam.UltimateAuth.Server/Flows/Login/LoginOrchestrator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Flows/Login/LoginOrchestrator.cs @@ -12,7 +12,6 @@ using CodeBeam.UltimateAuth.Server.Infrastructure; using CodeBeam.UltimateAuth.Users; using CodeBeam.UltimateAuth.Users.Contracts; -using static System.Runtime.InteropServices.JavaScript.JSType; // TODO: Identifier-based throttling, Exponential lockout @@ -274,7 +273,7 @@ public async Task LoginAsync(AuthFlowContext flow, LoginRequest req PrimaryUserName = identifiers?.UserName, DisplayName = profile?.DisplayName, TimeZone = profile?.TimeZone, - AuthenticatedAt = now + AuthenticatedAt = now, }; var accessToken = await _tokens.IssueAccessTokenAsync(flow, tokenContext, ct); @@ -313,7 +312,8 @@ public async Task LoginAsync(AuthFlowContext flow, LoginRequest req ChainId = chainId, Metadata = SessionMetadata.Empty, Mode = flow.EffectiveMode, - SessionOptions = flow.Options.Session + SessionOptions = flow.Options.Session, + TokenOptions = flow.Options.Token }; var authContext = flow.ToAuthContext(now); @@ -354,7 +354,7 @@ public async Task LoginAsync(AuthFlowContext flow, LoginRequest req PrimaryUserName = identifiers?.UserName, DisplayName = profile?.DisplayName, TimeZone = profile?.TimeZone, - AuthenticatedAt = now + AuthenticatedAt = now, }; var accessToken = await _tokens.IssueAccessTokenAsync(flow, tokenContext, ct); diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs index 8e3b726b..800b8e04 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs @@ -67,7 +67,7 @@ UAuthMode.PureOpaque or UAuthMode.Hybrid ? now.Add(max) : (DateTimeOffset?)null; - var sessionExpiresAt = now.Add(sessionOptions.Lifetime); + var sessionExpiresAt = now.Add(context.TokenOptions.SessionIdLifetime); if (absoluteExpiresAt is { } absolute && sessionExpiresAt > absolute) sessionExpiresAt = absolute; @@ -268,14 +268,6 @@ public async Task RotateSessionAsync(SessionRotationContext conte if (!AuthSessionId.TryCreate(opaqueSessionId, out var newSessionId)) throw new InvalidCastException("Can't create opaque session id."); - var expiresAt = now.Add(sessionOptions.Lifetime); - if (sessionOptions.MaxLifetime is not null) - { - var absoluteExpiry = now.Add(sessionOptions.MaxLifetime.Value); - if (absoluteExpiry < expiresAt) - expiresAt = absoluteExpiry; - } - IssuedSession? issued = null; await kernel.ExecuteAsync(async _ => @@ -307,8 +299,13 @@ await kernel.ExecuteAsync(async _ => throw new SecurityException("Chain does not belong to the current user/tenant."); if (chain.RootId != root.RootId) - { throw new SecurityException("Chain does not belong to the active session root."); + + var expiresAt = now.Add(context.TokenOptions.SessionIdLifetime); + + if (chain.AbsoluteExpiresAt is { } absolute && expiresAt > absolute) + { + expiresAt = absolute; } var newSessionUnbound = UAuthSession.Create( diff --git a/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs b/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs index d6c07c4f..0a7032a6 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/Defaults/ConfigureDefaults.cs @@ -40,8 +40,6 @@ private static void ApplyPureOpaqueDefaults(UAuthServerOptions options) session.TouchInterval ??= TimeSpan.FromDays(1); session.MaxLifetime ??= null; - token.IssueRefreshToken = false; - cookie.Session.Lifetime.IdleBuffer = TimeSpan.FromDays(2); } @@ -61,8 +59,6 @@ private static void ApplySemiHybridDefaults(UAuthServerOptions options) var token = options.Token; var cookie = options.Cookie; - token.IssueRefreshToken = true; - cookie.AccessToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); cookie.RefreshToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); } @@ -75,8 +71,6 @@ private static void ApplyPureJwtDefaults(UAuthServerOptions options) session.TouchInterval = null; - token.IssueRefreshToken = true; - cookie.AccessToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); cookie.RefreshToken.Lifetime.IdleBuffer = TimeSpan.FromMinutes(5); } diff --git a/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthServerOptionsValidator.cs b/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthServerOptionsValidator.cs index 2940b71f..54df44c6 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthServerOptionsValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthServerOptionsValidator.cs @@ -73,9 +73,9 @@ allowedModes is null || if (anySessionModeAllowed) { - if (options.Session.Lifetime <= TimeSpan.Zero) + if (options.Token.SessionIdLifetime <= TimeSpan.Zero) { - return ValidateOptionsResult.Fail("Session.Lifetime must be greater than zero."); + return ValidateOptionsResult.Fail("Token.SessionIdLifetime must be greater than zero."); } if (options.Session.MaxLifetime is { } maxLifetime) diff --git a/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthServerSessionOptionsValidator.cs b/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthServerSessionOptionsValidator.cs index 8b7baf0b..a328eeba 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthServerSessionOptionsValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthServerSessionOptionsValidator.cs @@ -8,28 +8,34 @@ public ValidateOptionsResult Validate(string? name, UAuthServerOptions options) { var errors = new List(); var session = options.Session; + var sessionLifetime = options.Token.SessionIdLifetime; - if (session.Lifetime <= TimeSpan.Zero) - errors.Add("Session.Lifetime must be greater than zero."); + if (sessionLifetime <= TimeSpan.Zero) + errors.Add("Token.SessionIdLifetime must be greater than zero."); if (session.MaxLifetime.HasValue && session.MaxLifetime <= TimeSpan.Zero) + { errors.Add("Session.MaxLifetime must be greater than zero when specified."); + } - if (session.MaxLifetime.HasValue && session.MaxLifetime < session.Lifetime) - errors.Add("Session.MaxLifetime must be greater than or equal to Session.Lifetime."); + if (session.MaxLifetime.HasValue && session.MaxLifetime < sessionLifetime) + { + errors.Add("Session.MaxLifetime must be greater than or equal to Token.SessionIdLifetime."); + } if (session.IdleTimeout.HasValue && session.IdleTimeout < TimeSpan.Zero) + { errors.Add("Session.IdleTimeout cannot be negative."); + } - if (options.Session.IdleTimeout is { } idle && options.Session.TouchInterval is { } touch && idle > TimeSpan.Zero && touch >= idle) + if (session.IdleTimeout is { } idle && session.TouchInterval is { } touch && idle > TimeSpan.Zero && touch >= idle) { errors.Add("Session.TouchInterval must be less than Session.IdleTimeout."); } - if (session.SlidingExpiration && session.TouchInterval is { } touchInterval && touchInterval >= session.Lifetime) + if (session.SlidingExpiration && session.TouchInterval is { } touchInterval && touchInterval >= sessionLifetime) { - errors.Add( - "Session.TouchInterval must be less than Session.Lifetime when SlidingExpiration is enabled."); + errors.Add("Session.TouchInterval must be less than Token.SessionIdLifetime when SlidingExpiration is enabled."); } return errors.Count == 0 diff --git a/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthServerTokenOptionsValidator.cs b/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthServerTokenOptionsValidator.cs index fe445470..b7ad2c5d 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthServerTokenOptionsValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthServerTokenOptionsValidator.cs @@ -9,42 +9,47 @@ public ValidateOptionsResult Validate(string? name, UAuthServerOptions options) var errors = new List(); var tokens = options.Token; - if (options.Token.RefreshTokenConcurrentRequestWindow < TimeSpan.Zero) + if (tokens.SessionIdLifetime <= TimeSpan.Zero) { - errors.Add("Token.RefreshTokenConcurrentRequestWindow cannot be negative."); + errors.Add("Token.SessionIdLifetime must be greater than zero."); } - if (!tokens.IssueJwt && !tokens.IssueOpaque) - errors.Add("Token: At least one of IssueJwt or IssueOpaque must be enabled."); - if (tokens.AccessTokenLifetime <= TimeSpan.Zero) + { errors.Add("Token.AccessTokenLifetime must be greater than zero."); + } - if (tokens.IssueRefresh) + if (tokens.RefreshTokenConcurrentRequestWindow < TimeSpan.Zero) + { + errors.Add("Token.RefreshTokenConcurrentRequestWindow cannot be negative."); + } + + if (tokens.IssueRefreshToken) { if (tokens.RefreshTokenLifetime <= TimeSpan.Zero) - errors.Add("Token.RefreshTokenLifetime must be greater than zero when IssueRefresh is enabled."); + { + errors.Add("Token.RefreshTokenLifetime must be greater than zero when refresh tokens are enabled."); + } if (tokens.RefreshTokenLifetime <= tokens.AccessTokenLifetime) + { errors.Add("Token.RefreshTokenLifetime must be greater than Token.AccessTokenLifetime."); + } } - if (tokens.IssueJwt) + if (string.IsNullOrWhiteSpace(tokens.Issuer) || tokens.Issuer.Trim().Length < 3) { - if (string.IsNullOrWhiteSpace(tokens.Issuer) || tokens.Issuer.Trim().Length < 3) - errors.Add("Token.Issuer must be at least 3 characters when IssueJwt is enabled."); - - if (string.IsNullOrWhiteSpace(tokens.Audience) || tokens.Audience.Trim().Length < 3) - errors.Add("Token.Audience must be at least 3 characters when IssueJwt is enabled."); + errors.Add("Token.Issuer must be at least 3 characters."); } - if (tokens.IssueOpaque) + if (string.IsNullOrWhiteSpace(tokens.Audience) || tokens.Audience.Trim().Length < 3) { - if (tokens.OpaqueIdBytes < 24) - errors.Add("Token.OpaqueIdBytes must be at least 24 bytes (192-bit entropy)."); + errors.Add("Token.Audience must be at least 3 characters."); + } - if (tokens.OpaqueIdBytes > 128) - errors.Add("Token.OpaqueIdBytes must not exceed 128 bytes."); + if (tokens.OpaqueIdBytes is < 24 or > 128) + { + errors.Add("Token.OpaqueIdBytes must be between 24 and 128 bytes."); } return errors.Count == 0 diff --git a/src/CodeBeam.UltimateAuth.Server/Services/RefreshFlowService.cs b/src/CodeBeam.UltimateAuth.Server/Services/RefreshFlowService.cs index 830ffc37..f7035dd7 100644 --- a/src/CodeBeam.UltimateAuth.Server/Services/RefreshFlowService.cs +++ b/src/CodeBeam.UltimateAuth.Server/Services/RefreshFlowService.cs @@ -66,7 +66,7 @@ private async Task HandleSessionOnlyAsync(AuthFlowContext flo var touchPolicy = new SessionTouchPolicy { TouchInterval = flow.Options.Session.TouchInterval, - Lifetime = flow.Options.Session.Lifetime, + Lifetime = flow.Options.Token.SessionIdLifetime, SlidingExpiration = flow.Options.Session.SlidingExpiration, IdleTimeout = flow.Options.Session.IdleTimeout }; @@ -129,7 +129,7 @@ private async Task HandleHybridAsync(AuthFlowContext flow, Re var touchPolicy = new SessionTouchPolicy { TouchInterval = flow.Options.Session.TouchInterval, - Lifetime = flow.Options.Session.Lifetime, + Lifetime = flow.Options.Token.SessionIdLifetime, SlidingExpiration = flow.Options.Session.SlidingExpiration, IdleTimeout = flow.Options.Session.IdleTimeout }; diff --git a/src/CodeBeam.UltimateAuth.Server/Services/RefreshTokenRotationService.cs b/src/CodeBeam.UltimateAuth.Server/Services/RefreshTokenRotationService.cs index c3a67cf2..7dbff855 100644 --- a/src/CodeBeam.UltimateAuth.Server/Services/RefreshTokenRotationService.cs +++ b/src/CodeBeam.UltimateAuth.Server/Services/RefreshTokenRotationService.cs @@ -35,7 +35,7 @@ public RefreshTokenRotationService(IRefreshTokenValidator validator, IRefreshTok // TODO: Handle reuse detection and make flow knows situation, but don't make security branch. public async Task RotateAsync(AuthFlowContext flow, RefreshTokenRotationContext context, CancellationToken ct = default) { - if (flow.EffectiveMode == UAuthMode.PureOpaque || !flow.Options.Token.IssueRefresh) + if (flow.EffectiveMode == UAuthMode.PureOpaque || !flow.Options.Token.IssueRefreshToken) { return Failed(); } diff --git a/src/CodeBeam.UltimateAuth.Server/Services/SessionLineageValidator.cs b/src/CodeBeam.UltimateAuth.Server/Services/SessionLineageValidator.cs index 9a51646a..8e956863 100644 --- a/src/CodeBeam.UltimateAuth.Server/Services/SessionLineageValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Services/SessionLineageValidator.cs @@ -61,17 +61,32 @@ public async Task ValidateAsync(SessionValidationContex var root = await store.GetActiveRootByUserAsync(session.UserKey, ct); - if (root is null || root.IsRevoked) + if (root is null) { return SessionValidationResult.Invalid(SessionState.Revoked); } + if (root.IsRevoked) + { + return SessionValidationResult.Invalid( + SessionState.Revoked, + session.UserKey, + session.SessionId, + session.ChainId, + root.RootId); + } + if (root.RootId != chain.RootId || root.Tenant != context.Tenant || root.UserKey != session.UserKey || root.SecurityVersion != session.SecurityVersionAtCreation) { - return SessionValidationResult.Invalid(SessionState.SecurityMismatch); + return SessionValidationResult.Invalid( + SessionState.SecurityMismatch, + session.UserKey, + session.SessionId, + session.ChainId, + root.RootId); } var deviceMismatch = diff --git a/tests/CodeBeam.UltimateAuth.Tests.Integration.EfCore/DeviceLimitPostgresTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Integration.EfCore/DeviceLimitPostgresTests.cs index 4b4537fa..0f924939 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Integration.EfCore/DeviceLimitPostgresTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Integration.EfCore/DeviceLimitPostgresTests.cs @@ -189,8 +189,11 @@ private static async Task IssueAsync( Mode = UAuthMode.Hybrid, SessionOptions = new UAuthSessionOptions { - Lifetime = TimeSpan.FromHours(8), MaxSessionsPerChain = 20 + }, + TokenOptions = new UAuthTokenOptions + { + SessionIdLifetime = TimeSpan.FromHours(8) } }; diff --git a/tests/CodeBeam.UltimateAuth.Tests.Integration/RefreshTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Integration/RefreshTests.cs index cbb3beb4..3d555f5c 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Integration/RefreshTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Integration/RefreshTests.cs @@ -1584,7 +1584,7 @@ public async Task Refresh_Hybrid_WhenSessionExpired_ShouldReturnUnauthorized() { await using var factory = AuthServerFactory.Create(options => { - options.Session.Lifetime = TimeSpan.FromMinutes(30); + options.Token.SessionIdLifetime = TimeSpan.FromMinutes(30); options.Session.MaxLifetime = TimeSpan.FromDays(7); options.Token.RefreshTokenLifetime = TimeSpan.FromDays(7); }); @@ -1629,7 +1629,7 @@ public async Task Refresh_Hybrid_WhenChainIdleTimeoutExceeded_ShouldReturnUnauth { await using var factory = AuthServerFactory.Create(options => { - options.Session.Lifetime = TimeSpan.FromDays(7); + options.Token.SessionIdLifetime = TimeSpan.FromDays(7); options.Session.MaxLifetime = TimeSpan.FromDays(7); options.Session.IdleTimeout = TimeSpan.FromMinutes(30); options.Token.RefreshTokenLifetime = TimeSpan.FromDays(7); @@ -1674,7 +1674,7 @@ public async Task Refresh_Hybrid_JustBeforeChainIdleTimeout_ShouldSucceed() { await using var factory = AuthServerFactory.Create(options => { - options.Session.Lifetime = TimeSpan.FromDays(7); + options.Token.SessionIdLifetime = TimeSpan.FromDays(7); options.Session.MaxLifetime = TimeSpan.FromDays(7); options.Session.IdleTimeout = TimeSpan.FromMinutes(30); options.Token.RefreshTokenLifetime = TimeSpan.FromDays(7); @@ -1720,7 +1720,7 @@ public async Task Refresh_Hybrid_AtChainIdleTimeout_ShouldReturnUnauthorized() { await using var factory = AuthServerFactory.Create(options => { - options.Session.Lifetime = TimeSpan.FromDays(7); + options.Token.SessionIdLifetime = TimeSpan.FromDays(7); options.Session.MaxLifetime = TimeSpan.FromDays(7); options.Session.IdleTimeout = TimeSpan.FromMinutes(30); options.Token.RefreshTokenLifetime = TimeSpan.FromDays(7); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Integration/SessionSlidingExpirationTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Integration/SessionSlidingExpirationTests.cs index 89545c72..f340733a 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Integration/SessionSlidingExpirationTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Integration/SessionSlidingExpirationTests.cs @@ -126,7 +126,7 @@ public async Task IdentifierGet_ExpiredIdleSession_ShouldReturnUnauthorized(stri { using var factory = AuthServerFactory.Create(o => { - o.Session.Lifetime = TimeSpan.FromMinutes(5); + o.Token.SessionIdLifetime = TimeSpan.FromMinutes(5); o.Session.MaxLifetime = null; o.Session.IdleTimeout = TimeSpan.FromSeconds(10); o.Session.TouchInterval = TimeSpan.FromSeconds(5); @@ -420,7 +420,7 @@ public async Task ZeroIdleTimeout_RefreshShouldRemainValidBeforeSessionExpiry(st { await using var factory = AuthServerFactory.Create(o => { - o.Session.Lifetime = TimeSpan.FromHours(1); + o.Token.SessionIdLifetime = TimeSpan.FromHours(1); o.Session.MaxLifetime = null; o.Session.IdleTimeout = TimeSpan.Zero; o.Session.TouchInterval = TimeSpan.FromMinutes(5); @@ -442,7 +442,7 @@ private static AuthServerFactory CreateFactory(bool sliding, TimeSpan? maxLifeti { var factory = AuthServerFactory.Create(o => { - o.Session.Lifetime = TimeSpan.FromDays(4); + o.Token.SessionIdLifetime = TimeSpan.FromDays(4); o.Session.SlidingExpiration = sliding; o.Session.MaxLifetime = maxLifetime; o.Session.IdleTimeout = null; @@ -540,7 +540,7 @@ private static AuthServerFactory CreateIdleSlidingFactory() { var factory = AuthServerFactory.Create(o => { - o.Session.Lifetime = TimeSpan.FromHours(1); + o.Token.SessionIdLifetime = TimeSpan.FromHours(1); o.Session.MaxLifetime = null; o.Session.SlidingExpiration = true; o.Session.IdleTimeout = TimeSpan.FromMinutes(30); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs index 9e57fa33..a178f9a2 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs @@ -100,30 +100,6 @@ public void Effective_options_should_apply_defaults_for_each_auth_mode(UAuthMode effective.Options.Should().NotBeSameAs(original); } - [Fact] - public void SemiHybrid_should_apply_expected_session_defaults() - { - var original = new UAuthServerOptions - { - Session = - { - SlidingExpiration = true, - TouchInterval = TimeSpan.FromMinutes(5) - } - }; - - var provider = CreateProviderForMode(original, UAuthMode.SemiHybrid); - - var effective = provider.GetEffective(TenantKey.Single, UAuthApplicationProfile.BlazorServer); - - effective.Options.Session.SlidingExpiration.Should().BeFalse(); - effective.Options.Session.TouchInterval.Should().BeNull(); - - // The original configuration must remain unchanged. - original.Session.SlidingExpiration.Should().BeTrue(); - original.Session.TouchInterval.Should().Be(TimeSpan.FromMinutes(5)); - } - [Fact] public void SemiHybrid_should_apply_expected_token_defaults() { @@ -131,9 +107,6 @@ public void SemiHybrid_should_apply_expected_token_defaults() { Token = { - IssueJwt = false, - IssueOpaque = false, - AddJwtIdClaim = false, AccessTokenLifetime = TimeSpan.FromHours(1), RefreshTokenLifetime = TimeSpan.FromHours(2) } @@ -147,9 +120,6 @@ public void SemiHybrid_should_apply_expected_token_defaults() var token = effective.Options.Token; - token.IssueJwt.Should().BeTrue(); - token.IssueOpaque.Should().BeTrue(); - token.AddJwtIdClaim.Should().BeTrue(); token.AccessTokenLifetime.Should().Be(TimeSpan.FromHours(1)); token.RefreshTokenLifetime.Should().Be(TimeSpan.FromHours(2)); } @@ -193,12 +163,7 @@ public void PureOpaque_should_initialize_missing_optional_session_defaults() effective.Options.Session.IdleTimeout.Should().Be(TimeSpan.FromDays(7)); effective.Options.Session.TouchInterval.Should().Be(TimeSpan.FromDays(1)); effective.Options.Session.MaxLifetime.Should().BeNull(); - effective.Options.Session.DeviceMismatchBehavior - .Should().Be(DeviceMismatchBehavior.Reject); - - effective.Options.Token.IssueJwt.Should().BeFalse(); - effective.Options.Token.IssueOpaque.Should().BeFalse(); - effective.Options.Token.IssueRefresh.Should().BeFalse(); + effective.Options.Session.DeviceMismatchBehavior.Should().Be(DeviceMismatchBehavior.Reject); effective.Options.Cookie.Session.Lifetime.IdleBuffer .Should().Be(TimeSpan.FromDays(2)); @@ -245,10 +210,8 @@ public void Hybrid_should_apply_expected_defaults() var options = effective.Options; options.Session.SlidingExpiration.Should().BeTrue(); - options.Session.TouchInterval.Should().BeNull(); + options.Session.TouchInterval.Should().Be(TimeSpan.FromMinutes(5)); - options.Token.IssueJwt.Should().BeTrue(); - options.Token.IssueOpaque.Should().BeTrue(); options.Token.AccessTokenLifetime.Should().Be(TimeSpan.FromMinutes(10)); options.Token.RefreshTokenLifetime.Should().Be(TimeSpan.FromDays(7)); @@ -284,14 +247,8 @@ public void PureJwt_should_apply_stateless_defaults() var options = effective.Options; - options.Session.SlidingExpiration.Should().BeFalse(); - options.Session.IdleTimeout.Should().BeNull(); - options.Session.MaxLifetime.Should().BeNull(); options.Session.TouchInterval.Should().BeNull(); - options.Token.IssueJwt.Should().BeTrue(); - options.Token.IssueOpaque.Should().BeFalse(); - options.Token.AddJwtIdClaim.Should().BeTrue(); options.Token.AccessTokenLifetime.Should().Be(TimeSpan.FromMinutes(10)); options.Token.RefreshTokenLifetime.Should().Be(TimeSpan.FromDays(7)); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/LoginOrchestratorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/LoginOrchestratorTests.cs index 70b26d7b..5b01ee46 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/LoginOrchestratorTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/LoginOrchestratorTests.cs @@ -940,7 +940,7 @@ public async Task PureJwt_commit_without_token_request_should_reject_early() TestContext.Current.CancellationToken); var exception = await act.Should().ThrowAsync(); - exception.Which.Code.Should().Be("pure_jwt_requires_token_delivery"); + exception.Which.Code.Should().Be("jwt_mode_requires_token_delivery"); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshTokenRotationServiceTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshTokenRotationServiceTests.cs index 4cab4673..ba39ef3e 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshTokenRotationServiceTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshTokenRotationServiceTests.cs @@ -4,11 +4,9 @@ using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; using CodeBeam.UltimateAuth.Core.MultiTenancy; -using CodeBeam.UltimateAuth.Core.Options; using CodeBeam.UltimateAuth.Server.Abstractions; using CodeBeam.UltimateAuth.Server.Auth; using CodeBeam.UltimateAuth.Server.Infrastructure; -using CodeBeam.UltimateAuth.Server.Options; using CodeBeam.UltimateAuth.Server.Services; using CodeBeam.UltimateAuth.Tests.Unit.Helpers; using CodeBeam.UltimateAuth.Users; @@ -464,7 +462,7 @@ public async Task RotateAsync_SingleTenant_UsesSingleTenantForIssuance() public async Task RotateAsync_RefreshDisabled_SkipsValidationAndStore() { var test = new Fixture(UAuthMode.PureJwt); - test.Flow.Options.Token.IssueRefresh = false; + test.Flow.Options.Token.IssueRefreshToken = false; AssertFailed(await test.RotateAsync()); test.Validator.VerifyNoOtherCalls(); @@ -518,6 +516,8 @@ private sealed class Fixture public Mock Claims { get; } = new(); public Mock Identifiers { get; } = new(); public Mock Profiles { get; } = new(); + public Mock LineageValidator { get; } = new(); + public AccessToken AccessToken { get; } = new() { Token = "access-token", @@ -536,7 +536,7 @@ public Fixture(UAuthMode mode, TenantKey? tenant = null, bool multiTenant = fals Tenant = tenant ?? TenantKey.Single; var options = TestServerOptions.Default(); options.MultiTenant.Enabled = multiTenant; - options.Token.IssueRefresh = true; + options.Token.IssueRefreshToken = true; Flow = new AuthFlowContext( flowType: AuthFlowType.RefreshSession, @@ -596,17 +596,43 @@ public RefreshToken CreateToken(bool? sessionFree = null) createdAt: AuthenticatedAt, expiresAt: Now.AddDays(7), refreshChainId: RefreshChainId.New(), - deviceId: noSession ? TestDevice.Default().DeviceId : null, + deviceId: noSession || Flow.EffectiveMode == UAuthMode.SemiHybrid + ? TestDevice.Default().DeviceId + : null, authenticatedAt: AuthenticatedAt); } public void Validate(RefreshToken token) - => SetValidation(RefreshTokenValidationResult.Valid(token, token.TokenHash)); + { + SetValidation( + RefreshTokenValidationResult.Valid(token, token.TokenHash)); + + if (Flow.EffectiveMode == UAuthMode.SemiHybrid && + token.SessionId is AuthSessionId sessionId && + token.SessionChainId is SessionChainId chainId) + { + LineageValidator + .Setup(x => x.ValidateAsync( + It.Is(c => + c.Tenant == Tenant && + c.SessionId == sessionId), + SessionCredentialPurpose.MetadataOnly, + It.IsAny())) + .ReturnsAsync(SessionValidationResult.Active( + Tenant, + User, + sessionId, + chainId, + SessionRootId.New(), + ClaimsSnapshot.Empty, + AuthenticatedAt, + token.DeviceId)); + } + } public void SetValidation(RefreshTokenValidationResult validation) { - Validator.Setup(x => x.ValidateAsync( - It.IsAny(), It.IsAny())) + Validator.Setup(x => x.ValidateAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(validation); } @@ -658,7 +684,8 @@ public Task RotateAsync(AuthSessionId? expectedSe Issuer.Object, Claims.Object, Identifiers.Object, - Profiles.Object); + Profiles.Object, + LineageValidator.Object); return service.RotateAsync( Flow, diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/ServerOptionsValidatorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/ServerOptionsValidatorTests.cs index b87a4575..58ac6440 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/ServerOptionsValidatorTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/ServerOptionsValidatorTests.cs @@ -1,7 +1,6 @@ using AwesomeAssertions; using CodeBeam.UltimateAuth.Core.Domain; using CodeBeam.UltimateAuth.Core.Extensions; -using CodeBeam.UltimateAuth.Core.Options; using CodeBeam.UltimateAuth.Server.Extensions; using CodeBeam.UltimateAuth.Server.Options; using Microsoft.Extensions.Configuration; @@ -53,7 +52,7 @@ public void Valid_server_session_options_should_pass() services.AddUltimateAuthServer(o => { - o.Session.Lifetime = TimeSpan.FromMinutes(30); + o.Token.SessionIdLifetime = TimeSpan.FromMinutes(30); o.Session.IdleTimeout = TimeSpan.FromMinutes(10); o.Cryptography.JwtSigningKey = @@ -66,16 +65,10 @@ public void Valid_server_session_options_should_pass() services.AddOptions().ValidateOnStart(); using var provider = services.BuildServiceProvider(); + var options = provider.GetRequiredService>().Value; - var options = provider - .GetRequiredService>() - .Value; - - options.Session.Lifetime.Should() - .Be(TimeSpan.FromMinutes(30)); - - options.Session.IdleTimeout.Should() - .Be(TimeSpan.FromMinutes(10)); + options.Token.SessionIdLifetime.Should().Be(TimeSpan.FromMinutes(30)); + options.Session.IdleTimeout.Should().Be(TimeSpan.FromMinutes(10)); } [Fact] @@ -87,7 +80,6 @@ public void Server_token_options_with_small_opaque_id_should_fail() services.AddUltimateAuth(); services.AddUltimateAuthServer(o => { - o.Token.IssueOpaque = true; o.Token.OpaqueIdBytes = 8; }); @@ -112,8 +104,6 @@ public void Valid_server_token_options_should_pass() services.AddUltimateAuth(); services.AddUltimateAuthServer(o => { - o.Token.IssueJwt = true; - o.Token.IssueOpaque = true; o.Token.AccessTokenLifetime = TimeSpan.FromMinutes(5); o.Token.RefreshTokenLifetime = TimeSpan.FromDays(1); o.Token.OpaqueIdBytes = 32; @@ -551,8 +541,8 @@ public void Pkce_positive_authorization_lifetime_passes() => [InlineData(0)] [InlineData(-1)] public void Session_nonpositive_lifetime_fails(int ticks) => - ShouldReject(o => o.Session.Lifetime = TimeSpan.FromTicks(ticks), - "Session.Lifetime"); + ShouldReject(o => o.Token.SessionIdLifetime = TimeSpan.FromTicks(ticks), + "Token.SessionIdLifetime"); [Fact] public void Session_nonpositive_max_lifetime_fails() => @@ -563,7 +553,7 @@ public void Session_nonpositive_max_lifetime_fails() => public void Session_max_lifetime_less_than_lifetime_fails() => ShouldReject(o => { - o.Session.Lifetime = TimeSpan.FromMinutes(30); + o.Token.SessionIdLifetime = TimeSpan.FromMinutes(30); o.Session.MaxLifetime = TimeSpan.FromMinutes(29); }, "Session.MaxLifetime"); @@ -571,7 +561,7 @@ public void Session_max_lifetime_less_than_lifetime_fails() => public void Session_equal_max_lifetime_passes() => ShouldAccept(o => { - o.Session.Lifetime = TimeSpan.FromMinutes(30); + o.Token.SessionIdLifetime = TimeSpan.FromMinutes(30); o.Session.MaxLifetime = TimeSpan.FromMinutes(30); o.Session.IdleTimeout = TimeSpan.Zero; }); @@ -590,14 +580,6 @@ public void Token_negative_concurrent_refresh_window_fails() => o.Token.RefreshTokenConcurrentRequestWindow = TimeSpan.FromTicks(-1), "RefreshTokenConcurrentRequestWindow"); - [Fact] - public void Token_no_issuance_fails_under_current_validator() => - ShouldReject(o => - { - o.Token.IssueJwt = false; - o.Token.IssueOpaque = false; - }, "IssueJwt or IssueOpaque"); - [Fact] public void Token_nonpositive_access_lifetime_fails() => ShouldReject(o => o.Token.AccessTokenLifetime = TimeSpan.Zero, @@ -607,7 +589,7 @@ public void Token_nonpositive_access_lifetime_fails() => public void Token_nonpositive_refresh_lifetime_fails_when_enabled() => ShouldReject(o => { - o.Token.IssueRefresh = true; + o.Token.IssueRefreshToken = true; o.Token.RefreshTokenLifetime = TimeSpan.Zero; }, "RefreshTokenLifetime"); @@ -615,20 +597,19 @@ public void Token_nonpositive_refresh_lifetime_fails_when_enabled() => public void Token_refresh_lifetime_equal_to_access_lifetime_fails() => ShouldReject(o => { - o.Token.IssueRefresh = true; + o.Token.IssueRefreshToken = true; o.Token.AccessTokenLifetime = TimeSpan.FromMinutes(10); o.Token.RefreshTokenLifetime = TimeSpan.FromMinutes(10); }, "RefreshTokenLifetime"); [Theory] - [InlineData(true, " ", "UAuthClient", "Token.Issuer")] - [InlineData(true, "ab", "UAuthClient", "Token.Issuer")] - [InlineData(true, "UAuth", " ", "Token.Audience")] - [InlineData(true, "UAuth", "ab", "Token.Audience")] - public void Token_invalid_jwt_identifiers_fail(bool issueJwt, string issuer, string audience, string expected) => + [InlineData(" ", "UAuthClient", "Token.Issuer")] + [InlineData("ab", "UAuthClient", "Token.Issuer")] + [InlineData("UAuth", " ", "Token.Audience")] + [InlineData("UAuth", "ab", "Token.Audience")] + public void Token_invalid_jwt_identifiers_fail(string issuer, string audience, string expected) => ShouldReject(o => { - o.Token.IssueJwt = issueJwt; o.Token.Issuer = issuer; o.Token.Audience = audience; }, expected); @@ -640,7 +621,6 @@ public void Token_invalid_jwt_identifiers_fail(bool issueJwt, string issuer, str public void Token_opaque_entropy_outside_limits_fails(int bytes) => ShouldReject(o => { - o.Token.IssueOpaque = true; o.Token.OpaqueIdBytes = bytes; }, "OpaqueIdBytes"); @@ -650,25 +630,14 @@ public void Token_opaque_entropy_outside_limits_fails(int bytes) => public void Token_opaque_entropy_boundary_values_pass(int bytes) => ShouldAccept(o => { - o.Token.IssueOpaque = true; o.Token.OpaqueIdBytes = bytes; }); - [Fact] - public void Token_jwt_fields_are_not_required_when_jwt_disabled() => - ShouldAccept(o => - { - o.Token.IssueJwt = false; - o.Token.IssueOpaque = true; - o.Token.Issuer = ""; - o.Token.Audience = ""; - }); - [Fact] public void Token_refresh_lifetime_is_not_checked_when_refresh_disabled() => ShouldAccept(o => { - o.Token.IssueRefresh = false; + o.Token.IssueRefreshToken = false; o.Token.RefreshTokenLifetime = TimeSpan.Zero; }); @@ -712,7 +681,7 @@ public void Pagination_multiple_errors_are_reported() => private static void ConfigureValidCrossOptions(UAuthServerOptions o) { o.AllowedModes = new[] { UAuthMode.Hybrid }; - o.Session.Lifetime = TimeSpan.FromDays(7); + o.Token.SessionIdLifetime = TimeSpan.FromDays(7); o.Session.MaxLifetime = TimeSpan.FromDays(10); o.Token.AccessTokenLifetime = TimeSpan.FromMinutes(10); o.Token.RefreshTokenLifetime = TimeSpan.FromDays(7); @@ -783,8 +752,8 @@ public void Server_session_lifetime_nonpositive_fails() => ShouldReject(o => { ConfigureValidCrossOptions(o); - o.Session.Lifetime = TimeSpan.Zero; - }, "Session.Lifetime"); + o.Token.SessionIdLifetime = TimeSpan.Zero; + }, "Token.SessionIdLifetime"); [Fact] public void Server_session_max_lifetime_nonpositive_fails() => @@ -825,17 +794,15 @@ public void Server_null_session_max_lifetime_passes_under_current_rules() => [Theory] [InlineData(1, 5)] [InlineData(5, 5)] - public void Session_sliding_expiration_touch_interval_greater_than_or_equal_to_lifetime_fails( - int lifetimeMinutes, - int touchIntervalMinutes) => + public void Session_sliding_expiration_touch_interval_greater_than_or_equal_to_lifetime_fails(int lifetimeMinutes, int touchIntervalMinutes) => ShouldReject(o => { o.Session.SlidingExpiration = true; - o.Session.Lifetime = TimeSpan.FromMinutes(lifetimeMinutes); + o.Token.SessionIdLifetime = TimeSpan.FromMinutes(lifetimeMinutes); o.Session.TouchInterval = TimeSpan.FromMinutes(touchIntervalMinutes); o.Session.IdleTimeout = null; o.Session.MaxLifetime = null; - }, "Session.TouchInterval must be less than Session.Lifetime"); + }, "Session.TouchInterval must be less than Token.SessionIdLifetime"); [Fact] @@ -843,13 +810,44 @@ public void Session_sliding_expiration_touch_interval_less_than_lifetime_passes( ShouldAccept(o => { o.Session.SlidingExpiration = true; - o.Session.Lifetime = TimeSpan.FromMinutes(5); + o.Token.SessionIdLifetime = TimeSpan.FromMinutes(5); o.Session.TouchInterval = TimeSpan.FromMinutes(1); o.Session.IdleTimeout = null; o.Session.MaxLifetime = null; }); + [Theory] + [InlineData(0)] + [InlineData(-1)] + public void Token_session_id_lifetime_must_be_positive( + int ticks) + { + ShouldReject( + o => o.Token.SessionIdLifetime = TimeSpan.FromTicks(ticks), "Token.SessionIdLifetime"); + } + [Fact] + public void Refresh_can_be_disabled_without_selecting_token_format() + { + ShouldAccept( + o => + { + o.Token.IssueRefreshToken = false; + o.Token.RefreshTokenLifetime = TimeSpan.Zero; + }); + } + + [Fact] + public void Token_format_is_not_configured_separately() + { + ShouldAccept( + o => + { + o.AuthMode = UAuthMode.PureJwt; + o.Token.AccessTokenLifetime = + TimeSpan.FromMinutes(10); + }); + } private static void ShouldReject(Action configure, string expected) diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthSessionValidatorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthSessionValidatorTests.cs index 40a5e331..73abfe01 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthSessionValidatorTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthSessionValidatorTests.cs @@ -722,9 +722,9 @@ private static Fixture CreateFixture( options.Session.IdleTimeout = idleTimeout; options.Session.DeviceMismatchBehavior = deviceMismatchBehavior; - var sut = new UAuthSessionValidator( - storeFactory.Object, - claimsProvider.Object); + var lineageValidator = new SessionLineageValidator(storeFactory.Object); + + var sut = new UAuthSessionValidator(lineageValidator, claimsProvider.Object); var context = new SessionValidationContext { @@ -757,4 +757,4 @@ private sealed record Fixture( UAuthSessionChain Chain, UAuthSession Session, SessionValidationContext Context); -} \ No newline at end of file +} diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/DeviceLimitAdmissionTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/DeviceLimitAdmissionTests.cs index 09c188e2..4366fa75 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/DeviceLimitAdmissionTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/DeviceLimitAdmissionTests.cs @@ -21,10 +21,14 @@ public sealed class DeviceLimitAdmissionTests private static readonly UAuthSessionOptions SessionOptions = new() { - Lifetime = TimeSpan.FromHours(8), MaxSessionsPerChain = 20 }; + private static readonly UAuthTokenOptions TokenOptions = new() + { + SessionIdLifetime = TimeSpan.FromHours(8) + }; + [Fact] public async Task RejectNewLogin_WhenGlobalLimitReached_KeepsExistingSessionActive() { @@ -426,6 +430,7 @@ private static SessionIssuanceContext Context( Metadata = SessionMetadata.Empty, Mode = UAuthMode.Hybrid, SessionOptions = SessionOptions, + TokenOptions = TokenOptions, ChainId = chainId }; diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/UAuthSessionIssuerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/UAuthSessionIssuerTests.cs index dd54a772..ea72bc4b 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/UAuthSessionIssuerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/UAuthSessionIssuerTests.cs @@ -54,8 +54,7 @@ await act.Should() [Fact] public async Task IssueSessionAsync_WhenOpaqueGeneratorReturnsInvalidId_ShouldFailBeforeStoreAccess() { - var fixture = CreateFixture( - opaqueToken: "invalid"); + var fixture = CreateFixture(opaqueToken: "invalid"); var context = CreateIssuanceContext(fixture); @@ -1682,8 +1681,7 @@ private static Fixture CreateFixture( var options = new UAuthServerOptions(); - options.Session.Lifetime = - lifetime ?? Lifetime; + options.Token.SessionIdLifetime = lifetime ?? Lifetime; options.Session.MaxLifetime = maxLifetime; @@ -1702,34 +1700,25 @@ private static Fixture CreateFixture( storeFactory, store, tokenGenerator, - options.Session); + options.Session, + options.Token); } // ===================================================================== // Setup helpers // ===================================================================== - private static void SetupNewIssuance( - Fixture fixture, - SessionIssuanceContext context) + private static void SetupNewIssuance(Fixture fixture, SessionIssuanceContext context) { - var root = - CreateRoot( - context.Tenant, - context.UserKey); + var root = CreateRoot(context.Tenant, context.UserKey); - SetupRoot( - fixture, - context.UserKey, - root); + SetupRoot(fixture, context.UserKey, root); SetupEmptySessions(fixture); SetupSessionAndChainPersistence(fixture); } - private static RotationSetup SetupSuccessfulRotation( - Fixture fixture, - SessionRotationContext context) + private static RotationSetup SetupSuccessfulRotation(Fixture fixture, SessionRotationContext context) { var root = CreateRoot( @@ -1884,7 +1873,8 @@ private static SessionIssuanceContext CreateIssuanceContext(Fixture fixture, Use Metadata = SessionMetadata.Empty, Mode = mode, ChainId = chainId, - SessionOptions = fixture.SessionOptions + SessionOptions = fixture.SessionOptions, + TokenOptions = fixture.TokenOptions }; } @@ -1902,7 +1892,8 @@ private static SessionRotationContext CreateRotationContext(Fixture fixture, UAu Claims = ClaimsSnapshot.Empty, Metadata = SessionMetadata.Empty, Mode = mode, - SessionOptions = fixture.SessionOptions + SessionOptions = fixture.SessionOptions, + TokenOptions = fixture.TokenOptions }; } @@ -1963,5 +1954,6 @@ private sealed record Fixture( Mock StoreFactory, Mock Store, Mock TokenGenerator, - UAuthSessionOptions SessionOptions); + UAuthSessionOptions SessionOptions, + UAuthTokenOptions TokenOptions); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Tokens/UAuthTokenIssuerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Tokens/UAuthTokenIssuerTests.cs index 7dca927b..d84df266 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Tokens/UAuthTokenIssuerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Tokens/UAuthTokenIssuerTests.cs @@ -304,8 +304,7 @@ public async Task IssueAccessTokenAsync_WhenJwtIdEnabled_ShouldGenerateJti() var fixture = CreateFixture(); var flow = CreateFlow( - UAuthMode.PureJwt, - addJwtIdClaim: true); + UAuthMode.PureJwt); UAuthJwtTokenDescriptor? captured = null; @@ -337,8 +336,7 @@ public async Task IssueAccessTokenAsync_WhenJwtIdDisabled_ShouldNotGenerateJti() var fixture = CreateFixture(); var flow = CreateFlow( - UAuthMode.PureJwt, - addJwtIdClaim: false); + UAuthMode.PureJwt); UAuthJwtTokenDescriptor? captured = null; @@ -947,7 +945,7 @@ public async Task IssueAccessTokenAsync_WhenClaimsAreEmpty_ShouldOnlyIncludeFram { var fixture = CreateFixture(); - var flow = CreateFlow(UAuthMode.PureJwt, addJwtIdClaim: false); + var flow = CreateFlow(UAuthMode.PureJwt); var context = CreateTokenContext(sessionId: null, claims: ClaimsSnapshot.Empty); @@ -989,8 +987,7 @@ public async Task IssueAccessTokenAsync_WhenCustomClaimIsReserved_ShouldIgnoreIt var fixture = CreateFixture(); var flow = CreateFlow( - UAuthMode.PureJwt, - addJwtIdClaim: false); + UAuthMode.PureJwt); var context = CreateTokenContext( sessionId: null, @@ -1082,8 +1079,7 @@ public async Task IssueAccessTokenAsync_WhenCustomJtiExists_ShouldUseGeneratedJt var fixture = CreateFixture(); var flow = CreateFlow( - UAuthMode.PureJwt, - addJwtIdClaim: true); + UAuthMode.PureJwt); var context = CreateTokenContext( claims: ClaimsSnapshot.From( @@ -1112,8 +1108,7 @@ public async Task IssueAccessTokenAsync_WhenJwtIdDisabled_ShouldRejectCustomJti( var fixture = CreateFixture(); var flow = CreateFlow( - UAuthMode.PureJwt, - addJwtIdClaim: false); + UAuthMode.PureJwt); var context = CreateTokenContext( claims: ClaimsSnapshot.From( @@ -1198,7 +1193,7 @@ public async Task IssueRefreshTokenAsync_WhenIssueRefreshDisabled_ShouldReturnNu var fixture = CreateFixture(); var flow = CreateFlow(mode); - flow.Options.Token.IssueRefresh = false; + flow.Options.Token.IssueRefreshToken = false; var result = await fixture.Sut.IssueRefreshTokenAsync( flow, @@ -1231,7 +1226,6 @@ private static AuthFlowContext CreateFlow( string? issuer = null, string? audience = null, string? keyId = null, - bool addJwtIdClaim = true, bool issueRefresh = true) { /* @@ -1248,7 +1242,7 @@ private static AuthFlowContext CreateFlow( flow.Options.Token.AccessTokenLifetime = accessTokenLifetime ?? TimeSpan.FromMinutes(15); flow.Options.Token.RefreshTokenLifetime = refreshTokenLifetime ?? TimeSpan.FromDays(30); - flow.Options.Token.IssueRefresh = issueRefresh; + flow.Options.Token.IssueRefreshToken = issueRefresh; if (issuer is not null) flow.Options.Token.Issuer = issuer; @@ -1257,7 +1251,6 @@ private static AuthFlowContext CreateFlow( flow.Options.Token.Audience = audience; flow.Options.Token.KeyId = keyId; - flow.Options.Token.AddJwtIdClaim = addJwtIdClaim; return flow; } From 3e68fab4764db6c7b284e0a22fa83adc717f3f38 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Can=20Karag=C3=B6z?= Date: Tue, 1 Dec 2026 21:51:47 +0300 Subject: [PATCH 6/6] Fix Tests --- .../Options/UAuthTokenOptions.cs | 2 + .../Issuers/UAuthSessionIssuer.cs | 9 +- .../SessionSlidingExpirationTests.cs | 6 +- .../UAuthResourceApiOptionsValidatorTests.cs | 9 +- .../EffectiveServerOptionsProviderTests.cs | 28 +++++ .../Server/RefreshFlowServiceTests.cs | 69 +++++------ ...UAuthResourceAuthenticationHandlerTests.cs | 10 +- .../Sessions/UAuthSessionIssuerTests.cs | 45 +++---- .../Tokens/UAuthTokenIssuerTests.cs | 114 +++++------------- 9 files changed, 128 insertions(+), 164 deletions(-) diff --git a/src/CodeBeam.UltimateAuth.Core/Options/UAuthTokenOptions.cs b/src/CodeBeam.UltimateAuth.Core/Options/UAuthTokenOptions.cs index c6545ec2..03fe97ba 100644 --- a/src/CodeBeam.UltimateAuth.Core/Options/UAuthTokenOptions.cs +++ b/src/CodeBeam.UltimateAuth.Core/Options/UAuthTokenOptions.cs @@ -77,8 +77,10 @@ public bool IssueRefresh internal UAuthTokenOptions Clone() => new() { + SessionIdLifetime = SessionIdLifetime, AccessTokenLifetime = AccessTokenLifetime, RefreshTokenLifetime = RefreshTokenLifetime, + IssueRefreshToken = IssueRefreshToken, OpaqueIdBytes = OpaqueIdBytes, Issuer = Issuer, Audience = Audience, diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs index 800b8e04..1e619d3b 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs @@ -228,13 +228,20 @@ context.Device.DeviceId is not DeviceId incomingDeviceId || ipAddress: context.Device.IpAddress); } + var effectiveExpiresAt = sessionExpiresAt; + + if (chain.AbsoluteExpiresAt is { } chainAbsolute && effectiveExpiresAt > chainAbsolute) + { + effectiveExpiresAt = chainAbsolute; + } + var session = UAuthSession.Create( sessionId: sessionId, tenant: context.Tenant, userKey: context.UserKey, chainId: chain.ChainId, now: now, - expiresAt: sessionExpiresAt, + expiresAt: effectiveExpiresAt, securityVersion: root.SecurityVersion, device: sessionDevice, claims: context.Claims, diff --git a/tests/CodeBeam.UltimateAuth.Tests.Integration/SessionSlidingExpirationTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Integration/SessionSlidingExpirationTests.cs index f340733a..4e6ec8d7 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Integration/SessionSlidingExpirationTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Integration/SessionSlidingExpirationTests.cs @@ -183,8 +183,7 @@ public async Task IdentifierGet_ExpiredIdleSession_ShouldReturnUnauthorized(stri [Theory] [InlineData("BlazorServer")] [InlineData("BlazorWasm")] - public async Task InfiniteSliding_ThirtyConsecutiveRefreshes_ShouldKeepSessionAlive( - string profile) + public async Task InfiniteSliding_ThirtyConsecutiveRefreshes_ShouldKeepSessionAlive(string profile) { await using var factory = CreateFactory( sliding: true, @@ -298,8 +297,7 @@ public async Task Sliding_ExactlyAtSessionExpiry_ShouldRejectRefresh( [Theory] [InlineData("BlazorServer")] [InlineData("BlazorWasm")] - public async Task Sliding_WithIdleTimeout_RegularRefreshes_ShouldRemainActive( - string profile) + public async Task Sliding_WithIdleTimeout_RegularRefreshes_ShouldRemainActive(string profile) { await using var factory = CreateIdleSlidingFactory(); using var client = CreateClient(factory, profile); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiOptionsValidatorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiOptionsValidatorTests.cs index 1d61d284..eee7f1c2 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiOptionsValidatorTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiOptionsValidatorTests.cs @@ -272,12 +272,9 @@ public void PureJwt_DeviceRebinding_ShouldFail() { var options = ValidOptions(UAuthMode.PureJwt); - options.Auth.Device.MismatchBehavior = - DeviceMismatchBehavior.AllowAndRebind; + options.Auth.Device.MismatchBehavior = DeviceMismatchBehavior.AllowAndRebind; - AssertInvalid( - options, - "PureJwt does not support device rebinding."); + AssertInvalid(options, "JWT authentication modes do not support device rebinding."); } [Fact] @@ -523,7 +520,7 @@ public void MultipleInvalidFields_ShouldReportAllApplicableErrors() options, "Auth.Session.CookieName is required.", "Auth.AccessToken.HeaderName is required.", - "PureJwt does not support device rebinding.", + "JWT authentication modes do not support device rebinding.", "Auth.Jwt.Issuer is required.", "Auth.Jwt.Audience is required.", "Auth.Jwt.ValidAlgorithms must contain valid algorithms.", diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs index a178f9a2..c913b09a 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs @@ -422,6 +422,34 @@ public void Clone_should_not_share_profile_mode_mappings() .Should().Be(UAuthMode.PureJwt); } + [Theory] + [InlineData(UAuthMode.PureOpaque)] + [InlineData(UAuthMode.Hybrid)] + [InlineData(UAuthMode.SemiHybrid)] + [InlineData(UAuthMode.PureJwt)] + public void Effective_options_preserve_session_lifetime_and_refresh_policy(UAuthMode mode) + { + var original = new UAuthServerOptions + { + AuthMode = mode + }; + + original.Token.SessionIdLifetime = TimeSpan.FromHours(2); + original.Token.IssueRefreshToken = false; + + var provider = CreateProviderForMode(original, mode); + + var effective = provider.GetEffective( + TenantKey.Single, + UAuthApplicationProfile.BlazorServer); + + effective.Options.Token.SessionIdLifetime + .Should().Be(TimeSpan.FromHours(2)); + + effective.Options.Token.IssueRefreshToken + .Should().BeFalse(); + } + [Theory] [InlineData(UAuthMode.Hybrid)] [InlineData(UAuthMode.SemiHybrid)] diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshFlowServiceTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshFlowServiceTests.cs index c23c3554..5a81fd48 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshFlowServiceTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshFlowServiceTests.cs @@ -1,13 +1,10 @@ -using CodeBeam.UltimateAuth.Core.Abstractions; -using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; using CodeBeam.UltimateAuth.Core.MultiTenancy; -using CodeBeam.UltimateAuth.Core.Options; using CodeBeam.UltimateAuth.Server; using CodeBeam.UltimateAuth.Server.Auth; using CodeBeam.UltimateAuth.Server.Flows; using CodeBeam.UltimateAuth.Server.Infrastructure; -using CodeBeam.UltimateAuth.Server.Options; using CodeBeam.UltimateAuth.Server.Services; using CodeBeam.UltimateAuth.Tests.Unit.Helpers; using AwesomeAssertions; @@ -364,70 +361,56 @@ public async Task RefreshAsync_Hybrid_WhenTouchFails_DoesNotRotateRefreshToken() Times.Never); } - [Fact] - public async Task RefreshAsync_SemiHybrid_WhenSessionInvalid_ReturnsReauthWithoutRotation() - { - var (sut, validator, touch, rotation) = CreateSut(); - - validator - .Setup(x => x.ValidateSessionAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync(SessionValidationResult.Invalid(SessionState.SecurityMismatch)); - - var result = await sut.RefreshAsync( - CreateFlow(UAuthMode.SemiHybrid), - CreateRequest(SessionId, "refresh-token"), ct: TestContext.Current.CancellationToken); - - AssertReauth(result); - rotation.VerifyNoOtherCalls(); - touch.VerifyNoOtherCalls(); - } - [Fact] public async Task RefreshAsync_SemiHybrid_WhenRotationSucceeds_ReturnsRotatedWithoutTouchingSession() { var (sut, validator, touch, rotation) = CreateSut(); - var validation = CreateActiveValidation(); var execution = CreateSuccessfulRotation(); - validator - .Setup(x => x.ValidateSessionAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync(validation); - rotation .Setup(x => x.RotateAsync( It.IsAny(), It.Is(c => - c.ExpectedSessionId == SessionId && + c.ExpectedSessionId == null && c.RefreshToken == "refresh-token"), It.IsAny())) .ReturnsAsync(execution); var result = await sut.RefreshAsync( CreateFlow(UAuthMode.SemiHybrid), - CreateRequest(SessionId, "refresh-token"), ct: TestContext.Current.CancellationToken); + CreateRequest(null, "refresh-token"), + ct: TestContext.Current.CancellationToken); result.IsSuccess.Should().BeTrue(); result.Outcome.Should().Be(RefreshOutcome.Rotated); - result.SessionId.Should().Be(SessionId); + result.SessionId.Should().BeNull(); result.AccessToken.Should().BeSameAs(execution.Result.AccessToken); result.RefreshToken.Should().BeSameAs(execution.Result.RefreshToken); + + rotation.Verify(x => x.RotateAsync( + It.IsAny(), + It.Is(c => + c.ExpectedSessionId == null && + c.RefreshToken == "refresh-token"), + It.IsAny()), + Times.Once); + + validator.VerifyNoOtherCalls(); touch.VerifyNoOtherCalls(); + rotation.VerifyNoOtherCalls(); } [Fact] public async Task RefreshAsync_SemiHybrid_WhenRotationFails_ReturnsReauthWithoutTouch() { var (sut, validator, touch, rotation) = CreateSut(); - var validation = CreateActiveValidation(); - - validator - .Setup(x => x.ValidateSessionAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync(validation); rotation .Setup(x => x.RotateAsync( It.IsAny(), - It.IsAny(), + It.Is(c => + c.ExpectedSessionId == null && + c.RefreshToken == "refresh-token"), It.IsAny())) .ReturnsAsync(new RefreshTokenRotationExecution { @@ -436,10 +419,22 @@ public async Task RefreshAsync_SemiHybrid_WhenRotationFails_ReturnsReauthWithout var result = await sut.RefreshAsync( CreateFlow(UAuthMode.SemiHybrid), - CreateRequest(SessionId, "refresh-token"), ct: TestContext.Current.CancellationToken); + CreateRequest(null, "refresh-token"), + ct: TestContext.Current.CancellationToken); AssertReauth(result); + + rotation.Verify(x => x.RotateAsync( + It.IsAny(), + It.Is(c => + c.ExpectedSessionId == null && + c.RefreshToken == "refresh-token"), + It.IsAny()), + Times.Once); + + validator.VerifyNoOtherCalls(); touch.VerifyNoOtherCalls(); + rotation.VerifyNoOtherCalls(); } private static ( diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthResourceAuthenticationHandlerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthResourceAuthenticationHandlerTests.cs index 55c86c76..12646a46 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthResourceAuthenticationHandlerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthResourceAuthenticationHandlerTests.cs @@ -443,7 +443,7 @@ public async Task AuthenticateAsync_PureJwt_WhenCredentialIsNotAccessToken_Shoul result.Succeeded.Should().BeFalse(); result.Failure!.Message.Should() - .Be("PureJwt requires an access token."); + .Be("JWT authentication requires an access token."); VerifyNoSessionValidation(setup); } @@ -605,7 +605,7 @@ public async Task AuthenticateAsync_PureJwt_WhenSessionClaimExists_ShouldFail() result.Succeeded.Should().BeFalse(); result.Failure!.Message.Should() - .Be("Session-bound JWT is not valid in PureJwt mode."); + .Be("JWT identity does not satisfy authentication mode."); VerifyNoSessionValidation(setup); } @@ -632,7 +632,7 @@ public async Task AuthenticateAsync_PureJwt_WhenDeviceClaimIsMissing_ShouldFail( result.Succeeded.Should().BeFalse(); result.Failure!.Message.Should() - .Be("PureJwt requires a valid device binding."); + .Be("JWT identity does not satisfy authentication mode."); } [Fact] @@ -659,7 +659,7 @@ public async Task AuthenticateAsync_PureJwt_WhenDeviceClaimIsDuplicated_ShouldFa result.Succeeded.Should().BeFalse(); result.Failure!.Message.Should() - .Be("PureJwt requires a valid device binding."); + .Be("JWT identity does not satisfy authentication mode."); } [Fact] @@ -683,7 +683,7 @@ public async Task AuthenticateAsync_PureJwt_WhenDeviceDoesNotMatch_ShouldFail() result.Succeeded.Should().BeFalse(); result.Failure!.Message.Should() - .Be("JWT device mismatch."); + .Be("JWT identity does not satisfy authentication mode."); VerifyNoSessionValidation(setup); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/UAuthSessionIssuerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/UAuthSessionIssuerTests.cs index ea72bc4b..9f02e5d9 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/UAuthSessionIssuerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/UAuthSessionIssuerTests.cs @@ -62,7 +62,8 @@ public async Task IssueSessionAsync_WhenOpaqueGeneratorReturnsInvalidId_ShouldFa fixture.Sut.IssueSessionAsync(context); await act.Should() - .ThrowAsync(); + .ThrowAsync() + .WithMessage("Could not generate session identifier."); fixture.StoreFactory.Verify( x => x.Create(It.IsAny()), @@ -1196,9 +1197,7 @@ public async Task RotateSessionAsync_WhenMaxLifetimeIsShorter_ShouldCapNewSessio var context = CreateRotationContext(fixture); - SetupSuccessfulRotation( - fixture, - context); + SetupSuccessfulRotation(fixture, context, absoluteExpiresAt: Now.AddHours(2)); UAuthSession? persisted = null; @@ -1718,18 +1717,11 @@ private static void SetupNewIssuance(Fixture fixture, SessionIssuanceContext con SetupSessionAndChainPersistence(fixture); } - private static RotationSetup SetupSuccessfulRotation(Fixture fixture, SessionRotationContext context) + private static RotationSetup SetupSuccessfulRotation(Fixture fixture, SessionRotationContext context, DateTimeOffset? absoluteExpiresAt = null) { - var root = - CreateRoot( - context.Tenant, - context.UserKey); + var root = CreateRoot(context.Tenant, context.UserKey); - var chain = - CreateChain( - root, - context.UserKey, - context.Tenant); + var chain = CreateChain(root, context.UserKey, context.Tenant, absoluteExpiresAt); var oldSession = CreateSession( @@ -1737,7 +1729,10 @@ private static RotationSetup SetupSuccessfulRotation(Fixture fixture, SessionRot chain.ChainId, Now.AddHours(-1), context.CurrentSessionId, - root.SecurityVersion); + root.SecurityVersion, + credentialPurpose: context.Mode == UAuthMode.SemiHybrid + ? SessionCredentialPurpose.MetadataOnly + : SessionCredentialPurpose.Opaque); SetupRoot( fixture, @@ -1897,20 +1892,16 @@ private static SessionRotationContext CreateRotationContext(Fixture fixture, UAu }; } - private static UAuthSessionRoot CreateRoot( - TenantKey tenant, - UserKey userKey) + private static UAuthSessionRoot CreateRoot(TenantKey tenant, UserKey userKey) { - return UAuthSessionRoot.Create( - tenant, - userKey, - Now.AddDays(-1)); + return UAuthSessionRoot.Create(tenant, userKey, Now.AddDays(-1)); } private static UAuthSessionChain CreateChain( UAuthSessionRoot root, UserKey userKey, - TenantKey tenant) + TenantKey tenant, + DateTimeOffset? absoluteExpiresAt = null) { return UAuthSessionChain.Create( SessionChainId.New(), @@ -1918,7 +1909,7 @@ private static UAuthSessionChain CreateChain( tenant, userKey, Now.AddHours(-2), - Now.AddDays(7), + absoluteExpiresAt ?? Now.AddDays(7), TestDevice.Default(), ClaimsSnapshot.Empty, root.SecurityVersion); @@ -1929,7 +1920,8 @@ private static UAuthSession CreateSession( SessionChainId chainId, DateTimeOffset createdAt, AuthSessionId? sessionId = null, - long securityVersion = 0) + long securityVersion = 0, + SessionCredentialPurpose credentialPurpose = SessionCredentialPurpose.Opaque) { return UAuthSession.Create( sessionId ?? AuthSessionId.Parse(Guid.NewGuid().ToString(), null), @@ -1941,7 +1933,8 @@ private static UAuthSession CreateSession( securityVersion, TestDevice.Default(), ClaimsSnapshot.Empty, - SessionMetadata.Empty); + SessionMetadata.Empty, + credentialPurpose: credentialPurpose); } private sealed record RotationSetup( diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Tokens/UAuthTokenIssuerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Tokens/UAuthTokenIssuerTests.cs index d84df266..bceb8dd6 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Tokens/UAuthTokenIssuerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Tokens/UAuthTokenIssuerTests.cs @@ -103,26 +103,21 @@ await fixture.Sut.IssueAccessTokenAsync( [Theory] [InlineData(UAuthMode.SemiHybrid)] [InlineData(UAuthMode.PureJwt)] - public async Task IssueAccessTokenAsync_WhenModeUsesJwt_ShouldIssueJwt( - UAuthMode mode) + public async Task IssueAccessTokenAsync_WhenModeUsesJwt_ShouldIssueJwt(UAuthMode mode) { var fixture = CreateFixture(); var flow = CreateFlow(mode); - var context = CreateTokenContext(); + var context = mode == UAuthMode.SemiHybrid + ? CreateTokenContext(sessionId: CreateSessionId("jwt-session-0000000000000000000000000001"), chainId: SessionChainId.New()) + : CreateTokenContext(); - var result = - await fixture.Sut.IssueAccessTokenAsync( - flow, - context, ct: TestContext.Current.CancellationToken); + var result = await fixture.Sut.IssueAccessTokenAsync(flow, context, ct: TestContext.Current.CancellationToken); result.Format.Should().Be(TokenFormat.Jwt); result.Token.Should().Be(Jwt); - fixture.JwtGenerator.Verify( - x => x.CreateToken( - It.IsAny()), - Times.Once); + fixture.JwtGenerator.Verify(x => x.CreateToken(It.IsAny()), Times.Once); } [Fact] @@ -231,18 +226,15 @@ await fixture.Sut.IssueAccessTokenAsync( } [Fact] - public async Task IssueAccessTokenAsync_WhenJwtAndSessionExists_ShouldIncludeSessionClaim() + public async Task IssueAccessTokenAsync_WhenModeIsSemiHybrid_ShouldIncludeSessionClaim() { var fixture = CreateFixture(); - var sessionId = - CreateSessionId( - "jwt-session-0000000000000000000000000001"); + var sessionId = CreateSessionId("jwt-session-0000000000000000000000000001"); var flow = CreateFlow(UAuthMode.SemiHybrid); - var context = CreateTokenContext( - sessionId: sessionId); + var context = CreateTokenContext(sessionId: sessionId, chainId: SessionChainId.New()); UAuthJwtTokenDescriptor? captured = null; @@ -330,35 +322,6 @@ await fixture.Sut.IssueAccessTokenAsync( .Be(JwtId); } - [Fact] - public async Task IssueAccessTokenAsync_WhenJwtIdDisabled_ShouldNotGenerateJti() - { - var fixture = CreateFixture(); - - var flow = CreateFlow( - UAuthMode.PureJwt); - - UAuthJwtTokenDescriptor? captured = null; - - fixture.JwtGenerator - .Setup(x => x.CreateToken( - It.IsAny())) - .Callback( - descriptor => captured = descriptor) - .Returns(Jwt); - - await fixture.Sut.IssueAccessTokenAsync( - flow, - CreateTokenContext(), ct: TestContext.Current.CancellationToken); - - fixture.OpaqueGenerator.Verify( - x => x.GenerateJwtId(), - Times.Never); - - captured!.Claims.Should() - .NotContainKey("jti"); - } - // ===================================================================== // Refresh token - guards // ===================================================================== @@ -858,13 +821,19 @@ private static Fixture CreateFixture() [Theory] [InlineData(UAuthMode.SemiHybrid)] [InlineData(UAuthMode.PureJwt)] - public async Task IssueAccessTokenAsync_WhenMultipleRolesExist_ShouldPreserveAllRoles( - UAuthMode mode) + public async Task IssueAccessTokenAsync_WhenMultipleRolesExist_ShouldPreserveAllRoles(UAuthMode mode) { var fixture = CreateFixture(); var flow = CreateFlow(mode); var context = CreateTokenContext( + sessionId: mode == UAuthMode.SemiHybrid + ? CreateSessionId( + "jwt-session-0000000000000000000000000001") + : null, + chainId: mode == UAuthMode.SemiHybrid + ? SessionChainId.New() + : null, claims: ClaimsSnapshot.From( ("role", "Admin"), ("role", "Editor"), @@ -962,16 +931,14 @@ public async Task IssueAccessTokenAsync_WhenClaimsAreEmpty_ShouldOnlyIncludeFram captured.Should().NotBeNull(); - captured!.Claims.Should().HaveCount(3); - - captured.Claims!["sub"].Should().Be(context.UserKey.Value); + captured!.Claims.Should().HaveCount(4); + captured.Claims["sub"].Should().Be(context.UserKey.Value); captured.Claims["tenant"].Should().Be(context.Tenant.Value); - captured.Claims["device_id"].Should().Be(context.DeviceId!.Value.Value); + captured.Claims["jti"].Should().Be(JwtId); captured.Claims.Should().NotContainKey("sid"); - captured.Claims.Should().NotContainKey("jti"); } [Theory] @@ -1006,11 +973,16 @@ public async Task IssueAccessTokenAsync_WhenCustomClaimIsReserved_ShouldIgnoreIt captured.Should().NotBeNull(); - captured!.Claims.Should() - .NotContainKey(reservedType); + if (reservedType == "jti") + { + captured!.Claims!["jti"].Should().Be(JwtId); + } + else + { + captured!.Claims.Should().NotContainKey(reservedType); + } - captured.Claims!["department"] - .Should().Be("legal"); + captured.Claims["department"].Should().Be("legal"); } [Fact] @@ -1102,34 +1074,6 @@ public async Task IssueAccessTokenAsync_WhenCustomJtiExists_ShouldUseGeneratedJt Times.Once); } - [Fact] - public async Task IssueAccessTokenAsync_WhenJwtIdDisabled_ShouldRejectCustomJti() - { - var fixture = CreateFixture(); - - var flow = CreateFlow( - UAuthMode.PureJwt); - - var context = CreateTokenContext( - claims: ClaimsSnapshot.From( - ("jti", "attacker-jti"))); - - UAuthJwtTokenDescriptor? captured = null; - - fixture.JwtGenerator - .Setup(x => x.CreateToken(It.IsAny())) - .Callback(d => captured = d) - .Returns(Jwt); - - await fixture.Sut.IssueAccessTokenAsync(flow, context, ct: TestContext.Current.CancellationToken); - - captured!.Claims.Should().NotContainKey("jti"); - - fixture.OpaqueGenerator.Verify( - x => x.GenerateJwtId(), - Times.Never); - } - [Fact] public async Task IssueTokens_ShouldUseEffectiveLifetimes() {