Skip to content
ERPForAll DocsDevelopment

    The audit trail

    Status: stages A and B (ADR 0039, ADR 0151). Optional chain seals, retention and the audit reader are separate planned work; there is no audit screen yet. ADR 0167 specifies the reader and additive read policy. The typed reader engine, database authority and successful-read selection are in place. Dedicated serving APIs remain pending. Odoo Community has no framework audit trail; this is ERPForAll’s own design.

    What is recorded without you doing anything

    Section titled “What is recorded without you doing anything”
    What happenedRowWhen it is written
    A JSON-2 call that changes data commitsone change rowin the same transaction, by one INSERT before COMMIT
    That call is denied, fails, ends with an unknown COMMIT, or is a replay of an idempotent callone attempt rowon its own connection after the call ended
    An unselected read by a usernothingno audit statement
    A successful read selected by model, elevation or operator policyone read_ok attemptindependently, before releasing the buffered result
    A server action flagged run_as_superuser runsan elevation entry in the transaction’s rowbefore the elevated body runs

    A bulk call over a thousand records is still one row. A call retried after a serialization failure writes only the row of the attempt that ends the call, with its attempt number. If the audit row cannot be written, the change is rolled back and the caller gets 503 erp.audit_unavailable: audit is never skipped.

    A row holds who acted (principal kind, subject, the key that was used as an id, the delegating user), the model, the method and its effect, the ids the call named (consecutive ids as ranges), a SHA-256 digest of the redacted arguments, the correlation and operation ids, the company set, the policy generations, the outcome and a bounded error class. It never holds a key, key name, password, hash, token, cookie, login, address or error message. Record values are digested after redaction (redaction version 2): a field marked secret (#[field(char, secret = true)], or FieldDecl::secret(true)), restricted fields, binary and image fields and unknown fields are replaced by their reason, for example {"$redacted":"secret"}, before anything is hashed, so the digest of two different passwords is the same. A method that takes no record values contributes only the names of its arguments. Mark every field that holds a password or another credential secret: the base addon marks res.users.password and the password wizards’ fields. The marker also applies inside x2many create and update commands (triples, and a plain list of value maps), because each nested record is redacted with its own model’s declarations; a shape the redaction does not recognise, or a many2one given a list or map, is replaced whole by {"$redacted":"unparsed"}. An extension cannot switch secret off once an addon set it (the registry refuses with a programming error naming the field), a related field whose path ends at a secret field is secret too, and ir.config_parameter.value is marked secret. A field that is not marked keeps its value in the digest, so a reader of the rows can still confirm a guess about a low-entropy value there (a PIN, a phone number); the digest is evidence that a call happened, not a place to hide such data. Fields declared at runtime (ir.model.fields custom fields) cannot be marked secret yet.

    Authentication code records a lifecycle change in the transaction that makes it. The event is written with the change or not at all, and is dropped if a savepoint around it rolls back:

    use erp_sdk::audit::{ApiKeyRevoked, AuthEvent, KeyRouteScope, RevokeCause};
    use erp_sdk::{ApiKeyId, KeyKind, Transaction, UserId};
    fn revoke_recorded(tx: &mut Transaction) -> erp_sdk::Result<()> {
    let event = ApiKeyRevoked::new(
    ApiKeyId::new(91).map_err(erp_sdk::Error::from)?,
    UserId::new(7).map_err(erp_sdk::Error::from)?,
    KeyKind::User,
    KeyRouteScope::Rpc,
    RevokeCause::Owner,
    );
    tx.audit_auth(AuthEvent::ApiKeyRevoked(event))
    }

    audit_auth refuses before any statement when the audit store is not ready, in a read-only transaction and after the commit preamble froze the buffer. When the audit store is unavailable the revocation fails too: revocation is atomic with its audit row. The one exception is the operator’s emergency revocation on the owner connection, described below.

    erp auth emergency-revoke (cli.md) ends API keys and sessions on the owner connection when the runtime role cannot write audit rows. It still writes its own row in the same transaction, with origin cli and the core System principal. The events are:

    EventFields
    emergency.revocation (the header, one per row)reason (compromised, lost, offboarding or incident), keys, sessions (counts)
    api_key.revokedas for an ordinary revocation, with cause {"kind":"emergency"}
    session.revokedsession id, user, cause "emergency" (one per named session)
    user_sessions.revokeduser, cause "emergency", count (all sessions of a user)

    Core code calls erp_security::auth::emergency::revoke(tx, &Target, EmergencyReason) in a read-committed transaction opened for the core System principal with an OperationIdentity, then commits. The call refuses before any deletion when the principal is not the core System principal, when the audit store cannot take the row (Transaction::audit_store_state) and when current_user does not own res_users_apikeys, erp_session and erp_event.ir_audit_entry. On an error the caller rolls the transaction back. Addon code does not call it.

    The owner role can rewrite its own rows: the row is evidence, not a defence against a hostile owner.

    No constructor accepts a string that could carry a credential: events are made of ids, closed enums, flags and counts. A new kind of event is a new AuthEvent variant added by the slice that owns it, with its own validated payload. Addons cannot suppress, rewrite or delete a row: the request role holds INSERT on the columns it supplies and nothing else, the table is in the closed event namespace (every ORM and RPC operation on it is refused), and no context key disables audit.

    A flagged action (set by an administrator, on an action with groups) runs with superuser mode. The order is fixed: the caller’s own right to run the action (group membership) is checked first, a caller who may not run it records nothing, then the transaction records the elevation (action id, root action id, groups, who last wrote the action and when) and only then does the action and its subtree run with the elevated environment. A flagged action inside an elevated subtree is recorded as its own entry. The same action twice in one transaction is one entry with a count. When the store cannot take the row the action does not run.

    Opening an elevation block (Transaction::elevated, see scoped elevation blocks) calls the crate-private hook Transaction::record_elevation on block entry, after the scope was validated and before the body runs; an error aborts the block before any elevated statement, and a refused entry records nothing. The entry’s grant is {"kind": "scoped", "block": <number of the first block>, "items": [...]} with each item’s model, operations, fields ("*" for all) and lifted rules. The hook only buffers (no statement, no second connection), deduplicates by reason, scope (by value), original attribution and effective subject, allows 128 distinct entries per transaction attempt and keeps the evidence of an elevation whose savepoint rolled back, marked savepoint_rolled_back. The unscoped escape hatch Transaction::audited_unscoped_sudo records each call.

    • The table erp_event.ir_audit_entry is installed by every runtime grant publication (erp db publish-grants) and by erp audit maintain, with today plus 31 UTC daily partitions. A missing partition fails the insert; the server therefore refuses to start with no partition ahead of today and logs an error with one day left. The server creates the missing days itself at every start and once an hour on every node (Orm::maintain_event_partitions); a failed hourly run is logged and retried, and erp audit maintain repairs the window by hand.
    • Runtime contract version 8 (erp db runtime-grant-contract) preserves the insert-only runtime right and adds isolated SELECT-only reader publication/admission. Restoring an older publisher is refused before publication or pointer switching; old binaries do not implement this reader contract.
    • Configuration refuses identical runtime and owner roles. A configured reader must also differ from runtime, owner and heartbeat roles.

    The test harness installs the real table in every database that builds its tables; there is no recording sink in any build. Read rows over an owner connection. HarnessBuilder::without_audit_store() starts from an empty event namespace, for tests of the event schema or of the refusal while the store is missing.

    erp_orm::audit::seal provides pure format-1 canonical values, complete schema-1 row digests, ordered batch digests and validated seal envelopes (ADR 0039). These helpers do not write audit events, connect to a database, publish a witness or verify history. Supply already-redacted values; encoding is not redaction. RowDigest::schema1 requires every persisted column name, including generated columns, and sorts them bytewise. The database adapter remains responsible for SQL types, actual schema versions and (xid,id) ordering.

    Use CanonicalValue::numeric with an exact decimal token, never a value rounded through floating point; timestamp_micros takes integral UTC microseconds and xid preserves unsigned xid8. Structured values are built from typed children, not parsed with the ordinary f64 JSON parser. The codec bounds each encoded value/row to 8 MiB, each collection/batch to 65,536 members, decimal input/output to 4,096 bytes, and nesting to 16 containers. These are safety limits; batch defaults are a separate policy described in the owner-side sealing section below. Rejections are typed CodecError values with no payload in their messages; CanonicalValue debug output omits content. Raw encoded bytes still contain the input and must not be logged.

    The row adapter and owner-side batch operation are described below. Verification and CLI/configuration remain separate chain packages. The external witness library is described below. No new operator command, configuration or installation step is provided by the codec alone. Its serving integration and screen remain pending.

    ADR 0167 defines three dedicated read-only methods on ir.audit.entry: audit_search, audit_read and audit_export. They are not available yet. Do not route audit storage through generic ORM methods or an owner connection while waiting for this work. The request role remains INSERT-only; the reader will use a separate restricted SELECT role.

    The typed engine requires both audit.read and audit-model read permission. Current target model, record and company rules still apply. The initial reader returns only entry identity/time, kind/outcome, model, method/effect and target ids. It conceals whole rows with any inaccessible or deleted target, unknown metadata or no target; it also conceals argument digests, raw events and identity/correlation aggregates. Search and export use the same projection, including their filters and continuation. This is a bounded view of currently authorized history, not recovery of deleted data or a complete forensic export.

    The native audit_reads = true declaration and its owned equivalent compose monotonically: an extension cannot disable another declaration’s true value. Operator policy may additionally select all users or members of named groups. It cannot disable mandatory attempts, model opt-in or elevation recording, and request context cannot override it. A selected successful read remains READ ONLY and its result is withheld until the independent read_ok attempt commits.

    No audit history is seeded during installation: rows describe real operations. Capability and model ACL defaults belong in base. The audit.read mapping already exists; dedicated audit-model ACL installation, serving binders and JSON-2 tests remain obligations of INTEGRATE. Optional reader credential admission is described below. This engine does not make the serving API available or claim Agent/Service RPC admission.

    The internal erp_orm::audit::reader service provides validated AuditQuery, ReadRequest and composite EntryKey types. AuditReader::search, read and export use the transaction’s original caller, with all elevation removed, on the primary. Field groups apply to requested fields and continuation keys. The registered capability is erp_security::audit::AUDIT_READ; its existing base data mapping is reused. A System-only transaction cannot supply reader authority. Generic event ORM operations still refuse.

    Queries require one known model and a positive UTC interval of at most 31 days. Page size defaults to 100 and cannot exceed 1,000; direct reads accept at most 1,000 composite keys. Candidate scans are bounded to 4,096 rows and 16 MiB of payload; each stored target set expands to at most 4,096 IDs. Continuations are at most 1 KiB and bind the query, caller, companies and current generations. A full page’s continuation does not promise another eligible row. Scan, output and deadline limits return errors without partial success.

    The engine has no public enabled-pool constructor in shipped builds. AuditReader::unavailable() fails explicitly; for_tests exists only with test-faults and uses real restricted-role storage. INTEGRATE must compose the admitted reader handle with this service and serving-generation wiring before enabling any endpoint. The reader authority facility below supplies credential admission and shared connection-budget configuration. No owner-connection fallback is provided. Engine tests do not establish installed defaults, JSON-2 behavior or two-node admission. Dedicated reader methods and their RPC tests remain pending; the operational reader authority below does not open the current API or claim Agent/Service RPC admission.

    The optional server [audit_read_policy] table accepts exactly one mode:

    [audit_read_policy]
    user_groups = ['base.group_system']

    Alternatively use all_users = true. Omit the table, use all_users = false, or use user_groups = [] for defaults-only selection. Both mode keys together, an empty table, unknown keys, wrong types and group expressions are errors. Supply at most 256 positive group XML IDs, each at most 256 UTF-8 bytes. Duplicate names and order do not affect the shared configuration digest.

    Group matching uses the caller’s current transaction-bound effective memberships, including implied groups, independently of request debug mode. Unresolved group references fail the operation, even when another group matches or the model already requires auditing. Fix the operator configuration or restore the group; an unknown group never silently disables recording. Subsequent operations use refreshed membership under the normal authorization invalidation contract.

    Model opt-in, observed elevation and mandatory denial/failure/replay/commit-unknown attempts cannot be disabled by this configuration. Nodes must agree on its canonical value before serving together. The normal native startup and lifecycle recomposition use the same RPC settings construction.

    The optional audit_reader_database_url_file names a mode-600 regular file containing a PostgreSQL URL for a dedicated login on the same database endpoint. Relative paths resolve next to the server configuration. Symlinks, malformed files, another endpoint/database and a reused role are refused. Connection material is node-local and omitted from configuration Debug, shared settings digests and reader admission errors. The credential can read raw audit storage: keep it in the trusted platform boundary, never in addon state, RPC input or client configuration.

    Transaction::grant_audit_reader_role publishes schema USAGE and SELECT on the audit parent only. It reconciles direct event table, column, partition and sequence ACLs for this role, then verifies its effective privileges. Inherited or PUBLIC excess privileges, unsafe role attributes, ownership, role-switch paths, schema creation, database CREATE/TEMPORARY and executable application SECURITY DEFINER functions are refused. Operator remediation must remove the source of those privileges; publication does not rewrite unrelated roles or shared PUBLIC grants. New event partitions remove non-owner default ACLs so upkeep cannot grant direct partition access. Existing partition drift is caught by reader admission and reconciled by publication where directly granted to the reader.

    AuditReaderRoles::new declares the other deployment identities. AuditReaderConnection::open constructs its own private single-slot pool from the reader credential. It verifies the actual login, effective rights and a random live-session challenge against the trusted primary’s pg_stat_activity. Every new connection is admitted; verify rechecks pooled role/privilege state before generation publication. No raw pool or SQL operation is exposed by the public handle. A query/projection service will be attached by the reader integration slice.

    With reader configuration absent, the server retains eight request slots and no reader pool. When configured, it reserves one of those slots: seven request slots and one reader slot, reused across registry generations. Policy and independent attempt-writer facilities retain their existing budgets. Invalid supplied credentials fail startup without trying owner/runtime/node credentials. Absence preserves ordinary writes; dedicated reader methods and their unavailable response remain pending.

    erp_orm::audit::seal::{Anchor, AnchorRange, AuditWitness} describes operator-side external anchors. Anchor carries a validated SealIdentity, SHA-256 seal hash and format version 1. Construction validates these types; callers must separately establish that the database seal is valid and its transaction committed. The trait’s synchronous publication and scoped fetching must never run inside an ordinary request transaction.

    erp_cli::audit::FileWitness implements this contract and supplies inventory() independently of database rows, heads or epoch lists. Inventory retains anchors for database history that has since disappeared, sorts by incarnation/epoch/batch identity and collapses identical duplicates. Scoped fetch validates the entire file before filtering; corruption outside its range still fails. An empty inventory provides no external assurance. Database comparison and recovery orchestration remain pending.

    use erp_orm::audit::seal::{Anchor, AnchorRange, SealIdentity};
    let identity = SealIdentity::new([1; 16], 1, 1)?;
    let anchor = Anchor::new(identity, [9; 32], 1)?;
    let range = AnchorRange::new(1, 100)?;
    assert!(range.contains(anchor.identity().batch_no()));
    # Ok::<(), Box<dyn std::error::Error>>(())

    FileWitness requires an existing trusted operator directory and a regular single-link file; publication creates a missing file with owner-only permissions. Reads never create evidence. Each operation opens fresh descriptors and uses an operating-system advisory lock. A competing operation (file creation or locking) returns typed WitnessError::Busy; callers may retry under their own bounded policy. Publication validates existing records, appends only a new identity, then synchronizes the file and directory. Identical retries also synchronize, so an earlier synchronization failure can be reconciled without duplicate records. Conflicting identities fail without rewriting history. I/O failures preserve the operation and OS error kind without echoing paths or JSON.

    The closed JSONL format contains only incarnation, epoch, batch number, seal hash and format version. Unknown/duplicate/missing fields, wrong types, malformed identities and unsupported versions are refused. Bounds are 1,024 bytes per physical line including LF, 16 MiB per file and 65,536 physical records. Blank lines and a final line without LF fail; CRLF is accepted. Exceeding a bound refuses operation rather than silently dropping evidence. There is no automatic truncation, rotation or torn-record repair, and file storage provides no database verification by itself. No witness command or server configuration key is introduced by this library delivery.

    Transaction::install_audit_chain_schema installs or validates the unpartitioned erp_event.ir_audit_chain, ir_audit_seal and seal sequence. It requires the System principal with full elevation and the database owner connection. Existing objects must match the closed catalog declaration; drift requires explicit owner recovery. The installer creates no epoch. The caller commits or rolls back its transaction.

    Use EpochReason::new with an identifier of 1 to 128 ASCII letters, digits, dots, underscores or hyphens. initialize_audit_chain explicitly creates epoch 1; new_audit_chain_epoch preserves its incarnation and links the next epoch to the current final seal. An empty predecessor epoch is refused. Both operations require Read Committed isolation and share a transaction advisory lock with sealing. EpochChange::Busy means another maintenance transaction holds that lock; retry in a new transaction. Created describes an insertion awaiting the caller’s commit.

    EpochState reports the inherited lower-exclusive cursor and predecessor hash. A new epoch cannot reset either. These metadata operations do not seal audit rows, publish an external witness or establish verified history. The file witness library is described above; SEALER, VERIFY and INTEGRATE provide the remaining database orchestration. No operator CLI for these new operations is delivered by the schema package. Runtime roles receive zero table, column or sequence authority on chain storage under contract v6.

    Transaction::seal_audit_batch(&SealOptions) reads the next committed safe prefix of persisted audit rows and inserts one immutable seal/checkpoint in the caller’s transaction. Initialize the chain explicitly with initialize_audit_chain first. Use the database owner connection, System/full authority and Read Committed isolation, as for epoch maintenance.

    SealOptions::default() admits at most 10,000 rows and 8 MiB of cumulative stored encoded_bytes. SealOptions::new(rows, bytes) accepts 1..=65,536 rows and 1..=8 MiB. Stored estimates do not authorize unbounded decoding: transport is limited to 8 MiB per row and 16 MiB per batch, with the existing canonical depth, member, number and byte bounds applied independently. Invalid estimates, unsupported schema/value shapes and an oversized first row are explicit errors.

    The operation returns SealOutcome::Busy when another maintenance transaction holds the shared epoch/sealer lock, NoWork when no safe row is available, or Staged(SealReport). Staged still requires the caller to commit. Rollback discards both seal and checkpoint; sequence-generated seal ids may have gaps. After an error, roll back the transaction. Confirm commit before publishing an external witness anchor. A failed or uncertain commit requires reconciliation by identity; the report alone does not prove persistence or external assurance.

    The prefix is ordered by (xid,id) and lies strictly below snapshot xmin from the selection statement. A long-running writer can delay sealing, so NoWork is not a declaration that all history has been sealed. The first seal of a linked epoch inherits the preceding epoch’s cursor and final hash.

    Every persisted schema-1 column contributes to the row digest, including generated ids, timestamp, xid and the stored byte estimate. JSONB numbers retain exact decimal tokens; SQL integers, UUIDs, bytea, SQL NULL and timestamp microseconds use their own canonical types. Transport JSON text is never hashed as the row encoding.

    This component is an owner-side library operation. The erp audit seal command, configuration and commit-to-witness recovery are planned; row verification is described in the next section. Retention and the audit-log serving UI retain their separate obligations.

    Verify the chain against a witness inventory

    Section titled “Verify the chain against a witness inventory”

    Transaction::verify_audit_chain(&VerifyScope, &WitnessEvidence) re-reads rows, seals and epoch links and recomputes every digest and seal hash. Use an owner System/full transaction opened with REPEATABLE READ (one snapshot for the whole walk; Read Committed is refused). It writes nothing and takes no lock, so a running sealer never blocks it.

    WitnessEvidence::NotConfigured means no witness; WitnessEvidence::Inventory takes an AnchorInventory built from anchors your witness returned (at most 65,536; identical duplicates collapse; two anchors for one identity with different hashes are refused at construction). VerifyScope::full() walks everything; VerifyScope::range(epoch, first, last) verifies inclusive batches of one epoch, checks the stored predecessor boundary, compares anchors inside that range only, and marks the report partial.

    The result is a value, not an error: VerifyOutcome::Failed(VerifyFailure) names the first defect in (epoch, batch_no) order (FailurePoint plus a stable VerifyProblem; no row payload). It covers changed or deleted rows, edited seal columns, broken links, a missing anchored seal (deleted middle seal, suffix or epoch), a hash that differs from its anchor, anchors of another incarnation and anchors with no chain. Err only means the verifier could not run (not System/full, wrong isolation, catalog drift, SQL failure).

    VerifyReport::assurance() states what the success means. NoWitness and NoAnchors are internal consistency only. AnchoredThrough { epoch, batch_no } is the last anchored seal; the chain links cover every earlier seal. Seals after it (unanchored_tail) and rows after the head’s last cursor (unsealed_tail, full scope only) are counted with their create_date bounds in UTC microseconds and are not verified. Deleting seals from the end cannot be seen without an anchor for them. The erp audit verify command and its exit codes are planned.

    The accounting policy records AuthEvent::AccountLockDateChanged through the same transaction buffer. Its validated payload contains a positive company id, an exhaustive AccountLockField, and old/new optional dates encoded as integer days since 1970. Actor and time come from the existing row attribution and database timestamp. No free-text reason or arbitrary JSON is accepted.

    A no-op emits no event. Savepoint rollback drops the event describing the rolled-back mutation; a failed audit INSERT rolls back the company date and fiscal-period changes. This does not widen the audit reader’s permitted projection fields or expose event payloads through its existing API.