diff --git a/src/scrobbler/__init__.py b/src/scrobbler/__init__.py index dfd0cc9..e4ae041 100644 --- a/src/scrobbler/__init__.py +++ b/src/scrobbler/__init__.py @@ -11,16 +11,26 @@ def create_app(config_object=None): from scrobbler.extensions import db, migrate from scrobbler.metrics import http as http_metrics - app = Flask(__name__) + app = Flask(__name__, static_folder=None) # API only: the UI is hosted separately app.config.from_object(config_object or Config) db.init_app(app) migrate.init_app(app, db, directory=_migrations_dir()) http_metrics.init_app(app) + from flask_cors import CORS + + from scrobbler import api from scrobbler.lastfm import bp as lastfm_bp app.register_blueprint(lastfm_bp) + api.init_app(app) + CORS( + app, + resources={r"/api/v1/*": {"origins": app.config["CORS_ORIGINS"]}}, + allow_headers=["Authorization", "Content-Type"], + max_age=600, + ) if app.config["START_METRICS_SERVER"]: from scrobbler.metrics.server import start_metrics_server diff --git a/src/scrobbler/api/__init__.py b/src/scrobbler/api/__init__.py new file mode 100644 index 0000000..d15571d --- /dev/null +++ b/src/scrobbler/api/__init__.py @@ -0,0 +1,50 @@ +"""JSON REST API used by the web UI, mounted at /api/v1.""" + +from flask import Flask, jsonify +from flask_smorest import Api +from werkzeug.exceptions import HTTPException + +from scrobbler.schemas import ErrorSchema + +BEARER = [{"bearerAuth": []}] + + +class ScrobblerApi(Api): + ERROR_SCHEMA = ErrorSchema + + def handle_http_exception(self, error: HTTPException): + """Render every HTTP error as {"error": {"code", "message", "details"?}}.""" + data = getattr(error, "data", None) or {} + body = { + "code": data.get("code") or error.name.lower().replace(" ", "_"), + "message": data.get("message") or error.description, + } + details = data.get("errors") or data.get("messages") + if details: + body["details"] = details + response = jsonify({"error": body}) + response.status_code = error.code or 500 + for name, value in (data.get("headers") or {}).items(): + response.headers[name] = value + return response + + +api = ScrobblerApi() + + +def init_app(app: Flask) -> None: + api.init_app(app) + api.spec.components.security_scheme( + "bearerAuth", + { + "type": "http", + "scheme": "bearer", + "description": "Token from POST /api/v1/auth/login", + }, + ) + + from scrobbler.api import apps, auth, sessions + + api.register_blueprint(auth.blp, url_prefix="/api/v1/auth") + api.register_blueprint(apps.blp, url_prefix="/api/v1/apps") + api.register_blueprint(sessions.blp, url_prefix="/api/v1/sessions") diff --git a/src/scrobbler/api/apps.py b/src/scrobbler/api/apps.py new file mode 100644 index 0000000..1c2d754 --- /dev/null +++ b/src/scrobbler/api/apps.py @@ -0,0 +1,45 @@ +from flask import g +from flask_smorest import Blueprint, abort + +from scrobbler.api.decorators import authenticated +from scrobbler.schemas import ApiAppCreateSchema, ApiAppSchema, ErrorSchema +from scrobbler.services import accounts + +blp = Blueprint( + "ui_apps", + __name__, + description=( + "API applications. Each has an API key and shared secret that a scrobbling " + "client uses against the Last.fm-compatible `/2.0/` endpoint." + ), +) + + +@blp.route("", methods=["GET"]) +@authenticated(blp) +@blp.response(200, ApiAppSchema(many=True)) +def list_apps(): + """List your API applications""" + return accounts.list_api_apps(g.user) + + +@blp.route("", methods=["POST"]) +@authenticated(blp) +@blp.arguments(ApiAppCreateSchema) +@blp.response(201, ApiAppSchema) +def create_app(body): + """Create an API application""" + return accounts.create_api_app(g.user, body["name"]) + + +@blp.route("/", methods=["DELETE"]) +@authenticated(blp) +@blp.response(204) +@blp.alt_response(404, schema=ErrorSchema, description="No such application") +def delete_app(api_key): + """Delete an API application + + Also revokes every session issued to it. + """ + if not accounts.delete_api_app(g.user, api_key): + abort(404, code="not_found", message="No such application") diff --git a/src/scrobbler/api/auth.py b/src/scrobbler/api/auth.py new file mode 100644 index 0000000..214178e --- /dev/null +++ b/src/scrobbler/api/auth.py @@ -0,0 +1,61 @@ +from flask import g +from flask_smorest import Blueprint, abort + +from scrobbler import metrics +from scrobbler.api.decorators import authenticated, bearer_token +from scrobbler.schemas import ErrorSchema, LoginSchema, RegisterSchema, TokenSchema, UserSchema +from scrobbler.services import accounts + +blp = Blueprint("ui_auth", __name__, description="Web UI accounts and login") + + +@blp.route("/register", methods=["POST"]) +@blp.arguments(RegisterSchema) +@blp.response(201, TokenSchema) +@blp.alt_response(409, schema=ErrorSchema, description="Username taken") +@blp.alt_response(400, schema=ErrorSchema, description="Invalid username or password") +def register(body): + """Create an account + + Registers a user and logs them in, returning a bearer token. + """ + try: + user = accounts.register(body["username"], body["email"], body["password"]) + except accounts.AccountError as err: + abort(409 if err.code == "username_taken" else 400, code=err.code, message=err.message) + return {"token": accounts.issue_ui_token(user), "user": user} + + +@blp.route("/login", methods=["POST"]) +@blp.arguments(LoginSchema) +@blp.response(200, TokenSchema) +@blp.alt_response(401, schema=ErrorSchema, description="Wrong username or password") +def login(body): + """Log in + + Exchanges a username and password for a bearer token valid for 30 days. + """ + user = accounts.authenticate(body["username"], body["password"]) + metrics.ui_logins_total.labels(result="success" if user else "failure").inc() + if user is None: + abort(401, code="invalid_credentials", message="Wrong username or password") + return {"token": accounts.issue_ui_token(user), "user": user} + + +@blp.route("/logout", methods=["POST"]) +@authenticated(blp) +@blp.response(204) +def logout(): + """Log out + + Revokes the bearer token used for this request. + """ + accounts.revoke_ui_token(bearer_token()) + + +@blp.route("/me", methods=["GET"]) +@authenticated(blp) +@blp.response(200, UserSchema) +def me(): + """Current user""" + return g.user diff --git a/src/scrobbler/api/decorators.py b/src/scrobbler/api/decorators.py new file mode 100644 index 0000000..6ad0ddc --- /dev/null +++ b/src/scrobbler/api/decorators.py @@ -0,0 +1,43 @@ +import functools + +from flask import g, request +from flask_smorest import Blueprint, abort + +from scrobbler.api import BEARER +from scrobbler.schemas import ErrorSchema +from scrobbler.services import accounts + + +def bearer_token() -> str | None: + header = request.headers.get("Authorization", "") + scheme, _, token = header.partition(" ") + return token.strip() if scheme.lower() == "bearer" and token.strip() else None + + +def require_ui_token(func): + @functools.wraps(func) + def wrapper(*args, **kwargs): + token = bearer_token() + user = accounts.resolve_ui_token(token) if token else None + if user is None: + abort( + 401, + code="unauthorized", + message="Missing, invalid or expired bearer token", + headers={"WWW-Authenticate": "Bearer"}, + ) + g.user = user + return func(*args, **kwargs) + + return wrapper + + +def authenticated(blp: Blueprint): + """Require a UI bearer token and document it (security scheme + 401) in OpenAPI.""" + + def decorator(func): + func = require_ui_token(func) + func = blp.alt_response(401, schema=ErrorSchema, description="Not authenticated")(func) + return blp.doc(security=BEARER)(func) + + return decorator diff --git a/src/scrobbler/api/sessions.py b/src/scrobbler/api/sessions.py new file mode 100644 index 0000000..66bc565 --- /dev/null +++ b/src/scrobbler/api/sessions.py @@ -0,0 +1,33 @@ +from flask import g +from flask_smorest import Blueprint, abort + +from scrobbler.api.decorators import authenticated +from scrobbler.schemas import ErrorSchema, SessionSchema +from scrobbler.services import accounts + +blp = Blueprint( + "ui_sessions", + __name__, + description="Last.fm session keys issued to scrobbling clients on your behalf.", +) + + +@blp.route("", methods=["GET"]) +@authenticated(blp) +@blp.response(200, SessionSchema(many=True)) +def list_sessions(): + """List client sessions""" + return accounts.list_sessions(g.user) + + +@blp.route("/", methods=["DELETE"]) +@authenticated(blp) +@blp.response(204) +@blp.alt_response(404, schema=ErrorSchema, description="No such session") +def revoke_session(session_id): + """Revoke a client session + + The client's session key stops working immediately (Last.fm error 9). + """ + if not accounts.revoke_session(g.user, session_id): + abort(404, code="not_found", message="No such session") diff --git a/src/scrobbler/config.py b/src/scrobbler/config.py index 7f7f337..1963f9d 100644 --- a/src/scrobbler/config.py +++ b/src/scrobbler/config.py @@ -25,6 +25,30 @@ class Config: # server is started by gunicorn.conf.py instead, so this stays off there. START_METRICS_SERVER = os.environ.get("START_METRICS_SERVER", "0") == "1" + # OpenAPI document and docs (flask-smorest) + API_TITLE = "Scrobbler API" + API_VERSION = "v1" + OPENAPI_VERSION = "3.1.0" + OPENAPI_URL_PREFIX = "/api" + OPENAPI_JSON_PATH = "openapi.json" + OPENAPI_DOCS_ENABLED = os.environ.get("OPENAPI_DOCS_ENABLED", "1") == "1" + OPENAPI_SWAGGER_UI_PATH = "docs" if OPENAPI_DOCS_ENABLED else None + OPENAPI_SWAGGER_UI_URL = os.environ.get( + "OPENAPI_SWAGGER_UI_URL", "https://cdn.jsdelivr.net/npm/swagger-ui-dist@5/" + ) + OPENAPI_REDOC_PATH = "redoc" if OPENAPI_DOCS_ENABLED else None + OPENAPI_REDOC_URL = os.environ.get( + "OPENAPI_REDOC_URL", "https://cdn.jsdelivr.net/npm/redoc@2/bundles/redoc.standalone.js" + ) + API_SPEC_OPTIONS = { + "info": { + "description": ( + "Two APIs: `/2.0/` is Last.fm (Audioscrobbler 2.0) compatible, for players " + "and scrobblers; `/api/v1/` is the JSON API used by the web UI." + ) + }, + } + # Last.fm behaviour AUTH_TOKEN_TTL_SECONDS = 60 * 60 UI_TOKEN_TTL_DAYS = 30 diff --git a/src/scrobbler/schemas/__init__.py b/src/scrobbler/schemas/__init__.py new file mode 100644 index 0000000..b827c70 --- /dev/null +++ b/src/scrobbler/schemas/__init__.py @@ -0,0 +1,58 @@ +"""Marshmallow schemas for the /api/v1 JSON API. They drive both request +validation and the generated OpenAPI document.""" + +from marshmallow import Schema, fields, validate + + +class ErrorDetailSchema(Schema): + code = fields.String(required=True, metadata={"example": "invalid_credentials"}) + message = fields.String(required=True, metadata={"example": "Wrong username or password"}) + details = fields.Dict(metadata={"description": "Per-field validation errors, if any"}) + + +class ErrorSchema(Schema): + error = fields.Nested(ErrorDetailSchema, required=True) + + +class UserSchema(Schema): + id = fields.Integer(dump_only=True) + username = fields.String(dump_only=True, metadata={"example": "alice"}) + email = fields.String(dump_only=True, metadata={"example": "alice@example.com"}) + created_at = fields.DateTime(dump_only=True) + + +class RegisterSchema(Schema): + username = fields.String(required=True, validate=validate.Length(min=2, max=32)) + email = fields.Email(required=True) + password = fields.String(required=True, load_only=True, validate=validate.Length(min=8)) + + +class LoginSchema(Schema): + username = fields.String(required=True) + password = fields.String(required=True, load_only=True) + + +class TokenSchema(Schema): + token = fields.String( + required=True, metadata={"description": "Bearer token for the Authorization header"} + ) + user = fields.Nested(UserSchema, required=True) + + +class ApiAppSchema(Schema): + name = fields.String(dump_only=True, metadata={"example": "Living room player"}) + api_key = fields.String(dump_only=True, metadata={"example": "a" * 32}) + shared_secret = fields.String(dump_only=True, metadata={"example": "b" * 32}) + created_at = fields.DateTime(dump_only=True) + + +class ApiAppCreateSchema(Schema): + name = fields.String(required=True, validate=validate.Length(min=1, max=100)) + + +class SessionSchema(Schema): + id = fields.Integer(dump_only=True) + app_name = fields.String( + dump_only=True, attribute="api_app.name", metadata={"example": "Pano Scrobbler"} + ) + created_at = fields.DateTime(dump_only=True) diff --git a/src/scrobbler/services/__init__.py b/src/scrobbler/services/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/scrobbler/services/accounts.py b/src/scrobbler/services/accounts.py new file mode 100644 index 0000000..d7b57e0 --- /dev/null +++ b/src/scrobbler/services/accounts.py @@ -0,0 +1,143 @@ +"""Users, UI bearer tokens, API applications and Last.fm sessions.""" + +import hashlib +import re +import secrets +from datetime import UTC, datetime, timedelta + +from flask import current_app +from sqlalchemy import func +from werkzeug.security import check_password_hash, generate_password_hash + +from scrobbler import metrics +from scrobbler.extensions import db +from scrobbler.models import ApiApp, Session, UiToken, User + +USERNAME_RE = re.compile(r"^[A-Za-z0-9_.-]{2,32}$") +MIN_PASSWORD_LENGTH = 8 +# Checked against when the username doesn't exist, so failed logins take the same time. +_DUMMY_HASH = generate_password_hash("not-a-real-password") + + +class AccountError(Exception): + def __init__(self, code: str, message: str): + self.code, self.message = code, message + super().__init__(message) + + +def _now() -> datetime: + return datetime.now(UTC) + + +def _sha256(value: str) -> str: + return hashlib.sha256(value.encode()).hexdigest() + + +# --- Users --------------------------------------------------------------------- + + +def find_user(username: str) -> User | None: + return db.session.scalar(db.select(User).where(func.lower(User.username) == username.lower())) + + +def register(username: str, email: str, password: str) -> User: + if not USERNAME_RE.match(username): + raise AccountError( + "invalid_username", "Usernames are 2-32 letters, digits, dots, dashes or underscores" + ) + if len(password) < MIN_PASSWORD_LENGTH: + raise AccountError( + "weak_password", f"Passwords must be at least {MIN_PASSWORD_LENGTH} characters" + ) + if find_user(username) is not None: + raise AccountError("username_taken", "That username is already taken") + user = User(username=username, email=email, password_hash=generate_password_hash(password)) + db.session.add(user) + db.session.commit() + metrics.registrations_total.inc() + return user + + +def authenticate(username: str, password: str) -> User | None: + user = find_user(username) + if user is None: + check_password_hash(_DUMMY_HASH, password) + return None + return user if check_password_hash(user.password_hash, password) else None + + +# --- UI bearer tokens ---------------------------------------------------------- + + +def issue_ui_token(user: User) -> str: + raw = secrets.token_urlsafe(32) + ttl = timedelta(days=current_app.config["UI_TOKEN_TTL_DAYS"]) + db.session.add(UiToken(token_hash=_sha256(raw), user=user, expires_at=_now() + ttl)) + db.session.commit() + return raw + + +def resolve_ui_token(raw: str) -> User | None: + token = db.session.scalar(db.select(UiToken).filter_by(token_hash=_sha256(raw))) + if token is None or token.expires_at <= _now(): + return None + if _now() - token.last_used_at > timedelta(minutes=1): + token.last_used_at = _now() + db.session.commit() + return token.user + + +def revoke_ui_token(raw: str) -> None: + db.session.execute(db.delete(UiToken).filter_by(token_hash=_sha256(raw))) + db.session.commit() + + +# --- API applications ---------------------------------------------------------- + + +def list_api_apps(user: User) -> list[ApiApp]: + return list( + db.session.scalars( + db.select(ApiApp).filter_by(owner_id=user.id).order_by(ApiApp.created_at) + ) + ) + + +def create_api_app(user: User, name: str) -> ApiApp: + api_app = ApiApp( + api_key=secrets.token_hex(16), shared_secret=secrets.token_hex(16), name=name, owner=user + ) + db.session.add(api_app) + db.session.commit() + return api_app + + +def delete_api_app(user: User, api_key: str) -> bool: + result = db.session.execute(db.delete(ApiApp).filter_by(owner_id=user.id, api_key=api_key)) + db.session.commit() + return result.rowcount > 0 + + +# --- Last.fm sessions ---------------------------------------------------------- + + +def create_session(user: User, api_app: ApiApp, flow: str) -> Session: + session = Session(session_key=secrets.token_hex(16), user=user, api_app=api_app) + db.session.add(session) + db.session.commit() + metrics.auth_sessions_created_total.labels(flow=flow).inc() + return session + + +def list_sessions(user: User) -> list[Session]: + return list( + db.session.scalars( + db.select(Session).filter_by(user_id=user.id).order_by(Session.created_at.desc()) + ) + ) + + +def revoke_session(user: User, session_id: int) -> bool: + result = db.session.execute(db.delete(Session).filter_by(user_id=user.id, id=session_id)) + db.session.commit() + return result.rowcount > 0 diff --git a/tests/conftest.py b/tests/conftest.py index 00628a9..0346354 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -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}"} diff --git a/tests/test_ui_apps_sessions.py b/tests/test_ui_apps_sessions.py new file mode 100644 index 0000000..1c2437d --- /dev/null +++ b/tests/test_ui_apps_sessions.py @@ -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) diff --git a/tests/test_ui_auth.py b/tests/test_ui_auth.py new file mode 100644 index 0000000..9563b8b --- /dev/null +++ b/tests/test_ui_auth.py @@ -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