refactor(web): add Forgejo service + token encryption modules

Centralize all Forgejo HTTP in app/services/forgejo.py (get/post +
authorize_url/exchange_code/fetch_user, typed ForgejoError, defensive
base-URL join). Centralize credential encryption in app/auth/tokens.py
(decrypt_pat/set_pat, set_client_secret/decrypt_client_secret) so the
get_fernet()+crypto+column pattern no longer leaks into routers.

auth/settings/setup now delegate to these modules; the duplicated
client-secret encrypt block and per-call httpx clients are gone.
This commit is contained in:
ZTatman 2026-06-10 16:58:55 -04:00
parent 8b7f2664d0
commit e3ead49f13
6 changed files with 252 additions and 119 deletions

54
web/app/auth/tokens.py Normal file
View file

@ -0,0 +1,54 @@
"""App-aware token encryption.
The single place that pairs the application Fernet cipher (`get_fernet`) with a
model's ciphertext column. Routers and handlers call these helpers instead of
deriving the cipher and touching the encrypted columns directly, so the at-rest
encryption detail — and any future key rotation — lives in one file.
This sits one layer above `app.auth.crypto`, which holds the cipher primitives
and knows nothing about the application or its models.
"""
from __future__ import annotations
from datetime import UTC, datetime
from typing import TYPE_CHECKING
from app.auth.crypto import decrypt_optional, decrypt_token, encrypt_optional, encrypt_token
from app.config import get_fernet
if TYPE_CHECKING:
from app.models.app_settings import AppSettings
from app.models.user import User
def decrypt_pat(user: User) -> str | None:
"""Return the user's decrypted Forgejo PAT, or None if none is stored."""
return decrypt_optional(get_fernet(), user.pat_encrypted)
def set_pat(user: User, raw: str | None) -> None:
"""Store (or clear) a user's Forgejo PAT.
Passing None clears it. The registered-at stamp is kept in sync with the
ciphertext so the two columns can never drift apart.
"""
user.pat_encrypted = encrypt_optional(get_fernet(), raw)
user.pat_registered_at = datetime.now(UTC) if raw else None
def set_client_secret(app_settings: AppSettings, raw: str) -> None:
"""Encrypt and store the Forgejo OAuth client secret.
Raises ValueError (from `get_fernet`) when the encryption key is unavailable.
"""
app_settings.forgejo_oauth_client_secret_encrypted = encrypt_token(get_fernet(), raw)
def decrypt_client_secret(app_settings: AppSettings) -> str:
"""Return the decrypted Forgejo OAuth client secret.
Raises ValueError when the key is unavailable or the ciphertext can't be
decrypted (e.g. the encryption key changed).
"""
return decrypt_token(get_fernet(), app_settings.forgejo_oauth_client_secret_encrypted)

View file

