< Summary

Information
Class: RoleRadar.Application.Audit.Queries.ListAuditEntriesQueryValidator
Assembly: RoleRadar.Application
File(s): /home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Audit/Queries/ListAuditEntriesQuery.cs
Line coverage
100%
Covered lines: 19
Uncovered lines: 0
Coverable lines: 19
Total lines: 183
Line coverage: 100%
Branch coverage
100%
Covered branches: 34
Total branches: 34
Branch coverage: 100%
Method coverage

Feature is only available for sponsors

Upgrade to PRO version

Metrics

MethodBranch coverage Crap Score Cyclomatic complexity Line coverage
Validate(...)100%3434100%
Invalid(...)100%11100%

File(s)

/home/runner/work/roleradar/roleradar/src/RoleRadar.Application/Audit/Queries/ListAuditEntriesQuery.cs

#LineLine coverage
 1using System.Buffers.Text;
 2using System.Globalization;
 3using System.Text;
 4using RoleRadar.Application.Abstractions;
 5using RoleRadar.Domain.Common;
 6
 7namespace 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
 10public sealed record ListAuditEntriesQuery(
 11    OwnerId OwnerId,
 12    string? EntityType = null,
 13    string? EntityId = null,
 14    string? Actor = null,
 15    DateTimeOffset? FromUtc = null,
 16    DateTimeOffset? ToUtc = null,
 17    int Limit = ListAuditEntriesQuery.DefaultLimit,
 18    string? Cursor = null,
 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>
 31public 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>
 41public 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>
 44public 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>
 59public 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.</
 114public static class ListAuditEntriesQueryValidator
 115{
 116    public static ResultError? Validate(ListAuditEntriesQuery query)
 117    {
 278118        ArgumentNullException.ThrowIfNull(query);
 119
 278120        if (string.IsNullOrWhiteSpace(query.OwnerId.Value))
 121        {
 4122            return Invalid("An owner is required.");
 123        }
 124
 274125        if (query.Limit is < 1 or > ListAuditEntriesQuery.MaxLimit)
 126        {
 20127            return Invalid($"Limit must be between 1 and {ListAuditEntriesQuery.MaxLimit}.");
 128        }
 129
 254130        if (query.EntityType is not null && !AuditEntityTypes.IsKnown(query.EntityType))
 131        {
 14132            return Invalid($"Entity type must be one of: {string.Join(", ", AuditEntityTypes.Known)}.");
 133        }
 134
 240135        if (query.EntityId is not null
 240136            && (string.IsNullOrWhiteSpace(query.EntityId) || query.EntityId.Length > ListAuditEntriesQuery.MaxEntityIdLe
 137        {
 6138            return Invalid($"Entity id must be 1 to {ListAuditEntriesQuery.MaxEntityIdLength} characters.");
 139        }
 140
 234141        if (query.Actor is not null
 234142            && (string.IsNullOrWhiteSpace(query.Actor) || query.Actor.Length > ListAuditEntriesQuery.MaxActorLength))
 143        {
 4144            return Invalid($"Actor must be 1 to {ListAuditEntriesQuery.MaxActorLength} characters.");
 145        }
 146
 230147        if (query.FromUtc is { } from && query.ToUtc is { } to && from >= to)
 148        {
 12149            return Invalid("From must be earlier than to.");
 150        }
 151
 218152        if (query.Cursor is not null && !AuditCursorCodec.TryDecode(query.Cursor, out _, out _))
 153        {
 16154            return Invalid("Cursor is not a valid paging token.");
 155        }
 156
 202157        return null;
 158    }
 159
 76160    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>
 167public 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}