Skip to content

audit_trail.integrity

Tamper evidence for the audit log.

With AuditTrail(integrity=Integrity()) every audit row carries its PostgreSQL transaction id (xid) and salted commitments to the parts of the entry that scrubbing may erase. A sealer job (maintenance.seal()) hashes the rows of finished transactions into blocks chained by hash, in the block table; drop_expired appends a retire block before it drops a partition, and scrub/scrub_actor delete the salt of each erased part and stamp it with the scrub's own xid. verify walks the chain, rebuilds every block from the rows it can still read and reports every break. export_checkpoint gives a signed statement of the head of the chain to keep where the database cannot reach it; prepare_checkpoint and record_checkpoint do the same in two steps, so that signing holds no lock or transaction. A KeyHistory says from which block on each key may no longer sign. erasure_journal lists the scrubs since a point, for a checkpoint to commit to, and reapply_erasures erases those rows again after a restore brought them back. export_bundle writes a range of the chain and the rows it seals to one file, and verify_bundle checks it without the database, also from the command line: python -m audit_trail.integrity verify-bundle.

This makes the log tamper-evident, not tamper-proof: a change is detected, not prevented, and what verification can detect depends on where the checkpoints and signing keys are kept. See the integrity guide.

The reference signers are in audit_trail.integrity.ed25519 (Ed25519) and audit_trail.integrity.ecdsa (ECDSA P-256), and audit_trail.integrity.keys checks keys of both; they need the sqlalchemy-audit-trail[integrity] extra, and nothing else here does.

ACKNOWLEDGEABLE module-attribute

ACKNOWLEDGEABLE: frozenset[FailureKind] = frozenset(
    {
        FailureKind.ROOT_MISMATCH,
        FailureKind.ROW_COUNT_MISMATCH,
        FailureKind.COMMITMENT_MISMATCH,
        FailureKind.COMMITMENT_MISSING,
        FailureKind.ERASURE_UNEXPLAINED,
        FailureKind.SCRUB_COUNT_MISMATCH,
        FailureKind.SEGMENT_MISSING,
        FailureKind.RETIRED_EARLY,
        FailureKind.DETACHED_PARTITION,
    }
)

Failures an ack block can waive: those about rows and partitions. A broken chain cannot be waived from inside it.

SCOPE_KEYS module-attribute

SCOPE_KEYS: frozenset[str] = frozenset(
    {
        "table",
        "partition",
        "stream",
        "seq",
        "group",
        "id",
        "xid",
        "xid_from",
        "xid_to",
        "id_from",
        "id_to",
    }
)

Keys of an ack's scope. table, partition, stream and group are text, the others integers; xid_from/xid_to and id_from/id_to are [from, to) ranges. A finding matches when it has every field the scope names, with a matching value.

Integrity dataclass

Integrity()

Integrity settings of the processes that write audit entries.

With AuditTrail(integrity=Integrity()) the audit tables declare the integrity columns, and every write stores the row's transaction id (the column default) and salted commitments to its erasable parts. The tables need those columns: migrations.add_integrity adds them to an existing install. There are no settings yet.

CheckpointRefusedError

CheckpointRefusedError(
    message: str, report: VerificationReport
)

Bases: ValueError

prepare_checkpoint would not prepare a statement.

Attributes:

Name Type Description
report

The verification that has failures, or whose head is no longer in the chain.

Source code in audit_trail/integrity/_anchor.py
def __init__(self, message: str, report: VerificationReport) -> None:
    super().__init__(message)
    self.report = report

Fork dataclass

Fork(
    seq: int,
    incarnation: int,
    closing_seq: int | None,
    xid_at_fork: int,
    id_floor: dict[str, int] | None,
    id_count: dict[str, int] | None,
)

What declare_fork wrote.

Attributes:

Name Type Description
seq int

The fork block.

incarnation int

The incarnation it starts.

closing_seq int | None

The closing seal block of the old incarnation; None when nothing was left to seal.

xid_at_fork int

Where the new incarnation's seal blocks start.

id_floor dict[str, int] | None

Highest id of each stream at the fork, None without an id window.

id_count dict[str, int] | None

Rows of each stream at or below it.

RecordedCheckpoint dataclass

RecordedCheckpoint(
    seq: int, checkpoint: Checkpoint, created: bool
)

What record_checkpoint stored.

Attributes:

Name Type Description
seq int

The checkpoint block that holds the note.

checkpoint Checkpoint

The checkpoint, with its signatures.

created bool

False when the same note was recorded before, and this is the block that holds it.

ReplicationError

ReplicationError(
    reason: ReplicationProblem,
    message: str,
    *,
    seq: int,
    lsn: str,
)

Bases: Exception

The checkpoint block was not confirmed by the synchronous standbys.

The block is in the chain already; no checkpoint was returned. A later export, once the standbys are back, writes a new one.

Attributes:

Name Type Description
reason ReplicationProblem

NO_SYNC_STANDBY: synchronous_standby_names is empty, or pg_stat_replication lists fewer standbys with sync_state sync (FIRST n) or quorum (ANY n) than it asks for, for longer than a grace of two seconds (capped by replication_timeout), or the role cannot see them (reading the view needs pg_monitor). An empty setting raises at once. NOT_REPLICATED: they are listed, but not as many as it asks for flushed the block's WAL within the timeout; or the block's COMMIT, waiting for them under synchronous_commit, was cut off (its backend was terminated) after the block was written. CHECK_FAILED: reading the WAL position or the standbys failed, or such a cut-off COMMIT could not be checked; the cause is chained.

seq

The checkpoint block.

lsn

The WAL position the standbys had to reach; empty when reading it failed.

Source code in audit_trail/integrity/_anchor.py
def __init__(
    self, reason: ReplicationProblem, message: str, *, seq: int, lsn: str
) -> None:
    super().__init__(f"{reason}: {message}")
    self.reason: ReplicationProblem = reason
    self.seq = seq
    self.lsn = lsn

BlockRange dataclass

BlockRange(first: int, last: int)

A scope of blocks by seq, both ends included.

Raises:

Type Description
ValueError

An end is not an integer of at least 1, or last is below first.

BundleResult dataclass

BundleResult(
    first: int,
    last: int,
    previous: int | None,
    rows: int,
    scrub_records: int,
    checkpoints: int,
    files: dict[str, str],
    manifest: str,
)

What export_bundle wrote.

Attributes:

Name Type Description
first int

The first block in scope.

last int

The last block in scope.

previous int | None

The block before first that the bundle also holds; None when first is the genesis block.

rows int

Rows in rows.jsonl.

scrub_records int

Records in scrubs.jsonl.

checkpoints int

Checkpoints in checkpoints.jsonl.

files dict[str, str]

The SHA-256 of every entry the manifest lists, as hex, by name.

manifest str

The manifest note, signed when a signer was given.

TimeRange dataclass

TimeRange(start: datetime, end: datetime)

A scope by time: the blocks written in [start, end).

A block is in it when its sealed_at is. Rows are sealed after they are written, so the first block may hold a few rows written just before start, and rows written just before end may be sealed by a block after it. sealed_at is not hashed: a reader of the bundle can check that its blocks are an unbroken range of the chain, not that they were written in the time range.

Raises:

Type Description
ValueError

A timestamp is naive, or end is not after start.

BundleError

Bases: ValueError

A bundle that cannot be read as one.

Not a zip file, an entry missing or out of order, a line that is not JSON of the format, or entries that contradict each other. The message names the entry and the line, never a stored value. A bundle that reads but does not match its chain is not an error: verify_bundle reports that as findings.

CanonicalEncodingError

Bases: ValueError

A value has no canonical encoding.

The message names the problem, never the value, which may be personal data.

Checkpoint dataclass

Checkpoint(
    chain: str,
    seq: int,
    block_hash: bytes,
    xid_to: int,
    sealed_at: datetime,
    incarnation: int = 1,
    signatures: tuple[NoteSignature, ...] = (),
    extensions: tuple[str, ...] = (),
    journal: bytes | None = None,
)

A checkpoint of the chain.

Attributes:

Name Type Description
chain str

The chain id.

seq int

The block it names, a checkpoint block when exported.

block_hash bytes

That block's hash.

xid_to int

The xid the chain was sealed up to (exclusive) then.

sealed_at datetime

When the block was written, as the database had it.

incarnation int

The incarnation of the chain then: 1 before any fork, then the number of the newest fork block's.

signatures tuple[NoteSignature, ...]

The note's signature lines; empty when unsigned.

extensions tuple[str, ...]

The application's lines after the statement, signed with it, in order; see export_checkpoint's extensions for what a line may hold.

journal bytes | None

The commitment of an erasure journal (ErasureJournal.commitment), 32 bytes; None for a checkpoint without one, written as a version 1 statement.

Raises:

Type Description
ValueError

An extension line is not valid, or journal is not 32 bytes.

text property

text: str

The note text: the statement, then the extension lines.

note property

note: Note

The checkpoint as a note.

to_note

to_note() -> str

The signed note to store; the text alone when unsigned.

Source code in audit_trail/integrity/_checkpoint.py
def to_note(self) -> str:
    """The signed note to store; the text alone when unsigned."""
    return str(self.note)

signed

signed(signers: Iterable[Signer]) -> Checkpoint

The checkpoint with a signature by each of signers added.

Source code in audit_trail/integrity/_checkpoint.py
def signed(self, signers: Iterable[Signer]) -> Checkpoint:
    """The checkpoint with a signature by each of ``signers`` added."""
    note = add_signatures(self.note, signers)
    return _replace_signatures(self, note.signatures)

verify

verify(verifier: SignatureVerifier) -> list[str]

Check the signatures; the key_id of each that verified.

Raises:

Type Description
NoteError

BAD_SIGNATURE or UNKNOWN_KEY.

Source code in audit_trail/integrity/_checkpoint.py
def verify(self, verifier: SignatureVerifier) -> list[str]:
    """Check the signatures; the ``key_id`` of each that verified.

    Raises:
        NoteError: ``BAD_SIGNATURE`` or ``UNKNOWN_KEY``.
    """
    return verify_note(self.note, verifier)

from_note classmethod

from_note(note: str) -> Checkpoint

Read a checkpoint back from to_note.

Signatures are read, not checked; verify checks them, with the keys trusted for it.

Raises:

Type Description
NoteError

MALFORMED: not a note, its statement is not one of a known version, or an extension line is one no version could write (check_extension(..., reading=True)).

Source code in audit_trail/integrity/_checkpoint.py
@classmethod
def from_note(cls, note: str) -> Checkpoint:
    """Read a checkpoint back from ``to_note``.

    Signatures are read, not checked; ``verify`` checks them, with the
    keys trusted for it.

    Raises:
        NoteError: ``MALFORMED``: not a note, its statement is not one of
            a known version, or an extension line is one no version
            could write (``check_extension(..., reading=True)``).
    """
    parsed = parse_note(note)
    lines = parsed.text[:-1].split("\n")
    reader = _VERSIONS.get(lines[0])
    if reader is None:
        raise _malformed("the first line is not a known statement version")
    size, read = reader
    if len(lines) < size:
        raise _malformed("the statement is cut short")
    extensions = tuple(lines[size:])
    try:
        statement = read(lines[:size])
        for line in extensions:
            check_extension(line, reading=True)
    except ValueError as exc:
        if isinstance(exc, NoteError):
            raise
        raise _malformed(str(exc)) from None
    checkpoint = _unchecked(statement, extensions=extensions)
    if checkpoint.text != parsed.text:
        raise NoteError("MALFORMED", "the checkpoint statement is not canonical")
    return _replace_signatures(checkpoint, parsed.signatures)

KeyHistory

KeyHistory(windows: Mapping[str, KeyWindow])

The window of every signing key, by key_id.

A signature by a key the history does not name does not count either: give every key the verifier knows a window.

A window limits which blocks a key may attest, not when it signed: a checkpoint signature is judged at the seq the checkpoint names, so whoever holds a key can still sign a statement naming an earlier block inside its window. Drop a compromised key from the verifier used for newly received checkpoints (record_checkpoint).

Parameters:

Name Type Description Default
windows Mapping[str, KeyWindow]

key_id (name+hash, as Signer.key_id gives it) to its window.

required

Raises:

Type Description
ValueError

A key id is empty or a window is not a KeyWindow.

Source code in audit_trail/integrity/_history.py
def __init__(self, windows: Mapping[str, KeyWindow]) -> None:
    checked: dict[str, KeyWindow] = {}
    for key_id, window in windows.items():
        if not isinstance(key_id, str) or not key_id:
            raise ValueError("a key id is non-empty text")
        if not isinstance(window, KeyWindow):
            raise ValueError(f"the window of {key_id} is not a KeyWindow")
        checked[key_id] = window
    self._windows = checked

windows property

windows: dict[str, KeyWindow]

The windows, by key_id; a copy.

from_vkeys classmethod

from_vkeys(vkeys: Iterable[str]) -> KeyHistory

The history of keys that were never rotated: each verifier key may sign from block 1 on, with no end.

For one key, or keys none of which was retired or compromised; give it the same verifier keys as the verifier. Once a key is rotated out, build the history with its window instead.

Parameters:

Name Type Description Default
vkeys Iterable[str]

The verifier keys, as Ed25519Signer.vkey and EcdsaP256Signer.vkey give them.

required

Raises:

Type Description
ValueError

A key is not a verifier key.

Source code in audit_trail/integrity/_history.py
@classmethod
def from_vkeys(cls, vkeys: Iterable[str]) -> KeyHistory:
    """The history of keys that were never rotated: each verifier key
    may sign from block 1 on, with no end.

    For one key, or keys none of which was retired or compromised; give
    it the same verifier keys as the verifier. Once a key is rotated
    out, build the history with its window instead.

    Args:
        vkeys: The verifier keys, as ``Ed25519Signer.vkey`` and
            ``EcdsaP256Signer.vkey`` give them.

    Raises:
        ValueError: A key is not a verifier key.
    """
    windows: dict[str, KeyWindow] = {}
    for vkey in vkeys:
        if not isinstance(vkey, str):
            raise ValueError("a verifier key is text")
        key = parse_vkey(vkey, f"{vkey!r} is not a verifier key")
        windows[key.key_id] = KeyWindow()
    return cls(windows)

to_json

to_json() -> str

The history as JSON text, for a file kept with the keys.

{key_id: {"valid_from": n, "retired_at": n | null, "compromised_from": n | null}}, canonically encoded: the form the command line's --key-history file holds, and history in a bundle's keys.json. from_json reads it back.

Source code in audit_trail/integrity/_history.py
def to_json(self) -> str:
    """The history as JSON text, for a file kept with the keys.

    ``{key_id: {"valid_from": n, "retired_at": n | null,
    "compromised_from": n | null}}``, canonically encoded: the form the
    command line's ``--key-history`` file holds, and ``history`` in a
    bundle's ``keys.json``. ``from_json`` reads it back.
    """
    return canonical(history_to_mapping(self)).decode("utf-8")

from_json classmethod

from_json(text: str) -> KeyHistory

Read a history back from to_json, or a key history file.

The text need not be canonical: a file written by hand reads too. A window may leave out a field, which then takes its default.

Parameters:

Name Type Description Default
text str

The JSON text, as to_json gives it.

required

Raises:

Type Description
ValueError

The text is not JSON (the JSON error is the cause), is not the form to_json writes, or a window is not valid.

Source code in audit_trail/integrity/_history.py
@classmethod
def from_json(cls, text: str) -> KeyHistory:
    """Read a history back from ``to_json``, or a key history file.

    The text need not be canonical: a file written by hand reads too. A
    window may leave out a field, which then takes its default.

    Args:
        text: The JSON text, as ``to_json`` gives it.

    Raises:
        ValueError: The text is not JSON (the JSON error is the cause),
            is not the form ``to_json`` writes, or a window is not valid.
    """
    try:
        value = json.loads(text)
    except (ValueError, RecursionError) as exc:
        raise ValueError("a key history is JSON text") from exc
    return history_from_mapping(value)

check

check(
    key_id: str, position: int
) -> tuple[KeyProblem, str] | None

Why key_id's signature at position does not count, and a sentence saying so; None when it counts.

