466 lines
22 KiB
Python
466 lines
22 KiB
Python
"""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
|