auditrum 0.4.2__tar.gz → 0.4.4__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (105) hide show
  1. {auditrum-0.4.2 → auditrum-0.4.4}/PKG-INFO +1 -1
  2. auditrum-0.4.4/auditrum/integrations/django/admin.py +207 -0
  3. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/runtime.py +31 -1
  4. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/utils.py +18 -5
  5. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum.egg-info/PKG-INFO +1 -1
  6. {auditrum-0.4.2 → auditrum-0.4.4}/pyproject.toml +1 -1
  7. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_admin.py +210 -35
  8. auditrum-0.4.2/auditrum/integrations/django/admin.py +0 -123
  9. {auditrum-0.4.2 → auditrum-0.4.4}/LICENSE +0 -0
  10. {auditrum-0.4.2 → auditrum-0.4.4}/README.md +0 -0
  11. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/__init__.py +0 -0
  12. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/blame.py +0 -0
  13. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/cli.py +0 -0
  14. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/context.py +0 -0
  15. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/executor.py +0 -0
  16. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/hardening.py +0 -0
  17. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/hash_chain.py +0 -0
  18. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/__init__.py +0 -0
  19. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/__init__.py +0 -0
  20. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/apps.py +0 -0
  21. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/audit.py +0 -0
  22. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/executor.py +0 -0
  23. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/management/__init__.py +0 -0
  24. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/management/commands/__init__.py +0 -0
  25. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/management/commands/audit_add_partitions.py +0 -0
  26. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/management/commands/auditrum_makemigrations.py +0 -0
  27. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/management/commands/auditrum_refresh_schema.py +0 -0
  28. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/middleware.py +0 -0
  29. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/migrations/0001_initial.py +0 -0
  30. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/migrations/0002_drop_content_type_id.py +0 -0
  31. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/migrations/0003_refresh_schema_04.py +0 -0
  32. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/migrations/__init__.py +0 -0
  33. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/mixins.py +0 -0
  34. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/models.py +0 -0
  35. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/operations.py +0 -0
  36. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/settings.py +0 -0
  37. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/shell_context.py +0 -0
  38. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/tasks.py +0 -0
  39. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/templates/audit/object_history.html +0 -0
  40. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/templatetags/__init__.py +0 -0
  41. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/templatetags/audit_tags.py +0 -0
  42. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/django/tracking.py +0 -0
  43. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/sqlalchemy/__init__.py +0 -0
  44. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/integrations/sqlalchemy/core.py +0 -0
  45. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/observability/__init__.py +0 -0
  46. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/observability/otel.py +0 -0
  47. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/observability/prometheus.py +0 -0
  48. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/observability/sentry.py +0 -0
  49. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/retention.py +0 -0
  50. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/revert.py +0 -0
  51. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/schema.py +0 -0
  52. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/settings.py +0 -0
  53. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/timetravel.py +0 -0
  54. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/tracking/__init__.py +0 -0
  55. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/tracking/_template.py +0 -0
  56. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/tracking/manager.py +0 -0
  57. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/tracking/spec.py +0 -0
  58. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/tracking/templates/__init__.py +0 -0
  59. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/tracking/templates/audit_attach_context.sql +0 -0
  60. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/tracking/templates/audit_current_user_id.sql +0 -0
  61. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/tracking/templates/audit_reconstruct_row.sql +0 -0
  62. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/tracking/templates/audit_reconstruct_table.sql +0 -0
  63. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/tracking/templates/audit_trigger.sql +0 -0
  64. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/triggers.py +0 -0
  65. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum/utils.py +0 -0
  66. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum.egg-info/SOURCES.txt +0 -0
  67. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum.egg-info/dependency_links.txt +0 -0
  68. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum.egg-info/entry_points.txt +0 -0
  69. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum.egg-info/requires.txt +0 -0
  70. {auditrum-0.4.2 → auditrum-0.4.4}/auditrum.egg-info/top_level.txt +0 -0
  71. {auditrum-0.4.2 → auditrum-0.4.4}/setup.cfg +0 -0
  72. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_blame.py +0 -0
  73. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_cli.py +0 -0
  74. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_context.py +0 -0
  75. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_audit.py +0 -0
  76. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_executor.py +0 -0
  77. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_init.py +0 -0
  78. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_middleware.py +0 -0
  79. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_models.py +0 -0
  80. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_operations.py +0 -0
  81. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_partitions_command.py +0 -0
  82. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_refresh_schema_command.py +0 -0
  83. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_runtime.py +0 -0
  84. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_settings.py +0 -0
  85. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_shell_context.py +0 -0
  86. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_tasks.py +0 -0
  87. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_templatetags.py +0 -0
  88. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_tracking_decorator.py +0 -0
  89. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_django_utils.py +0 -0
  90. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_executor.py +0 -0
  91. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_hardening.py +0 -0
  92. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_hash_chain.py +0 -0
  93. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_historical_row.py +0 -0
  94. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_mixins.py +0 -0
  95. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_observability.py +0 -0
  96. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_properties.py +0 -0
  97. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_retention.py +0 -0
  98. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_revert.py +0 -0
  99. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_schema.py +0 -0
  100. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_sqlalchemy_integration.py +0 -0
  101. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_timetravel.py +0 -0
  102. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_tracking_manager.py +0 -0
  103. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_tracking_spec.py +0 -0
  104. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_triggers.py +0 -0
  105. {auditrum-0.4.2 → auditrum-0.4.4}/tests/test_utils.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: auditrum
