diff --git a/ReadMe.md b/ReadMe.md index e9810f4..7d2c326 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -32,7 +32,7 @@ Protect personal data | Protect personal user data in database by encrypt user d Role assignment routes accept a named request object such as `{ "roles": ["Admin"] }` rather than a bare string array. Bulk user-claim routes accept `{ "claims": [{ "type": "department", "value": "finance" }] }`. Role create and update routes accept `{ "role": { ... } }`; the nested role payload uses the consumer's configured role type so custom role fields remain available. These request shapes are versioned API changes for clients of those routes. Single-claim requests continue to use the named `ClaimDto` body, and the authentication, registration, verification, and password routes use named request DTOs. -An external identity with an untrusted email claim is rejected with the same generic authentication failure whether that email matches an existing account or not. An existing account is linked only when the configured email trust policy approves the provider claim. Identity operations do not expose cancellation overloads; endpoint handlers check request cancellation before starting them and finish in-flight writes. Identity provides no transaction spanning user creation and external-login linking, so if linking fails after creation the valid account remains; retrying with the same trusted provider can link it. The service does not delete or unlink records that a concurrent operation may already be using. +An external login whose email claim is not trusted is never matched to an existing account by email: the claim is ignored, and a new account is created without that email. Identity operations do not expose cancellation overloads; endpoint handlers check request cancellation before starting them and finish in-flight writes. See [External login policy](#external-login-policy) for account resolution, linking, unlinking, and the limits of the non-transactional design. `IUserManager` provides user lookup, create, update, delete, and principal lookup operations. For services that need specific capabilities, inject focused contracts such as `IUserPasswordManager`, `IUserEmailManager`, `IUserRoleManager`, or `IUserClaimManager`. `AddRuntimeAppsAuthentication()` registers these contracts to the same scoped `RuntimeAppsUserManager` instance. The concrete manager remains customizable: derive from `RuntimeAppsUserManager` and register it with `.AddUserManager()` after calling `AddRuntimeAppsAuthentication`. A manager registered directly as `UserManager` before the builder must also derive from `RuntimeAppsUserManager` to share the focused interfaces. @@ -152,6 +152,8 @@ In the backend, we provide some external login validators. each validator has a option.ClientId = builder.Configuration["Authentication:Facebook:AppId"]; option.ClientSecret = builder.Configuration["Authentication:Facebook:AppSecret"]; option.Mapper = (data) => FacebookExternalLoginOption>.UserIdentityMapper, int>(data); + // Facebook emails are trusted by default; set Never to stop relying on them. + // option.EmailTrust = ExternalLoginEmailTrustMode.Never; }) ``` @@ -162,6 +164,8 @@ In the backend, we provide some external login validators. each validator has a option.ClientId = builder.Configuration["Authentication:Microsoft:ClientId"]; option.ClientSecret = builder.Configuration["Authentication:Microsoft:ClientSecret"]; option.Mapper = (data) => MicrosoftExternalLoginOption>.UserIdentityMapper, int>(data); + // Microsoft emails are not trusted by default. Read "Email trust" before enabling Always. + // option.EmailTrust = ExternalLoginEmailTrustMode.Always; }) ``` @@ -338,9 +342,65 @@ Map `MapAdminUserApi()` separately from public registrati External provider login does not require a second email challenge by default. Set `RequireEmailVerificationForExternalLogins = true` to require email verification before issuing an application token when the provider email is not trusted. -External authentication and email confirmation remain separate. The default trust policy accepts verified Google Gmail/Googlemail addresses and verified Google Workspace addresses when the signed hosted-domain claim matches the email domain. Facebook and Microsoft email claims are not trusted by default. Developers can replace `IExternalLoginEmailTrustPolicy`. +#### Email trust -When the configured trust policy approves a provider's email claim, external login may automatically link that identity to a local account with the same email. Matching email alone is never sufficient: untrusted or unverified claims are rejected before the account lookup. Applications that do not want trusted-email auto-linking should use a trust policy that approves no claims and provide linking through an authenticated account-management flow. +Whether a provider's email claim is trusted decides two things: whether an existing local account with that email may be linked to the external identity, and whether a newly created account starts with a confirmed email. Each provider has an `EmailTrust` option: + +| Mode | Meaning | +| --- | --- | +| `Verified` | Trust only emails the provider asserts as verified. For Google this also requires a Gmail/Googlemail address, or an address in the token's signed hosted-domain claim. | +| `Always` | Trust any non-empty email claim from the provider. | +| `Never` | Never trust the provider's email claim. | + +| Provider | Default | Notes | +| --- | --- | --- | +| Google | `Verified` | Verified Gmail addresses and verified Workspace addresses that match the hosted domain. | +| Facebook | `Always` | Chosen so users are not blocked. Set `Never` if your application should not rely on Facebook's email claim. | +| Microsoft | `Never` | Microsoft email claims are mutable and are not proof of mailbox ownership, especially with the multi-tenant `common` endpoint. Enable `Always` only if you restrict sign-in to tenants you control and accept this risk. | + +```cs +.AddMicrosoftExternalLogin(builder.Configuration, option => option.EmailTrust = ExternalLoginEmailTrustMode.Never) +``` + +```json +"Authentication": { "ExternalLogin": { "Facebook": { "EmailTrust": "Never" } } } +``` + +Custom `IExternalLoginProvider` implementations keep the `Verified` behavior and are never trusted by the default policy; replace `IExternalLoginEmailTrustPolicy` to decide for them. + +#### How an external login resolves to an account + +1. If the external identity (provider and subject) is already linked, that account signs in. +2. Otherwise, if the email is trusted and an account with that email exists, the identity is linked to it. If that account's email was **never confirmed**, the account is first neutralized: its password is removed and its refresh tokens are revoked, then the login is linked and the email is marked confirmed. This prevents someone who registered an address they do not own from keeping access through the password they set. +3. Otherwise a new account is created. An email that is not trusted is ignored: it is not used for lookup and is not stored, so the outcome does not reveal whether that email belongs to an account. The user name falls back to `PROVIDER_subject` (the trusted email is still used as the user name when there is one). + +Failures return the same generic response and never reveal whether an account exists. If creating the account succeeds but linking the login fails, the new account is removed again; the removal is guarded by Identity's concurrency stamp, so an account that something else has modified is left in place. + +#### Managing linked logins + +`MapAccountManagementApi` also maps these authenticated endpoints when an external provider is registered: + +| Route | Purpose | +| --- | --- | +| `GET logins` | Lists the providers linked to the current account (provider names only). | +| `POST logins/link` | Links an identity: `{ "provider", "token", "currentPassword" }` or `{ "provider", "token", "reauthenticationProvider", "reauthenticationToken" }`. | +| `POST logins/unlink` | Unlinks a provider: `{ "provider" }`. | + +Linking requires fresh proof of control of the account: the current password (failures count toward lockout), or a fresh token from a provider that is already linked to the same account. The provider's email does not need to match the account email and is never copied onto it. An account can hold one identity per provider, and an identity that belongs to another account cannot be linked (409). Unlinking is refused with 409 when it would remove the last usable way to sign in, and revokes the account's refresh tokens. A password and linked providers can be used together; `POST password` is unchanged. Status codes: 400 invalid request, 401 not authenticated, 403 re-authentication failed, 409 conflict. + +Custom `IUserPasswordManager` implementations get a default `HasPasswordAsync` that returns `false`, so existing implementations still compile. Until you implement it, unlinking is refused and password re-authentication is rejected (fail closed). + +#### Limits + +ASP.NET Core Identity saves each manager call separately and this library adds no cross-store transaction. Multi-step operations are ordered so that a failure at any step leaves the account safe, and operations that can race are re-checked afterwards and undone. A process crash between two steps cannot be repaired automatically: for example, after the password of an unconfirmed account has been removed but before the login is linked, the account is left without a password and retrying the same trusted login completes the link. No schema change or migration is required. + +#### Upgrade notes + +- Facebook emails are now trusted by default (`Always`). To keep the previous behavior set `EmailTrust = ExternalLoginEmailTrustMode.Never`. +- Microsoft emails stay untrusted by default; set `EmailTrust` explicitly to opt in. +- An untrusted email no longer causes a login to be rejected: a new account is created without that email. Applications that need a verified email should keep `RequireEmailVerificationForExternalLogins = true`. +- A trusted login that matches an existing unconfirmed account now removes that account's password. +- `UserAccountService` keeps its existing constructors; `IExternalLoginService` is optional and composed automatically when it is not registered. ### Migration note diff --git a/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs b/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs index 2da988e..517af30 100644 --- a/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs +++ b/RuntimeApps.Authentication/DependencyInjection/FeatureRegistrationExtensions.cs @@ -143,6 +143,7 @@ private static RuntimeAppsAuthenticationBuilder AddProvider< o.Validate(x => !string.IsNullOrWhiteSpace(x.ClientId) && !string.IsNullOrWhiteSpace(x.ClientSecret), "External login requires ClientId and ClientSecret.").ValidateOnStart(); b.Services.TryAddEnumerable(ServiceDescriptor.Transient, TProvider>()); b.Services.TryAddScoped, DefaultExternalLoginEmailTrustPolicy>(); + b.Services.TryAddScoped, ExternalLoginService>(); return b; } private static class TOptionSection { public static string Name => typeof(T).Name.StartsWith("Google", StringComparison.Ordinal) ? "Authentication:ExternalLogin:Google" : typeof(T).Name.StartsWith("Facebook", StringComparison.Ordinal) ? "Authentication:ExternalLogin:Facebook" : "Authentication:ExternalLogin:Microsoft"; } diff --git a/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs index 4d7ead4..704d020 100644 --- a/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs @@ -260,6 +260,59 @@ public static IEndpointRouteBuilder MapAccountManagementApi() + ?.IsService(typeof(IExternalLoginService)) == true) { + authorizedRouteGroup.MapGet("logins", async Task (IUserManager userManager, IExternalLoginService externalLoginService, HttpContext httpContext, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); + var user = await userManager.GetUserAsync(httpContext.User); + if(user == null) + return TypedResults.Unauthorized(); + + cancellationToken.ThrowIfCancellationRequested(); + return TypedResults.Ok(await externalLoginService.ListLoginsAsync(user, cancellationToken)); + }).WithName("AccountManagement_ListExternalLogins").WithTags("Account management").WithSummary("List the external logins linked to the current account") + .Produces>(StatusCodes.Status200OK) + .Produces(StatusCodes.Status401Unauthorized) + .Produces(StatusCodes.Status403Forbidden); + + authorizedRouteGroup.MapPost("logins/link", async Task ([FromBody] LinkExternalLoginModel request, IUserManager userManager, IExternalLoginService externalLoginService, HttpContext httpContext, CancellationToken cancellationToken) => { + if(string.IsNullOrWhiteSpace(request?.Provider) || string.IsNullOrWhiteSpace(request.Token)) + return ValidationProblemFactory.CreateValidationProblem("InvalidExternalLogin", "Provider and token are required."); + cancellationToken.ThrowIfCancellationRequested(); + var user = await userManager.GetUserAsync(httpContext.User); + if(user == null) + return TypedResults.Unauthorized(); + + cancellationToken.ThrowIfCancellationRequested(); + var result = await externalLoginService.LinkAsync(user, request, cancellationToken); + return result.Succeeded ? TypedResults.Ok() : result.CreatePublicError(); + }).WithName("AccountManagement_LinkExternalLogin").WithTags("Account management").WithSummary("Link an external login to the current account after re-authentication") + .Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status401Unauthorized) + .Produces(StatusCodes.Status403Forbidden) + .Produces(StatusCodes.Status409Conflict); + + authorizedRouteGroup.MapPost("logins/unlink", async Task ([FromBody] UnlinkExternalLoginModel request, IUserManager userManager, IExternalLoginService externalLoginService, HttpContext httpContext, CancellationToken cancellationToken) => { + if(string.IsNullOrWhiteSpace(request?.Provider)) + return ValidationProblemFactory.CreateValidationProblem("InvalidExternalLogin", "Provider is required."); + cancellationToken.ThrowIfCancellationRequested(); + var user = await userManager.GetUserAsync(httpContext.User); + if(user == null) + return TypedResults.Unauthorized(); + + cancellationToken.ThrowIfCancellationRequested(); + var result = await externalLoginService.UnlinkAsync(user, request.Provider, cancellationToken); + return result.Succeeded ? TypedResults.Ok() : result.CreatePublicError(); + }).WithName("AccountManagement_UnlinkExternalLogin").WithTags("Account management").WithSummary("Unlink an external login unless it is the last authentication method") + .Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status401Unauthorized) + .Produces(StatusCodes.Status403Forbidden) + .Produces(StatusCodes.Status409Conflict); + } + return endpoints; } diff --git a/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs b/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs index 09d69a5..ed5d219 100644 --- a/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs +++ b/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs @@ -4,6 +4,7 @@ using Microsoft.Extensions.Options; using RuntimeApps.Authentication.Features.Account.Contracts; using RuntimeApps.Authentication.Features.ExternalLogin.Contracts; +using RuntimeApps.Authentication.Features.ExternalLogin.Services; using RuntimeApps.Authentication.Features.Verification.Contracts; using RuntimeApps.Authentication.Features.RefreshTokens.Contracts; using RuntimeApps.Authentication.Features.RefreshTokens.Models; @@ -15,12 +16,9 @@ public class UserAccountService: IUserAccountService where TUser : IdentityUser where TKey : IEquatable { private readonly IUserManager _userManager; - private readonly IUserLoginManager _loginManager; - private readonly IUserEmailManager _emailManager; private readonly ISignInManager _signInManager; private readonly Microsoft.AspNetCore.Http.IHttpContextAccessor _contextAccessor; - private readonly IEnumerable> _externalLoginProviders; - private readonly IExternalLoginEmailTrustPolicy _externalLoginEmailTrustPolicy; + private readonly IExternalLoginService _externalLoginService; private readonly VerificationOptions _verificationOptions; private readonly IVerificationWorkflowService _verificationWorkflow; private readonly IAuthenticationSessionIssuer _sessionIssuer; @@ -36,9 +34,39 @@ public UserAccountService(IUserManager userManager, IJwtProvider jwtUtils = null) : this(userManager, signInManager, externalLoginProviders, authenticationHandlerProvider, contextAccessor, userClaimsPrincipalFactory, authenticationSchemeProvider, - jwtUtils, null, null, null, null, null, null, null) { + jwtUtils, null, null, null, null, null, null, null, null) { } + // Preserve the previous public constructor signature for existing compiled consumers. It has no + // optional parameters so that calls with fewer arguments bind to the constructor below, which + // is also the one dependency injection selects. + public UserAccountService(IUserManager userManager, + ISignInManager signInManager, + IEnumerable> externalLoginProviders, + IAuthenticationHandlerProvider authenticationHandlerProvider, + IHttpContextAccessor contextAccessor, + IUserClaimsPrincipalFactory userClaimsPrincipalFactory, + IAuthenticationSchemeProvider authenticationSchemeProvider, + IJwtProvider jwtUtils, + IRefreshTokenService refreshTokenService, + IOptions refreshTokenOptions, + IExternalLoginEmailTrustPolicy externalLoginEmailTrustPolicy, + IOptions verificationOptions, + IVerificationWorkflowService verificationWorkflow, + IUserLoginManager loginManager, + IUserEmailManager emailManager, + IAuthenticationSessionIssuer sessionIssuer) + : this(userManager, signInManager, externalLoginProviders, authenticationHandlerProvider, + contextAccessor, userClaimsPrincipalFactory, authenticationSchemeProvider, + jwtUtils, refreshTokenService, refreshTokenOptions, externalLoginEmailTrustPolicy, + verificationOptions, verificationWorkflow, loginManager, emailManager, sessionIssuer, + (IExternalLoginService)null) { + } + + /// + /// Resolves accounts for external logins. When omitted, a default service is composed from the + /// other dependencies, so existing constructors and registrations keep working. + /// public UserAccountService(IUserManager userManager, ISignInManager signInManager, IEnumerable> externalLoginProviders, @@ -54,92 +82,32 @@ public UserAccountService(IUserManager userManager, IVerificationWorkflowService verificationWorkflow = null, IUserLoginManager loginManager = null, IUserEmailManager emailManager = null, - IAuthenticationSessionIssuer sessionIssuer = null) { + IAuthenticationSessionIssuer sessionIssuer = null, + IExternalLoginService externalLoginService = null) { _userManager = userManager; - _loginManager = loginManager ?? userManager as IUserLoginManager; - _emailManager = emailManager ?? userManager as IUserEmailManager; _signInManager = signInManager; - _externalLoginProviders = externalLoginProviders; _contextAccessor = contextAccessor; - _externalLoginEmailTrustPolicy = externalLoginEmailTrustPolicy; _verificationOptions = verificationOptions?.Value ?? new VerificationOptions(); _verificationWorkflow = verificationWorkflow; _sessionIssuer = sessionIssuer; + _externalLoginService = externalLoginService ?? new ExternalLoginService( + externalLoginProviders, + userManager, + loginManager ?? userManager as IUserLoginManager, + emailManager ?? userManager as IUserEmailManager, + userManager as IUserPasswordManager, + signInManager, + externalLoginEmailTrustPolicy, + verificationOptions, + refreshTokenService); } public virtual async Task> ExternalLoginAsync(string providerName, string token, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); - var provider = _externalLoginProviders.FirstOrDefault(p => string.Equals(p.Provider, providerName, StringComparison.OrdinalIgnoreCase)); - if(provider == null) - return ExternalAuthenticationFailed(); - - var providerResult = await provider.ValidateAsync(token, cancellationToken); - if(providerResult?.LoginInfo == null || providerResult.User == null) - return ExternalAuthenticationFailed(); - - cancellationToken.ThrowIfCancellationRequested(); - var loginInfo = providerResult.LoginInfo; - // Identity manager/store APIs used below have no CancellationToken overloads. - var user = await _loginManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey); - cancellationToken.ThrowIfCancellationRequested(); - if(user == null) { - var trustedEmail = _externalLoginEmailTrustPolicy?.IsEmailTrusted(provider.Provider, providerResult) == true; - // Do not look up an untrusted email and branch on whether it belongs to an - // account. Reject the same untrusted identity before either account path. - if((!string.IsNullOrWhiteSpace(providerResult.Email) && !trustedEmail) || - (_verificationOptions.RequireEmailVerificationForExternalLogins && !trustedEmail)) - return ExternalAuthenticationFailed(); - - var existingEmailUser = string.IsNullOrWhiteSpace(providerResult.Email) - ? null - : await _emailManager.FindByEmailAsync(providerResult.Email); - cancellationToken.ThrowIfCancellationRequested(); - - if(existingEmailUser != null) { - user = existingEmailUser; - var wasEmailConfirmed = user.EmailConfirmed; - // Link first. If the subsequent confirmation update fails, undo the link. - var addLoginResult = await _loginManager.AddLoginAsync(user, loginInfo); - if(!addLoginResult.Succeeded) - return ExternalAuthenticationFailed(); - - if(!wasEmailConfirmed) { - user.EmailConfirmed = true; - var updateResult = await _userManager.UpdateAsync(user); - if(!updateResult.Succeeded) { - user.EmailConfirmed = wasEmailConfirmed; - // The link is a complete, trusted Identity association. Keep it - // retryable if confirmation persistence fails instead of racing a - // concurrent login by compensating with RemoveLoginAsync. - return ExternalAuthenticationFailed(); - } - } - } else { - user = providerResult.User; - if(string.IsNullOrWhiteSpace(user.Email)) - user.Email = providerResult.Email; - if(string.IsNullOrWhiteSpace(user.UserName)) - user.UserName = !string.IsNullOrWhiteSpace(providerResult.Email) - ? providerResult.Email - : $"{provider.Provider}_{loginInfo.ProviderKey}"; - user.EmailConfirmed = trustedEmail; - - var createResult = await _userManager.CreateAsync(user); - if(!createResult.Succeeded) - return ExternalAuthenticationFailed(); - - var addLoginResult = await _loginManager.AddLoginAsync(user, loginInfo); - if(!addLoginResult.Succeeded) - // Identity exposes no transaction spanning user creation and external - // login linking. Leave the valid account in place: the same trusted - // provider retry can find it and attach the login. Deleting it here - // could race another operation that has already started using it. - return ExternalAuthenticationFailed(); - } - } - - if(user == null) + var resolved = await _externalLoginService.ResolveLoginAsync(providerName, token, cancellationToken); + if(!resolved.Succeeded || resolved.Data == null) return ExternalAuthenticationFailed(); + var user = resolved.Data; // The non-cancellable Identity writes above are now consistent. Honor cancellation // before sending verification or issuing an authentication session. diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Contracts/IExternalLoginService.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Contracts/IExternalLoginService.cs new file mode 100644 index 0000000..506174c --- /dev/null +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Contracts/IExternalLoginService.cs @@ -0,0 +1,29 @@ +using RuntimeApps.Authentication.Features.ExternalLogin.Models; +using RuntimeApps.Authentication.Shared.Models; +namespace RuntimeApps.Authentication.Features.ExternalLogin.Contracts { + /// + /// Resolves local accounts for validated external identities and manages the external logins of an + /// authenticated account. Login, link and unlink are separate operations. Provider token validation + /// stays in . + /// + /// + /// ASP.NET Core Identity manager calls used here do not accept cancellation tokens. Cancellation is + /// checked before writes begin and is not observed between dependent writes. + /// + public interface IExternalLoginService where TUser : class { + /// + /// Validates the provider token and returns the local account for it: an account already linked to + /// the identity, an existing account matched by a trusted email, or a newly created account. + /// Failures are deliberately generic. + /// + Task> ResolveLoginAsync(string provider, string token, CancellationToken cancellationToken = default); + + /// Links an external identity to after re-authentication. + Task LinkAsync(TUser user, LinkExternalLoginModel request, CancellationToken cancellationToken = default); + + /// Unlinks the provider's identity unless it is the account's last usable authentication method. + Task UnlinkAsync(TUser user, string provider, CancellationToken cancellationToken = default); + + Task> ListLoginsAsync(TUser user, CancellationToken cancellationToken = default); + } +} diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Models/BaseExternalLoginOption.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Models/BaseExternalLoginOption.cs index 839f7b7..4ee7506 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Models/BaseExternalLoginOption.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Models/BaseExternalLoginOption.cs @@ -2,5 +2,10 @@ namespace RuntimeApps.Authentication.Features.ExternalLogin.Models { public class BaseExternalLoginOption { public string ClientId { get; set; } public string ClientSecret { get; set; } + /// + /// Decides whether the default email trust policy accepts this provider's email claim. + /// Each provider option class sets its own default. + /// + public ExternalLoginEmailTrustMode EmailTrust { get; set; } = ExternalLoginEmailTrustMode.Verified; } } diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalLoginEmailTrustMode.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalLoginEmailTrustMode.cs new file mode 100644 index 0000000..0a96d60 --- /dev/null +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalLoginEmailTrustMode.cs @@ -0,0 +1,22 @@ +namespace RuntimeApps.Authentication.Features.ExternalLogin.Models { + /// + /// Controls whether accepts the + /// email claim returned by an external provider. A trusted email may be used to link the external + /// identity to an existing local account and to create a confirmed account. + /// + public enum ExternalLoginEmailTrustMode { + /// + /// Trust only email claims the provider asserts are verified. Google additionally requires a + /// Gmail/Googlemail address or an address in the token's hosted domain. Providers that do not + /// assert verification (and custom providers) are never trusted in this mode. + /// + Verified = 0, + /// + /// Trust any non-empty email claim from the provider. Use only when the provider guarantees that + /// the claim proves mailbox ownership. + /// + Always = 1, + /// Never trust email claims from the provider. + Never = 2 + } +} diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalLoginProviderResult.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalLoginProviderResult.cs index 3c05871..c3a85a8 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalLoginProviderResult.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalLoginProviderResult.cs @@ -7,5 +7,7 @@ public sealed class ExternalLoginProviderResult where TUser : class { public string Email { get; init; } public bool EmailVerified { get; init; } public string HostedDomain { get; init; } + /// How the default trust policy should treat . Set from the provider's options. + public ExternalLoginEmailTrustMode EmailTrustMode { get; init; } = ExternalLoginEmailTrustMode.Verified; } } diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalLoginSummary.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalLoginSummary.cs new file mode 100644 index 0000000..06661e8 --- /dev/null +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalLoginSummary.cs @@ -0,0 +1,6 @@ +namespace RuntimeApps.Authentication.Features.ExternalLogin.Models { + /// A linked external login as shown to the account owner. Provider subject keys are never exposed. + public class ExternalLoginSummary { + public string Provider { get; set; } + } +} diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Models/FacebookExternalLoginOption.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Models/FacebookExternalLoginOption.cs index 56fcd6a..037691d 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Models/FacebookExternalLoginOption.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Models/FacebookExternalLoginOption.cs @@ -5,6 +5,12 @@ namespace RuntimeApps.Authentication.Features.ExternalLogin.Models { public class FacebookExternalLoginOption : BaseExternalLoginOption where TUser : class, new() { + public FacebookExternalLoginOption() { + // Trusted by default so users are not blocked. Applications that do not want to rely on + // Facebook's email claim should set EmailTrust to Never. + EmailTrust = ExternalLoginEmailTrustMode.Always; + } + public string AccessTokenUrl { get; set; } = "https://graph.facebook.com/oauth/access_token?client_id={0}&client_secret={1}&grant_type=client_credentials"; public string DebugTokenUrl { get; set; } = "https://graph.facebook.com/debug_token?input_token={0}&access_token={1}"; public string GraphApiVersion { get; set; } = "v27.0"; diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Models/LinkExternalLoginModel.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Models/LinkExternalLoginModel.cs new file mode 100644 index 0000000..596bc94 --- /dev/null +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Models/LinkExternalLoginModel.cs @@ -0,0 +1,21 @@ +using System.ComponentModel.DataAnnotations; + +namespace RuntimeApps.Authentication.Features.ExternalLogin.Models { + /// + /// Request to link an external identity to the signed-in account. Linking requires fresh proof of + /// control of the account: the current password, or a fresh token from a provider that is already + /// linked to the account. + /// + public class LinkExternalLoginModel { + [Required] + public string Provider { get; set; } + [Required] + public string Token { get; set; } + /// Current password of the account. Accepted as re-authentication when the account has a password. + public string CurrentPassword { get; set; } + /// Provider of an already-linked identity used for re-authentication. + public string ReauthenticationProvider { get; set; } + /// Fresh token from . + public string ReauthenticationToken { get; set; } + } +} diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Models/MicrosoftExternalLoginOption.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Models/MicrosoftExternalLoginOption.cs index 8f65fb4..18ecb2e 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Models/MicrosoftExternalLoginOption.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Models/MicrosoftExternalLoginOption.cs @@ -5,6 +5,12 @@ namespace RuntimeApps.Authentication.Features.ExternalLogin.Models { public class MicrosoftExternalLoginOption: BaseExternalLoginOption where TUser : class, new() { + public MicrosoftExternalLoginOption() { + // Microsoft email claims are mutable and are not proof of mailbox ownership, especially with + // the multi-tenant "common" endpoint. Applications opt in explicitly (see the README). + EmailTrust = ExternalLoginEmailTrustMode.Never; + } + public string IssuerEndpoint { get; set; } = "https://login.microsoftonline.com/common/v2.0/"; public string ConfigurationAddress { get; set; } = "/.well-known/openid-configuration"; public Func Mapper { get; set; } = (data) => new TUser(); diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Models/UnlinkExternalLoginModel.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Models/UnlinkExternalLoginModel.cs new file mode 100644 index 0000000..1739314 --- /dev/null +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Models/UnlinkExternalLoginModel.cs @@ -0,0 +1,9 @@ +using System.ComponentModel.DataAnnotations; + +namespace RuntimeApps.Authentication.Features.ExternalLogin.Models { + /// Request to unlink the external identity of a provider from the signed-in account. + public class UnlinkExternalLoginModel { + [Required] + public string Provider { get; set; } + } +} diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Providers/FacebookExternalLoginProvider.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Providers/FacebookExternalLoginProvider.cs index 25e4fcc..3d703de 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Providers/FacebookExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Providers/FacebookExternalLoginProvider.cs @@ -70,8 +70,10 @@ public async Task> ValidateAsync(string token LoginInfo = new UserLoginInfo(Provider, userInfo.Id.Value.ToString(CultureInfo.InvariantCulture), Provider), Email = userInfo.Email, - // Facebook's current response model does not provide a trustworthy email-verified assertion. - EmailVerified = false + // Facebook's current response model does not provide an email-verified assertion. + // Whether the email is trusted is decided by EmailTrust. + EmailVerified = false, + EmailTrustMode = option.EmailTrust }; } catch(OperationCanceledException) { throw; diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Providers/GoogleExternalLoginProvider.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Providers/GoogleExternalLoginProvider.cs index e5bd94d..130f22d 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Providers/GoogleExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Providers/GoogleExternalLoginProvider.cs @@ -19,6 +19,19 @@ public GoogleExternalLoginProvider( public string Provider => "GOOGLE"; + /// + /// Validates the Google ID token's signature, issuer, expiry and audience. The default + /// implementation delegates to with the configured client ID + /// as the only accepted audience. Overridable so the provider's own handling can be tested without + /// reaching Google's certificate endpoint. + /// + protected virtual Task ValidatePayloadAsync( + string token, string audience, CancellationToken cancellationToken) => + GoogleJsonWebSignature.ValidateAsync(token, + new GoogleJsonWebSignature.ValidationSettings { + Audience = new[] { audience } + }); + /// The Google token validation library does not expose cancellation. Cancellation is checked before validation begins. public async Task> ValidateAsync(string token, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); @@ -27,12 +40,9 @@ public async Task> ValidateAsync(string token return null; try { - var payload = await GoogleJsonWebSignature.ValidateAsync(token, - new GoogleJsonWebSignature.ValidationSettings { - Audience = new[] { option.ClientId } - }); + var payload = await ValidatePayloadAsync(token, option.ClientId, cancellationToken); - if(string.IsNullOrWhiteSpace(payload.Subject)) + if(payload == null || string.IsNullOrWhiteSpace(payload.Subject)) return null; var user = option.Mapper(payload); @@ -44,7 +54,8 @@ public async Task> ValidateAsync(string token LoginInfo = new UserLoginInfo(Provider, payload.Subject, Provider), Email = payload.Email, EmailVerified = payload.EmailVerified, - HostedDomain = payload.HostedDomain + HostedDomain = payload.HostedDomain, + EmailTrustMode = option.EmailTrust }; } catch(OperationCanceledException) { throw; diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Providers/MicrosoftExternalLoginProvider.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Providers/MicrosoftExternalLoginProvider.cs index b9e3702..d761c0d 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Providers/MicrosoftExternalLoginProvider.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Providers/MicrosoftExternalLoginProvider.cs @@ -82,7 +82,8 @@ public async Task> ValidateAsync(string token LoginInfo = new UserLoginInfo(Provider, $"{tenantIdClaim}:{objectId}", Provider), Email = jwtToken.Claims.FirstOrDefault(claim => claim.Type == "email")?.Value, // Microsoft email claims are mutable and do not prove mailbox ownership. - EmailVerified = false + EmailVerified = false, + EmailTrustMode = option.EmailTrust }; } catch(OperationCanceledException) { throw; diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Services/DefaultExternalLoginEmailTrustPolicy.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Services/DefaultExternalLoginEmailTrustPolicy.cs index 3db5092..5f5fce7 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Services/DefaultExternalLoginEmailTrustPolicy.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Services/DefaultExternalLoginEmailTrustPolicy.cs @@ -2,13 +2,29 @@ using RuntimeApps.Authentication.Features.ExternalLogin.Models; namespace RuntimeApps.Authentication.Features.ExternalLogin.Services { /// - /// Trusts verified Google Gmail/Googlemail addresses and verified Google Workspace addresses - /// whose email domain matches the token's hosted-domain claim. Other providers require a custom policy. + /// Applies the provider's , carried on the validated result. + /// + /// : no email is trusted. + /// : any non-empty email is trusted. + /// : trusts verified Google Gmail/Googlemail addresses + /// and verified Google Workspace addresses whose email domain matches the token's hosted-domain claim. + /// Other providers require a custom policy or a different mode. + /// /// public sealed class DefaultExternalLoginEmailTrustPolicy: IExternalLoginEmailTrustPolicy where TUser : class { public bool IsEmailTrusted(string provider, ExternalLoginProviderResult result) { - if(result == null || !result.EmailVerified || string.IsNullOrWhiteSpace(result.Email) || + if(result == null || string.IsNullOrWhiteSpace(result.Email)) + return false; + + switch(result.EmailTrustMode) { + case ExternalLoginEmailTrustMode.Never: + return false; + case ExternalLoginEmailTrustMode.Always: + return true; + } + + if(!result.EmailVerified || !string.Equals(provider, "GOOGLE", StringComparison.OrdinalIgnoreCase)) return false; diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Services/ExternalLoginService.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Services/ExternalLoginService.cs new file mode 100644 index 0000000..e4d7c36 --- /dev/null +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Services/ExternalLoginService.cs @@ -0,0 +1,311 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging; +using Microsoft.Extensions.Options; +using RuntimeApps.Authentication.Features.ExternalLogin.Contracts; +using RuntimeApps.Authentication.Features.ExternalLogin.Models; +using RuntimeApps.Authentication.Features.RefreshTokens.Contracts; +using RuntimeApps.Authentication.Features.Verification.Models; +using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Shared.Models; +namespace RuntimeApps.Authentication.Features.ExternalLogin.Services { + /// + /// Default . + /// + /// ASP.NET Core Identity saves each manager call separately and this library has no cross-store + /// transaction, so multi-step operations are ordered so that a failure at any step leaves the account + /// safe, and operations that can race are re-checked afterwards and undone. A crash between two steps + /// cannot be repaired by this service. + /// + /// + public class ExternalLoginService: IExternalLoginService + where TUser : IdentityUser + where TKey : IEquatable { + private const string GenericFailureCode = "ExternalAuthenticationFailed"; + private const string GenericFailureDescription = "External authentication could not be completed."; + + private readonly IEnumerable> _providers; + private readonly IUserManager _userManager; + private readonly IUserLoginManager _loginManager; + private readonly IUserEmailManager _emailManager; + private readonly IUserPasswordManager _passwordManager; + private readonly ISignInManager _signInManager; + private readonly IExternalLoginEmailTrustPolicy _trustPolicy; + private readonly bool _requireEmailVerification; + private readonly IRefreshTokenService _refreshTokenService; + private readonly ILogger _logger; + + public ExternalLoginService(IEnumerable> providers, + IUserManager userManager, + IUserLoginManager loginManager, + IUserEmailManager emailManager, + IUserPasswordManager passwordManager, + ISignInManager signInManager, + IExternalLoginEmailTrustPolicy trustPolicy = null, + IOptions verificationOptions = null, + IRefreshTokenService refreshTokenService = null, + ILogger> logger = null) { + _providers = providers; + _userManager = userManager; + _loginManager = loginManager; + _emailManager = emailManager; + _passwordManager = passwordManager; + _signInManager = signInManager; + _trustPolicy = trustPolicy; + _requireEmailVerification = verificationOptions?.Value?.RequireEmailVerificationForExternalLogins ?? false; + _refreshTokenService = refreshTokenService; + _logger = logger; + } + + public virtual async Task> ResolveLoginAsync(string providerName, string token, CancellationToken cancellationToken = default) { + cancellationToken.ThrowIfCancellationRequested(); + var provider = FindProvider(providerName); + if(provider == null) + return ResolveFailed(); + + var providerResult = await provider.ValidateAsync(token, cancellationToken); + if(providerResult?.LoginInfo == null || providerResult.User == null) + return ResolveFailed(); + + cancellationToken.ThrowIfCancellationRequested(); + var loginInfo = providerResult.LoginInfo; + // Identity manager/store APIs used below have no CancellationToken overloads. + var user = await _loginManager.FindByLoginAsync(loginInfo.LoginProvider, loginInfo.ProviderKey); + cancellationToken.ThrowIfCancellationRequested(); + if(user != null) + return new Result(user); + + var trustedEmail = _trustPolicy?.IsEmailTrusted(provider.Provider, providerResult) == true; + if(_requireEmailVerification && !trustedEmail) + return ResolveFailed(); + + // An email the policy does not trust is ignored: it is never used to find an account and is + // never stored, so the outcome cannot reveal whether it belongs to an account. + var email = trustedEmail && !string.IsNullOrWhiteSpace(providerResult.Email) ? providerResult.Email : null; + var existingEmailUser = email == null ? null : await _emailManager.FindByEmailAsync(email); + cancellationToken.ThrowIfCancellationRequested(); + + return existingEmailUser != null + ? await LinkExistingAccountAsync(existingEmailUser, loginInfo) + : await CreateAccountAsync(provider.Provider, providerResult, loginInfo, email, trustedEmail); + } + + public virtual async Task LinkAsync(TUser user, LinkExternalLoginModel request, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(user); + cancellationToken.ThrowIfCancellationRequested(); + if(string.IsNullOrWhiteSpace(request?.Provider) || string.IsNullOrWhiteSpace(request.Token)) + return Fail(ResultCode.BadRequest, "InvalidExternalLogin", "Provider and token are required."); + + if(!await IsReauthenticatedAsync(user, request, cancellationToken)) + return Fail(ResultCode.Forbidden, "ReauthenticationRequired", + "Re-authentication is required to link an external login."); + + cancellationToken.ThrowIfCancellationRequested(); + var provider = FindProvider(request.Provider); + if(provider == null) + return Fail(ResultCode.BadRequest, GenericFailureCode, GenericFailureDescription); + + // Only the validated provider subject is used. The provider's email, verified or not, is neither + // required to match the account nor copied onto it. + var identity = await provider.ValidateAsync(request.Token, cancellationToken); + if(identity?.LoginInfo == null) + return Fail(ResultCode.BadRequest, GenericFailureCode, GenericFailureDescription); + + cancellationToken.ThrowIfCancellationRequested(); + var loginInfo = identity.LoginInfo; + // One identity per provider per account. + var existing = await _loginManager.GetLoginsAsync(user); + if(existing.Any(login => SameProvider(login.LoginProvider, loginInfo.LoginProvider))) + return Fail(ResultCode.Conflict, "ExternalLoginConflict", "The external login could not be linked."); + + var added = await _loginManager.AddLoginAsync(user, loginInfo); + if(!added.Succeeded) + return added.Errors.Any(error => error.Code == "LoginAlreadyAssociated") + ? Fail(ResultCode.Conflict, "ExternalLoginConflict", "The external login could not be linked.") + : Fail(ResultCode.BadRequest, GenericFailureCode, GenericFailureDescription); + + // Two concurrent links of different identities for one provider can both pass the check above. + var after = await _loginManager.GetLoginsAsync(user); + if(after.Count(login => SameProvider(login.LoginProvider, loginInfo.LoginProvider)) > 1) { + await _loginManager.RemoveLoginAsync(user, loginInfo.LoginProvider, loginInfo.ProviderKey); + return Fail(ResultCode.Conflict, "ExternalLoginConflict", "The external login could not be linked."); + } + + return new Result(); + } + + public virtual async Task UnlinkAsync(TUser user, string providerName, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(user); + cancellationToken.ThrowIfCancellationRequested(); + if(string.IsNullOrWhiteSpace(providerName)) + return Fail(ResultCode.BadRequest, "InvalidExternalLogin", "Provider is required."); + + var logins = await _loginManager.GetLoginsAsync(user); + var matches = logins.Where(login => SameProvider(login.LoginProvider, providerName)).ToList(); + if(matches.Count == 0) + return Fail(ResultCode.BadRequest, "ExternalLoginNotLinked", "The external login is not linked to this account."); + if(matches.Count > 1) + return Fail(ResultCode.Conflict, "ExternalLoginAmbiguous", "The external login could not be unlinked."); + + var target = matches[0]; + var otherLogins = logins.Where(login => !ReferenceEquals(login, target)); + if(!await HasUsableMethodAsync(user, otherLogins)) + return Fail(ResultCode.Conflict, "LastAuthenticationMethod", + "The last authentication method of the account cannot be removed."); + + var removed = await _loginManager.RemoveLoginAsync(user, target.LoginProvider, target.ProviderKey); + if(!removed.Succeeded) + return Fail(ResultCode.BadRequest, "ExternalLoginNotUnlinked", "The external login could not be unlinked."); + + // Concurrent unlinks can each pass the check above. Re-check and restore the login so the + // account is never left without a way to sign in; concurrent requests fail instead. + if(!await HasUsableMethodAsync(user, await _loginManager.GetLoginsAsync(user))) { + var restored = await _loginManager.AddLoginAsync(user, target); + if(!restored.Succeeded) + _logger?.LogError("Restoring an external login after a rejected unlink failed for provider {Provider}.", target.LoginProvider); + return Fail(ResultCode.Conflict, "LastAuthenticationMethod", + "The last authentication method of the account cannot be removed."); + } + + await RevokeSessionsAsync(user); + return new Result(); + } + + public virtual async Task> ListLoginsAsync(TUser user, CancellationToken cancellationToken = default) { + ArgumentNullException.ThrowIfNull(user); + cancellationToken.ThrowIfCancellationRequested(); + var logins = await _loginManager.GetLoginsAsync(user); + return logins.Select(login => new ExternalLoginSummary { Provider = login.LoginProvider }).ToList(); + } + + private async Task> LinkExistingAccountAsync(TUser existing, UserLoginInfo loginInfo) { + var wasConfirmed = existing.EmailConfirmed; + if(!wasConfirmed) { + // The account was registered with this email but the email was never verified, so whoever + // registered it may not own the mailbox and may know its password. Make the account safe + // before attaching the verified identity. Each step leaves the account safe if a later + // one fails, and a retry of the same login repeats them. + if(_passwordManager == null) + return ResolveFailed(); + var removed = await _passwordManager.RemovePasswordAsync(existing); + if(removed?.Succeeded != true) + return ResolveFailed(); + await RevokeSessionsAsync(existing); + } + + var added = await _loginManager.AddLoginAsync(existing, loginInfo); + if(added?.Succeeded != true) + return ResolveFailed(); + + if(!wasConfirmed) { + existing.EmailConfirmed = true; + var updated = await _userManager.UpdateAsync(existing); + if(updated?.Succeeded != true) { + existing.EmailConfirmed = false; + // The link is complete and the account no longer has a password. Keep both so the + // same trusted login can be retried instead of racing a concurrent login. + return ResolveFailed(); + } + } + + return new Result(existing); + } + + private async Task> CreateAccountAsync(string providerName, + ExternalLoginProviderResult providerResult, + UserLoginInfo loginInfo, + string trustedEmail, + bool trusted) { + var user = providerResult.User; + if(trustedEmail == null) { + // Mappers commonly copy the claim into Email and UserName. An untrusted claim is not stored. + if(string.Equals(user.UserName, providerResult.Email, StringComparison.OrdinalIgnoreCase)) + user.UserName = null; + user.Email = null; + } else if(string.IsNullOrWhiteSpace(user.Email)) { + user.Email = trustedEmail; + } + + if(string.IsNullOrWhiteSpace(user.UserName)) + user.UserName = trustedEmail ?? $"{providerName}_{loginInfo.ProviderKey}"; + user.EmailConfirmed = trusted && trustedEmail != null; + + var created = await _userManager.CreateAsync(user); + if(created?.Succeeded != true) + return ResolveFailed(); + + var added = await _loginManager.AddLoginAsync(user, loginInfo); + if(added?.Succeeded != true) { + await TryDeleteAsync(user); + return ResolveFailed(); + } + + return new Result(user); + } + + /// + /// Removes the account created by the current operation after its login could not be attached. + /// Identity's delete is guarded by the concurrency stamp, so an account that something else has + /// already modified is left in place. + /// + private async Task TryDeleteAsync(TUser user) { + try { + var deleted = await _userManager.DeleteAsync(user); + if(deleted?.Succeeded != true) + _logger?.LogWarning("Removing an account whose external login could not be attached did not succeed."); + } catch(Exception exception) when(exception is not OperationCanceledException) { + _logger?.LogWarning("Removing an account whose external login could not be attached failed. Exception type: {ExceptionType}.", + exception.GetType().FullName); + } + } + + private async Task IsReauthenticatedAsync(TUser user, LinkExternalLoginModel request, CancellationToken cancellationToken) { + if(!string.IsNullOrEmpty(request.CurrentPassword)) { + if(_passwordManager == null || !await _passwordManager.HasPasswordAsync(user)) + return false; + // Counts failures toward lockout, like a password sign-in. + var check = await _signInManager.CheckPasswordSignInAsync(user, request.CurrentPassword, true); + return check?.Succeeded == true; + } + + if(!string.IsNullOrWhiteSpace(request.ReauthenticationProvider) && !string.IsNullOrWhiteSpace(request.ReauthenticationToken)) { + var provider = FindProvider(request.ReauthenticationProvider); + if(provider == null) + return false; + var identity = await provider.ValidateAsync(request.ReauthenticationToken, cancellationToken); + if(identity?.LoginInfo == null) + return false; + // The fresh identity must be one that is already linked to this very account. + var logins = await _loginManager.GetLoginsAsync(user); + return logins.Any(login => + SameProvider(login.LoginProvider, identity.LoginInfo.LoginProvider) && + string.Equals(login.ProviderKey, identity.LoginInfo.ProviderKey, StringComparison.Ordinal)); + } + + return false; + } + + /// A usable method is a password, or a linked login whose provider is still registered. + private async Task HasUsableMethodAsync(TUser user, IEnumerable logins) { + if(_passwordManager != null && await _passwordManager.HasPasswordAsync(user)) + return true; + return logins.Any(login => _providers.Any(provider => SameProvider(provider.Provider, login.LoginProvider))); + } + + private async Task RevokeSessionsAsync(TUser user) { + if(_refreshTokenService != null) + await _refreshTokenService.RevokeAllAsync(user.Id, CancellationToken.None); + } + + private IExternalLoginProvider FindProvider(string providerName) => + _providers.FirstOrDefault(provider => SameProvider(provider.Provider, providerName)); + + private static bool SameProvider(string left, string right) => + string.Equals(left, right, StringComparison.OrdinalIgnoreCase); + + private static Result ResolveFailed() => + new(ResultCode.BadRequest, Result.CreateErrors(GenericFailureCode, GenericFailureDescription)); + + private static Result Fail(ResultCode code, string errorCode, string description) => + new(code, Result.CreateErrors(errorCode, description)); + } +} diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserPasswordManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserPasswordManager.cs index 7f6a863..ce2dd11 100644 --- a/RuntimeApps.Authentication/Identity/Contracts/IUserPasswordManager.cs +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserPasswordManager.cs @@ -4,6 +4,12 @@ namespace RuntimeApps.Authentication.Identity.Contracts { /// Identity password operations do not accept cancellation tokens; callers check before writing and finish essential session revocation afterward. public interface IUserPasswordManager where TUser : class { Task CheckPasswordAsync(TUser user, string password); + /// + /// Whether the account has a password. Satisfied by UserManager<TUser>.HasPasswordAsync in + /// RuntimeAppsUserManager. The default returns false so a custom manager that does not + /// implement it fails closed: external-login unlinking is refused and password re-authentication is rejected. + /// + Task HasPasswordAsync(TUser user); Task AddPasswordAsync(TUser user, string password); Task ChangePasswordAsync(TUser user, string currentPassword, string newPassword); Task RemovePasswordAsync(TUser user); diff --git a/Samples/RuntimeApps.Authentication.Sample/ReadMe.md b/Samples/RuntimeApps.Authentication.Sample/ReadMe.md index 900f818..e2b084b 100644 --- a/Samples/RuntimeApps.Authentication.Sample/ReadMe.md +++ b/Samples/RuntimeApps.Authentication.Sample/ReadMe.md @@ -101,6 +101,15 @@ app.MapGroup("api").MapVerificationApi(); app.MapGroup("api/account").MapAccountManagementApi(); ``` +When an external login provider is registered, `MapAccountManagementApi` also exposes `GET api/account/logins`, +`POST api/account/logins/link` and `POST api/account/logins/unlink` for the signed-in user. Linking needs the +current password or a fresh token from an already linked provider. + +## External login email trust + +`appsettings.json` shows the default `Authentication:ExternalLogin::EmailTrust` values (`Verified`, `Always`, +`Never`). A trusted email can link an external identity to an existing account with the same email; Microsoft emails +are not trusted by default. See the repository ReadMe, "External login policy", before changing them. ## Email verification diff --git a/Samples/RuntimeApps.Authentication.Sample/appsettings.json b/Samples/RuntimeApps.Authentication.Sample/appsettings.json index db297b7..eb5ff0e 100644 --- a/Samples/RuntimeApps.Authentication.Sample/appsettings.json +++ b/Samples/RuntimeApps.Authentication.Sample/appsettings.json @@ -40,6 +40,11 @@ "FromName": "RuntimeApps Authentication Sample" } }, + "ExternalLogin": { + "Google": { "EmailTrust": "Verified" }, + "Facebook": { "EmailTrust": "Always" }, + "Microsoft": { "EmailTrust": "Never" } + }, "ForgotPassword": { "Method": "VerificationCode" }, diff --git a/Tests/RuntimeApps.Authentication.Test/AccountExternalLoginEndpointTest.cs b/Tests/RuntimeApps.Authentication.Test/AccountExternalLoginEndpointTest.cs new file mode 100644 index 0000000..0c8e8a8 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/AccountExternalLoginEndpointTest.cs @@ -0,0 +1,214 @@ +using System.Text; +using Microsoft.AspNetCore.Authorization; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using RuntimeApps.Authentication.Endpoints.Account; +using RuntimeApps.Authentication.Features.Account.Contracts; +using RuntimeApps.Authentication.Features.ExternalLogin.Contracts; +using RuntimeApps.Authentication.Features.ExternalLogin.Models; +using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Shared.Models; + +namespace RuntimeApps.Authentication.Test; + +/// HTTP contract of the authenticated external-login management endpoints. +public sealed class AccountExternalLoginEndpointTest { + private readonly Mock>> _service = new(); + private readonly Mock>> _userManager = new(); + private readonly IdentityUser _user = new() { Id = 7 }; + + public AccountExternalLoginEndpointTest() { + _userManager.Setup(m => m.GetUserAsync(It.IsAny())).ReturnsAsync(_user); + } + + private IServiceProvider Services(bool includeExternalLoginService = true) { + var services = new ServiceCollection(); + services.AddLogging().AddProblemDetails(); + services.AddSingleton(_userManager.Object); + services.AddSingleton(Mock.Of, Dto>>()); + services.AddSingleton(Mock.Of>>()); + if(includeExternalLoginService) + services.AddSingleton(_service.Object); + return services.BuildServiceProvider(); + } + + private static RouteEndpoint[] Map(IServiceProvider services) { + var builder = new Builder(services); + builder.MapGroup("api/account").MapAccountManagementApi, Dto, int>(); + return builder.DataSources.SelectMany(source => source.Endpoints).OfType().ToArray(); + } + + private static RouteEndpoint Route(RouteEndpoint[] endpoints, string route) => + endpoints.Single(endpoint => endpoint.RoutePattern.RawText == route); + + private static async Task<(int Status, string Body)> Send(RouteEndpoint endpoint, IServiceProvider services, string method, string json = null) { + var context = new DefaultHttpContext { RequestServices = services }; + context.Request.Method = method; + if(json != null) { + var bytes = Encoding.UTF8.GetBytes(json); + context.Request.ContentType = "application/json"; + context.Request.Body = new MemoryStream(bytes); + context.Request.ContentLength = bytes.Length; + context.Features.Set(new BodyFeature()); + } + await using var response = new MemoryStream(); + context.Response.Body = response; + await endpoint.RequestDelegate!(context); + response.Position = 0; + return (context.Response.StatusCode, await new StreamReader(response).ReadToEndAsync()); + } + + [Fact] + public void ExternalLoginRoutes_AreMappedOnlyWhenTheServiceIsRegistered() { + var unmapped = Map(Services(includeExternalLoginService: false)).Select(e => e.RoutePattern.RawText).ToArray(); + var mapped = Map(Services()).Select(e => e.RoutePattern.RawText).ToArray(); + + Assert.DoesNotContain(unmapped, route => route.Contains("logins", StringComparison.Ordinal)); + Assert.Contains("api/account/logins", mapped); + Assert.Contains("api/account/logins/link", mapped); + Assert.Contains("api/account/logins/unlink", mapped); + } + + [Fact] + public void ExternalLoginRoutes_RequireAuthorizationAndDeclareErrorContracts() { + var endpoints = Map(Services()); + + foreach(var route in new[] { "api/account/logins", "api/account/logins/link", "api/account/logins/unlink" }) { + var endpoint = Route(endpoints, route); + Assert.NotEmpty(endpoint.Metadata.GetOrderedMetadata()); + Assert.Null(endpoint.Metadata.GetMetadata()); + var statuses = endpoint.Metadata.GetOrderedMetadata() + .Select(metadata => metadata.StatusCode).ToArray(); + Assert.Contains(StatusCodes.Status401Unauthorized, statuses); + Assert.Contains(StatusCodes.Status403Forbidden, statuses); + } + + var linkStatuses = Route(endpoints, "api/account/logins/link").Metadata + .GetOrderedMetadata().Select(m => m.StatusCode).ToArray(); + Assert.Contains(StatusCodes.Status409Conflict, linkStatuses); + Assert.Contains(StatusCodes.Status400BadRequest, linkStatuses); + } + + [Fact] + public async Task List_ReturnsProvidersForCurrentAccount() { + _service.Setup(s => s.ListLoginsAsync(_user, It.IsAny())) + .ReturnsAsync(new List { new() { Provider = "GOOGLE" } }); + var services = Services(); + + var response = await Send(Route(Map(services), "api/account/logins"), services, "GET"); + + Assert.Equal(StatusCodes.Status200OK, response.Status); + Assert.Contains("GOOGLE", response.Body); + } + + [Fact] + public async Task List_UnknownCurrentUser_Returns401() { + _userManager.Setup(m => m.GetUserAsync(It.IsAny())).ReturnsAsync((IdentityUser)null); + var services = Services(); + + var response = await Send(Route(Map(services), "api/account/logins"), services, "GET"); + + Assert.Equal(StatusCodes.Status401Unauthorized, response.Status); + _service.Verify(s => s.ListLoginsAsync(It.IsAny>(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Link_Success_Returns200() { + _service.Setup(s => s.LinkAsync(_user, It.Is(m => m.Provider == "MICROSOFT" && m.CurrentPassword == "pw"), It.IsAny())) + .ReturnsAsync(new Result()); + var services = Services(); + + var response = await Send(Route(Map(services), "api/account/logins/link"), services, "POST", + "{\"Provider\":\"MICROSOFT\",\"Token\":\"t\",\"CurrentPassword\":\"pw\"}"); + + Assert.Equal(StatusCodes.Status200OK, response.Status); + } + + [Fact] + public async Task Link_MalformedBody_Returns400WithoutCallingService() { + var services = Services(); + + var response = await Send(Route(Map(services), "api/account/logins/link"), services, "POST", "{\"Provider\":\"\",\"Token\":\"t\"}"); + + Assert.Equal(StatusCodes.Status400BadRequest, response.Status); + Assert.Contains("InvalidExternalLogin", response.Body); + _service.Verify(s => s.LinkAsync(It.IsAny>(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Theory] + [InlineData(ResultCode.Forbidden, StatusCodes.Status403Forbidden)] + [InlineData(ResultCode.Conflict, StatusCodes.Status409Conflict)] + [InlineData(ResultCode.BadRequest, StatusCodes.Status400BadRequest)] + public async Task Link_Failure_MapsToStatusWithoutInternalDetail(ResultCode code, int expectedStatus) { + _service.Setup(s => s.LinkAsync(_user, It.IsAny(), It.IsAny())) + .ReturnsAsync(new Result(code, Result.CreateErrors("InternalCode", "private internal detail"))); + var services = Services(); + + var response = await Send(Route(Map(services), "api/account/logins/link"), services, "POST", + "{\"Provider\":\"MICROSOFT\",\"Token\":\"t\",\"CurrentPassword\":\"pw\"}"); + + Assert.Equal(expectedStatus, response.Status); + Assert.DoesNotContain("private internal detail", response.Body); + Assert.DoesNotContain("InternalCode", response.Body); + } + + [Fact] + public async Task Link_UnknownCurrentUser_Returns401() { + _userManager.Setup(m => m.GetUserAsync(It.IsAny())).ReturnsAsync((IdentityUser)null); + var services = Services(); + + var response = await Send(Route(Map(services), "api/account/logins/link"), services, "POST", + "{\"Provider\":\"MICROSOFT\",\"Token\":\"t\",\"CurrentPassword\":\"pw\"}"); + + Assert.Equal(StatusCodes.Status401Unauthorized, response.Status); + } + + [Fact] + public async Task Unlink_Success_Returns200() { + _service.Setup(s => s.UnlinkAsync(_user, "GOOGLE", It.IsAny())).ReturnsAsync(new Result()); + var services = Services(); + + var response = await Send(Route(Map(services), "api/account/logins/unlink"), services, "POST", "{\"Provider\":\"GOOGLE\"}"); + + Assert.Equal(StatusCodes.Status200OK, response.Status); + } + + [Fact] + public async Task Unlink_LastAuthenticationMethod_Returns409WithoutInternalDetail() { + _service.Setup(s => s.UnlinkAsync(_user, "GOOGLE", It.IsAny())) + .ReturnsAsync(new Result(ResultCode.Conflict, Result.CreateErrors("LastAuthenticationMethod", "private detail"))); + var services = Services(); + + var response = await Send(Route(Map(services), "api/account/logins/unlink"), services, "POST", "{\"Provider\":\"GOOGLE\"}"); + + Assert.Equal(StatusCodes.Status409Conflict, response.Status); + Assert.DoesNotContain("private detail", response.Body); + } + + [Fact] + public async Task Unlink_MalformedBody_Returns400() { + var services = Services(); + + var response = await Send(Route(Map(services), "api/account/logins/unlink"), services, "POST", "{\"Provider\":\" \"}"); + + Assert.Equal(StatusCodes.Status400BadRequest, response.Status); + _service.Verify(s => s.UnlinkAsync(It.IsAny>(), It.IsAny(), It.IsAny()), Times.Never); + } + + public sealed class Dto { } + + private sealed class BodyFeature : IHttpRequestBodyDetectionFeature { + public bool CanHaveBody => true; + } + + private sealed class Builder(IServiceProvider services) : IEndpointRouteBuilder { + public ICollection DataSources { get; } = new List(); + public IServiceProvider ServiceProvider { get; } = services; + public IApplicationBuilder CreateApplicationBuilder() => new ApplicationBuilder(ServiceProvider); + } +} diff --git a/Tests/RuntimeApps.Authentication.Test/ExternalLoginEmailTrustPolicyTest.cs b/Tests/RuntimeApps.Authentication.Test/ExternalLoginEmailTrustPolicyTest.cs index 370e62f..76b4e05 100644 --- a/Tests/RuntimeApps.Authentication.Test/ExternalLoginEmailTrustPolicyTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/ExternalLoginEmailTrustPolicyTest.cs @@ -36,16 +36,72 @@ public void GoogleEmailTrust_RequiresVerifiedEmailAndTrustedDomain( } [Fact] - public void FacebookEmail_IsNeverTrustedByDefault() { + public void VerifiedMode_DoesNotTrustNonGoogleProviders() { var result = new ExternalLoginProviderResult { User = new object(), Email = "person@example.com", - EmailVerified = true + EmailVerified = true, + EmailTrustMode = ExternalLoginEmailTrustMode.Verified + }; + + Assert.False(_policy.IsEmailTrusted("FACEBOOK", result)); + } + + [Theory] + [InlineData("FACEBOOK", false)] + [InlineData("MICROSOFT", false)] + [InlineData("GOOGLE", false)] + [InlineData("MICROSOFT", true)] + public void AlwaysMode_TrustsAnyNonEmptyEmailRegardlessOfVerification(string provider, bool verified) { + var result = new ExternalLoginProviderResult { + User = new object(), + Email = "person@example.com", + EmailVerified = verified, + EmailTrustMode = ExternalLoginEmailTrustMode.Always + }; + + Assert.True(_policy.IsEmailTrusted(provider, result)); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public void AlwaysMode_DoesNotTrustMissingEmail(string email) { + var result = new ExternalLoginProviderResult { + User = new object(), + Email = email, + EmailTrustMode = ExternalLoginEmailTrustMode.Always }; Assert.False(_policy.IsEmailTrusted("FACEBOOK", result)); } + [Fact] + public void NeverMode_DoesNotTrustEvenVerifiedGmail() { + var result = new ExternalLoginProviderResult { + User = new object(), + Email = "person@gmail.com", + EmailVerified = true, + EmailTrustMode = ExternalLoginEmailTrustMode.Never + }; + + Assert.False(_policy.IsEmailTrusted("GOOGLE", result)); + } + + [Fact] + public void ResultWithoutExplicitMode_DefaultsToVerified() { + var result = new ExternalLoginProviderResult { User = new object(), Email = "person@example.com" }; + + Assert.Equal(ExternalLoginEmailTrustMode.Verified, result.EmailTrustMode); + Assert.False(_policy.IsEmailTrusted("CUSTOM", result)); + } + + [Fact] + public void NullResult_IsNotTrusted() { + Assert.False(_policy.IsEmailTrusted("GOOGLE", null)); + } + [Fact] public void UnverifiedGoogleEmail_IsNotTrusted() { var result = new ExternalLoginProviderResult { diff --git a/Tests/RuntimeApps.Authentication.Test/ExternalLoginLinkingTest.cs b/Tests/RuntimeApps.Authentication.Test/ExternalLoginLinkingTest.cs new file mode 100644 index 0000000..a71e2b0 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/ExternalLoginLinkingTest.cs @@ -0,0 +1,447 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using Moq; +using RuntimeApps.Authentication.Features.ExternalLogin.Contracts; +using RuntimeApps.Authentication.Features.ExternalLogin.Models; +using RuntimeApps.Authentication.Features.ExternalLogin.Services; +using RuntimeApps.Authentication.Features.RefreshTokens.Contracts; +using RuntimeApps.Authentication.Features.Verification.Models; +using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Shared.Models; +namespace RuntimeApps.Authentication.Test { + /// Linking, unlinking and listing the external logins of an authenticated account. + public class ExternalLoginLinkingTest { + private const string Google = "GOOGLE"; + private const string Microsoft = "MICROSOFT"; + + private readonly Mock> _google = new(); + private readonly Mock> _microsoft = new(); + private readonly Mock> _userManager = new(); + private readonly Mock> _loginManager = new(); + private readonly Mock> _emailManager = new(); + private readonly Mock> _passwordManager = new(); + private readonly Mock> _signInManager = new(); + private readonly Mock> _refreshTokens = new(); + private readonly IdentityUser _user = new() { Id = "user-1", Email = "owner@example.com", EmailConfirmed = true }; + private readonly List _logins = new(); + + public ExternalLoginLinkingTest() { + _google.SetupGet(p => p.Provider).Returns(Google); + _microsoft.SetupGet(p => p.Provider).Returns(Microsoft); + _loginManager.Setup(m => m.GetLoginsAsync(_user)).ReturnsAsync(() => _logins.ToList()); + _loginManager.Setup(m => m.AddLoginAsync(_user, It.IsAny())).ReturnsAsync(IdentityResult.Success); + _loginManager.Setup(m => m.RemoveLoginAsync(_user, It.IsAny(), It.IsAny())).ReturnsAsync(IdentityResult.Success); + _passwordManager.Setup(m => m.HasPasswordAsync(_user)).ReturnsAsync(true); + _refreshTokens.Setup(s => s.RevokeAllAsync(It.IsAny(), It.IsAny())).ReturnsAsync(1); + } + + private ExternalLoginService CreateService(IUserPasswordManager passwordManager = null) => + new(new[] { _google.Object, _microsoft.Object }, + _userManager.Object, _loginManager.Object, _emailManager.Object, + passwordManager ?? _passwordManager.Object, + _signInManager.Object, + Mock.Of>(), + Options.Create(new VerificationOptions()), + _refreshTokens.Object); + + private void Validates(Mock> provider, string token, string providerName, string subject, string email = null) => + provider.Setup(p => p.ValidateAsync(token, It.IsAny())) + .ReturnsAsync(new ExternalLoginProviderResult { + User = new IdentityUser { Email = email }, LoginInfo = new UserLoginInfo(providerName, subject, providerName), Email = email + }); + + private void PasswordIs(string password, bool correct) => + _signInManager.Setup(m => m.CheckPasswordSignInAsync(_user, password, true)) + .ReturnsAsync(correct ? SignInResult.Success : SignInResult.Failed); + + private static LinkExternalLoginModel LinkWithPassword(string provider = Microsoft, string token = "new-token", string password = "correct") => + new() { Provider = provider, Token = token, CurrentPassword = password }; + + private static void AssertFailure(Result result, ResultCode code, string errorCode) { + Assert.False(result.Succeeded); + Assert.Equal(code, result.Code); + Assert.Equal(errorCode, Assert.Single(result.Errors).Code); + } + + // ---------- Link ---------- + + [Theory] + [InlineData(null, "token")] + [InlineData("", "token")] + [InlineData(Microsoft, null)] + [InlineData(Microsoft, " ")] + public async Task Link_MissingProviderOrToken_IsBadRequest(string provider, string token) { + var result = await CreateService().LinkAsync(_user, new LinkExternalLoginModel { Provider = provider, Token = token, CurrentPassword = "correct" }); + + AssertFailure(result, ResultCode.BadRequest, "InvalidExternalLogin"); + _loginManager.Verify(m => m.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Link_WithoutReauthentication_IsForbidden() { + Validates(_microsoft, "new-token", Microsoft, "tenant:oid"); + + var result = await CreateService().LinkAsync(_user, new LinkExternalLoginModel { Provider = Microsoft, Token = "new-token" }); + + AssertFailure(result, ResultCode.Forbidden, "ReauthenticationRequired"); + _microsoft.Verify(p => p.ValidateAsync(It.IsAny(), It.IsAny()), Times.Never); + _loginManager.Verify(m => m.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Link_WrongPassword_IsForbiddenAndCountsTowardLockout() { + Validates(_microsoft, "new-token", Microsoft, "tenant:oid"); + PasswordIs("wrong", correct: false); + + var result = await CreateService().LinkAsync(_user, LinkWithPassword(password: "wrong")); + + AssertFailure(result, ResultCode.Forbidden, "ReauthenticationRequired"); + _signInManager.Verify(m => m.CheckPasswordSignInAsync(_user, "wrong", true), Times.Once); + _loginManager.Verify(m => m.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Link_PasswordSuppliedButAccountHasNoPassword_IsForbiddenWithoutPasswordCheck() { + _passwordManager.Setup(m => m.HasPasswordAsync(_user)).ReturnsAsync(false); + Validates(_microsoft, "new-token", Microsoft, "tenant:oid"); + + var result = await CreateService().LinkAsync(_user, LinkWithPassword()); + + AssertFailure(result, ResultCode.Forbidden, "ReauthenticationRequired"); + _signInManager.Verify(m => m.CheckPasswordSignInAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Link_CorrectPassword_LinksIdentity() { + var identity = new UserLoginInfo(Microsoft, "tenant:oid", Microsoft); + Validates(_microsoft, "new-token", Microsoft, "tenant:oid"); + PasswordIs("correct", correct: true); + + var result = await CreateService().LinkAsync(_user, LinkWithPassword()); + + Assert.True(result.Succeeded); + _loginManager.Verify(m => m.AddLoginAsync(_user, It.Is(l => + l.LoginProvider == identity.LoginProvider && l.ProviderKey == identity.ProviderKey)), Times.Once); + } + + [Fact] + public async Task Link_DoesNotRequireProviderEmailToMatchAndDoesNotCopyIt() { + Validates(_microsoft, "new-token", Microsoft, "tenant:oid", email: "different@other.example"); + PasswordIs("correct", correct: true); + + var result = await CreateService().LinkAsync(_user, LinkWithPassword()); + + Assert.True(result.Succeeded); + Assert.Equal("owner@example.com", _user.Email); + _userManager.Verify(m => m.UpdateAsync(It.IsAny()), Times.Never); + _emailManager.Verify(m => m.FindByEmailAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task Link_ReauthenticatedByAlreadyLinkedProviderToken_LinksIdentity() { + _logins.Add(new UserLoginInfo(Google, "google-sub", Google)); + Validates(_google, "fresh-google", Google, "google-sub"); + Validates(_microsoft, "new-token", Microsoft, "tenant:oid"); + + var result = await CreateService().LinkAsync(_user, new LinkExternalLoginModel { + Provider = Microsoft, Token = "new-token", ReauthenticationProvider = Google, ReauthenticationToken = "fresh-google" + }); + + Assert.True(result.Succeeded); + _signInManager.Verify(m => m.CheckPasswordSignInAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Link_ReauthenticationTokenOfAnotherSubject_IsForbidden() { + _logins.Add(new UserLoginInfo(Google, "google-sub", Google)); + Validates(_google, "someone-else", Google, "other-sub"); + Validates(_microsoft, "new-token", Microsoft, "tenant:oid"); + + var result = await CreateService().LinkAsync(_user, new LinkExternalLoginModel { + Provider = Microsoft, Token = "new-token", ReauthenticationProvider = Google, ReauthenticationToken = "someone-else" + }); + + AssertFailure(result, ResultCode.Forbidden, "ReauthenticationRequired"); + _loginManager.Verify(m => m.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Link_ReauthenticationProviderNotLinkedToAccount_IsForbidden() { + Validates(_google, "fresh-google", Google, "google-sub"); + Validates(_microsoft, "new-token", Microsoft, "tenant:oid"); + + var result = await CreateService().LinkAsync(_user, new LinkExternalLoginModel { + Provider = Microsoft, Token = "new-token", ReauthenticationProvider = Google, ReauthenticationToken = "fresh-google" + }); + + AssertFailure(result, ResultCode.Forbidden, "ReauthenticationRequired"); + } + + [Fact] + public async Task Link_InvalidOrUnknownReauthenticationProvider_IsForbidden() { + _logins.Add(new UserLoginInfo(Google, "google-sub", Google)); + _google.Setup(p => p.ValidateAsync("bad", It.IsAny())).ReturnsAsync((ExternalLoginProviderResult)null); + + var invalidToken = await CreateService().LinkAsync(_user, new LinkExternalLoginModel { + Provider = Microsoft, Token = "new-token", ReauthenticationProvider = Google, ReauthenticationToken = "bad" + }); + var unknownProvider = await CreateService().LinkAsync(_user, new LinkExternalLoginModel { + Provider = Microsoft, Token = "new-token", ReauthenticationProvider = "Nope", ReauthenticationToken = "x" + }); + + AssertFailure(invalidToken, ResultCode.Forbidden, "ReauthenticationRequired"); + AssertFailure(unknownProvider, ResultCode.Forbidden, "ReauthenticationRequired"); + } + + [Fact] + public async Task Link_UnknownProvider_IsGenericBadRequest() { + PasswordIs("correct", correct: true); + + var result = await CreateService().LinkAsync(_user, LinkWithPassword(provider: "Nope")); + + AssertFailure(result, ResultCode.BadRequest, "ExternalAuthenticationFailed"); + } + + [Fact] + public async Task Link_InvalidProviderToken_IsGenericBadRequest() { + PasswordIs("correct", correct: true); + _microsoft.Setup(p => p.ValidateAsync("new-token", It.IsAny())).ReturnsAsync((ExternalLoginProviderResult)null); + + var result = await CreateService().LinkAsync(_user, LinkWithPassword()); + + AssertFailure(result, ResultCode.BadRequest, "ExternalAuthenticationFailed"); + _loginManager.Verify(m => m.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Link_SecondIdentityForSameProvider_IsConflict() { + _logins.Add(new UserLoginInfo(Microsoft, "tenant:first", Microsoft)); + Validates(_microsoft, "new-token", Microsoft, "tenant:second"); + PasswordIs("correct", correct: true); + + var result = await CreateService().LinkAsync(_user, LinkWithPassword()); + + AssertFailure(result, ResultCode.Conflict, "ExternalLoginConflict"); + _loginManager.Verify(m => m.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Link_IdentityBelongsToAnotherAccount_IsConflict() { + Validates(_microsoft, "new-token", Microsoft, "tenant:oid"); + PasswordIs("correct", correct: true); + _loginManager.Setup(m => m.AddLoginAsync(_user, It.IsAny())) + .ReturnsAsync(IdentityResult.Failed(new IdentityError { Code = "LoginAlreadyAssociated" })); + + var result = await CreateService().LinkAsync(_user, LinkWithPassword()); + + AssertFailure(result, ResultCode.Conflict, "ExternalLoginConflict"); + } + + [Fact] + public async Task Link_OtherStoreFailure_IsGenericBadRequestWithoutIdentityDetail() { + Validates(_microsoft, "new-token", Microsoft, "tenant:oid"); + PasswordIs("correct", correct: true); + _loginManager.Setup(m => m.AddLoginAsync(_user, It.IsAny())) + .ReturnsAsync(IdentityResult.Failed(new IdentityError { Code = "Db", Description = "private db detail" })); + + var result = await CreateService().LinkAsync(_user, LinkWithPassword()); + + AssertFailure(result, ResultCode.BadRequest, "ExternalAuthenticationFailed"); + Assert.DoesNotContain("private db detail", result.Errors.Single().Description); + } + + [Fact] + public async Task Link_ConcurrentLinksOfSameProvider_AreUndoneAndReportedAsConflict() { + Validates(_microsoft, "new-token", Microsoft, "tenant:oid"); + PasswordIs("correct", correct: true); + var calls = 0; + _loginManager.Setup(m => m.GetLoginsAsync(_user)).ReturnsAsync(() => { + calls++; + return calls == 1 + ? new List() + : new List { + new UserLoginInfo(Microsoft, "tenant:other-request", Microsoft), + new UserLoginInfo(Microsoft, "tenant:oid", Microsoft) + }; + }); + + var result = await CreateService().LinkAsync(_user, LinkWithPassword()); + + AssertFailure(result, ResultCode.Conflict, "ExternalLoginConflict"); + _loginManager.Verify(m => m.RemoveLoginAsync(_user, Microsoft, "tenant:oid"), Times.Once); + } + + [Fact] + public async Task Link_Cancelled_ThrowsBeforeAnyCheckOrWrite() { + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + await Assert.ThrowsAnyAsync(() => + CreateService().LinkAsync(_user, LinkWithPassword(), cancellation.Token)); + + _signInManager.Verify(m => m.CheckPasswordSignInAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + _loginManager.Verify(m => m.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + // ---------- Unlink ---------- + + [Fact] + public async Task Unlink_BlankProvider_IsBadRequest() { + var result = await CreateService().UnlinkAsync(_user, " "); + + AssertFailure(result, ResultCode.BadRequest, "InvalidExternalLogin"); + } + + [Fact] + public async Task Unlink_ProviderNotLinked_IsBadRequest() { + _logins.Add(new UserLoginInfo(Google, "google-sub", Google)); + + var result = await CreateService().UnlinkAsync(_user, Microsoft); + + AssertFailure(result, ResultCode.BadRequest, "ExternalLoginNotLinked"); + _loginManager.Verify(m => m.RemoveLoginAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Unlink_AmbiguousDuplicateProviderRows_IsConflict() { + _logins.Add(new UserLoginInfo(Google, "a", Google)); + _logins.Add(new UserLoginInfo(Google, "b", Google)); + + var result = await CreateService().UnlinkAsync(_user, Google); + + AssertFailure(result, ResultCode.Conflict, "ExternalLoginAmbiguous"); + _loginManager.Verify(m => m.RemoveLoginAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Unlink_OnlyLoginButAccountHasPassword_RemovesLoginAndRevokesSessions() { + _logins.Add(new UserLoginInfo(Google, "google-sub", Google)); + _loginManager.Setup(m => m.RemoveLoginAsync(_user, Google, "google-sub")).Returns(() => { + _logins.Clear(); + return Task.FromResult(IdentityResult.Success); + }); + + var result = await CreateService().UnlinkAsync(_user, "google"); + + Assert.True(result.Succeeded); + _loginManager.Verify(m => m.RemoveLoginAsync(_user, Google, "google-sub"), Times.Once); + _refreshTokens.Verify(s => s.RevokeAllAsync("user-1", It.IsAny()), Times.Once); + } + + [Fact] + public async Task Unlink_NoPasswordButAnotherUsableLogin_Succeeds() { + _passwordManager.Setup(m => m.HasPasswordAsync(_user)).ReturnsAsync(false); + _logins.Add(new UserLoginInfo(Google, "google-sub", Google)); + _logins.Add(new UserLoginInfo(Microsoft, "tenant:oid", Microsoft)); + _loginManager.Setup(m => m.RemoveLoginAsync(_user, Google, "google-sub")).Returns(() => { + _logins.RemoveAll(l => l.LoginProvider == Google); + return Task.FromResult(IdentityResult.Success); + }); + + var result = await CreateService().UnlinkAsync(_user, Google); + + Assert.True(result.Succeeded); + } + + [Fact] + public async Task Unlink_LastAuthenticationMethod_IsConflictAndNothingIsRemoved() { + _passwordManager.Setup(m => m.HasPasswordAsync(_user)).ReturnsAsync(false); + _logins.Add(new UserLoginInfo(Google, "google-sub", Google)); + + var result = await CreateService().UnlinkAsync(_user, Google); + + AssertFailure(result, ResultCode.Conflict, "LastAuthenticationMethod"); + _loginManager.Verify(m => m.RemoveLoginAsync(It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + _refreshTokens.Verify(s => s.RevokeAllAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Unlink_RemainingLoginUsesUnregisteredProvider_DoesNotCountAsUsable() { + _passwordManager.Setup(m => m.HasPasswordAsync(_user)).ReturnsAsync(false); + _logins.Add(new UserLoginInfo(Google, "google-sub", Google)); + _logins.Add(new UserLoginInfo("RETIRED", "old", "RETIRED")); + + var result = await CreateService().UnlinkAsync(_user, Google); + + AssertFailure(result, ResultCode.Conflict, "LastAuthenticationMethod"); + } + + [Fact] + public async Task Unlink_CustomPasswordManagerWithoutHasPassword_FailsClosed() { + _logins.Add(new UserLoginInfo(Google, "google-sub", Google)); + + var result = await CreateService(new LegacyPasswordManager()).UnlinkAsync(_user, Google); + + AssertFailure(result, ResultCode.Conflict, "LastAuthenticationMethod"); + } + + [Fact] + public async Task Unlink_StoreRemovalFails_IsBadRequest() { + _logins.Add(new UserLoginInfo(Google, "google-sub", Google)); + _loginManager.Setup(m => m.RemoveLoginAsync(_user, Google, "google-sub")).ReturnsAsync(IdentityResult.Failed()); + + var result = await CreateService().UnlinkAsync(_user, Google); + + AssertFailure(result, ResultCode.BadRequest, "ExternalLoginNotUnlinked"); + _refreshTokens.Verify(s => s.RevokeAllAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Unlink_ConcurrentUnlinkLeavesNoMethod_RestoresLoginAndReportsConflict() { + // Both requests passed the first check; by the re-check the other one has removed the password. + var hasPasswordCalls = 0; + _passwordManager.Setup(m => m.HasPasswordAsync(_user)).ReturnsAsync(() => ++hasPasswordCalls == 1); + _logins.Add(new UserLoginInfo(Google, "google-sub", Google)); + _logins.Add(new UserLoginInfo(Microsoft, "tenant:oid", Microsoft)); + _loginManager.Setup(m => m.RemoveLoginAsync(_user, Google, "google-sub")).Returns(() => { + _logins.RemoveAll(l => l.LoginProvider == Google); + _logins.RemoveAll(l => l.LoginProvider == Microsoft); + return Task.FromResult(IdentityResult.Success); + }); + + var result = await CreateService().UnlinkAsync(_user, Google); + + AssertFailure(result, ResultCode.Conflict, "LastAuthenticationMethod"); + _loginManager.Verify(m => m.AddLoginAsync(_user, It.Is(l => l.LoginProvider == Google && l.ProviderKey == "google-sub")), Times.Once); + _refreshTokens.Verify(s => s.RevokeAllAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + // ---------- List ---------- + + [Fact] + public async Task List_ReturnsProvidersOnlyAndNeverSubjectKeys() { + _logins.Add(new UserLoginInfo(Google, "secret-subject", Google)); + _logins.Add(new UserLoginInfo(Microsoft, "tenant:oid", Microsoft)); + + var logins = await CreateService().ListLoginsAsync(_user); + + Assert.Equal(new[] { Google, Microsoft }, logins.Select(l => l.Provider)); + Assert.Equal(new[] { nameof(ExternalLoginSummary.Provider) }, + typeof(ExternalLoginSummary).GetProperties().Select(p => p.Name)); + } + + [Fact] + public async Task List_NoLogins_ReturnsEmpty() { + Assert.Empty(await CreateService().ListLoginsAsync(_user)); + } + + // ---------- Compatibility ---------- + + [Fact] + public async Task PasswordManagerWithoutHasPassword_DefaultsToFalse() { + IUserPasswordManager manager = new LegacyPasswordManager(); + + Assert.False(await manager.HasPasswordAsync(_user)); + } + + private sealed class LegacyPasswordManager : IUserPasswordManager { + public Task CheckPasswordAsync(IdentityUser user, string password) => Task.FromResult(true); + public Task AddPasswordAsync(IdentityUser user, string password) => Task.FromResult(IdentityResult.Success); + public Task ChangePasswordAsync(IdentityUser user, string currentPassword, string newPassword) => Task.FromResult(IdentityResult.Success); + public Task RemovePasswordAsync(IdentityUser user) => Task.FromResult(IdentityResult.Success); + public Task GeneratePasswordResetTokenAsync(IdentityUser user) => Task.FromResult("token"); + public Task ResetPasswordAsync(IdentityUser user, string token, string newPassword) => Task.FromResult(IdentityResult.Success); + public Task HasPasswordAsync(IdentityUser user) => Task.FromResult(false); + } + } +} diff --git a/Tests/RuntimeApps.Authentication.Test/ExternalLoginProviderValidationTest.cs b/Tests/RuntimeApps.Authentication.Test/ExternalLoginProviderValidationTest.cs new file mode 100644 index 0000000..c24cdec --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/ExternalLoginProviderValidationTest.cs @@ -0,0 +1,467 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Net; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; +using Google.Apis.Auth; +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Logging.Abstractions; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using Moq; +using RuntimeApps.Authentication.Features.ExternalLogin.Models; +using RuntimeApps.Authentication.Features.ExternalLogin.Providers; +namespace RuntimeApps.Authentication.Test { + /// + /// Provider-level validation matrix: invalid signature, issuer/audience mismatch, expiry, unverified + /// email and missing subject. Microsoft is exercised with real JWT validation against a stubbed + /// metadata endpoint. Facebook is exercised against stubbed Graph API responses. Google's signature, + /// issuer, expiry and audience checks live in Google.Apis.Auth, which needs Google's certificate + /// endpoint, so those tests simulate the library rejecting a token and verify how the provider + /// reacts and which audience it asks the library to enforce. + /// + public class ExternalLoginProviderValidationTest { + // ---------- Google ---------- + + private sealed class TestableGoogleProvider: GoogleExternalLoginProvider { + private readonly Func _validate; + + public TestableGoogleProvider(GoogleExternalLoginOption option, + Func validate) + : base(Microsoft.Extensions.Options.Options.Create(option), NullLogger>.Instance) { + _validate = validate; + } + + public int ValidationCalls { get; private set; } + public string RequestedAudience { get; private set; } + + protected override Task ValidatePayloadAsync( + string token, string audience, CancellationToken cancellationToken) { + ValidationCalls++; + RequestedAudience = audience; + return Task.FromResult(_validate(token, audience)); + } + } + + private static GoogleExternalLoginOption GoogleOption(string clientId = "google-client") => + new GoogleExternalLoginOption { + ClientId = clientId, + ClientSecret = "secret", + Mapper = payload => new IdentityUser { Email = payload.Email, UserName = payload.Email } + }; + + [Fact] + public async Task Google_ValidToken_ReturnsStableSubjectAndAsksLibraryToEnforceConfiguredAudience() { + var provider = new TestableGoogleProvider(GoogleOption(), (token, audience) => new GoogleJsonWebSignature.Payload { + Subject = "google-subject-1", + Email = "person@gmail.com", + EmailVerified = true + }); + + var result = await provider.ValidateAsync("id-token"); + + Assert.NotNull(result); + Assert.Equal("GOOGLE", result.LoginInfo.LoginProvider); + Assert.Equal("google-subject-1", result.LoginInfo.ProviderKey); + Assert.Equal("person@gmail.com", result.Email); + Assert.True(result.EmailVerified); + Assert.Equal("google-client", provider.RequestedAudience); + Assert.Equal(ExternalLoginEmailTrustMode.Verified, result.EmailTrustMode); + } + + [Theory] + [InlineData("Invalid signature.")] + [InlineData("Issuer is not accounts.google.com.")] + [InlineData("Audience does not match the configured client ID.")] + [InlineData("JWT has expired.")] + public async Task Google_TokenRejectedByLibrary_ReturnsNull(string reason) { + var provider = new TestableGoogleProvider(GoogleOption(), + (token, audience) => throw new InvalidJwtException(reason)); + + var result = await provider.ValidateAsync("id-token"); + + Assert.Null(result); + } + + [Theory] + [InlineData(null)] + [InlineData("")] + [InlineData(" ")] + public async Task Google_MissingSubject_ReturnsNull(string subject) { + var provider = new TestableGoogleProvider(GoogleOption(), (token, audience) => new GoogleJsonWebSignature.Payload { + Subject = subject, + Email = "person@gmail.com", + EmailVerified = true + }); + + var result = await provider.ValidateAsync("id-token"); + + Assert.Null(result); + } + + [Fact] + public async Task Google_UnverifiedEmail_IsReportedAsUnverified() { + var provider = new TestableGoogleProvider(GoogleOption(), (token, audience) => new GoogleJsonWebSignature.Payload { + Subject = "google-subject-1", + Email = "person@gmail.com", + EmailVerified = false + }); + + var result = await provider.ValidateAsync("id-token"); + + Assert.NotNull(result); + Assert.False(result.EmailVerified); + } + + [Theory] + [InlineData("", "google-client")] + [InlineData(" ", "google-client")] + [InlineData("id-token", "")] + [InlineData("id-token", " ")] + public async Task Google_MissingTokenOrClientId_ReturnsNullWithoutValidating(string token, string clientId) { + var provider = new TestableGoogleProvider(GoogleOption(clientId), + (t, audience) => new GoogleJsonWebSignature.Payload { Subject = "google-subject-1" }); + + var result = await provider.ValidateAsync(token); + + Assert.Null(result); + Assert.Equal(0, provider.ValidationCalls); + } + + [Fact] + public async Task Google_MapperReturnsNull_ReturnsNull() { + var option = GoogleOption(); + option.Mapper = payload => null; + var provider = new TestableGoogleProvider(option, + (token, audience) => new GoogleJsonWebSignature.Payload { Subject = "google-subject-1" }); + + var result = await provider.ValidateAsync("id-token"); + + Assert.Null(result); + } + + [Fact] + public async Task Google_CancellationRequested_IsNotSwallowed() { + var provider = new TestableGoogleProvider(GoogleOption(), + (token, audience) => new GoogleJsonWebSignature.Payload { Subject = "google-subject-1" }); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + await Assert.ThrowsAnyAsync(() => + provider.ValidateAsync("id-token", cancellation.Token)); + Assert.Equal(0, provider.ValidationCalls); + } + + // ---------- Stubbed HTTP ---------- + + private sealed class StubHandler: HttpMessageHandler { + private readonly List<(string Prefix, string Body)> _routes = new List<(string, string)>(); + + public List RequestedUrls { get; } = new List(); + + public StubHandler Route(string prefix, string body) { + _routes.Add((prefix, body)); + return this; + } + + protected override Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { + var url = request.RequestUri.ToString(); + RequestedUrls.Add(url); + foreach(var (prefix, body) in _routes) { + if(url.StartsWith(prefix, StringComparison.Ordinal)) + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.OK) { + Content = new StringContent(body, Encoding.UTF8, "application/json") + }); + } + return Task.FromResult(new HttpResponseMessage(HttpStatusCode.NotFound)); + } + } + + private static IHttpClientFactory FactoryFor(StubHandler handler) { + var factory = new Mock(); + // Providers dispose the client they create, so every call gets a new client over the shared handler. + factory.Setup(item => item.CreateClient(It.IsAny())) + .Returns(() => new HttpClient(handler, disposeHandler: false)); + return factory.Object; + } + + // ---------- Microsoft ---------- + + private const string MicrosoftClientId = "ms-client"; + private const string MicrosoftTenant = "11111111-1111-1111-1111-111111111111"; + private const string MicrosoftObjectId = "22222222-2222-2222-2222-222222222222"; + private const string MicrosoftKeyId = "test-key"; + private const string MetadataUrl = "https://login.microsoftonline.com/common/v2.0/.well-known/openid-configuration"; + private const string JwksUrl = "https://login.microsoftonline.com/common/discovery/v2.0/keys"; + + private static string IssuerFor(string tenant) => $"https://login.microsoftonline.com/{tenant}/v2.0"; + + private static StubHandler MicrosoftMetadata(RSA signingKey) { + var parameters = signingKey.ExportParameters(false); + var jwks = "{\"keys\":[{\"kty\":\"RSA\",\"use\":\"sig\",\"alg\":\"RS256\",\"kid\":\"" + MicrosoftKeyId + + "\",\"n\":\"" + Base64UrlEncoder.Encode(parameters.Modulus) + + "\",\"e\":\"" + Base64UrlEncoder.Encode(parameters.Exponent) + "\"}]}"; + var configuration = "{\"issuer\":\"https://login.microsoftonline.com/{tenantid}/v2.0\"," + + "\"jwks_uri\":\"" + JwksUrl + "\"," + + "\"id_token_signing_alg_values_supported\":[\"RS256\"]}"; + return new StubHandler().Route(MetadataUrl, configuration).Route(JwksUrl, jwks); + } + + private static string MicrosoftToken(RSA signingKey, + string issuer = null, + string audience = MicrosoftClientId, + string tenant = MicrosoftTenant, + string objectId = MicrosoftObjectId, + DateTime? notBefore = null, + DateTime? expires = null) { + var claims = new List { new Claim("email", "person@contoso.com") }; + if(tenant != null) + claims.Add(new Claim("tid", tenant)); + if(objectId != null) + claims.Add(new Claim("oid", objectId)); + + var credentials = new SigningCredentials( + new RsaSecurityKey(signingKey) { KeyId = MicrosoftKeyId }, SecurityAlgorithms.RsaSha256); + var token = new JwtSecurityToken( + issuer ?? IssuerFor(tenant ?? MicrosoftTenant), audience, claims, + notBefore ?? DateTime.UtcNow.AddMinutes(-5), expires ?? DateTime.UtcNow.AddMinutes(55), credentials); + return new JwtSecurityTokenHandler().WriteToken(token); + } + + private static MicrosoftExternalLoginProvider MicrosoftProvider(StubHandler handler) => + new MicrosoftExternalLoginProvider( + Microsoft.Extensions.Options.Options.Create(new MicrosoftExternalLoginOption { + ClientId = MicrosoftClientId, + ClientSecret = "secret", + Mapper = jwt => new IdentityUser { Email = jwt.Claims.FirstOrDefault(claim => claim.Type == "email")?.Value } + }), + FactoryFor(handler), + NullLogger>.Instance); + + [Fact] + public async Task Microsoft_ValidToken_ReturnsTenantScopedSubjectAndUnverifiedEmail() { + using var key = RSA.Create(2048); + var provider = MicrosoftProvider(MicrosoftMetadata(key)); + + var result = await provider.ValidateAsync(MicrosoftToken(key)); + + Assert.NotNull(result); + Assert.Equal("MICROSOFT", result.LoginInfo.LoginProvider); + Assert.Equal($"{MicrosoftTenant}:{MicrosoftObjectId}", result.LoginInfo.ProviderKey); + Assert.Equal("person@contoso.com", result.Email); + Assert.False(result.EmailVerified); + Assert.Equal(ExternalLoginEmailTrustMode.Never, result.EmailTrustMode); + } + + [Fact] + public async Task Microsoft_InvalidSignature_ReturnsNull() { + using var trustedKey = RSA.Create(2048); + using var attackerKey = RSA.Create(2048); + var provider = MicrosoftProvider(MicrosoftMetadata(trustedKey)); + + var result = await provider.ValidateAsync(MicrosoftToken(attackerKey)); + + Assert.Null(result); + } + + [Fact] + public async Task Microsoft_IssuerDoesNotMatchTenantClaim_ReturnsNull() { + using var key = RSA.Create(2048); + var provider = MicrosoftProvider(MicrosoftMetadata(key)); + var token = MicrosoftToken(key, issuer: IssuerFor("33333333-3333-3333-3333-333333333333")); + + var result = await provider.ValidateAsync(token); + + Assert.Null(result); + } + + [Fact] + public async Task Microsoft_AudienceMismatch_ReturnsNull() { + using var key = RSA.Create(2048); + var provider = MicrosoftProvider(MicrosoftMetadata(key)); + + var result = await provider.ValidateAsync(MicrosoftToken(key, audience: "another-application")); + + Assert.Null(result); + } + + [Fact] + public async Task Microsoft_ExpiredToken_ReturnsNull() { + using var key = RSA.Create(2048); + var provider = MicrosoftProvider(MicrosoftMetadata(key)); + var token = MicrosoftToken(key, notBefore: DateTime.UtcNow.AddHours(-2), expires: DateTime.UtcNow.AddHours(-1)); + + var result = await provider.ValidateAsync(token); + + Assert.Null(result); + } + + [Fact] + public async Task Microsoft_MissingObjectId_ReturnsNull() { + using var key = RSA.Create(2048); + var provider = MicrosoftProvider(MicrosoftMetadata(key)); + + var result = await provider.ValidateAsync(MicrosoftToken(key, objectId: null)); + + Assert.Null(result); + } + + [Fact] + public async Task Microsoft_MissingTenantId_ReturnsNull() { + using var key = RSA.Create(2048); + var provider = MicrosoftProvider(MicrosoftMetadata(key)); + + var result = await provider.ValidateAsync(MicrosoftToken(key, tenant: null)); + + Assert.Null(result); + } + + [Fact] + public async Task Microsoft_MetadataUnavailable_ReturnsNull() { + using var key = RSA.Create(2048); + var provider = MicrosoftProvider(new StubHandler()); + + var result = await provider.ValidateAsync(MicrosoftToken(key)); + + Assert.Null(result); + } + + // ---------- Facebook ---------- + + private const long FacebookAppId = 42; + private const long FacebookUserId = 123; + + private static StubHandler FacebookGraph(string debugTokenBody, string meBody) => + new StubHandler() + .Route("https://graph.facebook.com/oauth/access_token?", "{\"access_token\":\"app-token\",\"token_type\":\"bearer\"}") + .Route("https://graph.facebook.com/debug_token?", debugTokenBody) + .Route("https://graph.facebook.com/v27.0/me?", meBody); + + private static string DebugBody(long appId = FacebookAppId, long? userId = FacebookUserId, bool isValid = true, long expiresAt = 0) => + "{\"data\":{\"app_id\":" + appId + ",\"is_valid\":" + (isValid ? "true" : "false") + + ",\"expires_at\":" + expiresAt + + (userId.HasValue ? ",\"user_id\":" + userId.Value : string.Empty) + "}}"; + + private static string MeBody(long? id = FacebookUserId, string email = "person@example.com") => + "{" + (id.HasValue ? "\"id\":" + id.Value + "," : string.Empty) + "\"email\":\"" + email + "\",\"name\":\"Person\"}"; + + private static FacebookExternalLoginProvider FacebookProvider(StubHandler handler, string clientId = "42") => + new FacebookExternalLoginProvider( + Microsoft.Extensions.Options.Options.Create(new FacebookExternalLoginOption { + ClientId = clientId, + ClientSecret = "secret", + Mapper = data => new IdentityUser { Email = data.Email } + }), + FactoryFor(handler), + NullLogger>.Instance); + + [Fact] + public async Task Facebook_ValidToken_ReturnsSubjectAndUnverifiedEmail() { + var future = DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds(); + var provider = FacebookProvider(FacebookGraph(DebugBody(expiresAt: future), MeBody())); + + var result = await provider.ValidateAsync("user-access-token"); + + Assert.NotNull(result); + Assert.Equal("FACEBOOK", result.LoginInfo.LoginProvider); + Assert.Equal("123", result.LoginInfo.ProviderKey); + Assert.Equal("person@example.com", result.Email); + Assert.False(result.EmailVerified); + Assert.Equal(ExternalLoginEmailTrustMode.Always, result.EmailTrustMode); + } + + [Fact] + public async Task Facebook_ConfiguredNever_CarriesConfiguredTrustMode() { + var future = DateTimeOffset.UtcNow.AddHours(1).ToUnixTimeSeconds(); + var provider = new FacebookExternalLoginProvider( + Microsoft.Extensions.Options.Options.Create(new FacebookExternalLoginOption { + ClientId = "42", + ClientSecret = "secret", + EmailTrust = ExternalLoginEmailTrustMode.Never, + Mapper = data => new IdentityUser { Email = data.Email } + }), + FactoryFor(FacebookGraph(DebugBody(expiresAt: future), MeBody())), + NullLogger>.Instance); + + var result = await provider.ValidateAsync("user-access-token"); + + Assert.Equal(ExternalLoginEmailTrustMode.Never, result.EmailTrustMode); + } + + [Fact] + public void ProviderOptions_DefaultEmailTrust() { + Assert.Equal(ExternalLoginEmailTrustMode.Verified, new GoogleExternalLoginOption().EmailTrust); + Assert.Equal(ExternalLoginEmailTrustMode.Always, new FacebookExternalLoginOption().EmailTrust); + Assert.Equal(ExternalLoginEmailTrustMode.Never, new MicrosoftExternalLoginOption().EmailTrust); + } + + [Fact] + public async Task Facebook_InvalidToken_ReturnsNull() { + var provider = FacebookProvider(FacebookGraph(DebugBody(isValid: false), MeBody())); + + var result = await provider.ValidateAsync("user-access-token"); + + Assert.Null(result); + } + + [Fact] + public async Task Facebook_TokenIssuedForAnotherApplication_ReturnsNull() { + var provider = FacebookProvider(FacebookGraph(DebugBody(appId: 99), MeBody())); + + var result = await provider.ValidateAsync("user-access-token"); + + Assert.Null(result); + } + + [Fact] + public async Task Facebook_ExpiredToken_ReturnsNull() { + var past = DateTimeOffset.UtcNow.AddHours(-1).ToUnixTimeSeconds(); + var provider = FacebookProvider(FacebookGraph(DebugBody(expiresAt: past), MeBody())); + + var result = await provider.ValidateAsync("user-access-token"); + + Assert.Null(result); + } + + [Fact] + public async Task Facebook_MissingSubjectInTokenInspection_ReturnsNull() { + var provider = FacebookProvider(FacebookGraph(DebugBody(userId: null), MeBody())); + + var result = await provider.ValidateAsync("user-access-token"); + + Assert.Null(result); + } + + [Fact] + public async Task Facebook_MissingSubjectInProfile_ReturnsNull() { + var provider = FacebookProvider(FacebookGraph(DebugBody(), MeBody(id: null))); + + var result = await provider.ValidateAsync("user-access-token"); + + Assert.Null(result); + } + + [Fact] + public async Task Facebook_ProfileSubjectDiffersFromInspectedToken_ReturnsNull() { + var provider = FacebookProvider(FacebookGraph(DebugBody(userId: 123), MeBody(id: 124))); + + var result = await provider.ValidateAsync("user-access-token"); + + Assert.Null(result); + } + + [Theory] + [InlineData("not-a-number")] + [InlineData("")] + [InlineData("-42")] + public async Task Facebook_InvalidConfiguredAppId_ReturnsNullWithoutCallingFacebook(string clientId) { + var handler = FacebookGraph(DebugBody(), MeBody()); + var provider = FacebookProvider(handler, clientId); + + var result = await provider.ValidateAsync("user-access-token"); + + Assert.Null(result); + Assert.Empty(handler.RequestedUrls); + } + } +} diff --git a/Tests/RuntimeApps.Authentication.Test/ExternalLoginServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/ExternalLoginServiceTest.cs new file mode 100644 index 0000000..a26394f --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/ExternalLoginServiceTest.cs @@ -0,0 +1,358 @@ +using Microsoft.AspNetCore.Identity; +using Microsoft.Extensions.Options; +using Moq; +using RuntimeApps.Authentication.Features.ExternalLogin.Contracts; +using RuntimeApps.Authentication.Features.ExternalLogin.Models; +using RuntimeApps.Authentication.Features.ExternalLogin.Services; +using RuntimeApps.Authentication.Features.RefreshTokens.Contracts; +using RuntimeApps.Authentication.Features.Verification.Models; +using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Shared.Models; +namespace RuntimeApps.Authentication.Test { + /// Account resolution for validated external identities (ResolveLoginAsync). + public class ExternalLoginServiceTest { + private const string Provider = "Google"; + private const string Subject = "subject-1"; + private const string TrustedEmail = "person@example.com"; + + private readonly Mock> _provider = new(); + private readonly Mock> _userManager = new(); + private readonly Mock> _loginManager = new(); + private readonly Mock> _emailManager = new(); + private readonly Mock> _passwordManager = new(); + private readonly Mock> _trustPolicy = new(); + private readonly Mock> _refreshTokens = new(); + private readonly UserLoginInfo _loginInfo = new(Provider, Subject, Provider); + private bool _requireVerification; + + public ExternalLoginServiceTest() { + _provider.SetupGet(p => p.Provider).Returns(Provider); + _loginManager.Setup(m => m.FindByLoginAsync(Provider, Subject)).ReturnsAsync((IdentityUser)null); + _emailManager.Setup(m => m.FindByEmailAsync(It.IsAny())).ReturnsAsync((IdentityUser)null); + _userManager.Setup(m => m.CreateAsync(It.IsAny())).ReturnsAsync(IdentityResult.Success); + _userManager.Setup(m => m.UpdateAsync(It.IsAny())).ReturnsAsync(IdentityResult.Success); + _userManager.Setup(m => m.DeleteAsync(It.IsAny())).ReturnsAsync(IdentityResult.Success); + _loginManager.Setup(m => m.AddLoginAsync(It.IsAny(), It.IsAny())).ReturnsAsync(IdentityResult.Success); + _passwordManager.Setup(m => m.RemovePasswordAsync(It.IsAny())).ReturnsAsync(IdentityResult.Success); + _refreshTokens.Setup(s => s.RevokeAllAsync(It.IsAny(), It.IsAny())).ReturnsAsync(1); + } + + private ExternalLoginService CreateService(bool withPasswordManager = true, bool withRefreshTokens = true) => + new(new[] { _provider.Object }, + _userManager.Object, + _loginManager.Object, + _emailManager.Object, + withPasswordManager ? _passwordManager.Object : null, + Mock.Of>(), + _trustPolicy.Object, + Options.Create(new VerificationOptions { RequireEmailVerificationForExternalLogins = _requireVerification }), + withRefreshTokens ? _refreshTokens.Object : null); + + private IdentityUser SetupProvider(string email, bool trusted, IdentityUser mapped = null) { + var user = mapped ?? new IdentityUser { Email = email, UserName = email }; + _provider.Setup(p => p.ValidateAsync("token", It.IsAny())) + .ReturnsAsync(new ExternalLoginProviderResult { + User = user, LoginInfo = _loginInfo, Email = email, EmailVerified = trusted + }); + _trustPolicy.Setup(p => p.IsEmailTrusted(Provider, It.IsAny>())).Returns(trusted); + return user; + } + + private static void AssertGenericFailure(Result result) { + Assert.False(result.Succeeded); + Assert.Equal(ResultCode.BadRequest, result.Code); + var error = Assert.Single(result.Errors); + Assert.Equal("ExternalAuthenticationFailed", error.Code); + Assert.Equal("External authentication could not be completed.", error.Description); + } + + [Fact] + public async Task UnknownProvider_FailsGenerically() { + var result = await CreateService().ResolveLoginAsync("Nope", "token"); + + AssertGenericFailure(result); + _userManager.Verify(m => m.CreateAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task ProviderRejectsToken_FailsGenerically() { + _provider.Setup(p => p.ValidateAsync("token", It.IsAny())) + .ReturnsAsync((ExternalLoginProviderResult)null); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + AssertGenericFailure(result); + _loginManager.Verify(m => m.FindByLoginAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task ExistingLogin_ReturnsLinkedAccountWithoutWrites() { + var linked = new IdentityUser { Id = "linked" }; + SetupProvider(TrustedEmail, trusted: true); + _loginManager.Setup(m => m.FindByLoginAsync(Provider, Subject)).ReturnsAsync(linked); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + Assert.True(result.Succeeded); + Assert.Same(linked, result.Data); + _emailManager.Verify(m => m.FindByEmailAsync(It.IsAny()), Times.Never); + _userManager.Verify(m => m.CreateAsync(It.IsAny()), Times.Never); + _loginManager.Verify(m => m.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task TrustedEmail_CreatesConfirmedAccountAndLinksLogin() { + var user = SetupProvider(TrustedEmail, trusted: true); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + Assert.True(result.Succeeded); + Assert.Same(user, result.Data); + Assert.True(user.EmailConfirmed); + Assert.Equal(TrustedEmail, user.Email); + Assert.Equal(TrustedEmail, user.UserName); + _userManager.Verify(m => m.CreateAsync(user), Times.Once); + _loginManager.Verify(m => m.AddLoginAsync(user, _loginInfo), Times.Once); + } + + [Fact] + public async Task TrustedEmail_MapperLeftEmailBlank_UsesTrustedEmail() { + var user = SetupProvider(TrustedEmail, trusted: true, mapped: new IdentityUser()); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + Assert.True(result.Succeeded); + Assert.Equal(TrustedEmail, user.Email); + Assert.Equal(TrustedEmail, user.UserName); + Assert.True(user.EmailConfirmed); + } + + [Fact] + public async Task TrustedEmail_ConfirmedExistingAccount_LinksWithoutTouchingPassword() { + SetupProvider(TrustedEmail, trusted: true); + var existing = new IdentityUser { Id = "existing", Email = TrustedEmail, EmailConfirmed = true }; + _emailManager.Setup(m => m.FindByEmailAsync(TrustedEmail)).ReturnsAsync(existing); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + Assert.True(result.Succeeded); + Assert.Same(existing, result.Data); + _loginManager.Verify(m => m.AddLoginAsync(existing, _loginInfo), Times.Once); + _passwordManager.Verify(m => m.RemovePasswordAsync(It.IsAny()), Times.Never); + _refreshTokens.Verify(s => s.RevokeAllAsync(It.IsAny(), It.IsAny()), Times.Never); + _userManager.Verify(m => m.CreateAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task TrustedEmail_UnconfirmedExistingAccount_IsNeutralizedBeforeLinking() { + SetupProvider(TrustedEmail, trusted: true); + var existing = new IdentityUser { Id = "existing", Email = TrustedEmail, EmailConfirmed = false }; + _emailManager.Setup(m => m.FindByEmailAsync(TrustedEmail)).ReturnsAsync(existing); + var order = new List(); + _passwordManager.Setup(m => m.RemovePasswordAsync(existing)).Returns(() => { + order.Add("remove-password"); + return Task.FromResult(IdentityResult.Success); + }); + _refreshTokens.Setup(s => s.RevokeAllAsync("existing", It.IsAny())).Returns(() => { + order.Add("revoke-sessions"); + return Task.FromResult(1); + }); + _loginManager.Setup(m => m.AddLoginAsync(existing, _loginInfo)).Returns(() => { + order.Add("add-login"); + return Task.FromResult(IdentityResult.Success); + }); + _userManager.Setup(m => m.UpdateAsync(existing)).Returns(() => { + order.Add("confirm-email"); + return Task.FromResult(IdentityResult.Success); + }); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + Assert.True(result.Succeeded); + Assert.Same(existing, result.Data); + Assert.True(existing.EmailConfirmed); + Assert.Equal(new[] { "remove-password", "revoke-sessions", "add-login", "confirm-email" }, order); + _userManager.Verify(m => m.CreateAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task UnconfirmedExistingAccount_WithoutPasswordManager_FailsClosedWithoutLinking() { + SetupProvider(TrustedEmail, trusted: true); + var existing = new IdentityUser { Id = "existing", Email = TrustedEmail, EmailConfirmed = false }; + _emailManager.Setup(m => m.FindByEmailAsync(TrustedEmail)).ReturnsAsync(existing); + + var result = await CreateService(withPasswordManager: false).ResolveLoginAsync(Provider, "token"); + + AssertGenericFailure(result); + _loginManager.Verify(m => m.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never); + Assert.False(existing.EmailConfirmed); + } + + [Fact] + public async Task UnconfirmedExistingAccount_PasswordRemovalFails_DoesNotLink() { + SetupProvider(TrustedEmail, trusted: true); + var existing = new IdentityUser { Id = "existing", Email = TrustedEmail, EmailConfirmed = false }; + _emailManager.Setup(m => m.FindByEmailAsync(TrustedEmail)).ReturnsAsync(existing); + _passwordManager.Setup(m => m.RemovePasswordAsync(existing)).ReturnsAsync(IdentityResult.Failed()); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + AssertGenericFailure(result); + _loginManager.Verify(m => m.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never); + Assert.False(existing.EmailConfirmed); + } + + [Fact] + public async Task UnconfirmedExistingAccount_LinkFails_StaysUnconfirmed() { + SetupProvider(TrustedEmail, trusted: true); + var existing = new IdentityUser { Id = "existing", Email = TrustedEmail, EmailConfirmed = false }; + _emailManager.Setup(m => m.FindByEmailAsync(TrustedEmail)).ReturnsAsync(existing); + _loginManager.Setup(m => m.AddLoginAsync(existing, _loginInfo)).ReturnsAsync(IdentityResult.Failed()); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + AssertGenericFailure(result); + Assert.False(existing.EmailConfirmed); + _userManager.Verify(m => m.UpdateAsync(It.IsAny()), Times.Never); + _userManager.Verify(m => m.DeleteAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task UnconfirmedExistingAccount_ConfirmUpdateFails_ResetsFlagAndFails() { + SetupProvider(TrustedEmail, trusted: true); + var existing = new IdentityUser { Id = "existing", Email = TrustedEmail, EmailConfirmed = false }; + _emailManager.Setup(m => m.FindByEmailAsync(TrustedEmail)).ReturnsAsync(existing); + _userManager.Setup(m => m.UpdateAsync(existing)).ReturnsAsync(IdentityResult.Failed()); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + AssertGenericFailure(result); + Assert.False(existing.EmailConfirmed); + } + + [Fact] + public async Task UntrustedEmail_IsIgnoredForLookupAndNotStored() { + var user = SetupProvider("victim@example.com", trusted: false); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + Assert.True(result.Succeeded); + Assert.Same(user, result.Data); + _emailManager.Verify(m => m.FindByEmailAsync(It.IsAny()), Times.Never); + Assert.Null(user.Email); + Assert.False(user.EmailConfirmed); + Assert.Equal("Google_subject-1", user.UserName); + } + + [Fact] + public async Task UntrustedEmail_ExistingAccountWithSameEmail_IsNeverLinked() { + SetupProvider("victim@example.com", trusted: false); + var victim = new IdentityUser { Id = "victim", Email = "victim@example.com", EmailConfirmed = true }; + _emailManager.Setup(m => m.FindByEmailAsync("victim@example.com")).ReturnsAsync(victim); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + Assert.True(result.Succeeded); + Assert.NotSame(victim, result.Data); + _loginManager.Verify(m => m.AddLoginAsync(victim, It.IsAny()), Times.Never); + } + + [Fact] + public async Task UntrustedEmail_KeepsMapperUserNameThatIsNotTheEmail() { + var user = SetupProvider("someone@example.com", trusted: false, + mapped: new IdentityUser { Email = "someone@example.com", UserName = "custom-name" }); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + Assert.True(result.Succeeded); + Assert.Equal("custom-name", user.UserName); + Assert.Null(user.Email); + } + + [Fact] + public async Task NoEmailAtAll_UsesProviderSubjectUserName() { + var user = SetupProvider(null, trusted: true, mapped: new IdentityUser()); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + Assert.True(result.Succeeded); + Assert.Equal("Google_subject-1", user.UserName); + Assert.False(user.EmailConfirmed); + } + + [Fact] + public async Task RequireVerification_UntrustedEmail_FailsBeforeAnyWrite() { + _requireVerification = true; + SetupProvider("person@example.com", trusted: false); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + AssertGenericFailure(result); + _emailManager.Verify(m => m.FindByEmailAsync(It.IsAny()), Times.Never); + _userManager.Verify(m => m.CreateAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task CreateFails_FailsGenericallyWithoutLinkingOrDeleting() { + SetupProvider(TrustedEmail, trusted: true); + _userManager.Setup(m => m.CreateAsync(It.IsAny())).ReturnsAsync(IdentityResult.Failed()); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + AssertGenericFailure(result); + _loginManager.Verify(m => m.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never); + _userManager.Verify(m => m.DeleteAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task LinkFailsAfterCreate_DeletesCreatedAccount() { + var user = SetupProvider(TrustedEmail, trusted: true); + _loginManager.Setup(m => m.AddLoginAsync(user, _loginInfo)).ReturnsAsync(IdentityResult.Failed()); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + AssertGenericFailure(result); + _userManager.Verify(m => m.DeleteAsync(user), Times.Once); + } + + [Fact] + public async Task LinkFailsAndCompensatingDeleteThrows_StillReturnsGenericFailure() { + var user = SetupProvider(TrustedEmail, trusted: true); + _loginManager.Setup(m => m.AddLoginAsync(user, _loginInfo)).ReturnsAsync(IdentityResult.Failed()); + _userManager.Setup(m => m.DeleteAsync(user)).ThrowsAsync(new InvalidOperationException("db detail")); + + var result = await CreateService().ResolveLoginAsync(Provider, "token"); + + AssertGenericFailure(result); + Assert.DoesNotContain("db detail", result.Errors.Single().Description); + } + + [Fact] + public async Task CancelledBeforeStart_Throws_AndWritesNothing() { + SetupProvider(TrustedEmail, trusted: true); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + await Assert.ThrowsAnyAsync(() => + CreateService().ResolveLoginAsync(Provider, "token", cancellation.Token)); + + _userManager.Verify(m => m.CreateAsync(It.IsAny()), Times.Never); + } + + [Fact] + public async Task CancellationDuringCreate_DoesNotInterruptLinking() { + var user = SetupProvider(TrustedEmail, trusted: true); + using var cancellation = new CancellationTokenSource(); + _userManager.Setup(m => m.CreateAsync(user)).Returns(() => { + cancellation.Cancel(); + return Task.FromResult(IdentityResult.Success); + }); + + var result = await CreateService().ResolveLoginAsync(Provider, "token", cancellation.Token); + + Assert.True(result.Succeeded); + _loginManager.Verify(m => m.AddLoginAsync(user, _loginInfo), Times.Once); + _userManager.Verify(m => m.DeleteAsync(It.IsAny()), Times.Never); + } + } +} diff --git a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs index a45ab9e..d262057 100644 --- a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs @@ -262,58 +262,39 @@ public async Task ExternalLogin_Success_CreateNewUser() { } [Fact] - public async Task ExternalLogin_ExistingEmail_DoesNotAutomaticallyLink() { + public async Task ExternalLogin_UntrustedEmail_DoesNotLookUpOrLinkExistingAccount() { const string provider = "Google"; const string token = "provider-token"; var existingUser = new IdentityUser { Email = "existing@example.com", EmailConfirmed = true }; var loginInfo = new UserLoginInfo(provider, token, provider); + var created = new IdentityUser { Email = existingUser.Email, UserName = existingUser.Email }; + var appToken = new RuntimeApps.Authentication.Shared.Models.Token { AuthenticationToken = "access" }; _externalLoginProvider1.SetupGet(item => item.Provider).Returns("Not Selected"); _externalLoginProvider2.SetupGet(item => item.Provider).Returns(provider); _externalLoginProvider2.Setup(item => item.ValidateAsync(token)) .ReturnsAsync(new RuntimeApps.Authentication.Features.ExternalLogin.Models.ExternalLoginProviderResult { - User = new IdentityUser { Email = existingUser.Email }, - LoginInfo = loginInfo, - Email = existingUser.Email, - EmailVerified = true + User = created, LoginInfo = loginInfo, Email = existingUser.Email, EmailVerified = true }); + _externalLoginEmailTrustPolicyMock.Setup(policy => policy.IsEmailTrusted(provider, It.IsAny>())).Returns(false); _loginManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); - _emailManagerMock.Setup(manager => manager.FindByEmailAsync(existingUser.Email)).ReturnsAsync(existingUser); + _userManagerMock.Setup(manager => manager.CreateAsync(created)).ReturnsAsync(IdentityResult.Success); + _loginManagerMock.Setup(manager => manager.AddLoginAsync(created, loginInfo)).ReturnsAsync(IdentityResult.Success); + _sessionIssuerMock.Setup(issuer => issuer.IssueAsync(created, It.IsAny())).ReturnsAsync(appToken); var result = await _userAccountService.ExternalLoginAsync(provider, token); - Assert.False(result.Succeeded); - Assert.Equal(RuntimeApps.Authentication.Shared.Models.ResultCode.BadRequest, result.Code); - Assert.Equal("ExternalAuthenticationFailed", result.Errors.Single().Code); - _loginManagerMock.Verify(manager => manager.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); - _emailManagerMock.Verify(manager => manager.FindByEmailAsync(It.IsAny()), Times.Never()); - } - - [Fact] - public async Task ExternalLogin_UntrustedEmailWithoutMatchingAccount_HasSameGenericFailure() { - const string provider = "Google"; - const string token = "provider-token"; - var loginInfo = new UserLoginInfo(provider, token, provider); - _externalLoginProvider1.SetupGet(item => item.Provider).Returns("Not Selected"); - _externalLoginProvider2.SetupGet(item => item.Provider).Returns(provider); - _externalLoginProvider2.Setup(item => item.ValidateAsync(token)) - .ReturnsAsync(new RuntimeApps.Authentication.Features.ExternalLogin.Models.ExternalLoginProviderResult { - User = new IdentityUser { Email = "new@example.com" }, LoginInfo = loginInfo, - Email = "new@example.com", EmailVerified = false - }); - _loginManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); - - var result = await _userAccountService.ExternalLoginAsync(provider, token); - - Assert.False(result.Succeeded); - Assert.Equal(RuntimeApps.Authentication.Shared.Models.ResultCode.BadRequest, result.Code); - Assert.Equal("ExternalAuthenticationFailed", result.Errors.Single().Code); - Assert.Equal("External authentication could not be completed.", result.Errors.Single().Description); + Assert.True(result.Succeeded); + Assert.Same(created, result.Data); + // The untrusted claim is not used to find an account and is not stored on the new one. _emailManagerMock.Verify(manager => manager.FindByEmailAsync(It.IsAny()), Times.Never()); - _userManagerMock.Verify(manager => manager.CreateAsync(It.IsAny()), Times.Never()); + _loginManagerMock.Verify(manager => manager.AddLoginAsync(existingUser, It.IsAny()), Times.Never()); + Assert.Null(created.Email); + Assert.False(created.EmailConfirmed); + Assert.Equal("Google_provider-token", created.UserName); } [Fact] - public async Task ExternalLogin_FailedLinkAfterCreateLeavesRetryableUserWithoutSession() { + public async Task ExternalLogin_FailedLinkAfterCreateRemovesCreatedUserWithoutSession() { const string provider = "Google"; const string token = "provider-token"; var user = new IdentityUser { Email = "trusted@example.com", UserName = "trusted@example.com" }; @@ -328,13 +309,15 @@ public async Task ExternalLogin_FailedLinkAfterCreateLeavesRetryableUserWithoutS _loginManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); _emailManagerMock.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync((IdentityUser)null); _userManagerMock.Setup(manager => manager.CreateAsync(user)).ReturnsAsync(IdentityResult.Success); + _userManagerMock.Setup(manager => manager.DeleteAsync(user)).ReturnsAsync(IdentityResult.Success); _loginManagerMock.Setup(manager => manager.AddLoginAsync(user, loginInfo)).ReturnsAsync(IdentityResult.Failed()); + var result = await _userAccountService.ExternalLoginAsync(provider, token); Assert.False(result.Succeeded); + Assert.Equal("ExternalAuthenticationFailed", result.Errors.Single().Code); _userManagerMock.Verify(manager => manager.CreateAsync(user), Times.Once); - _userManagerMock.Verify(manager => manager.DeleteAsync(user), Times.Never); - _loginManagerMock.Verify(manager => manager.AddLoginAsync(user, loginInfo), Times.Once); + _userManagerMock.Verify(manager => manager.DeleteAsync(user), Times.Once); _sessionIssuerMock.Verify(issuer => issuer.IssueAsync(It.IsAny(), It.IsAny()), Times.Never); } @@ -395,30 +378,6 @@ public async Task ExternalLogin_TrustedEmailCanLinkExistingAccount() { _loginManagerMock.Verify(manager => manager.AddLoginAsync(user, loginInfo), Times.Once); } - [Fact] - public async Task ExternalLogin_UnverifiedEmail_DoesNotLinkExistingAccount() { - const string provider = "Google"; - const string token = "provider-token"; - var user = new IdentityUser { Email = "existing@example.com", EmailConfirmed = true }; - var loginInfo = new UserLoginInfo(provider, token, provider); - _externalLoginProvider1.SetupGet(item => item.Provider).Returns("Not Selected"); - _externalLoginProvider2.SetupGet(item => item.Provider).Returns(provider); - _externalLoginProvider2.Setup(item => item.ValidateAsync(token)) - .ReturnsAsync(new RuntimeApps.Authentication.Features.ExternalLogin.Models.ExternalLoginProviderResult { - User = new IdentityUser { Email = user.Email }, LoginInfo = loginInfo, - Email = user.Email, EmailVerified = false - }); - _loginManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); - _emailManagerMock.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync(user); - - var result = await _userAccountService.ExternalLoginAsync(provider, token); - - Assert.False(result.Succeeded); - Assert.Equal(RuntimeApps.Authentication.Shared.Models.ResultCode.BadRequest, result.Code); - Assert.Equal("ExternalAuthenticationFailed", result.Errors.Single().Code); - _loginManagerMock.Verify(manager => manager.AddLoginAsync(It.IsAny(), It.IsAny()), Times.Never()); - } - [Fact] public async Task ExternalLogin_CanRequireEmailVerificationWithoutIssuingToken() { const string provider = "Google";