From 7622f7433a84c18a836ba00e426da11a22874572 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 14:01:12 +0100 Subject: [PATCH] Last.fm auth: mobile sessions and the desktop token flow - auth.getMobileSession (username + password), auth.getToken and auth.getSession with Last.fm error codes 4/14/15 - /api/auth/ redirects clients' approval links to the web UI's approve page; /api/v1/tokens lets the UI show and approve a token - Tokens expire after an hour, are single use and bound to their app - The legacy md5 authToken form is deliberately unsupported (it needs unsalted password hashes) Co-Authored-By: Claude Opus 5.5 --- src/scrobbler/api/__init__.py | 3 +- src/scrobbler/api/tokens.py | 50 +++++++++++++ src/scrobbler/lastfm/__init__.py | 10 ++- src/scrobbler/lastfm/methods/__init__.py | 2 + src/scrobbler/lastfm/methods/auth.py | 76 +++++++++++++++++++ src/scrobbler/schemas/__init__.py | 11 +++ src/scrobbler/services/accounts.py | 50 ++++++++++++- tests/test_lastfm_auth.py | 93 ++++++++++++++++++++++++ 8 files changed, 292 insertions(+), 3 deletions(-) create mode 100644 src/scrobbler/api/tokens.py create mode 100644 src/scrobbler/lastfm/methods/auth.py create mode 100644 tests/test_lastfm_auth.py diff --git a/src/scrobbler/api/__init__.py b/src/scrobbler/api/__init__.py index d15571d..2cc6e0d 100644 --- a/src/scrobbler/api/__init__.py +++ b/src/scrobbler/api/__init__.py @@ -43,8 +43,9 @@ def init_app(app: Flask) -> None: }, ) - from scrobbler.api import apps, auth, sessions + from scrobbler.api import apps, auth, sessions, tokens 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") + api.register_blueprint(tokens.blp, url_prefix="/api/v1/tokens") diff --git a/src/scrobbler/api/tokens.py b/src/scrobbler/api/tokens.py new file mode 100644 index 0000000..2c6394e --- /dev/null +++ b/src/scrobbler/api/tokens.py @@ -0,0 +1,50 @@ +from flask import g +from flask_smorest import Blueprint, abort + +from scrobbler.api.decorators import authenticated +from scrobbler.schemas import ApproveTokenSchema, AuthTokenInfoSchema, ErrorSchema +from scrobbler.services import accounts + +blp = Blueprint( + "ui_tokens", + __name__, + description=( + "Approve Last.fm desktop-auth tokens. Clients send the user to `/api/auth/`, " + "which redirects to the UI's approve page, which calls these endpoints." + ), +) + + +def _token_or_404(token: str): + try: + return accounts.get_auth_token(token) + except accounts.AuthTokenError as err: + abort(404, code=f"token_{err.reason}", message="Unknown or expired token") + + +@blp.route("/", methods=["GET"]) +@authenticated(blp) +@blp.response(200, AuthTokenInfoSchema) +@blp.alt_response(404, schema=ErrorSchema, description="Unknown or expired token") +def token_info(token): + """Describe a token awaiting approval + + Returns the name of the application asking for access. + """ + auth_token = _token_or_404(token) + return {"api_app": auth_token.api_app, "approved": auth_token.user_id is not None} + + +@blp.route("/approve", methods=["POST"]) +@authenticated(blp) +@blp.arguments(ApproveTokenSchema) +@blp.response(204) +@blp.alt_response(404, schema=ErrorSchema, description="Unknown or expired token") +def approve(body): + """Approve a token + + Grants the requesting application a session for your account once it calls + auth.getSession. + """ + _token_or_404(body["token"]) + accounts.approve_auth_token(g.user, body["token"]) diff --git a/src/scrobbler/lastfm/__init__.py b/src/scrobbler/lastfm/__init__.py index 6350715..740f379 100644 --- a/src/scrobbler/lastfm/__init__.py +++ b/src/scrobbler/lastfm/__init__.py @@ -2,7 +2,7 @@ import time -from flask import Blueprint, Response, request +from flask import Blueprint, Response, current_app, redirect, request from scrobbler import metrics from scrobbler.extensions import db @@ -92,4 +92,12 @@ def dispatch() -> Response: return response +@bp.route("/api/auth/", methods=["GET"], strict_slashes=False) +def approve_redirect() -> Response: + """Where Last.fm clients send users to approve a token. Approval happens in the + separately hosted web UI, so hand the query string over to its approve page.""" + query = request.query_string.decode() + return redirect(f"{current_app.config['UI_BASE_URL']}/approve.html?{query}", code=302) + + from scrobbler.lastfm import methods # noqa: E402,F401 (register handlers) diff --git a/src/scrobbler/lastfm/methods/__init__.py b/src/scrobbler/lastfm/methods/__init__.py index 6eb23d4..9dfe015 100644 --- a/src/scrobbler/lastfm/methods/__init__.py +++ b/src/scrobbler/lastfm/methods/__init__.py @@ -1 +1,3 @@ """Importing this package registers every Last.fm method handler.""" + +from scrobbler.lastfm.methods import auth # noqa: F401 diff --git a/src/scrobbler/lastfm/methods/auth.py b/src/scrobbler/lastfm/methods/auth.py new file mode 100644 index 0000000..db97099 --- /dev/null +++ b/src/scrobbler/lastfm/methods/auth.py @@ -0,0 +1,76 @@ +from scrobbler.lastfm import errors +from scrobbler.lastfm.errors import LastFMError +from scrobbler.lastfm.registry import Call, Param, lastfm_method +from scrobbler.lastfm.responses import El +from scrobbler.services import accounts + + +def _session_el(session) -> El: + return El.of( + "session", + El.text_el("name", session.user.username), + El.text_el("key", session.session_key), + El.text_el("subscriber", 0), + ) + + +@lastfm_method( + "auth.getMobileSession", + summary="Create a session key from a username and password", + signed=True, + params=( + Param("username", "Username", required=True, example="alice"), + Param("password", "Password (send over HTTPS, as a POST body)", required=True), + ), + notes=( + "The legacy `authToken` (md5 of username + md5(password)) form is not supported, " + "because it requires storing unsalted password hashes. Clients that only support " + "it (such as pylast's `password_hash`) should use the desktop flow instead." + ), + example_xml=( + 'aliced580d57f32848f5dcf574d1ce18d78b2' + "0" + ), +) +def get_mobile_session(call: Call) -> El: + user = accounts.authenticate(call.params["username"], call.params["password"]) + if user is None: + raise LastFMError(errors.AUTHENTICATION_FAILED, "Invalid username or password") + return _session_el(accounts.create_session(user, call.api_app, flow="mobile")) + + +@lastfm_method( + "auth.getToken", + summary="Fetch an unapproved request token (desktop auth flow, step 1)", + signed=True, + notes=( + "Send the user to `/api/auth/?api_key=…&token=…` to approve the token, then call " + "auth.getSession. Tokens expire after 60 minutes." + ), + example_xml='cf45fe5a3e3cebe168480a086d7fe481', +) +def get_token(call: Call) -> El: + return El.text_el("token", accounts.create_auth_token(call.api_app)) + + +@lastfm_method( + "auth.getSession", + summary="Exchange an approved token for a session key (desktop auth flow, step 3)", + signed=True, + params=(Param("token", "Token from auth.getToken, approved by the user", required=True),), + example_xml=( + 'aliced580d57f32848f5dcf574d1ce18d78b2' + "0" + ), +) +def get_session(call: Call) -> El: + try: + session = accounts.exchange_auth_token(call.api_app, call.params["token"]) + except accounts.AuthTokenError as err: + code = { + "expired": errors.TOKEN_EXPIRED, + "unauthorized": errors.UNAUTHORIZED_TOKEN, + }.get(err.reason, errors.AUTHENTICATION_FAILED) + message = "Invalid authentication token supplied" if err.reason == "invalid" else None + raise LastFMError(code, message) from err + return _session_el(session) diff --git a/src/scrobbler/schemas/__init__.py b/src/scrobbler/schemas/__init__.py index b827c70..e383e4e 100644 --- a/src/scrobbler/schemas/__init__.py +++ b/src/scrobbler/schemas/__init__.py @@ -56,3 +56,14 @@ class SessionSchema(Schema): dump_only=True, attribute="api_app.name", metadata={"example": "Pano Scrobbler"} ) created_at = fields.DateTime(dump_only=True) + + +class AuthTokenInfoSchema(Schema): + app_name = fields.String( + dump_only=True, attribute="api_app.name", metadata={"example": "Pano Scrobbler"} + ) + approved = fields.Boolean(dump_only=True) + + +class ApproveTokenSchema(Schema): + token = fields.String(required=True, metadata={"description": "Token from auth.getToken"}) diff --git a/src/scrobbler/services/accounts.py b/src/scrobbler/services/accounts.py index d7b57e0..c5e3bc2 100644 --- a/src/scrobbler/services/accounts.py +++ b/src/scrobbler/services/accounts.py @@ -11,7 +11,7 @@ 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 +from scrobbler.models import ApiApp, AuthToken, Session, UiToken, User USERNAME_RE = re.compile(r"^[A-Za-z0-9_.-]{2,32}$") MIN_PASSWORD_LENGTH = 8 @@ -141,3 +141,51 @@ 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 + + +# --- Last.fm desktop auth tokens ----------------------------------------------- + + +class AuthTokenError(Exception): + """Raised with a reason: "invalid", "expired" or "unauthorized".""" + + def __init__(self, reason: str): + self.reason = reason + super().__init__(reason) + + +def create_auth_token(api_app: ApiApp) -> str: + token = AuthToken(token=secrets.token_hex(16), api_app=api_app) + db.session.add(token) + db.session.commit() + return token.token + + +def get_auth_token(token: str) -> AuthToken: + """A token that exists and hasn't expired, or AuthTokenError.""" + auth_token = db.session.scalar(db.select(AuthToken).filter_by(token=token)) + if auth_token is None: + raise AuthTokenError("invalid") + ttl = timedelta(seconds=current_app.config["AUTH_TOKEN_TTL_SECONDS"]) + if auth_token.created_at + ttl <= _now(): + raise AuthTokenError("expired") + return auth_token + + +def approve_auth_token(user: User, token: str) -> AuthToken: + auth_token = get_auth_token(token) + auth_token.user = user + db.session.commit() + return auth_token + + +def exchange_auth_token(api_app: ApiApp, token: str) -> Session: + """Swap an approved token for a session key. Tokens are single use.""" + auth_token = get_auth_token(token) + if auth_token.api_app_id != api_app.id: + raise AuthTokenError("invalid") + if auth_token.user is None: + raise AuthTokenError("unauthorized") + user = auth_token.user + db.session.delete(auth_token) + return create_session(user, api_app, flow="desktop") diff --git a/tests/test_lastfm_auth.py b/tests/test_lastfm_auth.py new file mode 100644 index 0000000..8b7212f --- /dev/null +++ b/tests/test_lastfm_auth.py @@ -0,0 +1,93 @@ +import xml.etree.ElementTree as ET +from datetime import UTC, datetime, timedelta +from urllib.parse import parse_qs, urlsplit + +from conftest import signed +from scrobbler.extensions import db +from scrobbler.models import AuthToken, Session + + +def call(client, api_app, method, **params): + data = signed({"method": method, "api_key": api_app.api_key, **params}, api_app.shared_secret) + return ET.fromstring(client.post("/2.0/", data=data).data) + + +def error_code(root): + return root.find("error").get("code") + + +def test_mobile_session(client, api_app, user, metric_delta): + created = metric_delta("scrobbler_auth_sessions_created_total", flow="mobile") + root = call(client, api_app, "auth.getMobileSession", username="ALICE", password="hunter22") + assert root.find("session/name").text == "alice" + key = root.find("session/key").text + assert db.session.scalar(db.select(Session).filter_by(session_key=key)).user_id == user.id + assert created.delta == 1 + + +def test_mobile_session_bad_password(client, api_app, user, metric_delta): + failures = metric_delta("scrobbler_auth_failures_total", reason="bad_password") + root = call(client, api_app, "auth.getMobileSession", username="alice", password="nope") + assert error_code(root) == "4" + assert failures.delta == 1 + + +def test_mobile_session_requires_signature(client, api_app, user): + params = { + "method": "auth.getMobileSession", + "api_key": api_app.api_key, + "username": "alice", + "password": "hunter22", + } + assert error_code(ET.fromstring(client.post("/2.0/", data=params).data)) == "13" + + +def test_desktop_flow(client, api_app, user, auth, metric_delta): + created = metric_delta("scrobbler_auth_sessions_created_total", flow="desktop") + token = call(client, api_app, "auth.getToken").find("token").text + + # Not approved yet + assert error_code(call(client, api_app, "auth.getSession", token=token)) == "14" + + # The client sends the user to /api/auth/, which hands over to the UI + redirect = client.get(f"/api/auth/?api_key={api_app.api_key}&token={token}") + assert redirect.status_code == 302 + location = urlsplit(redirect.headers["Location"]) + assert location.path == "/approve.html" + assert parse_qs(location.query) == {"api_key": [api_app.api_key], "token": [token]} + + # The UI shows who is asking, then approves + info = client.get(f"/api/v1/tokens/{token}", headers=auth).get_json() + assert info == {"app_name": api_app.name, "approved": False} + approved = client.post("/api/v1/tokens/approve", json={"token": token}, headers=auth) + assert approved.status_code == 204 + + root = call(client, api_app, "auth.getSession", token=token) + assert root.find("session/name").text == "alice" + assert created.delta == 1 + + # Tokens are single use + assert error_code(call(client, api_app, "auth.getSession", token=token)) == "4" + + +def test_token_is_bound_to_its_app(client, api_app, make_app, user, auth): + token = call(client, api_app, "auth.getToken").find("token").text + client.post("/api/v1/tokens/approve", json={"token": token}, headers=auth) + other_app = make_app(owner=user) + assert error_code(call(client, other_app, "auth.getSession", token=token)) == "4" + + +def test_expired_token(client, api_app, auth): + token = call(client, api_app, "auth.getToken").find("token").text + auth_token = db.session.scalar(db.select(AuthToken).filter_by(token=token)) + auth_token.created_at = datetime.now(UTC) - timedelta(hours=2) + db.session.commit() + + assert error_code(call(client, api_app, "auth.getSession", token=token)) == "15" + response = client.post("/api/v1/tokens/approve", json={"token": token}, headers=auth) + assert response.status_code == 404 + assert response.get_json()["error"]["code"] == "token_expired" + + +def test_unknown_token_in_ui(client, auth): + assert client.get("/api/v1/tokens/nope", headers=auth).status_code == 404