From 0b1046951421ba8d0dd0c6d36ef31a03e5c10e3c Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 20:26:33 +0100 Subject: [PATCH] Sharing settings API, public profiles and ActivityPub docs (phase 1, step 4) - /api/v1/federation/settings (GET, PATCH): sharing on/off, visibility (followers-only default), follow approval, discoverable/indexable, display name and bio, plus the read-only handle and URLs - /api/v1/federation/profiles/: public profile for the UI page, only for users sharing - ActivityPub endpoints documented under an ActivityPub tag - docs/openapi.json is now exported with every optional module on (python -m scrobbler.openapi.export); the drift test and route checks cover both a federation-off and a federation-on app - Boundary: federation may use scrobbler.api.get_api to register its blueprint; the checker proves other scrobbler.api modules stay off limits Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- README.md | 2 +- docs/openapi.json | 714 ++++++++++++++++++++++++++- src/scrobbler/federation/README.md | 1 + src/scrobbler/federation/__init__.py | 6 +- src/scrobbler/federation/api.py | 93 ++++ src/scrobbler/federation/openapi.py | 156 ++++++ src/scrobbler/federation/schemas.py | 40 ++ src/scrobbler/openapi/export.py | 41 ++ tests/test_federation_api.py | 82 +++ tests/test_federation_boundary.py | 6 +- tests/test_openapi.py | 45 +- 11 files changed, 1175 insertions(+), 11 deletions(-) create mode 100644 src/scrobbler/federation/api.py create mode 100644 src/scrobbler/federation/openapi.py create mode 100644 src/scrobbler/federation/schemas.py create mode 100644 src/scrobbler/openapi/export.py create mode 100644 tests/test_federation_api.py diff --git a/README.md b/README.md index 56d16ec..b9b96a2 100644 --- a/README.md +++ b/README.md @@ -106,7 +106,7 @@ uv run ruff check && uv run ruff format --check ``` - **Migrations** come in two branches, `core` and `federation`. After changing core models, run `uv run flask --app scrobbler db migrate --head core@head -m "…"`; federation tables use `--head federation@head` (see `src/scrobbler/federation/README.md`). Apply them with `db upgrade heads`. CI fails if the models and migrations disagree. -- **API docs**: after changing an endpoint, run `uv run flask --app scrobbler openapi write --format=json docs/openapi.json`. A test fails if the committed spec is stale. Every route has to appear in the spec, and every UI route has to declare bearer auth. +- **API docs**: after changing an endpoint, run `uv run python -m scrobbler.openapi.export docs/openapi.json`. It documents the API with every optional module (such as federation) switched on. A test fails if the committed spec is stale. Every route has to appear in the spec, and every UI route has to declare bearer auth. - **Demo traffic**: `uv run python scripts/generate_traffic.py --minutes 5` sends a realistic mix of scrobbles and errors, so the dashboards have something to show. The test suite includes an end-to-end run with [pylast](https://github.com/pylast/pylast) over HTTPS and a real two-worker gunicorn run, which checks that metrics aggregate across workers. diff --git a/docs/openapi.json b/docs/openapi.json index 0cf219a..3138115 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1382,7 +1382,7 @@ "Last.fm" ], "summary": "Call a Last.fm API method (query string)", - "description": "Last.fm (Audioscrobbler 2.0) compatible API. Point a scrobbler's \"custom Last.fm\nserver\" setting at this server's `/2.0/`.\n\n**Signing.** Signed methods need `api_sig`: take every parameter except `format`,\n`callback` and `api_sig`, sort by name, concatenate each name followed by its\nvalue, append your application's shared secret, and take the md5 hex digest.\n\n**Sessions.** Methods that act as a user need `sk`, a session key from\n`auth.getMobileSession` or the desktop flow (`auth.getToken`, approval at\n`/api/auth/`, then `auth.getSession`).\n\n**Errors** use Last.fm's codes: 2 (Invalid service), 3 (Invalid Method), 4 (Authentication Failed), 6 (Invalid parameters), 8 (Operation failed), 9 (Invalid session key), 10 (Invalid API key), 13 (Invalid method signature supplied), 14 (Unauthorized Token), 15 (This token has expired), 29 (Rate limit exceeded).\n\n## Methods\n### `auth.getMobileSession`\n\nCreate a session key from a username and password.\n\n*Requires:* signed.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `username` | yes | Username |\n| `password` | yes | Password (send over HTTPS, as a POST body) |\n\nThe legacy `authToken` (md5 of username + md5(password)) form is not supported, because it requires storing unsalted password hashes. Clients that only support it (such as pylast's `password_hash`) should use the desktop flow instead.\n\n### `auth.getSession`\n\nExchange an approved token for a session key (desktop auth flow, step 3).\n\n*Requires:* signed.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `token` | yes | Token from auth.getToken, approved by the user |\n\n### `auth.getToken`\n\nFetch an unapproved request token (desktop auth flow, step 1).\n\n*Requires:* signed.\n\nSend the user to `/api/auth/?api_key=\u2026&token=\u2026` to approve the token, then call auth.getSession. Tokens expire after 60 minutes.\n\n### `track.scrobble`\n\nScrobble up to 50 tracks.\n\n*Requires:* signed, session key.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `artist[i]` | yes | Artist name |\n| `track[i]` | yes | Track title |\n| `timestamp[i]` | yes | Unix time the track started playing |\n| `album[i]` | no | Album title |\n| `albumArtist[i]` | no | Album artist, if different from the track artist |\n| `duration[i]` | no | Track length in seconds |\n| `trackNumber[i]` | no | Position on the album |\n| `mbid[i]` | no | MusicBrainz track id |\n\nTracks are array parameters indexed from 0 (`artist[0]`, `track[0]`, ...); a single un-indexed track is also accepted. Tracks are ignored (not an error) when the artist or track is empty (codes 1/2), the timestamp is over 14 days old (3) or more than 5 minutes in the future (4). Re-sending an already stored scrobble is accepted, so retries are safe.\n\n### `track.updateNowPlaying`\n\nSet the track the user is listening to now.\n\n*Requires:* signed, session key.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `artist` | yes | Artist name |\n| `track` | yes | Track title |\n| `album` | no | Album title |\n| `albumArtist` | no | Album artist |\n| `duration` | no | Track length in seconds; now-playing expires after it |\n| `trackNumber` | no | Position on the album |\n| `mbid` | no | MusicBrainz track id |\n\nNow playing expires after the track's duration (10 minutes if not given).\n\n### `user.getInfo`\n\nA user's profile and play count.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n\n### `user.getRecentTracks`\n\nRecently scrobbled tracks, newest first, led by the now-playing track.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n| `limit` | no | Results per page (default 50, max 200) |\n| `page` | no | Page number (default 1) |\n| `from` | no | Only scrobbles at or after this Unix time |\n| `to` | no | Only scrobbles at or before this Unix time |\n\n### `user.getTopAlbums`\n\nMost played albums over a period.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n| `period` | no | overall | 7day | 1month | 3month | 6month | 12month (default overall) |\n| `limit` | no | Results per page (default 50, max 1000) |\n| `page` | no | Page number (default 1) |\n\n### `user.getTopArtists`\n\nMost played artists over a period.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n| `period` | no | overall | 7day | 1month | 3month | 6month | 12month (default overall) |\n| `limit` | no | Results per page (default 50, max 1000) |\n| `page` | no | Page number (default 1) |\n\n### `user.getTopTracks`\n\nMost played tracks over a period.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n| `period` | no | overall | 7day | 1month | 3month | 6month | 12month (default overall) |\n| `limit` | no | Results per page (default 50, max 1000) |\n| `page` | no | Page number (default 1) |", + "description": "Last.fm (Audioscrobbler 2.0) compatible API. Point a scrobbler's \"custom Last.fm\nserver\" setting at this server's `/2.0/`.\n\n**Signing.** Signed methods need `api_sig`: take every parameter except `format`,\n`callback` and `api_sig`, sort by name, concatenate each name followed by its\nvalue, append your application's shared secret, and take the md5 hex digest.\n\n**Sessions.** Methods that act as a user need `sk`, a session key from\n`auth.getMobileSession` or the desktop flow (`auth.getToken`, approval at\n`/api/auth/`, then `auth.getSession`).\n\n**Errors** use Last.fm's codes: 2 (Invalid service), 3 (Invalid Method), 4 (Authentication Failed), 6 (Invalid parameters), 8 (Operation failed), 9 (Invalid session key), 10 (Invalid API key), 13 (Invalid method signature supplied), 14 (Unauthorized Token), 15 (This token has expired), 29 (Rate limit exceeded).\n\n## Methods\n### `auth.getMobileSession`\n\nCreate a session key from a username and password.\n\n*Requires:* signed.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `username` | yes | Username |\n| `password` | yes | Password (send over HTTPS, as a POST body) |\n\nThe legacy `authToken` (md5 of username + md5(password)) form is not supported, because it requires storing unsalted password hashes. Clients that only support it (such as pylast's `password_hash`) should use the desktop flow instead.\n\n### `auth.getSession`\n\nExchange an approved token for a session key (desktop auth flow, step 3).\n\n*Requires:* signed.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `token` | yes | Token from auth.getToken, approved by the user |\n\n### `auth.getToken`\n\nFetch an unapproved request token (desktop auth flow, step 1).\n\n*Requires:* signed.\n\nSend the user to `/api/auth/?api_key=…&token=…` to approve the token, then call auth.getSession. Tokens expire after 60 minutes.\n\n### `track.scrobble`\n\nScrobble up to 50 tracks.\n\n*Requires:* signed, session key.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `artist[i]` | yes | Artist name |\n| `track[i]` | yes | Track title |\n| `timestamp[i]` | yes | Unix time the track started playing |\n| `album[i]` | no | Album title |\n| `albumArtist[i]` | no | Album artist, if different from the track artist |\n| `duration[i]` | no | Track length in seconds |\n| `trackNumber[i]` | no | Position on the album |\n| `mbid[i]` | no | MusicBrainz track id |\n\nTracks are array parameters indexed from 0 (`artist[0]`, `track[0]`, ...); a single un-indexed track is also accepted. Tracks are ignored (not an error) when the artist or track is empty (codes 1/2), the timestamp is over 14 days old (3) or more than 5 minutes in the future (4). Re-sending an already stored scrobble is accepted, so retries are safe.\n\n### `track.updateNowPlaying`\n\nSet the track the user is listening to now.\n\n*Requires:* signed, session key.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `artist` | yes | Artist name |\n| `track` | yes | Track title |\n| `album` | no | Album title |\n| `albumArtist` | no | Album artist |\n| `duration` | no | Track length in seconds; now-playing expires after it |\n| `trackNumber` | no | Position on the album |\n| `mbid` | no | MusicBrainz track id |\n\nNow playing expires after the track's duration (10 minutes if not given).\n\n### `user.getInfo`\n\nA user's profile and play count.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n\n### `user.getRecentTracks`\n\nRecently scrobbled tracks, newest first, led by the now-playing track.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n| `limit` | no | Results per page (default 50, max 200) |\n| `page` | no | Page number (default 1) |\n| `from` | no | Only scrobbles at or after this Unix time |\n| `to` | no | Only scrobbles at or before this Unix time |\n\n### `user.getTopAlbums`\n\nMost played albums over a period.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n| `period` | no | overall | 7day | 1month | 3month | 6month | 12month (default overall) |\n| `limit` | no | Results per page (default 50, max 1000) |\n| `page` | no | Page number (default 1) |\n\n### `user.getTopArtists`\n\nMost played artists over a period.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n| `period` | no | overall | 7day | 1month | 3month | 6month | 12month (default overall) |\n| `limit` | no | Results per page (default 50, max 1000) |\n| `page` | no | Page number (default 1) |\n\n### `user.getTopTracks`\n\nMost played tracks over a period.\n\n*Requires:* api_key only.\n\n| Parameter | Required | Description |\n|---|---|---|\n| `user` | yes | Username to fetch data for |\n| `period` | no | overall | 7day | 1month | 3month | 6month | 12month (default overall) |\n| `limit` | no | Results per page (default 50, max 1000) |\n| `page` | no | Page number (default 1) |", "operationId": "lastfmGet", "parameters": [ { @@ -1856,6 +1856,561 @@ } } } + }, + "/api/v1/federation/settings": { + "get": { + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SharingSettings" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Your sharing settings", + "description": "Sharing is off and posts are followers-only until you change them.", + "tags": [ + "Federation" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "patch": { + "responses": { + "422": { + "description": "Invalid settings", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SharingSettings" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "requestBody": { + "required": true, + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/SharingSettingsUpdate" + } + } + } + }, + "summary": "Change your sharing settings", + "description": "Turning sharing on makes you findable as your handle. Your handle can't change once\npeople follow you. Visibility changes apply to new posts only.", + "tags": [ + "Federation" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/federation/profiles/{username}": { + "get": { + "responses": { + "404": { + "description": "No one sharing with that name", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/PublicProfile" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "A public fediverse profile", + "description": "For the web UI's profile page. Only users who share are visible.", + "tags": [ + "Federation" + ] + }, + "parameters": [ + { + "in": "path", + "name": "username", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + }, + "/.well-known/webfinger": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "WebFinger", + "description": "Resolves `acct:user@domain` (or an actor URL) to the user's actor. Only users sharing their listening can be found.", + "operationId": "federation_webfinger_lookup", + "responses": { + "200": { + "description": "JRD", + "content": { + "application/jrd+json": { + "schema": { + "type": "object" + } + } + } + }, + "400": { + "description": "Not a resource on this server" + }, + "404": { + "description": "Unknown, or not sharing (the two are indistinguishable)" + } + }, + "parameters": [ + { + "name": "resource", + "in": "query", + "required": true, + "schema": { + "type": "string" + }, + "example": "acct:alice@scrobble.example" + } + ] + } + }, + "/.well-known/host-meta": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "host-meta", + "description": "XRD pointing at WebFinger (RFC 6415).", + "operationId": "federation_host_meta", + "responses": { + "200": { + "description": "XRD", + "content": { + "application/xrd+xml": { + "schema": { + "type": "string" + } + } + } + } + } + } + }, + "/.well-known/nodeinfo": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "NodeInfo discovery", + "description": "Links to the NodeInfo 2.1 document.", + "operationId": "federation_nodeinfo_discovery", + "responses": { + "200": { + "description": "Links", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + } + } + }, + "/nodeinfo/2.1": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "NodeInfo 2.1", + "description": "Software name and version, protocols, and users sharing.", + "operationId": "federation_nodeinfo_document", + "responses": { + "200": { + "description": "NodeInfo", + "content": { + "application/json": { + "schema": { + "type": "object" + } + } + } + } + } + } + }, + "/users/{username}": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "Actor", + "description": "A user's `Person` actor when asked for ActivityPub JSON; browsers are redirected to the web UI's profile page.", + "operationId": "federation_actor", + "responses": { + "200": { + "description": "Person", + "content": { + "application/activity+json": { + "schema": { + "type": "object" + } + } + } + }, + "302": { + "description": "Redirect to the profile page (non-ActivityPub Accept)" + }, + "404": { + "description": "Unknown, or not sharing (the two are indistinguishable)" + } + }, + "parameters": [ + { + "name": "username", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "username", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + }, + "/users/{username}/outbox": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "Outbox", + "description": "The user's published activities.", + "operationId": "federation_outbox", + "responses": { + "200": { + "description": "OrderedCollection", + "content": { + "application/activity+json": { + "schema": { + "type": "object" + } + } + } + }, + "404": { + "description": "Unknown, or not sharing (the two are indistinguishable)" + } + }, + "parameters": [ + { + "name": "username", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "username", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + }, + "/users/{username}/followers": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "Followers", + "description": "Follower count (members aren't listed).", + "operationId": "federation_followers", + "responses": { + "200": { + "description": "OrderedCollection", + "content": { + "application/activity+json": { + "schema": { + "type": "object" + } + } + } + }, + "404": { + "description": "Unknown, or not sharing (the two are indistinguishable)" + } + }, + "parameters": [ + { + "name": "username", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "username", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + }, + "/users/{username}/following": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "Following", + "description": "Accounts the user follows.", + "operationId": "federation_following", + "responses": { + "200": { + "description": "OrderedCollection", + "content": { + "application/activity+json": { + "schema": { + "type": "object" + } + } + } + }, + "404": { + "description": "Unknown, or not sharing (the two are indistinguishable)" + } + }, + "parameters": [ + { + "name": "username", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "username", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + }, + "/actor": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "Instance actor", + "description": "The server's `Application` actor.", + "operationId": "federation_instance_actor", + "responses": { + "200": { + "description": "Application", + "content": { + "application/activity+json": { + "schema": { + "type": "object" + } + } + } + } + } + } + }, + "/actor/outbox": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "Instance outbox", + "description": "Always empty.", + "operationId": "federation_instance_outbox", + "responses": { + "200": { + "description": "OrderedCollection", + "content": { + "application/activity+json": { + "schema": { + "type": "object" + } + } + } + } + } + } + }, + "/users/{username}/inbox": { + "post": { + "tags": [ + "ActivityPub" + ], + "summary": "User inbox", + "description": "Receives activities for one user (signed deliveries).", + "operationId": "federation_user_inbox", + "responses": { + "202": { + "description": "Accepted" + }, + "404": { + "description": "Unknown, or not sharing (the two are indistinguishable)" + }, + "413": { + "description": "Too large" + } + }, + "parameters": [ + { + "name": "username", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "application/activity+json": { + "schema": { + "type": "object" + } + } + } + } + }, + "parameters": [ + { + "in": "path", + "name": "username", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ] + }, + "/inbox": { + "post": { + "tags": [ + "ActivityPub" + ], + "summary": "Shared inbox", + "description": "Receives activities for any user on this server.", + "operationId": "federation_shared_inbox", + "responses": { + "202": { + "description": "Accepted" + }, + "413": { + "description": "Too large" + } + }, + "requestBody": { + "content": { + "application/activity+json": { + "schema": { + "type": "object" + } + } + } + } + } } }, "tags": [ @@ -1890,6 +2445,14 @@ { "name": "Last.fm", "description": "Last.fm-compatible API for players and scrobblers" + }, + { + "name": "Federation", + "description": "Sharing listening on the fediverse (ActivityPub). These endpoints only exist when the server has federation enabled; a 404 means it doesn't." + }, + { + "name": "ActivityPub", + "description": "Fediverse endpoints, served on the web UI's domain" } ], "openapi": "3.1.0", @@ -3005,6 +3568,155 @@ "api_key", "user" ] + }, + "SharingSettings": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Share listening on the fediverse" + }, + "visibility": { + "type": "string", + "enum": [ + "followers", + "unlisted", + "public" + ], + "description": "Who sees posts: `followers` (default), `unlisted` (anyone visiting the profile, not public timelines) or `public`. Followers-only is only as private as who may follow: see `manually_approves_followers`." + }, + "manually_approves_followers": { + "type": "boolean" + }, + "discoverable": { + "type": "boolean", + "description": "May appear in profile directories" + }, + "indexable": { + "type": "boolean", + "description": "Posts may be indexed for search" + }, + "display_name": { + "type": [ + "string", + "null" + ], + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 500 + }, + "handle": { + "type": "string", + "readOnly": true, + "example": "@alice@scrobble.example" + }, + "actor_url": { + "type": "string", + "readOnly": true + }, + "profile_url": { + "type": "string", + "readOnly": true + }, + "followers": { + "type": "integer", + "readOnly": true, + "description": "0 until following arrives" + } + }, + "additionalProperties": false + }, + "SharingSettingsUpdate": { + "type": "object", + "properties": { + "enabled": { + "type": "boolean", + "description": "Share listening on the fediverse" + }, + "visibility": { + "type": "string", + "enum": [ + "followers", + "unlisted", + "public" + ], + "description": "Who sees posts: `followers` (default), `unlisted` (anyone visiting the profile, not public timelines) or `public`. Followers-only is only as private as who may follow: see `manually_approves_followers`." + }, + "manually_approves_followers": { + "type": "boolean" + }, + "discoverable": { + "type": "boolean", + "description": "May appear in profile directories" + }, + "indexable": { + "type": "boolean", + "description": "Posts may be indexed for search" + }, + "display_name": { + "type": [ + "string", + "null" + ], + "maxLength": 100 + }, + "bio": { + "type": [ + "string", + "null" + ], + "maxLength": 500 + }, + "handle": { + "type": "string", + "readOnly": true, + "example": "@alice@scrobble.example" + }, + "actor_url": { + "type": "string", + "readOnly": true + }, + "profile_url": { + "type": "string", + "readOnly": true + }, + "followers": { + "type": "integer", + "readOnly": true, + "description": "0 until following arrives" + } + }, + "additionalProperties": false + }, + "PublicProfile": { + "type": "object", + "properties": { + "username": { + "type": "string" + }, + "display_name": { + "type": "string" + }, + "bio": { + "type": [ + "string", + "null" + ] + }, + "handle": { + "type": "string", + "example": "@alice@scrobble.example" + }, + "actor_url": { + "type": "string" + } + }, + "additionalProperties": false } }, "responses": { diff --git a/src/scrobbler/federation/README.md b/src/scrobbler/federation/README.md index 3023cd6..1043ce3 100644 --- a/src/scrobbler/federation/README.md +++ b/src/scrobbler/federation/README.md @@ -12,6 +12,7 @@ or switched off without touching anything else. Design: `docs/design/activitypub Signature schemes, vocabulary and document formats live there. 3. **The rest of this package uses only the core's public surface**: - `scrobbler.__version__` + - `scrobbler.api.get_api` (to register federation's API blueprint and document its paths) - `scrobbler.events` - `scrobbler.extensions` (`db`) - `scrobbler.worker` diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py index 1d67351..769b0f1 100644 --- a/src/scrobbler/federation/__init__.py +++ b/src/scrobbler/federation/__init__.py @@ -28,6 +28,10 @@ def init_app(app: Flask) -> None: return log.info("federation enabled: handles @user@%s, actors at %s", config.domain, config.base_url) - from scrobbler.federation import web + from scrobbler.api import get_api + from scrobbler.federation import api, openapi, web app.register_blueprint(web.bp) + core_api = get_api(app) + core_api.register_blueprint(api.blp, url_prefix="/api/v1/federation") + openapi.register(app, core_api) diff --git a/src/scrobbler/federation/api.py b/src/scrobbler/federation/api.py new file mode 100644 index 0000000..91132c2 --- /dev/null +++ b/src/scrobbler/federation/api.py @@ -0,0 +1,93 @@ +"""/api/v1/federation: sharing settings for the web UI, and public profiles.""" + +from flask import current_app, g +from flask_smorest import Blueprint, abort + +from scrobbler.api.decorators import authenticated +from scrobbler.federation import metrics as fed_metrics +from scrobbler.federation import sharing +from scrobbler.federation.schemas import ( + PublicProfileSchema, + SharingSettingsSchema, + SharingSettingsUpdateSchema, +) +from scrobbler.schemas import ErrorSchema + +blp = Blueprint( + "Federation", + __name__, + description=( + "Sharing listening on the fediverse (ActivityPub). These endpoints only exist when " + "the server has federation enabled; a 404 means it doesn't." + ), +) + + +def _identity(username: str) -> dict: + config = current_app.extensions["federation"] + return { + "handle": f"@{username}@{config.domain}", + "actor_url": f"{config.base_url}/users/{username}", + "profile_url": f"{current_app.config['UI_BASE_URL']}/profile.html?u={username}", + } + + +def _settings_body(user, settings) -> dict: + return { + **{field: getattr(settings, field) for field in sharing.EDITABLE}, + **_identity(user.username), + "followers": 0, + } + + +@blp.route("/settings", methods=["GET"]) +@authenticated(blp) +@blp.response(200, SharingSettingsSchema) +def get_settings(): + """Your sharing settings + + Sharing is off and posts are followers-only until you change them. + """ + return _settings_body(g.user, sharing.settings_for(g.user.id)) + + +@blp.route("/settings", methods=["PATCH"]) +@authenticated(blp) +@blp.arguments(SharingSettingsUpdateSchema) +@blp.response(200, SharingSettingsSchema) +@blp.alt_response(422, schema=ErrorSchema, description="Invalid settings") +def update_settings(changes): + """Change your sharing settings + + Turning sharing on makes you findable as your handle. Your handle can't change once + people follow you. Visibility changes apply to new posts only. + """ + try: + settings, toggled = sharing.update(g.user.id, changes) + except ValueError as err: + abort(422, code="invalid_settings", message=str(err)) + if toggled is not None: + fed_metrics.sharing_changes_total.labels(change="enabled" if toggled else "disabled").inc() + return _settings_body(g.user, settings) + + +@blp.route("/profiles/", methods=["GET"]) +@blp.response(200, PublicProfileSchema) +@blp.alt_response(404, schema=ErrorSchema, description="No one sharing with that name") +def public_profile(username): + """A public fediverse profile + + For the web UI's profile page. Only users who share are visible. + """ + found = sharing.shared_user(username) + if found is None: + fed_metrics.lookups_total.labels(kind="profile", result="not_found").inc() + abort(404, code="not_found", message="No one here shares their listening under that name.") + fed_metrics.lookups_total.labels(kind="profile", result="found").inc() + user, settings = found + return { + "username": user.username, + "display_name": settings.display_name or user.username, + "bio": settings.bio, + **{k: v for k, v in _identity(user.username).items() if k != "profile_url"}, + } diff --git a/src/scrobbler/federation/openapi.py b/src/scrobbler/federation/openapi.py new file mode 100644 index 0000000..a9c1f05 --- /dev/null +++ b/src/scrobbler/federation/openapi.py @@ -0,0 +1,156 @@ +"""OpenAPI descriptions of the ActivityPub endpoints (served on the UI's domain).""" + +from flask import Flask +from flask_smorest import Api + +TAG = "ActivityPub" + +_AP = {"application/activity+json": {"schema": {"type": "object"}}} +_NOT_FOUND = {"description": "Unknown, or not sharing (the two are indistinguishable)"} +_USERNAME = {"name": "username", "in": "path", "required": True, "schema": {"type": "string"}} + +# endpoint -> (method, summary, description, extra parameters, responses) +_OPERATIONS = { + "federation.webfinger_lookup": ( + "get", + "WebFinger", + "Resolves `acct:user@domain` (or an actor URL) to the user's actor. Only users " + "sharing their listening can be found.", + [ + { + "name": "resource", + "in": "query", + "required": True, + "schema": {"type": "string"}, + "example": "acct:alice@scrobble.example", + } + ], + { + "200": { + "description": "JRD", + "content": {"application/jrd+json": {"schema": {"type": "object"}}}, + }, + "400": {"description": "Not a resource on this server"}, + "404": _NOT_FOUND, + }, + ), + "federation.host_meta": ( + "get", + "host-meta", + "XRD pointing at WebFinger (RFC 6415).", + [], + { + "200": { + "description": "XRD", + "content": {"application/xrd+xml": {"schema": {"type": "string"}}}, + } + }, + ), + "federation.nodeinfo_discovery": ( + "get", + "NodeInfo discovery", + "Links to the NodeInfo 2.1 document.", + [], + { + "200": { + "description": "Links", + "content": {"application/json": {"schema": {"type": "object"}}}, + } + }, + ), + "federation.nodeinfo_document": ( + "get", + "NodeInfo 2.1", + "Software name and version, protocols, and users sharing.", + [], + { + "200": { + "description": "NodeInfo", + "content": {"application/json": {"schema": {"type": "object"}}}, + } + }, + ), + "federation.actor": ( + "get", + "Actor", + "A user's `Person` actor when asked for ActivityPub JSON; browsers are redirected to " + "the web UI's profile page.", + [_USERNAME], + { + "200": {"description": "Person", "content": _AP}, + "302": {"description": "Redirect to the profile page (non-ActivityPub Accept)"}, + "404": _NOT_FOUND, + }, + ), + "federation.outbox": ( + "get", + "Outbox", + "The user's published activities.", + [_USERNAME], + {"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND}, + ), + "federation.followers": ( + "get", + "Followers", + "Follower count (members aren't listed).", + [_USERNAME], + {"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND}, + ), + "federation.following": ( + "get", + "Following", + "Accounts the user follows.", + [_USERNAME], + {"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND}, + ), + "federation.instance_actor": ( + "get", + "Instance actor", + "The server's `Application` actor.", + [], + {"200": {"description": "Application", "content": _AP}}, + ), + "federation.instance_outbox": ( + "get", + "Instance outbox", + "Always empty.", + [], + {"200": {"description": "OrderedCollection", "content": _AP}}, + ), + "federation.user_inbox": ( + "post", + "User inbox", + "Receives activities for one user (signed deliveries).", + [_USERNAME], + { + "202": {"description": "Accepted"}, + "404": _NOT_FOUND, + "413": {"description": "Too large"}, + }, + ), + "federation.shared_inbox": ( + "post", + "Shared inbox", + "Receives activities for any user on this server.", + [], + {"202": {"description": "Accepted"}, "413": {"description": "Too large"}}, + ), +} + + +def register(app: Flask, api: Api) -> None: + api.spec.tag({"name": TAG, "description": "Fediverse endpoints, served on the web UI's domain"}) + rules = {rule.endpoint: rule for rule in app.url_map.iter_rules()} + for endpoint, (method, summary, description, parameters, responses) in _OPERATIONS.items(): + operation = { + "tags": [TAG], + "summary": summary, + "description": description, + "operationId": endpoint.replace(".", "_"), + "responses": responses, + } + if parameters: + operation["parameters"] = parameters + if method == "post": + operation["requestBody"] = {"content": _AP} + api.spec.path(rule=rules[endpoint], operations={method: operation}) diff --git a/src/scrobbler/federation/schemas.py b/src/scrobbler/federation/schemas.py new file mode 100644 index 0000000..24b3c14 --- /dev/null +++ b/src/scrobbler/federation/schemas.py @@ -0,0 +1,40 @@ +from marshmallow import Schema, fields, validate + +from scrobbler.federation.models import VISIBILITIES + + +class SharingSettingsSchema(Schema): + enabled = fields.Boolean(metadata={"description": "Share listening on the fediverse"}) + visibility = fields.String( + validate=validate.OneOf(VISIBILITIES), + metadata={ + "description": ( + "Who sees posts: `followers` (default), `unlisted` (anyone visiting the " + "profile, not public timelines) or `public`. Followers-only is only as private " + "as who may follow: see `manually_approves_followers`." + ) + }, + ) + manually_approves_followers = fields.Boolean() + discoverable = fields.Boolean(metadata={"description": "May appear in profile directories"}) + indexable = fields.Boolean(metadata={"description": "Posts may be indexed for search"}) + display_name = fields.String(allow_none=True, validate=validate.Length(max=100)) + bio = fields.String(allow_none=True, validate=validate.Length(max=500)) + handle = fields.String(dump_only=True, metadata={"example": "@alice@scrobble.example"}) + actor_url = fields.String(dump_only=True) + profile_url = fields.String(dump_only=True) + followers = fields.Integer( + dump_only=True, metadata={"description": "0 until following arrives"} + ) + + +class PublicProfileSchema(Schema): + username = fields.String() + display_name = fields.String() + bio = fields.String(allow_none=True) + handle = fields.String(metadata={"example": "@alice@scrobble.example"}) + actor_url = fields.String() + + +class SharingSettingsUpdateSchema(SharingSettingsSchema): + """Any subset of the editable settings (read-only fields are rejected).""" diff --git a/src/scrobbler/openapi/export.py b/src/scrobbler/openapi/export.py new file mode 100644 index 0000000..a6f5801 --- /dev/null +++ b/src/scrobbler/openapi/export.py @@ -0,0 +1,41 @@ +"""Write docs/openapi.json: the API as documented with every optional module enabled. + + uv run python -m scrobbler.openapi.export docs/openapi.json + +A running server's own /api/openapi.json only lists what it has enabled. +""" + +import json +import sys + +from scrobbler.config import Config + + +class DocsConfig(Config): + START_METRICS_SERVER = False + UI_BASE_URL = "https://scrobble.example" + FEDERATION_ENABLED = "1" + FEDERATION_DOMAIN = "scrobble.example" + FEDERATION_BASE_URL = "https://scrobble.example" + FEDERATION_KEY_SECRET = "documentation-only-not-a-real-secret-0000" + + +def build_spec() -> dict: + from scrobbler import create_app + from scrobbler.api import get_api + + app = create_app(DocsConfig) + with app.app_context(): + return get_api(app).spec.to_dict() + + +def main(argv: list[str]) -> None: + path = argv[1] if len(argv) > 1 else "docs/openapi.json" + with open(path, "w") as out: + json.dump(build_spec(), out, indent=2, ensure_ascii=False) + out.write("\n") + print(f"wrote {path}") + + +if __name__ == "__main__": + main(sys.argv) diff --git a/tests/test_federation_api.py b/tests/test_federation_api.py new file mode 100644 index 0000000..d88dea6 --- /dev/null +++ b/tests/test_federation_api.py @@ -0,0 +1,82 @@ +import pytest + + +@pytest.fixture +def fed_auth(fed_ctx, user): + from scrobbler.services.accounts import issue_ui_token + + return {"Authorization": f"Bearer {issue_ui_token(user)}"} + + +def test_settings_start_private(fed_client, fed_auth): + body = fed_client.get("/api/v1/federation/settings", headers=fed_auth).get_json() + assert body["enabled"] is False + assert body["visibility"] == "followers" + assert (body["discoverable"], body["indexable"], body["manually_approves_followers"]) == ( + False, + False, + False, + ) + assert body["handle"] == "@alice@scrobble.test" + assert body["actor_url"] == "https://scrobble.test/users/alice" + assert body["profile_url"] == "http://localhost:8080/profile.html?u=alice" + + +def test_enable_and_change_settings(fed_client, fed_auth, metric_delta): + enabled = metric_delta("scrobbler_federation_sharing_changes_total", change="enabled") + response = fed_client.patch( + "/api/v1/federation/settings", + json={"enabled": True, "visibility": "unlisted", "display_name": "Alice", "bio": "Hi"}, + headers=fed_auth, + ) + assert response.status_code == 200 + body = response.get_json() + assert (body["enabled"], body["visibility"], body["display_name"]) == ( + True, + "unlisted", + "Alice", + ) + assert enabled.delta == 1 + # Now findable + doc = fed_client.get("/users/alice", headers={"Accept": "application/activity+json"}).get_json() + assert doc["name"] == "Alice" + # A partial update leaves the rest alone + body = fed_client.patch( + "/api/v1/federation/settings", json={"bio": None}, headers=fed_auth + ).get_json() + assert (body["visibility"], body["bio"]) == ("unlisted", None) + + +@pytest.mark.parametrize( + "changes", + [ + {"visibility": "everyone"}, + {"handle": "@x@y"}, + {"display_name": "x" * 101}, + {"enabled": "maybe"}, + ], +) +def test_invalid_settings_are_rejected(fed_client, fed_auth, changes): + response = fed_client.patch("/api/v1/federation/settings", json=changes, headers=fed_auth) + assert response.status_code == 422 + + +def test_settings_need_auth(fed_client): + assert fed_client.get("/api/v1/federation/settings").status_code == 401 + + +def test_public_profile(fed_client, sharing_user, make_user): + body = fed_client.get("/api/v1/federation/profiles/Alice").get_json() + assert body == { + "username": "alice", + "display_name": "Alice", + "bio": "Listening.", + "handle": "@alice@scrobble.test", + "actor_url": "https://scrobble.test/users/alice", + } + make_user(username="bob") + assert fed_client.get("/api/v1/federation/profiles/bob").status_code == 404 + + +def test_disabled_server_has_no_federation_api(client, auth): + assert client.get("/api/v1/federation/settings", headers=auth).status_code == 404 diff --git a/tests/test_federation_boundary.py b/tests/test_federation_boundary.py index 625eb4e..09d459c 100644 --- a/tests/test_federation_boundary.py +++ b/tests/test_federation_boundary.py @@ -36,6 +36,7 @@ FRAMEWORKS = ( ) CORE_PUBLIC_SURFACE = ( "scrobbler.__version__", + "scrobbler.api.get_api", "scrobbler.events", "scrobbler.extensions", "scrobbler.worker", @@ -85,7 +86,8 @@ def violations(module: str, imports: set[str]) -> list[str]: problems.append(f"{module} (protocol) imports {name}") elif within(module, FEDERATION): for name in imports: - if not within(name, "scrobbler") or name == "scrobbler": + # The packages themselves (for their public names listed above) are fine. + if not within(name, "scrobbler") or name in ("scrobbler", "scrobbler.api"): continue if within(name, FEDERATION) or any(within(name, ok) for ok in CORE_PUBLIC_SURFACE): continue @@ -126,6 +128,7 @@ def test_federation_package_is_checked(): (PROTOCOL + ".vocab", "from ..config import FederationConfig", "imports"), (FEDERATION + ".inbox", "from scrobbler.models import User", "core internals"), (FEDERATION + ".inbox", "from scrobbler import metrics", "core internals"), + (FEDERATION + ".api", "from scrobbler.api import apps", "core internals"), ], ) def test_the_checker_catches_violations(module, source, expected): @@ -143,6 +146,7 @@ def test_the_checker_catches_violations(module, source, expected): "from scrobbler.services import stats\nfrom scrobbler import events", ), (FEDERATION + ".inbox", "from .protocol import vocab\nfrom flask import Blueprint"), + (FEDERATION, "from scrobbler.api import get_api"), (PROTOCOL + ".signatures.rfc9421", "from ..vocab import note\nimport hashlib"), ], ) diff --git a/tests/test_openapi.py b/tests/test_openapi.py index 8e84d9f..25c11e6 100644 --- a/tests/test_openapi.py +++ b/tests/test_openapi.py @@ -8,7 +8,17 @@ from openapi_spec_validator import validate from scrobbler.lastfm.registry import METHODS COMMITTED_SPEC = Path(__file__).resolve().parents[1] / "docs" / "openapi.json" -DOCUMENTED_PREFIXES = ("/api/v1/", "/2.0/", "/api/auth/", "/healthz") +DOCUMENTED_PREFIXES = ( + "/api/v1/", + "/2.0/", + "/api/auth/", + "/healthz", + "/.well-known/", + "/nodeinfo/", + "/users/", + "/inbox", + "/actor", +) HTTP_VERBS = {"get", "put", "post", "delete", "patch", "head", "options"} @@ -25,7 +35,21 @@ def test_spec_is_valid_openapi(spec): validate(spec) -def test_every_api_route_is_documented(app, spec): +@pytest.fixture(scope="module") +def fed_spec(fed_app): + return fed_app.test_client().get("/api/openapi.json").get_json() + + +def test_every_api_route_is_documented(app, spec, fed_app, fed_spec): + _check_documented(app, spec) + _check_documented(fed_app, fed_spec) # with federation's routes too + + +def test_federation_off_documents_no_federation_paths(spec): + assert not [p for p in spec["paths"] if p.startswith(("/api/v1/federation", "/users/"))] + + +def _check_documented(app, spec): for rule in app.url_map.iter_rules(): if not rule.rule.startswith(DOCUMENTED_PREFIXES): continue @@ -47,8 +71,13 @@ def test_every_lastfm_method_is_documented(spec): assert len(request_schemas) == len(METHODS) -def test_ui_routes_declare_bearer_auth(spec): - public = {("/api/v1/auth/login", "post"), ("/api/v1/auth/register", "post")} +def test_ui_routes_declare_bearer_auth(fed_spec): + spec = fed_spec # includes the federation API + public = { + ("/api/v1/auth/login", "post"), + ("/api/v1/auth/register", "post"), + ("/api/v1/federation/profiles/{username}", "get"), + } for path, operations in spec["paths"].items(): if not path.startswith("/api/v1/"): continue @@ -67,9 +96,11 @@ def test_docs_pages_are_served(client): assert client.get("/api/redoc").status_code == 200 -def test_committed_spec_is_up_to_date(spec): +def test_committed_spec_is_up_to_date(): + from scrobbler.openapi.export import build_spec + committed = json.loads(COMMITTED_SPEC.read_text()) - assert committed == spec, ( + assert committed == build_spec(), ( "docs/openapi.json is stale. Regenerate it with: " - "uv run flask --app scrobbler openapi write --format=json docs/openapi.json" + "uv run python -m scrobbler.openapi.export docs/openapi.json" )