Source code in audit_trail/integrity/_history.py
def check(self, key_id: str, position: int) -> tuple[KeyProblem, str] | None:
    """Why ``key_id``'s signature at ``position`` does not count, and a
    sentence saying so; ``None`` when it counts."""
    window = self._windows.get(key_id)
    if window is None:
        return KeyProblem.NOT_VALID, f"the key history has no window for {key_id}"
    problem = window.problem(position)
    if problem is KeyProblem.COMPROMISED:
        return problem, (
            f"{key_id} is compromised from block {window.compromised_from}; "
            f"this signature is at {position}"
        )
    if problem is KeyProblem.NOT_VALID:
        end = "" if window.retired_at is None else f" to {window.retired_at}"
        return problem, (
            f"{key_id} may sign from block {window.valid_from}{end}; this "
            f"signature is at {position}"
        )
    return None

KeyWindow dataclass

KeyWindow(
    valid_from: int = 1,
    retired_at: int | None = None,
    compromised_from: int | None = None,
)

The blocks one key may sign.

Attributes:

Name Type Description
valid_from int

The first seq the key may sign.

retired_at int | None

The first seq it may no longer sign, after a planned rotation; None while it is in use.

compromised_from int | None

The first seq from which its signatures are not trusted, because someone else may hold it; None when it is not known to be compromised. Signatures below it still count.

Raises:

Type Description
ValueError

A position is not an integer of at least 1, or retired_at is below valid_from.

problem

problem(position: int) -> KeyProblem | None

Why a signature at position does not count; None if it does.

Source code in audit_trail/integrity/_history.py
def problem(self, position: int) -> KeyProblem | None:
    """Why a signature at ``position`` does not count; ``None`` if it does."""
    if self.compromised_from is not None and position >= self.compromised_from:
        return KeyProblem.COMPROMISED
    if position < self.valid_from or (
        self.retired_at is not None and position >= self.retired_at
    ):
        return KeyProblem.NOT_VALID
    return None

ErasedRow dataclass

ErasedRow(
    table: str,
    id: int,
    xid: int,
    groups: tuple[str, ...],
    seq: int | None,
    leaf: bytes,
)

One row a scrub erased.

Attributes:

Name Type Description
table str

activity or transaction.

id int

The row's id.

xid int

The row's xid.

groups tuple[str, ...]

The groups the scrub erased, sorted.

seq int | None

The seal block that held the row when the journal was built; None when it was not sealed yet.

leaf bytes

The leaf hash of the row's sealed fields.

Erasure dataclass

Erasure(
    xid: int,
    erased_at: datetime,
    severity: int,
    reasons: tuple[str, ...] = (),
    rows: tuple[ErasedRow, ...] = (),
    uncommitted: tuple[UncommittedRow, ...] = (),
)

One scrub: the rows its transaction erased.

Attributes:

Name Type Description
xid int

The scrub's transaction id, which its stamps carry.

erased_at datetime

created_at of its audit.scrubbed record.

severity int

The severity of that record.

reasons tuple[str, ...]

The reason codes its records give, sorted; for a scrub that re-applied another, the original one's (reapplies).

rows tuple[ErasedRow, ...]

The rows it erased and stamped, by table and id.

uncommitted tuple[UncommittedRow, ...]

The rows it erased that carry no commitments, as its records list them, by table and id.

ErasureJournal dataclass

ErasureJournal(
    chain: str,
    since: datetime | None,
    blocks: tuple[tuple[int, bytes], ...],
    erasures: tuple[Erasure, ...],
    version: int = JOURNAL_VERSION,
)

The scrubs since a point, as erasure_journal builds them.

Attributes:

Name Type Description
chain str

The chain id.

since datetime | None

Only scrubs recorded at or after this; None for all.

blocks tuple[tuple[int, bytes], ...]

(seq, block_hash) of the genesis block and of every block a row names, sorted: what the chain held when the journal was built.

erasures tuple[Erasure, ...]

The scrubs, by xid.

version int

The canonical form: 2, or 1 for a journal 0.5.0 wrote, which lists no uncommitted rows.

Raises:

Type Description
ValueError

A row names a block blocks does not state, a version 1 journal lists uncommitted rows, or a field is invalid.

rows property

rows: int

The number of rows the journal names, with commitments or without.

commitment property

commitment: bytes

The SHA-256 commitment a version 2 checkpoint statement states.

to_json

to_json() -> str

The canonical form, the text to keep with the checkpoint.

Source code in audit_trail/integrity/_journal.py
def to_json(self) -> str:
    """The canonical form, the text to keep with the checkpoint."""
    return self._canonical().decode()

from_json classmethod

from_json(text: str) -> ErasureJournal

Read a journal back from to_json, of either version.

Raises:

Type Description
ValueError

The text is not a journal in its canonical form.

Source code in audit_trail/integrity/_journal.py
@classmethod
def from_json(cls, text: str) -> ErasureJournal:
    """Read a journal back from ``to_json``, of either version.

    Raises:
        ValueError: The text is not a journal in its canonical form.
    """
    try:
        value: Any = json.loads(text)
        journal = _journal(value)
    except (ValueError, TypeError, KeyError, AttributeError) as exc:
        raise ValueError(f"not an erasure journal: {exc}") from None
    if journal.to_json() != text:
        raise ValueError("not an erasure journal: the text is not canonical")
    return journal

JournalRefusedError

Bases: ValueError

reapply_erasures does not trust the journal; nothing was changed.

ReappliedErasures dataclass

ReappliedErasures(
    shared_to: int,
    activity_rows: int = 0,
    transaction_rows: int = 0,
    already_erased: int = 0,
    outside: tuple[JournalRow, ...] = (),
    missing: tuple[JournalRow, ...] = (),
    mismatched: tuple[JournalRow, ...] = (),
    unproven: tuple[ErasedRow, ...] = (),
    uncommitted: tuple[UncommittedRow, ...] = (),
)

What reapply_erasures did.

Attributes:

Name Type Description
shared_to int

The newest block the checkpoint proves this chain shares with the one it was taken of.

activity_rows int

audit_activity rows changed; a row erased by both a scrub and a scrub_actor counts once for each.

transaction_rows int

audit_transaction rows changed.

already_erased int

Rows whose groups were stamped already (or, for a row without commitments, are in erased form already), left alone.

outside tuple[JournalRow, ...]

Rows nothing in the chain proves are the ones the scrub erased, left alone: rows not sealed within the shared prefix, without include_unproven, and rows without commitments (UncommittedRow), without include_uncommitted.

missing tuple[JournalRow, ...]

Rows the database no longer has, such as rows of a dropped partition.

mismatched tuple[JournalRow, ...]

Rows that are no longer the row the journal names, left alone: another xid or leaf hash, for an unproven row a value that no longer matches its commitment, and for a row without commitments another xid, or commitments now. Within the shared prefix verify reports them too.

unproven tuple[ErasedRow, ...]

Rows outside the shared prefix that include_unproven selected for re-erasure after the checks. The counts are what the updates changed; the two agree when one run goes at a time, as the restore procedure has it, but a run that overlaps another can list a row here that the other one erased first.

uncommitted tuple[UncommittedRow, ...]

Rows without commitments that include_uncommitted selected for re-erasure after the checks, as for unproven.

UncommittedRow dataclass

UncommittedRow(
    table: str,
    id: int,
    xid: int | None,
    groups: tuple[str, ...],
)

One row a scrub erased that carries no commitments.

Written before integrity was added, or by a writer without it: the scrub could not stamp it, and its record lists it instead. Nothing in the chain attests it, so the journal names it by id and xid only.

Attributes:

Name Type Description
table str

activity or transaction.

id int

The row's id.

xid int | None

The row's xid; None for a row written before the column existed.

groups tuple[str, ...]

The groups the scrub erased, sorted.

NoteError

NoteError(
    reason: Literal[
        "MALFORMED", "BAD_SIGNATURE", "UNKNOWN_KEY"
    ],
    message: str,
)

Bases: ValueError

A note that is not a well-formed signed note, or that fails to verify.

Attributes:

Name Type Description
reason

MALFORMED: not in the format. BAD_SIGNATURE: a signature of a known key does not verify. UNKNOWN_KEY: no signature is from a known key (or there is none).

Source code in audit_trail/integrity/_note.py
def __init__(
    self, reason: Literal["MALFORMED", "BAD_SIGNATURE", "UNKNOWN_KEY"], message: str
) -> None:
    super().__init__(f"{reason}: {message}")
    self.reason = reason

Genesis dataclass

Genesis(chain: str, enforce_from: int, created: bool)

The genesis block of a chain.

Attributes:

Name Type Description
chain str

The chain id, a UUID as text.

enforce_from int

Rows with a lower xid are out of scope.

created bool

Whether this call wrote it.

SealHealth dataclass

SealHealth(
    started: bool,
    sealed_to: int | None,
    last_sealed_at: datetime | None,
    unsealed_rows: int,
    seal_lag: timedelta | None,
    max_seal_lag: timedelta,
    prepared: list[str] = list(),
    problem: str | None = None,
)

How far the sealer is behind.

Attributes:

Name Type Description
started bool

Whether the chain has a genesis block.

sealed_to int | None

The xid the chain is sealed up to (exclusive).

last_sealed_at datetime | None

When the block holding sealed_to was written.

unsealed_rows int

Committed rows at or above sealed_to, counted up to UNSEALED_ROWS_CAP.

seal_lag timedelta | None

Age of the unsealed entry with the lowest xid in each table, the older of the two, None when there is none. Age is measured from the entry's own time (issued_at, created_at), not from its commit, so a transaction that ran longer than max_seal_lag is flagged briefly once it commits, until the next seal.

max_seal_lag timedelta

The threshold the report was made with.

prepared list[str]

Global ids of prepared transactions in this database older than max_seal_lag. Each holds the horizon back until it is committed or rolled back, so sealing stalls behind it.

problem str | None

Why the chain is not started, naming the step to run: migrations.add_integrity() when the block table does not exist, migrations.write_genesis() when it has no genesis block; else None.

ok property

ok: bool

Whether the chain is started, not lagging and not held back.

SealRefusedError

SealRefusedError(reason: SealRefusal, message: str)

Bases: Exception

The sealer refused to seal, and changed nothing.

Attributes:

Name Type Description
reason SealRefusal

XID_REWIND: the horizon is below the last sealed one, or a row of the current incarnation has an xid that no transaction has had yet, so the database was restored from a dump or is a logical replica, and its transaction ids repeat stored ones. NO_GENESIS: the chain has not been started with write_genesis. ID_FLOOR_VIOLATION: after a fork with an id window, an identity sequence is behind the floor, or a stream has more rows at or below the floor than the fork counted: new rows got ids of the restored ones (ALTER ... RESTART, or a data-only restore without the sequence values) and would never be sealed.

Source code in audit_trail/integrity/_seal.py
def __init__(self, reason: SealRefusal, message: str) -> None:
    super().__init__(f"{reason}: {message}")
    self.reason: SealRefusal = reason

SealResult dataclass

SealResult(
    blocks: int,
    rows: int,
    horizon: int | None,
    capped: bool = False,
    skipped: Literal["standby", "subscriber", "busy"]
    | None = None,
)

What one seal call did.

Attributes:

Name Type Description
blocks int

Blocks written, 0 or 1.

rows int

Rows sealed into the block.

horizon int | None

The xid the chain is sealed up to (exclusive) after the call; None when the call was skipped.

capped bool

max_rows cut the block short and finished rows remain unsealed; call again.

skipped Literal['standby', 'subscriber', 'busy'] | None

Why nothing was attempted: "standby" (the server is in recovery), "subscriber" (a logical-replication subscription writes into the block table, so the publisher seals) or "busy" (another sealer holds the lock).

SignatureVerifier

Bases: Protocol

Checks signatures made by known keys.

key_algorithm

key_algorithm(key_id: str) -> str | None

The algorithm of a known key; None for an unknown one.

Source code in audit_trail/integrity/_sign.py
def key_algorithm(self, key_id: str) -> str | None:
    """The algorithm of a known key; ``None`` for an unknown one."""
    ...

verify

verify(
    key_id: str,
    algorithm: str,
    message: bytes,
    signature: bytes,
) -> bool

Whether signature is the signature of message by the key.

Source code in audit_trail/integrity/_sign.py
def verify(
    self, key_id: str, algorithm: str, message: bytes, signature: bytes
) -> bool:
    """Whether ``signature`` is the signature of ``message`` by the key."""
    ...

Signer

Bases: Protocol

Signs blocks and checkpoints.

Attributes:

Name Type Description
key_id str

<key name>+<8 hex digits of the key hash>; see the module documentation. Stored with every block it signs.

algorithm str

Name of the signature algorithm, such as "ed25519".

sign

sign(message: bytes) -> bytes

The signature of message, without the key hash.

Source code in audit_trail/integrity/_sign.py
def sign(self, message: bytes) -> bytes:
    """The signature of ``message``, without the key hash."""
    ...

Anchor

Bases: StrEnum

Whether the chain was checked against a trusted checkpoint.

FailureKind

Bases: StrEnum

What can make a verification fail; a closed set.

Finding dataclass

Finding(
    kind: FailureKind | NoteKind,
    detail: str,
    seq: int | None = None,
    table: str | None = None,
    partition: str | None = None,
    stream: str | None = None,
    id: int | None = None,
    xid: int | None = None,
    group: str | None = None,
    count: int | None = None,
    root: str | None = None,
    waived: FailureKind | None = None,
    ack: int | None = None,
)

One failure or note.

Attributes:

Name Type Description
kind FailureKind | NoteKind

What was found.

detail str

A sentence for people; never a stored value or a salt.

seq int | None

The block it concerns.

table str | None

"transaction" or "activity".

partition str | None

Name of the partition, without schema.

stream str | None

The segment's stream.

id int | None

The row's id.

xid int | None

The row's xid, or the scrub's for a count.

group str | None

The erasable group.

count int | None

How many rows a note or a count covers.

root str | None

For a root or row count mismatch, the root rebuilt from the rows, base64; a hash of leaves, never a value.

waived FailureKind | None

For an ACKNOWLEDGED note, the failure it stands for.

ack int | None

For an ACKNOWLEDGED note, the seq of the ack block.

NoteKind

Bases: StrEnum

What a verification notes without failing.

Status

Bases: StrEnum

Overall result of a verification.

VerificationReport dataclass

VerificationReport(
    status: Status,
    anchor: Anchor,
    verified_to: int | None,
    failures: list[Finding],
    notes: list[Finding],
    head: Checkpoint | None = None,
    since: int | None = None,
)

What verify found.

Attributes:

Name Type Description
status Status

FAILED with any failure, else VALID_WITH_NOTES with any note, else VALID.

anchor Anchor

UNANCHORED until checkpoints exist.

verified_to int | None

seq of the last block checked.

failures list[Finding]

Every failure, in the order found.

notes list[Finding]

Every note, acknowledged failures included.

head Checkpoint | None

The last block checked, as an unsigned checkpoint statement: the chain, its seq and hash, and the sealed horizon, time and incarnation then. Keep the report to pass it to prepare_checkpoint(verified=...) or verify(since=...).

since int | None

The seq of the earlier report's head when this run compared only the rows after it (verify(since=...)); None for a full run.

kinds

kinds() -> set[FailureKind | NoteKind]

The kinds of every failure and note.

Source code in audit_trail/integrity/_verify.py
def kinds(self) -> set[FailureKind | NoteKind]:
    """The kinds of every failure and note."""
    return {finding.kind for finding in (*self.failures, *self.notes)}

adeclare_fork async

adeclare_fork(
    connection: AsyncConnection,
    tables: AuditTables,
    last_good_checkpoint: Checkpoint | str,
    *,
    reason: str,
    signer: Signer | None = None,
    id_window: bool | None = None,
) -> Fork

Async declare_fork, on an AsyncConnection; the same arguments.

Raises:

Type Description
ValueError

As declare_fork.

SealRefusedError

As declare_fork.

Source code in audit_trail/integrity/_anchor.py
async def adeclare_fork(
    connection: AsyncConnection,
    tables: AuditTables,
    last_good_checkpoint: Checkpoint | str,
    *,
    reason: str,
    signer: Signer | None = None,
    id_window: bool | None = None,
) -> Fork:
    """Async ``declare_fork``, on an ``AsyncConnection``; the same arguments.

    Raises:
        ValueError: As ``declare_fork``.
        SealRefusedError: As ``declare_fork``.
    """
    return await connection.run_sync(
        lambda sync_conn: declare_fork(
            sync_conn,
            tables,
            last_good_checkpoint,
            reason=reason,
            signer=signer,
            id_window=id_window,
        )
    )

