Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Move Super Search auth into search_auth, fix JWT user lookup

Daoud Clarke8953befa17bb
diff --git a/mwmbl/search_auth.py b/mwmbl/search_auth.py
index 0258ea8..2db3443 100644
--- a/mwmbl/search_auth.py
+++ b/mwmbl/search_auth.py
@@ -3,10 +3,12 @@ Authentication for the search API using the X-API-Key header.
"""
import hashlib
+from asgiref.sync import sync_to_async
from django.core.cache import cache
+from ninja.errors import HttpError
from ninja.security import APIKeyHeader
-from mwmbl.models import ApiKey
+from mwmbl.models import ApiKey, MwmblUser
CACHE_TTL = 3600 # 1 hour; explicit invalidation handles all mutation paths
@@ -50,3 +52,34 @@ class SearchApiKeyAuth(APIKeyHeader):
cache.set(cache_key, api_key, CACHE_TTL)
return api_key
+
+
+async def authenticate_user(request) -> MwmblUser:
+ """Resolve the requesting user from either an X-API-Key header or a JWT.
+
+ Returns the user on success; raises ``HttpError(401)`` otherwise. Database
+ lookups are off-loaded via ``sync_to_async`` so this can be awaited from
+ async views.
+ """
+ raw_key = request.headers.get("X-API-Key")
+ if raw_key:
+ api_key = await sync_to_async(SearchApiKeyAuth().authenticate)(request, raw_key)
+ if api_key is None:
+ raise HttpError(401, "Invalid API key.")
+ return await sync_to_async(lambda: api_key.user)()
+
+ auth_header = request.headers.get("Authorization", "")
+ if auth_header.startswith("Bearer "):
+ # Defer JWT validation and user lookup to ninja-jwt rather than decoding
+ # the token by hand: this respects the configured token classes, user-id
+ # claim/field, and the is_active check.
+ from ninja_jwt.authentication import AsyncJWTAuth
+ from ninja_jwt.exceptions import AuthenticationFailed, TokenError
+
+ token = auth_header[len("Bearer "):]
+ try:
+ return await AsyncJWTAuth().async_jwt_authenticate(request, token)
+ except (TokenError, AuthenticationFailed):
+ raise HttpError(401, "Invalid token.")
+
+ raise HttpError(401, "Authentication required: X-API-Key or Bearer token.")
diff --git a/mwmbl/tinysearchengine/super_search.py b/mwmbl/tinysearchengine/super_search.py
index af08fdb..d1830bf 100644
--- a/mwmbl/tinysearchengine/super_search.py
+++ b/mwmbl/tinysearchengine/super_search.py
@@ -31,13 +31,12 @@ from ninja.errors import HttpError
from pydantic import BaseModel, Field
from mwmbl.crawler.retrieve import crawl_url
-from mwmbl.models import MwmblUser
from mwmbl.quota import (
check_rate_limit,
decrement_monthly_super_search,
increment_monthly_super_search,
)
-from mwmbl.search_auth import SearchApiKeyAuth
+from mwmbl.search_auth import authenticate_user
from mwmbl.search_setup import ltr_model
from mwmbl.tinysearchengine.indexer import Document
from mwmbl.tinysearchengine.ltr_rank import score_documents
@@ -306,37 +305,6 @@ def _title_from_url(url: str) -> str:
-async def _authenticate(request) -> MwmblUser:
- """Resolve the requesting user from either an X-API-Key header or a JWT.
-
- Returns the user on success; raises HttpError(401) otherwise.
- Database lookups are off-loaded via ``sync_to_async`` because the view
- that calls this is async.
- """
- raw_key = request.headers.get("X-API-Key")
- if raw_key:
- api_key = await sync_to_async(SearchApiKeyAuth().authenticate)(request, raw_key)
- if api_key is None:
- raise HttpError(401, "Invalid API key.")
- return await sync_to_async(lambda: api_key.user)()
-
- auth_header = request.headers.get("Authorization", "")
- if auth_header.startswith("Bearer "):
- token = auth_header[len("Bearer "):]
- try:
- from ninja_jwt.tokens import AccessToken
- access = AccessToken(token)
- user_id = access["user_id"]
- except Exception:
- raise HttpError(401, "Invalid token.")
- try:
- return await sync_to_async(MwmblUser.objects.get)(id=user_id)
- except MwmblUser.DoesNotExist:
- raise HttpError(401, "Unknown user.")
-
- raise HttpError(401, "Authentication required: X-API-Key or Bearer token.")
-
-
# ---------------------------------------------------------------------------
# Pipeline
# ---------------------------------------------------------------------------
@@ -653,7 +621,7 @@ def init_router() -> None:
},
)
async def super_search(request, q: str):
- user = await _authenticate(request)
+ user = await authenticate_user(request)
if not await sync_to_async(check_rate_limit)(user.id):
raise HttpError(429, "Rate limit exceeded: maximum 5 requests per second.")