simple-module-db 0.0.43__tar.gz → 0.0.44__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 (132) hide show
  1. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/PKG-INFO +2 -2
  2. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/pyproject.toml +2 -2
  3. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/_bulk_audit_records.py +22 -4
  4. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/audit.py +7 -4
  5. simple_module_db-0.0.44/simple_module_db/audit_redaction.py +71 -0
  6. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/audit_sinks.py +1 -1
  7. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/bulk_audit.py +3 -2
  8. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/leases.py +3 -1
  9. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/listeners.py +8 -1
  10. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/query_filter.py +1 -1
  11. simple_module_db-0.0.44/simple_module_db/query_stats.py +85 -0
  12. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/stored_settings.py +12 -0
  13. simple_module_db-0.0.44/tests/test_db_credential_audit.py +168 -0
  14. simple_module_db-0.0.44/tests/test_db_credential_log_masking.py +16 -0
  15. simple_module_db-0.0.44/tests/test_db_query_stats.py +95 -0
  16. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/.gitignore +0 -0
  17. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/LICENSE +0 -0
  18. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/README.md +0 -0
  19. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/__init__.py +0 -0
  20. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/_bulk_pk_update.py +0 -0
  21. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/_core_joins.py +0 -0
  22. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/_core_walk.py +0 -0
  23. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/_engine_policies.py +0 -0
  24. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/_entity_selectables.py +0 -0
  25. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/_migration_render.py +0 -0
  26. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/_outer_joins.py +0 -0
  27. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/_persisted_owner.py +0 -0
  28. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/_secondary_scope.py +0 -0
  29. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/admission.py +0 -0
  30. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/base.py +0 -0
  31. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/bulk_audit_targets.py +0 -0
  32. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/bulk_guard.py +0 -0
  33. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/callbacks.py +0 -0
  34. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/core_scope.py +0 -0
  35. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/data_compatibility.py +0 -0
  36. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/deps.py +0 -0
  37. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/engine_options.py +0 -0
  38. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/extensions.py +0 -0
  39. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/flush_guard.py +0 -0
  40. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/independent.py +0 -0
  41. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/insert_guard.py +0 -0
  42. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/insert_scope.py +0 -0
  43. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/migration_portability.py +0 -0
  44. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/migrations.py +0 -0
  45. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/mixins.py +0 -0
  46. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/model_registry.py +0 -0
  47. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/pagination.py +0 -0
  48. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/provider.py +0 -0
  49. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/py.typed +0 -0
  50. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/resource_policy.py +0 -0
  51. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/scope_predicates.py +0 -0
  52. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/search.py +0 -0
  53. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/session.py +0 -0
  54. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/tenancy.py +0 -0
  55. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/tenant_cleanup.py +0 -0
  56. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/transaction.py +0 -0
  57. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/types.py +0 -0
  58. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/user_directory_sql.py +0 -0
  59. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/simple_module_db/writes.py +0 -0
  60. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/_audit_models.py +0 -0
  61. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/_bulk_audit_support.py +0 -0
  62. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/_core_scope_models.py +0 -0
  63. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/_db_dml_scope_models.py +0 -0
  64. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/_db_read_scope_models.py +0 -0
  65. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/_db_shape_matrix.py +0 -0
  66. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/_models.py +0 -0
  67. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/conftest.py +0 -0
  68. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_audit.py +0 -0
  69. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_audit_per_engine.py +0 -0
  70. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_aware_datetime.py +0 -0
  71. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_base.py +0 -0
  72. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_aliased_join_text_scope.py +0 -0
  73. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_aliased_selectable_scope.py +0 -0
  74. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_audit_regressions.py +0 -0
  75. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_bulk_audit.py +0 -0
  76. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_bulk_audit_targets.py +0 -0
  77. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_connection_policy.py +0 -0
  78. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_core_full_setup_join.py +0 -0
  79. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_core_in_orm_select.py +0 -0
  80. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_core_join_scope.py +0 -0
  81. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_core_nested_scope.py +0 -0
  82. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_data_compatibility_doctor.py +0 -0
  83. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_dml_target_scope.py +0 -0
  84. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_doctor_session_filters.py +0 -0
  85. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_engine_options.py +0 -0
  86. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_engine_policy_resolution.py +0 -0
  87. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_extensions.py +0 -0
  88. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_extensions_pg.py +0 -0
  89. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_flush_persisted_owner.py +0 -0
  90. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_independent_checkpoint.py +0 -0
  91. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_insert_select_tenant.py +0 -0
  92. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_insert_value_subqueries.py +0 -0
  93. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_lease_lock_wait.py +0 -0
  94. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_listeners_attach.py +0 -0
  95. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_logging.py +0 -0
  96. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_migration_review_regressions.py +0 -0
  97. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_nested_dml_and_bulk_api.py +0 -0
  98. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_pagination.py +0 -0
  99. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_pagination_options.py +0 -0
  100. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_relationship_loader_scope.py +0 -0
  101. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_response_finalization.py +0 -0
  102. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_savepoint_callbacks.py +0 -0
  103. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_secondary_scope_execution.py +0 -0
  104. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_shape_matrix_dml.py +0 -0
  105. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_shape_matrix_joins.py +0 -0
  106. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_shape_matrix_selects.py +0 -0
  107. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_sqlite_admission_lock.py +0 -0
  108. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_sqlite_savepoint.py +0 -0
  109. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_sqlite_wal_switch.py +0 -0
  110. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_stored_settings.py +0 -0
  111. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_strict_insert_context.py +0 -0
  112. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_tenant_cleanup.py +0 -0
  113. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_tenant_upsert_guard.py +0 -0
  114. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_user_directory_sql.py +0 -0
  115. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_db_write_marks.py +0 -0
  116. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_default_tenant.py +0 -0
  117. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_independent_session.py +0 -0
  118. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_migration_portability.py +0 -0
  119. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_migrations.py +0 -0
  120. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_mixins.py +0 -0
  121. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_multi_tenancy.py +0 -0
  122. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_query_filter_outer_joins.py +0 -0
  123. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_query_filter_rel_outer_joins.py +0 -0
  124. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_query_filters.py +0 -0
  125. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_rollback_logging.py +0 -0
  126. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_session.py +0 -0
  127. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_soft_delete_shapes.py +0 -0
  128. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_tenant_dml.py +0 -0
  129. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_tenant_shapes.py +0 -0
  130. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_tenant_strict.py +0 -0
  131. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_transaction.py +0 -0
  132. {simple_module_db-0.0.43 → simple_module_db-0.0.44}/tests/test_writes.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: simple_module_db
