From d2471002e4f2ba8b87d71fca153e8de292d6994e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Can=20Karag=C3=B6z?= Date: Thu, 3 Dec 2026 15:53:12 +0300 Subject: [PATCH 1/2] refactor(architecture): Introduce Surrogate Model and Consolidate Authentication Architecture --- .../Domain/Surrogates/SurrogateKind.cs | 23 +++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/CodeBeam.UltimateAuth.Core/Domain/Surrogates/SurrogateKind.cs diff --git a/src/CodeBeam.UltimateAuth.Core/Domain/Surrogates/SurrogateKind.cs b/src/CodeBeam.UltimateAuth.Core/Domain/Surrogates/SurrogateKind.cs new file mode 100644 index 00000000..59416dfc --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Core/Domain/Surrogates/SurrogateKind.cs @@ -0,0 +1,23 @@ +namespace CodeBeam.UltimateAuth.Core.Domain; + +/// +/// Identifies the kind of secondary authentication data used to maintain authentication continuity. +/// +public enum SurrogateKind +{ + /// + /// An authentication-capable session identifier. + /// Metadata-only session identifiers are not surrogates. + /// + SessionId = 0, + + /// + /// A token used to authenticate subsequent requests. + /// + AccessToken = 10, + + /// + /// A token used to renew authentication without presenting the original credential again. + /// + RefreshToken = 20 +} From 484c562a0c3eb5a3f701cf6a7f06a74b5a61e3ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mehmet=20Can=20Karag=C3=B6z?= Date: Thu, 3 Dec 2026 21:15:46 +0300 Subject: [PATCH 2/2] Main Implementation --- .../Contracts/Token/PrimaryToken.cs | 19 -- .../Contracts/Token/TokenValidationResult.cs | 68 ------ .../Domain/Principals/GrantKind.cs | 8 - .../Domain/Principals/PrimaryTokenKind.cs | 7 - ...edentialPurpose.cs => SessionIdPurpose.cs} | 2 +- .../Domain/Session/UAuthSession.cs | 12 +- .../Extensions/UAuthModeExtensions.cs | 105 ++++++++ .../Options/TokenResponseMode.cs | 10 - .../Abstractions/ICredentialResponseWriter.cs | 12 - .../Abstractions/ISessionLineageValidator.cs | 2 +- .../Abstractions/ISurrogateResponseWriter.cs | 12 + .../Auth/Context/AuthFlowContext.cs | 10 +- .../Auth/Context/AuthFlowContextFactory.cs | 8 - .../Auth/IPrimaryTokenResolver.cs | 8 - .../Auth/PrimaryTokenResolver.cs | 19 -- .../Auth/Response/AuthResponseResolver.cs | 225 +++++++++--------- .../Auth/Response/EffectiveAuthResponse.cs | 32 ++- ...very.cs => EffectiveSurrogateTransport.cs} | 24 +- ...> SurrogateTransportCollisionValidator.cs} | 22 +- .../Auth/SemiHybridAuthorityValidator.cs | 2 +- .../AspNetCore/UAuthAuthenticationHandler.cs | 10 +- .../UAuthResourceAuthenticationHandler.cs | 91 +++---- .../Domain/HeaderTokenFormat.cs | 7 - .../Domain/HeaderValueFormat.cs | 10 + ...tDeliveryMode.cs => SurrogateTransport.cs} | 2 +- .../Endpoints/LoginEndpointHandler.cs | 12 +- .../Endpoints/LogoutEndpointHandler.cs | 10 +- .../Endpoints/PkceEndpointHandler.cs | 14 +- .../Endpoints/RefreshEndpointHandler.cs | 14 +- .../Endpoints/UAuthLoginTransportEndpoint.cs | 5 +- .../Endpoints/ValidateEndpointHandler.cs | 14 +- .../Extensions/ServiceCollectionExtensions.cs | 10 +- .../Extensions/SurrogateResolverExtensions.cs | 17 ++ .../Flows/Refresh/IRefreshResponsePolicy.cs | 2 +- .../Flows/Refresh/RefreshResponsePolicy.cs | 14 +- .../Flows/Refresh/RefreshTokenResolver.cs | 2 +- .../Cookies/IUAuthCookiePolicyBuilder.cs | 2 +- .../Cookies/UAuthCookiePolicyBuilder.cs | 14 +- .../ITransportCredentialResolver.cs | 10 - .../AspNetCore/TransportCredential.cs | 12 - .../AspNetCore/TransportCredentialKind.cs | 9 - .../AspNetCore/TransportCredentialResolver.cs | 51 ---- .../Credentials/IUAuthBodyPolicyBuilder.cs | 2 +- .../Credentials/IUAuthHeaderPolicyBuilder.cs | 2 +- ...seWriter.cs => SurrogateResponseWriter.cs} | 56 ++--- .../Credentials/UAuthBodyPolicyBuilder.cs | 2 +- .../Credentials/UAuthHeaderPolicyBuilder.cs | 8 +- .../Issuers/UAuthSessionIssuer.cs | 14 +- .../SessionId/SessionIdResolver.cs | 27 +-- .../Surrogates/ISurrogateResolver.cs | 9 + .../Surrogates/ResolvedSurrogate.cs | 22 ++ .../SurrogateReader.cs} | 14 +- .../Surrogates/SurrogateResolver.cs | 24 ++ .../Options/CredentialResponseOptions.cs | 60 ----- ...ptions.cs => SurrogateTransportOptions.cs} | 8 +- .../Options/UAuthHubCorsOptionsSetup.cs | 2 +- .../Options/UAuthResourceApiOptions.cs | 83 +++---- .../Options/UAuthResponseOptions.cs | 25 -- .../Options/UAuthServerOptions.cs | 16 +- ...s.cs => UAuthSurrogateTransportOptions.cs} | 14 +- .../UAuthResourceApiOptionsValidator.cs | 18 +- .../ResourceApi/RemoteHubValidationService.cs | 29 +-- .../ResourceApi/ResourceSessionIdResolver.cs | 41 +--- .../ResourceSurrogateTransportFactory.cs | 55 +++++ .../Security/UAuthCsrfGrantInspector.cs | 14 -- .../Security/UAuthCsrfPolicyEvaluator.cs | 2 +- .../Security/UAuthCsrfSurrogateInspector.cs | 14 ++ .../Services/JwtLogoutService.cs | 2 +- .../Services/RefreshTokenRotationService.cs | 2 +- .../Services/SessionLineageValidator.cs | 2 +- .../Services/UAuthSessionValidator.cs | 2 +- .../Data/UAuthSessionsModelBuilder.cs | 2 +- .../Projections/SessionProjection.cs | 2 +- .../Infrastructure/AuthServerFactory.cs | 2 +- .../LoginTests.cs | 6 +- .../PureJwtIdentityTests.cs | 16 +- .../RefreshTests.cs | 2 +- .../ResourceApi/ResourceApiTestHost.cs | 14 +- .../Core/UAuthModeExtensionsTests.cs | 118 +++++++++ .../Helpers/AuthFlowTestFactory.cs | 13 +- .../RemoteHubValidationServiceTests.cs | 55 ++--- .../ResourceSessionIdResolverTests.cs | 91 ++++--- .../UAuthResourceApiOptionsTests.cs | 36 +-- .../UAuthResourceApiOptionsValidatorTests.cs | 30 ++- .../UAuthResourceApiRegistrationTests.cs | 13 +- .../Security/UAuthCsrfPolicyEvaluatorTests.cs | 68 +++--- ...cs => UAuthCsrfSurrogateInspectorTests.cs} | 38 +-- .../Server/AuthFlowContextFactoryTests.cs | 30 +-- .../Server/AuthResponseResolverTests.cs | 6 +- .../Server/CookieInfrastructureTests.cs | 96 ++++---- .../Server/CredentialInfrastructureTests.cs | 30 +-- .../EffectiveServerOptionsProviderTests.cs | 15 +- .../Server/GrantCredentialReaderTests.cs | 159 ++++++------- .../Server/JwtLogoutServiceTests.cs | 6 +- .../Server/LoginEndpointHandlerTests.cs | 20 +- .../Server/LogoutEndpointHandlerTests.cs | 3 - .../Server/PkceEndpointHandlerTests.cs | 25 +- .../Server/RefreshFlowServiceTests.cs | 7 +- .../Server/RefreshTokenResolverTests.cs | 30 +-- .../RefreshTokenRotationServiceTests.cs | 9 +- .../SemiHybridAuthorityValidatorTests.cs | 20 +- .../Server/SessionEndpointHandlerTests.cs | 1 - ...sts.cs => SurrogateResponseWriterTests.cs} | 166 ++++++------- ...rogateTransportCollisionValidatorTests.cs} | 93 ++++---- .../TransportCredentialResolverTests.cs | 104 ++++---- .../Server/UAuthCorsHubOptionsSetupTests.cs | 20 +- .../Server/UAuthFlowServiceTests.cs | 13 +- .../UAuthLoginTransportEndpointTests.cs | 26 +- ...UAuthResourceAuthenticationHandlerTests.cs | 59 +++-- .../Server/UAuthSessionValidatorTests.cs | 8 +- ...thStatusAuthorizationResultHandlerTests.cs | 37 +-- .../Server/ValidateEndpointHandlerTests.cs | 111 ++++----- .../Sessions/SessionIdResolverTests.cs | 70 +++--- .../Sessions/UAuthSessionIssuerTests.cs | 6 +- 114 files changed, 1507 insertions(+), 1677 deletions(-) delete mode 100644 src/CodeBeam.UltimateAuth.Core/Contracts/Token/PrimaryToken.cs delete mode 100644 src/CodeBeam.UltimateAuth.Core/Contracts/Token/TokenValidationResult.cs delete mode 100644 src/CodeBeam.UltimateAuth.Core/Domain/Principals/GrantKind.cs delete mode 100644 src/CodeBeam.UltimateAuth.Core/Domain/Principals/PrimaryTokenKind.cs rename src/CodeBeam.UltimateAuth.Core/Domain/Session/{SessionCredentialPurpose.cs => SessionIdPurpose.cs} (92%) create mode 100644 src/CodeBeam.UltimateAuth.Core/Extensions/UAuthModeExtensions.cs delete mode 100644 src/CodeBeam.UltimateAuth.Core/Options/TokenResponseMode.cs delete mode 100644 src/CodeBeam.UltimateAuth.Server/Abstractions/ICredentialResponseWriter.cs create mode 100644 src/CodeBeam.UltimateAuth.Server/Abstractions/ISurrogateResponseWriter.cs delete mode 100644 src/CodeBeam.UltimateAuth.Server/Auth/IPrimaryTokenResolver.cs delete mode 100644 src/CodeBeam.UltimateAuth.Server/Auth/PrimaryTokenResolver.cs rename src/CodeBeam.UltimateAuth.Server/Auth/Response/{EffectiveGrantDelivery.cs => EffectiveSurrogateTransport.cs} (58%) rename src/CodeBeam.UltimateAuth.Server/Auth/Response/{GrantDeliveryCollisionValidator.cs => SurrogateTransportCollisionValidator.cs} (59%) delete mode 100644 src/CodeBeam.UltimateAuth.Server/Domain/HeaderTokenFormat.cs create mode 100644 src/CodeBeam.UltimateAuth.Server/Domain/HeaderValueFormat.cs rename src/CodeBeam.UltimateAuth.Server/Domain/{GrantDeliveryMode.cs => SurrogateTransport.cs} (95%) create mode 100644 src/CodeBeam.UltimateAuth.Server/Extensions/SurrogateResolverExtensions.cs delete mode 100644 src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/ITransportCredentialResolver.cs delete mode 100644 src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/TransportCredential.cs delete mode 100644 src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/TransportCredentialKind.cs delete mode 100644 src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/TransportCredentialResolver.cs rename src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/{CredentialResponseWriter.cs => SurrogateResponseWriter.cs} (66%) create mode 100644 src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/ISurrogateResolver.cs create mode 100644 src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/ResolvedSurrogate.cs rename src/CodeBeam.UltimateAuth.Server/Infrastructure/{Credentials/GrantCredentialReader.cs => Surrogates/SurrogateReader.cs} (90%) create mode 100644 src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/SurrogateResolver.cs delete mode 100644 src/CodeBeam.UltimateAuth.Server/Options/CredentialResponseOptions.cs rename src/CodeBeam.UltimateAuth.Server/Options/{GrantDeliveryOptions.cs => SurrogateTransportOptions.cs} (84%) delete mode 100644 src/CodeBeam.UltimateAuth.Server/Options/UAuthResponseOptions.cs rename src/CodeBeam.UltimateAuth.Server/Options/{UAuthGrantDeliveryOptions.cs => UAuthSurrogateTransportOptions.cs} (73%) create mode 100644 src/CodeBeam.UltimateAuth.Server/ResourceApi/ResourceSurrogateTransportFactory.cs delete mode 100644 src/CodeBeam.UltimateAuth.Server/Security/UAuthCsrfGrantInspector.cs create mode 100644 src/CodeBeam.UltimateAuth.Server/Security/UAuthCsrfSurrogateInspector.cs create mode 100644 tests/CodeBeam.UltimateAuth.Tests.Unit/Core/UAuthModeExtensionsTests.cs rename tests/CodeBeam.UltimateAuth.Tests.Unit/Security/{UAuthCsrfGrantInspectorTests.cs => UAuthCsrfSurrogateInspectorTests.cs} (55%) rename tests/CodeBeam.UltimateAuth.Tests.Unit/Server/{CredentialResponseWriterTests.cs => SurrogateResponseWriterTests.cs} (70%) rename tests/CodeBeam.UltimateAuth.Tests.Unit/Server/{GrantDeliveryCollisionValidatorTests.cs => SurrogateTransportCollisionValidatorTests.cs} (54%) diff --git a/src/CodeBeam.UltimateAuth.Core/Contracts/Token/PrimaryToken.cs b/src/CodeBeam.UltimateAuth.Core/Contracts/Token/PrimaryToken.cs deleted file mode 100644 index 368e4a4b..00000000 --- a/src/CodeBeam.UltimateAuth.Core/Contracts/Token/PrimaryToken.cs +++ /dev/null @@ -1,19 +0,0 @@ -//using CodeBeam.UltimateAuth.Core.Domain; - -//namespace CodeBeam.UltimateAuth.Core.Contracts; - -//public sealed record PrimaryToken -//{ -// public PrimaryTokenKind Kind { get; } -// public string Value { get; } - -// private PrimaryToken(PrimaryTokenKind kind, string value) -// { -// Kind = kind; -// Value = value; -// } - -// public static PrimaryToken FromSession(AuthSessionId sessionId) => new(PrimaryTokenKind.Session, sessionId.ToString()); - -// public static PrimaryToken FromAccessToken(AccessToken token) => new(PrimaryTokenKind.AccessToken, token.Token); -//} diff --git a/src/CodeBeam.UltimateAuth.Core/Contracts/Token/TokenValidationResult.cs b/src/CodeBeam.UltimateAuth.Core/Contracts/Token/TokenValidationResult.cs deleted file mode 100644 index c77b6a71..00000000 --- a/src/CodeBeam.UltimateAuth.Core/Contracts/Token/TokenValidationResult.cs +++ /dev/null @@ -1,68 +0,0 @@ -//using CodeBeam.UltimateAuth.Core.Domain; -//using CodeBeam.UltimateAuth.Core.MultiTenancy; -//using System.Security.Claims; - -//namespace CodeBeam.UltimateAuth.Core.Contracts; - -//public sealed record TokenValidationResult -//{ -// public bool IsValid { get; init; } -// public TokenFormat Format { get; init; } -// public TenantKey? Tenant { get; init; } -// public TUserId? UserId { get; init; } -// public AuthSessionId? SessionId { get; init; } -// public IReadOnlyCollection Claims { get; init; } = Array.Empty(); -// public TokenInvalidReason? InvalidReason { get; init; } -// public DateTimeOffset? ExpiresAt { get; set; } - -// private TokenValidationResult( -// bool isValid, -// TokenFormat format, -// TenantKey? tenant, -// TUserId? userId, -// AuthSessionId? sessionId, -// IReadOnlyCollection? claims, -// TokenInvalidReason? invalidReason, -// DateTimeOffset? expiresAt -// ) -// { -// IsValid = isValid; -// Format = format; -// Tenant = tenant; -// UserId = userId; -// SessionId = sessionId; -// Claims = claims ?? Array.Empty(); -// InvalidReason = invalidReason; -// ExpiresAt = expiresAt; -// } - -// public static TokenValidationResult Valid( -// TokenFormat format, -// TenantKey tenant, -// TUserId userId, -// AuthSessionId? sessionId, -// IReadOnlyCollection claims, -// DateTimeOffset? expiresAt) -// => new( -// isValid: true, -// format, -// tenant, -// userId, -// sessionId, -// claims, -// invalidReason: null, -// expiresAt -// ); - -// public static TokenValidationResult Invalid(TokenFormat format, TokenInvalidReason reason) -// => new( -// isValid: false, -// format: format, -// tenant: null, -// userId: default, -// sessionId: null, -// claims: null, -// invalidReason: reason, -// expiresAt: null -// ); -//} diff --git a/src/CodeBeam.UltimateAuth.Core/Domain/Principals/GrantKind.cs b/src/CodeBeam.UltimateAuth.Core/Domain/Principals/GrantKind.cs deleted file mode 100644 index 162dac79..00000000 --- a/src/CodeBeam.UltimateAuth.Core/Domain/Principals/GrantKind.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace CodeBeam.UltimateAuth.Core.Domain; - -public enum GrantKind -{ - Session = 0, - AccessToken = 10, - RefreshToken = 20 -} diff --git a/src/CodeBeam.UltimateAuth.Core/Domain/Principals/PrimaryTokenKind.cs b/src/CodeBeam.UltimateAuth.Core/Domain/Principals/PrimaryTokenKind.cs deleted file mode 100644 index 7b3ae60e..00000000 --- a/src/CodeBeam.UltimateAuth.Core/Domain/Principals/PrimaryTokenKind.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace CodeBeam.UltimateAuth.Core.Domain; - -public enum PrimaryTokenKind -{ - Session = 0, - AccessToken = 10 -} diff --git a/src/CodeBeam.UltimateAuth.Core/Domain/Session/SessionCredentialPurpose.cs b/src/CodeBeam.UltimateAuth.Core/Domain/Session/SessionIdPurpose.cs similarity index 92% rename from src/CodeBeam.UltimateAuth.Core/Domain/Session/SessionCredentialPurpose.cs rename to src/CodeBeam.UltimateAuth.Core/Domain/Session/SessionIdPurpose.cs index 7aecc82e..2ecb11c3 100644 --- a/src/CodeBeam.UltimateAuth.Core/Domain/Session/SessionCredentialPurpose.cs +++ b/src/CodeBeam.UltimateAuth.Core/Domain/Session/SessionIdPurpose.cs @@ -3,7 +3,7 @@ /// /// Defines whether a persisted session can authenticate an opaque credential or only represents JWT lineage. /// -public enum SessionCredentialPurpose +public enum SessionIdPurpose { /// /// The session ID is an opaque authentication credential. diff --git a/src/CodeBeam.UltimateAuth.Core/Domain/Session/UAuthSession.cs b/src/CodeBeam.UltimateAuth.Core/Domain/Session/UAuthSession.cs index 5a71277e..7186ecc4 100644 --- a/src/CodeBeam.UltimateAuth.Core/Domain/Session/UAuthSession.cs +++ b/src/CodeBeam.UltimateAuth.Core/Domain/Session/UAuthSession.cs @@ -19,10 +19,10 @@ public sealed class UAuthSession : IVersionedEntity public SessionMetadata Metadata { get; } public long Version { get; set; } - public SessionCredentialPurpose CredentialPurpose { get; } + public SessionIdPurpose CredentialPurpose { get; } - public bool IsOpaqueCredential => CredentialPurpose == SessionCredentialPurpose.Opaque; - public bool IsMetadataOnly => CredentialPurpose == SessionCredentialPurpose.MetadataOnly; + public bool IsOpaqueCredential => CredentialPurpose == SessionIdPurpose.Opaque; + public bool IsMetadataOnly => CredentialPurpose == SessionIdPurpose.MetadataOnly; public bool IsRevoked => RevokedAt != null; @@ -39,7 +39,7 @@ private UAuthSession( ClaimsSnapshot claims, SessionMetadata metadata, long version, - SessionCredentialPurpose credentialPurpose) + SessionIdPurpose credentialPurpose) { SessionId = sessionId; Tenant = tenant; @@ -67,7 +67,7 @@ public static UAuthSession Create( DeviceContext device, ClaimsSnapshot? claims, SessionMetadata metadata, - SessionCredentialPurpose credentialPurpose = SessionCredentialPurpose.Opaque) + SessionIdPurpose credentialPurpose = SessionIdPurpose.Opaque) { if (!Enum.IsDefined(credentialPurpose)) throw new ArgumentOutOfRangeException(nameof(credentialPurpose)); @@ -123,7 +123,7 @@ internal static UAuthSession FromProjection( ClaimsSnapshot claims, SessionMetadata metadata, long version, - SessionCredentialPurpose credentialPurpose) + SessionIdPurpose credentialPurpose) { return new UAuthSession( sessionId, diff --git a/src/CodeBeam.UltimateAuth.Core/Extensions/UAuthModeExtensions.cs b/src/CodeBeam.UltimateAuth.Core/Extensions/UAuthModeExtensions.cs new file mode 100644 index 00000000..7871af1b --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Core/Extensions/UAuthModeExtensions.cs @@ -0,0 +1,105 @@ +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; + +namespace CodeBeam.UltimateAuth.Core.Extensions; + +public static class UAuthModeExtensions +{ + public static SurrogateKind GetPrimarySurrogateKind(this UAuthMode mode) + => mode switch + { + UAuthMode.PureOpaque or UAuthMode.Hybrid + => SurrogateKind.SessionId, + + UAuthMode.SemiHybrid or UAuthMode.PureJwt + => SurrogateKind.AccessToken, + + _ => throw UnsupportedMode(mode) + }; + + public static bool SupportsSessionLineage(this UAuthMode mode) + => mode switch + { + UAuthMode.PureOpaque or + UAuthMode.Hybrid or + UAuthMode.SemiHybrid => true, + + UAuthMode.PureJwt => false, + + _ => throw UnsupportedMode(mode) + }; + + public static bool UsesSessionIdForAuthentication(this UAuthMode mode) + => mode.GetPrimarySurrogateKind() == SurrogateKind.SessionId; + + public static bool SupportsAccessToken(this UAuthMode mode) + => mode switch + { + UAuthMode.PureOpaque => false, + + UAuthMode.Hybrid or + UAuthMode.SemiHybrid or + UAuthMode.PureJwt => true, + + _ => throw UnsupportedMode(mode) + }; + + public static bool SupportsRefreshToken(this UAuthMode mode) + => mode switch + { + UAuthMode.PureOpaque => false, + + UAuthMode.Hybrid or + UAuthMode.SemiHybrid or + UAuthMode.PureJwt => true, + + _ => throw UnsupportedMode(mode) + }; + + public static TokenFormat? GetAccessTokenFormat(this UAuthMode mode) + => mode switch + { + UAuthMode.PureOpaque => null, + + UAuthMode.Hybrid => TokenFormat.Opaque, + + UAuthMode.SemiHybrid or + UAuthMode.PureJwt => TokenFormat.Jwt, + + _ => throw UnsupportedMode(mode) + }; + + public static bool SupportsSurrogate(this UAuthMode mode, SurrogateKind kind) + => kind switch + { + SurrogateKind.SessionId + => mode.UsesSessionIdForAuthentication(), + + SurrogateKind.AccessToken + => mode.SupportsAccessToken(), + + SurrogateKind.RefreshToken + => mode.SupportsRefreshToken(), + + _ => throw new ArgumentOutOfRangeException( + nameof(kind), kind, "Unsupported surrogate kind.") + }; + + public static TokenFormat? GetTokenFormat(this UAuthMode mode, SurrogateKind kind) + { + if (!mode.SupportsSurrogate(kind)) + return null; + + return kind switch + { + SurrogateKind.SessionId => TokenFormat.Opaque, + SurrogateKind.AccessToken => mode.GetAccessTokenFormat(), + SurrogateKind.RefreshToken => TokenFormat.Opaque, + + _ => throw new ArgumentOutOfRangeException(nameof(kind), kind, "Unsupported surrogate kind.") + }; + } + + private static ArgumentOutOfRangeException UnsupportedMode(UAuthMode mode) + => new(nameof(mode), mode, "Unsupported authentication mode."); +} diff --git a/src/CodeBeam.UltimateAuth.Core/Options/TokenResponseMode.cs b/src/CodeBeam.UltimateAuth.Core/Options/TokenResponseMode.cs deleted file mode 100644 index d7b8f0ee..00000000 --- a/src/CodeBeam.UltimateAuth.Core/Options/TokenResponseMode.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace CodeBeam.UltimateAuth.Core.Options; - -[Obsolete("TokenResponseMode is no longer supported. Use GrantDeliveryMode instead.")] -public enum TokenResponseMode -{ - None = 0, - Cookie = 10, - Header = 20, - Body = 30 -} diff --git a/src/CodeBeam.UltimateAuth.Server/Abstractions/ICredentialResponseWriter.cs b/src/CodeBeam.UltimateAuth.Server/Abstractions/ICredentialResponseWriter.cs deleted file mode 100644 index 51be3f4b..00000000 --- a/src/CodeBeam.UltimateAuth.Server/Abstractions/ICredentialResponseWriter.cs +++ /dev/null @@ -1,12 +0,0 @@ -using CodeBeam.UltimateAuth.Core.Contracts; -using CodeBeam.UltimateAuth.Core.Domain; -using Microsoft.AspNetCore.Http; - -namespace CodeBeam.UltimateAuth.Server.Abstractions; - -public interface ICredentialResponseWriter -{ - void Write(HttpContext context, GrantKind kind, AuthSessionId sessionId); - void Write(HttpContext context, GrantKind kind, AccessToken accessToken); - void Write(HttpContext context, GrantKind kind, RefreshTokenInfo refreshToken); -} diff --git a/src/CodeBeam.UltimateAuth.Server/Abstractions/ISessionLineageValidator.cs b/src/CodeBeam.UltimateAuth.Server/Abstractions/ISessionLineageValidator.cs index aa8d6a39..ecb4fa34 100644 --- a/src/CodeBeam.UltimateAuth.Server/Abstractions/ISessionLineageValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Abstractions/ISessionLineageValidator.cs @@ -5,5 +5,5 @@ namespace CodeBeam.UltimateAuth.Server.Abstractions; public interface ISessionLineageValidator { - Task ValidateAsync(SessionValidationContext context, SessionCredentialPurpose expectedPurpose, CancellationToken ct = default); + Task ValidateAsync(SessionValidationContext context, SessionIdPurpose expectedPurpose, CancellationToken ct = default); } diff --git a/src/CodeBeam.UltimateAuth.Server/Abstractions/ISurrogateResponseWriter.cs b/src/CodeBeam.UltimateAuth.Server/Abstractions/ISurrogateResponseWriter.cs new file mode 100644 index 00000000..450776e2 --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/Abstractions/ISurrogateResponseWriter.cs @@ -0,0 +1,12 @@ +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; +using Microsoft.AspNetCore.Http; + +namespace CodeBeam.UltimateAuth.Server.Abstractions; + +public interface ISurrogateResponseWriter +{ + void Write(HttpContext context, SurrogateKind kind, AuthSessionId sessionId); + void Write(HttpContext context, SurrogateKind kind, AccessToken accessToken); + void Write(HttpContext context, SurrogateKind kind, RefreshTokenInfo refreshToken); +} diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowContext.cs b/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowContext.cs index 6fa0d95b..1f8a83c1 100644 --- a/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowContext.cs +++ b/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowContext.cs @@ -1,7 +1,7 @@ using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; using CodeBeam.UltimateAuth.Core.MultiTenancy; -using CodeBeam.UltimateAuth.Core.Options; +using CodeBeam.UltimateAuth.Core.Extensions; using CodeBeam.UltimateAuth.Server.Domain; using CodeBeam.UltimateAuth.Server.Infrastructure; using CodeBeam.UltimateAuth.Server.Options; @@ -26,12 +26,12 @@ public sealed class AuthFlowContext public EffectiveAuthResponse Response { get; } public ReturnUrlInfo ReturnUrlInfo { get; } - public PrimaryTokenKind PrimaryTokenKind { get; } + public SurrogateKind PrimarySurrogateKind => EffectiveMode.GetPrimarySurrogateKind(); // Helpers public bool AllowsTokenIssuance => - Response.AccessTokenDelivery.Mode != GrantDeliveryMode.None || - Response.RefreshTokenDelivery.Mode != GrantDeliveryMode.None; + Response.AccessTokenTransport.Mode != SurrogateTransport.None || + Response.RefreshTokenTransport.Mode != SurrogateTransport.None; public bool IsSingleTenant => Tenant.IsSingle; public bool IsMultiTenant => Tenant.IsNormal; @@ -47,7 +47,6 @@ internal AuthFlowContext( SessionSecurityContext? session, UAuthServerOptions options, EffectiveAuthResponse response, - PrimaryTokenKind primaryTokenKind, ReturnUrlInfo returnUrlInfo) { if (!tenantKey.IsValid || tenantKey.IsUnresolved) @@ -66,7 +65,6 @@ internal AuthFlowContext( Options = options; Response = response; - PrimaryTokenKind = primaryTokenKind; ReturnUrlInfo = returnUrlInfo; } diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowContextFactory.cs b/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowContextFactory.cs index 5fc3c942..69dcb6aa 100644 --- a/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowContextFactory.cs +++ b/src/CodeBeam.UltimateAuth.Server/Auth/Context/AuthFlowContextFactory.cs @@ -16,7 +16,6 @@ namespace CodeBeam.UltimateAuth.Server.Auth; internal sealed class AuthFlowContextFactory : IAuthFlowContextFactory { private readonly IApplicationProfileReader _applicationProfileReader; - private readonly IPrimaryTokenResolver _primaryTokenResolver; private readonly IEffectiveServerOptionsProvider _serverOptionsProvider; private readonly IAuthResponseResolver _authResponseResolver; private readonly IDeviceResolver _deviceResolver; @@ -27,7 +26,6 @@ internal sealed class AuthFlowContextFactory : IAuthFlowContextFactory public AuthFlowContextFactory( IApplicationProfileReader applicationProfileReader, - IPrimaryTokenResolver primaryTokenResolver, IEffectiveServerOptionsProvider serverOptionsProvider, IAuthResponseResolver authResponseResolver, IDeviceResolver deviceResolver, @@ -37,7 +35,6 @@ public AuthFlowContextFactory( IClock clock) { _applicationProfileReader = applicationProfileReader; - _primaryTokenResolver = primaryTokenResolver; _serverOptionsProvider = serverOptionsProvider; _authResponseResolver = authResponseResolver; _deviceResolver = deviceResolver; @@ -64,7 +61,6 @@ public async ValueTask CreateAsync(HttpContext ctx, AuthFlowTyp if (allowedModes is { Count: > 0 } && !allowedModes.Contains(effectiveMode)) throw new InvalidOperationException($"Auth mode '{effectiveMode}' is not allowed by server configuration."); - var primaryTokenKind = _primaryTokenResolver.Resolve(effectiveMode); var response = _authResponseResolver.Resolve(effectiveMode, flowType, applicationProfile, effective); var deviceInfo = await _deviceResolver.ResolveAsync(ctx); var deviceContext = _deviceContextFactory.Create(deviceInfo); @@ -168,7 +164,6 @@ public async ValueTask CreateAsync(HttpContext ctx, AuthFlowTyp sessionSecurityContext, options, response, - primaryTokenKind, returnUrlInfo ); } @@ -194,7 +189,6 @@ public async ValueTask RecreateWithApplicationProfileAsync(Auth throw new InvalidOperationException("An authenticated flow cannot change its authentication mode through a application profile override."); } - var primaryTokenKind = _primaryTokenResolver.Resolve(effectiveMode); var response = _authResponseResolver.Resolve(effectiveMode, flowType, overriddenProfile, effective); var returnUrlInfo = existing.ReturnUrlInfo; @@ -212,7 +206,6 @@ public async ValueTask RecreateWithApplicationProfileAsync(Auth session, options, response, - primaryTokenKind, returnUrlInfo ); } @@ -233,7 +226,6 @@ public ValueTask RecreateWithDeviceAsync(AuthFlowContext existi existing.Session, existing.Options, existing.Response, - existing.PrimaryTokenKind, existing.ReturnUrlInfo )); } diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/IPrimaryTokenResolver.cs b/src/CodeBeam.UltimateAuth.Server/Auth/IPrimaryTokenResolver.cs deleted file mode 100644 index 07a03b27..00000000 --- a/src/CodeBeam.UltimateAuth.Server/Auth/IPrimaryTokenResolver.cs +++ /dev/null @@ -1,8 +0,0 @@ -using CodeBeam.UltimateAuth.Core.Domain; - -namespace CodeBeam.UltimateAuth.Server.Auth; - -public interface IPrimaryTokenResolver -{ - PrimaryTokenKind Resolve(UAuthMode effectiveMode); -} diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/PrimaryTokenResolver.cs b/src/CodeBeam.UltimateAuth.Server/Auth/PrimaryTokenResolver.cs deleted file mode 100644 index 4f3fd31f..00000000 --- a/src/CodeBeam.UltimateAuth.Server/Auth/PrimaryTokenResolver.cs +++ /dev/null @@ -1,19 +0,0 @@ -using CodeBeam.UltimateAuth.Core.Domain; - -namespace CodeBeam.UltimateAuth.Server.Auth; - -internal sealed class PrimaryTokenResolver : IPrimaryTokenResolver -{ - public PrimaryTokenKind Resolve(UAuthMode effectiveMode) - { - return effectiveMode switch - { - UAuthMode.PureOpaque => PrimaryTokenKind.Session, - UAuthMode.Hybrid => PrimaryTokenKind.Session, - UAuthMode.SemiHybrid => PrimaryTokenKind.AccessToken, - UAuthMode.PureJwt => PrimaryTokenKind.AccessToken, - _ => throw new InvalidOperationException( - $"Unsupported auth mode: {effectiveMode}") - }; - } -} diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/Response/AuthResponseResolver.cs b/src/CodeBeam.UltimateAuth.Server/Auth/Response/AuthResponseResolver.cs index 5bfe525a..db6f403a 100644 --- a/src/CodeBeam.UltimateAuth.Server/Auth/Response/AuthResponseResolver.cs +++ b/src/CodeBeam.UltimateAuth.Server/Auth/Response/AuthResponseResolver.cs @@ -1,5 +1,5 @@ -using CodeBeam.UltimateAuth.Core.Contracts; -using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Core.Extensions; using CodeBeam.UltimateAuth.Server.Domain; using CodeBeam.UltimateAuth.Server.Options; using Microsoft.Net.Http.Headers; @@ -8,17 +8,21 @@ namespace CodeBeam.UltimateAuth.Server.Auth; internal sealed class AuthResponseResolver : IAuthResponseResolver { - public EffectiveAuthResponse Resolve(UAuthMode effectiveMode, AuthFlowType flowType, UAuthApplicationProfile applicationProfile, EffectiveUAuthServerOptions effectiveOptions) + public EffectiveAuthResponse Resolve( + UAuthMode effectiveMode, + AuthFlowType flowType, + UAuthApplicationProfile applicationProfile, + EffectiveUAuthServerOptions effectiveOptions) { var options = effectiveOptions.Options; var redirect = flowType switch { - AuthFlowType.Login or AuthFlowType.Reauthentication => - EffectiveRedirectResponse.FromLogin(options.Redirect.Login), + AuthFlowType.Login or AuthFlowType.Reauthentication + => EffectiveRedirectResponse.FromLogin(options.Redirect.Login), - AuthFlowType.Logout => - EffectiveRedirectResponse.FromLogout(options.Redirect.Logout), + AuthFlowType.Logout + => EffectiveRedirectResponse.FromLogout(options.Redirect.Logout), _ => EffectiveRedirectResponse.Disabled }; @@ -27,151 +31,98 @@ public EffectiveAuthResponse Resolve(UAuthMode effectiveMode, AuthFlowType flowT } public EffectiveAuthResponse ResolveForAuthentication(UAuthMode effectiveMode, UAuthApplicationProfile applicationProfile, EffectiveUAuthServerOptions effectiveOptions) - { - return ResolveCore(effectiveMode, applicationProfile, effectiveOptions, EffectiveRedirectResponse.Disabled); - } + => ResolveCore(effectiveMode, applicationProfile, effectiveOptions, EffectiveRedirectResponse.Disabled); - private EffectiveAuthResponse ResolveCore(UAuthMode effectiveMode, UAuthApplicationProfile applicationProfile, EffectiveUAuthServerOptions effectiveOptions, EffectiveRedirectResponse redirect) + private static EffectiveAuthResponse ResolveCore( + UAuthMode effectiveMode, + UAuthApplicationProfile applicationProfile, + EffectiveUAuthServerOptions effectiveOptions, + EffectiveRedirectResponse redirect) { var options = effectiveOptions.Options; - var delivery = options.GrantDelivery; - - var session = ResolveGrant( - GrantKind.Session, - TokenFormat.Opaque, - effectiveMode is UAuthMode.PureOpaque or UAuthMode.Hybrid, - effectiveMode is UAuthMode.PureOpaque or UAuthMode.Hybrid - ? GrantDeliveryMode.Cookie - : GrantDeliveryMode.None, - delivery.Session, - delivery.Default, - applicationProfile, - options); - - var accessToken = ResolveGrant( - GrantKind.AccessToken, - effectiveMode is UAuthMode.PureOpaque or UAuthMode.Hybrid - ? TokenFormat.Opaque - : TokenFormat.Jwt, - effectiveMode is UAuthMode.Hybrid - or UAuthMode.SemiHybrid - or UAuthMode.PureJwt, - effectiveMode == UAuthMode.PureOpaque - ? GrantDeliveryMode.None - : GrantDeliveryMode.Header, - delivery.AccessToken, - delivery.Default, - applicationProfile, - options); - - var refreshToken = ResolveGrant( - GrantKind.RefreshToken, - TokenFormat.Opaque, - effectiveMode is UAuthMode.Hybrid - or UAuthMode.SemiHybrid - or UAuthMode.PureJwt, - GrantDeliveryMode.Cookie, - delivery.RefreshToken, - delivery.Default, - applicationProfile, - options); - - var response = new EffectiveAuthResponse(session, accessToken, refreshToken, redirect); - GrantDeliveryCollisionValidator.Validate(response); + + var response = new EffectiveAuthResponse( + ResolveTransport(SurrogateKind.SessionId, effectiveMode, applicationProfile, options), + ResolveTransport(SurrogateKind.AccessToken, effectiveMode, applicationProfile, options), + ResolveTransport(SurrogateKind.RefreshToken, effectiveMode, applicationProfile, options), + redirect); + + SurrogateTransportCollisionValidator.Validate(response); return response; } - private static EffectiveGrantDelivery ResolveGrant( - GrantKind kind, - TokenFormat tokenFormat, - bool available, - GrantDeliveryMode modeDefault, - GrantDeliveryOptions configured, - GrantDeliveryMode? globalDefault, - UAuthApplicationProfile applicationProfile, - UAuthServerOptions server) + private static EffectiveSurrogateTransport ResolveTransport(SurrogateKind kind, UAuthMode effectiveMode, UAuthApplicationProfile applicationProfile, UAuthServerOptions server) { - if (!available) + var configured = kind switch + { + SurrogateKind.SessionId + => server.Transport.SessionId, + + SurrogateKind.AccessToken + => server.Transport.AccessToken, + + SurrogateKind.RefreshToken + => server.Transport.RefreshToken, + + _ => throw new ArgumentOutOfRangeException(nameof(kind)) + }; + + var tokenFormat = effectiveMode.GetTokenFormat(kind); + + if (tokenFormat is null) { - if (configured.Mode is not null && configured.Mode != GrantDeliveryMode.None) + if (configured.Mode is not null && configured.Mode != SurrogateTransport.None) { - throw new InvalidOperationException($"Grant '{kind}' is not available in the selected authentication mode."); + throw new InvalidOperationException($"Surrogate '{kind}' is not available in the selected authentication mode."); } - return EffectiveGrantDelivery.Disabled(kind); + return EffectiveSurrogateTransport.Disabled(kind); } - var profileDefault = applicationProfile == UAuthApplicationProfile.Maui && - modeDefault == GrantDeliveryMode.Cookie - ? GrantDeliveryMode.Header - : modeDefault; - var mode = configured.Mode - ?? globalDefault - ?? profileDefault; + ?? server.Transport.Default + ?? GetDefaultTransport(kind, applicationProfile); if (!Enum.IsDefined(mode)) { - throw new InvalidOperationException( - $"Invalid delivery mode '{mode}' for grant '{kind}'."); + throw new InvalidOperationException($"Invalid transport '{mode}' for surrogate '{kind}'."); } - if (mode == GrantDeliveryMode.None) + if (mode == SurrogateTransport.None) { - throw new InvalidOperationException( - $"Grant '{kind}' is required by the selected authentication mode " + - "and cannot have delivery mode None."); + throw new InvalidOperationException($"Surrogate '{kind}' is required by the selected authentication mode and cannot have transport None."); } - if (mode == GrantDeliveryMode.Body) + if (mode == SurrogateTransport.Body) { - throw new NotSupportedException($"Body grant delivery is not supported for '{kind}'."); + throw new NotSupportedException($"Body transport is not supported for '{kind}'."); } - var cookie = mode == GrantDeliveryMode.Cookie - ? kind switch - { - GrantKind.Session => server.Cookie.Session, - GrantKind.AccessToken => server.Cookie.AccessToken, - GrantKind.RefreshToken => server.Cookie.RefreshToken, - _ => throw new InvalidOperationException($"Unsupported grant kind '{kind}'.") - } + var cookie = mode == SurrogateTransport.Cookie + ? GetCookieOptions(kind, server) : null; if (cookie is not null) { - try - { - _ = new SetCookieHeaderValue(cookie.Name, "validation").ToString(); - } - catch (ArgumentException ex) - { - throw new InvalidOperationException($"Invalid cookie name '{cookie.Name}' for grant '{kind}'.", ex); - } + ValidateCookieName(cookie, kind); } - var headerName = configured.HeaderName ?? kind switch - { - GrantKind.Session => "uas", - GrantKind.AccessToken => "uat", - GrantKind.RefreshToken => "uar", - _ => throw new InvalidOperationException($"Unsupported grant kind '{kind}'.") - }; + var headerName = configured.HeaderName ?? GetDefaultHeaderName(kind); - var headerFormat = configured.HeaderFormat ?? HeaderTokenFormat.Bearer; + var headerFormat = configured.HeaderFormat ?? HeaderValueFormat.Bearer; - var requestHeaderName = kind == GrantKind.AccessToken + var requestHeaderName = kind == SurrogateKind.AccessToken ? "Authorization" : headerName; - var requestHeaderFormat = kind == GrantKind.AccessToken - ? HeaderTokenFormat.Bearer + var requestHeaderFormat = kind == SurrogateKind.AccessToken + ? HeaderValueFormat.Bearer : headerFormat; - return new EffectiveGrantDelivery( + return new EffectiveSurrogateTransport( kind, - tokenFormat, + tokenFormat.Value, mode, headerName, headerFormat, @@ -179,4 +130,54 @@ private static EffectiveGrantDelivery ResolveGrant( requestHeaderName, requestHeaderFormat); } + + private static SurrogateTransport GetDefaultTransport(SurrogateKind kind, UAuthApplicationProfile applicationProfile) + { + if (applicationProfile == UAuthApplicationProfile.Maui) + return SurrogateTransport.Header; + + return kind switch + { + SurrogateKind.SessionId => SurrogateTransport.Cookie, + SurrogateKind.AccessToken => SurrogateTransport.Header, + SurrogateKind.RefreshToken => SurrogateTransport.Cookie, + + _ => throw new ArgumentOutOfRangeException(nameof(kind)) + }; + } + + private static UAuthCookieOptions GetCookieOptions(SurrogateKind kind, UAuthServerOptions server) + => kind switch + { + SurrogateKind.SessionId => server.Cookie.Session, + SurrogateKind.AccessToken => server.Cookie.AccessToken, + SurrogateKind.RefreshToken => server.Cookie.RefreshToken, + + _ => throw new ArgumentOutOfRangeException(nameof(kind)) + }; + + private static string GetDefaultHeaderName(SurrogateKind kind) + => kind switch + { + SurrogateKind.SessionId => "uas", + SurrogateKind.AccessToken => "uat", + SurrogateKind.RefreshToken => "uar", + + _ => throw new ArgumentOutOfRangeException(nameof(kind)) + }; + + private static void ValidateCookieName(UAuthCookieOptions cookie, SurrogateKind kind) + { + try + { + _ = new SetCookieHeaderValue( + cookie.Name, "validation").ToString(); + } + catch (ArgumentException ex) + { + throw new InvalidOperationException( + $"Invalid cookie name '{cookie.Name}' " + + $"for surrogate '{kind}'.", ex); + } + } } diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/Response/EffectiveAuthResponse.cs b/src/CodeBeam.UltimateAuth.Server/Auth/Response/EffectiveAuthResponse.cs index f1d587ba..95a2c4aa 100644 --- a/src/CodeBeam.UltimateAuth.Server/Auth/Response/EffectiveAuthResponse.cs +++ b/src/CodeBeam.UltimateAuth.Server/Auth/Response/EffectiveAuthResponse.cs @@ -1,21 +1,33 @@ -namespace CodeBeam.UltimateAuth.Server.Auth; +using CodeBeam.UltimateAuth.Core.Domain; + +namespace CodeBeam.UltimateAuth.Server.Auth; public sealed class EffectiveAuthResponse { - public EffectiveGrantDelivery SessionIdDelivery { get; } - public EffectiveGrantDelivery AccessTokenDelivery { get; } - public EffectiveGrantDelivery RefreshTokenDelivery { get; } + public EffectiveSurrogateTransport SessionIdTransport { get; } + public EffectiveSurrogateTransport AccessTokenTransport { get; } + public EffectiveSurrogateTransport RefreshTokenTransport { get; } public EffectiveRedirectResponse Redirect { get; } public EffectiveAuthResponse( - EffectiveGrantDelivery sessionIdDelivery, - EffectiveGrantDelivery accessTokenDelivery, - EffectiveGrantDelivery refreshTokenDelivery, + EffectiveSurrogateTransport sessionIdTransport, + EffectiveSurrogateTransport accessTokenTransport, + EffectiveSurrogateTransport refreshTokenTransport, EffectiveRedirectResponse redirect) { - SessionIdDelivery = sessionIdDelivery; - AccessTokenDelivery = accessTokenDelivery; - RefreshTokenDelivery = refreshTokenDelivery; + SessionIdTransport = sessionIdTransport; + AccessTokenTransport = accessTokenTransport; + RefreshTokenTransport = refreshTokenTransport; Redirect = redirect; } + + public EffectiveSurrogateTransport GetTransport(SurrogateKind kind) + => kind switch + { + SurrogateKind.SessionId => SessionIdTransport, + SurrogateKind.AccessToken => AccessTokenTransport, + SurrogateKind.RefreshToken => RefreshTokenTransport, + + _ => throw new ArgumentOutOfRangeException(nameof(kind)) + }; } diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/Response/EffectiveGrantDelivery.cs b/src/CodeBeam.UltimateAuth.Server/Auth/Response/EffectiveSurrogateTransport.cs similarity index 58% rename from src/CodeBeam.UltimateAuth.Server/Auth/Response/EffectiveGrantDelivery.cs rename to src/CodeBeam.UltimateAuth.Server/Auth/Response/EffectiveSurrogateTransport.cs index b433395b..98e9e314 100644 --- a/src/CodeBeam.UltimateAuth.Server/Auth/Response/EffectiveGrantDelivery.cs +++ b/src/CodeBeam.UltimateAuth.Server/Auth/Response/EffectiveSurrogateTransport.cs @@ -5,29 +5,29 @@ namespace CodeBeam.UltimateAuth.Server.Auth; -public sealed class EffectiveGrantDelivery +public sealed class EffectiveSurrogateTransport { - public GrantKind Kind { get; } + public SurrogateKind Kind { get; } public TokenFormat TokenFormat { get; } - public GrantDeliveryMode Mode { get; } + public SurrogateTransport Mode { get; } public string? Name { get; } - public HeaderTokenFormat HeaderFormat { get; } + public HeaderValueFormat HeaderFormat { get; } public string? RequestHeaderName { get; } - public HeaderTokenFormat RequestHeaderFormat { get; } + public HeaderValueFormat RequestHeaderFormat { get; } public UAuthCookieOptions? Cookie { get; } - public EffectiveGrantDelivery( - GrantKind kind, + public EffectiveSurrogateTransport( + SurrogateKind kind, TokenFormat tokenFormat, - GrantDeliveryMode mode, + SurrogateTransport mode, string? name = null, - HeaderTokenFormat headerFormat = HeaderTokenFormat.Bearer, + HeaderValueFormat headerFormat = HeaderValueFormat.Bearer, UAuthCookieOptions? cookie = null, string? requestHeaderName = null, - HeaderTokenFormat? requestHeaderFormat = null) + HeaderValueFormat? requestHeaderFormat = null) { Kind = kind; TokenFormat = tokenFormat; @@ -42,6 +42,6 @@ public EffectiveGrantDelivery( Cookie = cookie; } - public static EffectiveGrantDelivery Disabled(GrantKind kind) - => new(kind, TokenFormat.Opaque, GrantDeliveryMode.None); + public static EffectiveSurrogateTransport Disabled(SurrogateKind kind) + => new(kind, TokenFormat.Opaque, SurrogateTransport.None); } diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/Response/GrantDeliveryCollisionValidator.cs b/src/CodeBeam.UltimateAuth.Server/Auth/Response/SurrogateTransportCollisionValidator.cs similarity index 59% rename from src/CodeBeam.UltimateAuth.Server/Auth/Response/GrantDeliveryCollisionValidator.cs rename to src/CodeBeam.UltimateAuth.Server/Auth/Response/SurrogateTransportCollisionValidator.cs index 13978318..dc087f5a 100644 --- a/src/CodeBeam.UltimateAuth.Server/Auth/Response/GrantDeliveryCollisionValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Auth/Response/SurrogateTransportCollisionValidator.cs @@ -3,31 +3,31 @@ namespace CodeBeam.UltimateAuth.Server.Auth; // TODO: Support collision detection with externally configured authentication schemes and reserved credential transport names. -internal static class GrantDeliveryCollisionValidator +internal static class SurrogateTransportCollisionValidator { public static void Validate(EffectiveAuthResponse response) { var grants = new[] { - response.SessionIdDelivery, - response.AccessTokenDelivery, - response.RefreshTokenDelivery + response.SessionIdTransport, + response.AccessTokenTransport, + response.RefreshTokenTransport }; - ValidateNames(grants, GrantDeliveryMode.Cookie, grant => grant.Cookie?.Name, "cookie"); + ValidateNames(grants, SurrogateTransport.Cookie, grant => grant.Cookie?.Name, "cookie"); - ValidateNames(grants, GrantDeliveryMode.Header, grant => grant.Name, "response header"); + ValidateNames(grants, SurrogateTransport.Header, grant => grant.Name, "response header"); - ValidateNames(grants, GrantDeliveryMode.Header, grant => grant.RequestHeaderName, "request header"); + ValidateNames(grants, SurrogateTransport.Header, grant => grant.RequestHeaderName, "request header"); } private static void ValidateNames( - IEnumerable grants, - GrantDeliveryMode mode, - Func nameSelector, + IEnumerable grants, + SurrogateTransport mode, + Func nameSelector, string source) { - var names = new Dictionary(StringComparer.OrdinalIgnoreCase); + var names = new Dictionary(StringComparer.OrdinalIgnoreCase); foreach (var grant in grants) { diff --git a/src/CodeBeam.UltimateAuth.Server/Auth/SemiHybridAuthorityValidator.cs b/src/CodeBeam.UltimateAuth.Server/Auth/SemiHybridAuthorityValidator.cs index 08d1f133..2790df0e 100644 --- a/src/CodeBeam.UltimateAuth.Server/Auth/SemiHybridAuthorityValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Auth/SemiHybridAuthorityValidator.cs @@ -84,7 +84,7 @@ private async Task ValidateCoreAsync( SessionOptions = sessionOptions, Now = _clock.UtcNow }, - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, ct); if (!result.IsValid) diff --git a/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthAuthenticationHandler.cs b/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthAuthenticationHandler.cs index 6e5b8abf..970db14e 100644 --- a/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthAuthenticationHandler.cs +++ b/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthAuthenticationHandler.cs @@ -19,7 +19,7 @@ namespace CodeBeam.UltimateAuth.Server.Authentication; internal sealed class UAuthAuthenticationHandler : AuthenticationHandler { - private readonly ITransportCredentialResolver _transportCredentialResolver; + private readonly ISurrogateResolver _surrogateResolver; private readonly ISessionValidator _sessionValidator; private readonly IDeviceContextFactory _deviceContextFactory; private readonly IAuthStateSnapshotFactory _snapshotFactory; @@ -31,7 +31,7 @@ internal sealed class UAuthAuthenticationHandler : AuthenticationHandler options, ILoggerFactory logger, UrlEncoder encoder, @@ -46,7 +46,7 @@ public UAuthAuthenticationHandler( IClock uauthClock) : base(options, logger, encoder) { - _transportCredentialResolver = transportCredentialResolver; + _surrogateResolver = surrogateResolver; _sessionValidator = sessionValidator; _deviceContextFactory = deviceContextFactory; _snapshotFactory = snapshotFactory; @@ -68,14 +68,14 @@ protected override async Task HandleAuthenticateAsync() var response = _authResponseResolver.ResolveForAuthentication(mode, applicationProfile, effective); - var credential = await _transportCredentialResolver.ResolveAsync(Context, mode, response); + var credential = await _surrogateResolver.ResolvePrimaryAsync(Context, mode, response); if (mode is UAuthMode.PureJwt or UAuthMode.SemiHybrid) { if (credential is null) return AuthenticateResult.NoResult(); - if (credential.Kind != TransportCredentialKind.AccessToken) + if (credential.Kind != SurrogateKind.AccessToken) { return AuthenticateResult.Fail("JWT authentication requires an access token."); } diff --git a/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthResourceAuthenticationHandler.cs b/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthResourceAuthenticationHandler.cs index 5366576d..8c05f793 100644 --- a/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthResourceAuthenticationHandler.cs +++ b/src/CodeBeam.UltimateAuth.Server/Authentication/AspNetCore/UAuthResourceAuthenticationHandler.cs @@ -3,9 +3,8 @@ using CodeBeam.UltimateAuth.Core.Defaults; using CodeBeam.UltimateAuth.Core.Domain; using CodeBeam.UltimateAuth.Core.MultiTenancy; +using CodeBeam.UltimateAuth.Core.Extensions; using CodeBeam.UltimateAuth.Server.Abstractions; -using CodeBeam.UltimateAuth.Server.Auth; -using CodeBeam.UltimateAuth.Server.Domain; using CodeBeam.UltimateAuth.Server.Extensions; using CodeBeam.UltimateAuth.Server.Infrastructure; using CodeBeam.UltimateAuth.Server.Options; @@ -21,7 +20,7 @@ namespace CodeBeam.UltimateAuth.Server.Authentication; internal sealed class UAuthResourceAuthenticationHandler : AuthenticationHandler { - private readonly ITransportCredentialResolver _credentialResolver; + private readonly ISurrogateResolver _surrogateResolver; private readonly ISessionValidator _sessionValidator; private readonly IDeviceContextFactory _deviceFactory; private readonly IServiceProvider _services; @@ -30,7 +29,7 @@ internal sealed class UAuthResourceAuthenticationHandler : AuthenticationHandler private readonly IClock _clock; public UAuthResourceAuthenticationHandler( - ITransportCredentialResolver credentialResolver, + ISurrogateResolver surrogateResolver, ISessionValidator sessionValidator, IDeviceContextFactory deviceFactory, IServiceProvider services, @@ -42,7 +41,7 @@ public UAuthResourceAuthenticationHandler( UrlEncoder encoder) : base(options, logger, encoder) { - _credentialResolver = credentialResolver; + _surrogateResolver = surrogateResolver; _sessionValidator = sessionValidator; _deviceFactory = deviceFactory; _services = services; @@ -56,51 +55,43 @@ protected override async Task HandleAuthenticateAsync() var tenant = Context.GetTenant(); var mode = _modeProvider.Mode; - return mode is UAuthMode.PureJwt or UAuthMode.SemiHybrid - ? await AuthenticateJwtAsync(tenant, mode) - : await AuthenticateSessionAsync(tenant); + return mode.GetPrimarySurrogateKind() switch + { + SurrogateKind.SessionId + => await AuthenticateSessionAsync(tenant), + + SurrogateKind.AccessToken + => await AuthenticateJwtAsync(tenant, mode), + + _ => AuthenticateResult.Fail("Unsupported primary surrogate.") + }; } private async Task AuthenticateSessionAsync(TenantKey tenant) { - var mode = _modeProvider.Mode; - - var sessionDelivery = new EffectiveGrantDelivery( - GrantKind.Session, - TokenFormat.Opaque, - _resourceOptions.Auth.Session.DeliveryMode, - name: "Authorization", - headerFormat: HeaderTokenFormat.Bearer, - cookie: new UAuthCookieOptions - { - Name = _resourceOptions.Auth.Session.CookieName - }); - - var response = new EffectiveAuthResponse( - sessionDelivery, - EffectiveGrantDelivery.Disabled(GrantKind.AccessToken), - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), - EffectiveRedirectResponse.Disabled); + var transport = ResourceSurrogateTransportFactory.CreateSessionId(_resourceOptions.Auth); - var credential = await _credentialResolver.ResolveAsync(Context, mode, response); + var surrogate = await _surrogateResolver.ResolveAsync(Context, transport); - if (credential is null) + if (surrogate is null) return AuthenticateResult.NoResult(); - if (credential.Kind != TransportCredentialKind.Session) + if (surrogate.Kind != SurrogateKind.SessionId) { - return AuthenticateResult.Fail("Resource authentication requires a session credential."); + return AuthenticateResult.Fail("Resource authentication requires a session surrogate."); } - if (!AuthSessionId.TryCreate(credential.Value, out var sessionId)) + if (!AuthSessionId.TryCreate(surrogate.Value, out var sessionId)) + { return AuthenticateResult.Fail("Invalid session"); + } var result = await _sessionValidator.ValidateSessionAsync( new SessionValidationContext { Tenant = tenant, SessionId = sessionId, - Device = _deviceFactory.Create(credential.Device), + Device = _deviceFactory.Create(surrogate.Device), Now = _clock.UtcNow }, Context.RequestAborted); @@ -128,39 +119,26 @@ private async Task AuthenticateSessionAsync(TenantKey tenant private async Task AuthenticateJwtAsync(TenantKey tenant, UAuthMode mode) { - var accessDelivery = new EffectiveGrantDelivery( - GrantKind.AccessToken, - TokenFormat.Jwt, - _resourceOptions.Auth.AccessToken.DeliveryMode, - name: _resourceOptions.Auth.AccessToken.HeaderName, - headerFormat: _resourceOptions.Auth.AccessToken.HeaderFormat, - cookie: new UAuthCookieOptions - { - Name = _resourceOptions.Auth.AccessToken.CookieName - }); + var transport = ResourceSurrogateTransportFactory.CreateAccessToken(mode, _resourceOptions.Auth); - var response = new EffectiveAuthResponse( - EffectiveGrantDelivery.Disabled(GrantKind.Session), - accessDelivery, - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), - EffectiveRedirectResponse.Disabled); + var surrogate = await _surrogateResolver.ResolveAsync(Context, transport); - var credential = await _credentialResolver.ResolveAsync(Context, mode, response); - - if (credential is null) + if (surrogate is null) return AuthenticateResult.NoResult(); - if (credential.Kind != TransportCredentialKind.AccessToken) + if (surrogate.Kind != SurrogateKind.AccessToken) { 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(surrogate.Value, tenant, Context.RequestAborted); if (validated is null) + { return AuthenticateResult.Fail("Invalid JWT access token."); + } var mismatchBehavior = _resourceOptions.Auth.Device.MismatchBehavior; @@ -176,7 +154,14 @@ private async Task AuthenticateJwtAsync(TenantKey tenant, UA } } - if (!UAuthJwtPrincipalFactory.TryCreate(validated, mode, mismatchBehavior, requestDeviceId, Scheme.Name, out var principal) || principal is null) + if (!UAuthJwtPrincipalFactory.TryCreate( + validated, + mode, + mismatchBehavior, + requestDeviceId, + Scheme.Name, + out var principal) || + principal is null) { return AuthenticateResult.Fail("JWT identity does not satisfy authentication mode."); } diff --git a/src/CodeBeam.UltimateAuth.Server/Domain/HeaderTokenFormat.cs b/src/CodeBeam.UltimateAuth.Server/Domain/HeaderTokenFormat.cs deleted file mode 100644 index 42fdd5de..00000000 --- a/src/CodeBeam.UltimateAuth.Server/Domain/HeaderTokenFormat.cs +++ /dev/null @@ -1,7 +0,0 @@ -namespace CodeBeam.UltimateAuth.Server.Domain; - -public enum HeaderTokenFormat -{ - Bearer = 0, - Raw = 10 -} diff --git a/src/CodeBeam.UltimateAuth.Server/Domain/HeaderValueFormat.cs b/src/CodeBeam.UltimateAuth.Server/Domain/HeaderValueFormat.cs new file mode 100644 index 00000000..bf27f007 --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/Domain/HeaderValueFormat.cs @@ -0,0 +1,10 @@ +namespace CodeBeam.UltimateAuth.Server.Domain; + +/// +/// Defines how a value is represented in an HTTP header. +/// +public enum HeaderValueFormat +{ + Bearer = 0, + Raw = 10 +} diff --git a/src/CodeBeam.UltimateAuth.Server/Domain/GrantDeliveryMode.cs b/src/CodeBeam.UltimateAuth.Server/Domain/SurrogateTransport.cs similarity index 95% rename from src/CodeBeam.UltimateAuth.Server/Domain/GrantDeliveryMode.cs rename to src/CodeBeam.UltimateAuth.Server/Domain/SurrogateTransport.cs index a955a20d..d043328d 100644 --- a/src/CodeBeam.UltimateAuth.Server/Domain/GrantDeliveryMode.cs +++ b/src/CodeBeam.UltimateAuth.Server/Domain/SurrogateTransport.cs @@ -3,7 +3,7 @@ /// /// Defines how an issued authentication grant is delivered to the client in an HTTP response. /// -public enum GrantDeliveryMode +public enum SurrogateTransport { /// /// The grant is not delivered. diff --git a/src/CodeBeam.UltimateAuth.Server/Endpoints/LoginEndpointHandler.cs b/src/CodeBeam.UltimateAuth.Server/Endpoints/LoginEndpointHandler.cs index 6cccc125..47e3e67a 100644 --- a/src/CodeBeam.UltimateAuth.Server/Endpoints/LoginEndpointHandler.cs +++ b/src/CodeBeam.UltimateAuth.Server/Endpoints/LoginEndpointHandler.cs @@ -20,7 +20,7 @@ internal sealed class LoginEndpointHandler : ILoginEndpointHandler { private readonly IAuthFlowContextAccessor _authFlow; private readonly IUAuthInternalFlowService _internalFlowService; - private readonly ICredentialResponseWriter _credentialResponseWriter; + private readonly ISurrogateResponseWriter _credentialResponseWriter; private readonly IAuthRedirectResolver _redirectResolver; private readonly IAuthStore _authStore; private readonly ILoginIdentifierResolver _loginIdentifierResolver; @@ -30,7 +30,7 @@ internal sealed class LoginEndpointHandler : ILoginEndpointHandler public LoginEndpointHandler( IAuthFlowContextAccessor authFlow, IUAuthInternalFlowService internalFlowService, - ICredentialResponseWriter credentialResponseWriter, + ISurrogateResponseWriter credentialResponseWriter, IAuthRedirectResolver redirectResolver, IAuthStore authStore, ILoginIdentifierResolver loginIdentifierResolver, @@ -60,7 +60,7 @@ public async Task LoginAsync(HttpContext ctx) var isFetch = ctx.Request.HasFormContentType && (await ctx.GetCachedFormAsync())?["__uauth_response_mode"].FirstOrDefault() == "fetch"; - if (!isFetch && (authFlow.Response.AccessTokenDelivery.Mode == GrantDeliveryMode.Header || authFlow.Response.SessionIdDelivery.Mode == GrantDeliveryMode.Header)) + if (!isFetch && (authFlow.Response.AccessTokenTransport.Mode == SurrogateTransport.Header || authFlow.Response.SessionIdTransport.Mode == SurrogateTransport.Header)) { return Results.BadRequest(new { @@ -156,17 +156,17 @@ public async Task LoginAsync(HttpContext ctx) if (result.SessionId is AuthSessionId sessionId) { - _credentialResponseWriter.Write(ctx, GrantKind.Session, sessionId); + _credentialResponseWriter.Write(ctx, SurrogateKind.SessionId, sessionId); } if (result.AccessToken is not null) { - _credentialResponseWriter.Write(ctx, GrantKind.AccessToken, result.AccessToken); + _credentialResponseWriter.Write(ctx, SurrogateKind.AccessToken, result.AccessToken); } if (result.RefreshToken is not null) { - _credentialResponseWriter.Write(ctx, GrantKind.RefreshToken, result.RefreshToken); + _credentialResponseWriter.Write(ctx, SurrogateKind.RefreshToken, result.RefreshToken); } var decision = _redirectResolver.ResolveSuccess(authFlow, ctx); diff --git a/src/CodeBeam.UltimateAuth.Server/Endpoints/LogoutEndpointHandler.cs b/src/CodeBeam.UltimateAuth.Server/Endpoints/LogoutEndpointHandler.cs index 4376b73f..7f090159 100644 --- a/src/CodeBeam.UltimateAuth.Server/Endpoints/LogoutEndpointHandler.cs +++ b/src/CodeBeam.UltimateAuth.Server/Endpoints/LogoutEndpointHandler.cs @@ -58,9 +58,9 @@ await _flow.LogoutAsync( } } - DeleteIfCookie(ctx, authFlow.Response.SessionIdDelivery); - DeleteIfCookie(ctx, authFlow.Response.RefreshTokenDelivery); - DeleteIfCookie(ctx, authFlow.Response.AccessTokenDelivery); + DeleteIfCookie(ctx, authFlow.Response.SessionIdTransport); + DeleteIfCookie(ctx, authFlow.Response.RefreshTokenTransport); + DeleteIfCookie(ctx, authFlow.Response.AccessTokenTransport); var decision = _redirectResolver.ResolveSuccess(authFlow, ctx); @@ -199,9 +199,9 @@ public async Task LogoutAllAdminAsync(HttpContext ctx, UserKey userKey) return Results.Ok(); } - private void DeleteIfCookie(HttpContext ctx, EffectiveGrantDelivery delivery) + private void DeleteIfCookie(HttpContext ctx, EffectiveSurrogateTransport delivery) { - if (delivery.Mode != GrantDeliveryMode.Cookie) + if (delivery.Mode != SurrogateTransport.Cookie) return; var cookie = delivery.Cookie diff --git a/src/CodeBeam.UltimateAuth.Server/Endpoints/PkceEndpointHandler.cs b/src/CodeBeam.UltimateAuth.Server/Endpoints/PkceEndpointHandler.cs index 4a7ddbc5..d6b9e0f6 100644 --- a/src/CodeBeam.UltimateAuth.Server/Endpoints/PkceEndpointHandler.cs +++ b/src/CodeBeam.UltimateAuth.Server/Endpoints/PkceEndpointHandler.cs @@ -28,7 +28,7 @@ internal sealed class PkceEndpointHandler : IPkceEndpointHandler private readonly IAuthStore _authStore; private readonly IPkceAuthorizationValidator _validator; private readonly IClock _clock; - private readonly ICredentialResponseWriter _credentialResponseWriter; + private readonly ISurrogateResponseWriter _credentialResponseWriter; private readonly IAuthRedirectResolver _redirectResolver; public PkceEndpointHandler( @@ -39,7 +39,7 @@ public PkceEndpointHandler( IAuthStore authStore, IPkceAuthorizationValidator validator, IClock clock, - ICredentialResponseWriter credentialResponseWriter, + ISurrogateResponseWriter credentialResponseWriter, IAuthRedirectResolver redirectResolver) { _authContext = authContext; @@ -162,8 +162,8 @@ public async Task CompleteAsync(HttpContext ctx) var isFetch = ctx.Request.HasFormContentType && (await ctx.GetCachedFormAsync())?["__uauth_response_mode"].FirstOrDefault() == "fetch"; if (!isFetch && - (auth.Response.AccessTokenDelivery.Mode == GrantDeliveryMode.Header || - auth.Response.SessionIdDelivery.Mode == GrantDeliveryMode.Header)) + (auth.Response.AccessTokenTransport.Mode == SurrogateTransport.Header || + auth.Response.SessionIdTransport.Mode == SurrogateTransport.Header)) { return Results.BadRequest(new { @@ -210,13 +210,13 @@ public async Task CompleteAsync(HttpContext ctx) var login = result.LoginResult!; if (login.SessionId is not null) - _credentialResponseWriter.Write(ctx, GrantKind.Session, login.SessionId.Value); + _credentialResponseWriter.Write(ctx, SurrogateKind.SessionId, login.SessionId.Value); if (login.AccessToken is not null) - _credentialResponseWriter.Write(ctx, GrantKind.AccessToken, login.AccessToken); + _credentialResponseWriter.Write(ctx, SurrogateKind.AccessToken, login.AccessToken); if (login.RefreshToken is not null) - _credentialResponseWriter.Write(ctx, GrantKind.RefreshToken, login.RefreshToken); + _credentialResponseWriter.Write(ctx, SurrogateKind.RefreshToken, login.RefreshToken); var decision = _redirectResolver.ResolveSuccess(auth, ctx); diff --git a/src/CodeBeam.UltimateAuth.Server/Endpoints/RefreshEndpointHandler.cs b/src/CodeBeam.UltimateAuth.Server/Endpoints/RefreshEndpointHandler.cs index 6f1ff5cf..825063c3 100644 --- a/src/CodeBeam.UltimateAuth.Server/Endpoints/RefreshEndpointHandler.cs +++ b/src/CodeBeam.UltimateAuth.Server/Endpoints/RefreshEndpointHandler.cs @@ -12,7 +12,7 @@ public sealed class RefreshEndpointHandler : IRefreshEndpointHandler { private readonly IAuthFlowContextAccessor _authContext; private readonly IRefreshFlowService _refreshFlow; - private readonly ICredentialResponseWriter _credentialWriter; + private readonly ISurrogateResponseWriter _credentialWriter; private readonly IRefreshResponseWriter _refreshWriter; private readonly IRefreshTokenResolver _refreshTokenResolver; private readonly IRefreshResponsePolicy _refreshPolicy; @@ -20,7 +20,7 @@ public sealed class RefreshEndpointHandler : IRefreshEndpointHandler public RefreshEndpointHandler( IAuthFlowContextAccessor authContext, IRefreshFlowService refreshFlow, - ICredentialResponseWriter credentialWriter, + ISurrogateResponseWriter credentialWriter, IRefreshResponseWriter refreshWriter, IRefreshTokenResolver refreshTokenResolver, IRefreshResponsePolicy refreshPolicy) @@ -58,18 +58,18 @@ public async Task RefreshAsync(HttpContext ctx) var primary = _refreshPolicy.SelectPrimary(flow, request, result); - if (primary == GrantKind.Session && result.SessionId is not null) + if (primary == SurrogateKind.SessionId && result.SessionId is not null) { - _credentialWriter.Write(ctx, GrantKind.Session, result.SessionId.Value); + _credentialWriter.Write(ctx, SurrogateKind.SessionId, result.SessionId.Value); } - else if (primary == GrantKind.AccessToken && result.AccessToken is not null) + else if (primary == SurrogateKind.AccessToken && result.AccessToken is not null) { - _credentialWriter.Write(ctx, GrantKind.AccessToken, result.AccessToken); + _credentialWriter.Write(ctx, SurrogateKind.AccessToken, result.AccessToken); } if (_refreshPolicy.WriteRefreshToken(flow) && result.RefreshToken is not null) { - _credentialWriter.Write(ctx, GrantKind.RefreshToken, result.RefreshToken); + _credentialWriter.Write(ctx, SurrogateKind.RefreshToken, result.RefreshToken); } if (flow.Options.Diagnostics.EnableRefreshDetails) diff --git a/src/CodeBeam.UltimateAuth.Server/Endpoints/UAuthLoginTransportEndpoint.cs b/src/CodeBeam.UltimateAuth.Server/Endpoints/UAuthLoginTransportEndpoint.cs index d8be8510..edf100d0 100644 --- a/src/CodeBeam.UltimateAuth.Server/Endpoints/UAuthLoginTransportEndpoint.cs +++ b/src/CodeBeam.UltimateAuth.Server/Endpoints/UAuthLoginTransportEndpoint.cs @@ -10,15 +10,14 @@ public static IResult Get(HttpContext context, IAuthFlowContextAccessor accessor { var response = accessor.Current.Response; - var sessionHeader = response.SessionIdDelivery.Mode == GrantDeliveryMode.Header; + var sessionHeader = response.SessionIdTransport.Mode == SurrogateTransport.Header; - var accessHeader = response.AccessTokenDelivery.Mode == GrantDeliveryMode.Header; + var accessHeader = response.AccessTokenTransport.Mode == SurrogateTransport.Header; context.Response.Headers.CacheControl = "no-store"; return Results.Ok(new { - // The current client does not manage header-delivered opaque session IDs. Supported = !sessionHeader, // Native navigation cannot capture response headers. diff --git a/src/CodeBeam.UltimateAuth.Server/Endpoints/ValidateEndpointHandler.cs b/src/CodeBeam.UltimateAuth.Server/Endpoints/ValidateEndpointHandler.cs index 35ab0d30..c819f4f9 100644 --- a/src/CodeBeam.UltimateAuth.Server/Endpoints/ValidateEndpointHandler.cs +++ b/src/CodeBeam.UltimateAuth.Server/Endpoints/ValidateEndpointHandler.cs @@ -14,7 +14,7 @@ namespace CodeBeam.UltimateAuth.Server.Endpoints; internal sealed class ValidateEndpointHandler : IValidateEndpointHandler { private readonly IAuthFlowContextAccessor _authContext; - private readonly ITransportCredentialResolver _credentialResolver; + private readonly ISurrogateResolver _surrogateResolver; private readonly ISessionValidator _sessionValidator; private readonly SemiHybridAuthorityValidator _authorityValidator; private readonly IAuthStateSnapshotFactory _snapshotFactory; @@ -22,14 +22,14 @@ internal sealed class ValidateEndpointHandler : IValidateEndpointHandler public ValidateEndpointHandler( IAuthFlowContextAccessor authContext, - ITransportCredentialResolver credentialResolver, + ISurrogateResolver surrogateResolver, ISessionValidator sessionValidator, SemiHybridAuthorityValidator authorityValidator, IAuthStateSnapshotFactory snapshotFactory, IClock clock) { _authContext = authContext; - _credentialResolver = credentialResolver; + _surrogateResolver = surrogateResolver; _sessionValidator = sessionValidator; _authorityValidator = authorityValidator; _snapshotFactory = snapshotFactory; @@ -45,9 +45,9 @@ public async Task ValidateAsync(HttpContext context, CancellationToken return await ValidateJwtAsync(context, auth, ct); } - var credential = await _credentialResolver.ResolveAsync(context, auth.EffectiveMode, auth.Response); + var surrogate = await _surrogateResolver.ResolvePrimaryAsync(context, auth.EffectiveMode, auth.Response); - if (credential is null) + if (surrogate is null) { return Results.Json( new AuthValidationResult @@ -58,9 +58,9 @@ public async Task ValidateAsync(HttpContext context, CancellationToken ); } - if (credential.Kind == TransportCredentialKind.Session) + if (surrogate.Kind == SurrogateKind.SessionId) { - if (!AuthSessionId.TryCreate(credential.Value, out var sessionId)) + if (!AuthSessionId.TryCreate(surrogate.Value, out var sessionId)) { return Results.Json( new AuthValidationResult diff --git a/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs b/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs index 2cae5fe3..0febdd24 100644 --- a/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs +++ b/src/CodeBeam.UltimateAuth.Server/Extensions/ServiceCollectionExtensions.cs @@ -233,7 +233,7 @@ private static IServiceCollection AddUltimateAuthServerInternal(this IServiceCol sp.GetRequiredService(), sp.GetRequiredService(), sp.GetRequiredService(), - sp.GetRequiredService())); + sp.GetRequiredService())); services.TryAddScoped(); services.TryAddScoped(); @@ -281,10 +281,9 @@ private static IServiceCollection AddUltimateAuthServerInternal(this IServiceCol services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); - services.TryAddScoped(); + services.TryAddScoped(); services.TryAddSingleton(); services.TryAddSingleton(); - services.TryAddSingleton(); services.TryAddSingleton(); services.TryAddScoped(); @@ -319,7 +318,7 @@ private static IServiceCollection AddUltimateAuthServerInternal(this IServiceCol }); }); - services.TryAddScoped(); + services.TryAddScoped(); services.TryAddScoped(); services.TryAddSingleton(); @@ -515,10 +514,9 @@ private static IServiceCollection AddUltimateAuthResourceInternal(this IServiceC services.TryAddScoped(); services.TryAddScoped(); - services.TryAddScoped(); + services.TryAddScoped(); services.TryAddScoped(); services.TryAddScoped(); - services.TryAddSingleton(); services.TryAddSingleton(); diff --git a/src/CodeBeam.UltimateAuth.Server/Extensions/SurrogateResolverExtensions.cs b/src/CodeBeam.UltimateAuth.Server/Extensions/SurrogateResolverExtensions.cs new file mode 100644 index 00000000..d4188dc6 --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/Extensions/SurrogateResolverExtensions.cs @@ -0,0 +1,17 @@ +using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Core.Extensions; +using CodeBeam.UltimateAuth.Server.Auth; +using CodeBeam.UltimateAuth.Server.Infrastructure; +using Microsoft.AspNetCore.Http; + +namespace CodeBeam.UltimateAuth.Server.Extensions; + +public static class SurrogateResolverExtensions +{ + public static ValueTask ResolvePrimaryAsync(this ISurrogateResolver resolver, HttpContext context, UAuthMode mode, EffectiveAuthResponse response) + { + var kind = mode.GetPrimarySurrogateKind(); + + return resolver.ResolveAsync(context, response.GetTransport(kind)); + } +} diff --git a/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/IRefreshResponsePolicy.cs b/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/IRefreshResponsePolicy.cs index 9d8e1515..ad2dcd7b 100644 --- a/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/IRefreshResponsePolicy.cs +++ b/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/IRefreshResponsePolicy.cs @@ -6,6 +6,6 @@ namespace CodeBeam.UltimateAuth.Server.Flows; public interface IRefreshResponsePolicy { - GrantKind SelectPrimary(AuthFlowContext flow, RefreshFlowRequest request, RefreshFlowResult result); + SurrogateKind SelectPrimary(AuthFlowContext flow, RefreshFlowRequest request, RefreshFlowResult result); bool WriteRefreshToken(AuthFlowContext flow); } diff --git a/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/RefreshResponsePolicy.cs b/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/RefreshResponsePolicy.cs index a1f6f186..31d03f25 100644 --- a/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/RefreshResponsePolicy.cs +++ b/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/RefreshResponsePolicy.cs @@ -6,24 +6,24 @@ namespace CodeBeam.UltimateAuth.Server.Flows; internal class RefreshResponsePolicy : IRefreshResponsePolicy { - public GrantKind SelectPrimary(AuthFlowContext flow, RefreshFlowRequest request, RefreshFlowResult result) + public SurrogateKind SelectPrimary(AuthFlowContext flow, RefreshFlowRequest request, RefreshFlowResult result) { if (flow.EffectiveMode == UAuthMode.PureOpaque) - return GrantKind.Session; + return SurrogateKind.SessionId; if (flow.EffectiveMode is UAuthMode.PureJwt or UAuthMode.SemiHybrid) - return GrantKind.AccessToken; + return SurrogateKind.AccessToken; if (!string.IsNullOrWhiteSpace(request.RefreshToken) && request.SessionId == null) - return GrantKind.AccessToken; + return SurrogateKind.AccessToken; if (request.SessionId != null) - return GrantKind.Session; + return SurrogateKind.SessionId; if (flow.ApplicationProfile == UAuthApplicationProfile.Api) - return GrantKind.AccessToken; + return SurrogateKind.AccessToken; - return GrantKind.Session; + return SurrogateKind.SessionId; } diff --git a/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/RefreshTokenResolver.cs b/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/RefreshTokenResolver.cs index 17c6aa1c..b1ef54f5 100644 --- a/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/RefreshTokenResolver.cs +++ b/src/CodeBeam.UltimateAuth.Server/Flows/Refresh/RefreshTokenResolver.cs @@ -21,6 +21,6 @@ public RefreshTokenResolver(IAuthFlowContextAccessor authContext) if (flow is null) return null; - return GrantCredentialReader.Read(context, flow.Response.RefreshTokenDelivery); + return SurrogateReader.Read(context, flow.Response.RefreshTokenTransport); } } diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Cookies/IUAuthCookiePolicyBuilder.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Cookies/IUAuthCookiePolicyBuilder.cs index c87c97ed..b94a07b7 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Cookies/IUAuthCookiePolicyBuilder.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Cookies/IUAuthCookiePolicyBuilder.cs @@ -6,5 +6,5 @@ namespace CodeBeam.UltimateAuth.Server.Infrastructure; public interface IUAuthCookiePolicyBuilder { - CookieOptions Build(EffectiveGrantDelivery delivery, AuthFlowContext context, GrantKind kind); + CookieOptions Build(EffectiveSurrogateTransport delivery, AuthFlowContext context, SurrogateKind kind); } diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Cookies/UAuthCookiePolicyBuilder.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Cookies/UAuthCookiePolicyBuilder.cs index 3247858e..bd9a93e9 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Cookies/UAuthCookiePolicyBuilder.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Cookies/UAuthCookiePolicyBuilder.cs @@ -8,9 +8,9 @@ namespace CodeBeam.UltimateAuth.Server.Infrastructure; internal sealed class UAuthCookiePolicyBuilder : IUAuthCookiePolicyBuilder { - public CookieOptions Build(EffectiveGrantDelivery delivery, AuthFlowContext context, GrantKind kind) + public CookieOptions Build(EffectiveSurrogateTransport delivery, AuthFlowContext context, SurrogateKind kind) { - if (delivery.Mode != GrantDeliveryMode.Cookie) + if (delivery.Mode != SurrogateTransport.Cookie) { throw new InvalidOperationException($"Cookie policy requested for non-cookie grant '{kind}'."); } @@ -51,7 +51,7 @@ private static SameSiteMode ResolveSameSite(UAuthCookieOptions cookie, AuthFlowC }; } - private static void ApplyLifetime(CookieOptions target, UAuthCookieOptions src, AuthFlowContext context, GrantKind kind) + private static void ApplyLifetime(CookieOptions target, UAuthCookieOptions src, AuthFlowContext context, SurrogateKind kind) { var buffer = src.Lifetime.IdleBuffer ?? TimeSpan.Zero; var baseLifetime = ResolveBaseLifetime(context, kind, src); @@ -62,7 +62,7 @@ private static void ApplyLifetime(CookieOptions target, UAuthCookieOptions src, } } - private static TimeSpan? ResolveBaseLifetime(AuthFlowContext context, GrantKind kind, UAuthCookieOptions src) + private static TimeSpan? ResolveBaseLifetime(AuthFlowContext context, SurrogateKind kind, UAuthCookieOptions src) { if (src.MaxAge is not null) return src.MaxAge; @@ -72,9 +72,9 @@ private static void ApplyLifetime(CookieOptions target, UAuthCookieOptions src, return kind switch { - GrantKind.Session => ResolveSessionLifetime(context), - GrantKind.RefreshToken => context.Options.Token.RefreshTokenLifetime, - GrantKind.AccessToken => context.Options.Token.AccessTokenLifetime, + SurrogateKind.SessionId => ResolveSessionLifetime(context), + SurrogateKind.RefreshToken => context.Options.Token.RefreshTokenLifetime, + SurrogateKind.AccessToken => context.Options.Token.AccessTokenLifetime, _ => null }; } diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/ITransportCredentialResolver.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/ITransportCredentialResolver.cs deleted file mode 100644 index a8eb9f14..00000000 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/ITransportCredentialResolver.cs +++ /dev/null @@ -1,10 +0,0 @@ -using CodeBeam.UltimateAuth.Core.Domain; -using CodeBeam.UltimateAuth.Server.Auth; -using Microsoft.AspNetCore.Http; - -namespace CodeBeam.UltimateAuth.Server.Infrastructure; - -public interface ITransportCredentialResolver -{ - ValueTask ResolveAsync(HttpContext context, UAuthMode mode, EffectiveAuthResponse response); -} diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/TransportCredential.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/TransportCredential.cs deleted file mode 100644 index aac3255f..00000000 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/TransportCredential.cs +++ /dev/null @@ -1,12 +0,0 @@ -using CodeBeam.UltimateAuth.Core.Contracts; - -namespace CodeBeam.UltimateAuth.Server.Infrastructure; - -public sealed class TransportCredential -{ - public required TransportCredentialKind Kind { get; init; } - public required string Value { get; init; } - - public string? TenantId { get; init; } - public required DeviceInfo Device { get; init; } -} diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/TransportCredentialKind.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/TransportCredentialKind.cs deleted file mode 100644 index 870a458e..00000000 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/TransportCredentialKind.cs +++ /dev/null @@ -1,9 +0,0 @@ -namespace CodeBeam.UltimateAuth.Server.Infrastructure; - -public enum TransportCredentialKind -{ - Session = 0, - AccessToken = 10, - RefreshToken = 20, - Hub = 30 -} diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/TransportCredentialResolver.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/TransportCredentialResolver.cs deleted file mode 100644 index 164c764b..00000000 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/AspNetCore/TransportCredentialResolver.cs +++ /dev/null @@ -1,51 +0,0 @@ -using CodeBeam.UltimateAuth.Core.Domain; -using CodeBeam.UltimateAuth.Server.Auth; -using CodeBeam.UltimateAuth.Server.Extensions; -using Microsoft.AspNetCore.Http; - -namespace CodeBeam.UltimateAuth.Server.Infrastructure; - -internal sealed class TransportCredentialResolver : ITransportCredentialResolver -{ - private readonly IPrimaryTokenResolver _primaryTokenResolver; - - public TransportCredentialResolver(IPrimaryTokenResolver primaryTokenResolver) - { - _primaryTokenResolver = primaryTokenResolver; - } - - public async ValueTask ResolveAsync(HttpContext context, UAuthMode mode, EffectiveAuthResponse response) - { - var primaryToken = _primaryTokenResolver.Resolve(mode); - - var (delivery, kind) = primaryToken switch - { - PrimaryTokenKind.Session => - ( - response.SessionIdDelivery, - TransportCredentialKind.Session - ), - - PrimaryTokenKind.AccessToken => - ( - response.AccessTokenDelivery, - TransportCredentialKind.AccessToken - ), - - _ => throw new InvalidOperationException($"Unsupported primary token kind: {primaryToken}") - }; - - var value = GrantCredentialReader.Read(context, delivery); - - if (value is null) - return null; - - return new TransportCredential - { - Kind = kind, - Value = value, - TenantId = context.GetTenant().Value, - Device = await context.GetDeviceAsync() - }; - } -} diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/IUAuthBodyPolicyBuilder.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/IUAuthBodyPolicyBuilder.cs index 72cff948..87ae9f89 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/IUAuthBodyPolicyBuilder.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/IUAuthBodyPolicyBuilder.cs @@ -5,5 +5,5 @@ namespace CodeBeam.UltimateAuth.Server.Infrastructure; public interface IUAuthBodyPolicyBuilder { - object BuildBodyValue(string rawValue, EffectiveGrantDelivery delivery, AuthFlowContext context); + object BuildBodyValue(string rawValue, EffectiveSurrogateTransport delivery, AuthFlowContext context); } diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/IUAuthHeaderPolicyBuilder.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/IUAuthHeaderPolicyBuilder.cs index 4b6f34be..e339155c 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/IUAuthHeaderPolicyBuilder.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/IUAuthHeaderPolicyBuilder.cs @@ -5,5 +5,5 @@ namespace CodeBeam.UltimateAuth.Server.Infrastructure; public interface IUAuthHeaderPolicyBuilder { - string BuildHeaderValue(string rawValue, EffectiveGrantDelivery delivery, AuthFlowContext context); + string BuildHeaderValue(string rawValue, EffectiveSurrogateTransport delivery, AuthFlowContext context); } diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/CredentialResponseWriter.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/SurrogateResponseWriter.cs similarity index 66% rename from src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/CredentialResponseWriter.cs rename to src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/SurrogateResponseWriter.cs index ae510830..7763d4fa 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/CredentialResponseWriter.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/SurrogateResponseWriter.cs @@ -1,6 +1,5 @@ using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; -using CodeBeam.UltimateAuth.Core.Options; using CodeBeam.UltimateAuth.Server.Abstractions; using CodeBeam.UltimateAuth.Server.Auth; using CodeBeam.UltimateAuth.Server.Domain; @@ -8,14 +7,14 @@ namespace CodeBeam.UltimateAuth.Server.Infrastructure; -internal sealed class CredentialResponseWriter : ICredentialResponseWriter +internal sealed class SurrogateResponseWriter : ISurrogateResponseWriter { private readonly IAuthFlowContextAccessor _authContext; private readonly IUAuthCookieManager _cookieManager; private readonly IUAuthCookiePolicyBuilder _cookiePolicy; private readonly IUAuthHeaderPolicyBuilder _headerPolicy; - public CredentialResponseWriter( + public SurrogateResponseWriter( IAuthFlowContextAccessor authContext, IUAuthCookieManager cookieManager, IUAuthCookiePolicyBuilder cookiePolicy, @@ -27,22 +26,22 @@ public CredentialResponseWriter( _headerPolicy = headerPolicy; } - public void Write(HttpContext context, GrantKind kind, AuthSessionId sessionId) + public void Write(HttpContext context, SurrogateKind kind, AuthSessionId sessionId) => WriteInternal(context, kind, sessionId.ToString()); - public void Write(HttpContext context, GrantKind kind, AccessToken token) + public void Write(HttpContext context, SurrogateKind kind, AccessToken token) { ArgumentNullException.ThrowIfNull(token); WriteInternal(context, kind, token.Token); - if (kind != GrantKind.AccessToken) + if (kind != SurrogateKind.AccessToken) return; var auth = _authContext.Current; - var delivery = auth.Response.AccessTokenDelivery; + var delivery = auth.Response.AccessTokenTransport; - if (delivery.Mode != GrantDeliveryMode.Header) + if (delivery.Mode != SurrogateTransport.Header) return; var headerName = delivery.Name; @@ -60,10 +59,10 @@ public void Write(HttpContext context, GrantKind kind, AccessToken token) headers.CacheControl = "no-store"; } - public void Write(HttpContext context, GrantKind kind, RefreshTokenInfo token) + public void Write(HttpContext context, SurrogateKind kind, RefreshTokenInfo token) => WriteInternal(context, kind, token.Token); - public void WriteInternal(HttpContext context, GrantKind kind, string value) + public void WriteInternal(HttpContext context, SurrogateKind kind, string value) { var auth = _authContext.Current; var delivery = ResolveDelivery(auth.Response, kind); @@ -76,18 +75,18 @@ public void WriteInternal(HttpContext context, GrantKind kind, string value) switch (delivery.Mode) { - case GrantDeliveryMode.None: + case SurrogateTransport.None: return; - case GrantDeliveryMode.Cookie: + case SurrogateTransport.Cookie: WriteCookie(context, kind, value, delivery, auth); return; - case GrantDeliveryMode.Header: + case SurrogateTransport.Header: WriteHeader(context, value, delivery, auth); return; - case GrantDeliveryMode.Body: + case SurrogateTransport.Body: throw new NotSupportedException( $"Body grant delivery is not supported for '{kind}'."); @@ -97,16 +96,10 @@ public void WriteInternal(HttpContext context, GrantKind kind, string value) } } - private void WriteCookie( - HttpContext context, - GrantKind kind, - string value, - EffectiveGrantDelivery delivery, - AuthFlowContext auth) + private void WriteCookie(HttpContext context, SurrogateKind kind, string value, EffectiveSurrogateTransport delivery, AuthFlowContext auth) { var cookie = delivery.Cookie - ?? throw new InvalidOperationException( - $"Cookie options missing for grant '{kind}'."); + ?? throw new InvalidOperationException($"Cookie options missing for grant '{kind}'."); var cookieOptions = _cookiePolicy.Build(delivery, auth, kind); @@ -117,18 +110,13 @@ private void WriteCookie( cookieOptions); } - private void WriteHeader( - HttpContext context, - string value, - EffectiveGrantDelivery delivery, - AuthFlowContext auth) + private void WriteHeader(HttpContext context, string value, EffectiveSurrogateTransport delivery, AuthFlowContext auth) { var headerName = delivery.Name; if (string.IsNullOrWhiteSpace(headerName)) { - throw new InvalidOperationException( - $"Header name missing for grant '{delivery.Kind}'."); + throw new InvalidOperationException($"Header name missing for grant '{delivery.Kind}'."); } var formatted = _headerPolicy.BuildHeaderValue( @@ -139,14 +127,12 @@ private void WriteHeader( context.Response.Headers[headerName] = formatted; } - private static EffectiveGrantDelivery ResolveDelivery( - EffectiveAuthResponse response, - GrantKind kind) + private static EffectiveSurrogateTransport ResolveDelivery(EffectiveAuthResponse response, SurrogateKind kind) => kind switch { - GrantKind.Session => response.SessionIdDelivery, - GrantKind.AccessToken => response.AccessTokenDelivery, - GrantKind.RefreshToken => response.RefreshTokenDelivery, + SurrogateKind.SessionId => response.SessionIdTransport, + SurrogateKind.AccessToken => response.AccessTokenTransport, + SurrogateKind.RefreshToken => response.RefreshTokenTransport, _ => throw new ArgumentOutOfRangeException(nameof(kind)) }; } \ No newline at end of file diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/UAuthBodyPolicyBuilder.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/UAuthBodyPolicyBuilder.cs index 638887ad..53697639 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/UAuthBodyPolicyBuilder.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/UAuthBodyPolicyBuilder.cs @@ -4,7 +4,7 @@ namespace CodeBeam.UltimateAuth.Server.Infrastructure; internal class UAuthBodyPolicyBuilder : IUAuthBodyPolicyBuilder { - public object BuildBodyValue(string rawValue, EffectiveGrantDelivery delivery, AuthFlowContext context) + public object BuildBodyValue(string rawValue, EffectiveSurrogateTransport delivery, AuthFlowContext context) { throw new NotImplementedException(); } diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/UAuthHeaderPolicyBuilder.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/UAuthHeaderPolicyBuilder.cs index 7e678d21..6af62e7d 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/UAuthHeaderPolicyBuilder.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/UAuthHeaderPolicyBuilder.cs @@ -5,9 +5,9 @@ namespace CodeBeam.UltimateAuth.Server.Infrastructure; internal sealed class UAuthHeaderPolicyBuilder : IUAuthHeaderPolicyBuilder { - public string BuildHeaderValue(string rawValue, EffectiveGrantDelivery delivery, AuthFlowContext context) + public string BuildHeaderValue(string rawValue, EffectiveSurrogateTransport delivery, AuthFlowContext context) { - if (delivery.Mode != GrantDeliveryMode.Header) + if (delivery.Mode != SurrogateTransport.Header) { throw new InvalidOperationException($"Header policy requested for non-header grant '{delivery.Kind}'."); } @@ -19,8 +19,8 @@ public string BuildHeaderValue(string rawValue, EffectiveGrantDelivery delivery, return delivery.HeaderFormat switch { - HeaderTokenFormat.Bearer => $"Bearer {rawValue}", - HeaderTokenFormat.Raw => rawValue, + HeaderValueFormat.Bearer => $"Bearer {rawValue}", + HeaderValueFormat.Raw => rawValue, _ => throw new InvalidOperationException($"Unsupported header token format: {delivery.HeaderFormat}") }; } diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs index 8eb4fa48..abffe8c5 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Issuers/UAuthSessionIssuer.cs @@ -38,10 +38,10 @@ public async Task IssueSessionAsync(SessionIssuanceContext contex var purpose = context.Mode switch { UAuthMode.PureOpaque or UAuthMode.Hybrid - => SessionCredentialPurpose.Opaque, + => SessionIdPurpose.Opaque, UAuthMode.SemiHybrid - => SessionCredentialPurpose.MetadataOnly, + => SessionIdPurpose.MetadataOnly, UAuthMode.PureJwt => throw new InvalidOperationException("PureJwt does not create sessions."), @@ -51,8 +51,8 @@ UAuthMode.PureOpaque or UAuthMode.Hybrid var rawSessionId = purpose switch { - SessionCredentialPurpose.Opaque => _opaqueGenerator.Generate(), - SessionCredentialPurpose.MetadataOnly => + SessionIdPurpose.Opaque => _opaqueGenerator.Generate(), + SessionIdPurpose.MetadataOnly => _opaqueGenerator.Generate(), _ => throw new InvalidOperationException("Unsupported session credential purpose.") @@ -256,7 +256,7 @@ context.Device.DeviceId is not DeviceId incomingDeviceId || return new IssuedSession { Session = session, - OpaqueSessionId = purpose == SessionCredentialPurpose.Opaque ? rawSessionId : null + OpaqueSessionId = purpose == SessionIdPurpose.Opaque ? rawSessionId : null }; } @@ -313,10 +313,10 @@ await kernel.ExecuteAsync(async _ => var expectedPurpose = context.Mode switch { UAuthMode.PureOpaque or UAuthMode.Hybrid - => SessionCredentialPurpose.Opaque, + => SessionIdPurpose.Opaque, UAuthMode.SemiHybrid - => SessionCredentialPurpose.MetadataOnly, + => SessionIdPurpose.MetadataOnly, _ => throw new InvalidOperationException("Session rotation is not supported in this mode.") }; diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/SessionId/SessionIdResolver.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/SessionId/SessionIdResolver.cs index 7d5e432a..98a1d77d 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/SessionId/SessionIdResolver.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/SessionId/SessionIdResolver.cs @@ -1,4 +1,5 @@ using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Core.Extensions; using CodeBeam.UltimateAuth.Server.Abstractions; using CodeBeam.UltimateAuth.Server.Auth; using Microsoft.AspNetCore.Http; @@ -8,23 +9,20 @@ namespace CodeBeam.UltimateAuth.Server.Infrastructure; public sealed class SessionIdResolver : ISessionIdResolver { private readonly IApplicationProfileReader _applicationProfileReader; - private readonly IEffectiveServerOptionsProvider _effectiveOptionsProvider; - private readonly IAuthResponseResolver _authResponseResolver; - - private readonly ITransportCredentialResolver _transportCredentialResolver; + private readonly ISurrogateResolver _surrogateResolver; internal SessionIdResolver( IApplicationProfileReader applicationProfileReader, IEffectiveServerOptionsProvider effectiveOptionsProvider, IAuthResponseResolver authResponseResolver, - ITransportCredentialResolver transportCredentialResolver) + ISurrogateResolver surrogateResolver) { _applicationProfileReader = applicationProfileReader; _effectiveOptionsProvider = effectiveOptionsProvider; _authResponseResolver = authResponseResolver; - _transportCredentialResolver = transportCredentialResolver; + _surrogateResolver = surrogateResolver; } public async ValueTask ResolveAsync(HttpContext context, CancellationToken ct = default) @@ -35,23 +33,22 @@ internal SessionIdResolver( var effective = _effectiveOptionsProvider.GetEffective(context, applicationProfile); - // JWT-based modes must never resolve an opaque session authentication credential. - if (effective.Mode is not (UAuthMode.PureOpaque or UAuthMode.Hybrid)) - { + if (!effective.Mode.UsesSessionIdForAuthentication()) return null; - } var response = _authResponseResolver.ResolveForAuthentication(effective.Mode, applicationProfile, effective); - var credential = await _transportCredentialResolver.ResolveAsync(context, effective.Mode, response); + var surrogate = await _surrogateResolver.ResolveAsync(context, response.SessionIdTransport); - if (credential is null || credential.Kind != TransportCredentialKind.Session) + if (surrogate is null || surrogate.Kind != SurrogateKind.SessionId) { return null; } - return AuthSessionId.TryCreate(credential.Value, out var sessionId) - ? sessionId - : null; + return AuthSessionId.TryCreate( + surrogate.Value, + out var sessionId) + ? sessionId + : null; } } diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/ISurrogateResolver.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/ISurrogateResolver.cs new file mode 100644 index 00000000..ad99f65c --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/ISurrogateResolver.cs @@ -0,0 +1,9 @@ +using CodeBeam.UltimateAuth.Server.Auth; +using Microsoft.AspNetCore.Http; + +namespace CodeBeam.UltimateAuth.Server.Infrastructure; + +public interface ISurrogateResolver +{ + ValueTask ResolveAsync(HttpContext context, EffectiveSurrogateTransport transport); +} diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/ResolvedSurrogate.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/ResolvedSurrogate.cs new file mode 100644 index 00000000..40286e39 --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/ResolvedSurrogate.cs @@ -0,0 +1,22 @@ +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; + +namespace CodeBeam.UltimateAuth.Server.Infrastructure; + +/// +/// Represents a surrogate resolved from an incoming request. +/// +/// +/// Resolution does not establish authenticity or validity. +/// The surrogate and its request context must be validated before being trusted. +/// +public sealed class ResolvedSurrogate +{ + public required SurrogateKind Kind { get; init; } + + public required string Value { get; init; } + + public string? TenantId { get; init; } + + public required DeviceInfo Device { get; init; } +} diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/GrantCredentialReader.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/SurrogateReader.cs similarity index 90% rename from src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/GrantCredentialReader.cs rename to src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/SurrogateReader.cs index a06eab25..0b9a7168 100644 --- a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Credentials/GrantCredentialReader.cs +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/SurrogateReader.cs @@ -4,16 +4,16 @@ namespace CodeBeam.UltimateAuth.Server.Infrastructure; -internal static class GrantCredentialReader +internal static class SurrogateReader { - public static string? Read(HttpContext context, EffectiveGrantDelivery delivery) + public static string? Read(HttpContext context, EffectiveSurrogateTransport delivery) { return delivery.Mode switch { - GrantDeliveryMode.Cookie => + SurrogateTransport.Cookie => ReadCookie(context, delivery.Cookie?.Name), - GrantDeliveryMode.Header => + SurrogateTransport.Header => ReadHeader(context, delivery.RequestHeaderName, delivery.RequestHeaderFormat), _ => null @@ -34,7 +34,7 @@ internal static class GrantCredentialReader return Normalize(value); } - public static string? ReadHeader(HttpContext context, string? name, HeaderTokenFormat format) + public static string? ReadHeader(HttpContext context, string? name, HeaderValueFormat format) { if (string.IsNullOrWhiteSpace(name)) return null; @@ -55,7 +55,7 @@ internal static class GrantCredentialReader switch (format) { - case HeaderTokenFormat.Bearer: + case HeaderValueFormat.Bearer: const string prefix = "Bearer "; if (!value.StartsWith(prefix, StringComparison.OrdinalIgnoreCase)) @@ -66,7 +66,7 @@ internal static class GrantCredentialReader value = value[prefix.Length..]; break; - case HeaderTokenFormat.Raw: + case HeaderValueFormat.Raw: break; default: diff --git a/src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/SurrogateResolver.cs b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/SurrogateResolver.cs new file mode 100644 index 00000000..53bda78e --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/Infrastructure/Surrogates/SurrogateResolver.cs @@ -0,0 +1,24 @@ +using CodeBeam.UltimateAuth.Server.Auth; +using CodeBeam.UltimateAuth.Server.Extensions; +using Microsoft.AspNetCore.Http; + +namespace CodeBeam.UltimateAuth.Server.Infrastructure; + +internal sealed class SurrogateResolver : ISurrogateResolver +{ + public async ValueTask ResolveAsync(HttpContext context, EffectiveSurrogateTransport transport) + { + var value = SurrogateReader.Read(context, transport); + + if (value is null) + return null; + + return new ResolvedSurrogate + { + Kind = transport.Kind, + Value = value, + TenantId = context.GetTenant().Value, + Device = await context.GetDeviceAsync() + }; + } +} diff --git a/src/CodeBeam.UltimateAuth.Server/Options/CredentialResponseOptions.cs b/src/CodeBeam.UltimateAuth.Server/Options/CredentialResponseOptions.cs deleted file mode 100644 index 2ca502b8..00000000 --- a/src/CodeBeam.UltimateAuth.Server/Options/CredentialResponseOptions.cs +++ /dev/null @@ -1,60 +0,0 @@ -using CodeBeam.UltimateAuth.Core.Contracts; -using CodeBeam.UltimateAuth.Core.Domain; -using CodeBeam.UltimateAuth.Core.Options; -using CodeBeam.UltimateAuth.Server.Domain; - -namespace CodeBeam.UltimateAuth.Server.Options; - -[Obsolete("CredentialResponseOptions is no longer supported. Use GrantDeliveryOptions instead.")] -public sealed class CredentialResponseOptions -{ - public GrantKind Kind { get; init; } - public TokenResponseMode Mode { get; set; } = TokenResponseMode.None; - - /// - /// Header or body name - /// - public string? Name { get; set; } - - /// - /// Applies when Mode = Header - /// - public HeaderTokenFormat HeaderFormat { get; set; } = HeaderTokenFormat.Bearer; - public TokenFormat TokenFormat { get; set; } - - // Only for cookie - public UAuthCookieOptions? Cookie { get; init; } - - internal CredentialResponseOptions Clone() => new() - { - Kind = Kind, - Mode = Mode, - Name = Name, - HeaderFormat = HeaderFormat, - TokenFormat = TokenFormat, - Cookie = Cookie?.Clone() - }; - - public CredentialResponseOptions WithCookie(UAuthCookieOptions cookie) - { - if (Mode != TokenResponseMode.Cookie) - throw new InvalidOperationException("Cookie can only be set when Mode = Cookie."); - - return new CredentialResponseOptions() - { - Kind = Kind, - Mode = Mode, - Name = Name, - HeaderFormat = HeaderFormat, - TokenFormat = TokenFormat, - Cookie = cookie - }; - } - - public static CredentialResponseOptions Disabled(GrantKind kind) - => new() - { - Kind = kind, - Mode = TokenResponseMode.None - }; -} diff --git a/src/CodeBeam.UltimateAuth.Server/Options/GrantDeliveryOptions.cs b/src/CodeBeam.UltimateAuth.Server/Options/SurrogateTransportOptions.cs similarity index 84% rename from src/CodeBeam.UltimateAuth.Server/Options/GrantDeliveryOptions.cs rename to src/CodeBeam.UltimateAuth.Server/Options/SurrogateTransportOptions.cs index f529170c..2f949673 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/GrantDeliveryOptions.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/SurrogateTransportOptions.cs @@ -11,7 +11,7 @@ namespace CodeBeam.UltimateAuth.Server.Options; /// Grant identity, token format, and issuance behavior are determined by the effective authentication mode /// and cannot be changed through delivery options. /// -public sealed class GrantDeliveryOptions +public sealed class SurrogateTransportOptions { /// /// Gets or sets the delivery mode for this grant. @@ -19,7 +19,7 @@ public sealed class GrantDeliveryOptions /// /// Null inherits the global delivery preference or the authentication mode and application profile defaults when no global preference is configured. /// - public GrantDeliveryMode? Mode { get; set; } + public SurrogateTransport? Mode { get; set; } /// /// Gets or sets the HTTP response header name when delivery mode is Header. @@ -29,9 +29,9 @@ public sealed class GrantDeliveryOptions /// /// Gets or sets the header value format when delivery mode is Header. /// - public HeaderTokenFormat? HeaderFormat { get; set; } + public HeaderValueFormat? HeaderFormat { get; set; } - internal GrantDeliveryOptions Clone() => new() + internal SurrogateTransportOptions Clone() => new() { Mode = Mode, HeaderName = HeaderName, diff --git a/src/CodeBeam.UltimateAuth.Server/Options/UAuthHubCorsOptionsSetup.cs b/src/CodeBeam.UltimateAuth.Server/Options/UAuthHubCorsOptionsSetup.cs index 3e016a26..1ae9e0ae 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/UAuthHubCorsOptionsSetup.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/UAuthHubCorsOptionsSetup.cs @@ -20,7 +20,7 @@ public void Configure(CorsOptions options) if (origins.Length == 0) return; - var accessHeader = server.GrantDelivery.AccessToken.HeaderName ?? "uat"; + var accessHeader = server.Transport.AccessToken.HeaderName ?? "uat"; var exposedHeaders = new HashSet(StringComparer.OrdinalIgnoreCase) { diff --git a/src/CodeBeam.UltimateAuth.Server/Options/UAuthResourceApiOptions.cs b/src/CodeBeam.UltimateAuth.Server/Options/UAuthResourceApiOptions.cs index 9b3016ee..62064df2 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/UAuthResourceApiOptions.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/UAuthResourceApiOptions.cs @@ -43,9 +43,25 @@ public sealed class UAuthResourceAuthOptions /// public UAuthMode? Mode { get; set; } - public UAuthResourceSessionOptions Session { get; set; } = new(); + public UAuthResourceSurrogateTransportOptions SessionId + { + get; + set; + } = new() + { + Mode = SurrogateTransport.Cookie, + CookieName = "uas" + }; - public UAuthResourceAccessTokenOptions AccessToken { get; set; } = new(); + public UAuthResourceSurrogateTransportOptions AccessToken + { + get; + set; + } = new() + { + Mode = SurrogateTransport.Header, + CookieName = "uat" + }; public UAuthResourceDeviceOptions Device { get; set; } = new(); @@ -55,7 +71,7 @@ public sealed class UAuthResourceAuthOptions internal UAuthResourceAuthOptions Clone() => new() { Mode = Mode, - Session = Session.Clone(), + SessionId = SessionId.Clone(), AccessToken = AccessToken.Clone(), Device = Device.Clone(), Jwt = Jwt is null @@ -72,44 +88,6 @@ public sealed class UAuthResourceAuthOptions }; } -/// -/// Incoming opaque session credential configuration. -/// -public sealed class UAuthResourceSessionOptions -{ - public GrantDeliveryMode DeliveryMode { get; set; } = GrantDeliveryMode.Cookie; - - public string CookieName { get; set; } = "uas"; - - internal UAuthResourceSessionOptions Clone() => new() - { - DeliveryMode = DeliveryMode, - CookieName = CookieName - }; -} - -/// -/// Incoming access token credential configuration. -/// -public sealed class UAuthResourceAccessTokenOptions -{ - public GrantDeliveryMode DeliveryMode { get; set; } = GrantDeliveryMode.Header; - - public string CookieName { get; set; } = "uat"; - - public string HeaderName { get; set; } = "Authorization"; - - public HeaderTokenFormat HeaderFormat { get; set; } = HeaderTokenFormat.Bearer; - - internal UAuthResourceAccessTokenOptions Clone() => new() - { - DeliveryMode = DeliveryMode, - CookieName = CookieName, - HeaderName = HeaderName, - HeaderFormat = HeaderFormat - }; -} - /// /// Device security policies applied during credential validation. /// @@ -190,3 +168,26 @@ public sealed class UAuthResourceValidationOptions Default = Default }; } + +/// +/// Configures how a Resource API accepts an incoming surrogate. +/// +public sealed class UAuthResourceSurrogateTransportOptions +{ + public SurrogateTransport Mode { get; set; } + + public string CookieName { get; set; } = string.Empty; + + public string HeaderName { get; set; } = "Authorization"; + + public HeaderValueFormat HeaderFormat { get; set; } = HeaderValueFormat.Bearer; + + internal UAuthResourceSurrogateTransportOptions Clone() + => new() + { + Mode = Mode, + CookieName = CookieName, + HeaderName = HeaderName, + HeaderFormat = HeaderFormat + }; +} diff --git a/src/CodeBeam.UltimateAuth.Server/Options/UAuthResponseOptions.cs b/src/CodeBeam.UltimateAuth.Server/Options/UAuthResponseOptions.cs deleted file mode 100644 index 39662674..00000000 --- a/src/CodeBeam.UltimateAuth.Server/Options/UAuthResponseOptions.cs +++ /dev/null @@ -1,25 +0,0 @@ -namespace CodeBeam.UltimateAuth.Server.Options; - -/// -/// Legacy authentication response configuration. -/// -[Obsolete( - "UAuthResponseOptions is no longer supported. " + - "Use UAuthGrantDeliveryOptions and UAuthRedirectOptions instead.")] -public sealed class UAuthResponseOptions -{ - [Obsolete("Use GrantDelivery.Session instead.")] - public CredentialResponseOptions SessionIdDelivery { get; set; } = new(); - - [Obsolete("Use GrantDelivery.AccessToken instead.")] - public CredentialResponseOptions AccessTokenDelivery { get; set; } = new(); - - [Obsolete("Use GrantDelivery.RefreshToken instead.")] - public CredentialResponseOptions RefreshTokenDelivery { get; set; } = new(); - - [Obsolete("Use Redirect.Login instead.")] - public LoginRedirectOptions Login { get; set; } = new(); - - [Obsolete("Use Redirect.Logout instead.")] - public LogoutRedirectOptions Logout { get; set; } = new(); -} diff --git a/src/CodeBeam.UltimateAuth.Server/Options/UAuthServerOptions.cs b/src/CodeBeam.UltimateAuth.Server/Options/UAuthServerOptions.cs index 206dd800..eb138011 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/UAuthServerOptions.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/UAuthServerOptions.cs @@ -137,7 +137,7 @@ public sealed class UAuthServerOptions /// /// Configures how authentication grants are delivered to clients. /// - public UAuthGrantDeliveryOptions GrantDelivery { get; set; } = new(); + public UAuthSurrogateTransportOptions Transport { get; set; } = new(); /// /// Configures authentication flow redirects. @@ -189,18 +189,6 @@ public sealed class UAuthServerOptions /// public UAuthArtifactStoreOptions AuthArtifacts { get; set; } = new(); - [Obsolete("AuthResponse is no longer supported. Use GrantDelivery and Redirect instead.")] - public UAuthResponseOptions AuthResponse - { - get => throw new NotSupportedException( - "AuthResponse is no longer supported. " + - "Use GrantDelivery and Redirect instead."); - - set => throw new NotSupportedException( - "AuthResponse is no longer supported. " + - "Use GrantDelivery and Redirect instead."); - } - // ------------------------------------------------------- // CUSTOMIZATION HOOKS @@ -240,7 +228,7 @@ internal UAuthServerOptions Clone() Cookie = Cookie.Clone(), Diagnostics = Diagnostics.Clone(), - GrantDelivery = GrantDelivery.Clone(), + Transport = Transport.Clone(), Redirect = Redirect.Clone(), ResetCredential = ResetCredential.Clone(), CredentialSessionPolicy = CredentialSessionPolicy.Clone(), diff --git a/src/CodeBeam.UltimateAuth.Server/Options/UAuthGrantDeliveryOptions.cs b/src/CodeBeam.UltimateAuth.Server/Options/UAuthSurrogateTransportOptions.cs similarity index 73% rename from src/CodeBeam.UltimateAuth.Server/Options/UAuthGrantDeliveryOptions.cs rename to src/CodeBeam.UltimateAuth.Server/Options/UAuthSurrogateTransportOptions.cs index e8e6ad92..ef4ae257 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/UAuthGrantDeliveryOptions.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/UAuthSurrogateTransportOptions.cs @@ -10,7 +10,7 @@ namespace CodeBeam.UltimateAuth.Server.Options; /// /// The effective authentication mode determines which grants exist and which delivery configurations are supported. /// -public sealed class UAuthGrantDeliveryOptions +public sealed class UAuthSurrogateTransportOptions { /// /// Gets or sets the default delivery mode for grants issued by the authentication mode. @@ -18,27 +18,27 @@ public sealed class UAuthGrantDeliveryOptions /// /// Null uses authentication mode and application profile defaults. Individual grant settings take precedence. /// - public GrantDeliveryMode? Default { get; set; } + public SurrogateTransport? Default { get; set; } /// /// Configures delivery of the session grant. /// - public GrantDeliveryOptions Session { get; set; } = new(); + public SurrogateTransportOptions SessionId { get; set; } = new(); /// /// Configures delivery of the access token grant. /// - public GrantDeliveryOptions AccessToken { get; set; } = new(); + public SurrogateTransportOptions AccessToken { get; set; } = new(); /// /// Configures delivery of the refresh token grant. /// - public GrantDeliveryOptions RefreshToken { get; set; } = new(); + public SurrogateTransportOptions RefreshToken { get; set; } = new(); - internal UAuthGrantDeliveryOptions Clone() => new() + internal UAuthSurrogateTransportOptions Clone() => new() { Default = Default, - Session = Session.Clone(), + SessionId = SessionId.Clone(), AccessToken = AccessToken.Clone(), RefreshToken = RefreshToken.Clone() }; diff --git a/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthResourceApiOptionsValidator.cs b/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthResourceApiOptionsValidator.cs index 0070c43a..89a2de27 100644 --- a/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthResourceApiOptionsValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Options/Validators/UAuthResourceApiOptionsValidator.cs @@ -54,8 +54,8 @@ public ValidateOptionsResult Validate(string? name, UAuthResourceApiOptions opti if (errors.Count > 0) return ValidateOptionsResult.Fail(errors); - if (auth.Session is null) - errors.Add("Auth.Session must be configured."); + if (auth.SessionId is null) + errors.Add("Auth.SessionId must be configured."); if (auth.AccessToken is null) errors.Add("Auth.AccessToken must be configured."); @@ -66,21 +66,21 @@ public ValidateOptionsResult Validate(string? name, UAuthResourceApiOptions opti if (options.Cryptography is null) errors.Add("Cryptography must be configured."); - if (auth.Session is not null) + if (auth.SessionId is not null) { - if (!Enum.IsDefined(auth.Session.DeliveryMode)) - errors.Add("Auth.Session.DeliveryMode is invalid."); + if (!Enum.IsDefined(auth.SessionId.Mode)) + errors.Add("Auth.SessionId.Mode is invalid."); - if (string.IsNullOrWhiteSpace(auth.Session.CookieName)) - errors.Add("Auth.Session.CookieName is required."); + if (string.IsNullOrWhiteSpace(auth.SessionId.CookieName)) + errors.Add("Auth.SessionId.CookieName is required."); } if (auth.AccessToken is not null) { var token = auth.AccessToken; - if (!Enum.IsDefined(token.DeliveryMode)) - errors.Add("Auth.AccessToken.DeliveryMode is invalid."); + if (!Enum.IsDefined(token.Mode)) + errors.Add("Auth.AccessToken.Mode is invalid."); if (!Enum.IsDefined(token.HeaderFormat)) errors.Add("Auth.AccessToken.HeaderFormat is invalid."); diff --git a/src/CodeBeam.UltimateAuth.Server/ResourceApi/RemoteHubValidationService.cs b/src/CodeBeam.UltimateAuth.Server/ResourceApi/RemoteHubValidationService.cs index 5a37fb78..f2cddb3e 100644 --- a/src/CodeBeam.UltimateAuth.Server/ResourceApi/RemoteHubValidationService.cs +++ b/src/CodeBeam.UltimateAuth.Server/ResourceApi/RemoteHubValidationService.cs @@ -19,13 +19,13 @@ internal sealed class RemoteHubValidationService private static readonly object CacheKey = new(); private readonly HttpClient _http; - private readonly ITransportCredentialResolver _credentials; + private readonly ISurrogateResolver _surrogateResolver; private readonly UAuthResourceApiOptions _options; - public RemoteHubValidationService(HttpClient http, ITransportCredentialResolver credentials, IOptions options) + public RemoteHubValidationService(HttpClient http, ISurrogateResolver surrogateResolver, IOptions options) { _http = http; - _credentials = credentials; + _surrogateResolver = surrogateResolver; _options = options.Value; } @@ -73,26 +73,11 @@ SessionValidationResult Invalid() var access = _options.Auth.AccessToken; - var delivery = new EffectiveGrantDelivery( - GrantKind.AccessToken, - TokenFormat.Jwt, - access.DeliveryMode, - name: access.HeaderName, - headerFormat: access.HeaderFormat, - cookie: new UAuthCookieOptions - { - Name = access.CookieName - }); - - var response = new EffectiveAuthResponse( - EffectiveGrantDelivery.Disabled(GrantKind.Session), - delivery, - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), - EffectiveRedirectResponse.Disabled); + var transport = ResourceSurrogateTransportFactory.CreateAccessToken(UAuthMode.SemiHybrid, _options.Auth); - var credential = await _credentials.ResolveAsync(context, UAuthMode.SemiHybrid, response); + var surrogate = await _surrogateResolver.ResolveAsync(context, transport); - if (credential is null || credential.Kind != TransportCredentialKind.AccessToken) + if (surrogate is null || surrogate.Kind != SurrogateKind.AccessToken) { return Invalid(); } @@ -108,7 +93,7 @@ SessionValidationResult Invalid() using var request = new HttpRequestMessage(HttpMethod.Post, "/auth/validate"); - request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", credential.Value); + request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", surrogate.Value); request.Headers.TryAddWithoutValidation(UAuthConstants.Headers.Validation, nameof(UAuthValidationRequirement.HubValidated)); diff --git a/src/CodeBeam.UltimateAuth.Server/ResourceApi/ResourceSessionIdResolver.cs b/src/CodeBeam.UltimateAuth.Server/ResourceApi/ResourceSessionIdResolver.cs index 515aabb8..28947b84 100644 --- a/src/CodeBeam.UltimateAuth.Server/ResourceApi/ResourceSessionIdResolver.cs +++ b/src/CodeBeam.UltimateAuth.Server/ResourceApi/ResourceSessionIdResolver.cs @@ -1,7 +1,5 @@ -using CodeBeam.UltimateAuth.Core.Contracts; -using CodeBeam.UltimateAuth.Core.Domain; -using CodeBeam.UltimateAuth.Server.Auth; -using CodeBeam.UltimateAuth.Server.Domain; +using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Core.Extensions; using CodeBeam.UltimateAuth.Server.Options; using CodeBeam.UltimateAuth.Server.ResourceApi; using Microsoft.AspNetCore.Http; @@ -13,55 +11,36 @@ internal sealed class ResourceSessionIdResolver : ISessionIdResolver { private readonly ResourceApiAuthModeProvider _modeProvider; private readonly UAuthResourceApiOptions _options; - private readonly ITransportCredentialResolver _credentialResolver; + private readonly ISurrogateResolver _surrogateResolver; public ResourceSessionIdResolver( ResourceApiAuthModeProvider modeProvider, IOptions options, - ITransportCredentialResolver credentialResolver) + ISurrogateResolver surrogateResolver) { _modeProvider = modeProvider; _options = options.Value; - _credentialResolver = credentialResolver; + _surrogateResolver = surrogateResolver; } public async ValueTask ResolveAsync(HttpContext context, CancellationToken ct = default) { ct.ThrowIfCancellationRequested(); - var mode = _modeProvider.Mode; - - if (mode is not (UAuthMode.PureOpaque or UAuthMode.Hybrid)) - { + if (!_modeProvider.Mode.UsesSessionIdForAuthentication()) return null; - } - - var sessionDelivery = new EffectiveGrantDelivery( - GrantKind.Session, - TokenFormat.Opaque, - _options.Auth.Session.DeliveryMode, - name: "Authorization", - headerFormat: HeaderTokenFormat.Bearer, - cookie: new UAuthCookieOptions - { - Name = _options.Auth.Session.CookieName - }); - var response = new EffectiveAuthResponse( - sessionDelivery, - EffectiveGrantDelivery.Disabled(GrantKind.AccessToken), - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), - EffectiveRedirectResponse.Disabled); + var transport = ResourceSurrogateTransportFactory.CreateSessionId(_options.Auth); - var credential = await _credentialResolver.ResolveAsync(context, mode, response); + var surrogate = await _surrogateResolver.ResolveAsync(context, transport); - if (credential is null || credential.Kind != TransportCredentialKind.Session) + if (surrogate is null || surrogate.Kind != SurrogateKind.SessionId) { return null; } return AuthSessionId.TryCreate( - credential.Value, + surrogate.Value, out var sessionId) ? sessionId : null; diff --git a/src/CodeBeam.UltimateAuth.Server/ResourceApi/ResourceSurrogateTransportFactory.cs b/src/CodeBeam.UltimateAuth.Server/ResourceApi/ResourceSurrogateTransportFactory.cs new file mode 100644 index 00000000..a26da387 --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/ResourceApi/ResourceSurrogateTransportFactory.cs @@ -0,0 +1,55 @@ +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Core.Extensions; +using CodeBeam.UltimateAuth.Server.Auth; +using CodeBeam.UltimateAuth.Server.Domain; +using CodeBeam.UltimateAuth.Server.Options; + +namespace CodeBeam.UltimateAuth.Server.ResourceApi; + +internal static class ResourceSurrogateTransportFactory +{ + public static EffectiveSurrogateTransport CreatePrimary(UAuthMode mode, UAuthResourceAuthOptions options) + => Create(mode, mode.GetPrimarySurrogateKind(), options); + + public static EffectiveSurrogateTransport CreateSessionId(UAuthResourceAuthOptions options) + => CreateTransport(SurrogateKind.SessionId, TokenFormat.Opaque, options.SessionId); + + public static EffectiveSurrogateTransport CreateAccessToken(UAuthMode mode, UAuthResourceAuthOptions options) + => Create(mode, SurrogateKind.AccessToken, options); + + public static EffectiveSurrogateTransport Create(UAuthMode mode, SurrogateKind kind, UAuthResourceAuthOptions options) + { + var format = mode.GetTokenFormat(kind) + ?? throw new InvalidOperationException($"Surrogate '{kind}' is not supported by mode '{mode}'."); + + var configured = kind switch + { + SurrogateKind.SessionId => options.SessionId, + SurrogateKind.AccessToken => options.AccessToken, + + _ => throw new InvalidOperationException($"Resource APIs do not accept '{kind}' surrogates.") + }; + + return CreateTransport(kind, format, configured); + } + + private static EffectiveSurrogateTransport CreateTransport(SurrogateKind kind, TokenFormat format, UAuthResourceSurrogateTransportOptions configured) + { + if (configured.Mode is not (SurrogateTransport.Cookie or SurrogateTransport.Header)) + { + throw new InvalidOperationException($"Unsupported Resource API transport '{configured.Mode}' for '{kind}'."); + } + + return new EffectiveSurrogateTransport( + kind, + format, + configured.Mode, + name: configured.HeaderName, + headerFormat: configured.HeaderFormat, + cookie: new UAuthCookieOptions + { + Name = configured.CookieName + }); + } +} diff --git a/src/CodeBeam.UltimateAuth.Server/Security/UAuthCsrfGrantInspector.cs b/src/CodeBeam.UltimateAuth.Server/Security/UAuthCsrfGrantInspector.cs deleted file mode 100644 index 6cd07c67..00000000 --- a/src/CodeBeam.UltimateAuth.Server/Security/UAuthCsrfGrantInspector.cs +++ /dev/null @@ -1,14 +0,0 @@ -using CodeBeam.UltimateAuth.Server.Auth; -using CodeBeam.UltimateAuth.Server.Domain; - -namespace CodeBeam.UltimateAuth.Server.Security; - -internal static class UAuthCsrfGrantInspector -{ - public static bool UsesAuthenticationCookie(EffectiveAuthResponse response) - { - return response.SessionIdDelivery.Mode == GrantDeliveryMode.Cookie - || response.AccessTokenDelivery.Mode == GrantDeliveryMode.Cookie - || response.RefreshTokenDelivery.Mode == GrantDeliveryMode.Cookie; - } -} diff --git a/src/CodeBeam.UltimateAuth.Server/Security/UAuthCsrfPolicyEvaluator.cs b/src/CodeBeam.UltimateAuth.Server/Security/UAuthCsrfPolicyEvaluator.cs index ac9a84c2..77b2002e 100644 --- a/src/CodeBeam.UltimateAuth.Server/Security/UAuthCsrfPolicyEvaluator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Security/UAuthCsrfPolicyEvaluator.cs @@ -6,7 +6,7 @@ internal sealed class UAuthCsrfPolicyEvaluator { public bool RequiresProtection(AuthFlowContext auth, UAuthCsrfOperation operation) { - return RequiresProtection(operation, UAuthCsrfGrantInspector.UsesAuthenticationCookie(auth.Response)); + return RequiresProtection(operation, UAuthCsrfSurrogateInspector.UsesAuthenticationCookie(auth.Response)); } internal static bool RequiresProtection(UAuthCsrfOperation operation, bool usesAuthenticationCookie) diff --git a/src/CodeBeam.UltimateAuth.Server/Security/UAuthCsrfSurrogateInspector.cs b/src/CodeBeam.UltimateAuth.Server/Security/UAuthCsrfSurrogateInspector.cs new file mode 100644 index 00000000..aac0182d --- /dev/null +++ b/src/CodeBeam.UltimateAuth.Server/Security/UAuthCsrfSurrogateInspector.cs @@ -0,0 +1,14 @@ +using CodeBeam.UltimateAuth.Server.Auth; +using CodeBeam.UltimateAuth.Server.Domain; + +namespace CodeBeam.UltimateAuth.Server.Security; + +internal static class UAuthCsrfSurrogateInspector +{ + public static bool UsesAuthenticationCookie(EffectiveAuthResponse response) + { + return response.SessionIdTransport.Mode == SurrogateTransport.Cookie + || response.AccessTokenTransport.Mode == SurrogateTransport.Cookie + || response.RefreshTokenTransport.Mode == SurrogateTransport.Cookie; + } +} diff --git a/src/CodeBeam.UltimateAuth.Server/Services/JwtLogoutService.cs b/src/CodeBeam.UltimateAuth.Server/Services/JwtLogoutService.cs index 667f818d..3908127e 100644 --- a/src/CodeBeam.UltimateAuth.Server/Services/JwtLogoutService.cs +++ b/src/CodeBeam.UltimateAuth.Server/Services/JwtLogoutService.cs @@ -104,7 +104,7 @@ await store.ExecuteAsync( SessionOptions = flow.Options.Session, Now = now }, - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, ct); if (!lineage.IsValid || diff --git a/src/CodeBeam.UltimateAuth.Server/Services/RefreshTokenRotationService.cs b/src/CodeBeam.UltimateAuth.Server/Services/RefreshTokenRotationService.cs index 845e3dcc..02436f7e 100644 --- a/src/CodeBeam.UltimateAuth.Server/Services/RefreshTokenRotationService.cs +++ b/src/CodeBeam.UltimateAuth.Server/Services/RefreshTokenRotationService.cs @@ -237,7 +237,7 @@ validation.UserKey is not UserKey userKey || Device = context.Device, SessionOptions = flow.Options.Session }, - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, ct); if (!lineage.IsValid || diff --git a/src/CodeBeam.UltimateAuth.Server/Services/SessionLineageValidator.cs b/src/CodeBeam.UltimateAuth.Server/Services/SessionLineageValidator.cs index 54643755..6ddbdef3 100644 --- a/src/CodeBeam.UltimateAuth.Server/Services/SessionLineageValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Services/SessionLineageValidator.cs @@ -14,7 +14,7 @@ public SessionLineageValidator(ISessionStoreFactory storeFactory) _storeFactory = storeFactory; } - public async Task ValidateAsync(SessionValidationContext context, SessionCredentialPurpose expectedPurpose, CancellationToken ct = default) + public async Task ValidateAsync(SessionValidationContext context, SessionIdPurpose expectedPurpose, CancellationToken ct = default) { var options = context.SessionOptions ?? throw new InvalidOperationException("Session options are required for lineage validation."); diff --git a/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs b/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs index fc3cb6dd..f134bd65 100644 --- a/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs +++ b/src/CodeBeam.UltimateAuth.Server/Services/UAuthSessionValidator.cs @@ -18,7 +18,7 @@ public UAuthSessionValidator(ISessionLineageValidator lineageValidator, IUserCla public async Task ValidateSessionAsync(SessionValidationContext context, CancellationToken ct = default) { - var result = await _lineageValidator.ValidateAsync(context, SessionCredentialPurpose.Opaque, ct); + var result = await _lineageValidator.ValidateAsync(context, SessionIdPurpose.Opaque, ct); if (!result.IsValid || result.UserKey is not UserKey userKey || diff --git a/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Data/UAuthSessionsModelBuilder.cs b/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Data/UAuthSessionsModelBuilder.cs index 494e7d4e..e04e18ff 100644 --- a/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Data/UAuthSessionsModelBuilder.cs +++ b/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Data/UAuthSessionsModelBuilder.cs @@ -156,7 +156,7 @@ private static void ConfigureSessions(ModelBuilder b) e.Property(x => x.CredentialPurpose) .HasConversion() - .HasDefaultValue(SessionCredentialPurpose.Opaque) + .HasDefaultValue(SessionIdPurpose.Opaque) .IsRequired(); e.HasIndex(x => new { x.Tenant, x.SessionId }).IsUnique(); diff --git a/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Projections/SessionProjection.cs b/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Projections/SessionProjection.cs index 9adcfc02..3c284fe3 100644 --- a/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Projections/SessionProjection.cs +++ b/src/sessions/CodeBeam.UltimateAuth.Sessions.EntityFrameworkCore/Projections/SessionProjection.cs @@ -23,7 +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 SessionIdPurpose CredentialPurpose { get; set; } = SessionIdPurpose.Opaque; public bool IsRevoked => RevokedAt != null; } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Integration/Infrastructure/AuthServerFactory.cs b/tests/CodeBeam.UltimateAuth.Tests.Integration/Infrastructure/AuthServerFactory.cs index 98145c0c..7db210bc 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Integration/Infrastructure/AuthServerFactory.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Integration/Infrastructure/AuthServerFactory.cs @@ -67,7 +67,7 @@ protected override void ConfigureWebHost(IWebHostBuilder builder) services.PostConfigure(options => { // TODO: Decouple test projects and remove UAuthHub sample dependency. This is a temporary workaround to avoid UAuthHub sample's default cookie delivery mode from interfering with the tests. - options.GrantDelivery.Default = GrantDeliveryMode.Cookie; + options.Transport.Default = SurrogateTransport.Cookie; options.RateLimiting.Enabled = false; options.Login.IncludeFailureDetails = false; options.DeviceLimits.MaxDevices = null; diff --git a/tests/CodeBeam.UltimateAuth.Tests.Integration/LoginTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Integration/LoginTests.cs index de2dac52..1528a7dc 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Integration/LoginTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Integration/LoginTests.cs @@ -1864,9 +1864,9 @@ public async Task HybridLogin_WithSessionCookieAndBearerToken_ShouldValidate() using var factory = AuthServerFactory.Create(options => { options.AuthMode = UAuthMode.Hybrid; - options.GrantDelivery.Session.Mode = GrantDeliveryMode.Cookie; - options.GrantDelivery.AccessToken.Mode = GrantDeliveryMode.Header; - options.GrantDelivery.RefreshToken.Mode = GrantDeliveryMode.Cookie; + options.Transport.SessionId.Mode = SurrogateTransport.Cookie; + options.Transport.AccessToken.Mode = SurrogateTransport.Header; + options.Transport.RefreshToken.Mode = SurrogateTransport.Cookie; }); var ct = TestContext.Current.CancellationToken; diff --git a/tests/CodeBeam.UltimateAuth.Tests.Integration/PureJwtIdentityTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Integration/PureJwtIdentityTests.cs index fce7226f..dc4f69fb 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Integration/PureJwtIdentityTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Integration/PureJwtIdentityTests.cs @@ -580,26 +580,22 @@ public static async Task CreateAsync(DeviceMismatchBehavior deviceMismatch options.Session.DeviceMismatchBehavior = deviceMismatchBehavior; - options.GrantDelivery.AccessToken.Mode = GrantDeliveryMode.Header; - options.GrantDelivery.AccessToken.HeaderName = "Authorization"; - options.GrantDelivery.AccessToken.HeaderFormat = HeaderTokenFormat.Bearer; + options.Transport.AccessToken.Mode = SurrogateTransport.Header; + options.Transport.AccessToken.HeaderName = "Authorization"; + options.Transport.AccessToken.HeaderFormat = HeaderValueFormat.Bearer; }) .AddUltimateAuthInMemory(); builder.Services.Replace(ServiceDescriptor.Scoped(_ => runtimeStateProvider.Object)); - var sessionValidator = - new Mock(MockBehavior.Strict); + var sessionValidator = new Mock(MockBehavior.Strict); - builder.Services.Replace( - ServiceDescriptor.Scoped( - _ => sessionValidator.Object)); + builder.Services.Replace(ServiceDescriptor.Scoped(_ => sessionValidator.Object)); var app = builder.Build(); app.UseRouting(); - app.UseUltimateAuthWithAspNetCore( - useRateLimiting: false); + app.UseUltimateAuthWithAspNetCore(useRateLimiting: false); app.MapGet("/test/purejwt/identity", async ( diff --git a/tests/CodeBeam.UltimateAuth.Tests.Integration/RefreshTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Integration/RefreshTests.cs index 3d555f5c..a69879ca 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Integration/RefreshTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Integration/RefreshTests.cs @@ -2447,7 +2447,7 @@ public async Task Refresh_Hybrid_Maui_HeaderCredentials_ShouldSupportConsecutive using var factory = AuthServerFactory.Create(options => { options.AuthMode = UAuthMode.Hybrid; - options.GrantDelivery.Default = GrantDeliveryMode.Header; + options.Transport.Default = SurrogateTransport.Header; }); factory.Clock.Reset(); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Integration/ResourceApi/ResourceApiTestHost.cs b/tests/CodeBeam.UltimateAuth.Tests.Integration/ResourceApi/ResourceApiTestHost.cs index 3e7eab37..ebf42d5e 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Integration/ResourceApi/ResourceApiTestHost.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Integration/ResourceApi/ResourceApiTestHost.cs @@ -46,7 +46,7 @@ public static async Task CreateAsync( { options.Hub.BaseUrl = "https://uauth.test"; options.Auth.Mode = UAuthMode.PureOpaque; - options.Auth.Session.DeliveryMode = GrantDeliveryMode.Header; + options.Auth.SessionId.Mode = SurrogateTransport.Header; configureResourceApi?.Invoke(options); }); @@ -85,14 +85,14 @@ public static async Task CreateAsync( // Resource API tests authenticate with: // Authorization: Bearer var authenticationResponse = new EffectiveAuthResponse( - new EffectiveGrantDelivery( - GrantKind.Session, + new EffectiveSurrogateTransport( + SurrogateKind.SessionId, TokenFormat.Opaque, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: "Authorization", - headerFormat: HeaderTokenFormat.Bearer), - EffectiveGrantDelivery.Disabled(GrantKind.AccessToken), - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + headerFormat: HeaderValueFormat.Bearer), + EffectiveSurrogateTransport.Disabled(SurrogateKind.AccessToken), + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), EffectiveRedirectResponse.Disabled); var authResponseResolver = new Mock(); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Core/UAuthModeExtensionsTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Core/UAuthModeExtensionsTests.cs new file mode 100644 index 00000000..97381fc9 --- /dev/null +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Core/UAuthModeExtensionsTests.cs @@ -0,0 +1,118 @@ +using CodeBeam.UltimateAuth.Core.Contracts; +using CodeBeam.UltimateAuth.Core.Domain; +using CodeBeam.UltimateAuth.Core.Extensions; + +namespace CodeBeam.UltimateAuth.Tests.Unit.Core; + +public class UAuthModeExtensionsTests +{ + [Theory] + [InlineData(UAuthMode.PureOpaque, SurrogateKind.SessionId, true, false, false, null)] + [InlineData(UAuthMode.Hybrid, SurrogateKind.SessionId, true, true, true, TokenFormat.Opaque)] + [InlineData(UAuthMode.SemiHybrid, SurrogateKind.AccessToken, true, true, true, TokenFormat.Jwt)] + [InlineData(UAuthMode.PureJwt, SurrogateKind.AccessToken, false, true, true, TokenFormat.Jwt)] + public void Mode_ShouldExposeExpectedCharacteristics( + UAuthMode mode, + SurrogateKind primarySurrogate, + bool supportsLineage, + bool supportsAccessToken, + bool supportsRefreshToken, + TokenFormat? accessTokenFormat) + { + Assert.Equal( + primarySurrogate, + mode.GetPrimarySurrogateKind()); + + Assert.Equal( + supportsLineage, + mode.SupportsSessionLineage()); + + Assert.Equal( + supportsAccessToken, + mode.SupportsAccessToken()); + + Assert.Equal( + supportsRefreshToken, + mode.SupportsRefreshToken()); + + Assert.Equal( + accessTokenFormat, + mode.GetAccessTokenFormat()); + + Assert.Equal( + primarySurrogate == SurrogateKind.SessionId, + mode.UsesSessionIdForAuthentication()); + } + + [Fact] + public void UnsupportedMode_ShouldBeRejected() + { + var mode = (UAuthMode)int.MaxValue; + + Assert.Throws( + () => mode.GetPrimarySurrogateKind()); + + Assert.Throws( + () => mode.SupportsSessionLineage()); + + Assert.Throws( + () => mode.SupportsAccessToken()); + + Assert.Throws( + () => mode.SupportsRefreshToken()); + + Assert.Throws( + () => mode.GetAccessTokenFormat()); + + Assert.Throws( + () => mode.UsesSessionIdForAuthentication()); + } + + [Theory] + [InlineData(UAuthMode.PureOpaque, true, false, false)] + [InlineData(UAuthMode.Hybrid, true, true, true)] + [InlineData(UAuthMode.SemiHybrid, false, true, true)] + [InlineData(UAuthMode.PureJwt, false, true, true)] + public void SupportsSurrogate_ShouldMatchMode( + UAuthMode mode, + bool sessionId, + bool accessToken, + bool refreshToken) + { + Assert.Equal( + sessionId, + mode.SupportsSurrogate(SurrogateKind.SessionId)); + + Assert.Equal( + accessToken, + mode.SupportsSurrogate(SurrogateKind.AccessToken)); + + Assert.Equal( + refreshToken, + mode.SupportsSurrogate(SurrogateKind.RefreshToken)); + } + + [Theory] + [InlineData(UAuthMode.PureOpaque, TokenFormat.Opaque, null, null)] + [InlineData(UAuthMode.Hybrid, TokenFormat.Opaque, TokenFormat.Opaque, TokenFormat.Opaque)] + [InlineData(UAuthMode.SemiHybrid, null, TokenFormat.Jwt, TokenFormat.Opaque)] + [InlineData(UAuthMode.PureJwt, null, TokenFormat.Jwt ,TokenFormat.Opaque)] + public void GetTokenFormat_ShouldMatchMode(UAuthMode mode, TokenFormat? sessionId, TokenFormat? accessToken, TokenFormat? refreshToken) + { + Assert.Equal(sessionId, mode.GetTokenFormat(SurrogateKind.SessionId)); + Assert.Equal(accessToken, mode.GetTokenFormat(SurrogateKind.AccessToken)); + Assert.Equal(refreshToken, mode.GetTokenFormat(SurrogateKind.RefreshToken)); + } + + [Fact] + public void UnsupportedSurrogateKind_ShouldBeRejected() + { + var kind = (SurrogateKind)int.MaxValue; + + Assert.Throws( + () => UAuthMode.Hybrid.SupportsSurrogate(kind)); + + Assert.Throws( + () => UAuthMode.Hybrid.GetTokenFormat(kind)); + } +} diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Helpers/AuthFlowTestFactory.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Helpers/AuthFlowTestFactory.cs index daa76a8a..a98e94f2 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Helpers/AuthFlowTestFactory.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Helpers/AuthFlowTestFactory.cs @@ -37,16 +37,15 @@ public static AuthFlowContext New( session: session, options: TestServerOptions.Default(), response: response ?? new EffectiveAuthResponse( - sessionIdDelivery: - EffectiveGrantDelivery.Disabled(GrantKind.Session), - accessTokenDelivery: - EffectiveGrantDelivery.Disabled(GrantKind.AccessToken), - refreshTokenDelivery: - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + sessionIdTransport: + EffectiveSurrogateTransport.Disabled(SurrogateKind.SessionId), + accessTokenTransport: + EffectiveSurrogateTransport.Disabled(SurrogateKind.AccessToken), + refreshTokenTransport: + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), redirect: redirect ?? EffectiveRedirectResponse.Disabled ), - primaryTokenKind: PrimaryTokenKind.Session, returnUrlInfo: returnUrlInfo ?? ReturnUrlInfo.None() ); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/RemoteHubValidationServiceTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/RemoteHubValidationServiceTests.cs index 4e34eeee..a69a7011 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/RemoteHubValidationServiceTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/RemoteHubValidationServiceTests.cs @@ -5,11 +5,13 @@ using CodeBeam.UltimateAuth.Core.MultiTenancy; using CodeBeam.UltimateAuth.Server.Abstractions; using CodeBeam.UltimateAuth.Server.Auth; +using CodeBeam.UltimateAuth.Server.Extensions; using CodeBeam.UltimateAuth.Server.Infrastructure; using CodeBeam.UltimateAuth.Server.Options; using CodeBeam.UltimateAuth.Server.ResourceApi; using CodeBeam.UltimateAuth.Tests.Unit.Helpers; using Microsoft.AspNetCore.Http; +using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Moq; @@ -55,8 +57,7 @@ public async Task ValidateAsync_ShouldSendExpectedHubValidationRequest() fixture.Credentials.Verify(x => x.ResolveAsync( fixture.Context, - UAuthMode.SemiHybrid, - It.IsAny()), Times.Once); + It.IsAny()), Times.Once); } [Fact] @@ -166,16 +167,15 @@ public async Task ValidateAsync_InvalidClaim_ShouldReject( } [Fact] - public async Task ValidateAsync_MissingCredential_ShouldReject() + public async Task ValidateAsync_MissingSurrogate_ShouldReject() { using var fixture = CreateFixture(); fixture.Credentials .Setup(x => x.ResolveAsync( fixture.Context, - UAuthMode.SemiHybrid, - It.IsAny())) - .ReturnsAsync((TransportCredential?)null); + It.IsAny())) + .ReturnsAsync((ResolvedSurrogate?)null); var result = await ValidateAsync(fixture); @@ -185,20 +185,17 @@ public async Task ValidateAsync_MissingCredential_ShouldReject() } [Theory] - [InlineData(TransportCredentialKind.Session)] - [InlineData(TransportCredentialKind.RefreshToken)] - [InlineData(TransportCredentialKind.Hub)] - public async Task ValidateAsync_WrongCredentialKind_ShouldReject( - TransportCredentialKind kind) + [InlineData(SurrogateKind.SessionId)] + [InlineData(SurrogateKind.RefreshToken)] + public async Task ValidateAsync_WrongCredentialKind_ShouldReject(SurrogateKind kind) { using var fixture = CreateFixture(); fixture.Credentials .Setup(x => x.ResolveAsync( fixture.Context, - UAuthMode.SemiHybrid, - It.IsAny())) - .ReturnsAsync(CreateCredential(kind)); + It.IsAny())) + .ReturnsAsync(CreateSurrogate(kind)); var result = await ValidateAsync(fixture); @@ -549,8 +546,7 @@ await act.Should() [Theory] [InlineData(true)] [InlineData(false)] - public async Task ValidateAsync_SameRequest_ShouldCacheResult( - bool valid) + public async Task ValidateAsync_SameRequest_ShouldCacheResult(bool valid) { using var fixture = CreateFixture(); @@ -573,8 +569,7 @@ public async Task ValidateAsync_SameRequest_ShouldCacheResult( fixture.Credentials.Verify(x => x.ResolveAsync( fixture.Context, - UAuthMode.SemiHybrid, - It.IsAny()), Times.Once); + It.IsAny()), Times.Once); } [Fact] @@ -588,11 +583,8 @@ public async Task ValidateAsync_DifferentRequests_ShouldNotShareCache() fixture.Services); fixture.Credentials - .Setup(x => x.ResolveAsync( - secondContext, - UAuthMode.SemiHybrid, - It.IsAny())) - .ReturnsAsync(CreateCredential()); + .Setup(x => x.ResolveAsync(secondContext, It.IsAny())) + .ReturnsAsync(CreateSurrogate()); fixture.DeviceResolver .Setup(x => x.ResolveAsync(secondContext)) @@ -625,7 +617,7 @@ private static Fixture CreateFixture() DeviceMismatchBehavior.Reject; var credentials = - new Mock( + new Mock( MockBehavior.Strict); var deviceResolver = @@ -638,11 +630,8 @@ private static Fixture CreateFixture() var context = CreateHttpContext(services); credentials - .Setup(x => x.ResolveAsync( - context, - UAuthMode.SemiHybrid, - It.IsAny())) - .ReturnsAsync(CreateCredential()); + .Setup(x => x.ResolveAsync(context, It.IsAny())) + .ReturnsAsync(CreateSurrogate()); deviceResolver .Setup(x => x.ResolveAsync(context)) @@ -712,11 +701,9 @@ private static ClaimsPrincipal CreatePrincipal( UAuthConstants.SchemeDefaults.GlobalScheme)); } - private static TransportCredential CreateCredential( - TransportCredentialKind kind = - TransportCredentialKind.AccessToken) + private static ResolvedSurrogate CreateSurrogate(SurrogateKind kind = SurrogateKind.AccessToken) { - return new TransportCredential + return new ResolvedSurrogate { Kind = kind, Value = AccessToken, @@ -803,7 +790,7 @@ private static void AssertInvalid( private sealed record Fixture( RemoteHubValidationService Sut, DefaultHttpContext Context, - Mock Credentials, + Mock Credentials, Mock DeviceResolver, RecordingHttpHandler Handler, UAuthResourceApiOptions Options, diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/ResourceSessionIdResolverTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/ResourceSessionIdResolverTests.cs index e5efbfde..790376e1 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/ResourceSessionIdResolverTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/ResourceSessionIdResolverTests.cs @@ -4,6 +4,7 @@ using CodeBeam.UltimateAuth.Core.Options; using CodeBeam.UltimateAuth.Server.Auth; using CodeBeam.UltimateAuth.Server.Domain; +using CodeBeam.UltimateAuth.Server.Extensions; using CodeBeam.UltimateAuth.Server.Infrastructure; using CodeBeam.UltimateAuth.Server.Options; using CodeBeam.UltimateAuth.Server.ResourceApi; @@ -26,7 +27,7 @@ public async Task ResolveAsync_WhenSessionBasedMode_ShouldResolveSession(UAuthMo var (sut, context, transport) = CreateSut( mode, CreateCredential( - TransportCredentialKind.Session, + SurrogateKind.SessionId, sessionId.Value)); var result = await sut.ResolveAsync( @@ -37,8 +38,7 @@ public async Task ResolveAsync_WhenSessionBasedMode_ShouldResolveSession(UAuthMo transport.Verify(x => x.ResolveAsync( context, - mode, - It.IsAny()), + It.IsAny()), Times.Once); } @@ -82,7 +82,7 @@ public async Task ResolveAsync_WhenCredentialIsAccessToken_ShouldReturnNull(UAut var (sut, context, _) = CreateSut( mode, CreateCredential( - TransportCredentialKind.AccessToken, + SurrogateKind.AccessToken, sessionId.Value)); var result = await sut.ResolveAsync( @@ -101,7 +101,7 @@ public async Task ResolveAsync_WhenSessionIdIsInvalid_ShouldReturnNull(string va var (sut, context, _) = CreateSut( UAuthMode.PureOpaque, CreateCredential( - TransportCredentialKind.Session, + SurrogateKind.SessionId, value)); var result = await sut.ResolveAsync( @@ -118,7 +118,7 @@ public async Task ResolveAsync_ShouldUseConfiguredSessionCookie(UAuthMode mode) { var (sut, context, transport) = CreateSut( mode, - deliveryMode: GrantDeliveryMode.Cookie, + deliveryMode: SurrogateTransport.Cookie, cookieName: "custom-resource-session"); await sut.ResolveAsync( @@ -127,18 +127,15 @@ await sut.ResolveAsync( transport.Verify(x => x.ResolveAsync( context, - mode, - It.Is(response => - response.SessionIdDelivery.Mode == - GrantDeliveryMode.Cookie && - response.SessionIdDelivery.Kind == - GrantKind.Session && - response.SessionIdDelivery.TokenFormat == - TokenFormat.Opaque && - response.SessionIdDelivery.Cookie != null && - response.SessionIdDelivery.Cookie.Name == - "custom-resource-session")), + It.Is(t => + t.Mode == SurrogateTransport.Cookie && + t.Kind == SurrogateKind.SessionId && + t.TokenFormat == TokenFormat.Opaque && + t.Cookie != null && + t.Cookie.Name == "custom-resource-session")), Times.Once); + + transport.VerifyNoOtherCalls(); } [Theory] @@ -148,7 +145,7 @@ public async Task ResolveAsync_WhenHeaderIsConfigured_ShouldUseAuthorizationBear { var (sut, context, transport) = CreateSut( mode, - deliveryMode: GrantDeliveryMode.Header); + deliveryMode: SurrogateTransport.Header); await sut.ResolveAsync( context, @@ -156,21 +153,21 @@ await sut.ResolveAsync( transport.Verify(x => x.ResolveAsync( context, - mode, - It.Is(response => - response.SessionIdDelivery.Mode == - GrantDeliveryMode.Header && - response.SessionIdDelivery.RequestHeaderName == - "Authorization" && - response.SessionIdDelivery.RequestHeaderFormat == - HeaderTokenFormat.Bearer)), + It.Is(t => + t.Kind == SurrogateKind.SessionId && + t.TokenFormat == TokenFormat.Opaque && + t.Mode == SurrogateTransport.Header && + t.RequestHeaderName == "Authorization" && + t.RequestHeaderFormat == HeaderValueFormat.Bearer)), Times.Once); + + transport.VerifyNoOtherCalls(); } [Theory] [InlineData(UAuthMode.PureOpaque)] [InlineData(UAuthMode.Hybrid)] - public async Task ResolveAsync_ShouldDisableNonSessionGrants(UAuthMode mode) + public async Task ResolveAsync_ShouldResolveOnlySessionIdSurrogate(UAuthMode mode) { var (sut, context, transport) = CreateSut(mode); @@ -180,33 +177,28 @@ await sut.ResolveAsync( transport.Verify(x => x.ResolveAsync( context, - mode, - It.Is(response => - response.AccessTokenDelivery.Mode == - GrantDeliveryMode.None && - response.RefreshTokenDelivery.Mode == - GrantDeliveryMode.None)), + It.Is(t => + t.Kind == SurrogateKind.SessionId && + t.TokenFormat == TokenFormat.Opaque)), Times.Once); + + transport.VerifyNoOtherCalls(); } [Fact] public async Task ResolveAsync_WhenCancelled_ShouldThrowBeforeResolvingCredential() { - var (sut, context, transport) = - CreateSut(UAuthMode.PureOpaque); + var (sut, context, transport) = CreateSut(UAuthMode.PureOpaque); using var cancellation = new CancellationTokenSource(); cancellation.Cancel(); Func act = async () => { - await sut.ResolveAsync( - context, - cancellation.Token); + await sut.ResolveAsync(context, cancellation.Token); }; - await act.Should() - .ThrowAsync(); + await act.Should().ThrowAsync(); transport.VerifyNoOtherCalls(); } @@ -214,11 +206,11 @@ await act.Should() private static ( ResourceSessionIdResolver Sut, DefaultHttpContext Context, - Mock Transport) + Mock Transport) CreateSut( UAuthMode mode, - TransportCredential? credential = null, - GrantDeliveryMode deliveryMode = GrantDeliveryMode.Cookie, + ResolvedSurrogate? credential = null, + SurrogateTransport deliveryMode = SurrogateTransport.Cookie, string cookieName = "uas") { var context = new DefaultHttpContext(); @@ -226,8 +218,8 @@ private static ( var options = new UAuthResourceApiOptions(); options.Auth.Mode = mode; - options.Auth.Session.DeliveryMode = deliveryMode; - options.Auth.Session.CookieName = cookieName; + options.Auth.SessionId.Mode = deliveryMode; + options.Auth.SessionId.CookieName = cookieName; var wrappedOptions = Options.Create(options); @@ -235,14 +227,13 @@ private static ( wrappedOptions, Mock.Of()); - var transport = new Mock( + var transport = new Mock( MockBehavior.Strict); transport .Setup(x => x.ResolveAsync( context, - mode, - It.IsAny())) + It.IsAny())) .ReturnsAsync(credential); var sut = new ResourceSessionIdResolver( @@ -253,9 +244,9 @@ private static ( return (sut, context, transport); } - private static TransportCredential CreateCredential(TransportCredentialKind kind, string value) + private static ResolvedSurrogate CreateCredential(SurrogateKind kind, string value) { - return new TransportCredential + return new ResolvedSurrogate { Kind = kind, Value = value, diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiOptionsTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiOptionsTests.cs index 7f5322b9..c4bfec07 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiOptionsTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiOptionsTests.cs @@ -21,15 +21,15 @@ public void Defaults_ShouldBeInitializedCorrectly() Assert.Null(options.Auth.Mode); Assert.Null(options.Auth.Jwt); - Assert.Equal(GrantDeliveryMode.Cookie, options.Auth.Session.DeliveryMode); + Assert.Equal(SurrogateTransport.Cookie, options.Auth.SessionId.Mode); - Assert.Equal("uas", options.Auth.Session.CookieName); + Assert.Equal("uas", options.Auth.SessionId.CookieName); - Assert.Equal(GrantDeliveryMode.Header, options.Auth.AccessToken.DeliveryMode); + Assert.Equal(SurrogateTransport.Header, options.Auth.AccessToken.Mode); Assert.Equal("uat", options.Auth.AccessToken.CookieName); Assert.Equal("Authorization", options.Auth.AccessToken.HeaderName); - Assert.Equal(HeaderTokenFormat.Bearer, options.Auth.AccessToken.HeaderFormat); + Assert.Equal(HeaderValueFormat.Bearer, options.Auth.AccessToken.HeaderFormat); Assert.Equal(DeviceMismatchBehavior.Reject, options.Auth.Device.MismatchBehavior); @@ -48,16 +48,16 @@ public void Clone_ShouldPreserveConfiguredValues() Assert.Equal(source.Auth.Mode, clone.Auth.Mode); Assert.Equal( - source.Auth.Session.DeliveryMode, - clone.Auth.Session.DeliveryMode); + source.Auth.SessionId.Mode, + clone.Auth.SessionId.Mode); Assert.Equal( - source.Auth.Session.CookieName, - clone.Auth.Session.CookieName); + source.Auth.SessionId.CookieName, + clone.Auth.SessionId.CookieName); Assert.Equal( - source.Auth.AccessToken.DeliveryMode, - clone.Auth.AccessToken.DeliveryMode); + source.Auth.AccessToken.Mode, + clone.Auth.AccessToken.Mode); Assert.Equal( source.Auth.AccessToken.CookieName, @@ -127,7 +127,7 @@ public void Clone_ShouldCreateIndependentNestedObjects() Assert.NotSame(source, clone); Assert.NotSame(source.Auth, clone.Auth); - Assert.NotSame(source.Auth.Session, clone.Auth.Session); + Assert.NotSame(source.Auth.SessionId, clone.Auth.SessionId); Assert.NotSame(source.Auth.AccessToken, clone.Auth.AccessToken); Assert.NotSame(source.Auth.Device, clone.Auth.Device); Assert.NotSame(source.Auth.Jwt, clone.Auth.Jwt); @@ -146,7 +146,7 @@ public void Clone_ModifyingClone_ShouldNotModifySource() var clone = source.Clone(); clone.Auth.Mode = UAuthMode.PureOpaque; - clone.Auth.Session.CookieName = "changed-session"; + clone.Auth.SessionId.CookieName = "changed-session"; clone.Auth.AccessToken.CookieName = "changed-access"; clone.Auth.AccessToken.HeaderName = "X-Changed"; clone.Auth.Device.MismatchBehavior = @@ -157,7 +157,7 @@ public void Clone_ModifyingClone_ShouldNotModifySource() clone.MultiTenant.HeaderName = "X-Other-Tenant"; Assert.Equal(UAuthMode.PureJwt, source.Auth.Mode); - Assert.Equal("session-custom", source.Auth.Session.CookieName); + Assert.Equal("session-custom", source.Auth.SessionId.CookieName); Assert.Equal("access-custom", source.Auth.AccessToken.CookieName); Assert.Equal("X-Access-Token", source.Auth.AccessToken.HeaderName); Assert.Equal( @@ -298,18 +298,18 @@ private static UAuthResourceApiOptions CreateConfiguredOptions() { Mode = UAuthMode.PureJwt, - Session = new UAuthResourceSessionOptions + SessionId = new UAuthResourceSurrogateTransportOptions { - DeliveryMode = GrantDeliveryMode.Cookie, + Mode = SurrogateTransport.Cookie, CookieName = "session-custom" }, - AccessToken = new UAuthResourceAccessTokenOptions + AccessToken = new UAuthResourceSurrogateTransportOptions { - DeliveryMode = GrantDeliveryMode.Cookie, + Mode = SurrogateTransport.Cookie, CookieName = "access-custom", HeaderName = "X-Access-Token", - HeaderFormat = HeaderTokenFormat.Bearer + HeaderFormat = HeaderValueFormat.Bearer }, Device = new UAuthResourceDeviceOptions diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiOptionsValidatorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiOptionsValidatorTests.cs index e426d64c..f82fcef5 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiOptionsValidatorTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiOptionsValidatorTests.cs @@ -137,19 +137,17 @@ public void MissingRootSections_ShouldReportAllErrors() } [Theory] - [InlineData("Session", "Auth.Session must be configured.")] + [InlineData("Session", "Auth.SessionId must be configured.")] [InlineData("AccessToken", "Auth.AccessToken must be configured.")] [InlineData("Device", "Auth.Device must be configured.")] - public void MissingAuthSection_ShouldFail( - string section, - string expectedError) + public void MissingAuthSection_ShouldFail(string section, string expectedError) { var options = ValidOptions(); switch (section) { case "Session": - options.Auth.Session = null!; + options.Auth.SessionId = null!; break; case "AccessToken": options.Auth.AccessToken = null!; @@ -167,13 +165,13 @@ public void MissingAuthSections_ShouldReportAllErrors() { var options = ValidOptions(); - options.Auth.Session = null!; + options.Auth.SessionId = null!; options.Auth.AccessToken = null!; options.Auth.Device = null!; AssertErrors( options, - "Auth.Session must be configured.", + "Auth.SessionId must be configured.", "Auth.AccessToken must be configured.", "Auth.Device must be configured."); } @@ -182,11 +180,11 @@ public void MissingAuthSections_ShouldReportAllErrors() public void InvalidSessionDeliveryMode_ShouldFail() { var options = ValidOptions(); - options.Auth.Session.DeliveryMode = (GrantDeliveryMode)999; + options.Auth.SessionId.Mode = (SurrogateTransport)999; AssertInvalid( options, - "Auth.Session.DeliveryMode is invalid."); + "Auth.SessionId.Mode is invalid."); } [Theory] @@ -196,29 +194,29 @@ public void InvalidSessionDeliveryMode_ShouldFail() public void MissingSessionCookieName_ShouldFail(string? value) { var options = ValidOptions(); - options.Auth.Session.CookieName = value!; + options.Auth.SessionId.CookieName = value!; AssertInvalid( options, - "Auth.Session.CookieName is required."); + "Auth.SessionId.CookieName is required."); } [Fact] public void InvalidAccessTokenDeliveryMode_ShouldFail() { var options = ValidOptions(); - options.Auth.AccessToken.DeliveryMode = (GrantDeliveryMode)999; + options.Auth.AccessToken.Mode = (SurrogateTransport)999; AssertInvalid( options, - "Auth.AccessToken.DeliveryMode is invalid."); + "Auth.AccessToken.Mode is invalid."); } [Fact] public void InvalidAccessTokenHeaderFormat_ShouldFail() { var options = ValidOptions(); - options.Auth.AccessToken.HeaderFormat = (HeaderTokenFormat)999; + options.Auth.AccessToken.HeaderFormat = (HeaderValueFormat)999; AssertInvalid( options, @@ -500,7 +498,7 @@ public void MultipleInvalidFields_ShouldReportAllApplicableErrors() { var options = ValidOptions(UAuthMode.PureJwt); - options.Auth.Session.CookieName = ""; + options.Auth.SessionId.CookieName = ""; options.Auth.AccessToken.HeaderName = ""; options.Auth.Device.MismatchBehavior = DeviceMismatchBehavior.AllowAndRebind; @@ -514,7 +512,7 @@ public void MultipleInvalidFields_ShouldReportAllApplicableErrors() AssertErrors( options, - "Auth.Session.CookieName is required.", + "Auth.SessionId.CookieName is required.", "Auth.AccessToken.HeaderName is required.", "JWT authentication modes do not support device rebinding.", "Auth.Jwt.Issuer is required.", diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiRegistrationTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiRegistrationTests.cs index 1f679a85..c1ceb60b 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiRegistrationTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/ResourceApi/UAuthResourceApiRegistrationTests.cs @@ -67,11 +67,9 @@ public void AddUltimateAuthResourceApi_ShouldRegisterTransportCredentialResolver using var scope = provider.CreateScope(); - var resolver = - scope.ServiceProvider.GetRequiredService(); + var resolver = scope.ServiceProvider.GetRequiredService(); - resolver.Should() - .BeOfType(); + resolver.Should().BeOfType(); } [Fact] @@ -80,12 +78,9 @@ public void AddUltimateAuthResourceApi_ShouldRegisterDeviceContextFactory() using var provider = CreateProvider(); using var scope = provider.CreateScope(); + var factory = scope.ServiceProvider.GetRequiredService(); - var factory = - scope.ServiceProvider.GetRequiredService(); - - factory.Should() - .BeOfType(); + factory.Should().BeOfType(); } [Fact] diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Security/UAuthCsrfPolicyEvaluatorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Security/UAuthCsrfPolicyEvaluatorTests.cs index ac0945c2..63dd1598 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Security/UAuthCsrfPolicyEvaluatorTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Security/UAuthCsrfPolicyEvaluatorTests.cs @@ -41,22 +41,22 @@ public void RequiresProtection_WhenOperationIsUnknown_ShouldFailClosed(bool uses } [Theory] - [InlineData(GrantKind.Session)] - [InlineData(GrantKind.AccessToken)] - [InlineData(GrantKind.RefreshToken)] + [InlineData(SurrogateKind.SessionId)] + [InlineData(SurrogateKind.AccessToken)] + [InlineData(SurrogateKind.RefreshToken)] public void RequiresProtection_WhenAnyGrantUsesCookie_ShouldReturnTrue( - GrantKind cookieGrant) + SurrogateKind cookieGrant) { var response = CreateResponse( - sessionMode: cookieGrant == GrantKind.Session - ? GrantDeliveryMode.Cookie - : GrantDeliveryMode.Header, - accessMode: cookieGrant == GrantKind.AccessToken - ? GrantDeliveryMode.Cookie - : GrantDeliveryMode.Header, - refreshMode: cookieGrant == GrantKind.RefreshToken - ? GrantDeliveryMode.Cookie - : GrantDeliveryMode.Header); + sessionMode: cookieGrant == SurrogateKind.SessionId + ? SurrogateTransport.Cookie + : SurrogateTransport.Header, + accessMode: cookieGrant == SurrogateKind.AccessToken + ? SurrogateTransport.Cookie + : SurrogateTransport.Header, + refreshMode: cookieGrant == SurrogateKind.RefreshToken + ? SurrogateTransport.Cookie + : SurrogateTransport.Header); var flow = AuthFlowTestFactory.New(response: response); @@ -76,9 +76,9 @@ public void RequiresProtection_WhenAllGrantsUseHeader_ShouldReturnFalse( UAuthCsrfOperation operation) { var response = CreateResponse( - GrantDeliveryMode.Header, - GrantDeliveryMode.Header, - GrantDeliveryMode.Header); + SurrogateTransport.Header, + SurrogateTransport.Header, + SurrogateTransport.Header); var flow = AuthFlowTestFactory.New(response: response); @@ -96,9 +96,9 @@ public void RequiresProtection_WhenAllGrantsAreDisabled_ShouldReturnFalse( UAuthCsrfOperation operation) { var response = CreateResponse( - GrantDeliveryMode.None, - GrantDeliveryMode.None, - GrantDeliveryMode.None); + SurrogateTransport.None, + SurrogateTransport.None, + SurrogateTransport.None); var flow = AuthFlowTestFactory.New(response: response); @@ -112,9 +112,9 @@ public void RequiresProtection_WhenAllGrantsAreDisabled_ShouldReturnFalse( public void RequiresProtection_WhenAccessTokenUsesHeaderAndRefreshUsesCookie_ShouldReturnTrue() { var response = CreateResponse( - GrantDeliveryMode.None, - GrantDeliveryMode.Header, - GrantDeliveryMode.Cookie); + SurrogateTransport.None, + SurrogateTransport.Header, + SurrogateTransport.Cookie); var flow = AuthFlowTestFactory.New(response: response); @@ -127,29 +127,29 @@ public void RequiresProtection_WhenAccessTokenUsesHeaderAndRefreshUsesCookie_Sho } private static EffectiveAuthResponse CreateResponse( - GrantDeliveryMode sessionMode, - GrantDeliveryMode accessMode, - GrantDeliveryMode refreshMode) + SurrogateTransport sessionMode, + SurrogateTransport accessMode, + SurrogateTransport refreshMode) { return new EffectiveAuthResponse( - CreateDelivery(GrantKind.Session, sessionMode, "uas"), - CreateDelivery(GrantKind.AccessToken, accessMode, "uat"), - CreateDelivery(GrantKind.RefreshToken, refreshMode, "uar"), + CreateDelivery(SurrogateKind.SessionId, sessionMode, "uas"), + CreateDelivery(SurrogateKind.AccessToken, accessMode, "uat"), + CreateDelivery(SurrogateKind.RefreshToken, refreshMode, "uar"), EffectiveRedirectResponse.Disabled); } - private static EffectiveGrantDelivery CreateDelivery( - GrantKind kind, - GrantDeliveryMode mode, + private static EffectiveSurrogateTransport CreateDelivery( + SurrogateKind kind, + SurrogateTransport mode, string name) { - return new EffectiveGrantDelivery( + return new EffectiveSurrogateTransport( kind, TokenFormat.Opaque, mode, name: name, - headerFormat: HeaderTokenFormat.Bearer, - cookie: mode == GrantDeliveryMode.Cookie + headerFormat: HeaderValueFormat.Bearer, + cookie: mode == SurrogateTransport.Cookie ? new UAuthCookieOptions { Name = name } : null); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Security/UAuthCsrfGrantInspectorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Security/UAuthCsrfSurrogateInspectorTests.cs similarity index 55% rename from tests/CodeBeam.UltimateAuth.Tests.Unit/Security/UAuthCsrfGrantInspectorTests.cs rename to tests/CodeBeam.UltimateAuth.Tests.Unit/Security/UAuthCsrfSurrogateInspectorTests.cs index ca8534cd..d5100bb5 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Security/UAuthCsrfGrantInspectorTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Security/UAuthCsrfSurrogateInspectorTests.cs @@ -7,19 +7,19 @@ namespace CodeBeam.UltimateAuth.Tests.Unit.Server; -public sealed class UAuthCsrfGrantInspectorTests +public sealed class UAuthCsrfSurrogateInspectorTests { - public static TheoryData DeliveryCombinations + public static TheoryData DeliveryCombinations { get { - var data = new TheoryData(); + var data = new TheoryData(); var modes = new[] { - GrantDeliveryMode.None, - GrantDeliveryMode.Header, - GrantDeliveryMode.Cookie + SurrogateTransport.None, + SurrogateTransport.Header, + SurrogateTransport.Cookie }; foreach (var session in modes) @@ -27,9 +27,9 @@ public static TheoryData _profileReader = new(MockBehavior.Strict); - private readonly Mock _primaryTokenResolver = new(MockBehavior.Strict); private readonly Mock _optionsProvider = new(MockBehavior.Strict); private readonly Mock _responseResolver = new(MockBehavior.Strict); private readonly Mock _deviceResolver = new(MockBehavior.Strict); @@ -106,10 +105,6 @@ public AuthFlowContextFactoryTests() .Setup(x => x.GetEffective(_http, Profile)) .Returns(_effective); - _primaryTokenResolver - .Setup(x => x.Resolve(UAuthMode.SemiHybrid)) - .Returns(PrimaryTokenKind.AccessToken); - _responseResolver .Setup(x => x.Resolve( UAuthMode.SemiHybrid, @@ -137,7 +132,6 @@ public AuthFlowContextFactoryTests() _sut = new AuthFlowContextFactory( _profileReader.Object, - _primaryTokenResolver.Object, _optionsProvider.Object, _responseResolver.Object, _deviceResolver.Object, @@ -220,7 +214,7 @@ private void SetupLineage( _lineageValidator .Setup(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, Ct)) .ReturnsAsync(result); } @@ -320,10 +314,6 @@ public async Task CreateAsync_SemiHybrid_Standard_ShouldAuthenticateWithoutSessi Assert.Equal(Tenant, result.Tenant); Assert.Equal(_deviceContext, result.Device); - Assert.Equal( - PrimaryTokenKind.AccessToken, - result.PrimaryTokenKind); - Assert.Same(_options, result.Options); Assert.Same(_response, result.Response); @@ -349,11 +339,11 @@ public async Task CreateAsync_SemiHybrid_HubValidated_ShouldCreateSessionContext _lineageValidator .Setup(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, Ct)) .Callback< SessionValidationContext, - SessionCredentialPurpose, + SessionIdPurpose, CancellationToken>( (context, _, _) => captured = context) .ReturnsAsync(CreateActiveLineage()); @@ -385,7 +375,7 @@ public async Task CreateAsync_SemiHybrid_HubValidated_ShouldCreateSessionContext _lineageValidator.Verify( x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, Ct), Times.Once); @@ -419,7 +409,7 @@ public async Task CreateAsync_SemiHybrid_InvalidLineage_ShouldRemainAnonymous( _lineageValidator.Verify( x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, Ct), Times.Once); @@ -466,7 +456,7 @@ public async Task CreateAsync_SemiHybrid_LineageBindingMismatch_ShouldRemainAnon _lineageValidator.Verify( x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, Ct), Times.Once); @@ -535,7 +525,7 @@ public async Task CreateAsync_SemiHybrid_RepeatedHubValidation_ShouldReuseLineag _lineageValidator.Verify( x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, Ct), Times.Once); @@ -575,7 +565,7 @@ public async Task CreateAsync_SemiHybrid_ShouldHonorEndpointClassification(UAuth _lineageValidator.Verify( x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, Ct), Times.Once); } @@ -615,7 +605,7 @@ public async Task CreateAsync_SemiHybrid_EndpointOverride_ShouldRequireHubValida _lineageValidator.Verify( x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, Ct), Times.Once); @@ -654,7 +644,7 @@ public async Task CreateAsync_SemiHybrid_MandatoryHubValidation_CannotBeDowngrad _lineageValidator.Verify( x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, Ct), Times.Once); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/AuthResponseResolverTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/AuthResponseResolverTests.cs index 13b4bc8c..91407970 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/AuthResponseResolverTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/AuthResponseResolverTests.cs @@ -24,8 +24,8 @@ public void Resolve_ShouldEnableExpectedGrants(UAuthMode mode, bool session, boo var result = sut.ResolveForAuthentication(mode, UAuthApplicationProfile.BlazorWasm, effective); - Assert.Equal(session, result.SessionIdDelivery.Mode != GrantDeliveryMode.None); - Assert.Equal(accessToken, result.AccessTokenDelivery.Mode != GrantDeliveryMode.None); - Assert.Equal(refreshToken, result.RefreshTokenDelivery.Mode != GrantDeliveryMode.None); + Assert.Equal(session, result.SessionIdTransport.Mode != SurrogateTransport.None); + Assert.Equal(accessToken, result.AccessTokenTransport.Mode != SurrogateTransport.None); + Assert.Equal(refreshToken, result.RefreshTokenTransport.Mode != SurrogateTransport.None); } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/CookieInfrastructureTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/CookieInfrastructureTests.cs index 18e6024d..00fc1a31 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/CookieInfrastructureTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/CookieInfrastructureTests.cs @@ -25,15 +25,15 @@ public void Build_should_throw_when_cookie_options_are_missing() { var context = AuthFlowTestFactory.New(); - var delivery = new EffectiveGrantDelivery( - kind: GrantKind.Session, + var delivery = new EffectiveSurrogateTransport( + kind: SurrogateKind.SessionId, tokenFormat: TokenFormat.Opaque, - mode: GrantDeliveryMode.Cookie); + mode: SurrogateTransport.Cookie); var act = () => _builder.Build( delivery, context, - GrantKind.Session); + SurrogateKind.SessionId); act.Should() .Throw() @@ -55,7 +55,7 @@ public void Build_should_preserve_explicit_cookie_settings() cookie.SameSite = SameSiteMode.Strict; var options = Build( - GrantKind.Session, + SurrogateKind.SessionId, cookie); options.HttpOnly.Should().BeTrue(); @@ -72,7 +72,7 @@ public void Build_should_support_non_http_only_cookie_configuration() cookie.HttpOnly = false; var options = Build( - GrantKind.Session, + SurrogateKind.SessionId, cookie); options.HttpOnly.Should().BeFalse(); @@ -85,7 +85,7 @@ public void Build_should_disable_secure_when_policy_is_not_always() cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest; var options = Build( - GrantKind.Session, + SurrogateKind.SessionId, cookie); options.Secure.Should().BeFalse(); @@ -99,7 +99,7 @@ public void Build_should_preserve_host_only_cookie_configuration() cookie.Path = "/"; var options = Build( - GrantKind.Session, + SurrogateKind.SessionId, cookie); options.Domain.Should().BeNull(); @@ -134,9 +134,9 @@ public void Build_should_resolve_same_site_from_deployment_mode( context.Options.HubDeploymentMode = deploymentMode; var options = _builder.Build( - CreateResponse(GrantKind.Session, cookie), + CreateResponse(SurrogateKind.SessionId, cookie), context, - GrantKind.Session); + SurrogateKind.SessionId); options.SameSite.Should().Be(expected); } @@ -156,9 +156,9 @@ public void Explicit_same_site_should_override_deployment_mode( UAuthHubDeploymentMode.External; var options = _builder.Build( - CreateResponse(GrantKind.Session, cookie), + CreateResponse(SurrogateKind.SessionId, cookie), context, - GrantKind.Session); + SurrogateKind.SessionId); options.SameSite.Should().Be(explicitMode); } @@ -183,9 +183,9 @@ public void Explicit_max_age_should_override_all_other_lifetimes() TimeSpan.FromHours(4); var options = _builder.Build( - CreateResponse(GrantKind.Session, cookie), + CreateResponse(SurrogateKind.SessionId, cookie), context, - GrantKind.Session); + SurrogateKind.SessionId); options.MaxAge.Should().Be(TimeSpan.FromMinutes(35)); } @@ -206,9 +206,9 @@ public void Absolute_lifetime_override_should_take_precedence_over_grant_lifetim TimeSpan.FromHours(4); var options = _builder.Build( - CreateResponse(GrantKind.Session, cookie), + CreateResponse(SurrogateKind.SessionId, cookie), context, - GrantKind.Session); + SurrogateKind.SessionId); // Current implementation adds IdleBuffer even // when AbsoluteLifetimeOverride is specified. @@ -223,7 +223,7 @@ public void Null_idle_buffer_should_be_treated_as_zero() cookie.Lifetime.IdleBuffer = null; var options = Build( - GrantKind.Session, + SurrogateKind.SessionId, cookie); options.MaxAge.Should().Be(TimeSpan.FromMinutes(30)); @@ -237,7 +237,7 @@ public void Zero_idle_buffer_should_not_extend_lifetime() cookie.Lifetime.IdleBuffer = TimeSpan.Zero; var options = Build( - GrantKind.Session, + SurrogateKind.SessionId, cookie); options.MaxAge.Should().Be(TimeSpan.FromMinutes(30)); @@ -262,9 +262,9 @@ public void Pure_opaque_session_should_use_idle_timeout() TimeSpan.FromDays(7); var options = _builder.Build( - CreateResponse(GrantKind.Session, cookie), + CreateResponse(SurrogateKind.SessionId, cookie), context, - GrantKind.Session); + SurrogateKind.SessionId); options.MaxAge.Should().Be(TimeSpan.FromMinutes(25)); } @@ -284,9 +284,9 @@ public void Hybrid_session_should_use_refresh_lifetime_when_longer() TimeSpan.FromDays(7); var options = _builder.Build( - CreateResponse(GrantKind.Session, cookie), + CreateResponse(SurrogateKind.SessionId, cookie), context, - GrantKind.Session); + SurrogateKind.SessionId); options.MaxAge.Should().Be( TimeSpan.FromDays(7) + TimeSpan.FromMinutes(5)); @@ -307,9 +307,9 @@ public void Hybrid_session_should_use_idle_timeout_when_longer() TimeSpan.FromHours(2); var options = _builder.Build( - CreateResponse(GrantKind.Session, cookie), + CreateResponse(SurrogateKind.SessionId, cookie), context, - GrantKind.Session); + SurrogateKind.SessionId); options.MaxAge.Should().Be( TimeSpan.FromHours(12) + TimeSpan.FromMinutes(5)); @@ -330,9 +330,9 @@ public void Non_hybrid_session_should_use_idle_timeout() TimeSpan.FromDays(1); var options = _builder.Build( - CreateResponse(GrantKind.Session, cookie), + CreateResponse(SurrogateKind.SessionId, cookie), context, - GrantKind.Session); + SurrogateKind.SessionId); options.MaxAge.Should().Be(TimeSpan.FromMinutes(20)); } @@ -352,9 +352,9 @@ public void Access_token_cookie_should_use_access_token_lifetime() TimeSpan.FromMinutes(15); var options = _builder.Build( - CreateResponse(GrantKind.AccessToken, cookie), + CreateResponse(SurrogateKind.AccessToken, cookie), context, - GrantKind.AccessToken); + SurrogateKind.AccessToken); options.MaxAge.Should().Be(TimeSpan.FromMinutes(20)); } @@ -370,9 +370,9 @@ public void Refresh_token_cookie_should_use_refresh_token_lifetime() TimeSpan.FromDays(14); var options = _builder.Build( - CreateResponse(GrantKind.RefreshToken, cookie), + CreateResponse(SurrogateKind.RefreshToken, cookie), context, - GrantKind.RefreshToken); + SurrogateKind.RefreshToken); options.MaxAge.Should().Be( TimeSpan.FromDays(14) + TimeSpan.FromMinutes(5)); @@ -386,7 +386,7 @@ public void Unknown_grant_kind_without_override_should_not_set_max_age() cookie.Lifetime.AbsoluteLifetimeOverride = null; var options = Build( - (GrantKind)999, + (SurrogateKind)999, cookie); options.MaxAge.Should().BeNull(); @@ -399,7 +399,7 @@ public void Unknown_grant_kind_should_still_support_explicit_max_age() cookie.MaxAge = TimeSpan.FromMinutes(10); var options = Build( - (GrantKind)999, + (SurrogateKind)999, cookie); options.MaxAge.Should().Be(TimeSpan.FromMinutes(15)); @@ -611,15 +611,15 @@ public void Build_should_reject_non_cookie_delivery() { var context = AuthFlowTestFactory.New(); - var delivery = new EffectiveGrantDelivery( - kind: GrantKind.Session, + var delivery = new EffectiveSurrogateTransport( + kind: SurrogateKind.SessionId, tokenFormat: TokenFormat.Opaque, - mode: GrantDeliveryMode.Header); + mode: SurrogateTransport.Header); var act = () => _builder.Build( delivery, context, - GrantKind.Session); + SurrogateKind.SessionId); act.Should() .Throw() @@ -631,16 +631,16 @@ public void Build_should_reject_mismatched_grant_kind() { var context = AuthFlowTestFactory.New(); - var delivery = new EffectiveGrantDelivery( - kind: GrantKind.RefreshToken, + var delivery = new EffectiveSurrogateTransport( + kind: SurrogateKind.RefreshToken, tokenFormat: TokenFormat.Opaque, - mode: GrantDeliveryMode.Cookie, + mode: SurrogateTransport.Cookie, cookie: CreateCookie()); var act = () => _builder.Build( delivery, context, - GrantKind.Session); + SurrogateKind.SessionId); act.Should() .Throw() @@ -651,17 +651,11 @@ public void Build_should_reject_mismatched_grant_kind() // HELPERS // --------------------------------------------------------- - private CookieOptions Build( - GrantKind kind, - UAuthCookieOptions cookie, - UAuthMode mode = UAuthMode.PureOpaque) + private CookieOptions Build(SurrogateKind kind, UAuthCookieOptions cookie, UAuthMode mode = UAuthMode.PureOpaque) { var context = AuthFlowTestFactory.New(mode: mode); - return _builder.Build( - CreateResponse(kind, cookie), - context, - kind); + return _builder.Build(CreateResponse(kind, cookie), context, kind); } private static UAuthCookieOptions CreateCookie() @@ -681,12 +675,12 @@ private static UAuthCookieOptions CreateCookie() }; } - private static EffectiveGrantDelivery CreateResponse(GrantKind kind, UAuthCookieOptions cookie) + private static EffectiveSurrogateTransport CreateResponse(SurrogateKind kind, UAuthCookieOptions cookie) { - return new EffectiveGrantDelivery( + return new EffectiveSurrogateTransport( kind: kind, tokenFormat: TokenFormat.Opaque, - mode: GrantDeliveryMode.Cookie, + mode: SurrogateTransport.Cookie, cookie: cookie); } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/CredentialInfrastructureTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/CredentialInfrastructureTests.cs index f119ce1b..526326bc 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/CredentialInfrastructureTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/CredentialInfrastructureTests.cs @@ -21,7 +21,7 @@ public void Header_builder_should_format_bearer_tokens( string expected) { var builder = new UAuthHeaderPolicyBuilder(); - var delivery = HeaderDelivery(HeaderTokenFormat.Bearer); + var delivery = HeaderDelivery(HeaderValueFormat.Bearer); builder.BuildHeaderValue(raw, delivery, null!) .Should().Be(expected); @@ -31,7 +31,7 @@ public void Header_builder_should_format_bearer_tokens( public void Header_builder_should_preserve_raw_tokens() { var builder = new UAuthHeaderPolicyBuilder(); - var delivery = HeaderDelivery(HeaderTokenFormat.Raw); + var delivery = HeaderDelivery(HeaderValueFormat.Raw); builder.BuildHeaderValue("raw-token", delivery, null!) .Should().Be("raw-token"); @@ -44,7 +44,7 @@ public void Header_builder_should_preserve_raw_tokens() public void Header_builder_should_reject_empty_values(string? value) { var builder = new UAuthHeaderPolicyBuilder(); - var delivery = HeaderDelivery(HeaderTokenFormat.Bearer); + var delivery = HeaderDelivery(HeaderValueFormat.Bearer); Action act = () => builder.BuildHeaderValue(value!, delivery, null!); @@ -59,7 +59,7 @@ public void Header_builder_should_reject_unsupported_format() { var builder = new UAuthHeaderPolicyBuilder(); - var delivery = HeaderDelivery((HeaderTokenFormat)999); + var delivery = HeaderDelivery((HeaderValueFormat)999); Action act = () => builder.BuildHeaderValue("token", delivery, null!); @@ -70,19 +70,19 @@ public void Header_builder_should_reject_unsupported_format() } [Theory] - [InlineData(GrantDeliveryMode.None)] - [InlineData(GrantDeliveryMode.Cookie)] - [InlineData(GrantDeliveryMode.Body)] + [InlineData(SurrogateTransport.None)] + [InlineData(SurrogateTransport.Cookie)] + [InlineData(SurrogateTransport.Body)] public void Header_builder_should_reject_non_header_delivery( - GrantDeliveryMode mode) + SurrogateTransport mode) { var builder = new UAuthHeaderPolicyBuilder(); - var delivery = new EffectiveGrantDelivery( - kind: GrantKind.AccessToken, + var delivery = new EffectiveSurrogateTransport( + kind: SurrogateKind.AccessToken, tokenFormat: TokenFormat.Jwt, mode: mode, - headerFormat: HeaderTokenFormat.Bearer); + headerFormat: HeaderValueFormat.Bearer); Action act = () => builder.BuildHeaderValue("token", delivery, null!); @@ -91,12 +91,12 @@ public void Header_builder_should_reject_non_header_delivery( .Throw(); } - private static EffectiveGrantDelivery HeaderDelivery(HeaderTokenFormat format) + private static EffectiveSurrogateTransport HeaderDelivery(HeaderValueFormat format) { - return new EffectiveGrantDelivery( - kind: GrantKind.AccessToken, + return new EffectiveSurrogateTransport( + kind: SurrogateKind.AccessToken, tokenFormat: TokenFormat.Jwt, - mode: GrantDeliveryMode.Header, + mode: SurrogateTransport.Header, name: "Authorization", headerFormat: format); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs index c913b09a..64b177ad 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/EffectiveServerOptionsProviderTests.cs @@ -165,11 +165,9 @@ public void PureOpaque_should_initialize_missing_optional_session_defaults() effective.Options.Session.MaxLifetime.Should().BeNull(); effective.Options.Session.DeviceMismatchBehavior.Should().Be(DeviceMismatchBehavior.Reject); - effective.Options.Cookie.Session.Lifetime.IdleBuffer - .Should().Be(TimeSpan.FromDays(2)); + effective.Options.Cookie.Session.Lifetime.IdleBuffer.Should().Be(TimeSpan.FromDays(2)); - effective.Options.GrantDelivery.RefreshToken.Mode - .Should().BeNull(); + effective.Options.Transport.RefreshToken.Mode.Should().BeNull(); } [Fact] @@ -215,14 +213,11 @@ public void Hybrid_should_apply_expected_defaults() options.Token.AccessTokenLifetime.Should().Be(TimeSpan.FromMinutes(10)); options.Token.RefreshTokenLifetime.Should().Be(TimeSpan.FromDays(7)); - options.Cookie.Session.Lifetime.IdleBuffer - .Should().Be(TimeSpan.FromMinutes(5)); + options.Cookie.Session.Lifetime.IdleBuffer.Should().Be(TimeSpan.FromMinutes(5)); - options.Cookie.RefreshToken.Lifetime.IdleBuffer - .Should().Be(TimeSpan.FromMinutes(5)); + options.Cookie.RefreshToken.Lifetime.IdleBuffer.Should().Be(TimeSpan.FromMinutes(5)); - options.GrantDelivery.RefreshToken.Mode - .Should().BeNull(); + options.Transport.RefreshToken.Mode.Should().BeNull(); } [Fact] diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/GrantCredentialReaderTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/GrantCredentialReaderTests.cs index 9a0ac369..2b1ea477 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/GrantCredentialReaderTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/GrantCredentialReaderTests.cs @@ -16,32 +16,32 @@ public sealed class GrantCredentialReaderTests private const string Token = "valid-token-value"; [Theory] - [InlineData(GrantKind.Session, "uas")] - [InlineData(GrantKind.AccessToken, "uat")] - [InlineData(GrantKind.RefreshToken, "uar")] - public void Read_WhenCookieIsConfigured_ShouldReadConfiguredCookie(GrantKind kind, string name) + [InlineData(SurrogateKind.SessionId, "uas")] + [InlineData(SurrogateKind.AccessToken, "uat")] + [InlineData(SurrogateKind.RefreshToken, "uar")] + public void Read_WhenCookieIsConfigured_ShouldReadConfiguredCookie(SurrogateKind kind, string name) { var context = new DefaultHttpContext(); context.Request.Headers.Cookie = $"{name}={Token}"; var delivery = CreateCookieDelivery(kind, name); - GrantCredentialReader.Read(context, delivery) + SurrogateReader.Read(context, delivery) .Should().Be(Token); } [Theory] - [InlineData(GrantKind.Session, "uas")] - [InlineData(GrantKind.AccessToken, "Authorization")] - [InlineData(GrantKind.RefreshToken, "uar")] - public void Read_WhenHeaderIsConfigured_ShouldReadConfiguredHeader(GrantKind kind, string name) + [InlineData(SurrogateKind.SessionId, "uas")] + [InlineData(SurrogateKind.AccessToken, "Authorization")] + [InlineData(SurrogateKind.RefreshToken, "uar")] + public void Read_WhenHeaderIsConfigured_ShouldReadConfiguredHeader(SurrogateKind kind, string name) { var context = new DefaultHttpContext(); context.Request.Headers[name] = $"Bearer {Token}"; var delivery = CreateHeaderDelivery(kind, name); - GrantCredentialReader.Read(context, delivery) + SurrogateReader.Read(context, delivery) .Should().Be(Token); } @@ -53,16 +53,16 @@ public void Read_ShouldUseRequestHeaderInsteadOfResponseHeader() context.Request.Headers["uat"] = "wrong-token"; context.Request.Headers.Authorization = $"Bearer {Token}"; - var delivery = new EffectiveGrantDelivery( - GrantKind.AccessToken, + var delivery = new EffectiveSurrogateTransport( + SurrogateKind.AccessToken, TokenFormat.Jwt, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: "uat", - headerFormat: HeaderTokenFormat.Raw, + headerFormat: HeaderValueFormat.Raw, requestHeaderName: "Authorization", - requestHeaderFormat: HeaderTokenFormat.Bearer); + requestHeaderFormat: HeaderValueFormat.Bearer); - GrantCredentialReader.Read(context, delivery) + SurrogateReader.Read(context, delivery) .Should().Be(Token); } @@ -72,16 +72,16 @@ public void Read_WhenRequestHeaderIsMissing_ShouldNotUseResponseHeader() var context = new DefaultHttpContext(); context.Request.Headers["uat"] = Token; - var delivery = new EffectiveGrantDelivery( - GrantKind.AccessToken, + var delivery = new EffectiveSurrogateTransport( + SurrogateKind.AccessToken, TokenFormat.Jwt, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: "uat", - headerFormat: HeaderTokenFormat.Raw, + headerFormat: HeaderValueFormat.Raw, requestHeaderName: "Authorization", - requestHeaderFormat: HeaderTokenFormat.Bearer); + requestHeaderFormat: HeaderValueFormat.Bearer); - GrantCredentialReader.Read(context, delivery) + SurrogateReader.Read(context, delivery) .Should().BeNull(); } @@ -94,9 +94,9 @@ public void Read_WhenCookieIsConfigured_ShouldIgnoreHeader() context.Request.Headers.Authorization = "Bearer wrong-token"; var delivery = CreateCookieDelivery( - GrantKind.Session, "uas"); + SurrogateKind.SessionId, "uas"); - GrantCredentialReader.Read(context, delivery) + SurrogateReader.Read(context, delivery) .Should().Be(Token); } @@ -109,9 +109,9 @@ public void Read_WhenHeaderIsConfigured_ShouldIgnoreCookie() context.Request.Headers.Authorization = $"Bearer {Token}"; var delivery = CreateHeaderDelivery( - GrantKind.Session, "Authorization"); + SurrogateKind.SessionId, "Authorization"); - GrantCredentialReader.Read(context, delivery) + SurrogateReader.Read(context, delivery) .Should().Be(Token); } @@ -124,9 +124,9 @@ public void Read_WhenCookieIsMissing_ShouldNotFallbackToHeader() context.Request.Headers["uas"] = Token; var delivery = CreateCookieDelivery( - GrantKind.Session, "uas"); + SurrogateKind.SessionId, "uas"); - GrantCredentialReader.Read(context, delivery) + SurrogateReader.Read(context, delivery) .Should().BeNull(); } @@ -137,9 +137,9 @@ public void Read_WhenHeaderIsMissing_ShouldNotFallbackToCookie() context.Request.Headers.Cookie = $"uas={Token}"; var delivery = CreateHeaderDelivery( - GrantKind.Session, "Authorization"); + SurrogateKind.SessionId, "Authorization"); - GrantCredentialReader.Read(context, delivery) + SurrogateReader.Read(context, delivery) .Should().BeNull(); } @@ -152,9 +152,9 @@ public void Read_WhenHeaderIsMalformed_ShouldNotFallbackToCookie() context.Request.Headers.Cookie = $"uas={Token}"; var delivery = CreateHeaderDelivery( - GrantKind.Session, "Authorization"); + SurrogateKind.SessionId, "Authorization"); - GrantCredentialReader.Read(context, delivery) + SurrogateReader.Read(context, delivery) .Should().BeNull(); } @@ -163,16 +163,15 @@ public void Read_WhenHeaderIsMalformed_ShouldNotFallbackToCookie() [InlineData("bearer valid-token-value")] [InlineData("BEARER valid-token-value")] [InlineData(" Bearer valid-token-value ")] - public void ReadHeader_WhenBearerIsValid_ShouldReturnToken( - string value) + public void ReadHeader_WhenBearerIsValid_ShouldReturnToken(string value) { var context = new DefaultHttpContext(); context.Request.Headers.Authorization = value; - GrantCredentialReader.ReadHeader( + SurrogateReader.ReadHeader( context, "Authorization", - HeaderTokenFormat.Bearer) + HeaderValueFormat.Bearer) .Should().Be(Token); } @@ -187,32 +186,30 @@ public void ReadHeader_WhenBearerIsValid_ShouldReturnToken( [InlineData("Bearer token\tvalue")] [InlineData("Bearer token,value")] [InlineData("Bearer token1, Bearer token2")] - public void ReadHeader_WhenBearerIsMalformed_ShouldReturnNull( - string value) + public void ReadHeader_WhenBearerIsMalformed_ShouldReturnNull(string value) { var context = new DefaultHttpContext(); context.Request.Headers.Authorization = value; - GrantCredentialReader.ReadHeader( + SurrogateReader.ReadHeader( context, "Authorization", - HeaderTokenFormat.Bearer) + HeaderValueFormat.Bearer) .Should().BeNull(); } [Theory] [InlineData("valid-token-value")] [InlineData(" valid-token-value ")] - public void ReadHeader_WhenRawIsConfigured_ShouldReturnToken( - string value) + public void ReadHeader_WhenRawIsConfigured_ShouldReturnToken(string value) { var context = new DefaultHttpContext(); context.Request.Headers["uat"] = value; - GrantCredentialReader.ReadHeader( + SurrogateReader.ReadHeader( context, "uat", - HeaderTokenFormat.Raw) + HeaderValueFormat.Raw) .Should().Be(Token); } @@ -229,10 +226,10 @@ public void ReadHeader_WhenRawIsMalformed_ShouldReturnNull( var context = new DefaultHttpContext(); context.Request.Headers["uat"] = value; - GrantCredentialReader.ReadHeader( + SurrogateReader.ReadHeader( context, "uat", - HeaderTokenFormat.Raw) + HeaderValueFormat.Raw) .Should().BeNull(); } @@ -249,10 +246,10 @@ public void ReadHeader_WhenMultipleValuesExist_ShouldReturnNull( context.Request.Headers.Authorization = new StringValues(new[] { first, second }); - GrantCredentialReader.ReadHeader( + SurrogateReader.ReadHeader( context, "Authorization", - HeaderTokenFormat.Bearer) + HeaderValueFormat.Bearer) .Should().BeNull(); } @@ -264,10 +261,10 @@ public void ReadHeader_WhenMultipleRawValuesExist_ShouldReturnNull() context.Request.Headers["uat"] = new StringValues(new[] { "token1", "token2" }); - GrantCredentialReader.ReadHeader( + SurrogateReader.ReadHeader( context, "uat", - HeaderTokenFormat.Raw) + HeaderValueFormat.Raw) .Should().BeNull(); } @@ -280,10 +277,10 @@ public void ReadHeader_WhenNameIsInvalid_ShouldReturnNull( { var context = new DefaultHttpContext(); - GrantCredentialReader.ReadHeader( + SurrogateReader.ReadHeader( context, name, - HeaderTokenFormat.Bearer) + HeaderValueFormat.Bearer) .Should().BeNull(); } @@ -293,10 +290,10 @@ public void ReadHeader_WhenFormatIsUnsupported_ShouldReturnNull() var context = new DefaultHttpContext(); context.Request.Headers.Authorization = $"Bearer {Token}"; - GrantCredentialReader.ReadHeader( + SurrogateReader.ReadHeader( context, "Authorization", - (HeaderTokenFormat)999) + (HeaderValueFormat)999) .Should().BeNull(); } @@ -306,7 +303,7 @@ public void ReadCookie_WhenCookieIsMissing_ShouldReturnNull() var context = new DefaultHttpContext(); context.Request.Headers.Cookie = "other-cookie=other-value"; - GrantCredentialReader.ReadCookie(context, "uas") + SurrogateReader.ReadCookie(context, "uas") .Should().BeNull(); } @@ -319,7 +316,7 @@ public void ReadCookie_WhenNameIsInvalid_ShouldReturnNull( { var context = new DefaultHttpContext(); - GrantCredentialReader.ReadCookie(context, name) + SurrogateReader.ReadCookie(context, name) .Should().BeNull(); } @@ -329,7 +326,7 @@ public void ReadCookie_WhenCookieIsEmpty_ShouldReturnNull() var context = new DefaultHttpContext(); context.Request.Headers.Cookie = "uas="; - GrantCredentialReader.ReadCookie(context, "uas") + SurrogateReader.ReadCookie(context, "uas") .Should().BeNull(); } @@ -341,16 +338,15 @@ public void ReadCookie_ShouldIgnoreUnrelatedCookies() context.Request.Headers.Cookie = $"other=other-value; uas={Token}; uar=refresh-token"; - GrantCredentialReader.ReadCookie(context, "uas") + SurrogateReader.ReadCookie(context, "uas") .Should().Be(Token); } [Theory] - [InlineData(GrantKind.Session)] - [InlineData(GrantKind.AccessToken)] - [InlineData(GrantKind.RefreshToken)] - public void Read_WhenDeliveryIsDisabled_ShouldReturnNull( - GrantKind kind) + [InlineData(SurrogateKind.SessionId)] + [InlineData(SurrogateKind.AccessToken)] + [InlineData(SurrogateKind.RefreshToken)] + public void Read_WhenDeliveryIsDisabled_ShouldReturnNull(SurrogateKind kind) { var context = new DefaultHttpContext(); @@ -359,9 +355,9 @@ public void Read_WhenDeliveryIsDisabled_ShouldReturnNull( context.Request.Headers.Authorization = $"Bearer {Token}"; - GrantCredentialReader.Read( + SurrogateReader.Read( context, - EffectiveGrantDelivery.Disabled(kind)) + EffectiveSurrogateTransport.Disabled(kind)) .Should().BeNull(); } @@ -373,14 +369,14 @@ public void Read_ShouldNeverResolveCredentialFromQueryString() context.Request.QueryString = new QueryString( $"?uas={Token}&sessionId={Token}&uat={Token}"); - GrantCredentialReader.Read( + SurrogateReader.Read( context, - CreateCookieDelivery(GrantKind.Session, "uas")) + CreateCookieDelivery(SurrogateKind.SessionId, "uas")) .Should().BeNull(); - GrantCredentialReader.Read( + SurrogateReader.Read( context, - CreateHeaderDelivery(GrantKind.Session, "uas")) + CreateHeaderDelivery(SurrogateKind.SessionId, "uas")) .Should().BeNull(); } @@ -391,13 +387,12 @@ public void Read_ShouldNeverResolveCredentialFromQueryString() [InlineData("uas=; uas=token2")] [InlineData("uas=token1; UAS=token2")] [InlineData("other=value; uas=token1; uas=token2")] - public void ReadCookie_WhenDuplicateCredentialsExist_ShouldReturnNull( - string cookieHeader) + public void ReadCookie_WhenDuplicateCredentialsExist_ShouldReturnNull(string cookieHeader) { var context = new DefaultHttpContext(); context.Request.Headers.Cookie = cookieHeader; - GrantCredentialReader.ReadCookie(context, "uas") + SurrogateReader.ReadCookie(context, "uas") .Should().BeNull(); } @@ -413,7 +408,7 @@ public void ReadCookie_WhenDuplicateCredentialsExistAcrossHeaders_ShouldReturnNu "uas=token2" }); - GrantCredentialReader.ReadCookie(context, "uas") + SurrogateReader.ReadCookie(context, "uas") .Should().BeNull(); } @@ -425,7 +420,7 @@ public void ReadCookie_WhenUnrelatedCookieIsDuplicated_ShouldResolveCredential() context.Request.Headers.Cookie = "other=value1; uas=valid-token; other=value2"; - GrantCredentialReader.ReadCookie(context, "uas") + SurrogateReader.ReadCookie(context, "uas") .Should().Be("valid-token"); } @@ -437,30 +432,30 @@ public void ReadCookie_WhenSimilarCookieNamesExist_ShouldResolveCredential() context.Request.Headers.Cookie = "uas=valid-token; uas-other=other-token"; - GrantCredentialReader.ReadCookie(context, "uas") + SurrogateReader.ReadCookie(context, "uas") .Should().Be("valid-token"); } - private static EffectiveGrantDelivery CreateCookieDelivery(GrantKind kind, string name) + private static EffectiveSurrogateTransport CreateCookieDelivery(SurrogateKind kind, string name) { - return new EffectiveGrantDelivery( + return new EffectiveSurrogateTransport( kind, TokenFormat.Opaque, - GrantDeliveryMode.Cookie, + SurrogateTransport.Cookie, cookie: new UAuthCookieOptions { Name = name }); } - private static EffectiveGrantDelivery CreateHeaderDelivery(GrantKind kind, string name) + private static EffectiveSurrogateTransport CreateHeaderDelivery(SurrogateKind kind, string name) { - return new EffectiveGrantDelivery( + return new EffectiveSurrogateTransport( kind, TokenFormat.Opaque, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: name, - headerFormat: HeaderTokenFormat.Bearer); + headerFormat: HeaderValueFormat.Bearer); } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/JwtLogoutServiceTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/JwtLogoutServiceTests.cs index 0f9e73b4..6bed1c72 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/JwtLogoutServiceTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/JwtLogoutServiceTests.cs @@ -117,7 +117,7 @@ private void SetupLineage(SessionValidationResult result) _lineageValidator .Setup(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, Ct)) .ReturnsAsync(result); } @@ -576,11 +576,11 @@ public async Task SemiHybrid_ShouldReturnSessionIssuerResult( _lineageValidator .Setup(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, Ct)) .Callback< SessionValidationContext, - SessionCredentialPurpose, + SessionIdPurpose, CancellationToken>( (context, _, _) => captured = context) .ReturnsAsync(lineage); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/LoginEndpointHandlerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/LoginEndpointHandlerTests.cs index 7a26ae18..b9f3aefc 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/LoginEndpointHandlerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/LoginEndpointHandlerTests.cs @@ -732,20 +732,20 @@ public async Task LoginAsync_WhenIdentifierResolvesToDifferentUser_DoesNotSuppre [InlineData(true)] public async Task LoginAsync_HeaderDeliveryWithoutFetch_ReturnsBadRequest(bool sessionHeader) { - var headerDelivery = new EffectiveGrantDelivery( - sessionHeader ? GrantKind.Session : GrantKind.AccessToken, + var headerDelivery = new EffectiveSurrogateTransport( + sessionHeader ? SurrogateKind.SessionId : SurrogateKind.AccessToken, sessionHeader ? TokenFormat.Opaque : TokenFormat.Jwt, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: sessionHeader ? "uas" : "uat"); var response = new EffectiveAuthResponse( sessionHeader ? headerDelivery - : EffectiveGrantDelivery.Disabled(GrantKind.Session), + : EffectiveSurrogateTransport.Disabled(SurrogateKind.SessionId), sessionHeader - ? EffectiveGrantDelivery.Disabled(GrantKind.AccessToken) + ? EffectiveSurrogateTransport.Disabled(SurrogateKind.AccessToken) : headerDelivery, - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), EffectiveRedirectResponse.Disabled); var fixture = CreateFixture( @@ -830,7 +830,7 @@ public async Task LoginAsync_SuccessfulFetch_ReturnsRedirectInBody() fixture.CredentialWriter.Setup(x => x.Write( fixture.HttpContext, - GrantKind.Session, + SurrogateKind.SessionId, sessionId)); fixture.RedirectResolver.Setup(x => x.ResolveSuccess( @@ -851,7 +851,7 @@ public async Task LoginAsync_SuccessfulFetch_ReturnsRedirectInBody() fixture.CredentialWriter.Verify(x => x.Write( fixture.HttpContext, - GrantKind.Session, + SurrogateKind.SessionId, sessionId), Times.Once); } @@ -867,7 +867,7 @@ private static Fixture CreateFixture(AuthFlowContext? flow = null) var internalFlow = new Mock(MockBehavior.Strict); - var credentialWriter = new Mock(MockBehavior.Strict); + var credentialWriter = new Mock(MockBehavior.Strict); var redirectResolver = new Mock(MockBehavior.Loose); @@ -968,7 +968,7 @@ private sealed record Fixture( LoginEndpointHandler Sut, AuthFlowContext Flow, Mock InternalFlow, - Mock CredentialWriter, + Mock CredentialWriter, Mock RedirectResolver, Mock AuthStore, Mock IdentifierResolver, diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/LogoutEndpointHandlerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/LogoutEndpointHandlerTests.cs index cab1d97c..7b1009a0 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/LogoutEndpointHandlerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/LogoutEndpointHandlerTests.cs @@ -813,7 +813,6 @@ private static AuthFlowContext CreateFlowWithSession( session: session, options: source.Options, response: source.Response, - primaryTokenKind: source.PrimaryTokenKind, returnUrlInfo: source.ReturnUrlInfo ); } @@ -833,7 +832,6 @@ private static AuthFlowContext CreateUnauthenticatedFlow() session: null, options: source.Options, response: source.Response, - primaryTokenKind: source.PrimaryTokenKind, returnUrlInfo: source.ReturnUrlInfo ); } @@ -876,7 +874,6 @@ private static AuthFlowContext CreatePureJwtFlow() session: null, options: source.Options, response: source.Response, - primaryTokenKind: source.PrimaryTokenKind, returnUrlInfo: source.ReturnUrlInfo); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/PkceEndpointHandlerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/PkceEndpointHandlerTests.cs index 6025cc6e..cb8e9f50 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/PkceEndpointHandlerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/PkceEndpointHandlerTests.cs @@ -648,7 +648,7 @@ public async Task CompleteAsync_WhenSuccessfulAndRedirectDisabled_ReturnsOk() fixture.CredentialWriter .Setup(x => x.Write( fixture.HttpContext, - GrantKind.Session, + SurrogateKind.SessionId, sessionId)); fixture.RedirectResolver @@ -664,7 +664,7 @@ public async Task CompleteAsync_WhenSuccessfulAndRedirectDisabled_ReturnsOk() fixture.CredentialWriter.Verify(x => x.Write( fixture.HttpContext, - GrantKind.Session, + SurrogateKind.SessionId, sessionId), Times.Once); } @@ -692,7 +692,7 @@ public async Task CompleteAsync_WhenSuccessfulAndRedirectEnabled_ReturnsRedirect fixture.CredentialWriter .Setup(x => x.Write( fixture.HttpContext, - GrantKind.Session, + SurrogateKind.SessionId, sessionId)); fixture.RedirectResolver @@ -783,13 +783,13 @@ public async Task CompleteAsync_WhenDeviceLimitExceeded_PreservesHubFromForm() public async Task CompleteAsync_HeaderDeliveryWithoutFetch_ReturnsBadRequest() { var response = new EffectiveAuthResponse( - EffectiveGrantDelivery.Disabled(GrantKind.Session), - new EffectiveGrantDelivery( - GrantKind.AccessToken, + EffectiveSurrogateTransport.Disabled(SurrogateKind.SessionId), + new EffectiveSurrogateTransport( + SurrogateKind.AccessToken, TokenFormat.Jwt, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: "uat"), - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), EffectiveRedirectResponse.Disabled); var fixture = CreateFixture( @@ -882,7 +882,7 @@ public async Task CompleteAsync_SuccessfulFetch_ReturnsRedirectInBody() fixture.CredentialWriter.Setup(x => x.Write( fixture.HttpContext, - GrantKind.Session, + SurrogateKind.SessionId, sessionId)); fixture.RedirectResolver.Setup(x => x.ResolveSuccess( @@ -904,7 +904,7 @@ public async Task CompleteAsync_SuccessfulFetch_ReturnsRedirectInBody() fixture.CredentialWriter.Verify(x => x.Write( fixture.HttpContext, - GrantKind.Session, + SurrogateKind.SessionId, sessionId), Times.Once); } @@ -939,7 +939,7 @@ private static Fixture CreateFixture( new Mock(MockBehavior.Strict); var credentialWriter = - new Mock(MockBehavior.Strict); + new Mock(MockBehavior.Strict); var redirectResolver = new Mock(MockBehavior.Strict); @@ -1040,7 +1040,6 @@ private static AuthFlowContext CreateNonLoginFlow() session: source.Session, options: source.Options, response: source.Response, - primaryTokenKind: source.PrimaryTokenKind, returnUrlInfo: source.ReturnUrlInfo); } @@ -1051,7 +1050,7 @@ private sealed record Fixture( Mock InternalFlow, Mock AuthStore, Mock Validator, - Mock CredentialWriter, + Mock CredentialWriter, Mock RedirectResolver, DefaultHttpContext HttpContext); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshFlowServiceTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshFlowServiceTests.cs index 5a81fd48..cedb048b 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshFlowServiceTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshFlowServiceTests.cs @@ -521,11 +521,10 @@ private static AuthFlowContext CreateFlow(UAuthMode mode) session: null, options: effective.Options, response: new EffectiveAuthResponse( - sessionIdDelivery: EffectiveGrantDelivery.Disabled(GrantKind.Session), - accessTokenDelivery: EffectiveGrantDelivery.Disabled(GrantKind.AccessToken), - refreshTokenDelivery: EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + sessionIdTransport: EffectiveSurrogateTransport.Disabled(SurrogateKind.SessionId), + accessTokenTransport: EffectiveSurrogateTransport.Disabled(SurrogateKind.AccessToken), + refreshTokenTransport: EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), redirect: EffectiveRedirectResponse.Disabled), - primaryTokenKind: PrimaryTokenKind.AccessToken, returnUrlInfo: ReturnUrlInfo.None()); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshTokenResolverTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshTokenResolverTests.cs index d835baff..471700f1 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshTokenResolverTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshTokenResolverTests.cs @@ -49,9 +49,9 @@ public void Resolve_WhenCookieIsConfigured_ShouldResolveRefreshCookie(UAuthMode } [Theory] - [InlineData(HeaderTokenFormat.Bearer, "Bearer valid-refresh-token")] - [InlineData(HeaderTokenFormat.Raw, "valid-refresh-token")] - public void Resolve_WhenHeaderIsConfigured_ShouldResolveRefreshHeader(HeaderTokenFormat format, string headerValue) + [InlineData(HeaderValueFormat.Bearer, "Bearer valid-refresh-token")] + [InlineData(HeaderValueFormat.Raw, "valid-refresh-token")] + public void Resolve_WhenHeaderIsConfigured_ShouldResolveRefreshHeader(HeaderValueFormat format, string headerValue) { var context = new DefaultHttpContext(); @@ -209,7 +209,7 @@ public void Resolve_WhenRefreshDeliveryIsDisabled_ShouldReturnNull() $"Bearer {RefreshToken}"; var sut = CreateSut( - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), UAuthMode.PureOpaque); sut.Resolve(context).Should().BeNull(); @@ -232,11 +232,11 @@ public void Resolve_ShouldNeverUseQueryString() .Should().BeNull(); } - private static RefreshTokenResolver CreateSut(EffectiveGrantDelivery refreshDelivery, UAuthMode mode = UAuthMode.Hybrid) + private static RefreshTokenResolver CreateSut(EffectiveSurrogateTransport refreshDelivery, UAuthMode mode = UAuthMode.Hybrid) { var response = new EffectiveAuthResponse( - EffectiveGrantDelivery.Disabled(GrantKind.Session), - EffectiveGrantDelivery.Disabled(GrantKind.AccessToken), + EffectiveSurrogateTransport.Disabled(SurrogateKind.SessionId), + EffectiveSurrogateTransport.Disabled(SurrogateKind.AccessToken), refreshDelivery, EffectiveRedirectResponse.Disabled); @@ -253,24 +253,24 @@ private static RefreshTokenResolver CreateSut(EffectiveGrantDelivery refreshDeli return new RefreshTokenResolver(accessor.Object); } - private static EffectiveGrantDelivery CreateCookieDelivery(string name = "uar") + private static EffectiveSurrogateTransport CreateCookieDelivery(string name = "uar") { - return new EffectiveGrantDelivery( - GrantKind.RefreshToken, + return new EffectiveSurrogateTransport( + SurrogateKind.RefreshToken, TokenFormat.Opaque, - GrantDeliveryMode.Cookie, + SurrogateTransport.Cookie, cookie: new UAuthCookieOptions { Name = name }); } - private static EffectiveGrantDelivery CreateHeaderDelivery(string name = "uar", HeaderTokenFormat format = HeaderTokenFormat.Bearer) + private static EffectiveSurrogateTransport CreateHeaderDelivery(string name = "uar", HeaderValueFormat format = HeaderValueFormat.Bearer) { - return new EffectiveGrantDelivery( - GrantKind.RefreshToken, + return new EffectiveSurrogateTransport( + SurrogateKind.RefreshToken, TokenFormat.Opaque, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: name, headerFormat: format); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshTokenRotationServiceTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshTokenRotationServiceTests.cs index cba42849..8edac14b 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshTokenRotationServiceTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/RefreshTokenRotationServiceTests.cs @@ -570,11 +570,10 @@ public Fixture(UAuthMode mode, TenantKey? tenant = null, bool multiTenant = fals session: null, options: options, response: new EffectiveAuthResponse( - sessionIdDelivery: EffectiveGrantDelivery.Disabled(GrantKind.Session), - accessTokenDelivery: EffectiveGrantDelivery.Disabled(GrantKind.AccessToken), - refreshTokenDelivery: EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + sessionIdTransport: EffectiveSurrogateTransport.Disabled(SurrogateKind.SessionId), + accessTokenTransport: EffectiveSurrogateTransport.Disabled(SurrogateKind.AccessToken), + refreshTokenTransport: EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), redirect: EffectiveRedirectResponse.Disabled), - primaryTokenKind: PrimaryTokenKind.AccessToken, returnUrlInfo: ReturnUrlInfo.None()); StoreFactory.Setup(x => x.Create(Tenant)).Returns(Store.Object); @@ -636,7 +635,7 @@ token.SessionId is AuthSessionId sessionId && It.Is(c => c.Tenant == Tenant && c.SessionId == sessionId), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, It.IsAny())) .ReturnsAsync(SessionValidationResult.Active( Tenant, diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SemiHybridAuthorityValidatorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SemiHybridAuthorityValidatorTests.cs index ef5164f0..c95eb450 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SemiHybridAuthorityValidatorTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SemiHybridAuthorityValidatorTests.cs @@ -35,10 +35,10 @@ public async Task ValidateAsync_ValidPrincipal_ShouldValidateMetadataLineage() fixture.Lineage .Setup(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken)) .Callback((context, _, _) => { captured = context; @@ -59,7 +59,7 @@ public async Task ValidateAsync_ValidPrincipal_ShouldValidateMetadataLineage() fixture.Lineage.Verify(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken), Times.Once); fixture.Lineage.VerifyNoOtherCalls(); @@ -214,7 +214,7 @@ public async Task ValidateAsync_AllowPolicy_ShouldAcceptMissingOrDifferentDevice It.Is(c => c.Device == device && c.SessionOptions == fixture.Options), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken)) .ReturnsAsync(expected); @@ -228,7 +228,7 @@ public async Task ValidateAsync_AllowPolicy_ShouldAcceptMissingOrDifferentDevice fixture.Lineage.Verify(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken), Times.Once); } @@ -340,7 +340,7 @@ public async Task ValidateAsync_SameRequest_ShouldCacheResult( fixture.Lineage.Verify(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken), Times.Once); } @@ -360,7 +360,7 @@ await ValidateAsync(fixture with fixture.Lineage.Verify(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken), Times.Exactly(2)); } @@ -376,7 +376,7 @@ public async Task ValidateAsync_ConcurrentCalls_ShouldShareInFlightTask() fixture.Lineage .Setup(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken)) .Returns(completion.Task); @@ -391,7 +391,7 @@ public async Task ValidateAsync_ConcurrentCalls_ShouldShareInFlightTask() fixture.Lineage.Verify(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken), Times.Once); } @@ -458,7 +458,7 @@ private static void SetupLineage( fixture.Lineage .Setup(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken)) .ReturnsAsync(result); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SessionEndpointHandlerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SessionEndpointHandlerTests.cs index 1eea4a3d..59eb1f34 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SessionEndpointHandlerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SessionEndpointHandlerTests.cs @@ -679,7 +679,6 @@ private static AuthFlowContext CreateUnauthenticatedFlow() session: null, options: authenticated.Options, response: authenticated.Response, - primaryTokenKind: authenticated.PrimaryTokenKind, returnUrlInfo: authenticated.ReturnUrlInfo); } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/CredentialResponseWriterTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SurrogateResponseWriterTests.cs similarity index 70% rename from tests/CodeBeam.UltimateAuth.Tests.Unit/Server/CredentialResponseWriterTests.cs rename to tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SurrogateResponseWriterTests.cs index 3f8f50d2..aa4fe84a 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/CredentialResponseWriterTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SurrogateResponseWriterTests.cs @@ -1,7 +1,6 @@ using AwesomeAssertions; using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; -using CodeBeam.UltimateAuth.Core.Options; using CodeBeam.UltimateAuth.Server.Auth; using CodeBeam.UltimateAuth.Server.Domain; using CodeBeam.UltimateAuth.Server.Infrastructure; @@ -11,13 +10,13 @@ namespace CodeBeam.UltimateAuth.Tests.Unit; -public class CredentialResponseWriterTests +public class SurrogateResponseWriterTests { [Theory] - [InlineData(GrantKind.Session)] - [InlineData(GrantKind.AccessToken)] - [InlineData(GrantKind.RefreshToken)] - public void None_delivery_should_not_write_credentials(GrantKind kind) + [InlineData(SurrogateKind.SessionId)] + [InlineData(SurrogateKind.AccessToken)] + [InlineData(SurrogateKind.RefreshToken)] + public void None_delivery_should_not_write_credentials(SurrogateKind kind) { var setup = CreateWriter(CreateResponse()); var context = TestHttpContext.Create(); @@ -30,17 +29,17 @@ public void None_delivery_should_not_write_credentials(GrantKind kind) } [Theory] - [InlineData(GrantKind.Session)] - [InlineData(GrantKind.AccessToken)] - [InlineData(GrantKind.RefreshToken)] - public void Header_delivery_should_write_correct_grant(GrantKind kind) + [InlineData(SurrogateKind.SessionId)] + [InlineData(SurrogateKind.AccessToken)] + [InlineData(SurrogateKind.RefreshToken)] + public void Header_delivery_should_write_correct_grant(SurrogateKind kind) { - var delivery = new EffectiveGrantDelivery( + var delivery = new EffectiveSurrogateTransport( kind, TokenFormat.Opaque, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: "Authorization", - headerFormat: HeaderTokenFormat.Bearer); + headerFormat: HeaderValueFormat.Bearer); var setup = CreateWriter(CreateResponse(kind, delivery)); var context = TestHttpContext.Create(); @@ -57,21 +56,21 @@ public void Header_delivery_should_write_correct_grant(GrantKind kind) [Fact] public void Raw_header_delivery_should_not_add_bearer_prefix() { - var delivery = new EffectiveGrantDelivery( - GrantKind.AccessToken, + var delivery = new EffectiveSurrogateTransport( + SurrogateKind.AccessToken, TokenFormat.Jwt, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: "Authorization", - headerFormat: HeaderTokenFormat.Raw); + headerFormat: HeaderValueFormat.Raw); var setup = CreateWriter( - CreateResponse(GrantKind.AccessToken, delivery)); + CreateResponse(SurrogateKind.AccessToken, delivery)); var context = TestHttpContext.Create(); setup.Writer.WriteInternal( context, - GrantKind.AccessToken, + SurrogateKind.AccessToken, "raw-token"); context.Response.Headers.Authorization.ToString() @@ -81,21 +80,21 @@ public void Raw_header_delivery_should_not_add_bearer_prefix() [Fact] public void Header_delivery_should_support_custom_header_name() { - var delivery = new EffectiveGrantDelivery( - GrantKind.AccessToken, + var delivery = new EffectiveSurrogateTransport( + SurrogateKind.AccessToken, TokenFormat.Jwt, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: "X-UAuth-Token", - headerFormat: HeaderTokenFormat.Raw); + headerFormat: HeaderValueFormat.Raw); var setup = CreateWriter( - CreateResponse(GrantKind.AccessToken, delivery)); + CreateResponse(SurrogateKind.AccessToken, delivery)); var context = TestHttpContext.Create(); setup.Writer.WriteInternal( context, - GrantKind.AccessToken, + SurrogateKind.AccessToken, "custom-token"); context.Response.Headers["X-UAuth-Token"].ToString() @@ -108,22 +107,22 @@ public void Header_delivery_should_support_custom_header_name() [Fact] public void Header_delivery_should_replace_existing_header() { - var delivery = new EffectiveGrantDelivery( - GrantKind.AccessToken, + var delivery = new EffectiveSurrogateTransport( + SurrogateKind.AccessToken, TokenFormat.Jwt, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: "Authorization", - headerFormat: HeaderTokenFormat.Bearer); + headerFormat: HeaderValueFormat.Bearer); var setup = CreateWriter( - CreateResponse(GrantKind.AccessToken, delivery)); + CreateResponse(SurrogateKind.AccessToken, delivery)); var context = TestHttpContext.Create(); context.Response.Headers.Authorization = "Bearer old-token"; setup.Writer.WriteInternal( context, - GrantKind.AccessToken, + SurrogateKind.AccessToken, "new-token"); context.Response.Headers.Authorization.ToString() @@ -131,21 +130,20 @@ public void Header_delivery_should_replace_existing_header() } [Theory] - [InlineData(GrantKind.Session)] - [InlineData(GrantKind.AccessToken)] - [InlineData(GrantKind.RefreshToken)] - public void Cookie_delivery_should_write_correct_credential( - GrantKind kind) + [InlineData(SurrogateKind.SessionId)] + [InlineData(SurrogateKind.AccessToken)] + [InlineData(SurrogateKind.RefreshToken)] + public void Cookie_delivery_should_write_correct_credential(SurrogateKind kind) { var cookie = new UAuthCookieOptions { Name = "uauth-credential" }; - var delivery = new EffectiveGrantDelivery( + var delivery = new EffectiveSurrogateTransport( kind, TokenFormat.Opaque, - GrantDeliveryMode.Cookie, + SurrogateTransport.Cookie, cookie: cookie); var setup = CreateWriter(CreateResponse(kind, delivery)); @@ -168,16 +166,15 @@ public void Cookie_delivery_should_write_correct_credential( } [Theory] - [InlineData(GrantKind.Session)] - [InlineData(GrantKind.AccessToken)] - [InlineData(GrantKind.RefreshToken)] - public void Cookie_delivery_without_options_should_throw( - GrantKind kind) + [InlineData(SurrogateKind.SessionId)] + [InlineData(SurrogateKind.AccessToken)] + [InlineData(SurrogateKind.RefreshToken)] + public void Cookie_delivery_without_options_should_throw(SurrogateKind kind) { - var delivery = new EffectiveGrantDelivery( + var delivery = new EffectiveSurrogateTransport( kind, TokenFormat.Opaque, - GrantDeliveryMode.Cookie); + SurrogateTransport.Cookie); var setup = CreateWriter(CreateResponse(kind, delivery)); var context = TestHttpContext.Create(); @@ -194,16 +191,15 @@ public void Cookie_delivery_without_options_should_throw( } [Theory] - [InlineData(GrantKind.Session)] - [InlineData(GrantKind.AccessToken)] - [InlineData(GrantKind.RefreshToken)] - public void Body_delivery_should_throw_not_supported( - GrantKind kind) + [InlineData(SurrogateKind.SessionId)] + [InlineData(SurrogateKind.AccessToken)] + [InlineData(SurrogateKind.RefreshToken)] + public void Body_delivery_should_throw_not_supported(SurrogateKind kind) { - var delivery = new EffectiveGrantDelivery( + var delivery = new EffectiveSurrogateTransport( kind, TokenFormat.Opaque, - GrantDeliveryMode.Body); + SurrogateTransport.Body); var setup = CreateWriter(CreateResponse(kind, delivery)); var context = TestHttpContext.Create(); @@ -227,7 +223,7 @@ public void Unsupported_grant_kind_should_throw() Action act = () => setup.Writer.WriteInternal( context, - (GrantKind)999, + (SurrogateKind)999, "token"); act.Should() @@ -238,22 +234,22 @@ public void Unsupported_grant_kind_should_throw() [Fact] public void Header_policy_failure_should_propagate() { - var delivery = new EffectiveGrantDelivery( - GrantKind.AccessToken, + var delivery = new EffectiveSurrogateTransport( + SurrogateKind.AccessToken, TokenFormat.Jwt, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: "Authorization", - headerFormat: (HeaderTokenFormat)999); + headerFormat: (HeaderValueFormat)999); var setup = CreateWriter( - CreateResponse(GrantKind.AccessToken, delivery)); + CreateResponse(SurrogateKind.AccessToken, delivery)); var context = TestHttpContext.Create(); Action act = () => setup.Writer.WriteInternal( context, - GrantKind.AccessToken, + SurrogateKind.AccessToken, "token"); act.Should() @@ -267,21 +263,21 @@ public void Header_policy_failure_should_propagate() [Fact] public void Mismatched_grant_kind_should_throw() { - var delivery = new EffectiveGrantDelivery( - GrantKind.RefreshToken, + var delivery = new EffectiveSurrogateTransport( + SurrogateKind.RefreshToken, TokenFormat.Opaque, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: "Authorization"); var setup = CreateWriter( - CreateResponse(GrantKind.AccessToken, delivery)); + CreateResponse(SurrogateKind.AccessToken, delivery)); var context = TestHttpContext.Create(); Action act = () => setup.Writer.WriteInternal( context, - GrantKind.AccessToken, + SurrogateKind.AccessToken, "token"); act.Should() @@ -295,20 +291,20 @@ public void Mismatched_grant_kind_should_throw() [Fact] public void Unsupported_delivery_mode_should_throw() { - var delivery = new EffectiveGrantDelivery( - GrantKind.AccessToken, + var delivery = new EffectiveSurrogateTransport( + SurrogateKind.AccessToken, TokenFormat.Jwt, - (GrantDeliveryMode)999); + (SurrogateTransport)999); var setup = CreateWriter( - CreateResponse(GrantKind.AccessToken, delivery)); + CreateResponse(SurrogateKind.AccessToken, delivery)); var context = TestHttpContext.Create(); Action act = () => setup.Writer.WriteInternal( context, - GrantKind.AccessToken, + SurrogateKind.AccessToken, "token"); act.Should() @@ -326,7 +322,7 @@ private static WriterSetup CreateWriter(EffectiveAuthResponse response) var cookieManager = new FakeCookieManager(); var cookiePolicy = new FakeCookiePolicyBuilder(); - var writer = new CredentialResponseWriter( + var writer = new SurrogateResponseWriter( accessor, cookieManager, cookiePolicy, @@ -339,25 +335,23 @@ private static WriterSetup CreateWriter(EffectiveAuthResponse response) cookiePolicy); } - private static EffectiveAuthResponse CreateResponse( - GrantKind? kind = null, - EffectiveGrantDelivery? delivery = null) + private static EffectiveAuthResponse CreateResponse(SurrogateKind? kind = null, EffectiveSurrogateTransport? delivery = null) { - var session = EffectiveGrantDelivery.Disabled(GrantKind.Session); - var access = EffectiveGrantDelivery.Disabled(GrantKind.AccessToken); - var refresh = EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken); + var session = EffectiveSurrogateTransport.Disabled(SurrogateKind.SessionId); + var access = EffectiveSurrogateTransport.Disabled(SurrogateKind.AccessToken); + var refresh = EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken); switch (kind) { - case GrantKind.Session: + case SurrogateKind.SessionId: session = delivery!; break; - case GrantKind.AccessToken: + case SurrogateKind.AccessToken: access = delivery!; break; - case GrantKind.RefreshToken: + case SurrogateKind.RefreshToken: refresh = delivery!; break; } @@ -370,7 +364,7 @@ private static EffectiveAuthResponse CreateResponse( } private sealed record WriterSetup( - CredentialResponseWriter Writer, + SurrogateResponseWriter Writer, AuthFlowContext Auth, FakeCookieManager CookieManager, FakeCookiePolicyBuilder CookiePolicy); @@ -421,12 +415,11 @@ public void Delete(HttpContext context, string name) } } - private sealed class FakeCookiePolicyBuilder - : IUAuthCookiePolicyBuilder + private sealed class FakeCookiePolicyBuilder : IUAuthCookiePolicyBuilder { public int BuildCount { get; private set; } - public GrantKind? LastKind { get; private set; } - public EffectiveGrantDelivery? LastDelivery { get; private set; } + public SurrogateKind? LastKind { get; private set; } + public EffectiveSurrogateTransport? LastDelivery { get; private set; } public AuthFlowContext? LastAuth { get; private set; } public CookieOptions CookieOptions { get; } = new() @@ -436,10 +429,7 @@ private sealed class FakeCookiePolicyBuilder SameSite = SameSiteMode.Strict }; - public CookieOptions Build( - EffectiveGrantDelivery delivery, - AuthFlowContext context, - GrantKind kind) + public CookieOptions Build(EffectiveSurrogateTransport delivery, AuthFlowContext context, SurrogateKind kind) { BuildCount++; LastDelivery = delivery; diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/GrantDeliveryCollisionValidatorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SurrogateTransportCollisionValidatorTests.cs similarity index 54% rename from tests/CodeBeam.UltimateAuth.Tests.Unit/Server/GrantDeliveryCollisionValidatorTests.cs rename to tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SurrogateTransportCollisionValidatorTests.cs index 2a4042c5..92f3e0a4 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/GrantDeliveryCollisionValidatorTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/SurrogateTransportCollisionValidatorTests.cs @@ -1,25 +1,24 @@ using AwesomeAssertions; using CodeBeam.UltimateAuth.Core.Contracts; using CodeBeam.UltimateAuth.Core.Domain; -using CodeBeam.UltimateAuth.Core.Options; using CodeBeam.UltimateAuth.Server.Auth; using CodeBeam.UltimateAuth.Server.Domain; using CodeBeam.UltimateAuth.Server.Options; namespace CodeBeam.UltimateAuth.Tests.Unit.Server; -public sealed class GrantDeliveryCollisionValidatorTests +public sealed class SurrogateTransportCollisionValidatorTests { [Fact] public void Validate_WhenGrantNamesAreDistinct_ShouldPass() { var response = CreateResponse( - Cookie(GrantKind.Session, "uas"), - Header(GrantKind.AccessToken, "uat", "Authorization"), - Cookie(GrantKind.RefreshToken, "uar")); + Cookie(SurrogateKind.SessionId, "uas"), + Header(SurrogateKind.AccessToken, "uat", "Authorization"), + Cookie(SurrogateKind.RefreshToken, "uar")); Action act = () => - GrantDeliveryCollisionValidator.Validate(response); + SurrogateTransportCollisionValidator.Validate(response); act.Should().NotThrow(); } @@ -32,12 +31,12 @@ public void Validate_WhenCookieNamesCollide_ShouldThrow( string refreshName) { var response = CreateResponse( - Cookie(GrantKind.Session, sessionName), - Header(GrantKind.AccessToken, "uat", "Authorization"), - Cookie(GrantKind.RefreshToken, refreshName)); + Cookie(SurrogateKind.SessionId, sessionName), + Header(SurrogateKind.AccessToken, "uat", "Authorization"), + Cookie(SurrogateKind.RefreshToken, refreshName)); Action act = () => - GrantDeliveryCollisionValidator.Validate(response); + SurrogateTransportCollisionValidator.Validate(response); act.Should() .Throw() @@ -52,12 +51,12 @@ public void Validate_WhenResponseHeaderNamesCollide_ShouldThrow( string accessName) { var response = CreateResponse( - Header(GrantKind.Session, sessionName, "uas"), - Header(GrantKind.AccessToken, accessName, "Authorization"), - Cookie(GrantKind.RefreshToken, "uar")); + Header(SurrogateKind.SessionId, sessionName, "uas"), + Header(SurrogateKind.AccessToken, accessName, "Authorization"), + Cookie(SurrogateKind.RefreshToken, "uar")); Action act = () => - GrantDeliveryCollisionValidator.Validate(response); + SurrogateTransportCollisionValidator.Validate(response); act.Should() .Throw() @@ -72,12 +71,12 @@ public void Validate_WhenRequestHeaderNamesCollide_ShouldThrow( string accessName) { var response = CreateResponse( - Header(GrantKind.Session, "uas", sessionName), - Header(GrantKind.AccessToken, "uat", accessName), - Cookie(GrantKind.RefreshToken, "uar")); + Header(SurrogateKind.SessionId, "uas", sessionName), + Header(SurrogateKind.AccessToken, "uat", accessName), + Cookie(SurrogateKind.RefreshToken, "uar")); Action act = () => - GrantDeliveryCollisionValidator.Validate(response); + SurrogateTransportCollisionValidator.Validate(response); act.Should() .Throw() @@ -88,12 +87,12 @@ public void Validate_WhenRequestHeaderNamesCollide_ShouldThrow( public void Validate_WhenCookieAndHeaderShareName_ShouldPass() { var response = CreateResponse( - Cookie(GrantKind.Session, "token"), - Header(GrantKind.AccessToken, "token", "token"), - Cookie(GrantKind.RefreshToken, "uar")); + Cookie(SurrogateKind.SessionId, "token"), + Header(SurrogateKind.AccessToken, "token", "token"), + Cookie(SurrogateKind.RefreshToken, "uar")); Action act = () => - GrantDeliveryCollisionValidator.Validate(response); + SurrogateTransportCollisionValidator.Validate(response); act.Should().NotThrow(); } @@ -102,12 +101,12 @@ public void Validate_WhenCookieAndHeaderShareName_ShouldPass() public void Validate_WhenRequestAndResponseHeadersShareName_ShouldPass() { var response = CreateResponse( - Header(GrantKind.Session, "uas", "uat"), - Header(GrantKind.AccessToken, "uat", "Authorization"), - Cookie(GrantKind.RefreshToken, "uar")); + Header(SurrogateKind.SessionId, "uas", "uat"), + Header(SurrogateKind.AccessToken, "uat", "Authorization"), + Cookie(SurrogateKind.RefreshToken, "uar")); Action act = () => - GrantDeliveryCollisionValidator.Validate(response); + SurrogateTransportCollisionValidator.Validate(response); act.Should().NotThrow(); } @@ -116,12 +115,12 @@ public void Validate_WhenRequestAndResponseHeadersShareName_ShouldPass() public void Validate_ShouldIgnoreDisabledGrants() { var response = CreateResponse( - EffectiveGrantDelivery.Disabled(GrantKind.Session), - Header(GrantKind.AccessToken, "uat", "Authorization"), - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken)); + EffectiveSurrogateTransport.Disabled(SurrogateKind.SessionId), + Header(SurrogateKind.AccessToken, "uat", "Authorization"), + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken)); Action act = () => - GrantDeliveryCollisionValidator.Validate(response); + SurrogateTransportCollisionValidator.Validate(response); act.Should().NotThrow(); } @@ -134,12 +133,12 @@ public void Validate_WhenHeaderNameIsMissing_ShouldThrow( string? name) { var response = CreateResponse( - Header(GrantKind.Session, name, "uas"), - EffectiveGrantDelivery.Disabled(GrantKind.AccessToken), - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken)); + Header(SurrogateKind.SessionId, name, "uas"), + EffectiveSurrogateTransport.Disabled(SurrogateKind.AccessToken), + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken)); Action act = () => - GrantDeliveryCollisionValidator.Validate(response); + SurrogateTransportCollisionValidator.Validate(response); act.Should() .Throw() @@ -147,9 +146,9 @@ public void Validate_WhenHeaderNameIsMissing_ShouldThrow( } private static EffectiveAuthResponse CreateResponse( - EffectiveGrantDelivery session, - EffectiveGrantDelivery access, - EffectiveGrantDelivery refresh) + EffectiveSurrogateTransport session, + EffectiveSurrogateTransport access, + EffectiveSurrogateTransport refresh) { return new EffectiveAuthResponse( session, @@ -158,32 +157,32 @@ private static EffectiveAuthResponse CreateResponse( EffectiveRedirectResponse.Disabled); } - private static EffectiveGrantDelivery Cookie( - GrantKind kind, + private static EffectiveSurrogateTransport Cookie( + SurrogateKind kind, string name) { - return new EffectiveGrantDelivery( + return new EffectiveSurrogateTransport( kind, TokenFormat.Opaque, - GrantDeliveryMode.Cookie, + SurrogateTransport.Cookie, cookie: new UAuthCookieOptions { Name = name }); } - private static EffectiveGrantDelivery Header( - GrantKind kind, + private static EffectiveSurrogateTransport Header( + SurrogateKind kind, string? responseName, string? requestName) { - return new EffectiveGrantDelivery( + return new EffectiveSurrogateTransport( kind, TokenFormat.Opaque, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: responseName, - headerFormat: HeaderTokenFormat.Bearer, + headerFormat: HeaderValueFormat.Bearer, requestHeaderName: requestName, - requestHeaderFormat: HeaderTokenFormat.Bearer); + requestHeaderFormat: HeaderValueFormat.Bearer); } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/TransportCredentialResolverTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/TransportCredentialResolverTests.cs index 92fcf438..043b1582 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/TransportCredentialResolverTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/TransportCredentialResolverTests.cs @@ -3,10 +3,10 @@ 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; +using CodeBeam.UltimateAuth.Server.Extensions; using CodeBeam.UltimateAuth.Server.Infrastructure; using CodeBeam.UltimateAuth.Server.Options; using CodeBeam.UltimateAuth.Tests.Unit.Helpers; @@ -23,13 +23,13 @@ public sealed class TransportCredentialResolverTests private const string RefreshToken = "refresh-token-value"; [Theory] - [InlineData(UAuthMode.PureOpaque, TransportCredentialKind.Session, SessionToken)] - [InlineData(UAuthMode.Hybrid, TransportCredentialKind.Session, SessionToken)] - [InlineData(UAuthMode.SemiHybrid, TransportCredentialKind.AccessToken, AccessToken)] - [InlineData(UAuthMode.PureJwt, TransportCredentialKind.AccessToken, AccessToken)] + [InlineData(UAuthMode.PureOpaque, SurrogateKind.SessionId, SessionToken)] + [InlineData(UAuthMode.Hybrid, SurrogateKind.SessionId, SessionToken)] + [InlineData(UAuthMode.SemiHybrid, SurrogateKind.AccessToken, AccessToken)] + [InlineData(UAuthMode.PureJwt, SurrogateKind.AccessToken, AccessToken)] public async Task ResolveAsync_ShouldSelectPrimaryCredentialAccordingToMode( UAuthMode mode, - TransportCredentialKind expectedKind, + SurrogateKind expectedKind, string expectedValue) { var context = CreateContext(); @@ -55,7 +55,7 @@ public async Task ResolveAsync_ShouldSelectPrimaryCredentialAccordingToMode( var sut = CreateSut(); - var result = await sut.ResolveAsync( + var result = await sut.ResolvePrimaryAsync( context, mode, CreateResponse()); @@ -84,7 +84,7 @@ public async Task ResolveAsync_WhenSessionIsMissing_ShouldNotFallbackToAccessTok var sut = CreateSut(); - var result = await sut.ResolveAsync( + var result = await sut.ResolvePrimaryAsync( context, mode, CreateResponse()); @@ -105,7 +105,7 @@ public async Task ResolveAsync_WhenAccessTokenIsMissing_ShouldNotFallbackToSessi var sut = CreateSut(); - var result = await sut.ResolveAsync( + var result = await sut.ResolvePrimaryAsync( context, mode, CreateResponse()); @@ -128,7 +128,7 @@ public async Task ResolveAsync_ShouldNeverUseRefreshTokenAsPrimaryCredential( var sut = CreateSut(); - var result = await sut.ResolveAsync( + var result = await sut.ResolvePrimaryAsync( context, mode, CreateResponse()); @@ -153,14 +153,14 @@ public async Task ResolveAsync_WhenPrimaryDeliveryIsDisabled_ShouldReturnNull( $"Bearer {AccessToken}"; var response = new EffectiveAuthResponse( - EffectiveGrantDelivery.Disabled(GrantKind.Session), - EffectiveGrantDelivery.Disabled(GrantKind.AccessToken), - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + EffectiveSurrogateTransport.Disabled(SurrogateKind.SessionId), + EffectiveSurrogateTransport.Disabled(SurrogateKind.AccessToken), + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), EffectiveRedirectResponse.Disabled); var sut = CreateSut(); - var result = await sut.ResolveAsync( + var result = await sut.ResolvePrimaryAsync( context, mode, response); @@ -184,7 +184,7 @@ public async Task ResolveAsync_WhenAccessTokenIsMalformed_ShouldNotFallbackToSes var sut = CreateSut(); - var result = await sut.ResolveAsync( + var result = await sut.ResolvePrimaryAsync( context, mode, CreateResponse()); @@ -214,25 +214,25 @@ public async Task ResolveAsync_WhenSessionUsesHeader_ShouldResolveConfiguredHead context.Request.Headers.Cookie = "uas=wrong-token"; var response = new EffectiveAuthResponse( - new EffectiveGrantDelivery( - GrantKind.Session, + new EffectiveSurrogateTransport( + SurrogateKind.SessionId, TokenFormat.Opaque, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: "X-Session", - headerFormat: HeaderTokenFormat.Raw), - EffectiveGrantDelivery.Disabled(GrantKind.AccessToken), - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + headerFormat: HeaderValueFormat.Raw), + EffectiveSurrogateTransport.Disabled(SurrogateKind.AccessToken), + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), EffectiveRedirectResponse.Disabled); var sut = CreateSut(); - var result = await sut.ResolveAsync( + var result = await sut.ResolvePrimaryAsync( context, UAuthMode.PureOpaque, response); result.Should().NotBeNull(); - result!.Kind.Should().Be(TransportCredentialKind.Session); + result!.Kind.Should().Be(SurrogateKind.SessionId); result.Value.Should().Be(SessionToken); } @@ -261,51 +261,33 @@ public async Task ResolveAsync_WhenAccessTokenUsesCookie_ShouldResolveConfigured "Bearer wrong-token"; var response = new EffectiveAuthResponse( - EffectiveGrantDelivery.Disabled(GrantKind.Session), - new EffectiveGrantDelivery( - GrantKind.AccessToken, + EffectiveSurrogateTransport.Disabled(SurrogateKind.SessionId), + new EffectiveSurrogateTransport( + SurrogateKind.AccessToken, TokenFormat.Jwt, - GrantDeliveryMode.Cookie, + SurrogateTransport.Cookie, cookie: new UAuthCookieOptions { Name = "uat" }), - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), EffectiveRedirectResponse.Disabled); var sut = CreateSut(); - var result = await sut.ResolveAsync( + var result = await sut.ResolvePrimaryAsync( context, UAuthMode.PureJwt, response); result.Should().NotBeNull(); - result!.Kind.Should().Be(TransportCredentialKind.AccessToken); + result!.Kind.Should().Be(SurrogateKind.AccessToken); result.Value.Should().Be(AccessToken); } - [Fact] - public async Task ResolveAsync_WhenModeIsUnsupported_ShouldThrow() - { - var context = CreateContext(); - var sut = CreateSut(); - - Func act = async () => - { - await sut.ResolveAsync( - context, - (UAuthMode)999, - CreateResponse()); - }; - - await act.Should().ThrowAsync(); - } - - private static TransportCredentialResolver CreateSut() + private static SurrogateResolver CreateSut() { - return new TransportCredentialResolver( - new PrimaryTokenResolver()); + return new SurrogateResolver(); } private static DefaultHttpContext CreateContext() @@ -321,26 +303,26 @@ private static DefaultHttpContext CreateContext() private static EffectiveAuthResponse CreateResponse() { return new EffectiveAuthResponse( - new EffectiveGrantDelivery( - GrantKind.Session, + new EffectiveSurrogateTransport( + SurrogateKind.SessionId, TokenFormat.Opaque, - GrantDeliveryMode.Cookie, + SurrogateTransport.Cookie, cookie: new UAuthCookieOptions { Name = "uas" }), - new EffectiveGrantDelivery( - GrantKind.AccessToken, + new EffectiveSurrogateTransport( + SurrogateKind.AccessToken, TokenFormat.Jwt, - GrantDeliveryMode.Header, + SurrogateTransport.Header, name: "uat", - headerFormat: HeaderTokenFormat.Raw, + headerFormat: HeaderValueFormat.Raw, requestHeaderName: "Authorization", - requestHeaderFormat: HeaderTokenFormat.Bearer), - new EffectiveGrantDelivery( - GrantKind.RefreshToken, + requestHeaderFormat: HeaderValueFormat.Bearer), + new EffectiveSurrogateTransport( + SurrogateKind.RefreshToken, TokenFormat.Opaque, - GrantDeliveryMode.Cookie, + SurrogateTransport.Cookie, cookie: new UAuthCookieOptions { Name = "uar" diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthCorsHubOptionsSetupTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthCorsHubOptionsSetupTests.cs index d4dc9bc7..91f14670 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthCorsHubOptionsSetupTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthCorsHubOptionsSetupTests.cs @@ -60,27 +60,15 @@ public void Configure_ExposesJwtTransportHeaders() public void Configure_ExposesConfiguredAccessTokenHeader() { var server = new UAuthServerOptions(); - - server.Hub.AllowedClientOrigins.Add( - "https://app.example.com"); - - server.GrantDelivery.AccessToken.HeaderName = - "X-Custom-Access"; - - var setup = new UAuthHubCorsOptionsSetup( - Options.Create(server)); - + server.Hub.AllowedClientOrigins.Add("https://app.example.com"); + server.Transport.AccessToken.HeaderName = "X-Custom-Access"; + var setup = new UAuthHubCorsOptionsSetup(Options.Create(server)); var cors = new CorsOptions(); - setup.Configure(cors); - var policy = cors.GetPolicy("UAuthHub"); Assert.NotNull(policy); - - Assert.Contains( - "X-Custom-Access", - policy.ExposedHeaders); + Assert.Contains("X-Custom-Access", policy.ExposedHeaders); } [Fact] diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthFlowServiceTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthFlowServiceTests.cs index 5a7b9944..2ebf5753 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthFlowServiceTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthFlowServiceTests.cs @@ -747,15 +747,14 @@ private static AuthFlowContext CreateFlow( session: session, options: TestServerOptions.Default(), response: new EffectiveAuthResponse( - sessionIdDelivery: - EffectiveGrantDelivery.Disabled(GrantKind.Session), - accessTokenDelivery: - EffectiveGrantDelivery.Disabled(GrantKind.AccessToken), - refreshTokenDelivery: - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + sessionIdTransport: + EffectiveSurrogateTransport.Disabled(SurrogateKind.SessionId), + accessTokenTransport: + EffectiveSurrogateTransport.Disabled(SurrogateKind.AccessToken), + refreshTokenTransport: + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), redirect: EffectiveRedirectResponse.Disabled), - primaryTokenKind: PrimaryTokenKind.Session, returnUrlInfo: ReturnUrlInfo.None()); } } diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthLoginTransportEndpointTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthLoginTransportEndpointTests.cs index 2d987485..4d4fb2fb 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthLoginTransportEndpointTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthLoginTransportEndpointTests.cs @@ -14,16 +14,16 @@ namespace CodeBeam.UltimateAuth.Tests.Unit.Server; public sealed class UAuthLoginTransportEndpointTests { [Theory] - [InlineData(GrantDeliveryMode.Cookie, GrantDeliveryMode.None, true, true, false)] - [InlineData(GrantDeliveryMode.Cookie, GrantDeliveryMode.Header, true, false, true)] - [InlineData(GrantDeliveryMode.Header, GrantDeliveryMode.None, false, false, false)] - [InlineData(GrantDeliveryMode.Header, GrantDeliveryMode.Header, false, false, true)] - public void Get_ReportsEffectiveTransportCapabilities(GrantDeliveryMode session, GrantDeliveryMode access, bool supported, bool navigationSupported, bool accessTokenInHeader) + [InlineData(SurrogateTransport.Cookie, SurrogateTransport.None, true, true, false)] + [InlineData(SurrogateTransport.Cookie, SurrogateTransport.Header, true, false, true)] + [InlineData(SurrogateTransport.Header, SurrogateTransport.None, false, false, false)] + [InlineData(SurrogateTransport.Header, SurrogateTransport.Header, false, false, true)] + public void Get_ReportsEffectiveTransportCapabilities(SurrogateTransport session, SurrogateTransport access, bool supported, bool navigationSupported, bool accessTokenInHeader) { var response = new EffectiveAuthResponse( - Delivery(GrantKind.Session, session), - Delivery(GrantKind.AccessToken, access), - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + Delivery(SurrogateKind.SessionId, session), + Delivery(SurrogateKind.AccessToken, access), + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), EffectiveRedirectResponse.Disabled); var flow = AuthFlowTestFactory.New(response: response); @@ -45,14 +45,14 @@ public void Get_ReportsEffectiveTransportCapabilities(GrantDeliveryMode session, json.GetProperty("accessTokenInHeader").GetBoolean().Should().Be(accessTokenInHeader); } - private static EffectiveGrantDelivery Delivery(GrantKind kind,GrantDeliveryMode mode) + private static EffectiveSurrogateTransport Delivery(SurrogateKind kind,SurrogateTransport mode) { - if (mode == GrantDeliveryMode.None) - return EffectiveGrantDelivery.Disabled(kind); + if (mode == SurrogateTransport.None) + return EffectiveSurrogateTransport.Disabled(kind); - return new EffectiveGrantDelivery( + return new EffectiveSurrogateTransport( kind, - kind == GrantKind.AccessToken + kind == SurrogateKind.AccessToken ? TokenFormat.Jwt : TokenFormat.Opaque, mode); diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthResourceAuthenticationHandlerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthResourceAuthenticationHandlerTests.cs index 12646a46..a9345424 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthResourceAuthenticationHandlerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthResourceAuthenticationHandlerTests.cs @@ -11,6 +11,7 @@ using CodeBeam.UltimateAuth.Server.Authentication; using CodeBeam.UltimateAuth.Server.Contracts; using CodeBeam.UltimateAuth.Server.Domain; +using CodeBeam.UltimateAuth.Server.Extensions; using CodeBeam.UltimateAuth.Server.Infrastructure; using CodeBeam.UltimateAuth.Server.Options; using CodeBeam.UltimateAuth.Server.ResourceApi; @@ -66,9 +67,8 @@ public async Task AuthenticateAsync_WhenCredentialDoesNotExist_ShouldReturnNoRes setup.CredentialResolver .Setup(x => x.ResolveAsync( It.IsAny(), - UAuthMode.PureOpaque, - It.IsAny())) - .ReturnsAsync((TransportCredential?)null); + It.IsAny())) + .ReturnsAsync((ResolvedSurrogate?)null); var result = await AuthenticateAsync(setup); @@ -89,8 +89,7 @@ public async Task AuthenticateAsync_WhenCredentialIsMalformed_ShouldFail() setup.CredentialResolver .Setup(x => x.ResolveAsync( It.IsAny(), - UAuthMode.PureOpaque, - It.IsAny())) + It.IsAny())) .ReturnsAsync(CreateSessionCredential("invalid")); var result = await AuthenticateAsync(setup); @@ -114,8 +113,7 @@ public async Task AuthenticateAsync_WhenCredentialIsNotSession_ShouldFail() setup.CredentialResolver .Setup(x => x.ResolveAsync( It.IsAny(), - UAuthMode.PureOpaque, - It.IsAny())) + It.IsAny())) .ReturnsAsync(CreateJwtCredential()); var result = await AuthenticateAsync(setup); @@ -123,7 +121,7 @@ public async Task AuthenticateAsync_WhenCredentialIsNotSession_ShouldFail() result.Succeeded.Should().BeFalse(); result.Failure.Should().NotBeNull(); result.Failure!.Message.Should() - .Be("Resource authentication requires a session credential."); + .Be("Resource authentication requires a session surrogate."); setup.SessionValidator.Verify( x => x.ValidateSessionAsync( @@ -324,8 +322,7 @@ public async Task AuthenticateAsync_ShouldCreateDeviceFromTransportCredential() setup.CredentialResolver .Setup(x => x.ResolveAsync( It.IsAny(), - UAuthMode.PureOpaque, - It.IsAny())) + It.IsAny())) .ReturnsAsync(CreateSessionCredential(TestSessionId, deviceInfo)); setup.DeviceFactory @@ -409,9 +406,8 @@ public async Task AuthenticateAsync_PureJwt_WhenCredentialIsMissing_ShouldReturn setup.CredentialResolver .Setup(x => x.ResolveAsync( It.IsAny(), - UAuthMode.PureJwt, - It.IsAny())) - .ReturnsAsync((TransportCredential?)null); + It.IsAny())) + .ReturnsAsync((ResolvedSurrogate?)null); var result = await AuthenticateAsync(setup); @@ -435,8 +431,7 @@ public async Task AuthenticateAsync_PureJwt_WhenCredentialIsNotAccessToken_Shoul setup.CredentialResolver .Setup(x => x.ResolveAsync( It.IsAny(), - UAuthMode.PureJwt, - It.IsAny())) + It.IsAny())) .ReturnsAsync(CreateSessionCredential(TestSessionId)); var result = await AuthenticateAsync(setup); @@ -718,7 +713,7 @@ public async Task AuthenticateAsync_PureJwt_ShouldNotStoreSessionValidationResul private static TestSetup CreateTestContext( UAuthMode mode = UAuthMode.PureOpaque) { - var credentialResolver = new Mock(); + var credentialResolver = new Mock(); var sessionValidator = new Mock(); var deviceFactory = new Mock(); var deviceResolver = new Mock(); @@ -738,22 +733,22 @@ private static TestSetup CreateTestContext( credentialResolver .Setup(x => x.ResolveAsync( It.IsAny(), - UAuthMode.PureOpaque, - It.IsAny())) + It.Is( + t => t.Kind == SurrogateKind.SessionId))) .ReturnsAsync(CreateSessionCredential(TestSessionId)); credentialResolver .Setup(x => x.ResolveAsync( It.IsAny(), - UAuthMode.PureJwt, - It.IsAny())) + It.Is( + t => t.Kind == SurrogateKind.AccessToken))) .ReturnsAsync(CreateJwtCredential()); var services = new ServiceCollection(); services.AddLogging(); - services.AddSingleton( + services.AddSingleton( credentialResolver.Object); services.AddSingleton( @@ -777,13 +772,13 @@ private static TestSetup CreateTestContext( Auth = new UAuthResourceAuthOptions { Mode = mode, - Session = new UAuthResourceSessionOptions + SessionId = new UAuthResourceSurrogateTransportOptions { - DeliveryMode = GrantDeliveryMode.Cookie + Mode = SurrogateTransport.Cookie }, - AccessToken = new UAuthResourceAccessTokenOptions + AccessToken = new UAuthResourceSurrogateTransportOptions { - DeliveryMode = GrantDeliveryMode.Cookie + Mode = SurrogateTransport.Cookie } }, })); @@ -819,21 +814,21 @@ private static Task AuthenticateAsync(TestSetup setup) return setup.HttpContext.AuthenticateAsync(Scheme); } - private static TransportCredential CreateSessionCredential(string value, DeviceInfo? device = null) + private static ResolvedSurrogate CreateSessionCredential(string value, DeviceInfo? device = null) { - return new TransportCredential + return new ResolvedSurrogate { - Kind = TransportCredentialKind.Session, + Kind = SurrogateKind.SessionId, Value = value, Device = device ?? CreateDeviceInfo() }; } - private static TransportCredential CreateJwtCredential() + private static ResolvedSurrogate CreateJwtCredential() { - return new TransportCredential + return new ResolvedSurrogate { - Kind = TransportCredentialKind.AccessToken, + Kind = SurrogateKind.AccessToken, Value = TestJwt, Device = CreateDeviceInfo() }; @@ -895,7 +890,7 @@ private static void VerifyNoSessionValidation(TestSetup setup) private sealed record TestSetup( DefaultHttpContext HttpContext, - Mock CredentialResolver, + Mock CredentialResolver, Mock SessionValidator, Mock DeviceFactory, Mock DeviceResolver, diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthSessionValidatorTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthSessionValidatorTests.cs index 01637d5d..27a041ba 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthSessionValidatorTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthSessionValidatorTests.cs @@ -569,7 +569,7 @@ public async Task ValidateSessionAsync_MetadataOnlySession_ReturnsNotFound() device: fixture.Session.Device, claims: ClaimsSnapshot.Empty, metadata: SessionMetadata.Empty, - credentialPurpose: SessionCredentialPurpose.MetadataOnly); + credentialPurpose: SessionIdPurpose.MetadataOnly); fixture.Store .Setup(x => x.GetSessionAsync( @@ -615,17 +615,17 @@ public void MetadataOnlySession_PreservesPurpose_AfterMutation() device: DeviceContext.Anonymous(), claims: ClaimsSnapshot.Empty, metadata: SessionMetadata.Empty, - credentialPurpose: SessionCredentialPurpose.MetadataOnly); + credentialPurpose: SessionIdPurpose.MetadataOnly); session.IsMetadataOnly.Should().BeTrue(); session.ExtendExpiration(now.AddHours(2)) .CredentialPurpose.Should() - .Be(SessionCredentialPurpose.MetadataOnly); + .Be(SessionIdPurpose.MetadataOnly); session.Revoke(now.AddMinutes(10)) .CredentialPurpose.Should() - .Be(SessionCredentialPurpose.MetadataOnly); + .Be(SessionIdPurpose.MetadataOnly); } // --------------------------------------------------------------------- diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthStatusAuthorizationResultHandlerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthStatusAuthorizationResultHandlerTests.cs index eb7ba4d2..8f67c9f5 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthStatusAuthorizationResultHandlerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/UAuthStatusAuthorizationResultHandlerTests.cs @@ -102,8 +102,7 @@ private static SessionValidationResult CreateActiveLineage( userStatus: status); } - private static AuthValidationResult CreateHubResponse( - UserStatus status = UserStatus.Active) + private static AuthValidationResult CreateHubResponse(UserStatus status = UserStatus.Active) { return new AuthValidationResult { @@ -157,7 +156,7 @@ private sealed class Fixture : IDisposable public Mock DeviceContextFactory { get; } = new(MockBehavior.Strict); - public Mock Credentials { get; } + public Mock Credentials { get; } = new(MockBehavior.Strict); public Mock Clock { get; } @@ -180,26 +179,20 @@ private sealed class Fixture : IDisposable private readonly UAuthStatusAuthorizationResultHandler _sut = new(); - public Fixture( - UAuthMode mode, - bool resource = false) + public Fixture(UAuthMode mode, bool resource = false) { Context.User = CreatePrincipal(User.Value); Context.RequestAborted = CancellationToken; - Context.Items[ - UAuthConstants.HttpItems.TenantContextKey] = - UAuthTenantContext.Resolved(Tenant); + Context.Items[UAuthConstants.HttpItems.TenantContextKey] = UAuthTenantContext.Resolved(Tenant); ServerOptions.AuthMode = mode; - ServerOptions.Session.DeviceMismatchBehavior = - DeviceMismatchBehavior.Reject; + ServerOptions.Session.DeviceMismatchBehavior = DeviceMismatchBehavior.Reject; ResourceOptions.Auth.Mode = mode; - ResourceOptions.Auth.Device.MismatchBehavior = - DeviceMismatchBehavior.Reject; + ResourceOptions.Auth.Device.MismatchBehavior = DeviceMismatchBehavior.Reject; var effective = new EffectiveUAuthServerOptions { @@ -261,11 +254,10 @@ public Fixture( Credentials .Setup(x => x.ResolveAsync( Context, - UAuthMode.SemiHybrid, - It.IsAny())) - .ReturnsAsync(new TransportCredential + It.IsAny())) + .ReturnsAsync(new ResolvedSurrogate { - Kind = TransportCredentialKind.AccessToken, + Kind = SurrogateKind.AccessToken, Value = "test-access-token", TenantId = Tenant.Value, Device = deviceInfo @@ -352,7 +344,7 @@ public void SetupLineage(SessionValidationResult result) Lineage .Setup(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, CancellationToken)) .ReturnsAsync(result); } @@ -440,7 +432,7 @@ public void VerifyLocalAuthorityValidation() context.Device.DeviceId == Device && context.SessionOptions == ServerOptions.Session && context.Now == Now), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, CancellationToken), Times.Once); @@ -596,16 +588,13 @@ public async Task HandleAsync_AlreadyForbidden_ShouldNotRunAdditionalValidation( { using var fixture = new Fixture(UAuthMode.SemiHybrid); - await fixture.ExecuteAsync( - PolicyAuthorizationResult.Forbid()); + await fixture.ExecuteAsync(PolicyAuthorizationResult.Forbid()); fixture.AssertForbidden(); fixture.VerifyNoAuthorityValidation(); fixture.Users.VerifyNoOtherCalls(); - Assert.False( - fixture.Context.Response.Headers.ContainsKey( - UAuthConstants.Headers.AuthRecovery)); + Assert.False(fixture.Context.Response.Headers.ContainsKey(UAuthConstants.Headers.AuthRecovery)); } [Theory] diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/ValidateEndpointHandlerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/ValidateEndpointHandlerTests.cs index b4ab71c3..d0b23244 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/ValidateEndpointHandlerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Server/ValidateEndpointHandlerTests.cs @@ -29,16 +29,16 @@ public sealed class ValidateEndpointHandlerTests // ===================================================================== [Fact] - public async Task ValidateAsync_WhenCredentialIsMissing_ReturnsUnauthorizedNotFound() + public async Task ValidateAsync_WhenSurrogateIsMissing_ReturnsUnauthorizedNotFound() { var fixture = CreateFixture(); - fixture.CredentialResolver + fixture.SurrogateResolver .Setup(x => x.ResolveAsync( fixture.HttpContext, - fixture.Flow.EffectiveMode, - fixture.Flow.Response)) - .ReturnsAsync((TransportCredential?)null); + It.Is( + t => t.Kind == SurrogateKind.SessionId))) + .ReturnsAsync((ResolvedSurrogate?)null); var result = await fixture.Sut.ValidateAsync( fixture.HttpContext, @@ -63,24 +63,24 @@ public async Task ValidateAsync_WhenCredentialIsMissing_ReturnsUnauthorizedNotFo } [Fact] - public async Task ValidateAsync_WhenCredentialKindIsAccessToken_ReturnsUnauthorizedUnsupported() + public async Task ValidateAsync_WhenSurrogateKindIsAccessToken_ReturnsUnauthorizedUnsupported() { var fixture = CreateFixture(); - var credential = new TransportCredential + var surrogate = new ResolvedSurrogate { - Kind = TransportCredentialKind.AccessToken, + Kind = SurrogateKind.AccessToken, Value = "access-token", TenantId = fixture.Flow.Tenant.Value, Device = TestDevice.DefaultDeviceInfo() }; - fixture.CredentialResolver + fixture.SurrogateResolver .Setup(x => x.ResolveAsync( fixture.HttpContext, - fixture.Flow.EffectiveMode, - fixture.Flow.Response)) - .ReturnsAsync(credential); + It.Is( + t => t.Kind == SurrogateKind.SessionId))) + .ReturnsAsync(surrogate); var result = await fixture.Sut.ValidateAsync( fixture.HttpContext, @@ -97,6 +97,7 @@ public async Task ValidateAsync_WhenCredentialKindIsAccessToken_ReturnsUnauthori json.Value!.State.Should() .Be(SessionState.Unsupported); + json.Value.IsValid.Should().BeFalse(); json.Value.Snapshot.Should().BeNull(); fixture.SessionValidator.VerifyNoOtherCalls(); @@ -108,24 +109,24 @@ public async Task ValidateAsync_WhenCredentialKindIsAccessToken_ReturnsUnauthori // ===================================================================== [Fact] - public async Task ValidateAsync_WhenSessionCredentialCannotBeParsed_ReturnsUnauthorizedInvalid() + public async Task ValidateAsync_WhenSessionSurrogateCannotBeParsed_ReturnsUnauthorizedInvalid() { var fixture = CreateFixture(); - var credential = new TransportCredential + var surrogate = new ResolvedSurrogate { - Kind = TransportCredentialKind.Session, + Kind = SurrogateKind.SessionId, Value = "invalid", TenantId = fixture.Flow.Tenant.Value, Device = TestDevice.DefaultDeviceInfo() }; - fixture.CredentialResolver + fixture.SurrogateResolver .Setup(x => x.ResolveAsync( fixture.HttpContext, - fixture.Flow.EffectiveMode, - fixture.Flow.Response)) - .ReturnsAsync(credential); + It.Is( + t => t.Kind == SurrogateKind.SessionId))) + .ReturnsAsync(surrogate); var result = await fixture.Sut.ValidateAsync( fixture.HttpContext, @@ -161,9 +162,7 @@ public async Task ValidateAsync_WhenSessionCredentialIsValid_PassesExpectedConte var sessionId = TestIds.Session("validate-session"); - SetupSessionCredential( - fixture, - sessionId); + SetupSessionSurrogate(fixture, sessionId); SessionValidationContext? capturedContext = null; CancellationToken capturedToken = default; @@ -224,7 +223,7 @@ public async Task ValidateAsync_WhenValidationIsInvalidWithoutUserKey_ReturnsOkI var sessionId = TestIds.Session("missing-user-session"); - SetupSessionCredential( + SetupSessionSurrogate( fixture, sessionId); @@ -277,7 +276,7 @@ public async Task ValidateAsync_WhenSessionIsValid_ReturnsOkActiveWithSnapshot() var sessionId = TestIds.Session("active-session"); - SetupSessionCredential( + SetupSessionSurrogate( fixture, sessionId); @@ -349,7 +348,7 @@ public async Task ValidateAsync_WhenValidationIsInvalidButContainsUserKey_Return var userKey = UserKey.New(); - SetupSessionCredential( + SetupSessionSurrogate( fixture, sessionId); @@ -403,7 +402,7 @@ public async Task ValidateAsync_PropagatesCancellationTokenToSessionValidator() var sessionId = TestIds.Session("cancellation-session"); - SetupSessionCredential( + SetupSessionSurrogate( fixture, sessionId); @@ -442,7 +441,7 @@ public async Task ValidateAsync_WhenValidationIsActiveButHasNoUserKey_ReturnsUna var sessionId = TestIds.Session("active-without-user"); - SetupSessionCredential( + SetupSessionSurrogate( fixture, sessionId); @@ -507,7 +506,7 @@ public async Task ValidateAsync_PureJwt_NoCredential_ReturnsUnauthorizedNotFound json.Value!.State.Should().Be(SessionState.NotFound); json.Value.Snapshot.Should().BeNull(); - fixture.CredentialResolver.VerifyNoOtherCalls(); + fixture.SurrogateResolver.VerifyNoOtherCalls(); fixture.SessionValidator.VerifyNoOtherCalls(); fixture.SnapshotFactory.VerifyNoOtherCalls(); } @@ -530,7 +529,7 @@ public async Task ValidateAsync_PureJwt_AuthenticationFails_ReturnsUnauthorizedI json.Value!.State.Should().Be(SessionState.Invalid); json.Value.Snapshot.Should().BeNull(); - fixture.CredentialResolver.VerifyNoOtherCalls(); + fixture.SurrogateResolver.VerifyNoOtherCalls(); fixture.SessionValidator.VerifyNoOtherCalls(); fixture.SnapshotFactory.VerifyNoOtherCalls(); } @@ -616,7 +615,7 @@ public async Task ValidateAsync_PureJwt_ValidPrincipal_ReturnsActiveSnapshot() snapshot.Claims.Claims["uauth:permission"] .Should().Contain("users.read"); - fixture.CredentialResolver.VerifyNoOtherCalls(); + fixture.SurrogateResolver.VerifyNoOtherCalls(); fixture.SessionValidator.VerifyNoOtherCalls(); fixture.SnapshotFactory.VerifyNoOtherCalls(); } @@ -669,7 +668,7 @@ public async Task ValidateAsync_SemiHybrid_Standard_ShouldNotValidateLineage(str Assert.Null(ok.Value.ChainId); Assert.Null(ok.Value.RootId); - fixture.CredentialResolver.VerifyNoOtherCalls(); + fixture.SurrogateResolver.VerifyNoOtherCalls(); fixture.SessionValidator.VerifyNoOtherCalls(); fixture.LineageValidator.VerifyNoOtherCalls(); fixture.SnapshotFactory.VerifyNoOtherCalls(); @@ -755,7 +754,7 @@ public async Task ValidateAsync_PureJwt_HubValidated_ShouldReturnBadRequest(bool Assert.IsType(result); - fixture.CredentialResolver.VerifyNoOtherCalls(); + fixture.SurrogateResolver.VerifyNoOtherCalls(); fixture.SessionValidator.VerifyNoOtherCalls(); fixture.LineageValidator.VerifyNoOtherCalls(); fixture.SnapshotFactory.VerifyNoOtherCalls(); @@ -780,11 +779,11 @@ public async Task ValidateAsync_SemiHybrid_HubValidated_ShouldReturnAuthoritativ fixture.LineageValidator .Setup(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken)) .Callback< SessionValidationContext, - SessionCredentialPurpose, + SessionIdPurpose, CancellationToken>( (context, _, _) => captured = context) .ReturnsAsync(validation); @@ -839,7 +838,7 @@ public async Task ValidateAsync_SemiHybrid_HubValidated_ShouldReturnAuthoritativ fixture.LineageValidator.Verify( x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken), Times.Once); @@ -849,7 +848,7 @@ public async Task ValidateAsync_SemiHybrid_HubValidated_ShouldReturnAuthoritativ fixture.CancellationToken), Times.Once); - fixture.CredentialResolver.VerifyNoOtherCalls(); + fixture.SurrogateResolver.VerifyNoOtherCalls(); fixture.SessionValidator.VerifyNoOtherCalls(); } @@ -866,17 +865,11 @@ public async Task ValidateAsync_SemiHybrid_InvalidLineage_ShouldReturnInvalidSta out _, out _); - fixture.HttpContext.Request.Headers[ - UAuthConstants.Headers.Validation] = - "HubValidated"; + fixture.HttpContext.Request.Headers[UAuthConstants.Headers.Validation] = "HubValidated"; - SetupSemiHybridLineage( - fixture, - SessionValidationResult.Invalid(state)); + SetupSemiHybridLineage(fixture, SessionValidationResult.Invalid(state)); - var result = await fixture.Sut.ValidateAsync( - fixture.HttpContext, - fixture.CancellationToken); + var result = await fixture.Sut.ValidateAsync(fixture.HttpContext, fixture.CancellationToken); var ok = Assert.IsType>(result); @@ -886,7 +879,7 @@ public async Task ValidateAsync_SemiHybrid_InvalidLineage_ShouldReturnInvalidSta Assert.Null(ok.Value.Snapshot); fixture.SnapshotFactory.VerifyNoOtherCalls(); - fixture.CredentialResolver.VerifyNoOtherCalls(); + fixture.SurrogateResolver.VerifyNoOtherCalls(); fixture.SessionValidator.VerifyNoOtherCalls(); } @@ -1010,7 +1003,7 @@ public async Task ValidateAsync_ConfiguredHubValidation_CannotBeDowngraded(strin fixture.LineageValidator.Verify( x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken), Times.Once); } @@ -1067,7 +1060,7 @@ public async Task ValidateAsync_EndpointRequirement_CannotBeDowngraded() fixture.LineageValidator.Verify( x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken), Times.Once); } @@ -1112,7 +1105,7 @@ private static Fixture CreateFixture(UAuthMode mode = UAuthMode.PureOpaque) var flow = AuthFlowTestFactory.New(mode: mode); var authContext = new Mock(MockBehavior.Strict); - var credentialResolver = new Mock(MockBehavior.Strict); + var surrogateResolver = new Mock(MockBehavior.Strict); var sessionValidator = new Mock(MockBehavior.Strict); var snapshotFactory = new Mock(MockBehavior.Strict); var lineageValidator = new Mock(MockBehavior.Strict); @@ -1139,7 +1132,7 @@ private static Fixture CreateFixture(UAuthMode mode = UAuthMode.PureOpaque) var sut = new ValidateEndpointHandler( authContext.Object, - credentialResolver.Object, + surrogateResolver.Object, sessionValidator.Object, authorityValidator, snapshotFactory.Object, @@ -1148,7 +1141,7 @@ private static Fixture CreateFixture(UAuthMode mode = UAuthMode.PureOpaque) return new Fixture( sut, flow, - credentialResolver, + surrogateResolver, sessionValidator, lineageValidator, snapshotFactory, @@ -1230,7 +1223,7 @@ private static void SetupSemiHybridLineage( fixture.LineageValidator .Setup(x => x.ValidateAsync( It.IsAny(), - SessionCredentialPurpose.MetadataOnly, + SessionIdPurpose.MetadataOnly, fixture.CancellationToken)) .ReturnsAsync(validation); } @@ -1258,16 +1251,16 @@ private static AuthenticateResult JwtSuccess(ClaimsPrincipal principal) return AuthenticateResult.Success(new AuthenticationTicket(principal, UAuthConstants.SchemeDefaults.GlobalScheme)); } - private static void SetupSessionCredential(Fixture fixture, AuthSessionId sessionId) + private static void SetupSessionSurrogate(Fixture fixture, AuthSessionId sessionId) { - fixture.CredentialResolver + fixture.SurrogateResolver .Setup(x => x.ResolveAsync( fixture.HttpContext, - fixture.Flow.EffectiveMode, - fixture.Flow.Response)) - .ReturnsAsync(new TransportCredential + It.Is( + t => t.Kind == SurrogateKind.SessionId))) + .ReturnsAsync(new ResolvedSurrogate { - Kind = TransportCredentialKind.Session, + Kind = SurrogateKind.SessionId, Value = sessionId.Value, TenantId = fixture.Flow.Tenant.Value, Device = TestDevice.DefaultDeviceInfo() @@ -1305,7 +1298,7 @@ private static AuthStateSnapshot CreateSnapshot(TenantKey tenant, UserKey userKe private sealed record Fixture( ValidateEndpointHandler Sut, AuthFlowContext Flow, - Mock CredentialResolver, + Mock SurrogateResolver, Mock SessionValidator, Mock LineageValidator, Mock SnapshotFactory, diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/SessionIdResolverTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/SessionIdResolverTests.cs index 95b18591..2f90df8f 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/SessionIdResolverTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/SessionIdResolverTests.cs @@ -5,6 +5,7 @@ using CodeBeam.UltimateAuth.Server.Abstractions; using CodeBeam.UltimateAuth.Server.Auth; using CodeBeam.UltimateAuth.Server.Domain; +using CodeBeam.UltimateAuth.Server.Extensions; using CodeBeam.UltimateAuth.Server.Infrastructure; using CodeBeam.UltimateAuth.Server.Options; using CodeBeam.UltimateAuth.Tests.Unit.Helpers; @@ -28,7 +29,7 @@ public async Task ResolveAsync_ShouldResolveSessionCredential(UAuthMode mode) var (sut, context, transport) = CreateSut( mode, - CreateCredential(TransportCredentialKind.Session, SessionValue)); + CreateCredential(SurrogateKind.SessionId, SessionValue)); var result = await sut.ResolveAsync( context, @@ -38,20 +39,18 @@ public async Task ResolveAsync_ShouldResolveSessionCredential(UAuthMode mode) transport.Verify(x => x.ResolveAsync( context, - mode, - It.IsAny()), + It.IsAny()), Times.Once); } [Theory] [InlineData(UAuthMode.PureJwt)] [InlineData(UAuthMode.SemiHybrid)] - public async Task ResolveAsync_WhenJwtBasedMode_ShouldNotResolveSession( - UAuthMode mode) + public async Task ResolveAsync_WhenJwtBasedMode_ShouldNotResolveSession(UAuthMode mode) { var (sut, context, transport) = CreateSut( mode, - CreateCredential(TransportCredentialKind.Session, SessionValue)); + CreateCredential(SurrogateKind.SessionId, SessionValue)); var result = await sut.ResolveAsync( context, @@ -61,16 +60,14 @@ public async Task ResolveAsync_WhenJwtBasedMode_ShouldNotResolveSession( transport.Verify(x => x.ResolveAsync( It.IsAny(), - It.IsAny(), - It.IsAny()), + It.IsAny()), Times.Never); } [Theory] [InlineData(UAuthMode.PureOpaque)] [InlineData(UAuthMode.Hybrid)] - public async Task ResolveAsync_WhenCredentialIsMissing_ShouldReturnNull( - UAuthMode mode) + public async Task ResolveAsync_WhenCredentialIsMissing_ShouldReturnNull(UAuthMode mode) { var (sut, context, transport) = CreateSut(mode, null); @@ -82,21 +79,19 @@ public async Task ResolveAsync_WhenCredentialIsMissing_ShouldReturnNull( transport.Verify(x => x.ResolveAsync( context, - mode, - It.IsAny()), + It.IsAny()), Times.Once); } [Theory] [InlineData(UAuthMode.PureOpaque)] [InlineData(UAuthMode.Hybrid)] - public async Task ResolveAsync_WhenCredentialIsNotSession_ShouldReturnNull( - UAuthMode mode) + public async Task ResolveAsync_WhenCredentialIsNotSession_ShouldReturnNull(UAuthMode mode) { var (sut, context, _) = CreateSut( mode, CreateCredential( - TransportCredentialKind.AccessToken, + SurrogateKind.AccessToken, SessionValue)); var result = await sut.ResolveAsync( @@ -115,7 +110,7 @@ public async Task ResolveAsync_WhenSessionIdIsInvalid_ShouldReturnNull( { var (sut, context, _) = CreateSut( UAuthMode.PureOpaque, - CreateCredential(TransportCredentialKind.Session, value)); + CreateCredential(SurrogateKind.SessionId, value)); var result = await sut.ResolveAsync( context, @@ -127,15 +122,14 @@ public async Task ResolveAsync_WhenSessionIdIsInvalid_ShouldReturnNull( [Theory] [InlineData(UAuthMode.PureOpaque)] [InlineData(UAuthMode.Hybrid)] - public async Task ResolveAsync_ShouldUseEffectiveModeAndApplicationProfile( - UAuthMode mode) + public async Task ResolveAsync_ShouldUseEffectiveModeAndApplicationProfile(UAuthMode mode) { var context = new DefaultHttpContext(); var profileReader = new Mock(); var effectiveProvider = new Mock(); var responseResolver = new Mock(); - var transport = new Mock(); + var transport = new Mock(); var effective = new EffectiveUAuthServerOptions { @@ -161,9 +155,9 @@ public async Task ResolveAsync_ShouldUseEffectiveModeAndApplicationProfile( .Returns(response); transport - .Setup(x => x.ResolveAsync(context, mode, response)) + .Setup(x => x.ResolveAsync(context, response.SessionIdTransport)) .ReturnsAsync(CreateCredential( - TransportCredentialKind.Session, + SurrogateKind.SessionId, SessionValue)); var sut = new SessionIdResolver( @@ -191,22 +185,22 @@ public async Task ResolveAsync_ShouldUseEffectiveModeAndApplicationProfile( Times.Once); transport.Verify( - x => x.ResolveAsync(context, mode, response), + x => x.ResolveAsync(context, response.SessionIdTransport), Times.Once); } private static ( - SessionIdResolver Sut, - DefaultHttpContext Context, - Mock Transport) - CreateSut(UAuthMode mode, TransportCredential? credential) + SessionIdResolver Sut, + DefaultHttpContext Context, + Mock Transport) + CreateSut(UAuthMode mode, ResolvedSurrogate? surrogate) { var context = new DefaultHttpContext(); var profileReader = new Mock(); var effectiveProvider = new Mock(); var responseResolver = new Mock(); - var transport = new Mock(); + var transport = new Mock(); var effective = new EffectiveUAuthServerOptions { @@ -232,8 +226,10 @@ private static ( .Returns(response); transport - .Setup(x => x.ResolveAsync(context, mode, response)) - .ReturnsAsync(credential); + .Setup(x => x.ResolveAsync( + context, + response.SessionIdTransport)) + .ReturnsAsync(surrogate); var sut = new SessionIdResolver( profileReader.Object, @@ -247,24 +243,22 @@ private static ( private static EffectiveAuthResponse CreateResponse() { return new EffectiveAuthResponse( - new EffectiveGrantDelivery( - GrantKind.Session, + new EffectiveSurrogateTransport( + SurrogateKind.SessionId, TokenFormat.Opaque, - GrantDeliveryMode.Cookie, + SurrogateTransport.Cookie, cookie: new UAuthCookieOptions { Name = "uas" }), - EffectiveGrantDelivery.Disabled(GrantKind.AccessToken), - EffectiveGrantDelivery.Disabled(GrantKind.RefreshToken), + EffectiveSurrogateTransport.Disabled(SurrogateKind.AccessToken), + EffectiveSurrogateTransport.Disabled(SurrogateKind.RefreshToken), EffectiveRedirectResponse.Disabled); } - private static TransportCredential CreateCredential( - TransportCredentialKind kind, - string value) + private static ResolvedSurrogate CreateCredential(SurrogateKind kind, string value) { - return new TransportCredential + return new ResolvedSurrogate { Kind = kind, Value = value, diff --git a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/UAuthSessionIssuerTests.cs b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/UAuthSessionIssuerTests.cs index b6aa5829..66cf7ddc 100644 --- a/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/UAuthSessionIssuerTests.cs +++ b/tests/CodeBeam.UltimateAuth.Tests.Unit/Sessions/UAuthSessionIssuerTests.cs @@ -1776,8 +1776,8 @@ private static RotationSetup SetupSuccessfulRotation(Fixture fixture, SessionRot context.CurrentSessionId, root.SecurityVersion, credentialPurpose: context.Mode == UAuthMode.SemiHybrid - ? SessionCredentialPurpose.MetadataOnly - : SessionCredentialPurpose.Opaque); + ? SessionIdPurpose.MetadataOnly + : SessionIdPurpose.Opaque); chain = chain.AttachSession( oldSession.SessionId, @@ -1962,7 +1962,7 @@ private static UAuthSession CreateSession( DateTimeOffset createdAt, AuthSessionId? sessionId = null, long securityVersion = 0, - SessionCredentialPurpose credentialPurpose = SessionCredentialPurpose.Opaque) + SessionIdPurpose credentialPurpose = SessionIdPurpose.Opaque) { return UAuthSession.Create( sessionId ?? AuthSessionId.Parse(Guid.NewGuid().ToString(), null),