Skip to content

The audit trail and the outbox ​

Two things in the module happen after the transaction that decided them: the trail of the acts the framework's interceptor cannot see, and the verdict the consumers wait for. Both are written in the same transaction as the act, through the module's own outbox, and delivered after the commit. This page describes host composition, the trail contents, and the remaining gaps for product files. The decisions are D-02 (the outbox of ADR 0012), RN-GF-12, RN-GF-26 and RN-GF-27 (j).

Why an outbox ​

SaveChanges is audited by the framework's interceptor, which records row changes. Reading a file is not a row change, and neither are a download URL, a quarantine that moves an object, or a legal hold. Yet "who downloaded what" is the first question of a leak audit. The module therefore stages an explicit line for each, and the line has to be there if and only if the act was: written before the commit it could describe an act that never happened; written after it, a process that dies in between loses the proof (the behaviour up to v10.0, where the line was saved after the commit and a hold could be placed with none). The outbox gives both: the line is staged in the act's transaction and delivered at least once after it.

Composing it in the host ​

csharp
builder.Services.AddOutboxMessaging(outbox => outbox.AddGrydFilesOutbox(
    (_, options) => options.UseNpgsql(builder.Configuration.GetConnectionString("GrydFiles"))));
builder.Services.AddOutboxWorker();   // on the process that drains
  • AddGrydFilesOutbox (GrydFiles.Infrastructure.Messaging) goes inside the host's oneAddOutboxMessaging. It registers the producer files and two local consumers — files.audit-trail-v1 and files.outcome-v1 — that receipt into the module's own database. The context options must keep the default TrackAll tracking: the contexts refuse to be built otherwise.
  • AddOutboxWorker is the host's explicit choice of which process drains. It is not part of AddGrydFiles, and a process that only produces never drains. The process that drains has to compose AddGrydFiles and every consumer's AddGrydFilesConsumer, because the verdict handlers run there.
  • A host that composes AddGrydFiles without AddGrydFilesOutbox does not start. The module registers a start-up requirement (the same hook as the scan-engine one), and the failure says what to compose: the delivery of the trail (files.audit-trail-v1), the delivery of the verdicts (files.outcome-v1), and the worker. Without the delivery the lines and the verdicts would be staged in files.outbox and never read, so no trail would exist and no owner would ever be told a verdict — a failure that shows nowhere until somebody asks for the trail.
  • The module's schema gets four tables with the migration Files_GF_08_ActorAndOutbox: outbox, outbox_payload, outbox_delivery_state and inbox_receipt. The mechanism — ordering, retries, leases, receipts — is the Core's: Transactional outbox.

A host that provides the outbox ports itself (a test host with fakes for IFileAuditOutbox and IFileOutcomeOutbox) declares it with UseHostOutbox() on the module builder and is not refused; a host that declares nothing and composes nothing still is. The gauge is process-wide, like the meter: where a test process composes several hosts, the last one to start answers.

Does this process drain? ​

The module cannot refuse a host for a missing AddOutboxWorker: a producer-only API is legitimate, and the process that drains may be another one. So it reports instead. On start, a process that composes the module's outbox and no worker logs a notice at information level — a producer-only API is a legitimate host, and the line is on every one of its starts (This process stages the GrydFiles audit trail and verdicts in files.outbox but does not drain it), and every process publishes the gauge gryd_files.outbox.drain_in_process on the meter GrydFiles.Trail: 1 where the worker runs, 0 where it does not. The fleet-wide check is an alert on "no instance reports 1" — if no process drains, nothing in the trail or in the verdicts is ever delivered, and files.outbox only grows. (The Core's IOutboxWorkerDiagnostics says the same for a pump that started and then backed off; the gauge is the composition, not the health of the pump. It is process-wide, like the meter: where a test process composes several hosts, the last one to start answers.)

A durable store, or no host ​

