sentrykit 0.1.0rc1__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 (46) hide show
  1. sentrykit/__init__.py +200 -0
  2. sentrykit/audit.py +967 -0
  3. sentrykit/cedar.py +750 -0
  4. sentrykit/cli.py +1405 -0
  5. sentrykit/config.py +300 -0
  6. sentrykit/constraints.py +928 -0
  7. sentrykit/context.py +393 -0
  8. sentrykit/decorator.py +252 -0
  9. sentrykit/engine.py +1509 -0
  10. sentrykit/envelope.py +513 -0
  11. sentrykit/errors.py +252 -0
  12. sentrykit/integrations/__init__.py +1 -0
  13. sentrykit/integrations/base.py +767 -0
  14. sentrykit/integrations/fastapi.py +361 -0
  15. sentrykit/integrations/flask.py +342 -0
  16. sentrykit/integrations/mcp.py +929 -0
  17. sentrykit/integrations/pydantic_ai.py +728 -0
  18. sentrykit/integrations/tools.py +479 -0
  19. sentrykit/masking.py +459 -0
  20. sentrykit/policy/__init__.py +40 -0
  21. sentrykit/policy/loader.py +764 -0
  22. sentrykit/policy/pack/10-rbac.cedar +9 -0
  23. sentrykit/policy/pack/20-groups.cedar +9 -0
  24. sentrykit/policy/pack/30-ownership.cedar +8 -0
  25. sentrykit/policy/pack/40-delegation.cedar +40 -0
  26. sentrykit/policy/pack/50-expiry.cedar +24 -0
  27. sentrykit/policy/pack/60-break-glass.cedar +34 -0
  28. sentrykit/policy/pack/70-separation-of-duties.cedar +22 -0
  29. sentrykit/policy/pack/80-jit-elevation.cedar +32 -0
  30. sentrykit/policy/pack/entities.json +3 -0
  31. sentrykit/policy/pack/pack.cedarschema +45 -0
  32. sentrykit/policy/pack/templates/time-boxed-grant.cedartemplate +5 -0
  33. sentrykit/py.typed +0 -0
  34. sentrykit/registry.py +666 -0
  35. sentrykit/stores/__init__.py +116 -0
  36. sentrykit/stores/base.py +870 -0
  37. sentrykit/stores/composite.py +635 -0
  38. sentrykit/stores/filesystem.py +400 -0
  39. sentrykit/stores/jsonfile.py +701 -0
  40. sentrykit/stores/jsonl.py +357 -0
  41. sentrykit/stores/memory.py +500 -0
  42. sentrykit-0.1.0rc1.dist-info/METADATA +541 -0
  43. sentrykit-0.1.0rc1.dist-info/RECORD +46 -0
  44. sentrykit-0.1.0rc1.dist-info/WHEEL +4 -0
  45. sentrykit-0.1.0rc1.dist-info/entry_points.txt +20 -0
  46. sentrykit-0.1.0rc1.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,635 @@
