c_agri_trade_code/tests/backend/test_auth_logout.py

107 lines
4.0 KiB
Python

"""Automated Tests for Session Termination & Logout Invariants.
Fulfills TC-AUTH-004, FR-AUTH-003 & SRS-AUTH-003.
Standard: UP-AI v1.5 Quality Standard (≥95% backend domain coverage).
Tags: uc_001, fr_auth_003, 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, TEST_PERSONAS
from backend.app.auth.session import session_manager
from backend.app.api.auth import auth_controller
class TestSessionLogoutLifecycle(unittest.TestCase):
"""TC-AUTH-004: Application Session Termination & Replay Prevention Tests."""
def setUp(self):
session_manager.clear()
def test_tc_auth_004_happy_path_session_logout(self):
"""TC-AUTH-004: User initiates logout; session is terminated successfully."""
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"]
)
auth_header = f"Bearer {token}"
# 1. Verify session is active initially
active_res = auth_controller.get_session(auth_header)
self.assertTrue(active_res["authenticated"])
self.assertEqual(active_res["status_code"], 200)
# 2. Issue logout request
logout_res = auth_controller.logout(auth_header)
self.assertEqual(logout_res["status_code"], 200)
self.assertEqual(logout_res["status"], "logged_out")
# 3. FSM Invariant: Reusing the ended session must be rejected with 401
post_logout_res = auth_controller.get_session(auth_header)
self.assertFalse(post_logout_res["authenticated"])
self.assertEqual(post_logout_res["status_code"], 401)
self.assertIn("terminated", post_logout_res["error"].lower())
def test_logout_without_token_returns_401(self):
"""Negative check — Logout request without Bearer token returns 401."""
res = auth_controller.logout(None)
self.assertEqual(res["status_code"], 401)
self.assertEqual(res["error"], "MISSING_BEARER_TOKEN")
def test_protected_action_denied_after_logout(self):
"""FSM Invariant — Business command is denied after logout."""
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"]
)
auth_header = f"Bearer {token}"
res1 = auth_controller.execute_protected_action(auth_header, "market", "Read")
self.assertTrue(res1["success"])
auth_controller.logout(auth_header)
res2 = auth_controller.execute_protected_action(auth_header, "market", "Read")
self.assertFalse(res2.get("authenticated", True))
self.assertEqual(res2["status_code"], 401)
def test_session_manager_boundary_methods(self):
"""Boundary checks for session_manager methods."""
# Empty token
self.assertFalse(session_manager.is_session_active(""))
self.assertIsNone(session_manager.get_session(""))
self.assertFalse(session_manager.revoke_session(""))
# Register and get active session
session_manager.register_session("tok1", {"sub": "sub1", "email": "a@b.com", "exp": time.time() + 3600})
self.assertTrue(session_manager.is_session_active("tok1"))
self.assertIsNotNone(session_manager.get_session("tok1"))
# Artificially expire
session_manager._active_sessions["tok1"]["expires_at"] = time.time() - 10
self.assertFalse(session_manager.is_session_active("tok1"))
self.assertIsNone(session_manager.get_session("tok1"))
if __name__ == "__main__":
unittest.main()