Files
romm/backend/decorators/auth.py
Georges-Antoine Assi 1ab3a3625a feat(auth): use the OIDC picture claim as the user's avatar (#5730)
* feat(auth): use the OIDC picture claim as the user's avatar

On each OIDC sign-in, a user with no avatar, or one synced from the
provider earlier, gets the picture claim stored as their avatar. An
uploaded avatar is never replaced. The download goes through the
SSRF-guarded client (the configured provider's origin may reach a LAN
address), is capped at 5 MB, must sniff as a supported image, and any
failure is logged without blocking the sign-in.

Closes #4297

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(auth): address review on the OIDC avatar sync

Addresses Greptile's review on #5730:
- ask the UserInfo endpoint when the ID token has no picture claim
- keep an avatar uploaded while the picture downloaded
- allow only the OIDC provider's origins to reach private addresses
- trim docstrings and narrow await_args in the callback test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* test(auth): type the OIDC avatar test helpers for mypy

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: code-review

Bound the OIDC picture download with an overall deadline, trust the
OIDC CA bundle, catch hostname encoding errors so sign-in never 500s,
and set the synced avatar with a conditional update so a concurrent
upload wins.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: simplify

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: review-polish

Type the pytest fixtures and helpers in the OIDC avatar tests.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: prose

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(auth): remove the synced OIDC avatar when the user uploads one

Once avatar_path points at the uploaded avatar.<ext>, the sync never
touches the user's avatar again, so the old oidc-avatar.<ext> file
would otherwise stay on disk for good.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 16:23:21 -05:00

196 lines
6.6 KiB
Python

