| | | 1 | | using System.Buffers.Text; |
| | | 2 | | using System.Globalization; |
| | | 3 | | using System.Text; |
| | | 4 | | using RoleRadar.Application.Abstractions; |
| | | 5 | | using RoleRadar.Domain.Common; |
| | | 6 | | |
| | | 7 | | namespace RoleRadar.Application.Audit.Queries; |
| | | 8 | | |
| | | 9 | | /// <summary>Lists one owner's audit entries, newest first (feature 013, FR-020). Read-only: it writes nothing.</summary |
| | 226 | 10 | | public sealed record ListAuditEntriesQuery( |
| | 382 | 11 | | OwnerId OwnerId, |
| | 430 | 12 | | string? EntityType = null, |
| | 406 | 13 | | string? EntityId = null, |
| | 380 | 14 | | string? Actor = null, |
| | 348 | 15 | | DateTimeOffset? FromUtc = null, |
| | 144 | 16 | | DateTimeOffset? ToUtc = null, |
| | 622 | 17 | | int Limit = ListAuditEntriesQuery.DefaultLimit, |
| | 396 | 18 | | string? Cursor = null, |
| | 336 | 19 | | bool IncludeChangedFields = false) : IQuery<AuditListPage> |
| | | 20 | | { |
| | | 21 | | public const int DefaultLimit = 25; |
| | | 22 | | public const int MaxLimit = 100; |
| | | 23 | | public const int MaxEntityIdLength = 128; |
| | | 24 | | public const int MaxActorLength = 256; |
| | | 25 | | } |
| | | 26 | | |
| | | 27 | | /// <summary> |
| | | 28 | | /// One audit entry as the listing shows it. There is deliberately no member for appended text, before or after values o |
| | | 29 | | /// content summaries, so none of them can be carried, whatever the store returns. |
| | | 30 | | /// </summary> |
| | | 31 | | public sealed record AuditListItem( |
| | | 32 | | DateTime OccurredAtUtc, |
| | | 33 | | string EntityType, |
| | | 34 | | string EntityId, |
| | | 35 | | string Operation, |
| | | 36 | | string Actor, |
| | | 37 | | string? RequestCorrelationId, |
| | | 38 | | IReadOnlyList<string>? ChangedFields); |
| | | 39 | | |
| | | 40 | | /// <summary>One page of the listing. <see cref="NextCursor"/> is null on the last page.</summary> |
| | | 41 | | public sealed record AuditListPage(IReadOnlyList<AuditListItem> Items, string? NextCursor); |
| | | 42 | | |
| | | 43 | | /// <summary>The entity types that tracking and note writes put in <c>audit_log.entity_type</c>.</summary> |
| | | 44 | | public static class AuditEntityTypes |
| | | 45 | | { |
| | | 46 | | private static readonly string[] KnownTypes = |
| | | 47 | | ["note", "company", "posting", "application", "application_event", "contact", "criterion", "search_run"]; |
| | | 48 | | |
| | | 49 | | public static IReadOnlyList<string> Known => KnownTypes; |
| | | 50 | | |
| | | 51 | | public static bool IsKnown(string? entityType) => |
| | | 52 | | entityType is not null && Array.Exists(KnownTypes, known => string.Equals(known, entityType, StringComparison.Or |
| | | 53 | | } |
| | | 54 | | |
| | | 55 | | /// <summary> |
| | | 56 | | /// The opaque paging token: the (occurred_at, _id) of the last entry on a page. Keyset paging on that pair stays stable |
| | | 57 | | /// when entries are appended between pages. The token is URL-safe base64 of <c>v1:{unix milliseconds}:{id}</c>. |
| | | 58 | | /// </summary> |
| | | 59 | | public static class AuditCursorCodec |
| | | 60 | | { |
| | | 61 | | private const string Prefix = "v1:"; |
| | | 62 | | private const long MinUnixMilliseconds = -62135596800000; |
| | | 63 | | private const long MaxUnixMilliseconds = 253402300799999; |
| | | 64 | | |
| | | 65 | | public static string Encode(DateTime occurredAtUtc, Guid id) |
| | | 66 | | { |
| | | 67 | | var utc = occurredAtUtc.Kind == DateTimeKind.Utc ? occurredAtUtc : DateTime.SpecifyKind(occurredAtUtc, DateTimeK |
| | | 68 | | var millis = new DateTimeOffset(utc).ToUnixTimeMilliseconds(); |
| | | 69 | | var payload = string.Create(CultureInfo.InvariantCulture, $"{Prefix}{millis}:{id:N}"); |
| | | 70 | | return Base64Url.EncodeToString(Encoding.UTF8.GetBytes(payload)); |
| | | 71 | | } |
| | | 72 | | |
| | | 73 | | public static bool TryDecode(string? cursor, out DateTime occurredAtUtc, out Guid id) |
| | | 74 | | { |
| | | 75 | | occurredAtUtc = default; |
| | | 76 | | id = default; |
| | | 77 | | if (string.IsNullOrWhiteSpace(cursor)) |
| | | 78 | | { |
| | | 79 | | return false; |
| | | 80 | | } |
| | | 81 | | |
| | | 82 | | string payload; |
| | | 83 | | try |
| | | 84 | | { |
| | | 85 | | payload = Encoding.UTF8.GetString(Base64Url.DecodeFromChars(cursor)); |
| | | 86 | | } |
| | | 87 | | catch (FormatException) |
| | | 88 | | { |
| | | 89 | | return false; |
| | | 90 | | } |
| | | 91 | | |
| | | 92 | | if (!payload.StartsWith(Prefix, StringComparison.Ordinal)) |
| | | 93 | | { |
| | | 94 | | return false; |
| | | 95 | | } |
| | | 96 | | |
| | | 97 | | var parts = payload[Prefix.Length..].Split(':'); |
| | | 98 | | if (parts.Length != 2 |
| | | 99 | | || !long.TryParse(parts[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var millis) |
| | | 100 | | || millis is < MinUnixMilliseconds or > MaxUnixMilliseconds |
| | | 101 | | || !Guid.TryParseExact(parts[1], "N", out var parsedId) |
| | | 102 | | || parsedId == Guid.Empty) |
| | | 103 | | { |
| | | 104 | | return false; |
| | | 105 | | } |
| | | 106 | | |
| | | 107 | | occurredAtUtc = DateTimeOffset.FromUnixTimeMilliseconds(millis).UtcDateTime; |
| | | 108 | | id = parsedId; |
| | | 109 | | return true; |
| | | 110 | | } |
| | | 111 | | } |
| | | 112 | | |
| | | 113 | | /// <summary>The validation rules of data-model.md "ListAuditEntriesQuery". A failure is a result, never an exception.</ |
| | | 114 | | public static class ListAuditEntriesQueryValidator |
| | | 115 | | { |
| | | 116 | | public static ResultError? Validate(ListAuditEntriesQuery query) |
| | | 117 | | { |
| | | 118 | | ArgumentNullException.ThrowIfNull(query); |
| | | 119 | | |
| | | 120 | | if (string.IsNullOrWhiteSpace(query.OwnerId.Value)) |
| | | 121 | | { |
| | | 122 | | return Invalid("An owner is required."); |
| | | 123 | | } |
| | | 124 | | |
| | | 125 | | if (query.Limit is < 1 or > ListAuditEntriesQuery.MaxLimit) |
| | | 126 | | { |
| | | 127 | | return Invalid($"Limit must be between 1 and {ListAuditEntriesQuery.MaxLimit}."); |
| | | 128 | | } |
| | | 129 | | |
| | | 130 | | if (query.EntityType is not null && !AuditEntityTypes.IsKnown(query.EntityType)) |
| | | 131 | | { |
| | | 132 | | return Invalid($"Entity type must be one of: {string.Join(", ", AuditEntityTypes.Known)}."); |
| | | 133 | | } |
| | | 134 | | |
| | | 135 | | if (query.EntityId is not null |
| | | 136 | | && (string.IsNullOrWhiteSpace(query.EntityId) || query.EntityId.Length > ListAuditEntriesQuery.MaxEntityIdLe |
| | | 137 | | { |
| | | 138 | | return Invalid($"Entity id must be 1 to {ListAuditEntriesQuery.MaxEntityIdLength} characters."); |
| | | 139 | | } |
| | | 140 | | |
| | | 141 | | if (query.Actor is not null |
| | | 142 | | && (string.IsNullOrWhiteSpace(query.Actor) || query.Actor.Length > ListAuditEntriesQuery.MaxActorLength)) |
| | | 143 | | { |
| | | 144 | | return Invalid($"Actor must be 1 to {ListAuditEntriesQuery.MaxActorLength} characters."); |
| | | 145 | | } |
| | | 146 | | |
| | | 147 | | if (query.FromUtc is { } from && query.ToUtc is { } to && from >= to) |
| | | 148 | | { |
| | | 149 | | return Invalid("From must be earlier than to."); |
| | | 150 | | } |
| | | 151 | | |
| | | 152 | | if (query.Cursor is not null && !AuditCursorCodec.TryDecode(query.Cursor, out _, out _)) |
| | | 153 | | { |
| | | 154 | | return Invalid("Cursor is not a valid paging token."); |
| | | 155 | | } |
| | | 156 | | |
| | | 157 | | return null; |
| | | 158 | | } |
| | | 159 | | |
| | | 160 | | private static ResultError Invalid(string message) => new(ErrorCode.ValidationError, message); |
| | | 161 | | } |
| | | 162 | | |
| | | 163 | | /// <summary> |
| | | 164 | | /// Read-only handler for <c>roleradar audit list</c> (ADR 0041). It validates, then asks <see cref="IAuditLogReader"/>. |
| | | 165 | | /// It is a query, so the transaction and audit decorator does not wrap it: it writes nothing. |
| | | 166 | | /// </summary> |
| | | 167 | | public sealed class ListAuditEntriesQueryHandler(IAuditLogReader reader) : IQueryHandler<ListAuditEntriesQuery, AuditLis |
| | | 168 | | { |
| | | 169 | | private readonly IAuditLogReader _reader = reader ?? throw new ArgumentNullException(nameof(reader)); |
| | | 170 | | |
| | | 171 | | public async Task<Result<AuditListPage>> HandleAsync(ListAuditEntriesQuery query, CancellationToken cancellationToke |
| | | 172 | | { |
| | | 173 | | ArgumentNullException.ThrowIfNull(query); |
| | | 174 | | |
| | | 175 | | var invalid = ListAuditEntriesQueryValidator.Validate(query); |
| | | 176 | | if (invalid is not null) |
| | | 177 | | { |
| | | 178 | | return Result<AuditListPage>.Failure(invalid.Value); |
| | | 179 | | } |
| | | 180 | | |
| | | 181 | | return await _reader.ListAsync(query, cancellationToken); |
| | | 182 | | } |
| | | 183 | | } |