1
+ """Many backends behind one Protocol — the second half of the plugin mechanism.
2
+
3
+ Multiplicity never reaches the core. Configure three audit sinks and the governor still holds
4
+ exactly one :class:`~sentrykit.stores.base.AuditSink`; configure two policy directories and it
5
+ still holds one :class:`~sentrykit.stores.base.PolicySource`. Each composite *is-a* the
6
+ Protocol it composes, so "how many are configured" is a wiring question that
7
+ :mod:`sentrykit.registry` answers once and nothing downstream can ask again.
8
+
9
+ The three compose differently, because the three stores guarantee different things:
10
+
11
+ * **Policy sources union.** Their bundles are concatenated in a fixed order and reparsed as
12
+ one policy text. There is deliberately **no source precedence, and no "later source wins"
13
+ rule**: in Cedar an override is expressed as a ``forbid``, and forbid always beats permit
14
+ no matter where either policy sits in the text. That property is exactly what makes
15
+ merging sources safe at all. Ordering is fixed only because Cedar numbers policies
16
+ *positionally*, so the provenance index and the engine must be built from one identical
17
+ string.
18
+ * **Grant stores merge or route.** Merge-by-precedence when the members are overlapping views
19
+ of the same population (earlier members win per field); route-by-namespace when every member
20
+ declares one and each owns a disjoint population.
21
+ * **Audit sinks fan out.** Every sink is attempted on every record, under an explicit error
22
+ policy that says which failures are allowed to refuse production traffic.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import logging
28
+ from collections.abc import Iterator, Mapping, Sequence
29
+ from dataclasses import replace
30
+ from datetime import datetime
31
+ from typing import TYPE_CHECKING, Any, Final, Literal
32
+
33
+ from sentrykit.cedar import Entity, EntityRef
34
+ from sentrykit.constraints import ConstraintSet
35
+ from sentrykit.context import Principal
36
+ from sentrykit.errors import AuditUnavailable, ConfigurationError
37
+ from sentrykit.stores.base import (
38
+ AuditSink,
39
+ AuditWindow,
40
+ GrantRecord,
41
+ GrantSpec,
42
+ GrantStore,
43
+ PolicyBundle,
44
+ PolicyProvenance,
45
+ PolicySource,
46
+ SupportsClose,
47
+ )
48
+
49
+ if TYPE_CHECKING: # pragma: no cover - imported for annotations only
50
+ from sentrykit.audit import AuthzAuditRecord
51
+
52
+ __all__ = [
53
+ "AUDIT_ERROR_POLICIES",
54
+ "AuditErrorPolicy",
55
+ "CompositeAuditSink",
56
+ "CompositeGrantStore",
57
+ "CompositePolicySource",
58
+ ]
59
+
60
+ _LOGGER: Final = logging.getLogger("sentrykit.stores.composite")
61
+
62
+ AuditErrorPolicy = Literal["primary-durable", "all-or-nothing"]
63
+ """How a fan-out reacts when a member sink refuses a record. See :class:`CompositeAuditSink`."""
64
+
65
+ AUDIT_ERROR_POLICIES: Final[Mapping[str, AuditErrorPolicy]] = {
66
+ "primary-durable": "primary-durable",
67
+ "all-or-nothing": "all-or-nothing",
68
+ }
69
+ """The valid ``?on_error=`` values, so the registry can validate a DSN option against them."""
70
+
71
+
72
+ # --- policy sources ----------------------------------------------------------------------
73
+
74
+
75
+ class CompositePolicySource:
76
+ """Several policy sources, unioned into one bundle.
77
+
78
+ The union is a **concatenation, not a precedence chain**. Ordering the members cannot
79
+ change a decision: an override is a Cedar ``forbid``, and forbid wins wherever it sits.
80
+ The order is fixed anyway because Cedar's generated policy ids (``policy0``, ``policy1``)
81
+ are positional in the text it parsed — so the combined text is built once, and the
82
+ provenance index is derived from *that* string rather than reassembled from the members'.
83
+
84
+ Each member's declared ``@id`` is namespaced as ``<source-name>/<id>`` in the provenance
85
+ index. Cedar does not enforce ``@id`` uniqueness — two sources may both declare
86
+ ``@id("btg-read")`` and it parses without complaint — so the namespacing is sentrykit's
87
+ hygiene, and it is what keeps a decision's determining policies attributable to one
88
+ artifact. It is applied to the index rather than to the policy text, so Cedar keeps
89
+ reporting the raw ``@id``; :meth:`~sentrykit.stores.base.PolicyBundle.provenance_for`
90
+ resolves both spellings, which is what keeps the join working across a union.
91
+
92
+ Args:
93
+ sources: The members, in the order their policies are concatenated.
94
+ name: This composite's name, recorded on the combined bundle.
95
+
96
+ Raises:
97
+ ConfigurationError: If no sources were given, or if two of them share a name — the
98
+ name *is* the namespace, so duplicates would defeat the disambiguation.
99
+ """
100
+
101
+ __slots__ = ("_name", "_sources")
102
+
103
+ def __init__(self, sources: Sequence[PolicySource], *, name: str = "composite") -> None:
104
+ if not sources:
105
+ raise ConfigurationError("a composite policy source needs at least one member source")
106
+ seen: dict[str, None] = {}
107
+ for source in sources:
108
+ if source.name in seen:
109
+ raise ConfigurationError(
110
+ f"two policy sources are both named {source.name!r}; names namespace "
111
+ "policy ids, so they must be distinct"
112
+ )
113
+ seen[source.name] = None
114
+ self._sources = tuple(sources)
115
+ self._name = name
116
+
117
+ @property
118
+ def name(self) -> str:
119
+ """This composite's name."""
120
+ return self._name
121
+
122
+ @property
123
+ def sources(self) -> tuple[PolicySource, ...]:
124
+ """The members, in concatenation order."""
125
+ return self._sources
126
+
127
+ def load(self) -> PolicyBundle:
128
+ """Load every member and union them into one bundle.
129
+
130
+ Returns:
131
+ The combined bundle: every member's policy text concatenated in order, every
132
+ member's entities unioned, and one provenance entry per policy carrying the
133
+ member that contributed it and that member's namespaced policy id.
134
+
135
+ Raises:
136
+ ConfigurationError: If a member fails to load, if the combined text does not
137
+ parse, or if two members contribute conflicting definitions of one entity.
138
+ """
139
+ bundles = [source.load() for source in self._sources]
140
+ fragments = [bundle.policies.strip() for bundle in bundles]
141
+ # One concatenation, parsed once. Everything downstream -- the engine, the generated
142
+ # ids, the provenance index -- is derived from this single string, because Cedar
143
+ # numbers policies positionally and an index built from anything else mis-joins.
144
+ combined = PolicyBundle.from_text(
145
+ "\n\n".join(fragment for fragment in fragments if fragment),
146
+ schema=self._combined_schema(bundles),
147
+ entities=self._combined_entities(bundles),
148
+ source=self._name,
149
+ )
150
+ counts = [len(bundle.provenance) for bundle in bundles]
151
+ return replace(combined, provenance=self._attributed(combined.provenance, counts, bundles))
152
+
153
+ def current_hash(self) -> str:
154
+ """Return the digest of the bundle :meth:`load` would return right now.
155
+
156
+ The union's hash covers the *concatenated* text, so — unlike a single source, which
157
+ can usually stat a file — there is no shortcut: the combined string does not exist
158
+ until every member has been read. Polling a union therefore costs a load, which is
159
+ the price of the contract that a bundle hash pins exactly the logic a decision was
160
+ made against.
161
+ """
162
+ return self.load().bundle_hash
163
+
164
+ @staticmethod
165
+ def _combined_schema(bundles: Sequence[PolicyBundle]) -> str | None:
166
+ """Concatenate the members' schema fragments, dropping exact repeats.
167
+
168
+ Two sources shipping the same ``.cedarschema`` is the common case and must not become
169
+ a duplicate-declaration error; two sources declaring the *same entity type differently*
170
+ is a genuine conflict, and Cedar reports it when the bundle builds its engine.
171
+ """
172
+ fragments: list[str] = []
173
+ for bundle in bundles:
174
+ if bundle.schema and bundle.schema not in fragments:
175
+ fragments.append(bundle.schema)
176
+ return "\n\n".join(fragments) if fragments else None
177
+
178
+ def _combined_entities(self, bundles: Sequence[PolicyBundle]) -> tuple[Entity, ...]:
179
+ """Union the members' entity graphs.
180
+
181
+ Raises:
182
+ ConfigurationError: If two members contribute the same uid with different content.
183
+ Identical contributions are fine — two sources may legitimately both declare
184
+ ``Role::"admin"`` — but a divergent one would make the graph ambiguous, and
185
+ which of the two won would decide requests.
186
+ """
187
+ merged: dict[EntityRef, Entity] = {}
188
+ contributors: dict[EntityRef, str] = {}
189
+ for source, bundle in zip(self._sources, bundles, strict=True):
190
+ for entity in bundle.entities:
191
+ existing = merged.get(entity.uid)
192
+ if existing is None:
193
+ merged[entity.uid] = entity
194
+ contributors[entity.uid] = source.name
195
+ elif existing != entity:
196
+ raise ConfigurationError(
197
+ f"entity {entity.uid} is defined differently by policy sources "
198
+ f"{contributors[entity.uid]!r} and {source.name!r}; "
199
+ "the entity graph would be ambiguous"
200
+ )
201
+ return tuple(merged.values())
202
+
203
+ def _attributed(
204
+ self,
205
+ provenance: Sequence[PolicyProvenance],
206
+ counts: Sequence[int],
207
+ bundles: Sequence[PolicyBundle],
208
+ ) -> tuple[PolicyProvenance, ...]:
209
+ """Re-attach each combined provenance entry to the member that contributed it.
210
+
211
+ The combined entries carry the ids and annotations Cedar will report, because they
212
+ were read from the combined text. What they cannot know is *which artifact* each
213
+ policy came from — so the member's ``source`` and ``origin`` are stitched back on
214
+ positionally, using how many policies each member contributed.
215
+ """
216
+ attributed: list[PolicyProvenance] = []
217
+ offset = 0
218
+ for source, bundle, count in zip(self._sources, bundles, counts, strict=True):
219
+ for local in range(count):
220
+ if offset + local >= len(provenance): # pragma: no cover - defensive
221
+ break
222
+ entry = provenance[offset + local]
223
+ origin = bundle.provenance[local].origin if local < len(bundle.provenance) else ""
224
+ attributed.append(
225
+ replace(
226
+ entry,
227
+ policy_id=_namespaced_id(source.name, entry),
228
+ source=source.name,
229
+ origin=origin,
230
+ )
231
+ )
232
+ offset += count
233
+ attributed.extend(provenance[offset:])
234
+ return tuple(attributed)
235
+
236
+
237
+ def _namespaced_id(source: str, entry: PolicyProvenance) -> str:
238
+ """Namespace one declared policy id, idempotently.
239
+
240
+ A policy that declares no ``@id`` keeps Cedar's generated id, which is positional in the
241
+ combined text and therefore already unique across the union. An id that already carries
242
+ this source's prefix — a member that is itself namespaced, or a nested composite — is left
243
+ alone rather than prefixed twice.
244
+ """
245
+ if entry.policy_id == entry.cedar_id:
246
+ return entry.cedar_id
247
+ prefix = f"{source}/"
248
+ return entry.policy_id if entry.policy_id.startswith(prefix) else prefix + entry.policy_id
249
+
250
+
251
+ # --- grant stores ------------------------------------------------------------------------
252
+
253
+
254
+ class CompositeGrantStore:
255
+ """Several grant stores, either merged by precedence or routed by namespace.
256
+
257
+ Which one it is is not configured — it is inferred, because the two arrangements are
258
+ distinguishable by what the members declare. If **every** member exposes a non-empty
259
+ ``namespace`` attribute, the members own disjoint populations and lookups **route**: a
260
+ principal whose id or entity type is prefixed ``<namespace>:`` goes to exactly one store.
261
+ Otherwise the members are overlapping views of one population and lookups **merge**, with
262
+ earlier members winning.
263
+
264
+ Merging is per field, not per store: a principal known to two stores comes back with their
265
+ roles and parents unioned (order preserving, de-duplicated) and their attributes and
266
+ per-action constraint sets layered with the earlier store on top. That is what lets a
267
+ local override store sit in front of a corporate directory without either having to know
268
+ about the other.
269
+
270
+ Args:
271
+ stores: The members, in precedence order.
272
+ name: This composite's name.
273
+
274
+ Raises:
275
+ ConfigurationError: If no stores were given, or if two of them claim one namespace.
276
+ """
277
+
278
+ __slots__ = ("_name", "_routed", "_routes", "_stores")
279
+
280
+ def __init__(self, stores: Sequence[GrantStore], *, name: str = "composite") -> None:
281
+ if not stores:
282
+ raise ConfigurationError("a composite grant store needs at least one member store")
283
+ self._stores = tuple(stores)
284
+ self._name = name
285
+ namespaces = [_namespace_of(store) for store in self._stores]
286
+ self._routed = all(namespace is not None for namespace in namespaces)
287
+ self._routes: dict[str, GrantStore] = {}
288
+ if self._routed:
289
+ for store, namespace in zip(self._stores, namespaces, strict=True):
290
+ if namespace is None: # pragma: no cover - excluded by ``self._routed``
291
+ continue
292
+ claimed = self._routes.get(namespace)
293
+ if claimed is not None:
294
+ raise ConfigurationError(
295
+ f"grant stores {claimed.name!r} and {store.name!r} both claim "
296
+ f"namespace {namespace!r}; routing would be ambiguous"
297
+ )
298
+ self._routes[namespace] = store
299
+
300
+ @property
301
+ def name(self) -> str:
302
+ """This composite's name."""
303
+ return self._name
304
+
305
+ @property
306
+ def stores(self) -> tuple[GrantStore, ...]:
307
+ """The members, in precedence order."""
308
+ return self._stores
309
+
310
+ @property
311
+ def routed(self) -> bool:
312
+ """Whether lookups route by namespace rather than merging by precedence."""
313
+ return self._routed
314
+
315
+ def get_principal(
316
+ self,
317
+ principal: str | EntityRef,
318
+ *,
319
+ now: datetime | None = None,
320
+ ) -> Principal | None:
321
+ """Materialize a principal from the routed store, or from every store merged.
322
+
323
+ Args:
324
+ principal: The principal id (assumed type ``User``) or a full reference.
325
+ now: The moment expiries are evaluated against.
326
+
327
+ Returns:
328
+ The principal, or ``None`` when **no** member knows them — one member returning
329
+ ``None`` is not an answer, it is an absence, and the caller fails closed only when
330
+ every member is silent.
331
+ """
332
+ if self._routed:
333
+ return self._route(principal).get_principal(principal, now=now)
334
+ found = [
335
+ known
336
+ for known in (store.get_principal(principal, now=now) for store in self._stores)
337
+ if known is not None
338
+ ]
339
+ if not found:
340
+ return None
341
+ if len(found) == 1:
342
+ return found[0]
343
+ return _merged_principal(found)
344
+
345
+ def grants_for(
346
+ self,
347
+ principal: str | EntityRef,
348
+ *,
349
+ include_inactive: bool = False,
350
+ ) -> tuple[GrantRecord, ...]:
351
+ """List the grants held by ``principal``, oldest first, across every member.
352
+
353
+ Args:
354
+ principal: The principal id or reference.
355
+ include_inactive: Whether to include revoked and expired grants.
356
+
357
+ Returns:
358
+ The grants. Members are expected to timestamp in UTC, which is what makes one
359
+ ordering across several stores meaningful.
360
+ """
361
+ if self._routed:
362
+ return self._route(principal).grants_for(principal, include_inactive=include_inactive)
363
+ records: list[GrantRecord] = []
364
+ for store in self._stores:
365
+ records.extend(store.grants_for(principal, include_inactive=include_inactive))
366
+ return tuple(sorted(records, key=lambda record: record.granted_at))
367
+
368
+ def grant(self, spec: GrantSpec, *, now: datetime | None = None) -> GrantRecord:
369
+ """Confer a grant on the store that owns the principal.
370
+
371
+ Args:
372
+ spec: What to confer.
373
+ now: The grant timestamp.
374
+
375
+ Returns:
376
+ The stored record.
377
+
378
+ Raises:
379
+ ConfigurationError: If routing is in effect and no member owns the principal's
380
+ namespace, or if the owning store rejects the spec.
381
+ """
382
+ if self._routed:
383
+ return self._route(spec.principal).grant(spec, now=now)
384
+ # Merge mode has a precedence order, and the front of it is the store a host put there
385
+ # to hold its own writes -- writing to the corporate directory behind it would be a
386
+ # surprise, and often a read-only one.
387
+ return self._stores[0].grant(spec, now=now)
388
+
389
+ def revoke(
390
+ self,
391
+ grant_id: str,
392
+ *,
393
+ revoked_by: str | None = None,
394
+ reason: str | None = None,
395
+ now: datetime | None = None,
396
+ ) -> GrantRecord:
397
+ """Withdraw a grant from whichever member holds it.
398
+
399
+ A grant id names no principal, so there is nothing to route on even when routing is in
400
+ effect: the members are probed in order and the first one holding the id performs the
401
+ revocation.
402
+
403
+ Args:
404
+ grant_id: The id returned by :meth:`grant`.
405
+ revoked_by: The actor withdrawing it.
406
+ reason: Why.
407
+ now: The revocation timestamp.
408
+
409
+ Returns:
410
+ The updated record.
411
+
412
+ Raises:
413
+ ConfigurationError: If no member holds that grant.
414
+ """
415
+ for store in self._stores:
416
+ try:
417
+ return store.revoke(grant_id, revoked_by=revoked_by, reason=reason, now=now)
418
+ except ConfigurationError:
419
+ continue
420
+ known = ", ".join(store.name for store in self._stores)
421
+ raise ConfigurationError(f"no grant store holds grant {grant_id!r}; tried: {known}")
422
+
423
+ def entities(self) -> tuple[Entity, ...]:
424
+ """Union the stable entities every member contributes, first definition winning."""
425
+ merged: dict[EntityRef, Entity] = {}
426
+ for store in self._stores:
427
+ for entity in store.entities():
428
+ merged.setdefault(entity.uid, entity)
429
+ return tuple(merged.values())
430
+
431
+ def _route(self, principal: str | EntityRef | Principal) -> GrantStore:
432
+ """Find the member owning ``principal``.
433
+
434
+ Both spellings of a namespace are accepted, because both occur in practice: an id
435
+ prefix (``acme:alice``) and a Cedar type namespace (``Acme::User``, whose ``Acme::``
436
+ starts with ``Acme:``).
437
+
438
+ Raises:
439
+ ConfigurationError: If no member claims a matching namespace. Guessing at a
440
+ default would send one tenant's grants to another tenant's store.
441
+ """
442
+ reference = _reference_of(principal)
443
+ for candidate in (reference.id, reference.type):
444
+ prefix, separator, _ = candidate.partition(":")
445
+ if separator and prefix in self._routes:
446
+ return self._routes[prefix]
447
+ known = ", ".join(sorted(self._routes)) or "none"
448
+ raise ConfigurationError(
449
+ f"no grant store handles principal {reference}; known namespaces: {known}"
450
+ )
451
+
452
+
453
+ def _namespace_of(store: GrantStore) -> str | None:
454
+ """Read a store's optional ``namespace``.
455
+
456
+ Optional on purpose: the :class:`~sentrykit.stores.base.GrantStore` Protocol does not
457
+ require it, because a store serving the whole population has no namespace to declare, and
458
+ demanding ``namespace = None`` from every third-party backend would be contract for
459
+ contract's sake.
460
+ """
461
+ namespace = getattr(store, "namespace", None)
462
+ return namespace if isinstance(namespace, str) and namespace else None
463
+
464
+
465
+ def _reference_of(principal: str | EntityRef | Principal) -> EntityRef:
466
+ """Normalize the three ways a principal can be named into an entity reference."""
467
+ if isinstance(principal, Principal):
468
+ return principal.uid
469
+ return EntityRef.parse(principal, default_type="User")
470
+
471
+
472
+ def _merged_principal(found: Sequence[Principal]) -> Principal:
473
+ """Layer several views of one principal, earlier winning.
474
+
475
+ Roles and parents union — a role granted by any store is held — while attributes and
476
+ constraint sets are layered, so an earlier store's ``region`` or its narrower constraint
477
+ on one argument overrides a later store's.
478
+ """
479
+ roles: dict[str, None] = {}
480
+ parents: dict[EntityRef, None] = {}
481
+ for principal in found:
482
+ for role in principal.roles:
483
+ roles.setdefault(role, None)
484
+ for parent in principal.parents:
485
+ parents.setdefault(parent, None)
486
+
487
+ attributes: dict[str, object] = {}
488
+ constraints: dict[str, ConstraintSet] = {}
489
+ # Walk back to front so each earlier store overwrites what the later ones said.
490
+ for principal in reversed(found):
491
+ attributes.update(principal.attributes)
492
+ for action, layer in principal.constraints.items():
493
+ beneath = constraints.get(action)
494
+ constraints[action] = layer if beneath is None else beneath.merged_with(layer)
495
+
496
+ return Principal(
497
+ id=found[0].id,
498
+ type=found[0].type,
499
+ roles=tuple(roles),
500
+ parents=tuple(parents),
501
+ attributes=attributes,
502
+ constraints=constraints,
503
+ )
504
+
505
+
506
+ # --- audit sinks -------------------------------------------------------------------------
507
+
508
+
509
+ class CompositeAuditSink:
510
+ """Several audit sinks, written to on every record.
511
+
512
+ Every member is attempted before anything is raised, so one dead sink can never hide the
513
+ state of the rest — an operator reading the failure needs to know whether one replica is
514
+ down or all of them are. What happens next is the error policy:
515
+
516
+ * ``primary-durable`` — the **first** sink is the record of truth and must succeed; its
517
+ failure raises :class:`~sentrykit.errors.AuditUnavailable`, which under
518
+ ``fail_mode="closed"`` refuses the governed call. A failure in any other member is
519
+ logged at ``ERROR`` and swallowed: a replica or a search index being unreachable is an
520
+ operational problem, not a reason to refuse production traffic.
521
+ * ``all-or-nothing`` — any failure raises, carrying one ``failures`` entry per failed sink.
522
+ This is **not a transaction**: sinks that already accepted the record keep it, and
523
+ append-only storage has nothing to roll back to. The guarantee is "you will be told
524
+ that the copies diverged", not "nothing was written".
525
+
526
+ Args:
527
+ sinks: The members. The first is the primary under ``primary-durable``.
528
+ on_error: The error policy.
529
+ name: This composite's name, used when reporting a fan-out failure.
530
+
531
+ Raises:
532
+ ConfigurationError: If no sinks were given or ``on_error`` is not a known policy.
533
+ """
534
+
535
+ __slots__ = ("_name", "_on_error", "_sinks")
536
+
537
+ def __init__(
538
+ self,
539
+ sinks: Sequence[AuditSink],
540
+ *,
541
+ on_error: AuditErrorPolicy = "primary-durable",
542
+ name: str = "composite",
543
+ ) -> None:
544
+ if not sinks:
545
+ raise ConfigurationError("a composite audit sink needs at least one member sink")
546
+ if on_error not in AUDIT_ERROR_POLICIES:
547
+ known = ", ".join(sorted(AUDIT_ERROR_POLICIES))
548
+ raise ConfigurationError(f"on_error is {on_error!r}; expected one of {known}")
549
+ self._sinks = tuple(sinks)
550
+ self._on_error = on_error
551
+ self._name = name
552
+
553
+ @property
554
+ def name(self) -> str:
555
+ """This composite's name."""
556
+ return self._name
557
+
558
+ @property
559
+ def sinks(self) -> tuple[AuditSink, ...]:
560
+ """The members. The first is the primary."""
561
+ return self._sinks
562
+
563
+ @property
564
+ def on_error(self) -> AuditErrorPolicy:
565
+ """How this fan-out reacts to a member failing."""
566
+ return self._on_error
567
+
568
+ def write(self, record: AuthzAuditRecord) -> None:
569
+ """Append ``record`` to every member.
570
+
571
+ Args:
572
+ record: The record, already masked and already chained.
573
+
574
+ Raises:
575
+ AuditUnavailable: Under ``primary-durable`` when the first sink failed, and under
576
+ ``all-or-nothing`` when any sink did. ``failures`` carries one entry per
577
+ failed member either way.
578
+ """
579
+ failures: list[dict[str, Any]] = []
580
+ primary: Exception | None = None
581
+ for position, sink in enumerate(self._sinks):
582
+ try:
583
+ sink.write(record)
584
+ except Exception as exc:
585
+ # A sink is arbitrary backend code -- a socket, a file, a stranger's library.
586
+ # Anything it raises is a write that did not happen, and the policy below is
587
+ # what decides whether that refuses the governed call.
588
+ _LOGGER.error(
589
+ "Audit sink %r did not accept record %s: %s", sink.name, record.record_id, exc
590
+ )
591
+ failures.append({"sink": sink.name, "error": str(exc), "type": type(exc).__name__})
592
+ if position == 0:
593
+ primary = exc
594
+ if not failures:
595
+ return
596
+ if self._on_error == "primary-durable":
597
+ if primary is None:
598
+ return
599
+ raise AuditUnavailable(self._sinks[0].name, str(primary), failures) from primary
600
+ raise AuditUnavailable(
601
+ self._name,
602
+ f"{len(failures)} of {len(self._sinks)} sinks did not accept the record",
603
+ failures,
604
+ )
605
+
606
+ def query(self, window: AuditWindow) -> Iterator[AuthzAuditRecord]:
607
+ """Read back matching records **from the first sink only**.
608
+
609
+ A fan-out writes the same record to every member, so reading from all of them would
610
+ return each record once per sink. De-duplicating by ``record_hash`` would look tidier
611
+ and would be worse: it would silently paper over a divergence between two copies of an
612
+ allegedly tamper-evident log, which is precisely the thing an auditor came to find.
613
+ Reading one sink at a time keeps a comparison possible.
614
+
615
+ Args:
616
+ window: The filter.
617
+
618
+ Returns:
619
+ The primary sink's matching records, oldest first.
620
+ """
621
+ return self._sinks[0].query(window)
622
+
623
+ def close(self) -> None:
624
+ """Close every member that holds a resource.
625
+
626
+ Failures are logged rather than raised: close is cleanup, and one member's failure to
627
+ release a handle must not stop the others from releasing theirs.
628
+ """
629
+ for sink in self._sinks:
630
+ if not isinstance(sink, SupportsClose):
631
+ continue
632
+ try:
633
+ sink.close()
634
+ except Exception as exc:
635
+ _LOGGER.error("Audit sink %r failed to close: %s", sink.name, exc)