| | | 1 | | using ArturRios.Heimdall.Command.Services; |
| | | 2 | | using ArturRios.Heimdall.Shared.Messages; |
| | | 3 | | using ArturRios.Mediator.Command; |
| | | 4 | | using ArturRios.Mediator.Command.Interfaces; |
| | | 5 | | using ArturRios.Output; |
| | | 6 | | using Microsoft.Extensions.Logging; |
| | | 7 | | |
| | | 8 | | namespace ArturRios.Heimdall.Command.Auditing; |
| | | 9 | | |
| | | 10 | | /// <summary> |
| | | 11 | | /// Wraps a command handler so every attempted write produces one audit trail entry (NFR-09), |
| | | 12 | | /// without changing the wrapped handler — including one that throws instead of answering, which is |
| | | 13 | | /// recorded as a refusal and rethrown — plus one more for each side effect a successful |
| | | 14 | | /// command's output reports through <see cref="IAuditedSideEffects" />. Registered per-handler by |
| | | 15 | | /// <see cref="CommandHandlerRegistrationExtensions.AddAuditedCommandHandler{TCommand,TOutput,THandler}" />. |
| | | 16 | | /// </summary> |
| | 1042 | 17 | | public class AuditingCommandHandler<TCommand, TOutput>( |
| | 1042 | 18 | | ICommandHandlerAsync<TCommand, TOutput> inner, |
| | 1042 | 19 | | IAuditLogWriter auditLogWriter, |
| | 1042 | 20 | | ILogger<AuditingCommandHandler<TCommand, TOutput>> logger) |
| | | 21 | | : ICommandHandlerAsync<TCommand, TOutput> |
| | | 22 | | where TCommand : BaseCommand |
| | | 23 | | where TOutput : CommandOutput |
| | | 24 | | { |
| | | 25 | | public async Task<DataOutput<TOutput?>> HandleAsync(TCommand command, CancellationToken cancellationToken = default) |
| | | 26 | | { |
| | 1042 | 27 | | var action = typeof(TCommand).Name; |
| | | 28 | | |
| | | 29 | | DataOutput<TOutput?> result; |
| | | 30 | | |
| | | 31 | | try |
| | | 32 | | { |
| | 1042 | 33 | | result = await inner.HandleAsync(command, cancellationToken); |
| | 1033 | 34 | | } |
| | 9 | 35 | | catch (Exception exception) |
| | | 36 | | { |
| | | 37 | | // An attempt that threw is still an attempt (NFR-09). The hash gate's refusal is the one |
| | | 38 | | // that matters most: PasswordHashSaturationFilter turns it into a 503 outside this |
| | | 39 | | // decorator, so without an entry here a shed login leaves nothing and the |
| | | 40 | | // CREDENTIAL_VERIFICATION_SHEDDING signal, which counts entries with that reason, never |
| | | 41 | | // fires. Any other exception records one fixed reason — its own message can carry |
| | | 42 | | // provider text or caller input — and is rethrown unchanged for whatever handles it. |
| | 9 | 43 | | await TryWriteAsync( |
| | 9 | 44 | | action, null, false, |
| | 9 | 45 | | exception is PasswordHashGateSaturatedException |
| | 9 | 46 | | ? AuthMessages.AuthenticationTemporarilyUnavailable |
| | 9 | 47 | | : AuditMessages.CommandFailed); |
| | | 48 | | |
| | 9 | 49 | | throw; |
| | | 50 | | } |
| | | 51 | | |
| | 1033 | 52 | | var targetId = ResolveTargetId(result.Data); |
| | | 53 | | |
| | | 54 | | // Refusals are recorded too, and they are usually the entries worth having: a caller |
| | | 55 | | // repeatedly denied a scope they do not own, or repeatedly failing a password, leaves no |
| | | 56 | | // other trace anywhere. Only the first error is kept — enough to say why, and all of them |
| | | 57 | | // are the application's own canonical messages, so nothing a caller submitted is written |
| | | 58 | | // here. |
| | 1033 | 59 | | await TryWriteAsync( |
| | 1033 | 60 | | action, targetId, result.Success, result.Success ? null : result.Errors.FirstOrDefault()); |
| | | 61 | | |
| | | 62 | | // A side effect only happened if the command did, so a refusal records none. |
| | 1033 | 63 | | if (result.Success && result.Data is IAuditedSideEffects sideEffects) |
| | | 64 | | { |
| | 36 | 65 | | foreach (var sideEffect in sideEffects.AuditedSideEffects()) |
| | | 66 | | { |
| | 6 | 67 | | await TryWriteAsync(sideEffect, targetId, true, null); |
| | | 68 | | } |
| | | 69 | | } |
| | | 70 | | |
| | 1033 | 71 | | return result; |
| | 1033 | 72 | | } |
| | | 73 | | |
| | | 74 | | private async Task TryWriteAsync(string action, Guid? targetId, bool succeeded, string? failureReason) |
| | | 75 | | { |
| | | 76 | | try |
| | | 77 | | { |
| | 1048 | 78 | | await auditLogWriter.WriteAsync(action, targetId, succeeded, failureReason); |
| | 1039 | 79 | | } |
| | 9 | 80 | | catch (Exception exception) |
| | | 81 | | { |
| | | 82 | | // The trail is a record of what the API did, not part of doing it: a caller whose |
| | | 83 | | // request succeeded is not told it failed because the entry could not be written. |
| | 9 | 84 | | logger.LogWarning( |
| | 9 | 85 | | exception, "Failed to write audit log entry for {Action} (target {TargetId})", |
| | 9 | 86 | | action, targetId); |
| | 9 | 87 | | } |
| | 1048 | 88 | | } |
| | | 89 | | |
| | | 90 | | private static Guid? ResolveTargetId(TOutput? output) |
| | | 91 | | { |
| | 1033 | 92 | | if (output is null) |
| | | 93 | | { |
| | 559 | 94 | | return null; |
| | | 95 | | } |
| | | 96 | | |
| | 474 | 97 | | var property = typeof(TOutput).GetProperty("Id") ?? typeof(TOutput).GetProperty("PublicId"); |
| | | 98 | | |
| | 474 | 99 | | return property is not null && property.PropertyType == typeof(Guid) |
| | 474 | 100 | | ? (Guid?)property.GetValue(output) |
| | 474 | 101 | | : null; |
| | | 102 | | } |
| | | 103 | | } |