Metadata-Version: 2.5
Name: galeo
Version: 0.1.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`.

```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.

## 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. |
| `scopes` | Granted scopes |
| `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 and JWKS 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

`rotate_key()` simulates a key rotation.

## Development

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