Metadata-Version: 2.5
Name: origo
Version: 0.8.0
Summary: Drop-in OAuth 2.1 provider for servers. Developed originally for custom/private MCP servers. Works with FastMCP, FastAPI, and the raw MCP SDK.
Project-URL: Homepage, https://github.com/ieepirzy/origo
Project-URL: Documentation, https://github.com/ieepirzy/origo/blob/main/README.md
Project-URL: Source, https://github.com/ieepirzy/origo
Project-URL: Issues, https://github.com/ieepirzy/origo/issues
Author-email: ieepirzy <nervy_colder_1m@icloud.com>
License: MIT
License-File: LICENSE
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Internet :: WWW/HTTP :: HTTP Servers
Classifier: Topic :: Security
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Requires-Python: >=3.12
Requires-Dist: anyio>=3.0.0
Requires-Dist: cryptography>=41.0.0
Requires-Dist: python-multipart>=0.0.9
Requires-Dist: starlette>=0.27.0
Provides-Extra: code-health
Requires-Dist: pyright==1.1.408; extra == 'code-health'
Requires-Dist: radon==6.0.1; extra == 'code-health'
Requires-Dist: ruff==0.16.4; extra == 'code-health'
Provides-Extra: code-health-otel
Requires-Dist: opentelemetry-exporter-otlp-proto-http==1.44.0; extra == 'code-health-otel'
Requires-Dist: opentelemetry-sdk==1.44.0; extra == 'code-health-otel'
Provides-Extra: dev
Requires-Dist: fastmcp>=2.12.0; extra == 'dev'
Requires-Dist: httpx; extra == 'dev'
Requires-Dist: pytest; extra == 'dev'
Requires-Dist: pytest-asyncio; extra == 'dev'
Requires-Dist: pytest-cov; extra == 'dev'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.100.0; extra == 'fastapi'
Provides-Extra: fastmcp
Requires-Dist: fastmcp>=2.12.0; extra == 'fastmcp'
Description-Content-Type: text/markdown

# origo

