🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Security: exchange the OIDC login for a JWT with a single-use code, not a URL token (AUTH-03)
Omega (QA)ba00a85e48e0
diff --git a/backend/auth_routes.py b/backend/auth_routes.pyindex 4332a7a..ee0ca22 100644--- a/backend/auth_routes.py+++ b/backend/auth_routes.py@@ -348,6 +348,62 @@ def validate_token():'message': 'Invalid token'}), 401+@auth_bp.route('/oidc-exchange', methods=['POST'])+def oidc_exchange():+ """Exchange a single-use OIDC login code for a JWT (AUTH-03).++ The SSO callback redirects with ?code= instead of putting the JWT+ in the URL. The code lives 60 seconds, is deleted on first use, and+ only its hash is stored, so a database read alone cannot redeem it.+ No rate limiting here: the code space is 256 bits and a wrong guess+ costs one indexed lookup.+ """+ data = request.get_json(silent=True) or {}+ code = data.get('code')+ if not code or not isinstance(code, str):+ return jsonify({"error": "Invalid or expired login code!"}), 400+ code_hash = hashlib.sha256(code.encode()).hexdigest()+ conn = None+ try:+ conn = db_handler.get_db_connection()+ with conn.cursor() as cur:+ # Drop stale codes so the table stays small.+ cur.execute(+ "DELETE FROM oidc_login_codes "+ "WHERE expires_at <= (NOW() AT TIME ZONE 'UTC')")+ cur.execute(+ "SELECT user_id, is_new_user FROM oidc_login_codes "+ "WHERE code_hash = %s "+ "AND expires_at > (NOW() AT TIME ZONE 'UTC')",+ (code_hash,))+ row = cur.fetchone()+ if not row:+ conn.rollback()+ return jsonify({"error": "Invalid or expired login code!"}), 400+ user_id, is_new_user = row+ # Single use: delete before minting so a concurrent replay+ # finds nothing.+ cur.execute(+ "DELETE FROM oidc_login_codes WHERE code_hash = %s",+ (code_hash,))+ token, session_jti = generate_token(user_id)+ expires_at = datetime.now(UTC) + current_app.config['JWT_EXPIRATION_DELTA']+ cur.execute(+ 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent, login_method) VALUES (%s, %s, %s, %s, %s, %s)',+ (user_id, session_jti, expires_at, request.remote_addr,+ request.headers.get('User-Agent', ''), 'oidc')+ )+ conn.commit()+ return jsonify({"token": token, "new_user": bool(is_new_user)}), 200+ except Exception as e:+ if conn:+ conn.rollback()+ current_app.logger.error(f"OIDC code exchange failed: {e}")+ return jsonify({"error": "Login failed!"}), 500+ finally:+ if conn:+ db_handler.release_db_connection(conn)+@auth_bp.route('/user', methods=['GET'])@token_requireddef get_user():diff --git a/backend/migrations/055_create_oidc_login_codes.sql b/backend/migrations/055_create_oidc_login_codes.sqlnew file mode 100644index 0000000..692cbd7--- /dev/null+++ b/backend/migrations/055_create_oidc_login_codes.sql@@ -0,0 +1,16 @@+-- Migration 055: one-time OIDC login codes (AUTH-03)+-- The SSO callback used to deliver the full 24h JWT in the redirect+-- URL (auth-redirect.html?token=...), which then persisted in browser+-- history. The callback now stores a short-lived single-use code and+-- redirects with ?code=; the frontend exchanges it for the JWT over+-- POST. Only the SHA-256 hash of the code is stored, so a database+-- read alone cannot redeem it, and each code is deleted on first use.+CREATE TABLE IF NOT EXISTS oidc_login_codes (+ code_hash VARCHAR(255) PRIMARY KEY,+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,+ is_new_user BOOLEAN NOT NULL DEFAULT FALSE,+ expires_at TIMESTAMP NOT NULL,+ created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP+);+CREATE INDEX IF NOT EXISTS idx_oidc_login_codes_user ON oidc_login_codes(user_id);+CREATE INDEX IF NOT EXISTS idx_oidc_login_codes_expires ON oidc_login_codes(expires_at);diff --git a/backend/oidc_handler.py b/backend/oidc_handler.pyindex 4aea9f9..1bddb41 100644--- a/backend/oidc_handler.py+++ b/backend/oidc_handler.py@@ -1,7 +1,9 @@# backend/oidc_handler.py+import hashlibimport os+import secretsimport uuid-from datetime import datetime, UTC # Ensure timedelta is imported if used, though not in this snippet+from datetime import datetime, UTC, timedelta # Ensure timedelta is imported if used, though not in this snippetfrom flask import Blueprint, jsonify, redirect, url_for, current_app, request, session# Import shared extensions and utilities@@ -9,12 +11,10 @@ try:# Try relative imports (when modules are in same directory)from .extensions import oauthfrom .db_handler import get_db_connection, release_db_connection- from .auth_utils import generate_tokenexcept ImportError:# Fallback to direct importsfrom extensions import oauthfrom db_handler import get_db_connection, release_db_connection- from auth_utils import generate_tokenimport requests@@ -368,31 +368,31 @@ def oidc_callback_route():)if user_id:- # Generate app-specific JWT (AUTH-01: the returned jti is- # stored as the session row so the token can be revoked)- app_session_token, session_jti = generate_token(user_id)+ # AUTH-03: never put the JWT in the redirect URL (it+ # would persist in browser history). Store a short-lived+ # single-use code and let the frontend exchange it for+ # the token over POST. Only the hash is stored, and the+ # JWT plus its session row are minted at exchange time.+ login_code = secrets.token_urlsafe(32)+ code_hash = hashlib.sha256(login_code.encode()).hexdigest()+ code_expires_at = datetime.now(UTC) + timedelta(seconds=60)+ cur.execute(+ 'INSERT INTO oidc_login_codes (code_hash, user_id, is_new_user, expires_at) VALUES (%s, %s, %s, %s)',+ (code_hash, user_id, is_new_user, code_expires_at)+ )# Update last login timestampcur.execute('UPDATE users SET last_login = %s WHERE id = %s', (datetime.now(UTC), user_id))-- # Log OIDC session in user_sessions table- ip_address = request.remote_addr- user_agent = request.headers.get('User-Agent', '')- db_session_token = session_jti- expires_at = datetime.now(UTC) + current_app.config['JWT_EXPIRATION_DELTA']-- cur.execute(- 'INSERT INTO user_sessions (user_id, session_token, expires_at, ip_address, user_agent, login_method) VALUES (%s, %s, %s, %s, %s, %s)',- (user_id, db_session_token, expires_at, ip_address, user_agent, 'oidc')- )conn.commit()frontend_url = os.environ.get('FRONTEND_URL', current_app.config.get('APP_BASE_URL', 'http://localhost:8080')).rstrip('/')- redirect_target = f"{frontend_url}/auth-redirect.html?token={app_session_token}"+ redirect_target = f"{frontend_url}/auth-redirect.html?code={login_code}"if is_new_user:redirect_target += "&new_user=true"- logger.info(f"[OIDC_HANDLER] /oidc/callback redirecting to frontend: {redirect_target}")+ # Log the destination page only: the code is single-use,+ # but it must not land in the logs either.+ logger.info("[OIDC_HANDLER] /oidc/callback redirecting to frontend auth-redirect")return redirect(redirect_target)else:logger.error("[OIDC_HANDLER] /oidc/callback User ID not established after DB ops.")diff --git a/frontend/auth-redirect.html b/frontend/auth-redirect.htmlindex cf603f4..cb9c157 100644--- a/frontend/auth-redirect.html+++ b/frontend/auth-redirect.html@@ -97,7 +97,7 @@const loginLink = document.getElementById('loginLink');const params = new URLSearchParams(window.location.search);- const token = params.get('token');+ const code = params.get('code');const oidcError = params.get('oidc_error');const newUser = params.get('new_user');@@ -142,14 +142,39 @@errorMessageEl.textContent = message;errorMessageEl.style.display = 'block';loginLink.style.display = 'inline';- } else if (token) {- localStorage.setItem('auth_token', token);-- // Fetch user info immediately after storing token to ensure it's available- // when the main app loads, preventing preference key mismatches- fetchUserInfoAndRedirect(token, newUser === 'true');+ } else if (code) {+ // AUTH-03: exchange the single-use code for the JWT over+ // POST. The token never appears in the URL, so it cannot+ // persist in browser history.+ statusMessage.textContent = 'Exchanging login code...';+ try {+ const exchange = await fetch('/api/auth/oidc-exchange', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ code: code })+ });+ if (!exchange.ok) {+ throw new Error('Login code exchange failed');+ }+ const exchangeData = await exchange.json();+ const token = exchangeData.token;+ if (!token) {+ throw new Error('No token returned');+ }+ localStorage.setItem('auth_token', token);++ // Fetch user info immediately after storing token to ensure it's available+ // when the main app loads, preventing preference key mismatches+ fetchUserInfoAndRedirect(token, newUser === 'true');+ } catch (error) {+ console.error('Error exchanging login code:', error);+ statusMessage.textContent = 'SSO Login Failed';+ errorMessageEl.textContent = 'The login code expired or was already used. Please try logging in again.';+ errorMessageEl.style.display = 'block';+ loginLink.style.display = 'inline';+ }} else {- // No token and no error, unexpected state, redirect to login+ // No code and no error, unexpected state, redirect to loginstatusMessage.textContent = 'Redirecting to login...';setTimeout(() => {window.location.href = 'login.html';diff --git a/frontend/sw.js b/frontend/sw.jsindex 156863c..7f1e55f 100644--- a/frontend/sw.js+++ b/frontend/sw.js@@ -1,4 +1,4 @@-const CACHE_NAME = 'warracker-cache-v20260719002';+const CACHE_NAME = 'warracker-cache-v20261118001';const urlsToCache = [// HTML pages'./',diff --git a/tests/test_oidc_code_exchange.py b/tests/test_oidc_code_exchange.pynew file mode 100644index 0000000..cfce002--- /dev/null+++ b/tests/test_oidc_code_exchange.py@@ -0,0 +1,153 @@+"""AUTH-03: the OIDC login delivers a single-use code, not a JWT.++The SSO callback used to redirect to auth-redirect.html?token=<full+24h JWT>, which persisted in browser history. It now stores a+short-lived single-use code (only the hash is stored) and redirects+with ?code=; the frontend exchanges the code for the JWT over POST.+"""+import hashlib+import uuid+from datetime import datetime, UTC, timedelta+from urllib.parse import parse_qs, urlparse++import pytest++from backend import oidc_handler+from backend.auth_utils import decode_token_payload++CODE = "test-login-code-" + uuid.uuid4().hex+++def _code_hash(code):+ return hashlib.sha256(code.encode()).hexdigest()+++def _insert_code(db_connection, user_id, code, expires_in=300, is_new_user=False):+ with db_connection, db_connection.cursor() as cur:+ cur.execute(+ "INSERT INTO oidc_login_codes (code_hash, user_id, is_new_user, expires_at) "+ "VALUES (%s, %s, %s, %s)",+ (_code_hash(code), user_id,+ is_new_user, datetime.now(UTC) + timedelta(seconds=expires_in)),+ )+++def _user_id(db_connection, username):+ with db_connection.cursor() as cur:+ cur.execute("SELECT id FROM users WHERE username = %s", (username,))+ return cur.fetchone()[0]+++def _exchange(client, code):+ return client.post("/api/auth/oidc-exchange", json={"code": code})+++def test_exchange_mints_token_and_session(client, app, user_factory, db_connection):+ user = user_factory()+ uid = _user_id(db_connection, user["username"])+ code = "mint-" + uuid.uuid4().hex+ _insert_code(db_connection, uid, code)+ r = _exchange(client, code)+ assert r.status_code == 200, r.get_data(as_text=True)+ body = r.get_json()+ assert body["new_user"] is False+ token = body["token"]+ assert token++ # The token is a real JWT bound to a live session row (AUTH-01).+ with app.app_context():+ payload = decode_token_payload(token)+ assert payload["sub"] == str(uid)+ with db_connection.cursor() as cur:+ cur.execute(+ "SELECT COUNT(*) FROM user_sessions "+ "WHERE user_id = %s AND session_token = %s",+ (uid, payload["jti"]))+ assert cur.fetchone()[0] == 1+ cur.execute(+ "SELECT COUNT(*) FROM oidc_login_codes WHERE code_hash = %s",+ (_code_hash(code),))+ assert cur.fetchone()[0] == 0++ # And it validates through the normal endpoint.+ r = client.get("/api/auth/validate-token",+ headers={"Authorization": f"Bearer {token}"})+ assert r.status_code == 200+ assert r.get_json()["valid"] is True+++def test_exchange_is_single_use(client, user_factory, db_connection):+ user = user_factory()+ uid = _user_id(db_connection, user["username"])+ code = "once-" + uuid.uuid4().hex+ _insert_code(db_connection, uid, code)+ assert _exchange(client, code).status_code == 200+ r = _exchange(client, code)+ assert r.status_code == 400+ assert "Invalid or expired" in r.get_json()["error"]+++def test_exchange_rejects_unknown_and_expired_codes(+ client, user_factory, db_connection):+ user = user_factory()+ uid = _user_id(db_connection, user["username"])+ r = _exchange(client, "never-issued-" + uuid.uuid4().hex)+ assert r.status_code == 400+ assert "Invalid or expired" in r.get_json()["error"]++ expired = "expired-" + uuid.uuid4().hex+ _insert_code(db_connection, uid, expired, expires_in=-60)+ r = _exchange(client, expired)+ assert r.status_code == 400+ assert "Invalid or expired" in r.get_json()["error"]++ r = client.post("/api/auth/oidc-exchange", json={})+ assert r.status_code == 400+++# --- The callback redirects with a code, never a token ---++class _FakeOIDCClient:+ def __init__(self, sub, email):+ self._sub = sub+ self._email = email++ def authorize_access_token(self):+ return {"userinfo": {+ "sub": self._sub, "iss": "https://idp.example.com",+ "email": self._email, "given_name": "Oidc", "family_name": "Code",+ }}++ def userinfo(self, token=None):+ return {"sub": self._sub, "email": self._email}+++def test_callback_redirects_with_code_not_token(+ client, app, monkeypatch, db_connection):+ sub = "sub-" + uuid.uuid4().hex+ email = f"oidc-code-{uuid.uuid4().hex[:8]}@example.com"+ monkeypatch.setattr(+ oidc_handler.oauth, "create_client",+ lambda name: _FakeOIDCClient(sub, email))+ app.config["OIDC_ENABLED"] = True+ app.config["OIDC_PROVIDER_NAME"] = "testidp"+ try:+ r = client.get("/api/oidc/callback")+ finally:+ app.config["OIDC_ENABLED"] = False+ app.config.pop("OIDC_PROVIDER_NAME", None)+ assert r.status_code == 302, r.get_data(as_text=True)+ location = r.headers["Location"]+ query = parse_qs(urlparse(location).query)+ assert "token" not in query+ assert "code" in query+ assert query["new_user"] == ["true"]++ # The code redeems through the exchange endpoint.+ code = query["code"][0]+ r = _exchange(client, code)+ assert r.status_code == 200, r.get_data(as_text=True)+ assert r.get_json()["new_user"] is True+ with db_connection.cursor() as cur:+ cur.execute("SELECT COUNT(*) FROM users WHERE oidc_sub = %s", (sub,))+ assert cur.fetchone()[0] == 1