packagist damienharper/auditor 5.0.0

one hour ago

auditor 5.0.0

auditor 5.0 is a provider-agnostic core: the Doctrine ORM provider now lives in its own package, the audit
format moves to schema v2, and the core gains the building blocks to show the history of a business object
rather than of one table: audit roots, histories, blame contexts, readable and masked values.

auditor 5.0 is released together with:

Upgrade the three together.


⚠️ Breaking changes / upgrading

The full migration path is in UPGRADE-5.0.md
and in the upgrade guide. The changes you must act on:

  1. The Doctrine provider is no longer in the core. The DH\Auditor\Provider\Doctrine namespace is removed from
    damienharper/auditor: install damienharper/auditor-doctrine-provider:^2.0 (same class names).
    NeedsConversionToAuditableType moved to DH\Auditor\Provider\Doctrine\Transaction\. Symfony applications get
    it through auditor-bundle 8.0.
  2. Audit tables must be migrated to schema v2. Back up the audit tables, then run
    audit:schema:migrate --force --convert-all and audit:schema:update --force (auditor-doctrine-provider 2.0).
    The migration has no rollback: follow the
    auditor-doctrine-provider 2.0 upgrade guide.
  3. Entry and the LifecycleEvent payload changed. $entry->transactionHash is replaced by
    $entry->transactionId (a ULID), the blame columns are merged into one blame JSON ($entry->username,
    userFqdn, userFirewall and ip keep working), and getDiffs() returns the changes of a v2 entry. Custom
    providers reading $event->getPayload() must use transaction_id, blame and schema_version.
    TransactionInterface::getTransactionHash() is renamed getTransactionId().
  4. Persistence failures are no longer silent. AuditEventSubscriber throws a
    DH\Auditor\Exception\ProviderException when no storage provider could persist an audit entry; with the Doctrine
    provider, the flush fails and the transaction is rolled back.
  5. UserInterface declares ?string $fqdn and ?UserInterface $impersonator. Custom implementations must
    declare both (null when unknown).
  6. New requirement: symfony/uid ^8.1, installed with auditor (it generates the ULID transaction ids).
    PHP >= 8.4 and Symfony >= 8.1 are unchanged.

✨ What's new

Schema v2 audit format

Every audit entry now carries a sortable ULID transaction_id, a single blame JSON and a schema_version. Diffs
use one envelope for every operation: a source block describing the audited entity, the changes, and for
associations a target block. Legacy (v1) rows keep being read: Entry::fromArray() falls back on
transaction_hash and synthesises blame from the old columns.

$entry->schemaVersion;    // 2 (1 for legacy rows)
$entry->transactionId;    // ULID
$entry->blame;            // ['username' => ..., 'user_fqdn' => ..., 'user_firewall' => ..., 'ip' => ...]
$entry->getDiffSource();  // ['id' => '42', 'class' => 'App\Entity\Post', 'label' => 'My post', 'table' => 'post']
$entry->getDiffTarget();  // target of an associate / dissociate entry

Entry also gains toArray() (a flat array with the same keys for v1 and v2 entries, used by exports),
isSnapshot() (an insert written by audit:snapshot), and isDeepDiff() / isDiffLeaf() to walk the deep diff of
a JSON field.

Audit roots and histories

An application rarely shows the history of one table alone. #[AuditRoot] declares that the entries of an entity
belong to the history of another one (repeatable, with a path of associations), so that providers can read the
history of a business object across tables in one query:

use DH\Auditor\Attribute\Auditable;
use DH\Auditor\Attribute\AuditRoot;

#[Auditable]
#[AuditRoot('property')]
class PropertyFeature { /* … */ }

#[Auditable]
#[AuditRoot('property')]
#[AuditRoot('buyer')]          // repeatable: a bid belongs to the history of the property and of the buyer
class Bid { /* … */ }

#[Auditable]
#[AuditRoot('visit.property')] // a path of association properties
class VisitAttendee { /* … */ }

HistoryGrouper turns entries into actions (one per transaction, or any key you choose), ChangeExtractor turns them
into Change objects whatever their diff format, and BlameOrigin tells a web request from a console command, a
Messenger worker or the system:

use DH\Auditor\History\HistoryGrouper;

foreach (HistoryGrouper::byTransaction($entries) as $item) {
    $item->username;        // author
    $item->origin;          // BlameOrigin::Http, Console, Messenger or System
    $item->via;             // blame context, if any
    $item->getChanges();    // list<Change>, in chronological order
    $item->getMainChange(); // the creation, snapshot or deletion if any, otherwise the first change
}

See Histories.

Blame contexts

A blame context records how a change was made (an import, a console command, a Messenger message…) in the via
key of the blame JSON, next to the user. It may also carry the user to blame instead of the user provider's one.

use DH\Auditor\Blame\BlameContext;

$auditor->getConfiguration()->getBlameContextStack()->run(
    new BlameContext('import', 'Import batch #42', ['file' => 'products.csv']),
    fn () => $entityManager->flush(),
);