3
- Version: 0.0.43
3
+ Version: 0.0.44
4
4
  Summary: Per-module SQLModel Base, async session, standard mixins (Audit, SoftDelete, MultiTenant, Versioned) for simple_module
5
5
  Project-URL: Homepage, https://github.com/antosubash/simple_module_python
6
6
  Project-URL: Repository, https://github.com/antosubash/simple_module_python
@@ -25,7 +25,7 @@ Requires-Dist: aiosqlite<0.23,>=0.20
25
25
  Requires-Dist: alembic<2,>=1.14
26
26
  Requires-Dist: asyncpg<0.33,>=0.30
27
27
  Requires-Dist: psycopg2-binary<3,>=2.9
28
- Requires-Dist: simple-module-core==0.0.43
28
+ Requires-Dist: simple-module-core==0.0.44
29
29
  Requires-Dist: sqlalchemy[asyncio]<3,>=2.0.2
30
30
  Requires-Dist: sqlmodel<0.1,>=0.0.22
31
31
  Description-Content-Type: text/markdown
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "simple_module_db"
3
- version = "0.0.43"
3
+ version = "0.0.44"
4
4
  description = "Per-module SQLModel Base, async session, standard mixins (Audit, SoftDelete, MultiTenant, Versioned) for simple_module"
5
5
  readme = "README.md"
6
6
  license = "MIT"
@@ -28,7 +28,7 @@ dependencies = [
28
28
  # The async app code goes through asyncpg; migration env.py rewrites the
29
29
  # URL to +psycopg2 because Alembic's online migrations are sync-only.
30
30
  "psycopg2-binary>=2.9,<3",
31
- "simple_module_core==0.0.43",
31
+ "simple_module_core==0.0.44",
32
32
  "sqlalchemy[asyncio]>=2.0.2,<3",
33
33
  "sqlmodel>=0.0.22,<0.1",
34
34
  ]
@@ -10,7 +10,8 @@ from simple_module_core.correlation import correlation_id
10
10
  from sqlalchemy import inspect as sa_inspect
11
11
  from sqlalchemy.orm import ORMExecuteState, Session
12
12
 
13
- from simple_module_db.audit import AuditRecord, _serialize, format_pk
13
+ from simple_module_db.audit import AuditRecord, _excluded_fields, _serialize, format_pk
14
+ from simple_module_db.audit_redaction import model_for_audit, redact_changes, redact_entity_id
14
15
  from simple_module_db.query_filter import engine_policy
15
16
 
16
17
  logger = logging.getLogger("simple_module_db.bulk_audit")
