audit_trail.ledger¶
An append-only evidence ledger in its own tables.
A ledger holds named chains. Each chain is a log of entries the
application writes explicitly, sealed in the writer's own transaction: a
SECURITY DEFINER function takes the chain's lock, gives each entry the
next gapless seq, reads the append time, computes the entry's RFC 6962
leaf hash and the new tree root, and returns a Head per entry. The
application role may call that function and read the tables, but not write
them, so it can add entries but not change, reorder or delete existing ones.
The ledger needs no AuditTrail and no extra: it can sit next to the
row audit and write in the same transaction.
build_ledger_tablesdeclares the tables,create_ledger_tablescreates them with the functions, andledger_grant_statementslists the grants of the application role.create_chainstarts a chain with itsledger.chain_startedentry, which records its config.addbuffers an entry in a session, sync or async, to be appended at its commit; the returnedPendingHeadgets the head once the transaction has committed. It is the recommended way to write from a session.appendandappend_manyappend entries on a connection,acreate_chain,aappendandaappend_manyon anAsyncConnection.verifychecks a chain from its stored rows, and against the trusted checkpoints given ascheckpoints=, and returns aLedgerReport;inclusion_proofandconsistency_proofserve proofs from the stored nodes, which a client checks against roots it trusts withInclusionProof.verifyandConsistencyProof.verify. Async formsaverify,ainclusion_proofandaconsistency_proof.erasedeletes an entry's payload through a second definer function and appends its receipt,ledger.erased;change_configreplaces a chain's config, recorded inledger.config_changed;aeraseandachange_configare their async forms.ledger_eraser_grant_statementslists the grants of an optional eraser role, andledger_reader_grant_statementsthose of a read-only verifier role.- Every append first checks whether the database was restored, and starts
a new incarnation with a
ledger.incarnation_startedentry when it was (see "Restore detection" inaudit_trail.ledger._migrations).record_maintenanceandarecord_maintenanceappendledger.maintenancewith a reason code, to explain an incarnation that planned work started. Apg_upgradegivesledger.cluster_changedand no new incarnation;confirm_upgradeandaconfirm_upgradeappendledger.upgrade_confirmedonce the owner has checked the chain against a checkpoint taken before it, and until then a verifier notes itUNCONFIRMED_UPGRADE. prepare_checkpointreturns the unsigned checkpoint of a verified head, a C2SP tlog-checkpoint whose origin names the chain and its incarnation, holding no lock while the host signs it;record_checkpointchecks the signed note against the key history and the tree and appends it asledger.checkpoint, once per note. A checkpoint may commit to the erasure journal of its size (LedgerJournal,erasure_journal), and both return the consistency proof from the newest checkpoint before it. Async formsaprepare_checkpoint,arecord_checkpointandaerasure_journal.export_bundlewrites a range of a chain to a bundle of stream type"ledger", whichaudit_trail.integrity.verify_bundleand the command line check without the database, withverify's findings;verify_bundlehere is the same check, typed for a ledger bundle.record_bundle_manifestappendsledger.bundle_manifest, the digest of a bundle's host files, so that the log anchors them. Async formsaexport_bundleandarecord_bundle_manifest. The format is indocs/spec/ledger-v1.md.record_restorerecords a database restore, run by the owner: it appendsledger.restoredwith a trusted signed checkpoint, the lost range and the incarnation it explains, and erases again what the checkpoint's journal erased, within the prefix proven shared with it (seeaudit_trail.ledger._restore). Async formarecord_restore. Each checkpoint comes with a consistency proof from the checkpoint before it;RestoreKitkeeps the signed note, the journal and that proof together as JSON, off the database, andrecord_restoretakes it askit=.
A call denied a privilege (SQLSTATE 42501) raises
LedgerPermissionError, both a PermissionError and a SQLAlchemy
ProgrammingError, whose message says who may do it and the grant to
run; the driver's error is its __cause__.
The integrity names a ledger caller needs are re-exported here, so that
audit_trail.ledger alone is enough: Status, Anchor,
KeyHistory and KeyWindow, Signer and SignatureVerifier,
and the errors NoteError, BundleError and
CanonicalEncodingError. The reference signers stay in
audit_trail.integrity.ed25519 and audit_trail.integrity.ecdsa.
The entry body, the leaf input and the tree are described in
audit_trail.ledger._entry. Types and reason codes starting with
ledger. are the package's.
BUNDLE_MANIFEST
module-attribute
¶
The type of the entry record_bundle_manifest appends.
Its attributes are {"sha256": <base64>}: the digest of the host files
of a bundle (host_files_digest), so that a bundle holding the entry
anchors its host files in the log.
CHAIN_STARTED
module-attribute
¶
The type of a chain's first entry, which holds the chain's config.
CHECKPOINT
module-attribute
¶
The type of the entry record_checkpoint appends.
Its attributes are {"note": <signed note>}: a signed ledger checkpoint
(_checkpoint) of a head of the chain, in the incarnation the entry is
appended in.
CLUSTER_CHANGED
module-attribute
¶
The type of the entry an append writes first after a pg_upgrade.
A new system identifier with a higher major version and the same state-table
OID: no new incarnation. Its attributes are {"from": <identity>, "to":
<identity>}, as in ledger.incarnation_started. A verifier notes it
unconfirmed until a ledger.upgrade_confirmed entry names it.
CONFIG_CHANGED
module-attribute
¶
The type of the entry that records a chain's new config, whole.
ERASED
module-attribute
¶
The type of an erasure's receipt.
Its attributes are entry_id, incarnation and seq of the erased
entry, and the reason_code.
INCARNATION_STARTED
module-attribute
¶
The type of the entry an append writes first when it detects a restore.
It is the first entry of the new incarnation. Its attributes::
{"cause": "new_cluster" | "recreated" | "new_timeline",
"from": <identity>, "to": <identity>}
where an identity is {"server_major": <int>, "system_identifier":
"<decimal>", "table_oid": <int>, "timeline": <int>}: the identity stored
before and the one observed. The system identifier is a string, since it
does not fit a double.
MAINTENANCE
module-attribute
¶
The type of the entry record_maintenance appends.
Its attributes are {"incarnation": <int>, "reason": <reason code>}: the
incarnation it explains, the chain's incarnation when it was appended (so
also the entry's own), and the host's reason code.
NEW_CLUSTER
module-attribute
¶
The cause of an incarnation: the state table's OID and the system identifier changed (a dump restored into a new cluster), or the system identifier changed without a higher major version.
NEW_TIMELINE
module-attribute
¶
The cause of an incarnation: the WAL timeline changed (point-in-time recovery, a standby promoted).
RECREATED
module-attribute
¶
The cause of an incarnation: the state table's OID changed in the same cluster (a dump restored into it).
RESTORED
module-attribute
¶
The type of the entry record_restore appends after a restore.
Its attributes::
{"checkpoint": <signed note>, "incarnation": <int>,
"journal": <journal text> | null,
"lost": [<first>, <last>] | null,
"proof": [{"path": [<b64>, ...], "root": <b64>, "size": <int>}, ...],
"proven": {"root": <b64>, "size": <int>} | null,
"reapplied": <int>, "restored_size": <int>}
checkpoint is the signed ledger checkpoint of the history the restore
lost part of; incarnation the incarnation the entry explains, its own;
journal the canonical text of the checkpoint's erasure journal when the
checkpoint is above the restored size and one was given, null
otherwise (at or below it, the chain's receipts are the journal);
restored_size the chain's size the restore brought it back to; lost
the seq range above it that the checkpoint knew, null when the
checkpoint is not above it; proven the size and root of the
proven-shared prefix, null when nothing is proven; proof the
consistency proofs from it to the checkpoint; reapplied how many
re-applied receipts follow it. See audit_trail.ledger._restore.
UPGRADE_CONFIRMED
module-attribute
¶
The type of the entry confirm_upgrade appends.
The owner's statement that a ledger.cluster_changed entry was a real
pg_upgrade of this database, checked against a checkpoint taken before
it, and not a data-only restore of an older dump into a fresh cluster of a
higher major version, which restore detection cannot tell from one. Its
attributes are {"entry_id": <uuid>, "incarnation": <int>, "seq": <int>}:
those of the ledger.cluster_changed entry it confirms.
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.
KeyHistory ¶
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]
|
|
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
A key id is empty or a window is not a |
Source code in audit_trail/integrity/_history.py
from_vkeys
classmethod
¶
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 |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
A key is not a verifier key. |
Source code in audit_trail/integrity/_history.py
to_json ¶
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
from_json
classmethod
¶
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 |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
The text is not JSON (the JSON error is the cause),
is not the form |
Source code in audit_trail/integrity/_history.py
check ¶
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
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 |
retired_at |
int | None
|
The first |
compromised_from |
int | None
|
The first |
Raises:
| Type | Description |
|---|---|
ValueError
|
A position is not an integer of at least 1, or
|
problem ¶
Why a signature at position does not count; None if it does.
Source code in audit_trail/integrity/_history.py
NoteError ¶
Bases: ValueError
A note that is not a well-formed signed note, or that fails to verify.
Attributes:
| Name | Type | Description |
|---|---|---|
reason |
|
Source code in audit_trail/integrity/_note.py
Signer ¶
Bases: Protocol
Signs blocks and checkpoints.
Attributes:
| Name | Type | Description |
|---|---|---|
key_id |
str
|
|
algorithm |
str
|
Name of the signature algorithm, such as |
Anchor ¶
Bases: StrEnum
Whether the chain was checked against a trusted checkpoint.
Status ¶
Bases: StrEnum
Overall result of a verification.
CheckpointRefusedError ¶
Bases: ValueError
A checkpoint was not prepared or not recorded; nothing was written.
Attributes:
| Name | Type | Description |
|---|---|---|
report |
For |
Source code in audit_trail/ledger/_anchor.py
PreparedCheckpoint
dataclass
¶
PreparedCheckpoint(
checkpoint: LedgerCheckpoint,
journal: LedgerJournal | None,
report: LedgerReport,
proof: ConsistencyProof | None = None,
)
What prepare_checkpoint returns.
Attributes:
| Name | Type | Description |
|---|---|---|
checkpoint |
LedgerCheckpoint
|
The unsigned checkpoint: sign |
journal |
LedgerJournal | None
|
The erasure journal the checkpoint commits to, or |
report |
LedgerReport
|
The verification the checkpoint rests on. |
proof |
ConsistencyProof | None
|
The consistency proof from the newest checkpoint recorded
before (or |
kit ¶
The restore kit of the checkpoint once signed: the signed note,
the journal and the proof. Keep its to_json() off the database.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
signed_note
|
LedgerCheckpoint | str
|
The checkpoint signed, or its note text. |
required |
Raises:
| Type | Description |
|---|---|
ValueError
|
The note is not this checkpoint (its text differs). |
NoteError
|
The note is not a ledger checkpoint. |
Source code in audit_trail/ledger/_anchor.py
RecordedCheckpoint
dataclass
¶
RecordedCheckpoint(
seq: int,
incarnation: int,
leaf_hash: bytes,
checkpoint: LedgerCheckpoint,
created: bool,
head: Head | None,
journal: LedgerJournal | None = None,
proof: ConsistencyProof | None = None,
)
What record_checkpoint stored.
Attributes:
| Name | Type | Description |
|---|---|---|
seq |
int
|
The |
incarnation |
int
|
That entry's incarnation. |
leaf_hash |
bytes
|
That entry's leaf hash. |
checkpoint |
LedgerCheckpoint
|
The checkpoint, with its signatures. |
created |
bool
|
|
head |
Head | None
|
The head after the entry, when this call appended it;
|
journal |
LedgerJournal | None
|
The journal the checkpoint commits to, or |
proof |
ConsistencyProof | None
|
The consistency proof from the newest checkpoint recorded
before (or |
kit
property
¶
The restore kit: the signed note, the journal and the proof.
Keep its to_json() off the database, with the backups; after a
restore, give it to record_restore(kit=...).
LedgerBusyError ¶
Bases: Exception
The chain's lock was not granted within the lock_timeout.
Another transaction is appending to the chain and has not ended. The
transaction that raised this is aborted: roll it back and retry later.
lock_timeout bounds each lock wait, not the call: set
statement_timeout to bound the total, which cancels the statement
with SQLSTATE 57014 instead of raising this.
PendingHead ¶
The head of a buffered entry, set once its transaction has committed.
add returns one per entry. Until the commit, head is None:
the entry has no sequence number yet, or only a provisional one that a
rollback would free. After the commit, head is the entry's
Head. If the entry is discarded instead (rolled back, or the session
closed without committing), discarded is True and head stays
None.
Attributes:
| Name | Type | Description |
|---|---|---|
chain |
The chain the entry goes to. |
|
entry |
The entry. |
Source code in audit_trail/ledger/_buffer.py
EntryRange
dataclass
¶
A scope of entries by seq, both ends included.
Raises:
| Type | Description |
|---|---|
ValueError
|
An end is not an integer of at least 1, or |
LedgerBundleResult
dataclass
¶
LedgerBundleResult(
chain: str,
first: int,
last: int,
entries: int,
context: int,
nodes: int,
checkpoints: int,
files: dict[str, str],
manifest: str,
manifest_sha256: str,
)
What export_bundle wrote.
Attributes:
| Name | Type | Description |
|---|---|---|
chain |
str
|
The chain. |
first |
int
|
The first entry in scope. |
last |
int
|
The last entry in scope. |
entries |
int
|
Entries in |
context |
int
|
Entries in |
nodes |
int
|
Hashes in |
checkpoints |
int
|
Checkpoints in |
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. |
manifest_sha256 |
str
|
The SHA-256 of |
LedgerCheckpoint
dataclass
¶
LedgerCheckpoint(
origin: str,
size: int,
root: bytes,
journal: bytes | None = None,
extensions: tuple[str, ...] = (),
signatures: tuple[NoteSignature, ...] = (),
)
A checkpoint of a ledger chain: origin, size and root, maybe signed.
Attributes:
| Name | Type | Description |
|---|---|---|
origin |
str
|
|
size |
int
|
The tree size, at least 1. |
root |
bytes
|
The RFC 6962 root of the first |
journal |
bytes | None
|
The commitment of the erasure journal at |
extensions |
tuple[str, ...]
|
The host's lines after the statement, signed with it. |
signatures |
tuple[NoteSignature, ...]
|
The note's signature lines; empty when unsigned. |
Raises:
| Type | Description |
|---|---|
ValueError
|
A field is invalid. |
to_note ¶
signed ¶
The checkpoint with a signature by each of signers added.
Raises:
| Type | Description |
|---|---|
NoteError
|
|
Source code in audit_trail/ledger/_checkpoint.py
verify ¶
Check the signatures; the key_id of each that verified.
Raises:
| Type | Description |
|---|---|
NoteError
|
|
Source code in audit_trail/ledger/_checkpoint.py
from_note
classmethod
¶
Read a checkpoint from its note, signed or not.
Signatures are read, not checked; verify checks them.
Raises:
| Type | Description |
|---|---|
NoteError
|
|
Source code in audit_trail/ledger/_checkpoint.py
ChainConfig
dataclass
¶
ChainConfig(
reason_codes: tuple[str, ...] = (),
protected_types: tuple[str, ...] = (),
precondition: str | None = None,
detect_restores: bool = True,
)
The config of a chain, recorded in its ledger.chain_started entry.
Attributes:
| Name | Type | Description |
|---|---|---|
reason_codes |
tuple[str, ...]
|
The reason codes an erasure of this chain may give
( |
protected_types |
tuple[str, ...]
|
The entry types that may not be erased. |
precondition |
str | None
|
The name of a SQL function an erasure must pass,
optionally schema-qualified (a bare name is in the ledger's
schema), or |
detect_restores |
bool
|
Store the cluster identity, so that appends can tell when the database was restored. Creating a chain with it on fails where the identity functions cannot be called. |
as_dict ¶
The config as the attributes of ledger.chain_started.
Source code in audit_trail/ledger/_entry.py
Entry
dataclass
¶
Entry(
type: str,
attributes: Mapping[str, Any] = dict(),
payload: Mapping[str, Any] = dict(),
actor: str | None = None,
declared_at: datetime = _now(),
type_version: int = 1,
entry_id: UUID = uuid.uuid4(),
)
One entry to append.
Attributes:
| Name | Type | Description |
|---|---|---|
type |
str
|
The entry type, matching |
attributes |
Mapping[str, Any]
|
The never-erased fields: a JSON object the host validates. It must encode canonically. |
payload |
Mapping[str, Any]
|
The erasable groups: group name ( |
actor |
str | None
|
The submitting principal, or |
declared_at |
datetime
|
The time the host declares for the entry; an aware
|
type_version |
int
|
The version of the type's schema, 1 or more. |
entry_id |
UUID
|
The stable id host tables can reference before the entry is appended; a random UUID by default. |
Head
dataclass
¶
The tree head after one entry was appended.
The head is provisional until the transaction that appended the entry
commits: a rollback frees its seq for the next append.
Attributes:
| Name | Type | Description |
|---|---|---|
incarnation |
int
|
The chain's incarnation. |
seq |
int
|
The entry's sequence number, from 1, gapless in a chain. |
leaf_hash |
bytes
|
The entry's leaf hash, 32 bytes. |
size |
int
|
The size of the tree with this entry, equal to |
root |
bytes
|
The RFC 6962 root of that tree, 32 bytes. |
(seq, leaf_hash) is the writer's receipt for its own entry; what
anchors the log is (size, root).
ErasureRefusedError ¶
Bases: ValueError
The erase function refused the erasure; nothing was erased.
The message says why: the reason code is not one of the chain's, the entry's type is protected or the package's, the entry has no payload or is erased already, or the precondition refused it (or cannot be called). The transaction is aborted: roll it back.
JournalErasure
dataclass
¶
JournalErasure(
receipt: int,
receipt_id: UUID,
entry_id: UUID,
incarnation: int,
seq: int,
reason_code: str,
)
One receipt of a journal, ordered by its seq.
Attributes:
| Name | Type | Description |
|---|---|---|
receipt |
int
|
The receipt's |
receipt_id |
UUID
|
The receipt's |
entry_id |
UUID
|
The erased entry's |
incarnation |
int
|
The erased entry's incarnation. |
seq |
int
|
The erased entry's |
reason_code |
str
|
The reason code of the erasure. |
LedgerJournal
dataclass
¶
The receipts of a chain up to a size: what a checkpoint commits to.
Keep its text (to_json) with the signed checkpoint, off the
database: after a restore, it is what record_restore erases again.
Attributes:
| Name | Type | Description |
|---|---|---|
chain |
str
|
The chain. |
size |
int
|
The checkpoint's size: every receipt with a |
erasures |
tuple[JournalErasure, ...]
|
The receipts, by |
Raises:
| Type | Description |
|---|---|
ValueError
|
A field is invalid, a receipt is above |
to_json ¶
from_json
classmethod
¶
Read a journal back from to_json.
Raises:
| Type | Description |
|---|---|
ValueError
|
The text is not a journal in its canonical form. |
Source code in audit_trail/ledger/_journal.py
RestoreKit
dataclass
¶
RestoreKit(
checkpoint: LedgerCheckpoint,
journal: LedgerJournal | None = None,
proof: tuple[ConsistencyProof, ...] = (),
)
A checkpoint's signed note, journal and consistency proof, together.
Keep to_json() off the database, next to the backups, after each
checkpoint is signed (PreparedCheckpoint.kit,
RecordedCheckpoint.kit). After a restore, give the newest kit to
record_restore(kit=...).
A kit's journal covers the erasures up to its checkpoint's size only:
an erasure made after the newest kit comes back on a restore, and
record_restore does not report it. After erasures, take a
checkpoint with a journal and keep its new kit, and keep a log of
erasures off the database, to erase again after a restore.
Attributes:
| Name | Type | Description |
|---|---|---|
checkpoint |
LedgerCheckpoint
|
The signed checkpoint. |
journal |
LedgerJournal | None
|
The journal its journal line commits to, or |
proof |
tuple[ConsistencyProof, ...]
|
Consistency proof steps of the checkpoint's chain, each starting where the one before ends, the last at the checkpoint's size and root; empty when there is none. |
Raises:
| Type | Description |
|---|---|
ValueError
|
The parts do not belong together: the journal is missing, extra, or not the one the note commits to; a step is of another chain, does not hold between the roots it carries, does not start where the one before ends, or the last does not end at the checkpoint. |
to_json ¶
The kit as canonical JSON text.
Source code in audit_trail/ledger/_kit.py
from_json
classmethod
¶
Read a kit back from its JSON text.
Signatures, the journal's commitment and the proof are checked as
the constructor checks them, not trusted: record_restore checks
them against the keys and the chain.
Raises:
| Type | Description |
|---|---|
ValueError
|
The text is not a restore kit, or its parts do not belong together. |
Source code in audit_trail/ledger/_kit.py
LedgerPermissionError ¶
LedgerPermissionError(
message: str,
statement: str | None,
params: Any,
orig: BaseException,
hide_parameters: bool = False,
connection_invalidated: bool = False,
code: str | None = None,
ismulti: bool | None = None,
)
Bases: PermissionError, ProgrammingError
A ledger call was denied a privilege (SQLSTATE 42501).
It is both a PermissionError and a SQLAlchemy ProgrammingError
(so a DBAPIError): code that caught the driver's error around a
ledger call still catches it. It keeps that error's statement,
params and orig, and the error is its __cause__.
The message is the server's, followed by who may do what was denied and the fix, as in the "Permission errors" table of the ledger guide; for an object the table does not list, it points at that table. The transaction is aborted: roll it back.
Source code in audit_trail/ledger/_permissions.py
wrap
classmethod
¶
The error for a driver error of SQLSTATE 42501, explained.
Source code in audit_trail/ledger/_permissions.py
RecordedRestore
dataclass
¶
RecordedRestore(
seq: int,
incarnation: int,
leaf_hash: bytes,
checkpoint: LedgerCheckpoint,
created: bool,
started: bool,
restored_size: int,
lost: tuple[int, int] | None,
proven_size: int,
reapplied: tuple[JournalErasure, ...],
unproven: tuple[JournalErasure, ...],
head: Head | None,
)
What record_restore stored.
Attributes:
| Name | Type | Description |
|---|---|---|
seq |
int
|
The |
incarnation |
int
|
The incarnation it explains, its own. |
leaf_hash |
bytes
|
Its leaf hash. |
checkpoint |
LedgerCheckpoint
|
The checkpoint, with its signatures. |
created |
bool
|
|
started |
bool
|
Whether the entry started its incarnation (detection was off or missed the restore), rather than explaining one that restore detection started. |
restored_size |
int
|
The size the restore brought the chain back to. |
lost |
tuple[int, int] | None
|
The |
proven_size |
int
|
The proven-shared prefix: its entries are proven to be the checkpoint's; 0 when nothing is. |
reapplied |
tuple[JournalErasure, ...]
|
The journal's erasures applied again by this call. |
unproven |
tuple[JournalErasure, ...]
|
The journal's erasures whose target is in the chain with payload, outside the proven prefix: not applied again. |
head |
Head | None
|
The head after the last entry appended; |
RestoreRefusedError ¶
Bases: CheckpointRefusedError
A restore was not recorded; nothing was written or erased.
The message says why: the checkpoint is unsigned, signed outside a key window or of another chain, the journal is not the one it commits to, the proof does not lead to it, it is not of the chain's history from before the restore, or the journal names another entry than the proven prefix holds. When the function refused it, the transaction is aborted: roll it back.
Source code in audit_trail/ledger/_anchor.py
LedgerTables
dataclass
¶
LedgerTables(
metadata: MetaData,
schema: str,
entry: Table,
state: Table,
payload: Table,
node: Table,
config: Table,
)
The ledger tables and the metadata they are bound to.
Attributes:
| Name | Type | Description |
|---|---|---|
metadata |
MetaData
|
Metadata holding the tables. |
schema |
str
|
Schema of the tables and of the ledger functions. |
entry |
Table
|
|
state |
Table
|
|
payload |
Table
|
|
node |
Table
|
|
config |
Table
|
|
ConsistencyProof
dataclass
¶
ConsistencyProof(
chain: str,
old_size: int,
new_size: int,
old_root: bytes,
new_root: bytes,
path: tuple[bytes, ...],
)
An RFC 9162 consistency proof between two sizes of a chain's tree.
Check it with verify(old_root, new_root), giving the roots of heads
you trust, never self.old_root and self.new_root.
Attributes:
| Name | Type | Description |
|---|---|---|
chain |
str
|
The chain. |
old_size |
int
|
The smaller size. |
new_size |
int
|
The larger size. |
old_root |
bytes
|
The root of the tree of |
new_root |
bytes
|
The root of the tree of |
path |
tuple[bytes, ...]
|
The proof. |
verify ¶
Check that the tree of new_size with root new_root extends
the tree of old_size with root old_root, by RFC 9162 section
2.1.4.2.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
old_root
|
bytes
|
The root of a head of |
required |
new_root
|
bytes
|
The root of a head of |
required |
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
gives |
Source code in audit_trail/ledger/_tree.py
InclusionProof
dataclass
¶
InclusionProof(
chain: str,
seq: int,
size: int,
leaf_hash: bytes,
root: bytes,
path: tuple[bytes, ...],
)
An RFC 9162 inclusion proof of one entry in a tree of a chain.
Check it with verify(root), giving the root of a head of size
you trust, never self.root.
Attributes:
| Name | Type | Description |
|---|---|---|
chain |
str
|
The chain. |
seq |
int
|
The entry's |
size |
int
|
The size of the tree. |
leaf_hash |
bytes
|
The entry's stored leaf hash. |
root |
bytes
|
The root of the tree of |
path |
tuple[bytes, ...]
|
The proof, nearest the leaf first. |
verify ¶
Check that the entry is in the tree of size whose root is
root, by RFC 9162 section 2.1.3.2.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
root
|
bytes
|
The root of a head of |
required |
leaf_hash
|
bytes | None
|
The entry's leaf hash as you hold it, such as the
|
None
|
Returns:
| Type | Description |
|---|---|
bool
|
|
bool
|
raises, malformed input gives |
Source code in audit_trail/ledger/_tree.py
LedgerFailure ¶
Bases: StrEnum
What makes a ledger verification fail; a closed set.
LedgerFinding
dataclass
¶
LedgerFinding(
kind: LedgerFailure | LedgerNote,
detail: str,
seq: int | None = None,
entry_id: UUID | None = None,
group: str | None = None,
level: int | None = None,
index: int | None = None,
count: int | None = None,
)
One failure or note.
Attributes:
| Name | Type | Description |
|---|---|---|
kind |
LedgerFailure | LedgerNote
|
What was found. |
detail |
str
|
A sentence for people; never a stored value or a salt. |
seq |
int | None
|
The entry it concerns. |
entry_id |
UUID | None
|
That entry's id, when it could be read. |
group |
str | None
|
The payload group. |
level |
int | None
|
For a node, its level. |
index |
int | None
|
For a node, its index. |
count |
int | None
|
How many entries it concerns, where it says. |
LedgerHead
dataclass
¶
A head of a chain: the tree of its first size entries.
Attributes:
| Name | Type | Description |
|---|---|---|
chain |
str
|
The chain. |
incarnation |
int
|
The chain's incarnation at that size. |
size |
int
|
The number of entries. |
root |
bytes
|
The RFC 6962 root of their tree, 32 bytes. |
LedgerNote ¶
Bases: StrEnum
What a ledger verification notes without failing.
LedgerReport
dataclass
¶
LedgerReport(
status: Status,
chain: str,
head: LedgerHead,
failures: list[LedgerFinding],
notes: list[LedgerFinding],
since: int | None = None,
entries: int = 0,
anchor: Anchor | None = None,
)
What verify found.
Attributes:
| Name | Type | Description |
|---|---|---|
status |
Status
|
|
chain |
str
|
The chain. |
head |
LedgerHead
|
The head verified up to: the state row as read at the start of
the run. Keep the report to pass it to |
failures |
list[LedgerFinding]
|
Every failure, in the order found. |
notes |
list[LedgerFinding]
|
Every note. |
since |
int | None
|
The size of the earlier report's head when this run checked
only the entries after it ( |
entries |
int
|
How many entries this run read. |
anchor |
Anchor | None
|
|
kinds ¶
aerasure_journal
async
¶
aerasure_journal(
conn: AsyncConnection,
tables: LedgerTables,
chain: str,
size: int | None = None,
) -> LedgerJournal
Async erasure_journal, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_anchor.py
aprepare_checkpoint
async
¶
aprepare_checkpoint(
conn: AsyncConnection,
tables: LedgerTables,
chain: str,
*,
origin: str,
verify: Mapping[str, Any] | None = None,
verified: LedgerReport | None = None,
journal: bool = False,
extensions: Iterable[str] = (),
since_size: int | None = None,
) -> PreparedCheckpoint
Async prepare_checkpoint, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_anchor.py
arecord_checkpoint
async
¶
arecord_checkpoint(
conn: AsyncConnection,
tables: LedgerTables,
chain: str,
signed_note: LedgerCheckpoint | str,
*,
verifier: SignatureVerifier,
key_history: KeyHistory,
actor: str | None = None,
lock_timeout: str | None = None,
since_size: int | None = None,
) -> RecordedCheckpoint
Async record_checkpoint, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_anchor.py
erasure_journal ¶
erasure_journal(
conn: Connection,
tables: LedgerTables,
chain: str,
size: int | None = None,
) -> LedgerJournal
The erasure journal of a chain at size.
The same journal prepare_checkpoint(..., journal=True) commits to:
every ledger.erased receipt with a seq up to size. Use it to
get the journal of a checkpoint again, before a restore. It reads in
short READ ONLY transactions, or in the connection's when it has
one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Connection
|
The connection; a role that can read the ledger tables. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain. |
required |
size
|
int | None
|
The checkpoint's size; the chain's current size by default. |
None
|
Returns:
| Type | Description |
|---|---|
LedgerJournal
|
The journal. |
Raises:
| Type | Description |
|---|---|
ValueError
|
There is no such chain, or |
TypeError
|
|
Source code in audit_trail/ledger/_anchor.py
prepare_checkpoint ¶
prepare_checkpoint(
conn: Connection,
tables: LedgerTables,
chain: str,
*,
origin: str,
verify: Mapping[str, Any] | None = None,
verified: LedgerReport | None = None,
journal: bool = False,
extensions: Iterable[str] = (),
since_size: int | None = None,
) -> PreparedCheckpoint
The unsigned checkpoint of a head of the chain that verified.
The first half of a checkpoint whose signer takes its time: sign the
result, then give the note to record_checkpoint. Only committed data
is read, in short READ ONLY transactions; nothing is written, no
lock is taken, and the connection is left with no transaction open.
Give exactly one of:
verify: runverifynow, with these keyword arguments of it ({}for none), and prepare for the head it verified;verified: the report of an earlierverify, such as a long run the host stored. It must have no failures, and its head must still be a head of the chain: the stored frontier of its size must give its root, and a consistency proof from the stored nodes must lead from it to the current root. The checkpoint is for that head, not a newer one;verify(since=report)brings a report up to date quickly.
Either way the head must be in the chain's current incarnation: a head from before an incarnation started is refused.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Connection
|
A connection that can read the ledger tables, not in a transaction. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain. |
required |
origin
|
str
|
The host origin, a schema-less URL such as
|
required |
verify
|
Mapping[str, Any] | None
|
Keyword arguments for |
None
|
verified
|
LedgerReport | None
|
The report of an earlier |
None
|
journal
|
bool
|
Commit to the erasure journal at the head's size: every
|
False
|
extensions
|
Iterable[str]
|
The host's lines after the statement, signed with it, as integrity's checkpoints take them. |
()
|
since_size
|
int | None
|
The size the returned consistency proof starts from, in
|
None
|
Returns:
| Name | Type | Description |
|---|---|---|
PreparedCheckpoint
|
The unsigned checkpoint, the journal, the report and the proof. |
|
PreparedCheckpoint
|
Sign the checkpoint, then keep |
|
database |
PreparedCheckpoint
|
see "What to keep off the database" in |
PreparedCheckpoint
|
|
Raises:
| Type | Description |
|---|---|
CheckpointRefusedError
|
The verification has failures, or its head
is not a head of the chain as it is now, or is from before an
incarnation started ( |
ValueError
|
Both or neither of |
Source code in audit_trail/ledger/_anchor.py
197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | |
record_checkpoint ¶
record_checkpoint(
conn: Connection,
tables: LedgerTables,
chain: str,
signed_note: LedgerCheckpoint | str,
*,
verifier: SignatureVerifier,
key_history: KeyHistory,
actor: str | None = None,
lock_timeout: str | None = None,
since_size: int | None = None,
) -> RecordedCheckpoint
Append a signed checkpoint to its chain as ledger.checkpoint, once.
The second half of prepare_checkpoint. Before it writes, it checks:
- the note reads as a ledger checkpoint, and is signed;
- every signature of a key
verifierknows verifies, at least one does, and each of those keys is valid at the checkpoint's size inkey_history(windows are in chainseq); - the origin names this chain;
- a journal line states the commitment of the journal of the chain's receipts up to the size.
Then audit_ledger_record_checkpoint, a SECURITY DEFINER
function, takes the chain's lock (after restore detection, as an append
does) and checks again what it can in SQL: that the size is at most the
chain's, that the origin's incarnation is the chain's and the entry at
the size is in it (a head from before an incarnation started is
refused), and that the root is the root of the tree of that size, from
the stored nodes. It appends the entry, whose attributes are
{"note": <the note>}.
The same note, byte for byte, recorded again returns the entry holding it and appends nothing, also when two transactions record it at once: the second waits for the chain's lock and then finds the first's entry. The same head with other signatures (a cosignature added) is another note, and another entry.
Runs in the connection's current transaction, under the chain's lock,
as append_many does; the caller commits. The application role may
call it (ledger_grant_statements).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Connection
|
Connection to run on. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain. |
required |
signed_note
|
LedgerCheckpoint | str
|
The signed checkpoint, or its note text. |
required |
verifier
|
SignatureVerifier
|
Checks the note's signatures. |
required |
key_history
|
KeyHistory
|
The window of each key, by chain |
required |
actor
|
str | None
|
The |
None
|
lock_timeout
|
str | None
|
The |
None
|
since_size
|
int | None
|
As |
None
|
Returns:
| Type | Description |
|---|---|
RecordedCheckpoint
|
The entry holding the note, whether this call appended it, the |
RecordedCheckpoint
|
journal and the consistency proof from the checkpoint before. Keep |
RecordedCheckpoint
|
|
Raises:
| Type | Description |
|---|---|
NoteError
|
The note is not a ledger checkpoint ( |
CheckpointRefusedError
|
The note is unsigned, a key is outside its window, the origin names another chain or incarnation, the head is above the chain's size, from before an incarnation started or has another root, or the journal does not match (the transaction is then aborted when the function refused it). |
LedgerBusyError
|
The lock was not granted within |
ValueError
|
The chain name is refused, the connection is in
|
Source code in audit_trail/ledger/_anchor.py
361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 | |
aappend
async
¶
aappend(
connection: AsyncConnection,
tables: LedgerTables,
chain: str,
entry: Entry,
*,
lock_timeout: str | None = None,
) -> Head
Async append, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_append.py
aappend_many
async
¶
aappend_many(
connection: AsyncConnection,
tables: LedgerTables,
chain: str,
entries: Sequence[Entry],
*,
lock_timeout: str | None = None,
) -> list[Head]
Async append_many, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_append.py
acreate_chain
async
¶
acreate_chain(
connection: AsyncConnection,
tables: LedgerTables,
chain: str,
config: ChainConfig | None = None,
*,
actor: str | None = None,
) -> Head
Async create_chain, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_append.py
append ¶
append(
connection: Connection,
tables: LedgerTables,
chain: str,
entry: Entry,
*,
lock_timeout: str | None = None,
) -> Head
Append one entry to a chain, in the connection's current transaction.
See append_many.
Returns:
| Type | Description |
|---|---|
Head
|
The head after the entry. |
Source code in audit_trail/ledger/_append.py
append_many ¶
append_many(
connection: Connection,
tables: LedgerTables,
chain: str,
entries: Sequence[Entry],
*,
lock_timeout: str | None = None,
) -> list[Head]
Append entries to a chain in one call, under one lock.
Each entry is checked and its body encoded, with fresh salts for its
payload groups, before the database is called. audit_ledger_append
then locks the chain's state row, gives the entries consecutive seq numbers in
order, reads clock_timestamp() once as their append time, computes
their leaves and the new roots, and stores the entries, their payloads
and the subtree nodes they close.
With the chain's detect_restores on, the function first compares
the stored cluster identity with the observed one, under the lock, and
when the database was restored starts a new incarnation: it appends
ledger.incarnation_started before the entries, which then go into
the new incarnation (ledger.cluster_changed after a pg_upgrade).
That entry gets no head here; the heads returned are the entries'. See
"Restore detection" in audit_trail.ledger._migrations for the rules.
The lock is held until the transaction ends, so append last, just before
commit. The heads are provisional until then: a rollback frees their
numbers. An empty entries touches nothing and takes no lock.
lock_timeout bounds each lock wait, not the total: the call can
wait for the row's lock, then for the transaction of each writer that
held it before. Set statement_timeout to bound the whole call. The
lock is not fair, so under many writers on one chain the slowest
appends wait far longer than the median; spread writers over chains.
Append under READ COMMITTED. Under REPEATABLE READ or
SERIALIZABLE, a transaction that waited for the lock while another
appended to the chain fails with a serialization failure (SQLSTATE
40001) once the other commits; roll back and retry it. The
connection must not be in AUTOCOMMIT: the lock and lock_timeout
would then last only for the call.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Connection to run on; the caller commits. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain's name. |
required |
entries
|
Sequence[Entry]
|
The entries, in order, at most |
required |
lock_timeout
|
str | None
|
The |
None
|
Returns:
| Type | Description |
|---|---|
list[Head]
|
One head per entry, in order. |
Raises:
| Type | Description |
|---|---|
LedgerBusyError
|
The lock was not granted within |
ValueError
|
An entry or the chain name is refused, there are more
than |
TypeError
|
An entry field has the wrong type. |
Source code in audit_trail/ledger/_append.py
130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 | |
arecord_maintenance
async
¶
arecord_maintenance(
connection: AsyncConnection,
tables: LedgerTables,
chain: str,
reason: str,
*,
actor: str | None = None,
lock_timeout: str | None = None,
) -> Head
Async record_maintenance, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_append.py
create_chain ¶
create_chain(
connection: Connection,
tables: LedgerTables,
chain: str,
config: ChainConfig | None = None,
*,
actor: str | None = None,
) -> Head
Create a chain, with ledger.chain_started as its first entry.
The entry's attributes hold the whole config, which is also stored in
audit_ledger_config, so the chain never runs under a config it has
not recorded. With config.detect_restores on (the default) the state
row stores the cluster identity: the system identifier, the WAL timeline
from pg_walfile_name(pg_current_wal_lsn()), the state table's OID
and the server's major version.
Runs in the connection's current transaction; the caller commits. It
calls audit_ledger_create_chain, which by default only the owner of
the ledger functions may execute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Connection to run on. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The new chain's name, matching |
required |
config
|
ChainConfig | None
|
The chain's config; |
None
|
actor
|
str | None
|
The |
None
|
Returns:
| Type | Description |
|---|---|
Head
|
The head after the first entry: |
Raises:
| Type | Description |
|---|---|
ValueError
|
The name is refused, the connection is in
|
DBAPIError
|
The database refused it, for example because the
identity functions cannot be called with detection on, or the
config names a precondition function that exists and does not
set a |
Source code in audit_trail/ledger/_append.py
record_maintenance ¶
record_maintenance(
connection: Connection,
tables: LedgerTables,
chain: str,
reason: str,
*,
actor: str | None = None,
lock_timeout: str | None = None,
) -> Head
Append ledger.maintenance, explaining the chain's incarnation.
A restore the append function detects starts a new incarnation with a
ledger.incarnation_started entry. Planned work can look the same
from inside the database: a dump-and-restore upgrade, a switchover. After
it, record the reason, so that a verifier can tell it from an
unexplained incarnation. The entry's attributes are {"incarnation":
n, "reason": reason}: n is the chain's incarnation after the
append's own restore detection, so a restore detected by this call is
the one it explains.
Runs in the connection's current transaction, under the chain's lock,
as append_many does; the caller commits. It calls
audit_ledger_record_maintenance, which by default only the owner of
the ledger functions may execute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Connection to run on. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain's name. |
required |
reason
|
str
|
The host's reason code ( |
required |
actor
|
str | None
|
The |
None
|
lock_timeout
|
str | None
|
The |
None
|
Returns:
| Type | Description |
|---|---|
Head
|
The head after the entry. |
Raises:
| Type | Description |
|---|---|
LedgerBusyError
|
The lock was not granted within |
ValueError
|
The chain name, the reason code or the actor is
refused, the connection is in |
TypeError
|
|
Source code in audit_trail/ledger/_append.py
add ¶
add(
session: Session | AsyncSession,
tables: LedgerTables,
chain: str,
entry: Entry,
*,
lock_timeout: str | None = None,
) -> PendingHead
Buffer an entry, to be appended when the session commits.
The recommended way to write the ledger from a session. The entries of
a transaction are appended at its commit, after a final flush, with one
append_many call per chain (per MAX_BATCH entries of it), so
the chain's lock is held only from the append to the commit (see
audit_trail.ledger._buffer). The entry is checked now, and refused
entries raise here.
The head comes back in the returned PendingHead, after the commit:
a head handed out before it could name an entry a rollback undoes. An
entry added in a savepoint that is rolled back is discarded with it.
add runs no SQL, so it is called the same way with an
AsyncSession: the append then runs in await session.commit().
It begins the session's transaction if none has begun, as a query
would, so session.begin() comes before it, not after.
The commit raises what the append raises, and does not commit:
LedgerBusyError when a chain's lock was not granted within
lock_timeout, ValueError for an unknown chain, an
IntegrityError for an entry id used before, or the error of the
final flush. The database transaction is then aborted: roll the session
back.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
session
|
Session | AsyncSession
|
The session, sync or async. Its transaction must not be in
|
required |
tables
|
LedgerTables
|
The ledger tables. The connection is the session's for
|
required |
chain
|
str
|
The chain's name. |
required |
entry
|
Entry
|
The entry. Its type may not start with |
required |
lock_timeout
|
str | None
|
The |
None
|
Returns:
| Type | Description |
|---|---|
PendingHead
|
The entry's pending head. |
Raises:
| Type | Description |
|---|---|
ValueError
|
The chain name or the entry is refused. |
InvalidRequestError
|
No transaction has begun and the session's
|
TypeError
|
An entry field has the wrong type. |
Source code in audit_trail/ledger/_buffer.py
124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 | |
aexport_bundle
async
¶
aexport_bundle(
engine_or_conn: AsyncEngine | AsyncConnection,
tables: LedgerTables,
chain: str,
destination: str | PathLike[str] | BinaryIO,
scope: EntryRange | None = None,
*,
checkpoints: Iterable[LedgerCheckpoint | str] = (),
key_history: KeyHistory | None = None,
verifier: SignatureVerifier | None = None,
host_files: HostFiles | None = None,
signer: Signer | None = None,
chunk_rows: int = DEFAULT_CHUNK_ROWS,
) -> LedgerBundleResult
Async export_bundle, for an AsyncEngine or AsyncConnection;
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
|
|
ValueError
|
As |
Source code in audit_trail/ledger/_bundle.py
arecord_bundle_manifest
async
¶
arecord_bundle_manifest(
connection: AsyncConnection,
tables: LedgerTables,
chain: str,
host_files: HostFiles,
*,
actor: str | None = None,
lock_timeout: str | None = None,
) -> Head
Async record_bundle_manifest, on an AsyncConnection; the same
arguments.
Source code in audit_trail/ledger/_bundle.py
export_bundle ¶
export_bundle(
engine_or_conn: Engine | Connection,
tables: LedgerTables,
chain: str,
destination: str | PathLike[str] | BinaryIO,
scope: EntryRange | None = None,
*,
checkpoints: Iterable[LedgerCheckpoint | str] = (),
key_history: KeyHistory | None = None,
verifier: SignatureVerifier | None = None,
host_files: HostFiles | None = None,
signer: Signer | None = None,
chunk_rows: int = DEFAULT_CHUNK_ROWS,
) -> LedgerBundleResult
Write a range of a chain's entries to a bundle, to check offline.
The bundle is bundle version 1 with stream_type "ledger";
audit_trail.integrity.verify_bundle and python -m
audit_trail.integrity verify-bundle check it without the database,
with the checks and findings of verify. The layout is in the
audit_trail.ledger._bundle module documentation and in
docs/spec/ledger-v1.md.
It reads as verify does: the state row first, which bounds the
scope, then the entries chunk_rows at a time with their payload,
each chunk in a short READ ONLY transaction of its own (or in the
connection's transaction), writing them as it reads them. It takes no
lock, and does not verify: run verify for that.
Host files are covered by the manifest only as far as it is anchored:
by signer's signature, by its hash kept elsewhere
(LedgerBundleResult.manifest_sha256), or by a
ledger.bundle_manifest entry in scope (record_bundle_manifest)
that a trusted checkpoint covers.
A bundle holds the payload still stored, personal data among it: keep it as you keep the ledger tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
engine_or_conn
|
Engine | Connection
|
An engine, or a connection, whose role can read the ledger tables. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain. |
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
|
EntryRange | None
|
The entries to include; the whole chain, up to the size the state row names, by default. |
None
|
checkpoints
|
Iterable[LedgerCheckpoint | str]
|
Checkpoints to include, as |
()
|
key_history
|
KeyHistory | None
|
Included as it is; the bundle names keys only by id. |
None
|
verifier
|
SignatureVerifier | None
|
Checks the signatures of the checkpoints recorded before the scope, to find the newest trusted one; not included. |
None
|
host_files
|
HostFiles | None
|
Files to add under |
None
|
signer
|
Signer | None
|
Signs the manifest; |
None
|
chunk_rows
|
int
|
Entries read per transaction, at least 1. |
DEFAULT_CHUNK_ROWS
|
Returns:
| Type | Description |
|---|---|
LedgerBundleResult
|
What was written. |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
There is no such chain, the scope ends after the chain,
a checkpoint text is not a ledger checkpoint (a |
Source code in audit_trail/ledger/_bundle.py
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 | |
record_bundle_manifest ¶
record_bundle_manifest(
connection: Connection,
tables: LedgerTables,
chain: str,
host_files: HostFiles,
*,
actor: str | None = None,
lock_timeout: str | None = None,
) -> Head
Append ledger.bundle_manifest, anchoring a bundle's host files.
The entry's attributes are {"sha256": <base64>}, the digest of the
host files as a bundle lists them (name, SHA-256 and size of each, in
the order of the zip, which export_bundle writes in name order; see
docs/spec/ledger-v1.md). A bundle that holds the
entry, exported later with the same host_files, has its host files
anchored in the log: verify_bundle takes them as covered when the
entry is in scope and a trusted checkpoint covers it. Record a
checkpoint after this entry and before the export, so that one can.
Runs in the connection's current transaction, under the chain's lock,
as append_many does; the caller commits. It calls
audit_ledger_record_bundle_manifest, which
ledger_grant_statements grants the application role.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Connection to run on. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain's name. |
required |
host_files
|
HostFiles
|
The host files, as |
required |
actor
|
str | None
|
The |
None
|
lock_timeout
|
str | None
|
The |
None
|
Returns:
| Type | Description |
|---|---|
Head
|
The head after the entry. |
Raises:
| Type | Description |
|---|---|
LedgerBusyError
|
The lock was not granted within |
ValueError
|
The chain name or a host file name is refused, there
are no host files, the connection is in |
TypeError
|
|
Source code in audit_trail/ledger/_bundle.py
verify_bundle ¶
verify_bundle(
bundle: str | PathLike[str] | BinaryIO,
*,
verifier: SignatureVerifier,
key_history: KeyHistory | None = None,
checkpoints: Iterable[LedgerCheckpoint | str] = (),
require_signatures: bool = False,
manifest_sha256: str | None = None,
) -> LedgerReport
Check a ledger bundle written by export_bundle, without the database.
audit_trail.integrity.verify_bundle with the arguments that apply
to a ledger bundle, typed for it: see there.
Raises:
| Type | Description |
|---|---|
BundleError
|
The bundle cannot be read as one, or is not a ledger bundle. |
ValueError
|
A checkpoint text is not a ledger checkpoint (a
|
Source code in audit_trail/ledger/_bundle_verify.py
checkpoint_origin ¶
<host origin>/<chain>/i<incarnation>, each part checked.
Raises:
| Type | Description |
|---|---|
ValueError
|
A part is invalid. |
Source code in audit_trail/ledger/_checkpoint.py
entry_leaf_hash ¶
entry_leaf_hash(
chain: str,
incarnation: int,
seq: int,
appended_at: datetime,
body: bytes,
) -> bytes
The RFC 6962 leaf hash of an entry, SHA-256(0x00 || leaf_input).
Source code in audit_trail/ledger/_entry.py
leaf_input ¶
The input of an entry's leaf hash, as the append function builds it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
chain
|
str
|
The chain name. |
required |
incarnation
|
int
|
The incarnation the entry was appended in. |
required |
seq
|
int
|
The entry's sequence number. |
required |
appended_at
|
datetime
|
The append time, as stored in |
required |
body
|
bytes
|
The body bytes, as stored in |
required |
Source code in audit_trail/ledger/_entry.py
achange_config
async
¶
achange_config(
connection: AsyncConnection,
tables: LedgerTables,
chain: str,
config: ChainConfig,
*,
actor: str | None = None,
lock_timeout: str | None = None,
) -> Head
Async change_config, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_erase.py
aerase
async
¶
aerase(
connection: AsyncConnection,
tables: LedgerTables,
chain: str,
entry_id: UUID,
reason: str,
*,
actor: str | None = None,
lock_timeout: str | None = None,
) -> Head
Async erase, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_erase.py
change_config ¶
change_config(
connection: Connection,
tables: LedgerTables,
chain: str,
config: ChainConfig,
*,
actor: str | None = None,
lock_timeout: str | None = None,
) -> Head
Replace a chain's config, recording it in ledger.config_changed.
audit_ledger_change_config, a SECURITY DEFINER function, locks
the chain's state row, checks the config as create_chain does,
appends the entry, whose attributes are the whole new config, and
stores the config with that entry's seq as its recorded_seq,
all under the lock: an append or erasure runs under the config before
the change or after it, never a mix. detect_restores is fixed when
the chain is created and cannot change.
Runs in the connection's current transaction; the caller commits. By default only the owner of the ledger functions may call it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Connection to run on. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain's name. |
required |
config
|
ChainConfig
|
The new config, whole. |
required |
actor
|
str | None
|
The |
None
|
lock_timeout
|
str | None
|
The |
None
|
Returns:
| Type | Description |
|---|---|
Head
|
The head after the entry. |
Raises:
| Type | Description |
|---|---|
LedgerBusyError
|
The lock was not granted within |
ValueError
|
The chain name is refused, the connection is in
|
DBAPIError
|
The config names a precondition function that exists
and does not set a |
Source code in audit_trail/ledger/_erase.py
erase ¶
erase(
connection: Connection,
tables: LedgerTables,
chain: str,
entry_id: UUID,
reason: str,
*,
actor: str | None = None,
lock_timeout: str | None = None,
) -> Head
Erase an entry's payload, and append the receipt, ledger.erased.
audit_ledger_erase, a SECURITY DEFINER function, locks the
chain's state row (each lock wait bounded by lock_timeout, not the
total), then checks, under
the chain's current config:
- that
reasonis one of the chain's reason codes; - that the entry is in the chain, and its type is neither one of the
chain's protected types nor one of the package's (
ledger.), so a receipt is never erased; - that the entry has a payload, not yet erased: erasing an entry twice is refused, not repeated;
- that the chain's precondition function, if it has one, sets a
search_pathending inpg_tempand returnstruefor(chain, entry_id, reason).
It then deletes the entry's payload rows (values and salts) and appends
the receipt, whose attributes are the entry's entry_id,
incarnation and seq and the reason_code; no free text. The
entry's body and its commitments stay, so the tree is unchanged.
A restore brings the payload back. record_restore erases it again
only when the journal of the restore kit it is given lists the
erasure, and does not report an erasure made after that kit's
checkpoint. After erasures, take a checkpoint with journal=True and
keep its new kit; keep a log of erasures off the database too, and
after a restore erase again what it lists after the newest kit. The
restore may have lost a change_config that the reason code needs:
run it again first.
The precondition is the name of a function, never SQL text: the erase
function quotes its parts with format('%I'), resolves the exact
signature (text, uuid, text) and calls it with bound arguments. A
bare name is looked up in the ledger's schema. It must return
boolean and be owned by the ledger owner, so that no other role can
change what runs with the owner's rights. It may read what the owner
may: the entry and the other ledger tables, and host tables the owner
is granted. It must set its own search_path, ending in pg_temp,
or the eraser's temporary tables are searched first and could stand in
for the tables it reads; qualify the names it uses, or list their
schemas before pg_temp::
CREATE FUNCTION audit.may_erase(chain text, entry_id uuid, reason text)
RETURNS boolean LANGUAGE sql STABLE
SET search_path = pg_catalog, pg_temp
AS $$
SELECT NOT EXISTS (
SELECT FROM audit.legal_hold AS h WHERE h.entry_id = $2
)
$$;
Runs in the connection's current transaction; the caller commits. The
calling role needs EXECUTE on audit_ledger_erase and SELECT
on audit_ledger_entry: see ledger_eraser_grant_statements and
ledger_grant_statements(..., erase=True).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Connection to run on. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain's name. |
required |
entry_id
|
UUID
|
The entry's id. |
required |
reason
|
str
|
A reason code of the chain's config. |
required |
actor
|
str | None
|
The |
None
|
lock_timeout
|
str | None
|
The |
None
|
Returns:
| Type | Description |
|---|---|
Head
|
The head after the receipt. |
Raises:
| Type | Description |
|---|---|
ErasureRefusedError
|
A check refused the erasure. |
LedgerBusyError
|
The lock was not granted within |
ValueError
|
The chain name or reason code is refused, the
connection is in |
TypeError
|
|
Source code in audit_trail/ledger/_erase.py
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 | |
create_ledger_sql ¶
create_ledger_statements ¶
DDL creating the ledger tables and functions.
The schema (IF NOT EXISTS), the five tables and their indexes (IF
NOT EXISTS), a check that current_user owns each table and the
schema and that no other role may create in the schema, and the
SECURITY DEFINER functions (CREATE OR REPLACE), each with
EXECUTE revoked from PUBLIC:
audit_ledger_append(chain, bodies, payload_entries, payload_groups, payload_salts, payload_values), whichappendcalls, and which refuses the package'sledger.types;audit_ledger_append_entries, with the same arguments, which does the work for it and for the package's own entries;audit_ledger_create_chain(chain, config, body), whichcreate_chaincalls;audit_ledger_erase(chain, entry_id, reason, body), whicherasecalls;audit_ledger_change_config(chain, config, body), whichchange_configcalls;audit_ledger_cluster_identity(), which reads the cluster identity;audit_ledger_detect_restore(chain), which every append calls first (see "Restore detection");audit_ledger_record_maintenance(chain, reason, actor), whichrecord_maintenancecalls;audit_ledger_record_checkpoint(chain, body), whichrecord_checkpointcalls;audit_ledger_record_bundle_manifest(chain, digest, actor), whichrecord_bundle_manifestcalls.audit_ledger_record_restore(chain, note, journal, restored_size, proven_size, proven_root, proof, actor), whichrecord_restorecalls;audit_ledger_confirm_upgrade(chain, seq, actor), whichconfirm_upgradecalls.
The role that runs them owns the tables and the functions, and the
functions write as that role; grant the application what
ledger_grant_statements lists. Run them in a schema that role owns,
where no other role has CREATE: a table another role created there
first would be kept by IF NOT EXISTS, and a role that may create
there could add objects the functions would find. The check refuses a
table another role owns, a schema another role owns, and a schema in
which another role, or PUBLIC, has CREATE. Superusers, and roles
that are members of the owner, are not checked.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tables
|
LedgerTables
|
The ledger tables, from |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
The statements, in order, without trailing semicolons. |
Source code in audit_trail/ledger/_migrations.py
1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 | |
create_ledger_tables ¶
Execute create_ledger_statements on connection.
Runs in the connection's current transaction; the caller commits. Running it again replaces the functions and keeps the tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Connection to run on, such as Alembic's |
required |
tables
|
LedgerTables
|
The ledger tables, from |
required |
Source code in audit_trail/ledger/_migrations.py
drop_ledger_statements ¶
DDL dropping the ledger functions and tables; the schema is kept.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tables
|
LedgerTables
|
The ledger tables. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
The statements, in order, without trailing semicolons. |
Source code in audit_trail/ledger/_migrations.py
drop_ledger_tables ¶
Execute drop_ledger_statements on connection.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Connection to run on. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
Source code in audit_trail/ledger/_migrations.py
ledger_eraser_grant_statements ¶
The grants of an optional eraser role, which may only erase.
USAGE on the schema, SELECT on audit_ledger_entry (erase
reads the entry's incarnation and seq for the receipt) and
EXECUTE on audit_ledger_erase. Nothing else: the role cannot
append, record a checkpoint, delete payload rows itself, or change the
config. Like
ledger_grant_statements, the statements first revoke EXECUTE on
the other functions it must not call, and every privilege on the five
tables, which default privileges may have granted.
The eraser role is optional: ledger_grant_statements(...,
erase=True) lets the application role erase instead.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tables
|
LedgerTables
|
The ledger tables. |
required |
role
|
str
|
The eraser role. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
The statements, without trailing semicolons. |
Source code in audit_trail/ledger/_migrations.py
ledger_grant_statements ¶
The grants an application role needs to append to the ledger and read it.
USAGE on the schema, SELECT on the five tables and EXECUTE on
audit_ledger_append, audit_ledger_record_checkpoint and
audit_ledger_record_bundle_manifest. No
INSERT, UPDATE or DELETE: the role writes only through the
functions, so it can append new entries but not change, reorder or
delete existing ones. The record-checkpoint function appends only a
ledger.checkpoint entry naming a head of the stored tree; it cannot
check the note's signatures, which record_checkpoint and verify
do. The bundle-manifest function appends only a
ledger.bundle_manifest entry holding a digest. Creating a chain,
changing its config, recording maintenance, recording a restore or
confirming an upgrade needs the owner of the functions, or EXECUTE
on audit_ledger_create_chain, audit_ledger_change_config,
audit_ledger_record_maintenance, audit_ledger_record_restore or
audit_ledger_confirm_upgrade granted separately.
The statements also revoke EXECUTE on every other ledger function
and, unless erase is set, audit_ledger_erase from the role, in
case default privileges (ALTER DEFAULT PRIVILEGES ... GRANT EXECUTE ON
FUNCTIONS) granted it when the functions were created, and every
privilege on the five tables before granting SELECT, in case default
privileges on tables granted INSERT, UPDATE, DELETE,
TRUNCATE or TRIGGER (a trigger on a ledger table would run inside
the functions, as their owner). The ledger has no sequences.
Run them as the owner of the ledger tables, after
create_ledger_tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tables
|
LedgerTables
|
The ledger tables. |
required |
role
|
str
|
The application role. |
required |
erase
|
bool
|
Also grant |
False
|
Returns:
| Type | Description |
|---|---|
list[str]
|
The statements, without trailing semicolons. |
Source code in audit_trail/ledger/_migrations.py
1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 | |
ledger_reader_grant_statements ¶
The grants of a read-only role, such as a verifier or an auditor.
USAGE on the schema and SELECT on the five tables: enough for
verify, the proofs, prepare_checkpoint, erasure_journal and
export_bundle, which only read. Nothing else: the role cannot
append, record a checkpoint or a bundle manifest, erase, create a chain
or change its config, or write a row itself. Like
ledger_grant_statements, the statements first revoke EXECUTE on
every ledger function, and every privilege on the five tables, which
default privileges may have granted.
Run them as the owner of the ledger tables, after
create_ledger_tables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
tables
|
LedgerTables
|
The ledger tables. |
required |
role
|
str
|
The read-only role. |
required |
Returns:
| Type | Description |
|---|---|
list[str]
|
The statements, without trailing semicolons. |
Source code in audit_trail/ledger/_migrations.py
aconsistency_proof
async
¶
aconsistency_proof(
conn: AsyncConnection,
tables: LedgerTables,
chain: str,
old_size: int,
new_size: int | None = None,
) -> ConsistencyProof
Async consistency_proof, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_proof.py
ainclusion_proof
async
¶
ainclusion_proof(
conn: AsyncConnection,
tables: LedgerTables,
chain: str,
seq: int,
size: int | None = None,
) -> InclusionProof
Async inclusion_proof, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_proof.py
consistency_proof ¶
consistency_proof(
conn: Connection,
tables: LedgerTables,
chain: str,
old_size: int,
new_size: int | None = None,
) -> ConsistencyProof
The consistency proof from the tree of old_size to new_size.
Reads as inclusion_proof does. The proof is empty when old_size
is 0 or equals new_size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Connection
|
The connection; a role that can read the ledger tables. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain. |
required |
old_size
|
int
|
The smaller size, 0 or more. |
required |
new_size
|
int | None
|
The larger size; the chain's current size by default. |
None
|
Returns:
| Type | Description |
|---|---|
ConsistencyProof
|
The proof, with the roots of both sizes. |
Raises:
| Type | Description |
|---|---|
ValueError
|
There is no such chain, |
TypeError
|
A size is not an int. |
Source code in audit_trail/ledger/_proof.py
inclusion_proof ¶
inclusion_proof(
conn: Connection,
tables: LedgerTables,
chain: str,
seq: int,
size: int | None = None,
) -> InclusionProof
The inclusion proof of the entry at seq in the tree of size.
Reads the state row and O(log size) stored hashes, in a READ ONLY
transaction of its own, or in the connection's when it has one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Connection
|
The connection; a role that can read the ledger tables. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain. |
required |
seq
|
int
|
The entry's |
required |
size
|
int | None
|
The tree's size, at least |
None
|
Returns:
| Type | Description |
|---|---|
InclusionProof
|
The proof, with the leaf hash and the root of that size. |
Raises:
| Type | Description |
|---|---|
ValueError
|
There is no such chain, |
TypeError
|
|
Source code in audit_trail/ledger/_proof.py
arecord_restore
async
¶
arecord_restore(
conn: AsyncConnection,
tables: LedgerTables,
chain: str,
checkpoint_note: LedgerCheckpoint | str | None = None,
*,
journal: LedgerJournal | str | _Unset | None = _UNSET,
kit: RestoreKit | str | None = None,
verifier: SignatureVerifier,
key_history: KeyHistory,
proof: ConsistencyProof
| Iterable[ConsistencyProof] = (),
restored_size: int | None = None,
actor: str | None = None,
lock_timeout: str | None = None,
) -> RecordedRestore
Async record_restore, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_restore.py
record_restore ¶
record_restore(
conn: Connection,
tables: LedgerTables,
chain: str,
checkpoint_note: LedgerCheckpoint | str | None = None,
*,
journal: LedgerJournal | str | _Unset | None = _UNSET,
kit: RestoreKit | str | None = None,
verifier: SignatureVerifier,
key_history: KeyHistory,
proof: ConsistencyProof
| Iterable[ConsistencyProof] = (),
restored_size: int | None = None,
actor: str | None = None,
lock_timeout: str | None = None,
) -> RecordedRestore
Record a database restore in a chain, and erase again what it lost.
The operator runs it as the ledger owner after a restore, as a step of
the restore runbook, with the newest signed checkpoint kept off the
database, its journal and its proof: its RestoreKit as kit, or
each as its own argument. Record the newest kit first: a second call
with another note records a second restore (pass restored_size).
Appends before it are fine. Erasures made after the kit's checkpoint
are not erased again or reported: erase them again from your own log.
See audit_trail.ledger._restore for what is proven and what is
erased again. Before it writes, it checks:
- the note reads as a ledger checkpoint of this chain, signed, every
signature of a key
verifierknows verifies, and each such key is valid at the checkpoint's size inkey_history; - the journal, when given, is the one the checkpoint's journal line commits to, of this chain at the checkpoint's size;
- each step of
proofleads from the root the step before established, the first from the stored tree's root at its old size, and the last ends at the checkpoint's root.
A role granted EXECUTE on the function can call it with any note;
verify fails a ledger.restored entry whose checkpoint is not
signed by a trusted key, given verifier and key_history, and
each re-applied receipt that is not in the journal the checkpoint
commits to.
Then audit_ledger_record_restore, a SECURITY DEFINER function,
takes the chain's lock (after restore detection, as an append does),
works out the incarnation, the restored size and the proven prefix,
checks what it can again in SQL, and appends ledger.restored and
the re-applied receipts.
Runs in the connection's current transaction; the caller commits. Only
the owner of the ledger functions may call it, unless EXECUTE on
audit_ledger_record_restore is granted separately: it deletes
payload, and the function cannot check signatures.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Connection
|
Connection to run on. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain. |
required |
checkpoint_note
|
LedgerCheckpoint | str | None
|
The signed checkpoint, or its note text; not with
|
None
|
journal
|
LedgerJournal | str | _Unset | None
|
The checkpoint's journal ( |
_UNSET
|
kit
|
RestoreKit | str | None
|
The checkpoint's |
None
|
verifier
|
SignatureVerifier
|
Checks the note's signatures. |
required |
key_history
|
KeyHistory
|
The window of each key, by chain |
required |
proof
|
ConsistencyProof | Iterable[ConsistencyProof]
|
Consistency proofs taken before the restore, from a size the
chain still holds to the checkpoint's size, one or a chain of
them in order; none proves nothing above the restored size.
With |
()
|
restored_size
|
int | None
|
The size the restore brought the chain back to, when restore detection did not see it and appends followed it: without it, the chain's size is taken, and a checkpoint at or below that size is refused as not the chain's. When detection started the incarnation, it must be the size before. |
None
|
actor
|
str | None
|
The |
None
|
lock_timeout
|
str | None
|
The |
None
|
Returns:
| Type | Description |
|---|---|
RecordedRestore
|
The |
Raises:
| Type | Description |
|---|---|
NoteError
|
The note is not a ledger checkpoint ( |
RestoreRefusedError
|
A check refused it, or the kit's text is not a restore kit. |
LedgerBusyError
|
The lock was not granted within |
ValueError
|
The chain name is refused, the connection is in
|
TypeError
|
An argument has the wrong type, or |
Source code in audit_trail/ledger/_restore.py
231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 | |
build_ledger_tables ¶
Declare the ledger tables in metadata.
The tables are independent of the audit tables: a ledger needs no
AuditTrail, and the two can share a schema and a transaction. Create
them with create_ledger_tables, which also installs the functions
that write them.
audit_ledger_state, one row per chain: its incarnation, the treesize,rootandfrontier(the roots of the perfect subtrees of the tree, largest first, one per set bit ofsize), thelast_appended_attime, and the cluster identity read when the chain was created:system_identifier(pg_control_system()),timeline(frompg_walfile_name(pg_current_wal_lsn())),table_oid(of this table) andserver_major. They are null when the chain's config turns restore detection off, and are all null or all set.audit_ledger_entry, one row per entry:(chain, seq)is the key,bodythe canonical bytes as written,leaf_hashthe Merkle leaf, andentry_id,type,type_version,declared_at,actorandattributescopies of the body's fields for queries. A partial index lists theledger.erasedreceipts of a chain by theentry_idthey erase;create_ledger_tablesadds it to an install made before it.audit_ledger_payload, the erasable part: per entry and group, the salt and the canonical bytes of the value the body commits to.audit_ledger_node: per chain, the hash of every closed subtree of level 1 and up. Node(level, index)is the Merkle tree hash of the leaves[index * 2**level, (index + 1) * 2**level), by 0-based leaf index (seq - 1); level 0 is the entry'sleaf_hash.audit_ledger_config, one row per chain: the reason codes, protected types, precondition function and restore-detection setting recorded in the chain'sledger.chain_startedentry, and therecorded_seqof the entry that set them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata
|
MetaData | None
|
Metadata to declare them in; a new one by default. |
None
|
schema
|
str
|
Schema of the tables and of the ledger functions. |
'audit'
|
Returns:
| Type | Description |
|---|---|
LedgerTables
|
The tables. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in audit_trail/ledger/_schema.py
150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 | |
aconfirm_upgrade
async
¶
aconfirm_upgrade(
connection: AsyncConnection,
tables: LedgerTables,
chain: str,
seq: int,
*,
actor: str | None = None,
lock_timeout: str | None = None,
) -> Head
Async confirm_upgrade, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_upgrade.py
confirm_upgrade ¶
confirm_upgrade(
connection: Connection,
tables: LedgerTables,
chain: str,
seq: int,
*,
actor: str | None = None,
lock_timeout: str | None = None,
) -> Head
Append ledger.upgrade_confirmed, confirming a cluster change.
Confirm a ledger.cluster_changed entry only after checking that the
chain still holds what a checkpoint taken just before the upgrade
holds, with verify(..., checkpoints=[that checkpoint]): restore
detection cannot tell a pg_upgrade from a data-only restore of an
older dump into a fresh cluster of a higher major version, which loses
the entries written after the dump. Until then a verifier notes the
entry UNCONFIRMED_UPGRADE. Appends go on either way.
The entry's attributes are the entry_id, incarnation and
seq of the entry it confirms. Runs in the connection's current
transaction, under the chain's lock, as append_many does; the
caller commits. It calls audit_ledger_confirm_upgrade, which by
default only the owner of the ledger functions may execute.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
connection
|
Connection
|
Connection to run on. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain's name. |
required |
seq
|
int
|
The |
required |
actor
|
str | None
|
The |
None
|
lock_timeout
|
str | None
|
The |
None
|
Returns:
| Type | Description |
|---|---|
Head
|
The head after the entry. |
Raises:
| Type | Description |
|---|---|
LedgerBusyError
|
The lock was not granted within |
ValueError
|
The chain name, |
TypeError
|
|
Source code in audit_trail/ledger/_upgrade.py
averify
async
¶
averify(
conn: AsyncConnection,
tables: LedgerTables,
chain: str,
*,
since: LedgerReport | None = None,
checkpoints: Iterable[LedgerCheckpoint | str] = (),
chunk_rows: int = DEFAULT_CHUNK_ROWS,
verifier: SignatureVerifier | None = None,
key_history: KeyHistory | None = None,
require_signatures: bool = False,
) -> LedgerReport
Async verify, on an AsyncConnection; the same arguments.
Source code in audit_trail/ledger/_verify_db.py
verify ¶
verify(
conn: Connection,
tables: LedgerTables,
chain: str,
*,
since: LedgerReport | None = None,
checkpoints: Iterable[LedgerCheckpoint | str] = (),
chunk_rows: int = DEFAULT_CHUNK_ROWS,
verifier: SignatureVerifier | None = None,
key_history: KeyHistory | None = None,
require_signatures: bool = False,
) -> LedgerReport
Check a chain from its stored rows; report every failure and note.
Recomputes each entry's leaf from its header columns and body bytes,
the tree from the leaves, and compares them with the stored leaf
hashes, every stored node the entries close, and the state row's root,
frontier, incarnation and last append time. Checks that seq is
gapless from a first ledger.chain_started entry, that each body is
canonical and its columns copy it, that each payload row matches its
commitment and a missing one has a ledger.erased receipt, the
package's own entries by type (ledger.checkpoint entries: the note,
the head against the tree, the journal line, and with verifier the
signatures), and the config table against the newest config entry. See
audit_trail.ledger._verify for every finding.
Reads the state row first, and checks the chain up to the size it
names, so the report's head is a head the run verified. It takes no
lock: appends may go on during the run. A connection outside a
transaction is read in short READ ONLY transactions, one per chunk;
one inside a transaction is read in it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Connection
|
The connection; a role that can read the ledger tables. |
required |
tables
|
LedgerTables
|
The ledger tables. |
required |
chain
|
str
|
The chain. |
required |
since
|
LedgerReport | None
|
An earlier report of this chain without failures. Its head
must be a head of the stored tree: the stored frontier of its
size must give its root, and a consistency proof from the stored
nodes must lead from it to the current root, or the run fails
with |
None
|
checkpoints
|
Iterable[LedgerCheckpoint | str]
|
Trusted checkpoints, kept off the database host, as
|
()
|
chunk_rows
|
int
|
Entries, or nodes of one level, read per transaction; at least 1. |
DEFAULT_CHUNK_ROWS
|
verifier
|
SignatureVerifier | None
|
Checks the signatures of |
None
|
key_history
|
KeyHistory | None
|
With |
None
|
require_signatures
|
bool
|
Every checkpoint the run relies on must be
signed by a key |
False
|
Returns:
| Type | Description |
|---|---|
LedgerReport
|
The report. |
Raises:
| Type | Description |
|---|---|
TypeError
|
|
ValueError
|
There is no such chain, |
Source code in audit_trail/ledger/_verify_db.py
354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 | |