""" Built-in IndieAuth authorization server for StarPunk (v2.0.0, ADR-064) Micropub clients (Quill, Indigenous, ...) obtain tokens through IndieAuth. StarPunk issues them itself: the site owner approves a client after logging in with OIDC, and StarPunk hands out an authorization code and then an access token. Tokens are stored hashed and checked locally by /micropub. Only the authorization code flow with PKCE (S256) is supported, per the current IndieAuth spec: https://indieauth.spec.indieweb.org/ """ import base64 import hashlib import secrets from datetime import datetime, timedelta, timezone from typing import Any, Dict, List, Optional from urllib.parse import urljoin, urlparse import httpx from bs4 import BeautifulSoup from flask import current_app from starpunk.database import get_db from starpunk.utils import absolute_url_for CODE_LIFETIME_MINUTES = 10 SUPPORTED_SCOPES = ["create", "update", "delete", "media", "profile"] class AuthorizationRequestError(Exception): """ Invalid authorization request redirectable=False means the client_id or redirect_uri cannot be trusted, so the error must be shown to the user instead of sent to the client. """ def __init__(self, error: str, description: str, redirectable: bool = True): super().__init__(description) self.error = error self.description = description self.redirectable = redirectable class InvalidGrantError(Exception): """Authorization code is invalid, expired, used, or does not match""" def _hash(value: str) -> str: return hashlib.sha256(value.encode()).hexdigest() def issuer() -> str: """Issuer identifier (RFC 9207): the site URL with trailing slash""" return current_app.config["SITE_URL"].rstrip("/") + "/" def admin_me() -> str: """The single identity StarPunk issues tokens for""" return current_app.config["ADMIN_ME"] def check_scope(required_scope: str, token_scope: str) -> bool: """True if required_scope is one of the space-separated token scopes""" return bool(token_scope) and required_scope in token_scope.split() def _is_http_url(url: str) -> bool: parsed = urlparse(url or "") return parsed.scheme in ("http", "https") and bool(parsed.netloc) and not parsed.fragment def _same_origin(a: str, b: str) -> bool: pa, pb = urlparse(a), urlparse(b) return (pa.scheme, pa.hostname, pa.port) == (pb.scheme, pb.hostname, pb.port) def fetch_client_redirect_uris(client_id: str) -> List[str]: """ Fetch the redirect URIs a client publishes at its client_id URL Supports a JSON client metadata document ("redirect_uris") and the older HTML/Link header form (rel="redirect_uri"). Returns [] on any failure. """ import json from starpunk.webmention_ssrf import FetchTooLargeError, SSRFBlockedError, safe_get, user_agent # Every redirect hop is checked and the connection pinned to the checked # address, with a hard time limit (v2.11.0; DEV_MODE allows localhost) try: result = safe_get( client_id, headers={"Accept": "application/json, text/html;q=0.9", "User-Agent": user_agent(current_app.config.get("SITE_URL", ""))}, max_bytes=500_000, timeout=5.0, truncate=True, ) except (httpx.HTTPError, SSRFBlockedError, ValueError, FetchTooLargeError) as e: current_app.logger.info(f"IndieAuth: could not fetch client {client_id}: {e}") return [] if result.status_code != 200: return [] base = result.url uris: List[str] = [] if "json" in result.headers.get("Content-Type", ""): try: data = json.loads(result.text) except ValueError: return [] if isinstance(data, dict) and isinstance(data.get("redirect_uris"), list): uris.extend(u for u in data["redirect_uris"] if isinstance(u, str)) return uris link = httpx.Response(200, headers=result.headers).links.get("redirect_uri") if link and link.get("url"): uris.append(urljoin(base, link["url"])) soup = BeautifulSoup(result.text, "html.parser") for tag in soup.find_all(["link", "a"], href=True): if "redirect_uri" in (tag.get("rel") or []): uris.append(urljoin(base, tag["href"])) return uris def validate_authorization_request(params: Dict[str, str]) -> Dict[str, Any]: """ Validate an IndieAuth authorization request Args: params: Query (or form) parameters from the client Returns: Normalized request: client_id, redirect_uri, state, scopes, code_challenge Raises: AuthorizationRequestError """ client_id = (params.get("client_id") or "").strip() redirect_uri = (params.get("redirect_uri") or "").strip() # client_id / redirect_uri problems are never redirected to the client if not _is_http_url(client_id): raise AuthorizationRequestError( "invalid_request", "client_id must be an http(s) URL", redirectable=False ) if not redirect_uri or urlparse(redirect_uri).fragment: raise AuthorizationRequestError( "invalid_request", "redirect_uri is missing or invalid", redirectable=False ) if not _same_origin(client_id, redirect_uri): if redirect_uri not in fetch_client_redirect_uris(client_id): raise AuthorizationRequestError( "invalid_request", "redirect_uri is not registered by this client", redirectable=False, ) if params.get("response_type", "code") != "code": raise AuthorizationRequestError( "unsupported_response_type", "Only response_type=code is supported" ) if not params.get("state"): raise AuthorizationRequestError("invalid_request", "state is required") code_challenge = params.get("code_challenge") or "" if not code_challenge: raise AuthorizationRequestError("invalid_request", "PKCE code_challenge is required") if params.get("code_challenge_method", "S256") != "S256": raise AuthorizationRequestError( "invalid_request", "Only code_challenge_method=S256 is supported" ) scopes = [s for s in (params.get("scope") or "").split() if s] return { "client_id": client_id, "redirect_uri": redirect_uri, "state": params["state"], "scopes": scopes, "code_challenge": code_challenge, } def create_authorization_code( client_id: str, redirect_uri: str, scope: str, code_challenge: str ) -> str: """Issue a single-use authorization code (stored hashed)""" code = secrets.token_urlsafe(32) db = get_db(current_app) db.execute("DELETE FROM indieauth_codes WHERE expires_at <= datetime('now')") db.execute( """ INSERT INTO indieauth_codes (code_hash, client_id, redirect_uri, scope, code_challenge, expires_at) VALUES (?, ?, ?, ?, ?, ?) """, ( _hash(code), client_id, redirect_uri, scope, code_challenge, datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(minutes=CODE_LIFETIME_MINUTES), ), ) db.commit() return code def redeem_authorization_code( code: str, client_id: str, redirect_uri: str, code_verifier: str ) -> Dict[str, Any]: """ Redeem an authorization code exactly once Returns: {"me": ..., "scope": ..., "client_id": ...} Raises: InvalidGrantError """ if not code or not code_verifier: raise InvalidGrantError("code and code_verifier are required") db = get_db(current_app) # Atomic single use: only the first redemption flips used_at cursor = db.execute( """ UPDATE indieauth_codes SET used_at = datetime('now') WHERE code_hash = ? AND used_at IS NULL AND expires_at > datetime('now') """, (_hash(code),), ) db.commit() if cursor.rowcount != 1: raise InvalidGrantError("Authorization code is invalid, expired or already used") row = db.execute( "SELECT client_id, redirect_uri, scope, code_challenge FROM indieauth_codes WHERE code_hash = ?", (_hash(code),), ).fetchone() if row["client_id"] != client_id or row["redirect_uri"] != redirect_uri: raise InvalidGrantError("client_id or redirect_uri does not match the code") digest = hashlib.sha256(code_verifier.encode("ascii", "ignore")).digest() challenge = base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii") if not secrets.compare_digest(challenge, row["code_challenge"]): raise InvalidGrantError("PKCE verification failed") return {"me": admin_me(), "scope": row["scope"], "client_id": row["client_id"]} def create_access_token(client_id: str, scope: str) -> Dict[str, Any]: """Issue an access token (stored hashed); returns the token response""" token = secrets.token_urlsafe(32) lifetime_days = current_app.config.get("INDIEAUTH_TOKEN_LIFETIME_DAYS", 90) expires_at = datetime.now(timezone.utc).replace(tzinfo=None) + timedelta(days=lifetime_days) db = get_db(current_app) db.execute( """ INSERT INTO indieauth_tokens (token_hash, client_id, scope, expires_at) VALUES (?, ?, ?, ?) """, (_hash(token), client_id, scope, expires_at), ) db.commit() current_app.logger.info(f"IndieAuth: token issued to {client_id} (scope: {scope})") return { "access_token": token, "token_type": "Bearer", "scope": scope, "me": admin_me(), "expires_in": lifetime_days * 86400, } def verify_access_token(token: str) -> Optional[Dict[str, Any]]: """ Check a bearer token issued by StarPunk Returns: {"me", "client_id", "scope"} if active, otherwise None """ if not token: return None db = get_db(current_app) row = db.execute( """ SELECT id, client_id, scope FROM indieauth_tokens WHERE token_hash = ? AND revoked_at IS NULL AND expires_at > datetime('now') """, (_hash(token),), ).fetchone() if not row: return None db.execute( "UPDATE indieauth_tokens SET last_used_at = datetime('now') WHERE id = ?", (row["id"],), ) db.commit() return {"me": admin_me(), "client_id": row["client_id"], "scope": row["scope"]} def revoke_access_token(token: str) -> None: """Revoke a token by value (unknown tokens are ignored, per RFC 7009)""" db = get_db(current_app) db.execute( "UPDATE indieauth_tokens SET revoked_at = datetime('now') WHERE token_hash = ? AND revoked_at IS NULL", (_hash(token or ""),), ) db.commit() def revoke_token_by_id(token_id: int) -> None: """Revoke a token from the admin UI""" db = get_db(current_app) db.execute( "UPDATE indieauth_tokens SET revoked_at = datetime('now') WHERE id = ? AND revoked_at IS NULL", (token_id,), ) db.commit() def list_active_tokens() -> List[Dict[str, Any]]: """Tokens that can still be used, newest first""" db = get_db(current_app) rows = db.execute( """ SELECT id, client_id, scope, created_at, expires_at, last_used_at FROM indieauth_tokens WHERE revoked_at IS NULL AND expires_at > datetime('now') ORDER BY created_at DESC """ ).fetchall() return [dict(r) for r in rows]