Last.fm API core: signatures, XML/JSON responses and dispatcher
CI / test (push) Successful in 21s
CI / lint (push) Successful in 45s
CI / notify (push) Successful in 5s

- /2.0/ dispatcher backed by a method registry that declares each
  method's params and signature/session requirements
- api_sig verification per the Last.fm auth spec
- XML (default) and Last.fm-style JSON rendering, including error shapes
  and HTTP statuses per error code
- Last.fm request, error and auth-failure metrics with bounded labels

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
mattandClaude Opus 5.5 committed 2026-09-25 13:57:36 +01:00
1 parent ae8d3b65db
commit 9af8a4be8b
11 files changed
+585

No files matched your search

+1
View File
@@ -24,6 +24,7 @@ packages = ["src/scrobbler"]
[tool.pytest.ini_options]
testpaths = ["tests"]
pythonpath = ["tests"]
addopts = "-ra"
[tool.ruff]
+4
View File
@@ -18,6 +18,10 @@ def create_app(config_object=None):
migrate.init_app(app, db, directory=_migrations_dir())
http_metrics.init_app(app)
from scrobbler.lastfm import bp as lastfm_bp
app.register_blueprint(lastfm_bp)
if app.config["START_METRICS_SERVER"]:
from scrobbler.metrics.server import start_metrics_server
+95
View File
@@ -0,0 +1,95 @@
"""Last.fm / Audioscrobbler 2.0 compatible API, mounted at /2.0/."""
import time
from flask import Blueprint, Response, request
from scrobbler import metrics
from scrobbler.extensions import db
from scrobbler.lastfm import errors, signature
from scrobbler.lastfm.errors import LastFMError
from scrobbler.lastfm.registry import METHODS, Call, LastfmMethod
from scrobbler.lastfm.responses import render, render_error
from scrobbler.models import ApiApp, Session
bp = Blueprint("lastfm", __name__)
_AUTH_FAILURE_REASONS = {
errors.INVALID_API_KEY: "bad_api_key",
errors.INVALID_SIGNATURE: "bad_signature",
errors.INVALID_SESSION_KEY: "bad_session",
errors.AUTHENTICATION_FAILED: "bad_password",
errors.TOKEN_EXPIRED: "token_expired",
errors.UNAUTHORIZED_TOKEN: "token_unauthorized",
}
def _request_params() -> dict[str, str]:
# Clients send params in the query string (GET) or a form body (POST); body wins.
params = request.args.to_dict()
params.update(request.form.to_dict())
return params
def _authenticate(method: LastfmMethod, params: dict[str, str], fmt: str) -> Call:
api_key = params.get("api_key")
if not api_key:
raise LastFMError(errors.INVALID_PARAMETERS, "Missing required parameter: api_key")
api_app = db.session.scalar(db.select(ApiApp).filter_by(api_key=api_key))
if api_app is None:
raise LastFMError(errors.INVALID_API_KEY)
if method.signed and not signature.is_valid(params, api_app.shared_secret):
raise LastFMError(errors.INVALID_SIGNATURE)
call = Call(params=params, api_app=api_app, format=fmt)
if method.session:
sk = params.get("sk")
if not sk:
raise LastFMError(errors.INVALID_PARAMETERS, "Missing required parameter: sk")
session = db.session.scalar(db.select(Session).filter_by(session_key=sk))
if session is None or session.api_app_id != api_app.id:
raise LastFMError(errors.INVALID_SESSION_KEY)
call.user = session.user
missing = [p.name for p in method.params if p.required and not params.get(p.name)]
if missing:
raise LastFMError(
errors.INVALID_PARAMETERS, f"Missing required parameter: {', '.join(missing)}"
)
return call
@bp.route("/2.0/", methods=["GET", "POST"], strict_slashes=False)
def dispatch() -> Response:
params = _request_params()
fmt = "json" if params.get("format", "").lower() == "json" else "xml"
requested = (params.get("method") or "").lower()
method = METHODS.get(requested)
label = method.name if method else "unknown"
start = time.perf_counter()
try:
if method is None:
raise LastFMError(errors.INVALID_METHOD)
result = method.handler(_authenticate(method, params, fmt))
if isinstance(result, Response):
response = result
else:
el, force_list = result if isinstance(result, tuple) else (result, ())
response = render(el, fmt, force_list=force_list)
outcome = "ok"
except LastFMError as err:
db.session.rollback()
response = render_error(err, fmt)
outcome = "error"
metrics.lastfm_errors_total.labels(lastfm_method=label, code=str(err.code)).inc()
if reason := _AUTH_FAILURE_REASONS.get(err.code):
metrics.auth_failures_total.labels(reason=reason).inc()
metrics.lastfm_requests_total.labels(lastfm_method=label, format=fmt, outcome=outcome).inc()
metrics.lastfm_request_duration_seconds.labels(lastfm_method=label).observe(
time.perf_counter() - start
)
return response
from scrobbler.lastfm import methods # noqa: E402,F401 (register handlers)
+54
View File
@@ -0,0 +1,54 @@
"""Last.fm API error codes (https://www.last.fm/api/errorcodes)."""
INVALID_SERVICE = 2
INVALID_METHOD = 3
AUTHENTICATION_FAILED = 4
INVALID_PARAMETERS = 6
OPERATION_FAILED = 8
INVALID_SESSION_KEY = 9
INVALID_API_KEY = 10
INVALID_SIGNATURE = 13
UNAUTHORIZED_TOKEN = 14
TOKEN_EXPIRED = 15
RATE_LIMIT_EXCEEDED = 29
MESSAGES = {
INVALID_SERVICE: "Invalid service - This service does not exist",
INVALID_METHOD: "Invalid Method - No method with that name in this package",
AUTHENTICATION_FAILED: (
"Authentication Failed - You do not have permissions to access the service"
),
INVALID_PARAMETERS: "Invalid parameters - Your request is missing a required parameter",
OPERATION_FAILED: "Operation failed - Something else went wrong",
INVALID_SESSION_KEY: "Invalid session key - Please re-authenticate",
INVALID_API_KEY: "Invalid API key - You must be granted a valid key by last.fm",
INVALID_SIGNATURE: "Invalid method signature supplied",
UNAUTHORIZED_TOKEN: "Unauthorized Token - This token has not been authorized",
TOKEN_EXPIRED: "This token has expired",
RATE_LIMIT_EXCEEDED: "Rate limit exceeded",
}
HTTP_STATUS = {
INVALID_SERVICE: 400,
INVALID_METHOD: 400,
INVALID_PARAMETERS: 400,
AUTHENTICATION_FAILED: 403,
INVALID_SESSION_KEY: 403,
INVALID_API_KEY: 403,
INVALID_SIGNATURE: 403,
UNAUTHORIZED_TOKEN: 403,
TOKEN_EXPIRED: 403,
RATE_LIMIT_EXCEEDED: 429,
OPERATION_FAILED: 500,
}
class LastFMError(Exception):
def __init__(self, code: int, message: str | None = None):
self.code = code
self.message = message or MESSAGES.get(code, "Unknown error")
super().__init__(f"{code}: {self.message}")
@property
def http_status(self) -> int:
return HTTP_STATUS.get(self.code, 400)
+1
View File
@@ -0,0 +1 @@
"""Importing this package registers every Last.fm method handler."""
+88
View File
@@ -0,0 +1,88 @@
"""Registry of Last.fm API methods.
Each handler declares its name, parameters and auth requirements. The dispatcher
enforces the requirements and the OpenAPI document is generated from the same
entries, so the docs always list exactly the methods that exist.
"""
from collections.abc import Callable
from dataclasses import dataclass
from flask import Response
from scrobbler.lastfm.responses import El
from scrobbler.models import ApiApp, User
@dataclass(frozen=True)
class Param:
name: str
description: str
required: bool = False
example: str | None = None
@dataclass
class Call:
"""Everything a handler needs about the current request."""
params: dict[str, str]
api_app: ApiApp
format: str
user: User | None = None # set for methods that require a session key
def get(self, name: str, default: str | None = None) -> str | None:
value = self.params.get(name)
return value if value not in (None, "") else default
Handler = Callable[[Call], El | tuple[El, tuple[str, ...]] | Response]
@dataclass(frozen=True)
class LastfmMethod:
name: str
handler: Handler
summary: str
signed: bool = False
session: bool = False
params: tuple[Param, ...] = ()
example_xml: str | None = None
example_json: dict | None = None
notes: str = ""
METHODS: dict[str, LastfmMethod] = {}
def lastfm_method(
name: str,
*,
summary: str,
signed: bool = False,
session: bool = False,
params: tuple[Param, ...] = (),
example_xml: str | None = None,
example_json: dict | None = None,
notes: str = "",
):
"""Register a handler. Handlers return an `El` tree, or `(El, force_list_tags)`."""
def decorator(handler: Handler) -> Handler:
key = name.lower()
if key in METHODS:
raise ValueError(f"Last.fm method {name} registered twice")
METHODS[key] = LastfmMethod(
name=name,
handler=handler,
summary=summary,
signed=signed,
session=session,
params=params,
example_xml=example_xml,
example_json=example_json,
notes=notes,
)
return handler
return decorator
+95
View File
@@ -0,0 +1,95 @@
"""Render Last.fm responses as XML (the default) or Last.fm-style JSON.
Handlers build a small element tree with `El`; this module turns it into either
`<lfm status="ok">...</lfm>` or the JSON shape Last.fm uses, where:
* a text element with attributes becomes {"attr": ..., "#text": text}
* a container element's attributes go under "@attr"
* repeated child tags become a list
"""
from dataclasses import dataclass, field
from typing import Any
from xml.etree import ElementTree as ET
from flask import Response, jsonify
from scrobbler.lastfm.errors import LastFMError
@dataclass
class El:
tag: str
text: str | None = None
attrs: dict[str, Any] = field(default_factory=dict)
children: list["El"] = field(default_factory=list)
@classmethod
def of(cls, tag: str, *children: "El", **attrs: Any) -> "El":
return cls(tag, attrs=attrs, children=list(children))
@classmethod
def text_el(cls, tag: str, text: Any, **attrs: Any) -> "El":
return cls(tag, text="" if text is None else str(text), attrs=attrs)
def _to_xml(el: El) -> ET.Element:
node = ET.Element(el.tag, {k: str(v) for k, v in el.attrs.items()})
if el.text is not None:
node.text = el.text
for child in el.children:
node.append(_to_xml(child))
return node
def _to_json(el: El) -> Any:
attrs = {k: str(v) for k, v in el.attrs.items()}
if el.text is not None:
return {**attrs, "#text": el.text} if attrs else el.text
body: dict[str, Any] = {}
for child in el.children:
value = _to_json(child)
if child.tag in body:
existing = body[child.tag]
if isinstance(existing, list):
existing.append(value)
else:
body[child.tag] = [existing, value]
else:
body[child.tag] = value
if attrs:
body["@attr"] = attrs
return body
def render(el: El, fmt: str, *, force_list: tuple[str, ...] = ()) -> Response:
"""Render a successful response. `force_list` names child tags that must be JSON
lists even when there is only one (e.g. "track" in a recent-tracks page)."""
if fmt == "json":
body = _to_json(el)
for tag in force_list:
if isinstance(body, dict) and tag in body and not isinstance(body[tag], list):
body[tag] = [body[tag]]
return jsonify({el.tag: body})
root = ET.Element("lfm", {"status": "ok"})
root.append(_to_xml(el))
return _xml_response(root, 200)
def render_error(err: LastFMError, fmt: str) -> Response:
if fmt == "json":
response = jsonify({"error": err.code, "message": err.message})
response.status_code = err.http_status
return response
root = ET.Element("lfm", {"status": "failed"})
error = ET.SubElement(root, "error", {"code": str(err.code)})
error.text = err.message
return _xml_response(root, err.http_status)
def _xml_response(root: ET.Element, status: int) -> Response:
body = ET.tostring(root, encoding="unicode", xml_declaration=False)
return Response(
'<?xml version="1.0" encoding="UTF-8"?>\n' + body,
status=status,
mimetype="application/xml",
)
+19
View File
@@ -0,0 +1,19 @@
"""Last.fm request signatures: https://www.last.fm/api/authspec#_8-signing-calls"""
import hashlib
import hmac
from collections.abc import Mapping
UNSIGNED_PARAMS = frozenset({"format", "callback", "api_sig"})
def sign(params: Mapping[str, str], secret: str) -> str:
payload = "".join(
f"{name}{params[name]}" for name in sorted(params) if name not in UNSIGNED_PARAMS
)
return hashlib.md5((payload + secret).encode("utf-8")).hexdigest()
def is_valid(params: Mapping[str, str], secret: str) -> bool:
supplied = params.get("api_sig", "")
return bool(supplied) and hmac.compare_digest(sign(params, secret), supplied.lower())
+77
View File
@@ -51,3 +51,80 @@ class MetricDelta:
@pytest.fixture
def metric_delta():
return MetricDelta
# --- Factories ------------------------------------------------------------------
import secrets # noqa: E402
from datetime import UTC, datetime, timedelta # noqa: E402
from werkzeug.security import generate_password_hash # noqa: E402
from scrobbler.lastfm.signature import sign # noqa: E402
from scrobbler.models import ApiApp, Session, User # noqa: E402
@pytest.fixture
def make_user():
def make(username="alice", password="hunter22", email=None):
user = User(
username=username,
email=email or f"{username}@example.com",
password_hash=generate_password_hash(password),
)
db.session.add(user)
db.session.commit()
return user
return make
@pytest.fixture
def make_app(make_user):
def make(owner=None, name="Test Player"):
app_ = ApiApp(
api_key=secrets.token_hex(16),
shared_secret=secrets.token_hex(16),
name=name,
owner=owner or make_user(username=f"owner{secrets.token_hex(3)}"),
)
db.session.add(app_)
db.session.commit()
return app_
return make
@pytest.fixture
def make_session():
def make(user, api_app):
session = Session(session_key=secrets.token_hex(16), user=user, api_app=api_app)
db.session.add(session)
db.session.commit()
return session
return make
@pytest.fixture
def user(make_user):
return make_user()
@pytest.fixture
def api_app(make_app, user):
return make_app(owner=user)
@pytest.fixture
def session_key(make_session, user, api_app):
return make_session(user, api_app).session_key
def signed(params: dict, secret: str) -> dict:
"""Return params plus a valid api_sig."""
return {**params, "api_sig": sign(params, secret)}
def days_ago(days: float) -> int:
return int((datetime.now(UTC) - timedelta(days=days)).timestamp())
+122
View File
@@ -0,0 +1,122 @@
import xml.etree.ElementTree as ET
import pytest
from conftest import signed
from scrobbler.lastfm.registry import METHODS, Param, lastfm_method
from scrobbler.lastfm.responses import El
@pytest.fixture(autouse=True)
def _test_methods():
@lastfm_method("test.echo", summary="Echo", params=(Param("word", "A word", required=True),))
def echo(call):
return El.of("echo", El.text_el("word", call.get("word"), lang="en"))
@lastfm_method("test.signed", summary="Signed", signed=True)
def signed_method(call):
return El("signed")
@lastfm_method("test.whoami", summary="Session", signed=True, session=True)
def whoami(call):
return El.of("user", El.text_el("name", call.user.username))
yield
for name in ("test.echo", "test.signed", "test.whoami"):
METHODS.pop(name)
def lfm(response):
root = ET.fromstring(response.data)
assert root.tag == "lfm"
return root
def test_unknown_method_is_error_3(client, api_app):
response = client.get("/2.0/", query_string={"method": "nope.nope", "api_key": api_app.api_key})
root = lfm(response)
assert root.get("status") == "failed"
assert root.find("error").get("code") == "3"
assert response.status_code == 400
def test_missing_api_key_is_error_6(client):
root = lfm(client.get("/2.0/?method=test.echo&word=hi"))
assert root.find("error").get("code") == "6"
def test_unknown_api_key_is_error_10(client, metric_delta):
failures = metric_delta("scrobbler_auth_failures_total", reason="bad_api_key")
root = lfm(client.get("/2.0/?method=test.echo&word=hi&api_key=nope"))
assert root.find("error").get("code") == "10"
assert failures.delta == 1
def test_missing_required_param_is_error_6(client, api_app):
root = lfm(client.get(f"/2.0/?method=test.echo&api_key={api_app.api_key}"))
assert root.find("error").get("code") == "6"
assert "word" in root.find("error").text
def test_xml_response(client, api_app):
response = client.get(f"/2.0/?method=TEST.ECHO&word=hi&api_key={api_app.api_key}")
root = lfm(response)
assert response.status_code == 200
assert root.get("status") == "ok"
word = root.find("echo/word")
assert (word.text, word.get("lang")) == ("hi", "en")
def test_json_response_uses_lastfm_conventions(client, api_app):
response = client.post(
"/2.0/",
data={"method": "test.echo", "word": "hi", "api_key": api_app.api_key, "format": "json"},
)
assert response.get_json() == {"echo": {"word": {"lang": "en", "#text": "hi"}}}
def test_json_error_shape(client):
response = client.get("/2.0?method=nope&format=json")
assert response.get_json() == {
"error": 3,
"message": "Invalid Method - No method with that name in this package",
}
def test_signed_method_rejects_bad_signature(client, api_app, metric_delta):
errors = metric_delta("scrobbler_lastfm_errors_total", lastfm_method="test.signed", code="13")
params = {"method": "test.signed", "api_key": api_app.api_key, "api_sig": "0" * 32}
root = lfm(client.post("/2.0/", data=params))
assert root.find("error").get("code") == "13"
assert errors.delta == 1
def test_signed_method_accepts_good_signature(client, api_app):
params = signed({"method": "test.signed", "api_key": api_app.api_key}, api_app.shared_secret)
assert lfm(client.post("/2.0/", data={**params, "format": "xml"})).get("status") == "ok"
def test_session_method_resolves_user(client, api_app, session_key, user):
params = signed(
{"method": "test.whoami", "api_key": api_app.api_key, "sk": session_key},
api_app.shared_secret,
)
assert lfm(client.post("/2.0/", data=params)).find("user/name").text == user.username
def test_session_key_from_another_app_is_rejected(client, make_app, make_session, user):
app_a, app_b = make_app(owner=user), make_app(owner=user)
sk = make_session(user, app_a).session_key
params = signed(
{"method": "test.whoami", "api_key": app_b.api_key, "sk": sk}, app_b.shared_secret
)
assert lfm(client.post("/2.0/", data=params)).find("error").get("code") == "9"
def test_unknown_methods_share_one_metric_label(client, metric_delta):
unknown = metric_delta(
"scrobbler_lastfm_requests_total", lastfm_method="unknown", format="xml", outcome="error"
)
for name in ("a.b", "c.d", "e.f"):
client.get(f"/2.0/?method={name}")
assert unknown.delta == 3
+29
View File
@@ -0,0 +1,29 @@
import hashlib
from scrobbler.lastfm.signature import is_valid, sign
def test_signature_sorts_params_and_appends_secret():
params = {"token": "tok", "method": "auth.getSession", "api_key": "key"}
expected = hashlib.md5(b"api_keykeymethodauth.getSessiontokentokSECRET").hexdigest()
assert sign(params, "SECRET") == expected
def test_format_callback_and_api_sig_are_not_signed():
base = {"method": "track.scrobble", "api_key": "key"}
extra = {**base, "format": "json", "callback": "cb", "api_sig": "whatever"}
assert sign(base, "s") == sign(extra, "s")
def test_signature_uses_utf8():
params = {"artist": "Sigur Rós", "api_key": "k"}
expected = hashlib.md5("api_keykartistSigur RósS".encode()).hexdigest()
assert sign(params, "S") == expected
def test_is_valid_accepts_uppercase_hex_and_rejects_missing():
params = {"api_key": "k", "method": "m"}
sig = sign(params, "s")
assert is_valid({**params, "api_sig": sig.upper()}, "s")
assert not is_valid(params, "s")
assert not is_valid({**params, "api_sig": sig}, "other-secret")