3
- Version: 0.4.2
3
+ Version: 0.4.4
4
4
  Summary: Auditrum — a PostgreSQL audit system with rich contextual logging and Django integration
5
5
  Author-email: Andrei Karbanovich <andrey.karbanovich@icloud.com>
6
6
  License: MIT
@@ -0,0 +1,207 @@
1
+ from django.contrib import admin
2
+ from django.urls import NoReverseMatch, reverse
3
+ from django.utils.html import format_html
4
+
5
+ from auditrum.integrations.django.models import AuditContext, AuditLog
6
+ from auditrum.integrations.django.utils import model_for_table
7
+
8
+ __all__ = [
9
+ "AuditContextAdmin",
10
+ "AuditLogAdmin",
11
+ ]
12
+
13
+
14
+ def _admin_change_url(table_name: str, object_id) -> str | None:
15
+ """Return the admin ``change`` URL for ``(table_name, object_id)``,
16
+ or ``None`` if the table doesn't map to a registered admin model or
17
+ the URL pattern can't be reversed for that object id.
18
+
19
+ Resolves the model via the memoised :func:`model_for_table`, so the
20
+ table → URL-name lookup is O(1) per distinct table_name on the page.
21
+ """
22
+ model_cls = model_for_table(table_name)
23
+ if model_cls is None:
24
+ return None
25
+ opts = model_cls._meta
26
+ url_name = f"admin:{opts.app_label}_{opts.model_name}_change"
27
+ try:
28
+ return reverse(url_name, args=[object_id])
29
+ except NoReverseMatch:
30
+ return None
31
+
32
+
33
+ @admin.register(AuditContext)
34
+ class AuditContextAdmin(admin.ModelAdmin):
35
+ list_display = (
36
+ "id",
37
+ "created_at",
38
+ "source",
39
+ "user_label",
40
+ "change_reason",
41
+ "event_count",
42
+ )
43
+ readonly_fields = (
44
+ "id",
45
+ "metadata",
46
+ "created_at",
47
+ "updated_at",
48
+ "events_link",
49
+ )
50
+ ordering = ("-created_at",)
51
+ search_fields = ("id",)
52
+
53
+ @admin.display(description="Events")
54
+ def event_count(self, obj):
55
+ return obj.events.count()
56
+
57
+ @admin.display(description="Source")
58
+ def source(self, obj):
59
+ return (obj.metadata or {}).get("source") or "—"
60
+
61
+ @admin.display(description="User")
62
+ def user_label(self, obj):
63
+ # ``username`` is the human-readable label the middleware stamps
64
+ # when available; ``user_id`` is the typed integer — fall back
65
+ # to whichever is present so the admin row always renders
66
+ # something meaningful for event-by-user triage.
67
+ metadata = obj.metadata or {}
68
+ return metadata.get("username") or metadata.get("user_id") or "—"
69
+
70
+ @admin.display(description="Change Reason")
71
+ def change_reason(self, obj):
72
+ return (obj.metadata or {}).get("change_reason") or "—"
73
+
74
+ @admin.display(description="Events in this context")
75
+ def events_link(self, obj):
76
+ # Render a link to the pre-filtered AuditLog changelist rather
77
+ # than embedding an inline — bulk operations under a single
78
+ # context can produce thousands of rows, which the inline would
79
+ # try to load in one page and OOM the admin. The filtered
80
+ # changelist is paginated and cheap. The URL uses the FK
81
+ # field name (``context``), not the DB column, so Django's
82
+ # changelist maps it to ``filter(context=<uuid>)`` directly.
83
+ count = obj.events.count()
84
+ url = reverse("admin:auditrum_django_auditlog_changelist")
85
+ return format_html(
86
+ '<a href="{}?context={}">View {} events</a>',
87
+ url,
88
+ obj.id,
89
+ count,
90
+ )
91
+
92
+
93
+ @admin.register(AuditLog)
94
+ class AuditLogAdmin(admin.ModelAdmin):
95
+ list_display = (
96
+ "changed_at",
97
+ "operation",
98
+ "table_name",
99
+ "object_id",
100
+ "user_id",
101
+ "context_id",
102
+ "linked_object",
103
+ )
104
+ list_filter = ("operation", "table_name")
105
+ # ``context_id`` is only the ``db_column`` of the ``context`` FK —
106
+ # not a concrete field on the model — so Django's default
107
+ # ``__icontains`` search lookup fails with ``FieldError: Unsupported
108
+ # lookup 'icontains' for ForeignKey``. Traverse via ``context__id``
109
+ # with an explicit ``__exact`` lookup: UUIDs are unique identifiers
110
+ # so substring matching has no use, and ``exact`` dodges the
111
+ # ``UPPER(uuid)`` casting that ``iexact`` would trigger. Django 4+
112
+ # honours explicit lookup suffixes in ``search_fields``.
113
+ #
114
+ # The ORM optimises ``context__id__exact`` into a direct
115
+ # ``auditlog.context_id = <uuid>`` comparison — it detects that
116
+ # ``id`` is the PK of the referenced ``AuditContext`` and the FK
117
+ # column already holds that value, so no JOIN is emitted. The
118
+ # query hits the ``auditlog_context_id_idx`` btree directly.
119
+ search_fields = ("object_id", "context__id__exact")
120
+ readonly_fields = [f.name for f in AuditLog._meta.fields]
121
+ ordering = ("-changed_at",)
122
+
123
+ # When ``False`` (default) the ``linked_object`` column renders a
124
+ # cheap ``<table>#<id>`` link to the standard admin change view —
125
+ # zero SQL queries per row, regardless of page size. When ``True``,
126
+ # the changelist additionally batch-fetches every referenced target
127
+ # via :meth:`Manager.in_bulk` (one SELECT per distinct ``table_name``
128
+ # on the page, **not** one per row) so the column can render the
129
+ # live ``str(target)``. The default switched in 0.4.4 to fix an N+1
130
+ # that made changelists with hundreds of events cancellable under
131
+ # ASGI.
132
+ resolve_linked_objects: bool = False
133
+
134
+ def changelist_view(self, request, extra_context=None):
135
+ response = super().changelist_view(request, extra_context)
136
+ if not self.resolve_linked_objects:
137
+ return response
138
+ # ``response.context_data`` only exists for TemplateResponse —
139
+ # it isn't there on redirects (e.g. action POST → 302) or on
140
+ # responses already rendered by middleware. The early-return
141
+ # also covers ``cl is None`` when the changelist short-circuits.
142
+ context_data = getattr(response, "context_data", None) or {}
143
+ cl = context_data.get("cl")
144
+ if cl is not None:
145
+ self._attach_linked_targets(cl.result_list)
146
+ return response
147
+
148
+ @staticmethod
149
+ def _attach_linked_targets(rows) -> None:
150
+ """Resolve every ``(table_name, object_id)`` tuple on the page
151
+ in O(distinct table_names) SELECTs and stash the result on each
152
+ row as ``_auditrum_linked``. ``linked_object`` then prefers the
153
+ stashed instance over the cheap link.
154
+
155
+ Mismatched PK types (e.g. an int ``object_id`` against a UUID
156
+ column) raise from ``in_bulk`` — the per-table block is skipped
157
+ rather than aborting the whole page. Models that aren't
158
+ installed at all are simply skipped.
159
+ """
160
+ buckets: dict[str, set[str]] = {}
161
+ for row in rows:
162
+ if row.table_name and row.object_id:
163
+ buckets.setdefault(row.table_name, set()).add(str(row.object_id))
164
+
165
+ resolved: dict[tuple[str, str], object] = {}
166
+ for table_name, ids in buckets.items():
167
+ model_cls = model_for_table(table_name)
168
+ if model_cls is None:
169
+ continue
170
+ try:
171
+ fetched = model_cls._default_manager.in_bulk(ids)
172
+ except (ValueError, TypeError):
173
+ continue
174
+ for pk, instance in fetched.items():
175
+ resolved[(table_name, str(pk))] = instance
176
+
177
+ for row in rows:
178
+ row._auditrum_linked = resolved.get((row.table_name, str(row.object_id)))
179
+
180
+ @admin.display(description="Linked Object")
181
+ def linked_object(self, obj):
182
+ if not obj.object_id or not obj.table_name:
183
+ return "-"
184
+ # Tier 2: when ``resolve_linked_objects`` is enabled and
185
+ # ``changelist_view`` has stashed a pre-fetched target, render
186
+ # ``str(target)`` (preserving the pre-0.4.4 behaviour).
187
+ prefetched = getattr(obj, "_auditrum_linked", None)
188
+ if prefetched is not None:
189
+ get_url = getattr(prefetched, "get_absolute_url", None)
190
+ if callable(get_url):
191
+ try:
192
+ return format_html(
193
+ '<a href="{}">{}</a>',
194
+ get_url(),
195
+ str(prefetched),
196
+ )
197
+ except Exception:
198
+ return str(prefetched)
199
+ return str(prefetched)
200
+ # Tier 1 default: zero-query link to the standard admin change
201
+ # view. Keeps the column useful for navigation without paying
202
+ # one SELECT per row at render time.
203
+ label = f"{obj.table_name}#{obj.object_id}"
204
+ url = _admin_change_url(obj.table_name, obj.object_id)
205
+ if url is None:
206
+ return label
207
+ return format_html('<a href="{}">{}</a>', url, label)
@@ -208,7 +208,37 @@ def _inject_audit_context(execute, sql, params, many, context):
208
208
  if is_bytes:
