Metadata-Version: 2.5
Name: pontive
Version: 0.3.0
Summary: Pontive SDK for Python: the management API client, API and MCP server protection with Pontive access tokens, and server-side sessions for web apps.
Project-URL: Homepage, https://www.pontive.com
Project-URL: Documentation, https://www.pontive.com/docs
Project-URL: Source, https://github.com/pontivehq/pontive-python
Project-URL: Issues, https://github.com/pontivehq/pontive-python/issues
Author: Pontive
License-Expression: MIT
License-File: LICENSE
Keywords: authentication,authorization,jwt,mcp,oauth,oidc,pontive
Classifier: Development Status :: 4 - Beta
Classifier: Framework :: Django
Classifier: Framework :: FastAPI
Classifier: Framework :: Flask
Classifier: Intended Audience :: Developers
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3 :: Only
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: httpx>=0.27
Requires-Dist: joserfc>=1.7.6
Provides-Extra: django
Requires-Dist: django>=4.2; extra == 'django'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.110; extra == 'fastapi'
Provides-Extra: flask
Requires-Dist: flask>=3.0; extra == 'flask'
Provides-Extra: mcp
Requires-Dist: mcp>=1.20; extra == 'mcp'
Description-Content-Type: text/markdown

# Pontive SDK for Python

