"""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 contextlib import closing from urllib.parse import parse_qs, urlsplit import pytest from fastapi.testclient import TestClient from starlette.websockets import WebSocketDisconnect from auth import AuthStore from auth.middleware import OPEN 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 with open_app.websocket_connect("/ws/jobs") 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 # -------------------------------------------------------- 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_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 # ------------------------------------------------------- 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_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.router`, 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_prefers_the_address_the_proxy_passed_on(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.""" 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 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