$entry->via; // ['type' => 'import', 'label' => 'Import batch #42', 'data' => ['file' => 'products.csv']]

See Blame Context.

The class of the user and the impersonator in the blame

UserInterface now carries the class of the user in the application ($fqdn, written as user_fqdn) and the user
who impersonates them ($impersonator, written in an impersonator key of the blame only when set):

new User($id, $username, App\Entity\User::class, new User($adminId, $adminName, App\Entity\Admin::class));

$entry->impersonator; // ['id' => ..., 'username' => ..., 'fqdn' => ...], null without impersonator

Readable values in diffs: #[DiffLabel]

#[DiffLabel] stores a human-readable label next to the raw value of a field ({"value": 2, "label": "Processing"}),
computed at write time by a service implementing DiffLabelResolverInterface:

use DH\Auditor\Attribute\DiffLabel;

#[DiffLabel(resolver: StatusLabelResolver::class)]
private int $status;

Values kept out of the audit: #[Mask]

#[Mask] records that a field changed without storing its values. MaskStrategy::Hidden (the default) stores
"***"; MaskStrategy::KeyedHash stores an HMAC-SHA256 keyed with the provider's mask secret, so the entries of one
value can be found without storing it. Unlike #[Ignore], the change still shows in the history.

use DH\Auditor\Attribute\Mask;
use DH\Auditor\Masking\MaskStrategy;

#[Mask(strategy: MaskStrategy::KeyedHash)]
private string $email;

#[Mask]
private string $pin;

#[Ignore], #[DiffLabel] and #[Mask] can also be put on the class with a field argument, for models that do
not declare a property per column: #[Mask(field: 'email')].

Per-entity retention policy

#[Auditable] takes an optional retention policy, applied by the providers that support pruning:

#[Auditable(maxAge: 'P7Y')]      // keep 7 years of history
class Payment {}

#[Auditable(maxEntries: 10_000)] // keep the 10,000 most recent entries
class Session {}

disableStorage() and disableAuditing() take effect

Auditor::disableStorage() and Auditor::disableAuditing() only updated internal lists that nothing read. The
subscriber now skips the providers whose storage is disabled, and providers honour the auditing switch (the Doctrine
provider does from 2.0). The four switches now throw an InvalidArgumentException for a provider that was never
registered. This fix is also in the 4.x branch.

Faster Entry reads

The diffs, blame and extra_data JSON columns of an Entry are decoded once instead of on every accessor call:
reading a 50-entry page the way a viewer does went from about 7.6 ms to 0.8 ms in our benchmark.


What's Changed

Breaking changes

  • chore: remove embedded DoctrineProvider (v5.0) by @DamienHarper in #312
  • feat!: refactor audit schema to v2 — ULID transaction_id, blame JSON, unified diffs by @DamienHarper in #316
  • fix(subscriber): throw when no storage provider could persist an audit entry by @DamienHarper in #340
  • feat(blame): record the class of the user and the impersonator by @DamienHarper in #360

New features

  • feat: add #[DiffLabel] attribute and DiffLabelResolverInterface by @DamienHarper in #313
  • feat: add Entry::toArray() for structured export serialization by @DamienHarper in #319
  • feat: add per-entity retention policy to #[Auditable] by @DamienHarper in #320
  • feat: expose deep diff marker on Entry with isDeepDiff() and isDiffLeaf() by @DamienHarper in #330
  • feat(entry): add Entry::isSnapshot() for entries written by audit:snapshot by @DamienHarper in #343
  • feat(blame): blame contexts written in the via key of the blame JSON by @DamienHarper in #344
  • feat(attributes): #[Ignore] and #[DiffLabel] on the class, with a field argument by @DamienHarper in #347
  • feat: audit roots and histories by @DamienHarper in #349
  • feat(history): tell whether a HistoryGrouper groups by transaction by @DamienHarper in #357
  • feat(attributes): #[Mask] records a change without its values by @oleg-andreyev in #358

Bug fixes

  • fix(entry): fall back on transaction_hash whatever the order of the columns by @DamienHarper in #350
  • fix(auditor): make disableStorage() and disableAuditing() take effect by @DamienHarper in #355

Performance

Documentation

  • docs(upgrade): symfony/uid requirement and schema v2 migration steps in the 5.0 guide by @DamienHarper in #341
  • docs: new features of 5.0, blame context API and supported versions by @DamienHarper in #345
  • docs: bring the 5.0 docs in line with the code before the release by @DamienHarper in #351
  • docs: align the documentation with the code by @DamienHarper in #354
  • docs: state that the previous major only receives bug and security fixes by @DamienHarper in #336
  • docs(claude): describe the schema v2 payload and the auditor family by @DamienHarper in #332

Maintenance

Already shipped in 4.4.0

  • feat(auditor): allow skipping the runtime AuditEventSubscriber registration by @DamienHarper in #337

References

Full Changelog: 4.4.0...5.0.0

Don't miss a new auditor release

NewReleases is sending notifications on new releases.