Search by

qiick / laravel-audit

LucaGiardi20

Shared audit log for qiick Laravel products: the activity_log table, a secret-safe logging trait, server-side attribution, GDPR anonymisation and two-floor retention.

Package info

github.com/qiick-io/laravel-audit

pkg:composer/qiick/laravel-audit

Statistics

Installs: 0

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 5

dev-develop 2026-11-25 13:42 UTC

README

laravel-audit: Audit log core for Laravel products

qiick/laravel-audit

In development. Not released and not on Packagist yet: do not depend on it.

Shared audit log for qiick Laravel products, on top of spatie/laravel-activitylog v5: the common activity_log table (string morph ids, public_id, an optional organisation_id), a logging trait with a secret floor, server-side attribution (who acted, through which credential), a GDPR anonymisation contract and a two-floor retention purge. Product audit tables stay in the products.

Part of the qiick fleet. Binding design: projects/qiick/packages/laravel-audit-design.md in the knowledge base (decisions: decisions/2026-11-23-pre-1-0-extractions.md).

Status

Pre-0.1.0. Public APIs may change in any 0.x release; see UPGRADING.md. Do not require this package from production apps until a tagged release lands on Packagist (Packagist publish only after Luca’s go).

Requirements

  • PHP ^8.4. spatie/laravel-activitylog v5, which the design and every product build on, requires PHP 8.4, so the package cannot support 8.3.
  • Illuminate console / contracts / database / http / support ^12.0 || ^13.0 (never laravel/framework)
  • spatie/laravel-activitylog ^5.1.3: earlier 5.x releases write causer_id by name in the logger (causedByAnonymous(), the default causer), which audit.columns cannot follow
  • Optional: qiick/laravel-access, which fills actor_kind from its actor context.

Install (when published)

composer require qiick/laravel-audit
php artisan vendor:publish --tag=audit-config

Configuration

Key Default Meaning
audit.sensitive_attributes password, remember_token, two_factor_secret, two_factor_recovery_codes, key_hash, previous_key_hash, secret, token_hash, private_key logged as [redacted], on top of the built-in names and parts and encrypted* / hashed casts
audit.sensitive_parts [] extra name parts that make a value secret (other languages)
audit.personal_keys [] extra property keys the anonymiser scrubs
audit.user_agent_max 512 stored user agent length
audit.retention_days 365 general retention floor
audit.security_log_names auth, security, access, api-keys the security logs, kept longer
audit.security_retention_days 730 security logs retention floor
audit.purge.schedule true the provider schedules the purge daily
audit.purge.time 03:00 when the scheduled purge runs, UTC
audit.purge.chunk_size 1000 rows deleted per statement
audit.migrations.load true load the package's activity_log migration
audit.columns subject_id / causer_id morph id columns (externa 1.x only changes them)

Schema

