Last.fm API core: signatures, XML/JSON responses and dispatcher
- /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:
1 parent
ae8d3b65db
commit
9af8a4be8b
11 files changed
+585
No files matched your search
@@ -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())
|
||||
@@ -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
|
||||
@@ -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")
|
||||
Reference in new issue
Block a user