The lines are delivered to the registered IAuditStore. The default is NullAuditStore, which keeps nothing — fine for a product that does not audit, fatal for a module whose acts are control acts. So a host that composes AddGrydFiles with only NullAuditStore does not start, in every environment: the module registers a start-up requirement (the same hook as the scan-engine one) and the failure says that download, erasure and the release of a hold would be left without proof, and what to compose — AddGrydAudit, or a durable IAuditStore of your own. Any store that is not the null one satisfies it; the module does not require GrydAudit itself.

The module asks the store through IAuditDurability, and the refusals below stay as defense in depth: an act whose line could not be kept is refused, with nothing changed:

ActWith NullAuditStore (a host that got past start-up some other way)
Download URL503 FILE_AUDIT_TRAIL_UNAVAILABLE, nothing signed
Erasure (Erasure)503 FILE_AUDIT_TRAIL_UNAVAILABLE
Lifting a legal hold (Legal holds)503 FILE_AUDIT_TRAIL_UNAVAILABLE
Placing a hold, an ordinary purge, a quarantineDone; the line goes nowhere

Who downloaded what is the first question of a leak audit, so there is no download URL without a durable trail. Placing a hold is never refused for want of a trail: a refusal would leave the evidence unprotected. The durable store is GrydAudit (AddGrydAudit): its IAuditStore replaces the null one. The module delivers AuditEntry.Id = the outbox message id. GrydAudit's EfCoreAuditStore preserves that id as the AuditLog primary key and treats a duplicate key as an already stored line, including when a batch contains both repeated and new entries (DEC-GF-08-2, implemented in PR 197). That makes a retry after the Audit commit safe for this store. The Audit write and Files receipt still use separate transactions, so delivery remains at least once. PostgreSQL integration tests now inject a failure after the real Audit store commits and before Files confirms its receipt: replay completes the receipt with the same message id and leaves one Audit row. This covers tenant and platform delivery; it is fault injection at that boundary, not an operating-system process termination. A caller that supplied an explicit transaction on the Audit context must account for PostgreSQL aborting that transaction on a duplicate-key violation.

What is on the trail ​

ActionActChange typeSecurity event
stored_file.download_url_issuedA download URL for a person (user, IP, purpose)Accessedsucceeded
stored_file.purgedA purge, ordinary or erasure (reason, origin job/user, name redacted?, erasure, who registered)Deletedsucceeded
stored_file.quarantinedScanning → Infected, the first verdict (signature, engine, base version)Updatedsucceeded
stored_file.integrity_incidentThe object changed after the confirmation and the file, never released, was refused and purged (rejectionCode, confirmed size)Deletedfailed
stored_file.rescan_condemnedAvailable → Infected by a re-scan, with the cause: a signature the base learned after the release, or an object that stopped being the confirmed oneUpdatedfailed
stored_file.legal_hold_placed · .legal_hold_releasedA hold placed or lifted (holder, reason)Updatedsucceeded
stored_file.erasure_refusedAn erasure refused over what holds the file (refusal code, authors, holders)Deletedfailed

Every line carries the kind of author (ActorKind): a job is the system actor files.purge:retencao, files.purge:quarentena-vencida, … (or files.scan); a person is Authenticated; and a declared author is the person plus DeclaredScope and ServiceExecutor, so nothing presents a declared author as authenticated (RN-GF-10). The original name appears as the entity display name only when the act has it (an incident or a refused erasure has none, RN-GF-21). The labels for the catalogue come from FilesAuditCatalogContributor; the screen reads them in the audit contract.

Files without a tenant ​

A product file (tenantId null) has no tenant. The tenant writer continues to refuse it. v10.2.0 adds an explicit Core platform writer, separate platform receipts and a filtered platform execution frame. Files adopts this path for downloads, holds, purges, quarantine and integrity incidents, including re-scans. These events use files.platform-audit-trail v2; tenant audit payloads and routes remain v1.

Opting into platform audit ​

After the usual AddGrydFiles and durable AddGrydAudit composition, opt in on each host that produces these events and compose the route on its messaging builder:

