resource-engine 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.
Files changed (128) hide show
  1. resource_engine/__init__.py +96 -0
  2. resource_engine/application/__init__.py +1 -0
  3. resource_engine/application/actions.py +48 -0
  4. resource_engine/application/context.py +111 -0
  5. resource_engine/application/events.py +54 -0
  6. resource_engine/application/hooks.py +272 -0
  7. resource_engine/application/idempotency.py +277 -0
  8. resource_engine/application/manager.py +1987 -0
  9. resource_engine/application/query.py +47 -0
  10. resource_engine/application/registry.py +137 -0
  11. resource_engine/application/relations.py +470 -0
  12. resource_engine/application/resource.py +984 -0
  13. resource_engine/application/searching.py +162 -0
  14. resource_engine/application/settings.py +169 -0
  15. resource_engine/application/slots.py +67 -0
  16. resource_engine/application/state_machines.py +177 -0
  17. resource_engine/application/timers.py +347 -0
  18. resource_engine/application/transaction.py +100 -0
  19. resource_engine/application/views.py +239 -0
  20. resource_engine/audit/__init__.py +40 -0
  21. resource_engine/audit/export.py +280 -0
  22. resource_engine/audit/history.py +165 -0
  23. resource_engine/audit/janitor.py +257 -0
  24. resource_engine/audit/model.py +98 -0
  25. resource_engine/audit/recorder.py +145 -0
  26. resource_engine/audit/resource.py +68 -0
  27. resource_engine/audit/seal.py +327 -0
  28. resource_engine/audit/sink.py +69 -0
  29. resource_engine/authz/__init__.py +72 -0
  30. resource_engine/authz/apikeys.py +300 -0
  31. resource_engine/authz/base.py +143 -0
  32. resource_engine/authz/catalog.py +291 -0
  33. resource_engine/authz/conditions.py +416 -0
  34. resource_engine/authz/config.py +77 -0
  35. resource_engine/authz/evaluator.py +382 -0
  36. resource_engine/authz/external.py +249 -0
  37. resource_engine/authz/fields.py +44 -0
  38. resource_engine/authz/model.py +145 -0
  39. resource_engine/authz/resources.py +289 -0
  40. resource_engine/authz/roles.py +101 -0
  41. resource_engine/cache.py +144 -0
  42. resource_engine/calls.py +100 -0
  43. resource_engine/capabilities.py +145 -0
  44. resource_engine/composite.py +295 -0
  45. resource_engine/documents/__init__.py +69 -0
  46. resource_engine/documents/content.py +57 -0
  47. resource_engine/documents/events.py +49 -0
  48. resource_engine/documents/janitor.py +93 -0
  49. resource_engine/documents/machine.py +38 -0
  50. resource_engine/documents/manager.py +704 -0
  51. resource_engine/documents/model.py +91 -0
  52. resource_engine/documents/pipeline.py +98 -0
  53. resource_engine/documents/processors.py +320 -0
  54. resource_engine/documents/resource.py +39 -0
  55. resource_engine/domain/__init__.py +10 -0
  56. resource_engine/domain/events.py +50 -0
  57. resource_engine/domain/exceptions.py +23 -0
  58. resource_engine/email.py +417 -0
  59. resource_engine/errors.py +562 -0
  60. resource_engine/explorer.py +133 -0
  61. resource_engine/exports.py +687 -0
  62. resource_engine/generation.py +233 -0
  63. resource_engine/i18n.py +251 -0
  64. resource_engine/identity.py +46 -0
  65. resource_engine/integration.py +80 -0
  66. resource_engine/jobs.py +390 -0
  67. resource_engine/locale/ca/LC_MESSAGES/resource_engine.mo +0 -0
  68. resource_engine/locale/ca/LC_MESSAGES/resource_engine.po +206 -0
  69. resource_engine/locale/es/LC_MESSAGES/resource_engine.mo +0 -0
  70. resource_engine/locale/es/LC_MESSAGES/resource_engine.po +206 -0
  71. resource_engine/logs.py +201 -0
  72. resource_engine/messaging/__init__.py +73 -0
  73. resource_engine/messaging/asyncapi.py +529 -0
  74. resource_engine/messaging/cloudevents.py +98 -0
  75. resource_engine/messaging/consumer.py +165 -0
  76. resource_engine/messaging/delivery.py +115 -0
  77. resource_engine/messaging/envelope.py +193 -0
  78. resource_engine/messaging/hub.py +148 -0
  79. resource_engine/messaging/inbound.py +76 -0
  80. resource_engine/messaging/inspection.py +113 -0
  81. resource_engine/messaging/janitor.py +136 -0
  82. resource_engine/messaging/live.py +179 -0
  83. resource_engine/messaging/processing.py +357 -0
  84. resource_engine/messaging/publishing.py +318 -0
  85. resource_engine/messaging/relay.py +84 -0
  86. resource_engine/messaging/worker.py +166 -0
  87. resource_engine/nosql.py +394 -0
  88. resource_engine/ports/__init__.py +13 -0
  89. resource_engine/ports/activity.py +171 -0
  90. resource_engine/ports/audit.py +42 -0
  91. resource_engine/ports/authz.py +132 -0
  92. resource_engine/ports/cache.py +41 -0
  93. resource_engine/ports/email.py +118 -0
  94. resource_engine/ports/event_publisher.py +34 -0
  95. resource_engine/ports/idempotency.py +69 -0
  96. resource_engine/ports/identity.py +112 -0
  97. resource_engine/ports/locks.py +28 -0
  98. resource_engine/ports/messaging.py +197 -0
  99. resource_engine/ports/observability.py +60 -0
  100. resource_engine/ports/ratelimit.py +59 -0
  101. resource_engine/ports/repository.py +56 -0
  102. resource_engine/ports/storage.py +93 -0
  103. resource_engine/ports/templates.py +54 -0
  104. resource_engine/ports/tracing.py +61 -0
  105. resource_engine/ports/unit_of_work.py +46 -0
  106. resource_engine/processes.py +408 -0
  107. resource_engine/py.typed +0 -0
  108. resource_engine/querying.py +319 -0
  109. resource_engine/ratelimit.py +217 -0
  110. resource_engine/reporting.py +230 -0
  111. resource_engine/schema_examples.py +51 -0
  112. resource_engine/templates.py +143 -0
  113. resource_engine/tenancy.py +68 -0
  114. resource_engine/testing/__init__.py +34 -0
  115. resource_engine/testing/activity.py +123 -0
  116. resource_engine/testing/contracts.py +1416 -0
  117. resource_engine/testing/email.py +36 -0
  118. resource_engine/testing/engine.py +40 -0
  119. resource_engine/testing/memory.py +603 -0
  120. resource_engine/testing/storage.py +110 -0
  121. resource_engine/testing/tracing.py +100 -0
  122. resource_engine/tracing.py +156 -0
  123. resource_engine/translatable.py +80 -0
  124. resource_engine/versions.py +189 -0
  125. resource_engine-0.1.0.dist-info/METADATA +36 -0
  126. resource_engine-0.1.0.dist-info/RECORD +128 -0
  127. resource_engine-0.1.0.dist-info/WHEEL +4 -0
  128. resource_engine-0.1.0.dist-info/licenses/LICENSE +202 -0
