pontive 0.1.0__tar.gz

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 (43) hide show
  1. pontive-0.1.0/.gitignore +15 -0
  2. pontive-0.1.0/CHANGELOG.md +8 -0
  3. pontive-0.1.0/LICENSE +21 -0
  4. pontive-0.1.0/PKG-INFO +359 -0
  5. pontive-0.1.0/README.md +320 -0
  6. pontive-0.1.0/pyproject.toml +104 -0
  7. pontive-0.1.0/src/pontive/__init__.py +89 -0
  8. pontive-0.1.0/src/pontive/_env.py +38 -0
  9. pontive-0.1.0/src/pontive/_http.py +186 -0
  10. pontive-0.1.0/src/pontive/_jwt.py +206 -0
  11. pontive-0.1.0/src/pontive/_management.py +122 -0
  12. pontive-0.1.0/src/pontive/_oidc.py +268 -0
  13. pontive-0.1.0/src/pontive/_util.py +65 -0
  14. pontive-0.1.0/src/pontive/_version.py +1 -0
  15. pontive-0.1.0/src/pontive/authorization.py +479 -0
  16. pontive-0.1.0/src/pontive/cookies.py +118 -0
  17. pontive-0.1.0/src/pontive/django.py +258 -0
  18. pontive-0.1.0/src/pontive/errors.py +91 -0
  19. pontive-0.1.0/src/pontive/fastapi.py +204 -0
  20. pontive-0.1.0/src/pontive/flask.py +232 -0
  21. pontive-0.1.0/src/pontive/http.py +88 -0
  22. pontive-0.1.0/src/pontive/mcp.py +92 -0
  23. pontive-0.1.0/src/pontive/organization.py +48 -0
  24. pontive-0.1.0/src/pontive/preview_hosts.py +87 -0
  25. pontive-0.1.0/src/pontive/py.typed +0 -0
  26. pontive-0.1.0/src/pontive/resource_server.py +795 -0
  27. pontive-0.1.0/src/pontive/seal.py +61 -0
  28. pontive-0.1.0/src/pontive/server_auth.py +883 -0
  29. pontive-0.1.0/tests/__init__.py +0 -0
  30. pontive-0.1.0/tests/conftest.py +50 -0
  31. pontive-0.1.0/tests/django_settings.py +27 -0
  32. pontive-0.1.0/tests/django_urls.py +42 -0
  33. pontive-0.1.0/tests/flows.py +19 -0
  34. pontive-0.1.0/tests/issuer.py +151 -0
  35. pontive-0.1.0/tests/test_authorization.py +284 -0
  36. pontive-0.1.0/tests/test_django.py +85 -0
  37. pontive-0.1.0/tests/test_examples.py +36 -0
  38. pontive-0.1.0/tests/test_fastapi.py +136 -0
  39. pontive-0.1.0/tests/test_flask.py +94 -0
  40. pontive-0.1.0/tests/test_mcp.py +59 -0
  41. pontive-0.1.0/tests/test_resource_server.py +416 -0
  42. pontive-0.1.0/tests/test_seal_cookies.py +66 -0
  43. pontive-0.1.0/tests/test_server_auth.py +596 -0
