Admin login now uses OpenID Connect (PKCE, nonce, ID token verified against the provider JWKS) and only OIDC_ADMIN_SUB may log in. Micropub tokens are issued and verified by StarPunk itself, with a consent screen behind the OIDC session and a Connected Apps page to revoke them, so an external IndieAuth server (Gondulf) is no longer needed. Existing notes, media, tags, webmentions, author profile and sessions are unchanged. Migration 011 adds new tables only. BREAKING CHANGE: production requires OIDC_ISSUER, OIDC_CLIENT_ID, OIDC_CLIENT_SECRET and OIDC_ADMIN_SUB. The ADMIN_ME page must point Micropub apps at StarPunk's IndieAuth endpoints. See ADR-064. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
503 lines
14 KiB
Python
503 lines
14 KiB
Python
"""
|
|
Authentication module for StarPunk
|
|
|
|
Admin login uses OpenID Connect (authorization code flow with PKCE) against
|
|
a configured provider such as Pocket ID. Exactly one OIDC subject
|
|
(OIDC_ADMIN_SUB) may log in; a successful login creates a local session
|
|
for the site owner's identity URL (ADMIN_ME). No passwords are stored.
|
|
|
|
Security features:
|
|
- CSRF protection via single-use state tokens
|
|
- PKCE (S256) and nonce binding of the ID token to the login attempt
|
|
- ID token signature, issuer, audience and expiry checks
|
|
- Session tokens hashed in the database (SHA-256)
|
|
- HttpOnly, Secure, SameSite cookies
|
|
|
|
Functions:
|
|
initiate_login: Start the OIDC login flow
|
|
handle_callback: Finish the OIDC login flow and create a session
|
|
create_session: Create authenticated session
|
|
verify_session: Check if session is valid
|
|
destroy_session: Logout and cleanup
|
|
require_auth: Decorator for protected routes
|
|
|
|
Exceptions:
|
|
AuthError: Base authentication exception
|
|
InvalidStateError: CSRF state validation failed
|
|
UnauthorizedError: User not authorized as admin
|
|
OIDCError: Identity provider error
|
|
"""
|
|
|
|
import base64
|
|
import hashlib
|
|
import secrets
|
|
import time
|
|
from datetime import datetime, timedelta
|
|
from functools import wraps
|
|
from typing import Any, Dict, Optional, Tuple
|
|
from urllib.parse import urlencode
|
|
|
|
import httpx
|
|
import jwt
|
|
from flask import current_app, g, redirect, request, session, url_for
|
|
|
|
from starpunk.database import get_db
|
|
|
|
# Cached provider metadata: {issuer: (fetched_at, metadata)}
|
|
_METADATA_CACHE: Dict[str, Tuple[float, dict]] = {}
|
|
_METADATA_TTL = 3600
|
|
# One JWKS client per jwks_uri; PyJWKClient caches the keys itself
|
|
_JWKS_CLIENTS: Dict[str, jwt.PyJWKClient] = {}
|
|
|
|
LOGIN_STATE_MINUTES = 10
|
|
|
|
|
|
# Custom exceptions
|
|
class AuthError(Exception):
|
|
"""Base exception for authentication errors"""
|
|
|
|
|
|
class InvalidStateError(AuthError):
|
|
"""CSRF state validation failed"""
|
|
|
|
|
|
class UnauthorizedError(AuthError):
|
|
"""User not authorized as admin"""
|
|
|
|
|
|
class OIDCError(AuthError):
|
|
"""Identity provider error"""
|
|
|
|
|
|
def _hash_token(token: str) -> str:
|
|
"""
|
|
Hash token using SHA-256
|
|
|
|
Args:
|
|
token: Token to hash
|
|
|
|
Returns:
|
|
Hexadecimal hash string
|
|
"""
|
|
return hashlib.sha256(token.encode()).hexdigest()
|
|
|
|
|
|
def _generate_state_token() -> str:
|
|
"""Generate a URL-safe random token"""
|
|
return secrets.token_urlsafe(32)
|
|
|
|
|
|
def _pkce_challenge(verifier: str) -> str:
|
|
"""S256 PKCE challenge for a verifier (RFC 7636)"""
|
|
digest = hashlib.sha256(verifier.encode("ascii")).digest()
|
|
return base64.urlsafe_b64encode(digest).rstrip(b"=").decode("ascii")
|
|
|
|
|
|
def _redirect_uri() -> str:
|
|
"""OIDC redirect URI registered with the provider"""
|
|
return current_app.config["SITE_URL"].rstrip("/") + "/auth/callback"
|
|
|
|
|
|
def _safe_next_url(next_url: Optional[str]) -> Optional[str]:
|
|
"""Only allow redirects back to this site after login"""
|
|
if not next_url:
|
|
return None
|
|
site = current_app.config["SITE_URL"].rstrip("/")
|
|
if next_url.startswith(site + "/"):
|
|
return next_url
|
|
if next_url.startswith("/") and not next_url.startswith("//"):
|
|
return next_url
|
|
return None
|
|
|
|
|
|
def _cleanup_expired_sessions() -> None:
|
|
"""Remove expired sessions and pending login state"""
|
|
db = get_db(current_app)
|
|
db.execute("DELETE FROM sessions WHERE expires_at <= datetime('now')")
|
|
db.execute("DELETE FROM oidc_login_state WHERE expires_at <= datetime('now')")
|
|
db.commit()
|
|
|
|
|
|
def get_oidc_metadata() -> dict:
|
|
"""
|
|
Fetch (and cache) the provider's OpenID configuration
|
|
|
|
Raises:
|
|
OIDCError: Discovery failed or the issuer does not match
|
|
"""
|
|
issuer = current_app.config.get("OIDC_ISSUER", "").rstrip("/")
|
|
if not issuer:
|
|
raise OIDCError("OIDC_ISSUER is not configured")
|
|
|
|
cached = _METADATA_CACHE.get(issuer)
|
|
if cached and time.time() - cached[0] < _METADATA_TTL:
|
|
return cached[1]
|
|
|
|
url = f"{issuer}/.well-known/openid-configuration"
|
|
try:
|
|
response = httpx.get(url, timeout=10.0)
|
|
response.raise_for_status()
|
|
metadata = response.json()
|
|
except (httpx.HTTPError, ValueError) as e:
|
|
raise OIDCError(f"OIDC discovery failed: {e}")
|
|
|
|
if metadata.get("issuer", "").rstrip("/") != issuer:
|
|
raise OIDCError(
|
|
f"OIDC issuer mismatch: expected {issuer}, got {metadata.get('issuer')}"
|
|
)
|
|
for key in ("authorization_endpoint", "token_endpoint", "jwks_uri"):
|
|
if not metadata.get(key):
|
|
raise OIDCError(f"OIDC metadata is missing {key}")
|
|
|
|
_METADATA_CACHE[issuer] = (time.time(), metadata)
|
|
return metadata
|
|
|
|
|
|
def _get_signing_key(metadata: dict, id_token: str):
|
|
"""Resolve the key that signed an ID token from the provider's JWKS"""
|
|
jwks_uri = metadata["jwks_uri"]
|
|
client = _JWKS_CLIENTS.get(jwks_uri)
|
|
if client is None:
|
|
client = jwt.PyJWKClient(jwks_uri, timeout=10)
|
|
_JWKS_CLIENTS[jwks_uri] = client
|
|
return client.get_signing_key_from_jwt(id_token).key
|
|
|
|
|
|
def _validate_id_token(metadata: dict, id_token: str, nonce: str) -> dict:
|
|
"""
|
|
Verify the ID token signature and standard claims (OIDC Core 3.1.3.7)
|
|
|
|
Raises:
|
|
OIDCError: Token is invalid
|
|
"""
|
|
algorithms = metadata.get("id_token_signing_alg_values_supported") or ["RS256"]
|
|
algorithms = [alg for alg in algorithms if alg != "none"]
|
|
try:
|
|
key = _get_signing_key(metadata, id_token)
|
|
claims = jwt.decode(
|
|
id_token,
|
|
key,
|
|
algorithms=algorithms,
|
|
audience=current_app.config["OIDC_CLIENT_ID"],
|
|
issuer=metadata["issuer"],
|
|
options={"require": ["exp", "iat", "sub", "iss", "aud"]},
|
|
leeway=60,
|
|
)
|
|
except jwt.PyJWTError as e:
|
|
raise OIDCError(f"Invalid ID token: {e}")
|
|
|
|
if not nonce or not secrets.compare_digest(str(claims.get("nonce", "")), nonce):
|
|
raise OIDCError("ID token nonce does not match login request")
|
|
|
|
return claims
|
|
|
|
|
|
# Core authentication functions
|
|
def initiate_login(next_url: Optional[str] = None) -> str:
|
|
"""
|
|
Start the OIDC authorization code flow
|
|
|
|
Args:
|
|
next_url: Where to send the admin after login (same site only)
|
|
|
|
Returns:
|
|
Redirect URL to the provider's authorization endpoint
|
|
|
|
Raises:
|
|
OIDCError: Provider discovery failed
|
|
"""
|
|
metadata = get_oidc_metadata()
|
|
|
|
state = _generate_state_token()
|
|
nonce = secrets.token_urlsafe(32)
|
|
code_verifier = secrets.token_urlsafe(64)
|
|
|
|
db = get_db(current_app)
|
|
db.execute(
|
|
"""
|
|
INSERT INTO oidc_login_state (state, nonce, code_verifier, next_url, expires_at)
|
|
VALUES (?, ?, ?, ?, ?)
|
|
""",
|
|
(
|
|
state,
|
|
nonce,
|
|
code_verifier,
|
|
_safe_next_url(next_url),
|
|
datetime.utcnow() + timedelta(minutes=LOGIN_STATE_MINUTES),
|
|
),
|
|
)
|
|
db.commit()
|
|
|
|
params = {
|
|
"response_type": "code",
|
|
"client_id": current_app.config["OIDC_CLIENT_ID"],
|
|
"redirect_uri": _redirect_uri(),
|
|
"scope": "openid",
|
|
"state": state,
|
|
"nonce": nonce,
|
|
"code_challenge": _pkce_challenge(code_verifier),
|
|
"code_challenge_method": "S256",
|
|
}
|
|
|
|
current_app.logger.info("Auth: OIDC login initiated")
|
|
return f"{metadata['authorization_endpoint']}?{urlencode(params)}"
|
|
|
|
|
|
def _consume_login_state(state: str) -> Optional[dict]:
|
|
"""Fetch and delete a pending login (single use)"""
|
|
db = get_db(current_app)
|
|
row = db.execute(
|
|
"""
|
|
SELECT nonce, code_verifier, next_url FROM oidc_login_state
|
|
WHERE state = ? AND expires_at > datetime('now')
|
|
""",
|
|
(state,),
|
|
).fetchone()
|
|
db.execute("DELETE FROM oidc_login_state WHERE state = ?", (state,))
|
|
db.commit()
|
|
return dict(row) if row else None
|
|
|
|
|
|
def handle_callback(
|
|
code: str, state: str, iss: Optional[str] = None
|
|
) -> Tuple[str, Optional[str]]:
|
|
"""
|
|
Finish the OIDC flow: exchange the code, verify the ID token, check
|
|
the subject is the configured admin, and create a session.
|
|
|
|
Args:
|
|
code: Authorization code from the provider
|
|
state: CSRF state token
|
|
iss: Issuer from the redirect (RFC 9207), checked when present
|
|
|
|
Returns:
|
|
(session_token, next_url)
|
|
|
|
Raises:
|
|
InvalidStateError: State token validation failed
|
|
UnauthorizedError: Subject is not the configured admin
|
|
OIDCError: Provider or token error
|
|
"""
|
|
pending = _consume_login_state(state)
|
|
if not pending:
|
|
current_app.logger.warning("Auth: Invalid or expired OIDC state")
|
|
raise InvalidStateError("Invalid or expired state token")
|
|
|
|
metadata = get_oidc_metadata()
|
|
|
|
if iss and iss.rstrip("/") != metadata["issuer"].rstrip("/"):
|
|
raise OIDCError(f"Unexpected issuer in callback: {iss}")
|
|
|
|
try:
|
|
response = httpx.post(
|
|
metadata["token_endpoint"],
|
|
data={
|
|
"grant_type": "authorization_code",
|
|
"code": code,
|
|
"redirect_uri": _redirect_uri(),
|
|
"code_verifier": pending["code_verifier"],
|
|
},
|
|
auth=(
|
|
current_app.config["OIDC_CLIENT_ID"],
|
|
current_app.config["OIDC_CLIENT_SECRET"],
|
|
),
|
|
timeout=10.0,
|
|
)
|
|
except httpx.RequestError as e:
|
|
raise OIDCError(f"Token request failed: {e}")
|
|
|
|
if response.status_code != 200:
|
|
current_app.logger.error(
|
|
f"Auth: OIDC token endpoint returned {response.status_code}: {response.text[:200]}"
|
|
)
|
|
raise OIDCError(f"Token endpoint returned {response.status_code}")
|
|
|
|
try:
|
|
id_token = response.json().get("id_token")
|
|
except ValueError:
|
|
raise OIDCError("Token endpoint returned invalid JSON")
|
|
if not id_token:
|
|
raise OIDCError("Token endpoint returned no id_token")
|
|
|
|
claims = _validate_id_token(metadata, id_token, pending["nonce"])
|
|
|
|
admin_sub = current_app.config.get("OIDC_ADMIN_SUB", "")
|
|
if not admin_sub or not secrets.compare_digest(claims["sub"], admin_sub):
|
|
current_app.logger.warning(f"Auth: Unauthorized OIDC subject {claims['sub']}")
|
|
raise UnauthorizedError("This account is not the site admin")
|
|
|
|
me = current_app.config.get("ADMIN_ME")
|
|
if not me:
|
|
raise OIDCError("ADMIN_ME not configured")
|
|
|
|
session_token = create_session(me)
|
|
|
|
# Refresh the author h-card; never block login on it
|
|
try:
|
|
from starpunk.author_discovery import get_author_profile
|
|
|
|
get_author_profile(me, refresh=True)
|
|
except Exception as e:
|
|
current_app.logger.warning(f"Author discovery failed: {e}")
|
|
|
|
return session_token, pending["next_url"]
|
|
|
|
|
|
def create_session(me: str) -> str:
|
|
"""
|
|
Create authenticated session
|
|
|
|
Args:
|
|
me: Verified user identity URL
|
|
|
|
Returns:
|
|
Session token (plaintext, to be sent as cookie)
|
|
"""
|
|
# Generate secure token
|
|
session_token = secrets.token_urlsafe(32)
|
|
token_hash = _hash_token(session_token)
|
|
|
|
current_app.logger.debug("Auth: Session token generated (hash will be stored)")
|
|
|
|
# Calculate expiry (use configured session lifetime or default to 30 days)
|
|
session_lifetime = current_app.config.get("SESSION_LIFETIME", 30)
|
|
expires_at = datetime.utcnow() + timedelta(days=session_lifetime)
|
|
|
|
current_app.logger.debug(f"Auth: Session expiry: {expires_at} ({session_lifetime} days)")
|
|
|
|
# Get request metadata
|
|
user_agent = request.headers.get("User-Agent", "")[:200]
|
|
ip_address = request.remote_addr
|
|
|
|
current_app.logger.debug(f"Auth: Request metadata - IP: {ip_address}, User-Agent: {user_agent[:50]}...")
|
|
|
|
# Store in database
|
|
db = get_db(current_app)
|
|
db.execute(
|
|
"""
|
|
INSERT INTO sessions
|
|
(session_token_hash, me, expires_at, user_agent, ip_address)
|
|
VALUES (?, ?, ?, ?, ?)
|
|
""",
|
|
(token_hash, me, expires_at, user_agent, ip_address),
|
|
)
|
|
db.commit()
|
|
|
|
# Cleanup expired sessions
|
|
_cleanup_expired_sessions()
|
|
|
|
# Log session creation
|
|
current_app.logger.info(f"Auth: Session created for {me}")
|
|
|
|
return session_token
|
|
|
|
|
|
def verify_session(token: str) -> Optional[Dict[str, Any]]:
|
|
"""
|
|
Verify session token
|
|
|
|
Args:
|
|
token: Session token from cookie
|
|
|
|
Returns:
|
|
Session info dict if valid, None otherwise
|
|
"""
|
|
if not token:
|
|
current_app.logger.debug("Auth: No session token provided")
|
|
return None
|
|
|
|
|
|
token_hash = _hash_token(token)
|
|
|
|
db = get_db(current_app)
|
|
session_data = db.execute(
|
|
"""
|
|
SELECT id, me, created_at, expires_at, last_used_at
|
|
FROM sessions
|
|
WHERE session_token_hash = ?
|
|
AND expires_at > datetime('now')
|
|
""",
|
|
(token_hash,),
|
|
).fetchone()
|
|
|
|
if not session_data:
|
|
current_app.logger.debug("Auth: Session token invalid or expired")
|
|
return None
|
|
|
|
current_app.logger.debug(f"Auth: Session verified for {session_data['me']}")
|
|
|
|
# Update last_used_at for activity tracking
|
|
db.execute(
|
|
"""
|
|
UPDATE sessions
|
|
SET last_used_at = datetime('now')
|
|
WHERE id = ?
|
|
""",
|
|
(session_data["id"],),
|
|
)
|
|
db.commit()
|
|
|
|
return {
|
|
"me": session_data["me"],
|
|
"created_at": session_data["created_at"],
|
|
"expires_at": session_data["expires_at"],
|
|
}
|
|
|
|
|
|
def destroy_session(token: str) -> None:
|
|
"""
|
|
Destroy session (logout)
|
|
|
|
Args:
|
|
token: Session token to destroy
|
|
"""
|
|
if not token:
|
|
return
|
|
|
|
token_hash = _hash_token(token)
|
|
|
|
db = get_db(current_app)
|
|
db.execute(
|
|
"""
|
|
DELETE FROM sessions
|
|
WHERE session_token_hash = ?
|
|
""",
|
|
(token_hash,),
|
|
)
|
|
db.commit()
|
|
|
|
current_app.logger.info("Session destroyed")
|
|
|
|
|
|
def require_auth(f):
|
|
"""
|
|
Decorator to require authentication for a route
|
|
|
|
Usage:
|
|
@app.route('/admin')
|
|
@require_auth
|
|
def admin_dashboard():
|
|
return render_template('admin/dashboard.html')
|
|
"""
|
|
|
|
@wraps(f)
|
|
def decorated_function(*args, **kwargs):
|
|
# Get session token from cookie
|
|
session_token = request.cookies.get("starpunk_session")
|
|
|
|
# Verify session
|
|
session_info = verify_session(session_token)
|
|
|
|
if not session_info:
|
|
# Store intended destination
|
|
session["next"] = request.url
|
|
return redirect(url_for("auth.login_form"))
|
|
|
|
# Store user info in g for use in views
|
|
g.user = session_info
|
|
g.me = session_info["me"]
|
|
|
|
return f(*args, **kwargs)
|
|
|
|
return decorated_function
|