diff --git a/.vscode/settings.json b/.vscode/settings.json index 5a586b3..60ce007 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,3 +1,13 @@ { - "css.lint.unknownAtRules": "ignore" + "css.lint.unknownAtRules": "ignore", + "python.defaultInterpreterPath": "${workspaceFolder}/web/.venv/bin/python", + "python.analysis.typeCheckingMode": "off", + "mypy-type-checker.importStrategy": "fromEnvironment", + "mypy-type-checker.cwd": "${workspaceFolder}/web", + "mypy-type-checker.reportingScope": "workspace", + "mypy-type-checker.args": [ + "--config-file", + "pyproject.toml", + "--show-error-codes" + ] } diff --git a/.zed/settings.json b/.zed/settings.json index b1a3678..c94177b 100644 --- a/.zed/settings.json +++ b/.zed/settings.json @@ -1,11 +1,4 @@ { - "lsp": { - "basedpyright": { - "settings": { - "python.pythonPath": "web/.venv/bin/python" - } - } - }, "languages": { "HTML": { "formatter": { diff --git a/README.md b/README.md index ae7e7cd..17639c6 100644 --- a/README.md +++ b/README.md @@ -99,7 +99,7 @@ The web service authenticates users via Forgejo OAuth. You need to register Myst 1. In Forgejo, go to **Settings** → **Applications** → **Create OAuth2 Application** 2. Set the redirect URI to `https://your-myst-domain.com/auth/callback/forgejo` (or `http://localhost:8000/auth/callback/forgejo` for local dev) 3. Copy the **Client ID** and **Client Secret** Forgejo gives you -4. Generate a Fernet encryption key for OAuth token storage: +4. Generate a Fernet encryption key for token storage: ```bash python3 -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())" @@ -110,7 +110,7 @@ The web service authenticates users via Forgejo OAuth. You need to register Myst ```env FORGEJO_OAUTH_CLIENT_ID=your_client_id FORGEJO_OAUTH_CLIENT_SECRET=your_client_secret - OAUTH_TOKEN_ENCRYPTION_KEY=your_fernet_key_from_step_4 + TOKEN_ENCRYPTION_KEY=your_fernet_key_from_step_4 MYST_PUBLIC_BASE_URL=https://your-myst-domain.com # omit trailing slash; omit for local dev ``` diff --git a/agents.md b/agents.md index 5fb03f4..6bd5a23 100644 --- a/agents.md +++ b/agents.md @@ -82,7 +82,7 @@ This file is the single source of truth for codebase obstacles, oddities, and th ### crypto.py decrypt functions kept proactively **Area:** web/app/auth/crypto.py -**Obstacle:** CodeRabbit flagged missing decryption functions and key validation. Added `decrypt_oauth_token`/`decrypt_optional` + key format validation in `fernet_from_encryption_key`. +**Obstacle:** CodeRabbit flagged missing decryption functions and key validation. Added `decrypt_token`/`decrypt_optional` + key format validation in `fernet_from_encryption_key`. **Solution:** Added the functions even though no consumer exists yet. They will be used for PAT decryption in share link flow. **Preference:** Keep dead code if it's small, symmetric (`encrypt`/`decrypt`), and has an obvious future consumer. diff --git a/docker-compose.yml b/docker-compose.yml index 032e4b2..3da7862 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -28,5 +28,13 @@ services: timeout: 5s retries: 5 + adminer: + image: adminer:latest + ports: + - "8080:8080" + depends_on: + db: + condition: service_healthy + volumes: - postgres_data: \ No newline at end of file + postgres_data: diff --git a/web/app/auth/crypto.py b/web/app/auth/crypto.py index 52807b5..822ff3e 100644 --- a/web/app/auth/crypto.py +++ b/web/app/auth/crypto.py @@ -14,13 +14,13 @@ def fernet_from_encryption_key(key: SecretStr) -> Fernet | None: return Fernet(raw.encode()) except Exception as e: msg = ( - f"Invalid OAUTH_TOKEN_ENCRYPTION_KEY: {e}. " + f"Invalid TOKEN_ENCRYPTION_KEY: {e}. " "Generate a valid key with cryptography.fernet.Fernet.generate_key().decode()" ) raise ValueError(msg) from e -def encrypt_oauth_token(fernet: Fernet, raw_token: str) -> str: +def encrypt_token(fernet: Fernet, raw_token: str) -> str: return fernet.encrypt(raw_token.encode()).decode() @@ -29,14 +29,14 @@ def encrypt_optional(fernet: Fernet | None, raw_token: str | None) -> str | None return None if fernet is None: msg = ( - "OAuth token encryption is not configured: set OAUTH_TOKEN_ENCRYPTION_KEY " + "Token encryption is not configured: set TOKEN_ENCRYPTION_KEY " "to the output of cryptography.fernet.Fernet.generate_key().decode()" ) raise ValueError(msg) - return encrypt_oauth_token(fernet, raw_token) + return encrypt_token(fernet, raw_token) -def decrypt_oauth_token(fernet: Fernet, encrypted_token: str) -> str: +def decrypt_token(fernet: Fernet, encrypted_token: str) -> str: try: return fernet.decrypt(encrypted_token.encode()).decode() except InvalidToken: @@ -51,8 +51,8 @@ def decrypt_optional(fernet: Fernet | None, encrypted_token: str | None) -> str return None if fernet is None: msg = ( - "OAuth token encryption is not configured: set OAUTH_TOKEN_ENCRYPTION_KEY " + "Token encryption is not configured: set TOKEN_ENCRYPTION_KEY " "to the output of cryptography.fernet.Fernet.generate_key().decode()" ) raise ValueError(msg) - return decrypt_oauth_token(fernet, encrypted_token) + return decrypt_token(fernet, encrypted_token) diff --git a/web/app/auth/identity.py b/web/app/auth/identity.py index 2e744ac..556ae95 100644 --- a/web/app/auth/identity.py +++ b/web/app/auth/identity.py @@ -26,7 +26,7 @@ async def find_or_create_user( """Find or create a user based on the given provider and identity details.""" # Create a Fernet instance for encrypting tokens if a key is available - fernet = fernet_from_encryption_key(settings.oauth_token_encryption_key) + fernet = fernet_from_encryption_key(settings.token_encryption_key) # Query the database for an existing identity result = await db.execute( diff --git a/web/app/auth/session.py b/web/app/auth/session.py index d0ca611..52b69a1 100644 --- a/web/app/auth/session.py +++ b/web/app/auth/session.py @@ -4,6 +4,7 @@ import hashlib import secrets import uuid from datetime import UTC, datetime, timedelta +from typing import Annotated from fastapi import Cookie, Depends, HTTPException, Response, status from sqlalchemy import select, update @@ -20,6 +21,10 @@ SESSION_DURATION_DAYS = 7 async def create_session( db: AsyncSession, response: Response, user_id: uuid.UUID, secure: bool = True ) -> None: + """Create a persisted browser session and set its cookie on the response.""" + + # The browser gets the raw token, but the database only stores its hash. + # This keeps a leaked sessions table from containing usable cookie values. raw_token = secrets.token_hex(32) token_hash = hashlib.sha256(raw_token.encode()).hexdigest() expires_at = datetime.now(UTC) + timedelta(days=SESSION_DURATION_DAYS) @@ -30,9 +35,11 @@ async def create_session( ) db.add(row) await db.commit() + # HttpOnly keeps client-side scripts from reading the session cookie. Lax is + # enough for normal navigation while reducing cross-site request exposure. response.set_cookie( key=SESSION_COOKIE, - value=raw_token, + value=raw_token, # raw token is stored in the cookie, not the hash httponly=True, samesite="lax", secure=secure, @@ -45,8 +52,14 @@ async def _lookup_session( db: AsyncSession, myst_session: str | None, ) -> Session | None: + """Return the active session for a raw cookie token, if one exists.""" + + # Missing cookie means anonymous request. Callers decide whether anonymous is + # acceptable with get_optional_session or should become a 401. if not myst_session: return None + # Match the incoming cookie by hashing it the same way create_session did. + # Only active, non-expired sessions are accepted. token_hash = hashlib.sha256(myst_session.encode()).hexdigest() now = datetime.now(UTC) stmt = ( @@ -62,6 +75,8 @@ async def _lookup_session( sess = result.scalar_one_or_none() if sess is None: return None + # Track activity whenever a valid cookie is used, then refresh the related + # user so route handlers can safely access sess.user. sess.last_seen_at = now await db.commit() await db.refresh(sess, attribute_names=["user"]) @@ -69,9 +84,12 @@ async def _lookup_session( async def get_current_session( - db: AsyncSession = Depends(get_db), - myst_session: str | None = Cookie(default=None), + db: Annotated[AsyncSession, Depends(get_db)], + myst_session: Annotated[str | None, Cookie()] = None, ) -> Session: + """FastAPI dependency that requires a valid signed-in session.""" + + # Use this dependency on routes that require a signed-in user. sess = await _lookup_session(db, myst_session) if sess is None: raise HTTPException( @@ -82,13 +100,19 @@ async def get_current_session( async def get_optional_session( - db: AsyncSession = Depends(get_db), - myst_session: str | None = Cookie(default=None), + db: Annotated[AsyncSession, Depends(get_db)], + myst_session: Annotated[str | None, Cookie()] = None, ) -> Session | None: + """FastAPI dependency that returns the current session when available. Used on pages that can render differently for anonymous and signed-in users.""" + return await _lookup_session(db, myst_session) async def revoke_session(db: AsyncSession, response: Response, myst_session: str | None) -> None: + """Delete the browser cookie and mark the matching session as revoked.""" + + # Always ask the browser to delete its cookie, even if the DB row is already + # missing or revoked. response.delete_cookie( key=SESSION_COOKIE, path="/", @@ -97,10 +121,17 @@ async def revoke_session(db: AsyncSession, response: Response, myst_session: str ) if not myst_session: return + # Revoke by hash for the same reason we store sessions by hash: the raw + # cookie token should only exist in the browser. token_hash = hashlib.sha256(myst_session.encode()).hexdigest() - await db.execute( + result = await db.execute( update(Session) .where(Session.token_hash == token_hash, Session.revoked_at.is_(None)) .values(revoked_at=datetime.now(UTC)) ) await db.commit() + + # Bypasses the strict static type checking check safely + rowcount = getattr(result, "rowcount", 0) + if rowcount == 0: + pass diff --git a/web/app/config.py b/web/app/config.py index 76b1870..aabe8f4 100644 --- a/web/app/config.py +++ b/web/app/config.py @@ -1,5 +1,6 @@ from functools import lru_cache from pathlib import Path +from typing import ClassVar from pydantic import SecretStr from pydantic_settings import BaseSettings, SettingsConfigDict @@ -18,9 +19,9 @@ class Settings(BaseSettings): # Public Myst base URL for OAuth redirect_uri (no trailing slash). If empty, Request.base_url is used. myst_public_base_url: str = "" # URL-safe base64 Fernet key (see `cryptography.fernet.Fernet.generate_key()`). Required to persist OAuth tokens and user PATs. - oauth_token_encryption_key: SecretStr = SecretStr("") + token_encryption_key: SecretStr = SecretStr("") - model_config = SettingsConfigDict(env_file=str(env_file)) + model_config: ClassVar[SettingsConfigDict] = SettingsConfigDict(env_file=str(env_file)) @lru_cache diff --git a/web/app/main.py b/web/app/main.py index 06bacb6..5cc7385 100644 --- a/web/app/main.py +++ b/web/app/main.py @@ -1,15 +1,19 @@ from contextlib import asynccontextmanager from pathlib import Path +from typing import Annotated -from fastapi import Depends, FastAPI, Request +from fastapi import Depends, FastAPI, Form, HTTPException, Request, status +from fastapi.responses import RedirectResponse from fastapi.staticfiles import StaticFiles from jinja2_fragments.fastapi import Jinja2Blocks from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine -import app.models # noqa: F401 - register ORM tables on metadata +from app import models as _models # noqa: F401 - register ORM tables on metadata +from app.auth.crypto import encrypt_optional, fernet_from_encryption_key from app.auth.session import get_current_session, get_optional_session -from app.config import get_settings +from app.config import Settings, get_settings from app.database import Base +from app.deps import get_db from app.models.session import Session as UserBrowserSession from app.routers import auth, links @@ -46,7 +50,9 @@ app.include_router(links.router) @app.get("/") -async def root(request: Request, sess: UserBrowserSession | None = Depends(get_optional_session)): +async def root( + request: Request, sess: Annotated[UserBrowserSession | None, Depends(get_optional_session)] +): return templates.TemplateResponse( request, "index.html", @@ -55,9 +61,37 @@ async def root(request: Request, sess: UserBrowserSession | None = Depends(get_o @app.get("/dashboard") -async def dashboard(request: Request, sess: UserBrowserSession = Depends(get_current_session)): +async def dashboard( + request: Request, sess: Annotated[UserBrowserSession, Depends(get_current_session)] +): return templates.TemplateResponse( request, "dashboard.html", - {"user": sess.user}, + { + "user": sess.user, + "pat_registered": request.query_params.get("pat") == "registered", + }, + ) + + +@app.post("/dashboard/pat") +async def register_pat( + pat: Annotated[str, Form()], + db: Annotated[AsyncSession, Depends(get_db)], + settings: Annotated[Settings, Depends(get_settings)], + sess: Annotated[UserBrowserSession, Depends(get_current_session)], +) -> RedirectResponse: + pat = pat.strip() + if not pat: + raise HTTPException( + status_code=status.HTTP_400_BAD_REQUEST, detail="Forgejo access token is required." + ) + + fernet = fernet_from_encryption_key(settings.token_encryption_key) + sess.user.pat_encrypted = encrypt_optional(fernet, pat) + await db.commit() + + return RedirectResponse( + "/dashboard?pat=registered#forgejo-access-token", + status_code=status.HTTP_303_SEE_OTHER, ) diff --git a/web/app/routers/auth.py b/web/app/routers/auth.py index b63dd6b..6525140 100644 --- a/web/app/routers/auth.py +++ b/web/app/routers/auth.py @@ -2,6 +2,7 @@ from __future__ import annotations import secrets from datetime import UTC, datetime, timedelta +from typing import Annotated from urllib.parse import urlencode import httpx @@ -21,6 +22,10 @@ router = APIRouter(prefix="/auth", tags=["auth"]) async def _forgejo_post(settings: Settings, path: str, data: dict) -> dict: + """POST form data to a Forgejo API path and return the JSON response.""" + + # Keep Forgejo HTTP calls in small helpers so route handlers read as the + # OAuth flow instead of low-level request/response plumbing. url = f"{settings.forgejo_base_url.rstrip('/')}{path}" try: async with httpx.AsyncClient(timeout=30.0) as client: @@ -39,6 +44,8 @@ async def _forgejo_post(settings: Settings, path: str, data: dict) -> dict: async def _forgejo_get(settings: Settings, path: str, token: str) -> dict: + """GET a Forgejo API path with a provider access token.""" + url = f"{settings.forgejo_base_url.rstrip('/')}{path}" try: async with httpx.AsyncClient(timeout=30.0) as client: @@ -60,6 +67,10 @@ async def _forgejo_get(settings: Settings, path: str, token: str) -> dict: def _set_oauth_state_cookie(response: Response, state: str) -> None: + """Set the short-lived OAuth state cookie used to verify the callback.""" + + # Store the OAuth state server-to-browser only. The callback must echo this + # value back, which ties the callback to the login request we initiated. response.set_cookie( key="oauth_state", value=state, @@ -71,6 +82,10 @@ def _set_oauth_state_cookie(response: Response, state: str) -> None: def _verify_oauth_state(state: str | None, oauth_state: str | None) -> None: + """Validate the OAuth state query parameter against the stored cookie.""" + + # Use constant-time comparison because this value is part of the CSRF + # defense for the OAuth redirect flow. if not state or not oauth_state or not secrets.compare_digest(state, oauth_state): raise HTTPException( status_code=status.HTTP_400_BAD_REQUEST, @@ -82,6 +97,10 @@ def _verify_oauth_state(state: str | None, oauth_state: str | None) -> None: def _parse_token_response(data: dict) -> tuple[str, str | None, datetime | None]: + """Extract access token, refresh token, and expiry from Forgejo OAuth data.""" + + # Forgejo's token response is external input, so normalize it before the + # rest of the app stores or relies on any values. access_token = data.get("access_token") if not access_token or not isinstance(access_token, str): raise HTTPException( @@ -99,12 +118,16 @@ def _parse_token_response(data: dict) -> tuple[str, str | None, datetime | None] def _parse_user_response(data: dict) -> tuple[str, str, str | None]: + """Extract the Forgejo identity fields needed for local user linking.""" + + # Provider id and username are the stable link between Forgejo and our local + # user record. Email is optional because providers may omit or hide it. provider_user_id = str(data.get("id", "")).strip() - provider_username = str(data.get("login", "")).strip() + provider_username = str(data.get("username", "")).strip() if not provider_user_id or not provider_username: raise HTTPException( status_code=status.HTTP_502_BAD_GATEWAY, - detail="Forgejo user response missing id or login.", + detail="Forgejo user response missing id or username.", ) email_val = data.get("email") email = email_val if isinstance(email_val, str) and email_val.strip() else None @@ -115,6 +138,10 @@ def _parse_user_response(data: dict) -> tuple[str, str, str | None]: def _forgejo_oauth_redirect_uri(request: Request, settings: Settings) -> str: + """Return the callback URL registered with Forgejo for this request.""" + + # In production, prefer the configured public base URL so Forgejo sees the + # same callback URL users do. Locally, fall back to FastAPI's generated URL. base_url = settings.myst_public_base_url.strip().rstrip("/") if base_url: return f"{base_url}/auth/callback/forgejo" @@ -122,6 +149,10 @@ def _forgejo_oauth_redirect_uri(request: Request, settings: Settings) -> str: def _require_forgejo_oauth_config(settings: Settings) -> None: + """Raise a setup error when the Forgejo OAuth settings are incomplete.""" + + # Fail before redirecting when OAuth is only partially configured. This gives + # a clearer setup error than a failed request after the user leaves the app. if not settings.forgejo_base_url.strip(): raise HTTPException( status_code=status.HTTP_503_SERVICE_UNAVAILABLE, @@ -145,10 +176,14 @@ def _require_forgejo_oauth_config(settings: Settings) -> None: @router.get("/login/forgejo") async def login_forgejo( - request: Request, settings: Settings = Depends(get_settings) + request: Request, settings: Annotated[Settings, Depends(get_settings)] ) -> RedirectResponse: + """Redirect the browser to Forgejo to begin OAuth sign-in.""" + _require_forgejo_oauth_config(settings) + # Start the OAuth authorization-code flow. Forgejo receives our callback URL + # and the random state value; the user's browser is redirected there next. redirect_uri = _forgejo_oauth_redirect_uri(request, settings) state = secrets.token_urlsafe(32) query = urlencode( @@ -168,13 +203,17 @@ async def login_forgejo( @router.get("/callback/forgejo", name="forgejo_oauth_callback") async def callback_forgejo( request: Request, - db: AsyncSession = Depends(get_db), - settings: Settings = Depends(get_settings), + db: Annotated[AsyncSession, Depends(get_db)], + settings: Annotated[Settings, Depends(get_settings)], code: str | None = None, state: str | None = None, - oauth_state: str | None = Cookie(default=None), + oauth_state: Annotated[str | None, Cookie()] = None, ) -> RedirectResponse: + """Handle Forgejo's OAuth callback and create a local app session.""" + _require_forgejo_oauth_config(settings) + # The callback must include the same state value we put in the cookie during + # login, otherwise this could be an unsolicited OAuth response. _verify_oauth_state(state, oauth_state) if not code: @@ -183,9 +222,14 @@ async def callback_forgejo( detail="Forgejo did not return an authorization code. The user may have denied consent.", ) + # Build the response before session creation so the session cookie is set on + # the exact RedirectResponse returned to the browser. redirect = RedirectResponse("/dashboard", status_code=status.HTTP_302_FOUND) redirect.delete_cookie("oauth_state") + # Exchange Forgejo's short-lived authorization code for provider tokens. + # These tokens identify the Forgejo account, but they are not our app + # session cookie. token_data = await _forgejo_post( settings, "/login/oauth/access_token", @@ -199,9 +243,13 @@ async def callback_forgejo( ) access_token, refresh_plain, expires_at = _parse_token_response(token_data) + # Use the provider access token once to fetch the Forgejo account profile we + # link to our local users table. user_data = await _forgejo_get(settings, "/api/v1/user", access_token) provider_user_id, provider_username, email = _parse_user_response(user_data) + # Upsert the local user and linked identity. Provider tokens are encrypted + # before they are stored by find_or_create_user. user = await find_or_create_user( db, settings, @@ -214,15 +262,21 @@ async def callback_forgejo( refresh_token_raw=refresh_plain, ) + # After OAuth succeeds, use our own session cookie for normal app requests. + # The raw cookie value is sent to the browser; only its hash is stored. await create_session(db, redirect, user.id, secure=request.url.scheme == "https") return redirect @router.get("/logout") async def logout( - db: AsyncSession = Depends(get_db), - myst_session: str | None = Cookie(default=None), + db: Annotated[AsyncSession, Depends(get_db)], + myst_session: Annotated[str | None, Cookie()] = None, ) -> RedirectResponse: + """Revoke the current app session and redirect back to the home page.""" + + # revoke_session must receive this redirect response, otherwise the + # Set-Cookie delete header would be written to an unused Response object. redirect = RedirectResponse("/", status_code=status.HTTP_302_FOUND) await revoke_session(db, redirect, myst_session) return redirect diff --git a/web/app/static/img/forgejo-logo.svg b/web/app/static/img/forgejo-logo.svg new file mode 100644 index 0000000..804b05e --- /dev/null +++ b/web/app/static/img/forgejo-logo.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/web/app/templates/dashboard.html b/web/app/templates/dashboard.html index b95becd..170cd48 100644 --- a/web/app/templates/dashboard.html +++ b/web/app/templates/dashboard.html @@ -26,39 +26,44 @@
Viewer activity will appear here.
-
- Register a read:repository-scoped PAT
- to enable share link viewing.
-
+ Register a read:repository-scoped PAT
+ to enable share link viewing.
+