Skip to content

Speakr is a personal, self-hosted web application designed for transcribing audio recordings

Python

Return JSON 401 (not a 302 login redirect) for unauthenticated /api/ requests and any request presenting an API token, so clients stop mistaking the login page for success (fixes #333)

Murtaza Nasir8992132484ad
diff --git a/src/app.py b/src/app.py
index f7f9d886..fc79cd4c 100644
--- a/src/app.py
+++ b/src/app.py
@@ -606,6 +606,41 @@ def load_user_from_request(request):
return load_user_from_token()
+@login_manager.unauthorized_handler
+def handle_unauthorized():
+ """API requests get a JSON 401; browser page loads keep the login redirect.
+
+ Flask-Login's default is a 302 to /login for everything. Nearly every
+ HTTP client follows redirects and treats the resulting 200 text/html
+ login page as success, so integrations with a missing/invalid/expired
+ token "pass" their connection checks and fail later with confusing
+ JSON parse errors — or worse, report an upload as successful after the
+ redirect silently dropped the multipart body (issue #333).
+
+ A request is API-shaped when it targets an /api/ path or presented an
+ API token in any of the forms token_auth accepts; a token client
+ deserves a 401 whichever path it hits.
+ """
+ presented_token = bool(
+ request.headers.get('Authorization', '').startswith('Bearer ')
+ or request.headers.get('X-API-Token')
+ or request.headers.get('API-Token')
+ or request.args.get('token')
+ )
+ if request.path.startswith('/api/') or presented_token:
+ response = jsonify({'error': 'Authentication required: missing, invalid, expired, or revoked API token or session'})
+ response.status_code = 401
+ response.headers['WWW-Authenticate'] = 'Bearer'
+ return response
+
+ # Browser page load: replicate Flask-Login's default behavior
+ # (flash the login message, redirect to the login view with ?next=).
+ from flask_login.utils import login_url as _login_url
+ if login_manager.login_message:
+ flash(login_manager.login_message, category=login_manager.login_message_category)
+ return redirect(_login_url(url_for(login_manager.login_view), request.url))
+
+
# --- Embedding and Chunking Utilities ---
from src.api.auth import auth_bp, init_auth_extensions
diff --git a/tests/test_api_unauthorized_json.py b/tests/test_api_unauthorized_json.py
new file mode 100644
index 00000000..3e739c7e
--- /dev/null
+++ b/tests/test_api_unauthorized_json.py
@@ -0,0 +1,69 @@
+"""Unauthenticated API requests must get a JSON 401, not a 302 to /login.
+
+Regression tests for issue #333: Flask-Login's default unauthorized
+behavior redirects everything to the login page. HTTP clients follow the
+redirect, receive the login page as 200 text/html, and conclude the call
+succeeded — connection checks pass with garbage tokens, and a POST upload
+can silently turn into a GET /login with the body dropped.
+
+The handler in src/app.py returns a JSON 401 for /api/ paths and for any
+request that presented an API token (whatever the path), while keeping the
+login redirect for plain browser page loads.
+"""
+
+import os
+import sys
+
+sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+
+from src.app import app
+
+
+def _client():
+ return app.test_client()
+
+
+def test_api_v1_with_invalid_bearer_token_gets_json_401():
+ r = _client().get(
+ "/api/v1/tags",
+ headers={"Authorization": "Bearer definitely-not-a-real-token"},
+ )
+ assert r.status_code == 401
+ assert r.is_json
+ assert "error" in r.get_json()
+ assert r.headers.get("WWW-Authenticate") == "Bearer"
+
+
+def test_api_v1_with_no_credentials_gets_json_401():
+ r = _client().get("/api/v1/tags")
+ assert r.status_code == 401
+ assert r.is_json
+ assert "error" in r.get_json()
+
+
+def test_spa_api_path_unauthenticated_gets_json_401():
+ """Session-backed /api/ endpoints also 401 as JSON: the SPA's fetch
+ calls previously followed the redirect and choked on login-page HTML."""
+ r = _client().get("/api/tags")
+ assert r.status_code == 401
+ assert r.is_json
+
+
+def test_non_api_path_with_token_gets_json_401():
+ """A token client hitting a non-/api endpoint (e.g. /speakers) is still
+ an API caller — redirecting it to the login page would produce the same
+ false-success behavior from the issue. (Unsafe methods with an invalid
+ token are rejected even earlier, by the CSRF gate, with a 400 — also a
+ real error status, so no silent-success path exists there either.)"""
+ r = _client().get(
+ "/speakers",
+ headers={"X-API-Token": "not-a-real-token"},
+ )
+ assert r.status_code == 401
+ assert r.is_json
+
+
+def test_browser_page_load_still_redirects_to_login():
+ r = _client().get("/")
+ assert r.status_code == 302
+ assert "/login" in r.headers.get("Location", "")