| | | 1 | | using ArturRios.Data.Relational.Core.Entities; |
| | | 2 | | using ArturRios.Data.Relational.Core.Interfaces; |
| | | 3 | | using ArturRios.Heimdall.Command.Input; |
| | | 4 | | using ArturRios.Heimdall.Command.Output; |
| | | 5 | | using ArturRios.Heimdall.Domain.Entities; |
| | | 6 | | using ArturRios.Heimdall.Shared.Messages; |
| | | 7 | | using ArturRios.Heimdall.Shared.Retention; |
| | | 8 | | using ArturRios.Mediator.Command.Interfaces; |
| | | 9 | | using ArturRios.Output; |
| | | 10 | | using Microsoft.EntityFrameworkCore; |
| | | 11 | | |
| | | 12 | | namespace ArturRios.Heimdall.Command.Handlers; |
| | | 13 | | |
| | | 14 | | /// <summary> |
| | | 15 | | /// Handles <see cref="PurgeExpiredTokensCommand" /> (NFR-19): removes password reset tokens, |
| | | 16 | | /// email verification tokens, two-factor email codes, unconfirmed pending registrations (UC-47), |
| | | 17 | | /// spent application credentials (UC-55) and ended registration-attempt notice budgets (FR-SR-14) |
| | | 18 | | /// whose retention period has run out. All failures |
| | | 19 | | /// are returned as errors on the <see cref="DataOutput{T}" /> rather than thrown. |
| | | 20 | | /// </summary> |
| | | 21 | | /// <remarks> |
| | | 22 | | /// <para> |
| | | 23 | | /// <b>What makes a row purgeable.</b> The four token and registration tables purge on |
| | | 24 | | /// expiry: <c>ExpiresAt <= now - grace</c>. It covers a used row and an expired-unused |
| | | 25 | | /// row alike, and it is the only condition that can be applied to all four: neither |
| | | 26 | | /// <see cref="PasswordResetToken" /> nor <see cref="EmailVerificationToken" /> records when |
| | | 27 | | /// it was consumed, and only <see cref="TwoFactorEmailCode" /> carries a <c>CreatedAt</c>. |
| | | 28 | | /// Expiry is a sound proxy in any case — each of these is issued with a lifetime measured |
| | | 29 | | /// in minutes or hours, so a row's expiry is never far from its issue. A |
| | | 30 | | /// <see cref="PendingRegistration" /> is held for the same grace period, so that following |
| | | 31 | | /// a stale confirmation link answers "expired" rather than "invalid" for as long as it does |
| | | 32 | | /// for the tokens. |
| | | 33 | | /// </para> |
| | | 34 | | /// <para> |
| | | 35 | | /// An <see cref="ApplicationCredential" /> purges on a condition of its own: revoked or |
| | | 36 | | /// expired at or before <c>now - grace</c>, whichever came first. Expiry alone would not |
| | | 37 | | /// do — a credential may have none, and would then be kept for ever once revoked. |
| | | 38 | | /// </para> |
| | | 39 | | /// <para> |
| | | 40 | | /// An <see cref="AttemptNoticeBudget" /> purges once its window ended at or before the |
| | | 41 | | /// cutoff. An ended window counts nothing — the next notice starts a new one — so the row is |
| | | 42 | | /// only a digest of an address waiting to be removed, and the grace keeps it no longer than a |
| | | 43 | | /// token is kept. |
| | | 44 | | /// </para> |
| | | 45 | | /// <para> |
| | | 46 | | /// <b>Why a live token is never at risk.</b> The cutoff is strictly in the past, so a token |
| | | 47 | | /// that has not yet expired cannot match however the grace period is configured — the |
| | | 48 | | /// options type refuses a zero or negative one. A person mid-recovery is never affected by |
| | | 49 | | /// a run. |
| | | 50 | | /// </para> |
| | | 51 | | /// <para> |
| | | 52 | | /// <b>Running on more than one instance.</b> NFR-06 requires that no instance assume it is |
| | | 53 | | /// alone, and two purges may overlap. Nothing is claimed or locked: each run selects a |
| | | 54 | | /// batch, and <c>DeleteRangeAsync</c> re-reads those ids and removes what still exists, so |
| | | 55 | | /// an instance whose rows another already deleted simply removes fewer than it selected and |
| | | 56 | | /// reports the true count. That is the whole of the coordination, and it is enough because |
| | | 57 | | /// deleting an already-deleted row is the one concurrent outcome this pass can have. |
| | | 58 | | /// </para> |
| | | 59 | | /// </remarks> |
| | 13 | 60 | | public class PurgeExpiredTokensCommandHandler( |
| | 13 | 61 | | IAsyncReadOnlyRepository<PasswordResetToken, long> passwordResetTokenReader, |
| | 13 | 62 | | IAsyncRepository<PasswordResetToken, long> passwordResetTokenWriter, |
| | 13 | 63 | | IAsyncReadOnlyRepository<EmailVerificationToken, long> emailVerificationTokenReader, |
| | 13 | 64 | | IAsyncRepository<EmailVerificationToken, long> emailVerificationTokenWriter, |
| | 13 | 65 | | IAsyncReadOnlyRepository<TwoFactorEmailCode, long> twoFactorEmailCodeReader, |
| | 13 | 66 | | IAsyncRepository<TwoFactorEmailCode, long> twoFactorEmailCodeWriter, |
| | 13 | 67 | | IAsyncReadOnlyRepository<PendingRegistration, long> pendingRegistrationReader, |
| | 13 | 68 | | IAsyncRepository<PendingRegistration, long> pendingRegistrationWriter, |
| | 13 | 69 | | IAsyncReadOnlyRepository<ApplicationCredential, long> applicationCredentialReader, |
| | 13 | 70 | | IAsyncRepository<ApplicationCredential, long> applicationCredentialWriter, |
| | 13 | 71 | | IAsyncReadOnlyRepository<AttemptNoticeBudget, long> attemptNoticeBudgetReader, |
| | 13 | 72 | | IAsyncRepository<AttemptNoticeBudget, long> attemptNoticeBudgetWriter, |
| | 13 | 73 | | DataRetentionOptions retention) |
| | | 74 | | : ICommandHandlerAsync<PurgeExpiredTokensCommand, PurgeExpiredTokensCommandOutput> |
| | | 75 | | { |
| | | 76 | | public async Task<DataOutput<PurgeExpiredTokensCommandOutput?>> HandleAsync(PurgeExpiredTokensCommand command, Cance |
| | | 77 | | { |
| | 15 | 78 | | var output = DataOutput<PurgeExpiredTokensCommandOutput?>.New; |
| | 15 | 79 | | var cutoff = DateTime.UtcNow - retention.SingleUseTokenGrace; |
| | | 80 | | |
| | | 81 | | // Oldest first, so a backlog drains in the order it accumulated and no row can be starved by |
| | | 82 | | // fresher ones arriving ahead of it. |
| | 15 | 83 | | var passwordResetTokens = await PurgeAsync( |
| | 15 | 84 | | passwordResetTokenReader.Query() |
| | 15 | 85 | | .Where(token => token.ExpiresAt <= cutoff) |
| | 15 | 86 | | .OrderBy(token => token.ExpiresAt), |
| | 15 | 87 | | passwordResetTokenWriter); |
| | | 88 | | |
| | 15 | 89 | | var emailVerificationTokens = await PurgeAsync( |
| | 15 | 90 | | emailVerificationTokenReader.Query() |
| | 15 | 91 | | .Where(token => token.ExpiresAt <= cutoff) |
| | 15 | 92 | | .OrderBy(token => token.ExpiresAt), |
| | 15 | 93 | | emailVerificationTokenWriter); |
| | | 94 | | |
| | 15 | 95 | | var twoFactorEmailCodes = await PurgeAsync( |
| | 15 | 96 | | twoFactorEmailCodeReader.Query() |
| | 15 | 97 | | .Where(code => code.ExpiresAt <= cutoff) |
| | 15 | 98 | | .OrderBy(code => code.ExpiresAt), |
| | 15 | 99 | | twoFactorEmailCodeWriter); |
| | | 100 | | |
| | 15 | 101 | | var pendingRegistrations = await PurgeAsync( |
| | 15 | 102 | | pendingRegistrationReader.Query() |
| | 15 | 103 | | .Where(registration => registration.ExpiresAt <= cutoff) |
| | 15 | 104 | | .OrderBy(registration => registration.ExpiresAt), |
| | 15 | 105 | | pendingRegistrationWriter); |
| | | 106 | | |
| | | 107 | | // UC-55: a revoked or expired credential can never be accepted again, so after the same |
| | | 108 | | // grace as the single-use tokens it is removed — revoked or expired, whichever came first. |
| | 15 | 109 | | var applicationCredentials = await PurgeAsync( |
| | 15 | 110 | | applicationCredentialReader.Query() |
| | 15 | 111 | | .Where(credential => (credential.RevokedAt != null && credential.RevokedAt <= cutoff) || |
| | 15 | 112 | | (credential.ExpiresAt != null && credential.ExpiresAt <= cutoff)) |
| | 15 | 113 | | .OrderBy(credential => credential.RevokedAt ?? credential.ExpiresAt), |
| | 15 | 114 | | applicationCredentialWriter); |
| | | 115 | | |
| | | 116 | | // FR-SR-14: a notice budget whose window has ended counts nothing any more. |
| | 15 | 117 | | var attemptNoticeBudgets = await PurgeAsync( |
| | 15 | 118 | | attemptNoticeBudgetReader.Query() |
| | 15 | 119 | | .Where(budget => budget.WindowEndsAt <= cutoff) |
| | 15 | 120 | | .OrderBy(budget => budget.WindowEndsAt), |
| | 15 | 121 | | attemptNoticeBudgetWriter); |
| | | 122 | | |
| | | 123 | | // Every table is attempted before the run reports, so one failing table does not hide |
| | | 124 | | // whether the others were cleared — and the next run retries whatever was missed. |
| | 15 | 125 | | var errors = passwordResetTokens.Errors |
| | 15 | 126 | | .Concat(emailVerificationTokens.Errors) |
| | 15 | 127 | | .Concat(twoFactorEmailCodes.Errors) |
| | 15 | 128 | | .Concat(pendingRegistrations.Errors) |
| | 15 | 129 | | .Concat(applicationCredentials.Errors) |
| | 15 | 130 | | .Concat(attemptNoticeBudgets.Errors) |
| | 15 | 131 | | .ToList(); |
| | | 132 | | |
| | 15 | 133 | | if (errors.Count > 0) |
| | | 134 | | { |
| | 0 | 135 | | return output.WithErrors(errors); |
| | | 136 | | } |
| | | 137 | | |
| | | 138 | | // A run that removed nothing is a success: most runs find nothing to do, and a failed |
| | | 139 | | // outcome would fill the audit trail with refusals that never happened. |
| | 15 | 140 | | return output |
| | 15 | 141 | | .WithData(new PurgeExpiredTokensCommandOutput |
| | 15 | 142 | | { |
| | 15 | 143 | | PasswordResetTokensPurged = passwordResetTokens.Count, |
| | 15 | 144 | | EmailVerificationTokensPurged = emailVerificationTokens.Count, |
| | 15 | 145 | | TwoFactorEmailCodesPurged = twoFactorEmailCodes.Count, |
| | 15 | 146 | | PendingRegistrationsPurged = pendingRegistrations.Count, |
| | 15 | 147 | | ApplicationCredentialsPurged = applicationCredentials.Count, |
| | 15 | 148 | | AttemptNoticeBudgetsPurged = attemptNoticeBudgets.Count |
| | 15 | 149 | | }) |
| | 15 | 150 | | .WithMessage(RetentionMessages.ExpiredTokensPurged); |
| | 15 | 151 | | } |
| | | 152 | | |
| | | 153 | | /// <summary> |
| | | 154 | | /// Removes at most <c>PurgeBatchSize</c> of the candidates and reports how many rows were |
| | | 155 | | /// actually removed, or the persistence errors if the delete failed. |
| | | 156 | | /// </summary> |
| | | 157 | | private async Task<(int Count, IEnumerable<string> Errors)> PurgeAsync<T>( |
| | | 158 | | IQueryable<T> candidates, |
| | | 159 | | IAsyncRepository<T, long> writer) where T : Entity<long> |
| | | 160 | | { |
| | 90 | 161 | | var ids = await candidates |
| | 90 | 162 | | .Take(retention.PurgeBatchSize) |
| | 90 | 163 | | .Select(entity => entity.Id) |
| | 90 | 164 | | .ToListAsync(); |
| | | 165 | | |
| | 90 | 166 | | if (ids.Count == 0) |
| | | 167 | | { |
| | 75 | 168 | | return (0, []); |
| | | 169 | | } |
| | | 170 | | |
| | 15 | 171 | | var deletion = await writer.DeleteRangeAsync(ids); |
| | | 172 | | |
| | | 173 | | // The count comes from what the delete reported removing, not from what was selected: they |
| | | 174 | | // differ when another instance got there first, and the trail should record what this run |
| | | 175 | | // did rather than what it intended. |
| | 15 | 176 | | return deletion.Success |
| | 15 | 177 | | ? (deletion.Data?.Count() ?? 0, []) |
| | 15 | 178 | | : (0, deletion.Errors); |
| | 90 | 179 | | } |
| | | 180 | | } |