Skip to content

Commit f845602

Browse files
authored
Set the client IP for Infobase writes from FastAPI login and anonymize (#14589)
* Set the client IP for Infobase writes from FastAPI login and anonymize Logging in with Internet Archive credentials creates or activates the Open Library account when needed. Activation saves the /people profile, and Infobase stamps that transaction with web.ctx.ip, a Postgres inet column. web.py sets web.ctx.ip on every request; FastAPI never does, so the infogami client sent an empty X-REMOTE-IP and Postgres rejected the row ("invalid input syntax for type inet"), failing those logins. Wrap the audit_accounts calls in /account/login (form and JSON) and the anonymize call in /account/anonymize.json in web_ctx_ip(client_ip), as link, merge_authors and importapi already do. Fixes OL-INFOBASE-9VA * Set the anonymize client IP only around the Infobase delete web.ctx.ip is thread-local, and FastAPI runs every coroutine on one event-loop thread. Setting it around the whole awaited anonymize() kept it set while _anonymize_tables awaited. anonymize() now takes the client IP and sets it only around the synchronous _delete_infobase_data step, the one that writes to Infobase. Tests cover that the IP is set there and cleared before the awaits, and that the route passes it in.
1 parent 25f9fc4 commit f845602

4 files changed

Lines changed: 118 additions & 26 deletions

File tree

‎openlibrary/accounts/model.py‎

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@
3232
from openlibrary.plugins.openlibrary.pd import get_pd_org
3333
from openlibrary.utils import server_timing
3434
from openlibrary.utils.async_utils import async_bridge
35-
from openlibrary.utils.request_context import site
35+
from openlibrary.utils.request_context import site, web_ctx_ip
3636

3737
try:
3838
from simplejson.errors import JSONDecodeError
@@ -496,9 +496,18 @@ def set_bot_flag(self, flag) -> None:
496496
self.bot = flag
497497
self._save()
498498

499-
async def anonymize(self, test: bool = False) -> AccountAnonymizationResult:
499+
async def anonymize(self, ip: str, test: bool = False) -> AccountAnonymizationResult:
500+
"""Anonymize the account from a FastAPI route.
501+
502+
``ip`` is the client IP. Infobase stamps it on the transaction that
503+
clears the profile page, read from the thread-local ``web.ctx.ip``,
504+
which FastAPI never sets. It is set only around that synchronous
505+
step, not across the awaits below, so it can't leak into other
506+
requests running on the same event loop.
507+
"""
500508
if not test:
501-
self._delete_infobase_data()
509+
with web_ctx_ip(ip):
510+
self._delete_infobase_data()
502511
return await self._anonymize_tables(test)
503512

504513
def anonymize_sync(self, test: bool = False) -> AccountAnonymizationResult:

‎openlibrary/fastapi/account.py‎

Lines changed: 29 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -34,13 +34,14 @@
3434
get_authenticated_user,
3535
require_authenticated_user,
3636
)
37+
from openlibrary.fastapi.shared.dependencies import ClientIpDep # noqa: TC001
3738
from openlibrary.fastapi.shared.site_page import SitePage, SitePageRoute
3839
from openlibrary.fastapi.shared.utils import set_flash_cookie
3940
from openlibrary.i18n import gettext as _
4041
from openlibrary.plugins.upstream import account as legacy_account
4142
from openlibrary.plugins.upstream.account import get_login_error
4243
from openlibrary.plugins.upstream.utils import is_safe_redirect
43-
from openlibrary.utils.request_context import site
44+
from openlibrary.utils.request_context import site, web_ctx_ip
4445

4546
logger = logging.getLogger("openlibrary.fastapi.account")
4647

@@ -333,7 +334,7 @@ def _json_login_error(error: str) -> JSONResponse:
333334
)
334335

335336

