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 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 ¶
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
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; |
xid_at_fork |
int
|
Where the new incarnation's seal blocks start. |
id_floor |
dict[str, int] | None
|
Highest |
id_count |
dict[str, int] | None
|
Rows of each stream at or below it. |
RecordedCheckpoint
dataclass
¶
What record_checkpoint stored.
Attributes:
| Name | Type | Description |
|---|---|---|
seq |
int
|
The |
checkpoint |
Checkpoint
|
The checkpoint, with its signatures. |
created |
bool
|
|
ReplicationError ¶
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
|
|
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
BlockRange
dataclass
¶
A scope of blocks by seq, both ends included.
Raises:
| Type | Description |
|---|---|
ValueError
|
An end is not an integer of at least 1, or |
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 |
rows |
int
|
Rows in |
scrub_records |
int
|
Records 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. |
TimeRange
dataclass
¶
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 |
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 |
block_hash |
bytes
|
That block's hash. |
xid_to |
int
|
The |
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 |
journal |
bytes | None
|
The commitment of an erasure journal
( |
Raises:
| Type | Description |
|---|---|
ValueError
|
An extension line is not valid, or |
to_note ¶
signed ¶
The checkpoint with a signature by each of signers added.
verify ¶
Check the signatures; the key_id of each that verified.
Raises:
| Type | Description |
|---|---|
NoteError
|
|
Source code in audit_trail/integrity/_checkpoint.py
from_note
classmethod
¶
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
|
|
Source code in audit_trail/integrity/_checkpoint.py
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
ErasedRow
dataclass
¶
One row a scrub erased.
Attributes:
| Name | Type | Description |
|---|---|---|
table |
str
|
|
id |
int
|
The row's |
xid |
int
|
The row's |
groups |
tuple[str, ...]
|
The groups the scrub erased, sorted. |
seq |
int | None
|
The seal block that held the row when the journal was built;
|
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
|
|
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 ( |
rows |
tuple[ErasedRow, ...]
|
The rows it erased and stamped, by table and |
uncommitted |
tuple[UncommittedRow, ...]
|
The rows it erased that carry no commitments, as its
records list them, by table and |
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; |
blocks |
tuple[tuple[int, bytes], ...]
|
|
erasures |
tuple[Erasure, ...]
|
The scrubs, by |
version |
int
|
The canonical form: 2, or 1 for a journal 0.5.0 wrote,
which lists no |
Raises:
| Type | Description |
|---|---|
ValueError
|
A row names a block |
commitment
property
¶
The SHA-256 commitment a version 2 checkpoint statement states.
to_json ¶
from_json
classmethod
¶
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
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
|
|
transaction_rows |
int
|
|
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 |
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 |
unproven |
tuple[ErasedRow, ...]
|
Rows outside the shared prefix that |
uncommitted |
tuple[UncommittedRow, ...]
|
Rows without commitments that |
UncommittedRow
dataclass
¶
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
|
|
id |
int
|
The row's |
xid |
int | None
|
The row's |
groups |
tuple[str, ...]
|
The groups the scrub erased, sorted. |
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
Genesis
dataclass
¶
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 |
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 |
last_sealed_at |
datetime | None
|
When the block holding |
unsealed_rows |
int
|
Committed rows at or above |
seal_lag |
timedelta | None
|
Age of the unsealed entry with the lowest |
max_seal_lag |
timedelta
|
The threshold the report was made with. |
prepared |
list[str]
|
Global ids of prepared transactions in this database older
than |
problem |
str | None
|
Why the chain is not started, naming the step to run:
|
SealRefusedError ¶
Bases: Exception
The sealer refused to seal, and changed nothing.
Attributes:
| Name | Type | Description |
|---|---|---|
reason |
SealRefusal
|
|
Source code in audit_trail/integrity/_seal.py
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, |
rows |
int
|
Rows sealed into the block. |
horizon |
int | None
|
The |
capped |
bool
|
|
skipped |
Literal['standby', 'subscriber', 'busy'] | None
|
Why nothing was attempted: |
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.
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
|
|
partition |
str | None
|
Name of the partition, without schema. |
stream |
str | None
|
The segment's stream. |
id |
int | None
|
The row's |
xid |
int | None
|
The row's |
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 |
ack |
int | None
|
For an |
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
|
|
anchor |
Anchor
|
|
verified_to |
int | None
|
|
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 |
since |
int | None
|
The |
kinds ¶
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 |
SealRefusedError
|
As |
Source code in audit_trail/integrity/_anchor.py
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 |
SealRefusedError
|
As |
ReplicationError
|
As |
Source code in audit_trail/integrity/_anchor.py
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 |
ValueError
|
As |
Source code in audit_trail/integrity/_anchor.py
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 |
ValueError
|
As |
OperationalError
|
As |
Source code in audit_trail/integrity/_anchor.py
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:
- checks that
last_good_checkpointnames a genesis, checkpoint or fork block of this chain, with its hash; - 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; - 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; - writes the fork block, whose
xid_at_forkis 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 |
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 |
required |
reason
|
str
|
Why, for whoever reads the chain; stored in clear. |
required |
signer
|
Signer | None
|
Signs the closing seal and the fork block. |
None
|
id_window
|
bool | None
|
Record an id window. |
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 |
SealRefusedError
|
|
Source code in audit_trail/integrity/_anchor.py
854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 | |
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 |
required |
tables
|
AuditTables
|
Audit tables built with integrity. |
required |
signer
|
Signer | None
|
Signs the block and the note; |
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; |
()
|
journal
|
ErasureJournal | None
|
An erasure journal ( |
None
|
Returns:
| Type | Description |
|---|---|
Checkpoint
|
The checkpoint, signed by |
Raises:
| Type | Description |
|---|---|
ValueError
|
The tables were built without integrity, the connection
is in a transaction or in |
SealRefusedError
|
|
ReplicationError
|
|
Source code in audit_trail/integrity/_anchor.py
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 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 | |
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: runverifynow on this connection, in shortREAD ONLYtransactions, with these keyword arguments of it ({}for none), and prepare for the last block it checked;verified: the report of an earlierverify, 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 |
None
|
verified
|
VerificationReport | None
|
The report of an earlier |
None
|
extensions
|
Iterable[str]
|
The application's lines, as |
()
|
journal
|
ErasureJournal | None
|
An erasure journal to commit to, as |
None
|
Returns:
| Type | Description |
|---|---|
Checkpoint
|
The checkpoint, unsigned, naming the verified head. |
Raises:
| Type | Description |
|---|---|
CheckpointRefusedError
|
The verification, or the report, has
failures ( |
ValueError
|
Both or neither of |
Source code in audit_trail/integrity/_anchor.py
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 | |
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 |
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 |
None
|
signer
|
Signer | None
|
Signs the |
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 ( |
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 |
OperationalError
|
The connection was lost, also during the
|
Source code in audit_trail/integrity/_anchor.py
496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 | |
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 |
ValueError
|
As |
Source code in audit_trail/integrity/_bundle.py
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 |
required |
include
|
Include
|
The rows of |
'both'
|
checkpoints
|
Iterable[Checkpoint | str]
|
Checkpoints to include, as |
()
|
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 |
None
|
signer
|
Signer | None
|
Signs the manifest; |
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 |
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 |
Source code in audit_trail/integrity/_bundle.py
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_SCOPEnote, notTRUNCATED; - an
audit.scrubbedrecord sealed outside the scope, or not sealed yet, is counted, with anOUT_OF_SCOPEnote: 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 (aSCRUBBED_ROWS_RETIREDnote, as inverify), is anOUT_OF_SCOPEnote, since the others may be outside the scope; more stamps than recorded fail as inverify; - 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 anUNANCHOREDnote unless the manifest is anchored: signed by a keyverifierknows (and inside its window at the scope's last block, givenkey_history), or its hash given asmanifest_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 |
None
|
checkpoints
|
Iterable[Checkpoint | LedgerCheckpoint | str]
|
Trusted checkpoints, as |
()
|
retention
|
Mapping[int, timedelta | None] | None
|
Retention by severity, as for |
None
|
transaction_retention
|
timedelta | None
|
Retention of the transaction table, as for
|
None
|
system_severity
|
int | None
|
Severity of the |
None
|
require_signatures
|
bool
|
Every block and every checkpoint must be signed
by a key |
False
|
manifest_sha256
|
str | None
|
The SHA-256 of |
None
|
Returns:
| Type | Description |
|---|---|
VerificationReport | LedgerReport
|
The report. Its |
VerificationReport | LedgerReport
|
was checked; its |
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 |
Source code in audit_trail/integrity/_bundle_verify.py
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 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 | |
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 |
Source code in audit_trail/integrity/_journal.py
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 |
ValueError
|
As |
Source code in audit_trail/integrity/_journal.py
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
|
Returns:
| Type | Description |
|---|---|
ErasureJournal
|
The journal. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in audit_trail/integrity/_journal.py
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 |
required |
tables
|
AuditTables
|
Audit tables built with integrity. |
required |
journal
|
ErasureJournal | str
|
The journal, or its |
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 |
None
|
context
|
AuditContext | None
|
Who re-applies, for the entries; else the active
|
None
|
include_unproven
|
bool
|
Also erase again the rows outside the shared
prefix ( |
False
|
include_uncommitted
|
bool
|
Also erase again the rows the scrubs erased
that carry no commitments ( |
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 |
Source code in audit_trail/integrity/_journal.py
823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 | |
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 |
Raises:
| Type | Description |
|---|---|
ValueError
|
As |
Source code in audit_trail/integrity/_verify_db.py
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 |
required |
tables
|
AuditTables
|
Audit tables built with integrity. |
required |
kind
|
FailureKind | str
|
The failure kind to waive; only those about rows and
partitions ( |
required |
scope
|
Mapping[str, object]
|
What it covers; keys from |
required |
reason
|
str
|
Why, for whoever reads the chain; it is stored in clear. |
required |
retention
|
Mapping[int, timedelta | None] | None
|
As |
None
|
transaction_retention
|
timedelta | None
|
As |
None
|
system_severity
|
int | None
|
As |
None
|
chunk_rows
|
int
|
As |
DEFAULT_CHUNK_ROWS
|
signer
|
Signer | None
|
Signs the ack block; |
None
|
Returns:
| Type | Description |
|---|---|
int
|
The |
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 |
Source code in audit_trail/integrity/_verify_db.py
500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 | |
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 |
ValueError
|
As |
Source code in audit_trail/integrity/_verify_db.py
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 |
None
|
transaction_retention
|
timedelta | None
|
Retention of the transaction table, as
|
None
|
system_severity
|
int | None
|
Severity of the |
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
|
()
|
verifier
|
SignatureVerifier | None
|
Checks the signatures of signed blocks and checkpoints.
Given, a fork block that no key it knows signed is also a
|
None
|
require_signatures
|
bool
|
Every block and every checkpoint must be
signed by a key |
False
|
key_history
|
KeyHistory | None
|
When each key was valid, by block |
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
|
None
|
Returns:
| Type | Description |
|---|---|
VerificationReport
|
The report. |
Raises:
| Type | Description |
|---|---|
TypeError
|
The engine is an |
ValueError
|
The tables were built without integrity, the chain has
no genesis block, |
Source code in audit_trail/integrity/_verify_db.py
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 | |
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) isPRIVATE+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 ¶
Signs with an Ed25519 private key.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The key name, such as |
required |
private_key
|
Ed25519PrivateKey
|
The key. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
name |
The key name. |
|
key_id |
|
|
algorithm |
|
Source code in audit_trail/integrity/_ed25519.py
generate
classmethod
¶
from_seed
classmethod
¶
A signer from the 32-byte RFC 8032 private key (the seed).
from_skey
classmethod
¶
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
Ed25519Verifier ¶
Checks Ed25519 signatures of known keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vkeys
|
Iterable[str]
|
The verifier keys, as |
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 |
Source code in audit_trail/integrity/_ed25519.py
key_algorithm ¶
verify ¶
Whether signature is the key's Ed25519 signature of message.
Source code in audit_trail/integrity/_ed25519.py
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 ofSHA-256of the DER SubjectPublicKeyInfo; - a signature is the DER ECDSA signature of
SHA-256(message), the form a KMS or an HSM returns for anECDSA_SHA_256key.
audit_trail.integrity.keys.KeyVerifier checks Ed25519 and P-256 keys
together.
EcdsaP256Signer ¶
Signs with an ECDSA private key on NIST P-256.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
The key name, such as |
required |
private_key
|
EllipticCurvePrivateKey
|
The key, on the |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
name |
The key name. |
|
public_key |
The DER SubjectPublicKeyInfo of the public key. |
|
key_id |
|
|
algorithm |
|
Raises:
| Type | Description |
|---|---|
ValueError
|
The key is not an ECDSA key on P-256. |
Source code in audit_trail/integrity/_ecdsa.py
generate
classmethod
¶
from_pem
classmethod
¶
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
sign ¶
The DER ECDSA signature of SHA-256(message), about 70 bytes.
Not deterministic: each call draws a new nonce.
EcdsaP256Verifier ¶
Checks ECDSA P-256 signatures of known keys.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vkeys
|
Iterable[str]
|
The verifier keys, as |
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 |
Source code in audit_trail/integrity/_ecdsa.py
key_algorithm ¶
verify ¶
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
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 ¶
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 |
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 |
Source code in audit_trail/integrity/_keys.py
key_algorithm ¶
"ed25519" or "ecdsa-p256-sha256" for a known key, else None.
verify ¶
Whether signature is the key's signature of message.