209
209
  new_sql = new_sql.encode()
210
210
 
211
- return execute(new_sql, new_params, many, context)
211
+ result = execute(new_sql, new_params, many, context)
212
+
213
+ # The injection turns a single user statement into a two-statement
214
+ # submission. psycopg3 leaves the cursor positioned on the FIRST
215
+ # result set after ``execute`` — the ``SELECT set_config(...)``
216
+ # row — so any downstream ``cursor.fetchone()`` /
217
+ # ``cursor.fetchall()`` call by Django's ORM reads the GUC values
218
+ # instead of the user query's rows. For ``INSERT … RETURNING id``
219
+ # this means ``instance.pk`` ends up set to the context UUID
220
+ # string rather than the ``bigint`` the database actually
221
+ # generated — breaking ``.save()``, FK assignment, and every
222
+ # ``filter(pk=…)`` lookup downstream (eridan-catalog team hit
223
+ # this in four separate code paths on 0.4.2).
224
+ #
225
+ # Advancing to the next result set via ``nextset()`` before
226
+ # returning moves the cursor to the user's query results, so the
227
+ # rest of Django's pipeline sees exactly what it would without
228
+ # the wrapper. ``nextset()`` is a DB-API 2.0 method; psycopg3
229
+ # supports it, and it returns ``None`` (or ``False``) harmlessly
230
+ # for statements that produced only one result set (DDL, bare
231
+ # UPDATE/DELETE without RETURNING).
232
+ cursor = context.get("cursor")
233
+ if cursor is not None:
234
+ # Defensive: if a custom backend's cursor doesn't support
235
+ # ``nextset()``, fall through rather than crash. Better a
236
+ # cursor-state issue downstream than a hard failure here on
237
+ # every query.
238
+ with contextlib.suppress(Exception):
239
+ cursor.nextset()
240
+
241
+ return result
212
242
 