336-
async def _login_json(request: Request) -> Response:
337+
async def _login_json(request: Request, client_ip: str) -> Response:
337338
"""Mirror web.py's account_login_json for JSON request bodies.
338339
339340
S3 keys (access/secret) log the user in directly; username/password falls
@@ -346,14 +347,17 @@ async def _login_json(request: Request) -> Response:
346347

347348
# Try S3 authentication first, fallback to infogami user/pass
348349
if access and secret:
349-
audit = audit_accounts(
350-
email=None,
351-
password=None,
352-
require_link=True,
353-
s3_access_key=access,
354-
s3_secret_key=secret,
355-
test=test,
356-
)
350+
# audit_accounts can create or activate the OL account, which writes an
351+
# Infobase transaction stamped with web.ctx.ip; FastAPI never sets it.
352+
with web_ctx_ip(client_ip):
353+
audit = audit_accounts(
354+
email=None,
355+
password=None,
356+
require_link=True,
357+
s3_access_key=access,
358+
s3_secret_key=secret,
359+
test=test,
360+
)
357361
if error := audit.get("error"):
358362
return _json_login_error(error)
359363
if not (ol_username := audit.get("ol_username")):
@@ -420,6 +424,7 @@ def _login_error_response(redirect: str, action: str, username: str, message: st
420424
async def login(
421425
request: Request,
422426
form_data: Annotated[LoginForm, Form()],
427+
client_ip: ClientIpDep,
423428
) -> Response:
424429
"""
425430
Login endpoint - works identically to web.py version.
@@ -436,7 +441,7 @@ async def login(
436441
# A JSON body follows web.py's account_login_json: S3 keys (access/secret)
437442
# are required for password-less login.
438443
if (request.headers.get("content-type") or "").lower().startswith("application/json"):
439-
return await _login_json(request)
444+
return await _login_json(request, client_ip)
440445

441446
# web.py's web.input() merges query string params with the posted form
442447
# (the public openlibrary/api.py client logs in via query string).
@@ -451,14 +456,17 @@ async def login(
451456
test = form_data.test or q.get("test", "").lower() in ("yes", "true", "on", "1")
452457

453458
# Call the EXACT same audit function that web.py uses
454-
audit = audit_accounts(
455-
email="" if (access and secret) else username,
456-
password=password,
457-
require_link=True,
458-
s3_access_key=access,
459-
s3_secret_key=secret,
460-
test=test,
461-
)
459+
# audit_accounts can create or activate the OL account, which writes an
460+
# Infobase transaction stamped with web.ctx.ip; FastAPI never sets it.
461+
with web_ctx_ip(client_ip):
462+
audit = audit_accounts(
463+
email="" if (access and secret) else username,
464+
password=password,
465+
require_link=True,
466+
s3_access_key=access,
467+
s3_secret_key=secret,
468+
test=test,
469+
)
462470

463471
# Authentication errors go back to the login form with a message,
464472
# mirroring web.py's render_error
@@ -548,6 +556,7 @@ async def logout(request: Request) -> Response:
548556
)
549557
async def anonymize_account(
550558
request: Request,
559+
client_ip: ClientIpDep,
551560
test: Annotated[str, Form()] = "false",
552561
digest: Annotated[str, Form()] = "",
553562
msg: Annotated[str, Form()] = "",
@@ -587,7 +596,7 @@ async def anonymize_account(
587596
# This endpoint authenticates via HMAC+S3, not a user session, so
588597
# there is no auth token on the connection without RunAs.
589598
with RunAs(ol_account.username):
590-
result = await ol_account.anonymize(test=test_mode)
599+
result = await ol_account.anonymize(client_ip, test=test_mode)
591600
except Exception as e: # noqa: BLE001
592601
logger.error(e)
593602
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail="Internal Server Error")

‎openlibrary/tests/accounts/test_models.py‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
from unittest.mock import AsyncMock
44

55
import pytest
6+
import web
67
from requests.models import Response
78

89
from openlibrary.accounts import InternetArchiveAccount, OpenLibraryAccount, model
@@ -74,7 +75,7 @@ async def test_anonymize_test_mode_awaits_all_sql_models(monkeypatch):
7475
mocks[key] = async_mock
7576

7677
with mock.patch.object(OpenLibraryAccount, "get_activation_link", return_value=model.Link(code="abc123")):
77-
result = await account.anonymize(test=True)
78+
result = await account.anonymize("203.0.113.7", test=True)
7879

7980
assert result == {
8081
"new_username": "anonymous-abc123",
@@ -90,6 +91,26 @@ async def test_anonymize_test_mode_awaits_all_sql_models(monkeypatch):
9091
mocks[key].assert_awaited_once_with("testuser", "anonymous-abc123", _test=True)
9192

9293

94+
@pytest.mark.asyncio
95+
async def test_anonymize_sets_ip_only_around_infobase_delete(monkeypatch):
96+
# Infobase stamps the profile-clearing transaction with the thread-local web.ctx.ip;
97+
# it must not stay set across the awaits, where other requests share the event loop thread.
98+
account = OpenLibraryAccount(_key="/people/testuser")
99+
seen = {}
100+
web.ctx.ip = None
101+
monkeypatch.setattr(OpenLibraryAccount, "_delete_infobase_data", lambda self: seen.setdefault("delete", web.ctx.get("ip")))
102+
103+
async def fake_tables(self, test):
104+
seen["tables"] = web.ctx.get("ip")
105+
return {"new_username": "anonymous-abc123"}
106+
107+
monkeypatch.setattr(OpenLibraryAccount, "_anonymize_tables", fake_tables)
108+
109+
assert await account.anonymize("203.0.113.7") == {"new_username": "anonymous-abc123"}
110+
assert seen == {"delete": "203.0.113.7", "tables": None}
111+
assert web.ctx.get("ip") is None
112+
113+
93114
def test_anonymize_sync_deletes_infobase_data_on_calling_thread(monkeypatch):
94115
# Infobase saves read the request's thread-local web.ctx.ip, which the async bridge thread lacks.
95116
account = OpenLibraryAccount(_key="/people/testuser")

‎openlibrary/tests/fastapi/test_account.py‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,12 +5,25 @@
55
from unittest.mock import AsyncMock, MagicMock, patch
66
from urllib.parse import unquote
77

8+
import pytest
9+
import web
10+
811
from infogami import config
912
from openlibrary.core.auth import ExpiredTokenError, MissingKeyError
13+
from openlibrary.fastapi.shared.dependencies import get_client_ip
1014
from openlibrary.utils.request_context import RequestContextVars, req_context, site
1115

1216
_DEFAULT_HEADER = "LOW ak:sk"
1317
_SENTINEL = object()
18+
_CLIENT_IP = "203.0.113.7"
19+
20+
21+
@pytest.fixture(autouse=True)
22+
def _client_ip(fastapi_client):
23+
"""The bare test app has no middleware to set req_context, which get_client_ip reads."""
24+
fastapi_client.app.dependency_overrides[get_client_ip] = lambda: _CLIENT_IP
25+
yield
26+
fastapi_client.app.dependency_overrides.pop(get_client_ip, None)
1427

1528

1629
def _anonymize_post(
@@ -542,14 +555,54 @@ def test_login_forwards_s3_headers_to_audit(fastapi_client):
542555
assert kwargs["s3_secret_key"] == "sk"
543556

544557

558+
def _record_ctx_ip(result):
559+
"""An audit_accounts stand-in that records web.ctx.ip, which Infobase stamps on the transactions it writes."""
560+
seen = {}
561+
562+
def fake_audit(**kwargs):
563+
seen["ip"] = web.ctx.get("ip")
564+
return result
565+
566+
return fake_audit, seen
567+
568+
569+
def test_login_sets_client_ip_for_infobase_writes(fastapi_client):
570+
"""audit_accounts can create or activate the OL account; an empty ip made Postgres reject the transaction row."""
571+
fake_audit, seen = _record_ctx_ip({"ol_username": "testuser"})
572+
with (
573+
patch("openlibrary.fastapi.account.audit_accounts", side_effect=fake_audit),
574+
patch("openlibrary.fastapi.account.generate_login_code_for_user", return_value="token"),
575+
patch("openlibrary.fastapi.account.OpenLibraryAccount.get_by_email", return_value=None),
576+
):
577+
response = fastapi_client.post(
578+
"/account/login",
579+
data={"username": "testuser", "password": "password"},
580+
follow_redirects=False,
581+
)
582+
assert response.status_code == 303
583+
assert seen["ip"] == _CLIENT_IP
584+
585+
586+
def test_login_json_sets_client_ip_for_infobase_writes(fastapi_client):
587+
fake_audit, seen = _record_ctx_ip({"ol_username": "testuser"})
588+
with (
589+
patch("openlibrary.fastapi.account.audit_accounts", side_effect=fake_audit),
590+
patch("openlibrary.fastapi.account.generate_login_code_for_user", return_value="token"),
591+
patch("openlibrary.fastapi.account.OpenLibraryAccount.get_by_email", return_value=None),
592+
):
593+
response = fastapi_client.post("/account/login", json={"access": "ak", "secret": "sk"})
594+
assert response.status_code == 200
595+
assert seen["ip"] == _CLIENT_IP
596+
597+
545598
class TestAnonymizeAccount:
546599
def test_success(self, fastapi_client):
547600
resp, mock_account = _anonymize_post(fastapi_client)
548601

549602
assert resp.status_code == 200
550603
data = resp.json()
551604
assert data["new_username"] == "anonymous-abc123"
552-
mock_account.anonymize.assert_awaited_once_with(test=False)
605+
mock_account.anonymize.assert_awaited_once_with(_CLIENT_IP, test=False)
553606

554607
def test_success_with_test_mode(self, fastapi_client):
555608
resp, mock_account = _anonymize_post(
@@ -558,7 +611,7 @@ def test_success_with_test_mode(self, fastapi_client):
558611
)
559612

560613
assert resp.status_code == 200
561-
mock_account.anonymize.assert_awaited_once_with(test=True)
614+
mock_account.anonymize.assert_awaited_once_with(_CLIENT_IP, test=True)
562615

563616
def test_hmac_failure(self, fastapi_client):
564617
resp, _ = _anonymize_post(fastapi_client, hmac_return_value=False)

0 commit comments

Comments
 (0)