[Pontive](https://www.pontive.com) for Python servers: protect an API or an MCP
server with Pontive access tokens, keep signed-in sessions for a web app, check
permissions for a verified caller, and manage your instance through the
management API. The same behavior as
[`@pontive/server`](https://www.npmjs.com/package/@pontive/server),
with the same option names (in snake_case), environment variables, error codes
and cookies.

```sh
pip install pontive              # the core
pip install "pontive[fastapi]"   # or [flask], [django], [mcp]
```

Python 3.10 and later. Typed. Every call that does I/O has a sync method and an
async one prefixed `a` (`verify_token` / `averify_token`), on the same object.

| You are building | Use |
| --- | --- |
| An API or MCP server that accepts Pontive access tokens | `ResourceServer`, and `pontive.fastapi` / `pontive.flask` / `pontive.django` / `pontive.mcp` |
| A web app whose server signs users in and holds the session | `ServerAuth`, and its middleware for your framework |
| Permission checks for the caller, delegated or not | `AuthorizationClient` |
| Users, organizations, apps, roles, webhooks, billing: the management API | `Pontive`, `AsyncPontive` |

## Protect an API

```python
from pontive import ResourceServer

rs = ResourceServer(
    issuer="https://acme.auth.us.pontive.app",   # or a list, for several auth domains
    resource="https://api.acme.com",             # the API's identifier, as registered
    scopes=["files:read", "files:write"],
)

principal = rs.verify(request_headers, scopes=["files:read"])   # raises BearerError (401/403)
principal = await rs.averify_token(token, scopes=["files:read"])
```

Tokens are verified locally against the issuer's cached keys: `typ` must be
`at+jwt`, `aud` must hold `resource`, `exp`/`nbf` allow 60 seconds of skew,
and only `RS256`, `PS256` and `ES256` are accepted. A missing or failing token
is a `BearerError` whose `to_response()` is the `401`/`403` with the
`WWW-Authenticate` challenge MCP clients follow.

`Principal` carries `sub`, `kind` (`user`, `service_account`, `agent`),
`client_id`, `org_id`, `roles`, `permissions`, `scopes`, `claims` (every claim,
the claims template's included), `token`, and `is_delegated` with `actor`.

> **A delegated token** (`principal.is_delegated`: an agent acting for a user)
> has the user as `sub` and the agent as `actor`. Its authority is the
> intersection of the two. Never read or write by `sub` alone: check it by
> token with `AuthorizationClient`. Tenant data keys on `org_id`, never `sub`.

### FastAPI

```python
from fastapi import Depends, FastAPI
from pontive import Principal
from pontive.fastapi import add_resource_server, require_bearer

app = FastAPI()
add_resource_server(app, rs)  # /.well-known/oauth-protected-resource, and RFC 6750 error bodies

@app.get("/files")
async def files(principal: Principal = Depends(require_bearer(rs, scopes=["files:read"]))):
    return {"caller": principal.sub, "organization": principal.org_id}
```

### Flask

```python
from pontive.flask import current_principal, register_well_known, require_bearer

register_well_known(app, rs)

@app.get("/files")
@require_bearer(rs, scopes=["files:read"])
def files():
    return {"caller": current_principal().sub}
```

### Django

```python
from pontive.django import require_bearer, well_known_urls

@require_bearer(rs, scopes=["files:read"])
def files(request):
    return JsonResponse({"caller": request.principal.sub})

urlpatterns = [*well_known_urls(rs), path("files", files)]
```

`require_bearer` also takes `roles=` and `permissions=`: each listed must be in
the token, or the answer is `403` `insufficient_permission`. They read the
token's claims, which reflect the organization the token was issued for; for a
decision on a resource, use the authorization client.

### MCP servers

```python
from mcp.server.mcpserver import MCPServer   # FastMCP in mcp 1.x
from pontive.mcp import TokenVerifier, auth_settings, current_principal

rs = ResourceServer(issuer="https://acme.auth.us.pontive.app", resource="https://mcp.acme.com/mcp")
server = MCPServer("acme-files", token_verifier=TokenVerifier(rs), auth=auth_settings(rs, scopes=["files:read"]))

@server.tool()
async def read_file(path: str) -> str:
    principal = current_principal()
    await rs.aauthorize_tool(principal, "read_file")   # per-tool scopes
    ...
```

Per-tool scopes come from the API's scopes: pass the dashboard's scopes with
their `tools` (`scopes=[{"key": "files:read", "tools": [{"name": "read_file"}]}]`),
or `metadata_fetch=MetadataFetch(api_id=..., credential=..., management_url=...)`
to read them, and the metadata, from Pontive. `rs.authorize_tool_calls(principal, body)`
checks every `tools/call` in a JSON-RPC body before the transport sees it.

## Sessions for a web app

A confidential app (one with a client secret) signs users in on its server and
keeps the session in an encrypted, HttpOnly cookie. The middleware refreshes the
access token shortly before it expires, before your handler runs.

```sh
export PONTIVE_ISSUER=https://acme.auth.us.pontive.app
export PONTIVE_CLIENT_ID=app_...
export PONTIVE_CLIENT_SECRET=...
export PONTIVE_SESSION_SECRET=$(python -c "import secrets; print(secrets.token_urlsafe(32))")
```

Register `https://<your origin>/api/auth/callback` as a redirect URI and
`https://<your origin>/login` as a post-logout redirect URI on the app. Sign-in
starts at `/api/auth/login?returnTo=/somewhere`, sign-out at `/api/auth/logout`.

### FastAPI (or any Starlette app)

```python
from fastapi import Depends, FastAPI
from pontive import ServerAuth, Session
from pontive.fastapi import PontiveMiddleware, get_session, require_session

auth = ServerAuth(base_url="https://app.acme.com")   # the rest from PONTIVE_*
app = FastAPI()
app.add_middleware(PontiveMiddleware, auth=auth)

@app.get("/")
async def home(session: Session | None = Depends(get_session)):
    return {"email": session.user.email if session else None}
```

### Flask

```python
from pontive import ServerAuth
from pontive.flask import Pontive, current_session, login_required

Pontive(app, ServerAuth())

@app.get("/dashboard")
@login_required
def dashboard():
    return f"Hello {current_session().user.email}"
```

### Django

```python
# settings.py
MIDDLEWARE = [..., "pontive.django.PontiveMiddleware"]
PONTIVE = {"base_url": "https://app.acme.com"}   # ServerAuth's options; the rest from PONTIVE_*

# views.py
from pontive.django import login_required

@login_required
def dashboard(request):
    return HttpResponse(f"Hello {request.pontive_session.user.email}")
```

The middleware is sync and async capable.

### The session

`Session` has `user` (`id`, `email`, `name`, `username`, `picture`,
`email_verified`), `access_token` (to call APIs as the user), `expires_at`
(epoch seconds), `session_id`, `organization` (`id`, `roles`, `permissions`,
or `None`) and `claims`.

Move the session to another organization with
`auth.switch_organization_path(org_id, return_to="/team")`. A switch the user
cannot make comes back with `?organization_error=not_a_member` and leaves the
session as it was.

**Without a client secret** (a regular app, or a public oauth app, whose
browser SDK signs users in), `ServerAuth` runs in browser mode: it reads the
access-token cookie the auth server keeps current through the
[auth proxy](https://www.pontive.com/docs/sdk/auth-proxy), and sends a page
navigation whose token lapsed through the auth server's session handshake. It
never refreshes in this mode, so the browser stays the only thing that spends
the refresh token.

**Anything else** speaks `AuthRequest`/`AuthResponse`: `auth.handle(request)`
for the routes, `auth.refresh(request)` before your handler (apply
`outcome.set_cookies`, forward `outcome.cookie_header`), and
`auth.get_session(cookie_header)` anywhere.

### Options

| Option | Default | |
| --- | --- | --- |
| `issuer` | `PONTIVE_ISSUER` | The auth domain |
| `client_id` | `PONTIVE_CLIENT_ID` | The app's id |
| `client_secret` | `PONTIVE_CLIENT_SECRET` | Selects server mode |
| `session_secret` | `PONTIVE_SESSION_SECRET` | 32+ characters; rotating it signs everyone out |
| `base_url` | `X-Forwarded-*`, then the request | The app's public origin; set it behind a proxy |
| `base_path` | `/api/auth` | Where the routes live |
| `scopes` | `openid email profile offline_access` | |
| `redirect_uri` | `{origin}{base_path}/callback` | |
| `sign_in_path` | `/login` | Failed sign-ins and signed-out users land here |
| `after_sign_in_path` | `/` | |
| `cookie_name` | `pontive_session` | |
| `secure_cookies` | https origin | |
| `iframe_safe` | `"auto"` | `SameSite=None` on app-builder preview hosts |
| `preview_callback` | `"auto"` | The hosted preview callback on builder previews |
| `session_max_age_seconds` | 7 days | |
| `refresh_skew_seconds` | 60 | |
| `auth_path` | `/__pontive` | Browser mode: where the auth proxy is mounted |
| `http_client`, `async_http_client` | the SDK's own | `httpx` clients, e.g. for proxies or tests |

## Authorization checks

```python
from pontive import AuthorizationClient, ClientCredentials, ResourceRef

authz = AuthorizationClient(
    management_url="https://api.us.pontive.com",        # the authz host is https://authz.us.pontive.com
    issuer="https://acme.auth.us.pontive.app",          # to exchange client credentials
    credential=ClientCredentials("svc_...", "..."),     # holds sys:authz:check; or a key, or a function
)

authz.check(principal, "doc:write", ResourceRef("doc", "doc_1"), scopes=["files:write"])
authz.check_batch(principal, items)                      # one answer per item, 100 per request
authz.list_accessible(principal, resource_type="doc", permission="doc:read")
authz.filter_accessible(principal, chunks, lambda c: c.doc_id, resource_type="doc", permission="doc:read")
# and acheck, acheck_batch, alist_accessible, afilter_accessible
```

A delegated principal is checked by token, as the user-and-agent pair; anything
else by subject. A denial is `False`; a refused request raises
`AuthorizationError` with `status` and `code`.

## Manage your instance

```python
import pontive

client = pontive.Pontive()  # PONTIVE_SECRET_KEY from the environment

user = client.users.create({"email": "ada@example.com", "name": "Ada Lovelace"})
org = client.organizations.create({"name": "Analytical Engines", "owners": [user["id"]]})

for u in client.users.list(search="ada"):   # iterates across pages
    print(u["id"], u["email"])

page = client.users.list(limit=50)           # or one page at a time
page.data, page.has_next_page(), page.next_page()
```

`AsyncPontive` is the same for asyncio: `await client.users.get(...)`, and a
list is awaited for its first page or walked with `async for`.

- **Credentials.** `secret_key` (the instance's `pontive_sk_…` key, which names
  its instance and region), `token` (a string or a function), or
  `client_credentials=ClientCredentials(...)` with `issuer` (a service
  account's, exchanged and cached). The region picks
  `https://api.{region}.pontive.com` and the `authz.` and `ingest.` hosts beside
  it; `management_url` overrides it.
- **Shape.** Namespaces and methods follow the API's namespaces and operation
  ids: `client.users.list_sessions`, `client.billing.invoices.get_pdf`,
  `client.authn.password_policy.update`. Bodies are dicts, results are dicts, both
  typed with the TypedDicts in `pontive.management.types`. Query and header
  parameters are keyword arguments.
- **Retries.** A 429, a 5xx or a network failure is retried twice with backoff,
  honouring `Retry-After`, when the call is safe to repeat: any method but
  `POST`, or a `POST` that takes an idempotency key, which the client sets for
  you (`request_options={"idempotency_key": ...}` to choose it).
- **Errors.** A refusal raises `pontive.management.APIError`, a subclass per
  status (`NotFoundError`, `ConflictError`, `RateLimitError`, …), with `code`,
  `details` and `request_id`. No answer at all is `APIConnectionError`.
- **Headers.** `request_options={"on_response": callback}` sees each response,
  for a header such as the `ETag` an `if_match=` update needs.
- **Billing** is typed like the rest: `client.billing.customers.create({"name":
  "Acme"})` takes a `CreateCustomerRequest` and returns a `Customer`
  (TypedDicts).
- Not in this client: the platform API (`api.pontive.com`: workspaces,
  projects, instances).

The client is generated from the management API's OpenAPI documents;
`pontive/management/_generated` is not edited by hand.

## Environment

The variables every Pontive SDK reads, so docs read the same in every language.
A value passed in code always wins.

| Variable | Read by |
| --- | --- |
| `PONTIVE_ISSUER` | `ServerAuth` |
| `PONTIVE_CLIENT_ID` | `ServerAuth` |
| `PONTIVE_CLIENT_SECRET` | `ServerAuth` |
| `PONTIVE_SESSION_SECRET` | `ServerAuth` |
| `PONTIVE_SECRET_KEY` | `Pontive`, `AsyncPontive` |
| `PONTIVE_INSTANCE_ID` | `Pontive`, `AsyncPontive`: sent as `X-Pontive-Instance-ID` |
| `PONTIVE_MANAGEMENT_URL`, `PONTIVE_REGION` | `Pontive`, `AsyncPontive`: where the management API is |

The SDK reads the process environment only. To load a `.env` file, use
python-dotenv or your framework's settings.

## Design notes

- **Dependencies.** `httpx` gives one API for sync and async HTTP, and a
  `MockTransport` for tests. `joserfc` does JWS, JWE and JWK in one library,
  depends only on `cryptography`, is typed, and takes an explicit algorithm list
  on every call. PyJWT has no JWE (sealing would need a second library);
  python-jose is unmaintained; authlib brings a whole OAuth framework.
- **One protocol implementation.** Every HTTP exchange is written once, as a
  generator that yields requests; the sync and async methods only drive it. They
  cannot drift apart.
- **Sealing.** JWE compact, `dir` + `A256GCM`, keyed by the SHA-256 of
  `session_secret`, with `iat` and `exp`. The same format and payload as
  `@pontive/server`, so a Python app and a Node app sharing a domain, cookie name
  and secret read each other's sessions.
- **Refresh.** One refresh per refresh token in flight per process (threads
  wait on the first; coroutines share one task), and its result handed to late
  requests still holding the old cookie for 30 seconds. Across replicas the
  auth server's reuse grace covers the race. A `4xx` signs out; a network error
  or `5xx` keeps the session for the next request.
- **Keys.** Cached ten minutes; an unknown `kid` refetches the set at most once
  per 30 seconds, so a rotation is picked up at once. Keys that went stale while
  the issuer is unreachable keep verifying.

Not in this SDK, by design: `@pontive/server`'s **keyless mode** (it provisions an
unclaimed instance from inside a Node dev server). A Python app runs
`npx pontive@latest init` in its project directory and loads the variables it
writes to `.env.local`.


## Examples

[`examples/`](examples): an API with FastAPI, sign-in with Flask, sign-in with
Django in one file. Each says how to run it.

## Development

```sh
uv sync
uv run pytest
uv run ruff check src tests examples && uv run ruff format --check src tests examples
uv run mypy
```

Commits follow Conventional Commits; release-please opens the release PR.

## License

MIT
