sqlalchemy-audit-trail 0.1.0a1__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.
- sqlalchemy_audit_trail-0.1.0a1/.gitignore +23 -0
- sqlalchemy_audit_trail-0.1.0a1/LICENSE +21 -0
- sqlalchemy_audit_trail-0.1.0a1/PKG-INFO +51 -0
- sqlalchemy_audit_trail-0.1.0a1/README.md +9 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/__init__.py +30 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/_typing.py +17 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/checks.py +1 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/config.py +117 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/context.py +375 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/diff.py +563 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/events.py +441 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/integrations/__init__.py +1 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/integrations/fastapi.py +1 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/listener.py +1 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/maintenance.py +362 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/migrations.py +309 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/mixin.py +118 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/privacy.py +1 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/py.typed +0 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/query.py +1 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/relations.py +236 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/serialization.py +400 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/tables.py +232 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/testing.py +1 -0
- sqlalchemy_audit_trail-0.1.0a1/audit_trail/writer.py +1 -0
- sqlalchemy_audit_trail-0.1.0a1/pyproject.toml +99 -0
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
__pycache__/
|
|
2
|
+
*.py[cod]
|
|
3
|
+
*$py.class
|
|
4
|
+
*.egg-info/
|
|
5
|
+
.eggs/
|
|
6
|
+
dist/
|
|
7
|
+
build/
|
|
8
|
+
.venv/
|
|
9
|
+
venv/
|
|
10
|
+
.env
|
|
11
|
+
.env.*
|
|
12
|
+
.pytest_cache/
|
|
13
|
+
.mypy_cache/
|
|
14
|
+
.ruff_cache/
|
|
15
|
+
.coverage
|
|
16
|
+
htmlcov/
|
|
17
|
+
.idea/
|
|
18
|
+
.vscode/
|
|
19
|
+
*.swp
|
|
20
|
+
.DS_Store
|
|
21
|
+
/site
|
|
22
|
+
benchmark/results/*
|
|
23
|
+
!benchmark/results/.gitkeep
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 WiktorB2004
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: sqlalchemy-audit-trail
|
|
3
|
+
Version: 0.1.0a1
|
|
4
|
+
Summary: Audit trail for SQLAlchemy on PostgreSQL: entity change diffs and domain events in one partitioned log
|
|
5
|
+
Project-URL: Homepage, https://github.com/WiktorB2004/sqlalchemy-audit-trail
|
|
6
|
+
Project-URL: Repository, https://github.com/WiktorB2004/sqlalchemy-audit-trail
|
|
7
|
+
Project-URL: Issues, https://github.com/WiktorB2004/sqlalchemy-audit-trail/issues
|
|
8
|
+
Project-URL: Documentation, https://wiktorb2004.github.io/sqlalchemy-audit-trail/
|
|
9
|
+
Project-URL: Changelog, https://github.com/WiktorB2004/sqlalchemy-audit-trail/blob/main/CHANGELOG.md
|
|
10
|
+
Author: WiktorB2004
|
|
11
|
+
License-Expression: MIT
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Keywords: audit,audit-log,audit-trail,gdpr,history,postgresql,sqlalchemy
|
|
14
|
+
Classifier: Development Status :: 2 - Pre-Alpha
|
|
15
|
+
Classifier: Framework :: FastAPI
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
18
|
+
Classifier: Operating System :: OS Independent
|
|
19
|
+
Classifier: Programming Language :: Python
|
|
20
|
+
Classifier: Programming Language :: Python :: 3
|
|
21
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
24
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
25
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
26
|
+
Classifier: Topic :: Database
|
|
27
|
+
Classifier: Typing :: Typed
|
|
28
|
+
Requires-Python: <4.0,>=3.10
|
|
29
|
+
Requires-Dist: sqlalchemy<2.2,>=2.0
|
|
30
|
+
Provides-Extra: asyncio
|
|
31
|
+
Requires-Dist: sqlalchemy[asyncio]<2.2,>=2.0; extra == 'asyncio'
|
|
32
|
+
Provides-Extra: asyncpg
|
|
33
|
+
Requires-Dist: asyncpg>=0.29; extra == 'asyncpg'
|
|
34
|
+
Requires-Dist: sqlalchemy[asyncio]<2.2,>=2.0; extra == 'asyncpg'
|
|
35
|
+
Provides-Extra: fastapi
|
|
36
|
+
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
|
|
37
|
+
Provides-Extra: psycopg
|
|
38
|
+
Requires-Dist: psycopg[binary]>=3.1; extra == 'psycopg'
|
|
39
|
+
Provides-Extra: pydantic
|
|
40
|
+
Requires-Dist: pydantic>=2; extra == 'pydantic'
|
|
41
|
+
Description-Content-Type: text/markdown
|
|
42
|
+
|
|
43
|
+
# sqlalchemy-audit-trail
|
|
44
|
+
|
|
45
|
+
Audit trail for SQLAlchemy on PostgreSQL: automatic entity change diffs and explicit domain events in one chronological, partitioned log.
|
|
46
|
+
|
|
47
|
+
Work in progress.
|
|
48
|
+
|
|
49
|
+
## License
|
|
50
|
+
|
|
51
|
+
MIT
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Audit trail for SQLAlchemy on PostgreSQL."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
from audit_trail.config import AuditOptions, AuditTrail
|
|
6
|
+
from audit_trail.context import Actor, AuditContext
|
|
7
|
+
from audit_trail.diff import AuditOptionError, FieldPolicyError
|
|
8
|
+
from audit_trail.events import AuditEvent, Severity, event
|
|
9
|
+
from audit_trail.mixin import Audited
|
|
10
|
+
from audit_trail.serialization import Pseudonymized
|
|
11
|
+
|
|
12
|
+
try:
|
|
13
|
+
__version__ = version("sqlalchemy-audit-trail")
|
|
14
|
+
except PackageNotFoundError: # pragma: no cover - running from a source tree
|
|
15
|
+
__version__ = "0.0.0"
|
|
16
|
+
|
|
17
|
+
__all__ = [
|
|
18
|
+
"Actor",
|
|
19
|
+
"AuditContext",
|
|
20
|
+
"AuditEvent",
|
|
21
|
+
"AuditOptionError",
|
|
22
|
+
"AuditOptions",
|
|
23
|
+
"AuditTrail",
|
|
24
|
+
"Audited",
|
|
25
|
+
"FieldPolicyError",
|
|
26
|
+
"Pseudonymized",
|
|
27
|
+
"Severity",
|
|
28
|
+
"__version__",
|
|
29
|
+
"event",
|
|
30
|
+
]
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
"""Typing helpers shared across modules."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import NoReturn
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def assert_never(value: NoReturn) -> NoReturn:
|
|
9
|
+
"""Mark a branch that exhaustive matching makes unreachable.
|
|
10
|
+
|
|
11
|
+
``typing.assert_never`` needs Python 3.11; this is the 3.10-compatible
|
|
12
|
+
equivalent. Type checkers report an error when a value can still reach it.
|
|
13
|
+
|
|
14
|
+
Raises:
|
|
15
|
+
AssertionError: Always, if reached at runtime.
|
|
16
|
+
"""
|
|
17
|
+
raise AssertionError(f"unhandled value: {value!r}")
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Static checks of audited models, meant for CI."""
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
"""Library configuration: ``AuditTrail`` and per-model ``AuditOptions``."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from collections.abc import Callable, Collection
|
|
7
|
+
from dataclasses import dataclass, field
|
|
8
|
+
from enum import IntEnum
|
|
9
|
+
from typing import TYPE_CHECKING, Any, Literal
|
|
10
|
+
|
|
11
|
+
if TYPE_CHECKING:
|
|
12
|
+
from sqlalchemy.engine import Engine
|
|
13
|
+
from sqlalchemy.ext.asyncio import AsyncEngine
|
|
14
|
+
|
|
15
|
+
OnError = Literal["log", "raise"]
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
@dataclass(frozen=True)
|
|
19
|
+
class AuditOptions:
|
|
20
|
+
"""Audit settings for one model, set as ``__audit__`` on the class.
|
|
21
|
+
|
|
22
|
+
``label``, ``scope`` and ``target`` run while the session flushes and get
|
|
23
|
+
a read-only view of the instance instead of the instance itself. They may
|
|
24
|
+
read only attributes already loaded on it: reading an expired or unloaded
|
|
25
|
+
attribute emits no SQL, logs a warning on ``audit_trail.diff`` (once per
|
|
26
|
+
model, attribute and option) and the option falls back (``label`` and
|
|
27
|
+
``target`` to ``None``, ``scope`` to the context). Reading a
|
|
28
|
+
``functools.cached_property`` raises ``AuditOptionError``. Any other
|
|
29
|
+
exception they raise propagates and aborts the flush.
|
|
30
|
+
|
|
31
|
+
Attributes:
|
|
32
|
+
severity: Severity of the model's ``entity.*`` entries. ``None`` uses
|
|
33
|
+
the configured default.
|
|
34
|
+
verb_severity: Per-verb severity overrides, keyed by verb
|
|
35
|
+
(for example ``{"entity.deleted": MySeverity.HIGH}``).
|
|
36
|
+
track_relationships: Relationship names whose membership changes are
|
|
37
|
+
recorded as ``{"added": [...], "removed": [...]}``.
|
|
38
|
+
snapshot_on_load: JSON columns deep-copied on load and refresh, so an
|
|
39
|
+
in-place mutation still has an old value.
|
|
40
|
+
object_type: Name stored in ``object_type``. Defaults to the class name.
|
|
41
|
+
label: Returns the object's label, stored in ``object_label``.
|
|
42
|
+
scope: Returns the scope id, stored in ``scope_id``. Returning
|
|
43
|
+
``None`` means "no scope"; the scope comes from the context only
|
|
44
|
+
when this option is not set or it read an attribute that is not
|
|
45
|
+
loaded.
|
|
46
|
+
target: Returns ``(type, id)`` of the parent object, or ``None``. An
|
|
47
|
+
id of ``None`` also means no target; a tuple id is formatted as a
|
|
48
|
+
composite ``object_id``.
|
|
49
|
+
"""
|
|
50
|
+
|
|
51
|
+
severity: IntEnum | None = None
|
|
52
|
+
verb_severity: dict[str, IntEnum] = field(default_factory=dict)
|
|
53
|
+
track_relationships: Collection[str] = frozenset()
|
|
54
|
+
snapshot_on_load: Collection[str] = frozenset()
|
|
55
|
+
object_type: str | None = None
|
|
56
|
+
label: Callable[[Any], str | None] | None = None
|
|
57
|
+
scope: Callable[[Any], object] | None = None
|
|
58
|
+
target: Callable[[Any], tuple[str, object] | None] | None = None
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class AuditTrail:
|
|
62
|
+
"""Entry point of the library: configuration plus the public operations.
|
|
63
|
+
|
|
64
|
+
Args:
|
|
65
|
+
engine: Sync or async engine used for DDL and maintenance.
|
|
66
|
+
schema: Database schema holding the audit tables.
|
|
67
|
+
severities: The application's severity ``IntEnum``. ``None`` uses the
|
|
68
|
+
built-in ``Severity``.
|
|
69
|
+
durable_engine: Engine for durable writes. ``None`` builds a small
|
|
70
|
+
separate pool from ``engine``'s URL.
|
|
71
|
+
on_error: ``"log"`` keeps the business transaction alive when an audit
|
|
72
|
+
write fails; ``"raise"`` propagates. ``fail_closed`` events always
|
|
73
|
+
raise.
|
|
74
|
+
pseudonymize_key: HMAC key as ``bytes`` (version 1) or
|
|
75
|
+
``{version: key}``.
|
|
76
|
+
session_provider: Returns the current session, for hosts that keep it
|
|
77
|
+
in a context variable.
|
|
78
|
+
context_provider: Returns the current audit context.
|
|
79
|
+
json_encoder: Extra encoder for types the built-in one does not handle.
|
|
80
|
+
indexes: Names of the indexes to create. ``None`` uses the defaults.
|
|
81
|
+
warn_on_bulk: Log a warning when a bulk ``update()``/``delete()`` hits
|
|
82
|
+
an audited table.
|
|
83
|
+
auto_create_partitions: Let durable writes create a missing partition
|
|
84
|
+
and retry once. Needs DDL privileges.
|
|
85
|
+
allow_scrub: Enable ``scrub``/``scrub_actor``.
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
def __init__(
|
|
89
|
+
self,
|
|
90
|
+
engine: Engine | AsyncEngine,
|
|
91
|
+
*,
|
|
92
|
+
schema: str = "audit",
|
|
93
|
+
severities: type[IntEnum] | None = None,
|
|
94
|
+
durable_engine: Engine | AsyncEngine | None = None,
|
|
95
|
+
on_error: OnError = "log",
|
|
96
|
+
pseudonymize_key: bytes | dict[int, bytes] | None = None,
|
|
97
|
+
session_provider: Callable[[], Any] | None = None,
|
|
98
|
+
context_provider: Callable[[], Any] | None = None,
|
|
99
|
+
json_encoder: type[json.JSONEncoder] | None = None,
|
|
100
|
+
indexes: Collection[str] | None = None,
|
|
101
|
+
warn_on_bulk: bool = True,
|
|
102
|
+
auto_create_partitions: bool = False,
|
|
103
|
+
allow_scrub: bool = False,
|
|
104
|
+
) -> None:
|
|
105
|
+
self.engine = engine
|
|
106
|
+
self.schema = schema
|
|
107
|
+
self.severities = severities
|
|
108
|
+
self.durable_engine = durable_engine
|
|
109
|
+
self.on_error: OnError = on_error
|
|
110
|
+
self.pseudonymize_key = pseudonymize_key
|
|
111
|
+
self.session_provider = session_provider
|
|
112
|
+
self.context_provider = context_provider
|
|
113
|
+
self.json_encoder = json_encoder
|
|
114
|
+
self.indexes = indexes
|
|
115
|
+
self.warn_on_bulk = warn_on_bulk
|
|
116
|
+
self.auto_create_partitions = auto_create_partitions
|
|
117
|
+
self.allow_scrub = allow_scrub
|
|
@@ -0,0 +1,375 @@
|
|
|
1
|
+
"""Request context: who, where and how an audited change happened.
|
|
2
|
+
|
|
3
|
+
The context reaches the audit writer in one of three ways, checked in this
|
|
4
|
+
order by :func:`resolve_context`:
|
|
5
|
+
|
|
6
|
+
1. bound to a session with :func:`bind` (``session.info["audit_context"]``);
|
|
7
|
+
2. returned by a host-supplied ``context_provider``;
|
|
8
|
+
3. the built-in context variable, set with :func:`context`.
|
|
9
|
+
|
|
10
|
+
When none of them yields a context, an anonymous one is used.
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
from __future__ import annotations
|
|
14
|
+
|
|
15
|
+
from collections.abc import Callable
|
|
16
|
+
from contextvars import ContextVar, Token
|
|
17
|
+
from dataclasses import dataclass, field
|
|
18
|
+
from types import TracebackType
|
|
19
|
+
from typing import TYPE_CHECKING, Any, TypedDict
|
|
20
|
+
from uuid import UUID
|
|
21
|
+
|
|
22
|
+
if TYPE_CHECKING:
|
|
23
|
+
from sqlalchemy.ext.asyncio import AsyncSession
|
|
24
|
+
from sqlalchemy.orm import Session
|
|
25
|
+
|
|
26
|
+
_SESSION_INFO_KEY = "audit_context"
|
|
27
|
+
_ANONYMOUS = "anonymous"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
@dataclass(frozen=True)
|
|
31
|
+
class Actor:
|
|
32
|
+
"""Who performed an action.
|
|
33
|
+
|
|
34
|
+
Attributes:
|
|
35
|
+
type: Kind of actor, defined by the host (for example ``"user"``,
|
|
36
|
+
``"system"``, ``"api_key"``).
|
|
37
|
+
id: Opaque identifier of the actor, stored in ``actor_id``.
|
|
38
|
+
label: Human-readable snapshot (for example an e-mail address) that
|
|
39
|
+
survives deletion of the actor.
|
|
40
|
+
"""
|
|
41
|
+
|
|
42
|
+
type: str
|
|
43
|
+
id: str | None = None
|
|
44
|
+
label: str | None = None
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
@dataclass
|
|
48
|
+
class AuditContext:
|
|
49
|
+
"""Who, where and how of the current unit of work.
|
|
50
|
+
|
|
51
|
+
The object is mutable on purpose: it is set once (for example by a
|
|
52
|
+
middleware) and later updated in place with :func:`set_actor`, so changes
|
|
53
|
+
made in a worker thread are visible to the code that started it.
|
|
54
|
+
|
|
55
|
+
Attributes:
|
|
56
|
+
actor_type: Kind of actor. Defaults to ``"anonymous"``.
|
|
57
|
+
actor_id: Opaque identifier of the actor.
|
|
58
|
+
actor_label: Human-readable snapshot of the actor.
|
|
59
|
+
remote_addr: Client IP address.
|
|
60
|
+
user_agent: Client user agent.
|
|
61
|
+
method: Request method, for example ``"POST"``.
|
|
62
|
+
path: Request path.
|
|
63
|
+
channel: Entry point, for example ``"api"``, ``"admin"``, ``"cli"``,
|
|
64
|
+
``"worker"``.
|
|
65
|
+
auth_method: How the actor authenticated.
|
|
66
|
+
request_id: Identifier of the request.
|
|
67
|
+
correlation_id: Links several database transactions. When not given,
|
|
68
|
+
it is set to ``request_id`` at construction; changing
|
|
69
|
+
``request_id`` later does not update it.
|
|
70
|
+
scope_id: Scope of the change, for example a tenant.
|
|
71
|
+
extra: Additional host-defined context, stored as ``meta``.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
actor_type: str = _ANONYMOUS
|
|
75
|
+
actor_id: str | None = None
|
|
76
|
+
actor_label: str | None = None
|
|
77
|
+
remote_addr: str | None = None
|
|
78
|
+
user_agent: str | None = None
|
|
79
|
+
method: str | None = None
|
|
80
|
+
path: str | None = None
|
|
81
|
+
channel: str | None = None
|
|
82
|
+
auth_method: str | None = None
|
|
83
|
+
request_id: UUID | None = None
|
|
84
|
+
correlation_id: UUID | None = None
|
|
85
|
+
scope_id: str | None = None
|
|
86
|
+
extra: dict[str, Any] = field(default_factory=dict)
|
|
87
|
+
|
|
88
|
+
def __post_init__(self) -> None:
|
|
89
|
+
if self.correlation_id is None:
|
|
90
|
+
self.correlation_id = self.request_id
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
_current: ContextVar[AuditContext | None] = ContextVar(
|
|
94
|
+
"audit_trail_context", default=None
|
|
95
|
+
)
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def current_context() -> AuditContext | None:
|
|
99
|
+
"""Return the context set with :func:`context`, if any.
|
|
100
|
+
|
|
101
|
+
Returns:
|
|
102
|
+
The active context object, or ``None`` outside a :func:`context` block.
|
|
103
|
+
"""
|
|
104
|
+
return _current.get()
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
class ContextScope:
|
|
108
|
+
"""Sync and async context manager that activates one ``AuditContext``.
|
|
109
|
+
|
|
110
|
+
Returned by :func:`context`; entering it yields the activated context.
|
|
111
|
+
|
|
112
|
+
Args:
|
|
113
|
+
ctx: The context to activate.
|
|
114
|
+
"""
|
|
115
|
+
|
|
116
|
+
def __init__(self, ctx: AuditContext) -> None:
|
|
117
|
+
self._ctx = ctx
|
|
118
|
+
self._tokens: list[Token[AuditContext | None]] = []
|
|
119
|
+
|
|
120
|
+
def __enter__(self) -> AuditContext:
|
|
121
|
+
self._tokens.append(_current.set(self._ctx))
|
|
122
|
+
return self._ctx
|
|
123
|
+
|
|
124
|
+
def __exit__(
|
|
125
|
+
self,
|
|
126
|
+
exc_type: type[BaseException] | None,
|
|
127
|
+
exc: BaseException | None,
|
|
128
|
+
tb: TracebackType | None,
|
|
129
|
+
) -> None:
|
|
130
|
+
_current.reset(self._tokens.pop())
|
|
131
|
+
|
|
132
|
+
async def __aenter__(self) -> AuditContext:
|
|
133
|
+
return self.__enter__()
|
|
134
|
+
|
|
135
|
+
async def __aexit__(
|
|
136
|
+
self,
|
|
137
|
+
exc_type: type[BaseException] | None,
|
|
138
|
+
exc: BaseException | None,
|
|
139
|
+
tb: TracebackType | None,
|
|
140
|
+
) -> None:
|
|
141
|
+
self.__exit__(exc_type, exc, tb)
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def context(
|
|
145
|
+
ctx: AuditContext | None = None,
|
|
146
|
+
/,
|
|
147
|
+
*,
|
|
148
|
+
actor_type: str | None = None,
|
|
149
|
+
actor_id: str | None = None,
|
|
150
|
+
actor_label: str | None = None,
|
|
151
|
+
remote_addr: str | None = None,
|
|
152
|
+
user_agent: str | None = None,
|
|
153
|
+
method: str | None = None,
|
|
154
|
+
path: str | None = None,
|
|
155
|
+
channel: str | None = None,
|
|
156
|
+
auth_method: str | None = None,
|
|
157
|
+
request_id: UUID | None = None,
|
|
158
|
+
correlation_id: UUID | None = None,
|
|
159
|
+
scope_id: str | None = None,
|
|
160
|
+
extra: dict[str, Any] | None = None,
|
|
161
|
+
) -> ContextScope:
|
|
162
|
+
"""Activate an audit context for a block of code.
|
|
163
|
+
|
|
164
|
+
Usable as ``with context(...)`` and ``async with context(...)``. The
|
|
165
|
+
previous context is restored on exit. A nested block replaces the outer
|
|
166
|
+
context; it does not inherit its fields.
|
|
167
|
+
|
|
168
|
+
Pass either a ready :class:`AuditContext` or the fields of a new one; the
|
|
169
|
+
keyword arguments mirror the :class:`AuditContext` attributes.
|
|
170
|
+
|
|
171
|
+
Example::
|
|
172
|
+
|
|
173
|
+
with context(actor_type="system", actor_label="cleanup", channel="worker"):
|
|
174
|
+
...
|
|
175
|
+
|
|
176
|
+
Args:
|
|
177
|
+
ctx: A ready context to activate. Mutually exclusive with the
|
|
178
|
+
keyword arguments.
|
|
179
|
+
actor_type: Kind of actor. ``None`` means ``"anonymous"``.
|
|
180
|
+
actor_id: Opaque identifier of the actor.
|
|
181
|
+
actor_label: Human-readable snapshot of the actor.
|
|
182
|
+
remote_addr: Client IP address.
|
|
183
|
+
user_agent: Client user agent.
|
|
184
|
+
method: Request method.
|
|
185
|
+
path: Request path.
|
|
186
|
+
channel: Entry point, for example ``"worker"``.
|
|
187
|
+
auth_method: How the actor authenticated.
|
|
188
|
+
request_id: Identifier of the request.
|
|
189
|
+
correlation_id: Links several database transactions. Defaults to
|
|
190
|
+
``request_id``.
|
|
191
|
+
scope_id: Scope of the change, for example a tenant.
|
|
192
|
+
extra: Additional host-defined context, stored as ``meta``.
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
A context manager yielding the active :class:`AuditContext`.
|
|
196
|
+
|
|
197
|
+
Raises:
|
|
198
|
+
TypeError: If both ``ctx`` and keyword arguments are given.
|
|
199
|
+
"""
|
|
200
|
+
fields = (
|
|
201
|
+
actor_type,
|
|
202
|
+
actor_id,
|
|
203
|
+
actor_label,
|
|
204
|
+
remote_addr,
|
|
205
|
+
user_agent,
|
|
206
|
+
method,
|
|
207
|
+
path,
|
|
208
|
+
channel,
|
|
209
|
+
auth_method,
|
|
210
|
+
request_id,
|
|
211
|
+
correlation_id,
|
|
212
|
+
scope_id,
|
|
213
|
+
extra,
|
|
214
|
+
)
|
|
215
|
+
if ctx is not None:
|
|
216
|
+
if any(value is not None for value in fields):
|
|
217
|
+
raise TypeError("pass either an AuditContext or its fields, not both")
|
|
218
|
+
return ContextScope(ctx)
|
|
219
|
+
return ContextScope(
|
|
220
|
+
AuditContext(
|
|
221
|
+
actor_type=actor_type if actor_type is not None else _ANONYMOUS,
|
|
222
|
+
actor_id=actor_id,
|
|
223
|
+
actor_label=actor_label,
|
|
224
|
+
remote_addr=remote_addr,
|
|
225
|
+
user_agent=user_agent,
|
|
226
|
+
method=method,
|
|
227
|
+
path=path,
|
|
228
|
+
channel=channel,
|
|
229
|
+
auth_method=auth_method,
|
|
230
|
+
request_id=request_id,
|
|
231
|
+
correlation_id=correlation_id,
|
|
232
|
+
scope_id=scope_id,
|
|
233
|
+
extra=extra if extra is not None else {},
|
|
234
|
+
)
|
|
235
|
+
)
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
def set_actor(actor: Actor) -> AuditContext:
|
|
239
|
+
"""Set the actor on the active context, in place.
|
|
240
|
+
|
|
241
|
+
The active object is mutated rather than replaced, so an actor set from a
|
|
242
|
+
thread pool (for example a synchronous dependency) is visible to the
|
|
243
|
+
caller.
|
|
244
|
+
|
|
245
|
+
A context bound with :func:`bind` takes precedence, so ``set_actor`` on
|
|
246
|
+
the active object does not reach that session; set the actor fields on
|
|
247
|
+
the bound object instead.
|
|
248
|
+
|
|
249
|
+
Args:
|
|
250
|
+
actor: The actor. All three actor fields are overwritten.
|
|
251
|
+
|
|
252
|
+
Returns:
|
|
253
|
+
The updated context.
|
|
254
|
+
|
|
255
|
+
Raises:
|
|
256
|
+
RuntimeError: If no :func:`context` block is active.
|
|
257
|
+
"""
|
|
258
|
+
ctx = _current.get()
|
|
259
|
+
if ctx is None:
|
|
260
|
+
raise RuntimeError(
|
|
261
|
+
"no active audit context: enter context() first, or bind() an "
|
|
262
|
+
"AuditContext to the session and set its actor fields directly"
|
|
263
|
+
)
|
|
264
|
+
ctx.actor_type = actor.type
|
|
265
|
+
ctx.actor_id = actor.id
|
|
266
|
+
ctx.actor_label = actor.label
|
|
267
|
+
return ctx
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def bind(session: Session | AsyncSession, context: AuditContext) -> None:
|
|
271
|
+
"""Attach a context to one session.
|
|
272
|
+
|
|
273
|
+
Takes precedence over the provider and the built-in context variable.
|
|
274
|
+
Binding does not enable auditing on the session.
|
|
275
|
+
|
|
276
|
+
Args:
|
|
277
|
+
session: The session to attach the context to.
|
|
278
|
+
context: The context used for audit entries written by this session.
|
|
279
|
+
"""
|
|
280
|
+
session.info[_SESSION_INFO_KEY] = context
|
|
281
|
+
|
|
282
|
+
|
|
283
|
+
def resolve_context(
|
|
284
|
+
session: Session | AsyncSession,
|
|
285
|
+
context_provider: Callable[[], AuditContext | None] | None = None,
|
|
286
|
+
) -> AuditContext:
|
|
287
|
+
"""Return the context that applies to ``session``.
|
|
288
|
+
|
|
289
|
+
Checks, in order: the context bound with :func:`bind`, then
|
|
290
|
+
``context_provider()``, then the built-in context variable. The object is
|
|
291
|
+
returned as is, not copied, so later :func:`set_actor` calls stay visible.
|
|
292
|
+
|
|
293
|
+
Args:
|
|
294
|
+
session: The session being audited.
|
|
295
|
+
context_provider: Optional host hook returning the current context,
|
|
296
|
+
or ``None`` to fall through.
|
|
297
|
+
|
|
298
|
+
Returns:
|
|
299
|
+
The first context found, or a new anonymous one.
|
|
300
|
+
|
|
301
|
+
Raises:
|
|
302
|
+
TypeError: If ``session.info["audit_context"]`` is not an
|
|
303
|
+
:class:`AuditContext`.
|
|
304
|
+
"""
|
|
305
|
+
bound = session.info.get(_SESSION_INFO_KEY)
|
|
306
|
+
if bound is not None:
|
|
307
|
+
if not isinstance(bound, AuditContext):
|
|
308
|
+
raise TypeError(
|
|
309
|
+
f'session.info["{_SESSION_INFO_KEY}"] must be an AuditContext, '
|
|
310
|
+
f"got {type(bound).__name__}"
|
|
311
|
+
)
|
|
312
|
+
return bound
|
|
313
|
+
if context_provider is not None:
|
|
314
|
+
provided = context_provider()
|
|
315
|
+
if provided is not None:
|
|
316
|
+
return provided
|
|
317
|
+
active = _current.get()
|
|
318
|
+
if active is not None:
|
|
319
|
+
return active
|
|
320
|
+
return AuditContext()
|
|
321
|
+
|
|
322
|
+
|
|
323
|
+
class ContextSnapshot(TypedDict, total=False):
|
|
324
|
+
"""The ``data.context`` snapshot stored on each audit entry.
|
|
325
|
+
|
|
326
|
+
Every key is optional: empty values are left out.
|
|
327
|
+
"""
|
|
328
|
+
|
|
329
|
+
actor_type: str
|
|
330
|
+
actor_label: str
|
|
331
|
+
remote_addr: str
|
|
332
|
+
user_agent: str
|
|
333
|
+
method: str
|
|
334
|
+
path: str
|
|
335
|
+
channel: str
|
|
336
|
+
auth_method: str
|
|
337
|
+
request_id: str
|
|
338
|
+
meta: dict[str, object]
|
|
339
|
+
|
|
340
|
+
|
|
341
|
+
def context_snapshot(ctx: AuditContext) -> ContextSnapshot:
|
|
342
|
+
"""Build the ``data.context`` snapshot stored on each audit entry.
|
|
343
|
+
|
|
344
|
+
Empty values (``None``, ``""``, an empty ``extra``) are left out.
|
|
345
|
+
``actor_id`` is never included: it is stored in its own column.
|
|
346
|
+
|
|
347
|
+
Args:
|
|
348
|
+
ctx: The context to snapshot.
|
|
349
|
+
|
|
350
|
+
Returns:
|
|
351
|
+
The snapshot; ``request_id`` is a string and ``extra`` is copied as
|
|
352
|
+
``meta``. ``meta`` values are encoded to JSON by the writer.
|
|
353
|
+
"""
|
|
354
|
+
snapshot: ContextSnapshot = {}
|
|
355
|
+
if ctx.actor_type:
|
|
356
|
+
snapshot["actor_type"] = ctx.actor_type
|
|
357
|
+
if ctx.actor_label:
|
|
358
|
+
snapshot["actor_label"] = ctx.actor_label
|
|
359
|
+
if ctx.remote_addr:
|
|
360
|
+
snapshot["remote_addr"] = ctx.remote_addr
|
|
361
|
+
if ctx.user_agent:
|
|
362
|
+
snapshot["user_agent"] = ctx.user_agent
|
|
363
|
+
if ctx.method:
|
|
364
|
+
snapshot["method"] = ctx.method
|
|
365
|
+
if ctx.path:
|
|
366
|
+
snapshot["path"] = ctx.path
|
|
367
|
+
if ctx.channel:
|
|
368
|
+
snapshot["channel"] = ctx.channel
|
|
369
|
+
if ctx.auth_method:
|
|
370
|
+
snapshot["auth_method"] = ctx.auth_method
|
|
371
|
+
if ctx.request_id is not None:
|
|
372
|
+
snapshot["request_id"] = str(ctx.request_id)
|
|
373
|
+
if ctx.extra:
|
|
374
|
+
snapshot["meta"] = dict(ctx.extra)
|
|
375
|
+
return snapshot
|