Download the audit log as a CSV file

C# · ASP.NET Core · intermediate · modification

Adds the audit log download for workspace admins. `AuditLogEndpoints.cs` maps `GET /export` in the existing admin-only group: it parses and checks `from` and `to`, turns them into a half-open UTC range and returns a streamed CSV download. `AuditLogExport.cs` (new) writes the file in batches of 1,000 rows with keyset pagination on (`CreatedAt`, `Id`), flushing after each batch, so memory stays flat however long the range is. `AuditLogCsv.cs` (new) builds the header and the rows: RFC 4180 quoting plus an apostrophe in front of text that a spreadsheet would run as a formula. `AuditLogExportTests.cs` (new) covers the escaping, the workspace and date range, events that share a timestamp across a batch boundary, the response headers, the rejected ranges and the admin-only access.

ASP.NET Core 10 minimal API on .NET 10 (C# 14, nullable reference types enabled, implicit usings), EF Core 10 with Npgsql on PostgreSQL 16 in production. Existing and unchanged: `Program.cs` registers `AppDbContext` (scoped), `TimeProvider.System` as a singleton, JWT bearer authentication, the `WorkspaceAdmin` policy (a signed-in user whose `role` claim is `admin`), `AddProblemDetails` with `UseExceptionHandler`, and calls `app.MapAuditLogEndpoints()`; Kestrel keeps its default of no synchronous I/O. Every token carries a `workspace_id` claim, read by `user.GetWorkspaceId()` (`Workhub.Api.Auth`, existing). `AppDbContext.AuditEvents` is the `AuditEvent` entity: `Id` (long identity), `WorkspaceId` (int), `CreatedAt` (`DateTime`, UTC, mapped to `timestamptz`, set by the app when it writes the event, so two events can share a value and ids are not in `CreatedAt` order), `ActorEmail` (nullable, empty for system events), `Action` (a dotted name such as `document.shared`), `Target` (nullable, up to 500 characters of user-typed text) and `IpAddress` (nullable). Text columns hold valid Unicode without NUL characters. Audit events are append-only: the app inserts them and never updates or deletes them. An index on (`WorkspaceId`, `CreatedAt`, `Id`) exists. `AuditEventDto` is an existing record used by the list endpoint. The reverse proxy passes responses through as they are written. Tests use xUnit and the existing `WorkhubApiFactory` (`WebApplicationFactory<Program>` over an in-memory SQLite database, with the clock fixed at 2026-10-28 12:00 UTC): `CreateClientFor(workspaceId, role)` signs requests in, `SeedAsync(events)` inserts events. The download button ships separately in the web app.

Requirements

Files touched

Review this PR

C# practice