@@ -0,0 +1,15 @@
1
+ __pycache__/
2
+ *.py[cod]
3
+ .venv/
4
+ .venv-*/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ .coverage
12
+ htmlcov/
13
+ .env
14
+ .env.local
15
+ .DS_Store
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0 (2026-12-03)
4
+
5
+
6
+ ### Features
7
+
8
+ * the Pontive SDK for Python, at parity with pontkit-server ([68afc01](https://github.com/pontivehq/pontive-python/commit/68afc018c33c0fe95edf16e1c787752e1154de21))
pontive-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 pontivehq
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
pontive-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,359 @@
1
+ Metadata-Version: 2.5
2
+ Name: pontive
3
+ Version: 0.1.0
4
+ Summary: Pontive SDK for Python: protect APIs and MCP servers with Pontive access tokens, and keep server-side sessions for web apps.
5
+ Project-URL: Homepage, https://www.pontive.com
6
+ Project-URL: Documentation, https://www.pontive.com/docs
7
+ Project-URL: Source, https://github.com/pontivehq/pontive-python
8
+ Project-URL: Issues, https://github.com/pontivehq/pontive-python/issues
9
+ Author: Pontive
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: authentication,authorization,jwt,mcp,oauth,oidc,pontive
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Framework :: Django
15
+ Classifier: Framework :: FastAPI
16
+ Classifier: Framework :: Flask
17
+ Classifier: Intended Audience :: Developers
18
+ Classifier: Operating System :: OS Independent
19
+ Classifier: Programming Language :: Python :: 3
20
+ Classifier: Programming Language :: Python :: 3 :: Only
21
+ Classifier: Programming Language :: Python :: 3.10
22
+ Classifier: Programming Language :: Python :: 3.11
23
+ Classifier: Programming Language :: Python :: 3.12
24
+ Classifier: Programming Language :: Python :: 3.13
25
+ Classifier: Topic :: Security
26
+ Classifier: Typing :: Typed
27
+ Requires-Python: >=3.10
28
+ Requires-Dist: httpx>=0.27
29
+ Requires-Dist: joserfc>=1.7.6
30
+ Provides-Extra: django
31
+ Requires-Dist: django>=4.2; extra == 'django'
32
+ Provides-Extra: fastapi
33
+ Requires-Dist: fastapi>=0.110; extra == 'fastapi'
34
+ Provides-Extra: flask
35
+ Requires-Dist: flask>=3.0; extra == 'flask'
36
+ Provides-Extra: mcp
37
+ Requires-Dist: mcp>=1.20; extra == 'mcp'
38
+ Description-Content-Type: text/markdown
39
+
40
+ # Pontive SDK for Python
41
+
42
+ [Pontive](https://www.pontive.com) for Python servers: protect an API or an MCP
43
+ server with Pontive access tokens, keep signed-in sessions for a web app, and
44
+ check permissions for a verified caller. The same behavior as
45
+ [`@pontive/pontkit-server`](https://github.com/pontivehq/pontkit/tree/main/packages/server),
46
+ with the same option names (in snake_case), environment variables, error codes
47
+ and cookies.
48
+
49
+ ```sh
50
+ pip install pontive # the core
51
+ pip install "pontive[fastapi]" # or [flask], [django], [mcp]
52
+ ```
53
+
54
+ Python 3.10 and later. Typed. Every call that does I/O has a sync method and an
55
+ async one prefixed `a` (`verify_token` / `averify_token`), on the same object.
56
+
57
+ | You are building | Use |
58
+ | --- | --- |
59
+ | An API or MCP server that accepts Pontive access tokens | `ResourceServer`, and `pontive.fastapi` / `pontive.flask` / `pontive.django` / `pontive.mcp` |
60
+ | A web app whose server signs users in and holds the session | `ServerAuth`, and its middleware for your framework |
61
+ | Permission checks for the caller, delegated or not | `AuthorizationClient` |
62
+
63
+ ## Protect an API
64
+
65
+ ```python
66
+ from pontive import ResourceServer
67
+
68
+ rs = ResourceServer(
69
+ issuer="https://acme.auth.us.pontive.app", # or a list, for several auth domains
70
+ resource="https://api.acme.com", # the API's identifier, as registered
71
+ scopes=["files:read", "files:write"],
72
+ )
73
+
74
+ principal = rs.verify(request_headers, scopes=["files:read"]) # raises BearerError (401/403)
75
+ principal = await rs.averify_token(token, scopes=["files:read"])
76
+ ```
77
+
78
+ Tokens are verified locally against the issuer's cached keys: `typ` must be
79
+ `at+jwt`, `aud` must hold `resource`, `exp`/`nbf` allow 60 seconds of skew,
80
+ and only `RS256`, `PS256` and `ES256` are accepted. A missing or failing token
81
+ is a `BearerError` whose `to_response()` is the `401`/`403` with the
82
+ `WWW-Authenticate` challenge MCP clients follow.
83
+
84
+ `Principal` carries `sub`, `kind` (`user`, `service_account`, `agent`),
85
+ `client_id`, `org_id`, `roles`, `permissions`, `scopes`, `claims` (every claim,
86
+ the claims template's included), `token`, and `is_delegated` with `actor`.
87
+
88
+ > **A delegated token** (`principal.is_delegated`: an agent acting for a user)
89
+ > has the user as `sub` and the agent as `actor`. Its authority is the
90
+ > intersection of the two. Never read or write by `sub` alone: check it by
91
+ > token with `AuthorizationClient`. Tenant data keys on `org_id`, never `sub`.
92
+
93
+ ### FastAPI
94
+
95
+ ```python
96
+ from fastapi import Depends, FastAPI
97
+ from pontive import Principal
98
+ from pontive.fastapi import add_resource_server, require_bearer
99
+
100
+ app = FastAPI()
101
+ add_resource_server(app, rs) # /.well-known/oauth-protected-resource, and RFC 6750 error bodies
102
+
103
+ @app.get("/files")
104
+ async def files(principal: Principal = Depends(require_bearer(rs, scopes=["files:read"]))):
105
+ return {"caller": principal.sub, "organization": principal.org_id}
106
+ ```
107
+
108
+ ### Flask
109
+
110
+ ```python
111
+ from pontive.flask import current_principal, register_well_known, require_bearer
112
+
113
+ register_well_known(app, rs)
114
+
115
+ @app.get("/files")
116
+ @require_bearer(rs, scopes=["files:read"])
117
+ def files():
118
+ return {"caller": current_principal().sub}
119
+ ```
120
+
121
+ ### Django
122
+
123
+ ```python
124
+ from pontive.django import require_bearer, well_known_urls
125
+
126
+ @require_bearer(rs, scopes=["files:read"])
127
+ def files(request):
128
+ return JsonResponse({"caller": request.principal.sub})
129
+
130
+ urlpatterns = [*well_known_urls(rs), path("files", files)]
131
+ ```
132
+
133
+ `require_bearer` also takes `roles=` and `permissions=`: each listed must be in
134
+ the token, or the answer is `403` `insufficient_permission`. They read the
135
+ token's claims, which reflect the organization the token was issued for; for a
136
+ decision on a resource, use the authorization client.
137
+
138
+ ### MCP servers
139
+
140
+ ```python
141
+ from mcp.server.mcpserver import MCPServer # FastMCP in mcp 1.x
142
+ from pontive.mcp import TokenVerifier, auth_settings, current_principal
143
+
144
+ rs = ResourceServer(issuer="https://acme.auth.us.pontive.app", resource="https://mcp.acme.com/mcp")
145
+ server = MCPServer("acme-files", token_verifier=TokenVerifier(rs), auth=auth_settings(rs, scopes=["files:read"]))
146
+
147
+ @server.tool()
148
+ async def read_file(path: str) -> str:
149
+ principal = current_principal()
150
+ await rs.aauthorize_tool(principal, "read_file") # per-tool scopes
151
+ ...
152
+ ```
153
+
154
+ Per-tool scopes come from the API's scopes: pass the dashboard's scopes with
155
+ their `tools` (`scopes=[{"key": "files:read", "tools": [{"name": "read_file"}]}]`),
156
+ or `metadata_fetch=MetadataFetch(api_id=..., credential=..., management_url=...)`
157
+ to read them, and the metadata, from Pontive. `rs.authorize_tool_calls(principal, body)`
158
+ checks every `tools/call` in a JSON-RPC body before the transport sees it.
159
+
160
+ ## Sessions for a web app
161
+
162
+ A confidential app (one with a client secret) signs users in on its server and
163
+ keeps the session in an encrypted, HttpOnly cookie. The middleware refreshes the
164
+ access token shortly before it expires, before your handler runs.
165
+
166
+ ```sh
167
+ export PONTIVE_ISSUER=https://acme.auth.us.pontive.app
168
+ export PONTIVE_CLIENT_ID=app_...
169
+ export PONTIVE_CLIENT_SECRET=...
170
+ export PONTIVE_SESSION_SECRET=$(python -c "import secrets; print(secrets.token_urlsafe(32))")
171
+ ```
172
+
173
+ Register `https://<your origin>/api/auth/callback` as a redirect URI and
174
+ `https://<your origin>/login` as a post-logout redirect URI on the app. Sign-in
175
+ starts at `/api/auth/login?returnTo=/somewhere`, sign-out at `/api/auth/logout`.
176
+
177
+ ### FastAPI (or any Starlette app)
178
+
179
+ ```python
180
+ from fastapi import Depends, FastAPI
181
+ from pontive import ServerAuth, Session
182
+ from pontive.fastapi import PontiveMiddleware, get_session, require_session
183
+
184
+ auth = ServerAuth(base_url="https://app.acme.com") # the rest from PONTIVE_*
185
+ app = FastAPI()
186
+ app.add_middleware(PontiveMiddleware, auth=auth)
187
+
188
+ @app.get("/")
189
+ async def home(session: Session | None = Depends(get_session)):
190
+ return {"email": session.user.email if session else None}
191
+ ```
192
+
193
+ ### Flask
194
+
195
+ ```python
196
+ from pontive import ServerAuth
197
+ from pontive.flask import Pontive, current_session, login_required
198
+
199
+ Pontive(app, ServerAuth())
200
+
201
+ @app.get("/dashboard")
202
+ @login_required
203
+ def dashboard():
204
+ return f"Hello {current_session().user.email}"
205
+ ```
206
+
207
+ ### Django
208
+
209
+ ```python
210
+ # settings.py
211
+ MIDDLEWARE = [..., "pontive.django.PontiveMiddleware"]
212
+ PONTIVE = {"base_url": "https://app.acme.com"} # ServerAuth's options; the rest from PONTIVE_*
213
+
214
+ # views.py
215
+ from pontive.django import login_required
216
+
217
+ @login_required
218
+ def dashboard(request):
219
+ return HttpResponse(f"Hello {request.pontive_session.user.email}")
220
+ ```
221
+
222
+ The middleware is sync and async capable.
223
+
224
+ ### The session
225
+
226
+ `Session` has `user` (`id`, `email`, `name`, `username`, `picture`,
227
+ `email_verified`), `access_token` (to call APIs as the user), `expires_at`
228
+ (epoch seconds), `session_id`, `organization` (`id`, `roles`, `permissions`,
229
+ or `None`) and `claims`.
230
+
231
+ Move the session to another organization with
232
+ `auth.switch_organization_path(org_id, return_to="/team")`. A switch the user
233
+ cannot make comes back with `?organization_error=not_a_member` and leaves the
234
+ session as it was.
235
+
236
+ **Without a client secret** (a regular app, or a public oauth app, whose
237
+ browser SDK signs users in), `ServerAuth` runs in browser mode: it reads the
238
+ access-token cookie the auth server keeps current through the
239
+ [auth proxy](https://www.pontive.com/docs/sdk/auth-proxy), and sends a page
240
+ navigation whose token lapsed through the auth server's session handshake. It
241
+ never refreshes in this mode, so the browser stays the only thing that spends
242
+ the refresh token.
243
+
244
+ **Anything else** speaks `AuthRequest`/`AuthResponse`: `auth.handle(request)`
245
+ for the routes, `auth.refresh(request)` before your handler (apply
246
+ `outcome.set_cookies`, forward `outcome.cookie_header`), and
247
+ `auth.get_session(cookie_header)` anywhere.
248
+
249
+ ### Options
250
+
251
+ | Option | Default | |
252
+ | --- | --- | --- |
253
+ | `issuer` | `PONTIVE_ISSUER` | The auth domain |
254
+ | `client_id` | `PONTIVE_CLIENT_ID` | The app's id |
255
+ | `client_secret` | `PONTIVE_CLIENT_SECRET` | Selects server mode |
256
+ | `session_secret` | `PONTIVE_SESSION_SECRET` | 32+ characters; rotating it signs everyone out |
257
+ | `base_url` | `X-Forwarded-*`, then the request | The app's public origin; set it behind a proxy |
258
+ | `base_path` | `/api/auth` | Where the routes live |
259
+ | `scopes` | `openid email profile offline_access` | |
260
+ | `redirect_uri` | `{origin}{base_path}/callback` | |
261
+ | `sign_in_path` | `/login` | Failed sign-ins and signed-out users land here |
262
+ | `after_sign_in_path` | `/` | |
263
+ | `cookie_name` | `pontive_session` | |
264
+ | `secure_cookies` | https origin | |
265
+ | `iframe_safe` | `"auto"` | `SameSite=None` on app-builder preview hosts |
266
+ | `preview_callback` | `"auto"` | The hosted preview callback on builder previews |
267
+ | `session_max_age_seconds` | 7 days | |
268
+ | `refresh_skew_seconds` | 60 | |
269
+ | `auth_path` | `/__pontive` | Browser mode: where the auth proxy is mounted |
270
+ | `http_client`, `async_http_client` | the SDK's own | `httpx` clients, e.g. for proxies or tests |
271
+
272
+ ## Authorization checks
273
+
274
+ ```python
275
+ from pontive import AuthorizationClient, ClientCredentials, ResourceRef
276
+
277
+ authz = AuthorizationClient(
278
+ management_url="https://api.us.pontive.com", # the authz host is https://authz.us.pontive.com
279
+ issuer="https://acme.auth.us.pontive.app", # to exchange client credentials
280
+ credential=ClientCredentials("svc_...", "..."), # holds sys:authz:check; or a key, or a function
281
+ )
282
+
283
+ authz.check(principal, "doc:write", ResourceRef("doc", "doc_1"), scopes=["files:write"])
284
+ authz.check_batch(principal, items) # one answer per item, 100 per request
285
+ authz.list_accessible(principal, resource_type="doc", permission="doc:read")
286
+ authz.filter_accessible(principal, chunks, lambda c: c.doc_id, resource_type="doc", permission="doc:read")
287
+ # and acheck, acheck_batch, alist_accessible, afilter_accessible
288
+ ```
289
+
290
+ A delegated principal is checked by token, as the user-and-agent pair; anything
291
+ else by subject. A denial is `False`; a refused request raises
292
+ `AuthorizationError` with `status` and `code`.
293
+
294
+ ## Environment
295
+
296
+ The variables every Pontive SDK reads, so docs read the same in every language.
297
+ A value passed in code always wins.
298
+
299
+ | Variable | Read by |
300
+ | --- | --- |
301
+ | `PONTIVE_ISSUER` | `ServerAuth` |
302
+ | `PONTIVE_CLIENT_ID` | `ServerAuth` |
303
+ | `PONTIVE_CLIENT_SECRET` | `ServerAuth` |
304
+ | `PONTIVE_SESSION_SECRET` | `ServerAuth` |
305
+
306
+ The SDK reads the process environment only. To load a `.env` file, use
307
+ python-dotenv or your framework's settings.
308
+
309
+ ## Design notes
310
+
311
+ - **Dependencies.** `httpx` gives one API for sync and async HTTP, and a
312
+ `MockTransport` for tests. `joserfc` does JWS, JWE and JWK in one library,
313
+ depends only on `cryptography`, is typed, and takes an explicit algorithm list
314
+ on every call. PyJWT has no JWE (sealing would need a second library);
315
+ python-jose is unmaintained; authlib brings a whole OAuth framework.
316
+ - **One protocol implementation.** Every HTTP exchange is written once, as a
317
+ generator that yields requests; the sync and async methods only drive it. They
318
+ cannot drift apart.
319
+ - **Sealing.** JWE compact, `dir` + `A256GCM`, keyed by the SHA-256 of
320
+ `session_secret`, with `iat` and `exp`. The same format and payload as
321
+ pontkit-server, so a Python app and a Node app sharing a domain, cookie name
322
+ and secret read each other's sessions.
323
+ - **Refresh.** One refresh per refresh token in flight per process (threads
324
+ wait on the first; coroutines share one task), and its result handed to late
325
+ requests still holding the old cookie for 30 seconds. Across replicas the
326
+ auth server's reuse grace covers the race. A `4xx` signs out; a network error
327
+ or `5xx` keeps the session for the next request.
328
+ - **Keys.** Cached ten minutes; an unknown `kid` refetches the set at most once
329
+ per 30 seconds, so a rotation is picked up at once. Keys that went stale while
330
+ the issuer is unreachable keep verifying.
331
+
332
+ Not in this SDK, by design: pontkit-server's **keyless mode** (it provisions an
333
+ unclaimed instance from inside a Node dev server; a Python app runs
334
+ `npx pontive@latest init` and loads the variables it writes).
335
+
336
+ ## Roadmap
337
+
338
+ - **Phase 1 (this release):** everything above, at parity with `@pontive/pontkit-server`.
339
+ - **Phase 2:** a client for the Pontive management API, generated from its OpenAPI document.
340
+
341
+ ## Examples
342
+
343
+ [`examples/`](examples): an API with FastAPI, sign-in with Flask, sign-in with
344
+ Django in one file. Each says how to run it.
345
+
346
+ ## Development
347
+
348
+ ```sh
349
+ uv sync
350
+ uv run pytest
351
+ uv run ruff check src tests examples && uv run ruff format --check src tests examples
352
+ uv run mypy
353
+ ```
354
+
355
+ Commits follow Conventional Commits; release-please opens the release PR.
356
+
357
+ ## License
358
+
359
+ MIT