Project: pygitweb

85b8192 """
4a34d33 Authentication: local password login and OAuth2 authorization-code (browser).
FastAPI security integration
----------------------------
- ``OAuth2PasswordBearer`` + ``APIKeyCookie``: extract PyGitWeb's opaque session id from
``Authorization: Bearer`` or the login cookie. This is *not* an IdP JWT; OpenAPI still
documents the password ``/token`` flow that mints these session ids.
- ``OAuth2PasswordRequestForm``: local ``POST /token`` only (resource-owner password grant).
- External IdP login (Google/GitHub) uses standard authorization-code redirects implemented
in ``auth_oauth``; ``OAuth2AuthorizationCodeBearer`` is intentionally not used because
clients never receive or send the provider's access token—only our session id.
85b8192 """
from __future__ import annotations
7f2db6c import base64
import binascii
85b8192 import hmac
7f2db6c import secrets
import threading
from dataclasses import dataclass
from datetime import UTC, datetime, timedelta
from typing import Annotated, Literal
85b8192
from fastapi import APIRouter, Depends, Form, HTTPException, Query, status
7f2db6c from fastapi.responses import HTMLResponse, RedirectResponse, Response
85b8192 from fastapi.security import APIKeyCookie, OAuth2PasswordBearer, OAuth2PasswordRequestForm
7f2db6c from pydantic import BaseModel, Field, field_validator
85b8192
608d8b2 from pygitweb.auth_config import (
73c9c30 HttpKey,
LocalUser,
auth_config_path,
is_auth_configured,
is_local_auth_available,
is_oauth_auth_available,
write_auth_config,
608d8b2 )
4a34d33 from pygitweb.auth_oauth import OAUTH_STATE_COOKIE_NAME, oauth_router
b96c6f3 from pygitweb.config import auth_config, settings
71df48e from pygitweb.gravatar import gravatar_url
7f2db6c from pygitweb.password_hash import hash_password, verify_password
3abcfc4 from pygitweb.permissions import (
0b04b9f WILDCARD_PRINCIPAL,
73c9c30 Permission,
PermissionPrincipal,
has_ref_write_permission,
3abcfc4 )
fbd311b from pygitweb.projects import git_get_project_owner
5b01811 from pygitweb.sessions import AuthMethod, create_session, get_session, revoke_session
00e5b5b from pygitweb.templates_env import render_page
85b8192
ACCESS_TOKEN_COOKIE_NAME = "pygitweb_access_token"
LOGIN_COOKIE_MAX_AGE = 60 * 60 * 24 * 7
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token", auto_error=False)
_access_token_cookie = APIKeyCookie(name=ACCESS_TOKEN_COOKIE_NAME, auto_error=False)
fb2fe5d TAG_AUTH = "auth"
TAG_AUTH_LOCAL = "auth - local"
TAG_AUTH_OAUTH = "auth - OAuth"
auth_router = APIRouter()
4a34d33 auth_router.include_router(oauth_router)
85b8192
class User(BaseModel):
73c9c30 username: str
email: str | None = None
e6c6972
7f2db6c SmartHttpAuthError = Literal["unauthorized", "unavailable"]
_INVALID_KEY_ACTOR = "INVALID_KEY"
@dataclass(frozen=True, slots=True)
class SmartHttpCredentials:
73c9c30 required: bool
principal: PermissionPrincipal | None = None
readonly: bool = False
actor: str = ""
error: SmartHttpAuthError | None = None
7f2db6c
@dataclass(frozen=True, slots=True)
class PresentedHttpKey:
73c9c30 principal: PermissionPrincipal
readonly: bool
key_id: str
expired: bool
7f2db6c
_SMART_HTTP_CHALLENGE = {"WWW-Authenticate": 'Basic realm="pygitweb", Bearer'}
e6c6972 def principal_from_session(token: str | None) -> PermissionPrincipal | None:
73c9c30 if not token:
return None
rec = get_session(token)
if rec is None:
return None
return PermissionPrincipal(username=rec.username, email=rec.email)
e6c6972
b96c6f3 def _anonymous_principal_for_permissions() -> PermissionPrincipal | None:
73c9c30 for entry in auth_config.local_users:
if getattr(entry, "assume_anonymous", False):
return PermissionPrincipal(username=entry.user, email=entry.email)
return None
b96c6f3
def _principal_identity_for_permissions(token: str | None) -> str | None:
73c9c30 principal = principal_from_session(token)
if principal is not None:
return principal.identity
anonymous = _anonymous_principal_for_permissions()
if anonymous is not None:
return anonymous.identity
return None
b96c6f3
e6c6972 def has_permission(
73c9c30 permission: Permission,
project: str | None = None,
*,
token: str | None = None,
e6c6972 ) -> bool:
73c9c30 if not settings.AUTH:
return True
identity = _principal_identity_for_permissions(token)
if identity is None:
return False
return auth_config.oauth_permissions.has_permission(identity, permission, project)
e6c6972
0b04b9f def is_superuser(*, token: str | None = None) -> bool:
"""True when the principal is listed under the ``*`` permission grant."""
if not settings.AUTH:
return True
identity = _principal_identity_for_permissions(token)
if identity is None:
return False
allowed = auth_config.oauth_permissions.superuser_principals()
if WILDCARD_PRINCIPAL in allowed:
return True
if identity in allowed:
return True
lower = identity.lower()
return any(p.lower() == lower for p in allowed if p != WILDCARD_PRINCIPAL)
7f2db6c def _owner_matches_principal(project: str, principal: PermissionPrincipal) -> bool:
73c9c30 if not settings.AUTH:
return False
owner = git_get_project_owner(project)
if not owner or not owner.strip():
return False
owner_norm = owner.strip()
identity = principal.identity
if hmac.compare_digest(owner_norm, identity):
return True
return owner_norm.lower() == identity.lower()
fbd311b
7f2db6c def _owner_matches(project: str, token: str | None) -> bool:
73c9c30 if not token:
return False
principal = principal_from_session(token)
if principal is None:
return False
return _owner_matches_principal(project, principal)
7f2db6c
def principal_can_read_project(project: str, principal: PermissionPrincipal) -> bool:
73c9c30 if not settings.AUTH:
return True
if _owner_matches_principal(project, principal):
return True
return auth_config.oauth_permissions.has_permission(principal.identity, Permission.READ, project)
7f2db6c
def principal_can_write_project(project: str, principal: PermissionPrincipal) -> bool:
73c9c30 if not settings.AUTH:
return True
if _owner_matches_principal(project, principal):
return True
return auth_config.oauth_permissions.has_permission(principal.identity, Permission.WRITE, project)
7f2db6c
fbd311b def can_read_project(project: str, token: str | None) -> bool:
73c9c30 if not settings.AUTH:
return True
if _owner_matches(project, token):
return True
return has_permission(Permission.READ, project, token=token)
fbd311b
def can_write_project(project: str, token: str | None) -> bool:
73c9c30 if not settings.AUTH:
return True
if _owner_matches(project, token):
return True
return has_permission(Permission.WRITE, project, token=token)
fbd311b
3abcfc4 def can_push_ref(project: str, principal: PermissionPrincipal, ref_name: str) -> bool:
73c9c30 """Per-ref push check.
Project owners may push any ref. Otherwise, if any ``pgw.write_ref`` rule
applies to the project, only matching ``write_ref`` grants allow the push
(whitelist). With no ``write_ref`` rules for the project, project write is
enough. Names outside ``refs/`` are rejected.
"""
if not settings.AUTH:
return True
if _owner_matches_principal(project, principal):
return True
return has_ref_write_permission(
auth_config.oauth_permissions,
principal.identity,
project,
ref_name,
)
b96c6f3
fbd311b def ensure_read_project(project: str, token: str | None) -> None:
73c9c30 if can_read_project(project, token):
return
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No such project")
fbd311b
def ensure_write_project(project: str, token: str | None) -> None:
73c9c30 if not settings.AUTH:
return
if not is_auth_configured(auth_config):
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Authentication enabled but auth.json is not configured",
)
if not token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
if decode_access_token(token) is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
if can_write_project(project, token):
return
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Insufficient permissions",
)
fbd311b
e6c6972 def ensure_permission(
73c9c30 permission: Permission,
project: str | None = None,
*,
token: str | None,
e6c6972 ) -> None:
73c9c30 ensure_active_user_if_auth_enabled(token)
if project is not None:
ensure_read_project(project, token)
if has_permission(permission, project, token=token):
return
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN,
detail="Insufficient permissions",
)
e6c6972
ee8fef9 def get_local_user(username: str) -> User | None:
73c9c30 if not settings.AUTH or not is_local_auth_available(auth_config):
return None
for entry in auth_config.local_users:
if not entry.pass_hash and not entry.password:
continue
if hmac.compare_digest(entry.user, username):
return User(username=entry.user, email=entry.email)
return None
85b8192
4a34d33 def authenticate_local_user(username: str, password: str) -> User | None:
73c9c30 if auth_config.auth_mode not in ("local", "both"):
return None
for entry in auth_config.local_users:
if not hmac.compare_digest(entry.user, username):
continue
if entry.pass_hash:
if not verify_password(password, entry.pass_hash, config_salt=auth_config.salt):
return None
return User(username=entry.user, email=entry.email)
if entry.password is not None and hmac.compare_digest(entry.password, password):
return User(username=entry.user, email=entry.email)
return None
return None
85b8192
7f2db6c def _const_eq(left: str, right: str) -> bool:
73c9c30 if len(left) != len(right):
return False
return hmac.compare_digest(left, right)
7f2db6c
def _http_key_username_matches(user: str, email: str | None, username: str) -> bool:
73c9c30 if _const_eq(user, username):
return True
if not email:
return False
return _const_eq(email.casefold(), username.casefold())
7f2db6c
def _key_owner_name(principal: PermissionPrincipal) -> str:
73c9c30 email = principal.email.strip() if principal.email else ""
return email or principal.username
7f2db6c
def _http_key_actor(matched: PresentedHttpKey) -> str:
73c9c30 owner = _key_owner_name(matched.principal)
if matched.expired:
return f"{owner} {matched.key_id} (EXPIRED)"
return f"{owner} {matched.key_id}"
7f2db6c
def match_presented_http_key(username: str, password: str) -> PresentedHttpKey | None:
73c9c30 presented_user = username.strip()
presented_secret = password.strip()
if not presented_user or not presented_secret:
return None
now = datetime.now(UTC)
expired_match: PresentedHttpKey | None = None
for entry in auth_config.local_users:
if not _http_key_username_matches(entry.user, entry.email, presented_user):
continue
principal = PermissionPrincipal(username=entry.user, email=entry.email)
for key in entry.keys:
if not verify_password(presented_secret, key.secret, config_salt=auth_config.salt):
continue
if key.is_expired(now):
if expired_match is None:
expired_match = PresentedHttpKey(
principal=principal,
readonly=key.readonly,
key_id=key.id,
expired=True,
)
continue
return PresentedHttpKey(
principal=principal,
readonly=key.readonly,
key_id=key.id,
expired=False,
)
return expired_match
7f2db6c
def authenticate_http_key(username: str, password: str) -> tuple[PermissionPrincipal, bool] | None:
73c9c30 matched = match_presented_http_key(username, password)
if matched is None or matched.expired:
return None
return matched.principal, matched.readonly
7f2db6c
def _parse_basic_authorization(value: str) -> tuple[str, str] | None:
73c9c30 scheme, _, param = value.strip().partition(" ")
if scheme.lower() != "basic" or not param.strip():
return None
try:
decoded = base64.b64decode(param.strip(), validate=True)
text = decoded.decode("utf-8")
except (binascii.Error, UnicodeDecodeError, ValueError):
return None
username, sep, password = text.partition(":")
if not sep:
return None
return username, password
7f2db6c
def unauthorized_smart_http() -> HTTPException:
73c9c30 return HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers=_SMART_HTTP_CHALLENGE,
)
7f2db6c
def raise_for_smart_http_credentials(creds: SmartHttpCredentials) -> None:
73c9c30 if creds.error == "unavailable":
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Authentication enabled but auth.json is not configured",
)
if creds.error == "unauthorized":
raise unauthorized_smart_http()
7f2db6c
def _assumable_public_username(project: str, *, write: bool) -> str:
73c9c30 if write:
return ""
anonymous = _anonymous_principal_for_permissions()
if anonymous is None or not can_read_project(project, None):
return ""
return anonymous.username
7f2db6c
def load_smart_http_credentials(
73c9c30 authorization: str | None,
cookie_token: str | None,
*,
project: str,
write: bool,
7f2db6c ) -> SmartHttpCredentials:
73c9c30 if not settings.AUTH:
return SmartHttpCredentials(required=False)
if not is_auth_configured(auth_config) and not any(user.keys for user in auth_config.local_users):
return SmartHttpCredentials(required=True, error="unavailable")
if authorization:
scheme, _, rest = authorization.strip().partition(" ")
scheme_name = scheme.lower()
if scheme_name == "basic":
parsed = _parse_basic_authorization(authorization)
if parsed is None:
return SmartHttpCredentials(required=True, actor=_INVALID_KEY_ACTOR, error="unauthorized")
matched = match_presented_http_key(parsed[0], parsed[1])
if matched is None:
return SmartHttpCredentials(required=True, actor=_INVALID_KEY_ACTOR, error="unauthorized")
actor = _http_key_actor(matched)
if matched.expired:
return SmartHttpCredentials(required=True, actor=actor, error="unauthorized")
return SmartHttpCredentials(
required=True,
principal=matched.principal,
readonly=matched.readonly,
actor=actor,
)
if scheme_name == "bearer":
bearer_principal = principal_from_session(rest.strip())
if bearer_principal is None:
return SmartHttpCredentials(required=True, error="unauthorized")
return SmartHttpCredentials(
required=True,
principal=bearer_principal,
readonly=False,
actor=_key_owner_name(bearer_principal),
)
return SmartHttpCredentials(required=True, error="unauthorized")
if cookie_token and cookie_token.strip():
cookie_principal = principal_from_session(cookie_token)
if cookie_principal is None:
return SmartHttpCredentials(required=True, error="unauthorized")
return SmartHttpCredentials(
required=True,
principal=cookie_principal,
readonly=False,
actor=_key_owner_name(cookie_principal),
)
return SmartHttpCredentials(required=True, actor=_assumable_public_username(project, write=write))
7f2db6c
85b8192 def decode_access_token(token: str) -> User | None:
73c9c30 if not settings.AUTH:
return None
rec = get_session(token)
if rec is None:
return None
return User(username=rec.username)
85b8192
def safe_next_url(next_raw: str | None) -> str:
73c9c30 n = (next_raw or "/").strip()
if not n.startswith("/") or n.startswith("//"):
return "/"
return n
85b8192
def access_token_from_request(
73c9c30 bearer: Annotated[str | None, Depends(oauth2_scheme)],
cookie_token: Annotated[str | None, Depends(_access_token_cookie)],
85b8192 ) -> str | None:
73c9c30 b = bearer.strip() if bearer else None
c = cookie_token.strip() if cookie_token else None
return b or c
85b8192
def ensure_active_user_if_auth_enabled(token: str | None) -> None:
73c9c30 if not settings.AUTH:
return
if not is_auth_configured(auth_config):
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Authentication enabled but auth.json is not configured",
)
if not token:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
if decode_access_token(token) is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
85b8192
def require_active_user_if_auth_enabled(
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)],
85b8192 ) -> None:
73c9c30 ensure_active_user_if_auth_enabled(token)
85b8192
fb2fe5d @auth_router.get(
73c9c30 "/login",
response_class=HTMLResponse,
tags=[TAG_AUTH],
summary="Sign-in page",
description="HTML sign-in page. Shows local and/or OAuth options depending on auth.json.",
fb2fe5d )
85b8192 async def login_page(
73c9c30 next: Annotated[str, Query()] = "/",
85b8192 ) -> HTMLResponse:
73c9c30 if not settings.AUTH:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
next_safe = safe_next_url(next)
return render_page(
"login.html",
title=f"{settings.SITE_NAME} - Sign in",
next=next_safe,
error=None,
local_available=is_local_auth_available(auth_config),
oauth_available=is_oauth_auth_available(auth_config),
oauth_provider=str(auth_config.oauth_provider).strip() or "OAuth",
)
85b8192
fb2fe5d @auth_router.post(
73c9c30 "/login",
response_model=None,
tags=[TAG_AUTH_LOCAL],
summary="Local sign-in (form)",
description="Browser form login. Sets the pygitweb_access_token session cookie on success.",
responses={303: {"description": "Redirect to next URL with session cookie set"}},
fb2fe5d )
85b8192 async def login_form_submit(
73c9c30 username: Annotated[str, Form()],
password: Annotated[str, Form()],
next: Annotated[str, Form()] = "/",
85b8192 ) -> HTMLResponse | RedirectResponse:
73c9c30 if not settings.AUTH:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
if not is_local_auth_available(auth_config):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Local sign-in is not enabled")
next_safe = safe_next_url(next)
user = authenticate_local_user(username.strip(), password)
if user is None:
return render_page(
"login.html",
title=f"{settings.SITE_NAME} - Sign in",
next=next_safe,
error="Incorrect username or password.",
local_available=True,
oauth_available=is_oauth_auth_available(auth_config),
oauth_provider=str(auth_config.oauth_provider).strip() or "OAuth",
)
sid = create_session(user.username, email=user.email, auth_method="local")
resp = RedirectResponse(url=next_safe, status_code=303)
resp.set_cookie(
key=ACCESS_TOKEN_COOKIE_NAME,
value=sid,
httponly=True,
samesite="lax",
max_age=LOGIN_COOKIE_MAX_AGE,
path="/",
)
return resp
85b8192
fb2fe5d @auth_router.get(
73c9c30 "/logout",
tags=[TAG_AUTH],
summary="Sign out",
description="Revokes the current session (cookie or Bearer) and clears auth cookies.",
responses={303: {"description": "Redirect to next URL"}},
fb2fe5d )
8c60507 async def logout_page(
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)],
next: Annotated[str, Query()] = "/",
8c60507 ) -> RedirectResponse:
73c9c30 revoke_session(token)
resp = RedirectResponse(url=safe_next_url(next), status_code=303)
resp.delete_cookie(key=ACCESS_TOKEN_COOKIE_NAME, path="/")
resp.delete_cookie(key=OAUTH_STATE_COOKIE_NAME, path="/")
return resp
85b8192
fb2fe5d @auth_router.post(
73c9c30 "/token",
tags=[TAG_AUTH_LOCAL],
summary="Obtain session token (local)",
description=(
"OAuth2 password flow for API clients. Returns an opaque session id as access_token; "
"use Authorization: Bearer on protected routes. Not an identity-provider JWT."
),
fb2fe5d )
85b8192 async def login(form_data: Annotated[OAuth2PasswordRequestForm, Depends()]) -> dict[str, str]:
73c9c30 if not settings.AUTH:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
if not is_local_auth_available(auth_config):
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Local sign-in is not enabled")
user = authenticate_local_user(form_data.username, form_data.password)
if user is None:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Incorrect username or password")
sid = create_session(user.username, email=user.email, auth_method="local")
return {"access_token": sid, "token_type": "bearer"}
85b8192
fb2fe5d @auth_router.get(
73c9c30 "/auth/status",
tags=[TAG_AUTH],
summary="Auth status (navbar)",
description="Lightweight JSON for the navbar script. Does not return 401 when anonymous.",
fb2fe5d )
85b8192 async def auth_status(
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)],
85b8192 ) -> dict[str, bool | str | None]:
73c9c30 if not settings.AUTH:
return {"auth_enabled": False, "username": None, "gravatar_url": None}
if not token:
return {"auth_enabled": True, "username": None, "gravatar_url": None}
rec = get_session(token)
if rec is None:
return {"auth_enabled": True, "username": None, "gravatar_url": None}
avatar = gravatar_url(rec.email) if rec.email else None
return {"auth_enabled": True, "username": rec.username, "gravatar_url": avatar}
85b8192
7f2db6c _API_KEY_LOCK = threading.Lock()
class IssueApiKeyRequest(BaseModel):
73c9c30 id: str = Field(min_length=1)
readonly: bool = False
7f2db6c
73c9c30 @field_validator("id", mode="before")
@classmethod
def _strip_id(cls, value: object) -> object:
if not isinstance(value, str):
return value
stripped = value.strip()
if not stripped:
raise ValueError("must be a non-empty string")
return stripped
7f2db6c
class IssuedApiKey(BaseModel):
73c9c30 id: str
secret: str
readonly: bool
time_issued: datetime
time_expiry: datetime | None = None
7f2db6c
5b01811 def _local_user_by_email(email: str | None) -> LocalUser | None:
73c9c30 if not email:
return None
folded = email.strip().casefold()
if not folded:
return None
for entry in auth_config.local_users:
if entry.email and _const_eq(entry.email.casefold(), folded):
return entry
return None
7f2db6c
5b01811 def _local_user_for_principal(username: str, email: str | None) -> LocalUser | None:
73c9c30 for entry in auth_config.local_users:
if _const_eq(entry.user, username):
return entry
return _local_user_by_email(email)
5b01811
def _key_owner(username: str, email: str | None, auth_method: AuthMethod) -> LocalUser | None:
73c9c30 if auth_method == "oauth":
return _local_user_by_email(email)
return _local_user_for_principal(username, email)
5b01811
def _new_passwordless_user(email: str | None, auth_method: AuthMethod) -> LocalUser:
73c9c30 if auth_method != "oauth":
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No local account for API keys")
stored = email.strip() if email else ""
if len(stored) < 2:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="An email is required to store API keys")
for entry in auth_config.local_users:
if _const_eq(entry.user.casefold(), stored.casefold()):
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail="A local account already uses this name",
)
return LocalUser(user=stored, email=stored)
5b01811
def _drop_local_user(user: LocalUser) -> None:
73c9c30 for index, entry in enumerate(auth_config.local_users):
if entry is user:
del auth_config.local_users[index]
return
5b01811
7f2db6c def _key_expiry(issued: datetime) -> datetime | None:
73c9c30 days = settings.API_KEY_EXPIRY_DAYS
if days <= 0:
return None
return issued + timedelta(days=days)
7f2db6c
def _persist_auth_config() -> None:
73c9c30 write_auth_config(auth_config_path(settings), auth_config)
7f2db6c
def _public_key_rows(user: LocalUser) -> list[dict[str, str | bool | None]]:
73c9c30 rows: list[dict[str, str | bool | None]] = []
for key in user.keys:
rows.append({
"id": key.id,
"readonly": key.readonly,
"time_issued": key.time_issued.isoformat(),
"time_expiry": key.time_expiry.isoformat() if key.time_expiry else None,
})
return rows
7f2db6c
5b01811 def issue_api_key(
73c9c30 username: str,
email: str | None,
*,
key_id: str,
readonly: bool,
auth_method: AuthMethod = "local",
5b01811 ) -> IssuedApiKey:
73c9c30 with _API_KEY_LOCK:
user = _key_owner(username, email, auth_method)
created = False
if user is None:
user = _new_passwordless_user(email, auth_method)
created = True
if len(user.keys) >= settings.API_KEY_MAX_COUNT:
raise HTTPException(
status_code=status.HTTP_409_CONFLICT,
detail=f"API key limit reached ({settings.API_KEY_MAX_COUNT})",
)
if any(_const_eq(existing.id, key_id) for existing in user.keys):
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail="An API key with this id already exists")
issued = datetime.now(UTC)
plaintext = secrets.token_urlsafe(32)
stored = HttpKey(
id=key_id,
secret=hash_password(plaintext, config_salt=auth_config.salt),
readonly=readonly,
time_issued=issued,
time_expiry=_key_expiry(issued),
)
if created:
auth_config.local_users.append(user)
previous = list(user.keys)
user.keys = [*previous, stored]
try:
_persist_auth_config()
except Exception:
if created:
_drop_local_user(user)
else:
user.keys = previous
raise
return IssuedApiKey(
id=stored.id,
secret=plaintext,
readonly=stored.readonly,
time_issued=stored.time_issued,
time_expiry=stored.time_expiry,
)
7f2db6c
5b01811 def revoke_api_key(
73c9c30 username: str,
email: str | None,
key_id: str,
*,
auth_method: AuthMethod = "local",
5b01811 ) -> None:
73c9c30 with _API_KEY_LOCK:
user = _key_owner(username, email, auth_method)
if user is None:
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No local account for API keys")
remaining = [key for key in user.keys if not _const_eq(key.id, key_id)]
if len(remaining) == len(user.keys):
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No such API key")
previous = list(user.keys)
user.keys = remaining
try:
_persist_auth_config()
except Exception:
user.keys = previous
raise
7f2db6c
5b01811 def _account_keys(
73c9c30 username: str,
email: str | None,
auth_method: AuthMethod,
5b01811 ) -> tuple[list[dict[str, str | bool | None]] | None, str | None]:
73c9c30 if auth_method == "oauth":
user = _local_user_by_email(email)
if user is not None:
return _public_key_rows(user), user.user
stored = email.strip() if email else ""
if len(stored) < 2:
return None, None
return [], stored
user = _local_user_for_principal(username, email)
if user is None:
return None, None
return _public_key_rows(user), user.user
5b01811
def _session_identity(token: str | None) -> tuple[str, str | None, AuthMethod]:
73c9c30 ensure_active_user_if_auth_enabled(token)
rec = get_session(token or "")
if rec is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
return rec.username, rec.email, rec.auth_method
7f2db6c
fb2fe5d @auth_router.get(
73c9c30 "/user",
response_class=HTMLResponse,
response_model=None,
tags=[TAG_AUTH],
summary="Account page",
description="HTML account page for the signed-in user.",
fb2fe5d )
85b8192 async def user_account_page(
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)],
85b8192 ) -> HTMLResponse | RedirectResponse:
73c9c30 if not settings.AUTH:
return render_page(
"message.html",
title=f"{settings.SITE_NAME} - Account",
paragraphs=["Authentication is not enabled on this server."],
muted=True,
)
if not is_auth_configured(auth_config):
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Authentication is misconfigured",
)
rec = get_session(token or "")
if rec is None:
return RedirectResponse(url="/login?next=/user", status_code=303)
api_keys, api_key_user = _account_keys(rec.username, rec.email, rec.auth_method)
if api_key_user is not None and _const_eq(api_key_user, rec.username):
api_key_user = None
return render_page(
"user_profile.html",
title=f"{settings.SITE_NAME} - Account",
username=rec.username,
api_keys=api_keys,
api_key_user=api_key_user,
api_key_max=settings.API_KEY_MAX_COUNT,
api_key_expiry_days=settings.API_KEY_EXPIRY_DAYS,
)
85b8192
7f2db6c @auth_router.post(
73c9c30 "/user/keys",
response_model=IssuedApiKey,
tags=[TAG_AUTH],
summary="Issue an API key",
description=(
"Creates a Smart HTTP API key for the signed-in user. "
"An OAuth session is stored as a passwordless local account, matched by email, "
"the first time it issues a key. The plaintext secret is returned once. "
"Only its scrypt hash is stored."
),
7f2db6c )
async def issue_user_api_key(
92615af key: IssueApiKeyRequest,
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)],
7f2db6c ) -> IssuedApiKey:
73c9c30 if not settings.AUTH:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
username, email, auth_method = _session_identity(token)
92615af return issue_api_key(username, email, key_id=key.id, readonly=key.readonly, auth_method=auth_method)
7f2db6c
@auth_router.delete(
73c9c30 "/user/keys",
status_code=status.HTTP_204_NO_CONTENT,
tags=[TAG_AUTH],
summary="Revoke an API key",
description="Removes one Smart HTTP API key from the signed-in user.",
7f2db6c )
async def revoke_user_api_key(
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)],
id: Annotated[str, Query(min_length=1)],
7f2db6c ) -> Response:
73c9c30 if not settings.AUTH:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
username, email, auth_method = _session_identity(token)
revoke_api_key(username, email, id.strip(), auth_method=auth_method)
return Response(status_code=status.HTTP_204_NO_CONTENT)
7f2db6c
fb2fe5d @auth_router.get(
73c9c30 "/users/me",
response_model=User,
tags=[TAG_AUTH],
summary="Current user",
description="Returns the username for the current session (cookie or Bearer).",
fb2fe5d )
85b8192 async def read_users_me(
73c9c30 token: Annotated[str | None, Depends(access_token_from_request)],
85b8192 ) -> User:
73c9c30 if not settings.AUTH:
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Authentication is disabled")
ensure_active_user_if_auth_enabled(token)
u = decode_access_token(token or "")
if u is None:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Not authenticated",
headers={"WWW-Authenticate": "Bearer"},
)
return u