The package owns the activity_log migration (Spatie's table name and columns, so Spatie keeps working):

Column Type Notes
id bigint internal, never leaves the database
public_id uuid, unique UUID v7, generated by the model; the id resources and exports use
log_name, event string; event indexed, log_name indexed with created_at Spatie
description text Spatie
subject_type / subject_id, causer_type / causer_id string / string(64) morphs for bigint, UUID and ULID keys; indexes subject, causer
organisation_id uuid, nullable, indexed with created_at tenant perimeter
attribute_changes, properties json Spatie v5
schema_version unsigned small int, default 1 row format: 1 current, 0 legacy externa row
request_id string(128), indexed correlation with application logs (http-basics accepts up to 128 characters)
anonymised_at datetime set by the anonymiser
created_at, updated_at datetime (never MySQL TIMESTAMP, which ends in 2038); created_at NOT NULL, indexed UTC

There are no foreign keys: activity morphs never cascade, and audit rows are anonymised, never deleted on erasure. In production the migration's down() refuses to drop a table that has rows; migrate:fresh and db:wipe drop tables without down(), so never run them against a production database. The package sets activitylog.activity_model to Qiick\Audit\Models\Activity and activitylog.actions.log_activity to Qiick\Audit\Actions\LogActivityAction unless the product configured subclasses of its own.

Logging trait

use Qiick\Audit\Concerns\LogsActivity;

final class Project extends Model
{
    use LogsActivity;

    // Optional: a log name or extra excludes. The secret floor still applies.
    public function getActivitylogOptions(): LogOptions
    {
        return $this->auditActivityLogOptions()->useLogName('projects')->logExcept(['notes']);
    }
}

The trait never logs a secret value, but it logs that a secret changed: the value becomes [redacted] and the key stays, so "the password changed" is in the log. A value is secret when the model casts it as encrypted* or hashed, when its name (in any spelling: privateKey, remember-token, X-Api-Key) is on the floor (the built-in names, audit.sensitive_attributes), or when its name contains a secret part: password, secret, token, private_key, api_key, two_factor, recovery_code, remember, passphrase, passwd, credential, authorization, cookie, session, segreto, plus audit.sensitive_parts (for names in other languages). A name with a secret part is not redacted when the name ends in _at / _on or the cast is a date, a boolean or an integer: two_factor_confirmed_at records who turned two-factor on, and its value is a time. Short abbreviations (pwd, pass, otp, pin, cvv, iban, dsn) are exact names only.

This holds by name, by JSON path (settings->secret), through a relation (owner.password) and at any depth inside a logged JSON value. A relation logged by name (owner, owner.owner) and any value that holds a model are not logged at all. Description placeholders read only attributes and relations already loaded on the model, never call a model method, and stay as written for a secret or a non-scalar value.

The floor works on names. An accessor that the model logs is the model's responsibility: one that returns a related model's toArray() or a secret under an ordinary name is logged as it returns it.

Audit rows are written once: the model refuses to update or delete a stored row, with or without model events (saveQuietly(), deleteQuietly(), Model::withoutEvents()), and the package columns are not mass-assignable, even inside Model::unguarded(). This guards against mistakes, not against product code: Activity::query()->update() and ->delete() go through the query builder, which the anonymiser and the purge use, and the model cannot stop them. Never write to activity_log that way.

Trust boundary

The package protects the log against mistakes in application code, not against code that sets out to change it. Inside the package, a test allows query-builder writes to activity_log only in the anonymiser and the retention purge. The strong guarantee is the database: give the web and queue processes a role that can INSERT and SELECT on activity_log but not UPDATE or DELETE, and run audit:purge and the erasure job with a role that can. Each row's public_id and timestamps make tampering visible only to someone who compares copies; hash chaining is after 1.0 (design §3).

For models that cause activity, use Qiick\Audit\Concerns\CausesActivity (or HasActivity for both): their activitiesAsCauser() / activities() relations work on PostgreSQL for bigint keys and follow audit.columns. Never use Spatie's HasActivity: it brings Spatie's LogsActivity without the secret floor.

Attribution

Every row the package logs carries server-side attribution, written after every beforeLogging callback, so a caller can never forge it:

properties key Value
ip, user_agent the routed HTTP request (user agent cut to audit.user_agent_max); absent in console commands and jobs
actor_kind web_session, api_key, oauth_grant, public_api or unattended
api_key_id, api_key_prefix, api_key_created_by the bound API key: public UUID, display prefix, creator's public id
oauth_client_id the bound OAuth grant's client UUID

A caller's value for any of these keys is removed.

The causer: when a credential acts, its owner principal replaces any causer the caller chose. Otherwise the caller's choice stands: an explicit causedBy($admin) (an admin stopping an impersonation) or causedByAnonymous() is kept, and the signed-in user is the causer when none was chosen. Description placeholders are resolved before this rule, so under a credential :causer.name names the caller's causer, not the owner.

The key or OAuth middleware binds the credential once it is verified:

use Qiick\Audit\AuditContext;
use Qiick\Audit\Contracts\AuditActor;

AuditContext::bindCredential(new AuditActor(
    causer: $apiKey->ownerPrincipal,   // the credential's owner is the causer
    actorKind: 'api_key',
    apiKeyId: $apiKey->public_id,      // UUID, never the bigint
    apiKeyPrefix: $apiKey->prefix,
    apiKeyCreatedBy: $apiKey->creator->public_id,
));

Products that wrote api_key_id through Qiick\ApiKeys\Audit::withApiKeyId() bind the credential instead: the reserved key is the server's.

The organisation goes in the organisation_id column, never in properties: either explicitly, activity()->tap(Audit::inOrganisation($organisationUuid))->log(...), or from the product's OrganisationResolver binding (default: none). request_id comes from the request_id key of Laravel's context, which qiick/laravel-http-basics sets.

Erasure (GDPR)

The product's erasure job calls the anonymiser in the same transaction as the user tombstoning, or after it, never alone:

use Qiick\Audit\Contracts\AuditAnonymiser;
use Qiick\Audit\Contracts\ErasureSubject;
use Qiick\Audit\Contracts\MorphRef;

$report = app(AuditAnonymiser::class)->anonymise(new ErasureSubject(
    refs: [MorphRef::of($user), MorphRef::of($principal)],  // every model that identifies the person
    tombstone: $user->tombstone,                             // the product's unique tombstone
    identifiers: [$email, $username, $displayName],          // scrubbed from free text
));

Matching rows keep their event, log name, timestamps and morphs; their personal keys, the identifiers (as whole words) and any email address or phone-like sequence become the tombstone, and anonymised_at is set. A second run reports 0 rows. The tombstone must not contain an identifier or look like an email address or a phone number.

Retention

Every log is kept 365 days, and the security logs 730 days: auth, security, access and api-keys by default (audit.security_log_names), because security events are kept two years. Log names are stored trimmed and in lower case, so Auth and auth are one log on every engine. php artisan audit:purge deletes in two passes on created_at: rows outside the security logs past audit.retention_days, then security log rows past audit.security_retention_days. The provider schedules it daily at audit.purge.time (UTC); a product that runs it itself sets audit.purge.schedule to false.

Spatie's activitylog:clean goes through the same two floors: the package sets activitylog.actions.clean_log to its own clean action, so activitylog:clean --days=1 (or a named log) never deletes a row younger than 365 days, or a security log row younger than 730. A product that keeps it in the schedule loses nothing; audit:purge alone is enough.

Querying

Activity::query()->causedBy($user), ->forSubject($model) and ->forOrganisation($organisationUuid) bind ids as strings. forOrganisation never returns rows without an organisation: those are for the instance super-admin, through an unscoped query the product guards. causedBy, forSubject and activitiesAsSubject() do not filter by organisation: a tenant page always adds forOrganisation().

Boot checks

The application does not boot when:

  • activitylog.activity_model does not extend Qiick\Audit\Models\Activity, activitylog.actions.log_activity does not extend Qiick\Audit\Actions\LogActivityAction (it writes the attribution), or activitylog.actions.clean_log does not extend Qiick\Audit\Actions\CleanActivityLogAction (it applies the retention floors);
  • app.timezone is not UTC;
  • in production, activitylog.enabled is not true or activitylog.buffer.enabled is not false (security events must not be turned off or lost by one env variable).

Serialised rows never carry the bigint id; timestamps are RFC 3339 UTC. The security checklist maps every design risk to its tests: docs/security-checklist.md. Adopting the package in a product: UPGRADING.md.

Deprecation policy

This package follows Semantic Versioning (SemVer):

  • Deprecation in minor releases: When a public API (class, method, interface, config key, or environment variable) is deprecated, it is marked with @deprecated docblocks, documented in CHANGELOG.md and UPGRADING.md, and triggers a runtime notice or warning where appropriate. The deprecated feature remains functional and supported for at least one minor release.
  • Removal in major releases only: Deprecated APIs are never removed within the same major version (0.x or 1.x). Breaking removals occur exclusively at the next major release boundary (e.g. 2.0.0).
  • Pre-1.0 stability: In 0.x, breaking changes are documented in UPGRADING.md before each tagged release. Once 1.0.0 ships, public contracts and migrations are frozen and follow strict SemVer forward compatibility.

Security

Private vulnerability reporting: see SECURITY.md.

License

MIT. See LICENSE.