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/diff.py ADDED
@@ -0,0 +1,619 @@
1
+ """Entity change sets and per-column field policies.
2
+
3
+ Everything here reads the in-memory state of ORM instances and never emits
4
+ SQL, so it is safe to call from ``after_flush`` (also under ``AsyncSession``).
5
+
6
+ A column's policy is set where the column is defined::
7
+
8
+ hook_secret: Mapped[str] = mapped_column(info={"audit": "redact"})
9
+ email: Mapped[str] = mapped_column(info={"audit": "hash"})
10
+ embeddings: Mapped[bytes] = mapped_column(info={"audit": "exclude"})
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import functools
16
+ import json
17
+ import logging
18
+ from collections.abc import Callable, Collection, Iterable, Mapping, Sequence
19
+ from dataclasses import dataclass
20
+ from enum import Enum
21
+ from typing import TYPE_CHECKING, Any, Literal, NamedTuple, TypeAlias, cast
22
+
23
+ from sqlalchemy import Column, inspect
24
+ from sqlalchemy.orm import ColumnProperty
25
+ from sqlalchemy.orm.attributes import instance_state
26
+ from sqlalchemy.orm.base import NO_VALUE
27
+
28
+ from audit_trail._typing import assert_never
29
+ from audit_trail.config import AuditOptions, Target
30
+ from audit_trail.serialization import JSONValue, KeyRing, encode_value, hash_value
31
+
32
+ if TYPE_CHECKING:
33
+ from sqlalchemy.orm import InstanceState, Mapper
34
+
35
+ logger = logging.getLogger(__name__)
36
+
37
+ FieldPolicy: TypeAlias = Literal["exclude", "redact", "hash"]
38
+ """Policy of one column, from ``mapped_column(info={"audit": ...})``."""
39
+
40
+ ChangeKind: TypeAlias = Literal["created", "updated", "deleted"]
41
+ """Which change set to build: a new, a modified or a deleted instance."""
42
+
43
+ Changes: TypeAlias = dict[str, list[JSONValue]]
44
+ """``{attribute key: [old, new]}`` with JSON-ready values."""
45
+
46
+ REDACTED = "***"
47
+ """Stored in place of a non-null value of a ``redact`` column."""
48
+
49
+ UNKNOWN = "<unknown>"
50
+ """Marker stored where a value is not available without SQL."""
51
+
52
+ ERASED = "[erased]"
53
+ """Stored by ``scrub`` in place of a non-null value."""
54
+
55
+ SNAPSHOT_INFO_KEY = "audit_trail.snapshot"
56
+ """``InstanceState.info`` key holding the ``snapshot_on_load`` copies."""
57
+
58
+ _POLICIES: dict[str, FieldPolicy] = {
59
+ "exclude": "exclude",
60
+ "redact": "redact",
61
+ "hash": "hash",
62
+ }
63
+
64
+ _ValuePolicy: TypeAlias = Literal["redact", "hash"]
65
+
66
+
67
+ class FieldPolicyError(ValueError):
68
+ """A column's audit policy is invalid or cannot be applied."""
69
+
70
+
71
+ class AuditOptionError(TypeError):
72
+ """An audit option (``label``, ``scope``, ``target``) is misconfigured."""
73
+
74
+
75
+ class UseContext(Enum):
76
+ """Result of :func:`resolve_scope` meaning "take the scope from context"."""
77
+
78
+ USE_CONTEXT = "use_context"
79
+
80
+
81
+ USE_CONTEXT = UseContext.USE_CONTEXT
82
+
83
+
84
+ class _Missing(Enum):
85
+ VALUE = "missing"
86
+
87
+
88
+ _MISSING = _Missing.VALUE
89
+
90
+
91
+ @dataclass(frozen=True)
92
+ class _AuditedColumn:
93
+ key: str
94
+ column: Column[Any]
95
+ policy: _ValuePolicy | None
96
+
97
+
98
+ def options_of(model: type[Any]) -> AuditOptions:
99
+ """Return the model's ``__audit__`` options, or the defaults.
100
+
101
+ Args:
102
+ model: A mapped class.
103
+
104
+ Returns:
105
+ The model's ``AuditOptions``.
106
+ """
107
+ options = getattr(model, "__audit__", None)
108
+ return options if isinstance(options, AuditOptions) else AuditOptions()
109
+
110
+
111
+ def object_type_of(obj: object) -> str:
112
+ """Return the ``object_type`` of an instance.
113
+
114
+ Args:
115
+ obj: A mapped instance.
116
+
117
+ Returns:
118
+ ``AuditOptions.object_type``, or the class name when it is not set.
119
+ """
120
+ cls = type(obj)
121
+ return options_of(cls).object_type or cls.__name__
122
+
123
+
124
+ def field_policy(model: type[Any], key: str, column: Column[Any]) -> FieldPolicy | None:
125
+ """Return the audit policy set on a column.
126
+
127
+ Args:
128
+ model: The mapped class, named in the error message.
129
+ key: The column's attribute key, named in the error message.
130
+ column: The column.
131
+
132
+ Returns:
133
+ The policy, or ``None`` when the column has none.
134
+
135
+ Raises:
136
+ FieldPolicyError: ``info["audit"]`` is not a known policy.
137
+ """
138
+ raw = column.info.get("audit")
139
+ if raw is None:
140
+ return None
141
+ policy = _POLICIES.get(raw) if isinstance(raw, str) else None
142
+ if policy is None:
143
+ raise FieldPolicyError(
144
+ f"{model.__qualname__}.{key}: unknown audit policy {raw!r}; "
145
+ f"expected one of {', '.join(map(repr, _POLICIES))}"
146
+ )
147
+ return policy
148
+
149
+
150
+ def _audited_columns(
151
+ mapper: Mapper[Any], global_redact: frozenset[str] = frozenset()
152
+ ) -> list[_AuditedColumn]:
153
+ result = []
154
+ for prop in mapper.column_attrs:
155
+ column = prop.columns[0]
156
+ if not isinstance(column, Column):
157
+ continue # column_property() over an SQL expression
158
+ policy = field_policy(mapper.class_, prop.key, column)
159
+ match policy:
160
+ case "exclude":
161
+ continue
162
+ case None:
163
+ redact = prop.key in global_redact or column.name in global_redact
164
+ result.append(
165
+ _AuditedColumn(prop.key, column, "redact" if redact else None)
166
+ )
167
+ case "redact" | "hash":
168
+ result.append(_AuditedColumn(prop.key, column, policy))
169
+ case _:
170
+ assert_never(policy)
171
+ return result
172
+
173
+
174
+ def entity_changes(
175
+ obj: object,
176
+ kind: ChangeKind,
177
+ *,
178
+ keys: KeyRing | None = None,
179
+ json_encoder: type[json.JSONEncoder] | None = None,
180
+ global_redact: Collection[str] = (),
181
+ ) -> Changes:
182
+ """Build the ``changes`` of an ``entity.*`` entry from an instance.
183
+
184
+ Meant for ``after_flush``, while ``session.new`` / ``dirty`` / ``deleted``
185
+ and attribute history still describe the flush. Reads only what is in
186
+ memory and never emits SQL.
187
+
188
+ - ``created``: every audited column as ``[None, value]``, empty ones too.
189
+ - ``updated``: only columns with a net change. Old and new raw values are
190
+ compared with ``column.type.compare_values`` before any redaction or
191
+ encoding, so ``Decimal("1.5")`` vs ``Decimal("1.50")`` is no change.
192
+ An empty result means there is nothing to record.
193
+ - ``deleted``: every audited column as ``[value, None]``.
194
+
195
+ ``exclude`` columns are left out. ``redact`` stores ``"***"`` and
196
+ ``hash`` stores ``hv{n}:<hex>``; both keep null as null. Every other value
197
+ goes through ``encode_value``.
198
+
199
+ ``"<unknown>"`` is a marker, not a value: it stands where the value is not
200
+ in memory. That is the old value of a JSON column changed in place
201
+ (``MutableDict``) without ``snapshot_on_load``, a ``deleted`` column that
202
+ is not loaded (for example ``deferred``), and a ``created`` column filled
203
+ by a server-side default (``server_default``, ``Computed``, ``Identity``)
204
+ that was not fetched back. On PostgreSQL the mapper's default
205
+ ``eager_defaults="auto"`` fetches them with ``RETURNING`` on INSERT, so
206
+ ``created`` entries hold the real values; only a mapper with
207
+ ``eager_defaults=False`` leaves them ``"<unknown>"``. A ``created`` column
208
+ that was not set and has no server-side default is ``None``, as stored.
209
+
210
+ Args:
211
+ obj: A mapped instance.
212
+ kind: Which change set to build.
213
+ keys: Key ring for ``hash`` columns.
214
+ json_encoder: Host encoder for types ``encode_value`` does not handle.
215
+ global_redact: Attribute keys or column names redacted when the column
216
+ has no explicit policy. An extra safety net, not a replacement for
217
+ per-column policies.
218
+
219
+ Returns:
220
+ ``{attribute key: [old, new]}`` with JSON-ready values.
221
+
222
+ Raises:
223
+ FieldPolicyError: A column has an unknown policy, or the model has a
224
+ ``hash`` column and ``keys`` is ``None``.
225
+ UnserializableValueError: A value cannot be encoded.
226
+ """
227
+ state = instance_state(obj)
228
+ columns = _audited_columns(state.mapper, frozenset(global_redact))
229
+ if keys is None:
230
+ for spec in columns:
231
+ if spec.policy == "hash":
232
+ raise FieldPolicyError(
233
+ f"{state.class_.__qualname__}.{spec.key}: the hash policy "
234
+ "needs a key ring (pseudonymize_key)"
235
+ )
236
+
237
+ def render(value: object, spec: _AuditedColumn) -> JSONValue:
238
+ return _render(value, spec.policy, keys, json_encoder)
239
+
240
+ changes: Changes = {}
241
+ match kind:
242
+ case "created":
243
+ for spec in columns:
244
+ new = state.dict.get(spec.key, _MISSING)
245
+ if new is _MISSING and spec.column.server_default is None:
246
+ # Identity and Computed also live in server_default.
247
+ new = None
248
+ changes[spec.key] = [None, render(new, spec)]
249
+ case "deleted":
250
+ for spec in columns:
251
+ old = state.dict.get(spec.key, _MISSING)
252
+ changes[spec.key] = [render(old, spec), None]
253
+ case "updated":
254
+ snapshot: dict[str, object] = state.info.get(SNAPSHOT_INFO_KEY, {})
255
+ for spec in columns:
256
+ history = state.attrs[spec.key].history
257
+ if not history.added and not history.deleted:
258
+ continue
259
+ new = history.added[0] if history.added else None
260
+ if history.deleted:
261
+ old = history.deleted[0]
262
+ else:
263
+ # Changed in place (MutableDict): the committed value is
264
+ # gone unless snapshot_on_load kept a copy.
265
+ old = snapshot.get(spec.key, _MISSING)
266
+ if old is not _MISSING and spec.column.type.compare_values(old, new):
267
+ continue
268
+ changes[spec.key] = [render(old, spec), render(new, spec)]
269
+ case _:
270
+ assert_never(kind)
271
+ return changes
272
+
273
+
274
+ def _render(
275
+ value: object,
276
+ policy: _ValuePolicy | None,
277
+ keys: KeyRing | None,
278
+ json_encoder: type[json.JSONEncoder] | None,
279
+ ) -> JSONValue:
280
+ if value is _MISSING:
281
+ return UNKNOWN
282
+ match policy:
283
+ case None:
284
+ return encode_value(value, json_encoder=json_encoder)
285
+ case "redact":
286
+ return None if value is None else REDACTED
287
+ case "hash":
288
+ if value is None:
289
+ return None
290
+ assert keys is not None # entity_changes checks this up front
291
+ return hash_value(value, keys=keys, json_encoder=json_encoder)
292
+ case _:
293
+ assert_never(policy)
294
+
295
+
296
+ def object_id_of(obj: object) -> str:
297
+ """Return the ``object_id`` of an instance.
298
+
299
+ Uses the identity key when the instance has one. Inside ``after_flush``
300
+ that is still the key from before the flush, so a changed primary key
301
+ yields the old id. Objects inserted by the flush have no identity key yet;
302
+ their primary key is read from the instance.
303
+
304
+ Args:
305
+ obj: A mapped instance.
306
+
307
+ Returns:
308
+ ``str(pk)`` for a single-column key (a UUID in canonical lowercase
309
+ form), a compact JSON array of strings (``["a","1"]``) for a
310
+ composite one.
311
+
312
+ Raises:
313
+ ValueError: The instance has no primary key value yet.
314
+ """
315
+ object_id = state_object_id(instance_state(obj))
316
+ if object_id is None:
317
+ raise ValueError(f"{type(obj).__qualname__} instance has no primary key yet")
318
+ return object_id
319
+
320
+
321
+ def state_object_id(state: InstanceState[Any]) -> str | None:
322
+ """Return the ``object_id`` of an instance state, as :func:`object_id_of`.
323
+
324
+ Args:
325
+ state: The state of a mapped instance.
326
+
327
+ Returns:
328
+ The id, or ``None`` when the instance has no primary key value yet.
329
+ """
330
+ if state.key is not None:
331
+ return _format_identity(state.key[1])
332
+ mapper = state.mapper
333
+ values = tuple(
334
+ state.dict.get(mapper.get_property_by_column(column).key)
335
+ for column in mapper.primary_key
336
+ )
337
+ if any(value is None for value in values):
338
+ return None
339
+ return _format_identity(values)
340
+
341
+
342
+ def object_id_for(model: type[Any], pk: object) -> str:
343
+ """Return the ``object_id`` for a primary key of ``model``.
344
+
345
+ Args:
346
+ model: A mapped class.
347
+ pk: The key value, or a tuple of values in primary key column order
348
+ for a composite key.
349
+
350
+ Returns:
351
+ The same string ``object_id_of`` returns for that instance.
352
+
353
+ Raises:
354
+ ValueError: The number of values does not match the primary key, or
355
+ a value is ``None``.
356
+ """
357
+ mapper: Mapper[Any] = inspect(model)
358
+ values = pk if isinstance(pk, tuple) else (pk,)
359
+ if len(values) != len(mapper.primary_key):
360
+ raise ValueError(
361
+ f"{model.__qualname__} has a {len(mapper.primary_key)}-column primary "
362
+ f"key, got {len(values)} value(s)"
363
+ )
364
+ if any(value is None for value in values):
365
+ raise ValueError(f"primary key of {model.__qualname__} contains None")
366
+ return _format_identity(values)
367
+
368
+
369
+ def _format_identity(values: Sequence[object]) -> str:
370
+ if len(values) == 1:
371
+ return str(values[0])
372
+ return json.dumps([str(value) for value in values], separators=(",", ":"))
373
+
374
+
375
+ class _UnloadedAttributeError(Exception):
376
+ """Internal signal: an option read an attribute that is not loaded."""
377
+
378
+ def __init__(self, model: type[Any], attribute: str) -> None:
379
+ super().__init__(f"{model.__qualname__}.{attribute} is not loaded")
380
+ self.model = model
381
+ self.attribute = attribute
382
+
383
+
384
+ class _CachedPropertyError(Exception):
385
+ """Internal: an option read a ``functools.cached_property``."""
386
+
387
+ def __init__(self, model: type[Any], attribute: str) -> None:
388
+ super().__init__(f"{model.__qualname__}.{attribute} is a cached_property")
389
+ self.model = model
390
+ self.attribute = attribute
391
+
392
+
393
+ class _LoadedOnly:
394
+ """Read-only view of an instance that never loads anything.
395
+
396
+ Mapped attributes come from the instance's loaded state; one that would
397
+ need SQL raises ``_UnloadedAttributeError``. A column never set on an
398
+ instance without an identity yet is ``None``, unless it has a server-side
399
+ default. Properties, hybrids and
400
+ methods of the class run with the view as ``self``, so they cannot load
401
+ through the real instance either; so do ``__repr__`` and ``__str__``.
402
+ Loaded related instances are wrapped, also inside collections.
403
+ ``functools.cached_property`` is refused: it would have to store its
404
+ result on the view.
405
+ """
406
+
407
+ __slots__ = ("_audit_obj", "_audit_state")
408
+ _audit_obj: object
409
+ _audit_state: InstanceState[Any]
410
+
411
+ def __init__(self, obj: object) -> None:
412
+ object.__setattr__(self, "_audit_obj", obj)
413
+ object.__setattr__(self, "_audit_state", instance_state(obj))
414
+
415
+ def __getattr__(self, name: str) -> Any:
416
+ obj = self._audit_obj
417
+ state = self._audit_state
418
+ cls = type(obj)
419
+ if name in state.manager:
420
+ value = state.dict.get(name, NO_VALUE)
421
+ if value is NO_VALUE:
422
+ if _unset_is_null(state, name):
423
+ return None
424
+ raise _UnloadedAttributeError(cls, name)
425
+ return _wrap_related(state.mapper, name, value)
426
+ instance_dict: dict[str, Any] = getattr(obj, "__dict__", {})
427
+ for klass in cls.__mro__:
428
+ if name in vars(klass):
429
+ attr = vars(klass)[name]
430
+ break
431
+ else:
432
+ if name in instance_dict:
433
+ return instance_dict[name]
434
+ raise AttributeError(
435
+ f"{cls.__qualname__!r} object has no attribute {name!r}"
436
+ )
437
+ descriptor = type(attr)
438
+ is_data_descriptor = hasattr(descriptor, "__set__") or hasattr(
439
+ descriptor, "__delete__"
440
+ )
441
+ if not is_data_descriptor and name in instance_dict:
442
+ return instance_dict[name]
443
+ if isinstance(attr, functools.cached_property):
444
+ raise _CachedPropertyError(cls, name)
445
+ if hasattr(descriptor, "__get__"):
446
+ return attr.__get__(self, cls)
447
+ return attr
448
+
449
+ def __setattr__(self, name: str, value: object) -> None:
450
+ raise AttributeError("audit options must not modify the instance")
451
+
452
+ def __repr__(self) -> str:
453
+ obj = self._audit_obj
454
+ cls: type[object] = type(obj)
455
+ method: Callable[[object], str] = cls.__repr__
456
+ if method is object.__repr__:
457
+ return object.__repr__(obj)
458
+ return str(method(self))
459
+
460
+ def __str__(self) -> str:
461
+ cls: type[object] = type(self._audit_obj)
462
+ method: Callable[[object], str] = cls.__str__
463
+ if method is object.__str__:
464
+ # object.__str__ defers to __repr__, which applies the same rules.
465
+ return self.__repr__()
466
+ return str(method(self))
467
+
468
+
469
+ def _unset_is_null(state: InstanceState[Any], key: str) -> bool:
470
+ # A column never set on an instance that has no identity yet (new, or
471
+ # inserted by the flush being audited) is NULL in the row, as in
472
+ # entity_changes' "created" set, unless the database fills it in.
473
+ if state.key is not None:
474
+ return False
475
+ prop = state.mapper.get_property(key)
476
+ return isinstance(prop, ColumnProperty) and all(
477
+ isinstance(column, Column) and column.server_default is None
478
+ for column in prop.columns
479
+ )
480
+
481
+
482
+ def _wrap_related(mapper: Mapper[Any], name: str, value: object) -> object:
483
+ if name not in mapper.relationships or value is None:
484
+ return value
485
+ if isinstance(value, Mapping):
486
+ return {key: _LoadedOnly(item) for key, item in value.items()}
487
+ if mapper.relationships[name].uselist:
488
+ return [_LoadedOnly(item) for item in cast(Iterable[object], value)]
489
+ return _LoadedOnly(value)
490
+
491
+
492
+ _OptionName: TypeAlias = Literal["label", "scope", "target"]
493
+
494
+ # (model, attribute, option) already reported, so a misconfigured option on a
495
+ # busy model logs once per process instead of once per flush.
496
+ _warned: set[tuple[type[Any], str, _OptionName]] = set()
497
+
498
+
499
+ def _call_option(
500
+ obj: object, option: _OptionName, fn: Callable[[Any], Any]
501
+ ) -> tuple[bool, Any]:
502
+ try:
503
+ return True, fn(_LoadedOnly(obj))
504
+ except _UnloadedAttributeError as exc:
505
+ key = (exc.model, exc.attribute, option)
506
+ if key not in _warned:
507
+ _warned.add(key)
508
+ logger.warning(
509
+ "AuditOptions.%s of %s read %r, which is not loaded; using the "
510
+ "fallback. Options may only read attributes already loaded on "
511
+ "the instance. Logged once per process.",
512
+ option,
513
+ exc.model.__qualname__,
514
+ exc.attribute,
515
+ )
516
+ return False, None
517
+ except _CachedPropertyError as exc:
518
+ raise AuditOptionError(
519
+ f"AuditOptions.{option} of {exc.model.__qualname__} read "
520
+ f"{exc.attribute!r}: cached_property is not supported in audit "
521
+ "options; read the underlying column"
522
+ ) from None
523
+
524
+
525
+ def resolve_label(obj: object, options: AuditOptions) -> str | None:
526
+ """Evaluate ``options.label`` for ``object_label`` without emitting SQL.
527
+
528
+ Args:
529
+ obj: A mapped instance.
530
+ options: The model's options.
531
+
532
+ Returns:
533
+ The label as a string, or ``None`` when there is no ``label`` option,
534
+ it returns ``None``, or it read an attribute that is not loaded (then
535
+ logged once per model, attribute and option on the
536
+ ``audit_trail.diff`` logger).
537
+
538
+ Raises:
539
+ AuditOptionError: The option read a ``functools.cached_property``.
540
+ """
541
+ if options.label is None:
542
+ return None
543
+ ok, value = _call_option(obj, "label", options.label)
544
+ return str(value) if ok and value is not None else None
545
+
546
+
547
+ def resolve_scope(obj: object, options: AuditOptions) -> str | UseContext | None:
548
+ """Evaluate ``options.scope`` for ``scope_id`` without emitting SQL.
549
+
550
+ Args:
551
+ obj: A mapped instance.
552
+ options: The model's options.
553
+
554
+ Returns:
555
+ ``USE_CONTEXT`` when there is no ``scope`` option or it read an
556
+ attribute that is not loaded (then logged once per model, attribute
557
+ and option on the ``audit_trail.diff`` logger). Otherwise ``None``
558
+ when the option returned ``None`` (an explicit "no scope"), else the
559
+ value as a string.
560
+
561
+ Raises:
562
+ AuditOptionError: The option read a ``functools.cached_property``.
563
+ """
564
+ if options.scope is None:
565
+ return USE_CONTEXT
566
+ ok, value = _call_option(obj, "scope", options.scope)
567
+ if not ok:
568
+ return USE_CONTEXT
569
+ return None if value is None else str(value)
570
+
571
+
572
+ class ResolvedTarget(NamedTuple):
573
+ """A target as stored in ``target_type`` and ``target_id``."""
574
+
575
+ type: str
576
+ id: str
577
+ """Formatted like an ``object_id``."""
578
+
579
+
580
+ def resolve_target(obj: object, options: AuditOptions) -> ResolvedTarget | None:
581
+ """Evaluate ``options.target`` for ``target_type``/``target_id``.
582
+
583
+ Never emits SQL. The id is formatted like ``object_id``: a tuple becomes
584
+ a composite id, anything else ``str()``.
585
+
586
+ Args:
587
+ obj: A mapped instance.
588
+ options: The model's options.
589
+
590
+ Returns:
591
+ The stored target, or ``None`` when there is no ``target``
592
+ option, it returns ``None`` or an id of ``None``, or it read an
593
+ attribute that is not loaded (then logged once per model, attribute
594
+ and option on the ``audit_trail.diff`` logger).
595
+
596
+ Raises:
597
+ AuditOptionError: The option read a ``functools.cached_property``.
598
+ """
599
+ if options.target is None:
600
+ return None
601
+ ok, value = _call_option(obj, "target", options.target)
602
+ if not ok or value is None:
603
+ return None
604
+ return format_target(Target(*value))
605
+
606
+
607
+ def format_target(target: Target) -> ResolvedTarget | None:
608
+ """Format a target as stored in ``target_type`` and ``target_id``.
609
+
610
+ Args:
611
+ target: The type name and the id; a tuple id is a composite key.
612
+
613
+ Returns:
614
+ The stored target, or ``None`` when the id is ``None``.
615
+ """
616
+ if target.id is None:
617
+ return None
618
+ ids = target.id if isinstance(target.id, tuple) else (target.id,)
619
+ return ResolvedTarget(str(target.type), _format_identity(ids))