Commit 375a447d authored by Aryan Noshirvani's avatar Aryan Noshirvani

Replace HTTP Basic's native popup with a real branded login page

HTTP Basic Auth's credential prompt is a browser-native dialog - there
is no HTML/CSS control over it at all, so "make the login screen
better" had nowhere to go under the previous setup. Switched to a
proper login page (matching the console's dark/neon theme) backed by
a random per-session cookie:

- GET/POST /login: styled form, wrong credentials redirect back with
  an inline error instead of a blank 401.
- Session tokens are secrets.token_urlsafe(32), tracked in an
  in-memory dict with a 24h expiry - not the old hardcoded
  "valid_token_xyz" bypass value this app used to ship with.
- GET /logout clears the session and cookie.
- HTTP Basic is kept as a fallback authentication path (checked
  alongside the session cookie) specifically so curl -u still works
  for scripted/API access - only interactive browser use needed the
  new login page, and this repo's own test suite and my own manual
  testing throughout this session both rely on curl -u.

Added tests/test_docs_auth.py covering the full flow: redirect when
unauthenticated, login page rendering, wrong-credential error
redirect, correct-credential session + docs/openapi access, the Basic
fallback, and logout. Also manually verified live against the running
dev instance end-to-end with curl (cookie jar) before committing.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCxXmJVvDFJVHTUi4QgNzi
parent 383b5162
Pipeline #1002 passed with stage
in 11 minutes and 21 seconds
import base64
import os import os
import secrets import secrets
from fastapi import Depends, FastAPI, HTTPException, status from datetime import datetime, timedelta, timezone
from fastapi import Depends, FastAPI, Form, HTTPException, Request, status
from fastapi.responses import HTMLResponse, RedirectResponse from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.openapi.utils import get_openapi from fastapi.openapi.utils import get_openapi
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.staticfiles import StaticFiles from fastapi.staticfiles import StaticFiles
from src.api.routers import auth, discovery, library, music, remix, social from src.api.routers import auth, discovery, library, music, remix, social
...@@ -13,22 +15,61 @@ os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True) ...@@ -13,22 +15,61 @@ os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True)
os.makedirs("/root/antigrav-stax-audio/temp", exist_ok=True) os.makedirs("/root/antigrav-stax-audio/temp", exist_ok=True)
CONSOLE_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "console.html") CONSOLE_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "console.html")
LOGIN_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "login.html")
# --- Docs auth: a real branded login page + session cookie, with HTTP Basic kept as a
# fallback for scripted/curl access (no browser to show a login page to). Sessions are
# in-memory only - lost on restart, which is fine for an admin-facing docs gate. ---
SESSION_COOKIE_NAME = "stax_docs_session"
SESSION_DURATION = timedelta(hours=24)
_active_sessions: dict[str, datetime] = {}
def _create_session() -> str:
token = secrets.token_urlsafe(32)
_active_sessions[token] = datetime.now(timezone.utc) + SESSION_DURATION
return token
def _check_session_cookie(request: Request) -> bool:
token = request.cookies.get(SESSION_COOKIE_NAME)
if not token:
return False
expiry = _active_sessions.get(token)
if not expiry or expiry < datetime.now(timezone.utc):
_active_sessions.pop(token, None)
return False
return True
def _check_basic_auth(request: Request) -> bool:
auth_header = request.headers.get("authorization", "")
if not auth_header.lower().startswith("basic "):
return False
try:
decoded = base64.b64decode(auth_header[6:]).decode()
username, _, password = decoded.partition(":")
except Exception:
return False
if not DOCS_USERNAME or not DOCS_PASSWORD:
return False
return secrets.compare_digest(username, DOCS_USERNAME) and secrets.compare_digest(password, DOCS_PASSWORD)
docs_security = HTTPBasic()
def _is_authenticated(request: Request) -> bool:
return _check_session_cookie(request) or _check_basic_auth(request)
def verify_docs_auth(credentials: HTTPBasicCredentials = Depends(docs_security)):
def require_docs_auth(request: Request):
if not DOCS_USERNAME or not DOCS_PASSWORD: if not DOCS_USERNAME or not DOCS_PASSWORD:
raise HTTPException(status_code=500, detail="DOCS_USERNAME/DOCS_PASSWORD are not configured on this server.") raise HTTPException(status_code=500, detail="DOCS_USERNAME/DOCS_PASSWORD are not configured on this server.")
valid_username = secrets.compare_digest(credentials.username, DOCS_USERNAME) if not _is_authenticated(request):
valid_password = secrets.compare_digest(credentials.password, DOCS_PASSWORD)
if not (valid_username and valid_password):
raise HTTPException( raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED, status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password", detail="Not authenticated",
headers={"WWW-Authenticate": "Basic"}, headers={"WWW-Authenticate": "Basic"},
) )
return credentials.username
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None) app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
...@@ -48,14 +89,47 @@ async def root(): ...@@ -48,14 +89,47 @@ async def root():
return RedirectResponse(url="/docs") return RedirectResponse(url="/docs")
@app.get("/login", include_in_schema=False, response_class=HTMLResponse)
async def login_page():
with open(LOGIN_HTML_PATH, "r") as f:
return f.read()
@app.post("/login", include_in_schema=False)
async def login_submit(username: str = Form(...), password: str = Form(...)):
if not DOCS_USERNAME or not DOCS_PASSWORD:
raise HTTPException(status_code=500, detail="DOCS_USERNAME/DOCS_PASSWORD are not configured on this server.")
if secrets.compare_digest(username, DOCS_USERNAME) and secrets.compare_digest(password, DOCS_PASSWORD):
token = _create_session()
response = RedirectResponse(url="/docs", status_code=status.HTTP_303_SEE_OTHER)
response.set_cookie(
SESSION_COOKIE_NAME, token, httponly=True, samesite="lax",
max_age=int(SESSION_DURATION.total_seconds()),
)
return response
return RedirectResponse(url="/login?error=1", status_code=status.HTTP_303_SEE_OTHER)
@app.get("/logout", include_in_schema=False)
async def logout(request: Request):
token = request.cookies.get(SESSION_COOKIE_NAME)
if token:
_active_sessions.pop(token, None)
response = RedirectResponse(url="/login")
response.delete_cookie(SESSION_COOKIE_NAME)
return response
@app.get("/docs", include_in_schema=False, response_class=HTMLResponse) @app.get("/docs", include_in_schema=False, response_class=HTMLResponse)
async def get_documentation(username: str = Depends(verify_docs_auth)): async def get_documentation(request: Request):
if not _is_authenticated(request):
return RedirectResponse(url="/login")
with open(CONSOLE_HTML_PATH, "r") as f: with open(CONSOLE_HTML_PATH, "r") as f:
return f.read() return f.read()
@app.get("/openapi.json", include_in_schema=False) @app.get("/openapi.json", include_in_schema=False)
async def openapi(username: str = Depends(verify_docs_auth)): async def openapi(request: Request, _auth=Depends(require_docs_auth)):
if app.openapi_schema: if app.openapi_schema:
return app.openapi_schema return app.openapi_schema
openapi_schema = get_openapi( openapi_schema = get_openapi(
......
...@@ -254,6 +254,7 @@ ...@@ -254,6 +254,7 @@
<header> <header>
<h1>🎧 Stax<span> API</span> Console</h1> <h1>🎧 Stax<span> API</span> Console</h1>
<span class="badge" id="instance-badge">…</span> <span class="badge" id="instance-badge">…</span>
<a href="/logout" style="margin-left:auto; color:var(--text-dim); font-size:12.5px; text-decoration:none;">Log out</a>
</header> </header>
<main> <main>
......
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Stax API Console - Login</title>
<style>
:root {
--bg: #0D0F12;
--panel: #14171C;
--panel-2: #1B1F26;
--border: #262B33;
--text: #E7ECF2;
--text-dim: #8A93A3;
--accent: #00E5FF;
--accent-dim: #00B8CC;
--bad: #FF5C7A;
}
* { box-sizing: border-box; }
html, body {
height: 100%;
margin: 0;
}
body {
background: var(--bg);
color: var(--text);
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
display: flex;
align-items: center;
justify-content: center;
}
.card {
width: 100%;
max-width: 340px;
background: var(--panel);
border: 1px solid var(--border);
border-radius: 14px;
padding: 32px;
margin: 20px;
}
.card h1 {
font-size: 19px;
margin: 0 0 4px 0;
text-align: center;
}
.card h1 span { color: var(--accent); }
.card p.sub {
text-align: center;
color: var(--text-dim);
font-size: 12.5px;
margin: 0 0 24px 0;
}
label {
display: block;
font-size: 11.5px;
color: var(--text-dim);
text-transform: uppercase;
letter-spacing: 0.04em;
margin-bottom: 6px;
}
input {
width: 100%;
background: var(--panel-2);
border: 1px solid var(--border);
border-radius: 8px;
color: var(--text);
padding: 11px 12px;
font-size: 14px;
margin-bottom: 16px;
}
input:focus { outline: none; border-color: var(--accent); }
button {
width: 100%;
background: var(--accent);
color: #06141A;
border: none;
border-radius: 8px;
padding: 12px;
font-weight: 700;
font-size: 14px;
cursor: pointer;
margin-top: 4px;
}
button:hover { background: var(--accent-dim); }
.error {
display: none;
background: rgba(255, 92, 122, 0.1);
border: 1px solid var(--bad);
color: var(--bad);
border-radius: 8px;
padding: 10px 12px;
font-size: 12.5px;
margin-bottom: 16px;
text-align: center;
}
.error.show { display: block; }
</style>
</head>
<body>
<div class="card">
<h1>🎧 Stax<span> API</span></h1>
<p class="sub">Sign in to view the API console</p>
<div class="error" id="error-box">Incorrect username or password.</div>
<form method="post" action="/login">
<label for="username">Username</label>
<input type="text" id="username" name="username" autocomplete="username" required autofocus>
<label for="password">Password</label>
<input type="password" id="password" name="password" autocomplete="current-password" required>
<button type="submit">Sign In</button>
</form>
</div>
<script>
if (new URLSearchParams(location.search).get('error') === '1') {
document.getElementById('error-box').classList.add('show');
}
</script>
</body>
</html>
from src.core.config import DOCS_PASSWORD, DOCS_USERNAME
def test_docs_redirects_to_login_when_unauthenticated(client):
response = client.get("/docs", follow_redirects=False)
assert response.status_code in (302, 307)
assert response.headers["location"] == "/login"
def test_login_page_renders(client):
response = client.get("/login")
assert response.status_code == 200
assert "Sign in to view the API console" in response.text
def test_login_wrong_credentials_redirects_with_error(client):
response = client.post(
"/login", data={"username": "wrong", "password": "wrong"}, follow_redirects=False
)
assert response.status_code == 303
assert response.headers["location"] == "/login?error=1"
assert "stax_docs_session" not in response.cookies
def test_login_correct_credentials_sets_session_and_unlocks_docs(client):
response = client.post(
"/login",
data={"username": DOCS_USERNAME, "password": DOCS_PASSWORD},
follow_redirects=False,
)
assert response.status_code == 303
assert response.headers["location"] == "/docs"
assert "stax_docs_session" in response.cookies
docs_response = client.get("/docs")
assert docs_response.status_code == 200
assert "Stax API Console" in docs_response.text
openapi_response = client.get("/openapi.json")
assert openapi_response.status_code == 200
def test_basic_auth_fallback_still_works(client):
response = client.get("/openapi.json", auth=(DOCS_USERNAME, DOCS_PASSWORD))
assert response.status_code == 200
def test_logout_clears_session(client):
login_response = client.post(
"/login",
data={"username": DOCS_USERNAME, "password": DOCS_PASSWORD},
follow_redirects=False,
)
assert "stax_docs_session" in login_response.cookies
logout_response = client.get("/logout", follow_redirects=False)
assert logout_response.status_code in (302, 307)
docs_response = client.get("/docs", follow_redirects=False)
assert docs_response.status_code in (302, 307)
assert docs_response.headers["location"] == "/login"
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment