""" Authentication Middleware Test Suite Tests public endpoints bypass, token verification, API key access, and 401 Unauthorized enforcement. """ import sys import os import asyncio from pathlib import Path import pytest from starlette.responses import JSONResponse # Add backend root to path sys.path.insert(0, str(Path(__file__).parent.parent)) from fastapi.testclient import TestClient from main import app from middleware.auth import AuthenticationMiddleware client = TestClient(app) class MockRequest: def __init__(self, path, headers=None, method="POST"): self.url = type("URL", (), {"path": path})() self.method = method self.headers = headers or {} self.state = type("State", (), {})() async def dummy_next(req): return JSONResponse(status_code=200, content={"status": "passed"}) def test_public_endpoints_allowed(): """Verify health and root endpoints bypass authentication.""" res_health = client.get("/health") assert res_health.status_code == 200, f"Expected 200 on /health, got {res_health.status_code}" res_root = client.get("/") assert res_root.status_code == 200, f"Expected 200 on /, got {res_root.status_code}" def test_master_api_key_endpoint(): """Verify master API key grants access to protected endpoints.""" active_key = os.environ.get("MASTER_API_KEY", "alli_dev_test_secret_key_2026") headers_key = {"X-API-Key": active_key} res_key = client.post("/validate", json={"source_type": "int", "target_type": "float"}, headers=headers_key) assert res_key.status_code == 200, f"Expected 200 with X-API-Key, got {res_key.status_code}" @pytest.mark.asyncio async def test_strict_unauthenticated_request_blocked(): """Verify unauthenticated request returns 401 under strict mode.""" auth_mw = AuthenticationMiddleware(app=None, supabase_client=None) auth_mw.auth_required = True auth_mw.master_api_key = "alli_dev_test_secret_key_2026" req_unauth = MockRequest("/run") res_unauth = await auth_mw.dispatch(req_unauth, dummy_next) assert res_unauth.status_code == 401, f"Expected 401, got {res_unauth.status_code}" @pytest.mark.asyncio async def test_valid_master_api_key_dispatched(): """Verify valid master API key (>= 16 chars) succeeds.""" auth_mw = AuthenticationMiddleware(app=None, supabase_client=None) auth_mw.auth_required = True test_key = "alli_dev_test_secret_key_2026" auth_mw.master_api_key = test_key req_valid_key = MockRequest("/run", headers={"X-API-Key": test_key}) res_valid_key = await auth_mw.dispatch(req_valid_key, dummy_next) assert res_valid_key.status_code == 200, f"Expected 200, got {res_valid_key.status_code}" @pytest.mark.asyncio async def test_short_or_weak_api_key_rejected(): """Verify short API keys (< 16 chars) are strictly rejected.""" auth_mw = AuthenticationMiddleware(app=None, supabase_client=None) auth_mw.auth_required = True short_key = "short_key" auth_mw.master_api_key = short_key req_short = MockRequest("/run", headers={"X-API-Key": short_key}) res_short = await auth_mw.dispatch(req_short, dummy_next) assert res_short.status_code == 401, f"Expected 401 for short API key, got {res_short.status_code}" @pytest.mark.asyncio async def test_public_path_bypasses_middleware(): """Verify public path /health bypasses authentication strictly.""" auth_mw = AuthenticationMiddleware(app=None, supabase_client=None) auth_mw.auth_required = True req_pub = MockRequest("/health") res_pub = await auth_mw.dispatch(req_pub, dummy_next) assert res_pub.status_code == 200, f"Expected 200 on public path, got {res_pub.status_code}" if __name__ == "__main__": test_public_endpoints_allowed() test_master_api_key_endpoint() asyncio.run(test_strict_unauthenticated_request_blocked()) asyncio.run(test_valid_master_api_key_dispatched()) asyncio.run(test_short_or_weak_api_key_rejected()) asyncio.run(test_public_path_bypasses_middleware()) print("\nALL AUTH MIDDLEWARE TESTS PASSED DIRECTLY!")