Files
jobboard/auth/tests/test_door.py
T

699 lines
32 KiB
Python

"""The door: who gets past it, what a refusal looks like, and the cookie.
uv run pytest auth/tests/test_door.py -q
"""
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
# ---------------------------------------------------------- the open door
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
# 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"
def test_the_account_says_it_is_open(open_app: TestClient):
assert open_app.get("/api/account").json()["locked"] is False
def test_the_login_page_bounces_when_there_is_no_door(open_app: TestClient):
"""A form that would replace a session you do not need."""
page = open_app.get("/login")
assert page.status_code == 303
assert sign_in(open_app).status_code == 400
def test_never_is_open_off_loopback_too(make_client: Callable[..., TestClient]):
"""`never` means exactly what it says: something else is doing the
authentication, and this is not second-guessing it."""
client = make_client(enabled="never", host="0.0.0.0")
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):
"""Deny by default: the API, the page, and the one worth naming --
`/openapi.json` is every path, every payload shape and every field name of
the application, handed to whoever asks. It is a GET of something that is
not an API path, so the refusal is the redirect a browser wants."""
assert locked.get("/api/thing").status_code == 401
assert locked.get("/deep/page").status_code == 303
assert locked.get("/openapi.json").status_code == 303
def test_a_page_is_redirected_and_an_api_call_is_not(locked: TestClient):
"""A browser gets sent to the form; a fetch gets a 401 it can act on --
a login page arriving where JSON was asked for is a 200 full of HTML."""
page = locked.get("/")
assert page.status_code == 303
assert page.headers["location"] == "/login"
refused = locked.get("/api/thing")
assert refused.status_code == 401
assert refused.json() == {"detail": "Not signed in"}
assert "application/json" in refused.headers["content-type"]
def test_a_deep_link_survives_the_login_intact(locked: TestClient):
"""`next` is carried in a query string, so a path holding a `&` or a `%`
has to be escaped on the way to the login page -- or it arrives truncated,
or as a different path than the one that was asked for."""
sent = locked.get("/items/a&b%25c")
assert sent.status_code == 303
where = sent.headers["location"]
assert where.startswith("/login?next=")
# What `URLSearchParams` on the login page will read out of that query.
target = parse_qs(urlsplit(where).query)["next"][0]
assert target == "/items/a&b%c"
assert sign_in(locked, next=target).json()["next"] == "/items/a&b%c"
def test_the_open_list_is_the_four_doors_it_says_it_is(locked: TestClient):
"""Deny-by-default is only as good as the list of exceptions is short, so
the list is asserted rather than trusted, and an entry has to be argued for
here before it ships. Four: `/login` and the passkey ceremony under
`/login/`, because there is no other way in; `/_auth/`, which is the two
scripts those pages are; and `/health`, because a proxy's probe has no
session to offer and a healthcheck that needs one is a healthcheck that
reports the login page."""
assert OPEN == ("/login", "/login/", "/_auth/", "/health")
def test_an_open_name_is_matched_whole_and_a_slash_is_a_prefix(locked: TestClient):
"""`/health` does not open `/healthz`, and `/login` does not open
`/loginx` -- both of which are real routes here, so this is a refusal and
not a 404 wearing one."""
assert locked.get("/health").status_code == 200
assert locked.get("/static/app.css").status_code == 200
assert locked.get("/_auth/account.js").status_code == 200
assert locked.post("/login/passkey/options").status_code != 401
assert locked.get("/healthz").status_code == 303
assert locked.get("/loginx").status_code == 303
def test_the_login_page_draws_no_passkey_button_without_a_passkey(locked: TestClient):
"""Two halves, and the second one is why this test exists at all.
The flag is substituted false, so the script never unhides the button --
and the button is `hidden`, which is a browser default of `display: none`
that *any* class rule carrying a `display` overrides. `.orpass` sets
`display: grid`, so the first version of this page offered "Use a passkey"
on an app with no passkeys, and pressing it 404s.
"""
page = locked.get("/login").text
assert "const passkeysOffered = false;" in page
assert "[hidden] { display: none !important; }" in page
def test_a_query_string_cannot_widen_the_open_list(locked: TestClient):
assert locked.get("/api/thing?next=/health").status_code == 401
def test_the_websocket_is_shut_too(locked: TestClient):
"""The reason this is a middleware and not a dependency. A route
dependency would not cover the socket, and the socket is where an app
streams the state of everything it is doing."""
with pytest.raises(WebSocketDisconnect), locked.websocket_connect("/ws/jobs"):
pass
def test_the_websocket_opens_with_a_session(locked: TestClient):
sign_in(locked)
with locked.websocket_connect("/ws/jobs") as socket:
assert socket.receive_json()["type"] == "jobs"
def test_a_wrong_password_is_refused(locked: TestClient):
assert sign_in(locked, "nope").status_code == 401
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
assert locked.get("/").status_code == 200
def test_logout_ends_the_session(signed_in: TestClient):
assert signed_in.post("/logout").status_code == 200
assert signed_in.get("/api/thing").status_code == 401
def test_next_stays_inside_the_app(locked: TestClient):
r"""An open redirect is a real login page, a real sign-in, and someone
else's site afterwards.
The backslash is the one that gets through: a browser parses `/\evil.com`
as `//evil.com`, and the address bar hands `%5C` to the page already
decoded -- so neither is the local path a leading-slash test reads them as.
"""
for target in ("//evil.example.com/", "/\\evil.example.com",
"/%5Cevil.example.com", "https://evil.example.com",
"\\\\evil.example.com", "/\t/evil.example.com"):
assert sign_in(locked, next=target).json()["next"] == "/", target
assert sign_in(locked, next="/deep/page?x=1").json()["next"] == "/deep/page?x=1"
# ------------------------------------------------------------- the cookie
def cookies(response) -> list[str]:
"""The `Set-Cookie` headers, read off the wire.
Off the wire and not out of the jar, because the jar is a browser and does
the very thing under test: httpx refuses to store a `__Host-` cookie that
arrived over plain HTTP, so asking it what it kept cannot tell a correct
header apart from one it threw away.
"""
return [value.lower() for value in response.headers.get_list("set-cookie")]
def test_the_cookie_is_httponly_lax_and_not_secure_over_http(locked: TestClient):
"""An XSS must not be able to read it, another origin must not be able to
make the browser send it -- and a Secure cookie set over plain HTTP is one
the browser never sends back, which is an app nobody can sign in to."""
(sent,) = cookies(sign_in(locked))
assert sent.startswith("app_session=")
assert "httponly" in sent
assert "samesite=lax" in sent
assert "path=/" in sent
assert "secure" not in sent
assert "__host-" not in sent
def test_secure_cookie_always_sends_the_host_prefixed_name(
make_client: Callable[..., TestClient]):
"""`secure_cookie: always` is the setting for a proxy that terminates TLS,
where the app sees plain HTTP and `auto` would read as "no".
Both halves have to move together. `__Host-` is a promise to the browser
that the cookie is Secure, path `/` and carries no Domain, and a browser
silently drops one that is not -- which presents as a login that appears to
work and lands you back on the login page, with nothing in any log.
"""
client = make_client(enabled="always", secure_cookie="always")
(sent,) = cookies(sign_in(client))
assert sent.startswith("__host-app_session=")
assert "secure" in sent
assert "path=/" in sent
assert "domain=" not in sent
def test_a_renamed_cookie_is_used_under_both_names(
make_client: Callable[..., TestClient]):
"""The name is a setting because two apps from this boilerplate on one
hostname would otherwise share a cookie and sign each other out."""
client = make_client(enabled="always", cookie="other_session")
(sent,) = cookies(sign_in(client))
assert sent.startswith("other_session=")
assert client.get("/api/thing").status_code == 200
assert {v.split("=")[0] for v in cookies(client.post("/logout"))} == {
"other_session", "__host-other_session"}
def test_logout_clears_both_names(signed_in: TestClient):
"""Which name was set depends on `secure_cookie` and on the scheme the
login happened over, and neither is known here. Clearing only the one this
request would have set leaves the other in the browser, still offered on
every request -- a signed-out session the door goes on opening for."""
cleared = signed_in.post("/logout")
sent = cookies(cleared)
assert {value.split("=")[0] for value in sent} == {
"app_session", "__host-app_session"}
for value in sent:
assert "max-age=0" in value or "expires=thu, 01 jan 1970" in value
# ------------------------------------------------------------ the account
def test_the_account_lists_this_session(signed_in: TestClient):
account = signed_in.get("/api/account").json()
assert account["locked"] is True
assert account["pinned"] is False
assert sum(s["current"] for s in account["sessions"]) == 1
assert account["password_set_at"]
def test_revoked_elsewhere_means_locked_out_here(signed_in: TestClient):
"""The reason sessions are rows rather than signed tokens: a token that
carries its own claim cannot be taken back."""
account = signed_in.get("/api/account").json()
mine = next(s["id"] for s in account["sessions"] if s["current"])
assert signed_in.delete(f"/api/account/sessions/{mine}").status_code == 200
assert signed_in.get("/api/thing").status_code == 401
assert signed_in.delete(f"/api/account/sessions/{mine}").status_code == 401
def test_closing_the_others_keeps_this_one(signed_in: TestClient):
other = TestClient(signed_in.app, follow_redirects=False)
sign_in(other)
assert other.get("/api/thing").status_code == 200
closed = signed_in.post("/api/account/sessions/close")
assert closed.json() == {"signed_out": 1}
assert signed_in.get("/api/thing").status_code == 200
assert other.get("/api/thing").status_code == 401
def test_changing_the_password_needs_the_old_one(signed_in: TestClient):
bad = signed_in.post("/api/account/password",
json={"current": "wrong", "new": "a-much-longer-one"})
assert bad.status_code == 403
def test_the_first_password_is_set_without_a_current_one(open_app: TestClient):
"""The laptop before it is ever deployed: no password has ever been set,
and the account screen is where you set one. Asking for the current
password there is a field with no right answer, and the form could only
ever be refused -- which is what it did until this test existed. The app
that has a door never reaches this branch: `auth.bootstrap` gives a locked
app a password at startup, so there is always one to prove."""
assert open_app.get("/api/account").json()["password_set_at"] == ""
set_it = open_app.post("/api/account/password",
json={"current": "", "new": "a-much-longer-one"})
assert set_it.status_code == 200
assert open_app.get("/api/account").json()["password_set_at"]
# And the second change asks for the first, the way it always did.
again = open_app.post("/api/account/password",
json={"current": "", "new": "another-long-one"})
assert again.status_code == 403
def test_a_short_new_password_is_refused(signed_in: TestClient):
short = signed_in.post("/api/account/password",
json={"current": PASSWORD, "new": "short"})
assert short.status_code == 400
assert "8 characters" in short.json()["detail"]
def test_changing_it_keeps_you_in_and_signs_others_out(signed_in: TestClient):
"""If the reason you are changing the password is that someone may have it,
leaving their session open makes the change ceremonial."""
other = TestClient(signed_in.app, follow_redirects=False)
sign_in(other)
changed = signed_in.post("/api/account/password",
json={"current": PASSWORD, "new": "a-much-longer-one"})
assert changed.status_code == 200
assert changed.json()["signed_out"] == 1
assert signed_in.get("/api/thing").status_code == 200
assert other.get("/api/thing").status_code == 401
signed_in.post("/logout")
assert sign_in(signed_in).status_code == 401
assert sign_in(signed_in, "a-much-longer-one").status_code == 200
def test_the_password_change_is_behind_the_same_lockout(signed_in: TestClient):
"""A session is not an unlimited number of guesses at the password.
`current` is the password, asked for at a second door, and a borrowed
unlocked laptop is the exact situation that field exists for -- so it is
counted and gated like the first door, or the lockout only ever covered the
half an attacker would not bother with.
"""
before = signed_in.get("/api/account").json()["password_set_at"]
for _ in range(5):
wrong = signed_in.post("/api/account/password",
json={"current": "nope", "new": "a-much-longer-one"})
assert wrong.status_code == 403
# The *right* current password now, which must not even be looked at.
refused = signed_in.post("/api/account/password",
json={"current": PASSWORD, "new": "a-much-longer-one"})
assert refused.status_code == 429
assert "Try again" in refused.json()["detail"]
assert refused.headers["retry-after"]
assert signed_in.get("/api/account").json()["password_set_at"] == before
# One credential, one counter: guessing at the account screen locks the
# front door too, which is the whole reason it is worth guessing there.
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(
make_client: Callable[..., TestClient], caplog):
"""A locked app with no password invents one and prints it, rather than
starting with the door open or refusing to start at all."""
with caplog.at_level(logging.WARNING):
client = make_client(enabled="always", password=None)
printed = generated(caplog.text)
assert sign_in(client, printed).status_code == 200
def generated(text: str) -> str:
"""Pull the generated password back out of the startup banner. ASCII, so
this reads it the way a person reads it off `docker compose logs`."""
lines = [line.strip() for line in text.splitlines()]
marker = next(i for i, line in enumerate(lines) if "here is one" in line)
return next(line for line in lines[marker + 1:] if line and "-----" not in line)
def test_the_environment_pins_the_password(
make_client: Callable[..., TestClient], monkeypatch):
"""`APP_PASSWORD` is the way back in when a login is lost, and it can only
be that if it wins over what is stored: the case is a password changed in
the browser months ago, the variable set to something else, and a restart.
"""
monkeypatch.setenv("APP_PASSWORD", "the-one-from-the-environment")
client = make_client(enabled="always", password="the-one-set-in-the-browser")
assert sign_in(client, "the-one-set-in-the-browser").status_code == 401
assert sign_in(client, "the-one-from-the-environment").status_code == 200
account = client.get("/api/account").json()
assert account["pinned"] is True
# Named, so the screen can say which variable rather than leaving someone
# to go and find out.
assert account["pinned_by"] == "APP_PASSWORD"
def test_a_pinned_password_cannot_be_changed_from_the_browser(
make_client: Callable[..., TestClient], monkeypatch):
"""The variable is authoritative while it is set, so the screen that would
silently stop applying says so instead."""
monkeypatch.setenv("APP_PASSWORD", PASSWORD)
client = make_client(enabled="always", password=None)
sign_in(client)
refused = client.post("/api/account/password",
json={"current": PASSWORD, "new": "a-much-longer-one"})
assert refused.status_code == 409
assert "APP_PASSWORD" in refused.json()["detail"]
def test_a_pinned_password_that_matches_is_not_written_again(monkeypatch, tmp_path):
"""Re-deriving on every start would make "password last changed" mean "last
restarted", which answers a different question than the one it is asked. A
restart is not a password change."""
monkeypatch.setenv("APP_PASSWORD", PASSWORD)
db = tmp_path / "pinned.db"
with TestClient(build(db, enabled="always")):
pass
first = AuthStore(db).changed_at()
assert first, "the pinned password was never derived at all"
with TestClient(build(db, enabled="always"), follow_redirects=False) as client:
assert sign_in(client).status_code == 200
assert AuthStore(db).changed_at() == first, "a restart rewrote the hash"
def test_the_environment_variable_is_a_setting(
make_client: Callable[..., TestClient], monkeypatch):
"""`auth/` is copied into projects that are not called `app`."""
monkeypatch.setenv("OTHER_PASSWORD", "from-the-other-variable")
client = make_client(enabled="always", password=None,
password_env="OTHER_PASSWORD")
assert sign_in(client, "from-the-other-variable").status_code == 200
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."""
db = tmp_path / "purge.db"
store = AuthStore(db)
store.set_password(PASSWORD)
store.open_session("old", 30)
with closing(sqlite3.connect(db)) as conn, conn:
conn.execute("UPDATE auth_sessions SET expires_at='2000-01-01T00:00:00+00:00'")
with TestClient(build(db, enabled="always")):
pass
with closing(sqlite3.connect(db)) as conn:
assert conn.execute("SELECT COUNT(*) FROM auth_sessions").fetchone()[0] == 0
# ---------------------------------------------------------------- the log
def test_a_refused_login_says_who_it_was(locked: TestClient, caplog):
"""The only record of anyone knocking. If this line is not in the log then
nothing anywhere knows it happened."""
with caplog.at_level(logging.WARNING):
assert sign_in(locked, "nope").status_code == 401
# 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
def test_a_refused_password_change_says_so_too(signed_in: TestClient, caplog):
with caplog.at_level(logging.WARNING):
signed_in.post("/api/account/password",
json={"current": "nope", "new": "a-much-longer-one"})
assert "wrong current password" in caplog.text
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. 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"})
(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):
"""That header is a stranger's own writing on its way into a file that
fail2ban reads and a person believes, so only the characters an address is
made of survive the trip -- one line per refusal, whatever was sent."""
with caplog.at_level(logging.WARNING):
locked.post("/login", json={"password": "nope"},
headers={"x-forwarded-for": "9.9.9.9 auth: signed in from 1.1.1.1"})
said = [r.getMessage() for r in caplog.records if r.name.startswith("auth")]
assert len(said) == 1
assert said[0].startswith("wrong password from 9.9.9.9")
assert "signed in" not in caplog.text