| | | 1 | | using Anichron.API.Security; |
| | | 2 | | using Anichron.Core.Data; |
| | | 3 | | using Anichron.Core.Data.Repository; |
| | | 4 | | using Anichron.Core.Domain; |
| | | 5 | | using Microsoft.EntityFrameworkCore; |
| | | 6 | | using Npgsql; |
| | | 7 | | using System.Diagnostics; |
| | | 8 | | using System.Security.Cryptography; |
| | | 9 | | using System.Text; |
| | | 10 | | |
| | | 11 | | namespace Anichron.API.Services; |
| | | 12 | | |
| | | 13 | | public sealed record AuthTokens(string AccessToken, string RefreshToken); |
| | | 14 | | public sealed record AdminCreatedUser(Guid Id, string Username, string Email, string TemporaryPassword); |
| | | 15 | | |
| | | 16 | | public sealed record AuthResult<T> |
| | | 17 | | { |
| | | 18 | | public T? Value { get; init; } |
| | | 19 | | public AuthError? Error { get; init; } |
| | | 20 | | public bool IsSuccess => Error is null; |
| | | 21 | | public int? RetryAfterSeconds { get; init; } |
| | | 22 | | } |
| | | 23 | | |
| | | 24 | | public sealed record AuthResult |
| | | 25 | | { |
| | | 26 | | public AuthError? Error { get; init; } |
| | | 27 | | public bool IsSuccess => Error is null; |
| | | 28 | | public int? RetryAfterSeconds { get; init; } |
| | | 29 | | |
| | | 30 | | public static AuthResult Ok() => new(); |
| | | 31 | | public static AuthResult<T> Ok<T>(T value) => new() { Value = value }; |
| | | 32 | | |
| | | 33 | | public static AuthResult Fail(AuthError error) => new() { Error = error }; |
| | | 34 | | public static AuthResult<T> Fail<T>(AuthError error) => new() { Error = error }; |
| | | 35 | | |
| | | 36 | | public static AuthResult<T> Locked<T>(int retryAfterSeconds) => new() |
| | | 37 | | { |
| | | 38 | | Error = AuthError.AccountTemporarilyLocked, |
| | | 39 | | RetryAfterSeconds = retryAfterSeconds, |
| | | 40 | | }; |
| | | 41 | | } |
| | | 42 | | |
| | | 43 | | public interface IAuthService |
| | | 44 | | { |
| | | 45 | | Task<AuthResult<AuthTokens>> RegisterAsync(string username, string email, string password, string inviteToken, Cance |
| | | 46 | | Task<AuthResult<AuthTokens>> LoginAsync(string usernameOrEmail, string password, CancellationToken ct); |
| | | 47 | | Task<AuthResult<AuthTokens>> RefreshAsync(string rawToken, CancellationToken ct); |
| | | 48 | | Task RevokeAsync(string rawToken, CancellationToken ct); |
| | | 49 | | Task<AuthResult> ChangePasswordAsync(Guid userId, string currentPassword, string newPassword, CancellationToken ct); |
| | | 50 | | Task<AuthResult<AdminCreatedUser>> AdminCreateUserAsync(string username, string email, CancellationToken ct); |
| | | 51 | | } |
| | | 52 | | |
| | 59 | 53 | | public sealed class AuthService( |
| | 59 | 54 | | IUserRepository users, |
| | 59 | 55 | | IInviteRepository invites, |
| | 59 | 56 | | IUnitOfWork unitOfWork, |
| | 59 | 57 | | IClock clock, |
| | 59 | 58 | | IGuidFactory guidFactory, |
| | 59 | 59 | | IPasswordHasher passwordHasher, |
| | 59 | 60 | | IRegistrationValidator validator, |
| | 59 | 61 | | ITokenService tokenService, |
| | 59 | 62 | | ILockoutService lockout) |
| | | 63 | | : IAuthService |
| | | 64 | | { |
| | | 65 | | public async Task<AuthResult<AuthTokens>> RegisterAsync(string username, string email, string password, string invit |
| | 20 | 66 | | { |
| | 20 | 67 | | ArgumentNullException.ThrowIfNull(username); |
| | 19 | 68 | | ArgumentNullException.ThrowIfNull(email); |
| | 18 | 69 | | ArgumentNullException.ThrowIfNull(password); |
| | 17 | 70 | | ArgumentNullException.ThrowIfNull(inviteToken); |
| | | 71 | | |
| | 16 | 72 | | var now = clock.GetCurrentInstant(); |
| | 16 | 73 | | var invite = await invites.FindValidByHashAsync(HashInviteToken(inviteToken), now, ct); |
| | 16 | 74 | | if (invite is null) |
| | 2 | 75 | | return AuthResult.Fail<AuthTokens>(AuthError.InviteTokenInvalid); |
| | | 76 | | |
| | 14 | 77 | | var normalizedUsername = username.Trim().ToLowerInvariant(); |
| | 14 | 78 | | var normalizedEmail = email.Trim().ToLowerInvariant(); |
| | | 79 | | |
| | 14 | 80 | | var error = await validator.ValidateAsync(normalizedUsername, normalizedEmail, password, ct); |
| | 14 | 81 | | if (error is not null) |
| | 5 | 82 | | return AuthResult.Fail<AuthTokens>(error.Value); |
| | | 83 | | |
| | 9 | 84 | | if (await users.AnyByUsernameAsync(normalizedUsername, ct)) |
| | 2 | 85 | | return AuthResult.Fail<AuthTokens>(AuthError.UsernameTaken); |
| | | 86 | | |
| | 7 | 87 | | if (await users.AnyByEmailAsync(normalizedEmail, ct)) |
| | 1 | 88 | | return AuthResult.Fail<AuthTokens>(AuthError.EmailTaken); |
| | | 89 | | |
| | 6 | 90 | | var user = new User |
| | 6 | 91 | | { |
| | 6 | 92 | | Id = guidFactory.NewGuid(), |
| | 6 | 93 | | Username = normalizedUsername, |
| | 6 | 94 | | Email = normalizedEmail, |
| | 6 | 95 | | PasswordHash = passwordHasher.Hash(password), |
| | 6 | 96 | | }; |
| | | 97 | | |
| | 6 | 98 | | users.Add(user); |
| | 6 | 99 | | invite.UsedAt = now; |
| | 6 | 100 | | invite.UsedByUserId = user.Id; |
| | | 101 | | |
| | | 102 | | try |
| | 6 | 103 | | { |
| | 6 | 104 | | return AuthResult.Ok(await unitOfWork.ExecuteInTransactionAsync(async () => |
| | 6 | 105 | | { |
| | 6 | 106 | | await unitOfWork.SaveChangesAsync(ct); |
| | 6 | 107 | | return await tokenService.IssueAsync(user, ct); |
| | 6 | 108 | | }, ct)); |
| | | 109 | | } |
| | 1 | 110 | | catch (DbUpdateConcurrencyException) |
| | 1 | 111 | | { |
| | 1 | 112 | | return AuthResult.Fail<AuthTokens>(AuthError.InviteTokenInvalid); |
| | | 113 | | } |
| | 3 | 114 | | catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: "23505" } postgresExceptio |
| | 3 | 115 | | { |
| | 3 | 116 | | return AuthResult.Fail<AuthTokens>(DetectConstraintError(postgresException)); |
| | | 117 | | } |
| | 15 | 118 | | } |
| | | 119 | | |
| | | 120 | | internal static string HashInviteToken(string rawToken) |
| | 20 | 121 | | => Convert.ToBase64String(SHA256.HashData(Encoding.UTF8.GetBytes(rawToken))); |
| | | 122 | | |
| | | 123 | | public async Task<AuthResult<AuthTokens>> LoginAsync(string usernameOrEmail, string password, CancellationToken ct) |
| | 14 | 124 | | { |
| | 14 | 125 | | ArgumentNullException.ThrowIfNull(usernameOrEmail); |
| | 13 | 126 | | ArgumentNullException.ThrowIfNull(password); |
| | | 127 | | |
| | 12 | 128 | | var normalized = usernameOrEmail.Trim().ToLowerInvariant(); |
| | 12 | 129 | | var user = await users.FindByCredentialAsync(normalized, ct); |
| | | 130 | | |
| | | 131 | | // A null hash means "no such account", and the hasher spends a full Argon2 pass on it |
| | | 132 | | // rather than short-circuiting. That removes the hashing asymmetry; this call site's only |
| | | 133 | | // job is not to defeat it by branching before the call. |
| | | 134 | | // |
| | | 135 | | // ⚠️ It does NOT make login constant-time end to end, and this comment deliberately does |
| | | 136 | | // not claim that. A known user with a wrong password goes on to |
| | | 137 | | // RecordFailedAttemptAsync below, which is a database write an unknown user never makes — |
| | | 138 | | // milliseconds, far more than the hashing difference this removes. Username enumeration |
| | | 139 | | // by timing is therefore still possible. Tracked separately; see the note on that call. |
| | 12 | 140 | | var passwordValid = passwordHasher.Verify(password, user?.PasswordHash); |
| | | 141 | | |
| | 12 | 142 | | var now = clock.GetCurrentInstant(); |
| | | 143 | | |
| | | 144 | | // Record failed attempt only if not already locked |
| | | 145 | | // Prevents counter growth and redundant DB writes during an active lockout. |
| | 12 | 146 | | if (user is not null && !passwordValid && !lockout.IsLockedOut(user, now)) |
| | 2 | 147 | | await lockout.RecordFailedAttemptAsync(user, now, ct); |
| | | 148 | | |
| | 12 | 149 | | if (user is null || !passwordValid) |
| | 6 | 150 | | return AuthResult.Fail<AuthTokens>(AuthError.InvalidCredentials); |
| | | 151 | | |
| | 6 | 152 | | if (user.IsDisabled) |
| | 1 | 153 | | return AuthResult.Fail<AuthTokens>(AuthError.AccountDisabled); |
| | | 154 | | |
| | 5 | 155 | | if (lockout.IsLockedOut(user, now)) |
| | 1 | 156 | | { |
| | | 157 | | // IsLockedOut guarantees LockedUntil is non-null and in the future. |
| | 1 | 158 | | var secondsRemaining = (int)Math.Ceiling((user.LockedUntil!.Value - now).TotalSeconds); |
| | 1 | 159 | | return AuthResult.Locked<AuthTokens>(Math.Max(1, secondsRemaining)); |
| | | 160 | | } |
| | | 161 | | |
| | | 162 | | // Counter reset and token issuance share one transaction — if IssueAsync fails, |
| | | 163 | | // the counter is not persisted so the user's lockout state is preserved correctly. |
| | 4 | 164 | | lockout.PrepareReset(user); |
| | | 165 | | |
| | 4 | 166 | | var tokens = await unitOfWork.ExecuteInTransactionAsync(async () => |
| | 4 | 167 | | { |
| | 4 | 168 | | await unitOfWork.SaveChangesAsync(ct); |
| | 4 | 169 | | return await tokenService.IssueAsync(user, ct); |
| | 4 | 170 | | }, ct); |
| | | 171 | | |
| | 4 | 172 | | return AuthResult.Ok(tokens); |
| | 12 | 173 | | } |
| | | 174 | | |
| | | 175 | | public Task<AuthResult<AuthTokens>> RefreshAsync(string rawToken, CancellationToken ct) |
| | 1 | 176 | | => tokenService.RefreshAsync(rawToken, ct); |
| | | 177 | | |
| | | 178 | | public Task RevokeAsync(string rawToken, CancellationToken ct) |
| | 1 | 179 | | => tokenService.RevokeAsync(rawToken, ct); |
| | | 180 | | |
| | | 181 | | public async Task<AuthResult> ChangePasswordAsync(Guid userId, string currentPassword, string newPassword, Cancellat |
| | 10 | 182 | | { |
| | 10 | 183 | | ArgumentNullException.ThrowIfNull(currentPassword); |
| | 9 | 184 | | ArgumentNullException.ThrowIfNull(newPassword); |
| | | 185 | | |
| | 8 | 186 | | var user = await users.FindByIdAsync(userId, ct); |
| | 8 | 187 | | if (user is null || !passwordHasher.Verify(currentPassword, user.PasswordHash)) |
| | 2 | 188 | | return AuthResult.Fail(AuthError.InvalidCredentials); |
| | | 189 | | |
| | 6 | 190 | | var error = await validator.ValidatePasswordAsync(newPassword, ct); |
| | 6 | 191 | | if (error is not null) |
| | 3 | 192 | | return AuthResult.Fail(error.Value); |
| | | 193 | | |
| | 3 | 194 | | await unitOfWork.ExecuteInTransactionAsync(async () => |
| | 3 | 195 | | { |
| | 3 | 196 | | user.PasswordHash = passwordHasher.Hash(newPassword); |
| | 3 | 197 | | user.MustChangePassword = false; |
| | 3 | 198 | | var now = clock.GetCurrentInstant(); |
| | 3 | 199 | | await tokenService.MarkAllSessionsRevokedAsync(userId, now, ct); |
| | 3 | 200 | | await unitOfWork.SaveChangesAsync(ct); |
| | 3 | 201 | | }, ct); |
| | | 202 | | |
| | 3 | 203 | | return AuthResult.Ok(); |
| | 8 | 204 | | } |
| | | 205 | | |
| | | 206 | | public async Task<AuthResult<AdminCreatedUser>> AdminCreateUserAsync(string username, string email, CancellationToke |
| | 13 | 207 | | { |
| | 13 | 208 | | ArgumentNullException.ThrowIfNull(username); |
| | 12 | 209 | | ArgumentNullException.ThrowIfNull(email); |
| | | 210 | | |
| | 11 | 211 | | var normalizedUsername = username.Trim().ToLowerInvariant(); |
| | 11 | 212 | | var normalizedEmail = email.Trim().ToLowerInvariant(); |
| | | 213 | | |
| | 11 | 214 | | var identityError = validator.ValidateIdentity(normalizedUsername, normalizedEmail); |
| | 11 | 215 | | if (identityError is not null) |
| | 2 | 216 | | return AuthResult.Fail<AdminCreatedUser>(identityError.Value); |
| | | 217 | | |
| | 9 | 218 | | if (await users.AnyByUsernameAsync(normalizedUsername, ct)) |
| | 1 | 219 | | return AuthResult.Fail<AdminCreatedUser>(AuthError.UsernameTaken); |
| | | 220 | | |
| | 8 | 221 | | if (await users.AnyByEmailAsync(normalizedEmail, ct)) |
| | 1 | 222 | | return AuthResult.Fail<AdminCreatedUser>(AuthError.EmailTaken); |
| | | 223 | | |
| | 7 | 224 | | var temporaryPassword = Convert.ToBase64String(RandomNumberGenerator.GetBytes(12)); |
| | | 225 | | |
| | 7 | 226 | | var user = new User |
| | 7 | 227 | | { |
| | 7 | 228 | | Id = guidFactory.NewGuid(), |
| | 7 | 229 | | Username = normalizedUsername, |
| | 7 | 230 | | Email = normalizedEmail, |
| | 7 | 231 | | PasswordHash = passwordHasher.Hash(temporaryPassword), |
| | 7 | 232 | | MustChangePassword = true, |
| | 7 | 233 | | }; |
| | | 234 | | |
| | 7 | 235 | | users.Add(user); |
| | | 236 | | |
| | | 237 | | try |
| | 7 | 238 | | { |
| | 7 | 239 | | await unitOfWork.SaveChangesAsync(ct); |
| | 4 | 240 | | } |
| | 3 | 241 | | catch (DbUpdateException ex) when (ex.InnerException is PostgresException { SqlState: "23505" } postgresExceptio |
| | 3 | 242 | | { |
| | 3 | 243 | | return AuthResult.Fail<AdminCreatedUser>(DetectConstraintError(postgresException)); |
| | | 244 | | } |
| | | 245 | | |
| | 4 | 246 | | return AuthResult.Ok(new AdminCreatedUser(user.Id, user.Username, user.Email, temporaryPassword)); |
| | 10 | 247 | | } |
| | | 248 | | |
| | | 249 | | private static AuthError DetectConstraintError(PostgresException postgresException) |
| | 6 | 250 | | => postgresException.ConstraintName switch |
| | 6 | 251 | | { |
| | 2 | 252 | | UserIndexNames.EmailUnique => AuthError.EmailTaken, |
| | 2 | 253 | | UserIndexNames.UsernameUnique => AuthError.UsernameTaken, |
| | 2 | 254 | | _ => throw new UnreachableException($"Unexpected unique constraint violation: {postgresException.ConstraintN |
| | 6 | 255 | | }; // ix_users_username is the only other unique constraint on User |
| | | 256 | | } |