sqlalchemy-audit-trail 0.1.0__py3-none-any.whl

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.
audit_trail/context.py ADDED
@@ -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