An open source, non-profit web search engine
Record when an API key was last used
Daoud Clarkede8be18c7b40
diff --git a/mwmbl/crawler/app.py b/mwmbl/crawler/app.pyindex b9d8926..ce2dc05 100644--- a/mwmbl/crawler/app.py+++ b/mwmbl/crawler/app.py@@ -239,6 +239,7 @@ def _register_routes(r: Router | NinjaAPI):return 401, {"message": "Invalid API key or insufficient scope (crawl scope required)."}now = datetime.now(timezone.utc)+ ApiKey.objects.filter(pk=api_key.pk).update(last_used=now)now_ts = int(now.timestamp())documents = []diff --git a/mwmbl/platform/api.py b/mwmbl/platform/api.pyindex 9d46ab2..5ffe792 100644--- a/mwmbl/platform/api.py+++ b/mwmbl/platform/api.py@@ -1081,6 +1081,7 @@ def list_api_keys(request) -> list[ApiKeyListItem]:id=k.id,name=k.name,created_on=k.created_on,+ last_used=k.last_used,scopes=k.scopes,)for k in keysdiff --git a/mwmbl/platform/schemas.py b/mwmbl/platform/schemas.pyindex 104f6a6..7d65419 100644--- a/mwmbl/platform/schemas.py+++ b/mwmbl/platform/schemas.py@@ -86,6 +86,13 @@ class ApiKeyCreatedResponse(Schema):key: str = Field(description="The raw API key token. Shown only on creation.")name: str = Field(description="Human-readable label for this key.")created_on: datetime = Field(description="When the key was created.")+ last_used: Optional[datetime] = Field(+ default=None,+ description=(+ "When the key was last used to authenticate, or null if it never has been. "+ "Accurate to within an hour for search keys, which are cached between checks."+ ),+ )scopes: list[str] = Field(description="Scopes granted to this key.")@@ -98,6 +105,13 @@ class ApiKeyListItem(Schema):id: int = Field(description="Unique ID of the API key.")name: str = Field(description="Human-readable label for this key.")created_on: datetime = Field(description="When the key was created.")+ last_used: Optional[datetime] = Field(+ default=None,+ description=(+ "When the key was last used to authenticate, or null if it never has been. "+ "Accurate to within an hour for search keys, which are cached between checks."+ ),+ )scopes: list[str] = Field(description="Scopes granted to this key.")diff --git a/mwmbl/search_auth.py b/mwmbl/search_auth.pyindex a1e06a6..74f70a8 100644--- a/mwmbl/search_auth.py+++ b/mwmbl/search_auth.py@@ -3,6 +3,7 @@ Authentication for the search API using the X-API-Key header."""import hashlib+from datetime import datetime, timezonefrom asgiref.sync import sync_to_asyncfrom django.core.cache import cache@@ -51,6 +52,12 @@ class SearchApiKeyAuth(APIKeyHeader):except ApiKey.DoesNotExist:return None+ # Only on a cache miss, which is also what makes this affordable: a hot key is+ # served from cache for CACHE_TTL, so a busy caller costs one UPDATE an hour+ # rather than one per request. The stored time is therefore accurate to the hour,+ # which is the granularity "last used" is read at anyway.+ ApiKey.objects.filter(pk=api_key.pk).update(last_used=datetime.now(timezone.utc))+cache.set(cache_key, api_key, CACHE_TTL)return api_keydiff --git a/test/test_batches_endpoint_removed.py b/test/test_batches_endpoint_removed.pyindex d147cee..a3a22fa 100644--- a/test/test_batches_endpoint_removed.py+++ b/test/test_batches_endpoint_removed.py@@ -218,3 +218,24 @@ def test_the_api_key_is_stripped_from_the_uploaded_object(api_client, crawl_api_assert response.status_code == 200uploaded = upload_object.call_args.args[0]assert uploaded.api_key is None+++def test_posting_results_records_when_the_key_was_last_used(api_client, crawl_api_key):+ assert crawl_api_key.last_used is None++ with (+ patch("mwmbl.crawler.app.index_documents"),+ patch("mwmbl.crawler.app.upload_object", return_value="fake/path.json.gz"),+ patch("mwmbl.crawler.app.stats_manager"),+ ):+ response = api_client.post(+ "/api/v1/crawler/results",+ content_type="application/json",+ data={"results": []},+ **api_key_header(crawl_api_key.raw_key),+ )++ assert response.status_code == 200+ crawl_api_key.refresh_from_db()+ assert crawl_api_key.last_used is not None