UI REST API: accounts, bearer auth, API apps, sessions, OpenAPI docs
- flask-smorest API under /api/v1 with a uniform JSON error shape; spec at /api/openapi.json, Swagger UI at /api/docs, ReDoc at /api/redoc - Register/login/logout/me with hashed, expiring bearer tokens, documented as an OpenAPI bearer security scheme - API application and client-session management endpoints - CORS restricted to the configured UI origin(s) - Flask no longer serves static files: it is API-only - Login and registration metrics Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9af8a4be8b
commit
e026e56ee3
13 files changed
+626
-1
No files matched your search
@@ -26,6 +26,7 @@ def _clean_tables(app):
|
||||
tables = ", ".join(t.name for t in db.metadata.sorted_tables)
|
||||
db.session.execute(text(f"TRUNCATE {tables} RESTART IDENTITY CASCADE"))
|
||||
db.session.commit()
|
||||
db.session.remove() # drop identities that pointed at truncated rows
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -128,3 +129,16 @@ def signed(params: dict, secret: str) -> dict:
|
||||
|
||||
def days_ago(days: float) -> int:
|
||||
return int((datetime.now(UTC) - timedelta(days=days)).timestamp())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def ui_token(user):
|
||||
from scrobbler.services.accounts import issue_ui_token
|
||||
|
||||
return issue_ui_token(user)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth(ui_token):
|
||||
"""Authorization headers for the default user."""
|
||||
return {"Authorization": f"Bearer {ui_token}"}
|
||||
@@ -0,0 +1,35 @@
|
||||
from conftest import signed
|
||||
|
||||
|
||||
def test_app_crud(client, auth):
|
||||
created = client.post("/api/v1/apps", json={"name": "Player"}, headers=auth)
|
||||
assert created.status_code == 201
|
||||
app_ = created.get_json()
|
||||
assert len(app_["api_key"]) == len(app_["shared_secret"]) == 32
|
||||
|
||||
listed = client.get("/api/v1/apps", headers=auth).get_json()
|
||||
assert [a["api_key"] for a in listed] == [app_["api_key"]]
|
||||
|
||||
assert client.delete(f"/api/v1/apps/{app_['api_key']}", headers=auth).status_code == 204
|
||||
assert client.get("/api/v1/apps", headers=auth).get_json() == []
|
||||
assert client.delete(f"/api/v1/apps/{app_['api_key']}", headers=auth).status_code == 404
|
||||
|
||||
|
||||
def test_cannot_touch_other_users_apps(client, auth, make_user, make_app):
|
||||
other = make_app(owner=make_user(username="mallory"))
|
||||
assert client.delete(f"/api/v1/apps/{other.api_key}", headers=auth).status_code == 404
|
||||
assert client.get("/api/v1/apps", headers=auth).get_json() == []
|
||||
|
||||
|
||||
def test_revoked_session_key_stops_working(client, auth, api_app, session_key):
|
||||
sessions = client.get("/api/v1/sessions", headers=auth).get_json()
|
||||
assert [s["app_name"] for s in sessions] == [api_app.name]
|
||||
|
||||
assert client.delete(f"/api/v1/sessions/{sessions[0]['id']}", headers=auth).status_code == 204
|
||||
params = signed(
|
||||
{"method": "track.updateNowPlaying", "api_key": api_app.api_key, "sk": session_key},
|
||||
api_app.shared_secret,
|
||||
)
|
||||
# The method is registered in a later step; the session check runs first either way.
|
||||
response = client.post("/2.0/", data={**params, "format": "json"})
|
||||
assert response.get_json()["error"] in (3, 9)
|
||||
@@ -0,0 +1,109 @@
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
from scrobbler.extensions import db
|
||||
from scrobbler.models import UiToken
|
||||
|
||||
|
||||
def register(client, username="bob", password="correct horse", email=None):
|
||||
return client.post(
|
||||
"/api/v1/auth/register",
|
||||
json={
|
||||
"username": username,
|
||||
"email": email or f"{username}@example.com",
|
||||
"password": password,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_register_returns_token_and_user(client, metric_delta):
|
||||
registrations = metric_delta("scrobbler_registrations_total")
|
||||
response = register(client)
|
||||
assert response.status_code == 201
|
||||
body = response.get_json()
|
||||
assert body["user"]["username"] == "bob"
|
||||
assert "password" not in body["user"]
|
||||
me = client.get("/api/v1/auth/me", headers={"Authorization": f"Bearer {body['token']}"})
|
||||
assert me.get_json()["username"] == "bob"
|
||||
assert registrations.delta == 1
|
||||
|
||||
|
||||
def test_usernames_are_unique_case_insensitively(client):
|
||||
register(client, "Bob")
|
||||
response = register(client, "bOB")
|
||||
assert response.status_code == 409
|
||||
assert response.get_json()["error"]["code"] == "username_taken"
|
||||
|
||||
|
||||
def test_register_validation_errors_use_error_shape(client):
|
||||
response = register(client, password="short")
|
||||
assert response.status_code == 422
|
||||
error = response.get_json()["error"]
|
||||
assert error["code"] == "unprocessable_entity"
|
||||
assert "password" in error["details"]["json"]
|
||||
|
||||
|
||||
def test_invalid_username_is_rejected(client):
|
||||
response = register(client, username="no spaces", email="nospaces@example.com")
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["error"]["code"] == "invalid_username"
|
||||
|
||||
|
||||
def test_login(client, user, metric_delta):
|
||||
ok = metric_delta("scrobbler_ui_logins_total", result="success")
|
||||
failed = metric_delta("scrobbler_ui_logins_total", result="failure")
|
||||
|
||||
response = client.post("/api/v1/auth/login", json={"username": "ALICE", "password": "hunter22"})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["user"]["username"] == "alice"
|
||||
|
||||
bad = client.post("/api/v1/auth/login", json={"username": "alice", "password": "wrong"})
|
||||
assert bad.status_code == 401
|
||||
assert bad.get_json()["error"]["code"] == "invalid_credentials"
|
||||
nobody = client.post("/api/v1/auth/login", json={"username": "nobody", "password": "x"})
|
||||
assert nobody.status_code == 401
|
||||
assert (ok.delta, failed.delta) == (1, 2)
|
||||
|
||||
|
||||
def test_protected_routes_need_a_token(client):
|
||||
for headers in ({}, {"Authorization": "Bearer nope"}, {"Authorization": "Basic abc"}):
|
||||
response = client.get("/api/v1/auth/me", headers=headers)
|
||||
assert response.status_code == 401
|
||||
assert response.headers["WWW-Authenticate"] == "Bearer"
|
||||
assert response.get_json()["error"]["code"] == "unauthorized"
|
||||
|
||||
|
||||
def test_logout_revokes_the_token(client, auth):
|
||||
assert client.post("/api/v1/auth/logout", headers=auth).status_code == 204
|
||||
assert client.get("/api/v1/auth/me", headers=auth).status_code == 401
|
||||
|
||||
|
||||
def test_expired_tokens_are_rejected(client, auth):
|
||||
for token in db.session.scalars(db.select(UiToken)):
|
||||
token.expires_at = datetime.now(UTC) - timedelta(seconds=1)
|
||||
db.session.commit()
|
||||
assert client.get("/api/v1/auth/me", headers=auth).status_code == 401
|
||||
|
||||
|
||||
def test_cors_allows_only_the_configured_ui_origin(client, app):
|
||||
allowed = app.config["CORS_ORIGINS"][0]
|
||||
preflight = {
|
||||
"Access-Control-Request-Method": "GET",
|
||||
"Access-Control-Request-Headers": "Authorization",
|
||||
}
|
||||
ok = client.options("/api/v1/auth/me", headers={"Origin": allowed, **preflight})
|
||||
assert ok.headers["Access-Control-Allow-Origin"] == allowed
|
||||
assert "authorization" in ok.headers["Access-Control-Allow-Headers"].lower()
|
||||
|
||||
evil = client.options(
|
||||
"/api/v1/auth/me", headers={"Origin": "https://evil.example", **preflight}
|
||||
)
|
||||
assert "Access-Control-Allow-Origin" not in evil.headers
|
||||
|
||||
|
||||
def test_api_docs_are_served(client):
|
||||
spec = client.get("/api/openapi.json").get_json()
|
||||
assert "/api/v1/auth/login" in spec["paths"]
|
||||
assert spec["components"]["securitySchemes"]["bearerAuth"]["scheme"] == "bearer"
|
||||
assert spec["paths"]["/api/v1/auth/me"]["get"]["security"] == [{"bearerAuth": []}]
|
||||
assert client.get("/api/docs").status_code == 200
|
||||
assert client.get("/api/redoc").status_code == 200
|
||||
Reference in new issue
Block a user