Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/fastapi_multiauth/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import inspect
from typing import Any, Callable

import anyio.to_thread
from fastapi import HTTPException, Request


Expand Down Expand Up @@ -43,7 +44,7 @@ def ensure_async(fn: Callable[..., Any]) -> Callable[..., Any]:

@functools.wraps(fn)
async def wrapper(*args: Any, **kwargs: Any) -> Any:
result = fn(*args, **kwargs)
result = await anyio.to_thread.run_sync(functools.partial(fn, *args, **kwargs))
if inspect.isawaitable(result):
return await result
return result
Expand Down
13 changes: 13 additions & 0 deletions tests/test_multiauth.py
Original file line number Diff line number Diff line change
Expand Up @@ -3443,6 +3443,19 @@ def factory_validator(token: str):
response = client.get("/me", headers={"Authorization": f"Bearer {VALID_TOKEN}"})
assert response.status_code == 200

async def test_sync_validator_runs_in_worker_thread(self):
"""A blocking sync validator must not run on the event loop."""
import threading

from fastapi_multiauth.utils import ensure_async

loop_thread = threading.get_ident()

def validator(token: str) -> int:
return threading.get_ident()

assert await ensure_async(validator)("x") != loop_thread


class TestJWTValidatorJWKSRobustness:
JWKS_URL = "https://idp.example.com/jwks"
Expand Down