feat(accounts): require valid IA S3 keys on OTP service endpoints#12841
Conversation
There was a problem hiding this comment.
Pull request overview
This PR tightens access control for the legacy web.py OTP service endpoints (POST /account/otp/issue and POST /account/otp/redeem) by requiring callers to present valid IA S3 credentials via an Authorization: LOW access:secret header (intended to restrict OTP issuance/redemption to authorized Lenny instances).
Changes:
- Adds a module-level
_parse_low_auth_header()helper to parse theAuthorization: LOW ...header. - Validates parsed credentials via
InternetArchiveAccount.s3auth()at the start of both OTP endpoints. - Returns JSON error payloads for missing/malformed auth headers and invalid credentials.
…outages; add tests - _parse_low_auth_header(): strip both parts and raise ValueError if either is empty (catches 'LOW access:' or 'LOW :secret') - Extract _require_s3_auth() helper used by both OTP handlers; returns a distinct error when s3auth responds with a 5xx (auth_service_unavailable) vs invalid credentials (unauthorized) - Add TestOtpServiceS3Auth: tests for missing header, empty secret, invalid keys, 5xx outage, and valid keys proceeding to OTP issue/redeem Addresses Copilot review threads on #12841
…outages; add tests - _parse_low_auth_header(): strip both parts and raise ValueError if either is empty (catches 'LOW access:' or 'LOW :secret') - Extract _require_s3_auth() helper used by both OTP handlers; returns a distinct error when s3auth responds with a 5xx (auth_service_unavailable) vs invalid credentials (unauthorized) - Add TestOtpServiceS3Auth: tests for missing header, empty secret, invalid keys, 5xx outage, and valid keys proceeding to OTP issue/redeem Addresses Copilot review threads on #12841
be20661 to
78df9fc
Compare
|
Folded 1 pre-commit.ci bot commit into its parent ( Merge conflict still present in To reverse bot-fold: — Pierre, via PAM (Open Library's Project AI Manager) |
…outages; add tests - _parse_low_auth_header(): strip both parts and raise ValueError if either is empty (catches 'LOW access:' or 'LOW :secret') - Extract _require_s3_auth() helper used by both OTP handlers; returns a distinct error when s3auth responds with a 5xx (auth_service_unavailable) vs invalid credentials (unauthorized) - Add TestOtpServiceS3Auth: tests for missing header, empty secret, invalid keys, 5xx outage, and valid keys proceeding to OTP issue/redeem Addresses Copilot review threads on #12841
78df9fc to
387d0ea
Compare
|
Hi — I'm Pierre, an AI-assisted PR tidier running on behalf of @mekarpeles. I rebased this branch onto the latest What was done: rebased Why: keeps the branch mergeable and avoids drift from master. Safeguards: confirmed all 3 commits are authored by @mekarpeles; 0 unresolved review threads before pushing; used To reverse: run |
Adds Authorization: LOW <access>:<secret> validation to /account/otp/issue and /account/otp/redeem. Callers (Lenny instances) must supply valid IA S3 credentials — validated via s3auth — before OTP emails are issued or redeemed. Lenny already sends ol_auth_headers() with every OTP request; OL was previously ignoring them. This closes the gap so only Lenny nodes that have been configured with a linked IA/OL account can trigger OTP emails. Closes #12840
…outages; add tests - _parse_low_auth_header(): strip both parts and raise ValueError if either is empty (catches 'LOW access:' or 'LOW :secret') - Extract _require_s3_auth() helper used by both OTP handlers; returns a distinct error when s3auth responds with a 5xx (auth_service_unavailable) vs invalid credentials (unauthorized) - Add TestOtpServiceS3Auth: tests for missing header, empty secret, invalid keys, 5xx outage, and valid keys proceeding to OTP issue/redeem Addresses Copilot review threads on #12841
Adds direct unit tests for the new _parse_low_auth_header() helper (missing header, wrong prefix, no colon, empty parts, padded whitespace, colon-in-secret preservation) and a missing happy-path test for the redeem endpoint that mirrors the existing issue test.
b2bd697 to
292ea22
Compare
|
Code smell —
Suggested follow-up (not blocking this PR):
Leaving as a non-blocking note — the existing PR logic is correct as written. — PAM (Open Library's Project AI Manager), on behalf of @mekarpeles |
E2E Testing — auth gate + OTP flowThis comment was authored by Leno, via PAM (Open Library's Project AI Manager), on behalf of @mekarpeles. Setup
Required before running: add # conf/openlibrary.yml — add alongside ia_s3_auth_url
otp_seed: dev-otp-seed-for-e2e-testingAuth gate — rejection paths# No Authorization header → rejected
curl -s -X POST "http://localhost:8081/account/otp/issue" \
-H "X-Forwarded-For: 10.0.0.8" \
-d "email=test@example.com&ip=10.0.0.8&sendmail=false"
# {"error": "missing_or_invalid_authorization"}
# Wrong prefix → rejected
curl -s -X POST "http://localhost:8081/account/otp/issue" \
-H "Authorization: Bearer sometoken" \
-H "X-Forwarded-For: 10.0.0.8" \
-d "email=test@example.com&ip=10.0.0.8&sendmail=false"
# {"error": "missing_or_invalid_authorization"}
# Same rejections on /account/otp/redeem — verified ✓Happy path — issue + redeem# Step 1: issue OTP
curl -s -X POST "http://localhost:8081/account/otp/issue" \
-H "Authorization: LOW foo:foo" \
-H "X-Forwarded-For: 10.0.3.1" \
-d "email=test-e2e@example.com&ip=10.0.3.1&sendmail=false"
# {"success": "issued"}
# Step 2: compute OTP locally (same HMAC as OL uses)
python3 -c "
import hmac, hashlib, string, time
def shorten(d, n=6):
alph = string.digits + string.ascii_uppercase
n2, b = int.from_bytes(d, 'big'), ''
while n2 > 0:
n2, i = divmod(n2, 36); b = alph[i] + b
return b[:n].lower()
seed, sip, email, ip = 'dev-otp-seed-for-e2e-testing', '10.0.3.1', 'test-e2e@example.com', '10.0.3.1'
ts = int(time.time() // 60)
payload = f'{sip}:{email}:{ip}:{ts}'.encode()
print(shorten(hmac.new(seed.encode(), payload, hashlib.sha256).digest()))
"
# e.g. 5sp17k
# Step 3: redeem
curl -s -X POST "http://localhost:8081/account/otp/redeem" \
-H "Authorization: LOW foo:foo" \
-H "X-Forwarded-For: 10.0.3.1" \
-d "email=test-e2e@example.com&ip=10.0.3.1&otp=5sp17k"
# {"success": "redeemed"}Lenny integrationLenny's To point a local Lenny instance at a dev OL stack: OTP_SERVER=http://localhost:8081 OL_S3_ACCESS_KEY=foo OL_S3_SECRET_KEY=foo LENNY_LENDING_ENABLED=true ...Unit tests15/15 passing in Docker:
docker compose run --rm home python -m pytest openlibrary/plugins/upstream/tests/test_account.py::TestOtpServiceS3Auth openlibrary/plugins/upstream/tests/test_account.py::TestParseLowAuthHeader -vCI: all checks green (pre-commit.ci, python_tests, CodeQL). Known dev-only gaps (not PR bugs)
Automated test scriptAll of the above is reproducible with a standalone stdlib-only script (no dependencies beyond Python 3): https://gist.github.com/mekarpeles/c615ee72e807aa67d9f8df72359531ea python3 test_otp_auth_gate.py http://localhost:8080 dev-otp-seed-for-e2e-testing foo foo— Leno, via PAM (Open Library's Project AI Manager) |
OTP.generate() reads config.get('otp_seed') and crashes with
AttributeError if absent. Production has a real seed configured;
dev config was missing it entirely, breaking any local OTP testing.
Adds a placeholder value so the endpoint is exercisable in local
Docker. Documented in E2E test script (test_otp_auth_gate.py).
Summary
Closes #12840
The OTP service endpoints (
POST /account/otp/issueand/account/otp/redeem) are used by Lenny to implement patron passwordless login. Lenny already sendsAuthorization: LOW <access>:<secret>headers on every OTP call (viaol_auth_headers()), but OL was silently ignoring them.This PR adds validation: both endpoints now require a valid IA S3
Authorization: LOWheader before processing the request. Invalid or missing credentials return{"error": "unauthorized"}.Changes
openlibrary/plugins/upstream/account.py_parse_low_auth_header()helper — parsesAuthorization: LOW access:secretfrom the WSGI env (same pattern as the existingaccount_anonymize._parse_auth_header()instance method)otp_service_issue.POST()— validate S3 keys viaInternetArchiveAccount.s3auth()before issuing OTPotp_service_redeem.POST()— same validation before redeeming OTPWhy This Matters
Without this, any HTTP client can hit
/account/otp/issueand cause OL to send unsolicited OTP emails to arbitrary addresses. Requiring valid IA S3 keys ties OTP access to Lenny instances that have been explicitly linked to an IA account viamake ol-login.Companion PR
Test Plan
Authorizationheader →{"error": "missing_or_invalid_authorization"}{"error": "unauthorized"}/internal/fake/s3auth) acceptsfoo:foo, so existing local tests are unaffectedmake testpasses