diff --git a/.env.example b/.env.example index 2e4e751..1cd09a2 100644 --- a/.env.example +++ b/.env.example @@ -29,6 +29,9 @@ ART_STORAGE_DIR=var/album-art # Largest image a user may upload as their own album art (bytes). Uploaded art is # stored in ART_STORAGE_DIR too, so back that directory up. 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 # docker compose host ports (defaults shown) API_PORT=5050 diff --git a/docs/openapi.json b/docs/openapi.json index f7fd2d8..4233fae 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1921,6 +1921,166 @@ ] } }, + "/api/v1/me/avatar": { + "get": { + "responses": { + "404": { + "description": "You have no profile image", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "200": { + "description": "Your profile image (JPEG, PNG or WebP)" + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Your profile image", + "tags": [ + "Avatar" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "put": { + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "415": { + "description": "Not a JPEG, PNG or WebP image", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "413": { + "description": "Image too large", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "400": { + "description": "Empty file", + "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" + } + }, + "requestBody": { + "required": true, + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/AvatarUpload" + } + } + } + }, + "summary": "Upload a profile image", + "description": "Replaces your current one, whatever its source.", + "tags": [ + "Avatar" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "delete": { + "responses": { + "404": { + "description": "You have no profile image", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "204": { + "description": "No Content" + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Remove your profile image", + "tags": [ + "Avatar" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, "/healthz": { "get": { "responses": { @@ -3796,6 +3956,10 @@ "name": "Art", "description": "Album art, resolved from MusicBrainz / Cover Art Archive by a background worker. You can also upload your own art, or correct a failed lookup; those only change what you see." }, + { + "name": "Avatar", + "description": "Your profile image: upload one, or remove it." + }, { "name": "Health", "description": "Liveness for load balancers and containers" @@ -3931,6 +4095,30 @@ "type": "string", "format": "date-time", "readOnly": true + }, + "has_avatar": { + "type": "boolean", + "readOnly": true, + "description": "Whether you have a profile image" + }, + "avatar_source": { + "type": "string", + "enum": [ + "none", + "upload", + "gravatar" + ], + "readOnly": true, + "description": "Where your profile image comes from" + }, + "avatar_updated_at": { + "type": [ + "string", + "null" + ], + "format": "date-time", + "readOnly": true, + "description": "When it last changed" } }, "additionalProperties": false @@ -4654,6 +4842,20 @@ }, "additionalProperties": false }, + "AvatarUpload": { + "type": "object", + "properties": { + "file": { + "description": "A JPEG, PNG or WebP image", + "type": "string", + "format": "binary" + } + }, + "required": [ + "file" + ], + "additionalProperties": false + }, "Health": { "type": "object", "properties": { diff --git a/src/scrobbler/api/__init__.py b/src/scrobbler/api/__init__.py index 46b960f..cca7bc5 100644 --- a/src/scrobbler/api/__init__.py +++ b/src/scrobbler/api/__init__.py @@ -48,7 +48,18 @@ def init_app(app: Flask) -> None: }, ) - from scrobbler.api import apps, art, auth, health, imports, sessions, stats, tokens, tracks + from scrobbler.api import ( + apps, + art, + auth, + avatar, + health, + imports, + sessions, + stats, + tokens, + tracks, + ) api.register_blueprint(auth.blp, url_prefix="/api/v1/auth") api.register_blueprint(apps.blp, url_prefix="/api/v1/apps") @@ -58,6 +69,7 @@ def init_app(app: Flask) -> None: api.register_blueprint(tracks.blp, url_prefix="/api/v1/me/tracks") api.register_blueprint(imports.blp, url_prefix="/api/v1/imports") api.register_blueprint(art.blp, url_prefix="/api/v1/art") + api.register_blueprint(avatar.blp, url_prefix="/api/v1/me/avatar") api.register_blueprint(health.blp) from scrobbler.openapi import lastfm diff --git a/src/scrobbler/api/avatar.py b/src/scrobbler/api/avatar.py new file mode 100644 index 0000000..e74ff65 --- /dev/null +++ b/src/scrobbler/api/avatar.py @@ -0,0 +1,69 @@ +from flask import Response, current_app, g, request +from flask_smorest import Blueprint, abort + +from scrobbler import metrics +from scrobbler.api.decorators import authenticated +from scrobbler.schemas import AvatarUploadSchema, ErrorSchema, UserSchema +from scrobbler.services import avatars + +blp = Blueprint( + "Avatar", + __name__, + description="Your profile image: upload one, or remove it.", +) + + +@blp.route("", methods=["GET"]) +@authenticated(blp) +@blp.response(200, content_type="image/jpeg", description="Your profile image (JPEG, PNG or WebP)") +@blp.alt_response(404, schema=ErrorSchema, description="You have no profile image") +def get_avatar(): + """Your profile image""" + data = avatars.read(g.user) + if data is None: + abort(404, code="no_avatar", message="You have no profile image") + response = Response(data, mimetype=g.user.avatar_content_type or "image/jpeg") + response.headers["Cache-Control"] = "private, no-cache" # revalidate: it can change + response.add_etag() + return response.make_conditional(request) + + +@blp.route("", methods=["PUT"]) +@authenticated(blp) +@blp.arguments(AvatarUploadSchema, location="files") +@blp.response(200, UserSchema) +@blp.alt_response(400, schema=ErrorSchema, description="Empty file") +@blp.alt_response(413, schema=ErrorSchema, description="Image too large") +@blp.alt_response(415, schema=ErrorSchema, description="Not a JPEG, PNG or WebP image") +def upload_avatar(files): + """Upload a profile image + + Replaces your current one, whatever its source. + """ + limit = current_app.config["AVATAR_UPLOAD_MAX_BYTES"] + data = files["file"].read(limit + 1) + if not data: + metrics.avatar_uploads_total.labels("empty").inc() + abort(400, code="empty_file", message="That file is empty.") + if len(data) > limit: + metrics.avatar_uploads_total.labels("too_large").inc() + abort(413, code="file_too_large", message="That image is larger than this server accepts.") + try: + content_type = avatars.sniff_image_type(data) + except avatars.UnsupportedImage: + metrics.avatar_uploads_total.labels("bad_type").inc() + abort(415, code="unsupported_image", message="Upload a JPEG, PNG or WebP image.") + avatars.save(g.user, data, content_type, "upload") + metrics.avatar_uploads_total.labels("ok").inc() + metrics.avatar_upload_bytes.observe(len(data)) + return g.user + + +@blp.route("", methods=["DELETE"]) +@authenticated(blp) +@blp.response(204) +@blp.alt_response(404, schema=ErrorSchema, description="You have no profile image") +def delete_avatar(): + """Remove your profile image""" + if not avatars.remove(g.user): + abort(404, code="no_avatar", message="You have no profile image") diff --git a/src/scrobbler/config.py b/src/scrobbler/config.py index 8d52d16..3b3431b 100644 --- a/src/scrobbler/config.py +++ b/src/scrobbler/config.py @@ -72,6 +72,9 @@ class Config: ART_STORAGE_DIR = os.environ.get("ART_STORAGE_DIR", "var/album-art") # Largest image a user may upload as their own album art. ART_UPLOAD_MAX_BYTES = int(os.environ.get("ART_UPLOAD_MAX_BYTES", str(5 * 1024 * 1024))) + # 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))) 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 f4abe3a..28d221e 100644 --- a/src/scrobbler/metrics/__init__.py +++ b/src/scrobbler/metrics/__init__.py @@ -193,6 +193,23 @@ art_override_worker_seconds = Histogram( buckets=(0.25, 0.5, 1, 2.5, 5, 10, 20, 40, 80), ) +# Profile images +avatar_uploads_total = Counter( + "scrobbler_avatar_uploads_total", + "Profile image upload attempts: ok, empty, too_large or bad_type", + ["result"], +) +avatar_upload_bytes = Histogram( + "scrobbler_avatar_upload_bytes", + "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_actions_total = Counter( + "scrobbler_avatar_actions_total", + "Profile image changes: uploaded, removed", + ["action"], +) + # Database db_query_duration_seconds = Histogram( "scrobbler_db_query_duration_seconds", diff --git a/src/scrobbler/migrations/versions/b3e8a5d1f720_user_avatar.py b/src/scrobbler/migrations/versions/b3e8a5d1f720_user_avatar.py new file mode 100644 index 0000000..85d71c9 --- /dev/null +++ b/src/scrobbler/migrations/versions/b3e8a5d1f720_user_avatar.py @@ -0,0 +1,34 @@ +"""user avatar + +Revision ID: b3e8a5d1f720 +Revises: c7d2f08a19e4 +Create Date: 2026-10-13 09:00:00.000000 + +""" + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "b3e8a5d1f720" +down_revision = "c7d2f08a19e4" +branch_labels = None +depends_on = None + + +def upgrade(): + op.add_column( + "users", + sa.Column("avatar_source", sa.String(length=16), server_default="none", nullable=False), + ) + op.add_column("users", sa.Column("avatar_content_type", sa.String(length=32), nullable=True)) + op.add_column( + "users", sa.Column("avatar_updated_at", sa.DateTime(timezone=True), nullable=True) + ) + + +def downgrade(): + op.drop_column("users", "avatar_updated_at") + op.drop_column("users", "avatar_content_type") + op.drop_column("users", "avatar_source") diff --git a/src/scrobbler/models.py b/src/scrobbler/models.py index b9a4670..93cc12d 100644 --- a/src/scrobbler/models.py +++ b/src/scrobbler/models.py @@ -28,9 +28,18 @@ class User(db.Model): email: Mapped[str] = mapped_column(String(255)) password_hash: Mapped[str] = mapped_column(String(255)) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + # The profile image: none, upload or gravatar. Any image's bytes sit on disk (see + # services/avatars.py); these columns just say whether there is one, and what it is. + avatar_source: Mapped[str] = mapped_column(String(16), default="none", server_default="none") + avatar_content_type: Mapped[str | None] = mapped_column(String(32)) + avatar_updated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) __table_args__ = (Index("uq_users_username_lower", func.lower(username), unique=True),) + @property + def has_avatar(self) -> bool: + return self.avatar_source != "none" + class ApiApp(db.Model): """A client application; scrobblers authenticate with its key and secret.""" diff --git a/src/scrobbler/schemas/__init__.py b/src/scrobbler/schemas/__init__.py index 693ee80..72034f5 100644 --- a/src/scrobbler/schemas/__init__.py +++ b/src/scrobbler/schemas/__init__.py @@ -20,6 +20,17 @@ class UserSchema(Schema): username = fields.String(dump_only=True, metadata={"example": "alice"}) email = fields.String(dump_only=True, metadata={"example": "alice@example.com"}) created_at = fields.DateTime(dump_only=True) + has_avatar = fields.Boolean( + dump_only=True, metadata={"description": "Whether you have a profile image"} + ) + avatar_source = fields.String( + dump_only=True, + validate=validate.OneOf(["none", "upload", "gravatar"]), + metadata={"description": "Where your profile image comes from"}, + ) + avatar_updated_at = fields.DateTime( + dump_only=True, allow_none=True, metadata={"description": "When it last changed"} + ) class RegisterSchema(Schema): @@ -164,6 +175,10 @@ class AlbumArtUploadSchema(Schema): file = Upload(required=True, metadata={"description": "A JPEG, PNG or WebP image"}) +class AvatarUploadSchema(Schema): + file = Upload(required=True, metadata={"description": "A JPEG, PNG or WebP image"}) + + class AlbumArtCorrectionSchema(AlbumArtArgsSchema): search_artist = fields.String( validate=validate.Length(min=1, max=500), diff --git a/src/scrobbler/services/avatars.py b/src/scrobbler/services/avatars.py new file mode 100644 index 0000000..a3e82e1 --- /dev/null +++ b/src/scrobbler/services/avatars.py @@ -0,0 +1,73 @@ +"""Profile images. + +The bytes live on disk, in an "avatars" folder inside ART_STORAGE_DIR (so they share its +volume and its backups), one file per user named by user id with no extension. The users +row records where the image came from and its content type; that is the source of truth +for whether there is one. +""" + +import os +import tempfile +from datetime import UTC, datetime +from pathlib import Path + +from flask import current_app + +from scrobbler import metrics +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"] + + +def _path(user_id: int) -> Path: + return Path(current_app.config["ART_STORAGE_DIR"]) / "avatars" / str(user_id) + + +def read(user: User) -> bytes | None: + """The user's image bytes, or None if they have none (or the file has gone missing).""" + if not user.has_avatar: + return None + try: + return _path(user.id).read_bytes() + except FileNotFoundError: + return None + + +def _write(user_id: int, data: bytes) -> None: + """Writes via a temp file and a rename, so a reader never sees half an image.""" + path = _path(user_id) + path.parent.mkdir(parents=True, exist_ok=True) + fd, temp = tempfile.mkstemp(dir=path.parent, prefix=f".{user_id}.") + try: + with os.fdopen(fd, "wb") as file: + file.write(data) + os.replace(temp, path) + except BaseException: + Path(temp).unlink(missing_ok=True) + raise + + +def save(user: User, data: bytes, content_type: str, source: str) -> None: + """Make `data` the user's image. The caller has already validated it. The file is + written first, so a failure leaves the previous image (and row) intact.""" + _write(user.id, data) + user.avatar_source = source + user.avatar_content_type = content_type + user.avatar_updated_at = datetime.now(UTC) + db.session.commit() + metrics.avatar_actions_total.labels("uploaded" if source == "upload" else source).inc() + + +def remove(user: User) -> bool: + """Drops the user's image. False if they didn't have one.""" + if not user.has_avatar: + return False + user.avatar_source = "none" + user.avatar_content_type = None + user.avatar_updated_at = datetime.now(UTC) + db.session.commit() + _path(user.id).unlink(missing_ok=True) + metrics.avatar_actions_total.labels("removed").inc() + return True diff --git a/tests/test_avatar.py b/tests/test_avatar.py new file mode 100644 index 0000000..127ea99 --- /dev/null +++ b/tests/test_avatar.py @@ -0,0 +1,117 @@ +import io + +import pytest + +from scrobbler.extensions import db +from scrobbler.models import User +from scrobbler.services.accounts import issue_ui_token + +JPEG = b"\xff\xd8\xff\xe0fake-jpeg" +PNG = b"\x89PNG\r\n\x1a\nxxxx" +URL = "/api/v1/me/avatar" + + +@pytest.fixture +def storage(app, tmp_path): + saved = app.config["ART_STORAGE_DIR"] + app.config["ART_STORAGE_DIR"] = str(tmp_path) + yield tmp_path + app.config["ART_STORAGE_DIR"] = saved + + +def put(client, auth, data=JPEG, name="me.jpg"): + return client.put( + URL, + headers=auth, + data={"file": (io.BytesIO(data), name)}, + content_type="multipart/form-data", + ) + + +def test_endpoints_require_auth(client): + assert client.get(URL).status_code == 401 + assert client.put(URL).status_code == 401 + assert client.delete(URL).status_code == 401 + + +def test_no_avatar_to_begin_with(client, auth, user, storage): + assert client.get(URL, headers=auth).status_code == 404 + assert client.delete(URL, headers=auth).status_code == 404 + me = client.get("/api/v1/auth/me", headers=auth).get_json() + assert (me["has_avatar"], me["avatar_source"], me["avatar_updated_at"]) == (False, "none", None) + + +def test_upload_then_get_serves_the_image(client, auth, storage, metric_delta): + ok = metric_delta("scrobbler_avatar_uploads_total", result="ok") + size = metric_delta("scrobbler_avatar_upload_bytes_count") + action = metric_delta("scrobbler_avatar_actions_total", action="uploaded") + response = put(client, auth) + assert response.status_code == 200 + body = response.get_json() + assert (body["has_avatar"], body["avatar_source"]) == (True, "upload") + image = client.get(URL, headers=auth) + assert image.status_code == 200 + assert (image.data, image.mimetype) == (JPEG, "image/jpeg") + assert image.headers["Cache-Control"] == "private, no-cache" + assert (ok.delta, size.delta, action.delta) == (1, 1, 1) + assert client.get("/api/v1/auth/me", headers=auth).get_json()["has_avatar"] is True + + +def test_uploading_again_replaces_it(client, auth, storage): + put(client, auth) + put(client, auth, data=PNG, name="me.png") + image = client.get(URL, headers=auth) + assert (image.data, image.mimetype) == (PNG, "image/png") + assert [p.name for p in (storage / "avatars").iterdir()] == ["1"] # no stray temp files + + +def test_supports_conditional_requests(client, auth, storage): + put(client, auth) + first = client.get(URL, headers=auth) + again = client.get(URL, headers={**auth, "If-None-Match": first.headers["ETag"]}) + assert again.status_code == 304 + + +def test_delete_removes_the_image_and_file(client, auth, storage, metric_delta): + put(client, auth) + removed = metric_delta("scrobbler_avatar_actions_total", action="removed") + assert client.delete(URL, headers=auth).status_code == 204 + assert client.get(URL, headers=auth).status_code == 404 + assert not (storage / "avatars" / "1").exists() + assert client.get("/api/v1/auth/me", headers=auth).get_json()["has_avatar"] is False + assert removed.delta == 1 + + +def test_a_missing_file_reads_as_no_avatar(client, auth, storage): + put(client, auth) + (storage / "avatars" / "1").unlink() + assert client.get(URL, headers=auth).status_code == 404 + + +def test_avatars_are_per_user(client, auth, storage, make_user): + put(client, auth) + token = issue_ui_token(make_user(username="mallory")) + other = {"Authorization": f"Bearer {token}"} + assert client.get(URL, headers=other).status_code == 404 + assert db.session.scalar(db.select(User).where(User.username == "mallory")).has_avatar is False + + +@pytest.mark.parametrize( + ("data", "status", "result"), + [(b"", 400, "empty"), (b"GIF89a....", 415, "bad_type"), (JPEG + b"x" * 100, 413, "too_large")], +) +def test_upload_rejects_bad_files(client, auth, app, storage, metric_delta, data, status, result): + saved = app.config["AVATAR_UPLOAD_MAX_BYTES"] + app.config["AVATAR_UPLOAD_MAX_BYTES"] = 50 + try: + counted = metric_delta("scrobbler_avatar_uploads_total", result=result) + assert put(client, auth, data=data).status_code == status + assert counted.delta == 1 + assert client.get(URL, headers=auth).status_code == 404 + finally: + app.config["AVATAR_UPLOAD_MAX_BYTES"] = saved + + +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