diff --git a/ReadMe.md b/ReadMe.md index 1ff55f5..87156ae 100644 --- a/ReadMe.md +++ b/ReadMe.md @@ -28,6 +28,12 @@ Protect personal data | Protect personal user data in database by encrypt user d ## Getting Started +### Request body contracts + +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. + `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. To use this library do the steps: @@ -293,7 +299,7 @@ External provider login does not require a second email challenge by default. Se 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`. -External identities are not automatically linked to an existing local account based on a matching email address. Linking must be initiated from an authenticated account-management flow. +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. ### Migration note diff --git a/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs index 90760f2..4d7ead4 100644 --- a/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/Account/AccountApiEndpointRouteBuilderExtensions.cs @@ -28,21 +28,39 @@ public static IEndpointRouteBuilder MapAuthenticationApi( RequireServices(endpoints, "Authentication", typeof(IUserAccountService), typeof(IUserMapper)); var routeGroup = endpoints.MapGroup("").AllowAnonymous(); - routeGroup.MapPost("login", async Task>, ValidationProblem>> ([FromBody] UserLoginModel userLoginModel, IUserAccountService userAccountService, [FromServices] IUserMapper mapper, HttpContext context) => { + routeGroup.MapPost("login", async Task ([FromBody] UserLoginModel userLoginModel, IUserAccountService userAccountService, [FromServices] IUserMapper mapper, HttpContext context) => { + if(string.IsNullOrWhiteSpace(userLoginModel?.UserName) || string.IsNullOrEmpty(userLoginModel.Password)) + return ValidationProblemFactory.CreateValidationProblem("InvalidLogin", "User name and password are required."); var result = await userAccountService.LoginAsync(userLoginModel.UserName, userLoginModel.Password, context.RequestAborted); - if(!result.Succeeded) - return result.CreateValidationProblem(); + if(!result.Succeeded) { + // Keep the existing two-factor continuation response separate from credential failures. + if(result.Code == ResultCode.Accepted) + return TypedResults.Accepted((string)null, new AuthenticationContinuationResponse()); + // Keep unknown, unconfirmed, locked, and incorrect-password failures indistinguishable. + return TypedResults.Problem(statusCode: StatusCodes.Status401Unauthorized, + title: "Authentication failed", detail: "The username or password is incorrect.", + extensions: new Dictionary { ["code"] = "authentication_failed" }); + } return TypedResults.Ok(MapResult(result, mapper)); - }).WithName("Authentication_Login").WithTags("Authentication").WithSummary("Log in"); + }).WithName("Authentication_Login").WithTags("Authentication").WithSummary("Log in") + .Produces>(StatusCodes.Status200OK) + .Produces(StatusCodes.Status202Accepted) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .ProducesProblem(StatusCodes.Status401Unauthorized); if(endpoints.ServiceProvider.GetService() ?.IsService(typeof(IExternalLoginProvider)) == true) { - routeGroup.MapPost("login/external", async Task>, ValidationProblem>> ([FromBody] ExternalAuthModel request, IUserAccountService userAccountService, [FromServices] IUserMapper mapper, HttpContext context) => { + routeGroup.MapPost("login/external", async Task ([FromBody] ExternalAuthModel request, IUserAccountService userAccountService, [FromServices] IUserMapper mapper, HttpContext context) => { + if(string.IsNullOrWhiteSpace(request?.Provider) || string.IsNullOrWhiteSpace(request.Token)) + return ValidationProblemFactory.CreateValidationProblem("InvalidExternalLogin", "Provider and token are required."); var result = await userAccountService.ExternalLoginAsync(request.Provider, request.Token, context.RequestAborted); if(!result.Succeeded) - return result.CreateValidationProblem(); + return PublicErrorFactory.CreateExternalAuthenticationFailure(); return TypedResults.Ok(MapResult(result, mapper)); - }).WithName("Authentication_ExternalLogin").WithTags("Authentication").WithSummary("Log in with an external provider"); + }).WithName("Authentication_ExternalLogin").WithTags("Authentication").WithSummary("Log in with an external provider") + .Produces>(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .ProducesProblem(StatusCodes.Status401Unauthorized); } return endpoints; @@ -63,7 +81,7 @@ public static IEndpointRouteBuilder MapRegistrationApi(th var routeGroup = endpoints.MapGroup("").AllowAnonymous(); - routeGroup.MapPost("register", async Task>, ValidationProblem>> ( + routeGroup.MapPost("register", async Task ( [FromBody] RegisterUserModel user, IRegistrationService registrationService, [FromServices] IUserMapper mapper, @@ -74,9 +92,11 @@ public static IEndpointRouteBuilder MapRegistrationApi(th var result = await registrationService.RegisterAsync( mapper.ToUser(user.UserInfo), user.Password, httpContext.RequestAborted); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Accepted((string)null, result); - }).WithName("Registration_Register").WithTags("Registration").WithSummary("Register a user"); + }).WithName("Registration_Register").WithTags("Registration").WithSummary("Register a user") + .Produces>(StatusCodes.Status202Accepted) + .ProducesValidationProblem(StatusCodes.Status400BadRequest); return endpoints; } @@ -88,7 +108,7 @@ public static IEndpointRouteBuilder MapVerificationApi(th where TKey : IEquatable { RequireServices(endpoints, "Verification", typeof(IRegistrationService), typeof(IUserMapper), typeof(IVerificationWorkflowService), typeof(IVerificationRequestStore), typeof(IVerificationSender)); var routeGroup = endpoints.MapGroup("").AllowAnonymous(); - routeGroup.MapPost("register/verify", async Task>, ValidationProblem>> ( + routeGroup.MapPost("register/verify", async Task ( [FromBody] VerifyRegistrationModel request, IRegistrationService registrationService, [FromServices] IUserMapper mapper, @@ -99,11 +119,14 @@ public static IEndpointRouteBuilder MapVerificationApi(th var result = await registrationService.VerifyAsync( request.VerificationHandle, request.Code, httpContext.RequestAborted); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(MapResult(result, mapper)); - }).WithName("Verification_VerifyRegistration").WithTags("Verification").WithSummary("Verify a registration"); + }).WithName("Verification_VerifyRegistration").WithTags("Verification").WithSummary("Verify a registration") + .Produces>(StatusCodes.Status200OK) + .ProducesProblem(StatusCodes.Status403Forbidden) + .ProducesValidationProblem(StatusCodes.Status400BadRequest); - routeGroup.MapPost("register/resend", async Task>, ValidationProblem>> ( + routeGroup.MapPost("register/resend", async Task ( [FromBody] ResendRegistrationVerificationModel request, IRegistrationService registrationService, HttpContext httpContext) => { @@ -113,9 +136,11 @@ public static IEndpointRouteBuilder MapVerificationApi(th var result = await registrationService.ResendAsync( request.VerificationHandle, httpContext.RequestAborted); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Accepted((string)null, result); - }).WithName("Verification_ResendRegistration").WithTags("Verification").WithSummary("Resend registration verification"); + }).WithName("Verification_ResendRegistration").WithTags("Verification").WithSummary("Resend registration verification") + .Produces>(StatusCodes.Status202Accepted) + .ProducesValidationProblem(StatusCodes.Status400BadRequest); return endpoints; } @@ -141,14 +166,16 @@ public static IEndpointRouteBuilder MapAdminUserApi( else routeGroup.RequireAuthorization(authorizationPolicy); - routeGroup.MapPost("", async Task, ValidationProblem>> ( + routeGroup.MapPost("", async Task ( [FromBody] RegisterUserModel request, IUserManager userManager, - [FromServices] IUserMapper mapper) => { + [FromServices] IUserMapper mapper, + CancellationToken cancellationToken) => { if(request?.UserInfo == null || string.IsNullOrEmpty(request.Password)) return ValidationProblemFactory.CreateValidationProblem( "InvalidUser", "User information and password are required."); + cancellationToken.ThrowIfCancellationRequested(); var user = mapper.ToUser(request.UserInfo); if(string.IsNullOrWhiteSpace(user.UserName)) user.UserName = user.Email; @@ -156,10 +183,13 @@ public static IEndpointRouteBuilder MapAdminUserApi( var result = await userManager.CreateAsync(user, request.Password); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(mapper.ToDto(user)); - }); + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status401Unauthorized) + .Produces(StatusCodes.Status403Forbidden); return endpoints; } @@ -172,42 +202,63 @@ public static IEndpointRouteBuilder MapAccountManagementApi), typeof(IUserMapper), typeof(IUserPasswordManager)); var authorizedRouteGroup = endpoints.MapGroup("").RequireAuthorization(); - authorizedRouteGroup.MapGet("/", async (IUserManager userManager, HttpContext httpContext, IUserMapper mapper) => { + authorizedRouteGroup.MapGet("/", async Task (IUserManager userManager, HttpContext httpContext, IUserMapper mapper, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.GetUserAsync(httpContext.User); - return user != null ? mapper.ToDto(user) : null; - }).WithName("AccountManagement_Get").WithTags("Account management").WithSummary("Get the current account"); - - authorizedRouteGroup.MapPost("password/change", async Task> ([FromBody] ChangePasswordModel input, IUserManager userManager, IUserPasswordManager passwordManager, HttpContext httpContext, IServiceProvider services) => { + cancellationToken.ThrowIfCancellationRequested(); + return user != null ? TypedResults.Ok(mapper.ToDto(user)) : TypedResults.Unauthorized(); + }).WithName("AccountManagement_Get").WithTags("Account management").WithSummary("Get the current account") + .Produces(StatusCodes.Status200OK) + .Produces(StatusCodes.Status401Unauthorized) + .Produces(StatusCodes.Status403Forbidden); + + authorizedRouteGroup.MapPost("password/change", async Task ([FromBody] ChangePasswordModel input, IUserManager userManager, IUserPasswordManager passwordManager, HttpContext httpContext, IServiceProvider services, CancellationToken cancellationToken) => { + if(string.IsNullOrEmpty(input?.CurrentPassword) || string.IsNullOrEmpty(input.NewPassword)) + return ValidationProblemFactory.CreateValidationProblem("InvalidPassword", "Current and new passwords are required."); + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.GetUserAsync(httpContext.User); if(user == null) - return ValidationProblemFactory.CreateValidationProblem("NoAccess", "Cannot change password without login"); + return TypedResults.Unauthorized(); + cancellationToken.ThrowIfCancellationRequested(); var result = await passwordManager.ChangePasswordAsync(user, input.CurrentPassword, input.NewPassword); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); var refreshTokenService = services.GetService>(); if(refreshTokenService != null) - await refreshTokenService.RevokeAllAsync(user.Id, httpContext.RequestAborted); + await refreshTokenService.RevokeAllAsync(user.Id, CancellationToken.None); return TypedResults.Ok(); - }).WithName("AccountManagement_ChangePassword").WithTags("Account management").WithSummary("Change the current password"); - - authorizedRouteGroup.MapPost("password", async Task> ([FromBody] string password, IUserManager userManager, IUserPasswordManager passwordManager, HttpContext httpContext, IServiceProvider services) => { + }).WithName("AccountManagement_ChangePassword").WithTags("Account management").WithSummary("Change the current password") + .Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status401Unauthorized) + .Produces(StatusCodes.Status403Forbidden); + + authorizedRouteGroup.MapPost("password", async Task ([FromBody] AddPasswordRequest request, IUserManager userManager, IUserPasswordManager passwordManager, HttpContext httpContext, IServiceProvider services, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.GetUserAsync(httpContext.User); if(user == null) - return ValidationProblemFactory.CreateValidationProblem("NoAccess", "Cannot change password without login"); + return TypedResults.Unauthorized(); + if(string.IsNullOrEmpty(request?.Password)) + return ValidationProblemFactory.CreateValidationProblem("InvalidPassword", "Password is required."); - var result = await passwordManager.AddPasswordAsync(user, password); + cancellationToken.ThrowIfCancellationRequested(); + var result = await passwordManager.AddPasswordAsync(user, request?.Password); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); var refreshTokenService = services.GetService>(); if(refreshTokenService != null) - await refreshTokenService.RevokeAllAsync(user.Id, httpContext.RequestAborted); + await refreshTokenService.RevokeAllAsync(user.Id, CancellationToken.None); return TypedResults.Ok(); - }).WithName("AccountManagement_AddPassword").WithTags("Account management").WithSummary("Add a password to the current account"); + }).WithName("AccountManagement_AddPassword").WithTags("Account management").WithSummary("Add a password to the current account") + .Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status401Unauthorized) + .Produces(StatusCodes.Status403Forbidden); return endpoints; } diff --git a/RuntimeApps.Authentication/Endpoints/PasswordRecovery/ForgotPasswordApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/PasswordRecovery/ForgotPasswordApiEndpointRouteBuilderExtensions.cs index 2143985..4c76969 100644 --- a/RuntimeApps.Authentication/Endpoints/PasswordRecovery/ForgotPasswordApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/PasswordRecovery/ForgotPasswordApiEndpointRouteBuilderExtensions.cs @@ -45,9 +45,10 @@ public static IEndpointRouteBuilder MapPasswordRecoveryApi( HttpContext httpContext) => { var result = await service.RequestAsync(request?.Email, httpContext.RequestAborted); return TypedResults.Ok(result); - }).WithName("PasswordRecovery_Forgot").WithTags("Password recovery").WithSummary("Request a password reset"); + }).WithName("PasswordRecovery_Forgot").WithTags("Password recovery").WithSummary("Request a password reset") + .Produces(StatusCodes.Status200OK); - group.MapPost("reset-password", async Task> ( + group.MapPost("reset-password", async Task ( [FromBody] ResetPasswordModel request, IForgotPasswordService service, HttpContext httpContext) => { @@ -59,9 +60,11 @@ public static IEndpointRouteBuilder MapPasswordRecoveryApi( request.VerificationHandle, request.Credential, request.NewPassword, httpContext.RequestAborted); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }).WithName("PasswordRecovery_Reset").WithTags("Password recovery").WithSummary("Reset a password"); + }).WithName("PasswordRecovery_Reset").WithTags("Password recovery").WithSummary("Reset a password") + .Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest); return endpoints; } diff --git a/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs index 297a3e5..28994ae 100644 --- a/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/RefreshTokens/RefreshTokenApiEndpointRouteBuilderExtensions.cs @@ -1,4 +1,5 @@ using System.Net.Http.Json; +using System.Text.Json; using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Http; @@ -13,6 +14,7 @@ using RuntimeApps.Authentication.Features.Account.Models; using RuntimeApps.Authentication.Features.Account.Contracts; using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Shared.Models; namespace RuntimeApps.Authentication.Endpoints.RefreshTokens { public static class RefreshTokenApiEndpointRouteBuilderExtensions { /// @@ -48,8 +50,10 @@ public static IEndpointRouteBuilder MapSessionApi(this IEndpointRou var mode = GetSessionMode(sessionIssuers); var isCookie = mode == AuthenticationSessionMode.Cookie; RefreshTokenRequest request = null; - if(!isCookie && context.Request.HasJsonContentType()) - request = await context.Request.ReadFromJsonAsync(context.RequestAborted); + if(!isCookie && context.Request.HasJsonContentType()) { + try { request = await context.Request.ReadFromJsonAsync(context.RequestAborted); } + catch(JsonException) { return Results.Problem(statusCode: StatusCodes.Status400BadRequest, title: "Invalid request", detail: "The request body is invalid."); } + } if(isCookie && !IsAllowedOrigin(context, options.Value)) return Results.StatusCode(StatusCodes.Status403Forbidden); @@ -63,7 +67,7 @@ public static IEndpointRouteBuilder MapSessionApi(this IEndpointRou var user = await userManager.FindByIdAsync(Convert.ToString(session.UserId, System.Globalization.CultureInfo.InvariantCulture)); if(user == null) { - await refreshTokenService.RevokeAsync(session.RefreshToken, context.RequestAborted); + await refreshTokenService.RevokeAsync(session.RefreshToken, CancellationToken.None); return Results.Unauthorized(); } @@ -73,7 +77,7 @@ public static IEndpointRouteBuilder MapSessionApi(this IEndpointRou (hasExternalLogin && !verificationOptions.Value.RequireEmailVerificationForExternalLogins); if(isLockedOut || !emailPolicyAllowsSignIn || (user.EmailConfirmed && !await signInManager.CanSignInAsync(user))) { - await refreshTokenService.RevokeAsync(session.RefreshToken, context.RequestAborted); + await refreshTokenService.RevokeAsync(session.RefreshToken, CancellationToken.None); return Results.Unauthorized(); } @@ -107,7 +111,14 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal, .WithName("Session_Refresh") .WithTags("Sessions") .WithSummary("Refresh the current session") - .WithDescription("JWT clients send a RefreshTokenRequest JSON body. Cookie clients send the refresh-token cookie; the JSON body is optional for cookie authentication."); + .WithDescription("JWT clients send a RefreshTokenRequest JSON body. Cookie clients send the refresh-token cookie; the JSON body is optional for cookie authentication.") + .Produces(StatusCodes.Status200OK) + .Produces(StatusCodes.Status204NoContent) + .ProducesProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status401Unauthorized) + .Produces(StatusCodes.Status403Forbidden) + .Produces(StatusCodes.Status429TooManyRequests) + .ProducesProblem(StatusCodes.Status500InternalServerError); routes.MapPost("logout", async Task (HttpContext context, IRefreshTokenService refreshTokenService, @@ -116,8 +127,10 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal, IEnumerable> sessionIssuers) => { var isCookie = GetSessionMode(sessionIssuers) == AuthenticationSessionMode.Cookie; RefreshTokenRequest request = null; - if(!isCookie && context.Request.HasJsonContentType()) - request = await context.Request.ReadFromJsonAsync(context.RequestAborted); + if(!isCookie && context.Request.HasJsonContentType()) { + try { request = await context.Request.ReadFromJsonAsync(context.RequestAborted); } + catch(JsonException) { return Results.Problem(statusCode: StatusCodes.Status400BadRequest, title: "Invalid request", detail: "The request body is invalid."); } + } if(isCookie && !IsAllowedOrigin(context, options.Value)) return Results.StatusCode(StatusCodes.Status403Forbidden); @@ -136,7 +149,10 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal, .WithName("Session_Logout") .WithTags("Sessions") .WithSummary("Log out the current session") - .WithDescription("JWT clients send a RefreshTokenRequest JSON body. Cookie clients send the refresh-token cookie; the JSON body is optional for cookie authentication."); + .WithDescription("JWT clients send a RefreshTokenRequest JSON body. Cookie clients send the refresh-token cookie; the JSON body is optional for cookie authentication.") + .Produces(StatusCodes.Status204NoContent) + .ProducesProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status403Forbidden); routes.MapPost("logout/all", async Task (HttpContext context, IUserManager userManager, @@ -158,7 +174,10 @@ await context.SignInAsync(cookieOptions.Value.Scheme, principal, if(isCookie) DeleteRefreshCookie(context, options.Value); return Results.NoContent(); - }).RequireAuthorization().WithName("Session_LogoutAll").WithTags("Sessions").WithSummary("Log out all sessions"); + }).RequireAuthorization().WithName("Session_LogoutAll").WithTags("Sessions").WithSummary("Log out all sessions") + .Produces(StatusCodes.Status204NoContent) + .Produces(StatusCodes.Status401Unauthorized) + .Produces(StatusCodes.Status403Forbidden); return endpoints; } diff --git a/RuntimeApps.Authentication/Endpoints/Roles/Models/RoleRequest.cs b/RuntimeApps.Authentication/Endpoints/Roles/Models/RoleRequest.cs new file mode 100644 index 0000000..cb93240 --- /dev/null +++ b/RuntimeApps.Authentication/Endpoints/Roles/Models/RoleRequest.cs @@ -0,0 +1,9 @@ +using System.ComponentModel.DataAnnotations; + +namespace RuntimeApps.Authentication.Endpoints.Roles.Models { + /// + /// Request body for role creation and updates. The generic payload preserves consumer-defined + /// role fields while keeping the public operation envelope explicit. + /// + public sealed record RoleRequest([property: Required] TRole Role) where TRole : class; +} diff --git a/RuntimeApps.Authentication/Endpoints/Roles/RoleApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/Roles/RoleApiEndpointRouteBuilderExtensions.cs index b7ff7a9..79f0aa3 100644 --- a/RuntimeApps.Authentication/Endpoints/Roles/RoleApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/Roles/RoleApiEndpointRouteBuilderExtensions.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Endpoints.Roles.Models; using RuntimeApps.Authentication.Shared.Extensions; namespace RuntimeApps.Authentication.Endpoints.Roles { public static class RoleApiEndpointRouteBuilderExtensions { @@ -11,17 +12,26 @@ public static IEndpointRouteBuilder MapRoleGetApi(this IEndpointRouteBuil where TRole : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapGet("{roleId}", async Task ([FromRoute] string roleId, IRoleManager roleManager) => { - return await roleManager.FindByIdAsync(roleId); - }); + routeGroup.MapGet("{roleId}", async Task ([FromRoute] string roleId, IRoleManager roleManager, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); + var role = await roleManager.FindByIdAsync(roleId); + cancellationToken.ThrowIfCancellationRequested(); + return role == null ? TypedResults.NotFound() : TypedResults.Ok(role); + }).Produces(StatusCodes.Status200OK) + .Produces(StatusCodes.Status404NotFound); - routeGroup.MapGet("name/{roleName}", async Task ([FromRoute] string roleName, IRoleManager roleManager) => { - return await roleManager.FindByNameAsync(roleName); - }); + routeGroup.MapGet("name/{roleName}", async Task ([FromRoute] string roleName, IRoleManager roleManager, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); + var role = await roleManager.FindByNameAsync(roleName); + cancellationToken.ThrowIfCancellationRequested(); + return role == null ? TypedResults.NotFound() : TypedResults.Ok(role); + }).Produces(StatusCodes.Status200OK) + .Produces(StatusCodes.Status404NotFound); - routeGroup.MapGet("/", IEnumerable (IRoleManager roleManager) => { + routeGroup.MapGet("/", IEnumerable (IRoleManager roleManager, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); return roleManager.Roles.ToList(); - }); + }).Produces>(StatusCodes.Status200OK); return endpoints; } @@ -30,33 +40,45 @@ public static IEndpointRouteBuilder MapRoleManageApi(this IEndpointRouteB where TRole : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapPost("/", async Task> ([FromBody] TRole role, IRoleManager roleManager) => { - var result = await roleManager.CreateAsync(role); + routeGroup.MapPost("/", async Task ([FromBody] RoleRequest request, IRoleManager roleManager, CancellationToken cancellationToken) => { + if(request?.Role == null) + return ValidationProblemFactory.CreateValidationProblem("InvalidRole", "Role is required."); + cancellationToken.ThrowIfCancellationRequested(); + var result = await roleManager.CreateAsync(request.Role); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest); - routeGroup.MapPut("/", async Task> ([FromBody] TRole role, IRoleManager roleManager) => { - var result = await roleManager.UpdateAsync(role); + routeGroup.MapPut("/", async Task ([FromBody] RoleRequest request, IRoleManager roleManager, CancellationToken cancellationToken) => { + if(request?.Role == null) + return ValidationProblemFactory.CreateValidationProblem("InvalidRole", "Role is required."); + cancellationToken.ThrowIfCancellationRequested(); + var result = await roleManager.UpdateAsync(request.Role); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest); - routeGroup.MapDelete("{roleId}", async Task> ([FromRoute] string roleId, IRoleManager roleManager) => { + routeGroup.MapDelete("{roleId}", async Task ([FromRoute] string roleId, IRoleManager roleManager, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); var role = await roleManager.FindByIdAsync(roleId); if(role == null) - return ValidationProblemFactory.CreateValidationProblem("NotFound", "Role Not Found"); + return TypedResults.NotFound(); + cancellationToken.ThrowIfCancellationRequested(); var result = await roleManager.DeleteAsync(role); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); + }).Produces(StatusCodes.Status200OK) + .Produces(StatusCodes.Status404NotFound) + .ProducesValidationProblem(StatusCodes.Status400BadRequest); return endpoints; } diff --git a/RuntimeApps.Authentication/Endpoints/Roles/RoleClaimApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/Roles/RoleClaimApiEndpointRouteBuilderExtensions.cs index 9fbb085..4732aad 100644 --- a/RuntimeApps.Authentication/Endpoints/Roles/RoleClaimApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/Roles/RoleClaimApiEndpointRouteBuilderExtensions.cs @@ -12,14 +12,17 @@ public static IEndpointRouteBuilder MapRoleClaimGetApi(this IEndpointRout where TRole : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapGet("{roleId}/Claim", async Task>, ValidationProblem>> ([FromRoute] string roleId, IRoleManager roleManager, HttpContext httpContext) => { + routeGroup.MapGet("{roleId}/Claim", async Task ([FromRoute] string roleId, IRoleManager roleManager, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); var role = await roleManager.FindByIdAsync(roleId); if(role == null) return RoleNotFound(); + cancellationToken.ThrowIfCancellationRequested(); var result = await roleManager.GetClaimsAsync(role); + cancellationToken.ThrowIfCancellationRequested(); return TypedResults.Ok>(result.Select(c => new ClaimDto(c))); - }); + }).Produces>(StatusCodes.Status200OK).Produces(StatusCodes.Status404NotFound); return endpoints; } @@ -28,33 +31,47 @@ public static IEndpointRouteBuilder MapRoleClaimManageApi(this IEndpointR where TRole : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapPost("{roleId}/Claim", async Task> ([FromRoute] string roleId, [FromBody] ClaimDto claim, IRoleManager roleManager, HttpContext httpContext) => { + routeGroup.MapPost("{roleId}/Claim", async Task ([FromRoute] string roleId, [FromBody] ClaimDto claim, IRoleManager roleManager, CancellationToken cancellationToken) => { + if(!IsValidClaim(claim)) + return ValidationProblemFactory.CreateValidationProblem("InvalidClaim", "Claim type and value are required."); + cancellationToken.ThrowIfCancellationRequested(); var role = await roleManager.FindByIdAsync(roleId); if(role == null) return RoleNotFound(); + cancellationToken.ThrowIfCancellationRequested(); var result = await roleManager.AddClaimAsync(role, claim.ToClaim()); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status404NotFound); - routeGroup.MapDelete("{roleId}/Claim", async Task> ([FromRoute] string roleId, [FromBody] ClaimDto claim, IRoleManager roleManager, HttpContext httpContext) => { + routeGroup.MapDelete("{roleId}/Claim", async Task ([FromRoute] string roleId, [FromBody] ClaimDto claim, IRoleManager roleManager, CancellationToken cancellationToken) => { + if(!IsValidClaim(claim)) + return ValidationProblemFactory.CreateValidationProblem("InvalidClaim", "Claim type and value are required."); + cancellationToken.ThrowIfCancellationRequested(); var role = await roleManager.FindByIdAsync(roleId); if(role == null) return RoleNotFound(); + cancellationToken.ThrowIfCancellationRequested(); var result = await roleManager.RemoveClaimAsync(role, claim.ToClaim()); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status404NotFound); return endpoints; } - private static ValidationProblem RoleNotFound() => - ValidationProblemFactory.CreateValidationProblem("NotFound", "Role Not Found"); + private static IResult RoleNotFound() => TypedResults.NotFound(); + + private static bool IsValidClaim(ClaimDto claim) => + claim != null && !string.IsNullOrWhiteSpace(claim.Type) && claim.Value != null; } } diff --git a/RuntimeApps.Authentication/Endpoints/Users/UserApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/Users/UserApiEndpointRouteBuilderExtensions.cs index 1553aaf..2136ecd 100644 --- a/RuntimeApps.Authentication/Endpoints/Users/UserApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/Users/UserApiEndpointRouteBuilderExtensions.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using RuntimeApps.Authentication.Identity.Contracts; @@ -9,15 +10,21 @@ public static IEndpointRouteBuilder MapUserGetApi(this IEndpoin where TUserDto : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapGet("{userId}", async Task ([FromRoute] string userId, IUserManager userManager, [FromServices] IUserMapper mapper) => { + routeGroup.MapGet("{userId}", async Task ([FromRoute] string userId, IUserManager userManager, [FromServices] IUserMapper mapper, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.FindByIdAsync(userId); - return user != default ? mapper.ToDto(user) : default; - }); + cancellationToken.ThrowIfCancellationRequested(); + return user != default ? TypedResults.Ok(mapper.ToDto(user)) : TypedResults.NotFound(); + }).Produces(StatusCodes.Status200OK) + .Produces(StatusCodes.Status404NotFound); - routeGroup.MapGet("/", async Task ([FromQuery] string userName, IUserManager userManager, [FromServices] IUserMapper mapper) => { + routeGroup.MapGet("/", async Task ([FromQuery] string userName, IUserManager userManager, [FromServices] IUserMapper mapper, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.FindByNameAsync(userName); - return user != default ? mapper.ToDto(user) : default; - }); + cancellationToken.ThrowIfCancellationRequested(); + return user != default ? TypedResults.Ok(mapper.ToDto(user)) : TypedResults.NotFound(); + }).Produces(StatusCodes.Status200OK) + .Produces(StatusCodes.Status404NotFound); return endpoints; } diff --git a/RuntimeApps.Authentication/Endpoints/Users/UserClaimApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/Users/UserClaimApiEndpointRouteBuilderExtensions.cs index 16e01ec..2a22886 100644 --- a/RuntimeApps.Authentication/Endpoints/Users/UserClaimApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/Users/UserClaimApiEndpointRouteBuilderExtensions.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Features.Account.Models; using RuntimeApps.Authentication.Shared.Extensions; using RuntimeApps.Authentication.Shared.Models; namespace RuntimeApps.Authentication.Endpoints.Users { @@ -12,14 +13,18 @@ public static IEndpointRouteBuilder MapUserClaimGetApi(this IEndpointRout where TUser : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapGet("{userId}/claim", async Task>, ValidationProblem>> ([FromRoute] string userId, IUserManager userManager, IUserClaimManager claimManager) => { + routeGroup.MapGet("{userId}/claim", async Task ([FromRoute] string userId, IUserManager userManager, IUserClaimManager claimManager, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); + cancellationToken.ThrowIfCancellationRequested(); var result = await claimManager.GetClaimsAsync(user); + cancellationToken.ThrowIfCancellationRequested(); return TypedResults.Ok(result?.Select(c => new ClaimDto(c))); - }); + }).Produces>(StatusCodes.Status200OK) + .Produces(StatusCodes.Status404NotFound); return endpoints; } @@ -27,55 +32,84 @@ public static IEndpointRouteBuilder MapUserClaimManageApi(this IEndpointR where TUser : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapPost("{userId}/claim", async Task> ([FromRoute] string userId, [FromBody] ClaimDto claim, IUserManager userManager, IUserClaimManager claimManager) => { + routeGroup.MapPost("{userId}/claim", async Task ([FromRoute] string userId, [FromBody] ClaimDto claim, IUserManager userManager, IUserClaimManager claimManager, CancellationToken cancellationToken) => { + if(!IsValidClaim(claim)) + return ValidationProblemFactory.CreateValidationProblem("InvalidClaim", "Claim type and value are required."); + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); + cancellationToken.ThrowIfCancellationRequested(); var result = await claimManager.AddClaimAsync(user, claim.ToClaim()); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status404NotFound); - routeGroup.MapDelete("{userId}/claim", async Task> ([FromRoute] string userId, [FromBody] ClaimDto claim, IUserManager userManager, IUserClaimManager claimManager) => { + routeGroup.MapDelete("{userId}/claim", async Task ([FromRoute] string userId, [FromBody] ClaimDto claim, IUserManager userManager, IUserClaimManager claimManager, CancellationToken cancellationToken) => { + if(!IsValidClaim(claim)) + return ValidationProblemFactory.CreateValidationProblem("InvalidClaim", "Claim type and value are required."); + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); + cancellationToken.ThrowIfCancellationRequested(); var result = await claimManager.RemoveClaimAsync(user, claim.ToClaim()); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status404NotFound); - routeGroup.MapPost("{userId}/claim/bulk", async Task> ([FromRoute] string userId, [FromBody] IEnumerable claims, IUserManager userManager, IUserClaimManager claimManager) => { + routeGroup.MapPost("{userId}/claim/bulk", async Task ([FromRoute] string userId, [FromBody] BulkClaimsRequest request, IUserManager userManager, IUserClaimManager claimManager, CancellationToken cancellationToken) => { + if(!HasValidClaims(request?.Claims)) + return ValidationProblemFactory.CreateValidationProblem("InvalidClaims", "Provide at least one claim with a type and value."); + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await claimManager.AddClaimsAsync(user, claims.Select(c => c.ToClaim())); + cancellationToken.ThrowIfCancellationRequested(); + var result = await claimManager.AddClaimsAsync(user, request.Claims.Select(c => c.ToClaim())); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status404NotFound); - routeGroup.MapDelete("{userId}/claim/bulk", async Task> ([FromRoute] string userId, [FromBody] IEnumerable claims, IUserManager userManager, IUserClaimManager claimManager) => { + routeGroup.MapDelete("{userId}/claim/bulk", async Task ([FromRoute] string userId, [FromBody] BulkClaimsRequest request, IUserManager userManager, IUserClaimManager claimManager, CancellationToken cancellationToken) => { + if(!HasValidClaims(request?.Claims)) + return ValidationProblemFactory.CreateValidationProblem("InvalidClaims", "Provide at least one claim with a type and value."); + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await claimManager.RemoveClaimsAsync(user, claims.Select(c => c.ToClaim())); + cancellationToken.ThrowIfCancellationRequested(); + var result = await claimManager.RemoveClaimsAsync(user, request.Claims.Select(c => c.ToClaim())); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status404NotFound); return endpoints; } - private static ValidationProblem UserNotFound() => - ValidationProblemFactory.CreateValidationProblem("NotFound", "User not found"); + private static IResult UserNotFound() => TypedResults.NotFound(); + + private static bool IsValidClaim(ClaimDto claim) => + claim != null && !string.IsNullOrWhiteSpace(claim.Type) && claim.Value != null; + + private static bool HasValidClaims(IReadOnlyCollection claims) => + claims is { Count: > 0 } && claims.All(IsValidClaim); } } diff --git a/RuntimeApps.Authentication/Endpoints/Users/UserRoleApiEndpointRouteBuilderExtensions.cs b/RuntimeApps.Authentication/Endpoints/Users/UserRoleApiEndpointRouteBuilderExtensions.cs index 26637db..db461e4 100644 --- a/RuntimeApps.Authentication/Endpoints/Users/UserRoleApiEndpointRouteBuilderExtensions.cs +++ b/RuntimeApps.Authentication/Endpoints/Users/UserRoleApiEndpointRouteBuilderExtensions.cs @@ -4,6 +4,7 @@ using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Routing; using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Features.Account.Models; using RuntimeApps.Authentication.Shared.Extensions; namespace RuntimeApps.Authentication.Endpoints.Users { public static class UserRoleApiEndpointRouteBuilderExtensions { @@ -11,14 +12,18 @@ public static IEndpointRouteBuilder MapUserRoleGetApi(this IEndpointRoute where TUser : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapGet("{userId}/Role", async Task>, ValidationProblem>> ([FromRoute] string userId, IUserManager userManager, IUserRoleManager roleManager) => { + routeGroup.MapGet("{userId}/Role", async Task ([FromRoute] string userId, IUserManager userManager, IUserRoleManager roleManager, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); + cancellationToken.ThrowIfCancellationRequested(); var result = await roleManager.GetRolesAsync(user); + cancellationToken.ThrowIfCancellationRequested(); return TypedResults.Ok(result); - }); + }).Produces>(StatusCodes.Status200OK) + .Produces(StatusCodes.Status404NotFound); return endpoints; } @@ -27,59 +32,81 @@ public static IEndpointRouteBuilder MapUserRoleManageApi(this IEndpointRo where TUser : class { var routeGroup = endpoints.MapGroup(""); - routeGroup.MapPost("{userId}/Role", async Task> ([FromRoute] string userId, [FromBody] IEnumerable roles, IUserManager userManager, IUserRoleManager roleManager) => { + routeGroup.MapPost("{userId}/Role", async Task ([FromRoute] string userId, [FromBody] UserRolesRequest request, IUserManager userManager, IUserRoleManager roleManager, CancellationToken cancellationToken) => { + if(!HasValidRoles(request?.Roles)) + return ValidationProblemFactory.CreateValidationProblem("InvalidRoles", "Provide at least one non-empty role name."); + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await roleManager.AddToRolesAsync(user, roles); + cancellationToken.ThrowIfCancellationRequested(); + var result = await roleManager.AddToRolesAsync(user, request.Roles); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); - - routeGroup.MapDelete("{userId}/Role", async Task> ([FromRoute] string userId, [FromBody] IEnumerable roles, IUserManager userManager, IUserRoleManager roleManager) => { + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status404NotFound); + + routeGroup.MapDelete("{userId}/Role", async Task ([FromRoute] string userId, [FromBody] UserRolesRequest request, IUserManager userManager, IUserRoleManager roleManager, CancellationToken cancellationToken) => { + if(!HasValidRoles(request?.Roles)) + return ValidationProblemFactory.CreateValidationProblem("InvalidRoles", "Provide at least one non-empty role name."); + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); - var result = await roleManager.RemoveFromRolesAsync(user, roles); + cancellationToken.ThrowIfCancellationRequested(); + var result = await roleManager.RemoveFromRolesAsync(user, request.Roles); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status404NotFound); - routeGroup.MapPost("{userId}/Role/{roleName}", async Task> ([FromRoute] string userId, [FromRoute] string roleName, IUserManager userManager, IUserRoleManager roleManager) => { + routeGroup.MapPost("{userId}/Role/{roleName}", async Task ([FromRoute] string userId, [FromRoute] string roleName, IUserManager userManager, IUserRoleManager roleManager, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); + cancellationToken.ThrowIfCancellationRequested(); var result = await roleManager.AddToRoleAsync(user, roleName); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status404NotFound); - routeGroup.MapDelete("{userId}/Role/{roleName}", async Task> ([FromRoute] string userId, [FromRoute] string roleName, IUserManager userManager, IUserRoleManager roleManager) => { + routeGroup.MapDelete("{userId}/Role/{roleName}", async Task ([FromRoute] string userId, [FromRoute] string roleName, IUserManager userManager, IUserRoleManager roleManager, CancellationToken cancellationToken) => { + cancellationToken.ThrowIfCancellationRequested(); var user = await userManager.FindByIdAsync(userId); if(user == null) return UserNotFound(); + cancellationToken.ThrowIfCancellationRequested(); var result = await roleManager.RemoveFromRoleAsync(user, roleName); if(!result.Succeeded) - return result.CreateValidationProblem(); + return result.CreatePublicError(); return TypedResults.Ok(); - }); + }).Produces(StatusCodes.Status200OK) + .ProducesValidationProblem(StatusCodes.Status400BadRequest) + .Produces(StatusCodes.Status404NotFound); return endpoints; } - private static ValidationProblem UserNotFound() => - ValidationProblemFactory.CreateValidationProblem("NotFound", "User not found"); + private static IResult UserNotFound() => TypedResults.NotFound(); + + private static bool HasValidRoles(IReadOnlyCollection roles) => + roles is { Count: > 0 } && roles.All(role => !string.IsNullOrWhiteSpace(role)); } } diff --git a/RuntimeApps.Authentication/Features/Account/Models/AddPasswordRequest.cs b/RuntimeApps.Authentication/Features/Account/Models/AddPasswordRequest.cs new file mode 100644 index 0000000..d9752f5 --- /dev/null +++ b/RuntimeApps.Authentication/Features/Account/Models/AddPasswordRequest.cs @@ -0,0 +1,6 @@ +using System.ComponentModel.DataAnnotations; + +namespace RuntimeApps.Authentication.Features.Account.Models { + /// Request body for adding a password to the authenticated account. + public sealed record AddPasswordRequest([property: Required] string Password); +} diff --git a/RuntimeApps.Authentication/Features/Account/Models/AuthenticationContinuationResponse.cs b/RuntimeApps.Authentication/Features/Account/Models/AuthenticationContinuationResponse.cs new file mode 100644 index 0000000..618decf --- /dev/null +++ b/RuntimeApps.Authentication/Features/Account/Models/AuthenticationContinuationResponse.cs @@ -0,0 +1,4 @@ +namespace RuntimeApps.Authentication.Features.Account.Models { + /// Indicates that the first login step succeeded and another authentication step is required. + public sealed record AuthenticationContinuationResponse(bool RequiresTwoFactor = true); +} diff --git a/RuntimeApps.Authentication/Features/Account/Models/BulkClaimsRequest.cs b/RuntimeApps.Authentication/Features/Account/Models/BulkClaimsRequest.cs new file mode 100644 index 0000000..7042aab --- /dev/null +++ b/RuntimeApps.Authentication/Features/Account/Models/BulkClaimsRequest.cs @@ -0,0 +1,7 @@ +using System.ComponentModel.DataAnnotations; +using RuntimeApps.Authentication.Shared.Models; + +namespace RuntimeApps.Authentication.Features.Account.Models { + /// Request body for applying or removing multiple user claims. + public sealed record BulkClaimsRequest([property: Required, MinLength(1)] IReadOnlyCollection Claims); +} diff --git a/RuntimeApps.Authentication/Features/Account/Models/ChangePasswordModel.cs b/RuntimeApps.Authentication/Features/Account/Models/ChangePasswordModel.cs index 617b8e3..6406ee8 100644 --- a/RuntimeApps.Authentication/Features/Account/Models/ChangePasswordModel.cs +++ b/RuntimeApps.Authentication/Features/Account/Models/ChangePasswordModel.cs @@ -1,6 +1,10 @@ +using System.ComponentModel.DataAnnotations; + namespace RuntimeApps.Authentication.Features.Account.Models { public class ChangePasswordModel { + [Required] public string CurrentPassword { get; set; } + [Required] public string NewPassword { get; set; } } } diff --git a/RuntimeApps.Authentication/Features/Account/Models/UserLoginModel.cs b/RuntimeApps.Authentication/Features/Account/Models/UserLoginModel.cs index 9320a76..a2e4922 100644 --- a/RuntimeApps.Authentication/Features/Account/Models/UserLoginModel.cs +++ b/RuntimeApps.Authentication/Features/Account/Models/UserLoginModel.cs @@ -1,6 +1,10 @@ +using System.ComponentModel.DataAnnotations; + namespace RuntimeApps.Authentication.Features.Account.Models { public class UserLoginModel { + [Required] public string UserName { get; set; } + [Required] public string Password { get; set; } } } diff --git a/RuntimeApps.Authentication/Features/Account/Models/UserRolesRequest.cs b/RuntimeApps.Authentication/Features/Account/Models/UserRolesRequest.cs new file mode 100644 index 0000000..25ef662 --- /dev/null +++ b/RuntimeApps.Authentication/Features/Account/Models/UserRolesRequest.cs @@ -0,0 +1,6 @@ +using System.ComponentModel.DataAnnotations; + +namespace RuntimeApps.Authentication.Features.Account.Models { + /// Request body for assigning or removing roles from a user. + public sealed record UserRolesRequest([property: Required, MinLength(1)] IReadOnlyCollection Roles); +} diff --git a/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs b/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs index 3a434d6..09d69a5 100644 --- a/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs +++ b/RuntimeApps.Authentication/Features/Account/Services/UserAccountService.cs @@ -71,43 +71,49 @@ public virtual async Task> ExternalLoginAsync(string provid cancellationToken.ThrowIfCancellationRequested(); var provider = _externalLoginProviders.FirstOrDefault(p => string.Equals(p.Provider, providerName, StringComparison.OrdinalIgnoreCase)); if(provider == null) - return new Result(ResultCode.BadRequest, Result.CreateErrors("Unknown provider", "Provider is not added to system")); + return ExternalAuthenticationFailed(); var providerResult = await provider.ValidateAsync(token, cancellationToken); if(providerResult?.LoginInfo == null || providerResult.User == null) - return new Result(ResultCode.BadRequest, Result.CreateErrors("Invalid token", "Invalid External Authentication.")); + 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) { - // Never link an external identity to an existing account based on an unverified email. - if(!trustedEmail) - return new Result( - ResultCode.Conflict, - Result.CreateErrors("ExternalAccountLinkRequired", "Sign in to the existing account before linking this external provider.")); - user = existingEmailUser; - if(!user.EmailConfirmed) { + 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); - cancellationToken.ThrowIfCancellationRequested(); - if(!updateResult.Succeeded) - return new Result(ResultCode.BadRequest, updateResult.Errors); + 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(); + } } - - var addLoginResult = await _loginManager.AddLoginAsync(user, loginInfo); - cancellationToken.ThrowIfCancellationRequested(); - if(!addLoginResult.Succeeded) - return new Result(ResultCode.BadRequest, addLoginResult.Errors); } else { user = providerResult.User; if(string.IsNullOrWhiteSpace(user.Email)) @@ -119,32 +125,34 @@ public virtual async Task> ExternalLoginAsync(string provid user.EmailConfirmed = trustedEmail; var createResult = await _userManager.CreateAsync(user); - cancellationToken.ThrowIfCancellationRequested(); if(!createResult.Succeeded) - return new Result(ResultCode.BadRequest, createResult.Errors); + return ExternalAuthenticationFailed(); var addLoginResult = await _loginManager.AddLoginAsync(user, loginInfo); - cancellationToken.ThrowIfCancellationRequested(); if(!addLoginResult.Succeeded) - return new Result(ResultCode.BadRequest, addLoginResult.Errors); + // 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) - return new Result(ResultCode.BadRequest, Result.CreateErrors("Add_Error", "User cannot added")); + return ExternalAuthenticationFailed(); + + // The non-cancellable Identity writes above are now consistent. Honor cancellation + // before sending verification or issuing an authentication session. + cancellationToken.ThrowIfCancellationRequested(); if(_verificationOptions.RequireEmailVerificationForExternalLogins && !user.EmailConfirmed) { if(string.IsNullOrWhiteSpace(user.Email) || _verificationWorkflow == null) - return new Result( - ResultCode.Forbidden, - Result.CreateErrors("EmailVerificationRequired", "Email verification is required but no verified email address or verification workflow is available.")); + return ExternalAuthenticationFailed(); var verification = await _verificationWorkflow.StartAsync( user, VerificationPurpose.Registration, VerificationChannel.Email, user.Email, cancellationToken: cancellationToken); if(!verification.Succeeded) - return new Result( - ResultCode.Forbidden, - Result.CreateErrors(verification.ErrorCode, verification.ErrorDescription)); + return ExternalAuthenticationFailed(); return new Result(user, new Token { VerificationRequired = true, @@ -156,6 +164,10 @@ public virtual async Task> ExternalLoginAsync(string provid return await GenerateTokenAsync(user, cancellationToken); } + private static Result ExternalAuthenticationFailed() => + new(ResultCode.BadRequest, Result.CreateErrors( + "ExternalAuthenticationFailed", "External authentication could not be completed.")); + /// Identity lookup and password sign-in abstractions in ASP.NET Core do not expose cancellation overloads. public virtual async Task> LoginAsync(string userName, string password, CancellationToken cancellationToken = default) { cancellationToken.ThrowIfCancellationRequested(); @@ -182,21 +194,12 @@ public virtual Task> CompleteRegistrationAsync(TUser user, } protected virtual Result GetIdentityError(SignInResult signInResult) { - ResultCode code = ResultCode.BadRequest; - var description = "Username or password is incorrect"; - if(signInResult.IsNotAllowed) { - description = "You are not allowed to login"; - code = ResultCode.Forbidden; - } - else if(signInResult.IsLockedOut) { - description = "You are locked out"; - code = ResultCode.Conflict; - } - else if(signInResult.RequiresTwoFactor) { - description = "Two factor authentication required"; - code = ResultCode.Accepted; - } - return new Result(code, Result.CreateErrors(signInResult.ToString(), description)); + if(signInResult.RequiresTwoFactor) + return new Result(ResultCode.Accepted, Result.CreateErrors("TwoFactorRequired", "A second authentication step is required.")); + + // Keep all credential-state failures identical at the public boundary. + return new Result(ResultCode.BadRequest, + Result.CreateErrors("AuthenticationFailed", "The username or password is incorrect.")); } protected virtual async Task> GenerateTokenAsync(TUser user, CancellationToken cancellationToken = default) { diff --git a/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalAuthModel.cs b/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalAuthModel.cs index 303d04f..14d0364 100644 --- a/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalAuthModel.cs +++ b/RuntimeApps.Authentication/Features/ExternalLogin/Models/ExternalAuthModel.cs @@ -1,6 +1,10 @@ +using System.ComponentModel.DataAnnotations; + namespace RuntimeApps.Authentication.Features.ExternalLogin.Models { public class ExternalAuthModel { + [Required] public string Provider { get; set; } + [Required] public string Token { get; set; } } } diff --git a/RuntimeApps.Authentication/Features/PasswordRecovery/Services/ForgotPasswordService.cs b/RuntimeApps.Authentication/Features/PasswordRecovery/Services/ForgotPasswordService.cs index d50f5f2..df35fe8 100644 --- a/RuntimeApps.Authentication/Features/PasswordRecovery/Services/ForgotPasswordService.cs +++ b/RuntimeApps.Authentication/Features/PasswordRecovery/Services/ForgotPasswordService.cs @@ -117,7 +117,9 @@ public async Task ResetAsync( return new Result(ResultCode.BadRequest, resetResult.Errors); if(_refreshTokens != null) - await _refreshTokens.RevokeAllAsync(verification.Data.Id, cancellationToken); + // The password has already changed; finish session invalidation even if the + // client disconnects during this cleanup step. + await _refreshTokens.RevokeAllAsync(verification.Data.Id, CancellationToken.None); return new Result(); } diff --git a/RuntimeApps.Authentication/Features/Registration/Models/RegisterUserModel.cs b/RuntimeApps.Authentication/Features/Registration/Models/RegisterUserModel.cs index 0659bfd..7093dc8 100644 --- a/RuntimeApps.Authentication/Features/Registration/Models/RegisterUserModel.cs +++ b/RuntimeApps.Authentication/Features/Registration/Models/RegisterUserModel.cs @@ -1,7 +1,11 @@ +using System.ComponentModel.DataAnnotations; + namespace RuntimeApps.Authentication.Features.Registration.Models { public class RegisterUserModel where TUser : class { + [Required] public TUser UserInfo { get; set; } + [Required] public string Password { get; set; } } } diff --git a/RuntimeApps.Authentication/Features/Registration/Models/ResendRegistrationVerificationModel.cs b/RuntimeApps.Authentication/Features/Registration/Models/ResendRegistrationVerificationModel.cs index 1e5c9ba..0004f2b 100644 --- a/RuntimeApps.Authentication/Features/Registration/Models/ResendRegistrationVerificationModel.cs +++ b/RuntimeApps.Authentication/Features/Registration/Models/ResendRegistrationVerificationModel.cs @@ -1,5 +1,8 @@ +using System.ComponentModel.DataAnnotations; + namespace RuntimeApps.Authentication.Features.Registration.Models { public sealed class ResendRegistrationVerificationModel { + [Required] public string VerificationHandle { get; set; } } } diff --git a/RuntimeApps.Authentication/Features/Registration/Models/VerifyRegistrationModel.cs b/RuntimeApps.Authentication/Features/Registration/Models/VerifyRegistrationModel.cs index 80b0157..8f79d70 100644 --- a/RuntimeApps.Authentication/Features/Registration/Models/VerifyRegistrationModel.cs +++ b/RuntimeApps.Authentication/Features/Registration/Models/VerifyRegistrationModel.cs @@ -1,6 +1,10 @@ +using System.ComponentModel.DataAnnotations; + namespace RuntimeApps.Authentication.Features.Registration.Models { public sealed class VerifyRegistrationModel { + [Required] public string VerificationHandle { get; set; } + [Required] public string Code { get; set; } } } diff --git a/RuntimeApps.Authentication/Features/Registration/Services/RegistrationService.cs b/RuntimeApps.Authentication/Features/Registration/Services/RegistrationService.cs index 050ea07..1433cd9 100644 --- a/RuntimeApps.Authentication/Features/Registration/Services/RegistrationService.cs +++ b/RuntimeApps.Authentication/Features/Registration/Services/RegistrationService.cs @@ -37,6 +37,7 @@ public RegistrationService( public async Task> RegisterAsync( TUser user, string password, CancellationToken cancellationToken = default) { ArgumentNullException.ThrowIfNull(user); + cancellationToken.ThrowIfCancellationRequested(); if(string.IsNullOrWhiteSpace(user.Email) || string.IsNullOrEmpty(password)) return Failure("InvalidRegistration", "Email and password are required."); @@ -44,6 +45,7 @@ public async Task> RegisterAsync( user.UserName = user.Email; var existingUser = await _emailManager.FindByEmailAsync(user.Email); + cancellationToken.ThrowIfCancellationRequested(); // Do not create or modify confirmed accounts. Keep the response indistinguishable // from a pending registration to avoid exposing whether an email is registered. if(existingUser?.EmailConfirmed == true) @@ -56,15 +58,12 @@ public async Task> RegisterAsync( user.EmailConfirmed = false; var createResult = await _userManager.CreateAsync(user, password); if(!createResult.Succeeded) { - // A concurrent registration may have created the account after our initial lookup. - var racedUser = await _emailManager.FindByEmailAsync(user.Email); - if(racedUser?.EmailConfirmed == true) + // Duplicate identifiers are intentionally indistinguishable from the + // generic confirmed-account response. This also covers races between + // the initial lookup and Identity's uniqueness check. + if(createResult.Errors.Any(error => error.Code is "DuplicateEmail" or "DuplicateUserName")) return GenericResponse(); - if(racedUser == null) - return new Result(ResultCode.BadRequest, createResult.Errors); - - // Another request created this pending account first. Reuse it unchanged. - user = racedUser; + return new Result(ResultCode.BadRequest, createResult.Errors); } } @@ -73,6 +72,9 @@ public async Task> RegisterAsync( user, VerificationPurpose.Registration, VerificationChannel.Email, user.Email, cancellationToken: cancellationToken); + if(!verificationResult.Succeeded && verificationResult.ErrorCode == "VerificationRateLimited") + return GenericResponse(); + if(!verificationResult.Succeeded) return Failure(verificationResult.ErrorCode, verificationResult.ErrorDescription); diff --git a/RuntimeApps.Authentication/Features/Verification/Services/VerificationWorkflowService.cs b/RuntimeApps.Authentication/Features/Verification/Services/VerificationWorkflowService.cs index f647f93..f277445 100644 --- a/RuntimeApps.Authentication/Features/Verification/Services/VerificationWorkflowService.cs +++ b/RuntimeApps.Authentication/Features/Verification/Services/VerificationWorkflowService.cs @@ -83,18 +83,34 @@ public async Task StartAsync( Status = VerificationRequestStatus.Pending }; - if(!await _store.TryCreateAsync(request, now.AddHours(-1), _options.MaximumSendsPerHour, cancellationToken)) + bool requestCreated; + try { + requestCreated = await _store.TryCreateAsync( + request, now.AddHours(-1), _options.MaximumSendsPerHour, cancellationToken); + } catch(OperationCanceledException) when(cancellationToken.IsCancellationRequested) { + // A relational commit may win the race with cancellation. If the request is + // present, finish its verifier and delivery so it is not left unusable. + var persisted = await _store.FindByHandleHashAsync(request.PublicHandleHash, CancellationToken.None); + if(persisted == null) + throw; + request = persisted; + requestCreated = true; + } + + if(!requestCreated) return VerificationOperationResult.Failure("VerificationRateLimited", "The verification send limit has been reached."); - var credential = await CreateCredentialAsync(user, request, handle, cancellationToken); + // The request is now persisted. Complete verifier setup and delivery even if the + // HTTP request is aborted so we do not leave a pending handle with no credential. + var credential = await CreateCredentialAsync(user, request, handle, CancellationToken.None); if(string.IsNullOrWhiteSpace(credential)) return VerificationOperationResult.Failure("VerificationCodeGenerationFailed", "A verification credential could not be generated."); var protectedVerifier = _verifier.CreateVerifier(credential, request); - if(!await _store.TrySetInitialVerifierAsync(request.Id, protectedVerifier, now, request.ExpiresAt, cancellationToken)) + if(!await _store.TrySetInitialVerifierAsync(request.Id, protectedVerifier, now, request.ExpiresAt, CancellationToken.None)) return VerificationOperationResult.Failure("VerificationRequestUnavailable", "The verification request could not be initialized."); var context = CreateContext(user, request, handle, credential); - await _sender.SendAsync(context, credential, request.ExpiresAt, cancellationToken); + await _sender.SendAsync(context, credential, request.ExpiresAt, CancellationToken.None); return VerificationOperationResult.Success(handle, request.ExpiresAt); } @@ -119,11 +135,26 @@ public async Task ResendAsync( return VerificationOperationResult.Failure("VerificationCodeGenerationFailed", "A verification credential could not be generated."); var newVerifier = _verifier.CreateVerifier(credential, request); var expiresAt = now.Add(_options.CodeLifetime); - if(!await _store.TryResendAsync(request.Id, request.CodeVersion, newVerifier, now, expiresAt, - _options.ResendCooldown, now.AddHours(-1), _options.MaximumSendsPerHour, cancellationToken)) + bool resendCommitted; + try { + resendCommitted = await _store.TryResendAsync(request.Id, request.CodeVersion, newVerifier, now, expiresAt, + _options.ResendCooldown, now.AddHours(-1), _options.MaximumSendsPerHour, cancellationToken); + } catch(OperationCanceledException) when(cancellationToken.IsCancellationRequested) { + // If the atomic version update committed while cancellation was racing with + // the database response, finish delivery using the credential for that version. + var persisted = await _store.FindByHandleHashAsync( + request.PublicHandleHash, CancellationToken.None); + resendCommitted = persisted?.Status == VerificationRequestStatus.Pending && + persisted.CodeVersion == request.CodeVersion + 1 && persisted.LastSentAt == now; + if(!resendCommitted) + throw; + } + + if(!resendCommitted) return VerificationOperationResult.Failure("VerificationResendUnavailable", "The verification request cannot be resent yet."); - await _sender.SendAsync(CreateContext(user, request, verificationHandle, credential), credential, expiresAt, cancellationToken); + // The verifier/version update is committed; delivery is essential follow-through. + await _sender.SendAsync(CreateContext(user, request, verificationHandle, credential), credential, expiresAt, CancellationToken.None); return VerificationOperationResult.Success(verificationHandle, expiresAt); } diff --git a/RuntimeApps.Authentication/Identity/Contracts/IRoleManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IRoleManager.cs index 2af7bdb..28338ea 100644 --- a/RuntimeApps.Authentication/Identity/Contracts/IRoleManager.cs +++ b/RuntimeApps.Authentication/Identity/Contracts/IRoleManager.cs @@ -2,6 +2,10 @@ using Microsoft.AspNetCore.Identity; namespace RuntimeApps.Authentication.Identity.Contracts { + /// + /// Identity role manager operations do not expose cancellation overloads. Endpoint handlers + /// check cancellation before starting these calls and allow an in-flight write to complete. + /// public interface IRoleManager: IDisposable where TRole : class { IQueryable Roles { get; } Task CreateAsync(TRole role); diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserClaimManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserClaimManager.cs index 74a8052..c3cb3da 100644 --- a/RuntimeApps.Authentication/Identity/Contracts/IUserClaimManager.cs +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserClaimManager.cs @@ -2,6 +2,7 @@ using Microsoft.AspNetCore.Identity; namespace RuntimeApps.Authentication.Identity.Contracts { + /// Identity claim operations do not accept cancellation tokens; handlers check cancellation before starting writes. public interface IUserClaimManager where TUser : class { Task AddClaimAsync(TUser user, Claim claim); Task AddClaimsAsync(TUser user, IEnumerable claims); diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserManager.cs index 0dcf7e6..0affa8c 100644 --- a/RuntimeApps.Authentication/Identity/Contracts/IUserManager.cs +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserManager.cs @@ -2,6 +2,11 @@ using Microsoft.AspNetCore.Identity; namespace RuntimeApps.Authentication.Identity.Contracts { + /// + /// These methods wrap ASP.NET Core Identity APIs that do not accept cancellation tokens. + /// HTTP callers should check cancellation before starting an operation; an operation already + /// started must be allowed to finish so its persisted state is not reported as cancelled. + /// public interface IUserManager where TUser : class { Task GetUserAsync(ClaimsPrincipal principal); Task CreateAsync(TUser user); diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserPasswordManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserPasswordManager.cs index d0259b8..7f6a863 100644 --- a/RuntimeApps.Authentication/Identity/Contracts/IUserPasswordManager.cs +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserPasswordManager.cs @@ -1,6 +1,7 @@ using Microsoft.AspNetCore.Identity; 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); Task AddPasswordAsync(TUser user, string password); diff --git a/RuntimeApps.Authentication/Identity/Contracts/IUserRoleManager.cs b/RuntimeApps.Authentication/Identity/Contracts/IUserRoleManager.cs index e699037..17812ee 100644 --- a/RuntimeApps.Authentication/Identity/Contracts/IUserRoleManager.cs +++ b/RuntimeApps.Authentication/Identity/Contracts/IUserRoleManager.cs @@ -1,6 +1,7 @@ using Microsoft.AspNetCore.Identity; namespace RuntimeApps.Authentication.Identity.Contracts { + /// Identity role assignment calls do not accept cancellation tokens; handlers check cancellation before starting writes. public interface IUserRoleManager where TUser : class { Task AddToRoleAsync(TUser user, string role); Task AddToRolesAsync(TUser user, IEnumerable roles); diff --git a/RuntimeApps.Authentication/Shared/Extensions/PublicErrorFactory.cs b/RuntimeApps.Authentication/Shared/Extensions/PublicErrorFactory.cs new file mode 100644 index 0000000..ab56eb7 --- /dev/null +++ b/RuntimeApps.Authentication/Shared/Extensions/PublicErrorFactory.cs @@ -0,0 +1,64 @@ +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.HttpResults; +using Microsoft.AspNetCore.Identity; +using RuntimeApps.Authentication.Shared.Models; + +namespace RuntimeApps.Authentication.Shared.Extensions { + /// Maps internal results to safe, stable HTTP error contracts. + public static class PublicErrorFactory { + public static IResult CreateExternalAuthenticationFailure() => + TypedResults.Problem(statusCode: StatusCodes.Status401Unauthorized, + title: "Authentication failed", detail: "External authentication could not be completed.", + extensions: new Dictionary { ["code"] = "external_authentication_failed" }); + + public static IResult CreatePublicError(this IdentityResult result) => + new Result(ResultCode.BadRequest, result?.Errors ?? Enumerable.Empty()).CreatePublicError(); + + public static IResult CreatePublicError(this Result result) { + var status = result.Code switch { + ResultCode.BadRequest => StatusCodes.Status400BadRequest, + ResultCode.Forbidden => StatusCodes.Status403Forbidden, + ResultCode.Conflict => StatusCodes.Status409Conflict, + ResultCode.Locked => StatusCodes.Status423Locked, + _ => StatusCodes.Status400BadRequest + }; + + if(status == StatusCodes.Status400BadRequest) { + var errors = new Dictionary(); + foreach(var error in result.Errors ?? Enumerable.Empty()) { + var key = SafeCode(error.Code); + var message = SafeIdentityMessage(error.Code); + if(!errors.TryGetValue(key, out var messages)) messages = Array.Empty(); + errors[key] = messages.Append(message).Distinct().ToArray(); + } + if(errors.Count == 0) errors["request"] = new[] { "The request is invalid." }; + return TypedResults.ValidationProblem(errors); + } + + var (title, code, detail) = status switch { + StatusCodes.Status403Forbidden => ("Forbidden", "forbidden", "You are not allowed to perform this operation."), + StatusCodes.Status409Conflict => ("Conflict", "conflict", "The operation conflicts with the current resource state."), + StatusCodes.Status423Locked => ("Locked", "locked", "The resource is temporarily unavailable."), + _ => ("Bad Request", "bad_request", "The request could not be completed.") + }; + return TypedResults.Problem(statusCode: status, title: title, detail: detail, extensions: new Dictionary { ["code"] = code }); + } + + private static string SafeCode(string code) => code switch { + "PasswordTooShort" or "PasswordRequiresNonAlphanumeric" or "PasswordRequiresDigit" or "PasswordRequiresLower" or "PasswordRequiresUpper" or "PasswordRequiresUniqueChars" => "password", + "InvalidEmail" => "email", + "DuplicateEmail" or "DuplicateUserName" => "account", + "InvalidUserName" => "userName", + _ => "request" + }; + + private static string SafeIdentityMessage(string code) => code switch { + "PasswordTooShort" => "The password does not meet the minimum length requirement.", + "PasswordRequiresNonAlphanumeric" or "PasswordRequiresDigit" or "PasswordRequiresLower" or "PasswordRequiresUpper" or "PasswordRequiresUniqueChars" => "The password does not meet the configured password policy.", + "InvalidEmail" => "Enter a valid email address.", + "InvalidUserName" => "The user name is invalid.", + "DuplicateEmail" or "DuplicateUserName" => "The account could not be created.", + _ => "The request could not be completed." + }; + } +} diff --git a/RuntimeApps.Authentication/Shared/Extensions/ResultExtensions.cs b/RuntimeApps.Authentication/Shared/Extensions/ResultExtensions.cs index 484ea74..293103d 100644 --- a/RuntimeApps.Authentication/Shared/Extensions/ResultExtensions.cs +++ b/RuntimeApps.Authentication/Shared/Extensions/ResultExtensions.cs @@ -6,21 +6,26 @@ public static class ResultExtensions { public static ValidationProblem CreateValidationProblem(this Result result) { var errorDictionary = new Dictionary(1); - foreach(var error in result.Errors) { - string[] newDescriptions; - - if(errorDictionary.TryGetValue(error.Code, out var descriptions)) { - newDescriptions = new string[descriptions.Length + 1]; - Array.Copy(descriptions, newDescriptions, descriptions.Length); - newDescriptions[descriptions.Length] = error.Description; - } - else { - newDescriptions = new string[] { error.Description }; - } - - errorDictionary[error.Code] = newDescriptions; + foreach(var error in result.Errors ?? Enumerable.Empty()) { + var key = error.Code switch { + "PasswordTooShort" or "PasswordRequiresNonAlphanumeric" or "PasswordRequiresDigit" or "PasswordRequiresLower" or "PasswordRequiresUpper" or "PasswordRequiresUniqueChars" => "password", + "InvalidEmail" => "email", + "InvalidUserName" => "userName", + _ => "request" + }; + var message = error.Code switch { + "PasswordTooShort" => "The password does not meet the minimum length requirement.", + "PasswordRequiresNonAlphanumeric" or "PasswordRequiresDigit" or "PasswordRequiresLower" or "PasswordRequiresUpper" or "PasswordRequiresUniqueChars" => "The password does not meet the configured password policy.", + "InvalidEmail" => "Enter a valid email address.", + "InvalidUserName" => "The user name is invalid.", + _ => "The request could not be completed." + }; + if(!errorDictionary.TryGetValue(key, out var descriptions)) descriptions = Array.Empty(); + errorDictionary[key] = descriptions.Append(message).Distinct().ToArray(); } + if(errorDictionary.Count == 0) errorDictionary["request"] = new[] { "The request is invalid." }; + return TypedResults.ValidationProblem(errorDictionary); } } diff --git a/RuntimeApps.Authentication/Shared/Models/ApiResult.cs b/RuntimeApps.Authentication/Shared/Models/ApiResult.cs index 20d7aa9..df18d29 100644 --- a/RuntimeApps.Authentication/Shared/Models/ApiResult.cs +++ b/RuntimeApps.Authentication/Shared/Models/ApiResult.cs @@ -1,4 +1,5 @@ using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace RuntimeApps.Authentication.Shared.Models { @@ -20,7 +21,17 @@ public ApiResult(IdentityResult result): base(new Result(result.Succeeded ? Resu public override void OnFormatting(ActionContext context) { if(StatusCode == null && Value is Result result) { - StatusCode = (int)result.Code; + // ResultCode.BadRequest retains its historical numeric value (401) for + // serialized compatibility; HTTP semantics are mapped explicitly here. + StatusCode = result.Code switch { + ResultCode.Success => StatusCodes.Status200OK, + ResultCode.Accepted => StatusCodes.Status202Accepted, + ResultCode.BadRequest => StatusCodes.Status400BadRequest, + ResultCode.Forbidden => StatusCodes.Status403Forbidden, + ResultCode.Conflict => StatusCodes.Status409Conflict, + ResultCode.Locked => StatusCodes.Status423Locked, + _ => StatusCodes.Status500InternalServerError + }; } base.OnFormatting(context); } diff --git a/RuntimeApps.Authentication/Shared/Models/ResultCode.cs b/RuntimeApps.Authentication/Shared/Models/ResultCode.cs index e9c075a..3493067 100644 --- a/RuntimeApps.Authentication/Shared/Models/ResultCode.cs +++ b/RuntimeApps.Authentication/Shared/Models/ResultCode.cs @@ -2,6 +2,8 @@ namespace RuntimeApps.Authentication.Shared.Models { public enum ResultCode { Success = 200, Accepted = 202, + // Historical wire value retained for compatibility. Map to HTTP 400 explicitly; + // do not use this enum's underlying value as an HTTP status. BadRequest = 401, Forbidden = 403, Conflict = 409, diff --git a/Tests/RuntimeApps.Authentication.Test/FeatureEndpointMappingTest.cs b/Tests/RuntimeApps.Authentication.Test/FeatureEndpointMappingTest.cs index 70f67db..03cc523 100644 --- a/Tests/RuntimeApps.Authentication.Test/FeatureEndpointMappingTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/FeatureEndpointMappingTest.cs @@ -1,13 +1,17 @@ using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Features; using Microsoft.AspNetCore.Routing; using Microsoft.AspNetCore.Identity; using Microsoft.Extensions.DependencyInjection; using Moq; +using System.Text; using RuntimeApps.Authentication.Endpoints.Account; using RuntimeApps.Authentication.Features.Account.Contracts; +using RuntimeApps.Authentication.Features.Account.Models; using RuntimeApps.Authentication.Features.Registration.Contracts; +using RuntimeApps.Authentication.Features.ExternalLogin.Contracts; using RuntimeApps.Authentication.Features.Verification.Contracts; using RuntimeApps.Authentication.Identity.Contracts; @@ -26,6 +30,70 @@ public void AuthenticationMapping_DoesNotMapSessionEndpoints() { Assert.IsAssignableFrom(endpoint.Metadata.GetMetadata()); } + [Fact] + public void AuthenticationMetadata_DeclaresTokenFreeTwoFactorContinuation() { + using var host = CreateHost(includeVerificationDependencies: false); + host.Endpoints.MapAuthenticationApi, TestUserDto, int>(); + + var login = Assert.Single(Endpoints(host).OfType()); + var accepted = Assert.Single(login.Metadata.GetOrderedMetadata() + .Where(metadata => metadata.StatusCode == StatusCodes.Status202Accepted)); + Assert.Equal(typeof(AuthenticationContinuationResponse), accepted.Type); + Assert.DoesNotContain(typeof(RuntimeApps.Authentication.Shared.Models.Token).Name, accepted.Type!.GetProperties().Select(property => property.Name)); + } + + [Fact] + public void ExternalLoginMetadata_DeclaresSanitized401AndMalformedRequest400() { + using var host = CreateHost(includeVerificationDependencies: false, includeExternalProvider: true); + host.Endpoints.MapAuthenticationApi, TestUserDto, int>(); + + var externalLogin = Assert.Single(Endpoints(host).OfType() + .Where(endpoint => endpoint.RoutePattern.RawText?.Contains("external", StringComparison.OrdinalIgnoreCase) == true)); + var responses = externalLogin.Metadata.GetOrderedMetadata(); + Assert.Contains(responses, response => response.StatusCode == StatusCodes.Status400BadRequest && response.Type == typeof(HttpValidationProblemDetails)); + Assert.Contains(responses, response => response.StatusCode == StatusCodes.Status401Unauthorized && response.Type == typeof(Microsoft.AspNetCore.Mvc.ProblemDetails)); + } + + [Fact] + public async Task ExternalLogin_MalformedBodyReturns400AndProviderFailureReturnsSanitized401() { + using var host = CreateHost(includeVerificationDependencies: false, includeExternalProvider: true); + host.Endpoints.MapAuthenticationApi, TestUserDto, int>(); + var externalLogin = Endpoints(host).OfType() + .Single(endpoint => endpoint.RoutePattern.RawText?.Contains("external", StringComparison.OrdinalIgnoreCase) == true); + var account = Mock.Get(host.Endpoints.ServiceProvider.GetRequiredService>>()); + account.Setup(service => service.ExternalLoginAsync(It.IsAny(), It.IsAny(), It.IsAny())) + .ReturnsAsync(new RuntimeApps.Authentication.Shared.Models.Result, RuntimeApps.Authentication.Shared.Models.Token>( + RuntimeApps.Authentication.Shared.Models.ResultCode.BadRequest, + RuntimeApps.Authentication.Shared.Models.Result.CreateErrors("ProviderFailure", "private provider detail"))); + + static async Task<(int Status, string Body)> Send(RouteEndpoint endpoint, IServiceProvider services, string json) { + var context = new DefaultHttpContext(); + context.RequestServices = services; + context.Request.Method = "POST"; + context.Request.ContentType = "application/json"; + var bytes = Encoding.UTF8.GetBytes(json); + context.Request.Body = new MemoryStream(bytes); + context.Request.ContentLength = bytes.Length; + context.Features.Set(new TestBodyDetectionFeature()); + 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()); + } + + var malformed = await Send(externalLogin, host.Endpoints.ServiceProvider, "{\"Provider\":\"\",\"Token\":\"x\"}"); + Assert.Equal(StatusCodes.Status400BadRequest, malformed.Status); + Assert.Contains("InvalidExternalLogin", malformed.Body); + Assert.DoesNotContain("private provider detail", malformed.Body); + + var rejected = await Send(externalLogin, host.Endpoints.ServiceProvider, "{\"Provider\":\"sample\",\"Token\":\"invalid\"}"); + Assert.True(rejected.Status == StatusCodes.Status401Unauthorized, $"Expected 401, got {rejected.Status}: {rejected.Body}"); + Assert.Contains("External authentication could not be completed.", rejected.Body); + Assert.DoesNotContain("private provider detail", rejected.Body); + Assert.DoesNotContain("ProviderFailure", rejected.Body); + } + [Fact] public void RegistrationMapping_IsIndependentAndAnonymous() { using var host = CreateHost(includeVerificationDependencies: true); @@ -37,6 +105,9 @@ public void RegistrationMapping_IsIndependentAndAnonymous() { Assert.Equal("api/register/register", ((RouteEndpoint)endpoint).RoutePattern.RawText); Assert.IsAssignableFrom(endpoint.Metadata.GetMetadata()); Assert.Equal("Registration_Register", endpoint.Metadata.GetMetadata()?.EndpointName); + var accepted = Assert.Single(endpoint.Metadata.GetOrderedMetadata() + .Where(metadata => metadata.StatusCode == StatusCodes.Status202Accepted)); + Assert.Equal(typeof(RuntimeApps.Authentication.Shared.Models.Result), accepted.Type); } [Fact] @@ -70,17 +141,21 @@ public void RegistrationMapping_ReportsMissingDependenciesAtMappingTime() { Assert.Contains("IVerificationSender", error.Message, StringComparison.Ordinal); } - private static TestHost CreateHost(bool includeVerificationDependencies) { + private static TestHost CreateHost(bool includeVerificationDependencies, bool includeExternalProvider = false) { var services = new ServiceCollection(); + services.AddLogging().AddProblemDetails(); services.AddSingleton(Mock.Of, int>>()); services.AddSingleton(Mock.Of>>()); services.AddSingleton(Mock.Of, TestUserDto>>()); + if(includeExternalProvider) + services.AddSingleton>>(Mock.Of>>()); if(includeVerificationDependencies) { services.AddSingleton(Mock.Of, int>>()); services.AddSingleton(Mock.Of>()); services.AddSingleton(Mock.Of, int>>()); } - return new TestHost(services.BuildServiceProvider()); + var provider = services.BuildServiceProvider(); + return new TestHost(includeExternalProvider ? new TestServiceProvider(provider) : provider); } private static Endpoint[] Endpoints(TestHost host) => host.Endpoints.DataSources @@ -88,6 +163,16 @@ private static Endpoint[] Endpoints(TestHost host) => host.Endpoints.DataSources public sealed class TestUserDto { } + private sealed class TestServiceProvider(IServiceProvider inner) : IServiceProvider, IServiceProviderIsService { + public object GetService(Type serviceType) => serviceType == typeof(IServiceProviderIsService) ? this : inner.GetService(serviceType); + public bool IsService(Type serviceType) => serviceType == typeof(IExternalLoginProvider>) || + inner.GetService()?.IsService(serviceType) == true; + } + + private sealed class TestBodyDetectionFeature : IHttpRequestBodyDetectionFeature { + public bool CanHaveBody => true; + } + private sealed class TestHost : IDisposable { public TestHost(IServiceProvider services) => Endpoints = new TestEndpointRouteBuilder(services); public TestEndpointRouteBuilder Endpoints { get; } diff --git a/Tests/RuntimeApps.Authentication.Test/PublicErrorFactoryTest.cs b/Tests/RuntimeApps.Authentication.Test/PublicErrorFactoryTest.cs new file mode 100644 index 0000000..e38b9c8 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/PublicErrorFactoryTest.cs @@ -0,0 +1,69 @@ +using System.Text; +using System.Text.Json.Nodes; +using FluentAssertions; +using Microsoft.AspNetCore.Http; +using Microsoft.Extensions.DependencyInjection; +using RuntimeApps.Authentication.Shared.Extensions; +using RuntimeApps.Authentication.Shared.Models; + +namespace RuntimeApps.Authentication.Test; + +public class PublicErrorFactoryTest { + [Fact] + public async Task Identity_errors_are_sanitized_as_validation_problems() { + var result = new Result(ResultCode.BadRequest, + Result.CreateErrors("PasswordTooShort", "Secret policy detail")); + var context = new DefaultHttpContext(); + context.RequestServices = new ServiceCollection().AddLogging().AddProblemDetails().BuildServiceProvider(); + await using var body = new MemoryStream(); + context.Response.Body = body; + + await result.CreatePublicError().ExecuteAsync(context); + + context.Response.StatusCode.Should().Be(StatusCodes.Status400BadRequest); + body.Position = 0; + var response = await new StreamReader(body, Encoding.UTF8).ReadToEndAsync(); + response.Should().Contain("password").And.Contain("minimum length"); + response.Should().NotContain("Secret policy detail"); + } + + [Fact] + public async Task Forbidden_results_use_problem_details_and_403() { + var result = new Result(ResultCode.Forbidden, + Result.CreateErrors("Internal", "Sensitive internal detail")); + var context = new DefaultHttpContext(); + context.RequestServices = new ServiceCollection().AddLogging().AddProblemDetails().BuildServiceProvider(); + await using var body = new MemoryStream(); + context.Response.Body = body; + + await result.CreatePublicError().ExecuteAsync(context); + + context.Response.StatusCode.Should().Be(StatusCodes.Status403Forbidden); + body.Position = 0; + var response = await new StreamReader(body, Encoding.UTF8).ReadToEndAsync(); + response.Should().Contain("forbidden"); + response.Should().NotContain("Sensitive internal detail"); + } + + [Fact] + public async Task External_authentication_failures_are_generic_401_problem_details() { + static async Task<(int Status, string Body)> Execute() { + var context = new DefaultHttpContext(); + context.RequestServices = new ServiceCollection().AddLogging().AddProblemDetails().BuildServiceProvider(); + await using var body = new MemoryStream(); + context.Response.Body = body; + await PublicErrorFactory.CreateExternalAuthenticationFailure().ExecuteAsync(context); + body.Position = 0; + return (context.Response.StatusCode, await new StreamReader(body).ReadToEndAsync()); + } + + var (status, body) = await Execute(); + status.Should().Be(StatusCodes.Status401Unauthorized); + var problem = JsonNode.Parse(body)!.AsObject(); + problem["title"]!.GetValue().Should().Be("Authentication failed"); + problem["detail"]!.GetValue().Should().Be("External authentication could not be completed."); + problem["status"]!.GetValue().Should().Be(StatusCodes.Status401Unauthorized); + problem["code"]!.GetValue().Should().Be("external_authentication_failed"); + body.Should().NotContain("Identity").And.NotContain("provider-specific").And.NotContain("account exists"); + } +} diff --git a/Tests/RuntimeApps.Authentication.Test/PublicRequestContractTest.cs b/Tests/RuntimeApps.Authentication.Test/PublicRequestContractTest.cs new file mode 100644 index 0000000..0bcdfe1 --- /dev/null +++ b/Tests/RuntimeApps.Authentication.Test/PublicRequestContractTest.cs @@ -0,0 +1,72 @@ +using System.Text.Json; +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Http.Metadata; +using Microsoft.AspNetCore.Identity; +using Microsoft.AspNetCore.Routing; +using Microsoft.Extensions.DependencyInjection; +using Moq; +using RuntimeApps.Authentication.Endpoints.Roles; +using RuntimeApps.Authentication.Endpoints.Roles.Models; +using RuntimeApps.Authentication.Features.Account.Models; +using RuntimeApps.Authentication.Identity.Contracts; +using RuntimeApps.Authentication.Shared.Models; + +namespace RuntimeApps.Authentication.Test; + +public sealed class PublicRequestContractTest { + private static readonly JsonSerializerOptions WebJson = new(JsonSerializerDefaults.Web); + [Fact] + public void UserRolesRequest_UsesNamedCollectionProperty() { + var request = JsonSerializer.Deserialize("""{"roles":["Admin","Auditor"]}""", WebJson); + + Assert.Equal(new[] { "Admin", "Auditor" }, request?.Roles); + } + + [Fact] + public void BulkClaimsRequest_UsesNamedCollectionProperty() { + var request = JsonSerializer.Deserialize("""{"claims":[{"type":"department","value":"finance"}]}""", WebJson); + + var claim = Assert.Single(request!.Claims); + Assert.Equal("department", claim.Type); + Assert.Equal("finance", claim.Value); + } + + [Fact] + public void RoleRequest_PreservesConsumerSpecificRoleFieldsInsideNamedEnvelope() { + var request = JsonSerializer.Deserialize>("""{"role":{"name":"Admin","displayName":"Administrators"}}""", WebJson); + + Assert.NotNull(request); + Assert.Equal("Admin", request.Role.Name); + Assert.Equal("Administrators", request.Role.DisplayName); + } + + [Fact] + public void RoleManagementEndpointMetadata_DeclaresRoleRequestSchema() { + var serviceCollection = new ServiceCollection(); + serviceCollection.AddSingleton(Mock.Of>()); + var services = serviceCollection.BuildServiceProvider(); + var endpoints = new TestEndpointRouteBuilder(services); + endpoints.MapRoleManageApi(); + var endpoint = Assert.Single(endpoints.DataSources.SelectMany(source => source.Endpoints) + .OfType().Where(item => item.RoutePattern.RawText == "/" && + item.Metadata.GetMetadata()?.HttpMethods.Contains("POST") == true)); + + Assert.Contains(endpoint.Metadata.GetOrderedMetadata(), metadata => + metadata.RequestType == typeof(RoleRequest)); + Assert.Contains(endpoint.Metadata.GetOrderedMetadata(), metadata => + metadata.StatusCode == StatusCodes.Status200OK); + } + + public sealed class TestRole { + public string Name { get; set; } + public string DisplayName { get; set; } + } + + private sealed class TestEndpointRouteBuilder : IEndpointRouteBuilder { + public TestEndpointRouteBuilder(IServiceProvider services) => ServiceProvider = services; + public ICollection DataSources { get; } = new List(); + public IServiceProvider ServiceProvider { get; } + public IApplicationBuilder CreateApplicationBuilder() => new ApplicationBuilder(ServiceProvider); + } +} diff --git a/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs index a4cd26a..3c1ef21 100644 --- a/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/RegistrationServiceTest.cs @@ -47,6 +47,7 @@ public async Task Register_NewUser_CreatesPendingAccountAndStartsVerification() Assert.True(result.Succeeded); Assert.Equal("opaque-handle", result.Data.VerificationHandle); + Assert.Equal(GenericRegistrationMessage, result.Data.Message); Assert.False(user.EmailConfirmed); userManager.Verify(manager => manager.CreateAsync(user, "StrongPassword!1"), Times.Once); account.Verify(manager => manager.CompleteRegistrationAsync(It.IsAny()), Times.Never); @@ -91,11 +92,130 @@ public async Task Register_ExistingConfirmedUser_ReturnsGenericResponseWithoutSe Assert.True(result.Succeeded); Assert.False(string.IsNullOrWhiteSpace(result.Data.VerificationHandle)); + Assert.Equal(GenericRegistrationMessage, result.Data.Message); workflow.Verify(item => item.StartAsync( It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); } + [Fact] + public async Task Register_PendingUserRateLimited_ReturnsGenericAcceptedContractWithoutChangingAccount() { + var userManager = new Mock>(); + var emailManager = new Mock>(); + var workflow = new Mock>(); + var account = new Mock>(); + var existing = new IdentityUser { Email = "pending@example.com", UserName = "original-name", PhoneNumber = "123", EmailConfirmed = false }; + emailManager.Setup(manager => manager.FindByEmailAsync(existing.Email)).ReturnsAsync(existing); + workflow.Setup(service => service.StartAsync(existing, VerificationPurpose.Registration, VerificationChannel.Email, + existing.Email, null, null, It.IsAny())) + .ReturnsAsync(VerificationOperationResult.Failure("VerificationRateLimited", "Internal limit detail")); + + var result = await CreateService(userManager, emailManager, workflow, account) + .RegisterAsync(new IdentityUser { Email = existing.Email, UserName = "replacement-name" }, "ReplacementPassword!1"); + + Assert.True(result.Succeeded); + Assert.NotNull(result.Data); + Assert.Equal(GenericRegistrationMessage, result.Data.Message); + Assert.False(string.IsNullOrWhiteSpace(result.Data.VerificationHandle)); + Assert.Equal("original-name", existing.UserName); + Assert.Equal("123", existing.PhoneNumber); + Assert.False(existing.EmailConfirmed); + userManager.Verify(manager => manager.CreateAsync(It.IsAny(), It.IsAny()), Times.Never); + workflow.Verify(service => service.StartAsync(existing, VerificationPurpose.Registration, VerificationChannel.Email, + existing.Email, null, null, It.IsAny()), Times.Once); + } + + [Fact] + public async Task Register_NonRateLimitVerificationFailure_RemainsFailure() { + var userManager = new Mock>(); + var emailManager = new Mock>(); + var workflow = new Mock>(); + var account = new Mock>(); + var user = new IdentityUser { Email = "new@example.com", UserName = "new@example.com" }; + emailManager.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync((IdentityUser)null); + userManager.Setup(manager => manager.CreateAsync(user, "StrongPassword!1")).ReturnsAsync(IdentityResult.Success); + workflow.Setup(service => service.StartAsync(user, VerificationPurpose.Registration, VerificationChannel.Email, + user.Email, null, null, It.IsAny())) + .ReturnsAsync(VerificationOperationResult.Failure("VerificationStoreUnavailable", "Database unavailable")); + + var result = await CreateService(userManager, emailManager, workflow, account) + .RegisterAsync(user, "StrongPassword!1"); + + Assert.False(result.Succeeded); + Assert.Equal(ResultCode.BadRequest, result.Code); + Assert.Contains(result.Errors!, error => error.Code == "VerificationStoreUnavailable"); + } + + [Theory] + [InlineData("DuplicateEmail")] + [InlineData("DuplicateUserName")] + public async Task Register_ConcurrentDuplicateIdentifier_ReturnsGenericAcceptedContract(string code) { + var userManager = new Mock>(); + var emailManager = new Mock>(); + var workflow = new Mock>(); + var account = new Mock>(); + var user = new IdentityUser { Email = "new@example.com", UserName = "new-user" }; + emailManager.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync((IdentityUser)null); + userManager.Setup(manager => manager.CreateAsync(user, "StrongPassword!1")) + .ReturnsAsync(IdentityResult.Failed(new IdentityError { Code = code, Description = "Sensitive identity detail" })); + + var service = CreateService(userManager, emailManager, workflow, account); + var result = await service.RegisterAsync(user, "StrongPassword!1"); + + Assert.True(result.Succeeded); + Assert.NotNull(result.Data); + Assert.Equal(GenericRegistrationMessage, result.Data.Message); + Assert.False(string.IsNullOrWhiteSpace(result.Data.VerificationHandle)); + Assert.DoesNotContain("Sensitive identity detail", result.Errors?.Select(error => error.Description) ?? Array.Empty()); + workflow.Verify(item => item.StartAsync( + It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Register_CancellationBeforeCreateDoesNotPersistUser() { + var userManager = new Mock>(); + var emailManager = new Mock>(); + var workflow = new Mock>(); + var account = new Mock>(); + using var cancellation = new CancellationTokenSource(); + cancellation.Cancel(); + + var service = CreateService(userManager, emailManager, workflow, account); + await Assert.ThrowsAnyAsync(() => service.RegisterAsync( + new IdentityUser { Email = "new@example.com" }, "StrongPassword!1", cancellation.Token)); + + userManager.Verify(manager => manager.CreateAsync(It.IsAny(), It.IsAny()), Times.Never); + workflow.Verify(item => item.StartAsync( + It.IsAny(), It.IsAny(), It.IsAny(), + It.IsAny(), It.IsAny(), It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task Register_CancellationDuringVerificationLeavesOnlyPendingUnconfirmedUser() { + var userManager = new Mock>(); + var emailManager = new Mock>(); + var workflow = new Mock>(); + var account = new Mock>(); + using var cancellation = new CancellationTokenSource(); + var user = new IdentityUser { Email = "new@example.com", UserName = "new@example.com" }; + emailManager.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync((IdentityUser)null); + userManager.Setup(manager => manager.CreateAsync(user, "StrongPassword!1")).ReturnsAsync(IdentityResult.Success); + workflow.Setup(service => service.StartAsync( + user, VerificationPurpose.Registration, VerificationChannel.Email, user.Email, + null, null, It.IsAny())) + .Callback(() => cancellation.Cancel()) + .ThrowsAsync(new OperationCanceledException(cancellation.Token)); + + var service = CreateService(userManager, emailManager, workflow, account); + await Assert.ThrowsAnyAsync(() => + service.RegisterAsync(user, "StrongPassword!1", cancellation.Token)); + + Assert.False(user.EmailConfirmed); + userManager.Verify(manager => manager.CreateAsync(user, "StrongPassword!1"), Times.Once); + account.Verify(manager => manager.CompleteRegistrationAsync(It.IsAny(), It.IsAny()), Times.Never); + } + private static RegistrationService CreateService( Mock> userManager, Mock> emailManager, @@ -103,5 +223,7 @@ private static RegistrationService CreateService( Mock> account) => new(userManager.Object, emailManager.Object, workflow.Object, account.Object, Options.Create(new VerificationOptions())); + + private const string GenericRegistrationMessage = "If this email address can be registered, check your inbox for a verification message."; } } diff --git a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs index 363afea..a45ab9e 100644 --- a/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs +++ b/Tests/RuntimeApps.Authentication.Test/UserAccountServiceTest.cs @@ -144,9 +144,25 @@ public async Task Login_WrongPassword() { result.Meta.Should().BeNull(); } + [Fact] + public async Task Login_TwoFactorRequired_ReturnsContinuationWithoutIssuingSession() { + var user = new IdentityUser { UserName = "mfa-user", EmailConfirmed = true }; + _userManagerMock.Setup(manager => manager.FindByNameAsync(user.UserName)).ReturnsAsync(user); + _signInManagerMock.Setup(manager => manager.PasswordSignInAsync(user, "password", false, true)) + .ReturnsAsync(SignInResult.TwoFactorRequired); + + var result = await _userAccountService.LoginAsync(user.UserName, "password"); + + Assert.False(result.Succeeded); + Assert.Equal(RuntimeApps.Authentication.Shared.Models.ResultCode.Accepted, result.Code); + Assert.Null(result.Data); + Assert.Null(result.Meta); + _sessionIssuerMock.Verify(issuer => issuer.IssueAsync(It.IsAny(), It.IsAny()), Times.Never); + } + [Theory] - [InlineData(true, RuntimeApps.Authentication.Shared.Models.ResultCode.Conflict)] - [InlineData(false, RuntimeApps.Authentication.Shared.Models.ResultCode.Forbidden)] + [InlineData(true, RuntimeApps.Authentication.Shared.Models.ResultCode.BadRequest)] + [InlineData(false, RuntimeApps.Authentication.Shared.Models.ResultCode.BadRequest)] public async Task Login_LockedOutOrNotAllowed_DoesNotIssueSession(bool lockedOut, RuntimeApps.Authentication.Shared.Models.ResultCode expectedCode) { var user = new IdentityUser { UserName = "restricted", EmailConfirmed = true }; _userManagerMock.Setup(manager => manager.FindByNameAsync(user.UserName)).ReturnsAsync(user); @@ -220,6 +236,7 @@ public async Task ExternalLogin_Success_CreateNewUser() { .ReturnsAsync(new RuntimeApps.Authentication.Features.ExternalLogin.Models.ExternalLoginProviderResult { User = user, LoginInfo = loginInfo, Email = user.Email, EmailVerified = false }); + _externalLoginEmailTrustPolicyMock.Setup(policy => policy.IsEmailTrusted(provider, It.IsAny>())).Returns(true); _loginManagerMock.Setup(u => u.FindByLoginAsync(provider, token)) .ReturnsAsync(nullUSer); _emailManagerMock.Setup(u => u.FindByEmailAsync(user.Email)) @@ -265,8 +282,117 @@ public async Task ExternalLogin_ExistingEmail_DoesNotAutomaticallyLink() { var result = await _userAccountService.ExternalLoginAsync(provider, token); Assert.False(result.Succeeded); - Assert.Equal(RuntimeApps.Authentication.Shared.Models.ResultCode.Conflict, result.Code); + 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); + _emailManagerMock.Verify(manager => manager.FindByEmailAsync(It.IsAny()), Times.Never()); + _userManagerMock.Verify(manager => manager.CreateAsync(It.IsAny()), Times.Never()); + } + + [Fact] + public async Task ExternalLogin_FailedLinkAfterCreateLeavesRetryableUserWithoutSession() { + const string provider = "Google"; + const string token = "provider-token"; + var user = new IdentityUser { Email = "trusted@example.com", UserName = "trusted@example.com" }; + 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 = user, LoginInfo = loginInfo, Email = user.Email, EmailVerified = true + }); + _externalLoginEmailTrustPolicyMock.Setup(policy => policy.IsEmailTrusted(provider, It.IsAny>())).Returns(true); + _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); + _loginManagerMock.Setup(manager => manager.AddLoginAsync(user, loginInfo)).ReturnsAsync(IdentityResult.Failed()); + var result = await _userAccountService.ExternalLoginAsync(provider, token); + + Assert.False(result.Succeeded); + _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); + _sessionIssuerMock.Verify(issuer => issuer.IssueAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task ExternalLogin_CancellationAfterCreateFinishesLinkBeforeObservingCancellation() { + const string provider = "Google"; + const string token = "provider-token"; + using var cancellation = new CancellationTokenSource(); + var user = new IdentityUser { Email = "trusted@example.com", UserName = "trusted@example.com" }; + 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, It.IsAny())).ReturnsAsync( + new RuntimeApps.Authentication.Features.ExternalLogin.Models.ExternalLoginProviderResult { + User = user, LoginInfo = loginInfo, Email = user.Email, EmailVerified = true + }); + _externalLoginEmailTrustPolicyMock.Setup(policy => policy.IsEmailTrusted(provider, It.IsAny>())).Returns(true); + _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)).Returns(() => { + cancellation.Cancel(); + return Task.FromResult(IdentityResult.Success); + }); + _loginManagerMock.Setup(manager => manager.AddLoginAsync(user, loginInfo)).ReturnsAsync(IdentityResult.Success); + + await Assert.ThrowsAnyAsync(() => + _userAccountService.ExternalLoginAsync(provider, token, cancellation.Token)); + + _loginManagerMock.Verify(manager => manager.AddLoginAsync(user, loginInfo), Times.Once); + _sessionIssuerMock.Verify(issuer => issuer.IssueAsync(It.IsAny(), It.IsAny()), Times.Never); + } + + [Fact] + public async Task ExternalLogin_TrustedEmailCanLinkExistingAccount() { + const string provider = "Google"; + const string token = "provider-token"; + var user = new IdentityUser { Email = "trusted@example.com", EmailConfirmed = true }; + var loginInfo = new UserLoginInfo(provider, token, provider); + var expectedToken = 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 = user.Email }, LoginInfo = loginInfo, + Email = user.Email, EmailVerified = true + }); + _externalLoginEmailTrustPolicyMock.Setup(policy => policy.IsEmailTrusted(provider, It.IsAny>())).Returns(true); + _loginManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync((IdentityUser)null); + _emailManagerMock.Setup(manager => manager.FindByEmailAsync(user.Email)).ReturnsAsync(user); + _loginManagerMock.Setup(manager => manager.AddLoginAsync(user, loginInfo)).ReturnsAsync(IdentityResult.Success); + _sessionIssuerMock.Setup(issuer => issuer.IssueAsync(user, It.IsAny())).ReturnsAsync(expectedToken); + + var result = await _userAccountService.ExternalLoginAsync(provider, token); + + Assert.True(result.Succeeded); + Assert.Same(user, result.Data); + Assert.Same(expectedToken, result.Meta); + _loginManagerMock.Verify(manager => manager.AddLoginAsync(user, loginInfo), Times.Once); } [Fact] @@ -288,7 +414,8 @@ public async Task ExternalLogin_UnverifiedEmail_DoesNotLinkExistingAccount() { var result = await _userAccountService.ExternalLoginAsync(provider, token); Assert.False(result.Succeeded); - Assert.Equal(RuntimeApps.Authentication.Shared.Models.ResultCode.Conflict, result.Code); + 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()); } @@ -307,10 +434,7 @@ public async Task ExternalLogin_CanRequireEmailVerificationWithoutIssuingToken() .ReturnsAsync(new RuntimeApps.Authentication.Features.ExternalLogin.Models.ExternalLoginProviderResult { User = user, 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((IdentityUser)null); - _userManagerMock.Setup(manager => manager.CreateAsync(user)).ReturnsAsync(IdentityResult.Success); - _loginManagerMock.Setup(manager => manager.AddLoginAsync(user, loginInfo)).ReturnsAsync(IdentityResult.Success); + _loginManagerMock.Setup(manager => manager.FindByLoginAsync(provider, token)).ReturnsAsync(user); workflow.Setup(service => service.StartAsync( user, RuntimeApps.Authentication.Features.Verification.Models.VerificationPurpose.Registration, RuntimeApps.Authentication.Features.Verification.Models.VerificationChannel.Email, user.Email,