@@ -0,0 +1,257 @@
1
+ """Retention for the audit trail. Run ``AuditJanitor.run_once()`` periodically."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import asyncio
6
+ import contextlib
7
+ import logging
8
+ from collections.abc import Callable, Sequence
9
+ from dataclasses import dataclass
10
+ from datetime import UTC, datetime, timedelta
11
+ from typing import Any
12
+
13
+ from resource_engine.application.query import ListQuery
14
+ from resource_engine.audit.seal import AuditSealer, _before
15
+ from resource_engine.errors import ConfigurationError
16
+
17
+ logger = logging.getLogger("resource_engine.audit.janitor")
18
+
19
+
20
+ @dataclass(frozen=True)
21
+ class Retention:
22
+ """How long to keep the entries that match: a resource (or several), an
23
+ outcome (``ok``, ``denied``, ``failed``), or both. ``keep=None`` keeps them
24
+ forever. The first rule that matches an entry decides."""
25
+
26
+ keep: timedelta | None
27
+ resource: str | Sequence[str] | None = None
28
+ outcome: str | Sequence[str] | None = None
29
+
30
+ def __post_init__(self) -> None:
31
+ if self.keep is not None and self.keep <= timedelta(0):
32
+ raise ConfigurationError("Retention.keep must be positive or None")
33
+ if self.resource is None and self.outcome is None:
34
+ raise ConfigurationError(
35
+ "A retention rule needs a resource or an outcome",
36
+ hint="For everything else, use AuditJanitor(retention=...).",
37
+ )
38
+
39
+ @staticmethod
40
+ def _values(value: str | Sequence[str] | None) -> list[str] | None:
41
+ if value is None:
42
+ return None
43
+ return [value] if isinstance(value, str) else list(value)
44
+
45
+ def condition(self) -> dict[str, Any]:
46
+ """The rule's resource and outcome filter, as a list condition."""
47
+ parts = []
48
+ for field, value in (("resource", self.resource), ("outcome", self.outcome)):
49
+ values = self._values(value)
50
+ if values is not None:
51
+ parts.append({"in": [{"attr": f"resource.{field}"}, values]})
52
+ return parts[0] if len(parts) == 1 else {"and": parts}
53
+
54
+ def matches(self, entry: Any) -> bool:
55
+ """Whether ``entry`` falls under this rule."""
56
+ resources, outcomes = self._values(self.resource), self._values(self.outcome)
57
+ return (resources is None or entry.resource in resources) and (
58
+ outcomes is None or entry.outcome in outcomes
59
+ )
60
+
61
+
62
+ @dataclass
63
+ class AuditJanitorStats:
64
+ """What one run of the audit janitor did."""
65
+
66
+ sealed: int = 0 # entries sealed in this run
67
+ seals: int = 0 # seals created
68
+ purged: int = 0 # entries deleted
69
+ purged_seals: int = 0 # seals whose entries were deleted
70
+
71
+
72
+ class AuditJanitor:
73
+ """Seals pending entries (with a ``sealer``) and deletes old ones.
74
+
75
+ Args:
76
+ uow_factory: Units of work with the ``audit_log`` repository.
77
+ retention: Age after which entries are deleted. ``None`` (the default)
78
+ deletes nothing.
79
+ rules: ``Retention`` rules per resource or outcome, before the
80
+ default: ``Retention(timedelta(days=30), outcome="denied")``,
81
+ ``Retention(None, resource="invoices")`` (kept forever). The first
82
+ that matches an entry decides; entries no rule matches follow
83
+ ``retention``.
84
+ sealer: With a sealer, each run seals first, and retention deletes
85
+ whole sealed batches once every entry in them is past its own
86
+ retention. The seal stays, marked ``purged_at``, so the chain still
87
+ verifies. Unsealed entries are never deleted. Without one, entries older than
88
+ ``retention`` are deleted directly.
89
+ batch_size: Entries deleted per transaction.
90
+ """
91
+
92
+ def __init__(
93
+ self,
94
+ uow_factory: Callable[[], Any],
95
+ *,
96
+ retention: timedelta | None = None,
97
+ rules: Sequence[Retention] = (),
98
+ sealer: AuditSealer | None = None,
99
+ batch_size: int = 1000,
100
+ entries: str = "audit_log",
101
+ ) -> None:
102
+ if retention is not None and retention <= timedelta(0):
103
+ raise ConfigurationError("retention must be positive or None")
104
+ if batch_size < 1:
105
+ raise ConfigurationError("batch_size must be at least 1")
106
+ if retention is None and sealer is None and not any(r.keep for r in rules):
107
+ raise ConfigurationError(
108
+ "AuditJanitor has nothing to do",
109
+ hint="Pass retention=timedelta(days=...), a sealer, or both.",
110
+ doc="docs/audit.md#retention",
111
+ )
112
+ self.uow_factory = uow_factory
113
+ self.retention = retention
114
+ self.rules = list(rules)
115
+ self.sealer = sealer
116
+ self.batch_size = batch_size
117
+ self.entries_resource = entries
118
+
119
+ async def run_once(self, now: datetime | None = None) -> AuditJanitorStats:
120
+ """Seal pending entries, then delete those past their retention."""
121
+ now = now or datetime.now(UTC)
122
+ stats = AuditJanitorStats()
123
+ if self.sealer is not None:
124
+ seals = await self.sealer.seal_pending(now)
125
+ stats.seals = len(seals)
126
+ stats.sealed = sum(s.entries for s in seals)
127
+ keeps = [r.keep for r in self.rules if r.keep] + (
128
+ [self.retention] if self.retention else []
129
+ )
130
+ if keeps:
131
+ if self.sealer is not None:
132
+ await self._purge_sealed(now, min(keeps), stats)
133
+ else:
134
+ for condition in self._conditions(now):
135
+ stats.purged += await self._purge(condition)
136
+ if stats.seals or stats.purged:
137
+ logger.info(
138
+ "Audit: sealed %d entries in %d seals, purged %d entries",
139
+ stats.sealed,
140
+ stats.seals,
141
+ stats.purged,
142
+ )
143
+ return stats
144
+
145
+ def _conditions(self, now: datetime) -> list[dict[str, Any]]:
146
+ """One delete condition per rule (and the default): its entries, past its
147
+ retention, and not taken by an earlier rule."""
148
+ out: list[dict[str, Any]] = []
149
+ earlier: list[dict[str, Any]] = []
150
+ for rule in self.rules:
151
+ if rule.keep is not None:
152
+ parts = [rule.condition(), _before(now - rule.keep)]
153
+ if earlier:
154
+ parts.append({"not": {"or": list(earlier)}})
155
+ out.append({"and": parts})
156
+ earlier.append(rule.condition())
157
+ if self.retention is not None:
158
+ parts = [_before(now - self.retention)]
159
+ if earlier:
160
+ parts.append({"not": {"or": list(earlier)}})
161
+ out.append(parts[0] if len(parts) == 1 else {"and": parts})
162
+ return out
163
+
164
+ def keep_for(self, entry: Any) -> timedelta | None:
165
+ """How long ``entry`` is kept (``None``: forever)."""
166
+ for rule in self.rules:
167
+ if rule.matches(entry):
168
+ return rule.keep
169
+ return self.retention
170
+
171
+ async def _purge(self, condition: Any) -> int:
172
+ total = 0
173
+ while True:
174
+ async with self.uow_factory() as uow:
175
+ repo = uow.repository(self.entries_resource)
176
+ page = await repo.list(ListQuery(limit=self.batch_size, condition=condition))
177
+ for entry in page.items:
178
+ await repo.delete(entry)
179
+ await uow.commit()
180
+ total += len(page.items)
181
+ if len(page.items) < self.batch_size:
182
+ return total
183
+
184
+ async def _purge_sealed(
185
+ self, now: datetime, shortest: timedelta, stats: AuditJanitorStats
186
+ ) -> None:
187
+ """Delete sealed batches once every entry is past its own retention."""
188
+ assert self.sealer is not None
189
+ seals_resource = self.sealer.seals_resource
190
+ after = 0
191
+ while True:
192
+ async with self.uow_factory() as uow:
193
+ page = await uow.repository(seals_resource).list(
194
+ ListQuery(
195
+ limit=100,
196
+ condition={
197
+ "and": [
198
+ {"eq": [{"attr": "resource.purged_at"}, None]},
199
+ {"lt": [{"attr": "resource.last_at"}, now - shortest]},
200
+ {"gt": [{"attr": "resource.sequence"}, after]},
201
+ ]
202
+ },
203
+ order_by=["sequence"],
204
+ )
205
+ )
206
+ sequences = [seal.sequence for seal in page.items]
207
+ if not sequences:
208
+ return
209
+ for sequence in sequences:
210
+ after = sequence
211
+ if not await self._expired(sequence, now):
212
+ continue
213
+ stats.purged += await self._purge({"eq": [{"attr": "resource.seal"}, sequence]})
214
+ async with self.uow_factory() as uow:
215
+ repo = uow.repository(seals_resource)
216
+ stored = await repo.get(sequence)
217
+ stored.purged_at = datetime.now(UTC)
218
+ await repo.update(stored)
219
+ await uow.commit()
220
+ stats.purged_seals += 1
221
+
222
+ async def _expired(self, sequence: int, now: datetime) -> bool:
223
+ """Whether every entry of a sealed batch is past its retention."""
224
+ offset = 0
225
+ while True:
226
+ async with self.uow_factory() as uow: # read inside: SQL entries detach after
227
+ page = await uow.repository(self.entries_resource).list(
228
+ ListQuery(
229
+ limit=self.batch_size,
230
+ offset=offset,
231
+ condition={"eq": [{"attr": "resource.seal"}, sequence]},
232
+ )
233
+ )
234
+ for entry in page.items:
235
+ keep = self.keep_for(entry)
236
+ at = entry.at if entry.at.tzinfo else entry.at.replace(tzinfo=UTC)
237
+ if keep is None or at > now - keep:
238
+ return False
239
+ if len(page.items) < self.batch_size:
240
+ return True
241
+ offset += self.batch_size
242
+
243
+ async def run_forever(
244
+ self, *, interval: float = 3600.0, stop: asyncio.Event | None = None
245
+ ) -> None:
246
+ """Run every ``interval`` seconds until ``stop`` is set; failures are logged."""
247
+ stop = stop or asyncio.Event()
248
+ while not stop.is_set():
249
+ try:
250
+ await self.run_once()
251
+ except Exception:
252
+ logger.exception("Audit janitor run failed")
253
+ with contextlib.suppress(TimeoutError):
254
+ await asyncio.wait_for(stop.wait(), timeout=interval)
255
+
256
+
257
+ __all__ = ["AuditJanitor", "AuditJanitorStats", "Retention"]
@@ -0,0 +1,98 @@
1
+ """Audit entries and their read schema."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import uuid
6
+ from dataclasses import dataclass, field
7
+ from datetime import UTC, datetime
8
+ from typing import Any
9
+
10
+ from pydantic import BaseModel, ConfigDict, Field
11
+
12
+
13
+ @dataclass
14
+ class AuditEntry:
15
+ """Who did what to which record, and whether it was allowed."""
16
+
17
+ resource: str
18
+ operation: str
19
+ action: str
20
+ outcome: str # ok | denied | failed
21
+ actor: str | None = None
22
+ actor_roles: list[str] = field(default_factory=list)
23
+ entity_id: str | None = None
24
+ tenant: str | None = None
25
+ changes: dict[str, Any] = field(default_factory=dict)
26
+ details: dict[str, Any] = field(default_factory=dict)
27
+ correlation_id: str | None = None
28
+ at: datetime = field(default_factory=lambda: datetime.now(UTC))
29
+ id: str = field(default_factory=lambda: uuid.uuid4().hex)
30
+ seal: int | None = None # sequence of the AuditSeal covering this entry
31
+
32
+
33
+ @dataclass
34
+ class AuditSeal:
35
+ """A sealed batch of audit entries (see ``AuditSealer``).
36
+
37
+ ``digest`` hashes the batch's entries; ``hash`` covers the digest, the
38
+ batch's metadata and the previous seal's hash, so seals form a chain.
39
+ ``mac`` is an HMAC of ``hash`` when the sealer has a key. ``purged_at`` is
40
+ set when retention deleted the batch's entries; the seal itself stays.
41
+ """
42
+
43
+ sequence: int
44
+ previous: str | None
45
+ entries: int
46
+ first_at: datetime
47
+ last_at: datetime
48
+ digest: str
49
+ hash: str
50
+ mac: str | None = None
51
+ key_id: str | None = None
52
+ sealed_at: datetime = field(default_factory=lambda: datetime.now(UTC))
53
+ purged_at: datetime | None = None
54
+
55
+
56
+ class AuditEntryRead(BaseModel):
57
+ """An audit entry."""
58
+
59
+ model_config = ConfigDict(from_attributes=True)
60
+
61
+ id: str = Field(description="Entry id")
62
+ at: datetime = Field(description="When it happened (UTC)")
63
+ actor: str | None = Field(
64
+ default=None, description="Principal id, system:<job> or null (anonymous)"
65
+ )
66
+ actor_roles: list[str] = Field(description="Application roles of the actor at the time")
67
+ resource: str = Field(description="Resource name")
68
+ entity_id: str | None = Field(default=None, description="Target record")
69
+ tenant: str | None = Field(default=None, description="Tenant of the record or operation")
70
+ operation: str = Field(description="create, update, delete, transition, action, attach...")
71
+ action: str = Field(description="Permission action, e.g. transition:approve")
72
+ outcome: str = Field(description="ok, denied or failed")
73
+ changes: dict[str, Any] = Field(
74
+ description="field → {from, to}; masked fields → {changed: true}"
75
+ )
76
+ details: dict[str, Any] = Field(description="Transition, input, documents, denial reason")
77
+ correlation_id: str | None = Field(default=None, description="Shared with logs and events")
78
+ seal: int | None = Field(default=None, description="Seal covering the entry; null until sealed")
79
+
80
+
81
+ class AuditSealRead(BaseModel):
82
+ """A sealed batch of audit entries."""
83
+
84
+ model_config = ConfigDict(from_attributes=True)
85
+
86
+ sequence: int = Field(description="Position in the seal chain, from 1")
87
+ previous: str | None = Field(default=None, description="Hash of the previous seal")
88
+ entries: int = Field(description="Number of entries in the batch")
89
+ first_at: datetime = Field(description="Time of the oldest entry")
90
+ last_at: datetime = Field(description="Time of the newest entry")
91
+ digest: str = Field(description="SHA-256 of the batch's entries")
92
+ hash: str = Field(description="SHA-256 of the seal, chained to the previous one")
93
+ mac: str | None = Field(default=None, description="HMAC-SHA-256 of the hash, when keyed")
94
+ key_id: str | None = Field(default=None, description="Key that produced the HMAC")
95
+ sealed_at: datetime = Field(description="When the batch was sealed")
96
+ purged_at: datetime | None = Field(
97
+ default=None, description="When retention deleted the entries"
98
+ )
@@ -0,0 +1,145 @@
1
+ """Builds audit entries from an operation context."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ from typing import TYPE_CHECKING, Any
7
+
8
+ from pydantic import BaseModel
9
+ from pydantic_core import to_jsonable_python
10
+
11
+ from resource_engine.application.events import ResourceEvent, ResourceUpdated
12
+ from resource_engine.audit.model import AuditEntry
13
+
14
+ if TYPE_CHECKING:
15
+ from resource_engine.application.context import OperationContext
16
+
17
+ MASKED = {"changed": True}
18
+
19
+
20
+ def jsonable(value: Any) -> Any:
21
+ """``value`` as JSON-ready data; what JSON can't hold becomes text."""
22
+ return to_jsonable_python(value, fallback=str)
23
+
24
+
25
+ def actor_id(actor: Any) -> str | None:
26
+ """The id audit entries record for an actor (``system:<name>`` for the engine's own
27
+ principals)."""
28
+ from resource_engine.authz.base import SystemPrincipal
29
+
30
+ if isinstance(actor, SystemPrincipal):
31
+ return f"system:{actor.subject}"
32
+ return getattr(actor, "id", None) if actor is not None else None
33
+
34
+
35
+ def action_of(ctx: OperationContext) -> str:
36
+ """The audited action of an operation: ``create``, ``transition:<event>``,
37
+ ``attach:<slot>``..."""
38
+ if ctx.operation == "transition":
39
+ return f"transition:{ctx.transition}"
40
+ if ctx.operation == "action":
41
+ return f"action:{ctx.action}"
42
+ if ctx.operation in ("attach", "detach") and ctx.slot:
43
+ return f"{ctx.operation}:{ctx.slot}"
44
+ return ctx.operation
45
+
46
+
47
+ def masked_fields(ctx: OperationContext) -> frozenset[str]:
48
+ """Fields recorded as changed without their values: restricted and excluded ones."""
49
+ return frozenset(ctx.resource.restricted_fields) | frozenset(ctx.resource.audit_exclude)
50
+
51
+
52
+ def _plain(data: Any) -> dict[str, Any]:
53
+ if isinstance(data, BaseModel):
54
+ return data.model_dump(exclude_unset=True)
55
+ return dict(data) if isinstance(data, dict) else {}
56
+
57
+
58
+ def _mask_values(values: dict[str, Any], masked: frozenset[str]) -> dict[str, Any]:
59
+ return {k: (MASKED if k in masked else jsonable(v)) for k, v in values.items()}
60
+
61
+
62
+ def changes_of(ctx: OperationContext, masked: frozenset[str]) -> dict[str, Any]:
63
+ """The changes an operation made, field by field, with masked fields' values left out."""
64
+
65
+ def entry(name: str, **values: Any) -> Any:
66
+ return MASKED if name in masked else {k: jsonable(v) for k, v in values.items()}
67
+
68
+ op = ctx.operation
69
+ if op == "create":
70
+ created = {k: entry(k, to=v) for k, v in _plain(ctx.data).items()}
71
+ for state_field in ctx.resource.state_fields:
72
+ if state_field not in created and ctx.entity is not None:
73
+ created[state_field] = entry(state_field, to=getattr(ctx.entity, state_field, None))
74
+ return created
75
+ if op == "update":
76
+ out: dict[str, Any] = {}
77
+ for event in ctx.events:
78
+ if isinstance(event, ResourceUpdated):
79
+ for k, (old, new) in event.changes.items():
80
+ out[k] = entry(k, **{"from": old, "to": new})
81
+ return out
82
+ if op == "delete" and ctx.entity is not None:
83
+ read = ctx.resource.schemas.get("read")
84
+ names = [n for n in (read.model_fields if read else {}) if n != ctx.resource.id_field]
85
+ return {n: entry(n, **{"from": getattr(ctx.entity, n, None)}) for n in names}
86
+ machine = ctx.resource.machine_for(ctx.transition) if ctx.transition else None
87
+ if op == "transition" and machine is not None:
88
+ return {
89
+ machine.state_field: {
90
+ "from": jsonable(ctx.previous_state),
91
+ "to": jsonable(ctx.new_state),
92
+ }
93
+ }
94
+ return {}
95
+
96
+
97
+ def details_of(ctx: OperationContext, masked: frozenset[str]) -> dict[str, Any]:
98
+ """Extra facts about an operation for its audit entry: a transition's or action's input,
99
+ documents."""
100
+ details: dict[str, Any] = {}
101
+ if ctx.operation in ("transition", "action") and ctx.data is not None:
102
+ details["input"] = _mask_values(_plain(ctx.data), masked)
103
+ documents = [
104
+ {
105
+ "event": type(e).__name__,
106
+ **{
107
+ k: jsonable(v)
108
+ for k, v in dataclasses.asdict(e).items()
109
+ if k not in ("resource", "entity_id", "occurred_at", "event_id")
110
+ },
111
+ }
112
+ for e in ctx.events
113
+ if isinstance(e, ResourceEvent) and hasattr(e, "document_id")
114
+ ]
115
+ if documents:
116
+ details["documents"] = documents
117
+ return details
118
+
119
+
120
+ def entry_for(
121
+ ctx: OperationContext,
122
+ *,
123
+ roles: list[str],
124
+ outcome: str = "ok",
125
+ action: str | None = None,
126
+ details: dict[str, Any] | None = None,
127
+ ) -> AuditEntry:
128
+ """The audit entry for an operation."""
129
+ masked = masked_fields(ctx)
130
+ ok = outcome == "ok"
131
+ tenant_field = ctx.resource.tenant_field
132
+ tenant = getattr(ctx.entity, tenant_field, None) if tenant_field and ctx.entity else None
133
+ return AuditEntry(
134
+ resource=ctx.resource.name,
135
+ operation=ctx.operation,
136
+ action=action or action_of(ctx),
137
+ outcome=outcome,
138
+ actor=actor_id(ctx.actor),
139
+ actor_roles=roles,
140
+ entity_id=None if ctx.entity_id is None else str(ctx.entity_id),
141
+ tenant=jsonable(tenant or ctx.tenant),
142
+ changes=changes_of(ctx, masked) if ok else {},
143
+ details={**(details_of(ctx, masked) if ok else {}), **(details or {})},
144
+ correlation_id=ctx.correlation_id,
145
+ )
@@ -0,0 +1,68 @@
1
+ """The built-in, read-only ``audit_log`` resource."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from resource_engine.application.resource import Resource
6
+ from resource_engine.application.settings import Access, Listing
7
+ from resource_engine.audit.model import AuditEntry, AuditEntryRead, AuditSeal, AuditSealRead
8
+
9
+
10
+ class AuditLogResource(Resource):
11
+ """Audit trail: committed changes and refused attempts.
12
+
13
+ Entries are written by the engine only (no create, update or delete). The
14
+ resource is sensitive: wildcard grants do not reach it.
15
+
16
+ Business area:
17
+ Audit
18
+ """
19
+
20
+ name = "audit_log"
21
+ model = AuditEntry
22
+ id_type = str
23
+ schemas = {"read": AuditEntryRead}
24
+ operations = ["list", "get"]
25
+ operation_docs = {
26
+ "list": "Lists audit entries; filter by resource and entity_id for a record's history.",
27
+ "get": "Returns an audit entry.",
28
+ }
29
+ listing = Listing(
30
+ filterable=[
31
+ "resource",
32
+ "entity_id",
33
+ "tenant",
34
+ "actor",
35
+ "outcome",
36
+ "operation",
37
+ "correlation_id",
38
+ "seal",
39
+ ],
40
+ sortable=["at"],
41
+ max_page_size=500,
42
+ )
43
+ access = Access(wildcards=False)
44
+ audit = False
45
+
46
+
47
+ class AuditSealResource(Resource):
48
+ """Seals of the audit trail: one per sealed batch of entries, chained.
49
+
50
+ Written by ``AuditSealer`` only. Sensitive like the audit log.
51
+
52
+ Business area:
53
+ Audit
54
+ """
55
+
56
+ name = "audit_seals"
57
+ model = AuditSeal
58
+ id_field = "sequence"
59
+ id_type = int
60
+ schemas = {"read": AuditSealRead}
61
+ operations = ["list", "get"]
62
+ operation_docs = {
63
+ "list": "Lists the seals of the audit trail, in chain order.",
64
+ "get": "Returns a seal.",
65
+ }
66
+ listing = Listing(sortable=["sequence"], max_page_size=500)
67
+ access = Access(wildcards=False)
68
+ audit = False