aexport_checkpoint async

aexport_checkpoint(
    connection: AsyncConnection,
    tables: AuditTables,
    *,
    signer: Signer | None = None,
    require_replicated: bool = False,
    replication_timeout: timedelta = DEFAULT_REPLICATION_TIMEOUT,
    extensions: Iterable[str] = (),
    journal: ErasureJournal | None = None,
) -> Checkpoint

Async export_checkpoint, on an AsyncConnection; the same arguments.

Runs export_checkpoint through run_sync, so signer runs on the event loop: for a signer that waits (a person, a remote service), use aprepare_checkpoint and arecord_checkpoint.

Raises:

Type Description
ValueError

As export_checkpoint.

SealRefusedError

As export_checkpoint.

ReplicationError

As export_checkpoint.

Source code in audit_trail/integrity/_anchor.py
async def aexport_checkpoint(
    connection: AsyncConnection,
    tables: AuditTables,
    *,
    signer: Signer | None = None,
    require_replicated: bool = False,
    replication_timeout: timedelta = DEFAULT_REPLICATION_TIMEOUT,
    extensions: Iterable[str] = (),
    journal: ErasureJournal | None = None,
) -> Checkpoint:
    """Async ``export_checkpoint``, on an ``AsyncConnection``; the same arguments.

    Runs ``export_checkpoint`` through ``run_sync``, so ``signer`` runs on
    the event loop: for a signer that waits (a person, a remote service),
    use ``aprepare_checkpoint`` and ``arecord_checkpoint``.

    Raises:
        ValueError: As ``export_checkpoint``.
        SealRefusedError: As ``export_checkpoint``.
        ReplicationError: As ``export_checkpoint``.
    """
    return await connection.run_sync(
        lambda sync_conn: export_checkpoint(
            sync_conn,
            tables,
            signer=signer,
            require_replicated=require_replicated,
            replication_timeout=replication_timeout,
            extensions=extensions,
            journal=journal,
        )
    )

aprepare_checkpoint async

aprepare_checkpoint(
    connection: AsyncConnection,
    tables: AuditTables,
    *,
    verify: Mapping[str, Any] | None = None,
    verified: VerificationReport | None = None,
    extensions: Iterable[str] = (),
    journal: ErasureJournal | None = None,
) -> Checkpoint

Async prepare_checkpoint, on an AsyncConnection; the same arguments.

Raises:

Type Description
CheckpointRefusedError

As prepare_checkpoint.

ValueError

As prepare_checkpoint.

Source code in audit_trail/integrity/_anchor.py
async def aprepare_checkpoint(
    connection: AsyncConnection,
    tables: AuditTables,
    *,
    verify: Mapping[str, Any] | None = None,
    verified: VerificationReport | None = None,
    extensions: Iterable[str] = (),
    journal: ErasureJournal | None = None,
) -> Checkpoint:
    """Async ``prepare_checkpoint``, on an ``AsyncConnection``; the same arguments.

    Raises:
        CheckpointRefusedError: As ``prepare_checkpoint``.
        ValueError: As ``prepare_checkpoint``.
    """
    return await connection.run_sync(
        lambda sync_conn: prepare_checkpoint(
            sync_conn,
            tables,
            verify=verify,
            verified=verified,
            extensions=extensions,
            journal=journal,
        )
    )

arecord_checkpoint async

arecord_checkpoint(
    connection: AsyncConnection,
    tables: AuditTables,
    note: Checkpoint | str,
    *,
    verifier: SignatureVerifier,
    key_history: KeyHistory | None = None,
    signer: Signer | None = None,
) -> RecordedCheckpoint

Async record_checkpoint, on an AsyncConnection; the same arguments.

Raises:

Type Description
NoteError

As record_checkpoint.

ValueError

As record_checkpoint.

OperationalError

As record_checkpoint.

Source code in audit_trail/integrity/_anchor.py
async def arecord_checkpoint(
    connection: AsyncConnection,
    tables: AuditTables,
    note: Checkpoint | str,
    *,
    verifier: SignatureVerifier,
    key_history: KeyHistory | None = None,
    signer: Signer | None = None,
) -> RecordedCheckpoint:
    """Async ``record_checkpoint``, on an ``AsyncConnection``; the same arguments.

    Raises:
        NoteError: As ``record_checkpoint``.
        ValueError: As ``record_checkpoint``.
        OperationalError: As ``record_checkpoint``.
    """
    return await connection.run_sync(
        lambda sync_conn: record_checkpoint(
            sync_conn,
            tables,
            note,
            verifier=verifier,
            key_history=key_history,
            signer=signer,
        )
    )

declare_fork

declare_fork(
    connection: Connection,
    tables: AuditTables,
    last_good_checkpoint: Checkpoint | str,
    *,
    reason: str,
    signer: Signer | None = None,
    id_window: bool | None = None,
) -> Fork

Start a new incarnation of the chain after a restore.

Run it after the restore and before any writer starts. In one READ COMMITTED transaction, once it holds the sealer's advisory lock (so no seal, retire or ack block is written meanwhile), it:

  1. checks that last_good_checkpoint names a genesis, checkpoint or fork block of this chain, with its hash;
  2. with an id window, reads the highest id (id_floor) and the row count (id_count) of each stream, and refuses when a table's identity sequence is below the highest floor of its streams;
  3. writes the closing seal of the old incarnation: with an id window, over [sealed horizon, highest stored xid + 1) and the rows at or below the floor; without one, a normal seal up to the horizon. It is left out when there is nothing to seal;
  4. writes the fork block, whose xid_at_fork is the horizon now.

From then on the sealer and verify apply the id window: the old incarnations' blocks hold the rows at or below the floor, the new one's the rows above it, and every seal refuses with ID_FLOOR_VIOLATION when new rows got ids at or below the floor. The closing seal is one block, whatever its size.

Parameters:

Name Type Description Default
connection Connection

A connection that may insert into the block table, not in a transaction and not in AUTOCOMMIT mode.

required
tables AuditTables

Audit tables built with integrity.

required
last_good_checkpoint Checkpoint | str

The newest checkpoint the restored chain still has, kept off the database; a Checkpoint or its note text. Signatures are not checked here.

required
reason str

Why, for whoever reads the chain; stored in clear.

required
signer Signer | None

Signs the closing seal and the fork block. verify takes a fork as the explanation of a diverging checkpoint only when it is signed by a key it knows.

None
id_window bool | None

