🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
OIDC: enable PKCE (S256) when the provider advertises it
Omega (QA)7b5e68e83b5b
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a4065d9..708e2c9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -4,6 +4,8 @@- **Database credential defaults removed (#221, by Nam0101):** the built-in defaults for `DB_USER`, `DB_PASSWORD`, `DB_ADMIN_USER`, and `DB_ADMIN_PASSWORD` are gone, completing the deprecation announced in 1.0.5. The app, the migration runner, and the permissions script now stop with a clear message naming any missing variable instead of falling back to known credentials. `DATABASE_URL` still works as before: a URL containing a username and password supplies the app credentials, and the two admin variables remain required because migrations use them. Both shipped Docker Compose files, the env examples, and the Unraid template set all four explicitly, so installs that follow them need no action. The Unraid template also no longer prefills a default admin password.- _Files: `backend/config.py`, `backend/db_handler.py`, `backend/fix_permissions.py`, `backend/migrations/apply_migrations.py`, `Docker/entrypoint.sh`, `env.example`, `unraid/warracker.xml`, `tests/conftest.py`, `.github/workflows/tests.yml`, `tests/test_db_credentials_required.py`_+- **PKCE (S256) for OIDC sign-in (#288, suggested by John in Discord):** the OIDC authorization code flow now uses PKCE when the identity provider supports it. At startup Warracker reads the provider discovery document, and if it advertises S256 in `code_challenge_methods_supported`, the client is registered with PKCE enabled, so the authorization code is bound to a verifier only Warracker holds. Providers that do not advertise S256 keep the existing plain flow, and if the discovery document cannot be read at startup, sign-in continues without PKCE and a warning is logged. Nothing changes in the OIDC settings screens, and existing provider configurations need no changes.+ - _Files: `backend/oidc_handler.py`, `tests/test_oidc_pkce.py`_## 1.0.6 - 2026-11-10diff --git a/backend/oidc_handler.py b/backend/oidc_handler.pyindex 25ebe98..367653f 100644--- a/backend/oidc_handler.py+++ b/backend/oidc_handler.py@@ -16,11 +16,34 @@ except ImportError:from db_handler import get_db_connection, release_db_connectionfrom auth_utils import generate_token+import requests+import logginglogger = logging.getLogger(__name__) # Or use current_app.logger inside routesoidc_bp = Blueprint('oidc', __name__) # url_prefix will be set when registering in app.py+def _provider_supports_pkce(issuer_url):+ """True when the provider discovery document advertises PKCE S256.++ PKCE is enabled per provider (#288): providers whose discovery+ document does not list S256 keep the plain authorization code flow,+ so an IdP without PKCE support is not broken. Any discovery failure+ also falls back to no PKCE, with a warning, rather than blocking+ sign-in entirely.+ """+ metadata_url = f"{issuer_url.rstrip('/')}/.well-known/openid-configuration"+ try:+ response = requests.get(metadata_url, timeout=5)+ response.raise_for_status()+ methods = response.json().get('code_challenge_methods_supported') or []+ except (requests.RequestException, ValueError, AttributeError) as e:+ logger.warning(+ f"[FACTORY OIDC_INIT] Could not read OIDC discovery document at "+ f"{metadata_url} ({e}); continuing without PKCE.")+ return False+ return 'S256' in methods+def init_oidc_client(current_app_instance, db_conn_func, db_release_func):"""Function to initialize OIDC client based on settings"""from .extensions import oauth@@ -77,12 +100,21 @@ def init_oidc_client(current_app_instance, db_conn_func, db_release_func):if client_id and client_secret and issuer_url:logger.info(f"[FACTORY OIDC_INIT] Registering OIDC client '{provider_name}' with Authlib.")+ pkce_enabled = _provider_supports_pkce(issuer_url)+ current_app_instance.config['OIDC_PKCE_ENABLED'] = pkce_enabled+ client_kwargs = {'scope': scope}+ if pkce_enabled:+ client_kwargs['code_challenge_method'] = 'S256'+ logger.info(+ f"[FACTORY OIDC_INIT] PKCE (S256) for provider '{provider_name}': "+ f"{'enabled' if pkce_enabled else 'not advertised by the provider, disabled'}.")+oauth.register(name=provider_name,client_id=client_id,client_secret=client_secret,server_metadata_url=f"{issuer_url.rstrip('/')}/.well-known/openid-configuration",- client_kwargs={'scope': scope},+ client_kwargs=client_kwargs,override=True)logger.info(f"[FACTORY OIDC_INIT] OIDC client '{provider_name}' registered successfully.")diff --git a/tests/test_oidc_pkce.py b/tests/test_oidc_pkce.pynew file mode 100644index 0000000..cc1e9e3--- /dev/null+++ b/tests/test_oidc_pkce.py@@ -0,0 +1,182 @@+"""PKCE S256 support for the OIDC client (#288).++PKCE is enabled per provider: when the provider discovery document+advertises S256 in code_challenge_methods_supported, the Authlib client+is registered with code_challenge_method S256. Providers that do not+advertise S256, and providers whose discovery document cannot be read,+keep the plain authorization code flow.+"""+from urllib.parse import parse_qs, urlparse++import pytest+import requests+from flask import Flask++from backend import oidc_handler+from backend.extensions import oauth as shared_oauth++ISSUER = "https://idp.example.com/realms/main"+METADATA_URL = ISSUER + "/.well-known/openid-configuration"+++class FakeResponse:+ def __init__(self, payload, error=None):+ self._payload = payload+ self._error = error++ def raise_for_status(self):+ if self._error is not None:+ raise self._error++ def json(self):+ return self._payload+++def _stub_discovery(monkeypatch, payload, error=None):+ calls = []++ def fake_get(url, timeout=None):+ calls.append((url, timeout))+ return FakeResponse(payload, error=error)++ monkeypatch.setattr(oidc_handler.requests, "get", fake_get)+ return calls+++def test_pkce_supported_when_s256_advertised(monkeypatch):+ calls = _stub_discovery(+ monkeypatch, {"code_challenge_methods_supported": ["plain", "S256"]})+ assert oidc_handler._provider_supports_pkce(ISSUER + "/") is True+ assert calls == [(METADATA_URL, 5)]+++def test_pkce_not_supported_with_plain_only(monkeypatch):+ _stub_discovery(monkeypatch, {"code_challenge_methods_supported": ["plain"]})+ assert oidc_handler._provider_supports_pkce(ISSUER) is False+++def test_pkce_not_supported_when_methods_missing(monkeypatch):+ _stub_discovery(monkeypatch, {"issuer": ISSUER})+ assert oidc_handler._provider_supports_pkce(ISSUER) is False+++def test_pkce_falls_back_when_discovery_unreachable(monkeypatch):+ def fake_get(url, timeout=None):+ raise requests.ConnectionError("no route to host")++ monkeypatch.setattr(oidc_handler.requests, "get", fake_get)+ assert oidc_handler._provider_supports_pkce(ISSUER) is False+++def test_pkce_falls_back_on_http_error(monkeypatch):+ _stub_discovery(+ monkeypatch, {}, error=requests.HTTPError("404 Client Error"))+ assert oidc_handler._provider_supports_pkce(ISSUER) is False+++class FakeCursor:+ def __init__(self, rows):+ self._rows = rows++ def __enter__(self):+ return self++ def __exit__(self, *exc):+ return False++ def execute(self, query):+ self.query = query++ def fetchall(self):+ return self._rows+++class FakeConnection:+ def __init__(self, rows):+ self._rows = rows++ def cursor(self):+ return FakeCursor(self._rows)+++OIDC_ROWS = [+ ("oidc_enabled", "true"),+ ("oidc_provider_name", "testidp"),+ ("oidc_client_id", "warracker-client"),+ ("oidc_client_secret", "test-secret"),+ ("oidc_issuer_url", ISSUER),+ ("oidc_scope", "openid email profile"),+]++OIDC_ENV_VARS = (+ "OIDC_ENABLED", "OIDC_PROVIDER_NAME", "OIDC_CLIENT_ID",+ "OIDC_CLIENT_SECRET", "OIDC_CLIENT_SECRET_FILE", "OIDC_ISSUER_URL",+ "OIDC_SCOPE",+)+++def _run_init(monkeypatch, payload):+ for var in OIDC_ENV_VARS:+ monkeypatch.delenv(var, raising=False)+ _stub_discovery(monkeypatch, payload)++ registrations = []+ monkeypatch.setattr(+ shared_oauth, "register",+ lambda **kwargs: registrations.append(kwargs))++ app = Flask(__name__)+ oidc_handler.init_oidc_client(+ app, lambda: FakeConnection(OIDC_ROWS), lambda conn: None)+ assert len(registrations) == 1+ return app, registrations[0]+++def test_init_registers_s256_when_provider_advertises_it(monkeypatch):+ app, registration = _run_init(+ monkeypatch, {"code_challenge_methods_supported": ["S256"]})+ assert app.config["OIDC_ENABLED"] is True+ assert app.config["OIDC_PKCE_ENABLED"] is True+ assert registration["name"] == "testidp"+ assert registration["server_metadata_url"] == METADATA_URL+ assert registration["client_kwargs"] == {+ "scope": "openid email profile",+ "code_challenge_method": "S256",+ }+++def test_init_registers_without_pkce_when_provider_lacks_s256(monkeypatch):+ app, registration = _run_init(+ monkeypatch, {"code_challenge_methods_supported": ["plain"]})+ assert app.config["OIDC_ENABLED"] is True+ assert app.config["OIDC_PKCE_ENABLED"] is False+ assert registration["client_kwargs"] == {"scope": "openid email profile"}+++def test_authlib_builds_s256_challenge_for_registered_client():+ from authlib.integrations.flask_client import OAuth+ from authlib.oauth2.rfc7636 import create_s256_code_challenge++ app = Flask("pkce-authlib-test")+ app.secret_key = "pkce-test-secret"+ oauth = OAuth()+ oauth.init_app(app)+ oauth.register(+ name="pkceidp",+ client_id="warracker-client",+ client_secret="test-secret",+ authorize_url="https://idp.example.com/authorize",+ access_token_url="https://idp.example.com/token",+ client_kwargs={+ "scope": "openid email profile",+ "code_challenge_method": "S256",+ },+ )+ with app.test_request_context("/"):+ client = oauth.create_client("pkceidp")+ result = client.create_authorization_url(+ "https://warracker.example.com/api/oidc/callback")+ query = parse_qs(urlparse(result["url"]).query)+ assert query["code_challenge_method"] == ["S256"]+ assert query["code_challenge"] == [+ create_s256_code_challenge(result["code_verifier"])]