An open source, non-profit web search engine
Allow users to self-service create crawl-scoped API keys
Daoud Clarke2d05700843b9
diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.pyindex 4c149b3..27c70aa 100644--- a/mwmbl/platform/api.py+++ b/mwmbl/platform/api.py@@ -464,24 +464,27 @@ def get_agreement_history(request) -> list[AgreementResponse]:"/api-keys/",auth=JWTAuth(),response=ApiKeyCreatedResponse,- summary="Create a search API key",+ summary="Create an API key",description=(- "Create a new search-scoped API key for the authenticated user. "+ "Create a new API key for the authenticated user. "+ "Use `scope='search'` (default) for the search endpoint or `scope='crawl'` for the crawler endpoint. ""The raw key value is returned **only once** in this response — store it securely. "- "Use the key in the `X-API-Key` header when calling `GET /api/v1/search/`. "- "Requires a verified account."+ "Requires a verified account and acceptance of the relevant terms of service."),tags=["API Keys"],)def create_api_key(request, body: CreateApiKeyRequest):check_email_verified(request)- _require_current_agreement(request.user, AgreementType.TERMS_OF_SERVICE_API)+ if body.scope == ApiKey.Scope.CRAWL:+ _require_current_agreement(request.user, AgreementType.TERMS_OF_SERVICE_GUI)+ else:+ _require_current_agreement(request.user, AgreementType.TERMS_OF_SERVICE_API)from mwmbl.models import generate_api_keyraw_key, key_hash = generate_api_key()api_key = ApiKey.objects.create(user=request.user,name=body.name,- scopes=[ApiKey.Scope.SEARCH],+ scopes=[body.scope],key=key_hash,)return ApiKeyCreatedResponse(@@ -497,9 +500,9 @@ def create_api_key(request, body: CreateApiKeyRequest):"/api-keys/",auth=JWTAuth(),response=list[ApiKeyListItem],- summary="List search API keys",+ summary="List API keys",description=(- "List all search-scoped API keys belonging to the authenticated user. "+ "List all API keys belonging to the authenticated user. ""The raw key value is **not** included in this response. ""Requires a verified account."),@@ -507,10 +510,7 @@ def create_api_key(request, body: CreateApiKeyRequest):)def list_api_keys(request) -> list[ApiKeyListItem]:check_email_verified(request)- keys = ApiKey.objects.filter(- user=request.user,- scopes__contains=[ApiKey.Scope.SEARCH],- ).order_by("-created_on")+ keys = ApiKey.objects.filter(user=request.user).order_by("-created_on")return [ApiKeyListItem(id=k.id,@@ -525,9 +525,9 @@ def list_api_keys(request) -> list[ApiKeyListItem]:@router.delete("/api-keys/{key_id}",auth=JWTAuth(),- summary="Revoke a search API key",+ summary="Revoke an API key",description=(- "Permanently revoke (delete) a search-scoped API key owned by the authenticated user. "+ "Permanently revoke (delete) an API key owned by the authenticated user. ""Any subsequent requests using the revoked key will receive a 401 response. ""Returns 404 if the key does not exist or does not belong to the current user. ""Requires a verified account."@@ -536,11 +536,7 @@ def list_api_keys(request) -> list[ApiKeyListItem]:)def delete_api_key(request, key_id: int):check_email_verified(request)- api_key = ApiKey.objects.filter(- id=key_id,- user=request.user,- scopes__contains=[ApiKey.Scope.SEARCH],- ).first()+ api_key = ApiKey.objects.filter(id=key_id, user=request.user).first()if api_key is None:raise InvalidRequest("API key not found.", status=404)invalidate_api_key_cache(api_key.key)diff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.pyindex 83901c6..d26a424 100644--- a/mwmbl/platform/schemas.py+++ b/mwmbl/platform/schemas.py@@ -50,13 +50,17 @@ class ResetPasswordRequest(Schema):# ---------------------------------------------------------------------------class CreateApiKeyRequest(Schema):- """Request body for creating a new search-scoped API key."""+ """Request body for creating a new API key."""name: str = Field(default="",max_length=100,description="Optional human-readable label for this key.",example="My search app",)+ scope: Literal["search", "crawl"] = Field(+ default="search",+ description="Scope for this key. Use 'crawl' for the crawler endpoint, 'search' for the search endpoint.",+ )class ApiKeyCreatedResponse(Schema):diff --git a/test/test_search_api_key.py b/test/test_search_api_key.pyindex abf0e84..052f3f5 100644--- a/test/test_search_api_key.py+++ b/test/test_search_api_key.py@@ -46,12 +46,13 @@ def verified_user(db):verified=True,primary=True,)- version_id = settings.CURRENT_AGREEMENT_VERSIONS.get(AgreementType.TERMS_OF_SERVICE_API)- UserAgreement.objects.create(- user=user,- agreement_type=AgreementType.TERMS_OF_SERVICE_API,- version_id=version_id,- )+ for agreement_type in (AgreementType.TERMS_OF_SERVICE_API, AgreementType.TERMS_OF_SERVICE_GUI):+ version_id = settings.CURRENT_AGREEMENT_VERSIONS.get(agreement_type)+ UserAgreement.objects.create(+ user=user,+ agreement_type=agreement_type,+ version_id=version_id,+ )return user@@ -177,6 +178,54 @@ def test_create_api_key_default_name(api_client, access_token):assert response.json()["name"] == ""+def test_create_search_api_key_explicit_scope(api_client, access_token):+ response = api_client.post(+ "/api/v1/platform/api-keys/",+ content_type="application/json",+ data={"scope": "search"},+ **auth_headers(access_token),+ )+ assert response.status_code == 200+ assert response.json()["scopes"] == ["search"]+++def test_create_crawl_api_key(api_client, access_token):+ response = api_client.post(+ "/api/v1/platform/api-keys/",+ content_type="application/json",+ data={"name": "My crawler", "scope": "crawl"},+ **auth_headers(access_token),+ )+ assert response.status_code == 200+ data = response.json()+ assert data["scopes"] == ["crawl"]+ assert data["name"] == "My crawler"+ assert "key" in data+++def test_create_crawl_api_key_without_gui_tos_returns_403(api_client, db):+ """A user who has only accepted the API TOS cannot create a crawl key."""+ user = User.objects.create_user(+ username="apionly", email="[email protected]", password="testpass123"+ )+ EmailAddress.objects.create(user=user, email="[email protected]", verified=True, primary=True)+ version_id = settings.CURRENT_AGREEMENT_VERSIONS.get(AgreementType.TERMS_OF_SERVICE_API)+ UserAgreement.objects.create(+ user=user, agreement_type=AgreementType.TERMS_OF_SERVICE_API, version_id=version_id+ )+ token = str(RefreshToken.for_user(user).access_token)+ response = api_client.post(+ "/api/v1/platform/api-keys/",+ content_type="application/json",+ data={"scope": "crawl"},+ **auth_headers(token),+ )+ assert response.status_code == 403++# ---------------------------------------------------------------------------# API key management — GET /api/v1/platform/api-keys/# ---------------------------------------------------------------------------@@ -199,7 +248,7 @@ def test_list_api_keys_hides_raw_key(api_client, access_token, search_api_key):@pytest.mark.django_db-def test_list_api_keys_only_shows_search_scoped(api_client, access_token, search_api_key, crawl_api_key):+def test_list_api_keys_shows_all_scopes(api_client, access_token, search_api_key, crawl_api_key):response = api_client.get("/api/v1/platform/api-keys/",**auth_headers(access_token),@@ -207,7 +256,7 @@ def test_list_api_keys_only_shows_search_scoped(api_client, access_token, searchassert response.status_code == 200ids = [item["id"] for item in response.json()]assert search_api_key.id in ids- assert crawl_api_key.id not in ids+ assert crawl_api_key.id in ids@pytest.mark.django_db@@ -250,6 +299,17 @@ def test_delete_nonexistent_key_returns_404(api_client, access_token):assert response.status_code == 404+def test_delete_crawl_api_key(api_client, access_token, crawl_api_key):+ key_id = crawl_api_key.id+ response = api_client.delete(+ f"/api/v1/platform/api-keys/{key_id}",+ **auth_headers(access_token),+ )+ assert response.status_code == 200+ assert not ApiKey.objects.filter(id=key_id).exists()++# ---------------------------------------------------------------------------# Search endpoint — authentication# ---------------------------------------------------------------------------