CI / validate-monitoring (push) Successful in 10s
CI / lint (push) Successful in 16s
CI / federation-interop (push) Successful in 1m2s
CI / test (push) Successful in 2m40s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s
protocol/schedule.py (pure): target_week(now_utc, tz) resolves to exactly one Monday-Sunday week — the most recent one whose Monday 09:00-local posting gate has passed — computed via wall-clock arithmetic in the user's own zone so it's correct across a DST change (a week can be 6h23/7h01 of real time, never silently 7 flat days). Because it's a pure function of "now", a worker that was down for weeks naturally catches up with one post, not a backlog. Also resolve_timezone()/is_valid_timezone() for a settings field that can otherwise crash a task or silently do nothing forever. protocol/content.py (pure): the small HTML subset shared by every post kind (p, strong, em, ol, li), with escaping split from formatting so a hostile artist/track name can't inject markup. publishing/weekly.py: build_content() (the template) and check_and_post()/check_all() (the federation.weekly periodic task, every 15 minutes). An empty week is simply never posted, and — since the target week only ever advances — never reconsidered either, with no separate marker needed. has_post() lets the common "already posted this week" pass skip the stats queries entirely. Core: accounts.get_user(id) (federation needs it and can't import the User model directly); sharing.EDITABLE and update() gain timezone/post_weekly_summary/post_milestones, with the same now-not-later validation visibility already had. Tested: the DST week and gate boundaries against real computed reference dates (not guessed ones — one guess was wrong and the test caught it before it shipped), hostile/emoji/RTL names in the template, and the full task against a real database (empty vs non-empty weeks, posting twice, disabled settings, a worker down for weeks, a bad stored timezone not stopping other users). Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
107 lines
4.1 KiB
Python
107 lines
4.1 KiB
Python
from datetime import UTC, datetime, timedelta
|
|
|
|
from scrobbler.extensions import db
|
|
from scrobbler.models import UiToken
|
|
from scrobbler.services import accounts
|
|
|
|
|
|
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_get_user_by_id(app, user):
|
|
assert accounts.get_user(user.id).username == user.username
|
|
assert accounts.get_user(user.id + 999) is None
|