Skip to content

armgit / mwmbl

Public Imported from GitHub
0

An open source, non-profit web search engine

Blacklist rotated refresh tokens and re-check the user on refresh

Daoud Clarkecbcbe13fad7a
diff --git a/mwmbl/api.py b/mwmbl/api.py
index 06aacf0..930787e 100644
--- a/mwmbl/api.py
+++ b/mwmbl/api.py
@@ -20,13 +20,16 @@ typically at /api/v1/platform/token/pair, /api/v1/platform/token/refresh, etc.
from datetime import timedelta
+from django.contrib.auth import get_user_model
from ninja import Field
from ninja_extra import NinjaExtraAPI, api_controller, http_get, http_post
from ninja_extra.permissions import AllowAny
from ninja_jwt.controller import TokenObtainPairController, TokenVerificationController
-from ninja_jwt.schema import TokenObtainPairInputSchema
+from ninja_jwt.exceptions import AuthenticationFailed, InvalidToken, TokenError
+from ninja_jwt.schema import TokenObtainPairInputSchema, TokenRefreshInputSchema
from ninja_jwt.schema_control import SchemaControl
from ninja_jwt.settings import api_settings
+from ninja_jwt.tokens import RefreshToken
from scalar_ninja import ScalarViewer
from scalar_ninja.scalar_ninja import AgentConfig
@@ -65,6 +68,30 @@ class MwmblTokenController(TokenVerificationController, TokenObtainPairControlle
user_token.check_user_authentication_rule()
return user_token.to_response_schema()
+ @http_post(
+ "/refresh",
+ response=TokenRefreshInputSchema.get_response_schema(),
+ url_name="token_refresh",
+ operation_id="token_refresh",
+ summary="Refresh JWT token pair",
+ description=(
+ "Exchange a refresh token for a new access token and a new refresh token. "
+ "Each refresh token can only be used once."
+ ),
+ )
+ def refresh_token(self, refresh_token: TokenRefreshInputSchema):
+ # ninja_jwt only checks the token itself, so re-apply the login rule here,
+ # otherwise deactivated or deleted users could refresh indefinitely
+ try:
+ token = RefreshToken(refresh_token.refresh)
+ except TokenError as e:
+ raise InvalidToken(str(e)) from e
+ user_id = token[api_settings.USER_ID_CLAIM]
+ user = get_user_model().objects.filter(**{api_settings.USER_ID_FIELD: user_id}).first()
+ if user is None or not api_settings.USER_AUTHENTICATION_RULE(user):
+ raise AuthenticationFailed("No active account found for the given token")
+ return refresh_token.to_response_schema()
+
api = NinjaExtraAPI(
title="Mwmbl API",
diff --git a/mwmbl/apps.py b/mwmbl/apps.py
index aae5332..10b6890 100644
--- a/mwmbl/apps.py
+++ b/mwmbl/apps.py
@@ -142,6 +142,7 @@ class MwmblConfig(AppConfig):
from mwmbl.background import (
count_index_urls,
+ flush_expired_tokens,
purge_blacklisted_from_queue,
refresh_blacklist_snapshot,
report_usage_to_polar,
@@ -155,6 +156,7 @@ class MwmblConfig(AppConfig):
BLACKLIST_PURGE_TASK = "mwmbl.background.purge_blacklisted_from_queue"
MODERATION_RETRAIN_TASK = "mwmbl.background.retrain_domain_moderation_model"
INDEX_COUNT_TASK = "mwmbl.background.count_index_urls"
+ FLUSH_TOKENS_TASK = "mwmbl.background.flush_expired_tokens"
# Sync search counts once per hour (3600 seconds)
if not Task.objects.filter(task_name=SYNC_TASK).exists():
@@ -195,6 +197,10 @@ class MwmblConfig(AppConfig):
if not Task.objects.filter(task_name=INDEX_COUNT_TASK).exists():
count_index_urls(repeat=settings.INDEX_COUNT_RUN_INTERVAL_SECONDS, repeat_until=None)
+ # Clear expired refresh tokens out of the JWT blacklist tables once a day
+ if not Task.objects.filter(task_name=FLUSH_TOKENS_TASK).exists():
+ flush_expired_tokens(repeat=Task.DAILY, repeat_until=None)
+
except Exception:
# Don't prevent startup if background task scheduling fails
log.exception("Failed to schedule background tasks")
diff --git a/mwmbl/background.py b/mwmbl/background.py
index 851a8d8..bb806c7 100644
--- a/mwmbl/background.py
+++ b/mwmbl/background.py
@@ -350,3 +350,9 @@ def retrain_domain_moderation_model():
model, so the reload and the pending-queue rescore both take effect immediately.
"""
call_command("train_domain_moderation_model")
+
+
+@background(schedule=0)
+def flush_expired_tokens():
+ """Delete expired JWT refresh tokens from the blacklist tables, which gain a row per refresh."""
+ call_command("flushexpiredtokens")
diff --git a/mwmbl/settings_common.py b/mwmbl/settings_common.py
index fd847e1..dc94562 100644
--- a/mwmbl/settings_common.py
+++ b/mwmbl/settings_common.py
@@ -46,6 +46,7 @@ INSTALLED_APPS = [
"allauth.account",
"allauth.socialaccount",
"ninja_extra",
+ "ninja_jwt.token_blacklist",
"debug_toolbar",
"background_task",
]
@@ -245,6 +246,8 @@ NINJA_JWT = {
# visit at least once a year stay logged in indefinitely.
"REFRESH_TOKEN_LIFETIME": timedelta(days=365),
"ROTATE_REFRESH_TOKENS": True,
+ # Each refresh token works once, so a leaked token dies when its owner next refreshes
+ "BLACKLIST_AFTER_ROTATION": True,
}
# Database configuration (shared across all environments via DATABASE_URL env var)
diff --git a/test/test_auth.py b/test/test_auth.py
index 6e40b68..5b4c5ac 100644
--- a/test/test_auth.py
+++ b/test/test_auth.py
@@ -1,10 +1,14 @@
+from datetime import timedelta
+
import pytest
from allauth.account.models import EmailAddress
from django.contrib.auth import get_user_model
+from ninja_jwt.tokens import RefreshToken
User = get_user_model()
TOKEN_URL = "/api/v1/platform/token/pair"
+REFRESH_URL = "/api/v1/platform/token/refresh"
@pytest.fixture
@@ -109,20 +113,56 @@ def test_login_email_and_username_return_same_user(client, verified_user):
assert subject(by_username["access"]) == subject(by_email["access"])
-def test_refresh_rotates_refresh_token(client, verified_user):
- # Rotation restarts the refresh token lifetime, so active users stay logged in
- pair = client.post(
+def _obtain_pair(client):
+ return client.post(
TOKEN_URL,
{"username": "swift_falcon_379", "password": "correctpassword"},
content_type="application/json",
).json()
- response = client.post(
- "/api/v1/platform/token/refresh",
- {"refresh": pair["refresh"]},
- content_type="application/json",
- )
+
+
+def _refresh(client, refresh):
+ return client.post(REFRESH_URL, {"refresh": refresh}, content_type="application/json")
+
+
+def test_refresh_rotates_refresh_token(client, verified_user):
+ # Rotation restarts the refresh token lifetime, so active users stay logged in
+ pair = _obtain_pair(client)
+ response = _refresh(client, pair["refresh"])
assert response.status_code == 200
data = response.json()
assert data["access"]
assert data["refresh"] != pair["refresh"]
+
+ rotated = RefreshToken(data["refresh"])
+ assert rotated["exp"] - rotated["iat"] == timedelta(days=365).total_seconds()
+ assert _refresh(client, data["refresh"]).status_code == 200
+
+
+def test_rotated_out_refresh_token_is_rejected(client, verified_user):
+ pair = _obtain_pair(client)
+ assert _refresh(client, pair["refresh"]).status_code == 200
+
+ response = _refresh(client, pair["refresh"])
+ assert response.status_code == 401
+
+
+def test_refresh_rejected_for_deactivated_user(client, verified_user):
+ pair = _obtain_pair(client)
+ verified_user.is_active = False
+ verified_user.save()
+
+ response = _refresh(client, pair["refresh"])
+ assert response.status_code == 401
+
+
+def test_refresh_rejected_for_deleted_user(client, verified_user):
+ pair = _obtain_pair(client)
+ verified_user.delete()
+
+ response = _refresh(client, pair["refresh"])
+ assert response.status_code == 401