Record an id window. None decides by the horizon: an id window when transaction ids were rewound (pg_restore into a new cluster), none otherwise (PITR, pg_resetwal). The ids were rewound when the horizon is below the sealed horizon, or when a row of the current incarnation has an xid that no transaction has had yet (one restored unsealed, from above the new cluster's ids).

None

Returns:

Type Description
Fork

What was written.

Raises:

Type Description
ValueError

The checkpoint does not match the chain, the connection is in a transaction or in AUTOCOMMIT mode, the server is in recovery, or the tables were built without integrity.

SealRefusedError

NO_GENESIS; XID_REWIND when the ids were rewound and id_window is False; ID_FLOOR_VIOLATION when an identity sequence is behind the floor. Nothing was written.

Source code in audit_trail/integrity/_anchor.py
def declare_fork(
    connection: Connection,
    tables: AuditTables,
    last_good_checkpoint: Checkpoint | str,
    *,
    reason: str,
    signer: Signer | None = None,
    id_window: bool | None = None,
) -> Fork:
    """Start a new incarnation of the chain after a restore.

    Run it after the restore and before any writer starts.
    In one ``READ COMMITTED`` transaction, once it holds the sealer's
    advisory lock (so no seal, retire or ack block is written meanwhile),
    it:

    1. checks that ``last_good_checkpoint`` names a genesis, checkpoint or
       fork block of this chain, with its hash;
    2. with an id window, reads the highest ``id`` (``id_floor``) and the
       row count (``id_count``) of each stream, and refuses when a table's
       identity sequence is below the highest floor of its streams;
    3. writes the closing seal of the old incarnation: with an id window,
       over ``[sealed horizon, highest stored xid + 1)`` and the rows at or
       below the floor; without one, a normal seal up to the horizon. It is
       left out when there is nothing to seal;
    4. writes the fork block, whose ``xid_at_fork`` is the horizon now.

    From then on the sealer and ``verify`` apply the id window: the old
    incarnations' blocks hold the rows at or below the floor, the new one's
    the rows above it, and every seal refuses with ``ID_FLOOR_VIOLATION``
    when new rows got ids at or below the floor. The closing seal is one
    block, whatever its size.

    Args:
        connection: A connection that may insert into the block table, not
            in a transaction and not in ``AUTOCOMMIT`` mode.
        tables: Audit tables built with integrity.
        last_good_checkpoint: The newest checkpoint the restored chain still
            has, kept off the database; a ``Checkpoint`` or its note text.
            Signatures are not checked here.
        reason: Why, for whoever reads the chain; stored in clear.
        signer: Signs the closing seal and the fork block. ``verify`` takes
            a fork as the explanation of a diverging checkpoint only when it
            is signed by a key it knows.
        id_window: Record an id window. ``None`` decides by the horizon: an
            id window when transaction ids were rewound (``pg_restore`` into
            a new cluster), none otherwise (PITR, ``pg_resetwal``). The ids
            were rewound when the horizon is below the sealed horizon, or
            when a row of the current incarnation has an ``xid`` that no
            transaction has had yet (one restored unsealed, from above the
            new cluster's ids).

    Returns:
        What was written.

    Raises:
        ValueError: The checkpoint does not match the chain, the connection
            is in a transaction or in ``AUTOCOMMIT`` mode, the server is in
            recovery, or the tables were built without integrity.
        SealRefusedError: ``NO_GENESIS``; ``XID_REWIND`` when the ids were
            rewound and ``id_window`` is ``False``; ``ID_FLOOR_VIOLATION``
            when an identity sequence is behind the floor. Nothing was
            written.
    """
    block = block_table(tables)
    checkpoint = (
        Checkpoint.from_note(last_good_checkpoint)
        if isinstance(last_good_checkpoint, str)
        else last_good_checkpoint
    )
    _pg.check_transactional(connection, "declare_fork")
    check_idle(connection, "declare_fork")
    with connection.begin():
        horizon = _lock(connection, block)
        head = sealed_horizon(connection, block)
        last = last_block(connection, block)
        if head is None or last is None:
            raise _no_genesis(block)
        chain, sealed_to = head
        _check_checkpoint(connection, block, chain, checkpoint)
        window = current_window(connection, block)
        # Rewound when the horizon is below the sealed one, and also when it
        # is above it but below the xid of a row restored unsealed: a closing
        # seal up to the horizon would leave that row out, and new
        # transactions would reuse its id.
        ahead = future_xid(connection, tables, window_clauses(tables, window.id_floor))
        rewound = horizon < sealed_to or ahead is not None
        with_window = rewound if id_window is None else id_window
        if rewound and not with_window:
            if ahead is None:
                found = f"the horizon {horizon} is below the sealed horizon {sealed_to}"
            else:
                found = f"a row has the xid {ahead}, above the horizon {horizon}"
            raise SealRefusedError(
                "XID_REWIND",
                f"{found}: a fork without an id window needs transaction ids "
                "above every stored one (pg_resetwal --epoch)",
            )
        floors = counts = None
        if with_window:
            floors, counts = _floors(connection, tables)
            _check_sequences(connection, tables, floors)
            lower, upper = window.id_floor, floors
            closing_to = _highest_xid(connection, tables, lower, upper)
            closing_to = None if closing_to is None else closing_to + 1
        else:
            lower, upper = window.id_floor, None
            closing_to = horizon
        prev, seq = bytes(last.block_hash), int(last.seq) + 1
        closing_seq: int | None = None
        if closing_to is not None and closing_to > sealed_to:
            builder = SegmentBuilder()
            windows = window_clauses(tables, lower, upper)
            for stream, partition, row in leaf_rows(
                connection, tables, sealed_to, closing_to, windows
            ):
                builder.add(stream, partition, row)
            if builder.rows:
                body = seal_body(chain, seq, sealed_to, closing_to, builder.segments())
                prev = insert_block(connection, block, seq, "seal", prev, body, signer)
                closing_seq, seq = seq, seq + 1
        incarnation = window.incarnation + 1
        body = fork_body(
            chain,
            seq,
            incarnation=incarnation,
            reason=reason,
            prior_seq=checkpoint.seq,
            prior_hash=checkpoint.block_hash,
            xid_at_fork=horizon,
            id_floor=floors,
            id_count=counts,
        )
        insert_block(connection, block, seq, "fork", prev, body, signer)
    return Fork(seq, incarnation, closing_seq, horizon, floors, counts)

export_checkpoint

export_checkpoint(
    connection: Connection,
    tables: AuditTables,
    *,
    signer: Signer | None = None,
    require_replicated: bool = False,
    replication_timeout: timedelta = DEFAULT_REPLICATION_TIMEOUT,
    extensions: Iterable[str] = (),
    journal: ErasureJournal | None = None,
) -> Checkpoint

Append a checkpoint block and return the checkpoint that names it.

Takes the sealer's advisory lock (waiting for a running sealer) in a READ COMMITTED transaction of its own, appends a checkpoint block after the last block, and commits. The statement is {v, chain, seq, block_hash, xid_to, sealed_at, incarnation} of that block, framed as a C2SP signed note by Checkpoint.to_note.

With require_replicated, after the commit it reads pg_current_wal_insert_lsn(), at or past the block's commit record, and polls pg_stat_replication until as many synchronous standbys as synchronous_standby_names asks for have flushed that far: the n with sync_state = 'sync' for FIRST n (or a plain list, FIRST 1), n of those with quorum for ANY n. flush_lsn, not replay_lsn: the block is safe once it is on the standby's disk. With synchronous_commit = on and a synchronous standby the commit already waited for it; the check matters with local or off, and with quorum setups.

Parameters:

Name Type Description Default
connection Connection

A connection that may insert into the block table, not in a transaction and not in AUTOCOMMIT mode.

required
tables AuditTables

Audit tables built with integrity.

required
signer Signer | None

Signs the block and the note; None exports the statement unsigned (keep it where it cannot be changed).

None
require_replicated bool

Return the checkpoint only once the synchronous standbys have flushed the block.

False
replication_timeout timedelta

How long to wait for that.

DEFAULT_REPLICATION_TIMEOUT
extensions Iterable[str]

The application's own lines, added after the statement and signed with it; Checkpoint.extensions gives them back. Each is at most 1024 bytes of UTF-8 and reads as what it says (check_extension): not only whitespace, without control, format, private-use or unassigned characters, blank-looking letters or line breaks, and not starting with sqlalchemy-audit-trail/ in any case. They are not stored in the block: keep them with the checkpoint.

()
journal ErasureJournal | None

An erasure journal (erasure_journal) to commit to: the statement becomes version 2, with its commitment. Each block it states must be in the chain, with that hash, at or before the checkpoint's. Keep the journal with the checkpoint.

None

Returns:

Type Description
Checkpoint

The checkpoint, signed by signer if given.

Raises:

Type Description
ValueError

The tables were built without integrity, the connection is in a transaction or in AUTOCOMMIT mode, the server is in recovery, an extension line is not valid (checked before anything is written), or the journal does not match the chain (nothing is written).

SealRefusedError

NO_GENESIS.

ReplicationError

require_replicated, and the synchronous standbys did not confirm the block, or checking them failed; any error after the commit is one, with seq and lsn. Also, whatever require_replicated, when the connection is lost during the COMMIT (a terminated backend that waited for a synchronous standby): NOT_REPLICATED with seq and lsn when the block is written, CHECK_FAILED with seq alone when that cannot be read. A COMMIT that wrote nothing raises its own error.

Source code in audit_trail/integrity/_anchor.py
def export_checkpoint(
    connection: Connection,
    tables: AuditTables,
    *,
    signer: Signer | None = None,
    require_replicated: bool = False,
    replication_timeout: timedelta = DEFAULT_REPLICATION_TIMEOUT,
    extensions: Iterable[str] = (),
    journal: ErasureJournal | None = None,
) -> Checkpoint:
    """Append a checkpoint block and return the checkpoint that names it.

    Takes the sealer's advisory lock (waiting for a running
    sealer) in a ``READ COMMITTED`` transaction of its own, appends a
    ``checkpoint`` block after the last block, and commits. The statement is
    ``{v, chain, seq, block_hash, xid_to, sealed_at, incarnation}`` of that
    block, framed as a C2SP signed note by ``Checkpoint.to_note``.

    With ``require_replicated``, after the commit it reads
    ``pg_current_wal_insert_lsn()``, at or past the block's commit record,
    and polls ``pg_stat_replication`` until as many synchronous standbys as
    ``synchronous_standby_names`` asks for have flushed that far: the ``n``
    with ``sync_state = 'sync'`` for ``FIRST n`` (or a plain list, ``FIRST
    1``), ``n`` of those with ``quorum`` for ``ANY n``. ``flush_lsn``, not
    ``replay_lsn``: the block is safe once it is on the standby's disk. With
    ``synchronous_commit = on`` and a synchronous standby the commit already
    waited for it; the check matters with ``local`` or ``off``, and with
    quorum setups.

    Args:
        connection: A connection that may insert into the block table, not
            in a transaction and not in ``AUTOCOMMIT`` mode.
        tables: Audit tables built with integrity.
        signer: Signs the block and the note; ``None`` exports the
            statement unsigned (keep it where it cannot be changed).
        require_replicated: Return the checkpoint only once the synchronous
            standbys have flushed the block.
        replication_timeout: How long to wait for that.
        extensions: The application's own lines, added after the statement
            and signed with it; ``Checkpoint.extensions`` gives them back.
            Each is at most 1024 bytes of UTF-8 and reads as what it says
            (``check_extension``): not only whitespace, without control,
            format, private-use or unassigned characters, blank-looking
            letters or line breaks, and not starting with
            ``sqlalchemy-audit-trail/`` in any case. They are not stored in
            the block: keep them with the checkpoint.
        journal: An erasure journal (``erasure_journal``) to commit to: the
            statement becomes version 2, with its commitment. Each block it
            states must be in the chain, with that hash, at or before the
            checkpoint's. Keep the journal with the checkpoint.

    Returns:
        The checkpoint, signed by ``signer`` if given.

    Raises:
        ValueError: The tables were built without integrity, the connection
            is in a transaction or in ``AUTOCOMMIT`` mode, the server is in
            recovery, an extension line is not valid (checked before
            anything is written), or the journal does not match the chain
            (nothing is written).
        SealRefusedError: ``NO_GENESIS``.
        ReplicationError: ``require_replicated``, and the synchronous
            standbys did not confirm the block, or checking them failed;
            any error after the commit is one, with ``seq`` and ``lsn``.
            Also, whatever ``require_replicated``, when the connection is
            lost during the ``COMMIT`` (a terminated backend that waited for
            a synchronous standby): ``NOT_REPLICATED`` with ``seq`` and
            ``lsn`` when the block is written, ``CHECK_FAILED`` with ``seq``
            alone when that cannot be read. A ``COMMIT`` that wrote nothing
            raises its own error.
    """
    lines = check_extensions(extensions)
    block = block_table(tables)
    _pg.check_transactional(connection, "export_checkpoint")
    check_idle(connection, "export_checkpoint")
    committing = False
    try:
        with connection.begin():
            _lock(connection, block)
            seq, digest = _append_checkpoint(connection, block, signer)
            statement = head_at(connection, block, seq)
            assert statement is not None  # just written
            if journal is not None:
                check_journal(connection, block, journal, statement)
                statement = replace(statement, journal=journal.commitment)
            committing = True  # only the COMMIT is left
    except OperationalError as exc:
        if not committing:
            raise
        problem = _cut_commit(connection, block, seq, digest)
        if problem is None:
            raise
        raise problem from exc
    if require_replicated:
        wait_replicated(connection, seq, replication_timeout)
    checkpoint = replace(statement, extensions=lines)
    return checkpoint if signer is None else checkpoint.signed([signer])

prepare_checkpoint

prepare_checkpoint(
    connection: Connection,
    tables: AuditTables,
    *,
    verify: Mapping[str, Any] | None = None,
    verified: VerificationReport | None = None,
    extensions: Iterable[str] = (),
    journal: ErasureJournal | None = None,
) -> Checkpoint

The unsigned statement of a checkpoint of a head that verified.

The first half of a checkpoint whose signer takes its time, such as a person typing a PIN: sign the result (Checkpoint.signed, or any C2SP note signer over Checkpoint.text), then give the note to record_checkpoint. Nothing is written and no lock is taken, and the connection is left with no transaction open, so nothing waits for the signer. Blocks written meanwhile are not covered: the checkpoint names the head as it was.

Give exactly one of:

  • verify: run verify now on this connection, in short READ ONLY transactions, with these keyword arguments of it ({} for none), and prepare for the last block it checked;
  • verified: the report of an earlier verify, for example a long nightly run the host stored. It must have no failures, and its head must still be a block of this chain, with its hash, and no fork may have come after it; the statement is for that head, not a newer one. verify(since=report) brings a report up to the current head quickly.

Parameters:

Name Type Description Default
connection Connection

A connection that can read the audit tables and the block table, not in a transaction.

required
tables AuditTables

Audit tables built with integrity.

required
verify Mapping[str, Any] | None

Keyword arguments for verify: retention, transaction_retention, system_severity, chunk_rows, checkpoints, verifier, require_signatures, key_history and since.

None
verified VerificationReport | None

The report of an earlier verify.

None
extensions Iterable[str]

The application's lines, as export_checkpoint takes them, signed with the statement.

()
journal ErasureJournal | None

An erasure journal to commit to, as export_checkpoint takes it; each block it states must be in the chain, with that hash, at or before the head.

None

Returns:

Type Description
Checkpoint

The checkpoint, unsigned, naming the verified head.

Raises:

Type Description
CheckpointRefusedError

The verification, or the report, has failures (report holds it), the report's head is not a block of this chain as it is now, or it is from before a fork (an earlier incarnation).

ValueError

Both or neither of verify and verified, an unknown verify argument, an invalid extension line, a journal that does not match the chain, a connection in a transaction, or as verify.

Source code in audit_trail/integrity/_anchor.py
def prepare_checkpoint(
    connection: Connection,
    tables: AuditTables,
    *,
    verify: Mapping[str, Any] | None = None,
    verified: VerificationReport | None = None,
    extensions: Iterable[str] = (),
    journal: ErasureJournal | None = None,
) -> Checkpoint:
    """The unsigned statement of a checkpoint of a head that verified.

    The first half of a checkpoint whose signer takes its time, such as a
    person typing a PIN: sign the result (``Checkpoint.signed``, or any C2SP
    note signer over ``Checkpoint.text``), then give the note to
    ``record_checkpoint``. Nothing is written and no lock is taken, and the
    connection is left with no transaction open, so nothing waits for the
    signer. Blocks written meanwhile are not covered: the checkpoint names
    the head as it was.

    Give exactly one of:

    - ``verify``: run ``verify`` now on this connection, in short ``READ
      ONLY`` transactions, with these keyword arguments of it (``{}`` for
      none), and prepare for the last block it checked;
    - ``verified``: the report of an earlier ``verify``, for example a long
      nightly run the host stored. It must have no failures, and its head
      must still be a block of this chain, with its hash, and no fork may
      have come after it; the statement is for that head, not a newer
      one. ``verify(since=report)`` brings a report up to the current
      head quickly.

    Args:
        connection: A connection that can read the audit tables and the
            block table, not in a transaction.
        tables: Audit tables built with integrity.
        verify: Keyword arguments for ``verify``: ``retention``,
            ``transaction_retention``,
            ``system_severity``, ``chunk_rows``, ``checkpoints``,
            ``verifier``, ``require_signatures``, ``key_history`` and
            ``since``.
        verified: The report of an earlier ``verify``.
        extensions: The application's lines, as ``export_checkpoint`` takes
            them, signed with the statement.
        journal: An erasure journal to commit to, as ``export_checkpoint``
            takes it; each block it states must be in the chain, with that
            hash, at or before the head.

    Returns:
        The checkpoint, unsigned, naming the verified head.

    Raises:
        CheckpointRefusedError: The verification, or the report, has
            failures (``report`` holds it), the report's head is not a
            block of this chain as it is now, or it is from before a fork
            (an earlier incarnation).
        ValueError: Both or neither of ``verify`` and ``verified``, an
            unknown ``verify`` argument, an invalid extension line, a
            journal that does not match the chain, a connection in a
            transaction, or as ``verify``.
    """
    lines = check_extensions(extensions)
    if (verify is None) == (verified is None):
        raise ValueError("give either verify or verified")
    check_idle(connection, "prepare_checkpoint")
    block = block_table(tables)
    if verify is not None:
        allowed = inspect.signature(verify_options).parameters
        unknown = sorted(set(verify) - set(allowed))
        if unknown:
            raise ValueError(f"verify takes no argument {', '.join(unknown)}")
        options = verify_options(**verify)
        report = run_verification(connection, tables, block, options)
        name = "verify"
    else:
        assert verified is not None
        report, name = verified, "verified"
    head = clean_head(report, name, CheckpointRefusedError)
    with _pg.read_only(connection):
        current = head_at(connection, block, head.seq)
        if current is None or current.text != head.text:
            raise CheckpointRefusedError(
                f"the report's head, block {head.seq}, is not a block of this "
                "chain as it is now",
                report,
            )
        if (fork := fork_after(connection, block, head.seq)) is not None:
            raise CheckpointRefusedError(_before_fork(head.seq, fork), report)
        if journal is not None:
            check_journal(connection, block, journal, current)
            current = replace(current, journal=journal.commitment)
    return replace(current, extensions=lines)

record_checkpoint

record_checkpoint(
    connection: Connection,
    tables: AuditTables,
    note: Checkpoint | str,
    *,
    verifier: SignatureVerifier,
    key_history: KeyHistory | None = None,
    signer: Signer | None = None,
) -> RecordedCheckpoint

Store a signed checkpoint in the chain, once.

The second half of prepare_checkpoint. Before it writes, it checks the note: every signature of a key verifier knows verifies, at least one does, and with key_history each of those keys may sign at the seq the checkpoint names. Then, under the sealer's advisory lock in a READ COMMITTED transaction of its own, it checks that the statement is the head as the chain holds it (chain, seq, hash, sealed horizon, time and incarnation) and that no fork came after it, appends a checkpoint block whose body holds the note, and commits.

The same note, byte for byte, recorded again returns the block that holds it, and writes nothing: retry freely after a lost connection. The same head with other signatures (a cosignature added) is another note.

Keep the note off the database as well: the copy in the chain lets declare_fork take its head as the last good checkpoint, but only a copy that the database cannot reach anchors verify.

Parameters:

Name Type Description Default
connection Connection

A connection that may insert into the block table, not in a transaction and not in AUTOCOMMIT mode.

required
tables AuditTables

Audit tables built with integrity.

required
note Checkpoint | str

The signed checkpoint, or its note text.

required
verifier SignatureVerifier

Checks the note's signatures.

required
key_history KeyHistory | None

When each key was valid, by block seq.

None
signer Signer | None

Signs the checkpoint block (not the note), for a chain verified with require_signatures. It runs inside the transaction, so give a key that does not wait, such as the sealer's.

None

Returns:

Type Description
RecordedCheckpoint

The block that holds the note, and whether this call wrote it.

Raises:

Type Description
NoteError

The note is not a checkpoint (MALFORMED), a signature does not verify (BAD_SIGNATURE), or none is of a key the verifier knows (UNKNOWN_KEY).

ValueError

The note is unsigned, a key is outside its window, the head is not a block of this chain as it is or is from before a fork (an earlier incarnation), the connection is in a transaction or in AUTOCOMMIT mode, the server is in recovery, or the tables were built without integrity.

OperationalError

The connection was lost, also during the COMMIT; whether the block was written, a retry with the same note tells, and writes it at most once.

Source code in audit_trail/integrity/_anchor.py
def record_checkpoint(
    connection: Connection,
    tables: AuditTables,
    note: Checkpoint | str,
    *,
    verifier: SignatureVerifier,
    key_history: KeyHistory | None = None,
    signer: Signer | None = None,
) -> RecordedCheckpoint:
    """Store a signed checkpoint in the chain, once.

    The second half of ``prepare_checkpoint``. Before it writes, it checks
    the note: every signature of a key ``verifier`` knows verifies, at least
    one does, and with ``key_history`` each of those keys may sign at the
    ``seq`` the checkpoint names. Then, under the sealer's advisory lock in
    a ``READ COMMITTED`` transaction of its own, it checks that the
    statement is the head as the chain holds it (chain, ``seq``, hash,
    sealed horizon, time and incarnation) and that no fork came after it,
    appends a ``checkpoint`` block whose body holds the note, and commits.

    The same note, byte for byte, recorded again returns the block that
    holds it, and writes nothing: retry freely after a lost connection. The
    same head with other signatures (a cosignature added) is another note.

    Keep the note off the database as well: the copy in the chain lets
    ``declare_fork`` take its head as the last good checkpoint, but only a
    copy that the database cannot reach anchors ``verify``.

    Args:
        connection: A connection that may insert into the block table, not
            in a transaction and not in ``AUTOCOMMIT`` mode.
        tables: Audit tables built with integrity.
        note: The signed checkpoint, or its note text.
        verifier: Checks the note's signatures.
        key_history: When each key was valid, by block ``seq``.
        signer: Signs the ``checkpoint`` block (not the note), for a chain
            verified with ``require_signatures``. It runs inside the
            transaction, so give a key that does not wait, such as the
            sealer's.

    Returns:
        The block that holds the note, and whether this call wrote it.

    Raises:
        NoteError: The note is not a checkpoint (``MALFORMED``), a
            signature does not verify (``BAD_SIGNATURE``), or none is of a
            key the verifier knows (``UNKNOWN_KEY``).
        ValueError: The note is unsigned, a key is outside its window, the
            head is not a block of this chain as it is or is from before a
            fork (an earlier incarnation), the connection is in
            a transaction or in ``AUTOCOMMIT`` mode, the server is in
            recovery, or the tables were built without integrity.
        OperationalError: The connection was lost, also during the
            ``COMMIT``; whether the block was written, a retry with the
            same note tells, and writes it at most once.
    """
    checkpoint = Checkpoint.from_note(note) if isinstance(note, str) else note
    if not checkpoint.signatures:
        raise ValueError("the checkpoint is not signed; sign it first")
    for key_id in checkpoint.verify(verifier):
        if key_history is not None and (
            found := key_history.check(key_id, checkpoint.seq)
        ):
            raise ValueError(f"the checkpoint is signed outside a window: {found[1]}")
    stored = checkpoint.to_note()
    statement = replace(checkpoint, signatures=(), extensions=(), journal=None).text
    block = block_table(tables)
    _pg.check_transactional(connection, "record_checkpoint")
    check_idle(connection, "record_checkpoint")
    with connection.begin():
        _lock(connection, block)
        current = head_at(connection, block, checkpoint.seq)
        if current is None or current.text != statement:
            raise ValueError(
                f"the checkpoint does not name block {checkpoint.seq} of this "
                "chain as it is"
            )
        for seq, recorded in recorded_notes(connection, block, checkpoint.seq):
            if recorded == stored:
                return RecordedCheckpoint(seq, checkpoint, False)
        if (fork := fork_after(connection, block, checkpoint.seq)) is not None:
            raise ValueError(_before_fork(checkpoint.seq, fork))
        seq, _digest = _append_checkpoint(connection, block, signer, stored)
    return RecordedCheckpoint(seq, checkpoint, True)

aexport_bundle async

aexport_bundle(
    engine: AsyncEngine,
    tables: AuditTables,
    destination: str | PathLike[str] | BinaryIO,
    scope: BlockRange | TimeRange,
    *,
    include: Include = "both",
    checkpoints: Iterable[Checkpoint | str] = (),
    key_history: KeyHistory | None = None,
    host_files: Mapping[str, bytes | str | PathLike[str]]
    | None = None,
    signer: Signer | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
) -> BundleResult

Async export_bundle, for an AsyncEngine; the same arguments.

Runs export_bundle's reads and writes on one connection through run_sync; the file writes block the event loop while they run.

Raises:

Type Description
TypeError

The engine is a sync Engine; use export_bundle.

ValueError

As export_bundle.

Source code in audit_trail/integrity/_bundle.py
async def aexport_bundle(
    engine: AsyncEngine,
    tables: AuditTables,
    destination: str | os.PathLike[str] | BinaryIO,
    scope: BlockRange | TimeRange,
    *,
    include: Include = "both",
    checkpoints: Iterable[Checkpoint | str] = (),
    key_history: KeyHistory | None = None,
    host_files: Mapping[str, bytes | str | os.PathLike[str]] | None = None,
    signer: Signer | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
) -> BundleResult:
    """Async ``export_bundle``, for an ``AsyncEngine``; the same arguments.

    Runs ``export_bundle``'s reads and writes on one connection through
    ``run_sync``; the file writes block the event loop while they run.

    Raises:
        TypeError: The engine is a sync ``Engine``; use ``export_bundle``.
        ValueError: As ``export_bundle``.
    """
    from sqlalchemy.ext.asyncio import AsyncEngine

    if not isinstance(engine, AsyncEngine):
        raise TypeError("the engine is sync; use export_bundle")
    job = _job(
        tables, scope, include, checkpoints, key_history, host_files, signer, chunk_rows
    )
    async with engine.connect() as conn:
        return await conn.run_sync(
            lambda sync_conn: _write(sync_conn, job, destination)
        )

export_bundle

export_bundle(
    engine: Engine,
    tables: AuditTables,
    destination: str | PathLike[str] | BinaryIO,
    scope: BlockRange | TimeRange,
    *,
    include: Include = "both",
    checkpoints: Iterable[Checkpoint | str] = (),
    key_history: KeyHistory | None = None,
    host_files: Mapping[str, bytes | str | PathLike[str]]
    | None = None,
    signer: Signer | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
) -> BundleResult

Write a range of the chain and the rows it seals to a bundle.

Runs on one connection of its own from engine, in short READ ONLY transactions like verify, and takes no lock. It reads the chain, then the rows of each seal block in scope chunk_rows at a time, keyset-paged by (xid, id), and writes them as it reads them, so memory does not grow with the rows. The layout is in the audit_trail.integrity._bundle module documentation. The export does not verify: run verify for that.

A bundle holds the audit rows as stored, personal data among them: keep it as you keep the audit tables.

Parameters:

Name Type Description Default
engine Engine

An engine whose role can read the audit tables, the block table and the catalog.

required
tables AuditTables

Audit tables built with integrity.

required
destination str | PathLike[str] | BinaryIO

A path, or a binary file object open for writing. A path is removed again when the export fails.

required
scope BlockRange | TimeRange

A BlockRange, or a TimeRange mapped to whole blocks.

required
include Include

The rows of "transaction", "activity" or "both" tables.

'both'
checkpoints Iterable[Checkpoint | str]

Checkpoints to include, as Checkpoint objects or note texts. Checkpoints recorded in the chain that name a block of the bundle are included as well.

()
key_history KeyHistory | None

Included as it is; the bundle names keys only by id.

None
host_files Mapping[str, bytes | str | PathLike[str]] | None

Files of the caller to add under host/, by name, as bytes or as a path to read. A name is one or more /-separated parts of letters, digits, ., _ and -, none of them . or ...

None
signer Signer | None

Signs the manifest; None leaves it unsigned.

None
chunk_rows int

Rows read per transaction, at least 1.

DEFAULT_CHUNK_ROWS

Returns:

Type Description
BundleResult

What was written.

Raises:

Type Description
TypeError

The engine is an AsyncEngine; use aexport_bundle.

ValueError

The tables were built without integrity, the chain has no genesis block, the scope names no block of it, a checkpoint text is not a checkpoint (a NoteError), a host file name is not valid, or chunk_rows is below 1.

Source code in audit_trail/integrity/_bundle.py
def export_bundle(
    engine: Engine,
    tables: AuditTables,
    destination: str | os.PathLike[str] | BinaryIO,
    scope: BlockRange | TimeRange,
    *,
    include: Include = "both",
    checkpoints: Iterable[Checkpoint | str] = (),
    key_history: KeyHistory | None = None,
    host_files: Mapping[str, bytes | str | os.PathLike[str]] | None = None,
    signer: Signer | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
) -> BundleResult:
    """Write a range of the chain and the rows it seals to a bundle.

    Runs on one connection of its own from ``engine``, in short ``READ
    ONLY`` transactions like ``verify``, and takes no lock. It reads the
    chain, then the rows of each seal block in scope ``chunk_rows`` at a
    time, keyset-paged by ``(xid, id)``, and writes them as it reads them,
    so memory does not grow with the rows. The layout is in the
    ``audit_trail.integrity._bundle`` module documentation. The export does
    not verify: run ``verify`` for that.

    A bundle holds the audit rows as stored, personal data among them:
    keep it as you keep the audit tables.

    Args:
        engine: An engine whose role can read the audit tables, the block
            table and the catalog.
        tables: Audit tables built with integrity.
        destination: A path, or a binary file object open for writing. A
            path is removed again when the export fails.
        scope: A ``BlockRange``, or a ``TimeRange`` mapped to whole blocks.
        include: The rows of ``"transaction"``, ``"activity"`` or
            ``"both"`` tables.
        checkpoints: Checkpoints to include, as ``Checkpoint`` objects or
            note texts. Checkpoints recorded in the chain that name a block
            of the bundle are included as well.
        key_history: Included as it is; the bundle names keys only by id.
        host_files: Files of the caller to add under ``host/``, by name, as
            bytes or as a path to read. A name is one or more ``/``-separated
            parts of letters, digits, ``.``, ``_`` and ``-``, none of them
            ``.`` or ``..``.
        signer: Signs the manifest; ``None`` leaves it unsigned.
        chunk_rows: Rows read per transaction, at least 1.

    Returns:
        What was written.

    Raises:
        TypeError: The engine is an ``AsyncEngine``; use
            ``aexport_bundle``.
        ValueError: The tables were built without integrity, the chain has
            no genesis block, the scope names no block of it, a checkpoint
            text is not a checkpoint (a ``NoteError``), a host file name is
            not valid, or ``chunk_rows`` is below 1.
    """
    if not isinstance(engine, Engine):
        raise TypeError("the engine is async; use aexport_bundle")
    job = _job(
        tables, scope, include, checkpoints, key_history, host_files, signer, chunk_rows
    )
    with engine.connect() as conn:
        return _write(conn, job, destination)

verify_bundle

verify_bundle(
    bundle: str | PathLike[str] | BinaryIO,
    *,
    verifier: SignatureVerifier,
    key_history: KeyHistory | None = None,
    checkpoints: Iterable[
        Checkpoint | LedgerCheckpoint | str
    ] = (),
    retention: Mapping[int, timedelta | None] | None = None,
    transaction_retention: timedelta | None = None,
    system_severity: int | None = None,
    require_signatures: bool = False,
    manifest_sha256: str | None = None,
) -> VerificationReport | LedgerReport

Check a bundle written by export_bundle, without the database.

It reads the bundle's stream_type first. A ledger bundle ("ledger", written by audit_trail.ledger.export_bundle) is checked as audit_trail.ledger.verify_bundle checks it, and gives a LedgerReport: its checkpoints are ledger checkpoints, and retention, transaction_retention and system_severity do not apply to it. The rest of this describes an audit bundle ("audit"), which gives a VerificationReport.

The blocks of the bundle are checked as verify checks the chain, from the block before the scope on, and its rows against the seal blocks in scope, with the same findings for everything inside the scope. Keys and key ids in the bundle never establish trust: only verifier, key_history and checkpoints do, and a checkpoint in the bundle is used only when it carries a signature of a key verifier knows.

Besides verify's findings:

  • a checkpoint naming a block the bundle does not hold is an OUT_OF_SCOPE note, not TRUNCATED;
  • an audit.scrubbed record sealed outside the scope, or not sealed yet, is counted, with an OUT_OF_SCOPE note: it is not checked against a root. A scrub whose record counts more rows than carry its stamp in the bundle, more than retired partitions explain (a SCRUBBED_ROWS_RETIRED note, as in verify), is an OUT_OF_SCOPE note, since the others may be outside the scope; more stamps than recorded fail as in verify;
  • a retire block after the scope explains rows only when a trusted checkpoint names it or a known key signed it;
  • an entry that does not match the manifest is MANIFEST_MISMATCH; each host file is an UNANCHORED note unless the manifest is anchored: signed by a key verifier knows (and inside its window at the scope's last block, given key_history), or its hash given as manifest_sha256;
  • blocks missing from the end of the scope are TRUNCATED.

It does not report DETACHED_PARTITION, the unsealed tail, or XID_REWIND against the live horizon: they need the database.

Parameters:

Name Type Description Default
bundle str | PathLike[str] | BinaryIO

A path, or a binary file object open for reading that can seek.

required
verifier SignatureVerifier

The keys trusted to sign blocks, checkpoints and the manifest.

required
key_history KeyHistory | None

When each key was valid, by block seq, as for verify.

None
checkpoints Iterable[Checkpoint | LedgerCheckpoint | str]

Trusted checkpoints, as Checkpoint objects or note texts. The report is ANCHORED when one names a block of the bundle, with its hash.

()
retention Mapping[int, timedelta | None] | None

Retention by severity, as for verify (None or maintenance.KEEP for forever): a retire block inside it is RETIRED_EARLY. A severity it does not name is not checked.

None
transaction_retention timedelta | None

Retention of the transaction table, as for verify; used only with retention.

None
system_severity int | None

Severity of the audit.scrubbed records, as for verify.

None
require_signatures bool

Every block and every checkpoint must be signed by a key verifier knows.

False
manifest_sha256 str | None

The SHA-256 of manifest.note, as hex, kept or committed elsewhere when the bundle was written; it anchors the manifest. A bundle whose manifest has another hash fails with MANIFEST_MISMATCH.

None

Returns:

Type Description
VerificationReport | LedgerReport

The report. Its verified_to is the last block of the scope that

VerificationReport | LedgerReport

was checked; its head is None when the scope does not show

VerificationReport | LedgerReport

which incarnation of the chain it is in.

Raises:

Type Description
BundleError

The bundle cannot be read as one.

ValueError

A checkpoint text is not a checkpoint (a NoteError), manifest_sha256 is not 64 hex digits, transaction_retention is KEEP, or an option that does not apply to a ledger bundle is given for one.

Source code in audit_trail/integrity/_bundle_verify.py
def verify_bundle(
    bundle: str | os.PathLike[str] | BinaryIO,
    *,
    verifier: SignatureVerifier,
    key_history: KeyHistory | None = None,
    checkpoints: Iterable[Checkpoint | LedgerCheckpoint | str] = (),
    retention: Mapping[int, timedelta | None] | None = None,
    transaction_retention: timedelta | None = None,
    system_severity: int | None = None,
    require_signatures: bool = False,
    manifest_sha256: str | None = None,
) -> VerificationReport | LedgerReport:
    """Check a bundle written by ``export_bundle``, without the database.

    It reads the bundle's ``stream_type`` first. A ledger bundle (``"ledger"``,
    written by ``audit_trail.ledger.export_bundle``) is checked as
    ``audit_trail.ledger.verify_bundle`` checks it, and gives a
    ``LedgerReport``: its ``checkpoints`` are ledger checkpoints, and
    ``retention``, ``transaction_retention`` and ``system_severity`` do not
    apply to it. The rest of this describes an audit bundle (``"audit"``),
    which gives a ``VerificationReport``.

    The blocks of the bundle are checked as ``verify`` checks the chain,
    from the block before the scope on, and its rows against the seal blocks
    in scope, with the same findings for everything inside the scope. Keys
    and key ids in the bundle never establish trust: only ``verifier``,
    ``key_history`` and ``checkpoints`` do, and a checkpoint in the bundle
    is used only when it carries a signature of a key ``verifier`` knows.

    Besides ``verify``'s findings:

    - a checkpoint naming a block the bundle does not hold is an
      ``OUT_OF_SCOPE`` note, not ``TRUNCATED``;
    - an ``audit.scrubbed`` record sealed outside the scope, or not sealed
      yet, is counted, with an ``OUT_OF_SCOPE`` note: it is not checked
      against a root. A scrub whose record counts more rows than carry its
      stamp in the bundle, more than retired partitions explain (a
      ``SCRUBBED_ROWS_RETIRED`` note, as in ``verify``), is an
      ``OUT_OF_SCOPE`` note, since the others may be outside the scope;
      more stamps than recorded fail as in ``verify``;
    - a retire block after the scope explains rows only when a trusted
      checkpoint names it or a known key signed it;
    - an entry that does not match the manifest is ``MANIFEST_MISMATCH``;
      each host file is an ``UNANCHORED`` note unless the manifest is
      anchored: signed by a key ``verifier`` knows (and inside its window
      at the scope's last block, given ``key_history``), or its hash given
      as ``manifest_sha256``;
    - blocks missing from the end of the scope are ``TRUNCATED``.

    It does not report ``DETACHED_PARTITION``, the unsealed tail, or
    ``XID_REWIND`` against the live horizon: they need the database.

    Args:
        bundle: A path, or a binary file object open for reading that can
            seek.
        verifier: The keys trusted to sign blocks, checkpoints and the
            manifest.
        key_history: When each key was valid, by block ``seq``, as for
            ``verify``.
        checkpoints: Trusted checkpoints, as ``Checkpoint`` objects or note
            texts. The report is ``ANCHORED`` when one names a block of the
            bundle, with its hash.
        retention: Retention by severity, as for ``verify`` (``None`` or
            ``maintenance.KEEP`` for forever): a retire block inside it is
            ``RETIRED_EARLY``. A severity it does not name is not checked.
        transaction_retention: Retention of the transaction table, as for
            ``verify``; used only with ``retention``.
        system_severity: Severity of the ``audit.scrubbed`` records, as for
            ``verify``.
        require_signatures: Every block and every checkpoint must be signed
            by a key ``verifier`` knows.
        manifest_sha256: The SHA-256 of ``manifest.note``, as hex, kept or
            committed elsewhere when the bundle was written; it anchors the
            manifest. A bundle whose manifest has another hash fails with
            ``MANIFEST_MISMATCH``.

    Returns:
        The report. Its ``verified_to`` is the last block of the scope that
        was checked; its ``head`` is ``None`` when the scope does not show
        which incarnation of the chain it is in.

    Raises:
        BundleError: The bundle cannot be read as one.
        ValueError: A checkpoint text is not a checkpoint (a ``NoteError``),
            ``manifest_sha256`` is not 64 hex digits,
            ``transaction_retention`` is ``KEEP``, or an option that does
            not apply to a ledger bundle is given for one.
    """
    # The ledger's verifier imports this module.
    from audit_trail.ledger import _bundle_verify as _ledger
    from audit_trail.ledger._bundle_format import STREAM_TYPE as LEDGER

    checkpoints = list(checkpoints)
    with _archive(bundle) as archive:
        header = _ledger.peek_header(archive)
        if header is not None:
            version = header.get("bundle_version")
            # Version 2 is an audit bundle with state; every other one is 1.
            if not _known_version(version) or (
                version != BUNDLE_VERSION and header.get("stream_type") != STREAM_TYPE
            ):
                raise BundleError(f"bundle version {version!r} is not supported")
            if header.get("stream_type") not in (STREAM_TYPE, LEDGER):
                raise BundleError(
                    f"{HEADER}: stream_type is not {STREAM_TYPE!r} or {LEDGER!r}"
                )
        if header is not None and header.get("stream_type") == LEDGER:
            if (
                retention is not None
                or transaction_retention is not None
                or system_severity is not None
            ):
                raise ValueError(
                    "retention, transaction_retention and system_severity "
                    "apply to audit bundles, not to a ledger bundle"
                )
            options = _ledger.options_of(
                verifier, key_history, checkpoints, require_signatures, manifest_sha256
            )
            return _ledger.run(archive, options)
        return _verify_audit(
            archive,
            verifier=verifier,
            key_history=key_history,
            checkpoints=checkpoints,
            retention=retention,
            transaction_retention=transaction_retention,
            system_severity=system_severity,
            require_signatures=require_signatures,
            manifest_sha256=manifest_sha256,
        )

aerasure_journal async

aerasure_journal(
    connection: AsyncConnection,
    tables: AuditTables,
    *,
    since: datetime | None = None,
) -> ErasureJournal

Async erasure_journal, on an AsyncConnection; the same arguments.

Raises:

Type Description
ValueError

As erasure_journal.

Source code in audit_trail/integrity/_journal.py
async def aerasure_journal(
    connection: AsyncConnection,
    tables: AuditTables,
    *,
    since: datetime | None = None,
) -> ErasureJournal:
    """Async ``erasure_journal``, on an ``AsyncConnection``; the same arguments.

    Raises:
        ValueError: As ``erasure_journal``.
    """
    return await connection.run_sync(
        lambda sync_conn: erasure_journal(sync_conn, tables, since=since)
    )

areapply_erasures async

areapply_erasures(
    connection: AsyncConnection,
    tables: AuditTables,
    journal: ErasureJournal | str,
    *,
    checkpoint: Checkpoint | str,
    verifier: SignatureVerifier,
    key_history: KeyHistory | None = None,
    context: AuditContext | None = None,
    include_unproven: bool = False,
    include_uncommitted: bool = False,
) -> ReappliedErasures

Async reapply_erasures, on an AsyncConnection; the same arguments.

Raises:

Type Description
JournalRefusedError

As reapply_erasures.

ValueError

As reapply_erasures.

Source code in audit_trail/integrity/_journal.py
async def areapply_erasures(
    connection: AsyncConnection,
    tables: AuditTables,
    journal: ErasureJournal | str,
    *,
    checkpoint: Checkpoint | str,
    verifier: SignatureVerifier,
    key_history: KeyHistory | None = None,
    context: AuditContext | None = None,
    include_unproven: bool = False,
    include_uncommitted: bool = False,
) -> ReappliedErasures:
    """Async ``reapply_erasures``, on an ``AsyncConnection``; the same arguments.

    Raises:
        JournalRefusedError: As ``reapply_erasures``.
        ValueError: As ``reapply_erasures``.
    """
    return await connection.run_sync(
        lambda sync_conn: reapply_erasures(
            sync_conn,
            tables,
            journal,
            checkpoint=checkpoint,
            verifier=verifier,
            key_history=key_history,
            context=context,
            include_unproven=include_unproven,
            include_uncommitted=include_uncommitted,
        )
    )

erasure_journal

erasure_journal(
    connection: Connection,
    tables: AuditTables,
    *,
    since: datetime | None = None,
) -> ErasureJournal

The journal of the scrubs recorded since a point.

Reads, in one REPEATABLE READ, READ ONLY transaction, the audit.scrubbed records created at or after since, every row stamped by one of their transactions, and the chain, to name the seal block of each row and that block's hash. The rows a scrub erased without commitments, which it could not stamp, come from the uncommitted list of its records (written since 0.6.0). A scrub that erased nothing, or ran before write_genesis, is left out. It reads every row a scrub ever stamped, so on a large log run it next to the checkpoints, not on every request.

Keep the journal (to_json) with the checkpoint that commits to it: export_checkpoint(journal=...) or prepare_checkpoint(journal=...). Choose since before the oldest backup that may be restored, such as the sealed_at of the checkpoint taken with that backup.

Parameters:

Name Type Description Default
connection Connection

A connection that can read the audit tables and the block table, not in a transaction.

required
tables AuditTables

Audit tables built with integrity.

required
since datetime | None

An aware datetime; None for every scrub.

None

Returns:

Type Description
ErasureJournal

The journal.

Raises:

Type Description
ValueError

since is naive, the connection is in a transaction, the tables were built without integrity, or the chain has no genesis block.

Source code in audit_trail/integrity/_journal.py
def erasure_journal(
    connection: Connection,
    tables: AuditTables,
    *,
    since: datetime | None = None,
) -> ErasureJournal:
    """The journal of the scrubs recorded since a point.

    Reads, in one ``REPEATABLE READ``, ``READ ONLY`` transaction, the
    ``audit.scrubbed`` records created at or after ``since``, every row
    stamped by one of their transactions, and the chain, to name the seal
    block of each row and that block's hash. The rows a scrub erased
    without commitments, which it could not stamp, come from the
    ``uncommitted`` list of its records (written since 0.6.0). A scrub
    that erased nothing, or ran before ``write_genesis``, is left out. It
    reads every row a scrub ever stamped, so on a large log run it next to
    the checkpoints, not on every request.

    Keep the journal (``to_json``) with the checkpoint that commits to it:
    ``export_checkpoint(journal=...)`` or ``prepare_checkpoint(journal=...)``.
    Choose ``since`` before the oldest backup that may be restored, such as
    the ``sealed_at`` of the checkpoint taken with that backup.

    Args:
        connection: A connection that can read the audit tables and the
            block table, not in a transaction.
        tables: Audit tables built with integrity.
        since: An aware datetime; ``None`` for every scrub.

    Returns:
        The journal.

    Raises:
        ValueError: ``since`` is naive, the connection is in a transaction,
            the tables were built without integrity, or the chain has no
            genesis block.
    """
    if since is not None and since.utcoffset() is None:
        raise ValueError("since must be timezone-aware")
    block = block_table(tables)
    check_idle(connection, "erasure_journal")
    transaction = connection.begin()
    try:
        connection.execute(
            text("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ, READ ONLY")
        )
        return _build(connection, tables, block, since)
    finally:
        # Nothing was written; ending it either way releases the snapshot.
        transaction.rollback()

reapply_erasures

reapply_erasures(
    connection: Connection,
    tables: AuditTables,
    journal: ErasureJournal | str,
    *,
    checkpoint: Checkpoint | str,
    verifier: SignatureVerifier,
    key_history: KeyHistory | None = None,
    context: AuditContext | None = None,
    include_unproven: bool = False,
    include_uncommitted: bool = False,
) -> ReappliedErasures

Erase again, after a restore, the rows a trusted journal names.

Run it after the restore (and after declare_fork, when the restore calls for one), before the database is used again: until then the restored rows hold the erased values and their salts.

The journal is trusted only through checkpoint: it must be signed, every signature of a key verifier knows must verify and at least one must (with key_history, each such key inside its window at the checkpoint's seq), and its journal commitment must be this journal's. Otherwise JournalRefusedError, and nothing changes.

The blocks the checkpoint and the journal state that this chain still holds, with the same hash, prove it shared up to the newest of them (shared_to); a stated block at or below that with another hash is refused. A row is erased again only when the journal names a seal block for it within that prefix and its sealed fields still give the leaf hash the journal holds; with include_unproven, also the rows outside it that pass the checks described there, and with include_uncommitted, the rows without commitments that do. Groups already stamped (or, without commitments, in erased form) are left alone, so a second run changes nothing.

In one READ COMMITTED transaction of its own, each scrub's rows are erased as scrub and scrub_actor erase them (salts deleted, stamped with this transaction's id), and recorded by audit.scrubbed entries with the reason audit.restore_reapply, the severity of the original record, and reapplies: its xid and reasons.

Parameters:

Name Type Description Default
connection Connection

A connection whose role may update the audit tables (as for scrub), not in a transaction and not in AUTOCOMMIT mode.

required
tables AuditTables

Audit tables built with integrity.

required
journal ErasureJournal | str

The journal, or its to_json text.

required
checkpoint Checkpoint | str

The checkpoint that commits to it, or its note text, kept off the database.

required
verifier SignatureVerifier

Checks the checkpoint's signatures.

required
key_history KeyHistory | None

When each key was valid, by block seq.

None
context AuditContext | None

Who re-applies, for the entries; else the active context(), else anonymous.

None
include_unproven bool

Also erase again the rows outside the shared prefix (outside): not sealed when the journal was built, or sealed after shared_to. Only a row that is still there with the journal's table, id and xid, whose leaf hash (which covers its seal_commitments) still matches, and whose every part the journal names still holds the value its commitment was made to, with its salt (or is erased and stamped already). The journal holds no value, so this is the most it can check: such a row matches what the scrub erased, but no seal block attests it was in the chain the checkpoint was taken of. Their entries carry "unproven": true in reapplies, and the result lists them in unproven.

False
include_uncommitted bool

Also erase again the rows the scrubs erased that carry no commitments (UncommittedRow, from a version 2 journal): written before integrity was added, or by a writer without it. Only a row that is still there with the journal's table and id, the same xid (both None for a row older than the column) and still no commitments. Nothing else can be checked: no seal block or commitment attests the row. Their entries carry "uncommitted": true in reapplies, and the result lists them in uncommitted.

False

Returns:

Type Description
ReappliedErasures

What was erased, and the rows left alone.

Raises:

Type Description
JournalRefusedError

The checkpoint is unsigned, its signatures do not verify or are outside their windows, it commits to no journal or another one, it is of another chain, or the chain does not hold the blocks it and the journal state.

ValueError

The journal or the checkpoint is malformed, the connection is in a transaction or in AUTOCOMMIT mode, or the tables were built without integrity.

Source code in audit_trail/integrity/_journal.py
def reapply_erasures(
    connection: Connection,
    tables: AuditTables,
    journal: ErasureJournal | str,
    *,
    checkpoint: Checkpoint | str,
    verifier: SignatureVerifier,
    key_history: KeyHistory | None = None,
    context: AuditContext | None = None,
    include_unproven: bool = False,
    include_uncommitted: bool = False,
) -> ReappliedErasures:
    """Erase again, after a restore, the rows a trusted journal names.

    Run it after the restore (and after ``declare_fork``, when the restore
    calls for one), before the database is used again: until then the
    restored rows hold the erased values and their salts.

    The journal is trusted only through ``checkpoint``: it must be signed,
    every signature of a key ``verifier`` knows must verify and at least one
    must (with ``key_history``, each such key inside its window at the
    checkpoint's ``seq``), and its journal commitment must be this
    journal's. Otherwise ``JournalRefusedError``, and nothing changes.

    The blocks the checkpoint and the journal state that this chain still
    holds, with the same hash, prove it shared up to the newest of them
    (``shared_to``); a stated block at or below that with another hash is
    refused. A row is erased again only when the journal names a seal block
    for it within that prefix and its sealed fields still give the leaf
    hash the journal holds; with ``include_unproven``, also the rows
    outside it that pass the checks described there, and with
    ``include_uncommitted``, the rows without commitments that do. Groups
    already stamped (or, without commitments, in erased form) are left
    alone, so a second run changes nothing.

    In one ``READ COMMITTED`` transaction of its own, each scrub's rows are
    erased as ``scrub`` and ``scrub_actor`` erase them (salts deleted,
    stamped with this transaction's id), and recorded by ``audit.scrubbed``
    entries with the reason ``audit.restore_reapply``, the severity of the
    original record, and ``reapplies``: its ``xid`` and reasons.

    Args:
        connection: A connection whose role may update the audit tables
            (as for ``scrub``), not in a transaction and not in
            ``AUTOCOMMIT`` mode.
        tables: Audit tables built with integrity.
        journal: The journal, or its ``to_json`` text.
        checkpoint: The checkpoint that commits to it, or its note text,
            kept off the database.
        verifier: Checks the checkpoint's signatures.
        key_history: When each key was valid, by block ``seq``.
        context: Who re-applies, for the entries; else the active
            ``context()``, else anonymous.
        include_unproven: Also erase again the rows outside the shared
            prefix (``outside``): not sealed when the journal was built, or
            sealed after ``shared_to``. Only a row that is still there with
            the journal's table, ``id`` and ``xid``, whose leaf hash (which
            covers its ``seal_commitments``) still matches, and whose every
            part the journal names still holds the value its commitment was
            made to, with its salt (or is erased and stamped already). The
            journal holds no value, so this is the most it can check: such
            a row matches what the scrub erased, but no seal block attests
            it was in the chain the checkpoint was taken of. Their entries
            carry ``"unproven": true`` in ``reapplies``, and the result
            lists them in ``unproven``.
        include_uncommitted: Also erase again the rows the scrubs erased
            that carry no commitments (``UncommittedRow``, from a version 2
            journal): written before integrity was added, or by a writer
            without it. Only a row that is still there with the journal's
            table and ``id``, the same ``xid`` (both ``None`` for a row
            older than the column) and still no commitments. Nothing else
            can be checked: no seal block or commitment attests the row.
            Their entries carry ``"uncommitted": true`` in ``reapplies``,
            and the result lists them in ``uncommitted``.

    Returns:
        What was erased, and the rows left alone.

    Raises:
        JournalRefusedError: The checkpoint is unsigned, its signatures do
            not verify or are outside their windows, it commits to no
            journal or another one, it is of another chain, or the chain
            does not hold the blocks it and the journal state.
        ValueError: The journal or the checkpoint is malformed, the
            connection is in a transaction or in ``AUTOCOMMIT`` mode, or
            the tables were built without integrity.
    """
    from audit_trail import privacy

    if isinstance(journal, str):
        journal = ErasureJournal.from_json(journal)
    if isinstance(checkpoint, str):
        checkpoint = Checkpoint.from_note(checkpoint)
    _trust(journal, checkpoint, verifier, key_history)
    block = block_table(tables)
    _pg.check_transactional(connection, "reapply_erasures")
    check_idle(connection, "reapply_erasures")
    record_context = privacy.scrub_context(None) if context is None else context
    with connection.begin():
        connection.execute(text("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"))
        head = sealed_horizon(connection, block)
        if head is None or head[0] != checkpoint.chain:
            raise JournalRefusedError("the checkpoint is of another chain")
        shared_to = _shared_prefix(connection, block, journal, checkpoint)
        outside: list[JournalRow] = []
        unproven: list[ErasedRow] = []
        uncommitted: list[UncommittedRow] = []
        missing: list[JournalRow] = []
        mismatched: list[JournalRow] = []
        already = activity_rows = transaction_rows = 0
        for erasure in journal.erasures:
            inside = [r for r in erasure.rows if _proven(r, shared_to)]
            beyond = [r for r in erasure.rows if not _proven(r, shared_to)]
            if not include_unproven:
                outside.extend(beyond)
                beyond = []
            current = _current_rows(connection, tables, [*inside, *beyond])
            for rows, unproven_rows in ((inside, False), (beyond, True)):
                targets = _Targets()
                for row in rows:
                    found = current.get((row.table, row.id))
                    if found is None:
                        missing.append(row)
                    elif not _same_row(row, found, check_values=unproven_rows):
                        mismatched.append(row)
                    elif all(g in (found[_schema.ERASED] or {}) for g in row.groups):
                        already += 1
                    else:
                        targets.add(row)
                        if unproven_rows:
                            unproven.append(row)
                if not targets:
                    continue
                reapplies: dict[str, JSONValue] = {
                    "xid": erasure.xid,
                    "reasons": list(erasure.reasons),
                }
                if unproven_rows:
                    reapplies["unproven"] = True
                result = privacy.reapply(
                    connection,
                    tables,
                    scrub_ids=targets.scrub,
                    actor_ids=targets.actor,
                    transaction_ids=targets.transaction,
                    reapplies=reapplies,
                    record=privacy.ScrubbedRecord(
                        erasure.severity, record_context, None
                    ),
                )
                activity_rows += result.activity_rows
                transaction_rows += result.transaction_rows
            if not include_uncommitted:
                outside.extend(erasure.uncommitted)
                continue
            targets = _Targets()
            current = _current_rows(connection, tables, erasure.uncommitted)
            for plain in erasure.uncommitted:
                found = current.get((plain.table, plain.id))
                if found is None:
                    missing.append(plain)
                elif not _same_uncommitted(plain, found):
                    mismatched.append(plain)
                elif all(is_erased(plain.table, g, found) for g in plain.groups):
                    already += 1
                else:
                    targets.add(plain)
                    uncommitted.append(plain)
            if not targets:
                continue
            result = privacy.reapply(
                connection,
                tables,
                scrub_ids=targets.scrub,
                actor_ids=targets.actor,
                transaction_ids=targets.transaction,
                reapplies={
                    "xid": erasure.xid,
                    "reasons": list(erasure.reasons),
                    "uncommitted": True,
                },
                record=privacy.ScrubbedRecord(erasure.severity, record_context, None),
                uncommitted=True,
            )
            activity_rows += result.activity_rows
            transaction_rows += result.transaction_rows
    return ReappliedErasures(
        shared_to,
        activity_rows,
        transaction_rows,
        already,
        tuple(outside),
        tuple(missing),
        tuple(mismatched),
        tuple(unproven),
        tuple(uncommitted),
    )

aacknowledge async

aacknowledge(
    connection: AsyncConnection,
    tables: AuditTables,
    kind: FailureKind | str,
    scope: Mapping[str, object],
    reason: str,
    *,
    retention: Mapping[int, timedelta | None] | None = None,
    transaction_retention: timedelta | None = None,
    system_severity: int | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
    signer: Signer | None = None,
) -> int

Async acknowledge, on an AsyncConnection; the same arguments.

Runs acknowledge through run_sync.

Returns:

Type Description
int

The seq of the ack block.

Raises:

Type Description
ValueError

As acknowledge.

Source code in audit_trail/integrity/_verify_db.py
async def aacknowledge(
    connection: AsyncConnection,
    tables: AuditTables,
    kind: FailureKind | str,
    scope: Mapping[str, object],
    reason: str,
    *,
    retention: Mapping[int, timedelta | None] | None = None,
    transaction_retention: timedelta | None = None,
    system_severity: int | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
    signer: Signer | None = None,
) -> int:
    """Async ``acknowledge``, on an ``AsyncConnection``; the same arguments.

    Runs ``acknowledge`` through ``run_sync``.

    Returns:
        The ``seq`` of the ack block.

    Raises:
        ValueError: As ``acknowledge``.
    """
    return await connection.run_sync(
        lambda sync_conn: acknowledge(
            sync_conn,
            tables,
            kind,
            scope,
            reason,
            retention=retention,
            transaction_retention=transaction_retention,
            system_severity=system_severity,
            chunk_rows=chunk_rows,
            signer=signer,
        )
    )

acknowledge

acknowledge(
    connection: Connection,
    tables: AuditTables,
    kind: FailureKind | str,
    scope: Mapping[str, object],
    reason: str,
    *,
    retention: Mapping[int, timedelta | None] | None = None,
    transaction_retention: timedelta | None = None,
    system_severity: int | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
    signer: Signer | None = None,
) -> int

Waive a known incident with an ack block in the chain.

Runs verify on the connection first, and pins the failures of kind that scope matches as it observed them: the rows for a failure about a row, the root and row count for a segment, every field for the rest. Later verifications report those failures as ACKNOWLEDGED notes naming this block, instead of failing; a failure that is new or changed since, in the same scope, is reported again. The ack stays in the chain for every later reader. Takes the sealer's advisory lock and appends the block after the last one, hashed like every block, in a READ COMMITTED transaction of its own that it commits.

Parameters:

Name Type Description Default
connection Connection

A connection that may insert into the block table, not in a transaction and not in AUTOCOMMIT mode.

required
tables AuditTables

Audit tables built with integrity.

required
kind FailureKind | str

The failure kind to waive; only those about rows and partitions (ACKNOWLEDGEABLE).

required
scope Mapping[str, object]

What it covers; keys from SCOPE_KEYS, at least one other than table, such as {"xid_from": a, "xid_to": b} for a writer that ran without Integrity.

required
reason str

Why, for whoever reads the chain; it is stored in clear.

required
retention Mapping[int, timedelta | None] | None

As verify takes it, to observe RETIRED_EARLY.

None
transaction_retention timedelta | None

As verify takes it.

None
system_severity int | None

As verify takes it.

None
chunk_rows int

As verify takes it.

DEFAULT_CHUNK_ROWS
signer Signer | None

Signs the ack block; None leaves it unsigned.

None

Returns:

Type Description
int

The seq of the ack block.

Raises:

Type Description
ValueError

The kind cannot be waived, the scope is invalid, no failure of the kind is in the scope, the tables were built without integrity, the chain has no genesis block, or the connection is in a transaction or AUTOCOMMIT mode.

Source code in audit_trail/integrity/_verify_db.py
def acknowledge(
    connection: Connection,
    tables: AuditTables,
    kind: FailureKind | str,
    scope: Mapping[str, object],
    reason: str,
    *,
    retention: Mapping[int, timedelta | None] | None = None,
    transaction_retention: timedelta | None = None,
    system_severity: int | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
    signer: Signer | None = None,
) -> int:
    """Waive a known incident with an ``ack`` block in the chain.

    Runs ``verify`` on the connection first, and pins the
    failures of ``kind`` that ``scope`` matches as it observed them: the
    rows for a failure about a row, the root and row count for a segment,
    every field for the rest. Later verifications report those failures as
    ``ACKNOWLEDGED`` notes naming this block, instead of failing; a failure
    that is new or changed since, in the same scope, is reported again. The
    ack stays in the chain for every later reader. Takes the sealer's
    advisory lock and appends the block after the last one, hashed like
    every block, in a ``READ COMMITTED`` transaction of its own that it
    commits.

    Args:
        connection: A connection that may insert into the block table, not
            in a transaction and not in ``AUTOCOMMIT`` mode.
        tables: Audit tables built with integrity.
        kind: The failure kind to waive; only those about rows and
            partitions (``ACKNOWLEDGEABLE``).
        scope: What it covers; keys from ``SCOPE_KEYS``, at least one other
            than ``table``, such as ``{"xid_from": a, "xid_to": b}`` for a
            writer that ran without ``Integrity``.
        reason: Why, for whoever reads the chain; it is stored in clear.
        retention: As ``verify`` takes it, to observe ``RETIRED_EARLY``.
        transaction_retention: As ``verify`` takes it.
        system_severity: As ``verify`` takes it.
        chunk_rows: As ``verify`` takes it.
        signer: Signs the ack block; ``None`` leaves it unsigned.

    Returns:
        The ``seq`` of the ack block.

    Raises:
        ValueError: The kind cannot be waived, the scope is invalid, no
            failure of the kind is in the scope, the tables were built
            without integrity, the chain has no genesis block, or the
            connection is in a transaction or ``AUTOCOMMIT`` mode.
    """
    failure = failure_kind(str(kind))
    checked = check_scope(scope)
    options = verify_options(
        retention, transaction_retention, system_severity, chunk_rows
    )
    block = block_table(tables)
    if getattr(connection.connection.dbapi_connection, "autocommit", False):
        raise ValueError("acknowledge needs a transaction, not AUTOCOMMIT")
    if connection.in_transaction():
        raise ValueError(
            "acknowledge runs its own transaction; pass a connection that is "
            "not in a transaction"
        )
    report = run_verification(connection, tables, block, options)
    wanted = Ack(0, failure, checked)
    pins = {pin_key(f): pin(f) for f in report.failures if wanted.in_scope(f)}
    if not pins:
        raise ValueError(
            f"no {failure} failure in this scope; an ack would waive nothing"
        )
    waives = [pins[key] for key in sorted(pins, key=repr)]
    with connection.begin():
        connection.execute(text("SET TRANSACTION ISOLATION LEVEL READ COMMITTED"))
        # Blocks until no sealer runs; later statements see its block.
        _pg.xact_lock(connection, _pg.lock_key(block))
        created = connection.execute(
            text("SELECT to_regclass(:block) IS NOT NULL"),
            {"block": _pg.regclass(connection, block)},
        ).scalar_one()
        if not created:
            raise ValueError(missing_block_table(block))
        genesis = connection.execute(
            select(block.c.kind, block.c.body).where(block.c.seq == 1)
        ).one_or_none()
        last = last_block(connection, block)
        if genesis is None or genesis.kind != "genesis" or last is None:
            raise ValueError(
                f"{block.fullname} has no genesis block; run "
                "migrations.write_genesis() first"
            )
        chain = str(parse_body(bytes(genesis.body))["chain"])
        seq = int(last.seq) + 1
        body = ack_body(
            chain,
            seq,
            failure=failure.value,
            scope=checked,
            waives=waives,
            reason=reason,
        )
        insert_block(
            connection, block, seq, "ack", bytes(last.block_hash), body, signer
        )
    return seq

averify async

averify(
    engine: AsyncEngine,
    tables: AuditTables,
    *,
    retention: Mapping[int, timedelta | None] | None = None,
    transaction_retention: timedelta | None = None,
    system_severity: int | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
    checkpoints: Iterable[Checkpoint | str] = (),
    verifier: SignatureVerifier | None = None,
    require_signatures: bool = False,
    key_history: KeyHistory | None = None,
    since: VerificationReport | None = None,
) -> VerificationReport

Async verify, for an AsyncEngine; the same arguments.

Runs verify's reads on one connection through run_sync.

Raises:

Type Description
TypeError

The engine is a sync Engine; use verify.

ValueError

As verify.

Source code in audit_trail/integrity/_verify_db.py
async def averify(
    engine: AsyncEngine,
    tables: AuditTables,
    *,
    retention: Mapping[int, timedelta | None] | None = None,
    transaction_retention: timedelta | None = None,
    system_severity: int | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
    checkpoints: Iterable[Checkpoint | str] = (),
    verifier: SignatureVerifier | None = None,
    require_signatures: bool = False,
    key_history: KeyHistory | None = None,
    since: VerificationReport | None = None,
) -> VerificationReport:
    """Async ``verify``, for an ``AsyncEngine``; the same arguments.

    Runs ``verify``'s reads on one connection through
    ``run_sync``.

    Raises:
        TypeError: The engine is a sync ``Engine``; use ``verify``.
        ValueError: As ``verify``.
    """
    from sqlalchemy.ext.asyncio import AsyncEngine

    if not isinstance(engine, AsyncEngine):
        raise TypeError("the engine is sync; use verify")
    options = verify_options(
        retention,
        transaction_retention,
        system_severity,
        chunk_rows,
        checkpoints,
        verifier,
        require_signatures,
        key_history,
        since,
    )
    block = block_table(tables)
    async with engine.connect() as conn:
        return await conn.run_sync(
            lambda sync_conn: run_verification(sync_conn, tables, block, options)
        )

verify

verify(
    engine: Engine,
    tables: AuditTables,
    *,
    retention: Mapping[int, timedelta | None] | None = None,
    transaction_retention: timedelta | None = None,
    system_severity: int | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
    checkpoints: Iterable[Checkpoint | str] = (),
    verifier: SignatureVerifier | None = None,
    require_signatures: bool = False,
    key_history: KeyHistory | None = None,
    since: VerificationReport | None = None,
) -> VerificationReport

Check the hash chain and every row it seals; report all failures.

Runs on one connection of its own from engine, which it holds only between short READ ONLY transactions; it takes no lock, so runs side by side are fine and a pool of one does. It reads the catalog, then the chain, then the horizon, then each partition in chunks of chunk_rows rows, each in its own transaction, keyset-paged by (xid, id). A partition dropped during the run is read again once from the catalog; dropped again, it is reported as absent.

Parameters:

Name Type Description Default
engine Engine

An engine whose role can read the audit tables, the block table and the catalog.

required
tables AuditTables

Audit tables built with integrity.

required
retention Mapping[int, timedelta | None] | None

Retention by severity, as drop_expired takes it. Given, a retire block whose partition was still inside its retention is RETIRED_EARLY.

None
transaction_retention timedelta | None

Retention of the transaction table, as drop_expired takes it.

None
system_severity int | None

Severity of the audit.scrubbed records, the trail's system_severity. Given, an erasure whose record was sealed into a retired partition of that severity is ERASED_RECEIPT_RETIRED; otherwise it is SCRUB_COUNT_MISMATCH.

None
chunk_rows int

Rows read per transaction, at least 1.

DEFAULT_CHUNK_ROWS
checkpoints Iterable[Checkpoint | str]

Trusted checkpoints, kept off the database host, as Checkpoint objects or the note texts to_note gave. Each must name a block of the chain with its hash: a chain shorter than one is TRUNCATED, another hash at its seq is CHAIN_MISMATCH, and either one explained by a fork block after the fork's own prior checkpoint, signed by a key verifier knows, is a FORKED note; only a checkpoint taken before the fork (in an earlier incarnation) is explained. With verifier, a signed checkpoint must verify by c2sp.org/signed-note rules, or it is BAD_SIGNATURE / UNKNOWN_KEY and is not used. The report is ANCHORED when one matched, and the blocks after the newest match are an UNANCHORED_TAIL note.

()
verifier SignatureVerifier | None

Checks the signatures of signed blocks and checkpoints. Given, a fork block that no key it knows signed is also a FORKED_UNSIGNED note.

None
require_signatures bool

Every block and every checkpoint must be signed by a key verifier knows.

False
key_history KeyHistory | None

When each key was valid, by block seq. Given, a block signature is checked against its key's window at the block's seq, a checkpoint signature at the seq the checkpoint names: outside it is KEY_NOT_VALID (before valid_from, from retired_at, or a key without a window), or KEY_COMPROMISED from compromised_from, and the signature counts as none. Needs verifier.

None
since VerificationReport | None

An earlier report without failures, kept by the caller. Its head must still be in the chain, with its hash, or the run is TRUNCATED / CHAIN_MISMATCH. While the chain is in the head's incarnation, only the rows after the head's sealed horizon are read and compared with the seal blocks after it; every block is still checked, and the scrub counts, which need every row, are left to the next full run. After a fork since, the run is a full one. report.since says which it was.

None

Returns:

Type Description
VerificationReport

The report.

Raises:

Type Description
TypeError

The engine is an AsyncEngine; use averify.

ValueError

The tables were built without integrity, the chain has no genesis block, chunk_rows is below 1, a checkpoint text is not a checkpoint (a NoteError), require_signatures or key_history has no verifier, since has failures, or the database is a logical-replication subscriber of the block table: its rows carry the publisher's transaction ids, so verify on the publisher.

Source code in audit_trail/integrity/_verify_db.py
def verify(
    engine: Engine,
    tables: AuditTables,
    *,
    retention: Mapping[int, timedelta | None] | None = None,
    transaction_retention: timedelta | None = None,
    system_severity: int | None = None,
    chunk_rows: int = DEFAULT_CHUNK_ROWS,
    checkpoints: Iterable[Checkpoint | str] = (),
    verifier: SignatureVerifier | None = None,
    require_signatures: bool = False,
    key_history: KeyHistory | None = None,
    since: VerificationReport | None = None,
) -> VerificationReport:
    """Check the hash chain and every row it seals; report all failures.

    Runs on one connection of its own from ``engine``,
    which it holds only between short ``READ ONLY`` transactions; it takes
    no lock, so runs side by side are fine and a pool of one does. It reads
    the catalog, then the chain, then the horizon, then each partition in
    chunks of ``chunk_rows`` rows, each in its own transaction, keyset-paged
    by ``(xid, id)``. A partition dropped during the run is read again once
    from the catalog; dropped again, it is reported as absent.

    Args:
        engine: An engine whose role can read the audit tables, the block
            table and the catalog.
        tables: Audit tables built with integrity.
        retention: Retention by severity, as ``drop_expired`` takes it.
            Given, a retire block whose partition was still inside its
            retention is ``RETIRED_EARLY``.
        transaction_retention: Retention of the transaction table, as
            ``drop_expired`` takes it.
        system_severity: Severity of the ``audit.scrubbed`` records, the
            trail's ``system_severity``. Given, an erasure whose record was
            sealed into a retired partition of that severity is
            ``ERASED_RECEIPT_RETIRED``; otherwise it is
            ``SCRUB_COUNT_MISMATCH``.
        chunk_rows: Rows read per transaction, at least 1.
        checkpoints: Trusted checkpoints, kept off the database host, as
            ``Checkpoint`` objects or the note texts ``to_note`` gave. Each
            must name a block of the chain with its hash: a chain shorter
            than one is ``TRUNCATED``, another hash at its ``seq`` is
            ``CHAIN_MISMATCH``, and either one explained by a fork block
            after the fork's own prior checkpoint, signed by a key
            ``verifier`` knows, is a ``FORKED`` note; only a checkpoint
            taken before the fork (in an earlier incarnation) is explained.
            With ``verifier``, a signed checkpoint must verify by
            c2sp.org/signed-note rules, or it is ``BAD_SIGNATURE`` /
            ``UNKNOWN_KEY`` and is not used. The
            report is ``ANCHORED`` when one matched, and the blocks after
            the newest match are an ``UNANCHORED_TAIL`` note.
        verifier: Checks the signatures of signed blocks and checkpoints.
            Given, a fork block that no key it knows signed is also a
            ``FORKED_UNSIGNED`` note.
        require_signatures: Every block and every checkpoint must be
            signed by a key ``verifier`` knows.
        key_history: When each key was valid, by block ``seq``. Given, a
            block signature is checked against its key's window at the
            block's ``seq``, a checkpoint signature at the ``seq`` the
            checkpoint names: outside it is ``KEY_NOT_VALID`` (before
            ``valid_from``, from ``retired_at``, or a key without a window),
            or ``KEY_COMPROMISED`` from ``compromised_from``, and the
            signature counts as none. Needs ``verifier``.
        since: An earlier report without failures, kept by the caller. Its
            head must still be in the chain, with its hash, or the run is
            ``TRUNCATED`` / ``CHAIN_MISMATCH``. While the chain is in the
            head's incarnation, only the rows after the head's sealed
            horizon are read and compared with the seal blocks after it;
            every block is still checked, and the scrub counts, which need
            every row, are left to the next full run. After a fork since,
            the run is a full one. ``report.since`` says which it was.

    Returns:
        The report.

    Raises:
        TypeError: The engine is an ``AsyncEngine``; use ``averify``.
        ValueError: The tables were built without integrity, the chain has
            no genesis block, ``chunk_rows`` is below 1, a checkpoint text
            is not a checkpoint (a ``NoteError``), ``require_signatures``
            or ``key_history`` has no ``verifier``, ``since`` has failures,
            or the database is a logical-replication
            subscriber of the block table: its rows carry the publisher's
            transaction ids, so verify on the publisher.
    """
    if not isinstance(engine, Engine):
        raise TypeError("the engine is async; use averify")
    options = verify_options(
        retention,
        transaction_retention,
        system_severity,
        chunk_rows,
        checkpoints,
        verifier,
        require_signatures,
        key_history,
        since,
    )
    block = block_table(tables)
    with engine.connect() as conn:
        return run_verification(conn, tables, block, options)

audit_trail.integrity.ed25519

The reference signer and verifier: Ed25519, with cryptography.

Needs the sqlalchemy-audit-trail[integrity] extra; importing this module without it raises ImportError naming the extra. The rest of the library never imports it or cryptography.

Keys are named the way C2SP signed notes name them (c2sp.org/signed-note), so checkpoints signed with them can be checked with existing note tooling:

  • the verifier key (vkey) is <name>+<key hash>+base64(0x01 || public key);
  • the signer key (skey) is PRIVATE+KEY+<name>+<key hash>+base64(0x01 || 32-byte seed).

A key on the database host adds attribution only: whoever controls the host can use it. For a signature that catches a rewritten chain, keep the key elsewhere, or implement Signer against a KMS or HSM.

Ed25519Signer

Ed25519Signer(name: str, private_key: Ed25519PrivateKey)

Signs with an Ed25519 private key.

Parameters:

Name Type Description Default
name str

The key name, such as "audit.example.com/sealer-2026": no spaces and no +. A new name for each new key makes rotation easy to follow.

required
private_key Ed25519PrivateKey

The key.

required

Attributes:

Name Type Description
name

The key name.

key_id

<name>+<key hash>.

algorithm

"ed25519".

Source code in audit_trail/integrity/_ed25519.py
def __init__(self, name: str, private_key: Ed25519PrivateKey) -> None:
    self._key = private_key
    self.name = name
    self.public_key = private_key.public_key().public_bytes(
        Encoding.Raw, PublicFormat.Raw
    )
    self.key_id = make_key_id(name, note_key_hash(name, _TYPE, self.public_key))

skey property

skey: str

The signer key as text; keep it secret.

vkey property

vkey: str

The verifier key as text, for Ed25519Verifier.

generate classmethod

generate(name: str) -> Ed25519Signer

A signer with a new random key.

Source code in audit_trail/integrity/_ed25519.py
@classmethod
def generate(cls, name: str) -> Ed25519Signer:
    """A signer with a new random key."""
    return cls(name, Ed25519PrivateKey.generate())

from_seed classmethod

from_seed(name: str, seed: bytes) -> Ed25519Signer

A signer from the 32-byte RFC 8032 private key (the seed).

Source code in audit_trail/integrity/_ed25519.py
@classmethod
def from_seed(cls, name: str, seed: bytes) -> Ed25519Signer:
    """A signer from the 32-byte RFC 8032 private key (the seed)."""
    return cls(name, Ed25519PrivateKey.from_private_bytes(seed))

from_skey classmethod

from_skey(skey: str) -> Ed25519Signer

A signer from its PRIVATE+KEY+... encoding (see skey).

Raises:

Type Description
ValueError

Not an Ed25519 signer key, or the key hash does not match the key.

Source code in audit_trail/integrity/_ed25519.py
@classmethod
def from_skey(cls, skey: str) -> Ed25519Signer:
    """A signer from its ``PRIVATE+KEY+...`` encoding (see ``skey``).

    Raises:
        ValueError: Not an Ed25519 signer key, or the key hash does not
            match the key.
    """
    if not skey.startswith(_SKEY_PREFIX):
        raise ValueError("a signer key starts with PRIVATE+KEY+")
    key = parse_vkey(
        skey.removeprefix(_SKEY_PREFIX),
        _REFUSAL,
        _TYPE,
        accept=lambda material: len(material) == 32,
    )
    signer = cls.from_seed(key.name, key.material)
    if signer.key_id != key.key_id:
        raise ValueError("the signer key's hash does not match its key")
    return signer

sign

sign(message: bytes) -> bytes

The 64-byte RFC 8032 signature of message.

Source code in audit_trail/integrity/_ed25519.py
def sign(self, message: bytes) -> bytes:
    """The 64-byte RFC 8032 signature of ``message``."""
    return self._key.sign(message)

Ed25519Verifier

Ed25519Verifier(vkeys: Iterable[str])

Checks Ed25519 signatures of known keys.

Parameters:

Name Type Description Default
vkeys Iterable[str]

The verifier keys, as Ed25519Signer.vkey gives them. Give the old keys with the new one while blocks or checkpoints signed by them are still checked.

required

Raises:

Type Description
ValueError

A key is not an Ed25519 verifier key, its key hash does not match it, or two keys have one key_id (a collision of the 4-byte key hash): a signature could not tell them apart.

Source code in audit_trail/integrity/_ed25519.py
def __init__(self, vkeys: Iterable[str]) -> None:
    self._keys = load_vkeys(
        vkeys,
        _TYPE,
        _REFUSAL,
        Ed25519PublicKey.from_public_bytes,
        accept=lambda material: len(material) == 32,
    )

key_algorithm

key_algorithm(key_id: str) -> str | None

"ed25519" for a known key, else None.

Source code in audit_trail/integrity/_ed25519.py
def key_algorithm(self, key_id: str) -> str | None:
    """``"ed25519"`` for a known key, else ``None``."""
    return ED25519 if key_id in self._keys else None

verify

verify(
    key_id: str,
    algorithm: str,
    message: bytes,
    signature: bytes,
) -> bool

Whether signature is the key's Ed25519 signature of message.

Source code in audit_trail/integrity/_ed25519.py
def verify(
    self, key_id: str, algorithm: str, message: bytes, signature: bytes
) -> bool:
    """Whether ``signature`` is the key's Ed25519 signature of ``message``."""
    key = self._keys.get(key_id)
    if key is None or algorithm != ED25519:
        return False
    try:
        key.verify(signature, message)
    except InvalidSignature:
        return False
    return True

audit_trail.integrity.ecdsa

The ECDSA P-256 signer and verifier, with cryptography.

Needs the sqlalchemy-audit-trail[integrity] extra; importing this module without it raises ImportError naming the extra. The rest of the library never imports it or cryptography.

Keys and signatures follow C2SP signed notes (c2sp.org/signed-note), signature type 0x02, as the transparency-dev note tooling implements it:

  • the verifier key (vkey) is <name>+<key hash>+base64(0x02 || DER SubjectPublicKeyInfo), the key hash being the first 4 bytes of SHA-256 of the DER SubjectPublicKeyInfo;
  • a signature is the DER ECDSA signature of SHA-256(message), the form a KMS or an HSM returns for an ECDSA_SHA_256 key.

audit_trail.integrity.keys.KeyVerifier checks Ed25519 and P-256 keys together.

EcdsaP256Signer

EcdsaP256Signer(
    name: str, private_key: EllipticCurvePrivateKey
)

Signs with an ECDSA private key on NIST P-256.

Parameters:

Name Type Description Default
name str

The key name, such as "audit.example.com/sealer-2026": no spaces and no +.

required
private_key EllipticCurvePrivateKey

The key, on the SECP256R1 curve.

required

Attributes:

Name Type Description
name

The key name.

public_key

The DER SubjectPublicKeyInfo of the public key.

key_id

<name>+<key hash>.

algorithm

"ecdsa-p256-sha256".

Raises:

Type Description
ValueError

The key is not an ECDSA key on P-256.

Source code in audit_trail/integrity/_ecdsa.py
def __init__(self, name: str, private_key: ec.EllipticCurvePrivateKey) -> None:
    if not isinstance(private_key, ec.EllipticCurvePrivateKey) or not isinstance(
        private_key.curve, ec.SECP256R1
    ):
        raise ValueError("not an ECDSA key on P-256")
    self._key = private_key
    self.name = name
    self.public_key = _spki(private_key.public_key())
    self.key_id = make_key_id(name, note_key_hash(name, _TYPE, self.public_key))

vkey property

vkey: str

The verifier key as text, for EcdsaP256Verifier.

generate classmethod

generate(name: str) -> EcdsaP256Signer

A signer with a new random key.

Source code in audit_trail/integrity/_ecdsa.py
@classmethod
def generate(cls, name: str) -> EcdsaP256Signer:
    """A signer with a new random key."""
    return cls(name, ec.generate_private_key(ec.SECP256R1()))

from_pem classmethod

from_pem(
    name: str, pem: bytes, password: bytes | None = None
) -> EcdsaP256Signer

A signer from a PEM private key (PKCS #8 or SEC 1).

Raises:

Type Description
ValueError

Not a PEM private key, or not an ECDSA key on P-256.

Source code in audit_trail/integrity/_ecdsa.py
@classmethod
def from_pem(
    cls, name: str, pem: bytes, password: bytes | None = None
) -> EcdsaP256Signer:
    """A signer from a PEM private key (PKCS #8 or SEC 1).

    Raises:
        ValueError: Not a PEM private key, or not an ECDSA key on P-256.
    """
    key = load_pem_private_key(pem, password)
    if not isinstance(key, ec.EllipticCurvePrivateKey):
        raise ValueError("not an ECDSA key on P-256")
    return cls(name, key)

sign

sign(message: bytes) -> bytes

The DER ECDSA signature of SHA-256(message), about 70 bytes.

Not deterministic: each call draws a new nonce.

Source code in audit_trail/integrity/_ecdsa.py
def sign(self, message: bytes) -> bytes:
    """The DER ECDSA signature of ``SHA-256(message)``, about 70 bytes.

    Not deterministic: each call draws a new nonce.
    """
    return self._key.sign(message, _ALGORITHM)

EcdsaP256Verifier

EcdsaP256Verifier(vkeys: Iterable[str])

Checks ECDSA P-256 signatures of known keys.

Parameters:

Name Type Description Default
vkeys Iterable[str]

The verifier keys, as EcdsaP256Signer.vkey gives them, or as the transparency-dev note tooling writes them.

required

Raises:

Type Description
ValueError

A key is not an ECDSA P-256 verifier key, its key hash does not match it, or two keys have one key_id.

Source code in audit_trail/integrity/_ecdsa.py
def __init__(self, vkeys: Iterable[str]) -> None:
    self._keys = load_vkeys(vkeys, _TYPE, _REFUSAL, _public_key)

key_algorithm

key_algorithm(key_id: str) -> str | None

"ecdsa-p256-sha256" for a known key, else None.

Source code in audit_trail/integrity/_ecdsa.py
def key_algorithm(self, key_id: str) -> str | None:
    """``"ecdsa-p256-sha256"`` for a known key, else ``None``."""
    return ECDSA_P256 if key_id in self._keys else None

verify

verify(
    key_id: str,
    algorithm: str,
    message: bytes,
    signature: bytes,
) -> bool

Whether signature is the key's ECDSA signature of message.

The signature must be DER, as the signer writes it: another encoding of the same (r, s) is refused.

Source code in audit_trail/integrity/_ecdsa.py
def verify(
    self, key_id: str, algorithm: str, message: bytes, signature: bytes
) -> bool:
    """Whether ``signature`` is the key's ECDSA signature of ``message``.

    The signature must be DER, as the signer writes it: another encoding
    of the same ``(r, s)`` is refused.
    """
    key = self._keys.get(key_id)
    if key is None or algorithm != ECDSA_P256 or not _is_der(signature):
        return False
    try:
        key.verify(signature, message, _ALGORITHM)
    except InvalidSignature:
        return False
    return True

audit_trail.integrity.keys

One verifier for Ed25519 and ECDSA P-256 keys, with cryptography.

Needs the sqlalchemy-audit-trail[integrity] extra; importing this module without it raises ImportError naming the extra.

KeyVerifier reads verifier keys of both types, as Ed25519Signer.vkey and EcdsaP256Signer.vkey give them, so blocks and checkpoints signed by either, or a checkpoint signed by both, are checked with one verifier.

KeyVerifier

KeyVerifier(vkeys: Iterable[str])

Checks signatures of known keys, Ed25519 and ECDSA P-256 alike.

Each verifier key names its own type in its first byte (0x01 Ed25519, 0x02 ECDSA), so one list can hold both, such as an Ed25519 sealer key and a P-256 key in a KMS. A note signed by keys of both types is checked in one verify, each signature by its key's algorithm.

Parameters:

Name Type Description Default
vkeys Iterable[str]

The verifier keys, as Ed25519Signer.vkey and EcdsaP256Signer.vkey give them.

required

Raises:

Type Description
ValueError

A key is not a verifier key of a supported type, its key hash does not match it, or two keys have one key_id.

Source code in audit_trail/integrity/_keys.py
def __init__(self, vkeys: Iterable[str]) -> None:
    by_type: dict[int, list[str]] = {_ED25519: [], _ECDSA: []}
    key_ids: dict[int, set[str]] = {_ED25519: set(), _ECDSA: set()}
    for vkey in vkeys:
        refusal = f"{vkey!r} is not an Ed25519 (0x01) or ECDSA (0x02) key"
        key = parse_vkey(vkey, refusal)
        if key.signature_type not in by_type:
            raise ValueError(refusal)
        by_type[key.signature_type].append(vkey)
        key_ids[key.signature_type].add(key.key_id)
    self._ed25519 = Ed25519Verifier(by_type[_ED25519])
    self._ecdsa = EcdsaP256Verifier(by_type[_ECDSA])
    shared = key_ids[_ED25519] & key_ids[_ECDSA]
    if shared:
        raise ValueError(f"two different keys have the key id {min(shared)}")

key_algorithm

key_algorithm(key_id: str) -> str | None

"ed25519" or "ecdsa-p256-sha256" for a known key, else None.

Source code in audit_trail/integrity/_keys.py
def key_algorithm(self, key_id: str) -> str | None:
    """``"ed25519"`` or ``"ecdsa-p256-sha256"`` for a known key, else ``None``."""
    return self._ed25519.key_algorithm(key_id) or self._ecdsa.key_algorithm(key_id)

verify

verify(
    key_id: str,
    algorithm: str,
    message: bytes,
    signature: bytes,
) -> bool

Whether signature is the key's signature of message.

Source code in audit_trail/integrity/_keys.py
def verify(
    self, key_id: str, algorithm: str, message: bytes, signature: bytes
) -> bool:
    """Whether ``signature`` is the key's signature of ``message``."""
    if algorithm == ED25519:
        return self._ed25519.verify(key_id, algorithm, message, signature)
    if algorithm == ECDSA_P256:
        return self._ecdsa.verify(key_id, algorithm, message, signature)
    return False