Tokens werden einmal angezeigt und nur gehasht gespeichert. Anmeldung per Authorization: Bearer für Clips, Dateien, Projektliste/-anlage und den Live-Sync (WebSocket ohne Origin). Konto, Admin, Sessions, Tokens und Projektverwaltung bleiben der Browser-Session vorbehalten. Widerruf schließt die Verbindungen des Tokens sofort. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
233 lines
8.3 KiB
Python
233 lines
8.3 KiB
Python
import pytest
|
|
from fastapi.testclient import TestClient
|
|
from starlette.websockets import WebSocketDisconnect
|
|
|
|
from app.api import ws as ws_module
|
|
from app.models import ApiToken, Role, User
|
|
from tests.conftest import login
|
|
from tests.test_ws import connect
|
|
|
|
|
|
@pytest.fixture
|
|
def anna(client, make_user):
|
|
make_user("anna")
|
|
login(client, "anna")
|
|
return client
|
|
|
|
|
|
def create_token(c, name="Laptop"):
|
|
response = c.post("/api/tokens", json={"name": name})
|
|
assert response.status_code == 201, response.text
|
|
return response.json()
|
|
|
|
|
|
@pytest.fixture
|
|
def agent(anna):
|
|
"""A client without cookies that authenticates with a device token only."""
|
|
token = create_token(anna)["token"]
|
|
with TestClient(anna.app, base_url="https://testserver") as c:
|
|
c.headers["Authorization"] = f"Bearer {token}"
|
|
yield c
|
|
|
|
|
|
def ws_with_token(c, token, origin=None):
|
|
headers = {"Authorization": f"Bearer {token}"}
|
|
if origin:
|
|
headers["Origin"] = origin
|
|
return c.websocket_connect("/api/ws", headers=headers)
|
|
|
|
|
|
# --- Managing tokens ------------------------------------------------------------
|
|
|
|
|
|
def test_create_token_shows_value_once(anna):
|
|
created = create_token(anna, " Arbeits Laptop ")
|
|
|
|
assert created["name"] == "Arbeits Laptop"
|
|
assert created["token"].startswith("lc_")
|
|
assert len(created["token"]) > 40
|
|
assert created["prefix"] == created["token"][:10]
|
|
assert created["last_used_at"] is None
|
|
listed = anna.get("/api/tokens").json()
|
|
assert [t["name"] for t in listed] == ["Arbeits Laptop"]
|
|
assert "token" not in listed[0]
|
|
|
|
|
|
def test_only_the_hash_is_stored(anna, db):
|
|
plain = create_token(anna)["token"]
|
|
stored = db.query(ApiToken).one()
|
|
assert plain not in (stored.token_hash, stored.prefix)
|
|
assert len(stored.token_hash) == 64
|
|
|
|
|
|
@pytest.mark.parametrize("name", ["", " ", "x" * 101, "bad\x00name"])
|
|
def test_token_name_validation(anna, name):
|
|
assert anna.post("/api/tokens", json={"name": name}).status_code == 400
|
|
|
|
|
|
def test_token_limit(anna, monkeypatch):
|
|
monkeypatch.setattr("app.services.tokens.MAX_TOKENS_PER_USER", 1)
|
|
create_token(anna)
|
|
assert anna.post("/api/tokens", json={"name": "second"}).status_code == 400
|
|
|
|
|
|
def test_tokens_of_other_users_are_invisible(anna, client, make_user):
|
|
token = create_token(anna)
|
|
make_user("bert")
|
|
with TestClient(client.app, base_url="https://testserver") as bert:
|
|
login(bert, "bert")
|
|
assert bert.get("/api/tokens").json() == []
|
|
assert bert.delete(f"/api/tokens/{token['id']}").status_code == 404
|
|
assert len(anna.get("/api/tokens").json()) == 1
|
|
|
|
|
|
# --- Using tokens ---------------------------------------------------------------
|
|
|
|
|
|
def test_token_works_without_cookie_or_csrf(agent):
|
|
assert agent.cookies.get("lc_session") is None
|
|
created = agent.post("/api/clips", json={"content": "from agent"})
|
|
assert created.status_code == 201
|
|
assert agent.get("/api/clips").json()["items"][0]["content"] == "from agent"
|
|
assert (
|
|
agent.patch(f"/api/clips/{created.json()['id']}", json={"pinned": True}).status_code == 200
|
|
)
|
|
assert agent.post("/api/files", params={"name": "a.txt"}, content=b"data").status_code == 201
|
|
assert agent.get("/api/projects").status_code == 200
|
|
assert agent.post("/api/projects", json={"name": "Zwischenablage"}).status_code == 201
|
|
|
|
|
|
def test_token_records_last_use(anna, agent):
|
|
agent.get("/api/clips")
|
|
token = anna.get("/api/tokens").json()[0]
|
|
assert token["last_used_at"] is not None
|
|
assert token["last_ip"] == "testclient"
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
("method", "path", "body"),
|
|
[
|
|
("GET", "/api/auth/me", None),
|
|
("GET", "/api/auth/sessions", None),
|
|
("POST", "/api/auth/password", {"current_password": "x", "new_password": "y" * 12}),
|
|
("GET", "/api/tokens", None),
|
|
("POST", "/api/tokens", {"name": "more"}),
|
|
("GET", "/api/admin/users", None),
|
|
("PATCH", "/api/projects/1", {"name": "x"}),
|
|
("DELETE", "/api/projects/1", None),
|
|
("POST", "/api/projects/1/members", {"username": "x"}),
|
|
],
|
|
)
|
|
def test_token_cannot_reach_account_admin_or_project_management(agent, method, path, body):
|
|
assert agent.request(method, path, json=body).status_code == 401
|
|
|
|
|
|
def test_admin_token_cannot_use_admin_api(client, make_user):
|
|
make_user("root", role=Role.ADMIN)
|
|
login(client, "root")
|
|
token = create_token(client)["token"]
|
|
with TestClient(client.app, base_url="https://testserver") as c:
|
|
response = c.get("/api/admin/users", headers={"Authorization": f"Bearer {token}"})
|
|
assert response.status_code == 401
|
|
|
|
|
|
@pytest.mark.parametrize("value", ["lc_wrong", "not-a-token", "", "Bearer"])
|
|
def test_invalid_tokens(client, value):
|
|
response = client.get("/api/clips", headers={"Authorization": f"Bearer {value}"})
|
|
assert response.status_code == 401
|
|
|
|
|
|
def test_revoked_token_stops_working(anna, agent):
|
|
token_id = anna.get("/api/tokens").json()[0]["id"]
|
|
assert anna.delete(f"/api/tokens/{token_id}").status_code == 204
|
|
assert agent.get("/api/clips").status_code == 401
|
|
assert anna.delete(f"/api/tokens/{token_id}").status_code == 404
|
|
|
|
|
|
def test_tokens_of_deactivated_or_deleted_users(anna, agent, db):
|
|
user = db.query(User).filter_by(username="anna").one()
|
|
user.is_active = False
|
|
db.commit()
|
|
assert agent.get("/api/clips").status_code == 401
|
|
|
|
db.delete(user)
|
|
db.commit()
|
|
assert db.query(ApiToken).count() == 0
|
|
|
|
|
|
def test_token_respects_data_separation(anna, client, make_user):
|
|
secret = anna.post("/api/clips", json={"content": "anna only"}).json()
|
|
make_user("bert")
|
|
with TestClient(client.app, base_url="https://testserver") as bert:
|
|
login(bert, "bert")
|
|
token = create_token(bert)["token"]
|
|
bert.cookies.clear()
|
|
bert.headers["Authorization"] = f"Bearer {token}"
|
|
assert bert.get("/api/clips").json()["items"] == []
|
|
assert bert.get(f"/api/clips/{secret['id']}").status_code == 404
|
|
assert bert.delete(f"/api/clips/{secret['id']}").status_code == 404
|
|
|
|
|
|
# --- WebSocket ------------------------------------------------------------------
|
|
|
|
|
|
def test_websocket_with_token_and_without_origin(anna):
|
|
token = create_token(anna)["token"]
|
|
with ws_with_token(anna, token) as ws:
|
|
assert ws.receive_json() == {"type": "hello"}
|
|
anna.post("/api/clips", json={"content": "to the agent"})
|
|
event = ws.receive_json()
|
|
assert (event["type"], event["data"]["content"]) == ("clip.created", "to the agent")
|
|
|
|
|
|
def test_websocket_token_with_foreign_origin_is_rejected(anna):
|
|
token = create_token(anna)["token"]
|
|
with (
|
|
pytest.raises(WebSocketDisconnect) as exc,
|
|
ws_with_token(anna, token, "https://evil.example") as ws,
|
|
):
|
|
ws.receive_json()
|
|
assert exc.value.code == 4403
|
|
|
|
|
|
def test_websocket_invalid_token_is_4401(client):
|
|
with pytest.raises(WebSocketDisconnect) as exc, ws_with_token(client, "lc_nope") as ws:
|
|
ws.receive_json()
|
|
ws.receive_json()
|
|
assert exc.value.code == 4401
|
|
|
|
|
|
def test_revoking_token_closes_its_socket_only(anna):
|
|
laptop = create_token(anna, "Laptop")
|
|
desktop = create_token(anna, "Desktop")
|
|
|
|
with ws_with_token(anna, desktop["token"]) as desktop_ws, connect(anna) as browser_ws:
|
|
desktop_ws.receive_json()
|
|
browser_ws.receive_json()
|
|
with (
|
|
pytest.raises(WebSocketDisconnect) as exc,
|
|
ws_with_token(anna, laptop["token"]) as laptop_ws,
|
|
):
|
|
laptop_ws.receive_json()
|
|
anna.delete(f"/api/tokens/{laptop['id']}")
|
|
laptop_ws.receive_json()
|
|
assert exc.value.code == 4401
|
|
|
|
anna.post("/api/clips", json={"content": "still live"})
|
|
assert desktop_ws.receive_json()["type"] == "clip.created"
|
|
assert browser_ws.receive_json()["type"] == "clip.created"
|
|
|
|
|
|
def test_token_socket_is_revalidated(anna, db, monkeypatch):
|
|
monkeypatch.setattr(ws_module, "PING_INTERVAL_SECONDS", 0.05)
|
|
monkeypatch.setattr(ws_module, "REVALIDATE_INTERVAL_SECONDS", 0)
|
|
token = create_token(anna)["token"]
|
|
|
|
with pytest.raises(WebSocketDisconnect) as exc, ws_with_token(anna, token) as ws:
|
|
assert ws.receive_json() == {"type": "hello"}
|
|
db.query(User).filter_by(username="anna").one().is_active = False
|
|
db.commit()
|
|
while True:
|
|
assert ws.receive_json() == {"type": "ping"}
|
|
assert exc.value.code == 4401
|