c_agri_trade_code/tests/backend/test_auth_oidc.py

293 lines
13 KiB
Python

"""Automated Tests for OIDC PKCE Authentication & Token Validation.
Fulfills TC-AUTH-001, TC-AUTH-002, FR-AUTH-001 & SRS-AUTH-001.
Standard: UP-AI v1.5 Quality Standard (≥95% backend domain coverage).
Tags: uc_001, fr_auth_001, iteration_01
"""
import time
import unittest
import sys
from pathlib import Path
code_root = Path(__file__).resolve().parents[2]
repo_root = Path(__file__).resolve().parents[3]
if str(code_root) not in sys.path:
sys.path.insert(0, str(code_root))
if str(repo_root) not in sys.path:
sys.path.insert(0, str(repo_root))
from sandbox.identity_mock import (
mock_idp,
generate_pkce_challenge,
verify_pkce,
TEST_PERSONAS,
base64url_encode
)
from backend.app.auth.oidc import auth_service
from backend.app.auth.session import session_manager
from backend.app.api.auth import auth_controller
class TestOIDCAuthentication(unittest.TestCase):
"""TC-AUTH-001 & TC-AUTH-002: OIDC & Token Validation Multi-Path Tests."""
def setUp(self):
session_manager.clear()
def test_tc_auth_001_happy_path_token_verification(self):
"""TC-AUTH-001: Valid token returns authenticated application session."""
persona = TEST_PERSONAS["buyer@alpha.com"]
token = mock_idp.mint_jwt(
subject=persona["sub"],
email=persona["email"],
name=persona["name"],
roles=persona["roles"],
tenant_id=persona["tenant_id"],
expires_in_seconds=3600
)
auth_header = f"Bearer {token}"
result = auth_controller.get_session(auth_header)
self.assertTrue(result["authenticated"])
self.assertEqual(result["status_code"], 200)
self.assertEqual(result["subject"], persona["sub"])
self.assertEqual(result["email"], persona["email"])
self.assertIn("Mandi Buyer", result["roles"])
self.assertEqual(result["tenant_id"], "tenant-alpha")
def test_tc_auth_002_expired_token_rejection(self):
"""TC-AUTH-002: Boundary check — Expired token must be rejected with 401."""
persona = TEST_PERSONAS["buyer@alpha.com"]
expired_token = mock_idp.mint_jwt(
subject=persona["sub"],
email=persona["email"],
name=persona["name"],
roles=persona["roles"],
tenant_id=persona["tenant_id"],
expires_in_seconds=-100
)
auth_header = f"Bearer {expired_token}"
result = auth_controller.get_session(auth_header)
self.assertFalse(result["authenticated"])
self.assertEqual(result["status_code"], 401)
self.assertIn("expired", result["error"].lower())
def test_tampered_signature_rejection(self):
"""Negative check — Token with modified signature is rejected with 401."""
persona = TEST_PERSONAS["buyer@alpha.com"]
valid_token = mock_idp.mint_jwt(
subject=persona["sub"],
email=persona["email"],
name=persona["name"],
roles=persona["roles"],
tenant_id=persona["tenant_id"]
)
parts = valid_token.split(".")
tampered_sig = base64url_encode(b"invalid_tampered_signature_bytes_123")
tampered_token = f"{parts[0]}.{parts[1]}.{tampered_sig}"
result = auth_controller.get_session(f"Bearer {tampered_token}")
self.assertFalse(result["authenticated"])
self.assertEqual(result["status_code"], 401)
def test_malformed_token_header_rejection(self):
"""Negative check — Missing or invalid Bearer format fails closed."""
res1 = auth_controller.get_session(None)
self.assertEqual(res1["status_code"], 401)
res2 = auth_controller.get_session("Basic dXNlcjpwYXNz")
self.assertEqual(res2["status_code"], 401)
res3 = auth_controller.get_session("just_a_random_token")
self.assertEqual(res3["status_code"], 401)
def test_pkce_challenge_verification_invariant(self):
"""FSM invariant — PKCE code verifier and challenge validation."""
verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
challenge = generate_pkce_challenge(verifier)
self.assertTrue(verify_pkce(verifier, challenge))
self.assertFalse(verify_pkce(verifier + "altered", challenge))
def test_authorization_code_one_time_use_exchange(self):
"""FSM invariant — Authorization code cannot be exchanged twice (replay protection)."""
verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"
challenge = generate_pkce_challenge(verifier)
code = mock_idp.create_authorization_code(
email="buyer@alpha.com",
code_challenge=challenge,
redirect_uri="http://localhost:3000/auth/callback",
state="test_state_123"
)
token_data = mock_idp.exchange_code_for_tokens(
code=code,
code_verifier=verifier,
redirect_uri="http://localhost:3000/auth/callback"
)
self.assertIn("access_token", token_data)
with self.assertRaises(ValueError) as ctx:
mock_idp.exchange_code_for_tokens(
code=code,
code_verifier=verifier,
redirect_uri="http://localhost:3000/auth/callback"
)
self.assertIn("already been exchanged", str(ctx.exception))
def test_unknown_email_in_create_authorization_code(self):
"""Negative check — Unknown persona throws ValueError."""
with self.assertRaises(ValueError):
mock_idp.create_authorization_code("unknown@random.com", "challenge", "uri", "state")
def test_exchange_code_invalid_code(self):
"""Negative check — Non-existent code throws ValueError."""
with self.assertRaises(ValueError):
mock_idp.exchange_code_for_tokens("fake_code", "verifier", "uri")
def test_exchange_code_mismatched_verifier(self):
"""Negative check — Mismatched PKCE verifier fails exchange."""
verifier = "correct_verifier_123456789012345678901234567890"
challenge = generate_pkce_challenge(verifier)
code = mock_idp.create_authorization_code("buyer@alpha.com", challenge, "uri", "state")
with self.assertRaises(ValueError) as ctx:
mock_idp.exchange_code_for_tokens(code, "wrong_verifier", "uri")
self.assertIn("mismatch", str(ctx.exception).lower())
def test_exchange_code_expired(self):
"""Boundary check — Expired code cannot be exchanged."""
verifier = "test_verifier_1234567890"
challenge = generate_pkce_challenge(verifier)
code = mock_idp.create_authorization_code("buyer@alpha.com", challenge, "uri", "state")
# Artificially expire code
mock_idp.auth_codes[code]["expires_at"] = time.time() - 10
with self.assertRaises(ValueError) as ctx:
mock_idp.exchange_code_for_tokens(code, verifier, "uri")
self.assertIn("expired", str(ctx.exception).lower())
def test_token_premature_nbf_claim(self):
"""Boundary check — Token with future not-before (nbf) claim is rejected."""
persona = TEST_PERSONAS["buyer@alpha.com"]
token = mock_idp.mint_jwt(
subject=persona["sub"],
email=persona["email"],
name=persona["name"],
roles=persona["roles"],
tenant_id=persona["tenant_id"],
not_before_seconds=300
)
with self.assertRaises(ValueError) as ctx:
mock_idp.decode_and_verify_jwt(token)
self.assertIn("nbf", str(ctx.exception).lower())
def test_token_mismatched_issuer_audience(self):
"""Negative check — Mismatched issuer or audience is rejected."""
persona = TEST_PERSONAS["buyer@alpha.com"]
t1 = mock_idp.mint_jwt(persona["sub"], persona["email"], persona["name"], persona["roles"], persona["tenant_id"], custom_claims={"iss": "http://evil-issuer.com"})
with self.assertRaises(ValueError) as ctx:
mock_idp.decode_and_verify_jwt(t1)
self.assertIn("issuer", str(ctx.exception).lower())
t2 = mock_idp.mint_jwt(persona["sub"], persona["email"], persona["name"], persona["roles"], persona["tenant_id"], custom_claims={"aud": "evil-client"})
with self.assertRaises(ValueError) as ctx:
mock_idp.decode_and_verify_jwt(t2)
self.assertIn("audience", str(ctx.exception).lower())
def test_token_malformed_structure(self):
"""Negative check — Token not having 3 parts is rejected."""
with self.assertRaises(ValueError) as ctx:
mock_idp.decode_and_verify_jwt("part1.part2")
self.assertIn("structure", str(ctx.exception).lower())
def test_mock_idp_token_revocation(self):
"""FSM Invariant — Revoking token in mock IDP causes decode_and_verify_jwt to fail."""
persona = TEST_PERSONAS["buyer@alpha.com"]
token = mock_idp.mint_jwt(persona["sub"], persona["email"], persona["name"], persona["roles"], persona["tenant_id"])
mock_idp.revoke_token(token)
self.assertIn(token, mock_idp.revoked_tokens)
with self.assertRaises(ValueError) as ctx:
mock_idp.decode_and_verify_jwt(token)
self.assertIn("revoked", str(ctx.exception).lower())
def test_auth_service_empty_token_raises(self):
"""Negative check — verify_token with empty string raises ValueError."""
with self.assertRaises(ValueError) as ctx:
auth_service.verify_token("")
self.assertIn("missing", str(ctx.exception).lower())
def test_auth_service_jwks_network_and_caching(self):
"""Unit check — get_jwks handles successful network response and subsequent cache hit."""
from unittest.mock import patch, MagicMock
mock_resp = MagicMock()
mock_resp.status_code = 200
mock_resp.json.return_value = {"keys": [{"kid": "test-kid", "kty": "RSA"}]}
auth_service._jwks_cache = None
with patch("requests.get", return_value=mock_resp):
jwks1 = auth_service.get_jwks()
self.assertEqual(jwks1["keys"][0]["kid"], "test-kid")
# Cache hit (no network call needed)
jwks2 = auth_service.get_jwks()
self.assertEqual(jwks2, jwks1)
auth_service._jwks_cache = None
def test_auth_service_live_mode_verification(self):
"""Integration check — verify_token executes live Keycloak decode path when USE_IDENTITY_MOCK is False."""
from unittest.mock import patch
import jwt
persona = TEST_PERSONAS["buyer@alpha.com"]
token = mock_idp.mint_jwt(
subject=persona["sub"],
email=persona["email"],
name=persona["name"],
roles=persona["roles"],
tenant_id=persona["tenant_id"]
)
# Normal decode in live mode
with patch.object(auth_service.settings, "USE_IDENTITY_MOCK", False):
with patch("jwt.get_unverified_header", return_value={"alg": "RS256", "kid": "k1"}):
with patch("backend.app.auth.oidc.OIDCAuthService.get_jwks", return_value={"keys": []}):
with patch("jwt.decode", return_value={"sub": persona["sub"], "email": persona["email"], "roles": persona["roles"]}):
payload = auth_service.verify_token(token)
self.assertEqual(payload["sub"], persona["sub"])
# Expired token in live mode
with patch.object(auth_service.settings, "USE_IDENTITY_MOCK", False):
with patch("jwt.get_unverified_header", return_value={"alg": "RS256", "kid": "k1"}):
with patch("backend.app.auth.oidc.OIDCAuthService.get_jwks", return_value={"keys": []}):
with patch("jwt.decode", side_effect=jwt.ExpiredSignatureError("Expired")):
with self.assertRaises(ValueError) as ctx:
auth_service.verify_token(token)
self.assertIn("expired", str(ctx.exception).lower())
# Decode failure in live mode
with patch.object(auth_service.settings, "USE_IDENTITY_MOCK", False):
with patch("jwt.get_unverified_header", return_value={"alg": "RS256", "kid": "k1"}):
with patch("backend.app.auth.oidc.OIDCAuthService.get_jwks", return_value={"keys": []}):
with patch("jwt.decode", side_effect=RuntimeError("Signature invalid")):
with self.assertRaises(ValueError) as ctx:
auth_service.verify_token(token)
self.assertIn("failed", str(ctx.exception).lower())
# Test get_jwks error fallback when live Keycloak request fails
with patch.object(auth_service.settings, "USE_IDENTITY_MOCK", False):
auth_service._jwks_cache = None
with patch("requests.get", side_effect=Exception("Network error")):
res = auth_service.get_jwks()
self.assertEqual(res, {"keys": []})
if __name__ == "__main__":
unittest.main()