csharp
builder.Services.AddGrydFilesPlatformOutbox();
builder.Services.AddOutboxMessaging(outbox =>
{
    outbox.AddGrydFilesOutbox((_, options) =>
        options.UseNpgsql(builder.Configuration.GetConnectionString("GrydFiles")));
    outbox.AddGrydFilesPlatformAudit((_, options) =>
        options.UseNpgsql(builder.Configuration.GetConnectionString("GrydFiles")));
    outbox.AddGrydFilesPlatformOutcomes((_, options) =>
        options.UseNpgsql(builder.Configuration.GetConnectionString("GrydFiles")));
});
builder.Services.AddOutboxWorker(); // only on the process that drains

Apply Files_PlatformOutboxScope and Files_ExplicitOwnerRouting before starting these writers or workers. The former extends the source scope and creates platform_inbox_receipt; existing tenant messages retain their original scope, plan and receipts. See the Core migration order. Enabling the platform capability without its audit and both outcome routes fails host startup. A producer-only API may still omit the worker; another configured process must drain.

The trusted job opens TenantSnapshot.ForPlatformExecution() only for a selected global record, with filters enabled and global-only visibility. The file transition and v2 message commit or roll back together. The v2 payload has no tenant attribution field, and its consumer records a global Audit entry. An empty tenant session alone does not authorize platform staging. These APIs ship in v10.2.0; they are not part of v10.1.0.

Act on a product fileCurrent behavior
Quarantine after signature detection; re-scan condemned by signatureWith the explicit opt-in and durable store, stage platform audit in the file transaction; otherwise protect the file and count/log the missing trail
Download URL in a platform sessionRequires read:product-files, explicit platform execution and the durable platform route; otherwise permission refusal or 503 FILE_AUDIT_TRAIL_UNAVAILABLE
Purge or erasure by the route; retention and quarantine-expiry jobsStage the platform line with the tombstone when the explicit durable route is available; otherwise refuse (503) or skip/count the automatic purge
Lifting its platform holdStages the platform line with the change; without the durable route, 503 FILE_AUDIT_TRAIL_UNAVAILABLE
Placing a holdStages the platform line with the change when configured; otherwise preserves the hold and counts the missing trail
Object-changed incident, including re-scan divergenceStages the platform incident in the transaction when configured; otherwise preserves protection and counts/logs the missing trail
The verdict for an explicitly scoped ownerStaged as v2 for the persisted tenant or platform destination; a legacy unknown owner is counted as undeliverable
An erasure in process by a consumerExisting tenant trail goes to the tenant that asks

Product-file verdicts and owner identity ​

The source file's tenant and the owner's destination are separate facts. A reference stores OwnerTargetScope (Tenant, Platform or legacy Unknown) and OwnerTenantId; the expected reference stores the same destination. Identity includes these fields as well as scope and key. Two tenants can therefore hold the same product file under the same scope and key without one releasing or reading through the other's reference.

The reference DTO also reports the destination. The generic HTTP release endpoint accepts only a reference owned by the current tenant in an HTTP-managed scope. Platform and legacy unknown destinations use the consumer's explicitly authorized path; a reference id does not grant access.

The migration infers the owner tenant only for legacy tenant files, whose v1 contract already established it. A legacy product-file reference stays Unknown: a null file tenant is insufficient to establish a platform owner. Such references require explicit reconciliation by the product and continue to count as undeliverable when a verdict needs a destination.

Consumers opt into the separate contract while keeping their v1 handler:

csharp
services.AddGrydFilesConsumer<MyScope>(files => files
    .Handler<MyTenantOutcomeHandler>()
    .ProductFileOutcomes<MyProductOutcomeHandler>());

MyProductOutcomeHandler implements IFileOutcomeV2Handler. A trusted platform caller creates platform-owned content through StoreForPlatformOwnerAsync, confirms it through CompleteUploadForPlatformOwnerAsync, or attaches an available file through AddPlatformReferenceAsync. These calls require the opt-in capability, the registered v2 handler and an explicit filtered platform frame. Ordinary tenant reference calls derive the owner tenant from the authenticated session. They accept propagation only from an appropriate active reference, never from another tenant merely because its key matches.

