Add single-user GitHub OAuth, hardened for internet exposure
muse drives a download client and writes to the media library, so exposing it publicly needs more than a login form. It fails closed. Auth is on unless MUSE_AUTH=off is set explicitly, and when it is on with incomplete config the app refuses to start rather than serving open. The mode worth engineering against is not a broken login page, it is a misconfigured deploy quietly publishing an unauthenticated download client. Sessions are server-side: the cookie carries a 256-bit random token and nothing else, and only its SHA-256 is stored. There is no signed payload to get subtly wrong, a stolen database yields no usable cookies, and logout revokes for real. The allowlist is re-checked on every request so removing a user takes effect immediately rather than at session expiry. OAuth state is compared with secrets.compare_digest, so a callback the user did not initiate is rejected. MUSE_BASE_URL comes from config rather than X-Forwarded-* because those headers are attacker-controllable and this one is a redirect target. CSP is default-src 'self' with no unsafe-inline, which is why the stylesheet and script moved out of index.html into static files -- an injected <script> now cannot execute. Also frame-ancestors 'none', base-uri 'none', nosniff, DENY, no-referrer and HSTS. FastAPI's /docs, /redoc and /openapi.json are disabled so the login page does not hand out a map of every endpoint. /healthz is the only unauthenticated route and returns a bare ok, so the container healthcheck works without leaking anything. Verified: misconfigured auth refuses to boot; unauthenticated / redirects and /api/* returns 401; a forged state is rejected 400; a junk cookie is 401; a valid session for a non-allowlisted user is 401; all headers present; and the UI renders with no CSP violations in the console. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
10ccc282d4
commit
bc46fd80b3
6 files changed
+486
-187
No files matched your search
@@ -26,17 +26,20 @@ file on disk, two names — the same trick the *arrs use.
|
||||
|
||||
import asyncio
|
||||
import difflib
|
||||
import hashlib
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import sqlite3
|
||||
import uuid
|
||||
from contextlib import asynccontextmanager
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import httpx
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.responses import FileResponse
|
||||
from fastapi import FastAPI, HTTPException, Request
|
||||
from fastapi.responses import FileResponse, JSONResponse, RedirectResponse
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pydantic import BaseModel
|
||||
|
||||
@@ -102,6 +105,106 @@ DERIVATIVE = ("cover", "covers", "karaoke", "tribute", "remix", "remixed",
|
||||
"sped up", "slowed", "reverb", "8d", "nightcore")
|
||||
DERIVATIVE_RE = re.compile(r"\b(" + "|".join(DERIVATIVE) + r")\b")
|
||||
|
||||
# ─────────────────────────── auth ───────────────────────────
|
||||
#
|
||||
# Single-user GitHub OAuth, built so this can face the internet.
|
||||
#
|
||||
# FAILS CLOSED. Auth is on unless MUSE_AUTH is explicitly set to "off", and if
|
||||
# it is on with incomplete config the app refuses to start. The failure mode
|
||||
# worth engineering against is not a broken login page — it is a misconfigured
|
||||
# deploy quietly serving an unauthenticated download client to the internet.
|
||||
# You should have to *mean* it to run without auth.
|
||||
#
|
||||
# Sessions are server-side: the cookie carries a 256-bit random token and
|
||||
# nothing else, and the database stores only its SHA-256. There is no signed
|
||||
# payload to get wrong, a stolen database yields no usable cookies, and logout
|
||||
# and revocation actually revoke.
|
||||
AUTH_MODE = os.getenv("MUSE_AUTH", "github").strip().lower()
|
||||
GH_CLIENT_ID = os.getenv("MUSE_GITHUB_CLIENT_ID", "").strip()
|
||||
GH_CLIENT_SECRET = os.getenv("MUSE_GITHUB_CLIENT_SECRET", "").strip()
|
||||
ALLOWED_USERS = {u.strip().lower()
|
||||
for u in os.getenv("MUSE_ALLOWED_USERS", "").split(",") if u.strip()}
|
||||
# Absolute external URL, e.g. https://muse.aryan-singh.dev. Used to build the
|
||||
# OAuth callback. Taken from config rather than from X-Forwarded-* headers on
|
||||
# purpose: those are attacker-controllable and this is a redirect target.
|
||||
BASE_URL = os.getenv("MUSE_BASE_URL", "").rstrip("/")
|
||||
COOKIE_SECURE = os.getenv("MUSE_COOKIE_SECURE", "true").lower() != "false"
|
||||
SESSION_DAYS = int(os.getenv("MUSE_SESSION_DAYS", "7"))
|
||||
|
||||
SESSION_COOKIE = "muse_session"
|
||||
STATE_COOKIE = "muse_oauth_state"
|
||||
GH_AUTH = "https://github.com/login/oauth/authorize"
|
||||
GH_TOKEN = "https://github.com/login/oauth/access_token"
|
||||
GH_API = "https://api.github.com/user"
|
||||
|
||||
# Paths reachable without a session. Deliberately tiny: /healthz reports a bare
|
||||
# ok so the container healthcheck works without leaking configuration, and the
|
||||
# static assets must load on the login page itself.
|
||||
PUBLIC_PATHS = {"/healthz", "/auth/login", "/auth/callback", "/auth/logout"}
|
||||
|
||||
|
||||
def auth_preflight():
|
||||
if AUTH_MODE == "off":
|
||||
log.warning("=" * 62)
|
||||
log.warning("MUSE_AUTH=off — every endpoint is UNAUTHENTICATED.")
|
||||
log.warning("Never expose this to the internet in this state.")
|
||||
log.warning("=" * 62)
|
||||
return
|
||||
if AUTH_MODE != "github":
|
||||
raise RuntimeError(f"MUSE_AUTH must be 'github' or 'off', got {AUTH_MODE!r}")
|
||||
missing = [n for n, v in (
|
||||
("MUSE_GITHUB_CLIENT_ID", GH_CLIENT_ID),
|
||||
("MUSE_GITHUB_CLIENT_SECRET", GH_CLIENT_SECRET),
|
||||
("MUSE_ALLOWED_USERS", ALLOWED_USERS),
|
||||
("MUSE_BASE_URL", BASE_URL)) if not v]
|
||||
if missing:
|
||||
raise RuntimeError(
|
||||
"GitHub auth is enabled but " + ", ".join(missing) + " not set. "
|
||||
"Refusing to start: set them, or set MUSE_AUTH=off to run without "
|
||||
"authentication (LAN only).")
|
||||
if not BASE_URL.startswith("https://") and COOKIE_SECURE:
|
||||
log.warning("MUSE_BASE_URL is not https but cookies are Secure — the "
|
||||
"browser will refuse to send them. Set MUSE_COOKIE_SECURE=false "
|
||||
"only if you are testing over plain http on a LAN.")
|
||||
|
||||
|
||||
def _hash(tok: str) -> str:
|
||||
return hashlib.sha256(tok.encode()).hexdigest()
|
||||
|
||||
|
||||
def new_session(username: str) -> str:
|
||||
token = secrets.token_urlsafe(32)
|
||||
exp = datetime.now(timezone.utc) + timedelta(days=SESSION_DAYS)
|
||||
with db() as c:
|
||||
c.execute("INSERT INTO sessions (token_hash,username,expires_at) VALUES (?,?,?)",
|
||||
(_hash(token), username, exp.isoformat()))
|
||||
# Opportunistic sweep; no scheduler needed for a handful of rows.
|
||||
c.execute("DELETE FROM sessions WHERE expires_at < ?",
|
||||
(datetime.now(timezone.utc).isoformat(),))
|
||||
return token
|
||||
|
||||
|
||||
def session_user(request: Request) -> str | None:
|
||||
tok = request.cookies.get(SESSION_COOKIE)
|
||||
if not tok:
|
||||
return None
|
||||
with db() as c:
|
||||
row = c.execute(
|
||||
"SELECT username, expires_at FROM sessions WHERE token_hash=?",
|
||||
(_hash(tok),)).fetchone()
|
||||
if not row:
|
||||
return None
|
||||
try:
|
||||
if datetime.fromisoformat(row["expires_at"]) < datetime.now(timezone.utc):
|
||||
return None
|
||||
except ValueError:
|
||||
return None
|
||||
# Re-check the allowlist on every request, so removing someone from
|
||||
# MUSE_ALLOWED_USERS locks them out immediately instead of whenever their
|
||||
# session happens to expire.
|
||||
return row["username"] if row["username"].lower() in ALLOWED_USERS else None
|
||||
|
||||
|
||||
SAFE = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
|
||||
NOISE = re.compile(r"[^a-z0-9]+")
|
||||
|
||||
@@ -139,6 +242,14 @@ def init_db():
|
||||
created_at TEXT DEFAULT (datetime('now'))
|
||||
)
|
||||
""")
|
||||
c.execute("""
|
||||
CREATE TABLE IF NOT EXISTS sessions (
|
||||
token_hash TEXT PRIMARY KEY, -- sha256 of the cookie value
|
||||
username TEXT NOT NULL,
|
||||
created_at TEXT DEFAULT (datetime('now')),
|
||||
expires_at TEXT NOT NULL
|
||||
)
|
||||
""")
|
||||
|
||||
|
||||
def set_state(job_id: str, state: str, detail: str = "", **cols):
|
||||
@@ -391,6 +502,7 @@ async def import_worker():
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(_: FastAPI):
|
||||
auth_preflight() # raises and stops the container if misconfigured
|
||||
init_db()
|
||||
|
||||
# The queue lives in memory, so a restart mid-import would otherwise
|
||||
@@ -413,7 +525,129 @@ async def lifespan(_: FastAPI):
|
||||
t.cancel()
|
||||
|
||||
|
||||
app = FastAPI(title="muse", lifespan=lifespan)
|
||||
app = FastAPI(
|
||||
title="muse",
|
||||
lifespan=lifespan,
|
||||
# No interactive docs on an internet-facing app: they enumerate every
|
||||
# endpoint and schema for anyone who reaches the login page.
|
||||
docs_url=None, redoc_url=None, openapi_url=None,
|
||||
)
|
||||
|
||||
|
||||
@app.middleware("http")
|
||||
async def guard(request: Request, call_next):
|
||||
"""Require a session for everything except PUBLIC_PATHS, and stamp
|
||||
security headers on every response."""
|
||||
path = request.url.path
|
||||
if AUTH_MODE == "off" or path in PUBLIC_PATHS or path.startswith("/static/"):
|
||||
resp = await call_next(request)
|
||||
elif session_user(request):
|
||||
resp = await call_next(request)
|
||||
elif path.startswith("/api/"):
|
||||
# An API caller gets a status code, not an HTML redirect it can't use.
|
||||
resp = JSONResponse({"error": "unauthenticated"}, status_code=401)
|
||||
else:
|
||||
resp = RedirectResponse("/auth/login", status_code=302)
|
||||
|
||||
# Strict CSP is why the stylesheet and script live in separate files rather
|
||||
# than inline in index.html: with 'self' only and no 'unsafe-inline', an
|
||||
# injected <script> cannot execute. img-src allows Deezer's cover CDN over
|
||||
# https; connect-src is self only, so nothing can exfiltrate to a third
|
||||
# party from this page.
|
||||
resp.headers["Content-Security-Policy"] = (
|
||||
"default-src 'self'; img-src 'self' https: data:; "
|
||||
"style-src 'self'; script-src 'self'; connect-src 'self'; "
|
||||
"frame-ancestors 'none'; base-uri 'none'; form-action 'self'")
|
||||
resp.headers["X-Content-Type-Options"] = "nosniff"
|
||||
resp.headers["X-Frame-Options"] = "DENY"
|
||||
resp.headers["Referrer-Policy"] = "no-referrer"
|
||||
resp.headers["Permissions-Policy"] = "geolocation=(), microphone=(), camera=()"
|
||||
if COOKIE_SECURE:
|
||||
resp.headers["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"
|
||||
return resp
|
||||
|
||||
|
||||
def _set_cookie(resp, name, value, max_age):
|
||||
resp.set_cookie(name, value, max_age=max_age, httponly=True,
|
||||
secure=COOKIE_SECURE, samesite="lax", path="/")
|
||||
|
||||
|
||||
@app.get("/healthz")
|
||||
async def healthz():
|
||||
"""Unauthenticated on purpose, for the container healthcheck. Returns
|
||||
nothing but a literal ok — no versions, no config, no counts."""
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
@app.get("/auth/login")
|
||||
async def auth_login():
|
||||
if AUTH_MODE == "off":
|
||||
return RedirectResponse("/", status_code=302)
|
||||
state = secrets.token_urlsafe(24)
|
||||
url = (f"{GH_AUTH}?client_id={GH_CLIENT_ID}"
|
||||
f"&redirect_uri={BASE_URL}/auth/callback"
|
||||
f"&scope=read:user&state={state}&allow_signup=false")
|
||||
resp = RedirectResponse(url, status_code=302)
|
||||
# CSRF defence: the state we generated is echoed back by GitHub and must
|
||||
# match this cookie, so a callback the user did not initiate is rejected.
|
||||
_set_cookie(resp, STATE_COOKIE, state, 600)
|
||||
return resp
|
||||
|
||||
|
||||
@app.get("/auth/callback")
|
||||
async def auth_callback(request: Request, code: str = "", state: str = ""):
|
||||
if AUTH_MODE == "off":
|
||||
return RedirectResponse("/", status_code=302)
|
||||
|
||||
expected = request.cookies.get(STATE_COOKIE) or ""
|
||||
if not code or not state or not secrets.compare_digest(state, expected):
|
||||
log.warning("auth: rejected callback with bad or missing state")
|
||||
return JSONResponse({"error": "invalid state"}, status_code=400)
|
||||
|
||||
async with httpx.AsyncClient(timeout=20) as c:
|
||||
t = await c.post(GH_TOKEN, headers={"Accept": "application/json"},
|
||||
data={"client_id": GH_CLIENT_ID,
|
||||
"client_secret": GH_CLIENT_SECRET,
|
||||
"code": code,
|
||||
"redirect_uri": f"{BASE_URL}/auth/callback"})
|
||||
token = (t.json() or {}).get("access_token") if t.status_code == 200 else None
|
||||
if not token:
|
||||
log.warning("auth: token exchange failed (%s)", t.status_code)
|
||||
return JSONResponse({"error": "token exchange failed"}, status_code=401)
|
||||
|
||||
u = await c.get(GH_API, headers={"Authorization": f"Bearer {token}",
|
||||
"Accept": "application/vnd.github+json"})
|
||||
if u.status_code != 200:
|
||||
return JSONResponse({"error": "github user lookup failed"}, status_code=401)
|
||||
login = (u.json() or {}).get("login") or ""
|
||||
|
||||
if login.lower() not in ALLOWED_USERS:
|
||||
# Log the attempt: on an internet-facing box this is the signal that
|
||||
# someone found the login page.
|
||||
log.warning("auth: DENIED github user %r (not in MUSE_ALLOWED_USERS)", login)
|
||||
return JSONResponse({"error": "not authorised"}, status_code=403)
|
||||
|
||||
log.info("auth: signed in %s", login)
|
||||
resp = RedirectResponse("/", status_code=302)
|
||||
_set_cookie(resp, SESSION_COOKIE, new_session(login), SESSION_DAYS * 86400)
|
||||
resp.delete_cookie(STATE_COOKIE, path="/")
|
||||
return resp
|
||||
|
||||
|
||||
@app.get("/auth/logout")
|
||||
async def auth_logout(request: Request):
|
||||
tok = request.cookies.get(SESSION_COOKIE)
|
||||
if tok:
|
||||
with db() as c:
|
||||
c.execute("DELETE FROM sessions WHERE token_hash=?", (_hash(tok),))
|
||||
resp = RedirectResponse("/auth/login", status_code=302)
|
||||
resp.delete_cookie(SESSION_COOKIE, path="/")
|
||||
return resp
|
||||
|
||||
|
||||
@app.get("/api/me")
|
||||
async def me(request: Request):
|
||||
return {"user": session_user(request), "auth": AUTH_MODE}
|
||||
|
||||
|
||||
class RequestBody(BaseModel):
|
||||
|
||||
Reference in new issue
Block a user