Take auth/ whole from boilerplate 09e144d: the lockout claimed before the scrypt, APP_PASSWORD recovery closing every session, Starlette's cookie parser, the rightmost forwarded hop in the log, revoke_all on a password change, a 421 for a non-loopback Host on an open app, API tokens in auth_tokens behind Authorization: Bearer, and sockets closed with their credential

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
WolfandClaude Fable 5.1 committed 2026-10-27 11:51:21 +01:00
1 parent 83e965dfeb
commit 244e57ac29
19 files changed
+2288 -214

No files matched your search

+217 -8
View File
@@ -8,15 +8,19 @@ from __future__ import annotations
import logging
import sqlite3
from collections.abc import Callable
from concurrent.futures import ThreadPoolExecutor
from contextlib import closing
from urllib.parse import parse_qs, urlsplit
import pytest
from fastapi import Request
from fastapi.testclient import TestClient
from starlette.requests import HTTPConnection
from starlette.websockets import WebSocketDisconnect
from auth import AuthStore
from auth.middleware import OPEN
from auth.store import _GRACE
from auth.tests import PASSWORD, sign_in
from auth.tests.harness import build
@@ -27,7 +31,9 @@ def test_loopback_under_auto_needs_no_password(open_app: TestClient):
"""The default on a laptop: the machine's own login is already the door."""
assert open_app.get("/").status_code == 200
assert open_app.get("/api/thing").status_code == 200
with open_app.websocket_connect("/ws/jobs") as socket:
# The handshake names `testserver` unless told otherwise, and an unlocked
# app answers only to the names it is reached under.
with open_app.websocket_connect("/ws/jobs", headers={"host": "127.0.0.1"}) as socket:
assert socket.receive_json()["type"] == "jobs"
@@ -49,6 +55,49 @@ def test_never_is_open_off_loopback_too(make_client: Callable[..., TestClient]):
assert client.get("/api/thing").status_code == 200
# ------------------------------------------------ a proxy on the same machine
@pytest.mark.parametrize("header", [
{"x-forwarded-for": "203.0.113.9"}, {"x-forwarded-proto": "https"},
{"x-forwarded-host": "app.example.com"}, {"forwarded": "for=203.0.113.9"},
])
def test_an_open_app_refuses_what_a_proxy_forwarded(open_app: TestClient, header):
"""`auto` on loopback is open because only this machine can reach it. A
reverse proxy on the same machine makes that false while every request
still comes from 127.0.0.1; its headers are the only sign, so a request
carrying one is refused rather than served unlocked."""
refused = open_app.get("/api/thing", headers=header)
assert refused.status_code == 421
assert "auth.enabled: always" in refused.json()["detail"]
assert open_app.get("/api/thing").status_code == 200
def test_the_proxy_refusal_is_logged_once(open_app: TestClient, caplog):
with caplog.at_level(logging.WARNING):
for _ in range(3):
open_app.get("/api/thing", headers={"x-forwarded-for": "203.0.113.9"})
said = [r.getMessage() for r in caplog.records if "proxied" in r.getMessage()]
assert len(said) == 1 and "auth.enabled: always" in said[0]
def test_the_proxy_refusal_covers_the_socket(open_app: TestClient):
with pytest.raises(WebSocketDisconnect), \
open_app.websocket_connect("/ws/jobs", headers={"x-forwarded-for": "203.0.113.9"}):
pass
def test_a_locked_or_never_locked_app_serves_a_proxy(
locked: TestClient, make_client: Callable[..., TestClient]):
"""`always` has its own door and `never` is the operator's word: neither
is second-guessed from the headers."""
forwarded = {"x-forwarded-for": "203.0.113.9", "x-forwarded-proto": "https"}
assert locked.post("/login", json={"password": PASSWORD},
headers=forwarded).status_code == 200
assert locked.get("/api/thing", headers=forwarded).status_code == 200
never = make_client(enabled="never", host="127.0.0.1")
assert never.get("/api/thing", headers=forwarded).status_code == 200
# -------------------------------------------------------- the locked door
def test_everything_is_shut(locked: TestClient):
@@ -150,6 +199,21 @@ def test_a_wrong_password_is_refused(locked: TestClient):
assert locked.get("/api/thing").status_code == 401
def test_wrong_guesses_in_parallel_meet_the_lockout(locked: TestClient):
"""The lockout was read before the derivation and the failure written
after it, so thirty wrong guesses at once all found the door open and all
got a 401. Each is claimed before it is derived now: the first `_GRACE`
are looked at and the rest are told to wait."""
def guess(_: int) -> int:
# A client per thread, so no two share a cookie jar or a portal.
return sign_in(TestClient(locked.app), "nope").status_code
with ThreadPoolExecutor(max_workers=30) as pool:
said = list(pool.map(guess, range(30)))
assert said.count(401) == _GRACE, said
assert said.count(429) == 30 - _GRACE, said
def test_signing_in_opens_everything(locked: TestClient):
assert sign_in(locked).status_code == 200
assert locked.get("/api/thing").status_code == 200
@@ -352,6 +416,84 @@ def test_the_password_change_is_behind_the_same_lockout(signed_in: TestClient):
assert sign_in(signed_in).status_code == 429
def test_an_app_route_asks_for_the_password_through_the_package(
signed_in: TestClient, caplog):
"""A route outside the package that must take the current password (a
restore, whose body is the database file) calls `confirm_password`
rather than writing its own check, so it is counted and gated like the
front door."""
from auth import confirm_password, warn
@signed_in.app.post("/api/restore")
def restore(request: Request) -> dict[str, bool]:
confirm_password(request, request.headers.get("x-current-password", ""))
return {"ok": True}
with caplog.at_level(logging.WARNING):
wrong = signed_in.post("/api/restore", headers={"x-current-password": "nope"})
assert wrong.status_code == 403
assert "wrong current password from testclient" in caplog.text
assert {r.name for r in caplog.records if "from testclient" in r.getMessage()} == {
"auth.middleware"}
assert signed_in.post("/api/restore",
headers={"x-current-password": PASSWORD}).status_code == 200
for _ in range(5):
signed_in.post("/api/restore", headers={"x-current-password": "nope"})
refused = signed_in.post("/api/restore", headers={"x-current-password": PASSWORD})
assert refused.status_code == 429 and refused.headers["retry-after"]
assert sign_in(signed_in).status_code == 429
caplog.clear()
with caplog.at_level(logging.WARNING):
warn(HTTPConnection({"type": "http", "client": ("203.0.113.9", 1), "headers": []}),
"restore refused")
assert "restore refused from 203.0.113.9" in caplog.text
def test_a_file_route_without_the_header_is_refused_and_counts_nothing(
signed_in: TestClient, caplog):
"""A restore's body is the database, so the password rides in a header,
and a session alone is not enough: the restored file brings its own hash.
A missing header is a missing field and not a guess, so five of them leave
the right password working, at this route and at the front door."""
with caplog.at_level(logging.WARNING):
missing = signed_in.post("/thing/replace")
empty = signed_in.post("/thing/replace", headers={"x-current-password": ""})
for refused in (missing, empty):
assert refused.status_code == 403
assert "X-Current-Password" in refused.json()["detail"]
assert "no current password for POST /thing/replace from testclient" in caplog.text
for _ in range(5):
assert signed_in.post("/thing/replace").status_code == 403
assert signed_in.post("/thing/replace",
headers={"x-current-password": PASSWORD}).status_code == 200
assert sign_in(signed_in).status_code == 200
def test_a_file_route_counts_a_wrong_header(signed_in: TestClient, caplog):
with caplog.at_level(logging.WARNING):
wrong = signed_in.post("/thing/replace", headers={"x-current-password": "nope"})
assert wrong.status_code == 403
assert "wrong current password from testclient" in caplog.text
for _ in range(4):
signed_in.post("/thing/replace", headers={"x-current-password": "nope"})
refused = signed_in.post("/thing/replace", headers={"x-current-password": PASSWORD})
assert refused.status_code == 429 and refused.headers["retry-after"]
assert sign_in(signed_in).status_code == 429
def test_a_file_route_takes_the_right_header(signed_in: TestClient):
right = signed_in.post("/thing/replace", headers={"x-current-password": PASSWORD})
assert right.status_code == 200 and right.json() == {"ok": True}
def test_a_file_route_on_an_app_with_no_password_needs_no_header(open_app: TestClient):
"""The laptop that was never locked has nothing to confirm."""
assert open_app.post("/thing/replace").status_code == 200
# ------------------------------------------------------- the bootstrap
def test_a_generated_password_is_printed_once(
@@ -429,6 +571,51 @@ def test_the_environment_variable_is_a_setting(
assert client.get("/api/account").json()["pinned_by"] == "OTHER_PASSWORD"
def test_recovery_through_the_environment_signs_everyone_out(
tmp_path, monkeypatch, caplog):
"""`APP_PASSWORD` is the way back in when the password is lost, and the
reason it is lost may be that someone else has it and is signed in. So a
pinned password that replaces the stored one closes every session. Tokens
and passkeys stay, since the environment cannot tell whose they are, and
the log says how many so the owner knows to review them."""
db = tmp_path / "recovered.db"
store = AuthStore(db)
store.set_password("the-one-the-intruder-has")
intruder = store.open_session("intruder", 30)
_, token = store.create_token("intruder's cron", None)
store.add_passkey(b"cred", b"key", 0, "", "intruder's key")
monkeypatch.setenv("APP_PASSWORD", PASSWORD)
with caplog.at_level(logging.WARNING), \
TestClient(build(db, enabled="always"), follow_redirects=False) as client:
assert client.get("/api/thing",
headers={"cookie": f"app_session={intruder}"}).status_code == 401
assert client.get("/api/thing",
headers={"authorization": f"Bearer {token}"}).status_code == 200
assert sign_in(client).status_code == 200
mine = client.cookies["app_session"]
said = [r for r in caplog.records if "password reset from APP_PASSWORD" in r.getMessage()]
assert len(said) == 1 and said[0].levelno == logging.WARNING
assert "closed 1 sessions; 1 API tokens and 1 passkeys remain" in said[0].getMessage()
# A restart with the same variable matches and closes nothing.
caplog.clear()
with caplog.at_level(logging.WARNING), TestClient(build(db, enabled="always")) as client:
assert client.get("/api/thing",
headers={"cookie": f"app_session={mine}"}).status_code == 200
assert "password reset" not in caplog.text
def test_a_first_password_from_the_environment_is_not_a_recovery(
make_client: Callable[..., TestClient], monkeypatch, caplog):
monkeypatch.setenv("APP_PASSWORD", PASSWORD)
with caplog.at_level(logging.INFO):
client = make_client(enabled="always", password=None)
assert "password set from APP_PASSWORD" in caplog.text
assert "password reset" not in caplog.text
assert sign_in(client).status_code == 200
def test_expired_sessions_are_purged_at_startup(tmp_path):
"""Housekeeping, not a security boundary -- `touch` already refuses an
expired row. Without it the table grows forever."""
@@ -452,8 +639,8 @@ def test_a_refused_login_says_who_it_was(locked: TestClient, caplog):
nothing anywhere knows it happened."""
with caplog.at_level(logging.WARNING):
assert sign_in(locked, "nope").status_code == 401
# The logger is `auth.router`, so the line already says which package this
# came from and the message does not say it again.
# The logger is `auth.middleware`, so the line already says which package
# this came from and the message does not say it again.
assert "wrong password from testclient" in caplog.text
assert "auth: wrong password" not in caplog.text
@@ -465,15 +652,37 @@ def test_a_refused_password_change_says_so_too(signed_in: TestClient, caplog):
assert "wrong current password" in caplog.text
def test_the_log_prefers_the_address_the_proxy_passed_on(locked: TestClient, caplog):
def test_the_log_names_the_hop_the_proxy_added(locked: TestClient, caplog):
"""Behind a proxy the peer is a container on its own network and says
nothing about who is at the other end. Both are written, because the header
is only as good as whoever sent it -- which is also why nothing is decided
from it."""
nothing about who is at the other end. The proxy appends the address it
accepted the connection from to whatever `X-Forwarded-For` the caller
sent, so the rightmost hop is the proxy's word and every hop left of it
the caller's: logging the first let an attacker name whom fail2ban bans.
Both the hop and the peer are written, because the header is only as good
as whoever set it -- which is also why nothing is decided from it."""
with caplog.at_level(logging.WARNING):
locked.post("/login", json={"password": "nope"},
headers={"x-forwarded-for": "203.0.113.9, 10.9.9.9"})
assert "203.0.113.9 via testclient" in caplog.text
(said,) = [r.getMessage() for r in caplog.records if r.name == "auth.middleware"]
assert said == "wrong password from 10.9.9.9 via testclient"
assert "203.0.113.9" not in caplog.text
def test_the_log_falls_back_to_x_real_ip(locked: TestClient, caplog):
"""A proxy that sets `X-Real-IP` sets it outright. Read only when there is
no `X-Forwarded-For`, which a proxy that sends both keeps current too."""
with caplog.at_level(logging.WARNING):
locked.post("/login", json={"password": "nope"},
headers={"x-real-ip": "198.51.100.7"})
locked.post("/login", json={"password": "nope"},
headers={"x-real-ip": "198.51.100.7",
"x-forwarded-for": "203.0.113.9, 192.0.2.1"})
locked.post("/login", json={"password": "nope"},
headers={"x-forwarded-for": " ", "x-real-ip": "198.51.100.7"})
said = [r.getMessage() for r in caplog.records if r.name == "auth.middleware"]
assert said == ["wrong password from 198.51.100.7 via testclient",
"wrong password from 192.0.2.1 via testclient",
"wrong password from 198.51.100.7 via testclient"]
def test_a_forwarded_address_cannot_write_the_log_itself(locked: TestClient, caplog):