Metadata-Version: 2.5
Name: galeo
Version: 0.2.0
Summary: Validate Galeo access tokens and wire Galeo sign-in into Python services
Project-URL: Homepage, https://www.getgaleo.com
Project-URL: Documentation, https://www.getgaleo.com/docs/
License-Expression: Apache-2.0
License-File: LICENSE
Keywords: authentication,fastapi,galeo,jwt,oauth2,oidc
Classifier: Development Status :: 3 - Alpha
Classifier: Framework :: FastAPI
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Topic :: Security
Classifier: Typing :: Typed
Requires-Python: >=3.11
Requires-Dist: httpx>=0.27
Requires-Dist: joserfc>=1.7
Provides-Extra: dev
Requires-Dist: fastapi>=0.115; extra == 'dev'
Requires-Dist: mypy>=1.10; extra == 'dev'
Requires-Dist: pytest>=8; extra == 'dev'
Requires-Dist: ruff>=0.6; extra == 'dev'
Provides-Extra: fastapi
Requires-Dist: fastapi>=0.115; extra == 'fastapi'
Description-Content-Type: text/markdown

# galeo

Verify Galeo access tokens in Python services, map Galeo roles onto your own, and test all of it without a network.

It's the backend half of adding "Sign in with Galeo" to an app. The frontend half is [`@galeo/react`](https://www.npmjs.com/package/@galeo/react), which signs the user in and sends their access token on every API call.

```
pip install "galeo[fastapi]"
```

## Configure

Two values, both from the application's page in the Galeo admin console:

| | |
|---|---|
| `GALEO_ISSUER` | `https://<host>/auth/<organization>`, for the host your users sign in on |
| `GALEO_CLIENT_ID` | The application's client ID |

