| | | 1 | | using System.Linq.Expressions; |
| | | 2 | | using System.Runtime.CompilerServices; |
| | | 3 | | using ArturRios.Heimdall.Data.Configuration; |
| | | 4 | | using ArturRios.Heimdall.Domain.Entities; |
| | | 5 | | using ArturRios.Heimdall.Domain.Persistence; |
| | | 6 | | using Microsoft.EntityFrameworkCore; |
| | | 7 | | |
| | | 8 | | namespace ArturRios.Heimdall.Data.Persistence; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// <see cref="IAtomicWrites" /> on EF Core's <c>ExecuteUpdate</c>: each method is a single |
| | | 12 | | /// <c>UPDATE … WHERE</c> whose condition is the rule being enforced, and whose affected-row count |
| | | 13 | | /// says whether this caller won. |
| | | 14 | | /// </summary> |
| | | 15 | | /// <remarks> |
| | | 16 | | /// <para> |
| | | 17 | | /// PostgreSQL makes the condition and the write one step: under READ COMMITTED, an |
| | | 18 | | /// <c>UPDATE</c> that waits on another transaction's lock re-evaluates its <c>WHERE</c> |
| | | 19 | | /// against the row as that transaction left it. So two requests spending the same code both |
| | | 20 | | /// reach the row, one writes, and the other finds "unused" no longer true and writes nothing. |
| | | 21 | | /// No row version is needed, and no table changes shape for it. |
| | | 22 | | /// </para> |
| | | 23 | | /// <para> |
| | | 24 | | /// <c>ExecuteUpdate</c> bypasses the change tracker, which would leave the caller's tracked |
| | | 25 | | /// instance stale — and a later save would write the stale values back over the atomic ones. |
| | | 26 | | /// <see cref="Accept{T,TProperty}" /> sets the instance's current and original values to what |
| | | 27 | | /// was written, so the tracker sees nothing to save. |
| | | 28 | | /// </para> |
| | | 29 | | /// </remarks> |
| | 570 | 30 | | public sealed class AtomicWrites(AppDbContext context) : IAtomicWrites |
| | | 31 | | { |
| | | 32 | | public async Task<bool> TryReserveLoginAttemptAsync( |
| | | 33 | | Person person, int maxAttempts, DateTime now, DateTime lockedOutUntil) |
| | | 34 | | { |
| | | 35 | | // One statement, so the attempt that reaches the limit is also the one that locks: every |
| | | 36 | | // right-hand side reads the row as it was before the update. A request that dies after this |
| | | 37 | | // returns — shed by the hash gate, or cut off by a database fault — has still left a lock that |
| | | 38 | | // expires, and not a counter at the limit that nothing could ever reset. A row already at or |
| | | 39 | | // past the limit with no lockout date (left by an older instance, or by a lowered limit) is |
| | | 40 | | // admitted too: the same >= test locks it and resets the counter, so it heals itself. |
| | 97 | 41 | | var reserved = await context.Persons |
| | 97 | 42 | | .Where(x => x.Id == person.Id && |
| | 97 | 43 | | ((x.FailedLoginAttempts < maxAttempts && |
| | 97 | 44 | | (x.LockedOutUntil == null || x.LockedOutUntil <= now)) || |
| | 97 | 45 | | (x.FailedLoginAttempts >= maxAttempts && x.LockedOutUntil == null))) |
| | 194 | 46 | | .ExecuteUpdateAsync(set => set |
| | 194 | 47 | | .SetProperty(x => x.LockedOutUntil, |
| | 194 | 48 | | x => x.FailedLoginAttempts + 1 >= maxAttempts ? lockedOutUntil : x.LockedOutUntil) |
| | 194 | 49 | | .SetProperty(x => x.FailedLoginAttempts, |
| | 194 | 50 | | x => x.FailedLoginAttempts + 1 >= maxAttempts ? 0 : x.FailedLoginAttempts + 1)) == 1; |
| | | 51 | | |
| | 97 | 52 | | if (reserved) |
| | | 53 | | { |
| | 96 | 54 | | var reachedLimit = person.FailedLoginAttempts + 1 >= maxAttempts; |
| | | 55 | | |
| | 96 | 56 | | if (reachedLimit) |
| | | 57 | | { |
| | 3 | 58 | | Accept(person, x => x.LockedOutUntil, lockedOutUntil); |
| | | 59 | | } |
| | | 60 | | |
| | 96 | 61 | | Accept(person, x => x.FailedLoginAttempts, reachedLimit ? 0 : person.FailedLoginAttempts + 1); |
| | | 62 | | } |
| | | 63 | | |
| | 97 | 64 | | return reserved; |
| | 97 | 65 | | } |
| | | 66 | | |
| | | 67 | | public async Task<bool> TryChargePendingRegistrationGuessAsync(PendingRegistration pending, int maxGuesses) |
| | | 68 | | { |
| | 14 | 69 | | var charged = await context.PendingRegistrations |
| | 14 | 70 | | .Where(x => x.Id == pending.Id && x.FailedAttempts < maxGuesses) |
| | 28 | 71 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.FailedAttempts, x => x.FailedAttempts + 1)) == 1; |
| | | 72 | | |
| | 14 | 73 | | if (charged) |
| | | 74 | | { |
| | 10 | 75 | | Accept(pending, x => x.FailedAttempts, pending.FailedAttempts + 1); |
| | | 76 | | } |
| | | 77 | | |
| | 14 | 78 | | return charged; |
| | 14 | 79 | | } |
| | | 80 | | |
| | | 81 | | public async Task ClearLoginAttemptsAsync(Person person) |
| | | 82 | | { |
| | 79 | 83 | | await context.Persons |
| | 79 | 84 | | .Where(x => x.Id == person.Id) |
| | 158 | 85 | | .ExecuteUpdateAsync(set => set |
| | 158 | 86 | | .SetProperty(x => x.FailedLoginAttempts, 0) |
| | 158 | 87 | | .SetProperty(x => x.LockedOutUntil, (DateTime?)null)); |
| | | 88 | | |
| | 79 | 89 | | Accept(person, x => x.FailedLoginAttempts, 0); |
| | 79 | 90 | | Accept(person, x => x.LockedOutUntil, null); |
| | 79 | 91 | | } |
| | | 92 | | |
| | | 93 | | public async Task<bool> TryReserveSecondFactorAttemptAsync( |
| | | 94 | | Person person, int maxAttempts, DateTime now, IReadOnlyList<DateTime> lockedOutUntil) |
| | | 95 | | { |
| | 51 | 96 | | ArgumentOutOfRangeException.ThrowIfZero(lockedOutUntil.Count, nameof(lockedOutUntil)); |
| | | 97 | | |
| | | 98 | | // The login reservation's shape, for the same reasons: the reservation that reaches the limit |
| | | 99 | | // is the one that locks, and a row at or past the limit with no live lock — none at all, or |
| | | 100 | | // one that has run out, as a lowered limit would leave — is admitted and locked, so it heals |
| | | 101 | | // itself rather than being refused for good. What differs |
| | | 102 | | // is the lock's length, which depends on how many locks came before — so it is chosen by the |
| | | 103 | | // stored lockout count, inside the same statement, rather than from the count this request |
| | | 104 | | // read: two requests that both read "one lock so far" cannot both set the second lock's end. |
| | 51 | 105 | | var reserved = await context.Persons |
| | 51 | 106 | | .Where(x => x.Id == person.Id && |
| | 51 | 107 | | ((x.FailedSecondFactorAttempts < maxAttempts && |
| | 51 | 108 | | (x.SecondFactorLockedOutUntil == null || x.SecondFactorLockedOutUntil <= now)) || |
| | 51 | 109 | | (x.FailedSecondFactorAttempts >= maxAttempts && |
| | 51 | 110 | | (x.SecondFactorLockedOutUntil == null || x.SecondFactorLockedOutUntil <= now)))) |
| | 102 | 111 | | .ExecuteUpdateAsync(set => set |
| | 102 | 112 | | .SetProperty(x => x.SecondFactorLockedOutUntil, SecondFactorLockEnd(maxAttempts, lockedOutUntil)) |
| | 102 | 113 | | .SetProperty(x => x.SecondFactorLockouts, |
| | 102 | 114 | | x => x.FailedSecondFactorAttempts + 1 >= maxAttempts |
| | 102 | 115 | | ? x.SecondFactorLockouts + 1 |
| | 102 | 116 | | : x.SecondFactorLockouts) |
| | 102 | 117 | | .SetProperty(x => x.FailedSecondFactorAttempts, |
| | 102 | 118 | | x => x.FailedSecondFactorAttempts + 1 >= maxAttempts ? 0 : x.FailedSecondFactorAttempts + 1)) == 1; |
| | | 119 | | |
| | 51 | 120 | | if (reserved) |
| | | 121 | | { |
| | 46 | 122 | | var reachedLimit = person.FailedSecondFactorAttempts + 1 >= maxAttempts; |
| | | 123 | | |
| | 46 | 124 | | if (reachedLimit) |
| | | 125 | | { |
| | 4 | 126 | | Accept(person, x => x.SecondFactorLockedOutUntil, LockEndAfter(person.SecondFactorLockouts, lockedOutUnt |
| | 4 | 127 | | Accept(person, x => x.SecondFactorLockouts, person.SecondFactorLockouts + 1); |
| | | 128 | | } |
| | | 129 | | |
| | 46 | 130 | | Accept(person, x => x.FailedSecondFactorAttempts, reachedLimit ? 0 : person.FailedSecondFactorAttempts + 1); |
| | | 131 | | } |
| | | 132 | | else |
| | | 133 | | { |
| | 5 | 134 | | await TouchAsync(person); |
| | | 135 | | } |
| | | 136 | | |
| | 51 | 137 | | return reserved; |
| | 51 | 138 | | } |
| | | 139 | | |
| | | 140 | | public async Task ClearSecondFactorAttemptsAsync(Person person) |
| | | 141 | | { |
| | 28 | 142 | | await context.Persons |
| | 28 | 143 | | .Where(x => x.Id == person.Id) |
| | 56 | 144 | | .ExecuteUpdateAsync(set => set |
| | 56 | 145 | | .SetProperty(x => x.FailedSecondFactorAttempts, 0) |
| | 56 | 146 | | .SetProperty(x => x.SecondFactorLockedOutUntil, (DateTime?)null) |
| | 56 | 147 | | .SetProperty(x => x.SecondFactorLockouts, 0)); |
| | | 148 | | |
| | 28 | 149 | | Accept(person, x => x.FailedSecondFactorAttempts, 0); |
| | 28 | 150 | | Accept(person, x => x.SecondFactorLockedOutUntil, null); |
| | 28 | 151 | | Accept(person, x => x.SecondFactorLockouts, 0); |
| | 28 | 152 | | } |
| | | 153 | | |
| | | 154 | | public async Task<bool> TryReserveReauthenticationAsync( |
| | | 155 | | Person person, int maxFailures, DateTime now, DateTime windowStartedBy, DateTime pausedUntil) |
| | | 156 | | { |
| | | 157 | | // One statement, every right-hand side reading the row as it was. The window is open when it |
| | | 158 | | // started after windowStartedBy (a NULL start is no window, and compares false); the failure |
| | | 159 | | // counted here is then the window's next, or else the first of a new window. The failure that |
| | | 160 | | // reaches the limit pauses and closes the window in the same write, as the login reservation |
| | | 161 | | // locks, so a burst cannot each read "below the limit" and pass it together. |
| | 105 | 162 | | var reserved = await context.Persons |
| | 105 | 163 | | .Where(x => x.Id == person.Id && |
| | 105 | 164 | | (x.ReauthenticationPausedUntil == null || x.ReauthenticationPausedUntil <= now)) |
| | 210 | 165 | | .ExecuteUpdateAsync(set => set |
| | 210 | 166 | | .SetProperty(x => x.ReauthenticationPausedUntil, |
| | 210 | 167 | | x => (x.ReauthenticationWindowStartedAt > windowStartedBy |
| | 210 | 168 | | ? x.FailedReauthenticationAttempts + 1 |
| | 210 | 169 | | : 1) >= maxFailures |
| | 210 | 170 | | ? (DateTime?)pausedUntil |
| | 210 | 171 | | : x.ReauthenticationPausedUntil) |
| | 210 | 172 | | .SetProperty(x => x.ReauthenticationWindowStartedAt, |
| | 210 | 173 | | x => (x.ReauthenticationWindowStartedAt > windowStartedBy |
| | 210 | 174 | | ? x.FailedReauthenticationAttempts + 1 |
| | 210 | 175 | | : 1) >= maxFailures |
| | 210 | 176 | | ? null |
| | 210 | 177 | | : x.ReauthenticationWindowStartedAt > windowStartedBy |
| | 210 | 178 | | ? x.ReauthenticationWindowStartedAt |
| | 210 | 179 | | : (DateTime?)now) |
| | 210 | 180 | | .SetProperty(x => x.FailedReauthenticationAttempts, |
| | 210 | 181 | | x => (x.ReauthenticationWindowStartedAt > windowStartedBy |
| | 210 | 182 | | ? x.FailedReauthenticationAttempts + 1 |
| | 210 | 183 | | : 1) >= maxFailures |
| | 210 | 184 | | ? 0 |
| | 210 | 185 | | : x.ReauthenticationWindowStartedAt > windowStartedBy |
| | 210 | 186 | | ? x.FailedReauthenticationAttempts + 1 |
| | 210 | 187 | | : 1)) == 1; |
| | | 188 | | |
| | 105 | 189 | | if (reserved) |
| | | 190 | | { |
| | 96 | 191 | | var windowOpen = person.ReauthenticationWindowStartedAt > windowStartedBy; |
| | 96 | 192 | | var failures = windowOpen ? person.FailedReauthenticationAttempts + 1 : 1; |
| | 96 | 193 | | var paused = failures >= maxFailures; |
| | | 194 | | |
| | 96 | 195 | | if (paused) |
| | | 196 | | { |
| | 2 | 197 | | Accept(person, x => x.ReauthenticationPausedUntil, pausedUntil); |
| | | 198 | | } |
| | | 199 | | |
| | 96 | 200 | | Accept(person, x => x.ReauthenticationWindowStartedAt, |
| | 96 | 201 | | paused ? null : windowOpen ? person.ReauthenticationWindowStartedAt : now); |
| | 96 | 202 | | Accept(person, x => x.FailedReauthenticationAttempts, paused ? 0 : failures); |
| | | 203 | | } |
| | | 204 | | else |
| | | 205 | | { |
| | 9 | 206 | | await TouchAsync(person); |
| | | 207 | | } |
| | | 208 | | |
| | 105 | 209 | | return reserved; |
| | 105 | 210 | | } |
| | | 211 | | |
| | | 212 | | public async Task<AccountEmailReservation> TryReserveAccountEmailAsync( |
| | | 213 | | Person person, int maxPerWindow, DateTime now, DateTime lastSentBefore, DateTime windowEndsAt) |
| | | 214 | | { |
| | | 215 | | // One statement, every right-hand side reading the row as it was. Admitted only out of the |
| | | 216 | | // cooldown and under the window's count; an ended (or never opened) window starts again at |
| | | 217 | | // this send. Concurrent reservations queue on the row lock and re-read it, so a burst gets |
| | | 218 | | // exactly what is left — one inside a cooldown, at most the cap with none. |
| | 55 | 219 | | var reserved = await context.Persons |
| | 55 | 220 | | .Where(x => x.Id == person.Id && |
| | 55 | 221 | | (x.AccountEmailLastSentAt == null || x.AccountEmailLastSentAt <= lastSentBefore) && |
| | 55 | 222 | | (x.AccountEmailWindowEndsAt == null || x.AccountEmailWindowEndsAt <= now || |
| | 55 | 223 | | x.AccountEmailsSent < maxPerWindow)) |
| | 110 | 224 | | .ExecuteUpdateAsync(set => set |
| | 110 | 225 | | .SetProperty(x => x.AccountEmailsSent, |
| | 110 | 226 | | x => x.AccountEmailWindowEndsAt == null || x.AccountEmailWindowEndsAt <= now |
| | 110 | 227 | | ? 1 |
| | 110 | 228 | | : x.AccountEmailsSent + 1) |
| | 110 | 229 | | .SetProperty(x => x.AccountEmailWindowEndsAt, |
| | 110 | 230 | | x => x.AccountEmailWindowEndsAt == null || x.AccountEmailWindowEndsAt <= now |
| | 110 | 231 | | ? (DateTime?)windowEndsAt |
| | 110 | 232 | | : x.AccountEmailWindowEndsAt) |
| | 110 | 233 | | .SetProperty(x => x.AccountEmailLastSentAt, (DateTime?)now)) == 1; |
| | | 234 | | |
| | 55 | 235 | | if (reserved) |
| | | 236 | | { |
| | 26 | 237 | | var windowOpen = person.AccountEmailWindowEndsAt > now; |
| | | 238 | | |
| | 26 | 239 | | Accept(person, x => x.AccountEmailsSent, windowOpen ? person.AccountEmailsSent + 1 : 1); |
| | 26 | 240 | | Accept(person, x => x.AccountEmailWindowEndsAt, windowOpen ? person.AccountEmailWindowEndsAt : windowEndsAt) |
| | 26 | 241 | | Accept(person, x => x.AccountEmailLastSentAt, now); |
| | | 242 | | |
| | 26 | 243 | | return AccountEmailReservation.Reserved; |
| | | 244 | | } |
| | | 245 | | |
| | | 246 | | // Refused: read the row as it now is, to say which bound refused it and when it ends, and bring |
| | | 247 | | // the instance in line with it. The daily one is the more useful answer when both apply, since |
| | | 248 | | // waiting out the cooldown would not help. A row gone since it was loaded (a hard delete in |
| | | 249 | | // between) is refused too: nothing may be sent to a person who no longer exists. |
| | 29 | 250 | | var stored = await context.Persons |
| | 29 | 251 | | .AsNoTracking() |
| | 29 | 252 | | .Where(x => x.Id == person.Id) |
| | 29 | 253 | | .Select(x => new { x.AccountEmailsSent, x.AccountEmailWindowEndsAt, x.AccountEmailLastSentAt }) |
| | 29 | 254 | | .SingleOrDefaultAsync(); |
| | | 255 | | |
| | 29 | 256 | | if (stored is null) |
| | | 257 | | { |
| | 1 | 258 | | return AccountEmailReservation.CoolingDown; |
| | | 259 | | } |
| | | 260 | | |
| | 28 | 261 | | Accept(person, x => x.AccountEmailsSent, stored.AccountEmailsSent); |
| | 28 | 262 | | Accept(person, x => x.AccountEmailWindowEndsAt, stored.AccountEmailWindowEndsAt); |
| | 28 | 263 | | Accept(person, x => x.AccountEmailLastSentAt, stored.AccountEmailLastSentAt); |
| | | 264 | | |
| | 28 | 265 | | return stored.AccountEmailWindowEndsAt > now && stored.AccountEmailsSent >= maxPerWindow |
| | 28 | 266 | | ? AccountEmailReservation.DailyLimitReached |
| | 28 | 267 | | : AccountEmailReservation.CoolingDown; |
| | 55 | 268 | | } |
| | | 269 | | |
| | | 270 | | public async Task ClearAccountEmailsAsync(Person person) |
| | | 271 | | { |
| | 7 | 272 | | await context.Persons |
| | 7 | 273 | | .Where(x => x.Id == person.Id) |
| | 14 | 274 | | .ExecuteUpdateAsync(set => set |
| | 14 | 275 | | .SetProperty(x => x.AccountEmailsSent, 0) |
| | 14 | 276 | | .SetProperty(x => x.AccountEmailWindowEndsAt, (DateTime?)null) |
| | 14 | 277 | | .SetProperty(x => x.AccountEmailLastSentAt, (DateTime?)null)); |
| | | 278 | | |
| | 7 | 279 | | Accept(person, x => x.AccountEmailsSent, 0); |
| | 7 | 280 | | Accept(person, x => x.AccountEmailWindowEndsAt, null); |
| | 7 | 281 | | Accept(person, x => x.AccountEmailLastSentAt, null); |
| | 7 | 282 | | } |
| | | 283 | | |
| | | 284 | | public async Task ClearReauthenticationAttemptsAsync(Person person) |
| | | 285 | | { |
| | 62 | 286 | | await context.Persons |
| | 62 | 287 | | .Where(x => x.Id == person.Id) |
| | 124 | 288 | | .ExecuteUpdateAsync(set => set |
| | 124 | 289 | | .SetProperty(x => x.FailedReauthenticationAttempts, 0) |
| | 124 | 290 | | .SetProperty(x => x.ReauthenticationWindowStartedAt, (DateTime?)null) |
| | 124 | 291 | | .SetProperty(x => x.ReauthenticationPausedUntil, (DateTime?)null)); |
| | | 292 | | |
| | 62 | 293 | | Accept(person, x => x.FailedReauthenticationAttempts, 0); |
| | 62 | 294 | | Accept(person, x => x.ReauthenticationWindowStartedAt, null); |
| | 62 | 295 | | Accept(person, x => x.ReauthenticationPausedUntil, null); |
| | 62 | 296 | | } |
| | | 297 | | |
| | | 298 | | public async Task StartChallengeAsync(TwoFactorAuth configuration, Guid challengeId) |
| | | 299 | | { |
| | 28 | 300 | | await context.TwoFactorAuths |
| | 28 | 301 | | .Where(x => x.Id == configuration.Id) |
| | 56 | 302 | | .ExecuteUpdateAsync(set => set |
| | 56 | 303 | | .SetProperty(x => x.ChallengeId, challengeId) |
| | 56 | 304 | | .SetProperty(x => x.EmailCodeReissueCount, 0) |
| | 56 | 305 | | .SetProperty(x => x.ChallengeAttempts, 0)); |
| | | 306 | | |
| | 28 | 307 | | Accept(configuration, x => x.ChallengeId, challengeId); |
| | 28 | 308 | | Accept(configuration, x => x.EmailCodeReissueCount, 0); |
| | 28 | 309 | | Accept(configuration, x => x.ChallengeAttempts, 0); |
| | 28 | 310 | | } |
| | | 311 | | |
| | | 312 | | public async Task<bool> TryChargeChallengeGuessAsync(TwoFactorAuth configuration, Guid challengeId, int maxGuesses) |
| | | 313 | | { |
| | 38 | 314 | | var charged = await context.TwoFactorAuths |
| | 38 | 315 | | .Where(x => x.Id == configuration.Id && x.ChallengeId == challengeId && x.ChallengeAttempts < maxGuesses) |
| | 76 | 316 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.ChallengeAttempts, x => x.ChallengeAttempts + 1)) == 1; |
| | | 317 | | |
| | 38 | 318 | | if (charged) |
| | | 319 | | { |
| | 36 | 320 | | Accept(configuration, x => x.ChallengeAttempts, configuration.ChallengeAttempts + 1); |
| | | 321 | | } |
| | | 322 | | |
| | 38 | 323 | | return charged; |
| | 38 | 324 | | } |
| | | 325 | | |
| | | 326 | | public async Task ExpireChallengeIfExhaustedAsync(TwoFactorAuth configuration, Guid challengeId, int maxGuesses) |
| | | 327 | | { |
| | 19 | 328 | | var expired = await context.TwoFactorAuths |
| | 19 | 329 | | .Where(x => x.Id == configuration.Id && x.ChallengeId == challengeId && x.ChallengeAttempts >= maxGuesses) |
| | 38 | 330 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.ChallengeId, (Guid?)null)) == 1; |
| | | 331 | | |
| | 19 | 332 | | if (expired) |
| | | 333 | | { |
| | 2 | 334 | | Accept(configuration, x => x.ChallengeId, null); |
| | | 335 | | } |
| | 19 | 336 | | } |
| | | 337 | | |
| | | 338 | | public async Task<bool> TryRedeemChallengeAsync(TwoFactorAuth configuration, Guid challengeId) |
| | | 339 | | { |
| | 21 | 340 | | var redeemed = await context.TwoFactorAuths |
| | 21 | 341 | | .Where(x => x.Id == configuration.Id && x.ChallengeId == challengeId) |
| | 42 | 342 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.ChallengeId, (Guid?)null)) == 1; |
| | | 343 | | |
| | 21 | 344 | | if (redeemed) |
| | | 345 | | { |
| | 20 | 346 | | Accept(configuration, x => x.ChallengeId, null); |
| | | 347 | | } |
| | | 348 | | |
| | 21 | 349 | | return redeemed; |
| | 21 | 350 | | } |
| | | 351 | | |
| | | 352 | | public async Task<bool> TryChargeEmailCodeReissueAsync(TwoFactorAuth configuration, Guid challengeId, int maxReissue |
| | | 353 | | { |
| | 16 | 354 | | var charged = await context.TwoFactorAuths |
| | 16 | 355 | | .Where(x => x.Id == configuration.Id && x.ChallengeId == challengeId && x.EmailCodeReissueCount < maxReissue |
| | 32 | 356 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.EmailCodeReissueCount, x => x.EmailCodeReissueCount + 1)) |
| | | 357 | | |
| | 16 | 358 | | if (charged) |
| | | 359 | | { |
| | 16 | 360 | | Accept(configuration, x => x.EmailCodeReissueCount, configuration.EmailCodeReissueCount + 1); |
| | | 361 | | } |
| | | 362 | | |
| | 16 | 363 | | return charged; |
| | 16 | 364 | | } |
| | | 365 | | |
| | | 366 | | public async Task<bool> TryAdvanceTotpStepAsync(TwoFactorAuth configuration, long timeStep, DateTime now) |
| | | 367 | | { |
| | 15 | 368 | | var advanced = await context.TwoFactorAuths |
| | 15 | 369 | | .Where(x => x.Id == configuration.Id && |
| | 15 | 370 | | (x.LastTotpTimeStepUsed == null || x.LastTotpTimeStepUsed < timeStep)) |
| | 30 | 371 | | .ExecuteUpdateAsync(set => set |
| | 30 | 372 | | .SetProperty(x => x.LastTotpTimeStepUsed, timeStep) |
| | 30 | 373 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 374 | | |
| | 15 | 375 | | if (advanced) |
| | | 376 | | { |
| | 14 | 377 | | Accept(configuration, x => x.LastTotpTimeStepUsed, timeStep); |
| | 14 | 378 | | Accept(configuration, x => x.UpdatedAt, now); |
| | | 379 | | } |
| | | 380 | | |
| | 15 | 381 | | return advanced; |
| | 15 | 382 | | } |
| | | 383 | | |
| | | 384 | | public async Task<bool> TryChargeEmailCodeGuessAsync(TwoFactorEmailCode code, int maxGuesses, DateTime now) |
| | | 385 | | { |
| | 21 | 386 | | var charged = await context.TwoFactorEmailCodes |
| | 21 | 387 | | .Where(x => x.Id == code.Id && !x.Used && x.ExpiresAt > now && x.FailedAttempts < maxGuesses) |
| | 42 | 388 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.FailedAttempts, x => x.FailedAttempts + 1)) == 1; |
| | | 389 | | |
| | 21 | 390 | | if (charged) |
| | | 391 | | { |
| | 16 | 392 | | Accept(code, x => x.FailedAttempts, code.FailedAttempts + 1); |
| | | 393 | | } |
| | | 394 | | |
| | 21 | 395 | | return charged; |
| | 21 | 396 | | } |
| | | 397 | | |
| | | 398 | | public async Task RetireEmailCodeIfExhaustedAsync(TwoFactorEmailCode code, int maxGuesses) |
| | | 399 | | { |
| | 7 | 400 | | var retired = await context.TwoFactorEmailCodes |
| | 7 | 401 | | .Where(x => x.Id == code.Id && x.FailedAttempts >= maxGuesses) |
| | 14 | 402 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.Used, true)) == 1; |
| | | 403 | | |
| | 7 | 404 | | if (retired) |
| | | 405 | | { |
| | 5 | 406 | | Accept(code, x => x.Used, true); |
| | | 407 | | } |
| | 7 | 408 | | } |
| | | 409 | | |
| | | 410 | | public async Task<bool> TryConsumeEmailCodeAsync(TwoFactorEmailCode code) |
| | | 411 | | { |
| | 7 | 412 | | var consumed = await context.TwoFactorEmailCodes |
| | 7 | 413 | | .Where(x => x.Id == code.Id && !x.Used) |
| | 14 | 414 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.Used, true)) == 1; |
| | | 415 | | |
| | 7 | 416 | | if (consumed) |
| | | 417 | | { |
| | 7 | 418 | | Accept(code, x => x.Used, true); |
| | | 419 | | } |
| | | 420 | | |
| | 7 | 421 | | return consumed; |
| | 7 | 422 | | } |
| | | 423 | | |
| | | 424 | | public async Task<bool> TryConsumeRecoveryCodeAsync(TwoFactorRecoveryCode code, DateTime usedAt) |
| | | 425 | | { |
| | 20 | 426 | | var consumed = await context.TwoFactorRecoveryCodes |
| | 20 | 427 | | .Where(x => x.Id == code.Id && !x.Used) |
| | 40 | 428 | | .ExecuteUpdateAsync(set => set |
| | 40 | 429 | | .SetProperty(x => x.Used, true) |
| | 40 | 430 | | .SetProperty(x => x.UsedAt, usedAt)) == 1; |
| | | 431 | | |
| | 20 | 432 | | if (consumed) |
| | | 433 | | { |
| | 17 | 434 | | Accept(code, x => x.Used, true); |
| | 17 | 435 | | Accept(code, x => x.UsedAt, usedAt); |
| | | 436 | | } |
| | | 437 | | |
| | 20 | 438 | | return consumed; |
| | 20 | 439 | | } |
| | | 440 | | |
| | | 441 | | public async Task<bool> TryConsumePasswordResetTokenAsync(PasswordResetToken token, DateTime now) |
| | | 442 | | { |
| | 14 | 443 | | var consumed = await context.PasswordResetTokens |
| | 14 | 444 | | .Where(x => x.Id == token.Id && !x.Used && x.ExpiresAt > now) |
| | 28 | 445 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.Used, true)) == 1; |
| | | 446 | | |
| | 14 | 447 | | if (consumed) |
| | | 448 | | { |
| | 9 | 449 | | Accept(token, x => x.Used, true); |
| | | 450 | | } |
| | | 451 | | |
| | 14 | 452 | | return consumed; |
| | 14 | 453 | | } |
| | | 454 | | |
| | | 455 | | public async Task<bool> TryConsumeEmailVerificationTokenAsync(EmailVerificationToken token, DateTime now) |
| | | 456 | | { |
| | 15 | 457 | | var consumed = await context.EmailVerificationTokens |
| | 15 | 458 | | .Where(x => x.Id == token.Id && !x.Used && x.ExpiresAt > now) |
| | 30 | 459 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.Used, true)) == 1; |
| | | 460 | | |
| | 15 | 461 | | if (consumed) |
| | | 462 | | { |
| | 8 | 463 | | Accept(token, x => x.Used, true); |
| | | 464 | | } |
| | | 465 | | |
| | 15 | 466 | | return consumed; |
| | 15 | 467 | | } |
| | | 468 | | |
| | | 469 | | public async Task<bool> TrySetPasswordAsync(Person person, byte[] passwordHash, byte[] salt, DateTime now) |
| | | 470 | | { |
| | 13 | 471 | | var stamp = Guid.NewGuid(); |
| | | 472 | | |
| | 13 | 473 | | var written = await context.Persons |
| | 13 | 474 | | .Where(RedeemableAsRead(person)) |
| | 26 | 475 | | .ExecuteUpdateAsync(set => set |
| | 26 | 476 | | .SetProperty(x => x.PasswordHash, passwordHash) |
| | 26 | 477 | | .SetProperty(x => x.Salt, salt) |
| | 26 | 478 | | .SetProperty(x => x.SecurityStamp, stamp) |
| | 26 | 479 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 480 | | |
| | 13 | 481 | | if (written) |
| | | 482 | | { |
| | 10 | 483 | | Accept(person, x => x.PasswordHash, passwordHash); |
| | 10 | 484 | | Accept(person, x => x.Salt, salt); |
| | 10 | 485 | | Accept(person, x => x.SecurityStamp, stamp); |
| | 10 | 486 | | Accept(person, x => x.UpdatedAt, now); |
| | | 487 | | } |
| | | 488 | | |
| | 13 | 489 | | return written; |
| | 13 | 490 | | } |
| | | 491 | | |
| | | 492 | | public async Task ClearPasswordAsync(Person person) |
| | | 493 | | { |
| | 7 | 494 | | byte[] empty = []; |
| | | 495 | | |
| | 7 | 496 | | await context.Persons |
| | 7 | 497 | | .Where(x => x.Id == person.Id) |
| | 14 | 498 | | .ExecuteUpdateAsync(set => set |
| | 14 | 499 | | .SetProperty(x => x.PasswordHash, empty) |
| | 14 | 500 | | .SetProperty(x => x.Salt, empty)); |
| | | 501 | | |
| | 7 | 502 | | Accept(person, x => x.PasswordHash, empty); |
| | 7 | 503 | | Accept(person, x => x.Salt, empty); |
| | 7 | 504 | | } |
| | | 505 | | |
| | | 506 | | public async Task<bool> TryMarkEmailVerifiedAsync(Person person, DateTime now) |
| | | 507 | | { |
| | 10 | 508 | | var written = await context.Persons |
| | 10 | 509 | | .Where(RedeemableAsRead(person)) |
| | 20 | 510 | | .ExecuteUpdateAsync(set => set |
| | 20 | 511 | | .SetProperty(x => x.EmailVerified, true) |
| | 20 | 512 | | .SetProperty(x => x.UpdatedAt, now)) == 1; |
| | | 513 | | |
| | 10 | 514 | | if (written) |
| | | 515 | | { |
| | 8 | 516 | | Accept(person, x => x.EmailVerified, true); |
| | 8 | 517 | | Accept(person, x => x.UpdatedAt, now); |
| | | 518 | | } |
| | | 519 | | |
| | 10 | 520 | | return written; |
| | 10 | 521 | | } |
| | | 522 | | |
| | | 523 | | public async Task<bool> TryStampCredentialUseAsync(ApplicationCredential credential, DateTime now) |
| | | 524 | | { |
| | 12 | 525 | | var stamped = await context.ApplicationCredentials |
| | 12 | 526 | | .Where(x => x.Id == credential.Id) |
| | 12 | 527 | | .Where(ApplicationCredential.LiveAt(now)) |
| | 24 | 528 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.LastUsedAt, now)) == 1; |
| | | 529 | | |
| | 12 | 530 | | if (stamped) |
| | | 531 | | { |
| | 11 | 532 | | Accept(credential, x => x.LastUsedAt, now); |
| | | 533 | | } |
| | | 534 | | |
| | 12 | 535 | | return stamped; |
| | 12 | 536 | | } |
| | | 537 | | |
| | | 538 | | public async Task<bool> TryRevokeCredentialAsync(ApplicationCredential credential, DateTime revokedAt) |
| | | 539 | | { |
| | 6 | 540 | | var revoked = await context.ApplicationCredentials |
| | 6 | 541 | | .Where(x => x.Id == credential.Id && x.RevokedAt == null) |
| | 12 | 542 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.RevokedAt, revokedAt)) == 1; |
| | | 543 | | |
| | 6 | 544 | | if (revoked) |
| | | 545 | | { |
| | 4 | 546 | | Accept(credential, x => x.RevokedAt, revokedAt); |
| | | 547 | | } |
| | | 548 | | |
| | 6 | 549 | | return revoked; |
| | 6 | 550 | | } |
| | | 551 | | |
| | | 552 | | public async Task RotateSecurityStampAsync(Person person) |
| | | 553 | | { |
| | 39 | 554 | | var stamp = Guid.NewGuid(); |
| | | 555 | | |
| | 39 | 556 | | await context.Persons |
| | 39 | 557 | | .Where(x => x.Id == person.Id) |
| | 78 | 558 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.SecurityStamp, stamp)); |
| | | 559 | | |
| | 39 | 560 | | Accept(person, x => x.SecurityStamp, stamp); |
| | 39 | 561 | | } |
| | | 562 | | |
| | | 563 | | /// <summary> |
| | | 564 | | /// The row <paramref name="person" /> was read from, if it still holds the address it was |
| | | 565 | | /// read with and is not deleted, restricted or anonymised: the condition a single-use token |
| | | 566 | | /// is redeemed under (FR-PR-08, FR-EV-08). The address is captured now, so the comparison is |
| | | 567 | | /// against the value the caller read, not whatever the row holds by the time it runs. |
| | | 568 | | /// </summary> |
| | | 569 | | private static Expression<Func<Person, bool>> RedeemableAsRead(Person person) |
| | | 570 | | { |
| | 23 | 571 | | var id = person.Id; |
| | 23 | 572 | | var email = person.Email; |
| | | 573 | | |
| | 23 | 574 | | return x => x.Id == id && x.Email == email && !x.IsDeleted && |
| | 23 | 575 | | x.ProcessingRestrictedAt == null && x.AnonymisedAt == null; |
| | | 576 | | } |
| | | 577 | | |
| | | 578 | | /// <summary> |
| | | 579 | | /// Writes the person's row without changing it, after a factor reservation was refused. |
| | | 580 | | /// </summary> |
| | | 581 | | /// <remarks> |
| | | 582 | | /// A refused reservation's <c>UPDATE</c> matches no row, so PostgreSQL assigns it no transaction |
| | | 583 | | /// and flushes no commit, and it answers measurably sooner than an admitted one. That would |
| | | 584 | | /// tell a caller the second factor is locked, or re-authentication paused, without a word of |
| | | 585 | | /// the answer differing (FR-AU-12, FR-AU-13). Setting a column to itself writes a new row |
| | | 586 | | /// version and commits like the admitted write does; what remains is one more round trip. |
| | | 587 | | /// </remarks> |
| | | 588 | | private Task TouchAsync(Person person) => |
| | 14 | 589 | | context.Persons |
| | 14 | 590 | | .Where(x => x.Id == person.Id) |
| | 28 | 591 | | .ExecuteUpdateAsync(set => set.SetProperty(x => x.FailedSecondFactorAttempts, x => x.FailedSecondFactorAttem |
| | | 592 | | |
| | | 593 | | /// <summary> |
| | | 594 | | /// The value <see cref="TryReserveSecondFactorAttemptAsync" /> writes to the lock: unchanged, |
| | | 595 | | /// unless this reservation reaches <paramref name="maxAttempts" />, and then the entry of |
| | | 596 | | /// <paramref name="lockedOutUntil" /> the stored lockout count selects — a <c>CASE</c> over the |
| | | 597 | | /// count, with the last entry for every count from its own on. |
| | | 598 | | /// </summary> |
| | | 599 | | /// <remarks> |
| | | 600 | | /// Built as an expression tree because the number of entries is the caller's. Each end is read |
| | | 601 | | /// from a box rather than inlined, so EF Core sends it as a parameter, and the statement — and |
| | | 602 | | /// its cached plan — is the same on every call. |
| | | 603 | | /// </remarks> |
| | | 604 | | private static Expression<Func<Person, DateTime?>> SecondFactorLockEnd( |
| | | 605 | | int maxAttempts, IReadOnlyList<DateTime> lockedOutUntil) |
| | | 606 | | { |
| | 51 | 607 | | var row = Expression.Parameter(typeof(Person), "x"); |
| | 51 | 608 | | var lockouts = Expression.Property(row, nameof(Person.SecondFactorLockouts)); |
| | | 609 | | |
| | 51 | 610 | | Expression end = Boxed(lockedOutUntil[^1]); |
| | | 611 | | |
| | 816 | 612 | | for (var lockout = lockedOutUntil.Count - 2; lockout >= 0; lockout--) |
| | | 613 | | { |
| | 357 | 614 | | end = Expression.Condition( |
| | 357 | 615 | | Expression.Equal(lockouts, Expression.Constant(lockout)), Boxed(lockedOutUntil[lockout]), end); |
| | | 616 | | } |
| | | 617 | | |
| | 51 | 618 | | var reachesLimit = Expression.GreaterThanOrEqual( |
| | 51 | 619 | | Expression.Add(Expression.Property(row, nameof(Person.FailedSecondFactorAttempts)), Expression.Constant(1)), |
| | 51 | 620 | | Boxed(maxAttempts)); |
| | | 621 | | |
| | 51 | 622 | | return Expression.Lambda<Func<Person, DateTime?>>( |
| | 51 | 623 | | Expression.Condition(reachesLimit, end, Expression.Property(row, nameof(Person.SecondFactorLockedOutUntil))) |
| | 51 | 624 | | row); |
| | | 625 | | } |
| | | 626 | | |
| | | 627 | | /// <summary>The lock end <see cref="SecondFactorLockEnd" /> selects, for the instance.</summary> |
| | | 628 | | private static DateTime LockEndAfter(int lockouts, IReadOnlyList<DateTime> lockedOutUntil) => |
| | 4 | 629 | | lockouts >= 0 && lockouts < lockedOutUntil.Count - 1 ? lockedOutUntil[lockouts] : lockedOutUntil[^1]; |
| | | 630 | | |
| | | 631 | | private static MemberExpression Boxed(DateTime value) => |
| | 408 | 632 | | Expression.Field(Expression.Constant(new StrongBox<DateTime?>(value)), nameof(StrongBox<DateTime?>.Value)); |
| | | 633 | | |
| | | 634 | | private static MemberExpression Boxed(int value) => |
| | 51 | 635 | | Expression.Field(Expression.Constant(new StrongBox<int>(value)), nameof(StrongBox<int>.Value)); |
| | | 636 | | |
| | | 637 | | /// <summary> |
| | | 638 | | /// Brings the caller's instance in line with a write the change tracker did not see: the new |
| | | 639 | | /// value becomes both current and original, so the property is not saved again later. |
| | | 640 | | /// </summary> |
| | | 641 | | private void Accept<T, TProperty>(T entity, Expression<Func<T, TProperty>> property, TProperty value) |
| | | 642 | | where T : class |
| | | 643 | | { |
| | 1357 | 644 | | var entry = context.Entry(entity); |
| | 1357 | 645 | | var member = entry.Property(property); |
| | | 646 | | |
| | 1357 | 647 | | member.CurrentValue = value; |
| | | 648 | | |
| | 1357 | 649 | | if (entry.State is EntityState.Unchanged or EntityState.Modified) |
| | | 650 | | { |
| | 1357 | 651 | | member.OriginalValue = value; |
| | 1357 | 652 | | member.IsModified = false; |
| | | 653 | | } |
| | 1357 | 654 | | } |
| | | 655 | | } |