[![CI](https://github.com/ieepirzy/origo/actions/workflows/ci.yml/badge.svg)](https://github.com/ieepirzy/origo/actions/workflows/ci.yml)
[![PyPI version](https://img.shields.io/pypi/v/origo)](https://pypi.org/project/origo/)
[![Python versions](https://img.shields.io/pypi/pyversions/origo)](https://pypi.org/project/origo/)

> Implements the OAuth2.1 + PKCE flow as a drop-in Starlette based middleware layer, with public and private registration modes.

Drop-in OAuth 2.1 provider, originally developed for use in custom/private MCP servers. Handles the full Authorization Code + PKCE flow with no external identity provider required.

Works with **FastMCP**, **FastAPI**, the raw **MCP SDK**, and MCP clients on the **OpenAI platform** such as ChatGPT connectors.

> **Upgrading to 0.4.0?** `/authorize` now refuses requests unless people sign in through an identity provider, or you opt back in to the approve-only consent page. Set `ORIGO_ALLOW_UNAUTHENTICATED_CONSENT=true` **before** upgrading to keep today's behaviour. See [Upgrading to 0.4.0](#upgrading-to-040).

## Install

```bash
pip install origo
```

## Quickstart

### FastMCP

```python
from fastmcp import FastMCP
from origo import OAuthProvider, OAuthMiddleware
from starlette.routing import Mount
from starlette.applications import Starlette
import os

auth = OAuthProvider(
    base_url="https://mcp.yourdomain.com",
    clients={os.getenv("MCP_CLIENT_ID"): os.getenv("MCP_CLIENT_SECRET")},
)

mcp = FastMCP("my-server")

# ... define tools ...

mcp_app = mcp.streamable_http_app()
mcp_app.add_middleware(OAuthMiddleware, provider=auth)

# OAuth must be at root so /.well-known/ discovery works for MCP clients
root = Starlette(routes=[
    Mount("/mcp", app=mcp_app),      # protected MCP endpoint
    Mount("/", app=auth.asgi_app()), # /.well-known/, /authorize, /token, /register
])
```

### FastAPI

```python
from fastapi import FastAPI
from origo import OAuthProvider, OAuthMiddleware
from starlette.routing import Mount
from starlette.applications import Starlette
import os

auth = OAuthProvider(
    base_url="https://api.yourdomain.com",
    clients={os.getenv("OAUTH_CLIENT_ID"): os.getenv("OAUTH_CLIENT_SECRET")},
)

api = FastAPI()
api.add_middleware(OAuthMiddleware, provider=auth)

# ... define routes on api ...

app = Starlette(routes=[
    Mount("/api", app=api),          # protected API routes
    Mount("/", app=auth.asgi_app()), # OAuth at root
])
```


### MCP over SSE (`/sse`) deployments

Some MCP clients and hosted connector surfaces expect an SSE MCP endpoint such as `https://mcp.yourdomain.com/sse` instead of a streamable HTTP endpoint such as `/mcp`. Origo does not implement the MCP transport itself; your MCP server or deployment chooses whether `/sse`, `/mcp`, or both exist. Origo should wrap that MCP ASGI app with `OAuthMiddleware`, and `mcp_path` must match the externally visible protected MCP route so `/.well-known/oauth-protected-resource` advertises the same resource URI the client will request.

```python
from fastmcp import FastMCP
from origo import OAuthMiddleware, OAuthProvider
from starlette.applications import Starlette
from starlette.routing import Mount
import os

auth = OAuthProvider(
    base_url="https://mcp.yourdomain.com",
    clients={os.getenv("MCP_CLIENT_ID"): os.getenv("MCP_CLIENT_SECRET")},
    mcp_path="/sse",  # resource metadata becomes https://mcp.yourdomain.com/sse
)

mcp = FastMCP("my-server")

# Use your MCP framework's SSE ASGI app here. The exact constructor varies by
# framework/version; for FastMCP this may be `sse_app()` in SSE deployments.
sse_app = mcp.sse_app()
sse_app.add_middleware(OAuthMiddleware, provider=auth)

app = Starlette(routes=[
    Mount("/sse", app=sse_app),       # protected SSE MCP endpoint
    Mount("/", app=auth.asgi_app()), # OAuth and /.well-known/ discovery
])
```

If your server exposes both `/mcp` and `/sse`, create the protected-resource metadata for the endpoint your connector is configured to call. For multiple public MCP resources on one host, use separate `OAuthProvider` instances or deploy separate base URLs so each provider advertises one canonical `resource` value.

## How this differs from enterprise OAuth

Traditional OAuth deployments separate the authorization server from the resource server — the MCP server asks a dedicated auth service "is this token valid?" on every request (RFC 7662 token introspection). This is correct for multi-tenant systems where tokens need to be revoked instantly across many services.

`origo` collapses this into a single process. Token validation is an in-process lookup. Fast, zero network overhead, no second service to run. The tradeoff is that there's no centralized auth service to share across multiple resource servers. This also introduces a single point of failure, and security relies on sharing a process with the application it is authenticating for.

By default, origo persists state to a local SQLite file, so tokens survive restarts and redeploys — revocation means deleting rows from (or simply deleting) that file, not restarting. Pass `storage_path=None` for the old in-memory-only behavior instead, where a restart revokes everything (and forces every client through interactive re-authorization). See [Token persistence](#token-persistence) for the default file location and how to relocate or disable it.

**Use this when:**

- You're running a personal or private server (ex. MCP server) with simple OAuth requirements
- You control who gets client credentials
- Operational simplicity matters more than enterprise auth guarantees

**Put an identity provider in front (see [Per-user sign-in](#per-user-sign-in-upstream-oidc)) when:**

- Multiple users need independent identities. origo delegates the sign-in to your IdP (Keycloak, Google Workspace, Entra, …) and carries each person's identity in its own tokens.

**Use a proper auth server (Keycloak, Auth0, etc.) as the authorization server itself when:**

- You need instant token revocation
- You're sharing one auth service across many servers (ex. MCP servers)
- Compliance requirements mandate it

## Per-user sign-in (upstream OIDC)

By default nobody signs in on origo's consent page: it is an approve/deny button, so whoever opens the authorize URL can approve, and every token carries the same static `sub`. To tell people apart, configure an upstream OpenID Connect provider. `/authorize` then always sends the person to the IdP's own sign-in page (email, password, MFA — origo never sees a password) and issues a code only after verifying the IdP's answer:

```python
from origo import IdentityProvider, OAuthProvider

auth = OAuthProvider(
    base_url="https://mcp.example.com",
    public_registration=True,                      # e.g. claude.ai connectors via CIMD
    cimd_allowed_clients=["claude.ai"],             # which connector platforms may start a sign-in
    token_ttl=900,                                  # short: see "Disabled users" below
    identity_provider=IdentityProvider(
        issuer="https://auth.example.com/realms/staff",
        client_id=os.environ["OIDC_CLIENT_ID"],
        client_secret=os.environ["OIDC_CLIENT_SECRET"],
        allowed_email_domains=["example.com"],     # optional gate
        allowed_groups=["/mcp-users"],              # optional gate
    ),
)
```

The flow, per authorization:

1. The client identifies itself as before (pre-registered, DCR, or CIMD) and its `redirect_uri` is checked. With an IdP, `public_registration=True` **requires** `cimd_allowed_clients` (origo refuses to start without it): there is no consent screen, and a person with a live IdP session is signed in without a click, so any self-registered client could otherwise collect codes carrying their identity. The allowlist limits self-registered clients to the listed CIMD documents, turns DCR off, and refuses every other self-registered client, including ones persisted before the list existed. Never list a wildcard on a shared hosting domain (`*.vercel.app`, `*.github.io`, …): anyone can publish a CIMD document there. origo refuses the common ones and any wildcard over a single label (`*.app`), but the list is not exhaustive. With an IdP and `public_registration=False`, only pre-registered clients may authorize or refresh: self-registered clients left over from an earlier public deployment are refused.
2. origo parks the request and redirects to the IdP's authorization endpoint (found by discovery at `<issuer>/.well-known/openid-configuration`) using the code flow with PKCE, `state` and `nonce`. A `__Host-origo_login` cookie binds the sign-in to the browser that started it.
3. The IdP redirects back to **`{base_url}/authorize/callback`**. origo exchanges the code and verifies the `id_token`: signature against the IdP's JWKS (asymmetric algorithms only; `none` and HMAC are refused), `iss`, `aud`/`azp`, `exp` and `nonce`.
4. The allow gate runs: every configured gate must pass. `allowed_email_domains` matches the **verified** email's domain exactly (no subdomains); `allowed_groups` needs at least one exact match in the `groups_claim` claim (default `groups`; a dotted path such as `realm_access.roles` reaches nested claims). A refused or failed sign-in returns `error=access_denied` to the client and issues no code.
5. origo issues its own code, and from it its own tokens, carrying the person's claims.

**Claims.** `sub` is `<issuer>|<idp sub>`, so two IdPs or realms can never collide. `email` is included only when the IdP asserts `email_verified: true`. `name` and `groups` are included when present. The claims are stored with the grant, so they survive refresh-token rotation without another trip to the IdP. They surface in three places:

- `provider.verify_token(token)` returns `sub`, `email`, `name`, `groups` alongside `client_id`, `scope`, `resource` and `expires_at`, so a resource server can attribute a request to both the person and the client. The FastMCP adapter passes the same dict through as `AccessToken.claims`.
- With `extra_claims`, `verify_token` also returns `idp_claims`: the listed id_token claims exactly as the IdP issued them (see *Extra claims* below).
- `/userinfo` returns `sub`, plus `email` (`email` scope), `name` (`profile` scope) and `groups` (`groups` scope).
- The `id_token` from `/token` (for `openid` requests) carries the same claims under the same scope rules.

With an IdP configured, `auto_approve` and the consent page are never used, `POST /authorize` is refused, and tokens that name no person (for example ones persisted from before the IdP was configured) stop validating: those clients sign in again.

**Keycloak setup** (the first deployment target; any OIDC provider works the same way):

- Create a confidential OpenID Connect client with *Standard flow* on. Set its *Valid redirect URI* to exactly `https://<your origo base_url>/authorize/callback`.
- `issuer` is `https://<keycloak host>/realms/<realm>` (no trailing slash).
- For `allowed_groups`, add a *Group Membership* mapper to the client (or a client scope it uses) with *Add to ID token* on. With *Full group path* on, groups appear as `/name`; match them exactly as emitted.
- Users created by an admin need *Email verified* set, or the email claim is dropped and the domain gate refuses them.

**Disabled users.** By default, refresh does not go back to the IdP, so two bounds stand in for it. A signed-in grant can be refreshed only until `max_grant_age` (an `IdentityProvider` argument, default 12 hours) after the sign-in; then `/token` refuses and the client has to send the person back through `/authorize` (connector clients typically show "reconnect" rather than doing it silently). And every refresh re-applies the allow gate against the current configuration, so removing a group from `allowed_groups` (or a domain from `allowed_email_domains`) takes effect at the next refresh. A refused refresh also revokes the grant's live tokens. Within those bounds, a disabled person keeps access until `max_grant_age` runs out, so keep `token_ttl` short.

**Re-checking the IdP on every refresh** (`recheck_on_refresh=True`). origo keeps the IdP's own refresh token for each grant and, on every origo refresh, refreshes at the IdP first. Revocation then happens server-side and doesn't depend on what the client holds:

```python
IdentityProvider(
    issuer="https://auth.example.com/realms/staff",
    client_id=..., client_secret=...,
    allowed_groups=["/mcp-users"],
    recheck_on_refresh=True,
    token_key_files=["/run/secrets/origo-token-key"],   # 32 bytes: raw, hex or base64
)
```

- The IdP answering `invalid_grant` (account disabled, signed out, session revoked, SSO session idle or max reached), a different subject, or fresh claims failing the allow gate **ends the grant**: `/token` answers `invalid_grant` and every live access and refresh token of the grant is revoked. A disabled person loses access within one `token_ttl`.
- Fresh claims (name, email, groups) replace the stored ones on each refresh.
- An IdP that can't be reached or answers 5xx gets a `503 temporarily_unavailable` with `Retry-After`; the client's refresh token is **not** spent and the grant is kept, so a retry succeeds once the IdP is back.
- A grant's lifetime then follows the IdP's session settings (Keycloak: *SSO Session Idle/Max*, *Client Session Idle/Max*). A refresh every `token_ttl` keeps an idle timeout longer than it alive; a *Max* shorter than a working day means a sign-in sooner. `max_grant_age` stays an absolute upper bound on top.
- The IdP refresh tokens are sealed at rest with AES-256-GCM, each bound to its grant. The first key seals and every listed key opens, so to rotate a key put the new one first, keep the old one until every grant has refreshed once (each refresh re-seals under the first key), then drop it. Keys are required: `recheck_on_refresh` without one is a configuration error.
- The origo client at the IdP must be issued refresh tokens (Keycloak's default for a standard-flow client). A sign-in where the IdP issues none fails with `server_error`. If the IdP returns no `id_token` on refresh, origo reads the claims from its `userinfo_endpoint`.
- **Upgrading:** grants issued before `recheck_on_refresh` was turned on hold no IdP token, so their next refresh is refused and the person signs in once.

**Extra claims** (`extra_claims=[...]`). A resource server that needs more of the IdP's answer than `sub`, `email`, `name` and `groups`, such as which organizations the person belongs to or their roles on one client, names those id_token claims, each a name or a dotted path:

```python
IdentityProvider(
    issuer="https://auth.example.com/realms/staff",
    client_id=..., client_secret=...,
    extra_claims=["my_organizations", "resource_access.my-app.roles"],
    recheck_on_refresh=True, token_key_files=[...],
)
```

- `verify_token` returns them under `idp_claims`, re-nested along their paths (`{"my_organizations": {...}, "resource_access": {"my-app": {"roles": [...]}}}`). Only the listed paths are kept: other clients' roles under `resource_access` stay behind. A path the id_token lacks is left out, and `idp_claims` is absent when none is present.
- origo never interprets them, never mixes them in with its own claims, and never releases them in its own `/userinfo` or `id_token`. They are the IdP's statements for the resource server to judge.
- They are stored with the grant like the other claims. With `recheck_on_refresh` they are replaced from the IdP on every refresh, so a role or membership removed at the IdP is gone within one `token_ttl`. Without it they keep the sign-in's values until `max_grant_age`.
- At most 16 KiB of JSON (`origo.oidc.MAX_EXTRA_CLAIMS_BYTES`). A sign-in or recheck whose claims are larger is refused, never truncated.
- Managed sign-in (`ManagedSignIn`) finds the person through Keycloak's admin API, not an id_token, so its grants carry `idp_claims` only for what its own lookups put there (`client_roles_claim`, `organizations_claim`, below). A resource server that depends on any other refuses those tokens by itself.
- On Keycloak, the mapper behind each claim needs *Add to ID token* on, and *Add to userinfo* too if refreshed id_tokens are switched off.

**Several origo instances, one IdP.** Each origo deployment registers its own callback URL at the IdP (one client per deployment, or one client listing every callback). Pending sign-ins live in origo's storage, so processes that share one SQLite file can take each other's callbacks; separate deployments with separate storage each hold their own grants.

## Managed sign-in (ID-JAG, claude.ai managed authorization)

With an upstream identity provider configured, origo can also accept
**Identity Assertion JWT Authorization Grants** (draft-ietf-oauth-identity-assertion-authz-grant):
claude.ai's "managed authorization" connects every member of your organization
once, without each of them going through a browser sign-in. claude.ai signs a
short-lived assertion naming the member; its client presents it at `/token` as
an RFC 7523 `urn:ietf:params:oauth:grant-type:jwt-bearer` grant.

```python
from origo import IdentityProvider, ManagedSignIn, OAuthProvider

auth = OAuthProvider(
    base_url="https://mcp.example.com",
    public_registration=True,
    cimd_allowed_clients=["claude.ai"],
    identity_provider=IdentityProvider(
        issuer="https://auth.example.com/realms/staff",
        client_id="my-mcp",
        client_secret=os.environ["IDP_CLIENT_SECRET"],
    ),
    managed_sign_in=ManagedSignIn(
        # claude.ai -> Organization -> Connectors -> managed authorization:
        # "Claude-issued", the Issuer URL it shows (one per organization).
        issuer="https://identity.anthropic.com/issuers/iss_...",
        tenant=None,  # or the Tenant ID you entered there
        group_paths=False,  # match the realm's group mapper "Full group path"
    ),
)
```

What origo checks: header `typ` `oauth-id-jag+jwt` and an asymmetric `alg`;
the signature against the pinned issuer's JWKS; `iss`; `aud` is origo's own
issuer (`base_url`); `client_id` is the client calling `/token`, which must be
on `cimd_allowed_clients` and declare the grant in its metadata document;
`exp`, `iat` (no older than `max_assertion_age`, 300 s), `nbf`; `jti` is single
use (persisted, so replay is refused across restarts); `aud_tenant` when a
tenant is configured; `resource`, if present, is this server; the email is
plain ASCII. Non-finite times (`NaN`, `Infinity`) are refused.

Assertions are **not sender-constrained**: claude.ai's client is public and
the issuer does not bind them, so a leaked assertion could be redeemed once
within `max_assertion_age`. An assertion that carries `cnf` is refused, since
origo cannot verify the binding.

**Who the token is for.** The assertion only says "a member of this
organization, with this email". The token is for the one **enabled** Keycloak
user whose **verified** email matches, with no pending required actions and
no brute-force lockout, with the same subject
(`<issuer>|<keycloak id>`), groups and allow gate as an interactive sign-in. No
such user (or two) means `invalid_grant`: managed sign-in never creates
identities. By default the lookup uses the identity provider's own client
with the client-credentials grant, so the Keycloak client needs **Service
accounts** enabled and the realm-management role **view-users** (or use a
separate directory client, below). Browser-flow policies
(conditional access in a custom authentication flow) do not apply to this
path; the allow gate does.

**Keycloak's admin API inside the cluster.** If Keycloak exposes only
`/realms` publicly, point the lookup at its Service:
`ManagedSignIn(..., directory_url="http://keycloak.keycloak.svc.cluster.local:8080")`,
or set `ORIGO_MANAGED_SIGNIN_DIRECTORY_URL`. Plain http is accepted only for
a `*.svc.cluster.local` name; the client-credentials token still comes from
the issuer's token endpoint.

**A separate directory client.** The lookup's read roles sit on whichever
client takes the client-credentials token. If the identity provider's client
secret is also held elsewhere (say, by a web app signing people in with the
same client), give the reads to a dedicated client instead: a confidential
Keycloak client with service accounts only and no login flows, holding the
realm-management roles above, while the identity provider's client keeps
**Service accounts** off.

```python
ManagedSignIn(
    issuer="https://identity.anthropic.com/issuers/iss_...",
    directory_client_id="my-mcp-directory",
    # Read on each token fetch, so a rotated secret needs no restart.
    directory_client_secret_file="/run/secrets/directory-client-secret",
)
```

Or set `ORIGO_MANAGED_SIGNIN_DIRECTORY_CLIENT_ID` and
`ORIGO_MANAGED_SIGNIN_DIRECTORY_CLIENT_SECRET_FILE` (`directory_client_secret=`
takes the secret itself). Its token comes from the identity provider's token
endpoint, and origo never falls back to the identity provider's client: an
unreadable secret fails the sign-in (`server_error`, retryable), and half a
configuration (an id without a secret, or the reverse) is refused at start.
`client_roles_claim` still reads the person's roles in the identity
provider's own client; only the caller changes.

**Client roles and organizations.** By default the person is looked up with
their realm groups only. When the allow gate (or the resource server) reads
something else an interactive sign-in gets from the realm's mappers, ask for
it explicitly; each is opt-in and needs one more realm-management role:

```python
ManagedSignIn(
    issuer="https://identity.anthropic.com/issuers/iss_...",
    # The person's effective roles in the identity provider's own client,
    # where the realm's client-role mapper puts them. Point groups_claim here
    # to gate on them ("my-mcp": the identity provider's client_id). Needs
    # view-clients as well.
    client_roles_claim="resource_access.my-mcp.roles",
    # The person's organizations as {alias: {"id": id}}, the organization
    # membership mapper's shape with "Add organization id" on, for a gate
    # (IdentityProvider.check_gate's claims) that reads it. Needs
    # view-organizations.
    organizations_claim="my_organizations",
)
```

Both fail closed: if the lookup cannot be made or its answer cannot be read
(a missing realm-management role, an organization without an alias and id), `/token` answers
`503 temporarily_unavailable` and issues nothing. A missing `view-clients` is
caught at the client lookup, because Keycloak answers a role read for a client
the caller may not view with an empty list, not an error. Every organization
the person belongs to counts, a disabled one too (the mapper leaves those
out). `organizations_claim` must be exactly the claim your gate reads (a gate
looking elsewhere sees no organizations), and needs organizations enabled on
the realm. A `resource_access.<client>.roles` path must name the identity
provider's own client, whose roles it carries; any other is refused. Neither claim may sit under `sub`, `email`, `email_verified`, `name` or
`groups`, which origo sets itself. A claim also listed in the identity
provider's `extra_claims` reaches `idp_claims` as it would from an id_token.

No refresh token is issued: claude.ai asks for a fresh assertion, so removing
someone from the organization or disabling them in Keycloak stops them at
their next exchange (at most one `token_ttl`).

## Approve-only consent (no identity provider)

Without an `identity_provider`, `/authorize` **fails closed**: it answers `403 access_denied` and issues nothing, because the consent page would authenticate nobody. To keep the approve-only page (single-operator deployments, local development), opt in explicitly:

- **`ORIGO_ALLOW_UNAUTHENTICATED_CONSENT=true`** (env var), or
- **`allow_unauthenticated_consent=True`** in code. An explicit `False` overrides the env var.

origo logs a warning at startup when this is on. `auto_approve=True` is honoured only under this opt-in.

## Upgrading to 0.4.0

0.4.0 is a breaking release ([#130](https://github.com/ieepirzy/origo/issues/130)):

- **`/authorize` fails closed without an identity provider.** Deployments that rely on the consent page or `auto_approve=True` must set `ORIGO_ALLOW_UNAUTHENTICATED_CONSENT=true` (or pass `allow_unauthenticated_consent=True`) **before upgrading**, or every new authorization is refused. Existing access and refresh tokens keep working either way.
- **`verify_token` no longer reports a person for approve-only tokens.** It gains `sub`/`email`/`name`/`groups` only for tokens issued after upstream sign-in. `/userinfo` and the `id_token` still return the static `user_subject`/`user_email` for approve-only tokens.
- **SQLite storage is migrated automatically** on first open (new nullable `claims` columns and a `pending_logins` table). Downgrading to 0.3.x after tokens with claims were issued is not supported.
- **Stop every 0.3.x process before starting 0.4.0 on a shared SQLite file.** 0.3.x writes rows positionally, so once 0.4.0 has migrated the file, an old process still running against it fails its writes. No rolling upgrade across the two versions.

New: `identity_provider` (upstream OIDC sign-in), `cimd_allowed_clients`, the `/authorize/callback` route (public, like `/authorize`). Test suites that drive the consent flow should set `ORIGO_ALLOW_UNAUTHENTICATED_CONSENT=true` in their setup, next to `ORIGO_STORAGE_PATH=""`.

## Two Modes

### Private (default)

Only pre-registered clients can authenticate. Pass a `clients` dict:

```python
auth = OAuthProvider(
    base_url="https://mcp.yourdomain.com",
    clients={"my-client-id": "my-client-secret"},
    public_registration=False,  # default
)
```

### Public

Anyone can register as a client dynamically (DCR). A consent page is shown before access is granted:

```python
auth = OAuthProvider(
    base_url="https://mcp.yourdomain.com",
    public_registration=True,
)
```

Dynamically registered clients must supply `redirect_uris` at registration time. The `/authorize` endpoint validates the `redirect_uri` parameter against that registered list and rejects any URI not on it. Pre-registered clients (supplied via `clients=`) get their allowlist from `client_redirect_uris` and are held to the same exact-match, fail-closed rule: a pre-registered client with no configured URIs rejects every `redirect_uri`.

### Redirect URIs for pre-registered clients

Every rejected `redirect_uri` is logged on the `origo` logger (WARNING level) together with its `client_id`, so when a connector with an undocumented callback URL fails at `/authorize`, the exact value to add to `client_redirect_uris` is one log line away.

A pre-registered **confidential** client (one with a real secret) can opt out of exact matching entirely with the `ANY_REDIRECT_URI` sentinel, as the whole allowlist:

```python
from origo import ANY_REDIRECT_URI, OAuthProvider

auth = OAuthProvider(
    base_url="https://mcp.yourdomain.com",
    clients={"my-client-id": "my-client-secret"},
    client_redirect_uris={"my-client-id": ANY_REDIRECT_URI},  # or [ANY_REDIRECT_URI]
)
```

This exists for single-operator deployments facing connector surfaces (ChatGPT, Grok, …) whose callback URLs are undocumented or change, where the alternative would be the strictly more open `public_registration=True`. Know what it trades away before using it:

- **What still holds:** the client secret gates `/token`, so an authorization code that leaks to an attacker's redirect URI cannot be exchanged for a token; scheme validation still applies (`https` only, plus the loopback exemption and any `custom_redirect_uri_schemes`, never `javascript:`/`data:`); PKCE and `state` work unchanged; every wildcard-accepted URI is logged at INFO with its `client_id`, so you can harvest real connector callbacks and later pin them down to an exact list.
- **What it gives up:** exact redirect URI matching is a defense-in-depth layer required by the OAuth Security BCP (RFC 9700) — with it off, everything rests on the secret staying secret, and `/authorize` will bounce a browser to any `https` URL for anyone who knows the public `client_id` (with `auto_approve=True`, without even a consent page in between).

The sentinel is rejected at startup for clients without a secret, when mixed with explicit URIs, and is never available to dynamically registered clients.

Redirect URIs are validated for header safety independently of the fronting server: a `redirect_uri` containing a C0 control character (CR/LF response-splitting, NUL, tab, …), DEL, or a lone surrogate is rejected at `/authorize` (and at dynamic registration) rather than reflected into a `Location` header or allowed to raise an encoding error. `origo` does not rely on the ASGI server in front of it to strip such input.

By default, dynamically registered `redirect_uris` must use `https` (or `http://localhost`/`127.0.0.1`/`::1` for the RFC 8252 §7.3 native-app loopback exemption). Native/mobile app clients that use a private-use URI scheme instead (RFC 8252 §7.1, e.g. `myapp://callback`) are rejected unless the operator explicitly opts in:

```python
auth = OAuthProvider(
    base_url="https://mcp.yourdomain.com",
    public_registration=True,
    custom_redirect_uri_schemes=["myapp"],
)
```

Only schemes listed here are accepted — arbitrary `foo://` schemes are always rejected, since an unclaimed scheme could be registered by another app on the same device.

## Token persistence

**origo persists OAuth state to SQLite by default.** Every restart, redeploy, or crash used to silently log out every connected client — each one had to go through interactive re-authorization, which for long-lived MCP connectors presented as "auth randomly breaks". As of this version, that's no longer the default: with no code changes at all, an existing `OAuthProvider(...)` call now writes tokens to a SQLite file instead of keeping them only in memory. It stays a drop-in: same process, no extra service.

```python
auth = OAuthProvider(
    base_url="https://mcp.yourdomain.com",
    clients={os.getenv("MCP_CLIENT_ID"): os.getenv("MCP_CLIENT_SECRET")},
    # storage_path omitted -> persists automatically, see below
)
```

**Where it persists to.** With `storage_path` omitted, origo writes to `./.origo/<hash>.db` relative to the process's working directory, where `<hash>` is derived from `base_url` + `mcp_path` (so multiple `OAuthProvider` instances, or restarts of the same deployment, land on the same file without a collision). Two ways to change that without touching code:

- **`ORIGO_STORAGE_PATH=/data/origo`** (env var) — persists under that directory instead. Point this at a mounted volume so tokens survive a full redeploy, not just an in-process restart — `./.origo` under an ephemeral container filesystem only survives a crash/reload of the *same* container.
- **`ORIGO_STORAGE_PATH=`** (set to the empty string) — forces in-memory storage, restoring the pre-persistence behavior without editing code. Useful for test suites and CI.

And two ways in code:

- `storage_path=None` — the permanent, explicit opt-out: always in-memory, regardless of `ORIGO_STORAGE_PATH`.
- `storage_path="/exact/path/to/origo.db"` — persist to that exact file, ignoring the auto-derived default and `ORIGO_STORAGE_PATH`.

If the default path can't be created or opened (read-only filesystem, permission error), origo warns and falls back to in-memory storage for that run rather than failing to start — persistence quietly degrading to the old behavior is the safe failure mode for something that was never explicitly requested. An **explicit** `storage_path` that can't be opened raises instead, since a caller who asked for persistence by name should find out immediately if they didn't get it.

What persists: access tokens, refresh tokens, pending auth codes, and dynamically-registered (DCR/CIMD) clients. What doesn't: pre-registered `clients=` (your config re-seeds them every boot, so they are never written to disk) and the per-process RSA signing key (ID tokens are verified at delivery, so a restart only rotates the JWKS).

Security properties of the file:

- Every credential — auth codes, access tokens, refresh tokens, dynamic client secrets — is stored **only as a SHA-256 hash**. A copy of the database file yields no replayable credential. (This works because origo generates all of these as high-entropy random values; there is nothing guessable to attack offline.)
- The file is created with `0600` permissions, and SQLite's WAL sidecar files inherit that mode.
- Because dynamic client secrets are hashed, they exist in plaintext only in the one `/register` response that delivered them.

Two operational consequences worth knowing:

- **Revocation**: with in-memory storage a restart revoked everything; with persistence it deliberately doesn't. To revoke, delete rows from the SQLite file (or delete the file) — tokens are keyed by SHA-256 hash of the token value.
- **Registration flooding**: dynamically-registered clients also survive restarts, so on a `public_registration=True` deployment the `max_dynamic_clients` cap can now fill up permanently instead of being cleared by the next restart. Set `client_ttl` so abandoned registrations expire; origo warns at startup if you don't.

If you run multiple workers/processes against the same file, SQLite's WAL mode plus origo's transactional single-use exchanges (including reuse-detection's revoked-family marker) keep codes and refresh tokens atomic across processes — but note each process still generates its own RSA signing key, so run a single process if you rely on ID tokens.

**Upgrading from an in-memory-only origo version:** if your test suite constructs more than one `OAuthProvider` with the *same* `base_url`/`mcp_path` pair across different test cases and expects each to start with an empty store (a common pattern — reusing a fixed test `base_url` everywhere), those instances now share one persisted file by default and will leak state between tests. Set `ORIGO_STORAGE_PATH=""` for your test run (a single environment variable, e.g. in your test suite's setup or CI env) to keep the old fully-isolated-in-memory behavior; individual tests that want to exercise real persistence can still pass `storage_path=` explicitly, which always overrides the environment variable.

## Options

| Parameter | Type | Default | Description |
| --- | --- | --- | --- |
| `base_url` | `str` | required | Public base URL, no trailing slash |
| `clients` | `dict` | `None` | Pre-registered `{client_id: client_secret}` |
| `client_redirect_uris` | `dict` | `None` | Optional redirect URI allowlist for pre-registered clients (exact-match, fail-closed). A confidential client may map to `ANY_REDIRECT_URI` instead of a list — see [Redirect URIs for pre-registered clients](#redirect-uris-for-pre-registered-clients) |
| `public_registration` | `bool` | `False` | Allow dynamic client registration |
| `auto_approve` | `bool` | `False` | Skip consent page, auto-approve all valid clients. Only honoured with `allow_unauthenticated_consent`; ignored with an `identity_provider` |
| `identity_provider` | `IdentityProvider` | `None` | Upstream OIDC sign-in for every authorization — see [Per-user sign-in](#per-user-sign-in-upstream-oidc) |
| `allow_unauthenticated_consent` | `bool` | `None` (reads `$ORIGO_ALLOW_UNAUTHENTICATED_CONSENT`) | Without an IdP, allow the approve-only consent page instead of failing closed — see [Approve-only consent](#approve-only-consent-no-identity-provider) |
| `cimd_allowed_clients` | `list[str]` | `None` (any) | CIMD clients allowed to authorize: exact `client_id` URLs and/or host patterns (`"claude.ai"`, `"*.example.com"`; never a shared-hosting wildcard like `*.vercel.app`). When set, DCR (`/register`) is disabled and every other self-registered client, including already-persisted ones, is refused. Required with `identity_provider` + `public_registration=True` |
| `token_ttl` | `int` | `3600` | Access token lifetime in seconds |
| `refresh_token_ttl` | `int` | `2592000` (30 days) | Refresh token lifetime in seconds. Refresh tokens are single-use and rotated on every `/token` request; replaying a used one revokes the whole token family |
| `storage_path` | `str` | auto (`./.origo/<hash>.db`, or `$ORIGO_STORAGE_PATH`) | Path to a SQLite file for persistent storage (see [Token persistence](#token-persistence)). Pass `None` explicitly to force in-memory storage |
| `client_ttl` | `int` | `None` | Lifetime in seconds for dynamically-registered clients (DCR `/register` or CIMD). `None` means no expiration. Pre-registered `clients=` are always permanent |
| `max_dynamic_clients` | `int` | `1000` | Max number of dynamically-registered clients (DCR/CIMD) kept at once; registrations past the cap are rejected (HTTP 429) until existing ones expire via `client_ttl`. Pre-registered `clients=` don't count against this cap |
| `mcp_path` | `str` | `"/mcp"` | Path where MCP endpoint is mounted |
| `scopes_supported` | `list[str]` | `[]` | OAuth/OIDC scopes advertised in metadata |
| `resource_documentation` | `str` | `None` | Optional URL added to protected resource metadata |
| `user_email` | `str` | `None` | Optional static email claim returned by lightweight OIDC `/userinfo` |
| `allow_private_cimd` | `bool` | `False` | Allow CIMD `client_id` documents to be fetched from private/loopback/link-local hosts (see [CIMD and SSRF hardening](#cimd-and-ssrf-hardening)) |
| `custom_redirect_uri_schemes` | `list[str]` | `None` | Private-use URI schemes (RFC 8252 §7.1, e.g. `["myapp"]`) accepted as `redirect_uris` during dynamic registration, for native app clients |

## OAuth Endpoints

| Endpoint | Description |
| --- | --- |
| `GET /.well-known/oauth-authorization-server` | OAuth discovery |
| `GET /.well-known/openid-configuration` | OpenID Connect discovery |
| `GET /.well-known/oauth-protected-resource` | Resource metadata |
| `POST /register` | Dynamic client registration (public mode only) |
| `GET /authorize` | Redirect to the identity provider's sign-in; without one, show the consent page (or redirect immediately if `auto_approve=True`) when approve-only consent is allowed |
| `POST /authorize` | Submit consent form (approve-only consent only) |
| `GET /authorize/callback` | Identity provider's redirect back after sign-in |
| `POST /token` | Token exchange |
| `GET/POST /userinfo` | Lightweight OIDC userinfo endpoint for `openid` tokens |


## OpenAI platform compatibility

`origo` includes the OAuth behavior needed by OpenAI platform MCP clients that connect to protected MCP servers:

- Protected resource metadata advertises the canonical MCP resource and optional scopes/documentation.
- OAuth discovery advertises PKCE (`S256`), Client ID Metadata Document (CIMD) support, Dynamic Client Registration (DCR), OpenID Connect discovery, and token endpoint authentication methods including public PKCE clients (`none`).
- Dynamic client registration accepts `token_endpoint_auth_method=none` for clients that should exchange authorization codes without a client secret.
- CIMD clients can use an HTTPS metadata document URL as `client_id`; `origo` fetches it, validates redirect URIs, and treats it as a public PKCE client when the document requests `token_endpoint_auth_method=none`.
- The optional OAuth `resource` parameter is preserved from `/authorize` to `/token` and stored with the issued access token metadata, so applications can verify which MCP resource the token was minted for.
- `/token` issues a `refresh_token` alongside every access token. Long-lived MCP clients can exchange it (`grant_type=refresh_token`) for a new access token without a full interactive re-authorization once `token_ttl` expires. Refresh tokens are single-use — each `/token` call rotates in a new one — and are scoped to the same `client_id`/`resource` as the token they replaced. Replaying an already-used refresh token is treated as theft (per the OAuth 2.1 rotation guidance): the entire token family descended from that grant — live refresh tokens and access tokens both — is revoked on the spot, so a stolen-and-rotated chain dies the moment the legitimate holder's token resurfaces. (Corollary: a client that retries a `/token` refresh call after losing the response will trigger this and must re-authorize interactively.)
- `WWW-Authenticate` challenges include `resource_metadata` so ChatGPT can discover OAuth metadata when an unauthenticated tool call reaches the server.
- Optional lightweight OIDC support exposes `/.well-known/openid-configuration`, returns an unsigned `id_token` for `openid` requests, and serves `/userinfo` with `sub` plus `email` when `user_email` is configured and the token has the `email` scope.

For ChatGPT connectors, register the redirect URI shown in ChatGPT (for example, `https://chatgpt.com/connector/oauth/{callback_id}`) and use your public MCP endpoint as the `resource` value, typically `https://your-domain.example/mcp`.

### CIMD and SSRF hardening

A CIMD `client_id` is a URL supplied by whoever is calling `/authorize` — it isn't something `origo` chose, so it's attacker-controlled input. By default `origo` refuses to fetch a CIMD document from a hostname that resolves to a private, loopback, link-local, reserved, or multicast address, and it never follows HTTP redirects when fetching one. Both protections close the same class of bug: a malicious `client_id` URL trying to make your server issue a request to something on its internal network (cloud metadata endpoints, internal admin panels, etc.) instead of a legitimate public client registry.

Some deployments genuinely need to relax the host check — for example, an agent runtime and its `origo` instance colocated on the same private network or host, where the agent's CIMD document is intentionally served from an internal address rather than a public one. For that case, set `allow_private_cimd=True`:

```python
auth = OAuthProvider(
    base_url="https://mcp.internal.example.com",
    public_registration=True,
    allow_private_cimd=True,  # only if your CIMD documents are meant to live on your private network
)
```

`allow_private_cimd` only lifts the private-host restriction — the redirect-refusing fetch still applies unconditionally, so a CIMD host (private or public) still can't retarget the request via a 302 after the fact. Only enable it when you control, or otherwise trust, every host reachable from wherever `origo` runs; on a shared or multi-tenant network it reopens the SSRF surface the default configuration exists to close.

### Secure MCP tunnels

OpenAI Secure MCP Tunnel support is transport-level: run OpenAI's `tunnel-client` next to your private MCP server and point it at the local Origo-protected MCP URL. Origo's OAuth endpoints still need to be reachable for browser-facing authorization flows, either publicly or from wherever `tunnel-client` can forward discovery and MCP requests. Origo does not vendor or replace `tunnel-client`; it provides the OAuth/MCP metadata behavior the tunnel path preserves.

For the issue-by-issue compatibility triage behind this guidance, see [`docs/openai-connector-triage.md`](docs/openai-connector-triage.md).