import functools
import inspect
from collections.abc import Callable
from typing import Any, NoReturn
from authlib.integrations.starlette_client import OAuth
from authlib.oidc.discovery import get_well_known_url
from fastapi import HTTPException, Security, status
from fastapi.security.http import HTTPBasic
from fastapi.security.oauth2 import OAuth2PasswordBearer
from fastapi.types import DecoratedCallable
from starlette._utils import is_async_callable
from starlette.authentication import has_required_scope
from starlette.config import Config
from starlette.requests import Request
from config import (
OIDC_AUTH_PARAMS,
OIDC_CLAIM_ROLES,
OIDC_CLIENT_ID,
OIDC_CLIENT_SECRET,
OIDC_ENABLED,
OIDC_PROVIDER,
OIDC_REDIRECT_URI,
OIDC_SERVER_APPLICATION_URL,
OIDC_SERVER_METADATA_URL,
OIDC_TLS_CACERTFILE,
)
from handler.auth.constants import (
EDIT_SCOPES_MAP,
FULL_SCOPES_MAP,
READ_SCOPES_MAP,
WRITE_SCOPES_MAP,
Scope,
)
from utils.tls import build_ca_ssl_context
# Using the internal password flow
oauth2_password_bearer = OAuth2PasswordBearer(
tokenUrl="/api/token",
auto_error=False,
# The maps are keyed by Scope, which is a StrEnum; FastAPI wants plain str.
scopes={
str(scope): description
for scope_map in (
READ_SCOPES_MAP,
WRITE_SCOPES_MAP,
EDIT_SCOPES_MAP,
FULL_SCOPES_MAP,
)
for scope, description in scope_map.items()
},
)
# Using an OIDC authorization code flow
OIDC_SSL_CONTEXT = build_ca_ssl_context(OIDC_TLS_CACERTFILE)
config = Config(
environ={
"OIDC_ENABLED": str(OIDC_ENABLED),
"OIDC_PROVIDER": OIDC_PROVIDER,
"OIDC_CLIENT_ID": OIDC_CLIENT_ID,
"OIDC_CLIENT_SECRET": OIDC_CLIENT_SECRET,
"OIDC_REDIRECT_URI": OIDC_REDIRECT_URI,
"OIDC_SERVER_APPLICATION_URL": OIDC_SERVER_APPLICATION_URL,
}
)
oauth = OAuth(config=config)
oauth.register(
name="openid",
client_id=config.get("OIDC_CLIENT_ID"),
client_secret=config.get("OIDC_CLIENT_SECRET"),
server_metadata_url=OIDC_SERVER_METADATA_URL
or get_well_known_url(config.get("OIDC_SERVER_APPLICATION_URL"), external=True),
client_kwargs={
"scope": f"openid profile email {OIDC_CLAIM_ROLES}".strip(),
"verify": OIDC_SSL_CONTEXT,
# Authlib only derives a code_verifier when code_challenge_method is set,
# so providers that mandate PKCE refuse the code without it.
"code_challenge_method": "S256",
},
authorize_params=OIDC_AUTH_PARAMS or None,
)
def raise_auth_error(request: Request) -> NoReturn:
"""Raise the status matching the caller's auth state.
401 tells the client it has no valid credentials (so it can redirect to
login), while 403 means the authenticated user lacks the required scope
(an inline permission error, not a session problem).
"""
if not request.user.is_authenticated:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Forbidden")
def _requires_scopes(
scopes: list[Scope],
) -> Callable[[DecoratedCallable], DecoratedCallable]:
"""Scope guard mirroring starlette's `requires`, with a 401/403 split."""
def decorator(func: DecoratedCallable) -> DecoratedCallable:
sig = inspect.signature(func)
idx = next(
(
i
for i, parameter in enumerate(sig.parameters.values())
if parameter.name == "request"
),
None,
)
if idx is None:
raise Exception(f'No "request" argument on function "{func}"')
if is_async_callable(func):
@functools.wraps(func)
async def async_wrapper(*args: Any, **kwargs: Any) -> Any:
request = kwargs.get("request", args[idx] if idx < len(args) else None)
assert isinstance(request, Request)
if not has_required_scope(request, scopes):
raise_auth_error(request)
return await func(*args, **kwargs)
async_wrapper.required_scopes = tuple(scopes) # type: ignore[attr-defined]
return async_wrapper # type: ignore[return-value]
@functools.wraps(func)
def sync_wrapper(*args: Any, **kwargs: Any) -> Any:
request = kwargs.get("request", args[idx] if idx < len(args) else None)
assert isinstance(request, Request)
if not has_required_scope(request, scopes):
raise_auth_error(request)
return func(*args, **kwargs)
sync_wrapper.required_scopes = tuple(scopes) # type: ignore[attr-defined]
return sync_wrapper # type: ignore[return-value]
return decorator
# Maps each status to the description it gets on its own, and the sentence appended
# when the route already describes that status.
SCOPE_ERRORS: dict[int, tuple[str, str]] = {
status.HTTP_401_UNAUTHORIZED: (
"The request has no valid credentials.",
"Also returned when the request has no valid credentials.",
),
status.HTTP_403_FORBIDDEN: (
"The token lacks a scope this route needs.",
"Also returned when the token lacks a scope this route needs.",
),
}
def _with_scope_errors(
responses: dict[int | str, dict[str, Any]] | None,
) -> dict[int | str, dict[str, Any]]:
"""Add the scope guard's 401 and 403 to a route's documented responses."""
merged = {code: dict(entry) for code, entry in (responses or {}).items()}
for code, (alone, appended) in SCOPE_ERRORS.items():
entry = merged.setdefault(code, {})
own = entry.get("description")
entry["description"] = f"{own} {appended}" if own else alone
return merged
def protected_route(
method: Callable[..., Callable[[DecoratedCallable], DecoratedCallable]],
path: str,
scopes: list[Scope] | None = None,
**kwargs: Any,
) -> Callable[[DecoratedCallable], DecoratedCallable]:
if scopes:
kwargs["responses"] = _with_scope_errors(kwargs.get("responses"))
def decorator(func: DecoratedCallable) -> DecoratedCallable:
fn = _requires_scopes(scopes or [])(func)
return method(
path,
dependencies=[
Security(
dependency=oauth2_password_bearer,
scopes=scopes or [],
),
Security(dependency=HTTPBasic(auto_error=False)),
],
**kwargs,
)(fn)
return decorator