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.
- sentrykit/__init__.py +200 -0
- sentrykit/audit.py +967 -0
- sentrykit/cedar.py +750 -0
- sentrykit/cli.py +1405 -0
- sentrykit/config.py +300 -0
- sentrykit/constraints.py +928 -0
- sentrykit/context.py +393 -0
- sentrykit/decorator.py +252 -0
- sentrykit/engine.py +1509 -0
- sentrykit/envelope.py +513 -0
- sentrykit/errors.py +252 -0
- sentrykit/integrations/__init__.py +1 -0
- sentrykit/integrations/base.py +767 -0
- sentrykit/integrations/fastapi.py +361 -0
- sentrykit/integrations/flask.py +342 -0
- sentrykit/integrations/mcp.py +929 -0
- sentrykit/integrations/pydantic_ai.py +728 -0
- sentrykit/integrations/tools.py +479 -0
- sentrykit/masking.py +459 -0
- sentrykit/policy/__init__.py +40 -0
- sentrykit/policy/loader.py +764 -0
- sentrykit/policy/pack/10-rbac.cedar +9 -0
- sentrykit/policy/pack/20-groups.cedar +9 -0
- sentrykit/policy/pack/30-ownership.cedar +8 -0
- sentrykit/policy/pack/40-delegation.cedar +40 -0
- sentrykit/policy/pack/50-expiry.cedar +24 -0
- sentrykit/policy/pack/60-break-glass.cedar +34 -0
- sentrykit/policy/pack/70-separation-of-duties.cedar +22 -0
- sentrykit/policy/pack/80-jit-elevation.cedar +32 -0
- sentrykit/policy/pack/entities.json +3 -0
- sentrykit/policy/pack/pack.cedarschema +45 -0
- sentrykit/policy/pack/templates/time-boxed-grant.cedartemplate +5 -0
- sentrykit/py.typed +0 -0
- sentrykit/registry.py +666 -0
- sentrykit/stores/__init__.py +116 -0
- sentrykit/stores/base.py +870 -0
- sentrykit/stores/composite.py +635 -0
- sentrykit/stores/filesystem.py +400 -0
- sentrykit/stores/jsonfile.py +701 -0
- sentrykit/stores/jsonl.py +357 -0
- sentrykit/stores/memory.py +500 -0
- sentrykit-0.1.0rc1.dist-info/METADATA +541 -0
- sentrykit-0.1.0rc1.dist-info/RECORD +46 -0
- sentrykit-0.1.0rc1.dist-info/WHEEL +4 -0
- sentrykit-0.1.0rc1.dist-info/entry_points.txt +20 -0
- sentrykit-0.1.0rc1.dist-info/licenses/LICENSE +201 -0
sentrykit/registry.py
ADDED
|
@@ -0,0 +1,666 @@
|
|
|
1
|
+
"""One plugin mechanism, used by everything pluggable.
|
|
2
|
+
|
|
3
|
+
Four pieces, everywhere: a `Protocol` contract, a name-keyed registry, an in-process
|
|
4
|
+
``register_*`` decorator, and ``importlib.metadata`` entry-point discovery — the same set
|
|
5
|
+
for policy sources, grant stores, audit sinks and framework context providers. Adding
|
|
6
|
+
a sink and adding a framework are the same shape of task, and the core imports neither.
|
|
7
|
+
|
|
8
|
+
**Built-ins register through the decorator a third party would use.** They are not special-
|
|
9
|
+
cased anywhere; ``jsonl`` reaches the registry by exactly the path ``sentrykit-splunk`` would.
|
|
10
|
+
That is the property the plugin tests assert, because it is the only way to know an external
|
|
11
|
+
backend is a first-class citizen rather than a documented aspiration.
|
|
12
|
+
|
|
13
|
+
Backends are addressed by **DSN**: ``jsonl://./audit.jsonl?fsync=true``,
|
|
14
|
+
``file://./policies``, ``memory://``. The scheme selects the backend; everything after it is
|
|
15
|
+
the backend's business.
|
|
16
|
+
|
|
17
|
+
Discovery is **lazy**. ``EntryPoint.load()`` imports the plugin's module, so resolving every
|
|
18
|
+
installed backend at ``import sentrykit`` time would drag optional dependencies into every
|
|
19
|
+
process. The registry looks at entry points only when an in-process lookup misses, then
|
|
20
|
+
caches the result.
|
|
21
|
+
|
|
22
|
+
Three `importlib.metadata` details matter here: always call ``entry_points(group=...)``
|
|
23
|
+
(the bare call returns a different type on 3.11), treat the result as an iterable and
|
|
24
|
+
nothing more (it is a `list` subclass on 3.11 and a `tuple`
|
|
25
|
+
subclass on 3.12+), and expect an unknown group to be empty rather than to raise.
|
|
26
|
+
"""
|
|
27
|
+
|
|
28
|
+
from __future__ import annotations
|
|
29
|
+
|
|
30
|
+
import logging
|
|
31
|
+
from collections.abc import Callable, Iterable, Mapping, Sequence
|
|
32
|
+
from dataclasses import dataclass, field
|
|
33
|
+
from importlib import metadata
|
|
34
|
+
from typing import Final, Literal, TypeAlias, TypeVar, cast
|
|
35
|
+
from urllib.parse import unquote
|
|
36
|
+
|
|
37
|
+
from sentrykit.errors import ConfigurationError
|
|
38
|
+
from sentrykit.stores.base import (
|
|
39
|
+
AuditSink,
|
|
40
|
+
ContextProvider,
|
|
41
|
+
GrantStore,
|
|
42
|
+
PolicySource,
|
|
43
|
+
)
|
|
44
|
+
|
|
45
|
+
_LOGGER: Final = logging.getLogger("sentrykit.registry")
|
|
46
|
+
|
|
47
|
+
__all__ = [
|
|
48
|
+
"DSN",
|
|
49
|
+
"ENTRY_POINT_GROUPS",
|
|
50
|
+
"Configured",
|
|
51
|
+
"PluginKind",
|
|
52
|
+
"RegisteredPlugin",
|
|
53
|
+
"available",
|
|
54
|
+
"build_audit_sink",
|
|
55
|
+
"build_context_provider",
|
|
56
|
+
"build_grant_store",
|
|
57
|
+
"build_policy_source",
|
|
58
|
+
"clear_registry",
|
|
59
|
+
"parse_dsn",
|
|
60
|
+
"register_audit_sink",
|
|
61
|
+
"register_context_provider",
|
|
62
|
+
"register_grant_store",
|
|
63
|
+
"register_policy_source",
|
|
64
|
+
"registrations",
|
|
65
|
+
"remember",
|
|
66
|
+
"resolve",
|
|
67
|
+
]
|
|
68
|
+
|
|
69
|
+
PluginKind = Literal["policy_source", "grant_store", "audit_sink", "context_provider"]
|
|
70
|
+
"""The four extension points."""
|
|
71
|
+
|
|
72
|
+
Configured: TypeAlias = "str | object | Sequence[str | object]"
|
|
73
|
+
"""How a backend can be named: a DSN, a built backend, or a sequence mixing the two.
|
|
74
|
+
|
|
75
|
+
Deliberately not narrowed to each Protocol. The four ``build_*`` functions share one
|
|
76
|
+
normalization path, and a caller who passes something that satisfies no contract gets a
|
|
77
|
+
:class:`~sentrykit.errors.ConfigurationError` naming the protocol it failed — which is a
|
|
78
|
+
better error than a type checker's, and the only one available to a host wiring itself from a
|
|
79
|
+
config file at runtime.
|
|
80
|
+
"""
|
|
81
|
+
|
|
82
|
+
ENTRY_POINT_GROUPS: Final[Mapping[PluginKind, str]] = {
|
|
83
|
+
"policy_source": "sentrykit.policy_sources",
|
|
84
|
+
"grant_store": "sentrykit.grant_stores",
|
|
85
|
+
"audit_sink": "sentrykit.audit_sinks",
|
|
86
|
+
"context_provider": "sentrykit.context_providers",
|
|
87
|
+
}
|
|
88
|
+
"""Entry-point group per kind. A third-party package publishes into one of these."""
|
|
89
|
+
|
|
90
|
+
T = TypeVar("T")
|
|
91
|
+
|
|
92
|
+
_TRUTHY: Final[frozenset[str]] = frozenset({"true", "1", "yes", "on"})
|
|
93
|
+
_FALSEY: Final[frozenset[str]] = frozenset({"false", "0", "no", "off"})
|
|
94
|
+
|
|
95
|
+
_REGISTRY: Final[dict[PluginKind, dict[str, RegisteredPlugin]]] = {
|
|
96
|
+
kind: {} for kind in ENTRY_POINT_GROUPS
|
|
97
|
+
}
|
|
98
|
+
"""In-process registrations, by kind and name. Populated by the ``register_*`` decorators."""
|
|
99
|
+
|
|
100
|
+
_DISCOVERED: Final[set[PluginKind]] = set()
|
|
101
|
+
"""Kinds whose entry points have already been swept, so discovery runs at most once each."""
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
@dataclass(frozen=True, slots=True)
|
|
105
|
+
class DSN:
|
|
106
|
+
"""A parsed backend address.
|
|
107
|
+
|
|
108
|
+
Parsed by hand rather than with :func:`urllib.parse.urlsplit`, because the targets are
|
|
109
|
+
often filesystem paths and this library ships for ``win-64``: a URL parser reads the
|
|
110
|
+
``D:`` of ``file://D:/policies`` as a scheme-relative host and mangles it. Splitting on
|
|
111
|
+
the first ``://`` and the first ``?`` keeps a Windows path intact, which matters more here
|
|
112
|
+
than RFC conformance for addresses only sentrykit ever reads.
|
|
113
|
+
|
|
114
|
+
Attributes:
|
|
115
|
+
scheme: The registered backend name — ``jsonl``, ``file``, ``memory``.
|
|
116
|
+
target: Everything between the scheme and the query. Usually a path; may be empty
|
|
117
|
+
(``memory://``).
|
|
118
|
+
options: Query parameters, as strings.
|
|
119
|
+
raw: The DSN exactly as given, for error messages and provenance.
|
|
120
|
+
"""
|
|
121
|
+
|
|
122
|
+
scheme: str
|
|
123
|
+
target: str = ""
|
|
124
|
+
options: Mapping[str, str] = field(default_factory=dict)
|
|
125
|
+
raw: str = ""
|
|
126
|
+
|
|
127
|
+
def option(self, name: str, default: str | None = None) -> str | None:
|
|
128
|
+
"""Return one option, or ``default`` when it is absent."""
|
|
129
|
+
return self.options.get(name, default)
|
|
130
|
+
|
|
131
|
+
def flag(self, name: str, default: bool = False) -> bool:
|
|
132
|
+
"""Read an option as a boolean.
|
|
133
|
+
|
|
134
|
+
``true``/``1``/``yes``/``on`` are true, ``false``/``0``/``no``/``off`` are false, in
|
|
135
|
+
any case.
|
|
136
|
+
|
|
137
|
+
Raises:
|
|
138
|
+
ConfigurationError: If the value is present but is neither. A typo in
|
|
139
|
+
``?fsync=ture`` silently meaning "no" is exactly the kind of durability
|
|
140
|
+
setting that must not fail quietly.
|
|
141
|
+
"""
|
|
142
|
+
raw = self.options.get(name)
|
|
143
|
+
if raw is None:
|
|
144
|
+
return default
|
|
145
|
+
lowered = raw.strip().lower()
|
|
146
|
+
if lowered in _TRUTHY:
|
|
147
|
+
return True
|
|
148
|
+
if lowered in _FALSEY:
|
|
149
|
+
return False
|
|
150
|
+
raise ConfigurationError(
|
|
151
|
+
f"option {name!r} in {self.raw!r} is {raw!r}, which is not a boolean"
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
def integer(self, name: str, default: int | None = None) -> int | None:
|
|
155
|
+
"""Read an option as an integer.
|
|
156
|
+
|
|
157
|
+
Raises:
|
|
158
|
+
ConfigurationError: If the value is present and not an integer.
|
|
159
|
+
"""
|
|
160
|
+
raw = self.options.get(name)
|
|
161
|
+
if raw is None:
|
|
162
|
+
return default
|
|
163
|
+
try:
|
|
164
|
+
return int(raw.strip())
|
|
165
|
+
except ValueError as exc:
|
|
166
|
+
raise ConfigurationError(
|
|
167
|
+
f"option {name!r} in {self.raw!r} is {raw!r}, which is not an integer"
|
|
168
|
+
) from exc
|
|
169
|
+
|
|
170
|
+
|
|
171
|
+
def parse_dsn(dsn: str) -> DSN:
|
|
172
|
+
"""Parse a backend address.
|
|
173
|
+
|
|
174
|
+
Args:
|
|
175
|
+
dsn: ``scheme://target?key=value&key2=value2``. A bare name (``memory``) is accepted
|
|
176
|
+
and read as ``memory://``, since a schemeless backend with no target is common
|
|
177
|
+
enough that requiring the punctuation is just friction.
|
|
178
|
+
|
|
179
|
+
Returns:
|
|
180
|
+
The parsed address.
|
|
181
|
+
|
|
182
|
+
Raises:
|
|
183
|
+
ConfigurationError: If the string carries no usable scheme.
|
|
184
|
+
"""
|
|
185
|
+
text = dsn.strip()
|
|
186
|
+
if not text:
|
|
187
|
+
raise ConfigurationError("a backend DSN cannot be empty")
|
|
188
|
+
|
|
189
|
+
scheme, separator, remainder = text.partition("://")
|
|
190
|
+
if not separator:
|
|
191
|
+
# A bare name. Only meaningful when it *is* just a name -- anything carrying a path
|
|
192
|
+
# or a query without a scheme is a typo, and guessing at it would wire the host to a
|
|
193
|
+
# backend it did not ask for.
|
|
194
|
+
if "/" in text or "?" in text or ":" in text:
|
|
195
|
+
raise ConfigurationError(f"cannot parse backend DSN {dsn!r}; expected scheme://target")
|
|
196
|
+
scheme, remainder = text, ""
|
|
197
|
+
|
|
198
|
+
scheme = scheme.strip().lower()
|
|
199
|
+
if not scheme:
|
|
200
|
+
raise ConfigurationError(f"cannot parse backend DSN {dsn!r}; it names no scheme")
|
|
201
|
+
|
|
202
|
+
target, _, query = remainder.partition("?")
|
|
203
|
+
options: dict[str, str] = {}
|
|
204
|
+
for pair in query.split("&"):
|
|
205
|
+
if not pair:
|
|
206
|
+
continue
|
|
207
|
+
key, _, value = pair.partition("=")
|
|
208
|
+
options[unquote(key.strip())] = unquote(value.strip())
|
|
209
|
+
return DSN(scheme=scheme, target=unquote(target), options=options, raw=text)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
@dataclass(frozen=True, slots=True)
|
|
213
|
+
class RegisteredPlugin:
|
|
214
|
+
"""One registered backend, however it got here.
|
|
215
|
+
|
|
216
|
+
Attributes:
|
|
217
|
+
kind: Which extension point it plugs into.
|
|
218
|
+
name: The DSN scheme it answers to.
|
|
219
|
+
factory: Callable taking a :class:`DSN` and returning an instance. For a class
|
|
220
|
+
registered directly this is its ``from_dsn`` classmethod.
|
|
221
|
+
distribution: The distribution that supplied it (``sentrykit``, ``sentrykit-splunk``),
|
|
222
|
+
when discovery knows — ``EntryPoint.dist`` may be absent.
|
|
223
|
+
version: That distribution's version, when known.
|
|
224
|
+
source: ``builtin`` for an in-process registration, ``entry-point`` for a discovered
|
|
225
|
+
one. Recorded for diagnostics only: the core treats the two identically, which is
|
|
226
|
+
the whole point of the registry.
|
|
227
|
+
"""
|
|
228
|
+
|
|
229
|
+
kind: PluginKind
|
|
230
|
+
name: str
|
|
231
|
+
factory: Callable[[DSN], object]
|
|
232
|
+
distribution: str | None = None
|
|
233
|
+
version: str | None = None
|
|
234
|
+
source: Literal["builtin", "entry-point"] = "builtin"
|
|
235
|
+
|
|
236
|
+
|
|
237
|
+
def register_policy_source(name: str) -> Callable[[type[T]], type[T]]:
|
|
238
|
+
"""Register a :class:`~sentrykit.stores.base.PolicySource` under a DSN scheme.
|
|
239
|
+
|
|
240
|
+
The decorated class must expose ``from_dsn(cls, dsn: DSN) -> Self``.
|
|
241
|
+
|
|
242
|
+
Args:
|
|
243
|
+
name: The DSN scheme, e.g. ``file``.
|
|
244
|
+
|
|
245
|
+
Returns:
|
|
246
|
+
The decorator, which returns the class unchanged.
|
|
247
|
+
|
|
248
|
+
Raises:
|
|
249
|
+
ConfigurationError: If ``name`` is already registered for this kind by a *different*
|
|
250
|
+
class. Re-registering the same class is a no-op, so module reimport is harmless.
|
|
251
|
+
"""
|
|
252
|
+
return _register("policy_source", name)
|
|
253
|
+
|
|
254
|
+
|
|
255
|
+
def register_grant_store(name: str) -> Callable[[type[T]], type[T]]:
|
|
256
|
+
"""Register a :class:`~sentrykit.stores.base.GrantStore` under a DSN scheme.
|
|
257
|
+
|
|
258
|
+
See :func:`register_policy_source` for the contract.
|
|
259
|
+
"""
|
|
260
|
+
return _register("grant_store", name)
|
|
261
|
+
|
|
262
|
+
|
|
263
|
+
def register_audit_sink(name: str) -> Callable[[type[T]], type[T]]:
|
|
264
|
+
"""Register an :class:`~sentrykit.stores.base.AuditSink` under a DSN scheme.
|
|
265
|
+
|
|
266
|
+
See :func:`register_policy_source` for the contract.
|
|
267
|
+
"""
|
|
268
|
+
return _register("audit_sink", name)
|
|
269
|
+
|
|
270
|
+
|
|
271
|
+
def register_context_provider(name: str) -> Callable[[type[T]], type[T]]:
|
|
272
|
+
"""Register a :class:`~sentrykit.stores.base.ContextProvider` under a DSN scheme.
|
|
273
|
+
|
|
274
|
+
See :func:`register_policy_source` for the contract.
|
|
275
|
+
"""
|
|
276
|
+
return _register("context_provider", name)
|
|
277
|
+
|
|
278
|
+
|
|
279
|
+
def _register(kind: PluginKind, name: str) -> Callable[[type[T]], type[T]]:
|
|
280
|
+
"""Build the decorator the four public ``register_*`` functions return.
|
|
281
|
+
|
|
282
|
+
One implementation for all four kinds, because adding a sink and adding a framework are
|
|
283
|
+
meant to be the same task -- if the registration paths diverged, they would not be.
|
|
284
|
+
|
|
285
|
+
Args:
|
|
286
|
+
kind: Which extension point.
|
|
287
|
+
name: The DSN scheme.
|
|
288
|
+
|
|
289
|
+
Returns:
|
|
290
|
+
A decorator returning its class unchanged, so a registered class is still an ordinary
|
|
291
|
+
class its own tests can construct directly.
|
|
292
|
+
"""
|
|
293
|
+
scheme = name.strip().lower()
|
|
294
|
+
if not scheme:
|
|
295
|
+
raise ConfigurationError(f"a {kind} must be registered under a non-empty name")
|
|
296
|
+
|
|
297
|
+
def decorate(cls: type[T]) -> type[T]:
|
|
298
|
+
"""Record ``cls`` as the backend answering to ``scheme``."""
|
|
299
|
+
factory = getattr(cls, "from_dsn", None)
|
|
300
|
+
if not callable(factory):
|
|
301
|
+
raise ConfigurationError(
|
|
302
|
+
f"{cls.__qualname__} cannot be registered as a {kind} named {scheme!r}: "
|
|
303
|
+
"it has no from_dsn(dsn) classmethod"
|
|
304
|
+
)
|
|
305
|
+
existing = _REGISTRY[kind].get(scheme)
|
|
306
|
+
if existing is not None and getattr(existing.factory, "__self__", None) is not cls:
|
|
307
|
+
raise ConfigurationError(
|
|
308
|
+
f"a {kind} named {scheme!r} is already registered "
|
|
309
|
+
f"({existing.name} from {existing.source})"
|
|
310
|
+
)
|
|
311
|
+
_REGISTRY[kind][scheme] = RegisteredPlugin(kind=kind, name=scheme, factory=factory)
|
|
312
|
+
_LOGGER.debug("Registered %s %r from %s", kind, scheme, cls.__qualname__)
|
|
313
|
+
return cls
|
|
314
|
+
|
|
315
|
+
return decorate
|
|
316
|
+
|
|
317
|
+
|
|
318
|
+
def registrations(kind: PluginKind) -> Mapping[str, RegisteredPlugin]:
|
|
319
|
+
"""Return the in-process registrations for ``kind``, without triggering discovery.
|
|
320
|
+
|
|
321
|
+
Exposed for :func:`resolve` and for tests that need to see the registry as it stands.
|
|
322
|
+
"""
|
|
323
|
+
return _REGISTRY[kind]
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def remember(plugin: RegisteredPlugin) -> None:
|
|
327
|
+
"""Cache a discovered registration so the entry-point sweep runs once per kind.
|
|
328
|
+
|
|
329
|
+
An in-process registration always wins: a host that has explicitly registered a backend
|
|
330
|
+
has said which one it wants, and an installed package must not quietly replace it.
|
|
331
|
+
"""
|
|
332
|
+
_REGISTRY[plugin.kind].setdefault(plugin.name, plugin)
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def resolve(kind: PluginKind, name: str) -> RegisteredPlugin:
|
|
336
|
+
"""Find the backend registered as ``name``, discovering entry points if needed.
|
|
337
|
+
|
|
338
|
+
In-process registrations win over entry points, so a host can override a shipped backend
|
|
339
|
+
without uninstalling the package that provides it.
|
|
340
|
+
|
|
341
|
+
Args:
|
|
342
|
+
kind: Which extension point.
|
|
343
|
+
name: The DSN scheme.
|
|
344
|
+
|
|
345
|
+
Returns:
|
|
346
|
+
The registration.
|
|
347
|
+
|
|
348
|
+
Raises:
|
|
349
|
+
ConfigurationError: If nothing answers to that name. The message lists what *is*
|
|
350
|
+
available, because "unknown sink 'jsonl1'" with no list is a bad afternoon.
|
|
351
|
+
"""
|
|
352
|
+
scheme = name.strip().lower()
|
|
353
|
+
registered = _REGISTRY[kind]
|
|
354
|
+
plugin = registered.get(scheme)
|
|
355
|
+
if plugin is None and kind not in _DISCOVERED:
|
|
356
|
+
# Only sweep on a miss, and only once: ``EntryPoint.load()`` imports the plugin's
|
|
357
|
+
# module, so an eager sweep would pull every installed backend into every process.
|
|
358
|
+
discovered(kind)
|
|
359
|
+
plugin = registered.get(scheme)
|
|
360
|
+
if plugin is None:
|
|
361
|
+
known = ", ".join(sorted(registered)) or "none registered"
|
|
362
|
+
raise ConfigurationError(f"no {kind} is registered as {scheme!r}; available: {known}")
|
|
363
|
+
return plugin
|
|
364
|
+
|
|
365
|
+
|
|
366
|
+
def available(kind: PluginKind) -> tuple[str, ...]:
|
|
367
|
+
"""List every backend name available for ``kind``, discovering entry points.
|
|
368
|
+
|
|
369
|
+
Args:
|
|
370
|
+
kind: Which extension point.
|
|
371
|
+
|
|
372
|
+
Returns:
|
|
373
|
+
The names, sorted.
|
|
374
|
+
"""
|
|
375
|
+
if kind not in _DISCOVERED:
|
|
376
|
+
discovered(kind)
|
|
377
|
+
return tuple(sorted(_REGISTRY[kind]))
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def clear_registry(kind: PluginKind | None = None) -> None:
|
|
381
|
+
"""Drop registrations and the discovery cache.
|
|
382
|
+
|
|
383
|
+
For tests, and for a host that installs a plugin at runtime. Built-ins re-register on
|
|
384
|
+
their module's next import, so this is not a way to permanently remove one.
|
|
385
|
+
|
|
386
|
+
Args:
|
|
387
|
+
kind: Which extension point to clear, or ``None`` for all of them.
|
|
388
|
+
"""
|
|
389
|
+
kinds: tuple[PluginKind, ...] = tuple(ENTRY_POINT_GROUPS) if kind is None else (kind,)
|
|
390
|
+
for one in kinds:
|
|
391
|
+
_REGISTRY[one].clear()
|
|
392
|
+
# Drop the sweep marker too, or the next ``resolve`` would trust an empty registry.
|
|
393
|
+
_DISCOVERED.discard(one)
|
|
394
|
+
|
|
395
|
+
|
|
396
|
+
def build_policy_source(dsn: Configured | None) -> PolicySource | None:
|
|
397
|
+
"""Build a policy source from one DSN, or a composite from several.
|
|
398
|
+
|
|
399
|
+
Multiplicity is a composite that satisfies the same Protocol, so the core always holds
|
|
400
|
+
exactly one source and never learns how many were configured.
|
|
401
|
+
|
|
402
|
+
Args:
|
|
403
|
+
dsn: One DSN, several, an already-built source, a mix of the two, or ``None``.
|
|
404
|
+
|
|
405
|
+
Returns:
|
|
406
|
+
The single source when one DSN was given, a
|
|
407
|
+
:class:`~sentrykit.stores.composite.CompositePolicySource` when several were, and
|
|
408
|
+
``None`` when none were.
|
|
409
|
+
|
|
410
|
+
Raises:
|
|
411
|
+
ConfigurationError: If a scheme is unknown or a backend rejects its DSN.
|
|
412
|
+
"""
|
|
413
|
+
addresses = _addresses(dsn)
|
|
414
|
+
if not addresses:
|
|
415
|
+
return None
|
|
416
|
+
sources: list[PolicySource] = [
|
|
417
|
+
cast("PolicySource", _resolve("policy_source", member, PolicySource, "PolicySource"))
|
|
418
|
+
for member in addresses
|
|
419
|
+
]
|
|
420
|
+
if len(sources) == 1:
|
|
421
|
+
return sources[0]
|
|
422
|
+
from sentrykit.stores.composite import CompositePolicySource
|
|
423
|
+
|
|
424
|
+
return CompositePolicySource(sources)
|
|
425
|
+
|
|
426
|
+
|
|
427
|
+
def build_grant_store(dsn: Configured | None) -> GrantStore | None:
|
|
428
|
+
"""Build a grant store from one DSN, or a composite from several.
|
|
429
|
+
|
|
430
|
+
Several stores merge by precedence — earlier DSNs win — unless every one of them declares
|
|
431
|
+
a namespace, in which case the composite routes by namespace instead. See
|
|
432
|
+
:class:`~sentrykit.stores.composite.CompositeGrantStore`.
|
|
433
|
+
|
|
434
|
+
Args:
|
|
435
|
+
dsn: One DSN, several, or ``None``.
|
|
436
|
+
|
|
437
|
+
Returns:
|
|
438
|
+
The store, the composite, or ``None``.
|
|
439
|
+
|
|
440
|
+
Raises:
|
|
441
|
+
ConfigurationError: If a scheme is unknown or a backend rejects its DSN.
|
|
442
|
+
"""
|
|
443
|
+
addresses = _addresses(dsn)
|
|
444
|
+
if not addresses:
|
|
445
|
+
return None
|
|
446
|
+
stores: list[GrantStore] = [
|
|
447
|
+
cast("GrantStore", _resolve("grant_store", member, GrantStore, "GrantStore"))
|
|
448
|
+
for member in addresses
|
|
449
|
+
]
|
|
450
|
+
if len(stores) == 1:
|
|
451
|
+
return stores[0]
|
|
452
|
+
from sentrykit.stores.composite import CompositeGrantStore
|
|
453
|
+
|
|
454
|
+
return CompositeGrantStore(stores)
|
|
455
|
+
|
|
456
|
+
|
|
457
|
+
def build_audit_sink(dsn: Configured | None) -> AuditSink | None:
|
|
458
|
+
"""Build an audit sink from one DSN, or a fan-out composite from several.
|
|
459
|
+
|
|
460
|
+
Args:
|
|
461
|
+
dsn: One DSN, several, or ``None``. The error policy for a fan-out is a DSN option on
|
|
462
|
+
the *first* sink (``?on_error=primary-durable`` or ``?on_error=all-or-nothing``).
|
|
463
|
+
|
|
464
|
+
Returns:
|
|
465
|
+
The sink, the composite, or ``None`` when none were configured — which leaves
|
|
466
|
+
auditing off rather than silently discarding records into a null sink.
|
|
467
|
+
|
|
468
|
+
Raises:
|
|
469
|
+
ConfigurationError: If a scheme is unknown or a backend rejects its DSN.
|
|
470
|
+
"""
|
|
471
|
+
addresses = _addresses(dsn)
|
|
472
|
+
if not addresses:
|
|
473
|
+
return None
|
|
474
|
+
# Read the fan-out policy before building anything: a typo in ``?on_error=`` should be a
|
|
475
|
+
# wiring error, not a surprise the first time a replica goes down.
|
|
476
|
+
from sentrykit.stores.composite import AUDIT_ERROR_POLICIES, CompositeAuditSink
|
|
477
|
+
|
|
478
|
+
first = addresses[0]
|
|
479
|
+
# Only a DSN can carry the option; a caller passing a built sink first has no way to
|
|
480
|
+
# spell it, so the default stands rather than the wiring failing on their behalf.
|
|
481
|
+
requested = (
|
|
482
|
+
parse_dsn(first).option("on_error", "primary-durable") or ""
|
|
483
|
+
if isinstance(first, str)
|
|
484
|
+
else "primary-durable"
|
|
485
|
+
)
|
|
486
|
+
on_error = AUDIT_ERROR_POLICIES.get(requested)
|
|
487
|
+
if on_error is None:
|
|
488
|
+
known = ", ".join(sorted(AUDIT_ERROR_POLICIES))
|
|
489
|
+
raise ConfigurationError(
|
|
490
|
+
f"audit sink option 'on_error' in {first!r} is {requested!r}; expected {known}"
|
|
491
|
+
)
|
|
492
|
+
sinks: list[AuditSink] = [
|
|
493
|
+
cast("AuditSink", _resolve("audit_sink", member, AuditSink, "AuditSink"))
|
|
494
|
+
for member in addresses
|
|
495
|
+
]
|
|
496
|
+
if len(sinks) == 1:
|
|
497
|
+
return sinks[0]
|
|
498
|
+
return CompositeAuditSink(sinks, on_error=on_error)
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def build_context_provider(dsn: Configured | None) -> ContextProvider | None:
|
|
502
|
+
"""Build a framework context provider. Phases 3 and 4 supply the implementations.
|
|
503
|
+
|
|
504
|
+
Args:
|
|
505
|
+
dsn: One DSN, several, or ``None``.
|
|
506
|
+
|
|
507
|
+
Returns:
|
|
508
|
+
The provider, or ``None``.
|
|
509
|
+
|
|
510
|
+
Raises:
|
|
511
|
+
ConfigurationError: If a scheme is unknown.
|
|
512
|
+
"""
|
|
513
|
+
addresses = _addresses(dsn)
|
|
514
|
+
if not addresses:
|
|
515
|
+
return None
|
|
516
|
+
if len(addresses) > 1:
|
|
517
|
+
# There is no composite provider, and inventing one would have to guess which
|
|
518
|
+
# framework owns an incoming request. A process wires the provider for the boundary
|
|
519
|
+
# it actually serves.
|
|
520
|
+
raise ConfigurationError(
|
|
521
|
+
f"only one context provider can be configured, but {len(addresses)} were given: "
|
|
522
|
+
f"{', '.join(str(address) for address in addresses)}"
|
|
523
|
+
)
|
|
524
|
+
resolved = _resolve("context_provider", addresses[0], ContextProvider, "ContextProvider")
|
|
525
|
+
return cast("ContextProvider", resolved)
|
|
526
|
+
|
|
527
|
+
|
|
528
|
+
def discovered(kind: PluginKind) -> Iterable[RegisteredPlugin]:
|
|
529
|
+
"""Enumerate the entry-point registrations for ``kind``, loading each one.
|
|
530
|
+
|
|
531
|
+
Exposed so a host can inspect what is installed — and so the plugin test can assert that
|
|
532
|
+
a third-party distribution reaches the registry with no change to sentrykit.
|
|
533
|
+
|
|
534
|
+
Args:
|
|
535
|
+
kind: Which extension point.
|
|
536
|
+
|
|
537
|
+
Returns:
|
|
538
|
+
The discovered registrations. A plugin whose module fails to import is skipped with
|
|
539
|
+
an ``ERROR`` log rather than breaking every other backend.
|
|
540
|
+
"""
|
|
541
|
+
found: list[RegisteredPlugin] = []
|
|
542
|
+
# Always ``group=``: the bare call is the one spelling whose return type differs across
|
|
543
|
+
# 3.11--3.13. The result is only ever iterated -- it is a ``list`` subclass on 3.11 and a
|
|
544
|
+
# ``tuple`` subclass on 3.12+ -- and an unknown group comes back empty rather than raising.
|
|
545
|
+
for entry_point in metadata.entry_points(group=ENTRY_POINT_GROUPS[kind]):
|
|
546
|
+
try:
|
|
547
|
+
loaded = entry_point.load()
|
|
548
|
+
except Exception:
|
|
549
|
+
# One broken plugin must not take out every other backend: an unimportable sink
|
|
550
|
+
# is that distribution's problem, not a reason to leave the host with no audit.
|
|
551
|
+
_LOGGER.exception(
|
|
552
|
+
"Could not load %s plugin %r from %r; skipping it",
|
|
553
|
+
kind,
|
|
554
|
+
entry_point.name,
|
|
555
|
+
entry_point.value,
|
|
556
|
+
)
|
|
557
|
+
continue
|
|
558
|
+
factory = getattr(loaded, "from_dsn", None)
|
|
559
|
+
if not callable(factory):
|
|
560
|
+
_LOGGER.error(
|
|
561
|
+
"The %s plugin %r (%r) has no from_dsn(dsn) classmethod; skipping it",
|
|
562
|
+
kind,
|
|
563
|
+
entry_point.name,
|
|
564
|
+
entry_point.value,
|
|
565
|
+
)
|
|
566
|
+
continue
|
|
567
|
+
distribution = entry_point.dist
|
|
568
|
+
plugin = RegisteredPlugin(
|
|
569
|
+
kind=kind,
|
|
570
|
+
name=entry_point.name.strip().lower(),
|
|
571
|
+
factory=factory,
|
|
572
|
+
# ``EntryPoint.dist`` is typed ``Distribution | None``, so both hops are guarded.
|
|
573
|
+
distribution=getattr(distribution, "name", None) if distribution is not None else None,
|
|
574
|
+
version=getattr(distribution, "version", None) if distribution is not None else None,
|
|
575
|
+
source="entry-point",
|
|
576
|
+
)
|
|
577
|
+
remember(plugin)
|
|
578
|
+
found.append(plugin)
|
|
579
|
+
_DISCOVERED.add(kind)
|
|
580
|
+
return tuple(found)
|
|
581
|
+
|
|
582
|
+
|
|
583
|
+
def _addresses(dsn: Configured | None) -> tuple[object, ...]:
|
|
584
|
+
"""Normalize the ways a backend can be configured into a tuple of members.
|
|
585
|
+
|
|
586
|
+
A lone string is one DSN rather than a sequence of characters, which is the whole reason
|
|
587
|
+
this is a function and not an inline ``tuple(dsn)``. A member is either a DSN to build or
|
|
588
|
+
an already-built backend to use as it stands — see :func:`_resolve` for why both.
|
|
589
|
+
"""
|
|
590
|
+
if dsn is None:
|
|
591
|
+
return ()
|
|
592
|
+
if isinstance(dsn, str):
|
|
593
|
+
return (dsn,)
|
|
594
|
+
if isinstance(dsn, Sequence):
|
|
595
|
+
return tuple(dsn)
|
|
596
|
+
return (dsn,)
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def _resolve(kind: PluginKind, member: object, protocol: type, name: str) -> object:
|
|
600
|
+
"""Turn one configured member into a backend satisfying ``protocol``.
|
|
601
|
+
|
|
602
|
+
A string is a DSN and gets built; anything else is taken to be a backend already. Mixing
|
|
603
|
+
the two in one sequence is the point: composing the shipped policy pack with a source the
|
|
604
|
+
host constructed itself — ``[PackPolicySource(), LinkedPolicySource(links)]``, or
|
|
605
|
+
``["pack://", my_source]`` — is an ordinary thing to want, and requiring every member of a
|
|
606
|
+
union to be expressible as a DSN would put a backend holding live credentials or
|
|
607
|
+
in-memory state out of reach of the union entirely.
|
|
608
|
+
|
|
609
|
+
Args:
|
|
610
|
+
kind: Which extension point.
|
|
611
|
+
member: A DSN string, or a built backend.
|
|
612
|
+
protocol: The Protocol the result must satisfy.
|
|
613
|
+
name: The protocol's name, for the error message.
|
|
614
|
+
|
|
615
|
+
Returns:
|
|
616
|
+
The backend.
|
|
617
|
+
|
|
618
|
+
Raises:
|
|
619
|
+
ConfigurationError: If a DSN names an unknown scheme, a factory rejects it, or the
|
|
620
|
+
result does not satisfy ``protocol``.
|
|
621
|
+
"""
|
|
622
|
+
built = _instantiate(kind, member) if isinstance(member, str) else member
|
|
623
|
+
if not isinstance(built, protocol):
|
|
624
|
+
described = member if isinstance(member, str) else type(member).__name__
|
|
625
|
+
raise _unsatisfied(kind, str(described), name)
|
|
626
|
+
return built
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def _instantiate(kind: PluginKind, dsn: str) -> object:
|
|
630
|
+
"""Parse one DSN, resolve its backend, and build it.
|
|
631
|
+
|
|
632
|
+
Args:
|
|
633
|
+
kind: Which extension point.
|
|
634
|
+
dsn: The address.
|
|
635
|
+
|
|
636
|
+
Returns:
|
|
637
|
+
Whatever the backend's ``from_dsn`` returned, unchecked — the caller validates it
|
|
638
|
+
against the Protocol it is supposed to satisfy.
|
|
639
|
+
|
|
640
|
+
Raises:
|
|
641
|
+
ConfigurationError: If the DSN is unparseable, the scheme is unknown, or the factory
|
|
642
|
+
rejected the address.
|
|
643
|
+
"""
|
|
644
|
+
parsed = parse_dsn(dsn)
|
|
645
|
+
plugin = resolve(kind, parsed.scheme)
|
|
646
|
+
try:
|
|
647
|
+
return plugin.factory(parsed)
|
|
648
|
+
except ConfigurationError:
|
|
649
|
+
raise
|
|
650
|
+
except Exception as exc:
|
|
651
|
+
# A third-party factory can raise anything at all. The host asked to be *configured*,
|
|
652
|
+
# so a stranger's ``KeyError`` is reported as the configuration failure it is.
|
|
653
|
+
raise ConfigurationError(
|
|
654
|
+
f"the {kind} {parsed.scheme!r} could not be built from {parsed.raw!r}: {exc}"
|
|
655
|
+
) from exc
|
|
656
|
+
|
|
657
|
+
|
|
658
|
+
def _unsatisfied(kind: PluginKind, dsn: str, protocol: str) -> ConfigurationError:
|
|
659
|
+
"""Build the error for a backend that constructed but does not implement its contract.
|
|
660
|
+
|
|
661
|
+
Checked at wiring time on purpose: a sink missing ``query`` should fail when the process
|
|
662
|
+
starts, not when an auditor runs the yearly report.
|
|
663
|
+
"""
|
|
664
|
+
return ConfigurationError(
|
|
665
|
+
f"the {kind} built from {dsn!r} does not satisfy the {protocol} protocol"
|
|
666
|
+
)
|