Commit 3c11a7b4 authored by Aryan Noshirvani's avatar Aryan Noshirvani

Replace hardcoded-password docs auth with HTTP Basic + custom console

Ports the same fix already tested and running on dev to main:
- Removes the hardcoded plaintext admin/stax123 cookie-login flow and
  its fixed "valid_token_xyz" session-bypass cookie, replacing it with
  standard HTTP Basic Auth on /docs and /openapi.json, credentials
  from DOCS_USERNAME/DOCS_PASSWORD env vars (secrets.compare_digest).
- Replaces stock Swagger UI with the custom branded console (dark/neon
  theme matching the Flutter app), minus the AI Remix panel - main
  doesn't have the /remix router, so that panel would just point at a
  404. Kept the Tag & Identify panel (main's /music/upload is real)
  and the generic OpenAPI-driven endpoint explorer.

Tested locally end-to-end before this commit: full test suite 21/21
green, and manually verified on a scratch port (401 with no
credentials, 200 with correct ones, console renders without the
remix panel, /openapi.json lists main's actual routes).
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BCxXmJVvDFJVHTUi4QgNzi
parent be7e5940
Pipeline #999 passed with stages
in 3 minutes and 18 seconds
import os
import secrets
from fastapi import FastAPI, Depends, Request, Form, Response
from fastapi import Depends, FastAPI, HTTPException, status
from fastapi.responses import HTMLResponse, RedirectResponse
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.openapi.utils import get_openapi
from fastapi.security import APIKeyCookie
from fastapi.security import HTTPBasic, HTTPBasicCredentials
from fastapi.staticfiles import StaticFiles
from src.api.routers import auth, discovery, library, music, social
from src.core.config import DOCS_PASSWORD, DOCS_USERNAME
os.makedirs("/root/antigrav-stax-audio/downloads", exist_ok=True)
os.makedirs("/root/antigrav-stax-audio/temp", exist_ok=True)
cookie_sec = APIKeyCookie(name="session_token", auto_error=False)
CONSOLE_HTML_PATH = os.path.join(os.path.dirname(__file__), "static", "console.html")
docs_security = HTTPBasic()
def verify_docs_auth(credentials: HTTPBasicCredentials = Depends(docs_security)):
if not DOCS_USERNAME or not DOCS_PASSWORD:
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)
valid_password = secrets.compare_digest(credentials.password, DOCS_PASSWORD)
if not (valid_username and valid_password):
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect username or password",
headers={"WWW-Authenticate": "Basic"},
)
return credentials.username
def verify_cookie(session_token: str = Depends(cookie_sec)):
if not session_token or session_token != "valid_token_xyz":
return False
return True
app = FastAPI(docs_url=None, redoc_url=None, openapi_url=None)
......@@ -29,73 +41,20 @@ app.include_router(library.router)
app.include_router(music.router)
app.include_router(social.router)
@app.get("/", response_class=HTMLResponse, include_in_schema=False)
async def login_get(request: Request):
token = request.cookies.get("session_token")
if token == "valid_token_xyz":
return RedirectResponse(url="/docs", status_code=302)
html_content = """
<!DOCTYPE html>
<html>
<head>
<title>Stax API Login</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body { font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; display: flex; justify-content: center; align-items: center; height: 100vh; background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%); margin: 0; }
.login-box { background: white; padding: 40px; border-radius: 12px; box-shadow: 0 8px 24px rgba(0,0,0,0.1); width: 100%; max-width: 320px; text-align: center; }
h2 { margin-top: 0; color: #333; margin-bottom: 24px; font-weight: 600; }
input { width: 100%; padding: 12px; margin: 8px 0 16px 0; border: 1px solid #ddd; border-radius: 6px; box-sizing: border-box; font-size: 15px; transition: border-color 0.3s; }
input:focus { border-color: #007bff; outline: none; }
button { width: 100%; padding: 12px; background: #007bff; color: white; border: none; border-radius: 6px; cursor: pointer; font-size: 16px; font-weight: 600; transition: background 0.3s; }
button:hover { background: #0056b3; }
.error { color: #dc3545; font-size: 14px; margin-bottom: 10px; }
</style>
</head>
<body>
<div class="login-box">
<h2>Stax API Docs</h2>
<form method="post" action="/login">
<input type="text" name="username" placeholder="Username" required autocomplete="username">
<input type="password" name="password" placeholder="Password" required autocomplete="current-password">
<button type="submit">Login to Docs</button>
</form>
</div>
</body>
</html>
"""
return HTMLResponse(content=html_content)
@app.post("/login", include_in_schema=False)
async def login_post(response: Response, username: str = Form(...), password: str = Form(...)):
correct_username = secrets.compare_digest(username, "admin")
correct_password = secrets.compare_digest(password, "stax123")
if correct_username and correct_password:
res = RedirectResponse(url="/docs", status_code=302)
res.set_cookie(key="session_token", value="valid_token_xyz", httponly=True, max_age=86400)
return res
else:
return HTMLResponse("""
<div style="font-family: sans-serif; text-align: center; padding: 50px;">
<h2 style="color: red;">Invalid Credentials</h2>
<a href="/">Try Again</a>
</div>
""", status_code=401)
@app.get("/docs", include_in_schema=False)
async def get_documentation(request: Request):
token = request.cookies.get("session_token")
if token != "valid_token_xyz":
return RedirectResponse(url="/", status_code=302)
return get_swagger_ui_html(openapi_url="/openapi.json", title="Stax API Docs")
@app.get("/", include_in_schema=False)
async def root():
return RedirectResponse(url="/docs")
@app.get("/docs", include_in_schema=False, response_class=HTMLResponse)
async def get_documentation(username: str = Depends(verify_docs_auth)):
with open(CONSOLE_HTML_PATH, "r") as f:
return f.read()
@app.get("/openapi.json", include_in_schema=False)
async def openapi(request: Request):
token = request.cookies.get("session_token")
if token != "valid_token_xyz":
return RedirectResponse(url="/", status_code=302)
async def openapi(username: str = Depends(verify_docs_auth)):
if app.openapi_schema:
return app.openapi_schema
openapi_schema = get_openapi(
......@@ -104,12 +63,5 @@ async def openapi(request: Request):
description="API backend for the Stax App. Features music tagging and batch remixing.",
routes=app.routes,
)
openapi_schema["components"]["securitySchemes"] = {
"BearerAuth": {
"type": "http",
"scheme": "bearer",
"bearerFormat": "JWT"
}
}
app.openapi_schema = openapi_schema
return app.openapi_schema
This diff is collapsed.
......@@ -10,6 +10,10 @@ ACOUSTID_API_KEY = os.getenv("ACOUSTID_API_KEY", "8XaBELgH")
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY")
LALAL_API_KEY = os.getenv("LALAL_API_KEY")
# Gate for the interactive API docs (/docs, /openapi.json) - HTTP Basic Auth.
DOCS_USERNAME = os.getenv("DOCS_USERNAME")
DOCS_PASSWORD = os.getenv("DOCS_PASSWORD")
# Setup centralized logging
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s",
......
import os
os.environ.setdefault("DOCS_USERNAME", "test-docs-user")
os.environ.setdefault("DOCS_PASSWORD", "test-docs-password")
import pytest
from fastapi.testclient import TestClient
from src.api.main import app
......
from fastapi.testclient import TestClient
from src.api.main import app
from src.core.config import DOCS_PASSWORD, DOCS_USERNAME
client = TestClient(app)
def test_social_router_exists():
response = client.get("/openapi.json", cookies={"session_token": "valid_token_xyz"})
response = client.get("/openapi.json", auth=(DOCS_USERNAME, DOCS_PASSWORD))
assert response.status_code == 200
assert "/social/posts" in response.json()["paths"]
assert "/social/geo-drop" in response.json()["paths"]
......
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