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/__init__.py +67 -0
- audit_trail/_compaction.py +297 -0
- audit_trail/_typing.py +17 -0
- audit_trail/checks.py +303 -0
- audit_trail/config.py +950 -0
- audit_trail/context.py +375 -0
- audit_trail/diff.py +619 -0
- audit_trail/events.py +441 -0
- audit_trail/integrations/__init__.py +1 -0
- audit_trail/integrations/fastapi.py +378 -0
- audit_trail/listener.py +655 -0
- audit_trail/maintenance.py +1028 -0
- audit_trail/migrations.py +309 -0
- audit_trail/mixin.py +118 -0
- audit_trail/privacy.py +410 -0
- audit_trail/py.typed +0 -0
- audit_trail/pytest_plugin.py +94 -0
- audit_trail/query.py +1616 -0
- audit_trail/relations.py +222 -0
- audit_trail/serialization.py +400 -0
- audit_trail/tables.py +264 -0
- audit_trail/testing.py +589 -0
- audit_trail/writer.py +485 -0
- sqlalchemy_audit_trail-0.1.0.dist-info/METADATA +200 -0
- sqlalchemy_audit_trail-0.1.0.dist-info/RECORD +27 -0
- sqlalchemy_audit_trail-0.1.0.dist-info/WHEEL +4 -0
- sqlalchemy_audit_trail-0.1.0.dist-info/licenses/LICENSE +21 -0
audit_trail/__init__.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
"""Audit trail for SQLAlchemy on PostgreSQL."""
|
|
2
|
+
|
|
3
|
+
from importlib.metadata import PackageNotFoundError, version
|
|
4
|
+
|
|
5
|
+
from audit_trail.checks import ModelIssue, check_models
|
|
6
|
+
from audit_trail.config import AuditOptions, AuditTrail, Target
|
|
7
|
+
from audit_trail.context import Actor, AuditContext
|
|
8
|
+
from audit_trail.diff import AuditOptionError, FieldPolicyError
|
|
9
|
+
from audit_trail.events import AuditEvent, Severity, event
|
|
10
|
+
from audit_trail.listener import AsyncLoadError
|
|
11
|
+
from audit_trail.mixin import Audited
|
|
12
|
+
from audit_trail.privacy import ScrubNotAllowedError, ScrubResult
|
|
13
|
+
from audit_trail.query import (
|
|
14
|
+
ALL_HISTORY,
|
|
15
|
+
AccessCount,
|
|
16
|
+
ActivityDetail,
|
|
17
|
+
AllHistory,
|
|
18
|
+
Cursor,
|
|
19
|
+
FieldLabels,
|
|
20
|
+
Group,
|
|
21
|
+
LabelResolver,
|
|
22
|
+
Page,
|
|
23
|
+
RelationshipLabels,
|
|
24
|
+
TransactionHeader,
|
|
25
|
+
Visibility,
|
|
26
|
+
)
|
|
27
|
+
from audit_trail.serialization import Pseudonymized
|
|
28
|
+
from audit_trail.writer import AuditWriteError
|
|
29
|
+
|
|
30
|
+
try:
|
|
31
|
+
__version__ = version("sqlalchemy-audit-trail")
|
|
32
|
+
except PackageNotFoundError: # pragma: no cover - running from a source tree
|
|
33
|
+
__version__ = "0.0.0"
|
|
34
|
+
|
|
35
|
+
__all__ = [
|
|
36
|
+
"ALL_HISTORY",
|
|
37
|
+
"AccessCount",
|
|
38
|
+
"ActivityDetail",
|
|
39
|
+
"Actor",
|
|
40
|
+
"AllHistory",
|
|
41
|
+
"AsyncLoadError",
|
|
42
|
+
"AuditContext",
|
|
43
|
+
"AuditEvent",
|
|
44
|
+
"AuditOptionError",
|
|
45
|
+
"AuditOptions",
|
|
46
|
+
"AuditTrail",
|
|
47
|
+
"AuditWriteError",
|
|
48
|
+
"Audited",
|
|
49
|
+
"Cursor",
|
|
50
|
+
"FieldLabels",
|
|
51
|
+
"FieldPolicyError",
|
|
52
|
+
"Group",
|
|
53
|
+
"LabelResolver",
|
|
54
|
+
"ModelIssue",
|
|
55
|
+
"Page",
|
|
56
|
+
"Pseudonymized",
|
|
57
|
+
"RelationshipLabels",
|
|
58
|
+
"ScrubNotAllowedError",
|
|
59
|
+
"ScrubResult",
|
|
60
|
+
"Severity",
|
|
61
|
+
"Target",
|
|
62
|
+
"TransactionHeader",
|
|
63
|
+
"Visibility",
|
|
64
|
+
"__version__",
|
|
65
|
+
"check_models",
|
|
66
|
+
"event",
|
|
67
|
+
]
|
|
@@ -0,0 +1,297 @@
|
|
|
1
|
+
"""Read-time compaction of activity rows.
|
|
2
|
+
|
|
3
|
+
The listener writes one ``entity.*`` row per flush and object, so a single
|
|
4
|
+
database transaction can hold several rows for the same object. Compaction
|
|
5
|
+
merges them into the net change the transaction made. It is a pure function
|
|
6
|
+
over rows that were already fetched: no session, no SQL.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
from __future__ import annotations
|
|
10
|
+
|
|
11
|
+
import dataclasses
|
|
12
|
+
import json
|
|
13
|
+
from collections.abc import Iterable, Sequence
|
|
14
|
+
from datetime import datetime
|
|
15
|
+
from itertools import pairwise
|
|
16
|
+
from typing import TypeAlias, TypedDict
|
|
17
|
+
from uuid import UUID
|
|
18
|
+
|
|
19
|
+
from audit_trail._typing import assert_never
|
|
20
|
+
from audit_trail.context import ContextSnapshot
|
|
21
|
+
from audit_trail.diff import ERASED, REDACTED, UNKNOWN
|
|
22
|
+
from audit_trail.events import Crud
|
|
23
|
+
from audit_trail.relations import RelationshipChange
|
|
24
|
+
from audit_trail.serialization import JSONValue
|
|
25
|
+
|
|
26
|
+
__all__ = ["ActivityData", "ActivityRow", "FieldChange", "compact_rows"]
|
|
27
|
+
|
|
28
|
+
FieldChange: TypeAlias = list[JSONValue] | RelationshipChange
|
|
29
|
+
"""A column change ``[old, new]`` or a relationship change."""
|
|
30
|
+
|
|
31
|
+
_CRUD_BY_VERB: dict[str, Crud] = {member.value: member for member in Crud}
|
|
32
|
+
|
|
33
|
+
_GroupKey: TypeAlias = tuple[int, str | None, str | None]
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class _ActivityDataBase(TypedDict):
|
|
37
|
+
v: int
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ActivityData(_ActivityDataBase, total=False):
|
|
41
|
+
"""The ``data`` envelope of an activity row.
|
|
42
|
+
|
|
43
|
+
Attributes:
|
|
44
|
+
v: Envelope version.
|
|
45
|
+
changes: ``entity.*`` changes keyed by attribute name.
|
|
46
|
+
payload: Payload of a custom event.
|
|
47
|
+
context: Request context snapshot taken when the entry was written.
|
|
48
|
+
"""
|
|
49
|
+
|
|
50
|
+
changes: dict[str, FieldChange]
|
|
51
|
+
payload: dict[str, JSONValue]
|
|
52
|
+
context: ContextSnapshot
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class ActivityRow(TypedDict):
|
|
56
|
+
"""One ``audit_activity`` row, as fetched from the database.
|
|
57
|
+
|
|
58
|
+
Attributes:
|
|
59
|
+
id: Row id.
|
|
60
|
+
transaction_id: Id of the audit transaction the row belongs to.
|
|
61
|
+
verb: Event verb, e.g. ``entity.updated``.
|
|
62
|
+
severity: Severity value.
|
|
63
|
+
object_type: Type of the changed object.
|
|
64
|
+
object_id: Id of the changed object.
|
|
65
|
+
object_label: Label of the object when the row was written.
|
|
66
|
+
target_type: Type of the parent object.
|
|
67
|
+
target_id: Id of the parent object.
|
|
68
|
+
actor_id: Actor of the event.
|
|
69
|
+
scope_id: Scope, e.g. a tenant.
|
|
70
|
+
correlation_id: Correlation id of the transaction.
|
|
71
|
+
created_at: Start of the database transaction.
|
|
72
|
+
data: The ``data`` envelope.
|
|
73
|
+
"""
|
|
74
|
+
|
|
75
|
+
id: int
|
|
76
|
+
transaction_id: int
|
|
77
|
+
verb: str
|
|
78
|
+
severity: int
|
|
79
|
+
object_type: str | None
|
|
80
|
+
object_id: str | None
|
|
81
|
+
object_label: str | None
|
|
82
|
+
target_type: str | None
|
|
83
|
+
target_id: str | None
|
|
84
|
+
actor_id: str | None
|
|
85
|
+
scope_id: str | None
|
|
86
|
+
correlation_id: UUID | None
|
|
87
|
+
created_at: datetime
|
|
88
|
+
data: ActivityData
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def compact_rows(
|
|
92
|
+
rows: Iterable[ActivityRow], *, compact: bool = True
|
|
93
|
+
) -> list[ActivityRow]:
|
|
94
|
+
"""Merge the ``entity.*`` rows of each object within each transaction.
|
|
95
|
+
|
|
96
|
+
Rows are grouped by ``(transaction_id, object_type, object_id)`` and each
|
|
97
|
+
group is folded in ``id`` order. Whether the object existed before the
|
|
98
|
+
transaction (the first verb is not ``entity.created``) and exists after it
|
|
99
|
+
(the last verb is not ``entity.deleted``) decides the result:
|
|
100
|
+
|
|
101
|
+
- neither: the object never existed outside the transaction, so the group
|
|
102
|
+
is hidden;
|
|
103
|
+
- only after: one ``entity.created`` with the final values;
|
|
104
|
+
- only before: one ``entity.deleted`` with the old values of the first row;
|
|
105
|
+
- both: one ``entity.updated``. A delete and re-insert of the same id
|
|
106
|
+
becomes the difference between the state before the delete and after the
|
|
107
|
+
insert. An update with no field left is hidden.
|
|
108
|
+
|
|
109
|
+
Column changes merge to ``[first old, last new]``. In an
|
|
110
|
+
``entity.updated`` result a column whose old and new values are equal is
|
|
111
|
+
dropped; ``entity.created`` and ``entity.deleted`` keep every column, as a
|
|
112
|
+
replay needs the full state. Equality is on the canonical JSON form of the
|
|
113
|
+
stored values (typed comparison already happened when they were written),
|
|
114
|
+
so ``true`` and ``1`` differ. A ``"***"``, ``"<unknown>"`` or ``"[erased]"``
|
|
115
|
+
marker on either side is never treated as equal: it hides whether the
|
|
116
|
+
value changed.
|
|
117
|
+
Relationship changes merge net: an id added and then removed disappears,
|
|
118
|
+
and the other way round. An ``"[erased]"`` id never cancels or merges with
|
|
119
|
+
another: each side keeps one per occurrence, after the real ids. A
|
|
120
|
+
relationship left with no ids is dropped for every verb.
|
|
121
|
+
|
|
122
|
+
The merged row takes ``id``, ``created_at``, ``correlation_id`` and the
|
|
123
|
+
output position of the group's lowest-id row; the other rows of the group
|
|
124
|
+
are removed. ``severity`` is the highest of the group. ``object_label``,
|
|
125
|
+
``target_type``, ``target_id``, ``scope_id`` and ``data.context`` come from
|
|
126
|
+
the last row. Every other row keeps its position, so input sorted by ``id``
|
|
127
|
+
in either direction stays sorted.
|
|
128
|
+
|
|
129
|
+
A group is returned as is when its rows have different ``actor_id``
|
|
130
|
+
values, when its verbs are not a possible sequence (e.g. an update after a
|
|
131
|
+
delete), or when it re-inserts a deleted id and has relationship changes
|
|
132
|
+
(the collection before the delete is not known). Single-row groups and
|
|
133
|
+
rows with other verbs are returned as the same objects. The input is never
|
|
134
|
+
modified; merged rows may share nested values with it. Compacting a
|
|
135
|
+
compacted result changes nothing.
|
|
136
|
+
|
|
137
|
+
Args:
|
|
138
|
+
rows: Activity rows, typically all rows of some transactions.
|
|
139
|
+
compact: ``False`` returns the rows unchanged.
|
|
140
|
+
|
|
141
|
+
Returns:
|
|
142
|
+
The rows, compacted unless ``compact`` is ``False``.
|
|
143
|
+
"""
|
|
144
|
+
rows = list(rows)
|
|
145
|
+
if not compact:
|
|
146
|
+
return rows
|
|
147
|
+
|
|
148
|
+
groups: dict[_GroupKey, list[int]] = {}
|
|
149
|
+
for index, row in enumerate(rows):
|
|
150
|
+
if row["verb"] in _CRUD_BY_VERB:
|
|
151
|
+
key = (row["transaction_id"], row["object_type"], row["object_id"])
|
|
152
|
+
groups.setdefault(key, []).append(index)
|
|
153
|
+
|
|
154
|
+
output: list[ActivityRow | None] = list(rows)
|
|
155
|
+
for indices in groups.values():
|
|
156
|
+
if len(indices) < 2:
|
|
157
|
+
continue
|
|
158
|
+
ordered = sorted(indices, key=lambda index: rows[index]["id"])
|
|
159
|
+
group = [rows[index] for index in ordered]
|
|
160
|
+
if not _can_compact(group):
|
|
161
|
+
continue
|
|
162
|
+
for index in indices:
|
|
163
|
+
output[index] = None
|
|
164
|
+
output[ordered[0]] = _merge(group)
|
|
165
|
+
return [row for row in output if row is not None]
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
def _can_compact(group: Sequence[ActivityRow]) -> bool:
|
|
169
|
+
if len({row["actor_id"] for row in group}) > 1:
|
|
170
|
+
return False
|
|
171
|
+
verbs = [_CRUD_BY_VERB[row["verb"]] for row in group]
|
|
172
|
+
pairs = list(pairwise(verbs))
|
|
173
|
+
if not all(_may_follow(previous, current) for previous, current in pairs):
|
|
174
|
+
return False
|
|
175
|
+
reinserts = (Crud.DELETED, Crud.CREATED) in pairs
|
|
176
|
+
return not (reinserts and any(_has_relationships(row) for row in group))
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
def _may_follow(previous: Crud, current: Crud) -> bool:
|
|
180
|
+
match previous:
|
|
181
|
+
case Crud.CREATED | Crud.UPDATED:
|
|
182
|
+
return current is not Crud.CREATED
|
|
183
|
+
case Crud.DELETED:
|
|
184
|
+
return current is Crud.CREATED
|
|
185
|
+
case _:
|
|
186
|
+
assert_never(previous)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def _has_relationships(row: ActivityRow) -> bool:
|
|
190
|
+
changes = row["data"].get("changes", {})
|
|
191
|
+
return any(isinstance(change, dict) for change in changes.values())
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
def _merge(group: Sequence[ActivityRow]) -> ActivityRow | None:
|
|
195
|
+
first, last = group[0], group[-1]
|
|
196
|
+
existed = _CRUD_BY_VERB[first["verb"]] is not Crud.CREATED
|
|
197
|
+
exists = _CRUD_BY_VERB[last["verb"]] is not Crud.DELETED
|
|
198
|
+
if existed and exists:
|
|
199
|
+
verb = Crud.UPDATED
|
|
200
|
+
elif exists:
|
|
201
|
+
verb = Crud.CREATED
|
|
202
|
+
elif existed:
|
|
203
|
+
verb = Crud.DELETED
|
|
204
|
+
else:
|
|
205
|
+
return None
|
|
206
|
+
|
|
207
|
+
changes = _merge_changes(group, drop_unchanged=verb is Crud.UPDATED)
|
|
208
|
+
if verb is Crud.UPDATED and not changes:
|
|
209
|
+
return None
|
|
210
|
+
data: ActivityData = {"v": last["data"]["v"], "changes": changes}
|
|
211
|
+
if "context" in last["data"]:
|
|
212
|
+
data["context"] = last["data"]["context"]
|
|
213
|
+
return {
|
|
214
|
+
"id": first["id"],
|
|
215
|
+
"transaction_id": first["transaction_id"],
|
|
216
|
+
"verb": verb.value,
|
|
217
|
+
"severity": max(row["severity"] for row in group),
|
|
218
|
+
"object_type": first["object_type"],
|
|
219
|
+
"object_id": first["object_id"],
|
|
220
|
+
"object_label": last["object_label"],
|
|
221
|
+
"target_type": last["target_type"],
|
|
222
|
+
"target_id": last["target_id"],
|
|
223
|
+
"actor_id": first["actor_id"],
|
|
224
|
+
"scope_id": last["scope_id"],
|
|
225
|
+
"correlation_id": first["correlation_id"],
|
|
226
|
+
"created_at": first["created_at"],
|
|
227
|
+
"data": data,
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
@dataclasses.dataclass
|
|
232
|
+
class _RelationDelta:
|
|
233
|
+
# Insertion-ordered dicts used as sets keep the output deterministic.
|
|
234
|
+
# Erased ids are indistinguishable, so they are only counted.
|
|
235
|
+
added: dict[str, None] = dataclasses.field(default_factory=dict)
|
|
236
|
+
removed: dict[str, None] = dataclasses.field(default_factory=dict)
|
|
237
|
+
erased_added: int = 0
|
|
238
|
+
erased_removed: int = 0
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
def _merge_changes(
|
|
242
|
+
group: Sequence[ActivityRow], *, drop_unchanged: bool
|
|
243
|
+
) -> dict[str, FieldChange]:
|
|
244
|
+
order: dict[str, None] = {}
|
|
245
|
+
columns: dict[str, list[JSONValue]] = {}
|
|
246
|
+
relations: dict[str, _RelationDelta] = {}
|
|
247
|
+
for row in group:
|
|
248
|
+
for field, change in row["data"].get("changes", {}).items():
|
|
249
|
+
order[field] = None
|
|
250
|
+
if isinstance(change, list):
|
|
251
|
+
old = columns[field][0] if field in columns else change[0]
|
|
252
|
+
columns[field] = [old, change[1]]
|
|
253
|
+
continue
|
|
254
|
+
delta = relations.setdefault(field, _RelationDelta())
|
|
255
|
+
added, removed = delta.added, delta.removed
|
|
256
|
+
for item in change["removed"]:
|
|
257
|
+
if item == ERASED:
|
|
258
|
+
delta.erased_removed += 1
|
|
259
|
+
elif item in added:
|
|
260
|
+
del added[item]
|
|
261
|
+
else:
|
|
262
|
+
removed[item] = None
|
|
263
|
+
for item in change["added"]:
|
|
264
|
+
if item == ERASED:
|
|
265
|
+
delta.erased_added += 1
|
|
266
|
+
elif item in removed:
|
|
267
|
+
del removed[item]
|
|
268
|
+
else:
|
|
269
|
+
added[item] = None
|
|
270
|
+
|
|
271
|
+
merged: dict[str, FieldChange] = {}
|
|
272
|
+
for field in order:
|
|
273
|
+
if field in columns:
|
|
274
|
+
old, new = columns[field]
|
|
275
|
+
if not (drop_unchanged and _unchanged(old, new)):
|
|
276
|
+
merged[field] = [old, new]
|
|
277
|
+
else:
|
|
278
|
+
delta = relations[field]
|
|
279
|
+
added_ids = [*delta.added, *[ERASED] * delta.erased_added]
|
|
280
|
+
removed_ids = [*delta.removed, *[ERASED] * delta.erased_removed]
|
|
281
|
+
if added_ids or removed_ids:
|
|
282
|
+
merged[field] = {"added": added_ids, "removed": removed_ids}
|
|
283
|
+
return merged
|
|
284
|
+
|
|
285
|
+
|
|
286
|
+
def _unchanged(old: JSONValue, new: JSONValue) -> bool:
|
|
287
|
+
if _is_marker(old) or _is_marker(new):
|
|
288
|
+
return False
|
|
289
|
+
return _canonical(old) == _canonical(new)
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _is_marker(value: JSONValue) -> bool:
|
|
293
|
+
return value in (REDACTED, UNKNOWN, ERASED)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _canonical(value: JSONValue) -> str:
|
|
297
|
+
return json.dumps(value, sort_keys=True, separators=(",", ":"))
|
audit_trail/_typing.py
ADDED
|
@@ -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}")
|
audit_trail/checks.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
"""Static checks of audited models, meant for CI.
|
|
2
|
+
|
|
3
|
+
``check_models`` inspects the mapped classes of a registry and returns every
|
|
4
|
+
problem it finds instead of raising on the first one, so a single CI run
|
|
5
|
+
reports all of them, warnings included::
|
|
6
|
+
|
|
7
|
+
def test_audited_models() -> None:
|
|
8
|
+
errors = [i for i in check_models(Base) if i.level == "error"]
|
|
9
|
+
assert not errors, "\\n".join(map(str, errors))
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
from __future__ import annotations
|
|
13
|
+
|
|
14
|
+
import re
|
|
15
|
+
from collections.abc import Collection, Iterator
|
|
16
|
+
from dataclasses import dataclass
|
|
17
|
+
from typing import TYPE_CHECKING, Any, Literal, TypeAlias
|
|
18
|
+
|
|
19
|
+
from sqlalchemy import Column
|
|
20
|
+
from sqlalchemy.ext.mutable import Mutable
|
|
21
|
+
from sqlalchemy.orm import registry
|
|
22
|
+
from sqlalchemy.types import JSON, TypeDecorator
|
|
23
|
+
|
|
24
|
+
from audit_trail._typing import assert_never
|
|
25
|
+
from audit_trail.config import AuditOptions
|
|
26
|
+
from audit_trail.diff import field_policy, options_of
|
|
27
|
+
from audit_trail.mixin import Audited
|
|
28
|
+
from audit_trail.relations import _tracked, _TrackedAttribute
|
|
29
|
+
|
|
30
|
+
if TYPE_CHECKING:
|
|
31
|
+
from sqlalchemy.orm import Mapper, RelationshipProperty
|
|
32
|
+
from sqlalchemy.types import TypeEngine
|
|
33
|
+
|
|
34
|
+
__all__ = ["IssueCode", "IssueLevel", "ModelIssue", "check_models"]
|
|
35
|
+
|
|
36
|
+
IssueCode: TypeAlias = Literal[
|
|
37
|
+
"sensitive-column",
|
|
38
|
+
"json-in-place",
|
|
39
|
+
"relationship-both-sides",
|
|
40
|
+
"unknown-relationship",
|
|
41
|
+
]
|
|
42
|
+
"""What a ``ModelIssue`` is about."""
|
|
43
|
+
|
|
44
|
+
IssueLevel: TypeAlias = Literal["error", "warning"]
|
|
45
|
+
"""How serious a ``ModelIssue`` is."""
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
@dataclass(frozen=True)
|
|
49
|
+
class ModelIssue:
|
|
50
|
+
"""One problem found by :func:`check_models`.
|
|
51
|
+
|
|
52
|
+
Attributes:
|
|
53
|
+
code: What the problem is about.
|
|
54
|
+
model: The mapped class it was found on.
|
|
55
|
+
attribute: The attribute key it concerns.
|
|
56
|
+
message: A human-readable explanation, with the fix.
|
|
57
|
+
"""
|
|
58
|
+
|
|
59
|
+
code: IssueCode
|
|
60
|
+
model: type[Any]
|
|
61
|
+
attribute: str
|
|
62
|
+
message: str
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def level(self) -> IssueLevel:
|
|
66
|
+
"""``"error"`` for a leak or a corrupt trail, ``"warning"`` otherwise."""
|
|
67
|
+
match self.code:
|
|
68
|
+
case (
|
|
69
|
+
"sensitive-column" | "relationship-both-sides" | "unknown-relationship"
|
|
70
|
+
):
|
|
71
|
+
return "error"
|
|
72
|
+
case "json-in-place":
|
|
73
|
+
return "warning"
|
|
74
|
+
case _:
|
|
75
|
+
assert_never(self.code)
|
|
76
|
+
|
|
77
|
+
def __str__(self) -> str:
|
|
78
|
+
return (
|
|
79
|
+
f"{self.level}: {self.model.__qualname__}.{self.attribute}: "
|
|
80
|
+
f"{self.message} [{self.code}]"
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def check_models(
|
|
85
|
+
base: registry | type[Any], *, allow_names: Collection[str] = ()
|
|
86
|
+
) -> list[ModelIssue]:
|
|
87
|
+
"""Check the audited models of a registry for configuration mistakes.
|
|
88
|
+
|
|
89
|
+
Configures the registry's mappers first. Reports:
|
|
90
|
+
|
|
91
|
+
- ``sensitive-column`` (error): a column of an ``Audited`` model whose
|
|
92
|
+
attribute key or database column name looks sensitive and that has no
|
|
93
|
+
explicit ``info={"audit": ...}`` policy. A name looks sensitive when it
|
|
94
|
+
contains ``password`` or ``passwd``, has one of the words ``pwd``,
|
|
95
|
+
``secret(s)``, ``token(s)``, ``credential(s)``, ``apikey`` or
|
|
96
|
+
``encrypted``, or ends in ``_key``; words are split on ``_`` and
|
|
97
|
+
camelCase. Names given to ``global_redact`` do not count: they are an
|
|
98
|
+
extra safety net, not a decision about the column.
|
|
99
|
+
- ``json-in-place`` (warning): an audited JSON column that is neither
|
|
100
|
+
tracked by ``sqlalchemy.ext.mutable`` nor listed in
|
|
101
|
+
``AuditOptions.snapshot_on_load``. Its in-place changes
|
|
102
|
+
(``obj.data["a"] = 1``) are not detected. ``Mutable`` detects them but
|
|
103
|
+
leaves the old value unknown; ``snapshot_on_load`` alone keeps the old
|
|
104
|
+
value but only helps when the change is flagged (``flag_modified``).
|
|
105
|
+
- ``relationship-both-sides`` (error): both sides of one relationship
|
|
106
|
+
(``back_populates`` or ``backref``) are tracked, through
|
|
107
|
+
``AuditOptions.track_relationships`` or ``track_relationships()``;
|
|
108
|
+
every membership change would be recorded twice.
|
|
109
|
+
- ``unknown-relationship`` (error): ``AuditOptions.track_relationships``
|
|
110
|
+
names something that is not a collection relationship of the model
|
|
111
|
+
(a missing name, a column or a scalar relationship).
|
|
112
|
+
|
|
113
|
+
Whether a column is ``Mutable`` is found by assigning ``{}`` and ``[]``
|
|
114
|
+
to the attribute of a throwaway instance created without ``__init__``;
|
|
115
|
+
no session and no SQL are involved, but the model's own ``set``
|
|
116
|
+
listeners and validators run.
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
base: A ``registry``, or a declarative base class that has one.
|
|
120
|
+
allow_names: ``"Model.attribute"`` entries (class ``__qualname__``
|
|
121
|
+
and attribute key) whose names only look sensitive; they are not
|
|
122
|
+
reported as ``sensitive-column``.
|
|
123
|
+
|
|
124
|
+
Returns:
|
|
125
|
+
The issues, sorted by model, attribute and code. Empty when there
|
|
126
|
+
are none.
|
|
127
|
+
|
|
128
|
+
Raises:
|
|
129
|
+
TypeError: ``base`` is neither a registry nor has one.
|
|
130
|
+
FieldPolicyError: A column has an unknown audit policy.
|
|
131
|
+
"""
|
|
132
|
+
reg = _registry_of(base)
|
|
133
|
+
reg.configure()
|
|
134
|
+
allowed = frozenset(allow_names)
|
|
135
|
+
# Base classes first, so an inherited column is reported where it is
|
|
136
|
+
# declared rather than once per subclass.
|
|
137
|
+
mappers = sorted(
|
|
138
|
+
reg.mappers, key=lambda m: (len(m.class_.__mro__), m.class_.__qualname__)
|
|
139
|
+
)
|
|
140
|
+
issues: list[ModelIssue] = []
|
|
141
|
+
seen_columns: set[Column[Any]] = set()
|
|
142
|
+
for mapper in mappers:
|
|
143
|
+
if issubclass(mapper.class_, Audited):
|
|
144
|
+
issues.extend(_check_columns(mapper, allowed, seen_columns))
|
|
145
|
+
issues.extend(_check_relationships(mappers))
|
|
146
|
+
issues.sort(key=lambda i: (i.model.__qualname__, i.attribute, i.code))
|
|
147
|
+
return issues
|
|
148
|
+
|
|
149
|
+
|
|
150
|
+
def _registry_of(base: registry | type[Any]) -> registry:
|
|
151
|
+
if isinstance(base, registry):
|
|
152
|
+
return base
|
|
153
|
+
reg = getattr(base, "registry", None)
|
|
154
|
+
if isinstance(reg, registry):
|
|
155
|
+
return reg
|
|
156
|
+
raise TypeError(f"expected a registry or a declarative base, got {base!r}")
|
|
157
|
+
|
|
158
|
+
|
|
159
|
+
def _check_columns(
|
|
160
|
+
mapper: Mapper[Any], allowed: frozenset[str], seen: set[Column[Any]]
|
|
161
|
+
) -> Iterator[ModelIssue]:
|
|
162
|
+
cls = mapper.class_
|
|
163
|
+
options = options_of(cls)
|
|
164
|
+
for prop in mapper.column_attrs:
|
|
165
|
+
column = prop.columns[0]
|
|
166
|
+
if not isinstance(column, Column) or column in seen:
|
|
167
|
+
continue
|
|
168
|
+
seen.add(column)
|
|
169
|
+
key = prop.key
|
|
170
|
+
policy = field_policy(cls, key, column)
|
|
171
|
+
if policy is None and f"{cls.__qualname__}.{key}" not in allowed:
|
|
172
|
+
matched = [n for n in (key, column.name) if _looks_sensitive(n)]
|
|
173
|
+
if matched:
|
|
174
|
+
yield ModelIssue(
|
|
175
|
+
"sensitive-column",
|
|
176
|
+
cls,
|
|
177
|
+
key,
|
|
178
|
+
f"name {matched[0]!r} looks sensitive but the column has no "
|
|
179
|
+
'audit policy; set info={"audit": "redact"} (or "hash" / '
|
|
180
|
+
f'"exclude"), or pass "{cls.__qualname__}.{key}" in '
|
|
181
|
+
"allow_names",
|
|
182
|
+
)
|
|
183
|
+
if (
|
|
184
|
+
policy != "exclude"
|
|
185
|
+
and _is_json(column.type)
|
|
186
|
+
and key not in options.snapshot_on_load
|
|
187
|
+
and not _is_mutable(mapper, key)
|
|
188
|
+
):
|
|
189
|
+
yield ModelIssue(
|
|
190
|
+
"json-in-place",
|
|
191
|
+
cls,
|
|
192
|
+
key,
|
|
193
|
+
"in-place changes of this JSON column are not detected; wrap its "
|
|
194
|
+
"type with sqlalchemy.ext.mutable (MutableDict/MutableList) and "
|
|
195
|
+
"list it in snapshot_on_load to also keep the old value, or "
|
|
196
|
+
"always assign a new object",
|
|
197
|
+
)
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
_WORD = re.compile(r"[A-Z]+(?![a-z])|[A-Z]?[a-z]+|\d+")
|
|
201
|
+
_SENSITIVE_WORDS = frozenset(
|
|
202
|
+
{
|
|
203
|
+
"password",
|
|
204
|
+
"passwd",
|
|
205
|
+
"pwd",
|
|
206
|
+
"secret",
|
|
207
|
+
"secrets",
|
|
208
|
+
"token",
|
|
209
|
+
"tokens",
|
|
210
|
+
"credential",
|
|
211
|
+
"credentials",
|
|
212
|
+
"apikey",
|
|
213
|
+
"encrypted",
|
|
214
|
+
}
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
def _looks_sensitive(name: str) -> bool:
|
|
219
|
+
# "apiKey", "APIKey" and "api_key" all give ["api", "key"].
|
|
220
|
+
words = [word.lower() for word in _WORD.findall(name)]
|
|
221
|
+
flat = "".join(words)
|
|
222
|
+
if "password" in flat or "passwd" in flat:
|
|
223
|
+
return True
|
|
224
|
+
if _SENSITIVE_WORDS.intersection(words):
|
|
225
|
+
return True
|
|
226
|
+
return len(words) > 1 and words[-1] == "key"
|
|
227
|
+
|
|
228
|
+
|
|
229
|
+
def _is_json(type_: TypeEngine[Any]) -> bool:
|
|
230
|
+
if isinstance(type_, TypeDecorator):
|
|
231
|
+
type_ = type_.impl_instance
|
|
232
|
+
return isinstance(type_, JSON)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
def _is_mutable(mapper: Mapper[Any], key: str) -> bool:
|
|
236
|
+
# Mutable coerces the value on assignment; a Mutable of the other shape
|
|
237
|
+
# (MutableList given a dict) rejects it with ValueError.
|
|
238
|
+
probes: tuple[object, ...] = ({}, [])
|
|
239
|
+
for probe in probes:
|
|
240
|
+
obj = mapper.class_manager.new_instance()
|
|
241
|
+
try:
|
|
242
|
+
setattr(obj, key, probe)
|
|
243
|
+
except Exception: # a host validator may reject it; then warn
|
|
244
|
+
continue
|
|
245
|
+
if isinstance(getattr(obj, key), Mutable):
|
|
246
|
+
return True
|
|
247
|
+
return False
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _check_relationships(mappers: list[Mapper[Any]]) -> Iterator[ModelIssue]:
|
|
251
|
+
# The first (most base) class tracking each relationship property.
|
|
252
|
+
tracked: dict[RelationshipProperty[Any], type[Any]] = {}
|
|
253
|
+
reported_names: set[tuple[int, str]] = set()
|
|
254
|
+
for mapper in mappers:
|
|
255
|
+
cls = mapper.class_
|
|
256
|
+
options = options_of(cls) if issubclass(cls, Audited) else AuditOptions()
|
|
257
|
+
names = set(options.track_relationships)
|
|
258
|
+
relationships = mapper.relationships
|
|
259
|
+
for key, prop in relationships.items():
|
|
260
|
+
if (key in names and prop.uselist) or any(
|
|
261
|
+
_TrackedAttribute(klass, key) in _tracked for klass in cls.__mro__
|
|
262
|
+
):
|
|
263
|
+
tracked.setdefault(prop, cls)
|
|
264
|
+
for name in sorted(names):
|
|
265
|
+
relationship = relationships.get(name)
|
|
266
|
+
if relationship is not None and relationship.uselist:
|
|
267
|
+
continue
|
|
268
|
+
# Subclasses inherit the same options object; report it once.
|
|
269
|
+
if (id(options), name) in reported_names:
|
|
270
|
+
continue
|
|
271
|
+
reported_names.add((id(options), name))
|
|
272
|
+
if relationship is not None:
|
|
273
|
+
what = "a scalar relationship; only collections can be tracked"
|
|
274
|
+
elif name in mapper.column_attrs:
|
|
275
|
+
what = "a column, not a relationship of the model"
|
|
276
|
+
else:
|
|
277
|
+
what = "not an attribute, not a relationship of the model"
|
|
278
|
+
yield ModelIssue(
|
|
279
|
+
"unknown-relationship",
|
|
280
|
+
cls,
|
|
281
|
+
name,
|
|
282
|
+
f"track_relationships names {name!r}, which is {what}",
|
|
283
|
+
)
|
|
284
|
+
reported_pairs: set[frozenset[RelationshipProperty[Any]]] = set()
|
|
285
|
+
for prop, cls in tracked.items():
|
|
286
|
+
for reverse in prop._reverse_property:
|
|
287
|
+
pair = frozenset((prop, reverse))
|
|
288
|
+
if reverse not in tracked or pair in reported_pairs:
|
|
289
|
+
continue
|
|
290
|
+
reported_pairs.add(pair)
|
|
291
|
+
(first_cls, first_key), (other_cls, other_key) = sorted(
|
|
292
|
+
[(cls, prop.key), (tracked[reverse], reverse.key)],
|
|
293
|
+
key=lambda side: (side[0].__qualname__, side[1]),
|
|
294
|
+
)
|
|
295
|
+
yield ModelIssue(
|
|
296
|
+
"relationship-both-sides",
|
|
297
|
+
first_cls,
|
|
298
|
+
first_key,
|
|
299
|
+
"both sides of one relationship are tracked "
|
|
300
|
+
f"({first_cls.__qualname__}.{first_key} and "
|
|
301
|
+
f"{other_cls.__qualname__}.{other_key}); every change would be "
|
|
302
|
+
"recorded twice, track only one side",
|
|
303
|
+
)
|