From 9243fe4d3f69e0e27c3c840e50021e4c151511eb Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Tue, 13 Oct 2026 11:41:32 +0100 Subject: [PATCH] Let users pick their Gravatar as their profile image (SCR-1) Opt-in per user and gated by AVATAR_GRAVATAR_ENABLED. The server fetches the image by the SHA-256 of the account email and caches it with the uploads, so browsers never contact Gravatar. Co-Authored-By: Claude Sonnet 5.5 --- .env.example | 3 + docs/openapi.json | 66 ++++++++++++++- src/scrobbler/api/avatar.py | 28 ++++++- src/scrobbler/config.py | 8 ++ src/scrobbler/metrics/__init__.py | 12 ++- src/scrobbler/schemas/__init__.py | 8 ++ src/scrobbler/services/avatars.py | 79 +++++++++++++++++- tests/test_avatar.py | 128 ++++++++++++++++++++++++++++++ 8 files changed, 328 insertions(+), 4 deletions(-) diff --git a/.env.example b/.env.example index 1cd09a2..18dc38a 100644 --- a/.env.example +++ b/.env.example @@ -32,6 +32,9 @@ ART_UPLOAD_MAX_BYTES=5242880 # Largest profile image a user may upload (bytes). Stored in an "avatars" folder inside # ART_STORAGE_DIR, so the same backups cover it. AVATAR_UPLOAD_MAX_BYTES=2097152 +# Let users use their Gravatar as their profile image. The server fetches it, sending +# Gravatar a hash of the user's email address, so it's off unless you turn it on. +AVATAR_GRAVATAR_ENABLED=false # docker compose host ports (defaults shown) API_PORT=5050 diff --git a/docs/openapi.json b/docs/openapi.json index 4233fae..384128a 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -2081,6 +2081,65 @@ ] } }, + "/api/v1/me/avatar/gravatar": { + "post": { + "responses": { + "502": { + "description": "Gravatar couldn't be reached", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "Gravatar is off, or has no image for you", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/User" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Use your Gravatar as your profile image", + "description": "The server fetches the image for your account email from Gravatar (sending it a hash\nof the address) and keeps a copy. Call again to refresh it. Only available when the\nserver's admin has enabled it; see `gravatar_enabled` on `/auth/me`.", + "tags": [ + "Avatar" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, "/healthz": { "get": { "responses": { @@ -3958,7 +4017,7 @@ }, { "name": "Avatar", - "description": "Your profile image: upload one, or remove it." + "description": "Your profile image: upload one, use your Gravatar (if this server allows it), or remove it." }, { "name": "Health", @@ -4119,6 +4178,11 @@ "format": "date-time", "readOnly": true, "description": "When it last changed" + }, + "gravatar_enabled": { + "readOnly": true, + "type": "boolean", + "description": "Whether this server offers Gravatar" } }, "additionalProperties": false diff --git a/src/scrobbler/api/avatar.py b/src/scrobbler/api/avatar.py index e74ff65..b06f192 100644 --- a/src/scrobbler/api/avatar.py +++ b/src/scrobbler/api/avatar.py @@ -9,7 +9,10 @@ from scrobbler.services import avatars blp = Blueprint( "Avatar", __name__, - description="Your profile image: upload one, or remove it.", + description=( + "Your profile image: upload one, use your Gravatar (if this server allows it), " + "or remove it." + ), ) @@ -59,6 +62,29 @@ def upload_avatar(files): return g.user +@blp.route("/gravatar", methods=["POST"]) +@authenticated(blp) +@blp.response(200, UserSchema) +@blp.alt_response(404, schema=ErrorSchema, description="Gravatar is off, or has no image for you") +@blp.alt_response(502, schema=ErrorSchema, description="Gravatar couldn't be reached") +def use_gravatar(): + """Use your Gravatar as your profile image + + The server fetches the image for your account email from Gravatar (sending it a hash + of the address) and keeps a copy. Call again to refresh it. Only available when the + server's admin has enabled it; see `gravatar_enabled` on `/auth/me`. + """ + try: + avatars.use_gravatar(g.user) + except avatars.GravatarDisabled: + abort(404, code="gravatar_disabled", message="This server doesn't use Gravatar.") + except avatars.GravatarMissing: + abort(404, code="no_gravatar", message="Gravatar has no image for your email address.") + except avatars.GravatarUnavailable: + abort(502, code="gravatar_unavailable", message="Gravatar couldn't be reached.") + return g.user + + @blp.route("", methods=["DELETE"]) @authenticated(blp) @blp.response(204) diff --git a/src/scrobbler/config.py b/src/scrobbler/config.py index 3b3431b..b19492f 100644 --- a/src/scrobbler/config.py +++ b/src/scrobbler/config.py @@ -75,6 +75,14 @@ class Config: # Profile images live in an "avatars" folder inside ART_STORAGE_DIR. This is the # largest one a user may upload. AVATAR_UPLOAD_MAX_BYTES = int(os.environ.get("AVATAR_UPLOAD_MAX_BYTES", str(2 * 1024 * 1024))) + # Lets users pick their Gravatar as their profile image. Off by default: using one + # sends a hash of the user's email address to Gravatar (from this server, not their browser). + AVATAR_GRAVATAR_ENABLED = os.environ.get("AVATAR_GRAVATAR_ENABLED", "").lower() in ( + "1", + "true", + "yes", + ) + GRAVATAR_URL = os.environ.get("GRAVATAR_URL", "https://gravatar.com/avatar/") IMPORT_MAX_BYTES = int(os.environ.get("IMPORT_MAX_BYTES", str(200 * 1024 * 1024))) MAX_CONTENT_LENGTH = IMPORT_MAX_BYTES + 1024 * 1024 # uploads are the largest requests diff --git a/src/scrobbler/metrics/__init__.py b/src/scrobbler/metrics/__init__.py index 28d221e..a0823e9 100644 --- a/src/scrobbler/metrics/__init__.py +++ b/src/scrobbler/metrics/__init__.py @@ -204,9 +204,19 @@ avatar_upload_bytes = Histogram( "Size of accepted profile image uploads", buckets=(5_000, 10_000, 25_000, 50_000, 100_000, 250_000, 500_000, 1_000_000, 2_000_000), ) +avatar_gravatar_fetches_total = Counter( + "scrobbler_avatar_gravatar_fetches_total", + "Gravatar fetches: ok, none (no Gravatar for the email), bad_type, too_large or error", + ["result"], +) +avatar_gravatar_seconds = Histogram( + "scrobbler_avatar_gravatar_seconds", + "Latency of one Gravatar fetch", + buckets=(0.1, 0.25, 0.5, 1, 2.5, 5, 10), +) avatar_actions_total = Counter( "scrobbler_avatar_actions_total", - "Profile image changes: uploaded, removed", + "Profile image changes: uploaded, gravatar, removed", ["action"], ) diff --git a/src/scrobbler/schemas/__init__.py b/src/scrobbler/schemas/__init__.py index 72034f5..937e82d 100644 --- a/src/scrobbler/schemas/__init__.py +++ b/src/scrobbler/schemas/__init__.py @@ -1,6 +1,7 @@ """Marshmallow schemas for the /api/v1 JSON API. They drive both request validation and the generated OpenAPI document.""" +from flask import current_app from flask_smorest.fields import Upload from marshmallow import Schema, ValidationError, fields, validate, validates_schema @@ -31,6 +32,13 @@ class UserSchema(Schema): avatar_updated_at = fields.DateTime( dump_only=True, allow_none=True, metadata={"description": "When it last changed"} ) + gravatar_enabled = fields.Method( + "_gravatar_enabled", + metadata={"type": "boolean", "description": "Whether this server offers Gravatar"}, + ) + + def _gravatar_enabled(self, _user) -> bool: + return bool(current_app.config["AVATAR_GRAVATAR_ENABLED"]) class RegisterSchema(Schema): diff --git a/src/scrobbler/services/avatars.py b/src/scrobbler/services/avatars.py index a3e82e1..236765a 100644 --- a/src/scrobbler/services/avatars.py +++ b/src/scrobbler/services/avatars.py @@ -6,8 +6,12 @@ row records where the image came from and its content type; that is the source o for whether there is one. """ +import hashlib import os import tempfile +import time +import urllib.error +import urllib.request from datetime import UTC, datetime from pathlib import Path @@ -18,7 +22,34 @@ from scrobbler.extensions import db from scrobbler.models import User from scrobbler.services.art import IMAGE_TYPES, UnsupportedImage, sniff_image_type -__all__ = ["IMAGE_TYPES", "UnsupportedImage", "read", "remove", "save", "sniff_image_type"] +__all__ = [ + "IMAGE_TYPES", + "GravatarDisabled", + "GravatarMissing", + "GravatarUnavailable", + "UnsupportedImage", + "read", + "remove", + "save", + "sniff_image_type", + "use_gravatar", +] + +GRAVATAR_SIZE = 256 # px; plenty for a header icon or a profile page +GRAVATAR_MAX_BYTES = 1024 * 1024 +GRAVATAR_TIMEOUT = 5 # seconds - this runs inside a web request + + +class GravatarDisabled(Exception): + """The admin hasn't turned Gravatar on.""" + + +class GravatarMissing(Exception): + """Gravatar has no image for the user's email address.""" + + +class GravatarUnavailable(Exception): + """Gravatar couldn't be reached, or sent something unusable.""" def _path(user_id: int) -> Path: @@ -71,3 +102,49 @@ def remove(user: User) -> bool: _path(user.id).unlink(missing_ok=True) metrics.avatar_actions_total.labels("removed").inc() return True + + +def gravatar_url(email: str) -> str: + """Where Gravatar serves this address's image; d=404 asks for an error, not a stock + picture, when it has none. Gravatar keys on the SHA-256 of the trimmed, lower-cased email.""" + digest = hashlib.sha256(email.strip().lower().encode()).hexdigest() + base = current_app.config["GRAVATAR_URL"] + return f"{base}{digest}?s={GRAVATAR_SIZE}&d=404" + + +def _fetch_gravatar(email: str) -> bytes: + start = time.perf_counter() + try: + with urllib.request.urlopen(gravatar_url(email), timeout=GRAVATAR_TIMEOUT) as response: + data = response.read(GRAVATAR_MAX_BYTES + 1) + except urllib.error.HTTPError as err: + if err.code == 404: + metrics.avatar_gravatar_fetches_total.labels("none").inc() + raise GravatarMissing from err + metrics.avatar_gravatar_fetches_total.labels("error").inc() + raise GravatarUnavailable(str(err)) from err + except (urllib.error.URLError, TimeoutError) as err: + metrics.avatar_gravatar_fetches_total.labels("error").inc() + raise GravatarUnavailable(str(err)) from err + finally: + metrics.avatar_gravatar_seconds.observe(time.perf_counter() - start) + if len(data) > GRAVATAR_MAX_BYTES: + metrics.avatar_gravatar_fetches_total.labels("too_large").inc() + raise GravatarUnavailable("image too large") + return data + + +def use_gravatar(user: User) -> None: + """Fetch the Gravatar for the user's email and make it their image (also how it's + refreshed). Raises GravatarDisabled, GravatarMissing or GravatarUnavailable, leaving + any current image alone. The bytes are kept on disk, so browsers never talk to Gravatar.""" + if not current_app.config["AVATAR_GRAVATAR_ENABLED"]: + raise GravatarDisabled + data = _fetch_gravatar(user.email) + try: + content_type = sniff_image_type(data) + except UnsupportedImage as err: + metrics.avatar_gravatar_fetches_total.labels("bad_type").inc() + raise GravatarUnavailable("not an image") from err + save(user, data, content_type, "gravatar") + metrics.avatar_gravatar_fetches_total.labels("ok").inc() diff --git a/tests/test_avatar.py b/tests/test_avatar.py index 127ea99..a9e05ff 100644 --- a/tests/test_avatar.py +++ b/tests/test_avatar.py @@ -1,6 +1,9 @@ +import hashlib import io +import threading import pytest +from werkzeug.serving import make_server from scrobbler.extensions import db from scrobbler.models import User @@ -115,3 +118,128 @@ def test_upload_rejects_bad_files(client, auth, app, storage, metric_delta, data def test_upload_requires_a_file(client, auth, storage): response = client.put(URL, headers=auth, data={}, content_type="multipart/form-data") assert response.status_code == 422 + + +# --- Gravatar ------------------------------------------------------------------------------ + + +def _digest(email): + return hashlib.sha256(email.encode()).hexdigest() + + +GRAVATAR_JPEG = b"\xff\xd8\xff\xe0gravatar-jpeg" +_GRAVATARS = { + _digest("alice@example.com"): ("200 OK", GRAVATAR_JPEG), + _digest("html@example.com"): ("200 OK", b"not an image"), + _digest("big@example.com"): ("200 OK", b"\xff\xd8\xff" + b"x" * (1024 * 1024)), + _digest("boom@example.com"): ("500 Internal Server Error", b"boom"), +} +SEEN = [] + + +def _fake_gravatar(environ, start_response): + SEEN.append((environ["PATH_INFO"], environ["QUERY_STRING"])) + status, body = _GRAVATARS.get( + environ["PATH_INFO"].rsplit("/", 1)[-1], ("404 Not Found", b"not found") + ) + start_response(status, [("Content-Length", str(len(body)))]) + return [body] + + +@pytest.fixture(scope="module") +def fake_gravatar(): + server = make_server("127.0.0.1", 0, _fake_gravatar, threaded=True) + threading.Thread(target=server.serve_forever, daemon=True).start() + yield f"http://127.0.0.1:{server.server_port}/avatar/" + server.shutdown() + + +@pytest.fixture +def gravatar(app, storage, fake_gravatar): + keys = ("AVATAR_GRAVATAR_ENABLED", "GRAVATAR_URL") + saved = {k: app.config[k] for k in keys} + app.config.update(AVATAR_GRAVATAR_ENABLED=True, GRAVATAR_URL=fake_gravatar) + SEEN.clear() + yield + app.config.update(saved) + + +def use_gravatar(client, auth): + return client.post(f"{URL}/gravatar", headers=auth) + + +def set_email(user, email): + user.email = email + db.session.commit() + + +def test_gravatar_requires_auth(client): + assert client.post(f"{URL}/gravatar").status_code == 401 + + +def test_gravatar_is_off_by_default(client, auth, user, storage, metric_delta): + me = client.get("/api/v1/auth/me", headers=auth).get_json() + assert me["gravatar_enabled"] is False + response = use_gravatar(client, auth) + assert (response.status_code, response.get_json()["error"]["code"]) == ( + 404, + "gravatar_disabled", + ) + + +def test_gravatar_is_cached_and_served_like_an_upload(client, auth, user, gravatar, metric_delta): + ok = metric_delta("scrobbler_avatar_gravatar_fetches_total", result="ok") + action = metric_delta("scrobbler_avatar_actions_total", action="gravatar") + assert client.get("/api/v1/auth/me", headers=auth).get_json()["gravatar_enabled"] is True + response = use_gravatar(client, auth) + assert response.status_code == 200 + assert response.get_json()["avatar_source"] == "gravatar" + image = client.get(URL, headers=auth) + assert (image.data, image.mimetype) == (GRAVATAR_JPEG, "image/jpeg") + # Asked for the SHA-256 of the email at a fixed size, with a 404 rather than a stock picture. + assert [(f"/avatar/{_digest('alice@example.com')}", "s=256&d=404")] == SEEN + assert (ok.delta, action.delta) == (1, 1) + + +def test_gravatar_email_is_trimmed_and_lowercased(client, auth, user, gravatar): + set_email(user, " Alice@Example.COM ") + assert use_gravatar(client, auth).status_code == 200 + + +def test_gravatar_replaces_an_upload_and_back(client, auth, user, gravatar): + put(client, auth, data=PNG, name="me.png") + use_gravatar(client, auth) + assert client.get(URL, headers=auth).data == GRAVATAR_JPEG + put(client, auth) + assert client.get(URL, headers=auth).data == JPEG + assert client.get("/api/v1/auth/me", headers=auth).get_json()["avatar_source"] == "upload" + + +@pytest.mark.parametrize( + ("email", "status", "code", "result"), + [ + ("ghost@example.com", 404, "no_gravatar", "none"), + ("boom@example.com", 502, "gravatar_unavailable", "error"), + ("html@example.com", 502, "gravatar_unavailable", "bad_type"), + ("big@example.com", 502, "gravatar_unavailable", "too_large"), + ], +) +def test_gravatar_failures_keep_the_current_image( + client, auth, user, gravatar, metric_delta, email, status, code, result +): + put(client, auth) + set_email(user, email) + counted = metric_delta("scrobbler_avatar_gravatar_fetches_total", result=result) + response = use_gravatar(client, auth) + assert (response.status_code, response.get_json()["error"]["code"]) == (status, code) + assert counted.delta == 1 + assert client.get(URL, headers=auth).data == JPEG + + +def test_gravatar_unreachable_is_a_502(client, auth, user, gravatar, app): + app.config["GRAVATAR_URL"] = "http://127.0.0.1:1/avatar/" + response = use_gravatar(client, auth) + assert (response.status_code, response.get_json()["error"]["code"]) == ( + 502, + "gravatar_unavailable", + )