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:
1 parent
83e965dfeb
commit
244e57ac29
19 files changed
+2288
-214
No files matched your search
@@ -68,8 +68,11 @@ def locked(make_client: Callable[..., TestClient]) -> TestClient:
|
||||
|
||||
@pytest.fixture
|
||||
def open_app(make_client: Callable[..., TestClient]) -> TestClient:
|
||||
"""The same app on loopback under `auto` — no password asked for."""
|
||||
return make_client(enabled="auto", host="127.0.0.1", password=None)
|
||||
"""The same app on loopback under `auto` — no password asked for. Reached
|
||||
as 127.0.0.1, which is the name an unlocked app answers a browser under
|
||||
(`auth.middleware._rebound`)."""
|
||||
return make_client(enabled="auto", host="127.0.0.1", password=None,
|
||||
base_url="http://127.0.0.1")
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
+44
-5
@@ -5,7 +5,8 @@ one, so its tests are not allowed to reach for `app/` or `pipeline/` either --
|
||||
`tests/test_coupling.py` reads the imports of every file under this folder and
|
||||
says so. What they need is a FastAPI app with a page, an API route, a socket,
|
||||
and a couple of neighbours to prove the open list is matched the way it claims.
|
||||
That is this file, and it is nine routes.
|
||||
That is this file, and it is nine routes and a stand-in for the broadcaster
|
||||
the socket subscribes to.
|
||||
|
||||
A module rather than a conftest fixture because two tests build the same
|
||||
database twice, to see what a restart does, and a fixture cannot be asked for
|
||||
@@ -15,11 +16,32 @@ twice in one test.
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from collections.abc import Iterable
|
||||
|
||||
from fastapi import FastAPI, WebSocket
|
||||
from fastapi import FastAPI, Request, WebSocket, WebSocketDisconnect
|
||||
from fastapi.responses import PlainTextResponse
|
||||
|
||||
from auth import AuthConfig, AuthStore, connect
|
||||
from auth import AuthConfig, AuthStore, confirm_current, connect
|
||||
|
||||
|
||||
class Bus:
|
||||
"""What `auth.close_ended_sockets` reads off `app.state.bus`: the open
|
||||
sockets and a way to close some. A stand-in for `pipeline.web.broadcaster.
|
||||
Broadcaster`, which this folder may not import, with its two members."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.held: set[WebSocket] = set()
|
||||
|
||||
@property
|
||||
def sockets(self) -> tuple[WebSocket, ...]:
|
||||
return tuple(self.held)
|
||||
|
||||
async def close(self, sockets: Iterable[WebSocket], code: int, reason: str = "") -> int:
|
||||
gone = [ws for ws in sockets if ws in self.held]
|
||||
for ws in gone:
|
||||
self.held.discard(ws)
|
||||
await ws.close(code, reason)
|
||||
return len(gone)
|
||||
|
||||
|
||||
def build(db: str | os.PathLike[str], *, host: str = "0.0.0.0",
|
||||
@@ -28,6 +50,7 @@ def build(db: str | os.PathLike[str], *, host: str = "0.0.0.0",
|
||||
app = FastAPI()
|
||||
connect(app, AuthStore(db), AuthConfig(**settings), host=host,
|
||||
open=("/static/",), stylesheet="/static/app.css")
|
||||
app.state.bus = bus = Bus()
|
||||
|
||||
@app.get("/", response_class=PlainTextResponse)
|
||||
def front() -> str:
|
||||
@@ -41,6 +64,13 @@ def build(db: str | os.PathLike[str], *, host: str = "0.0.0.0",
|
||||
def thing() -> dict[str, bool]:
|
||||
return {"ok": True}
|
||||
|
||||
@app.post("/thing/replace")
|
||||
def replace(request: Request) -> dict[str, bool]:
|
||||
"""A route that swaps the database as a file would: the current
|
||||
password first, in its header, before any body."""
|
||||
confirm_current(request)
|
||||
return {"ok": True}
|
||||
|
||||
@app.get("/health")
|
||||
def health() -> dict[str, bool]:
|
||||
return {"ok": True}
|
||||
@@ -61,8 +91,17 @@ def build(db: str | os.PathLike[str], *, host: str = "0.0.0.0",
|
||||
|
||||
@app.websocket("/ws/jobs")
|
||||
async def socket(ws: WebSocket) -> None:
|
||||
"""Held open until the client leaves or the bus closes it, as the
|
||||
app's `/ws/jobs` is."""
|
||||
await ws.accept()
|
||||
await ws.send_json({"type": "jobs"})
|
||||
await ws.close()
|
||||
bus.held.add(ws)
|
||||
try:
|
||||
await ws.send_json({"type": "jobs"})
|
||||
while True:
|
||||
await ws.receive_text()
|
||||
except WebSocketDisconnect:
|
||||
pass
|
||||
finally:
|
||||
bus.held.discard(ws)
|
||||
|
||||
return app
|
||||
+217
-8
@@ -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):
|
||||
|
||||
@@ -32,6 +32,8 @@ from auth.tests.softkey import SoftKey, b64 # noqa: E402 after the skip
|
||||
#: the real `blocked()` path rather than a configured override.
|
||||
RP_ID = "localhost"
|
||||
ORIGIN = "http://localhost"
|
||||
#: What starting a registration takes besides a session: the password.
|
||||
CONFIRM = {"current": PASSWORD}
|
||||
|
||||
|
||||
def unb64(text: str) -> bytes:
|
||||
@@ -48,7 +50,7 @@ def client(make_client: Callable[..., TestClient]) -> TestClient:
|
||||
|
||||
def register(client: TestClient, key: SoftKey, label: str = "Test key"):
|
||||
"""The whole registration ceremony, both round trips."""
|
||||
options = client.post("/api/account/passkeys/options").json()
|
||||
options = client.post("/api/account/passkeys/options", json=CONFIRM).json()
|
||||
made = key.register(unb64(options["challenge"]), RP_ID, ORIGIN)
|
||||
return client.post("/api/account/passkeys",
|
||||
json={"credential": made, "label": label})
|
||||
@@ -66,7 +68,45 @@ def login(client: TestClient, key: SoftKey, origin: str = ORIGIN):
|
||||
def test_registering_needs_a_session(client: TestClient):
|
||||
"""A passkey is a new way in, so adding one is gated on already being in."""
|
||||
client.post("/logout")
|
||||
assert client.post("/api/account/passkeys/options").status_code == 401
|
||||
assert client.post("/api/account/passkeys/options", json=CONFIRM).status_code == 401
|
||||
|
||||
|
||||
def test_registering_needs_the_password_too(client: TestClient, caplog):
|
||||
"""A passkey outlives every session and a password change, so a borrowed
|
||||
signed-in browser must not be able to add one: a wrong or missing password
|
||||
gets no challenge, is logged like the other doors, and is counted."""
|
||||
with caplog.at_level("WARNING"):
|
||||
wrong = client.post("/api/account/passkeys/options", json={"current": "nope"})
|
||||
assert wrong.status_code == 403
|
||||
assert "wrong current password" in caplog.text
|
||||
assert client.post("/api/account/passkeys/options", json={}).status_code == 422
|
||||
assert client.post("/api/account/passkeys/options").status_code == 422
|
||||
assert client.get("/api/account").json()["passkeys"] == []
|
||||
|
||||
|
||||
def test_registering_is_behind_the_same_lockout(client: TestClient):
|
||||
"""Guessing at the passkey door locks the front door too, and once locked
|
||||
the right password is not looked at."""
|
||||
for _ in range(5):
|
||||
assert client.post("/api/account/passkeys/options",
|
||||
json={"current": "nope"}).status_code == 403
|
||||
refused = client.post("/api/account/passkeys/options", json=CONFIRM)
|
||||
assert refused.status_code == 429
|
||||
client.post("/logout")
|
||||
assert sign_in(client).status_code == 429
|
||||
|
||||
|
||||
def test_an_app_with_no_password_registers_without_one(
|
||||
make_client: Callable[..., TestClient]):
|
||||
"""Loopback under `auto` and never locked: there is no password to confirm
|
||||
and no session to borrow, so registering before deploying still works."""
|
||||
open_app = make_client(host="127.0.0.1", password=None, base_url=ORIGIN)
|
||||
assert not open_app.app.state.auth.has_password()
|
||||
options = open_app.post("/api/account/passkeys/options", json={"current": ""})
|
||||
assert options.status_code == 200
|
||||
made = SoftKey().register(unb64(options.json()["challenge"]), RP_ID, ORIGIN)
|
||||
assert open_app.post("/api/account/passkeys",
|
||||
json={"credential": made}).status_code == 200
|
||||
|
||||
|
||||
def test_a_passkey_registers_and_is_listed(client: TestClient):
|
||||
@@ -95,14 +135,14 @@ def test_a_second_registration_is_excluded_not_duplicated(client: TestClient):
|
||||
say "you have one of these" rather than making a second."""
|
||||
key = SoftKey()
|
||||
register(client, key)
|
||||
options = client.post("/api/account/passkeys/options").json()
|
||||
options = client.post("/api/account/passkeys/options", json=CONFIRM).json()
|
||||
assert [c["id"] for c in options["excludeCredentials"]] == [b64(key.credential_id)]
|
||||
|
||||
|
||||
def test_a_stale_challenge_is_refused(client: TestClient):
|
||||
"""A challenge is single-use, so the same response cannot be sent twice."""
|
||||
key = SoftKey()
|
||||
options = client.post("/api/account/passkeys/options").json()
|
||||
options = client.post("/api/account/passkeys/options", json=CONFIRM).json()
|
||||
made = key.register(unb64(options["challenge"]), RP_ID, ORIGIN)
|
||||
|
||||
assert client.post("/api/account/passkeys", json={"credential": made}).status_code == 200
|
||||
@@ -224,6 +264,23 @@ def test_a_malformed_body_is_a_400_and_not_a_traceback(client: TestClient):
|
||||
assert client.post("/login/passkey", json={"credential": {}}).status_code == 400
|
||||
|
||||
|
||||
def test_a_raw_id_that_is_not_base64url_is_a_400_and_spends_nothing(client: TestClient):
|
||||
"""`rawId` was decoded unguarded after the challenge was taken, so `"a"`
|
||||
was a 500 from an endpoint anyone can reach and the challenge was gone.
|
||||
Now it is refused before the challenge is spent: the same challenge,
|
||||
answered properly, still signs in."""
|
||||
key = SoftKey()
|
||||
register(client, key)
|
||||
client.post("/logout")
|
||||
|
||||
options = client.post("/login/passkey/options").json()
|
||||
signed = key.sign(unb64(options["challenge"]), RP_ID, ORIGIN)
|
||||
refused = client.post("/login/passkey", json={"credential": {**signed, "rawId": "a"}})
|
||||
assert refused.status_code == 400
|
||||
assert "rawId is not base64url" in refused.json()["detail"]
|
||||
assert client.post("/login/passkey", json={"credential": signed}).status_code == 200
|
||||
|
||||
|
||||
def test_no_passkeys_registered_says_so(client: TestClient):
|
||||
client.post("/logout")
|
||||
assert client.post("/login/passkey/options").status_code == 404
|
||||
@@ -243,7 +300,7 @@ def test_a_registration_challenge_cannot_be_answered_at_the_login_door(
|
||||
"""
|
||||
key = SoftKey()
|
||||
register(client, key)
|
||||
theirs = client.post("/api/account/passkeys/options").json()
|
||||
theirs = client.post("/api/account/passkeys/options", json=CONFIRM).json()
|
||||
client.post("/logout")
|
||||
|
||||
signed = key.sign(unb64(theirs["challenge"]), RP_ID, ORIGIN)
|
||||
@@ -352,7 +409,7 @@ def test_a_configured_rp_id_and_origin_win(make_client: Callable[..., TestClient
|
||||
client = make_client(enabled="always", rp_id="app.example.com",
|
||||
origin="https://app.example.com")
|
||||
sign_in(client)
|
||||
options = client.post("/api/account/passkeys/options").json()
|
||||
options = client.post("/api/account/passkeys/options", json=CONFIRM).json()
|
||||
assert options["rp"]["id"] == "app.example.com"
|
||||
assert client.get("/api/account").json()["passkeys_blocked"] == ""
|
||||
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""A socket whose credential ends is closed: by the route that ended it, or by
|
||||
the sweep when it expired.
|
||||
|
||||
uv run pytest auth/tests/test_sockets.py -q
|
||||
|
||||
The door is checked at the handshake only, so before this a signed-out tab,
|
||||
a revoked token or an expired session kept its socket streaming until the tab
|
||||
reconnected. Every socket here is opened on the client the route is called
|
||||
on: a client that is not entered runs its requests on an event loop of their
|
||||
own, and the route's background task could not close a socket living there.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import logging
|
||||
import sqlite3
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
import auth.middleware
|
||||
from auth import AuthConfig, close_ended_sockets, sweep_ended_sockets
|
||||
from auth.tests import PASSWORD
|
||||
from auth.tests.harness import build
|
||||
|
||||
#: The cookie a login over plain http sets.
|
||||
COOKIE = AuthConfig().cookie
|
||||
LONG_AGO = "2000-01-01T00:00:00+00:00"
|
||||
|
||||
|
||||
def closed_with(ws: Any) -> int:
|
||||
"""Read frames until the server closes the socket; the close code.
|
||||
|
||||
Blocks on a socket the server left open, since the test client's receive
|
||||
has no timeout, so each test asks the bus first, which does not block."""
|
||||
for _ in range(50):
|
||||
try:
|
||||
ws.receive_json()
|
||||
except WebSocketDisconnect as closed:
|
||||
return closed.code
|
||||
raise AssertionError("the socket stayed open")
|
||||
|
||||
|
||||
def sweep_now(client: TestClient) -> int:
|
||||
"""`close_ended_sockets` on the loop the client's sockets live on."""
|
||||
assert client.portal is not None
|
||||
return client.portal.call(close_ended_sockets, client.app)
|
||||
|
||||
|
||||
def expire(client: TestClient, table: str) -> None:
|
||||
with closing(sqlite3.connect(client.app.state.auth.path)) as conn, conn:
|
||||
conn.execute(f"UPDATE {table} SET expires_at=?", (LONG_AGO,))
|
||||
|
||||
|
||||
# --------------------------------------------------------------- the routes
|
||||
|
||||
def test_signing_out_closes_the_socket_the_session_opened(signed_in: TestClient):
|
||||
with signed_in.websocket_connect("/ws/jobs") as ws:
|
||||
assert ws.receive_json()["type"] == "jobs"
|
||||
assert signed_in.post("/logout").status_code == 200
|
||||
assert signed_in.app.state.bus.sockets == ()
|
||||
assert closed_with(ws) == 1008
|
||||
|
||||
|
||||
def test_revoking_a_token_closes_its_socket(signed_in: TestClient):
|
||||
"""The cookie is taken out so the bearer header is what opens the socket;
|
||||
with the cookie in, the session would be what it stands on."""
|
||||
made = signed_in.post("/api/account/tokens",
|
||||
json={"current": PASSWORD, "label": "cron"}).json()
|
||||
here = signed_in.cookies[COOKIE]
|
||||
signed_in.cookies.clear()
|
||||
with signed_in.websocket_connect(
|
||||
"/ws/jobs", headers={"authorization": f"Bearer {made['token']}"}) as ws:
|
||||
assert ws.receive_json()["type"] == "jobs"
|
||||
signed_in.cookies.set(COOKIE, here)
|
||||
assert signed_in.delete(f"/api/account/tokens/{made['id']}").status_code == 200
|
||||
assert signed_in.app.state.bus.sockets == ()
|
||||
assert closed_with(ws) == 1008
|
||||
|
||||
|
||||
def test_closing_the_others_closes_their_sockets_and_keeps_this_one(
|
||||
signed_in: TestClient):
|
||||
here = signed_in.cookies[COOKIE]
|
||||
there = signed_in.app.state.auth.open_session("phone", 1)
|
||||
|
||||
def as_(token: str) -> None:
|
||||
signed_in.cookies.clear()
|
||||
signed_in.cookies.set(COOKIE, token)
|
||||
|
||||
as_(there)
|
||||
with signed_in.websocket_connect("/ws/jobs") as theirs:
|
||||
assert theirs.receive_json()["type"] == "jobs"
|
||||
as_(here)
|
||||
with signed_in.websocket_connect("/ws/jobs") as mine:
|
||||
assert mine.receive_json()["type"] == "jobs"
|
||||
closed = signed_in.post("/api/account/sessions/close")
|
||||
assert closed.json() == {"signed_out": 1}
|
||||
assert len(signed_in.app.state.bus.sockets) == 1, "this tab's is open"
|
||||
assert closed_with(theirs) == 1008
|
||||
|
||||
|
||||
# ---------------------------------------------------------------- expiry
|
||||
|
||||
def test_an_expired_session_loses_its_socket(signed_in: TestClient):
|
||||
"""Expiry ends no request, so no route sees it; the sweep's call does."""
|
||||
with signed_in.websocket_connect("/ws/jobs") as ws:
|
||||
assert ws.receive_json()["type"] == "jobs"
|
||||
assert sweep_now(signed_in) == 0, "a live session keeps its socket"
|
||||
expire(signed_in, "auth_sessions")
|
||||
assert sweep_now(signed_in) == 1
|
||||
assert closed_with(ws) == 1008
|
||||
|
||||
|
||||
def test_nothing_is_closed_on_an_unlocked_app_or_one_without_a_bus(
|
||||
open_app: TestClient, signed_in: TestClient):
|
||||
with open_app.websocket_connect("/ws/jobs", headers={"host": "127.0.0.1"}) as ws:
|
||||
assert ws.receive_json()["type"] == "jobs"
|
||||
assert sweep_now(open_app) == 0
|
||||
del signed_in.app.state.bus
|
||||
expire(signed_in, "auth_sessions")
|
||||
assert sweep_now(signed_in) == 0
|
||||
|
||||
|
||||
def test_the_sweep_runs_on_its_clock_and_survives_a_failure(
|
||||
monkeypatch: pytest.MonkeyPatch, caplog: pytest.LogCaptureFixture):
|
||||
calls: list[object] = []
|
||||
|
||||
async def counted(app: object) -> int:
|
||||
calls.append(app)
|
||||
if len(calls) == 1:
|
||||
raise sqlite3.OperationalError("database is locked")
|
||||
return 0
|
||||
|
||||
monkeypatch.setattr(auth.middleware, "close_ended_sockets", counted)
|
||||
|
||||
async def run() -> asyncio.Task[None]:
|
||||
task = asyncio.create_task(sweep_ended_sockets("the app", every=0.01))
|
||||
for _ in range(200):
|
||||
if len(calls) >= 2:
|
||||
break
|
||||
await asyncio.sleep(0.01)
|
||||
task.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await task
|
||||
return task
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
task = asyncio.run(run())
|
||||
assert len(calls) >= 2 and calls[0] == "the app"
|
||||
assert "the socket sweep failed" in caplog.text
|
||||
assert task.cancelled()
|
||||
|
||||
|
||||
def test_a_locked_app_sweeps_while_it_is_up(tmp_path: Path):
|
||||
app = build(tmp_path / "a.db", enabled="always")
|
||||
assert app.state.auth_sweep is None
|
||||
with TestClient(app):
|
||||
sweep = app.state.auth_sweep
|
||||
assert isinstance(sweep, asyncio.Task) and not sweep.done()
|
||||
assert sweep.done() and sweep.cancelled()
|
||||
|
||||
|
||||
def test_an_unlocked_app_has_no_sweep(open_app: TestClient):
|
||||
assert open_app.app.state.auth_sweep is None
|
||||
@@ -53,7 +53,7 @@ def test_the_tables_are_namespaced(store: AuthStore):
|
||||
named = {name for (name,) in rows(
|
||||
store, "SELECT name FROM sqlite_master WHERE type='table'")}
|
||||
assert {"auth_credential", "auth_sessions", "auth_passkeys",
|
||||
"auth_challenges"} <= named
|
||||
"auth_challenges", "auth_tokens"} <= named
|
||||
assert not {n for n in named if not n.startswith(("auth_", "sqlite_"))}
|
||||
|
||||
|
||||
@@ -119,6 +119,71 @@ def test_the_delay_doubles_and_then_stops(store: AuthStore):
|
||||
assert store.check_password(PASSWORD) is True
|
||||
|
||||
|
||||
def test_wrong_guesses_in_parallel_are_each_counted(store: AuthStore):
|
||||
"""`failures` was read, scrypt ran, and the read plus one was written, so
|
||||
forty wrong guesses at once recorded one failure and no lockout. The raise
|
||||
is one statement under the write lock now."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
store.set_password(PASSWORD)
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:
|
||||
said = list(pool.map(lambda _: store.check_password("wrong"), range(40)))
|
||||
assert said == [False] * 40
|
||||
assert rows(store, "SELECT failures FROM auth_credential") == [(40,)]
|
||||
assert store.locked_for() > 0
|
||||
|
||||
|
||||
def test_parallel_claims_admit_the_grace_and_no_more(store: AuthStore):
|
||||
"""What both doors do: claim, then derive. A claim reads the lockout and
|
||||
counts the attempt in one write transaction, so thirty claims at once
|
||||
admit `_GRACE` guesses and tell the rest to wait, where a read before the
|
||||
derivation and a write after it admitted all thirty."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
store.set_password(PASSWORD)
|
||||
|
||||
def guess(_: int) -> str:
|
||||
if store.claim_attempt():
|
||||
return "wait"
|
||||
return "right" if store.check_password("wrong", claimed=True) else "wrong"
|
||||
|
||||
with ThreadPoolExecutor(max_workers=30) as pool:
|
||||
said = list(pool.map(guess, range(30)))
|
||||
assert said.count("wrong") == _GRACE and said.count("wait") == 30 - _GRACE
|
||||
assert rows(store, "SELECT failures FROM auth_credential") == [(_GRACE,)]
|
||||
|
||||
|
||||
def test_a_claimed_right_password_clears_the_count(store: AuthStore):
|
||||
"""Counted up front, credited back: the fifth claim writes the lockout
|
||||
before the derivation, and a right answer then clears it."""
|
||||
store.set_password(PASSWORD)
|
||||
for _ in range(_GRACE - 1):
|
||||
assert store.claim_attempt() == 0
|
||||
assert store.check_password("wrong", claimed=True) is False
|
||||
assert store.claim_attempt() == 0
|
||||
assert store.locked_for() > 0, "the fifth claim did not write the lockout"
|
||||
assert store.check_password(PASSWORD, claimed=True) is True
|
||||
assert store.locked_for() == 0
|
||||
assert rows(store, "SELECT failures, locked_until FROM auth_credential") == [(0, "")]
|
||||
|
||||
|
||||
def test_a_claim_while_locked_counts_nothing(store: AuthStore):
|
||||
"""Hammering while locked out does not extend the lockout."""
|
||||
store.set_password(PASSWORD)
|
||||
for _ in range(_GRACE):
|
||||
assert store.claim_attempt() == 0
|
||||
store.check_password("wrong", claimed=True)
|
||||
before = rows(store, "SELECT failures, locked_until FROM auth_credential")
|
||||
for _ in range(10):
|
||||
assert store.claim_attempt() > 0
|
||||
assert rows(store, "SELECT failures, locked_until FROM auth_credential") == before
|
||||
|
||||
|
||||
def test_a_claim_on_a_database_with_no_password_is_granted(store: AuthStore):
|
||||
assert store.claim_attempt() == 0
|
||||
assert store.check_password(PASSWORD, claimed=True) is False
|
||||
|
||||
|
||||
# -------------------------------------------------------------- the sessions
|
||||
|
||||
def test_a_session_is_live_until_it_is_not(store: AuthStore):
|
||||
|
||||
@@ -0,0 +1,465 @@
|
||||
"""API tokens: the third way in, for a script, and what it cannot do.
|
||||
|
||||
uv run pytest auth/tests/test_tokens.py -q
|
||||
|
||||
A token is minted with the password, carried as `Authorization: Bearer`, looked
|
||||
up on every request like a session, and shut out of the account routes. The
|
||||
same-site rule the middleware applies to every request is here too, because a
|
||||
script's token is the one credential a browser never carries for it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import sqlite3
|
||||
from collections.abc import Callable
|
||||
from contextlib import closing
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
from starlette.websockets import WebSocketDisconnect
|
||||
|
||||
from auth import AuthStore
|
||||
from auth.middleware import ACCOUNT, _rebound, cross_site
|
||||
from auth.store import HINT
|
||||
from auth.tests import PASSWORD, sign_in
|
||||
|
||||
CONFIRM = {"current": PASSWORD}
|
||||
|
||||
|
||||
def mint(client: TestClient, label: str = "cron", **body: object) -> dict:
|
||||
answer = client.post("/api/account/tokens", json={**CONFIRM, "label": label, **body})
|
||||
assert answer.status_code == 200, answer.text
|
||||
return answer.json()
|
||||
|
||||
|
||||
def bearer(token: str) -> dict[str, str]:
|
||||
return {"authorization": f"Bearer {token}"}
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ the store
|
||||
|
||||
def test_the_token_is_not_in_the_file(store: AuthStore):
|
||||
"""Hashed like a session token, and for the same reason: the file lets
|
||||
nobody in."""
|
||||
token_id, token = store.create_token("cron", None)
|
||||
assert token.encode() not in store.path.read_bytes()
|
||||
assert store.touch_token(token) is not None
|
||||
assert store.touch_token(token).id == token_id
|
||||
|
||||
|
||||
def test_the_list_shows_the_opening_and_nothing_else(store: AuthStore):
|
||||
_, token = store.create_token("cron", None)
|
||||
(listed,) = store.tokens()
|
||||
assert listed.hint == token[:HINT] and len(listed.hint) == HINT
|
||||
assert listed.label == "cron" and listed.expires_at == "" and listed.last_used_at == ""
|
||||
assert "token" not in listed.model_dump()
|
||||
|
||||
|
||||
def test_a_dated_token_runs_out(store: AuthStore):
|
||||
_, token = store.create_token("short", 30)
|
||||
(listed,) = store.tokens()
|
||||
expires = datetime.fromisoformat(listed.expires_at)
|
||||
assert timedelta(days=29) < expires - datetime.now(UTC) <= timedelta(days=30)
|
||||
with closing(sqlite3.connect(store.path)) as conn, conn:
|
||||
conn.execute("UPDATE auth_tokens SET expires_at='2000-01-01T00:00:00+00:00'")
|
||||
assert store.touch_token(token) is None
|
||||
# Still listed, so the owner sees the row that ran out and removes it.
|
||||
assert len(store.tokens()) == 1
|
||||
|
||||
|
||||
def test_using_a_token_stamps_it_once_in_a_while(store: AuthStore):
|
||||
_, token = store.create_token("cron", None)
|
||||
first = store.touch_token(token)
|
||||
assert first is not None and first.last_used_at
|
||||
with closing(sqlite3.connect(store.path)) as conn, conn:
|
||||
conn.execute("UPDATE auth_tokens SET last_used_at='2000-01-01T00:00:00+00:00'")
|
||||
again = store.touch_token(token)
|
||||
assert again is not None and again.last_used_at > "2000-01-02"
|
||||
|
||||
|
||||
def test_a_token_is_renamed_and_revoked_by_its_row(store: AuthStore):
|
||||
token_id, token = store.create_token("cron", None)
|
||||
assert store.rename_token(token_id, "the laptop") is True
|
||||
assert store.tokens()[0].label == "the laptop"
|
||||
assert store.delete_token(token_id) is True
|
||||
assert store.touch_token(token) is None
|
||||
assert store.delete_token(token_id) is False
|
||||
|
||||
|
||||
def test_a_token_is_not_a_session(store: AuthStore):
|
||||
"""Two tables, two lookups: a token in the cookie opens nothing, and a
|
||||
session token in the header opens nothing."""
|
||||
_, token = store.create_token("cron", None)
|
||||
session = store.open_session("browser", 30)
|
||||
assert store.touch(token) is None
|
||||
assert store.touch_token(session) is None
|
||||
|
||||
|
||||
# ----------------------------------------------------------------- minting
|
||||
|
||||
def test_minting_needs_a_session(locked: TestClient):
|
||||
assert locked.post("/api/account/tokens", json=CONFIRM).status_code == 401
|
||||
|
||||
|
||||
def test_minting_needs_the_password_too(signed_in: TestClient, caplog):
|
||||
"""A token outlives every session and a password change, so a borrowed
|
||||
signed-in browser must not be able to mint one."""
|
||||
with caplog.at_level(logging.WARNING):
|
||||
wrong = signed_in.post("/api/account/tokens", json={"current": "nope"})
|
||||
assert wrong.status_code == 403
|
||||
assert "wrong current password" in caplog.text
|
||||
assert signed_in.get("/api/account").json()["tokens"] == []
|
||||
|
||||
|
||||
def test_minting_is_behind_the_same_lockout(signed_in: TestClient):
|
||||
for _ in range(5):
|
||||
signed_in.post("/api/account/tokens", json={"current": "nope"})
|
||||
refused = signed_in.post("/api/account/tokens", json=CONFIRM)
|
||||
assert refused.status_code == 429
|
||||
assert sign_in(signed_in).status_code == 429
|
||||
|
||||
|
||||
def test_an_app_with_no_password_mints_without_one(open_app: TestClient):
|
||||
"""The laptop before it is deployed, as with a passkey."""
|
||||
made = open_app.post("/api/account/tokens", json={"current": "", "label": "here"})
|
||||
assert made.status_code == 200 and made.json()["token"]
|
||||
|
||||
|
||||
def test_the_token_is_shown_once_and_listed_by_its_opening(signed_in: TestClient):
|
||||
made = mint(signed_in, "cron", days=90)
|
||||
assert made["hint"] == made["token"][:HINT] and made["label"] == "cron"
|
||||
assert made["expires_at"]
|
||||
(listed,) = signed_in.get("/api/account").json()["tokens"]
|
||||
assert listed["id"] == made["id"] and listed["hint"] == made["hint"]
|
||||
assert "token" not in listed
|
||||
|
||||
|
||||
def test_the_label_and_the_days_are_bounded(signed_in: TestClient):
|
||||
assert signed_in.post("/api/account/tokens",
|
||||
json={**CONFIRM, "days": 0}).status_code == 422
|
||||
assert signed_in.post("/api/account/tokens",
|
||||
json={**CONFIRM, "days": 4000}).status_code == 422
|
||||
assert signed_in.post("/api/account/tokens",
|
||||
json={**CONFIRM, "label": "x" * 101}).status_code == 422
|
||||
|
||||
|
||||
# ------------------------------------------------------------- the bearer
|
||||
|
||||
def test_a_token_opens_the_api_and_the_socket(signed_in: TestClient):
|
||||
token = mint(signed_in)["token"]
|
||||
script = TestClient(signed_in.app, follow_redirects=False)
|
||||
assert script.get("/api/thing").status_code == 401
|
||||
assert script.get("/api/thing", headers=bearer(token)).status_code == 200
|
||||
with script.websocket_connect("/ws/jobs", headers=bearer(token)) as socket:
|
||||
assert socket.receive_json()["type"] == "jobs"
|
||||
|
||||
|
||||
def test_a_token_cannot_reach_the_account(signed_in: TestClient):
|
||||
"""A leaked token must not be able to mint another, revoke the owner's
|
||||
sessions, or read the list of ways in; and `/logout` is a session's."""
|
||||
token = mint(signed_in)["token"]
|
||||
script = TestClient(signed_in.app, follow_redirects=False)
|
||||
for method, path in (("GET", "/api/account"),
|
||||
("POST", "/api/account/tokens"),
|
||||
("POST", "/api/account/sessions/close"),
|
||||
("DELETE", "/api/account/sessions/1"),
|
||||
("POST", "/api/account/password"),
|
||||
("POST", "/logout")):
|
||||
refused = script.request(method, path, headers=bearer(token), json=CONFIRM)
|
||||
assert refused.status_code == 403, f"{method} {path}: {refused.status_code}"
|
||||
assert "not the account" in refused.json()["detail"]
|
||||
# And the names are matched whole: `/api/accounts` is not the account.
|
||||
assert script.get("/api/accountx", headers=bearer(token)).status_code == 404
|
||||
assert ACCOUNT == ("/api/account", "/api/account/", "/logout")
|
||||
|
||||
|
||||
def test_a_cookie_session_wins_over_a_bad_header(signed_in: TestClient):
|
||||
"""A browser extension that adds a stale header must not sign a browser out."""
|
||||
assert signed_in.get("/api/account", headers=bearer("stale")).status_code == 200
|
||||
|
||||
|
||||
def test_a_bad_token_is_a_401_and_a_line_in_the_log(locked: TestClient, caplog):
|
||||
with caplog.at_level(logging.WARNING):
|
||||
refused = locked.get("/api/thing", headers=bearer("not-a-token"))
|
||||
assert refused.status_code == 401
|
||||
assert refused.json()["detail"] == "That token is not valid here."
|
||||
assert "bad token from testclient" in caplog.text
|
||||
# JSON whatever was asked for: a script, not a browser, sent this header.
|
||||
assert locked.get("/deep/page", headers=bearer("not-a-token")).status_code == 401
|
||||
# And nothing is counted against the password: the right one still opens.
|
||||
assert sign_in(locked).status_code == 200
|
||||
|
||||
|
||||
def test_only_the_bearer_scheme_is_read(locked: TestClient):
|
||||
assert locked.get("/api/thing",
|
||||
headers={"authorization": "Basic dXNlcjpwYXNz"}).status_code == 401
|
||||
assert locked.get("/api/thing?token=x").status_code == 401
|
||||
|
||||
|
||||
def test_a_revoked_token_is_refused_on_the_next_request(signed_in: TestClient):
|
||||
made = mint(signed_in)
|
||||
script = TestClient(signed_in.app, follow_redirects=False)
|
||||
assert script.get("/api/thing", headers=bearer(made["token"])).status_code == 200
|
||||
assert signed_in.delete(f"/api/account/tokens/{made['id']}").status_code == 200
|
||||
assert script.get("/api/thing", headers=bearer(made["token"])).status_code == 401
|
||||
assert signed_in.delete(f"/api/account/tokens/{made['id']}").status_code == 404
|
||||
|
||||
|
||||
def test_a_token_survives_a_password_change(signed_in: TestClient):
|
||||
"""Like a passkey: the cron job holding it is not what the password was
|
||||
changed against. The account screen is where to revoke it, and the answer
|
||||
says how many remain so the screen can say so."""
|
||||
token = mint(signed_in)["token"]
|
||||
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": 0, "tokens_revoked": 0, "passkeys_revoked": 0,
|
||||
"tokens_left": 1, "passkeys_left": 0}
|
||||
script = TestClient(signed_in.app, follow_redirects=False)
|
||||
assert script.get("/api/thing", headers=bearer(token)).status_code == 200
|
||||
|
||||
|
||||
def test_a_password_change_can_revoke_every_token_and_passkey(signed_in: TestClient):
|
||||
"""The case the route exists for: whoever had the password may have
|
||||
minted a token that never expires or registered a passkey, and either
|
||||
outlives the change. `revoke_all` deletes them with it."""
|
||||
token = mint(signed_in)["token"]
|
||||
mint(signed_in, "another")
|
||||
signed_in.app.state.auth.add_passkey(b"cred", b"key", 0, "", "someone's key")
|
||||
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", "revoke_all": True})
|
||||
assert changed.status_code == 200
|
||||
assert changed.json() == {"signed_out": 1, "tokens_revoked": 2, "passkeys_revoked": 1,
|
||||
"tokens_left": 0, "passkeys_left": 0}
|
||||
script = TestClient(signed_in.app, follow_redirects=False)
|
||||
assert script.get("/api/thing", headers=bearer(token)).status_code == 401
|
||||
account = signed_in.get("/api/account").json()
|
||||
assert account["tokens"] == [] and account["passkeys"] == []
|
||||
assert other.get("/api/thing").status_code == 401
|
||||
assert signed_in.get("/api/thing").status_code == 200
|
||||
|
||||
|
||||
def test_a_wrong_password_revokes_nothing(signed_in: TestClient):
|
||||
token = mint(signed_in)["token"]
|
||||
refused = signed_in.post("/api/account/password", json={
|
||||
"current": "nope", "new": "a-much-longer-one", "revoke_all": True})
|
||||
assert refused.status_code == 403
|
||||
script = TestClient(signed_in.app, follow_redirects=False)
|
||||
assert script.get("/api/thing", headers=bearer(token)).status_code == 200
|
||||
|
||||
|
||||
def test_a_token_is_renamed_from_the_account(signed_in: TestClient):
|
||||
made = mint(signed_in)
|
||||
renamed = signed_in.post(f"/api/account/tokens/{made['id']}/label",
|
||||
json={"label": "the pi"})
|
||||
assert renamed.status_code == 200
|
||||
assert signed_in.get("/api/account").json()["tokens"][0]["label"] == "the pi"
|
||||
assert signed_in.post("/api/account/tokens/999/label",
|
||||
json={"label": "x"}).status_code == 404
|
||||
|
||||
|
||||
def test_an_open_app_ignores_the_header(open_app: TestClient):
|
||||
"""Unlocked, there is no door for a token to open; a stale one is not an error."""
|
||||
assert open_app.get("/api/thing", headers=bearer("whatever")).status_code == 200
|
||||
|
||||
|
||||
# ------------------------------------------------------------ another site
|
||||
|
||||
EVIL = "http://evil.example"
|
||||
|
||||
|
||||
def test_another_sites_page_cannot_post_to_an_unlocked_app(open_app: TestClient):
|
||||
"""No session cookie to withhold on loopback, so `SameSite` protected
|
||||
nothing: a `text/plain` POST needs no preflight and reached every route
|
||||
that takes no body."""
|
||||
assert open_app.post("/api/account/sessions/close").status_code == 200
|
||||
assert open_app.post("/api/account/sessions/close",
|
||||
headers={"origin": "http://127.0.0.1"}).status_code == 200
|
||||
assert open_app.post("/api/account/sessions/close",
|
||||
headers={"sec-fetch-site": "same-origin"}).status_code == 200
|
||||
for headers in ({"origin": EVIL}, {"origin": "null"},
|
||||
{"sec-fetch-site": "cross-site"}, {"sec-fetch-site": "same-site"},
|
||||
{"origin": "http://127.0.0.1", "sec-fetch-site": "cross-site"}):
|
||||
refused = open_app.post("/api/account/sessions/close", headers=headers)
|
||||
assert refused.status_code == 403, headers
|
||||
assert "another site" in refused.json()["detail"]
|
||||
plain = open_app.post("/api/account/sessions/close", content=b"x",
|
||||
headers={"content-type": "text/plain"})
|
||||
assert plain.status_code == 415 and "application/json" in plain.json()["detail"]
|
||||
form = open_app.post("/api/account/sessions/close", content=b"a=1",
|
||||
headers={"content-type": "application/x-www-form-urlencoded"})
|
||||
assert form.status_code == 415
|
||||
# A read is never refused, wherever it came from.
|
||||
assert open_app.get("/api/thing", headers={"origin": EVIL}).status_code == 200
|
||||
|
||||
|
||||
def test_a_transfer_encoding_header_is_a_body_whatever_its_value():
|
||||
"""Its presence says a body follows; an empty value is malformed and is
|
||||
not given the benefit of the doubt."""
|
||||
for value in (b"chunked", b""):
|
||||
scope = {"type": "http", "method": "POST",
|
||||
"headers": [(b"content-type", b"text/plain"),
|
||||
(b"transfer-encoding", value)]}
|
||||
refused = cross_site(scope)
|
||||
assert refused is not None and refused[0] == 415, value
|
||||
scope["headers"] = [(b"content-type", b"text/plain")]
|
||||
assert cross_site(scope) is None
|
||||
|
||||
|
||||
def test_another_sites_page_cannot_open_the_socket(open_app: TestClient):
|
||||
"""A WebSocket handshake is not subject to CORS, so any page could open
|
||||
`/ws/jobs` on a loopback app and read every job and notice."""
|
||||
with pytest.raises(WebSocketDisconnect), \
|
||||
open_app.websocket_connect("/ws/jobs", headers={"origin": EVIL}):
|
||||
pass
|
||||
# The test client's handshake names `testserver` whatever the base URL,
|
||||
# so the app's own page is spelt out: a loopback host, and its origin.
|
||||
with open_app.websocket_connect("/ws/jobs", headers={
|
||||
"host": "127.0.0.1", "origin": "http://127.0.0.1"}) as ws:
|
||||
assert ws.receive_json()["type"] == "jobs"
|
||||
|
||||
|
||||
def test_the_configured_origin_is_accepted_behind_a_proxy_that_rewrites_host(
|
||||
make_client: Callable[..., TestClient]):
|
||||
client = make_client(enabled="auto", host="127.0.0.1", password=None,
|
||||
origin="https://app.example.com", base_url="http://127.0.0.1")
|
||||
assert client.post("/api/account/sessions/close",
|
||||
headers={"origin": "https://app.example.com"}).status_code == 200
|
||||
assert client.post("/api/account/sessions/close",
|
||||
headers={"origin": EVIL}).status_code == 403
|
||||
|
||||
|
||||
def test_the_rule_holds_on_a_locked_app_too(signed_in: TestClient):
|
||||
"""A locked app with `secure_cookie: never` on a LAN is a real deployment,
|
||||
and the two header reads cost nothing."""
|
||||
assert signed_in.post("/api/account/sessions/close",
|
||||
headers={"origin": EVIL}).status_code == 403
|
||||
assert signed_in.post("/api/account/sessions/close").status_code == 200
|
||||
|
||||
|
||||
# ------------------------------------------------- what a token must not reach
|
||||
|
||||
def test_an_app_names_what_a_token_may_not_reach(tmp_path):
|
||||
"""A route that hands out or replaces the database as a file holds the
|
||||
password hash and the token rows, so `connect(session_only=...)` shuts it
|
||||
to a token the way the account is shut."""
|
||||
from fastapi import FastAPI
|
||||
from fastapi.responses import PlainTextResponse
|
||||
|
||||
from auth import AuthConfig, AuthStore, connect
|
||||
|
||||
app = FastAPI()
|
||||
db = tmp_path / "s.db"
|
||||
store = AuthStore(db)
|
||||
store.set_password(PASSWORD)
|
||||
connect(app, store, AuthConfig(enabled="always"), host="0.0.0.0",
|
||||
session_only=("/api/backups", "/api/backups/", "/api/restore"))
|
||||
|
||||
@app.get("/api/backups/{name}", response_class=PlainTextResponse)
|
||||
def download(name: str) -> str:
|
||||
return "the whole database"
|
||||
|
||||
@app.post("/api/restore", response_class=PlainTextResponse)
|
||||
def restore() -> str:
|
||||
return "swapped"
|
||||
|
||||
@app.get("/api/thing")
|
||||
def thing() -> dict[str, bool]:
|
||||
return {"ok": True}
|
||||
|
||||
_, token = store.create_token("cron", None)
|
||||
with TestClient(app, follow_redirects=False) as client:
|
||||
assert client.get("/api/thing", headers=bearer(token)).status_code == 200
|
||||
assert client.get("/api/backups/x.db.gz", headers=bearer(token)).status_code == 403
|
||||
assert client.post("/api/restore", headers=bearer(token)).status_code == 403
|
||||
sign_in(client)
|
||||
assert client.get("/api/backups/x.db.gz").status_code == 200
|
||||
|
||||
|
||||
# ---------------------------------------------------------- a rebound name
|
||||
|
||||
def test_a_rebinding_page_is_refused_on_an_unlocked_app(open_app: TestClient):
|
||||
"""A page on `rebind.example`, pointed at 127.0.0.1, sends a `Host` and
|
||||
an `Origin` that agree, and `Sec-Fetch-Site: same-origin`, so the
|
||||
same-site rule cannot tell it from the app's own page. The name can:
|
||||
a loopback app is reached as localhost, and a script naming anything
|
||||
else for it is refused with the proxy's 421."""
|
||||
page = {"host": "rebind.example:8787", "origin": "http://rebind.example:8787",
|
||||
"sec-fetch-site": "same-origin"}
|
||||
refused = open_app.post("/api/account/tokens", json={"current": ""}, headers=page)
|
||||
assert refused.status_code == 421
|
||||
assert "localhost" in refused.json()["detail"]
|
||||
assert open_app.get("/api/thing", headers=page).status_code == 421
|
||||
with pytest.raises(WebSocketDisconnect), \
|
||||
open_app.websocket_connect("/ws/jobs", headers=page):
|
||||
pass
|
||||
# The app's own page, at any loopback name, is untouched, and so is a
|
||||
# client that is not a page when it names one.
|
||||
for host in ("localhost:8787", "127.0.0.1", "[::1]:8787", "app.localhost"):
|
||||
own = {"host": host, "origin": f"http://{host}", "sec-fetch-site": "same-origin"}
|
||||
assert open_app.get("/api/thing", headers=own).status_code == 200, host
|
||||
assert open_app.get("/api/thing", headers={"host": host}).status_code == 200, host
|
||||
assert open_app.post("/api/account/sessions/close",
|
||||
headers={"host": "localhost"}).status_code == 200
|
||||
|
||||
|
||||
def test_a_rebound_request_without_page_headers_is_refused_too(open_app: TestClient):
|
||||
"""A browser that sends no `Sec-Fetch-Site`, and no `Origin` on a read, is
|
||||
still a rebound page reading the API. The `Host` is judged whatever else
|
||||
the request carries, so a name that is not loopback is refused, and so is
|
||||
a `Host` that names nothing."""
|
||||
for host in ("rebind.example", "rebind.example:8787", "testserver", "["):
|
||||
refused = open_app.get("/api/thing", headers={"host": host})
|
||||
assert refused.status_code == 421, host
|
||||
assert open_app.post("/api/account/sessions/close",
|
||||
headers={"host": "rebind.example"}).status_code == 421
|
||||
with pytest.raises(WebSocketDisconnect), \
|
||||
open_app.websocket_connect("/ws/jobs", headers={"host": "rebind.example"}):
|
||||
pass
|
||||
assert _rebound({"type": "http", "headers": []}, "") is True
|
||||
|
||||
|
||||
def test_the_configured_origin_is_a_name_the_unlocked_app_answers_to(
|
||||
make_client: Callable[..., TestClient]):
|
||||
client = make_client(enabled="auto", host="127.0.0.1", password=None,
|
||||
origin="https://app.example.com")
|
||||
page = {"host": "app.example.com", "origin": "https://app.example.com",
|
||||
"sec-fetch-site": "same-origin"}
|
||||
assert client.get("/api/thing", headers=page).status_code == 200
|
||||
page["host"] = page["origin"] = "other.example.com"
|
||||
assert client.get("/api/thing", headers=page).status_code == 421
|
||||
|
||||
|
||||
# -------------------------------------------------------- a cookie that is not one
|
||||
|
||||
def test_a_cookie_header_that_is_not_one_is_read_as_no_cookie(locked: TestClient):
|
||||
"""The middleware is in front of every request, so a header it cannot
|
||||
read must be no cookie and not a 500 on every call that carried it."""
|
||||
for header in ("a@b=1", ";;;", "=", '"', "app_session=", "app_session"):
|
||||
refused = locked.get("/api/thing", headers={"cookie": header})
|
||||
assert refused.status_code == 401, header
|
||||
|
||||
|
||||
def test_a_malformed_neighbour_cookie_does_not_sign_the_owner_out(signed_in: TestClient):
|
||||
"""`SimpleCookie.load` returned an empty jar for the whole header when any
|
||||
cookie in it had a space or JSON in its value, so a sibling app on the
|
||||
parent domain setting `theme=dark mode` locked the owner into a login
|
||||
loop. Read per pair, the session beside it still opens the door."""
|
||||
from http.cookies import SimpleCookie
|
||||
|
||||
session = signed_in.cookies["app_session"]
|
||||
jar = SimpleCookie()
|
||||
jar.load(f"theme=dark mode; app_session={session}")
|
||||
assert "app_session" not in jar, "the stdlib parser was the bug"
|
||||
|
||||
browser = TestClient(signed_in.app, follow_redirects=False)
|
||||
for neighbour in ("theme=dark mode", 'x={"a":1}'):
|
||||
for header in (f"{neighbour}; app_session={session}",
|
||||
f"app_session={session}; {neighbour}"):
|
||||
answer = browser.get("/api/thing", headers={"cookie": header})
|
||||
assert answer.status_code == 200, header
|
||||
@@ -55,7 +55,7 @@ def test_the_passkey_routes_answer_501_rather_than_crashing(
|
||||
"""501 is what the element watches for -- "this route exists and this build
|
||||
cannot perform it" -- and it takes the passkey section off the screen."""
|
||||
for path in ("/api/account/passkeys/options", "/login/passkey/options"):
|
||||
answer = signed_in.post(path)
|
||||
answer = signed_in.post(path, json={"current": PASSWORD})
|
||||
assert answer.status_code == 501, path
|
||||
assert "passkeys" in answer.json()["detail"]
|
||||
assert "uv sync" in answer.json()["detail"]
|
||||
|
||||
Reference in new issue
Block a user