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,342 @@
1
+ """The Flask context provider.
2
+
3
+ The WSGI half of one-decorator-N-providers. Same decorator, same envelope, same statuses — a
4
+ different pair of hooks:
5
+
6
+ ```python
7
+ from flask import Flask
8
+ from sentrykit.integrations.flask import FlaskProvider, protect_app
9
+
10
+ app = Flask(__name__)
11
+ protect_app(app, provider=FlaskProvider(identify=lambda request: request.headers.get("x-user")))
12
+ ```
13
+
14
+ ## Establish in `before_request`, release in `teardown_request`
15
+
16
+ Flask's hook ordering is what makes this work. For a request whose view raises, Flask runs:
17
+
18
+ ```
19
+ before_request -> view raises -> errorhandler renders -> teardown_request
20
+ ```
21
+
22
+ so the handler still sees the ambient principal, and `teardown_request` is the last hook — the
23
+ right place for the release. Three details follow from the same observation and each one is a
24
+ bug if ignored:
25
+
26
+ * `teardown_request` runs **even when `before_request` raised**, so the release has to cope
27
+ with there being no scope to release.
28
+ * `before_request` and `teardown_request` fire **even for a 404**, so establishment cannot
29
+ assume a view was matched.
30
+ * Everything happens on **one thread**, so the `ContextVar` token captured on the way in is
31
+ always resettable on the way out.
32
+
33
+ That release is the whole reason this module is careful. Flask serves a request on a pooled
34
+ worker thread, and its test client serves one in the caller's own context: an un-reset
35
+ `ContextVar` from request *N* is still ambient when request *N+1* starts, and request *N+1*
36
+ would be authorized as request *N*'s principal. §5 of the same notes measured it.
37
+
38
+ Flask `async def` views need the `asgiref` extra and are not exercised here; sync views are
39
+ the shape this provider is built for.
40
+ """
41
+
42
+ from __future__ import annotations
43
+
44
+ from flask import Blueprint, Flask, Request, Response, g, has_app_context, jsonify
45
+ from flask import request as current_request
46
+
47
+ from sentrykit.context import ContextScope
48
+ from sentrykit.errors import ConfigurationError, SentrykitError
49
+ from sentrykit.integrations.base import (
50
+ DEFAULT_PRINCIPAL_HEADER,
51
+ DEFAULT_REQUEST_ID_HEADER,
52
+ STATUS_BY_ERROR,
53
+ BaseContextProvider,
54
+ narrowing_headers,
55
+ )
56
+ from sentrykit.registry import DSN, register_context_provider
57
+
58
+ __all__ = [
59
+ "SCOPE_KEY",
60
+ "FlaskProvider",
61
+ "install_error_handlers",
62
+ "protect_app",
63
+ "protect_blueprint",
64
+ ]
65
+
66
+ SCOPE_KEY: str = "_sentrykit_scope"
67
+ """Attribute on :data:`flask.g` the request's context scope is parked under.
68
+
69
+ ``g`` rather than a module global because it is request-scoped and thread-local already, which
70
+ is exactly the lifetime the scope has. The name is public so a host debugging a leak knows what
71
+ to look at.
72
+ """
73
+
74
+
75
+ @register_context_provider("flask")
76
+ class FlaskProvider(BaseContextProvider[Request]):
77
+ """Establishes ambient context from a Flask request and renders refusals as JSON.
78
+
79
+ Construction is inherited from :class:`~sentrykit.integrations.base.BaseContextProvider`;
80
+ see there for ``identify``, ``grants``, ``environment`` and the header options. This class
81
+ supplies only the four framework seams plus the two Flask hooks.
82
+ """
83
+
84
+ @classmethod
85
+ def from_dsn(cls, dsn: DSN) -> FlaskProvider:
86
+ """Build from ``flask://`` — the registry's door, used by ``install()``.
87
+
88
+ A DSN-built provider has no application auth to call into, so it identifies callers by
89
+ the header named in ``?header=`` (default
90
+ :data:`~sentrykit.integrations.base.DEFAULT_PRINCIPAL_HEADER`). Real deployments
91
+ construct the provider directly and pass ``identify=``.
92
+
93
+ Args:
94
+ dsn: The parsed address. Options: ``header`` (principal id header),
95
+ ``request_id_header``.
96
+
97
+ Returns:
98
+ The provider.
99
+ """
100
+ # ``or`` rather than the option's own default, so ``?header=`` with an empty value
101
+ # falls back to the shipped header instead of wiring a provider that reads ``""``.
102
+ return cls(
103
+ principal_header=dsn.option("header") or DEFAULT_PRINCIPAL_HEADER,
104
+ request_id_header=dsn.option("request_id_header") or DEFAULT_REQUEST_ID_HEADER,
105
+ )
106
+
107
+ @property
108
+ def name(self) -> str:
109
+ """``flask``."""
110
+ return "flask"
111
+
112
+ def narrow(self, request: object) -> Request:
113
+ """Check that ``request`` is a Flask request, unwrapping the request-local proxy.
114
+
115
+ Inside a request, ``flask.request`` is a :class:`werkzeug.local.LocalProxy`, not a
116
+ :class:`flask.Request`. The proxy forwards ``__class__``, so ``isinstance`` alone
117
+ would accept it and quietly hand the *proxy* to the application's ``identify``
118
+ callback — an object whose attribute lookups fail the moment the request context is
119
+ gone. It is unwrapped here instead, so ``identify`` and ``environment`` always receive
120
+ the real request and may keep it.
121
+
122
+ Args:
123
+ request: The object the boundary handed over — a request or a proxy to one.
124
+
125
+ Returns:
126
+ The underlying request, typed.
127
+
128
+ Raises:
129
+ ConfigurationError: If it is not a Flask request — which means this provider was
130
+ wired to the wrong framework.
131
+ """
132
+ unwrap = getattr(request, "_get_current_object", None)
133
+ if callable(unwrap):
134
+ try:
135
+ request = unwrap()
136
+ except RuntimeError as exc:
137
+ raise ConfigurationError(
138
+ "the flask context provider was handed a request-local proxy bound to no "
139
+ "request; establish() belongs in a before_request hook"
140
+ ) from exc
141
+ if isinstance(request, Request):
142
+ return request
143
+ actual = type(request)
144
+ raise ConfigurationError(
145
+ "the flask context provider expects a flask.Request but was given a "
146
+ f"{actual.__module__}.{actual.__qualname__}; it is wired to the wrong framework"
147
+ )
148
+
149
+ def read_header(self, request: Request, name: str) -> str | None:
150
+ """Read one header from a Flask request. Werkzeug's headers are case-insensitive."""
151
+ # Bound to an annotated local rather than returned directly, so the module still
152
+ # type-checks in the default environment where flask is absent and every symbol
153
+ # imported from it is ``Any``.
154
+ value: str | None = request.headers.get(name)
155
+ return value
156
+
157
+ def render_error(self, error: Exception) -> tuple[Response, int]:
158
+ """Render a sentrykit refusal as a JSON response carrying the ``_authz`` envelope.
159
+
160
+ Args:
161
+ error: A :class:`~sentrykit.errors.SentrykitError`.
162
+
163
+ Returns:
164
+ ``(response, status)`` — the pair Flask accepts from an error handler, at the
165
+ status :func:`~sentrykit.integrations.base.status_for` maps the error to.
166
+ """
167
+ status, body = self.error_response(error)
168
+ # ``jsonify`` needs an application context; an error handler always runs inside one.
169
+ return jsonify(body), status
170
+
171
+ def before_request(self) -> None:
172
+ """Establish ambient context for the current request, parking the scope on ``g``.
173
+
174
+ Registered as a ``before_request`` hook. Takes no arguments and returns ``None``, which
175
+ is Flask's contract for "carry on with the request" — the provider never short-circuits
176
+ a request itself, because refusing is the decorator's job and an unauthenticated caller
177
+ may well be hitting a route that is not protected at all.
178
+ """
179
+ # Parked even when it is ``None`` (an unauthenticated caller establishes no scope), so
180
+ # ``g`` records that this hook ran rather than leaving teardown to guess.
181
+ setattr(g, SCOPE_KEY, self.establish(current_request))
182
+
183
+ def after_request(self, response: Response) -> Response:
184
+ """Add the narrowing headers to the outgoing response.
185
+
186
+ Registered as an ``after_request`` hook, which is the last place the headers are still
187
+ mutable and runs before ``teardown_request`` drops the recorder. Flask serves a request
188
+ on one thread in one context, so unlike the ASGI side there is no copied-context
189
+ problem here — the recorder is used anyway, because it is the channel that answers the
190
+ *response-level* question (a view may make several protected calls) and because one
191
+ answer shared by both frameworks is worth more than two shaped by their own plumbing.
192
+
193
+ Args:
194
+ response: The response Flask is about to send.
195
+
196
+ Returns:
197
+ The same response, with the headers added when anything was narrowed. An
198
+ unprotected route, or one that narrowed nothing, is returned untouched.
199
+ """
200
+ for name, value in narrowing_headers(*self.narrowing()).items():
201
+ response.headers[name] = value
202
+ return response
203
+
204
+ def teardown_request(self, error: BaseException | None = None) -> None:
205
+ """Release the context established for the current request.
206
+
207
+ Registered as a ``teardown_request`` hook, and total: a request whose
208
+ ``before_request`` never ran, or ran and raised, has no scope on ``g``, and that is a
209
+ no-op rather than a ``KeyError``. It tolerates being called with no application context
210
+ at all, so a host driving the hooks by hand cannot turn a missing context into a
211
+ teardown exception that masks the real one.
212
+
213
+ Args:
214
+ error: The exception that ended the request, or ``None``. Accepted because Flask
215
+ passes it; the release is the same either way, since
216
+ :meth:`~sentrykit.integrations.base.BaseContextProvider.release` is what makes
217
+ the *next* request safe and that is owed regardless of how this one ended.
218
+ """
219
+ scope: ContextScope | None = None
220
+ if has_app_context():
221
+ parked = g.pop(SCOPE_KEY, None)
222
+ if isinstance(parked, ContextScope):
223
+ scope = parked
224
+ # ``release`` is total and does not raise: it clears the context outright when there is
225
+ # no scope, and :func:`sentrykit.context._restore` downgrades an unusable token to a
226
+ # clear rather than letting it escape. Nothing here can mask ``error``.
227
+ self.release(scope)
228
+
229
+
230
+ def _effective_provider(provider: FlaskProvider | None) -> FlaskProvider:
231
+ """Resolve the provider the Flask hooks should be bound to.
232
+
233
+ The one place the defaulting rule lives, so :func:`install_error_handlers`,
234
+ :func:`protect_app` and :func:`protect_blueprint` cannot drift apart.
235
+
236
+ Unlike the ASGI side, resolution happens at *wiring* time rather than per request: Flask's
237
+ hooks are registered as bound methods, and a hook that re-resolved the provider on every
238
+ request could establish with one and release with another. The cost is a documented
239
+ ordering — ``install(context_provider=...)`` before ``protect_app(...)`` — and it buys
240
+ nothing to defer, because the grant store is already resolved lazily by
241
+ :attr:`~sentrykit.integrations.base.BaseContextProvider.grants`.
242
+
243
+ A governor wired to some *other* framework's provider is ignored rather than treated as an
244
+ error, since a process may legitimately serve a WSGI app beside an ASGI one. The fallback
245
+ is a bare header-identifying provider, which fails closed for any caller who sends no
246
+ header.
247
+
248
+ Args:
249
+ provider: An explicitly supplied provider, or ``None``.
250
+
251
+ Returns:
252
+ The explicit provider, the installed governor's when it is a :class:`FlaskProvider`, or
253
+ a freshly built default.
254
+ """
255
+ if provider is not None:
256
+ return provider
257
+ # Imported in the body rather than at module scope: the engine pulls in the whole decision
258
+ # path, and a framework adapter should not dictate the library's import order.
259
+ from sentrykit.engine import current_governor
260
+
261
+ governor = current_governor()
262
+ wired = governor.context_provider if governor is not None else None
263
+ if isinstance(wired, FlaskProvider):
264
+ return wired
265
+ return FlaskProvider()
266
+
267
+
268
+ def install_error_handlers(
269
+ target: Flask | Blueprint, provider: FlaskProvider | None = None
270
+ ) -> None:
271
+ """Register a handler for every sentrykit error on ``target``.
272
+
273
+ One handler per entry in :data:`~sentrykit.integrations.base.STATUS_BY_ERROR`, plus
274
+ :class:`~sentrykit.errors.SentrykitError` itself as the catch-all. Flask resolves a handler
275
+ by walking the exception's MRO, so a host that subclasses a shipped error is covered
276
+ without registering anything.
277
+
278
+ Args:
279
+ target: The application or blueprint to register on.
280
+ provider: The provider whose :meth:`FlaskProvider.render_error` builds the response.
281
+ """
282
+ resolved = _effective_provider(provider)
283
+ # ``SentrykitError`` is already a key of the mapping; naming it again is a harmless
284
+ # re-registration of the same handler and keeps the catch-all explicit at the call site.
285
+ for error_type in (*STATUS_BY_ERROR, SentrykitError):
286
+ # Flask registers handlers for ``Exception`` subclasses only; the mapping is keyed by
287
+ # ``BaseException`` so a future entry could in principle be neither.
288
+ if issubclass(error_type, Exception):
289
+ target.register_error_handler(error_type, resolved.render_error)
290
+
291
+
292
+ def protect_app(app: Flask, *, provider: FlaskProvider | None = None) -> FlaskProvider:
293
+ """Wire sentrykit into ``app`` in one call.
294
+
295
+ Registers the ``before_request`` establishment, the ``after_request`` narrowing headers,
296
+ the ``teardown_request`` release, and the error handlers, application-wide.
297
+
298
+ Args:
299
+ app: The application.
300
+ provider: The provider to use. Defaults to the one wired into the installed governor by
301
+ ``install(context_provider=...)``, and failing that to a header-identifying
302
+ :class:`FlaskProvider`. Call ``install()`` first if you want it picked up — see
303
+ :func:`_effective_provider` for why the default is resolved here and not per
304
+ request.
305
+
306
+ Returns:
307
+ The provider that was wired, so a caller can hold on to it.
308
+ """
309
+ resolved = _effective_provider(provider)
310
+ # Bound methods: ``before_request`` takes no arguments and ``teardown_request`` takes the
311
+ # exception, which is exactly what Flask passes each hook.
312
+ app.before_request(resolved.before_request)
313
+ app.after_request(resolved.after_request)
314
+ app.teardown_request(resolved.teardown_request)
315
+ install_error_handlers(app, resolved)
316
+ return resolved
317
+
318
+
319
+ def protect_blueprint(
320
+ blueprint: Blueprint, *, provider: FlaskProvider | None = None
321
+ ) -> FlaskProvider:
322
+ """Wire sentrykit into one blueprint rather than the whole application.
323
+
324
+ For an app where only part of the surface is governed — an ``/api`` blueprint in front of
325
+ an unprotected marketing site, or two blueprints authenticating callers differently. The
326
+ hooks are blueprint-scoped (``Blueprint.before_request`` / ``Blueprint.after_request`` /
327
+ ``Blueprint.teardown_request``), so they run only for this blueprint's routes, and its
328
+ error handlers likewise.
329
+
330
+ Args:
331
+ blueprint: The blueprint.
332
+ provider: The provider to use. Defaults as for :func:`protect_app`.
333
+
334
+ Returns:
335
+ The provider that was wired.
336
+ """
337
+ resolved = _effective_provider(provider)
338
+ blueprint.before_request(resolved.before_request)
339
+ blueprint.after_request(resolved.after_request)
340
+ blueprint.teardown_request(resolved.teardown_request)
341
+ install_error_handlers(blueprint, resolved)
342
+ return resolved