Validate admin config and registration input, and log config changes
fee_address was the dangerous one (B-05). PUT /admin/config assigned whatever it
was given, and a well-formed address from another chain (bc1...) parses fine as a
witness program — so every round's 30% commission would be signed and broadcast
to a script nobody holds the key for. A malformed one instead wedged the payout
with an unhandled EmbitError. It now has to pass is_valid_plm_address, the same
check user withdrawals already had. Numeric fields got bounds too:
fee_rate_sat_vb=0 produces transactions no node relays, which stalls bets,
payouts and withdrawals alike, and round_duration_seconds=0 expires a round the
instant it opens.
Config changes are audit-logged (B-10). /pause and /resume were logged but a
config edit wasn't, so the most sensitive setting in the system could be changed
without leaving any trace — contradicting CLAUDE.md, which says audit_log records
what changed. The entry carries a before/after diff per field, computed before
assignment, and no-op updates write nothing. `paused` was removed from
_CONFIG_FIELDS so the maintenance switch has exactly one audited path; it stays
in the response model.
Admin token comparison is constant-time (B-14), with the empty-token check kept
*ahead* of it: compare_digest("", "") returns True, so the obvious ordering would
have opened the panel on any instance without an ADMIN_TOKEN.
Registration input (B-12). It accepted an empty username and a one-character
password while /users/me/change-password demanded 8 — an odd place to be lenient
on a custodial system holding real funds. MIN_PASSWORD_LENGTH moved to
auth/security.py so both share it, and the username is constrained to 3-32 chars
of [A-Za-z0-9_.-]. The IntegrityError handler also distinguishes a username
collision (answers username_taken) from a derivation-index one (retries): a
concurrent duplicate username used to be retried five times and then reported as
derivation_index_conflict, which told the user the wrong thing.
verify_password (B-13) catches VerificationError and InvalidHashError, not just
VerifyMismatchError, so an unparseable stored hash reads as "wrong password"
instead of a 500 — logged as an error, since that one is a data problem.
guida-admin.md gains a table of the audit events worth watching, including
payout_failed, which needs manual intervention.
Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
daf66fd6bc
commit
85dce221c5
8 files changed
+229
-30
No files matched your search
@@ -4,6 +4,11 @@ from httpx import ASGITransport, AsyncClient
|
||||
|
||||
from app.config import settings
|
||||
|
||||
# A real PLM bech32 address: PUT /admin/config now validates fee_address, since a
|
||||
# foreign-chain address there would send every round's commission to a script
|
||||
# nobody can spend (B-05).
|
||||
_VALID_FEE_ADDRESS = "plm1q0xcqpzrky6eff2g52qdye53xkk9jxkvraxkkwd"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def client(monkeypatch, tmp_path):
|
||||
@@ -70,15 +75,15 @@ async def test_admin_reads_and_updates_config(client):
|
||||
assert resp.json()["fee_address"] == ""
|
||||
|
||||
resp = await client.put(
|
||||
"/admin/config", headers=headers, json={"fee_address": "plm1qfeeaddress", "bet_amount_sats": 500_000_000}
|
||||
"/admin/config", headers=headers, json={"fee_address": _VALID_FEE_ADDRESS, "bet_amount_sats": 500_000_000}
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
body = resp.json()
|
||||
assert body["fee_address"] == "plm1qfeeaddress"
|
||||
assert body["fee_address"] == _VALID_FEE_ADDRESS
|
||||
assert body["bet_amount_sats"] == 500_000_000
|
||||
|
||||
resp = await client.get("/admin/config", headers=headers)
|
||||
assert resp.json()["fee_address"] == "plm1qfeeaddress"
|
||||
assert resp.json()["fee_address"] == _VALID_FEE_ADDRESS
|
||||
|
||||
|
||||
async def test_admin_can_pause_and_resume_the_lottery(client):
|
||||
@@ -211,3 +216,60 @@ async def test_admin_reset_password_404_for_unknown_user(client):
|
||||
headers = {"X-Admin-Token": "test-admin-token"}
|
||||
resp = await client.post("/admin/users/999/reset-password", headers=headers)
|
||||
assert resp.status_code == 404
|
||||
|
||||
|
||||
async def test_config_update_is_audit_logged(client):
|
||||
"""B-10: /pause and /resume were logged but a config change wasn't, so the most
|
||||
sensitive setting in the system — fee_address, where 30% of every pool goes —
|
||||
could be changed without leaving any trace."""
|
||||
headers = {"X-Admin-Token": "test-admin-token"}
|
||||
await client.put("/admin/config", headers=headers, json={"fee_address": _VALID_FEE_ADDRESS})
|
||||
|
||||
resp = await client.get("/admin/audit-log", headers=headers)
|
||||
entries = [e for e in resp.json() if e["event_type"] == "config_updated"]
|
||||
assert len(entries) == 1
|
||||
assert entries[0]["payload"]["fee_address"] == {"from": "", "to": _VALID_FEE_ADDRESS}
|
||||
|
||||
|
||||
async def test_config_update_without_changes_logs_nothing(client):
|
||||
headers = {"X-Admin-Token": "test-admin-token"}
|
||||
await client.put("/admin/config", headers=headers, json={"fee_address": _VALID_FEE_ADDRESS})
|
||||
await client.put("/admin/config", headers=headers, json={"fee_address": _VALID_FEE_ADDRESS})
|
||||
|
||||
resp = await client.get("/admin/audit-log", headers=headers)
|
||||
assert len([e for e in resp.json() if e["event_type"] == "config_updated"]) == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
{"fee_address": "bc1qw508d6qejxtdg4y5r3zarvary0c5xw7kv8f3t4"}, # valid bech32, wrong chain
|
||||
{"fee_address": "plm1qbogus"}, # right HRP, broken checksum
|
||||
{"fee_address": "garbage"},
|
||||
{"fee_rate_sat_vb": 0}, # fee-less txs are never relayed: everything would stall
|
||||
{"round_duration_seconds": 0}, # a round that expires the instant it opens
|
||||
{"bet_amount_sats": -1},
|
||||
{"rbf_timeout_seconds": 1},
|
||||
],
|
||||
)
|
||||
async def test_config_rejects_unusable_values(client, payload):
|
||||
"""B-05: every one of these was accepted before. The bc1 case is the worst — it
|
||||
parses as a valid witness program, so each round's commission would be broadcast
|
||||
to a script nobody holds the key for."""
|
||||
headers = {"X-Admin-Token": "test-admin-token"}
|
||||
resp = await client.put("/admin/config", headers=headers, json=payload)
|
||||
assert resp.status_code == 422
|
||||
|
||||
# and nothing was written
|
||||
current = (await client.get("/admin/config", headers=headers)).json()
|
||||
for field, value in payload.items():
|
||||
assert current[field] != value
|
||||
|
||||
|
||||
async def test_pause_cannot_be_toggled_through_the_config_endpoint(client):
|
||||
"""B-10: `paused` used to be settable here, bypassing the audit-logged
|
||||
pause/resume endpoints."""
|
||||
headers = {"X-Admin-Token": "test-admin-token"}
|
||||
resp = await client.put("/admin/config", headers=headers, json={"paused": True})
|
||||
assert resp.status_code in (200, 422) # ignored or refused, but never applied
|
||||
assert (await client.get("/admin/config", headers=headers)).json()["paused"] is False
|
||||
@@ -11,3 +11,21 @@ def test_jwt_roundtrip(monkeypatch):
|
||||
monkeypatch.setattr(security.settings, "jwt_secret", "test-secret")
|
||||
token = security.create_access_token(user_id=42)
|
||||
assert security.decode_access_token(token) == 42
|
||||
|
||||
|
||||
def test_verify_password_returns_false_for_an_unparseable_hash():
|
||||
"""B-13: only VerifyMismatchError was caught, so a corrupted stored hash raised
|
||||
InvalidHashError and became an unhandled 500 on the login endpoint instead of a
|
||||
plain "wrong credentials" 401."""
|
||||
from app.auth.security import verify_password
|
||||
|
||||
assert verify_password("whatever", "not-an-argon2-hash") is False
|
||||
assert verify_password("whatever", "") is False
|
||||
|
||||
|
||||
def test_verify_password_still_rejects_a_wrong_password():
|
||||
from app.auth.security import hash_password, verify_password
|
||||
|
||||
stored = hash_password("correct-horse-battery")
|
||||
assert verify_password("correct-horse-battery", stored) is True
|
||||
assert verify_password("wrong", stored) is False
|
||||
@@ -45,7 +45,7 @@ async def client(monkeypatch, tmp_path):
|
||||
app = FastAPI()
|
||||
app.include_router(auth_router)
|
||||
app.include_router(users_router)
|
||||
app.state.electrum_listener = ElectrumListener(lambda: None, db_base.AsyncSessionLocal)
|
||||
app.state.electrum_listener = ElectrumListener(lambda endpoint: None, db_base.AsyncSessionLocal)
|
||||
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
||||
@@ -108,3 +108,26 @@ async def test_change_password_requires_auth(client):
|
||||
json={"current_password": "x", "new_password": "brand-new-password"},
|
||||
)
|
||||
assert resp.status_code in (401, 403)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"payload",
|
||||
[
|
||||
{"username": "", "password": "longenough1"},
|
||||
{"username": "ab", "password": "longenough1"}, # under 3 chars
|
||||
{"username": "bad user!", "password": "longenough1"}, # disallowed characters
|
||||
{"username": "validname", "password": "short"}, # under MIN_PASSWORD_LENGTH
|
||||
{"username": "validname", "password": ""},
|
||||
],
|
||||
)
|
||||
async def test_register_rejects_weak_credentials(client, payload):
|
||||
"""B-12: registration accepted an empty username and a one-character password,
|
||||
while /users/me/change-password demanded 8 — an odd place to be lenient on a
|
||||
custodial system holding real funds."""
|
||||
resp = await client.post("/auth/register", json=payload)
|
||||
assert resp.status_code == 422
|
||||
|
||||
|
||||
async def test_register_accepts_valid_credentials(client):
|
||||
resp = await client.post("/auth/register", json={"username": "goodname", "password": "longenough1"})
|
||||
assert resp.status_code == 201
|
||||
Reference in new issue
Block a user