213
243
 
214
244
  class auditrum_context(contextlib.ContextDecorator):
@@ -1,4 +1,5 @@
1
1
  from datetime import datetime
2
+ from functools import lru_cache
2
3
  from typing import Any, Protocol
3
4
 
4
5
  from django.apps import apps
@@ -15,6 +16,7 @@ from auditrum.utils import audit_tracked # re-exported for backwards compatibil
15
16
  class _ExecuteCursor(Protocol):
16
17
  def execute(self, query: str, params: Any = ..., /) -> Any: ...
17
18
 
19
+
18
20
  __all__ = [
19
21
  "audit_tracked",
20
22
  "link",
@@ -27,15 +29,22 @@ __all__ = [
27
29
  ]
28
30
 
29
31
 
32
+ @lru_cache(maxsize=512)
30
33
  def model_for_table(table_name: str) -> type[models.Model] | None:
31
34
  """Resolve a Django model class by its ``_meta.db_table`` name.
32
35
 
33
36
  Returns ``None`` when no installed model matches — the caller is
34
37
  expected to fall back to a table-name-only presentation, since audit
35
38
  rows can reference tables that live in a different service or were
36
- dropped after the event was recorded. Scans ``apps.get_models()``
37
- linearly; the set is small and stable per process, so a cache only
38
- pays off under pathological schemas.
39
+ dropped after the event was recorded.
40
+
41
+ Scans ``apps.get_models()`` linearly. The result is memoised for the
42
+ process lifetime: the AuditLog admin changelist calls this once per
43
+ rendered row, and Django's app registry is frozen after startup, so
44
+ the cache turns an O(N_rows × N_models) page render into one lookup
45
+ per distinct ``table_name`` ever seen. Tests that mutate the app
46
+ registry (rare — usually ``override_settings(INSTALLED_APPS=…)``)
47
+ must call ``model_for_table.cache_clear()`` explicitly.
39
48
  """
40
49
  for model in apps.get_models():
41
50
  if model._meta.db_table == table_name:
@@ -69,7 +78,9 @@ def resolve_field_value(model_class, field_name, value):
69
78
  value = f"[{value}]"
70
79
 
71
80
  # Date / Time fields
72
- elif isinstance(field, (models.DateTimeField, models.DateField, models.TimeField)) and value:
81
+ elif (
82
+ isinstance(field, (models.DateTimeField, models.DateField, models.TimeField)) and value
83
+ ):
73
84
  try:
74
85
  parsed = value
75
86
  if isinstance(value, str):
@@ -102,7 +113,9 @@ def render_log_changes(log):
102
113
  "<ul class='space-y-1'>{}</ul>",
103
114
  mark_safe(
104
115
  "".join(
105
- format_html("<li><strong>{}</strong>: {}</li>", *resolve_field_value(model_class, k, v))
116
+ format_html(
117
+ "<li><strong>{}</strong>: {}</li>", *resolve_field_value(model_class, k, v)
118
+ )
106
119
  for k, v in log.new_data.items()
107
120
  )
108
121
  ),
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: auditrum
3
- Version: 0.4.2
3
+ Version: 0.4.4
4
4
  Summary: Auditrum — a PostgreSQL audit system with rich contextual logging and Django integration
5
5
  Author-email: Andrei Karbanovich <andrey.karbanovich@icloud.com>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "auditrum"
7
- version = "0.4.2"
7
+ version = "0.4.4"
8
8
  description = "Auditrum — a PostgreSQL audit system with rich contextual logging and Django integration"
9
9
  readme = "README.md"
10
10
  authors = [
@@ -19,9 +19,7 @@ if not django_settings.configured:
19
19
  "django.contrib.messages",
20
20
  "auditrum.integrations.django",
21
21
  ],
22
- DATABASES={
23
- "default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}
24
- },
22
+ DATABASES={"default": {"ENGINE": "django.db.backends.sqlite3", "NAME": ":memory:"}},
25
23
  ROOT_URLCONF="django.contrib.contenttypes.urls",
26
24
  TEMPLATES=[
27
25
  {
@@ -145,13 +143,25 @@ class TestAuditLogAdminLinkedObject:
145
143
  """Regression for the 0.4 content_type bug: ``linked_object`` now
146
144
  resolves the instance via ``table_name`` (using ``model_for_table``)
147
145
  instead of the always-NULL ``content_object`` GenericForeignKey.
146
+
147
+ As of 0.4.4 the column also no longer fans out one SELECT per row.
148
+ The default path renders a zero-query ``<table>#<id>`` link to the
149
+ standard admin change view. Opt back in to live ``str(target)`` via
150
+ ``AuditLogAdmin.resolve_linked_objects = True`` — that path batches
151
+ fetches in :meth:`changelist_view` to one ``in_bulk`` per distinct
152
+ ``table_name``.
148
153
  """
149
154
 
150
- def test_returns_dash_when_table_unknown(self):
155
+ def test_renders_plain_label_when_table_unknown(self):
156
+ # When ``model_for_table`` doesn't recognise the table, fall back
157
+ # to a plain ``<table>#<id>`` label. Pre-0.4.4 this was ``"-"``;
158
+ # the label is strictly more useful for triage (cross-service
159
+ # audit rows still surface their identity) and avoids the
160
+ # surprise of dropped models silently disappearing from the UI.
151
161
  obj = MagicMock(spec=AuditLog)
152
162
  obj.table_name = "__no_such_table__"
153
163
  obj.object_id = "1"
154
- assert _auditlog_admin().linked_object(obj) == "-"
164
+ assert _auditlog_admin().linked_object(obj) == "__no_such_table__#1"
155
165
 
156
166
  def test_returns_dash_when_object_id_empty(self):
157
167
  obj = MagicMock(spec=AuditLog)
@@ -159,32 +169,81 @@ class TestAuditLogAdminLinkedObject:
159
169
  obj.object_id = ""
160
170
  assert _auditlog_admin().linked_object(obj) == "-"
161
171
 
162
- def test_returns_dash_when_instance_missing(self):
163
- """When ``model_for_table`` finds a matching model but the
164
- ``object_id`` refers to a deleted / never-existed row, resolve
165
- gracefully instead of raising to the admin changelist.
172
+ def test_returns_dash_when_table_name_empty(self):
173
+ obj = MagicMock(spec=AuditLog)
174
+ obj.table_name = ""
175
+ obj.object_id = "1"
176
+ assert _auditlog_admin().linked_object(obj) == "-"
177
+
178
+ def test_default_path_does_not_hit_db(self):
179
+ """Regression for the 0.4.3 N+1 in the AuditLog changelist:
180
+ rendering ``linked_object`` must never call
181
+ ``Manager.get`` / ``in_bulk`` on the default path. A page with N
182
+ rows used to issue N extra single-row SELECTs, blowing past
183
+ proxy/browser timeouts on filtered changelists.
166
184
  """
167
185
 
168
- class FakeDoesNotExist(Exception):
169
- pass
186
+ class ExplodingManager:
187
+ def get(self, *args, **kwargs):
188
+ raise AssertionError("linked_object hit the DB on the default path")
170
189
 
171
- class FakeManager:
172
- def get(self, pk):
173
- raise FakeDoesNotExist()
190
+ def in_bulk(self, *args, **kwargs):
191
+ raise AssertionError("linked_object hit the DB on the default path")
174
192
 
175
193
  class FakeModel:
176
- _default_manager = FakeManager()
177
- DoesNotExist = FakeDoesNotExist
194
+ _default_manager = ExplodingManager()
195
+ DoesNotExist = Exception
196
+
197
+ class _meta:
198
+ app_label = "fake"
199
+ model_name = "thing"
178
200
 
179
201
  obj = MagicMock(spec=AuditLog)
180
202
  obj.table_name = "orders"
181
203
  obj.object_id = "99999999"
182
204
 
183
- with patch(
184
- "auditrum.integrations.django.admin.model_for_table",
185
- return_value=FakeModel,
205
+ with (
206
+ patch(
207
+ "auditrum.integrations.django.admin.model_for_table",
208
+ return_value=FakeModel,
209
+ ),
210
+ patch(
211
+ "auditrum.integrations.django.admin.reverse",
212
+ return_value="/admin/fake/thing/99999999/change/",
213
+ ),
214
+ ):
215
+ html = _auditlog_admin().linked_object(obj)
216
+
217
+ assert "orders#99999999" in html
218
+ assert "/admin/fake/thing/99999999/change/" in html
219
+
220
+ def test_default_path_falls_back_to_label_when_no_admin_route(self):
221
+ """When the model exists but isn't admin-registered (so
222
+ ``reverse`` raises ``NoReverseMatch``), drop the ``<a>`` wrap
223
+ and emit the bare ``<table>#<id>`` label.
224
+ """
225
+ from django.urls import NoReverseMatch
226
+
227
+ class FakeModel:
228
+ class _meta:
229
+ app_label = "fake"
230
+ model_name = "thing"
231
+
232
+ obj = MagicMock(spec=AuditLog)
233
+ obj.table_name = "orders"
234
+ obj.object_id = "1"
235
+
236
+ with (
237
+ patch(
238
+ "auditrum.integrations.django.admin.model_for_table",
239
+ return_value=FakeModel,
240
+ ),
241
+ patch(
242
+ "auditrum.integrations.django.admin.reverse",
243
+ side_effect=NoReverseMatch(),
244
+ ),
186
245
  ):
187
- assert _auditlog_admin().linked_object(obj) == "-"
246
+ assert _auditlog_admin().linked_object(obj) == "orders#1"
188
247
 
189
248
  def test_search_fields_excludes_raw_context_id(self):
190
249
  """Regression for the 0.4.1 crash: ``context_id`` is only the
@@ -239,26 +298,142 @@ class TestAuditLogAdminLinkedObject:
239
298
  assert "object_id" in sql
240
299
  assert "LIKE" in sql.upper()
241
300
 
242
- def test_renders_link_when_instance_has_get_absolute_url(self):
243
- class FakeManager:
244
- def get(self, pk):
245
- target = MagicMock()
246
- target.get_absolute_url = MagicMock(return_value="/orders/1/")
247
- target.__str__ = MagicMock(return_value="Order #1")
248
- return target
249
-
250
- class FakeModel:
251
- _default_manager = FakeManager()
252
- DoesNotExist = Exception
301
+ def test_resolved_path_renders_get_absolute_url_when_prefetched(self):
302
+ """``resolve_linked_objects = True`` opts the admin into the
303
+ pre-0.4.4 ``str(target)`` rendering. The instance is provided
304
+ out-of-band (via ``_attach_linked_targets``) on the row as
305
+ ``_auditrum_linked``; ``linked_object`` then prefers it over
306
+ the cheap link.
307
+ """
308
+ target = MagicMock()
309
+ target.get_absolute_url = MagicMock(return_value="/orders/1/")
310
+ target.__str__ = MagicMock(return_value="Order #1")
253
311
 
254
312
  obj = MagicMock(spec=AuditLog)
255
313
  obj.table_name = "orders"
256
314
  obj.object_id = "1"
315
+ obj._auditrum_linked = target
316
+
317
+ html = _auditlog_admin().linked_object(obj)
318
+ assert "/orders/1/" in html
319
+ assert "Order #1" in html
320
+
321
+ def test_resolved_path_falls_back_to_str_when_no_url(self):
322
+ # ``MagicMock(spec=[])`` blocks every attr including ``__str__``,
323
+ # which we still need — use a real class with no
324
+ # ``get_absolute_url`` attribute instead.
325
+ class _Target:
326
+ def __str__(self) -> str:
327
+ return "Order #2"
328
+
329
+ obj = MagicMock(spec=AuditLog)
330
+ obj.table_name = "orders"
331
+ obj.object_id = "2"
332
+ obj._auditrum_linked = _Target()
333
+
334
+ assert _auditlog_admin().linked_object(obj) == "Order #2"
335
+
336
+
337
+ class TestAuditLogAdminBatchedResolve:
338
+ """The opt-in ``resolve_linked_objects`` path must keep changelist
339
+ rendering bounded by ``O(distinct table_names)`` SELECTs — the whole
340
+ point of the 0.4.4 fix is that adopters can recover the live
341
+ ``str(target)`` column without paying the per-row N+1.
342
+ """
343
+
344
+ def test_batches_in_bulk_per_table_name(self):
345
+ """50 rows across two distinct ``table_name`` values must hit
346
+ ``Manager.in_bulk`` exactly twice (once per table), not 50
347
+ times.
348
+ """
349
+ in_bulk_calls: list[tuple[str, set[str]]] = []
350
+
351
+ def _make_model(table: str):
352
+ class _Manager:
353
+ @staticmethod
354
+ def in_bulk(ids):
355
+ in_bulk_calls.append((table, set(ids)))
356
+ return {pk: f"{table}#{pk}" for pk in ids}
357
+
358
+ class _Model:
359
+ _default_manager = _Manager()
360
+
361
+ return _Model
362
+
363
+ models_by_table = {"orders": _make_model("orders"), "users": _make_model("users")}
364
+
365
+ rows = []
366
+ for i in range(40):
367
+ row = MagicMock(spec=AuditLog)
368
+ row.table_name = "orders"
369
+ row.object_id = str(i)
370
+ rows.append(row)
371
+ for i in range(10):
372
+ row = MagicMock(spec=AuditLog)
373
+ row.table_name = "users"
374
+ row.object_id = str(i)
375
+ rows.append(row)
257
376
 
258
377
  with patch(
259
378
  "auditrum.integrations.django.admin.model_for_table",
260
- return_value=FakeModel,
379
+ side_effect=lambda table: models_by_table.get(table),
261
380
  ):
262
- html = _auditlog_admin().linked_object(obj)
263
- assert "/orders/1/" in html
264
- assert "Order #1" in html
381
+ AuditLogAdmin._attach_linked_targets(rows)
382
+
383
+ # Exactly one ``in_bulk`` call per distinct table name, even
384
+ # though there are 50 rows on the page.
385
+ assert len(in_bulk_calls) == 2
386
+ tables_called = {call[0] for call in in_bulk_calls}
387
+ assert tables_called == {"orders", "users"}
388
+ # Every row got its target stashed for the renderer.
389
+ for row in rows:
390
+ assert row._auditrum_linked == f"{row.table_name}#{row.object_id}"
391
+
392
+ def test_skips_table_when_pk_type_mismatches(self):
393
+ """Mismatched PK types (e.g. integer ``object_id`` against a
394
+ UUID PK) raise ``ValueError`` from ``in_bulk``. The whole page
395
+ must keep rendering — only that one table is skipped.
396
+ """
397
+
398
+ class _BadManager:
399
+ @staticmethod
400
+ def in_bulk(ids):
401
+ raise ValueError("badly formed UUID")
402
+
403
+ class _BadModel:
404
+ _default_manager = _BadManager()
405
+
406
+ row = MagicMock(spec=AuditLog)
407
+ row.table_name = "orders"
408
+ row.object_id = "not-a-uuid"
409
+
410
+ with patch(
411
+ "auditrum.integrations.django.admin.model_for_table",
412
+ return_value=_BadModel,
413
+ ):
414
+ AuditLogAdmin._attach_linked_targets([row])
415
+
416
+ assert row._auditrum_linked is None
417
+
418
+ def test_changelist_view_skips_resolve_when_disabled(self):
419
+ """The default ``resolve_linked_objects = False`` must NOT call
420
+ ``_attach_linked_targets`` — that's what keeps the default page
421
+ render at zero extra SELECTs.
422
+ """
423
+ admin_ = _auditlog_admin()
424
+ assert admin_.resolve_linked_objects is False
425
+
426
+ with (
427
+ patch.object(
428
+ AuditLogAdmin,
429
+ "_attach_linked_targets",
430
+ ) as attach,
431
+ patch.object(
432
+ django_admin.ModelAdmin,
433
+ "changelist_view",
434
+ return_value=MagicMock(context_data={"cl": MagicMock()}),
435
+ ),
436
+ ):
437
+ admin_.changelist_view(MagicMock())
438
+
439
+ attach.assert_not_called()
@@ -1,123 +0,0 @@
1
- from django.contrib import admin
2
- from django.urls import reverse
3
- from django.utils.html import format_html
4
-
5
- from auditrum.integrations.django.models import AuditContext, AuditLog
6
- from auditrum.integrations.django.utils import model_for_table
7
-
8
- __all__ = [
9
- "AuditContextAdmin",
10
- "AuditLogAdmin",
11
- ]
12
-
13
-
14
- @admin.register(AuditContext)
15
- class AuditContextAdmin(admin.ModelAdmin):
16
- list_display = (
17
- "id",
18
- "created_at",
19
- "source",
20
- "user_label",
21
- "change_reason",
22
- "event_count",
23
- )
24
- readonly_fields = (
25
- "id",
26
- "metadata",
27
- "created_at",
28
- "updated_at",
29
- "events_link",
30
- )
31
- ordering = ("-created_at",)
32
- search_fields = ("id",)
33
-
34
- @admin.display(description="Events")
35
- def event_count(self, obj):
36
- return obj.events.count()
37
-
38
- @admin.display(description="Source")
39
- def source(self, obj):
40
- return (obj.metadata or {}).get("source") or "—"
41
-
42
- @admin.display(description="User")
43
- def user_label(self, obj):
44
- # ``username`` is the human-readable label the middleware stamps
45
- # when available; ``user_id`` is the typed integer — fall back
46
- # to whichever is present so the admin row always renders
47
- # something meaningful for event-by-user triage.
48
- metadata = obj.metadata or {}
49
- return (
50
- metadata.get("username")
51
- or metadata.get("user_id")
52
- or "—"
53
- )
54
-
55
- @admin.display(description="Change Reason")
56
- def change_reason(self, obj):
57
- return (obj.metadata or {}).get("change_reason") or "—"
58
-
59
- @admin.display(description="Events in this context")
60
- def events_link(self, obj):
61
- # Render a link to the pre-filtered AuditLog changelist rather
62
- # than embedding an inline — bulk operations under a single
63
- # context can produce thousands of rows, which the inline would
64
- # try to load in one page and OOM the admin. The filtered
65
- # changelist is paginated and cheap. The URL uses the FK
66
- # field name (``context``), not the DB column, so Django's
67
- # changelist maps it to ``filter(context=<uuid>)`` directly.
68
- count = obj.events.count()
69
- url = reverse("admin:auditrum_django_auditlog_changelist")
70
- return format_html(
71
- '<a href="{}?context={}">View {} events</a>',
72
- url,
73
- obj.id,
74
- count,
75
- )
76
-
77
-
78
- @admin.register(AuditLog)
79
- class AuditLogAdmin(admin.ModelAdmin):
80
- list_display = (
81
- "changed_at",
82
- "operation",
83
- "table_name",
84
- "object_id",
85
- "user_id",
86
- "context_id",
87
- "linked_object",
88
- )
89
- list_filter = ("operation", "table_name")
90
- # ``context_id`` is only the ``db_column`` of the ``context`` FK —
91
- # not a concrete field on the model — so Django's default
92
- # ``__icontains`` search lookup fails with ``FieldError: Unsupported
93
- # lookup 'icontains' for ForeignKey``. Traverse via ``context__id``
94
- # with an explicit ``__exact`` lookup: UUIDs are unique identifiers
95
- # so substring matching has no use, and ``exact`` dodges the
96
- # ``UPPER(uuid)`` casting that ``iexact`` would trigger. Django 4+
97
- # honours explicit lookup suffixes in ``search_fields``.
98
- #
99
- # The ORM optimises ``context__id__exact`` into a direct
100
- # ``auditlog.context_id = <uuid>`` comparison — it detects that
101
- # ``id`` is the PK of the referenced ``AuditContext`` and the FK
102
- # column already holds that value, so no JOIN is emitted. The
103
- # query hits the ``auditlog_context_id_idx`` btree directly.
104
- search_fields = ("object_id", "context__id__exact")
105
- readonly_fields = [f.name for f in AuditLog._meta.fields]
106
- ordering = ("-changed_at",)
107
-
108
- @admin.display(description="Linked Object")
109
- def linked_object(self, obj):
110
- model_class = model_for_table(obj.table_name)
111
- if model_class is None or not obj.object_id:
112
- return "-"
113
- try:
114
- target = model_class._default_manager.get(pk=obj.object_id)
115
- except (model_class.DoesNotExist, ValueError, TypeError):
116
- return "-"
117
- get_url = getattr(target, "get_absolute_url", None)
118
- if callable(get_url):
119
- try:
120
- return format_html('<a href="{}">{}</a>', get_url(), str(target))
121
- except Exception:
122
- return str(target)
123
- return str(target)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes