Files
DocsGPT/tests/test_auth.py
T
Alex a3d09e8890 fix(oidc): harden session security from PR review (CSRF, revocation, refresh)
Address the high/medium correctness findings on the OIDC/SCIM PR:

- Login CSRF / session fixation: bind `state` to a Secure/HttpOnly/SameSite=Lax
  cookie at login and require the callback to echo it, so a code+state captured
  from another browser can't silently sign a victim into the attacker's account.
- Require `exp` on session JWTs under AUTH_TYPE=oidc (require_exp), so an
  exp-less HS256 token signed with JWT_SECRET_KEY can't authenticate forever or
  outlive the denylist.
- Denylist now keys revocation on an `iat` watermark instead of a deletable
  flag: a fresh login (newer iat) self-supersedes a revocation without clearing
  it, so sessions revoked on other devices stay revoked. Drops the
  login/SCIM-reactivation denylist-clearing paths (allow_user/allow_idp_sub).
- Refresh: gate the disabled-account check on the post-grant identity (not just
  the old sub); attempt the IdP grant before consuming the refresh token and
  return a retryable 503 (restoring the token) on transient IdP errors instead
  of force-logging-out a live session.
- Gate the oidc blueprint at request time on AUTH_TYPE=oidc, so non-oidc
  deployments cleanly 404 these routes instead of 500-ing on an unset
  OIDC_ISSUER (mirrors SCIM_ENABLED).
- Surface revocation write failures: back-channel logout returns 502, and SCIM
  deactivation rolls back and returns 503, when the denylist write fails — so
  the IdP retries instead of recording a logout/deprovision that didn't revoke.
- Back-channel logout: require `jti`, run the replay check unconditionally, and
  reject stale `iat` beyond the replay-cache window.
- Make migration 0017 idempotent (IF NOT EXISTS) so re-apply can't wedge startup.
- SCIM userName matching is case-insensitive (caseExact=false) for the list
  filter and create-dedup.

Tests added/updated across test_oidc.py, test_scim.py, test_auth.py,
test_app_routes.py and the SCIM integration test.
2026-06-10 13:58:58 +01:00

219 lines
7.4 KiB
Python

from unittest.mock import Mock, patch
import pytest
@pytest.mark.unit
class TestHandleAuth:
def test_returns_local_when_no_auth_type(self):
from application.auth import handle_auth
mock_request = Mock()
with patch("application.auth.settings") as mock_settings:
mock_settings.AUTH_TYPE = "none"
result = handle_auth(mock_request)
assert result == {"sub": "local"}
def test_returns_none_when_no_jwt_header(self):
from application.auth import handle_auth
mock_request = Mock()
mock_request.headers.get.return_value = None
with patch("application.auth.settings") as mock_settings:
mock_settings.AUTH_TYPE = "simple_jwt"
result = handle_auth(mock_request)
assert result is None
def test_decodes_valid_jwt(self):
from application.auth import handle_auth
mock_request = Mock()
mock_request.headers.get.return_value = "Bearer valid_token"
with patch("application.auth.settings") as mock_settings, patch(
"application.auth.jwt"
) as mock_jwt:
mock_settings.AUTH_TYPE = "simple_jwt"
mock_settings.JWT_SECRET_KEY = "secret"
mock_jwt.decode.return_value = {"sub": "user123"}
result = handle_auth(mock_request)
assert result == {"sub": "user123"}
mock_jwt.decode.assert_called_once_with(
"valid_token",
"secret",
algorithms=["HS256"],
options={"verify_exp": False, "require_exp": False},
)
def test_returns_error_on_invalid_jwt(self):
from application.auth import handle_auth
mock_request = Mock()
mock_request.headers.get.return_value = "Bearer bad_token"
with patch("application.auth.settings") as mock_settings, patch(
"application.auth.jwt"
) as mock_jwt:
mock_settings.AUTH_TYPE = "session_jwt"
mock_settings.JWT_SECRET_KEY = "secret"
mock_jwt.decode.side_effect = Exception("Invalid token")
result = handle_auth(mock_request)
assert result["error"] == "invalid_token"
def test_strips_bearer_prefix(self):
from application.auth import handle_auth
mock_request = Mock()
mock_request.headers.get.return_value = "Bearer my_token"
with patch("application.auth.settings") as mock_settings, patch(
"application.auth.jwt"
) as mock_jwt:
mock_settings.AUTH_TYPE = "simple_jwt"
mock_settings.JWT_SECRET_KEY = "secret"
mock_jwt.decode.return_value = {"sub": "user1"}
handle_auth(mock_request)
mock_jwt.decode.assert_called_once()
assert mock_jwt.decode.call_args[0][0] == "my_token"
@pytest.mark.unit
class TestHandleAuthOidc:
"""AUTH_TYPE=oidc: same local HS256 session tokens, but exp is verified."""
def test_returns_none_when_no_jwt_header(self):
from application.auth import handle_auth
mock_request = Mock()
mock_request.headers.get.return_value = None
with patch("application.auth.settings") as mock_settings:
mock_settings.AUTH_TYPE = "oidc"
result = handle_auth(mock_request)
assert result is None
def test_decodes_valid_jwt_with_exp_verification(self):
from application.auth import handle_auth
mock_request = Mock()
mock_request.headers.get.return_value = "Bearer valid_token"
with patch("application.auth.settings") as mock_settings, patch(
"application.auth.jwt"
) as mock_jwt:
mock_settings.AUTH_TYPE = "oidc"
mock_settings.JWT_SECRET_KEY = "secret"
mock_jwt.decode.return_value = {"sub": "user123", "email": "u@example.com"}
result = handle_auth(mock_request)
assert result == {"sub": "user123", "email": "u@example.com"}
mock_jwt.decode.assert_called_once_with(
"valid_token",
"secret",
algorithms=["HS256"],
options={"verify_exp": True, "require_exp": True},
)
def test_expired_token_returns_token_expired(self):
from jose.exceptions import ExpiredSignatureError
from application.auth import handle_auth
mock_request = Mock()
mock_request.headers.get.return_value = "Bearer stale_token"
with patch("application.auth.settings") as mock_settings, patch(
"application.auth.jwt"
) as mock_jwt:
mock_settings.AUTH_TYPE = "oidc"
mock_settings.JWT_SECRET_KEY = "secret"
mock_jwt.decode.side_effect = ExpiredSignatureError("expired")
result = handle_auth(mock_request)
assert result["error"] == "token_expired"
def test_invalid_token_returns_invalid_token(self):
from application.auth import handle_auth
mock_request = Mock()
mock_request.headers.get.return_value = "Bearer bad_token"
with patch("application.auth.settings") as mock_settings, patch(
"application.auth.jwt"
) as mock_jwt:
mock_settings.AUTH_TYPE = "oidc"
mock_settings.JWT_SECRET_KEY = "secret"
mock_jwt.decode.side_effect = Exception("bad")
result = handle_auth(mock_request)
assert result["error"] == "invalid_token"
def test_token_without_exp_rejected_under_oidc(self):
# Under oidc, exp is REQUIRED: an exp-less HS256 token signed with the
# shared secret (e.g. a legacy simple_jwt/session_jwt token) must not
# authenticate, or it would be valid forever and unrevocable.
from jose import jwt as real_jwt
from application.auth import handle_auth
token = real_jwt.encode({"sub": "helper_user"}, "secret", algorithm="HS256")
mock_request = Mock()
mock_request.headers.get.return_value = f"Bearer {token}"
with patch("application.auth.settings") as mock_settings:
mock_settings.AUTH_TYPE = "oidc"
mock_settings.JWT_SECRET_KEY = "secret"
result = handle_auth(mock_request)
assert result["error"] == "invalid_token"
def test_expired_token_real_jose(self):
import time
from jose import jwt as real_jwt
from application.auth import handle_auth
token = real_jwt.encode(
{"sub": "helper_user", "exp": int(time.time()) - 3600},
"secret",
algorithm="HS256",
)
mock_request = Mock()
mock_request.headers.get.return_value = f"Bearer {token}"
with patch("application.auth.settings") as mock_settings:
mock_settings.AUTH_TYPE = "oidc"
mock_settings.JWT_SECRET_KEY = "secret"
result = handle_auth(mock_request)
assert result["error"] == "token_expired"
def test_simple_jwt_still_skips_exp_verification(self):
import time
from jose import jwt as real_jwt
from application.auth import handle_auth
token = real_jwt.encode(
{"sub": "local", "exp": int(time.time()) - 3600},
"secret",
algorithm="HS256",
)
mock_request = Mock()
mock_request.headers.get.return_value = f"Bearer {token}"
with patch("application.auth.settings") as mock_settings:
mock_settings.AUTH_TYPE = "simple_jwt"
mock_settings.JWT_SECRET_KEY = "secret"
result = handle_auth(mock_request)
assert result["sub"] == "local"