@@ -29,8 +30,16 @@ _ACTIVE_KEY: Final = "_sm_bulk_audit_active"
29
30
  class _Ctx:
30
31
  """What one audited statement records, built before it runs."""
31
32
 
32
- def __init__(self, entity_type: str, action: str, changes: list[dict[str, Any]]) -> None:
33
+ def __init__(
34
+ self,
35
+ entity_type: str,
36
+ action: str,
37
+ changes: list[dict[str, Any]],
38
+ model: type | None = None,
39
+ ) -> None:
33
40
  self.entity_type = entity_type
41
+ # The statement's own class when known: a name lookup scans the registry.
42
+ self._model = model or model_for_audit(entity_type)
34
43
  self.action = action
35
44
  self.row_actions = [action]
36
45
  self.changes = changes
@@ -45,7 +54,11 @@ class _Ctx:
45
54
  ) -> AuditRecord:
46
55
  return AuditRecord(
47
56
  entity_type=self.entity_type,
48
- entity_id=entity_id,
57
+ entity_id=(
58
+ entity_id
59
+ if entity_id == SUMMARY_ENTITY_ID
60
+ else redact_entity_id(self._model, entity_id)
61
+ ),
49
62
  action=action or self.action,
50
63
  changes=self.changes if changes is None else changes,
51
64
  user_id=self.user_id,
@@ -113,6 +126,11 @@ def record_bulk_audit(
113
126
  return
114
127
  name = entity_type if isinstance(entity_type, str) else entity_type.__name__
115
128
  diff = [{"field": k, "new": _serialize(v)} for k, v in (changes or {}).items()]
116
- ctx = _Ctx(name, action, diff)
129
+ ctx = _Ctx(name, action, diff, entity_type if isinstance(entity_type, type) else None)
130
+ model = ctx._model
131
+ if model is not None:
132
+ ctx.changes = redact_changes(
133
+ model, [c for c in diff if c["field"] not in _excluded_fields(model)]
134
+ )
117
135
  keys = [SUMMARY_ENTITY_ID] if ids is None else [str(i) for i in ids]
118
136
  _deliver(sync, callback, [ctx.record(k) for k in keys])
@@ -23,6 +23,7 @@ from typing import Any
23
23
  from sqlalchemy import inspect as sa_inspect
24
24
  from sqlalchemy.orm import Session
25
25
 
26
+ from simple_module_db.audit_redaction import redact_changes, redact_entity_id
26
27
  from simple_module_db.mixins import SoftDeleteMixin
27
28
 
28
29
  # Fields injected by AuditMixin — always excluded from change diffs
@@ -97,8 +98,10 @@ def _entity_pk_str(obj: object) -> str:
97
98
  if identity is None:
98
99
  # Pre-flush: fall back to the mapper-level key attrs
99
100
  mapper = inspector.mapper
100
- return format_pk([getattr(obj, col.key) for col in mapper.primary_key])
101
- return format_pk(identity)
101
+ pk = format_pk([getattr(obj, col.key) for col in mapper.primary_key])
102
+ else:
103
+ pk = format_pk(identity)
104
+ return redact_entity_id(type(obj), pk)
102
105
 
103
106
 
104
107
  def _column_names(obj: object) -> list[str]:
@@ -128,7 +131,7 @@ def _column_diffs(obj: object, inspector: Any, excl: frozenset[str]) -> list[dic
128
131
  old_val = hist.deleted[0] if hist.deleted else None
129
132
  new_val = hist.added[0] if hist.added else None
130
133
  changes.append({"field": col_name, "old": _serialize(old_val), "new": _serialize(new_val)})
131
- return changes
134
+ return redact_changes(type(obj), changes, obj)
132
135
 
133
136
 
134
137
  # ---------------------------------------------------------------------------
@@ -182,7 +185,7 @@ def snapshot_changes(
182
185
  obj_ref=obj,
183
186
  entity_type=type(obj).__name__,
184
187
  action="created",
185
- changes=changes,
188
+ changes=redact_changes(type(obj), changes, obj),
186
189
  user_id=user_id,
187
190
  correlation_id=correlation_id,
188
191
  )
@@ -0,0 +1,71 @@
1
+ """Shared credential redaction for flush, statement and manual audit capture."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any, Final
6
+
7
+ from sqlalchemy import inspect
8
+
9
+ AUDIT_REDACTED: Final = "[redacted]"
10
+
11
+
12
+ def model_for_audit(model: type | str) -> type | None:
13
+ """Accept a mapped class or its registered class name; None for unknown names."""
14
+ if isinstance(model, type):
15
+ return model
16
+ from simple_module_db.model_registry import classes_by_table
17
+
18
+ return next((cls for cls in classes_by_table.values() if cls.__name__ == model), None)
19
+
20
+
21
+ def redact_changes(
22
+ model: type, changes: list[dict[str, Any]], obj: object | None = None
23
+ ) -> list[dict[str, Any]]:
24
+ """Keep fields and diff shape, replacing credential values before delivery.
25
+
26
+ A row predicate receives both the current and pre-edit column values. With
27
+ no row (statement/manual capture) it receives None and must fail closed.
28
+ """
29
+ if not changes:
30
+ return changes
31
+ fields = set(getattr(model, "__audit_redact_fields__", ()))
32
+ predicate = getattr(model, "__audit_redact_row__", None)
33
+ if predicate is not None:
34
+ if obj is None:
35
+ fields.update(predicate(None))
36
+ else:
37
+ state = inspect(obj)
38
+ current: dict[str, Any] = {}
39
+ previous: dict[str, Any] = {}
40
+ for attr in state.mapper.column_attrs:
41
+ key = attr.key
42
+ value = current[key] = state.dict.get(key)
43
+ history = state.attrs[key].history
44
+ if history.has_changes():
45
+ previous[key] = history.deleted[0] if history.deleted else None
46
+ else:
47
+ previous[key] = value
48
+ fields.update(predicate(current))
49
+ if state.persistent:
50
+ fields.update(predicate(previous))
51
+ if not fields:
52
+ return changes
53
+ return [
54
+ {
55
+ k: AUDIT_REDACTED if c["field"] in fields and k in {"old", "new"} else v
56
+ for k, v in c.items()
57
+ }
58
+ for c in changes
59
+ ]
60
+
61
+
62
+ def pk_is_redacted(model: type | None) -> bool:
63
+ """True when a primary-key column of ``model`` is itself a redacted credential."""
64
+ fields = getattr(model, "__audit_redact_fields__", None)
65
+ if model is None or not fields:
66
+ return False
67
+ return any(col.key in fields for col in inspect(model).primary_key)
68
+
69
+
70
+ def redact_entity_id(model: type | None, entity_id: str) -> str:
71
+ return AUDIT_REDACTED if pk_is_redacted(model) else entity_id
@@ -7,7 +7,7 @@ the installed distributions instead: a module that stores audit records
7
7
  declares::
8
8
 
9
9
  [project.entry-points."simple_module.audit_sinks"]
10
- audit_log = "audit_log.capture:audit_callback"
10
+ audit_log = "audit_log.core.capture:audit_callback"
11
11
 
12
12
  and the worker binds the result to its engine with
13
13
  ``EngineTenancy(audit_callback=...)``. Neither side imports the other (#498).
@@ -52,6 +52,7 @@ from simple_module_db._bulk_audit_records import ( # noqa: F401 (re-exported)
52
52
  record_bulk_audit,
53
53
  )
54
54
  from simple_module_db.audit import _excluded_fields, format_pk
55
+ from simple_module_db.audit_redaction import redact_changes
55
56
  from simple_module_db.bulk_audit_targets import _is_set, _shown, _targets
56
57
  from simple_module_db.query_filter import engine_policy
57
58
  from simple_module_db.tenancy import ALL_TENANTS_OPTION
@@ -85,7 +86,7 @@ def _plan(execute_state: ORMExecuteState, cls: type) -> _Ctx | None:
85
86
  """The record shape for this statement, or ``None`` when nothing is audited."""
86
87
  name = cls.__name__
87
88
  if execute_state.is_delete:
88
- return _Ctx(name, ACTION_BULK_DELETED, [])
89
+ return _Ctx(name, ACTION_BULK_DELETED, [], cls)
89
90
  rows, many = _targets(execute_state, cls)
90
91
  default = ACTION_BULK_INSERTED if execute_state.is_insert else ACTION_BULK_UPDATED
91
92
  # The soft-delete flag picks a row's action; it is never a change, and
@@ -112,7 +113,7 @@ def _plan(execute_state: ORMExecuteState, cls: type) -> _Ctx | None:
112
113
  changes = [{"field": k} for k in kept]
113
114
  else:
114
115
  changes = [{"field": k, "new": _shown(rows[0][k])} for k in kept]
115
- ctx = _Ctx(name, actions[0] if actions else default, changes)
116
+ ctx = _Ctx(name, actions[0] if actions else default, redact_changes(cls, changes), cls)
116
117
  ctx.row_actions = actions or [default]
117
118
  return ctx
118
119
 
@@ -19,7 +19,7 @@ import asyncio
19
19
  import contextlib
20
20
  from collections.abc import AsyncGenerator
21
21
  from datetime import UTC, datetime, timedelta
22
- from typing import Any, Final
22
+ from typing import Any, ClassVar, Final
23
23
 
24
24
  from sqlalchemy import and_, func, select, text, update
25
25
  from sqlalchemy.dialects import postgresql, sqlite
@@ -48,6 +48,8 @@ Base = create_module_base(LEASE_METADATA_NAME)
48
48
  class LeaseRow(Base, table=True): # ty: ignore[unsupported-base]
49
49
  """One lease slot. ``holder`` is the owner's token, ``""`` when never held."""
50
50
 
51
+ __audit_redact_fields__: ClassVar[set[str]] = {"holder"}
52
+
51
53
  __tablename__ = TABLE_LEASE
52
54
 
53
55
  name: str = Field(primary_key=True, max_length=NAME_MAX_LENGTH)
@@ -13,6 +13,7 @@ from sqlalchemy import inspect as sa_inspect
13
13
  from sqlalchemy.orm import Session
14
14
 
15
15
  from simple_module_db._persisted_owner import mark_unverified, owner_mark, restore_owner_mark
16
+ from simple_module_db.audit_redaction import AUDIT_REDACTED, pk_is_redacted
16
17
  from simple_module_db.bulk_audit import audit_statement
17
18
  from simple_module_db.bulk_guard import install_bulk_guard
18
19
  from simple_module_db.flush_guard import guard_flush
@@ -76,8 +77,14 @@ def _entity_label(obj: object) -> str:
76
77
 
77
78
 
78
79
  def _entity_pk(obj: object) -> object:
79
- """Return the primary key value(s) if available, else None."""
80
+ """Return the primary key value(s) if available, else None.
81
+
82
+ A primary key that is itself a credential (a session or refresh token) is
83
+ masked: this value goes to the application log.
84
+ """
80
85
  try:
86
+ if pk_is_redacted(type(obj)):
87
+ return AUDIT_REDACTED
81
88
  inspector = sa_inspect(obj)
82
89
  if inspector is None:
83
90
  return None
@@ -46,7 +46,7 @@ from simple_module_db.tenancy import (
46
46
  )
47
47
 
48
48
  # ``_engine_policy`` (imported above) is re-exported: the per-engine policy map lives in
49
- # ``_engine_policies``; modules/background_tasks/tests/test_worker_tenancy.py reads it here.
49
+ # ``_engine_policies``; the background_tasks worker tenancy test reads it here.
50
50
 
51
51
 
52
52
  class EngineTenancy:
@@ -0,0 +1,85 @@
1
+ """Per-request SQL statement counting.
2
+
3
+ Development hosts install this on their engine and expose the totals in a
4
+ ``Server-Timing`` header (see ``simple_module_hosting._server_timing``), so a
5
+ page that issues one query per row shows up in the browser's network panel and
6
+ in the page-perf audit instead of only under load.
7
+
8
+ Counting is opt-in twice over: :func:`install_query_stats` adds the engine
9
+ listeners, and only code inside :func:`track_queries` is counted. Statements
10
+ run outside a tracked block (startup, background work) cost one ContextVar
11
+ read each.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import time
17
+ from collections.abc import Generator
18
+ from contextlib import contextmanager
19
+ from contextvars import ContextVar
20
+ from dataclasses import dataclass
21
+
22
+ from sqlalchemy import event
23
+ from sqlalchemy.ext.asyncio import AsyncEngine
24
+
25
+ __all__ = ["QueryStats", "install_query_stats", "track_queries"]
26
+
27
+ _START_KEY = "_sm_query_started"
28
+ _INSTALLED_FLAG = "_sm_query_stats_installed"
29
+
30
+
31
+ @dataclass(slots=True)
32
+ class QueryStats:
33
+ """Statements executed inside one :func:`track_queries` block."""
34
+
35
+ count: int = 0
36
+ seconds: float = 0.0
37
+ active: bool = True
38
+
39
+
40
+ _current: ContextVar[QueryStats | None] = ContextVar("sm_query_stats", default=None)
41
+
42
+
43
+ def _before(conn, cursor, statement, parameters, context, executemany) -> None:
44
+ stats = _current.get()
45
+ if stats is not None and stats.active and context is not None:
46
+ setattr(context, _START_KEY, time.perf_counter())
47
+
48
+
49
+ def _after(conn, cursor, statement, parameters, context, executemany) -> None:
50
+ stats = _current.get()
51
+ if stats is None or not stats.active:
52
+ return
53
+ stats.count += 1
54
+ started = getattr(context, _START_KEY, None) if context is not None else None
55
+ if started is not None:
56
+ stats.seconds += time.perf_counter() - started
57
+
58
+
59
+ def install_query_stats(engine: AsyncEngine) -> None:
60
+ """Count statements on *engine* for any :func:`track_queries` block.
61
+
62
+ Idempotent per engine.
63
+ """
64
+ sync_engine = engine.sync_engine
65
+ if getattr(sync_engine, _INSTALLED_FLAG, False):
66
+ return
67
+ event.listen(sync_engine, "before_cursor_execute", _before)
68
+ event.listen(sync_engine, "after_cursor_execute", _after)
69
+ setattr(sync_engine, _INSTALLED_FLAG, True)
70
+
71
+
72
+ @contextmanager
73
+ def track_queries() -> Generator[QueryStats]:
74
+ """Count the statements run by this task (and tasks it spawns) until exit.
75
+
76
+ The stats object is shared by reference, so work SQLAlchemy runs in a
77
+ greenlet or a child task still lands in the same totals.
78
+ """
79
+ stats = QueryStats()
80
+ token = _current.set(stats)
81
+ try:
82
+ yield stats
83
+ finally:
84
+ stats.active = False
85
+ _current.reset(token)
@@ -16,6 +16,7 @@ from collections.abc import Iterable
16
16
  from typing import Final
17
17
 
18
18
  from pydantic_settings import BaseSettings
19
+ from simple_module_core.secret_fields import conceals_secret
19
20
  from simple_module_core.settings_hydrate import build_settings
20
21
  from sqlalchemy import Select, UniqueConstraint, inspect, select
21
22
  from sqlalchemy.ext.asyncio import AsyncConnection, AsyncSession
@@ -84,6 +85,17 @@ class Setting(Base, AuditMixin, table=True): # ty: ignore[unsupported-base]
84
85
  inputs that don't parse.
85
86
  """
86
87
 
88
+ @staticmethod
89
+ def __audit_redact_row__(row: dict | None) -> set[str]:
90
+ # Fail closed: no row (bulk/manual capture) or a partly loaded one hides the value.
91
+ if (
92
+ row is None
93
+ or any(row.get(k) is None for k in (COL_KEY, COL_VALUE, COL_VALUE_TYPE))
94
+ or conceals_secret(row[COL_KEY], row[COL_VALUE], row[COL_VALUE_TYPE])
95
+ ):
96
+ return {COL_VALUE}
97
+ return set()
98
+
87
99
  __tablename__ = TABLE_SETTING
88
100
  __table_args__ = (UniqueConstraint(COL_SCOPE, COL_SCOPE_ID, COL_KEY, name=UQ_SCOPE_KEY),)
89
101
 
@@ -0,0 +1,168 @@
1
+ """Credential changes remain visible without recording their values."""
2
+
3
+ from datetime import UTC, datetime
4
+
5
+ import pytest
6
+ from simple_module_db.audit import collect_audit_records
7
+ from simple_module_db.leases import LeaseRow
8
+ from simple_module_db.stored_settings import Setting
9
+ from sqlalchemy.orm import Session
10
+
11
+
12
+ @pytest.mark.parametrize(
13
+ "key,value,value_type,expected",
14
+ [
15
+ ("mail.smtp_password", "private", "string", "[redacted]"),
16
+ ("host.secret_key", "private", "int", "[redacted]"),
17
+ ("mail.url", "smtp://user:private@localhost", "string", "[redacted]"),
18
+ ("mail.port", "587", "int", "587"),
19
+ ("users.reset_password_token_lifetime_seconds", "3600", "int", "3600"),
20
+ ],
21
+ )
22
+ def test_setting_create_redaction(key, value, value_type, expected):
23
+ with Session() as session:
24
+ session.add(Setting(key=key, value=value, value_type=value_type))
25
+ record = collect_audit_records(session)[0]
26
+ assert next(c["new"] for c in record.changes if c["field"] == "value") == expected
27
+
28
+
29
+ @pytest.fixture
30
+ def credential_session():
31
+ from simple_module_db.listeners import attach_session_listeners
32
+ from simple_module_db.query_filter import EngineTenancy, bind_engine_policy
33
+ from sqlalchemy import create_engine
34
+
35
+ engine = create_engine("sqlite://")
36
+ records = []
37
+ policy = EngineTenancy(
38
+ tenant_strict=False, audit_callback=lambda session, batch: records.extend(batch)
39
+ )
40
+ bind_engine_policy(engine, policy)
41
+
42
+ class AuditSession(Session):
43
+ pass
44
+
45
+ attach_session_listeners(AuditSession)
46
+ try:
47
+ Setting.metadata.create_all(engine)
48
+ with AuditSession(engine) as session:
49
+ yield session, records
50
+ finally:
51
+ engine.dispose()
52
+
53
+
54
+ @pytest.mark.parametrize("kind", ["setting", "renamed", "url"])
55
+ def test_credential_update_redacts_both_sides(credential_session, kind):
56
+ session, records = credential_session
57
+ entity = Setting(
58
+ key="mail.url" if kind == "url" else "mail.smtp_password",
59
+ value="smtp://u:private@localhost" if kind == "url" else "old-private",
60
+ )
61
+ field = "value"
62
+ session.add(entity)
63
+ session.flush()
64
+ records.clear()
65
+ setattr(entity, field, "public" if kind == "url" else "new-private")
66
+ if kind == "renamed":
67
+ entity.key = "mail.label"
68
+ session.flush()
69
+ assert next(c for c in records[0].changes if c["field"] == field) == {
70
+ "field": field,
71
+ "old": "[redacted]",
72
+ "new": "[redacted]",
73
+ }
74
+
75
+
76
+ @pytest.mark.parametrize("core", [False, True])
77
+ def test_bulk_credentials_redacted(credential_session, core):
78
+ from sqlalchemy import update
79
+
80
+ session, records = credential_session
81
+ session.add(Setting(key="mail.smtp_password", value="old-private"))
82
+ session.flush()
83
+ records.clear()
84
+ session.execute(update(Setting.__table__ if core else Setting).values(value="new-private"))
85
+ assert records[0].changes == [{"field": "value", "new": "[redacted]"}]
86
+
87
+
88
+ @pytest.mark.parametrize("by_name", [False, True])
89
+ def test_manual_bulk_redaction(credential_session, by_name):
90
+ from simple_module_db import record_bulk_audit
91
+
92
+ session, records = credential_session
93
+ record_bulk_audit(
94
+ session, "Setting" if by_name else Setting, "bulk_updated", ["1"], {"value": "private"}
95
+ )
96
+ assert records[0].changes == [{"field": "value", "new": "[redacted]"}]
97
+
98
+
99
+ def test_nonsecret_setting_update_retains_values(credential_session):
100
+ session, records = credential_session
101
+ setting = Setting(key="mail.port", value="587", value_type="int")
102
+ session.add(setting)
103
+ session.flush()
104
+ records.clear()
105
+ setting.value = "465"
106
+ session.flush()
107
+ assert records[0].changes == [{"field": "value", "old": "587", "new": "465"}]
108
+
109
+
110
+ @pytest.mark.parametrize("core", [False, True])
111
+ def test_bulk_insert_and_summary_redaction(credential_session, monkeypatch, core):
112
+ import simple_module_db.bulk_audit as bulk
113
+ from sqlalchemy import insert, update
114
+
115
+ session, records = credential_session
116
+ target = Setting.__table__ if core else Setting
117
+ session.execute(
118
+ insert(target).values(
119
+ key="mail.smtp_password",
120
+ value="private",
121
+ value_type="string",
122
+ scope="system",
123
+ scope_id="",
124
+ )
125
+ )
126
+ assert next(c["new"] for c in records[0].changes if c["field"] == "value") == "[redacted]"
127
+ records.clear()
128
+ monkeypatch.setattr(bulk, "BULK_AUDIT_ID_CAP", 0)
129
+ session.execute(update(target).values(value="new-private"))
130
+ assert records[0].entity_id == "*"
131
+ assert records[0].changes[0] == {"field": "value", "new": "[redacted]"}
132
+
133
+
134
+ def test_typed_setting_redaction():
135
+ from pydantic import SecretStr
136
+ from simple_module_core.secret_fields import register_typed_secrets
137
+ from sqlmodel import SQLModel
138
+
139
+ class CredentialSettings(SQLModel):
140
+ credential: SecretStr
141
+
142
+ register_typed_secrets("audit_test", CredentialSettings)
143
+ with Session() as session:
144
+ session.add(Setting(key="audit_test.credential", value="private"))
145
+ changes = collect_audit_records(session)[0].changes
146
+ assert next(c["new"] for c in changes if c["field"] == "value") == "[redacted]"
147
+
148
+
149
+ def test_manual_bulk_honors_field_exclusions(credential_session):
150
+ from _audit_models import PartialExcludeModel
151
+ from simple_module_db import record_bulk_audit
152
+
153
+ session, records = credential_session
154
+ record_bulk_audit(
155
+ session,
156
+ PartialExcludeModel,
157
+ "bulk_updated",
158
+ ["1"],
159
+ {"password_hash": "private", "username": "visible"},
160
+ )
161
+ assert records[0].changes == [{"field": "username", "new": "visible"}]
162
+
163
+
164
+ def test_lease_ownership_value_is_redacted():
165
+ with Session() as session:
166
+ session.add(LeaseRow(name="audit", slot=0, holder="private", expires_at=datetime.now(UTC)))
167
+ changes = collect_audit_records(session)[0].changes
168
+ assert next(c["new"] for c in changes if c["field"] == "holder") == "[redacted]"
@@ -0,0 +1,16 @@
1
+ """A credential used as a primary key never reaches the entity-change log."""
2
+
3
+ import uuid
4
+
5
+ from simple_module_db.listeners import _entity_pk
6
+ from users.models import RefreshToken, User
7
+
8
+
9
+ def test_token_primary_key_is_masked_in_log_identity():
10
+ token = RefreshToken(token="private", user_id=uuid.uuid4())
11
+ assert _entity_pk(token) == "[redacted]"
12
+
13
+
14
+ def test_ordinary_primary_key_is_kept():
15
+ user = User(email="log@test")
16
+ assert _entity_pk(user) != "[redacted]"
@@ -0,0 +1,95 @@
1
+ """Per-request SQL statement counting (feeds the dev Server-Timing header)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ from types import SimpleNamespace
7
+
8
+ import simple_module_db.query_stats as query_stats
9
+ from simple_module_db.query_stats import install_query_stats, track_queries
10
+ from sqlalchemy import text
11
+ from sqlalchemy.ext.asyncio import create_async_engine
12
+
13
+
14
+ async def test_counts_only_statements_inside_the_tracked_block() -> None:
15
+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")
16
+ install_query_stats(engine)
17
+ try:
18
+ async with engine.connect() as conn:
19
+ await conn.execute(text("select 1")) # untracked
20
+ with track_queries() as stats:
21
+ await conn.execute(text("select 1"))
22
+ await conn.execute(text("select 2"))
23
+ await conn.execute(text("select 3")) # after the block
24
+ assert stats.count == 2
25
+ assert stats.seconds > 0
26
+ finally:
27
+ await engine.dispose()
28
+
29
+
30
+ async def test_install_is_idempotent() -> None:
31
+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")
32
+ install_query_stats(engine)
33
+ install_query_stats(engine)
34
+ try:
35
+ with track_queries() as stats:
36
+ async with engine.connect() as conn:
37
+ await conn.execute(text("select 1"))
38
+ # A second install must not register the listeners twice.
39
+ assert stats.count == 1
40
+ finally:
41
+ await engine.dispose()
42
+
43
+
44
+ async def test_child_tasks_share_the_request_totals() -> None:
45
+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")
46
+ install_query_stats(engine)
47
+
48
+ async def one_query() -> None:
49
+ async with engine.connect() as conn:
50
+ await conn.execute(text("select 1"))
51
+
52
+ try:
53
+ with track_queries() as stats:
54
+ await asyncio.gather(one_query(), one_query())
55
+ assert stats.count == 2
56
+ finally:
57
+ await engine.dispose()
58
+
59
+
60
+ async def test_engine_without_install_counts_nothing() -> None:
61
+ engine = create_async_engine("sqlite+aiosqlite:///:memory:")
62
+ try:
63
+ with track_queries() as stats:
64
+ async with engine.connect() as conn:
65
+ await conn.execute(text("select 1"))
66
+ assert stats.count == 0
67
+ finally:
68
+ await engine.dispose()
69
+
70
+
71
+ async def test_child_task_stops_counting_after_block_exits() -> None:
72
+ resume = asyncio.Event()
73
+ counted = asyncio.Event()
74
+
75
+ async def child() -> None:
76
+ context = SimpleNamespace()
77
+ query_stats._before(None, None, None, None, context, False)
78
+ query_stats._after(None, None, None, None, context, False)
79
+ counted.set()
80
+ await resume.wait()
81
+ context = SimpleNamespace()
82
+ query_stats._before(None, None, None, None, context, False)
83
+ query_stats._after(None, None, None, None, context, False)
84
+ assert not vars(context)
85
+
86
+ with track_queries() as stats:
87
+ task = asyncio.create_task(child())
88
+ await counted.wait()
89
+ assert stats.count == 1
90
+ seconds = stats.seconds
91
+ assert seconds > 0
92
+ resume.set()
93
+ await task
94
+ assert stats.count == 1
95
+ assert stats.seconds == seconds