FileOutcomeRecordV2 keeps FileTenantId separate from OwnerTenantId. The worker uses distinct stable receipt routes, files.outcome-v2-tenant and files.outcome-v2-platform. It reads the global source with GlobalOnly, restores the recipient's frame, then calls the handler with its current SourceFile. Handlers use that current state so a delayed Available event cannot revive an infected file. An owner that has not yet committed its pointer requests redelivery; an owner that is gone releases only its exact destination via ReleaseProductReferenceAsync.

Delivery remains at least once: the owner's database and the Files receipt are separate transactions. Make effects idempotent by MessageId. Existing v1 payloads, plans and handler contracts retain their original meaning. Notifications adopts the explicit platform route for global attachments; a missing trusted platform frame is a refusal, not an inferred authority.

The counters remain gryd_files.audit_trail.unreachable (meters GrydFiles.Sweeps, with act = purge, quarantine, object-changed, rescan; and GrydFiles.Trail, with act = legal-hold) and gryd_files.scan.verdict_undeliverable (GrydFiles.Scanner). Successfully staged platform events do not increment the unreachable counter. ScanRequiredDisclosureService persists each waived profile through the platform outbox when the host opts into the durable route. Apply migrations before starting that host. Without opt-in it retains the legacy direct audit-store path; every composition logs the waiver. The disclosure retains its absent action, security category and boolean ScanRequired=false metadata. A configured but non-durable route logs the persistence failure.

HTTP authorization opens the platform frame only after the relevant grant is checked. For holds and purges, this happens after the use case locks and reads the global record. The frame lasts through the transaction and is restored on success or failure. A tenant downloading a global file keeps its tenant-attributed v1 trail. Having no tenant does not replace the required permission.

A released file condemned by a re-scan ​

A re-scan that takes a released file to Infected (RN-GF-17, RN-GF-18) has its own line, stored_file.rescan_condemned, staged in the transaction of the transition and delivered after the commit:

  • change type Updated, and no purge reason: nothing is destroyed — the record becomes Infected, the object is copied to the quarantine as evidence and the retention and the holds are untouched — so it is neither a quarantine of a file that was never released nor a deletion;
  • failed outcome, because content that was served as clean was condemned: it is the line an investigation starts from when it asks "who may have downloaded it";
  • the metadata Cause says which: signature (with Signature, Engine, DatabaseVersion) or object-changed (with RejectionCode, ConfirmedSizeBytes, Detail — the check that caught it);
  • the file name travels, like the first verdict's: the record still has it.

The refusal of a file that was never released, whose object changed between the confirmation and the first read, stays what it was: stored_file.integrity_incident, a Deleted with job:objeto-alterado, because that one does purge. The key is in the audit contract (§6.3), with its label in the three languages.

The label moved with the re-scan's own line. A released product file condemned by a re-scan is counted with act = rescan (it used to be quarantine for a detection and object-changed for a divergence). An alert on act="object-changed" no longer sees the re-scan's incidents, only the refusals of files that were never released: add rescan to the alert.

Collecting the metrics ​

The module has three meters, and a host collects each with AddMeter:

csharp
builder.Services.AddOpenTelemetry().WithMetrics(metrics => metrics
    .AddMeter(FileScanMetrics.MeterName)    // "GrydFiles.Scanner" — scan, queue, alerts, undeliverable verdicts
    .AddMeter(FileSweepMetrics.MeterName)   // "GrydFiles.Sweeps"  — purge, quarantine expiry, consistency
    .AddMeter(FileTrailMetrics.MeterName)); // "GrydFiles.Trail"   — a hold placed without its line; does this process drain?

The third one is easy to miss: without "GrydFiles.Trail" the only signal that a hold was placed with no trail line, and the one that says whether any process drains the outbox, never leave the process. See Watching the scan and Retention & Purge for the instruments.


The decisions behind this page are in ADR 0010; the contract is RN-GF-12 and RN-GF-27 of the specification.

Released under the MIT License.