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,479 @@
1
+ """Tool-manifest filtering: deciding what a principal is even *shown*.
2
+
3
+ The agent half of one-decorator-N-providers. A web provider has one job — establish context
4
+ at the boundary — because an HTTP client already knows which URLs exist. An agent boundary
5
+ has a second job: it tells the model what it may *attempt*, and that manifest is per-caller.
6
+
7
+ This module is the shared half of that, and it is deliberately framework-free. It imports no
8
+ `mcp` and no `pydantic_ai`; MCP's ``tools/list`` and Pydantic-AI's ``prepare`` are two
9
+ spellings of the same question, and they get one answer so they cannot drift apart.
10
+
11
+ ## The invariant
12
+
13
+ > **A tool is hidden from a principal if and only if invoking it would be refused by the
14
+ > authorization gate.**
15
+
16
+ Both halves matter, and the tests assert both together.
17
+
18
+ *Only if* — hiding is never the enforcement. The dispatch path runs the identical decision, so
19
+ a client that ignores the manifest and calls a hidden tool by name is refused exactly as if it
20
+ had never been hidden. Manifest filtering that *were* the enforcement would be a hole the
21
+ moment a caller skipped ``tools/list``, and "the model did not know the tool existed" is not
22
+ an access-control argument.
23
+
24
+ *If* — a tool the principal may invoke is never hidden. Hiding is a usability affordance: it
25
+ stops the model proposing calls that cannot succeed, burning turns and context on refusals it
26
+ could not have predicted. A filter that hid more than it had to would silently narrow what the
27
+ agent can do for its user.
28
+
29
+ ## Why "the gate" and not "the whole pipeline"
30
+
31
+ :meth:`~sentrykit.engine.Governor.plan` is run in full — this is the mechanism
32
+ :mod:`sentrykit.engine` was split for, in as many words — but its outcomes are read in two
33
+ groups:
34
+
35
+ * :class:`~sentrykit.errors.AuthzDenied` and :class:`~sentrykit.errors.NoContext` are about
36
+ **entitlement**. The principal may not perform this action at all, whatever they pass.
37
+ ⇒ hidden.
38
+ * :class:`~sentrykit.errors.DefaultUnavailable`,
39
+ :class:`~sentrykit.errors.NoValidArguments`,
40
+ :class:`~sentrykit.errors.ArgumentRejected` and
41
+ :class:`~sentrykit.errors.ValidationFailed` are about **arguments**, and the manifest probe
42
+ supplies none. A tool with a required parameter and no policy default raises
43
+ ``DefaultUnavailable`` for *everybody*; treating that as "denied" would hide every such tool
44
+ from every principal. ⇒ visible, and enforced on dispatch once the model has proposed
45
+ something to enforce against.
46
+
47
+ So the manifest answers the only question that is decidable before the model has proposed
48
+ anything, and the argument-level pipeline answers the rest at dispatch. That split is the
49
+ honest reading of the invariant above, and :data:`ENTITLEMENT_ERRORS` is the one place it is
50
+ written down.
51
+
52
+ ## An unprotected tool is not a governed tool
53
+
54
+ A callable with no ``@protect`` wrapper carries no action, no resource and no argument spec,
55
+ so there is nothing to decide about it. It is reported as :attr:`ToolDecision.governed`
56
+ ``False`` and left **visible**: sentrykit does not silently hide a tool its author never asked
57
+ it to govern, and pretending to have made a decision about one would be worse than saying so.
58
+ Hosts that want everything governed assert that themselves — which is a one-line test over
59
+ :func:`decide_tools`, and the shipped examples have it.
60
+ """
61
+
62
+ from __future__ import annotations
63
+
64
+ import functools
65
+ import inspect
66
+ import logging
67
+ from collections.abc import Callable, Iterable, Mapping, Sequence
68
+ from dataclasses import dataclass
69
+ from typing import Any, Final
70
+
71
+ from sentrykit.context import Principal
72
+ from sentrykit.decorator import ProtectedMeta, protected_meta
73
+ from sentrykit.engine import Governor, Plan, current_governor
74
+ from sentrykit.errors import AuthzDenied, ConfigurationError, NoContext, SentrykitError
75
+
76
+ __all__ = [
77
+ "ENTITLEMENT_ERRORS",
78
+ "ToolDecision",
79
+ "decide_tool",
80
+ "decide_tools",
81
+ "governed_meta",
82
+ "permitted_tools",
83
+ "proposable",
84
+ ]
85
+
86
+ _LOGGER: Final = logging.getLogger("sentrykit.integrations.tools")
87
+
88
+ ENTITLEMENT_ERRORS: Final[tuple[type[SentrykitError], ...]] = (AuthzDenied, NoContext)
89
+ """Refusals that mean *this principal may not do this at all*, so the tool is hidden.
90
+
91
+ Every other :class:`~sentrykit.errors.SentrykitError` is about the arguments of a particular
92
+ call, which a manifest probe has not got — see this module's docstring. Matched with
93
+ ``isinstance``, so a host subclassing one of these inherits its meaning.
94
+ """
95
+
96
+
97
+ @dataclass(frozen=True, slots=True)
98
+ class ToolDecision:
99
+ """What the shared gate concluded about one tool, for one principal.
100
+
101
+ Returned rather than a bare ``bool`` because the two agent providers need different parts
102
+ of it: MCP drops the hidden names from a ``tools/list`` result, Pydantic-AI returns
103
+ ``None`` from ``prepare`` for the same tools, and both want the refusal for a debug log
104
+ that explains *why* a tool the developer expected to see is missing.
105
+
106
+ Attributes:
107
+ name: The advertised tool name.
108
+ visible: Whether the tool should appear in this principal's manifest.
109
+ governed: Whether the underlying callable carries a ``@protect`` wrapper. ``False``
110
+ means no decision was made and :attr:`visible` is ``True`` by default — see the
111
+ module docstring.
112
+ error: The refusal that hid it, or the argument-level refusal that did not. ``None``
113
+ when planning succeeded or the tool is ungoverned.
114
+ plan: The successful plan, when there was one. Carries the action, the resource and
115
+ the principal's argument constraints, which is what an optional schema-narrowing
116
+ pass reads.
117
+ """
118
+
119
+ name: str
120
+ visible: bool
121
+ governed: bool
122
+ error: SentrykitError | None = None
123
+ plan: Plan | None = None
124
+
125
+
126
+ def governed_meta(fn: object) -> ProtectedMeta | None:
127
+ """Return the ``@protect`` metadata for a tool's callable, unwrapping one adapter layer.
128
+
129
+ An agent provider rarely registers the protected function itself. MCP registers a
130
+ :func:`proposable` shim; Pydantic-AI registers a ``ctx``-taking adapter around that shim,
131
+ which is **two** hops. Each layer records what it wraps under ``__wrapped__``, so the whole
132
+ chain is walked rather than a fixed number of links -- a filter that stopped one hop short
133
+ would read a governed tool as ungoverned and advertise it to everybody — exactly the
134
+ failure the manifest filter exists to prevent.
135
+
136
+ Args:
137
+ fn: The registered tool callable.
138
+
139
+ Returns:
140
+ The metadata, or ``None`` when nothing in the chain is protected.
141
+ """
142
+ # Bounded by identity rather than by a hop count: a chain that loops back on itself is a
143
+ # host's bug, and hanging inside a live tools/list would be a worse way to report it.
144
+ seen: set[int] = set()
145
+ current: object | None = fn
146
+ while current is not None and id(current) not in seen:
147
+ meta = protected_meta(current)
148
+ if meta is not None:
149
+ return meta
150
+ seen.add(id(current))
151
+ current = getattr(current, "__wrapped__", None)
152
+ return None
153
+
154
+
155
+ def _governor_for(name: str, meta: ProtectedMeta, governor: Governor | None) -> Governor:
156
+ """Resolve the governor a manifest probe decides against.
157
+
158
+ Same precedence as the decorator's: an explicitly passed governor, then one pinned to the
159
+ protected callable, then the process-installed one.
160
+
161
+ Args:
162
+ name: The tool name, for the error message.
163
+ meta: The protected callable's metadata.
164
+ governor: An explicitly supplied governor, or ``None``.
165
+
166
+ Returns:
167
+ The governor.
168
+
169
+ Raises:
170
+ ConfigurationError: If none can be resolved. Refusing here rather than defaulting to
171
+ "show everything" is the fail-closed rule applied to the manifest.
172
+ """
173
+ resolved = governor or meta.governor or current_governor()
174
+ if resolved is None:
175
+ raise ConfigurationError(
176
+ f"cannot decide whether to advertise the protected tool {name!r}: no governor is "
177
+ "installed; call install(...) before filtering a tool manifest"
178
+ )
179
+ return resolved
180
+
181
+
182
+ def decide_tool(
183
+ name: str,
184
+ fn: Callable[..., object],
185
+ *,
186
+ principal: Principal,
187
+ governor: Governor | None = None,
188
+ environment: Mapping[str, object] | None = None,
189
+ ) -> ToolDecision:
190
+ """Decide whether one tool belongs in ``principal``'s manifest.
191
+
192
+ Runs :meth:`~sentrykit.engine.Governor.plan` with **no proposed arguments** — the same
193
+ call the enforcement path makes, minus the arguments the model has not proposed yet — and
194
+ reads the outcome per this module's docstring.
195
+
196
+ Args:
197
+ name: The advertised tool name, for the returned decision and the logs.
198
+ fn: The registered callable. Unprotected callables are reported ungoverned and
199
+ visible.
200
+ principal: Who the manifest is for.
201
+ governor: The governor to decide against. Defaults to the one pinned to the protected
202
+ callable, and failing that to the process-installed one.
203
+ environment: Cedar request context for the probe, merged over the ambient
204
+ environment. A provider passes the same environment it would establish for a
205
+ dispatch, so a policy conditioning on ``context.channel`` sees ``agent`` here too.
206
+
207
+ Returns:
208
+ The decision.
209
+
210
+ Raises:
211
+ ConfigurationError: If ``fn`` is protected but no governor can be resolved. A manifest
212
+ that silently showed everything because nothing was installed would be the exact
213
+ failure the fail-closed rule exists to prevent.
214
+ """
215
+ meta = governed_meta(fn)
216
+ if meta is None:
217
+ return ToolDecision(name=name, visible=True, governed=False)
218
+
219
+ active = _governor_for(name, meta, governor)
220
+ try:
221
+ plan = active.plan(
222
+ meta.spec,
223
+ principal=principal,
224
+ action=meta.action,
225
+ resource=meta.resource,
226
+ # No proposed arguments: the model has not proposed any yet. This is what makes
227
+ # the probe answer an entitlement question and nothing else.
228
+ proposed=None,
229
+ environment=environment,
230
+ )
231
+ except ENTITLEMENT_ERRORS as exc:
232
+ _LOGGER.debug(
233
+ "Hiding tool from the manifest",
234
+ extra={
235
+ "tool": name,
236
+ "principal": str(principal.uid),
237
+ "action": str(meta.action),
238
+ "reason": type(exc).__name__,
239
+ },
240
+ )
241
+ return ToolDecision(name=name, visible=False, governed=True, error=exc)
242
+ except SentrykitError as exc:
243
+ # An argument-level refusal of an argument-free probe. It says nothing about whether
244
+ # this principal is entitled to the action, only that the call as probed is
245
+ # incomplete -- which every such call is. Advertise it; the dispatch path decides once
246
+ # the model has proposed something to decide about.
247
+ return ToolDecision(name=name, visible=True, governed=True, error=exc)
248
+ return ToolDecision(name=name, visible=True, governed=True, plan=plan)
249
+
250
+
251
+ def decide_tools(
252
+ tools: Mapping[str, Callable[..., object]] | Iterable[tuple[str, Callable[..., object]]],
253
+ *,
254
+ principal: Principal,
255
+ governor: Governor | None = None,
256
+ environment: Mapping[str, object] | None = None,
257
+ ) -> tuple[ToolDecision, ...]:
258
+ """Decide a whole manifest, in the order the tools were given.
259
+
260
+ Args:
261
+ tools: The registered tools, as a mapping or as ``(name, callable)`` pairs.
262
+ principal: Who the manifest is for.
263
+ governor: As for :func:`decide_tool`.
264
+ environment: As for :func:`decide_tool`.
265
+
266
+ Returns:
267
+ One decision per tool, in input order.
268
+
269
+ Raises:
270
+ ConfigurationError: As for :func:`decide_tool`.
271
+ """
272
+ entries = tools.items() if isinstance(tools, Mapping) else tools
273
+ return tuple(
274
+ decide_tool(name, fn, principal=principal, governor=governor, environment=environment)
275
+ for name, fn in entries
276
+ )
277
+
278
+
279
+ def permitted_tools(
280
+ tools: Mapping[str, Callable[..., object]] | Iterable[tuple[str, Callable[..., object]]],
281
+ *,
282
+ principal: Principal,
283
+ governor: Governor | None = None,
284
+ environment: Mapping[str, object] | None = None,
285
+ ) -> tuple[str, ...]:
286
+ """Return the names ``principal`` may be shown, in the order the tools were given.
287
+
288
+ The convenience form of :func:`decide_tools` for a caller that needs only the names.
289
+
290
+ Args:
291
+ tools: The registered tools, as a mapping or as ``(name, callable)`` pairs.
292
+ principal: Who the manifest is for.
293
+ governor: As for :func:`decide_tool`.
294
+ environment: As for :func:`decide_tool`.
295
+
296
+ Returns:
297
+ The permitted names.
298
+
299
+ Raises:
300
+ ConfigurationError: As for :func:`decide_tool`.
301
+ """
302
+ return tuple(
303
+ decision.name
304
+ for decision in decide_tools(
305
+ tools, principal=principal, governor=governor, environment=environment
306
+ )
307
+ if decision.visible
308
+ )
309
+
310
+
311
+ def _widened(label: str, name: str, annotation: object) -> object:
312
+ """Widen one parameter's annotation to admit the ``None`` that means *not proposed*.
313
+
314
+ Args:
315
+ label: The callable's qualified name, for the error message.
316
+ name: The parameter being widened.
317
+ annotation: Its resolved annotation, or :data:`inspect.Parameter.empty`.
318
+
319
+ Returns:
320
+ ``annotation | None``, or the annotation untouched when there was none to widen.
321
+
322
+ Raises:
323
+ ConfigurationError: If the annotation does not support ``|``. An unannotated parameter
324
+ is fine and common; one annotated with something that is not a type is a mistake in
325
+ the tool, and it surfaces here as the configuration error the docstring promises
326
+ rather than as a bare ``TypeError`` from inside a signature rebuild.
327
+ """
328
+ if annotation is inspect.Parameter.empty:
329
+ return annotation
330
+ try:
331
+ return annotation | None # type: ignore[operator]
332
+ except TypeError as exc:
333
+ raise ConfigurationError(
334
+ f"cannot make {name!r} on {label} omittable: its annotation {annotation!r} does "
335
+ f"not support `| None` ({exc})"
336
+ ) from exc
337
+
338
+
339
+ def proposable(
340
+ fn: Callable[..., Any],
341
+ *,
342
+ optional: Sequence[str] | None = None,
343
+ ) -> Callable[..., Any]:
344
+ """Re-declare a protected callable so a caller may **omit** the arguments policy supplies.
345
+
346
+ Both agent frameworks validate a proposal against the tool's advertised JSON schema
347
+ *before* dispatch, so an argument the schema marks ``required`` can never be left out and
348
+ can therefore never be filled in from the principal's defaults -- and that holds on each
349
+ of the two frameworks independently. Without this shim, default injection is unreachable
350
+ from an agent at all, which would leave one of the three things sentrykit does unusable at
351
+ the very boundary the agent integrations exist to govern.
352
+
353
+ This is the same move the FastAPI example already makes one layer out: its route declares
354
+ ``region: str | None = None`` and forwards only what the caller actually supplied. An
355
+ absent argument has to be *expressible at the boundary*, and on an agent boundary the
356
+ boundary is the tool signature.
357
+
358
+ The returned shim satisfies two introspections at once, which is the whole trick:
359
+
360
+ * :func:`inspect.signature` reports the **shim's** parameters, because a callable carrying
361
+ its own ``__signature__`` stops the unwrapping walk -- so the framework advertises the
362
+ optional schema; while
363
+ * :func:`inspect.unwrap` still reaches the protected callable through ``__wrapped__``, so
364
+ :func:`governed_meta` finds the ``@protect`` metadata and the manifest filter governs the
365
+ tool instead of waving it through as unprotected.
366
+
367
+ Every synthesized parameter is made **keyword-only**. Agent frameworks propose arguments by
368
+ name, so nothing is lost, and it removes the ordering trap where making one parameter
369
+ optional would leave a non-default parameter standing after a default one.
370
+
371
+ !!! warning
372
+ A parameter listed in ``optional`` cannot carry a meaningful ``None``: the shim reads
373
+ ``None`` as *not proposed* and drops it, exactly as the FastAPI example's
374
+ ``if region is not None`` does. Do not list a genuinely nullable parameter.
375
+
376
+ Args:
377
+ fn: The protected callable to register as a tool. Sync or async; the shim matches.
378
+ optional: Which parameters become omittable. Defaults to every parameter with no
379
+ Python-level default -- precisely the set whose value could only have come from
380
+ policy, and so precisely the set worth making omittable.
381
+
382
+ Returns:
383
+ The shim, to hand to ``@server.tool()`` or to
384
+ :func:`~sentrykit.integrations.pydantic_ai.tool_adapter`.
385
+
386
+ Raises:
387
+ ConfigurationError: If ``fn``'s signature cannot be introspected, or if ``optional``
388
+ names a parameter it does not declare or declares positional-only -- which could
389
+ not be proposed by name and so could not be omitted either.
390
+ """
391
+ label = getattr(fn, "__qualname__", repr(fn))
392
+ try:
393
+ # ``eval_str=True`` because every module here carries ``from __future__ import
394
+ # annotations``, so the raw annotations are *strings*. Two things then go wrong if they
395
+ # are left alone: ``str | None`` is a TypeError on a string, and the framework would
396
+ # later resolve the surviving forward references against the **shim's** ``__globals__``
397
+ # -- this module's -- rather than the tool's own. Resolving here, against ``fn``'s
398
+ # globals, removes both problems at once. It cannot fail for a callable ``@protect``
399
+ # accepted, since ArgumentSpec already resolved the same annotations at decoration.
400
+ signature = inspect.signature(fn, eval_str=True)
401
+ except (TypeError, ValueError, NameError, AttributeError) as exc:
402
+ raise ConfigurationError(f"cannot introspect the signature of {label}: {exc}") from exc
403
+
404
+ # ``*args``/``**kwargs`` are not parameters a caller proposes by name, and the engine's own
405
+ # ArgumentSpec does not model them either.
406
+ declared = {
407
+ key: parameter
408
+ for key, parameter in signature.parameters.items()
409
+ if parameter.kind not in (inspect.Parameter.VAR_POSITIONAL, inspect.Parameter.VAR_KEYWORD)
410
+ }
411
+
412
+ if optional is None:
413
+ chosen: tuple[str, ...] = tuple(
414
+ key
415
+ for key, parameter in declared.items()
416
+ if parameter.default is inspect.Parameter.empty
417
+ )
418
+ else:
419
+ chosen = tuple(optional)
420
+ unknown = sorted(key for key in chosen if key not in declared)
421
+ if unknown:
422
+ raise ConfigurationError(
423
+ f"{label} declares no proposable parameter named {', '.join(unknown)}; "
424
+ f"it declares {', '.join(declared) or 'none'}"
425
+ )
426
+ positional = sorted(
427
+ key for key in chosen if declared[key].kind is inspect.Parameter.POSITIONAL_ONLY
428
+ )
429
+ if positional:
430
+ raise ConfigurationError(
431
+ f"{label} declares {', '.join(positional)} positional-only, so it cannot be "
432
+ "proposed by name and cannot be made omittable"
433
+ )
434
+
435
+ omittable = frozenset(chosen)
436
+ parameters = [
437
+ parameter.replace(
438
+ kind=inspect.Parameter.KEYWORD_ONLY,
439
+ default=None if key in omittable else parameter.default,
440
+ annotation=(
441
+ _widened(label, key, parameter.annotation)
442
+ if key in omittable
443
+ else parameter.annotation
444
+ ),
445
+ )
446
+ for key, parameter in declared.items()
447
+ ]
448
+
449
+ def winnow(proposed: Mapping[str, object]) -> dict[str, object]:
450
+ """Drop the omittable arguments the caller did not actually propose."""
451
+ return {
452
+ key: value
453
+ for key, value in proposed.items()
454
+ if not (key in omittable and value is None)
455
+ }
456
+
457
+ shim: Callable[..., Any]
458
+ if inspect.iscoroutinefunction(fn):
459
+
460
+ async def async_shim(**proposed: object) -> object:
461
+ """Forward only the genuinely proposed arguments to the protected coroutine."""
462
+ return await fn(**winnow(proposed))
463
+
464
+ shim = async_shim
465
+ else:
466
+
467
+ def sync_shim(**proposed: object) -> object:
468
+ """Forward only the genuinely proposed arguments to the protected callable."""
469
+ return fn(**winnow(proposed))
470
+
471
+ shim = sync_shim
472
+
473
+ # ``update_wrapper`` copies __name__/__qualname__/__doc__/__module__/__dict__ and sets
474
+ # __wrapped__, which is the half :func:`governed_meta` needs. The explicit __signature__ is
475
+ # the half the framework needs, and it has to be set *after*, because it is the marker that
476
+ # stops ``inspect.signature`` walking __wrapped__ back to the required parameters.
477
+ functools.update_wrapper(shim, fn)
478
+ shim.__signature__ = signature.replace(parameters=parameters) # type: ignore[attr-defined]
479
+ return shim