"""Test ASGI Middleware.""" from typing import Any import pytest from starlette.applications import Starlette from starlette.middleware import Middleware from starlette.requests import Request from starlette.responses import PlainTextResponse from starlette.routing import Route from starlette.testclient import TestClient from jwtauth import JWTAuth from jwtauth.asgi.middleware import JWTAuthenticationMiddleware @pytest.fixture def auth() -> JWTAuth: """Get fixtured JWTAuth object.""" return JWTAuth(jwks_url="https://test/.well-known/jws", options={}) @pytest.fixture def app(auth: JWTAuth) -> Starlette: """Get fixtured AGI app.""" def private_endpoint(request: Request) -> Any: return PlainTextResponse("ok") def public_endpoint(request: Request) -> Any: return PlainTextResponse("ok") return Starlette( middleware=[ Middleware( JWTAuthenticationMiddleware, enabled=True, exclude_paths=["/public"], auth=auth, ), ], routes=[ Route("/private", private_endpoint), Route("/public", public_endpoint), ], ) @pytest.fixture def test_client(app: Starlette) -> TestClient: """Get fixtured TestClient.""" return TestClient(app) def test_jwt_auth_missing_authorization(test_client: TestClient) -> None: """Test missing authorization results in 401.""" response = test_client.get("/private") assert response.status_code == 401 assert response.json() == { "code": "missing_authorization", "message": 'Missing "Authorization" in headers.', } def test_jwt_auth_private_endpoint_valid_authorization( test_client: TestClient, auth: JWTAuth ) -> None: """Test private endpoint validates authorization.""" async def _get_token(*args: Any, **kwargs: Any) -> dict[str, Any]: return {} auth.aget_token = _get_token # type: ignore[method-assign] response = test_client.get( "/private", headers={"authorization": "bearer token"}, ) assert response.status_code == 200 def test_jwt_auth_public_endpoint(test_client: TestClient) -> None: """Test public endpoint does not require authorization.""" response = test_client.get("/public") assert response.status_code == 200