`GALEO_SCOPE` is optional and defaults to `openid profile email groups`. `GALEO_INTROSPECT`, `GALEO_CLIENT_SECRET` and `GALEO_CLIENT_AUTH_METHOD` are optional too; see [Cutting off blocked users](#cutting-off-blocked-users).

```python
from galeo import GaleoConfig

config = GaleoConfig.from_env()
# or GaleoConfig(issuer="https://login.example.com/auth/acme", client_id="…")
```

## FastAPI

```python
from fastapi import Depends, FastAPI
from galeo import GaleoConfig, Principal
from galeo.fastapi import Galeo

app = FastAPI()
galeo = Galeo(GaleoConfig.from_env())

# GET /auth/config: what the frontend needs to start sign-in.
app.include_router(galeo.config_router())


@app.get("/me")
def me(principal: Principal = Depends(galeo.principal)):
    return {"id": principal.subject, "email": principal.email, "roles": sorted(principal.roles)}


@app.delete("/projects/{project_id}")
def delete_project(
    project_id: str, principal: Principal = Depends(galeo.require_role("admin"))
): ...
```

- `galeo.principal` answers **401** with an RFC 6750 `WWW-Authenticate` challenge when the token is missing or invalid.
- If Galeo can't be reached and no signing keys are cached yet, it answers **503**. That's an outage, not a bad token, so clients retry instead of signing the user out.
- `galeo.optional_principal` returns `None` when there's no token.
- `galeo.require_role(...)` answers **403** unless the user holds one of the roles.

### WebSockets

Browsers can't set `Authorization` on a WebSocket, so send the token as a subprotocol with `new WebSocket(url, ["bearer", token])`:

```python
@app.websocket("/ws")
async def ws(websocket: WebSocket):
    principal = await galeo.websocket_principal(websocket)  # closes with 1008 if invalid
    await websocket.accept(subprotocol="bearer")
```

## What gets checked

`TokenVerifier.verify(token)` accepts a token only if all of these hold:

- **Signature:** checked with the key its `kid` names; RS256 only.
- **Token type:** `typ` is `at+jwt`. Galeo's ID tokens are signed with the same key and carry the same `sub` and `aud`, so they're refused here.
- **Issuer:** `iss` is your organization's issuer.
- **Audience:** `aud` is your client ID. Every app in the organization shares the issuer and signing key, so without this check another app's token would pass, carrying the roles it holds in that other app.
- **Validity window:** `exp` and `nbf` are current, allowing 30 seconds of skew.

Galeo's discovery document and keys are cached for as long as Galeo's `Cache-Control` allows.
- **Unknown `kid`:** a token naming a key the cache doesn't have triggers a refetch, but at most once a minute, so garbage tokens can't make your service hammer Galeo.
- **Outages:** if Galeo is unreachable, the last keys fetched stay in use.

## Cutting off blocked users

All of the checks above run in your service, without asking Galeo. So a token keeps working until it expires (60 minutes by default) even after Galeo has blocked its user. Introspection closes that window: once a token passes the local checks, the SDK also asks Galeo's introspection endpoint whether it's still active.

Galeo reports a token inactive once:
- the user is disabled, put on a security hold (for example, after being marked compromised), or their account expires;
- the application is deactivated.

Introspection doesn't catch everything. A user who only signed out, or whose session an admin ended, still has an active token. A token's roles also stay as they were when it was issued.

Turn it on for every route:

```python
galeo = Galeo(GaleoConfig.from_env())  # with GALEO_INTROSPECT=true
# or GaleoConfig(issuer=..., client_id=..., introspect=True)
```

Or only where it matters:

```python
@app.post("/payouts")
def payout(principal: Principal = Depends(galeo.active_principal)): ...


@app.delete("/projects/{project_id}")
def delete_project(
    project_id: str, principal: Principal = Depends(galeo.require_role("admin", introspect=True))
): ...
```

`TokenVerifier.verify(token, introspect=True)` and `galeo.websocket_principal(websocket, introspect=True)` do the same. A WebSocket is checked once, at the handshake. `introspect=False` turns it off for one call when it's on for the app.

- **Cost:** one call to Galeo per token every `introspection_cache_seconds` (default 30). The cache is also the longest a blocked user keeps access. Set it to 0 to ask on every request. Tokens that fail the local checks never reach Galeo.
- **A blocked user** gets **401** `error="invalid_token", error_description="token is no longer active"`.
- **Outages fail closed.** If Galeo can't be reached, or answers 5xx or 429, the request gets **503**, so clients retry instead of signing the user out. Failures aren't cached.
- **Client authentication:** a public client (token auth method `none`, the usual setup with `@galeo/react`) sends only its client ID. A confidential client sets `GALEO_CLIENT_SECRET`, and `GALEO_CLIENT_AUTH_METHOD` if the application uses `client_secret_post` instead of the default `client_secret_basic`. If Galeo refuses the credentials, verification raises `ConfigurationError` (a 500), not a 401.

## Requiring MFA

`galeo.require_aal(level)` admits only users who signed in at that assurance level or higher. Level 2 needs a second factor or a passkey, and level 3 a smart card.

```python
@app.post("/payouts")
def payout(principal: Principal = Depends(galeo.require_aal(2))): ...
```

Anyone below the level gets **401** with the [RFC 9470](https://www.rfc-editor.org/rfc/rfc9470) challenge `error="insufficient_user_authentication"`, with the level wanted in `acr_values`. `@galeo/react` reads it with `stepUpRequired(response)`, and `signIn({ aal })` sends the user back through Galeo to sign in again at that level. Refreshing the token doesn't help, because a refreshed token keeps the level of the original sign-in. A user with no second factor set up comes back at level 1 and is refused again, so the frontend should offer the step-up rather than force it.

`require_aal` takes `introspect=` like `require_role`. To require a role and a level together, add both dependencies.

## The Principal

| | |
|---|---|
| `subject` | The user's Galeo ID. Stable for the life of the account. |
| `key` | `(issuer, subject)`. **Key your local user records on this, not on email.** An email can change, and a different account can later hold it. |
| `email`, `name` | With the `email` / `profile` scopes |
| `roles` | The user's role names **in your application**, from the `groups` claim. Not directory groups. Narrowed to the chosen role if the app makes users pick one at sign-in. Always empty on Identity Platform plans, because roles need Identity Governance: `require_role` then always answers 403, and `RoleMapper` gives its default. |
| `scopes` | Granted scopes |
| `aal`, `acr` | The assurance level the sign-in reached: `aal` is 1 to 3, or 0 when the token states none (client credentials tokens), and `acr` is the claim itself, one of `galeo.ACR_AAL1` to `ACR_AAL3` |
| `amr` | How the user signed in ([RFC 8176](https://www.rfc-editor.org/rfc/rfc8176)), e.g. `{"pwd", "otp"}` |
| `claims`, `token` | The raw claims and token |

### Creating local users on first sign-in

```python
def current_user(
    principal: Principal = Depends(galeo.principal), db: Session = Depends(get_db)
) -> User:
    user = (
        db.query(User)
        .filter_by(galeo_issuer=principal.issuer, galeo_subject=principal.subject)
        .one_or_none()
    )
    if user is None:
        user = User(galeo_issuer=principal.issuer, galeo_subject=principal.subject)
        db.add(user)
    user.email, user.name = principal.email, principal.name
    user.role = roles.resolve(principal.roles)
    db.commit()
    return user
```

## Mapping roles

```python
from galeo import RoleMapper

roles = RoleMapper(
    {"admin": "admin", "program-lead": "lead"},  # Galeo role -> your role
    ranking=["admin", "lead", "contributor"],  # most to least privileged
    default="contributor",
)
roles.resolve(principal.roles)  # "admin", "lead" or "contributor"
```

Resolve on every sign-in and store the result. Don't only ever raise a stored role: someone removed from a role in Galeo has to lose it in your app too.

## Testing your app

```python
import pytest
from galeo.testing import FakeGaleo
from myapp.main import app, galeo


@pytest.fixture
def fake_galeo():
    fake = FakeGaleo(client_id="my-app")
    fake.install(galeo)  # the app's Galeo now trusts the fake's tokens
    return fake


def test_me(fake_galeo):
    token = fake_galeo.access_token(roles=["admin"], email="ada@example.test")
    res = TestClient(app).get("/me", headers={"Authorization": f"Bearer {token}"})
    assert res.json()["roles"] == ["admin"]
```

`FakeGaleo` serves discovery, JWKS and introspection in memory, so the real verification path runs. To build tokens that must be refused, push an argument out of range:
- `expires_in=-60` for an expired token
- `audience="another-app"` for another app's token
- `typ="JWT"` for an ID token

`aal=` sets the level the sign-in reached (default 1). `aal=2` makes an MFA sign-in, and `aal=None` makes a token with no level, like a client credentials token.

`rotate_key()` simulates a key rotation. `block_user(subject)` makes introspection report that user's tokens inactive, as Galeo does after disabling them, and `unblock_user(subject)` reverses it. `install()` keeps your app's `introspect` setting. Pass `client_secret=` to `FakeGaleo` to test a confidential client.

## Development

```
pip install -e ".[dev]"
pytest
ruff check . && mypy
```
