|
| 1 | +using BikeTracking.Api.Application.Users; |
| 2 | +using BikeTracking.Api.Contracts; |
| 3 | +using BikeTracking.Api.Infrastructure.Persistence; |
| 4 | +using BikeTracking.Api.Tests.TestSupport; |
| 5 | +using Microsoft.EntityFrameworkCore; |
| 6 | + |
| 7 | +namespace BikeTracking.Api.Tests.Application.Users; |
| 8 | + |
| 9 | +public sealed class IdentifyServiceTests |
| 10 | +{ |
| 11 | + [Fact] |
| 12 | + public async Task IdentifyAsync_ReturnsValidationFailure_WhenRequestIsInvalid() |
| 13 | + { |
| 14 | + var (_, service, _) = CreateService(pin => pin == "1234"); |
| 15 | + |
| 16 | + var result = await service.IdentifyAsync( |
| 17 | + new IdentifyRequest("", "12ab"), |
| 18 | + CancellationToken.None |
| 19 | + ); |
| 20 | + |
| 21 | + Assert.Equal(IdentifyResultType.ValidationFailed, result.ResultType); |
| 22 | + Assert.NotNull(result.Error); |
| 23 | + Assert.Contains("Name is required.", result.Error.Details ?? []); |
| 24 | + Assert.Contains("PIN must contain only numeric characters.", result.Error.Details ?? []); |
| 25 | + } |
| 26 | + |
| 27 | + [Fact] |
| 28 | + public async Task IdentifyAsync_ReturnsUnauthorized_WhenUserNotFound() |
| 29 | + { |
| 30 | + var (_, service, _) = CreateService(pin => pin == "1234"); |
| 31 | + |
| 32 | + var result = await service.IdentifyAsync( |
| 33 | + new IdentifyRequest("Unknown", "1234"), |
| 34 | + CancellationToken.None |
| 35 | + ); |
| 36 | + |
| 37 | + Assert.Equal(IdentifyResultType.Unauthorized, result.ResultType); |
| 38 | + } |
| 39 | + |
| 40 | + [Fact] |
| 41 | + public async Task IdentifyAsync_ReturnsUnauthorizedAndIncrementsAttemptState_WhenPinIsWrong() |
| 42 | + { |
| 43 | + var (dbContext, service, _) = CreateService(pin => pin == "1234"); |
| 44 | + var user = await SeedUserAsync(dbContext); |
| 45 | + |
| 46 | + var result = await service.IdentifyAsync( |
| 47 | + new IdentifyRequest("Alice", "0000"), |
| 48 | + CancellationToken.None |
| 49 | + ); |
| 50 | + |
| 51 | + Assert.Equal(IdentifyResultType.Unauthorized, result.ResultType); |
| 52 | + |
| 53 | + var updatedState = await dbContext.AuthAttemptStates.SingleAsync(x => |
| 54 | + x.UserId == user.UserId |
| 55 | + ); |
| 56 | + Assert.Equal(1, updatedState.ConsecutiveWrongCount); |
| 57 | + Assert.NotNull(updatedState.LastWrongAttemptUtc); |
| 58 | + Assert.NotNull(updatedState.DelayUntilUtc); |
| 59 | + } |
| 60 | + |
| 61 | + [Fact] |
| 62 | + public async Task IdentifyAsync_ReturnsSuccessAndResetsAttemptState_WhenPinMatches() |
| 63 | + { |
| 64 | + var (dbContext, service, _) = CreateService(pin => pin == "1234"); |
| 65 | + var user = await SeedUserAsync( |
| 66 | + dbContext, |
| 67 | + new AuthAttemptStateEntity |
| 68 | + { |
| 69 | + ConsecutiveWrongCount = 3, |
| 70 | + DelayUntilUtc = DateTime.UtcNow.AddSeconds(-1), |
| 71 | + LastWrongAttemptUtc = DateTime.UtcNow.AddSeconds(-2), |
| 72 | + } |
| 73 | + ); |
| 74 | + |
| 75 | + var result = await service.IdentifyAsync( |
| 76 | + new IdentifyRequest("Alice", "1234"), |
| 77 | + CancellationToken.None |
| 78 | + ); |
| 79 | + |
| 80 | + Assert.Equal(IdentifyResultType.Success, result.ResultType); |
| 81 | + Assert.NotNull(result.Response); |
| 82 | + Assert.Equal(user.UserId, result.Response.UserId); |
| 83 | + Assert.Equal("Alice", result.Response.UserName); |
| 84 | + Assert.True(result.Response.Authorized); |
| 85 | + |
| 86 | + var updatedState = await dbContext.AuthAttemptStates.SingleAsync(x => |
| 87 | + x.UserId == user.UserId |
| 88 | + ); |
| 89 | + Assert.Equal(0, updatedState.ConsecutiveWrongCount); |
| 90 | + Assert.Null(updatedState.DelayUntilUtc); |
| 91 | + Assert.NotNull(updatedState.LastSuccessfulAuthUtc); |
| 92 | + } |
| 93 | + |
| 94 | + [Fact] |
| 95 | + public async Task IdentifyAsync_CreatesAttemptState_WhenMissing() |
| 96 | + { |
| 97 | + var (dbContext, service, _) = CreateService(pin => pin == "1234"); |
| 98 | + var user = await SeedUserAsync(dbContext, attemptState: null); |
| 99 | + |
| 100 | + var result = await service.IdentifyAsync( |
| 101 | + new IdentifyRequest("Alice", "0000"), |
| 102 | + CancellationToken.None |
| 103 | + ); |
| 104 | + |
| 105 | + Assert.Equal(IdentifyResultType.Unauthorized, result.ResultType); |
| 106 | + |
| 107 | + var state = await dbContext.AuthAttemptStates.SingleAsync(x => x.UserId == user.UserId); |
| 108 | + Assert.Equal(1, state.ConsecutiveWrongCount); |
| 109 | + } |
| 110 | + |
| 111 | + [Fact] |
| 112 | + public async Task IdentifyAsync_ReturnsThrottled_WhenDelayWindowIsActive() |
| 113 | + { |
| 114 | + var (dbContext, service, pinHasher) = CreateService(pin => pin == "1234"); |
| 115 | + |
| 116 | + await SeedUserAsync( |
| 117 | + dbContext, |
| 118 | + new AuthAttemptStateEntity |
| 119 | + { |
| 120 | + ConsecutiveWrongCount = 2, |
| 121 | + DelayUntilUtc = DateTime.UtcNow.AddSeconds(5), |
| 122 | + LastWrongAttemptUtc = DateTime.UtcNow, |
| 123 | + } |
| 124 | + ); |
| 125 | + |
| 126 | + var result = await service.IdentifyAsync( |
| 127 | + new IdentifyRequest("Alice", "1234"), |
| 128 | + CancellationToken.None |
| 129 | + ); |
| 130 | + |
| 131 | + Assert.Equal(IdentifyResultType.Throttled, result.ResultType); |
| 132 | + Assert.InRange(result.RetryAfterSeconds, 1, 5); |
| 133 | + Assert.Equal(0, pinHasher.VerifyCallCount); |
| 134 | + } |
| 135 | + |
| 136 | + [Fact] |
| 137 | + public async Task IdentifyAsync_UsesProgressiveDelaySteps_ForWrongAttempts() |
| 138 | + { |
| 139 | + var (dbContext, service, _) = CreateService(pin => pin == "1234"); |
| 140 | + var user = await SeedUserAsync( |
| 141 | + dbContext, |
| 142 | + new AuthAttemptStateEntity { ConsecutiveWrongCount = 0 } |
| 143 | + ); |
| 144 | + |
| 145 | + var expectedSteps = new[] { 1, 2, 3, 5, 8, 15, 30 }; |
| 146 | + |
| 147 | + foreach (var expectedDelaySeconds in expectedSteps) |
| 148 | + { |
| 149 | + var result = await service.IdentifyAsync( |
| 150 | + new IdentifyRequest("Alice", "0000"), |
| 151 | + CancellationToken.None |
| 152 | + ); |
| 153 | + |
| 154 | + Assert.Equal(IdentifyResultType.Unauthorized, result.ResultType); |
| 155 | + |
| 156 | + var state = await dbContext.AuthAttemptStates.SingleAsync(x => x.UserId == user.UserId); |
| 157 | + Assert.NotNull(state.DelayUntilUtc); |
| 158 | + Assert.NotNull(state.LastWrongAttemptUtc); |
| 159 | + |
| 160 | + var delaySeconds = (int) |
| 161 | + Math.Round( |
| 162 | + (state.DelayUntilUtc!.Value - state.LastWrongAttemptUtc!.Value).TotalSeconds |
| 163 | + ); |
| 164 | + Assert.Equal(expectedDelaySeconds, delaySeconds); |
| 165 | + |
| 166 | + state.DelayUntilUtc = DateTime.UtcNow.AddSeconds(-1); |
| 167 | + await dbContext.SaveChangesAsync(); |
| 168 | + } |
| 169 | + } |
| 170 | + |
| 171 | + [Fact] |
| 172 | + public async Task IdentifyAsync_RespectsConfiguredMaxThrottleSeconds() |
| 173 | + { |
| 174 | + var (dbContext, service, _) = CreateService( |
| 175 | + pin => pin == "1234", |
| 176 | + options => |
| 177 | + { |
| 178 | + options.Throttle.StepsSeconds = [10]; |
| 179 | + options.Throttle.MaxSeconds = 4; |
| 180 | + } |
| 181 | + ); |
| 182 | + |
| 183 | + var user = await SeedUserAsync( |
| 184 | + dbContext, |
| 185 | + new AuthAttemptStateEntity { ConsecutiveWrongCount = 0 } |
| 186 | + ); |
| 187 | + |
| 188 | + var result = await service.IdentifyAsync( |
| 189 | + new IdentifyRequest("Alice", "0000"), |
| 190 | + CancellationToken.None |
| 191 | + ); |
| 192 | + |
| 193 | + Assert.Equal(IdentifyResultType.Unauthorized, result.ResultType); |
| 194 | + |
| 195 | + var state = await dbContext.AuthAttemptStates.SingleAsync(x => x.UserId == user.UserId); |
| 196 | + var delaySeconds = (int) |
| 197 | + Math.Round( |
| 198 | + (state.DelayUntilUtc!.Value - state.LastWrongAttemptUtc!.Value).TotalSeconds |
| 199 | + ); |
| 200 | + |
| 201 | + Assert.Equal(4, delaySeconds); |
| 202 | + } |
| 203 | + |
| 204 | + private static (BikeTrackingDbContext, IdentifyService, DelegatePinHasher) CreateService( |
| 205 | + Func<string, bool> verifyPin, |
| 206 | + Action<IdentityOptions>? configureOptions = null |
| 207 | + ) |
| 208 | + { |
| 209 | + var options = TestFactories.IdentityOptions(configureOptions); |
| 210 | + var dbContext = TestFactories.CreateDbContext(); |
| 211 | + var validator = new PinPolicyValidator(options); |
| 212 | + var pinHasher = new DelegatePinHasher(verifyPin); |
| 213 | + var service = new IdentifyService(dbContext, validator, pinHasher, options); |
| 214 | + |
| 215 | + return (dbContext, service, pinHasher); |
| 216 | + } |
| 217 | + |
| 218 | + private static async Task<UserEntity> SeedUserAsync( |
| 219 | + BikeTrackingDbContext dbContext, |
| 220 | + AuthAttemptStateEntity? attemptState = null |
| 221 | + ) |
| 222 | + { |
| 223 | + var user = new UserEntity |
| 224 | + { |
| 225 | + DisplayName = "Alice", |
| 226 | + NormalizedName = "ALICE", |
| 227 | + CreatedAtUtc = DateTime.UtcNow, |
| 228 | + IsActive = true, |
| 229 | + Credential = new UserCredentialEntity |
| 230 | + { |
| 231 | + PinHash = [1, 2, 3, 4], |
| 232 | + PinSalt = [5, 6, 7, 8], |
| 233 | + HashAlgorithm = "PBKDF2-SHA256", |
| 234 | + IterationCount = 10000, |
| 235 | + CredentialVersion = 1, |
| 236 | + UpdatedAtUtc = DateTime.UtcNow, |
| 237 | + }, |
| 238 | + AuthAttemptState = attemptState, |
| 239 | + }; |
| 240 | + |
| 241 | + dbContext.Users.Add(user); |
| 242 | + await dbContext.SaveChangesAsync(); |
| 243 | + |
| 244 | + return user; |
| 245 | + } |
| 246 | +} |
0 commit comments