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.
- resource_engine/__init__.py +96 -0
- resource_engine/application/__init__.py +1 -0
- resource_engine/application/actions.py +48 -0
- resource_engine/application/context.py +111 -0
- resource_engine/application/events.py +54 -0
- resource_engine/application/hooks.py +272 -0
- resource_engine/application/idempotency.py +277 -0
- resource_engine/application/manager.py +1987 -0
- resource_engine/application/query.py +47 -0
- resource_engine/application/registry.py +137 -0
- resource_engine/application/relations.py +470 -0
- resource_engine/application/resource.py +984 -0
- resource_engine/application/searching.py +162 -0
- resource_engine/application/settings.py +169 -0
- resource_engine/application/slots.py +67 -0
- resource_engine/application/state_machines.py +177 -0
- resource_engine/application/timers.py +347 -0
- resource_engine/application/transaction.py +100 -0
- resource_engine/application/views.py +239 -0
- resource_engine/audit/__init__.py +40 -0
- resource_engine/audit/export.py +280 -0
- resource_engine/audit/history.py +165 -0
- resource_engine/audit/janitor.py +257 -0
- resource_engine/audit/model.py +98 -0
- resource_engine/audit/recorder.py +145 -0
- resource_engine/audit/resource.py +68 -0
- resource_engine/audit/seal.py +327 -0
- resource_engine/audit/sink.py +69 -0
- resource_engine/authz/__init__.py +72 -0
- resource_engine/authz/apikeys.py +300 -0
- resource_engine/authz/base.py +143 -0
- resource_engine/authz/catalog.py +291 -0
- resource_engine/authz/conditions.py +416 -0
- resource_engine/authz/config.py +77 -0
- resource_engine/authz/evaluator.py +382 -0
- resource_engine/authz/external.py +249 -0
- resource_engine/authz/fields.py +44 -0
- resource_engine/authz/model.py +145 -0
- resource_engine/authz/resources.py +289 -0
- resource_engine/authz/roles.py +101 -0
- resource_engine/cache.py +144 -0
- resource_engine/calls.py +100 -0
- resource_engine/capabilities.py +145 -0
- resource_engine/composite.py +295 -0
- resource_engine/documents/__init__.py +69 -0
- resource_engine/documents/content.py +57 -0
- resource_engine/documents/events.py +49 -0
- resource_engine/documents/janitor.py +93 -0
- resource_engine/documents/machine.py +38 -0
- resource_engine/documents/manager.py +704 -0
- resource_engine/documents/model.py +91 -0
- resource_engine/documents/pipeline.py +98 -0
- resource_engine/documents/processors.py +320 -0
- resource_engine/documents/resource.py +39 -0
- resource_engine/domain/__init__.py +10 -0
- resource_engine/domain/events.py +50 -0
- resource_engine/domain/exceptions.py +23 -0
- resource_engine/email.py +417 -0
- resource_engine/errors.py +562 -0
- resource_engine/explorer.py +133 -0
- resource_engine/exports.py +687 -0
- resource_engine/generation.py +233 -0
- resource_engine/i18n.py +251 -0
- resource_engine/identity.py +46 -0
- resource_engine/integration.py +80 -0
- resource_engine/jobs.py +390 -0
- resource_engine/locale/ca/LC_MESSAGES/resource_engine.mo +0 -0
- resource_engine/locale/ca/LC_MESSAGES/resource_engine.po +206 -0
- resource_engine/locale/es/LC_MESSAGES/resource_engine.mo +0 -0
- resource_engine/locale/es/LC_MESSAGES/resource_engine.po +206 -0
- resource_engine/logs.py +201 -0
- resource_engine/messaging/__init__.py +73 -0
- resource_engine/messaging/asyncapi.py +529 -0
- resource_engine/messaging/cloudevents.py +98 -0
- resource_engine/messaging/consumer.py +165 -0
- resource_engine/messaging/delivery.py +115 -0
- resource_engine/messaging/envelope.py +193 -0
- resource_engine/messaging/hub.py +148 -0
- resource_engine/messaging/inbound.py +76 -0
- resource_engine/messaging/inspection.py +113 -0
- resource_engine/messaging/janitor.py +136 -0
- resource_engine/messaging/live.py +179 -0
- resource_engine/messaging/processing.py +357 -0
- resource_engine/messaging/publishing.py +318 -0
- resource_engine/messaging/relay.py +84 -0
- resource_engine/messaging/worker.py +166 -0
- resource_engine/nosql.py +394 -0
- resource_engine/ports/__init__.py +13 -0
- resource_engine/ports/activity.py +171 -0
- resource_engine/ports/audit.py +42 -0
- resource_engine/ports/authz.py +132 -0
- resource_engine/ports/cache.py +41 -0
- resource_engine/ports/email.py +118 -0
- resource_engine/ports/event_publisher.py +34 -0
- resource_engine/ports/idempotency.py +69 -0
- resource_engine/ports/identity.py +112 -0
- resource_engine/ports/locks.py +28 -0
- resource_engine/ports/messaging.py +197 -0
- resource_engine/ports/observability.py +60 -0
- resource_engine/ports/ratelimit.py +59 -0
- resource_engine/ports/repository.py +56 -0
- resource_engine/ports/storage.py +93 -0
- resource_engine/ports/templates.py +54 -0
- resource_engine/ports/tracing.py +61 -0
- resource_engine/ports/unit_of_work.py +46 -0
- resource_engine/processes.py +408 -0
- resource_engine/py.typed +0 -0
- resource_engine/querying.py +319 -0
- resource_engine/ratelimit.py +217 -0
- resource_engine/reporting.py +230 -0
- resource_engine/schema_examples.py +51 -0
- resource_engine/templates.py +143 -0
- resource_engine/tenancy.py +68 -0
- resource_engine/testing/__init__.py +34 -0
- resource_engine/testing/activity.py +123 -0
- resource_engine/testing/contracts.py +1416 -0
- resource_engine/testing/email.py +36 -0
- resource_engine/testing/engine.py +40 -0
- resource_engine/testing/memory.py +603 -0
- resource_engine/testing/storage.py +110 -0
- resource_engine/testing/tracing.py +100 -0
- resource_engine/tracing.py +156 -0
- resource_engine/translatable.py +80 -0
- resource_engine/versions.py +189 -0
- resource_engine-0.1.0.dist-info/METADATA +36 -0
- resource_engine-0.1.0.dist-info/RECORD +128 -0
- resource_engine-0.1.0.dist-info/WHEEL +4 -0
- resource_engine-0.1.0.dist-info/licenses/LICENSE +202 -0
|
@@ -0,0 +1,327 @@
|
|
|
1
|
+
"""Tamper evidence for the audit trail: sealed batches, chained.
|
|
2
|
+
|
|
3
|
+
Entries are written by concurrent transactions, so they are not chained one by
|
|
4
|
+
one. ``AuditSealer.seal_pending()`` (a periodic job) takes the unsealed entries
|
|
5
|
+
older than ``settle``, in ``(at, id)`` order, and seals them in batches:
|
|
6
|
+
|
|
7
|
+
- ``digest``: SHA-256 over the batch's entries in canonical JSON;
|
|
8
|
+
- ``hash``: SHA-256 over the digest, the batch's metadata and the previous
|
|
9
|
+
seal's hash, so each seal commits to the whole chain before it;
|
|
10
|
+
- ``mac``: HMAC-SHA-256 of ``hash`` when a key is configured, so whoever can
|
|
11
|
+
write the database cannot recompute the seals without the key.
|
|
12
|
+
|
|
13
|
+
``verify()`` walks the chain and reports entries changed, deleted or moved
|
|
14
|
+
between seals, seals changed, missing or reordered, and bad HMACs. Entries
|
|
15
|
+
written after the last run are not covered until the next one. Entries added
|
|
16
|
+
by someone with write access are sealed like any other: sealing detects later
|
|
17
|
+
changes, not forged writes.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
from __future__ import annotations
|
|
21
|
+
|
|
22
|
+
import dataclasses
|
|
23
|
+
import hashlib
|
|
24
|
+
import hmac
|
|
25
|
+
import json
|
|
26
|
+
from collections.abc import Callable, Mapping
|
|
27
|
+
from dataclasses import dataclass, field
|
|
28
|
+
from datetime import UTC, datetime, timedelta
|
|
29
|
+
from typing import Any
|
|
30
|
+
|
|
31
|
+
from resource_engine.application.query import ListQuery
|
|
32
|
+
from resource_engine.audit.model import AuditEntry, AuditSeal
|
|
33
|
+
from resource_engine.audit.recorder import jsonable
|
|
34
|
+
from resource_engine.errors import ConfigurationError
|
|
35
|
+
|
|
36
|
+
UNSEALED = {"eq": [{"attr": "resource.seal"}, None]}
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _utc(value: datetime) -> datetime:
|
|
40
|
+
"""SQLite gives naive datetimes back: they are UTC."""
|
|
41
|
+
return value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def canonical(entry: AuditEntry) -> bytes:
|
|
45
|
+
"""The bytes an entry is sealed as: every field but ``seal``, as sorted,
|
|
46
|
+
compact JSON, with ``at`` in UTC."""
|
|
47
|
+
data = {f.name: getattr(entry, f.name) for f in dataclasses.fields(AuditEntry)}
|
|
48
|
+
data.pop("seal")
|
|
49
|
+
data["at"] = _utc(data["at"]).isoformat()
|
|
50
|
+
return json.dumps(
|
|
51
|
+
jsonable(data), sort_keys=True, separators=(",", ":"), ensure_ascii=False
|
|
52
|
+
).encode()
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def entries_digest(entries: list[AuditEntry]) -> str:
|
|
56
|
+
"""SHA-256 over the canonical form of a run of audit entries."""
|
|
57
|
+
digest = hashlib.sha256()
|
|
58
|
+
for entry in entries:
|
|
59
|
+
digest.update(canonical(entry))
|
|
60
|
+
digest.update(b"\n")
|
|
61
|
+
return digest.hexdigest()
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def seal_hash(
|
|
65
|
+
sequence: int,
|
|
66
|
+
previous: str | None,
|
|
67
|
+
entries: int,
|
|
68
|
+
first_at: datetime,
|
|
69
|
+
last_at: datetime,
|
|
70
|
+
digest: str,
|
|
71
|
+
) -> str:
|
|
72
|
+
"""The hash of one seal, chained to the previous seal's hash."""
|
|
73
|
+
material = {
|
|
74
|
+
"sequence": sequence,
|
|
75
|
+
"previous": previous,
|
|
76
|
+
"entries": entries,
|
|
77
|
+
"first_at": _utc(first_at).isoformat(),
|
|
78
|
+
"last_at": _utc(last_at).isoformat(),
|
|
79
|
+
"digest": digest,
|
|
80
|
+
}
|
|
81
|
+
return hashlib.sha256(json.dumps(material, sort_keys=True).encode()).hexdigest()
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _mac(key: bytes, value: str) -> str:
|
|
85
|
+
return hmac.new(key, value.encode(), hashlib.sha256).hexdigest()
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
@dataclass(frozen=True)
|
|
89
|
+
class AuditProblem:
|
|
90
|
+
"""One finding of ``AuditSealer.verify``.
|
|
91
|
+
|
|
92
|
+
``kind``: ``entries_changed`` (digest or count differs: entries changed,
|
|
93
|
+
deleted or moved), ``seal_changed`` (the seal does not hash to itself),
|
|
94
|
+
``chain_broken`` (``previous`` does not match), ``seal_missing`` (a gap in
|
|
95
|
+
the sequence), ``bad_mac``, ``unsigned`` (a key is configured but the seal
|
|
96
|
+
has no HMAC), ``unknown_key``, ``orphan_entries`` (entries pointing at a
|
|
97
|
+
seal that does not exist).
|
|
98
|
+
"""
|
|
99
|
+
|
|
100
|
+
sequence: int | None
|
|
101
|
+
kind: str
|
|
102
|
+
message: str
|
|
103
|
+
|
|
104
|
+
|
|
105
|
+
@dataclass
|
|
106
|
+
class AuditVerification:
|
|
107
|
+
"""What verifying the audit seals found: counts and the problems, if any."""
|
|
108
|
+
|
|
109
|
+
seals: int = 0
|
|
110
|
+
entries: int = 0
|
|
111
|
+
purged_seals: int = 0
|
|
112
|
+
unsealed: int = 0
|
|
113
|
+
problems: list[AuditProblem] = field(default_factory=list)
|
|
114
|
+
|
|
115
|
+
@property
|
|
116
|
+
def ok(self) -> bool:
|
|
117
|
+
"""Whether no problems were found."""
|
|
118
|
+
return not self.problems
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
class AuditSealer:
|
|
122
|
+
"""Seals the audit trail in batches and verifies the chain.
|
|
123
|
+
|
|
124
|
+
Args:
|
|
125
|
+
uow_factory: Units of work with the ``audit_log`` and ``audit_seals``
|
|
126
|
+
repositories (``registry.register_audit(seals=True)``).
|
|
127
|
+
key: HMAC key. Without it, seals are plain hashes: they show accidental
|
|
128
|
+
or partial edits, not a rewrite of entries and seals together.
|
|
129
|
+
key_id: Stored with each seal, to rotate keys.
|
|
130
|
+
old_keys: Earlier keys by id, to verify seals they produced.
|
|
131
|
+
settle: Only entries older than this are sealed, so transactions still
|
|
132
|
+
running when the sealer starts get into a later batch, not a gap.
|
|
133
|
+
batch_size: Entries per seal (one transaction each).
|
|
134
|
+
|
|
135
|
+
Run one sealer at a time. In SQL, two sealers racing collide on the seal's
|
|
136
|
+
primary key and one of them rolls back.
|
|
137
|
+
"""
|
|
138
|
+
|
|
139
|
+
def __init__(
|
|
140
|
+
self,
|
|
141
|
+
uow_factory: Callable[[], Any],
|
|
142
|
+
*,
|
|
143
|
+
key: bytes | None = None,
|
|
144
|
+
key_id: str = "default",
|
|
145
|
+
old_keys: Mapping[str, bytes] | None = None,
|
|
146
|
+
settle: timedelta = timedelta(minutes=5),
|
|
147
|
+
batch_size: int = 1000,
|
|
148
|
+
entries: str = "audit_log",
|
|
149
|
+
seals: str = "audit_seals",
|
|
150
|
+
) -> None:
|
|
151
|
+
if batch_size < 1:
|
|
152
|
+
raise ConfigurationError("batch_size must be at least 1")
|
|
153
|
+
if settle < timedelta(0):
|
|
154
|
+
raise ConfigurationError("settle cannot be negative")
|
|
155
|
+
if key is not None and not key:
|
|
156
|
+
raise ConfigurationError("The HMAC key is empty", hint="Pass key=None for no HMAC.")
|
|
157
|
+
self.uow_factory = uow_factory
|
|
158
|
+
self.key = key
|
|
159
|
+
self.key_id = key_id
|
|
160
|
+
self.keys: dict[str, bytes] = dict(old_keys or {})
|
|
161
|
+
if key is not None:
|
|
162
|
+
self.keys[key_id] = key
|
|
163
|
+
self.settle = settle
|
|
164
|
+
self.batch_size = batch_size
|
|
165
|
+
self.entries_resource = entries
|
|
166
|
+
self.seals_resource = seals
|
|
167
|
+
|
|
168
|
+
# ------------------------------------------------------------------ seal
|
|
169
|
+
|
|
170
|
+
async def seal_pending(self, now: datetime | None = None) -> list[AuditSeal]:
|
|
171
|
+
"""Seal the unsealed entries older than ``settle``. Returns the new seals."""
|
|
172
|
+
cutoff = (now or datetime.now(UTC)) - self.settle
|
|
173
|
+
sealed: list[AuditSeal] = []
|
|
174
|
+
while True:
|
|
175
|
+
async with self.uow_factory() as uow:
|
|
176
|
+
entries_repo = uow.repository(self.entries_resource)
|
|
177
|
+
seals_repo = uow.repository(self.seals_resource)
|
|
178
|
+
page = await entries_repo.list(
|
|
179
|
+
ListQuery(
|
|
180
|
+
limit=self.batch_size,
|
|
181
|
+
condition={"and": [UNSEALED, _before(cutoff)]},
|
|
182
|
+
order_by=["at", "id"],
|
|
183
|
+
)
|
|
184
|
+
)
|
|
185
|
+
batch = page.items
|
|
186
|
+
if not batch:
|
|
187
|
+
return sealed
|
|
188
|
+
last = await _last_seal(seals_repo)
|
|
189
|
+
sequence = (last.sequence if last else 0) + 1
|
|
190
|
+
seal = self._seal(sequence, last.hash if last else None, batch)
|
|
191
|
+
for entry in batch:
|
|
192
|
+
entry.seal = sequence
|
|
193
|
+
await entries_repo.update(entry)
|
|
194
|
+
await seals_repo.add(seal)
|
|
195
|
+
sealed.append(dataclasses.replace(seal)) # usable after the session ends
|
|
196
|
+
await uow.commit()
|
|
197
|
+
if len(batch) < self.batch_size:
|
|
198
|
+
return sealed
|
|
199
|
+
|
|
200
|
+
def _seal(self, sequence: int, previous: str | None, batch: list[AuditEntry]) -> AuditSeal:
|
|
201
|
+
digest = entries_digest(batch)
|
|
202
|
+
first_at = min(_utc(e.at) for e in batch)
|
|
203
|
+
last_at = max(_utc(e.at) for e in batch)
|
|
204
|
+
value = seal_hash(sequence, previous, len(batch), first_at, last_at, digest)
|
|
205
|
+
return AuditSeal(
|
|
206
|
+
sequence=sequence,
|
|
207
|
+
previous=previous,
|
|
208
|
+
entries=len(batch),
|
|
209
|
+
first_at=first_at,
|
|
210
|
+
last_at=last_at,
|
|
211
|
+
digest=digest,
|
|
212
|
+
hash=value,
|
|
213
|
+
mac=_mac(self.key, value) if self.key is not None else None,
|
|
214
|
+
key_id=self.key_id if self.key is not None else None,
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
# ---------------------------------------------------------------- verify
|
|
218
|
+
|
|
219
|
+
async def verify(self) -> AuditVerification:
|
|
220
|
+
"""Walk the whole chain and recompute every seal and batch."""
|
|
221
|
+
report = AuditVerification()
|
|
222
|
+
previous: AuditSeal | None = None
|
|
223
|
+
offset = 0
|
|
224
|
+
async with self.uow_factory() as uow:
|
|
225
|
+
entries_repo = uow.repository(self.entries_resource)
|
|
226
|
+
seals_repo = uow.repository(self.seals_resource)
|
|
227
|
+
while True:
|
|
228
|
+
page = await seals_repo.list(
|
|
229
|
+
ListQuery(offset=offset, limit=500, order_by=["sequence"])
|
|
230
|
+
)
|
|
231
|
+
for seal in page.items:
|
|
232
|
+
await self._check(seal, previous, entries_repo, report)
|
|
233
|
+
previous = seal
|
|
234
|
+
offset += len(page.items)
|
|
235
|
+
if len(page.items) < 500:
|
|
236
|
+
break
|
|
237
|
+
last = previous.sequence if previous else 0
|
|
238
|
+
orphans = await entries_repo.list(
|
|
239
|
+
ListQuery(limit=1, condition={"gt": [{"attr": "resource.seal"}, last]})
|
|
240
|
+
)
|
|
241
|
+
if orphans.total:
|
|
242
|
+
report.problems.append(
|
|
243
|
+
AuditProblem(
|
|
244
|
+
None,
|
|
245
|
+
"orphan_entries",
|
|
246
|
+
f"{orphans.total} entries point at seals after {last}",
|
|
247
|
+
)
|
|
248
|
+
)
|
|
249
|
+
unsealed = await entries_repo.list(ListQuery(limit=1, condition=UNSEALED))
|
|
250
|
+
report.unsealed = unsealed.total
|
|
251
|
+
return report
|
|
252
|
+
|
|
253
|
+
async def _check(
|
|
254
|
+
self,
|
|
255
|
+
seal: AuditSeal,
|
|
256
|
+
previous: AuditSeal | None,
|
|
257
|
+
entries_repo: Any,
|
|
258
|
+
report: AuditVerification,
|
|
259
|
+
) -> None:
|
|
260
|
+
report.seals += 1
|
|
261
|
+
problems = report.problems
|
|
262
|
+
seq = seal.sequence
|
|
263
|
+
expected_seq = (previous.sequence if previous else 0) + 1
|
|
264
|
+
if seq != expected_seq:
|
|
265
|
+
problems.append(
|
|
266
|
+
AuditProblem(seq, "seal_missing", f"seals {expected_seq}..{seq - 1} are missing")
|
|
267
|
+
)
|
|
268
|
+
if seal.previous != (previous.hash if previous else None):
|
|
269
|
+
problems.append(
|
|
270
|
+
AuditProblem(seq, "chain_broken", "previous does not match the seal before")
|
|
271
|
+
)
|
|
272
|
+
recomputed = seal_hash(
|
|
273
|
+
seq, seal.previous, seal.entries, seal.first_at, seal.last_at, seal.digest
|
|
274
|
+
)
|
|
275
|
+
if recomputed != seal.hash:
|
|
276
|
+
problems.append(AuditProblem(seq, "seal_changed", "the seal does not hash to itself"))
|
|
277
|
+
if self.keys:
|
|
278
|
+
if seal.mac is None:
|
|
279
|
+
problems.append(AuditProblem(seq, "unsigned", "the seal has no HMAC"))
|
|
280
|
+
elif seal.key_id not in self.keys:
|
|
281
|
+
problems.append(
|
|
282
|
+
AuditProblem(seq, "unknown_key", f"no key {seal.key_id!r} to check the HMAC")
|
|
283
|
+
)
|
|
284
|
+
elif not hmac.compare_digest(_mac(self.keys[seal.key_id], seal.hash), seal.mac):
|
|
285
|
+
problems.append(AuditProblem(seq, "bad_mac", "the HMAC does not match"))
|
|
286
|
+
if seal.purged_at is not None:
|
|
287
|
+
report.purged_seals += 1
|
|
288
|
+
return
|
|
289
|
+
batch = await _batch(entries_repo, seq, max(seal.entries, 1) + 1)
|
|
290
|
+
report.entries += len(batch)
|
|
291
|
+
if len(batch) != seal.entries or entries_digest(batch) != seal.digest:
|
|
292
|
+
problems.append(
|
|
293
|
+
AuditProblem(
|
|
294
|
+
seq,
|
|
295
|
+
"entries_changed",
|
|
296
|
+
f"{len(batch)} entries found, {seal.entries} sealed; or their content changed",
|
|
297
|
+
)
|
|
298
|
+
)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _before(cutoff: datetime) -> dict[str, Any]:
|
|
302
|
+
return {"lt": [{"attr": "resource.at"}, cutoff]}
|
|
303
|
+
|
|
304
|
+
|
|
305
|
+
async def _last_seal(seals_repo: Any) -> AuditSeal | None:
|
|
306
|
+
page = await seals_repo.list(ListQuery(limit=1, order_by=["-sequence"]))
|
|
307
|
+
return page.items[0] if page.items else None
|
|
308
|
+
|
|
309
|
+
|
|
310
|
+
async def _batch(entries_repo: Any, sequence: int, limit: int) -> list[AuditEntry]:
|
|
311
|
+
"""The entries of a seal, in sealing order. ``limit`` is one more than the
|
|
312
|
+
seal's count, to notice entries added to the batch."""
|
|
313
|
+
items: list[AuditEntry] = []
|
|
314
|
+
offset = 0
|
|
315
|
+
while True:
|
|
316
|
+
page = await entries_repo.list(
|
|
317
|
+
ListQuery(
|
|
318
|
+
offset=offset,
|
|
319
|
+
limit=min(limit - len(items), 1000),
|
|
320
|
+
filters={"seal": sequence},
|
|
321
|
+
order_by=["at", "id"],
|
|
322
|
+
)
|
|
323
|
+
)
|
|
324
|
+
items += page.items
|
|
325
|
+
offset += len(page.items)
|
|
326
|
+
if not page.items or len(items) >= limit:
|
|
327
|
+
return items
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Audit sinks: the database (default), logs, or several at once."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import dataclasses
|
|
6
|
+
import json
|
|
7
|
+
import logging
|
|
8
|
+
from collections.abc import Callable, Sequence
|
|
9
|
+
from typing import Any, override
|
|
10
|
+
|
|
11
|
+
from resource_engine.audit.model import AuditEntry
|
|
12
|
+
from resource_engine.audit.recorder import jsonable
|
|
13
|
+
from resource_engine.ports.audit import AuditSink
|
|
14
|
+
|
|
15
|
+
log = logging.getLogger("resource_engine.audit")
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
class RepositoryAuditSink(AuditSink):
|
|
19
|
+
"""Writes entries to the built-in ``audit_log`` resource (any repository: SQL
|
|
20
|
+
table, in memory). Changes go into the operation's own transaction.
|
|
21
|
+
|
|
22
|
+
Args:
|
|
23
|
+
uow_factory: Opens a unit of work for entries written on their own.
|
|
24
|
+
resource: Name of the audit resource (``registry.register_audit()``).
|
|
25
|
+
"""
|
|
26
|
+
|
|
27
|
+
def __init__(self, uow_factory: Callable[[], Any], *, resource: str = "audit_log") -> None:
|
|
28
|
+
self.uow_factory = uow_factory
|
|
29
|
+
self.resource = resource
|
|
30
|
+
|
|
31
|
+
@override
|
|
32
|
+
async def record(self, entries: Sequence[AuditEntry], *, uow: Any = None) -> None:
|
|
33
|
+
if not entries:
|
|
34
|
+
return
|
|
35
|
+
if uow is not None:
|
|
36
|
+
repo = uow.repository(self.resource)
|
|
37
|
+
for entry in entries:
|
|
38
|
+
await repo.add(entry)
|
|
39
|
+
return
|
|
40
|
+
async with self.uow_factory() as own:
|
|
41
|
+
repo = own.repository(self.resource)
|
|
42
|
+
for entry in entries:
|
|
43
|
+
await repo.add(entry)
|
|
44
|
+
await own.commit()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
class LoggingAuditSink(AuditSink):
|
|
48
|
+
"""One structured log line (JSON) per entry, for deployments that ship logs."""
|
|
49
|
+
|
|
50
|
+
def __init__(self, logger: logging.Logger | None = None, level: int = logging.INFO) -> None:
|
|
51
|
+
self.logger = logger or log
|
|
52
|
+
self.level = level
|
|
53
|
+
|
|
54
|
+
@override
|
|
55
|
+
async def record(self, entries: Sequence[AuditEntry], *, uow: Any = None) -> None:
|
|
56
|
+
for entry in entries:
|
|
57
|
+
self.logger.log(self.level, "audit %s", json.dumps(jsonable(dataclasses.asdict(entry))))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
class CompositeAuditSink(AuditSink):
|
|
61
|
+
"""Sends entries to every sink, in order."""
|
|
62
|
+
|
|
63
|
+
def __init__(self, *sinks: Any) -> None:
|
|
64
|
+
self.sinks = sinks
|
|
65
|
+
|
|
66
|
+
@override
|
|
67
|
+
async def record(self, entries: Sequence[AuditEntry], *, uow: Any = None) -> None:
|
|
68
|
+
for sink in self.sinks:
|
|
69
|
+
await sink.record(entries, uow=uow)
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
"""Permissions: system roles in code, ABAC policies as data managed from front ends.
|
|
2
|
+
|
|
3
|
+
See docs/permissions.md.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
from resource_engine.authz.apikeys import ApiKey, ApiKeyAuthenticator, ApiKeyResource
|
|
7
|
+
from resource_engine.authz.base import RoleBasedAuthorizer, subject_view
|
|
8
|
+
from resource_engine.authz.catalog import ActionInfo, AttributeInfo, Catalog, action_matches
|
|
9
|
+
from resource_engine.authz.conditions import UNKNOWN, Env, evaluate, partial, validate
|
|
10
|
+
from resource_engine.authz.config import AuthzConfig, SystemRole
|
|
11
|
+
from resource_engine.authz.evaluator import (
|
|
12
|
+
PolicyAuthorizer,
|
|
13
|
+
PolicyFieldRules,
|
|
14
|
+
PolicyStore,
|
|
15
|
+
SystemPrincipal,
|
|
16
|
+
system_principal,
|
|
17
|
+
)
|
|
18
|
+
from resource_engine.authz.external import EngineAuthorizer, ResidualFieldRules, plain
|
|
19
|
+
from resource_engine.authz.fields import hidden_fields, mask
|
|
20
|
+
from resource_engine.authz.model import Policy, Role, RoleAssignment
|
|
21
|
+
from resource_engine.authz.resources import (
|
|
22
|
+
PolicyChanged,
|
|
23
|
+
PolicyResource,
|
|
24
|
+
RoleAssignmentResource,
|
|
25
|
+
RoleResource,
|
|
26
|
+
)
|
|
27
|
+
from resource_engine.authz.roles import (
|
|
28
|
+
CombinedRoleSource,
|
|
29
|
+
IdpRoleSource,
|
|
30
|
+
RoleSource,
|
|
31
|
+
StoredRoleSource,
|
|
32
|
+
)
|
|
33
|
+
|
|
34
|
+
__all__ = [
|
|
35
|
+
"UNKNOWN",
|
|
36
|
+
"ActionInfo",
|
|
37
|
+
"ApiKey",
|
|
38
|
+
"ApiKeyAuthenticator",
|
|
39
|
+
"ApiKeyResource",
|
|
40
|
+
"AttributeInfo",
|
|
41
|
+
"AuthzConfig",
|
|
42
|
+
"Catalog",
|
|
43
|
+
"CombinedRoleSource",
|
|
44
|
+
"EngineAuthorizer",
|
|
45
|
+
"Env",
|
|
46
|
+
"IdpRoleSource",
|
|
47
|
+
"Policy",
|
|
48
|
+
"PolicyAuthorizer",
|
|
49
|
+
"PolicyChanged",
|
|
50
|
+
"PolicyFieldRules",
|
|
51
|
+
"PolicyResource",
|
|
52
|
+
"PolicyStore",
|
|
53
|
+
"ResidualFieldRules",
|
|
54
|
+
"Role",
|
|
55
|
+
"RoleAssignment",
|
|
56
|
+
"RoleAssignmentResource",
|
|
57
|
+
"RoleBasedAuthorizer",
|
|
58
|
+
"RoleResource",
|
|
59
|
+
"RoleSource",
|
|
60
|
+
"StoredRoleSource",
|
|
61
|
+
"SystemPrincipal",
|
|
62
|
+
"SystemRole",
|
|
63
|
+
"action_matches",
|
|
64
|
+
"evaluate",
|
|
65
|
+
"hidden_fields",
|
|
66
|
+
"mask",
|
|
67
|
+
"partial",
|
|
68
|
+
"plain",
|
|
69
|
+
"subject_view",
|
|
70
|
+
"system_principal",
|
|
71
|
+
"validate",
|
|
72
|
+
]
|