sqlalchemy-audit-trail 0.3.0__tar.gz → 0.4.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/PKG-INFO +3 -1
  2. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/__init__.py +2 -0
  3. sqlalchemy_audit_trail-0.4.0/audit_trail/_pg.py +156 -0
  4. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/config.py +31 -4
  5. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/__init__.py +136 -0
  6. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_anchor.py +685 -0
  7. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_block.py +533 -0
  8. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_canonical.py +209 -0
  9. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_checkpoint.py +178 -0
  10. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_codec.py +81 -0
  11. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_commit.py +301 -0
  12. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_ed25519.py +176 -0
  13. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_merkle.py +54 -0
  14. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_note.py +248 -0
  15. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_options.py +17 -0
  16. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_retire.py +558 -0
  17. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_schema.py +144 -0
  18. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_seal.py +884 -0
  19. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_sign.py +181 -0
  20. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_types.py +39 -0
  21. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_verify.py +1993 -0
  22. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/_verify_db.py +602 -0
  23. sqlalchemy_audit_trail-0.4.0/audit_trail/integrity/ed25519.py +24 -0
  24. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/listener.py +3 -1
  25. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/maintenance.py +723 -70
  26. sqlalchemy_audit_trail-0.4.0/audit_trail/migrations.py +702 -0
  27. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/privacy.py +109 -12
  28. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/query.py +40 -5
  29. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/tables.py +38 -1
  30. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/testing.py +12 -2
  31. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/writer.py +139 -28
  32. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/pyproject.toml +4 -1
  33. sqlalchemy_audit_trail-0.3.0/audit_trail/migrations.py +0 -309
  34. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/.gitignore +0 -0
  35. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/LICENSE +0 -0
  36. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/README.md +0 -0
  37. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/_compaction.py +0 -0
  38. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/checks.py +0 -0
  39. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/context.py +0 -0
  40. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/diff.py +0 -0
  41. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/events.py +0 -0
  42. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/integrations/__init__.py +0 -0
  43. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/integrations/fastapi.py +0 -0
  44. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/mixin.py +0 -0
  45. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/py.typed +0 -0
  46. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/pytest_plugin.py +0 -0
  47. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/relations.py +0 -0
  48. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/audit_trail/serialization.py +0 -0
  49. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/benchmark/README.md +0 -0
  50. {sqlalchemy_audit_trail-0.3.0 → sqlalchemy_audit_trail-0.4.0}/examples/fastapi_app/README.md +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: sqlalchemy-audit-trail
3
- Version: 0.3.0
3
+ Version: 0.4.0
4
4
  Summary: Audit trail for SQLAlchemy on PostgreSQL: entity change diffs and domain events in one partitioned log
5
5
  Project-URL: Homepage, https://github.com/WiktorB2004/sqlalchemy-audit-trail
6
6
  Project-URL: Repository, https://github.com/WiktorB2004/sqlalchemy-audit-trail
@@ -33,6 +33,8 @@ Requires-Dist: asyncpg>=0.29; extra == 'asyncpg'
33
33
  Requires-Dist: sqlalchemy[asyncio]<2.2,>=2.0; extra == 'asyncpg'
34
34
  Provides-Extra: fastapi
35
35
  Requires-Dist: fastapi>=0.110; extra == 'fastapi'
36
+ Provides-Extra: integrity
37
+ Requires-Dist: cryptography>=42; extra == 'integrity'
36
38
  Provides-Extra: psycopg
37
39
  Requires-Dist: psycopg[binary]>=3.1; extra == 'psycopg'
38
40
  Provides-Extra: pydantic
@@ -7,6 +7,7 @@ from audit_trail.config import AuditOptions, AuditTrail, Target
7
7
  from audit_trail.context import Actor, AuditContext
8
8
  from audit_trail.diff import AuditOptionError, FieldPolicyError
9
9
  from audit_trail.events import AuditEvent, Severity, event
10
+ from audit_trail.integrity import Integrity
10
11
  from audit_trail.listener import AsyncLoadError