@ -3,60 +3,32 @@ from __future__ import annotations
import secrets
from datetime import UTC, datetime, timedelta
from typing import Annotated
from urllib.parse import urlencode
import httpx
from fastapi import APIRouter, Cookie, Depends, HTTPException, Request, status
from fastapi.responses import RedirectResponse
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.crypto import decrypt_token
from app.auth import tokens
from app.auth.identity import find_or_create_user
from app.auth.session import create_session, revoke_session
from app.config import get_app_settings, get_fernet
from app.config import get_app_settings
from app.deps import get_db
from app.models.app_settings import AppSettings
from app.services import forgejo
router = APIRouter(prefix="/auth", tags=["auth"])
# ── Forgejo API client ──
# ── Forgejo OAuth error translation ──
async def _forgejo_post(app_settings: AppSettings, path: str, data: dict) -> dict:
url = f"{app_settings.forgejo_base_url}{path}"
try:
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.post(url, data=data, headers={"Accept": "application/json"})
except httpx.RequestError:
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail="Cannot reach Forgejo. Check your connection settings.",
)
if resp.status_code != 200:
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Forgejo returned an error ({resp.status_code}). Verify your OAuth configuration.",
)
return resp.json()
async def _forgejo_get(app_settings: AppSettings, path: str, token: str) -> dict:
url = f"{app_settings.forgejo_base_url}{path}"
try:
async with httpx.AsyncClient(timeout=30.0) as client:
resp = await client.get(url, headers={"Authorization": f"token {token}"})
except httpx.RequestError:
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail="Cannot reach Forgejo. Check your connection settings.",
)
if resp.status_code != 200:
raise HTTPException(
status_code=status.HTTP_502_BAD_GATEWAY,
detail=f"Forgejo returned an error ({resp.status_code}). Verify your OAuth configuration.",
)
return resp.json()
def _oauth_gateway_error(exc: forgejo.ForgejoError) -> HTTPException:
"""Translate a Forgejo failure into the OAuth flow's 502 response."""
if exc.unreachable:
detail = "Cannot reach Forgejo. Check your connection settings."
else:
detail = f"Forgejo returned an error ({exc.status_code}). Verify your OAuth configuration."
return HTTPException(status_code=status.HTTP_502_BAD_GATEWAY, detail=detail)
# ── OAuth CSRF helpers ──
@ -126,7 +98,7 @@ def _forgejo_oauth_redirect_uri(request: Request, app_settings: AppSettings) ->
def _get_oauth_client_secret(app_settings: AppSettings) -> str:
try:
return decrypt_token(get_fernet(), app_settings.forgejo_oauth_client_secret_encrypted)
return tokens.decrypt_client_secret(app_settings)
except ValueError:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
@ -145,15 +117,7 @@ async def login_forgejo(
redirect_uri = _forgejo_oauth_redirect_uri(request, app_settings)
state = secrets.token_urlsafe(32)
query = urlencode(
{
"client_id": app_settings.forgejo_oauth_client_id,
"response_type": "code",
"redirect_uri": redirect_uri,
"state": state,
}
)
authorization_url = f"{app_settings.forgejo_base_url}/login/oauth/authorize?{query}"
authorization_url = forgejo.authorize_url(app_settings, redirect_uri=redirect_uri, state=state)
response = RedirectResponse(authorization_url, status_code=status.HTTP_302_FOUND)
_set_oauth_state_cookie(response, state)
return response
@ -181,20 +145,21 @@ async def callback_forgejo(
client_secret = _get_oauth_client_secret(app_settings)
redirect_uri = _forgejo_oauth_redirect_uri(request, app_settings)
token_data = await _forgejo_post(
app_settings,
"/login/oauth/access_token",
{
"grant_type": "authorization_code",
"client_id": app_settings.forgejo_oauth_client_id,
"client_secret": client_secret,
"code": code,
"redirect_uri": redirect_uri,
},
)
try:
token_data = await forgejo.exchange_code(
app_settings,
code=code,
client_secret=client_secret,
redirect_uri=redirect_uri,
)
except forgejo.ForgejoError as exc:
raise _oauth_gateway_error(exc) from exc
access_token, refresh_plain, expires_at = _parse_token_response(token_data)
user_data = await _forgejo_get(app_settings, "/api/v1/user", access_token)
try:
user_data = await forgejo.fetch_user(app_settings, access_token)
except forgejo.ForgejoError as exc:
raise _oauth_gateway_error(exc) from exc
provider_user_id, provider_username, email = _parse_user_response(user_data)
user = await find_or_create_user(

View file

@ -1,6 +1,5 @@
from __future__ import annotations
from datetime import UTC, datetime
from typing import Annotated
from fastapi import APIRouter, Depends, Form, HTTPException, Request, status
@ -8,9 +7,8 @@ from fastapi.responses import HTMLResponse, RedirectResponse
from starlette.responses import Response
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.crypto import encrypt_optional
from app.auth import tokens
from app.auth.session import get_current_session
from app.config import get_fernet
from app.deps import get_db
from app.models.session import Session as UserBrowserSession
from app.templating import templates
@ -28,8 +26,6 @@ async def settings_page(
"settings.html",
{
"user": sess.user,
"pat_registered": sess.user.has_pat,
"pat_registered_at": sess.user.pat_registered_at,
"pat_deleted": request.query_params.get("pat") == "deleted",
},
)
@ -48,9 +44,7 @@ async def register_pat(
detail="Forgejo access token is required.",
)
fernet = get_fernet()
sess.user.pat_encrypted = encrypt_optional(fernet, pat)
sess.user.pat_registered_at = datetime.now(UTC)
tokens.set_pat(sess.user, pat)
await db.commit()
return RedirectResponse(
@ -64,8 +58,7 @@ async def delete_pat(
db: Annotated[AsyncSession, Depends(get_db)],
sess: Annotated[UserBrowserSession, Depends(get_current_session)],
) -> RedirectResponse:
sess.user.pat_encrypted = None
sess.user.pat_registered_at = None
tokens.set_pat(sess.user, None)
await db.commit()
return RedirectResponse(

View file

@ -8,9 +8,9 @@ from starlette.responses import Response
from sqlalchemy import func as sql_func, select
from sqlalchemy.ext.asyncio import AsyncSession
from app.auth.crypto import encrypt_token
from app.auth import tokens
from app.auth.session import lookup_session
from app.config import get_fernet
from app.config import current_app_settings, set_app_settings
from app.deps import get_db
from app.models.app_settings import AppSettings
from app.models.user import User
@ -19,9 +19,21 @@ from app.templating import templates
router = APIRouter(prefix="/setup", tags=["setup"])
def _encryption_unavailable() -> HTTPException:
"""503 raised when the Forgejo client secret can't be encrypted (no key)."""
return HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=(
"TOKEN_ENCRYPTION_KEY is not set. Add it to your .env file or deployment "
"environment. Generate one with: "
"uv run python -c 'from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())'"
),
)
async def _require_auth_if_configured(
request: Request,
db: Annotated[AsyncSession, Depends(get_db)],
app_settings: Annotated[AppSettings | None, Depends(current_app_settings)],
firebreak_session: Annotated[str | None, Cookie()] = None,
) -> None:
"""Block anonymous access to /setup after initial configuration.
@ -29,7 +41,7 @@ async def _require_auth_if_configured(
If no users exist yet (e.g. bad OAuth config on first setup), the setup
token is still required but login is not — there's nobody to log in as.
"""
if request.app.state.app_settings is None:
if app_settings is None:
return
# If no users exist, allow access — the setup token still protects POST
@ -46,9 +58,12 @@ async def _require_auth_if_configured(
@router.get("", dependencies=[Depends(_require_auth_if_configured)])
async def setup_page(request: Request, db: Annotated[AsyncSession, Depends(get_db)]) -> Response:
async def setup_page(
request: Request,
db: Annotated[AsyncSession, Depends(get_db)],
existing: Annotated[AppSettings | None, Depends(current_app_settings)],
) -> Response:
"""Render the setup wizard. Pre-fills fields when reconfiguring."""
existing = request.app.state.app_settings
user_count = await db.scalar(select(sql_func.count()).select_from(User)) or 0
has_users = user_count > 0
public_base = (existing.firebreak_public_base_url if existing else "") or str(
@ -68,6 +83,7 @@ async def setup_page(request: Request, db: Annotated[AsyncSession, Depends(get_d
async def setup_submit(
request: Request,
db: Annotated[AsyncSession, Depends(get_db)],
app_settings: Annotated[AppSettings | None, Depends(current_app_settings)],
forgejo_base_url: Annotated[str, Form()],
forgejo_oauth_client_id: Annotated[str, Form()],
forgejo_oauth_client_secret: Annotated[str, Form()] = "",
@ -77,7 +93,7 @@ async def setup_submit(
"""Process the setup wizard — creates or updates Forgejo settings."""
user_count = await db.scalar(select(sql_func.count()).select_from(User)) or 0
has_users = user_count > 0
is_reconfiguring = request.app.state.app_settings is not None and has_users
is_reconfiguring = app_settings is not None and has_users
# Require setup token when no users exist (first-time or fixing bad config)
if not has_users:
@ -111,22 +127,12 @@ async def setup_submit(
row.firebreak_public_base_url = firebreak_public_base_url
if forgejo_oauth_client_secret:
try:
fernet = get_fernet()
tokens.set_client_secret(row, forgejo_oauth_client_secret)
except ValueError:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=(
"TOKEN_ENCRYPTION_KEY is not set. Add it to your .env file or deployment "
"environment. Generate one with: "
"uv run python -c 'from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())'"
),
)
row.forgejo_oauth_client_secret_encrypted = encrypt_token(
fernet, forgejo_oauth_client_secret
)
raise _encryption_unavailable()
await db.commit()
await db.refresh(row)
request.app.state.app_settings = row
set_app_settings(request.app, row)
return RedirectResponse("/", status_code=status.HTTP_303_SEE_OTHER)
# First-time setup (or retry after bad config) — no users exist yet
@ -136,38 +142,21 @@ async def setup_submit(
detail="Client Secret is required during initial setup.",
)
try:
fernet = get_fernet()
except ValueError:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail=(
"TOKEN_ENCRYPTION_KEY is not set. Add it to your .env file or deployment "
"environment. Generate one with: "
"uv run python -c 'from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())'"
),
)
encrypted_secret = encrypt_token(fernet, forgejo_oauth_client_secret)
# Update existing row if retrying after bad config, otherwise create
# Update existing row if retrying after bad config, otherwise create one.
result = await db.execute(select(AppSettings).where(AppSettings.id == 1))
row = result.scalar_one_or_none()
if row:
row.forgejo_base_url = forgejo_base_url
row.forgejo_oauth_client_id = forgejo_oauth_client_id
row.forgejo_oauth_client_secret_encrypted = encrypted_secret
row.firebreak_public_base_url = firebreak_public_base_url
else:
row = AppSettings(
id=1,
forgejo_base_url=forgejo_base_url,
forgejo_oauth_client_id=forgejo_oauth_client_id,
forgejo_oauth_client_secret_encrypted=encrypted_secret,
firebreak_public_base_url=firebreak_public_base_url,
)
if row is None:
row = AppSettings(id=1, forgejo_oauth_client_secret_encrypted="")
db.add(row)
row.forgejo_base_url = forgejo_base_url
row.forgejo_oauth_client_id = forgejo_oauth_client_id
row.firebreak_public_base_url = firebreak_public_base_url
try:
tokens.set_client_secret(row, forgejo_oauth_client_secret)
except ValueError:
raise _encryption_unavailable()
await db.commit()
await db.refresh(row)
request.app.state.app_settings = row
set_app_settings(request.app, row)
return RedirectResponse("/", status_code=status.HTTP_303_SEE_OTHER)

View file

132
web/app/services/forgejo.py Normal file
View file

@ -0,0 +1,132 @@
"""Thin async client for the Forgejo API.
Centralizes the httpx mechanics, base-URL joining, and error shape shared by
the OAuth flow (`app.routers.auth`) and the dashboard repository fragment
(`app.main`). Transport failures and non-2xx responses both surface as a typed
`ForgejoError`, leaving each caller free to decide how to handle them — the
OAuth routes translate it into an HTTP 502, while the dashboard renders an
inline message.
"""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from urllib.parse import urlencode
import httpx
if TYPE_CHECKING:
from app.models.app_settings import AppSettings
DEFAULT_TIMEOUT = 30.0
class ForgejoError(Exception):
"""A Forgejo API call failed — either unreachable or a non-2xx response."""
def __init__(self, message: str, *, status_code: int | None = None) -> None:
super().__init__(message)
self.message = message
# The HTTP status returned by Forgejo, or None if it was unreachable.
self.status_code = status_code
@property
def unreachable(self) -> bool:
"""True when the request never got an HTTP response (network error)."""
return self.status_code is None
def _url(app_settings: AppSettings, path: str) -> str:
# Defensive rstrip: a base URL stored with a trailing slash would otherwise
# produce a double slash (`https://forge//api/...`) and 404.
return f"{app_settings.forgejo_base_url.rstrip('/')}{path}"
async def get(
app_settings: AppSettings,
path: str,
*,
token: str | None = None,
params: dict[str, Any] | None = None,
timeout: float = DEFAULT_TIMEOUT,
) -> Any:
"""GET a Forgejo API path, returning parsed JSON. Raises ForgejoError."""
headers = {"Accept": "application/json"}
if token:
headers["Authorization"] = f"token {token}"
try:
async with httpx.AsyncClient(timeout=timeout) as client:
resp = await client.get(_url(app_settings, path), params=params, headers=headers)
except httpx.RequestError as exc:
raise ForgejoError("Cannot reach Forgejo. Check your connection settings.") from exc
if resp.status_code != 200:
raise ForgejoError(
f"Forgejo returned an error ({resp.status_code}).",
status_code=resp.status_code,
)
return resp.json()
async def post(
app_settings: AppSettings,
path: str,
data: dict[str, Any],
*,
timeout: float = DEFAULT_TIMEOUT,
) -> Any:
"""POST form data to a Forgejo API path, returning parsed JSON. Raises ForgejoError."""
try:
async with httpx.AsyncClient(timeout=timeout) as client:
resp = await client.post(
_url(app_settings, path), data=data, headers={"Accept": "application/json"}
)
except httpx.RequestError as exc:
raise ForgejoError("Cannot reach Forgejo. Check your connection settings.") from exc
if resp.status_code != 200:
raise ForgejoError(
f"Forgejo returned an error ({resp.status_code}).",
status_code=resp.status_code,
)
return resp.json()
# ── OAuth ──
def authorize_url(app_settings: AppSettings, *, redirect_uri: str, state: str) -> str:
"""Build the Forgejo OAuth authorize URL to redirect the browser to."""
query = urlencode(
{
"client_id": app_settings.forgejo_oauth_client_id,
"response_type": "code",
"redirect_uri": redirect_uri,
"state": state,
}
)
return f"{_url(app_settings, '/login/oauth/authorize')}?{query}"
async def exchange_code(
app_settings: AppSettings,
*,
code: str,
client_secret: str,
redirect_uri: str,
) -> Any:
"""Exchange an authorization code for tokens. Raises ForgejoError."""
return await post(
app_settings,
"/login/oauth/access_token",
{
"grant_type": "authorization_code",
"client_id": app_settings.forgejo_oauth_client_id,
"client_secret": client_secret,
"code": code,
"redirect_uri": redirect_uri,
},
)
async def fetch_user(app_settings: AppSettings, token: str) -> Any:
"""Fetch the authenticated user's Forgejo profile. Raises ForgejoError."""
return await get(app_settings, "/api/v1/user", token=token)