contiai / apps /api /app /core /auth.py
aliabozahra315's picture
Deploy 973e3b2
8fdf206
Raw History Blame Contribute Delete
13.1 kB
"""Supabase JWT authentication.
The previous backend had none: every endpoint was open, and the Bearer token
the frontend sent was never checked by anything. Here the token is verified,
the caller is resolved to a User, and admin routes require the admin role.
"""
from __future__ import annotations
import uuid
from datetime import UTC, datetime
from functools import lru_cache
from typing import Annotated
import jwt
from fastapi import Depends, HTTPException, status
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
from sqlalchemy.ext.asyncio import AsyncSession
from app.core.config import settings
from app.db.models import Department, User, UserRole, UserStatus
from app.db.session import get_session
bearer = HTTPBearer(auto_error=False)
class AuthError(HTTPException):
def __init__(self, detail: str):
super().__init__(status_code=status.HTTP_401_UNAUTHORIZED, detail=detail,
headers={"WWW-Authenticate": "Bearer"})
@lru_cache(maxsize=1)
def _jwks_client() -> jwt.PyJWKClient:
"""Supabase's public signing keys.
The project signs access tokens with an asymmetric key (ES256 on P-256),
so verification needs the public half rather than a shared secret. The
client caches keys and refetches when it meets an unfamiliar `kid`, which
is what makes key rotation a non-event here.
"""
return jwt.PyJWKClient(
f"{settings.supabase_url.rstrip('/')}/auth/v1/.well-known/jwks.json",
cache_keys=True,
lifespan=3600,
)
# Projects that have not migrated still sign with the shared secret. Both are
# accepted, decided by the header, never by trying one and falling through -
# that would let a caller pick the weaker path.
ASYMMETRIC = {"ES256", "RS256", "EdDSA"}
SYMMETRIC = {"HS256"}
def decode_token(token: str) -> dict:
try:
header = jwt.get_unverified_header(token)
except jwt.InvalidTokenError as e:
raise AuthError(f"malformed token: {e}") from None
alg = header.get("alg", "")
if alg in ASYMMETRIC:
if not settings.supabase_url:
raise AuthError("server is not configured to verify tokens")
try:
key = _jwks_client().get_signing_key_from_jwt(token).key
except Exception as e:
raise AuthError(f"could not fetch the signing key: {e}") from None
algorithms = [alg]
elif alg in SYMMETRIC:
if not settings.supabase_jwt_secret:
raise AuthError("server is not configured to verify tokens")
key = settings.supabase_jwt_secret
algorithms = ["HS256"]
else:
raise AuthError(f"unsupported signing algorithm: {alg or 'none'}")
try:
return jwt.decode(
token,
key,
algorithms=algorithms,
audience="authenticated",
# «token expired» on a computer a little behind the server's
# clock (2026-11-16): a minute either way is not an expired session
leeway=60,
options={"require": ["exp", "sub"]},
)
except jwt.ExpiredSignatureError:
raise AuthError("token has expired") from None
except jwt.InvalidTokenError as e:
raise AuthError(f"invalid token: {e}") from None
async def current_user(
creds: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer)],
db: Annotated[AsyncSession, Depends(get_session)],
) -> User:
if creds is None:
raise AuthError("missing Authorization header")
claims = decode_token(creds.credentials)
try:
user_id = uuid.UUID(claims["sub"])
except (KeyError, ValueError):
raise AuthError("token has no usable subject") from None
user_account = await db.get(User, user_id)
email = (claims.get("email") or "").strip().lower()
bootstrap = email and email in {
e.strip().lower() for e in (settings.bootstrap_admin_emails or [])
}
if user_account is None:
# First sign-in after Supabase created the auth user. The name and the
# department come from what was typed at sign-up, which Supabase keeps
# in user_metadata - this backend never sees the password.
if not email:
raise AuthError("token has no email; cannot create an account")
# An unknown id with a known email means the auth user was recreated
# (deleted in Supabase, signed up again). Creating a second row would
# violate the email's uniqueness and used to surface as a bare 500;
# refusing cleanly names the actual situation instead.
from sqlalchemy import select
existing = await db.scalar(select(User).where(User.email == email))
if existing is not None:
raise HTTPException(
status.HTTP_409_CONFLICT,
"هذا البريد مسجّل بحساب سابق على المنصة — راجع المسؤول لإعادة ربطه",
)
meta = claims.get("user_metadata") or {}
user_account = User(
id=user_id,
email=email,
full_name=(meta.get("full_name") or "").strip() or None,
department=_department_from(meta.get("department")),
role=UserRole.user,
# Every new account waits. An administrator approves it and picks
# which tools it gets; until then it can sign in and see that, and
# nothing else.
status=UserStatus.pending,
allowed_task_types=[],
)
db.add(user_account)
await db.flush()
if bootstrap:
_promote(user_account)
if user_account.status is UserStatus.suspended:
raise HTTPException(status.HTTP_403_FORBIDDEN, "الحساب موقوف مؤقتًا")
if user_account.status is UserStatus.disabled:
raise HTTPException(status.HTTP_403_FORBIDDEN, "هذا الحساب مُعطَّل")
return user_account
def is_founding(account: User) -> bool:
"""Whether this is an account nobody may take apart.
`BOOTSTRAP_ADMIN_EMAILS` already made these administrators on every
request, so demoting one never actually held - `_promote` put the role
back on the next call. That is a silent contradiction: the dashboard
offered a switch, the switch appeared to work, and the account was an
administrator again a second later.
Saying no outright is the honest version, and it covers the case the
re-promotion never did: a founding account could be suspended, disabled or
deleted, and none of those are undone by `_promote`. Deleting one would
lock the platform's owner out of their own dashboard with no way back in
that does not involve the database.
"""
email = (account.email or "").strip().lower()
if not email:
return False
return email in {e.strip().lower() for e in (settings.bootstrap_admin_emails or [])}
def _promote(account: User) -> None:
"""Make a bootstrap address an approved administrator.
Applied before the status checks below, so an address on this list can
always get back in - which is the point of having it.
"""
from app.pipelines.registry import all_pipelines
account.role = UserRole.admin
account.status = UserStatus.active
if not account.allowed_task_types:
account.allowed_task_types = [p.key for p in all_pipelines()]
if account.approved_at is None:
account.approved_at = datetime.now(UTC)
def _department_from(value: object) -> Department | None:
try:
return Department(str(value))
except ValueError:
return None
async def approved_user(
user_account: Annotated[User, Depends(current_user)],
) -> User:
"""A user who may actually do work.
Kept separate from ``current_user`` so a pending account can still read
``/v1/me`` and be told what it is waiting for. Every endpoint that creates
or runs anything depends on this one instead.
"""
if user_account.status is UserStatus.pending:
raise HTTPException(
status.HTTP_403_FORBIDDEN,
"حسابك بانتظار موافقة المسؤول",
)
return user_account
def uploads_closed(user_account: User) -> bool:
"""`settings.no_upload_emails`: no files, the new-تصور route and the web search alone."""
email = (user_account.email or "").strip().lower()
return email in {e.strip().lower() for e in (settings.no_upload_emails or [])}
def is_owner(user_account: User) -> bool:
"""The platform's owner (`settings.owner_emails`): the one account whose
access tracks the whole catalogue."""
email = (user_account.email or "").strip().lower()
return bool(email) and email in {
e.strip().lower() for e in (settings.owner_emails or [])}
#: pipelines still on trial: their runs are the founder's alone to see. The
#: admin views skip them for every other administrator - the run list, the
#: failure counts, the spend tables and a run's own detail page.
FOUNDER_ONLY_PIPELINES = frozenset({"book_v3"})
def hidden_pipelines(user_account: User) -> frozenset[str]:
"""The pipeline keys whose runs `user_account` must not see in admin views."""
return frozenset() if is_owner(user_account) else FOUNDER_ONLY_PIPELINES
#: the designers the founder may open to others; the book designer and the
#: studio stay his alone
GRANTABLE_DESIGNERS = ("bag", "slides", "studio")
#: in `design_access`: the account may design every finished run, not only
#: its own. Chosen per account by the founder.
ALL_RUNS = "all_runs"
def clean_design_access(values: list[str]) -> list[str]:
"""The stored form: designers in order, then `ALL_RUNS` - which means
nothing without a designer. Raises ValueError on an unknown value."""
unknown = [v for v in values if v not in (*GRANTABLE_DESIGNERS, ALL_RUNS)]
if unknown:
raise ValueError(", ".join(unknown))
out = [d for d in GRANTABLE_DESIGNERS if d in values]
return [*out, ALL_RUNS] if out and ALL_RUNS in values else out
#: Every account a designer is opened to designs any run finished from this day
#: on, whoever made it; earlier runs not its own only with `ALL_RUNS`.
DESIGN_OPEN_SINCE = datetime(2026, 10, 1, tzinfo=UTC)
def designs_all_runs(user_account: User) -> bool:
"""Whether this account may design runs that are not its own, of any date."""
return is_owner(user_account) or ALL_RUNS in (user_account.design_access or [])
def may_design_run(user_account: User, finished_at: datetime | None, owner_id) -> bool:
"""Whether this account may design this run: its own, one finished since
`DESIGN_OPEN_SINCE`, or any if the founder chose `ALL_RUNS` for it."""
if designs_all_runs(user_account) or owner_id == user_account.id:
return True
if finished_at is None:
return False
if finished_at.tzinfo is None:
finished_at = finished_at.replace(tzinfo=UTC)
return finished_at >= DESIGN_OPEN_SINCE
def may_design(user_account: User, which: str) -> bool:
"""Whether this account may use a designer: the founder always; anyone
else only one he has opened to them - the bag, slides or the studio
(«استوديو التصميم», grantable since 2026-11-14); the book designer stays his."""
if is_owner(user_account):
return True
return which in GRANTABLE_DESIGNERS and which in (user_account.design_access or [])
def designers_of(user_account: User) -> list[str]:
"""Every designer this account reaches, for the web app to show."""
if is_owner(user_account):
return [*GRANTABLE_DESIGNERS, "book"]
return [d for d in GRANTABLE_DESIGNERS if d in (user_account.design_access or [])]
def may_use(user_account: User, task_type: str) -> bool:
"""Whether this account may work with a task type.
Every account works with what it was granted - administrators included.
The owner asked for exactly that: a tool reaches someone, admin or not,
only when the owner turns it on for them from the dashboard. An
administrator still manages people and sees the whole catalogue on the
admin screens (that is where grants are handed out); what they can create
is their own grant.
The owner alone is not filtered. A grant list is a snapshot taken on the
day the account was approved, so a type registered afterwards is missing
from every list - the owner has to see it to decide who gets it.
"""
if is_owner(user_account):
return True
return task_type in (user_account.allowed_task_types or [])
async def current_admin(
user_account: Annotated[User, Depends(current_user)],
) -> User:
if user_account.role != UserRole.admin:
raise HTTPException(status.HTTP_403_FORBIDDEN, "administrator access is required")
return user_account
CurrentUser = Annotated[User, Depends(current_user)]
# The dependency for anything that costs money or creates work.
ApprovedUser = Annotated[User, Depends(approved_user)]
CurrentAdmin = Annotated[User, Depends(current_admin)]
Db = Annotated[AsyncSession, Depends(get_session)]