11
12
  from audit_trail.mixin import Audited
12
13
  from audit_trail.privacy import ScrubNotAllowedError, ScrubResult
@@ -54,6 +55,7 @@ __all__ = [
54
55
  "FieldLabels",
55
56
  "FieldPolicyError",
56
57
  "Group",
58
+ "Integrity",
57
59
  "LabelResolver",
58
60
  "ModelIssue",
59
61
  "Page",
@@ -0,0 +1,156 @@
1
+ """Small PostgreSQL helpers shared by the modules that talk to the database."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from collections.abc import Iterator
6
+ from contextlib import contextmanager
7
+ from typing import TYPE_CHECKING
8
+
9
+ from sqlalchemy import text
10
+
11
+ if TYPE_CHECKING:
12
+ from sqlalchemy import Connection, Table
13
+ from sqlalchemy.exc import DBAPIError
14
+
15
+ UNIQUE_VIOLATION = "23505"
16
+ """SQLSTATE of an insert that repeats a primary or unique key."""
17
+
18
+ CHECK_VIOLATION = "23514"
19
+ """SQLSTATE of a row that fits no partition (and of other CHECK violations)."""
20
+
21
+ UNDEFINED_COLUMN = "42703"
22
+ """SQLSTATE of a statement naming a column the table lacks."""
23
+
24
+ UNDEFINED_TABLE = "42P01"
25
+ """SQLSTATE of a statement naming a relation that does not exist."""
26
+
27
+ LOCK_NOT_AVAILABLE = "55P03"
28
+ """SQLSTATE raised when ``lock_timeout`` expires."""
29
+
30
+ OBJECT_NOT_IN_PREREQUISITE_STATE = "55000"
31
+ """SQLSTATE of a ``DETACH`` while a detach from the same parent is pending."""
32
+
33
+
34
+ XACT_LOCK = "pg_advisory_xact_lock(hashtext(:key))"
35
+ """SQL that waits for the transaction-level advisory lock named by ``:key``."""
36
+
37
+ TRY_XACT_LOCK = "pg_try_advisory_xact_lock(hashtext(:key))"
38
+ """SQL that tries the transaction-level advisory lock named by ``:key``."""
39
+
40
+ SUBSCRIBED = (
41
+ "EXISTS (SELECT FROM pg_catalog.pg_subscription_rel "
42
+ "WHERE srrelid = to_regclass(:table))"
43
+ )
44
+ """SQL that is true when a logical-replication subscription of this database
45
+ writes into the table named by ``:table``, in any state, enabled or not.
46
+ Every role can read ``pg_subscription_rel``."""
47
+
48
+
49
+ def sqlstate(exc: DBAPIError) -> str | None:
50
+ """The SQLSTATE of a database error, or ``None`` when the driver gives none.
51
+
52
+ psycopg 3 names it ``sqlstate``, psycopg2 ``pgcode``.
53
+ """
54
+ orig = exc.orig
55
+ code: str | None = getattr(orig, "sqlstate", None) or getattr(orig, "pgcode", None)
56
+ return code
57
+
58
+
59
+ def is_sqlstate(exc: DBAPIError, code: str) -> bool:
60
+ """Tell whether a database error has the SQLSTATE ``code``."""
61
+ return sqlstate(exc) == code
62
+
63
+
64
+ def check_transactional(connection: Connection, name: str) -> None:
65
+ """Refuse a connection in ``AUTOCOMMIT`` mode.
66
+
67
+ Raises:
68
+ ValueError: It is; the message names the caller, ``name``.
69
+ """
70
+ dbapi = connection.connection.dbapi_connection
71
+ if getattr(dbapi, "autocommit", False):
72
+ raise ValueError(f"{name} needs a transaction, not AUTOCOMMIT")
73
+
74
+
75
+ def set_config(connection: Connection, name: str, value: str, *, local: bool) -> str:
76
+ """Set a setting for the transaction or the session; return the old value.
77
+
78
+ Args:
79
+ connection: Connection to set it on.
80
+ name: The setting, e.g. ``lock_timeout``.
81
+ value: Its new value.
82
+ local: Set it for the rest of the transaction only, as ``SET LOCAL``.
83
+ """
84
+ previous: str = connection.execute(
85
+ text("SELECT current_setting(:name)"), {"name": name}
86
+ ).scalar_one()
87
+ connection.execute(
88
+ text("SELECT set_config(:name, :value, :local)"),
89
+ {"name": name, "value": value, "local": local},
90
+ )
91
+ return previous
92
+
93
+
94
+ def execute_ddl(connection: Connection, statement: str) -> None:
95
+ """Execute one DDL statement built by this library as-is.
96
+
97
+ The statement goes to the driver without parameters, so ``%`` and ``:``
98
+ inside quoted names are not taken for placeholders.
99
+
100
+ Args:
101
+ connection: Connection to run on.
102
+ statement: A statement built by this library.
103
+ """
104
+ connection.exec_driver_sql(statement, execution_options={"no_parameters": True})
105
+
106
+
107
+ def lock_key(block: Table) -> str:
108
+ """Key of the advisory lock that lets one writer of a seal chain run at a time."""
109
+ return f"audit_trail.seal:{block.schema}.{block.name}"
110
+
111
+
112
+ @contextmanager
113
+ def read_only(conn: Connection) -> Iterator[Connection]:
114
+ """A short ``READ ONLY`` transaction on a connection."""
115
+ transaction = conn.begin()
116
+ try:
117
+ conn.execute(text("SET TRANSACTION READ ONLY"))
118
+ yield conn
119
+ finally:
120
+ # Nothing was written; ending it either way releases the snapshot.
121
+ transaction.rollback()
122
+
123
+
124
+ def regclass(connection: Connection, table: Table) -> str:
125
+ """The quoted, schema-qualified name of a table, as ``to_regclass`` takes it."""
126
+ return connection.dialect.identifier_preparer.format_table(table)
127
+
128
+
129
+ def xact_lock(connection: Connection, key: str) -> None:
130
+ """Wait for an advisory lock held until the transaction ends."""
131
+ connection.execute(text(f"SELECT {XACT_LOCK}"), {"key": key})
132
+
133
+
134
+ def session_lock(connection: Connection, key: str) -> int:
135
+ """Wait for an advisory lock held until ``session_unlock`` or disconnect.
136
+
137
+ Returns the ``pg_backend_pid()`` of the backend that took it, which the
138
+ caller compares with its own to tell whether a pooler moved it.
139
+ """
140
+ pid: int = connection.execute(
141
+ text("SELECT pg_backend_pid() FROM pg_advisory_lock(hashtext(:key))"),
142
+ {"key": key},
143
+ ).scalar_one()
144
+ return pid
145
+
146
+
147
+ def session_unlock(connection: Connection, key: str) -> tuple[bool, int]:
148
+ """Release a lock taken by ``session_lock``.
149
+
150
+ Returns whether this backend held the lock, and its ``pg_backend_pid()``.
151
+ """
152
+ unlocked, pid = connection.execute(
153
+ text("SELECT pg_advisory_unlock(hashtext(:key)), pg_backend_pid()"),
154
+ {"key": key},
155
+ ).one()
156
+ return bool(unlocked), int(pid)
@@ -36,6 +36,7 @@ if TYPE_CHECKING:
36
36
  from sqlalchemy.ext.asyncio import AsyncEngine, AsyncSession, async_sessionmaker
37
37
  from sqlalchemy.orm import Session, sessionmaker
38
38
 
39
+ from audit_trail.integrity._options import Integrity
39
40
  from audit_trail.privacy import ScrubbedRecord, ScrubResult
40
41
  from audit_trail.writer import Entry, TransactionValues
41
42
 
@@ -156,6 +157,13 @@ class AuditTrail:
156
157
  it is not given ``since``, for example ``timedelta(days=30)``;
157
158
  ``since=ALL_HISTORY`` still lists the whole log. ``None`` reads
158
159
  the whole log, which gets slower as it grows.
160
+ integrity: Tamper-evidence settings of this writer, or ``None`` (the
161
+ default) to leave the audit tables as they are. With
162
+ ``Integrity()`` the tables declare the integrity columns, which
163
+ ``migrations.add_integrity`` adds to an existing install, and
164
+ every write stores commitments; once the chain is started, every
165
+ process that writes audit entries needs it. See the integrity
166
+ guide.
159
167
 
160
168
  Attributes:
161
169
  severities: The severity enum in use.
@@ -201,6 +209,7 @@ class AuditTrail:
201
209
  auto_create_partitions: bool = False,
202
210
  allow_scrub: bool = False,
203
211
  default_query_window: timedelta | None = None,
212
+ integrity: Integrity | None = None,
204
213
  ) -> None:
205
214
  self.engine = engine
206
215
  self.schema = schema
@@ -228,8 +237,16 @@ class AuditTrail:
228
237
  self.auto_create_partitions = auto_create_partitions
229
238
  self.allow_scrub = allow_scrub
230
239
  self.keys = None if pseudonymize_key is None else KeyRing(pseudonymize_key)
231
- self.tables = build_tables(schema=schema, indexes=indexes)
232
- self.maintenance = PartitionManager(engine, self.tables, self.severities)
240
+ self.integrity = integrity
241
+ self.tables = build_tables(
242
+ schema=schema, indexes=indexes, integrity=integrity is not None
243
+ )
244
+ self.maintenance = PartitionManager(
245
+ engine,
246
+ self.tables,
247
+ self.severities,
248
+ system_severity=self.registry.system_severity,
249
+ )
233
250
  from audit_trail.query import AuditQuery
234
251
 
235
252
  self.query = AuditQuery(
@@ -474,7 +491,12 @@ class AuditTrail:
474
491
  auto_create_partitions=self.auto_create_partitions,
475
492
  )
476
493
  except DURABLE_WRITE_ERRORS as exc:
477
- handle_durable_failure(exc, self.on_error, entry.flags.fail_closed)
494
+ handle_durable_failure(
495
+ exc,
496
+ self.on_error,
497
+ entry.flags.fail_closed,
498
+ integrity=self.integrity is not None,
499
+ )
478
500
 
479
501
  @overload
480
502
  async def alog(
@@ -594,7 +616,12 @@ class AuditTrail:
594
616
  auto_create_partitions=self.auto_create_partitions,
595
617
  )
596
618
  except async_durable_write_errors() as exc:
597
- handle_durable_failure(exc, self.on_error, entry.flags.fail_closed)
619
+ handle_durable_failure(
620
+ exc,
621
+ self.on_error,
622
+ entry.flags.fail_closed,
623
+ integrity=self.integrity is not None,
624
+ )
598
625
 
599
626
  def scrub(
600
627
  self,
@@ -0,0 +1,136 @@
1
+ """Tamper evidence for the audit log.
2
+
3
+ With ``AuditTrail(integrity=Integrity())`` every audit row carries its
4
+ PostgreSQL transaction id (``xid``) and salted commitments to the parts of
5
+ the entry that scrubbing may erase. A sealer job (``maintenance.seal()``)
6
+ hashes the rows of finished transactions into blocks chained by hash, in the
7
+ block table; ``drop_expired`` appends a ``retire`` block before it drops a
8
+ partition, and ``scrub``/``scrub_actor`` delete the salt of each erased part
9
+ and stamp it with the scrub's own ``xid``. ``verify`` walks the chain,
10
+ rebuilds every block from the rows it can still read and reports every
11
+ break. ``export_checkpoint`` gives a signed statement of the head of the
12
+ chain to keep where the database cannot reach it.
13
+
14
+ This makes the log tamper-evident, not tamper-proof: a change is detected,
15
+ not prevented, and what verification can detect depends on where the
16
+ checkpoints and signing keys are kept. See the integrity guide.
17
+
18
+ The reference Ed25519 signer is in ``audit_trail.integrity.ed25519`` and
19
+ needs the ``sqlalchemy-audit-trail[integrity]`` extra; nothing else here
20
+ does.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import importlib
26
+ from typing import TYPE_CHECKING, Any
27
+
28
+ from audit_trail.integrity._options import Integrity
29
+
30
+ if TYPE_CHECKING:
31
+ from audit_trail.integrity._anchor import (
32
+ Fork,
33
+ ReplicationError,
34
+ declare_fork,
35
+ export_checkpoint,
36
+ )
37
+ from audit_trail.integrity._canonical import CanonicalEncodingError
38
+ from audit_trail.integrity._checkpoint import Checkpoint
39
+ from audit_trail.integrity._note import NoteError
40
+ from audit_trail.integrity._seal import (
41
+ Genesis,
42
+ SealHealth,
43
+ SealRefusedError,
44
+ SealResult,
45
+ )
46
+ from audit_trail.integrity._sign import SignatureVerifier, Signer
47
+ from audit_trail.integrity._verify import (
48
+ ACKNOWLEDGEABLE,
49
+ SCOPE_KEYS,
50
+ Anchor,
51
+ FailureKind,
52
+ Finding,
53
+ NoteKind,
54
+ Status,
55
+ VerificationReport,
56
+ )
57
+ from audit_trail.integrity._verify_db import (
58
+ aacknowledge,
59
+ acknowledge,
60
+ averify,
61
+ verify,
62
+ )
63
+
64
+ # The rest loads on first use: ``verify`` and the checkpoint functions import
65
+ # ``audit_trail.maintenance``, which imports this package, and a writer needs
66
+ # none of them.
67
+ _LAZY = {
68
+ "ACKNOWLEDGEABLE": "_verify",
69
+ "SCOPE_KEYS": "_verify",
70
+ "Anchor": "_verify",
71
+ "CanonicalEncodingError": "_canonical",
72
+ "Checkpoint": "_checkpoint",
73
+ "FailureKind": "_verify",
74
+ "Finding": "_verify",
75
+ "Fork": "_anchor",
76
+ "Genesis": "_seal",
77
+ "NoteError": "_note",
78
+ "NoteKind": "_verify",
79
+ "ReplicationError": "_anchor",
80
+ "SealHealth": "_seal",
81
+ "SealRefusedError": "_seal",
82
+ "SealResult": "_seal",
83
+ "SignatureVerifier": "_sign",
84
+ "Signer": "_sign",
85
+ "Status": "_verify",
86
+ "VerificationReport": "_verify",
87
+ "aacknowledge": "_verify_db",
88
+ "acknowledge": "_verify_db",
89
+ "averify": "_verify_db",
90
+ "declare_fork": "_anchor",
91
+ "export_checkpoint": "_anchor",
92
+ "verify": "_verify_db",
93
+ }
94
+
95
+
96
+ def __getattr__(name: str) -> Any:
97
+ module = _LAZY.get(name)
98
+ if module is None:
99
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
100
+ value = getattr(importlib.import_module(f"{__name__}.{module}"), name)
101
+ globals()[name] = value
102
+ return value
103
+
104
+
105
+ def __dir__() -> list[str]:
106
+ return sorted({*globals(), *_LAZY})
107
+
108
+
109
+ __all__ = [
110
+ "ACKNOWLEDGEABLE",
111
+ "SCOPE_KEYS",
112
+ "Anchor",
113
+ "CanonicalEncodingError",
114
+ "Checkpoint",
115
+ "FailureKind",
116
+ "Finding",
117
+ "Fork",
118
+ "Genesis",
119
+ "Integrity",
120
+ "NoteError",
121
+ "NoteKind",
122
+ "ReplicationError",
123
+ "SealHealth",
124
+ "SealRefusedError",
125
+ "SealResult",
126
+ "SignatureVerifier",
127
+ "Signer",
128
+ "Status",
129
+ "VerificationReport",
130
+ "aacknowledge",
131
+ "acknowledge",
132
+ "averify",
133
+ "declare_fork",
134
+ "export_checkpoint",
135
+ "verify",
136
+ ]