Skip to content
This repository has been archived by the owner on Jun 3, 2024. It is now read-only.

Commit

Permalink
Merge pull request #216 from Qwant/fix-bancheck-status-code
Browse files Browse the repository at this point in the history
Bancheck: fix status code for banned client
  • Loading branch information
amatissart authored Mar 19, 2021
2 parents 8455e6d + 856dcb0 commit e30aead
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 11 deletions.
28 changes: 17 additions & 11 deletions idunn/utils/ban_check.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,25 @@

logger = logging.getLogger(__name__)

if settings["BANCHECK_ENABLED"]:
ban_check_http = AsyncClient(
base_url=settings["QWANT_API_BASE_URL"],
timeout=float(settings["BANCHECK_TIMEOUT"]),
)
else:
ban_check_http = None

def get_ban_check_http():
if settings["BANCHECK_ENABLED"]:
return AsyncClient(
base_url=settings["QWANT_API_BASE_URL"],
timeout=float(settings["BANCHECK_TIMEOUT"]),
)
return None


ban_check_http = get_ban_check_http()


async def check_banned_client(x_client_hash: Optional[str] = Header(None)):
if ban_check_http is None:
return
if not x_client_hash:
return

try:
response = await ban_check_http.get(
"/v3/captcha/isban", params={"client_hash": x_client_hash}
Expand All @@ -28,10 +33,11 @@ async def check_banned_client(x_client_hash: Optional[str] = Header(None)):
response_data = response.json()
response_status = response_data.get("status")
if response_status != "success":
raise Exception(f"Got invalid status {repr(response_status)} from ban check")
is_client_banned = bool(response_data.get("data"))
if is_client_banned:
raise HTTPException(status_code=429)
raise ValueError(f"Got invalid status {repr(response_status)} from ban check")
except Exception as err:
logger.error("Failed to check client is not banned", exc_info=True)
raise HTTPException(status_code=503) from err

is_client_banned = bool(response_data.get("data"))
if is_client_banned:
raise HTTPException(status_code=429)
31 changes: 31 additions & 0 deletions tests/test_instant_answer/test_ia_bancheck.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import pytest
from unittest.mock import patch
from fastapi.testclient import TestClient

from app import app
from idunn.utils.ban_check import get_ban_check_http
from tests.utils import override_settings


@pytest.fixture
def enable_bancheck(httpx_mock):
with override_settings(
{
"BANCHECK_ENABLED": True,
"QWANT_API_BASE_URL": "http://qwant-api.test",
}
), patch("idunn.utils.ban_check.ban_check_http", new_callable=get_ban_check_http):
httpx_mock.get(url__regex=r"http://qwant-api.test/v3/captcha/isban.*").respond(
json={"status": "success", "data": True}
)
yield


def test_ia_client_banned(enable_bancheck):
client = TestClient(app)
response = client.get(
"/v1/instant_answer",
params={"q": "paris", "lang": "fr"},
headers={"x-client-hash": "banned"},
)
assert response.status_code == 429

0 comments on commit e30aead

Please sign in to comment.