From d2c71d50f1da25d6775735d8b991f4d640accf9f Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 19:36:45 +0100 Subject: [PATCH 01/56] Design proposal: ActivityPub federation Research write-up for making Scrobbler users followable from the fediverse: protocol pieces (WebFinger, actor, inbox, signatures in both draft-cavage and RFC 9421, delivery), what gets posted (weekly summary, milestones, now playing), build-vs-library, data model, security, testing against GoToSocial, phased plan and open decisions. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/design/activitypub.md | 291 +++++++++++++++++++++++++++++++++++++ 1 file changed, 291 insertions(+) create mode 100644 docs/design/activitypub.md diff --git a/docs/design/activitypub.md b/docs/design/activitypub.md new file mode 100644 index 0000000..9efe9a0 --- /dev/null +++ b/docs/design/activitypub.md @@ -0,0 +1,291 @@ +# ActivityPub federation: design proposal + +Status: **proposal, for review.** Nothing here is built yet. The decisions still open are listed at the end. + +## Summary + +Let a user turn their Scrobbler account into a fediverse account, for example `@alice@scrobble.example`, that people on Mastodon, GoToSocial, Misskey and similar servers can follow. Followers see three kinds of post: + +- a **weekly listening summary** +- **milestones** (for example "10,000th scrobble") +- **what the user is playing now** + +The first version is **outbound only**: Scrobbler publishes, and it accepts and manages followers. Following other people and showing their listening in the UI is a possible later phase (see [Later](#later-following-and-listen-activities)). The data model is designed so it can be added without rework. + +Federation is **off for everyone until they turn it on**. Until then a user can't be found by WebFinger and nothing about them is published. + +**Recommendation:** write the protocol layer ourselves, on `cryptography` plus the Flask, SQLAlchemy and worker setup we already have (about 1,500 lines, in the four phases below), rather than adopt a library. The main reason is licensing (see [Build or buy](#build-or-buy)). + +## What users get + +- **Settings → Sharing**, a new UI page: + - A **Share my listening on the fediverse** switch. It shows the handle (`@alice@scrobble.example`) and warns that the handle can't change once people follow it. + - Choose what to post: + - **Weekly summary**: on by default once sharing is on. + - **Milestones**: on by default. + - **Now playing**: off by default, with two ways to show it. See [Now playing](#now-playing). + - **Who can see posts**: *Unlisted* (recommended: followers and profile visitors only, not public timelines), *Public*, or *Followers only*. + - **Approve followers manually** (off by default). + - Profile fields: display name, bio, avatar. The avatar defaults to a generated cover-art-style tile. +- **Followers**: a list of remote followers, with *Remove*. There are *Approve* and *Decline* buttons when manual approval is on. +- **Turning sharing off** deletes the published posts from followers' servers (`Delete` activities) and removes the followers. The account goes back to being unreachable. Keys are kept, so turning it on again keeps the same identity. Remote servers may still cache the old profile. + +## How it fits the current system + +``` +Mastodon, GoToSocial, … Scrobbler +──────────────────────────────────────────────────────────────────────────── +GET /.well-known/webfinger?resource=acct:… ─► API (only for opted-in users) +GET /users/alice (Accept: activity+json) ─► API actor document +POST /users/alice/inbox or /inbox ─► API verify signature, record, 202 + │ Follow → follower (+ Accept queued) + ▼ + Postgres ◄── worker (`flask worker`) + │ • delivers queued activities (signed POSTs) +◄──────────── POST {follower shared inbox} ──────┘ • weekly summaries, milestones, now playing +``` + +- The **API** serves everything a remote server fetches: WebFinger, NodeInfo, actors, outboxes and inboxes. The inbox only validates and records; it never makes outbound calls itself. +- The **worker** (today's import worker, generalised to `flask worker`) does all outbound work: `Accept`s, post deliveries, retries, and the scheduled weekly and milestone posts. It uses the same claim-with-`SKIP LOCKED` pattern as imports. +- The **UI** gains the Sharing and Followers pages, which call new `/api/v1/federation/*` endpoints. + +## Protocol pieces + +### Identity and domains ("decide later", made configurable) + +Two settings: + +- `FEDERATION_DOMAIN`: the handle's domain, as in `@alice@`. +- `FEDERATION_BASE_URL`: where the actor documents live, as in `https:///users/alice`. + +They can be the same (simplest) or different. If they differ, the handle domain only has to answer `/.well-known/webfinger` (and ideally `/.well-known/host-meta`). Mastodon supports this split: it follows the WebFinger `self` link to the actor. So the UI's nginx can forward just `/.well-known/webfinger` to the API and keep the API on its own hostname. + +**Both values become permanent once anyone follows**: actor IDs are how other servers identify the account. Renaming a user or moving domains later needs the `Move` flow and `alsoKnownAs` (see [Later](#later-following-and-listen-activities)). So we should: + +- stop users renaming themselves once they've enabled sharing, and +- refuse to start if the domain settings change while followers exist, unless an explicit migration flag is set. + +### WebFinger (RFC 7033) + +- `GET /.well-known/webfinger?resource=acct:alice@domain` returns `subject` plus two links: + - a `self` link of type `application/activity+json` pointing to the actor + - a `profile-page` link to the UI +- It returns **404** for unknown users and for users who haven't opted in. The response is identical in both cases, so the endpoint can't be used to list accounts. +- It's required: Mastodon resolves `@user@domain` through it. + +### Actor (`Person`) + +`GET /users/{username}` with `Accept: application/activity+json` or `application/ld+json; profile="https://www.w3.org/ns/activitystreams"` returns the actor document. Its fields: + +- `id`, `type: Person`, `preferredUsername`, `name`, `summary`, `url` (the UI profile), `icon` +- `inbox`, `outbox`, `followers`, `following`, and `endpoints.sharedInbox` +- `publicKey`: `{id: …#main-key, owner, publicKeyPem}` +- `manuallyApprovesFollowers`, and `discoverable` and `indexable`. The last two are **false** by default and are settings the user can change. +- `attachment`: `PropertyValue` profile fields, for example "Scrobbles: 12,345". This is also where [now playing](#now-playing) can live. + +A browser (a non-ActivityPub `Accept` header) is redirected to the UI profile page. + +### Keys and signatures + +- **One RSA-2048 key pair per federated user.** Mastodon's draft-signature path requires RSA. + - Private keys are **encrypted at rest** with a Fernet key derived from `FEDERATION_KEY_SECRET` (Mastodon 4.7 does the same). + - Ed25519 keys ([FEP-521a](https://codeberg.org/fediverse/fep/src/branch/main/fep/521a/fep-521a.md)) can be added later without breaking anything. +- **Outgoing**: sign with the draft-cavage HTTP Signatures scheme, still the most widely accepted. + - Signed headers: `(request-target) host date digest`, using `rsa-sha256`. + - The body digest goes in `Digest: SHA-256=…`. +- **Incoming**: verify both **draft-cavage** and **RFC 9421** (`Signature-Input`/`Signature`, which covers `@method`, `@target-uri` and `Content-Digest`). + - Mastodon 4.5+ accepts RFC 9421. + - Mastodon 4.7 *sends* RFC 9421 when a draft-signed request fails ("double-knocking"). Accepting both avoids needless failures. +- **Verification rules**: + - `Date` within ±12 hours. + - The digest must match the body. + - Fetch the `keyId` document and confirm its `owner` is the activity's `actor`. + - Cache remote keys, and re-fetch once on failure in case the key was rotated. + - Ignore Linked Data Signatures; Mastodon itself advises against implementing them. +- **Signed GETs**: some servers use "authorized fetch" (secure mode), which requires signed GETs. We always sign our fetches of remote actors, using an instance actor (`/actor`, type `Application`), so fetching works everywhere. + +The signing code is small and well specified. Test vectors come from the specs and from recorded Mastodon and GoToSocial requests. + +### Inbox + +- `POST /users/{u}/inbox` and a shared `POST /inbox`. Limits: 256 KB body, and JSON-LD content types only. +- Once the signature is verified, an activity is **recorded and answered with 202**. Processing is quick and does no network I/O. Activity IDs are deduplicated. + +| Activity | Handling | +|---|---| +| `Follow` (object = our actor) | Store the follower: `accepted`, or `pending` if manual approval is on. Queue an `Accept` (or wait for the user to decide). | +| `Undo` → `Follow` | Remove the follower. | +| `Delete` (actor) | Remove the follower and drop the cached actor. | +| `Update` (Person) | Refresh the cached actor, which may have a new shared inbox or key. | +| `Like`, `Announce`, `Create` (replies) | Recorded for metrics only; not shown in v1. | +| Anything else | Accepted and ignored. | + +- **Blocks**: + - A user can block a remote account, which also removes it as a follower. + - An admin can block a whole domain with `FEDERATION_BLOCKED_DOMAINS`. Blocked senders get 403, and their `Follow`s are rejected. + +### Collections + +- `outbox`: an `OrderedCollection`, paged, holding the user's public and unlisted `Create` activities, newest first. +- `followers`: shows `totalItems` only. Items are hidden, as Mastodon does by default. +- `following`: an empty collection in v1. + +### NodeInfo 2.1 + +Serve `/.well-known/nodeinfo` and `/nodeinfo/2.1`, giving the software name `scrobbler`, the version, protocols `["activitypub"]`, and user counts (opted-in users only). Fediverse tooling and statistics sites read it, and it's cheap. + +### Delivery + +- Every outgoing activity is saved, then turned into **delivery rows**: one per distinct inbox, using each follower's shared inbox where it has one. +- The worker delivers them with signed POSTs. Timeouts are 10s to connect and 20s to read. +- **Retries**: failures are retried with exponential backoff (1m, 5m, 30m, 2h, 6h, then every 12h) for up to **2 days**. After that the delivery is dropped and the peer marked unhealthy. + - 410 Gone and permanent 4xx responses aren't retried. + - 410 Gone for an actor removes it as a follower. +- **Outbound fetches are protected against SSRF**: HTTPS only, no private or loopback addresses (checked after DNS resolution), a 1 MB response limit, and at most 3 redirects. + +## What gets posted + +Posts are `Note` objects inside `Create` activities: Mastodon shows `Note` as a normal status, while other types are squashed into a title and link. The HTML uses only tags Mastodon keeps (`p`, `a`, `br`, `strong`, `em`, `ul`, `ol`, `li`), and all track and artist text is escaped. Each post also gets hashtags (`#NowPlaying`, `#Scrobbler`) as `Hashtag` tags. Visibility follows the user's setting: + +| Setting | `to` | `cc` | +|---|---|---| +| Public | `as:Public` | followers | +| Unlisted | followers | `as:Public` | +| Followers only | followers | *(none)* | + +### Weekly summary + +- The worker posts one per opted-in user, on Monday at 09:00 in the user's time zone. Users don't have a time zone yet, so the Sharing page adds one, defaulting to the browser's. +- Posting is idempotent: there's one summary per user per ISO week, so a worker restart doesn't post twice. +- Weeks with no plays are skipped. + +Example: + +> **This week: 312 scrobbles** +> Top artists: 1. Radiohead (48) 2. Björk (31) 3. Portishead (22) +> Top track: *Reckoner* by Radiohead (12 plays) +> #Scrobbler + +### Milestones + +These are checked after each scrobble batch and each import, and each one is posted at most once: + +- **Scrobble counts**: the 1,000th, 5,000th and 10,000th scrobble, then every 25,000. +- **Artist plays**: an artist's 100th or 500th play. +- **All-time top 10**: a new artist enters it. + +History imports never produce milestone posts: importing 50,000 old plays shouldn't set off a burst of them. Milestones only start counting after the import. + +### Now playing + +A new post for every track would flood followers' timelines. There are two options: + +1. **Profile field (recommended default)**: a "Now playing: *Reckoner* by Radiohead" field on the profile. The field is updated with an `Update(Person)` when the track changes, at most once every 5 minutes, and cleared when playback stops. Nothing appears in timelines; followers see it on the profile. This option is cheap and quiet. +2. **Posts (opt-in)**: a `Note` when a track starts, at most one every 30 minutes, and only for tracks played for at least 30 seconds. + - It uses the user's visibility setting, with a suggested default of *followers only* for these. + - Optionally, the previous now-playing post is deleted when the next one goes out, so only one exists at a time. + +## Build or buy + +| | Write it ourselves (recommended) | Pubby (Python) | Fedify (TypeScript) sidecar | +|---|---|---|---| +| Fits the codebase | Same Flask, SQLAlchemy, worker, metrics and OpenAPI patterns | Flask adapter and SQLAlchemy storage | A second language and service | +| Signatures | Draft-cavage and RFC 9421 (we write both) | HTTP Signatures (built in) | Draft, RFC 9421, FEP-8b32 | +| **Licence** | Ours | **AGPL-3.0-or-later**: offering the service over a network brings AGPL obligations for the whole app | MIT | +| Maturity | New code, but the scope is narrow | Active, but young (0.3.x, one maintainer) | The most complete framework | +| Effort | About 1,500 lines, mostly signatures, inbox and delivery | Less code, but we'd adapt its storage and flow to ours | A new service to run and monitor | + +Unless you're happy to license Scrobbler under the AGPL, adopting Pubby isn't free. Fedify is excellent, but it would split the backend across two languages. The protocol surface we need is small (four activity types in and three out), so writing it ourselves is the least total cost. It also keeps ActivityPub on the same metrics, dashboards and tests as everything else. + +## Data model + +| Table | Holds | +|---|---| +| `federation_settings` | Per user: `enabled`, visibility, which post types, now-playing mode, manual approval, discoverable and indexable, time zone, display name, bio, avatar | +| `actor_keys` | Per user, plus one instance actor: public key PEM, encrypted private key, created and rotated times | +| `remote_actors` | Cache: actor URI, inbox, shared inbox, key ID and PEM, handle, display name, `fetched_at`, health | +| `followers` | Local user ↔ remote actor, with state (`pending`, `accepted`), the Follow activity ID, and when | +| `blocks` | Per-user remote-actor blocks, plus admin domain blocks | +| `outbox_activities` | Our activities (ID, type, JSON, visibility, published). They are the source for the outbox collection and for deliveries | +| `deliveries` | Activity × target inbox: `attempts`, `next_attempt_at`, `status`, `last_error` | +| `inbox_activities` | Received activity IDs (for deduplication), type, actor, and outcome. Pruned after 30 days | +| `posted_milestones` / `weekly_posts` | One row per posted milestone or week, which keeps posting idempotent | + +## Security and privacy + +- **Opt-in.** Nothing about a user is published or discoverable until they turn sharing on. Existing listening history is never posted retroactively: summaries start from the next week, and milestones from the next scrobble. +- **Nothing that allows tracking**: we publish aggregates and choices the user made explicitly, never raw scrobble timestamps. Now-playing is throttled and can be switched off. +- **The inbox is the new attack surface**: + - signature checks before any processing + - body size limits + - rate limits per remote host + - activity deduplication + - the SSRF-hardened fetcher described above + - no HTML from remote servers is ever rendered in v1 +- **Followers can be removed or blocked**, and admins can block whole domains. +- **Private keys are encrypted at rest**, with `FEDERATION_KEY_SECRET` kept separate from `SECRET_KEY`. + +## Observability + +Everything goes on the existing Prometheus and Grafana setup: + +- **Metrics**: + - `scrobbler_federation_inbox_activities_total{type,result}` + - `scrobbler_federation_signature_failures_total{scheme,reason}` + - `scrobbler_federation_deliveries_total{result}` + - `scrobbler_federation_delivery_queue{status}` + - `scrobbler_federation_followers` + - `scrobbler_federation_posts_total{kind}` +- **Dashboard**: a new **Federation** dashboard. +- **Alerts**: the delivery queue growing for 30 minutes, and signature failures spiking. + +## Testing and interoperability + +- **Unit tests**: + - signing and verification against spec test vectors and recorded requests + - WebFinger, actor and collection shapes + - inbox state transitions + - delivery retry schedule + - visibility addressing +- **In-process federation**: two Scrobbler instances in one test process following each other. +- **A real peer in CI**: a [GoToSocial](https://gotosocial.org) container, which is a single binary with SQLite. It follows a Scrobbler user and we assert that it receives the `Accept` and the posts. That's much lighter than running Mastodon in CI. +- **Manual pass before release**: + - follow from a real Mastodon account + - check the profile, posts, profile-field updates and unfollowing + - check with [verify.funfedi.dev](https://verify.funfedi.dev/) or the [ActivityPub Academy](https://activitypub.academy/) + +## Phases + +Each phase can be released on its own, with its migration, docs, OpenAPI updates, metrics and tests. + +1. **Discoverable profile.** Settings, keys, WebFinger, the actor, NodeInfo and the Sharing page. A user can turn sharing on and be found from Mastodon, but can't be followed yet. +2. **Followers.** Inbox, signature verification (both schemes), the delivery queue with retries and signing, `Accept`, removing and blocking followers, the Followers page, and the GoToSocial CI test. +3. **Posts.** The outbox, weekly summaries, milestones, and deleting posts when sharing is turned off. Adds the Federation dashboard and alerts. +4. **Now playing.** The profile-field mode, then optional posts. + +## Later: following and `Listen` activities + +This is the "profiles plus friends' listening" option, deliberately left out of v1: + +- Users follow other Scrobbler users, or any actor that publishes listens, and see a friends feed in the UI. +- **Wire format**: ActivityStreams has a `Listen` activity type. Funkwhale already federates `Listen` activities whose object is a `Track`. We'd send the same thing to followers on Scrobbler and Funkwhale servers only. Mastodon ignores activity types it doesn't know, and a stream of `Listen`s isn't something people want in their timelines anyway. +- **Changes needed**: an outbound `Follow` flow, storing received listens, a feed UI, and moderation of incoming content. +- **Account migration** (`Move` and `alsoKnownAs`) would come with this, so users can change handle or domain without losing followers. + +## Decisions for you + +1. **Domain.** Handles on the UI's domain (nginx forwards `/.well-known/webfinger`) or on the API's? Both are supported; this is a deployment choice, but it's permanent once people follow. +2. **Licence.** OK to write it ourselves (recommended), or would you rather adopt Pubby and accept the AGPL? +3. **Default visibility** for summaries and milestones: *Unlisted* (recommended) or *Public*? +4. **Now-playing default** once a user turns it on: the profile field (recommended), or posts? +5. **Does it need an admin?** Phase 2 assumes domain blocks set in configuration. A real moderation UI (reports, per-domain policies) would be a separate piece of work. + +## Sources + +- [Mastodon ActivityPub spec](https://docs.joinmastodon.org/spec/activitypub/): object rendering, supported activities, actor properties, visibility addressing, allowed HTML +- [Mastodon security spec](https://docs.joinmastodon.org/spec/security/): draft-cavage requirements, RFC 9421 accepted from 4.5, 12-hour clock skew, LD Signatures not advised +- [Mastodon 4.7 release notes](https://blog.joinmastodon.org/2026/08/mastodon-4.7/): RFC 9421 fallback when sending, FEP-521a keys (RSA, Ed25519, ML-DSA-44), FEP-8b32, encrypted private keys +- [Mastodon WebFinger spec](https://docs.joinmastodon.org/spec/webfinger/) +- [SocialHub: RFC 9421 HTTP signatures in 2026](https://socialhub.activitypub.rocks/t/rfc-9421-http-signatures-in-2026/8427) +- [Funkwhale federation docs](https://docs.funkwhale.audio/develop/developer/federation/index.html): the `Listen` activity with a `Track` object +- [Pubby on PyPI](https://pypi.org/project/pubby/): features and AGPL-3.0-or-later licence From 5d71116613acc9626e3cbd7b7f9d7be60a2a1bbd Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 19:48:04 +0100 Subject: [PATCH 02/56] ActivityPub design: build in-house as one replaceable module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Settles build vs buy: write it ourselves (Scrobbler is BSD-3-Clause; the Python library option is AGPL) - New "Module structure" section: everything in scrobbler.federation, a pure protocol/ subpackage for spec-dependent code, pluggable signature schemes/inbox handlers/post kinds, core → federation only via blinker domain events, own federation_* tables in a separate Alembic branch, generic task worker, and boundary tests enforcing it - Adds a groundwork phase 0 and updates the open decisions Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/design/activitypub.md | 95 +++++++++++++++++++++++++++++++++++--- 1 file changed, 89 insertions(+), 6 deletions(-) diff --git a/docs/design/activitypub.md b/docs/design/activitypub.md index 9efe9a0..b11430e 100644 --- a/docs/design/activitypub.md +++ b/docs/design/activitypub.md @@ -14,7 +14,9 @@ The first version is **outbound only**: Scrobbler publishes, and it accepts and Federation is **off for everyone until they turn it on**. Until then a user can't be found by WebFinger and nothing about them is published. -**Recommendation:** write the protocol layer ourselves, on `cryptography` plus the Flask, SQLAlchemy and worker setup we already have (about 1,500 lines, in the four phases below), rather than adopt a library. The main reason is licensing (see [Build or buy](#build-or-buy)). +**Decided:** we write the protocol layer ourselves, on `cryptography` plus the Flask, SQLAlchemy and worker setup we already have (about 1,500 lines, in the four phases below). Scrobbler is BSD-licensed, and the ready-made Python library is AGPL (see [Build or buy](#build-or-buy)). + +All of it lives in **one self-contained package, `scrobbler.federation`**, behind a narrow interface. It can then be changed, replaced or switched off without touching the rest of the app, and changes to the specs (signature schemes, vocabulary, FEPs) stay inside it. See [Module structure](#module-structure). ## What users get @@ -49,6 +51,72 @@ POST /users/alice/inbox or /inbox ─► API verify signature, reco - The **worker** (today's import worker, generalised to `flask worker`) does all outbound work: `Accept`s, post deliveries, retries, and the scheduled weekly and milestone posts. It uses the same claim-with-`SKIP LOCKED` pattern as imports. - The **UI** gains the Sharing and Followers pages, which call new `/api/v1/federation/*` endpoints. +## Module structure + +Everything to do with ActivityPub lives in `src/scrobbler/federation/`. The rest of Scrobbler knows only two things about it: how to switch it on, and a handful of domain events. Replacing the implementation (with another library, or a rewrite when the specs move on) means replacing this package; nothing else changes. + +``` +src/scrobbler/ + events.py # core → anyone: blinker signals (scrobbles_stored, now_playing_changed, …) + worker.py # generic worker: runs tasks registered by any module + federation/ + __init__.py # init_app(app): the ONLY entry point. No-op unless FEDERATION_ENABLED + config.py # FEDERATION_* settings and their validation + protocol/ # pure ActivityPub: no Flask, no SQLAlchemy, no scrobbler imports + vocab.py # JSON-LD builders: Person, Note, Create, Accept, Update, Delete, collections + addressing.py # visibility → to/cc + webfinger.py # JRD documents, acct: parsing + nodeinfo.py + signatures/ + base.py # Signer / Verifier interfaces, SignedRequest value object + draft_cavage.py # one module per scheme; add/remove schemes here + rfc9421.py + net.py # SSRF-safe HTTP client; signed GET/POST using protocol.signatures + models.py # federation_* tables (own migrations, see below) + keys.py # key generation, encryption at rest, rotation + inbox.py # activity-type → handler registry (like the Last.fm method registry) + delivery.py # queue, retries, shared-inbox fan-out (a worker task) + publishing/ # what gets posted; each kind is a plug-in + summary.py # weekly summary + milestones.py + now_playing.py + subscribers.py # connects core events to publishing + web.py # Flask blueprint: webfinger, nodeinfo, actor, inbox, outbox, collections + api.py # /api/v1/federation/* (settings, followers) for the UI + metrics.py # federation's own Prometheus metrics +``` + +**Rules that keep the boundary clean:** + +1. **The core never imports `scrobbler.federation`.** The only exception is `create_app()`, which calls `federation.init_app(app)`. + - Core code tells the outside world what happened by sending **domain events** from `scrobbler/events.py`: + - `scrobbles_stored(user, scrobbles, source)` + - `now_playing_changed(user, track or None)` + - `import_finished(user, job)` + - `user_deleted(user)` + - These are blinker signals; blinker is already a Flask dependency. Federation subscribes to them; with federation off, nothing listens. + - Imports can pass `source="import"`, which is how milestones know to ignore imported history. +2. **Federation reads core data only through core services** (`services.stats`, `services.accounts`), never by querying core tables directly. So core schema changes don't break it. +3. **`federation.protocol` is pure.** It has no Flask, SQLAlchemy or `scrobbler` imports: just dicts, dataclasses and `cryptography`. + - This is where spec changes land. A new signature scheme is a new module under `signatures/`. A vocabulary change is a builder in `vocab.py`. + - It's tested with spec test vectors and recorded requests alone. +4. **Pluggable pieces go through registries**, not `if` chains: + - **Signature schemes.** `FEDERATION_SIGNATURE_SCHEMES=draft-cavage,rfc9421` sets which schemes are accepted and the order they're tried when sending. Dropping draft-cavage one day would be a config change followed by deleting a module. + - **Inbox activity handlers**: activity type → handler, the same pattern as the Last.fm method registry. + - **Post kinds**: summary, milestones and now playing each register as a publisher. +5. **Federation owns its data.** Its tables are all prefixed `federation_` and have foreign keys to `users` only. + - Its migrations live in their own Alembic branch (`migrations/versions/federation_*`, `branch_labels=("federation",)`), so they can be dropped or rewritten without touching the core migration history. + - Removing the module means dropping its branch, which drops its tables. +6. **Work in the background goes through a generic task runner.** Today's import worker becomes `scrobbler/worker.py`, which runs tasks registered by modules: imports register theirs, and federation registers delivery and scheduled posting. The worker doesn't know what ActivityPub is. +7. **Enforced by tests.** A boundary test walks every module's imports and fails if: + - anything outside `scrobbler.federation` imports it (apart from `create_app`), + - `federation.protocol` imports Flask, SQLAlchemy or `scrobbler`, or + - federation code imports core models directly. + + There's also a test that the whole app works with `FEDERATION_ENABLED=0`: no routes registered, no signal receivers, no tables touched. + +**Switching it off:** with `FEDERATION_ENABLED=0` (the default until an operator sets up a domain), `init_app` registers nothing. There are no routes, no subscribers and no worker tasks, and the app behaves exactly as it does today. + ## Protocol pieces ### Identity and domains ("decide later", made configurable) @@ -195,10 +263,14 @@ A new post for every track would flood followers' timelines. There are two optio | Maturity | New code, but the scope is narrow | Active, but young (0.3.x, one maintainer) | The most complete framework | | Effort | About 1,500 lines, mostly signatures, inbox and delivery | Less code, but we'd adapt its storage and flow to ours | A new service to run and monitor | -Unless you're happy to license Scrobbler under the AGPL, adopting Pubby isn't free. Fedify is excellent, but it would split the backend across two languages. The protocol surface we need is small (four activity types in and three out), so writing it ourselves is the least total cost. It also keeps ActivityPub on the same metrics, dashboards and tests as everything else. +**Decided: write it ourselves.** Scrobbler is BSD-3-Clause licensed. Using Pubby inside the app would make the running program subject to the AGPL, which defeats the point of a permissive licence. Fedify is excellent, but it would split the backend across two languages. The protocol surface we need is small (four activity types in and three out), so writing it ourselves is the least total cost. It also keeps ActivityPub on the same metrics, dashboards and tests as everything else, and it can all live in the one replaceable module described above. + +New dependency: `cryptography` (Apache-2.0 or BSD), for keys and signatures. ## Data model +All of these are federation's own tables, prefixed `federation_` and managed in its own Alembic branch (the names below leave the prefix off, except the first). The only link to the core schema is a foreign key to `users`. + | Table | Holds | |---|---| | `federation_settings` | Per user: `enabled`, visibility, which post types, now-playing mode, manual approval, discoverable and indexable, time zone, display name, bio, avatar | @@ -258,6 +330,14 @@ Everything goes on the existing Prometheus and Grafana setup: Each phase can be released on its own, with its migration, docs, OpenAPI updates, metrics and tests. +0. **Groundwork**, with no user-visible change: + - `scrobbler/events.py`, and the core sending its events + - the generic `scrobbler/worker.py`, with imports moved onto it + - the empty `scrobbler.federation` package with `init_app` + - its Alembic branch + - the boundary tests + + This lands first so every later phase is built inside the boundary from day one. 1. **Discoverable profile.** Settings, keys, WebFinger, the actor, NodeInfo and the Sharing page. A user can turn sharing on and be found from Mastodon, but can't be followed yet. 2. **Followers.** Inbox, signature verification (both schemes), the delivery queue with retries and signing, `Accept`, removing and blocking followers, the Followers page, and the GoToSocial CI test. 3. **Posts.** The outbox, weekly summaries, milestones, and deleting posts when sharing is turned off. Adds the Federation dashboard and alerts. @@ -274,11 +354,14 @@ This is the "profiles plus friends' listening" option, deliberately left out of ## Decisions for you +Settled so far: **build it ourselves** (the project is BSD-3-Clause), inside **one replaceable module**. + +Still open: + 1. **Domain.** Handles on the UI's domain (nginx forwards `/.well-known/webfinger`) or on the API's? Both are supported; this is a deployment choice, but it's permanent once people follow. -2. **Licence.** OK to write it ourselves (recommended), or would you rather adopt Pubby and accept the AGPL? -3. **Default visibility** for summaries and milestones: *Unlisted* (recommended) or *Public*? -4. **Now-playing default** once a user turns it on: the profile field (recommended), or posts? -5. **Does it need an admin?** Phase 2 assumes domain blocks set in configuration. A real moderation UI (reports, per-domain policies) would be a separate piece of work. +2. **Default visibility** for summaries and milestones: *Unlisted* (recommended) or *Public*? +3. **Now-playing default** once a user turns it on: the profile field (recommended), or posts? +4. **Does it need an admin?** Phase 2 assumes domain blocks set in configuration. A real moderation UI (reports, per-domain policies) would be a separate piece of work. ## Sources From 247c94a79c0f844fbf9e38aa584e7d6be9373cef Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 19:52:39 +0100 Subject: [PATCH 03/56] Plan for ActivityPub phase 0 (groundwork) Step-by-step plan: domain events, a generic worker with imports moved onto it, the empty federation module and config, separate Alembic branches, and boundary tests enforcing the module rules. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/design/activitypub-phase0.md | 81 +++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 docs/design/activitypub-phase0.md diff --git a/docs/design/activitypub-phase0.md b/docs/design/activitypub-phase0.md new file mode 100644 index 0000000..c118d43 --- /dev/null +++ b/docs/design/activitypub-phase0.md @@ -0,0 +1,81 @@ +# ActivityPub phase 0: groundwork + +This implements phase 0 of [activitypub.md](activitypub.md): the seams that federation will plug into. There's **no user-visible change**. All existing tests must keep passing, and the app behaves exactly as before with federation off, which is the default. + +## 1. Domain events: `scrobbler/events.py` + +Blinker signals in a `scrobbler` namespace. They're sent **after** the relevant commit, so receivers only ever see stored data. + +| Signal | Sender | Keyword arguments | Sent from | +|---|---|---|---| +| `scrobbles_stored` | the `User` | `scrobbles: list[TrackInput]` (newly stored only), `source: "scrobble" \| "import"` | `services.scrobbles.submit_scrobbles`, and `services.imports.store_chunk` via the job loop | +| `now_playing_changed` | the `User` | `track: TrackInput \| None` (`None` means stopped or cleared) | `update_now_playing`, and clearing when the same track is scrobbled | +| `import_finished` | the `User` | `job: ImportJob` | `services.imports`, when a job completes, fails or is cancelled | + +- Duplicates and ignored scrobbles aren't included, so listeners never see a play twice. +- A receiver that raises is logged and swallowed. A broken listener must never fail a scrobble. + +## 2. Generic worker: `scrobbler/worker.py` + +- **A task registry.** + - `register_task(name, fn)` for work queues. `fn()` returns `True` if it did something, and the worker loops straight away while there's work. + - `register_periodic(name, every, fn)` for scheduled jobs. +- **Imports move onto it.** `services.imports` registers: + - `imports` (claim and process one job) + - `imports.requeue_stalled` (every 60s, and once at start-up) +- **CLI.** A new `flask worker` command. + - `flask imports worker` stays as an alias, so existing deployments keep working. + - `docker-compose.yml` switches to `flask worker`. +- **Metric.** `scrobbler_worker_tasks_total{task,outcome}`, where outcome is `worked` or `error`, plus a panel on the Usage dashboard. +- **Isolation.** A task that raises is logged and counted, and the worker keeps going, so one module's bug can't stop another's work. + +## 3. Empty federation module: `scrobbler/federation/` + +- `__init__.py` holds `init_app(app)`, the only entry point, which `create_app()` calls. With `FEDERATION_ENABLED` off (the default) it returns without registering anything. +- `config.py` holds `FEDERATION_ENABLED`, `FEDERATION_DOMAIN` and `FEDERATION_BASE_URL`, and validates them. Enabling federation without a domain and an HTTPS base URL fails at start-up with a clear message. +- `protocol/__init__.py` states the purity rule; it's otherwise empty. +- `README.md` inside the package states the boundary rules and how to add migrations. + +## 4. Alembic branches + +- Label the existing core history `core` by adding `branch_labels = ("core",)` to the initial revision. +- Add a federation root revision: + - revision ID `federation_0001` + - `branch_labels = ("federation",)` + - `depends_on` the core revision that creates `users` + - no tables yet +- **Everything that runs `db upgrade` now upgrades `heads`**: the API entrypoint, CI, the test fixtures and the README. +- New core migrations use `flask db migrate --head core@head`; federation ones use `--head federation@head`. + +## 5. Boundary tests: `tests/test_federation_boundary.py` + +Static checks (using `ast`) over `src/scrobbler`: + +1. Nothing outside `scrobbler.federation` imports it, except `scrobbler/__init__.py`. +2. `scrobbler.federation.protocol` imports nothing from `flask*`, `sqlalchemy`, `werkzeug` or `scrobbler`, apart from itself. +3. The rest of `scrobbler.federation` imports only these parts of the core: + - `scrobbler.events` + - `scrobbler.extensions` + - `scrobbler.worker` + - `scrobbler.services` + - `scrobbler.api.decorators` + - `scrobbler.schemas` + + So no core models, and no core metrics. + +Runtime checks: + +4. With federation off: no routes from federation blueprints, no signal receivers defined in `scrobbler.federation`, and no worker tasks named `federation.*`. +5. With federation on but misconfigured, `create_app` raises a clear error. Correctly configured, it starts. + +## 6. Tests for the seams + +- **Events**: a scrobble batch sends only the newly stored plays; now-playing sends on start and on clear; a finished import sends `import_finished`; a failing receiver doesn't break scrobbling. +- **Worker**: registered tasks run, the loop keeps running while there's work, periodic tasks keep to their interval, and a failing task is counted but doesn't stop the others. +- **Migrations**: `heads` upgrades both branches, `db check` passes, and the federation branch is independent (it can be downgraded on its own). + +## 7. Docs and CI + +- README: `flask worker`, `db upgrade heads`, and the two-branch migration workflow. +- CI: upgrade `heads` before `db check`. +- Commit after each numbered section once its tests pass. From 59ff1bdfa06c7f435acbc91d963b837bd6466de8 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 19:54:27 +0100 Subject: [PATCH 04/56] Domain events for optional modules (phase 0, step 1) scrobbler/events.py defines blinker signals sent after commit: scrobbles_stored (newly stored plays only, source scrobble/import), now_playing_changed (track or None) and import_finished. A receiver that raises is logged and skipped, so optional modules can't break scrobbling or imports. store_chunk now reports which plays it stored. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/events.py | 32 ++++++++++ src/scrobbler/services/imports.py | 44 +++++++++----- src/scrobbler/services/scrobbles.py | 19 ++++-- tests/test_events.py | 90 +++++++++++++++++++++++++++++ 4 files changed, 165 insertions(+), 20 deletions(-) create mode 100644 src/scrobbler/events.py create mode 100644 tests/test_events.py diff --git a/src/scrobbler/events.py b/src/scrobbler/events.py new file mode 100644 index 0000000..955bf62 --- /dev/null +++ b/src/scrobbler/events.py @@ -0,0 +1,32 @@ +"""Domain events: how the core tells optional modules (such as federation) what happened. + +The core sends these after committing, so receivers only ever see stored data. Modules +subscribe with `signal.connect(receiver)`; the core never imports them. + + scrobbles_stored sender=User, scrobbles=[TrackInput, ...], source="scrobble" | "import" + Newly stored plays only: duplicates and ignored ones are left out. + now_playing_changed sender=User, track=TrackInput | None (None: stopped or cleared) + import_finished sender=User, job=ImportJob (completed, failed or cancelled) +""" + +import logging + +from blinker import Namespace, Signal + +log = logging.getLogger(__name__) + +_signals = Namespace() + +scrobbles_stored = _signals.signal("scrobbles-stored") +now_playing_changed = _signals.signal("now-playing-changed") +import_finished = _signals.signal("import-finished") + + +def send(signal: Signal, sender, **kwargs) -> None: + """Deliver to every receiver. A receiver that raises is logged and skipped: an + optional module's bug must never fail a scrobble or an import.""" + for receiver in signal.receivers_for(sender): + try: + receiver(sender, **kwargs) + except Exception: + log.exception("receiver %r of %s failed", receiver, signal.name) diff --git a/src/scrobbler/services/imports.py b/src/scrobbler/services/imports.py index f6a39b6..e8d8139 100644 --- a/src/scrobbler/services/imports.py +++ b/src/scrobbler/services/imports.py @@ -29,7 +29,7 @@ from flask import current_app from sqlalchemy import update from sqlalchemy.dialects.postgresql import insert -from scrobbler import metrics +from scrobbler import events, metrics from scrobbler.extensions import db from scrobbler.models import ImportJob, Scrobble, User from scrobbler.services.scrobbles import MAX_TEXT, TrackInput @@ -314,6 +314,7 @@ def cancel_job(user: User, job_id: int) -> ImportJob | None: job.payload = None db.session.commit() metrics.imports_total.labels(source=job.source, status="cancelled").inc() + events.send(events.import_finished, user, job=job) return job @@ -328,10 +329,13 @@ def _usable(item: TrackInput | None, now: datetime) -> bool: return datetime.fromtimestamp(item.timestamp, UTC) - now <= timedelta(seconds=limit) -def store_chunk(job: ImportJob, items: list[TrackInput | None]) -> None: - """Insert one chunk and update the job's counters (the caller commits).""" +def store_chunk(job: ImportJob, items: list[TrackInput | None]) -> list[TrackInput]: + """Insert one chunk and update the job's counters (the caller commits). + + Returns the plays that were newly stored (not duplicates or skipped rows). + """ now = _now() - rows, seen = [], set() + rows, seen = [], {} skipped = repeated = 0 for item in items: if not _usable(item, now): @@ -342,7 +346,7 @@ def store_chunk(job: ImportJob, items: list[TrackInput | None]) -> None: if key in seen: # the same play twice in one chunk: ON CONFLICT can't handle that repeated += 1 continue - seen.add(key) + seen[key] = item rows.append( { "user_id": job.user_id, @@ -355,16 +359,18 @@ def store_chunk(job: ImportJob, items: list[TrackInput | None]) -> None: "submitted_at": now, } ) - inserted = 0 + stored: list[TrackInput] = [] if rows: - inserted = len( - db.session.execute( + stored = [ + seen[tuple(row)] + for row in db.session.execute( insert(Scrobble) .values(rows) .on_conflict_do_nothing(constraint="uq_scrobbles_dedupe") - .returning(Scrobble.id) - ).all() - ) + .returning(Scrobble.played_at, Scrobble.artist, Scrobble.track) + ) + ] + inserted = len(stored) duplicates = len(rows) - inserted + repeated job.imported += inserted job.duplicates += duplicates @@ -375,6 +381,15 @@ def store_chunk(job: ImportJob, items: list[TrackInput | None]) -> None: counter.labels(source=job.source, result="imported").inc(inserted) counter.labels(source=job.source, result="duplicate").inc(duplicates) counter.labels(source=job.source, result="skipped").inc(skipped) + return stored + + +def _store_and_commit(job: ImportJob, items: list[TrackInput | None]) -> None: + stored = store_chunk(job, items) + db.session.commit() + if stored: + user = db.session.get(User, job.user_id) + events.send(events.scrobbles_stored, user, scrobbles=stored, source="import") def _cancelled(job: ImportJob) -> bool: @@ -402,8 +417,7 @@ def _process_file(job: ImportJob) -> None: for chunk in _chunks(items): if _cancelled(job): return - store_chunk(job, chunk) - db.session.commit() + _store_and_commit(job, chunk) # --- Last.fm API pull ------------------------------------------------------------------ @@ -484,9 +498,8 @@ def _process_lastfm(job: ImportJob) -> None: total_pages = int(attrs.get("totalPages") or 0) job.total = int(attrs.get("total") or 0) tracks = list(_json_tracks(body)) - store_chunk(job, [_track_from_json(t) for t in tracks]) job.next_page = page + 1 - db.session.commit() + _store_and_commit(job, [_track_from_json(t) for t in tracks]) if page >= total_pages or not tracks: return page += 1 @@ -553,6 +566,7 @@ def _finish(job: ImportJob, status: str, error: str | None = None) -> None: job.payload = None db.session.commit() metrics.imports_total.labels(source=job.source, status=status).inc() + events.send(events.import_finished, db.session.get(User, job.user_id), job=job) def run_worker(poll_seconds: float = 2.0, once: bool = False) -> None: diff --git a/src/scrobbler/services/scrobbles.py b/src/scrobbler/services/scrobbles.py index 5c934fc..2de6b53 100644 --- a/src/scrobbler/services/scrobbles.py +++ b/src/scrobbler/services/scrobbles.py @@ -8,7 +8,7 @@ from flask import current_app from sqlalchemy import func from sqlalchemy.dialects.postgresql import insert -from scrobbler import metrics +from scrobbler import events, metrics from scrobbler.extensions import db from scrobbler.models import ApiApp, NowPlaying, Scrobble, User @@ -147,9 +147,15 @@ def submit_scrobbles(user: User, api_app: ApiApp | None, items: list[TrackInput] if inserted: metrics.scrobble_lag_seconds.observe(max(0.0, (now - played_at).total_seconds())) - _clear_now_playing(user, [r.item for r in results if r.status != "ignored"]) + cleared = _clear_now_playing(user, [r.item for r in results if r.status != "ignored"]) db.session.commit() + stored = [r.item for r in results if r.status == "accepted"] + if stored: + events.send(events.scrobbles_stored, user, scrobbles=stored, source="scrobble") + if cleared: + events.send(events.now_playing_changed, user, track=None) + metrics.scrobble_batch_size.observe(len(items)) for result in results: metrics.scrobbles_total.labels(result=result.status).inc() @@ -158,17 +164,19 @@ def submit_scrobbles(user: User, api_app: ApiApp | None, items: list[TrackInput] return results -def _clear_now_playing(user: User, scrobbled: list[TrackInput]) -> None: +def _clear_now_playing(user: User, scrobbled: list[TrackInput]) -> bool: + """Remove now-playing if one of the scrobbled tracks is it. Returns True if removed.""" now_playing = db.session.get(NowPlaying, user.id) if now_playing is None: - return + return False for item in scrobbled: if (item.artist.lower(), item.track.lower()) == ( now_playing.artist.lower(), now_playing.track.lower(), ): db.session.delete(now_playing) - return + return True + return False # --- Now playing --------------------------------------------------------------- @@ -198,6 +206,7 @@ def update_now_playing(user: User, item: TrackInput) -> int: ) db.session.commit() metrics.now_playing_updates_total.inc() + events.send(events.now_playing_changed, user, track=item) return NOT_IGNORED diff --git a/tests/test_events.py b/tests/test_events.py new file mode 100644 index 0000000..ed99ded --- /dev/null +++ b/tests/test_events.py @@ -0,0 +1,90 @@ +import time +from contextlib import contextmanager + +from scrobbler import events +from scrobbler.services import imports, scrobbles +from scrobbler.services.scrobbles import TrackInput + + +@contextmanager +def capture(signal): + received = [] + + def receiver(sender, **kwargs): + received.append((sender, kwargs)) + + signal.connect(receiver) + try: + yield received + finally: + signal.disconnect(receiver) + + +def track(name, seconds_ago=60, artist="Artist"): + return TrackInput(artist=artist, track=name, timestamp=int(time.time()) - seconds_ago) + + +def test_scrobbles_stored_carries_only_new_plays(app, user): + first = track("One") + scrobbles.submit_scrobbles(user, None, [first]) + with capture(events.scrobbles_stored) as received: + scrobbles.submit_scrobbles( + user, + None, + [first, track("Two"), TrackInput(artist="", track="x", timestamp=int(time.time()))], + ) + [(sender, kwargs)] = received + assert sender.id == user.id + assert kwargs["source"] == "scrobble" + assert [s.track for s in kwargs["scrobbles"]] == ["Two"] + + +def test_nothing_is_sent_when_nothing_new_is_stored(app, user): + old = track("One") + scrobbles.submit_scrobbles(user, None, [old]) + with capture(events.scrobbles_stored) as received: + scrobbles.submit_scrobbles(user, None, [old]) + assert received == [] + + +def test_now_playing_started_and_cleared(app, user): + with capture(events.now_playing_changed) as received: + scrobbles.update_now_playing(user, TrackInput(artist="A", track="Song")) + scrobbles.submit_scrobbles(user, None, [track("Song", artist="A")]) + assert [kwargs["track"].track if kwargs["track"] else None for _, kwargs in received] == [ + "Song", + None, + ] + + +def test_imports_announce_stored_plays_and_completion(app, user): + when = time.strftime("%d %b %Y %H:%M", time.gmtime(time.time() - 86400 * 400)) + csv = f"Artist,,One,{when}\nArtist,,One,{when}\nArtist,,Two,{when}\n" + job = imports.create_file_import(user, "export.csv", csv.encode()) + with capture(events.scrobbles_stored) as stored, capture(events.import_finished) as finished: + imports.run_worker(once=True) + [(_, kwargs)] = stored + assert kwargs["source"] == "import" + assert sorted(s.track for s in kwargs["scrobbles"]) == ["One", "Two"] # the repeat once + [(sender, done)] = finished + assert sender.id == user.id + assert (done["job"].id, done["job"].status) == (job.id, "completed") + + +def test_cancelling_an_import_announces_it(app, user): + job = imports.create_file_import(user, "export.csv", b"A,,T,1600000000\n") + with capture(events.import_finished) as finished: + imports.cancel_job(user, job.id) + assert finished[0][1]["job"].status == "cancelled" + + +def test_a_failing_receiver_does_not_break_scrobbling(app, user): + def broken(sender, **kwargs): + raise RuntimeError("listener bug") + + events.scrobbles_stored.connect(broken) + try: + results = scrobbles.submit_scrobbles(user, None, [track("Still stored")]) + finally: + events.scrobbles_stored.disconnect(broken) + assert [r.status for r in results] == ["accepted"] From 098eab025f805815b60ee55af6bf65d7135dffac Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 19:57:25 +0100 Subject: [PATCH 05/56] Generic background worker (phase 0, step 2) scrobbler/worker.py runs tasks that modules register: queue tasks (called while they report work) and periodic tasks. A failing task is logged, counted, rolled back and doesn't stop the others. Imports are now just a registered task plus a periodic stall check. - `flask worker` replaces `flask imports worker` (kept as an alias); compose uses the new command - scrobbler_worker_tasks_total{task,outcome} and a Worker tasks panel on the Usage dashboard - WORKER_METRICS_PORT (IMPORT_WORKER_METRICS_PORT still honoured) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- README.md | 6 +- deploy/grafana/dashboards/usage.json | 69 +++++++++++++++++++++-- docker-compose.yml | 4 +- src/scrobbler/__init__.py | 5 +- src/scrobbler/cli.py | 50 ++++++++++++----- src/scrobbler/config.py | 5 +- src/scrobbler/metrics/__init__.py | 7 +++ src/scrobbler/services/imports.py | 28 ++++++---- src/scrobbler/worker.py | 83 ++++++++++++++++++++++++++++ tests/test_events.py | 4 +- tests/test_imports.py | 3 +- tests/test_ui_imports.py | 4 +- tests/test_worker.py | 66 ++++++++++++++++++++++ 13 files changed, 292 insertions(+), 42 deletions(-) create mode 100644 src/scrobbler/worker.py create mode 100644 tests/test_worker.py diff --git a/README.md b/README.md index ca193b5..001cfad 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,7 @@ Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana - **API** (`src/scrobbler/`): Flask under gunicorn. It is API-only and serves no pages. - **Web UI** (`frontend/`): plain HTML, CSS and JavaScript with no build step. Host it anywhere static files can be served. - **Docs**: OpenAPI at `/api/openapi.json`, Swagger UI at `/api/docs` and ReDoc at `/api/redoc`. A copy of the spec is committed at `docs/openapi.json`. -- **Import worker**: `flask imports worker` imports Last.fm history in the background, from export files or straight from Last.fm. +- **Worker**: `flask worker` runs background work, such as importing Last.fm history from export files or straight from Last.fm. - **Monitoring**: Prometheus metrics, four provisioned Grafana dashboards, and alert rules. ## Run it @@ -47,7 +47,7 @@ The images are `pkgs.daubney.dev/scrobbler/scrobbler-api` and `pkgs.daubney.dev/ | `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start | | `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) | | `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted | -| `IMPORT_WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port | +| `WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port (`IMPORT_WORKER_METRICS_PORT` still works) | | `API_BASE_URL` | ui image | `http://localhost:5050` | API location, written into `config.js` and the CSP | In `docker compose` the host ports are set with `DB_PORT`, `API_PORT`, `UI_PORT`, `PROMETHEUS_PORT` and `GRAFANA_PORT`. @@ -100,7 +100,7 @@ uv sync uv run flask --app scrobbler db upgrade uv run flask --app scrobbler run --port 5050 # API (port 5000 is taken by AirPlay on macOS) python -m http.server 8080 -d frontend # UI -uv run flask --app scrobbler imports worker # process imports +uv run flask --app scrobbler worker # background work (imports, …) uv run pytest # needs TEST_DATABASE_URL (see .env.example) uv run ruff check && uv run ruff format --check ``` diff --git a/deploy/grafana/dashboards/usage.json b/deploy/grafana/dashboards/usage.json index ffd61d4..d230503 100644 --- a/deploy/grafana/dashboards/usage.json +++ b/deploy/grafana/dashboards/usage.json @@ -572,7 +572,7 @@ }, { "type": "row", - "title": "Imports", + "title": "Background work", "id": 13, "collapsed": false, "gridPos": { @@ -878,6 +878,67 @@ "h": 8 } }, + { + "type": "timeseries", + "title": "Worker tasks", + "description": "Runs of each background task that did work, and failures. A task that keeps failing is logged by the worker.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (task) (increase(scrobbler_worker_tasks_total{outcome=\"worked\"}[$__rate_interval]))", + "legendFormat": "{{task}}", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (task) (increase(scrobbler_worker_tasks_total{outcome=\"error\"}[$__rate_interval]))", + "legendFormat": "{{task}} errors", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 70, + "showPoints": "never", + "spanNulls": true, + "drawStyle": "bars" + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 19, + "gridPos": { + "x": 12, + "y": 38, + "w": 12, + "h": 8 + } + }, { "type": "timeseries", "title": "Import duration (p95)", @@ -921,10 +982,10 @@ "sort": "desc" } }, - "id": 19, + "id": 20, "gridPos": { - "x": 12, - "y": 38, + "x": 0, + "y": 46, "w": 12, "h": 8 } diff --git a/docker-compose.yml b/docker-compose.yml index 31dff55..c9cfe75 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -42,13 +42,13 @@ services: db: condition: service_healthy - # Processes history imports (uploaded exports and pulls from Last.fm). + # Background work: history imports, and tasks registered by optional modules. worker: image: ${SCROBBLER_REGISTRY:-pkgs.daubney.dev/scrobbler}/scrobbler-api:${SCROBBLER_IMAGE_TAG:-local} build: context: . dockerfile: docker/api.Dockerfile - command: ["flask", "--app", "scrobbler", "imports", "worker"] + command: ["flask", "--app", "scrobbler", "worker"] environment: DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler SECRET_KEY: ${SECRET_KEY:-change-me} diff --git a/src/scrobbler/__init__.py b/src/scrobbler/__init__.py index e90c2a8..59b9f86 100644 --- a/src/scrobbler/__init__.py +++ b/src/scrobbler/__init__.py @@ -37,9 +37,12 @@ def create_app(config_object=None): max_age=600, ) - from scrobbler.cli import imports_cli + from scrobbler.cli import imports_cli, worker_command + from scrobbler.services import imports as import_service + app.cli.add_command(worker_command) app.cli.add_command(imports_cli) + import_service.register_worker_tasks() from scrobbler.metrics import db as db_metrics diff --git a/src/scrobbler/cli.py b/src/scrobbler/cli.py index d0a93b9..104e021 100644 --- a/src/scrobbler/cli.py +++ b/src/scrobbler/cli.py @@ -2,22 +2,44 @@ import logging import click from flask import current_app -from flask.cli import AppGroup +from flask.cli import AppGroup, with_appcontext + + +def _run_worker(once: bool, poll: float, serve_metrics: bool) -> None: + from scrobbler import worker + + logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") + if serve_metrics: + from scrobbler.metrics.server import start_metrics_server + + start_metrics_server(current_app.config["WORKER_METRICS_PORT"]) + logging.getLogger(__name__).info("worker tasks: %s", ", ".join(worker.registered())) + worker.run(poll_seconds=poll, once=once) + + +def _worker_options(fn): + fn = click.option( + "--metrics/--no-metrics", "serve_metrics", default=True, help="Serve Prometheus metrics." + )(fn) + fn = click.option( + "--poll", default=2.0, show_default=True, help="Seconds between checks when idle." + )(fn) + return click.option("--once", is_flag=True, help="Do all waiting work, then exit.")(fn) + + +@click.command("worker") +@_worker_options +@with_appcontext +def worker_command(once: bool, poll: float, serve_metrics: bool) -> None: + """Run background work: imports, and tasks registered by optional modules.""" + _run_worker(once, poll, serve_metrics) + imports_cli = AppGroup("imports", help="History imports.") @imports_cli.command("worker") -@click.option("--once", is_flag=True, help="Process waiting jobs, then exit.") -@click.option("--poll", default=2.0, show_default=True, help="Seconds between checks when idle.") -@click.option("--metrics/--no-metrics", default=True, help="Serve Prometheus metrics.") -def worker(once: bool, poll: float, metrics: bool) -> None: - """Process import jobs: uploaded Last.fm exports and pulls from Last.fm.""" - from scrobbler.services.imports import run_worker - - logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s") - if metrics: - from scrobbler.metrics.server import start_metrics_server - - start_metrics_server(current_app.config["IMPORT_WORKER_METRICS_PORT"]) - run_worker(poll_seconds=poll, once=once) +@_worker_options +def imports_worker(once: bool, poll: float, serve_metrics: bool) -> None: + """Alias for `flask worker` (kept for existing deployments).""" + _run_worker(once, poll, serve_metrics) diff --git a/src/scrobbler/config.py b/src/scrobbler/config.py index a6c3f2c..b29ad68 100644 --- a/src/scrobbler/config.py +++ b/src/scrobbler/config.py @@ -56,7 +56,10 @@ class Config: LASTFM_REQUEST_INTERVAL = float(os.environ.get("LASTFM_REQUEST_INTERVAL", "0.25")) 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 - IMPORT_WORKER_METRICS_PORT = int(os.environ.get("IMPORT_WORKER_METRICS_PORT", "9101")) + # IMPORT_WORKER_METRICS_PORT is the pre-0.3 name, still honoured. + WORKER_METRICS_PORT = int( + os.environ.get("WORKER_METRICS_PORT", os.environ.get("IMPORT_WORKER_METRICS_PORT", "9101")) + ) # Last.fm behaviour AUTH_TOKEN_TTL_SECONDS = 60 * 60 diff --git a/src/scrobbler/metrics/__init__.py b/src/scrobbler/metrics/__init__.py index b121678..61c8f1b 100644 --- a/src/scrobbler/metrics/__init__.py +++ b/src/scrobbler/metrics/__init__.py @@ -115,6 +115,13 @@ import_duration_seconds = Histogram( buckets=(1, 5, 15, 30, 60, 120, 300, 600, 1800, 3600, 7200), ) +# Background worker +worker_tasks_total = Counter( + "scrobbler_worker_tasks_total", + "Worker task runs that did work (queue tasks) or ran (periodic tasks), and failures", + ["task", "outcome"], +) + # Database db_query_duration_seconds = Histogram( "scrobbler_db_query_duration_seconds", diff --git a/src/scrobbler/services/imports.py b/src/scrobbler/services/imports.py index e8d8139..58a6978 100644 --- a/src/scrobbler/services/imports.py +++ b/src/scrobbler/services/imports.py @@ -569,15 +569,19 @@ def _finish(job: ImportJob, status: str, error: str | None = None) -> None: events.send(events.import_finished, db.session.get(User, job.user_id), job=job) -def run_worker(poll_seconds: float = 2.0, once: bool = False) -> None: - requeue_stalled() - while True: - job = claim_next_job() - if job is not None: - log.info("import job %s (%s) for user %s started", job.id, job.source, job.user_id) - process_job(job) - log.info("import job %s finished: %s", job.id, job.status) - continue - if once: - return - time.sleep(poll_seconds) +def work_once() -> bool: + """Worker task: process the oldest waiting import, if any.""" + job = claim_next_job() + if job is None: + return False + log.info("import job %s (%s) for user %s started", job.id, job.source, job.user_id) + process_job(job) + log.info("import job %s finished", job.id) + return True + + +def register_worker_tasks() -> None: + from scrobbler import worker + + worker.register_task("imports", work_once) + worker.register_periodic("imports.requeue_stalled", 60, requeue_stalled) diff --git a/src/scrobbler/worker.py b/src/scrobbler/worker.py new file mode 100644 index 0000000..c69decb --- /dev/null +++ b/src/scrobbler/worker.py @@ -0,0 +1,83 @@ +"""The background worker: runs tasks that modules register (`flask worker`). + +Modules register work at app start-up; the worker itself knows nothing about them. + + register_task(name, fn) fn() -> bool: True if it did some work. + Called repeatedly while there's work. + register_periodic(name, seconds, fn) fn() every `seconds` (and once at start). + +A task that raises is logged, counted and rolled back; the other tasks keep running. +""" + +import logging +import time +from collections.abc import Callable +from dataclasses import dataclass + +from scrobbler import metrics +from scrobbler.extensions import db + +log = logging.getLogger(__name__) + + +@dataclass +class _Task: + name: str + fn: Callable[[], object] + every: float | None = None # seconds, for periodic tasks + next_run: float = 0.0 # monotonic time; 0 = run at the first opportunity + + +_tasks: dict[str, _Task] = {} + + +def register_task(name: str, fn: Callable[[], bool]) -> None: + _tasks[name] = _Task(name, fn) + + +def register_periodic(name: str, every_seconds: float, fn: Callable[[], object]) -> None: + _tasks[name] = _Task(name, fn, every=every_seconds) + + +def registered() -> list[str]: + return sorted(_tasks) + + +def _call(task: _Task) -> bool: + try: + worked = bool(task.fn()) + except Exception: + log.exception("worker task %s failed", task.name) + db.session.rollback() + metrics.worker_tasks_total.labels(task=task.name, outcome="error").inc() + return False + if worked or task.every is not None: + metrics.worker_tasks_total.labels(task=task.name, outcome="worked").inc() + return worked + + +def run_once() -> bool: + """One pass: due periodic tasks, then each queue task once. True if any queue + task did work (so there may be more waiting).""" + now = time.monotonic() + worked = False + for task in list(_tasks.values()): + if task.every is not None: + if now >= task.next_run: + task.next_run = now + task.every + _call(task) + elif _call(task): + worked = True + return worked + + +def run(poll_seconds: float = 2.0, once: bool = False) -> None: + """Run until stopped. With once=True, run until there's no more work, then return.""" + for task in _tasks.values(): + task.next_run = 0.0 + while True: + if run_once(): + continue + if once: + return + time.sleep(poll_seconds) diff --git a/tests/test_events.py b/tests/test_events.py index ed99ded..c75be6d 100644 --- a/tests/test_events.py +++ b/tests/test_events.py @@ -1,7 +1,7 @@ import time from contextlib import contextmanager -from scrobbler import events +from scrobbler import events, worker from scrobbler.services import imports, scrobbles from scrobbler.services.scrobbles import TrackInput @@ -62,7 +62,7 @@ def test_imports_announce_stored_plays_and_completion(app, user): csv = f"Artist,,One,{when}\nArtist,,One,{when}\nArtist,,Two,{when}\n" job = imports.create_file_import(user, "export.csv", csv.encode()) with capture(events.scrobbles_stored) as stored, capture(events.import_finished) as finished: - imports.run_worker(once=True) + worker.run(once=True) [(_, kwargs)] = stored assert kwargs["source"] == "import" assert sorted(s.track for s in kwargs["scrobbles"]) == ["One", "Two"] # the repeat once diff --git a/tests/test_imports.py b/tests/test_imports.py index 708f853..b53cc33 100644 --- a/tests/test_imports.py +++ b/tests/test_imports.py @@ -6,6 +6,7 @@ from datetime import UTC, datetime, timedelta import pytest from werkzeug.serving import make_server +from scrobbler import worker from scrobbler.extensions import db from scrobbler.models import ImportJob, Scrobble from scrobbler.services import imports @@ -29,7 +30,7 @@ def stored(user): def run_all(): - imports.run_worker(once=True) + worker.run(once=True) db.session.expire_all() diff --git a/tests/test_ui_imports.py b/tests/test_ui_imports.py index add0dcb..f7d55ea 100644 --- a/tests/test_ui_imports.py +++ b/tests/test_ui_imports.py @@ -3,7 +3,7 @@ from datetime import UTC, datetime, timedelta import pytest -from scrobbler.services import imports +from scrobbler import worker def csv_bytes(n=3) -> bytes: @@ -45,7 +45,7 @@ def test_upload_then_follow_progress(client, auth): job = response.get_json() assert (job["source"], job["status"], job["filename"]) == ("csv", "pending", "export.csv") - imports.run_worker(once=True) + worker.run(once=True) done = client.get(f"/api/v1/imports/{job['id']}", headers=auth).get_json() assert (done["status"], done["imported"], done["total"]) == ("completed", 3, 3) assert client.get("/api/v1/me/summary", headers=auth).get_json()["scrobbles"] == 3 diff --git a/tests/test_worker.py b/tests/test_worker.py new file mode 100644 index 0000000..36ae8a4 --- /dev/null +++ b/tests/test_worker.py @@ -0,0 +1,66 @@ +import pytest + +from scrobbler import worker + + +@pytest.fixture +def tasks(app): + """An empty task registry for the test, restored afterwards.""" + saved = dict(worker._tasks) + worker._tasks.clear() + yield worker + worker._tasks.clear() + worker._tasks.update(saved) + + +def test_imports_are_registered_by_the_app(app): + assert {"imports", "imports.requeue_stalled"} <= set(worker.registered()) + + +def test_queue_tasks_run_until_there_is_no_work(tasks, metric_delta): + work = [3] + + def drain(): + if work[0] == 0: + return False + work[0] -= 1 + return True + + worked = metric_delta("scrobbler_worker_tasks_total", task="drain", outcome="worked") + tasks.register_task("drain", drain) + tasks.run(once=True) + assert work == [0] + assert worked.delta == 3 + + +def test_periodic_tasks_keep_their_interval(tasks): + calls = [] + tasks.register_periodic("tick", 3600, lambda: calls.append(1)) + busy = [2] + tasks.register_task("busy", lambda: busy.__setitem__(0, busy[0] - 1) or busy[0] >= 0) + tasks.run(once=True) # several passes while "busy" has work + assert calls == [1] # ran at start, then not again within the hour + + +def test_a_failing_task_does_not_stop_the_others(tasks, metric_delta): + done = [] + + def broken(): + raise RuntimeError("bug") + + errors = metric_delta("scrobbler_worker_tasks_total", task="broken", outcome="error") + tasks.register_task("broken", broken) + tasks.register_task("fine", lambda: done.append(1) and False) + tasks.run(once=True) + assert done == [1] + assert errors.delta == 1 + + +def test_worker_cli_lists_and_runs_tasks(app, tasks): + ran = [] + tasks.register_task("cli-test", lambda: ran.append(1) and False) + result = app.test_cli_runner().invoke(args=["worker", "--once", "--no-metrics"]) + assert result.exit_code == 0, result.output + assert ran == [1] + alias = app.test_cli_runner().invoke(args=["imports", "worker", "--once", "--no-metrics"]) + assert alias.exit_code == 0, alias.output From c79c42ee0008f16d5ce62d206ecc6204970df23b Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 19:59:47 +0100 Subject: [PATCH 06/56] Federation module skeleton and its own migration branch (phase 0, steps 3-4) - scrobbler.federation with init_app() as its only entry point, called from create_app(); does nothing unless FEDERATION_ENABLED - FederationConfig validates FEDERATION_DOMAIN (bare host) and FEDERATION_BASE_URL (https) when enabled, with clear errors - federation/protocol/ package for pure, framework-free protocol code - Package README with the boundary rules, configuration and migration workflow; .env.example lists the settings (off) - Alembic: existing history labelled `core`; new empty `federation` branch root (depends on the core users table). Everything upgrades `heads` (entrypoint, CI, tests); tests check both branches apply and that federation can be removed without touching core Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- .env.example | 5 ++ .gitea/workflows/ci.yml | 2 +- README.md | 4 +- docker/api-entrypoint.sh | 2 +- src/scrobbler/__init__.py | 4 ++ src/scrobbler/federation/README.md | 46 +++++++++++++++++ src/scrobbler/federation/__init__.py | 26 ++++++++++ src/scrobbler/federation/config.py | 51 +++++++++++++++++++ src/scrobbler/federation/protocol/__init__.py | 7 +++ .../versions/d6113d27cce6_initial_schema.py | 2 +- .../federation_0001_federation_branch_root.py | 25 +++++++++ tests/conftest.py | 2 +- tests/test_migrations.py | 42 +++++++++++++++ 13 files changed, 212 insertions(+), 6 deletions(-) create mode 100644 src/scrobbler/federation/README.md create mode 100644 src/scrobbler/federation/__init__.py create mode 100644 src/scrobbler/federation/config.py create mode 100644 src/scrobbler/federation/protocol/__init__.py create mode 100644 src/scrobbler/migrations/versions/federation_0001_federation_branch_root.py create mode 100644 tests/test_migrations.py diff --git a/.env.example b/.env.example index ffd6774..149253d 100644 --- a/.env.example +++ b/.env.example @@ -22,3 +22,8 @@ UI_PORT=8080 PROMETHEUS_PORT=9090 GRAFANA_PORT=3000 GRAFANA_ADMIN_PASSWORD=admin + +# ActivityPub federation (in development; off by default). See src/scrobbler/federation/README.md. +FEDERATION_ENABLED=0 +FEDERATION_DOMAIN= +FEDERATION_BASE_URL= diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 515c14f..3615b1d 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -52,7 +52,7 @@ jobs: - run: uv sync --locked - name: Migrations are in sync with the models run: | - uv run flask --app scrobbler db upgrade + uv run flask --app scrobbler db upgrade heads uv run flask --app scrobbler db check - run: uv run pytest diff --git a/README.md b/README.md index 001cfad..56d16ec 100644 --- a/README.md +++ b/README.md @@ -97,7 +97,7 @@ Unlike live scrobbles, imports keep plays of any age. They still skip rows with ```sh docker compose up -d db # Postgres with a scrobbler_test database uv sync -uv run flask --app scrobbler db upgrade +uv run flask --app scrobbler db upgrade heads uv run flask --app scrobbler run --port 5050 # API (port 5000 is taken by AirPlay on macOS) python -m http.server 8080 -d frontend # UI uv run flask --app scrobbler worker # background work (imports, …) @@ -105,7 +105,7 @@ uv run pytest # needs TEST_DATABASE_URL (see .env uv run ruff check && uv run ruff format --check ``` -- **Migrations**: after changing `models.py`, run `uv run flask --app scrobbler db migrate -m "…"`. CI fails if the models and migrations disagree. +- **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. - **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. diff --git a/docker/api-entrypoint.sh b/docker/api-entrypoint.sh index 72c75ea..443db7a 100755 --- a/docker/api-entrypoint.sh +++ b/docker/api-entrypoint.sh @@ -3,6 +3,6 @@ set -e if [ "${RUN_MIGRATIONS:-1}" = "1" ]; then # Not under gunicorn, so don't use (or pollute) the multiprocess metrics directory. - env -u PROMETHEUS_MULTIPROC_DIR flask --app scrobbler db upgrade + env -u PROMETHEUS_MULTIPROC_DIR flask --app scrobbler db upgrade heads fi exec "$@" diff --git a/src/scrobbler/__init__.py b/src/scrobbler/__init__.py index 59b9f86..1433f55 100644 --- a/src/scrobbler/__init__.py +++ b/src/scrobbler/__init__.py @@ -30,6 +30,10 @@ def create_app(config_object=None): app.register_blueprint(lastfm_bp) api.init_app(app) + + from scrobbler import federation # the only place the core touches federation + + federation.init_app(app) CORS( app, resources={r"/api/v1/*": {"origins": app.config["CORS_ORIGINS"]}}, diff --git a/src/scrobbler/federation/README.md b/src/scrobbler/federation/README.md new file mode 100644 index 0000000..b2ffd4a --- /dev/null +++ b/src/scrobbler/federation/README.md @@ -0,0 +1,46 @@ +# `scrobbler.federation` + +ActivityPub support, kept apart from the rest of the app so it can be changed, replaced +or switched off without touching anything else. Design: `docs/design/activitypub.md`. + +## Boundary rules (enforced by `tests/test_federation_boundary.py`) + +1. **Nothing outside this package imports it**, except `create_app()` calling + `federation.init_app(app)`. The core reports what happened through the domain events + in `scrobbler.events`; this package subscribes to them. +2. **`protocol/` is pure**: no Flask, SQLAlchemy, Werkzeug or `scrobbler` imports. + Signature schemes, vocabulary and document formats live there. +3. **The rest of this package uses only the core's public surface**: + - `scrobbler.events` + - `scrobbler.extensions` (`db`) + - `scrobbler.worker` + - `scrobbler.services.*` + - `scrobbler.api.decorators` + - `scrobbler.schemas` + + So no core models and no core metrics; federation defines its own. +4. **Off means off.** With `FEDERATION_ENABLED` unset, `init_app` registers no routes, + no event receivers and no worker tasks. + +## Configuration + +| Variable | Meaning | +|---|---| +| `FEDERATION_ENABLED` | `1` to turn federation on (default off) | +| `FEDERATION_DOMAIN` | Handle domain: users are `@name@`. **Permanent once anyone follows.** | +| `FEDERATION_BASE_URL` | Public `https://` URL of the API, where actors live (`/users/`) | + +## Migrations + +Federation's tables (all prefixed `federation_`) live in their own Alembic branch, +labelled `federation`, so they can be changed or dropped without touching core +migrations: + +```sh +uv run flask --app scrobbler db migrate --head federation@head -m "…" # federation tables +uv run flask --app scrobbler db migrate --head core@head -m "…" # everything else +uv run flask --app scrobbler db upgrade heads # apply both branches +``` + +When generating a federation migration, check it only touches `federation_*` tables. +Autogenerate compares all models, so core changes would otherwise leak into it. diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py new file mode 100644 index 0000000..b6e95ce --- /dev/null +++ b/src/scrobbler/federation/__init__.py @@ -0,0 +1,26 @@ +"""ActivityPub federation: optional, self-contained, replaceable. + +The rest of Scrobbler only calls `init_app(app)` (from `create_app`) and sends domain +events (`scrobbler.events`). Everything else about federation lives in this package; +see README.md here and docs/design/activitypub.md. + +With FEDERATION_ENABLED off (the default) `init_app` registers nothing: no routes, no +event receivers, no worker tasks. +""" + +import logging + +from flask import Flask + +from scrobbler.federation.config import FederationConfig + +log = logging.getLogger(__name__) + + +def init_app(app: Flask) -> None: + config = FederationConfig.from_mapping(app.config) + app.extensions["federation"] = config + if not config.enabled: + return + log.info("federation enabled: handles @user@%s, actors at %s", config.domain, config.base_url) + # Phase 1 onwards registers routes, event receivers and worker tasks here. diff --git a/src/scrobbler/federation/config.py b/src/scrobbler/federation/config.py new file mode 100644 index 0000000..a305aff --- /dev/null +++ b/src/scrobbler/federation/config.py @@ -0,0 +1,51 @@ +import os +from collections.abc import Mapping +from dataclasses import dataclass +from urllib.parse import urlsplit + + +class FederationConfigError(ValueError): + pass + + +def _flag(value) -> bool: + return str(value).strip().lower() in {"1", "true", "yes", "on"} + + +@dataclass(frozen=True) +class FederationConfig: + enabled: bool = False + domain: str = "" # the handle's domain: @user@ + base_url: str = "" # where actors live: /users/ + + @classmethod + def from_mapping(cls, config: Mapping) -> "FederationConfig": + """Read FEDERATION_* from the Flask config, falling back to the environment.""" + + def get(key: str, default: str = "") -> str: + value = config.get(key) + return str(value if value is not None else os.environ.get(key, default)) + + result = cls( + enabled=_flag(get("FEDERATION_ENABLED", "0")), + domain=get("FEDERATION_DOMAIN").strip().lower(), + base_url=get("FEDERATION_BASE_URL").strip().rstrip("/"), + ) + result.validate() + return result + + def validate(self) -> None: + if not self.enabled: + return + if not self.domain or "/" in self.domain or ":" in self.domain: + raise FederationConfigError( + "FEDERATION_DOMAIN must be a bare host name (e.g. scrobble.example) when " + "FEDERATION_ENABLED is on. It becomes part of every handle and can't change " + "once people follow." + ) + url = urlsplit(self.base_url) + if url.scheme != "https" or not url.netloc or url.query or url.fragment: + raise FederationConfigError( + "FEDERATION_BASE_URL must be the public https:// URL the API is served at " + "(e.g. https://api.scrobble.example) when FEDERATION_ENABLED is on." + ) diff --git a/src/scrobbler/federation/protocol/__init__.py b/src/scrobbler/federation/protocol/__init__.py new file mode 100644 index 0000000..e76b2cb --- /dev/null +++ b/src/scrobbler/federation/protocol/__init__.py @@ -0,0 +1,7 @@ +"""Pure ActivityPub protocol code: vocabulary builders, addressing, WebFinger and +NodeInfo documents, HTTP signature schemes. + +Rule: nothing in this package imports Flask, SQLAlchemy, Werkzeug or any other part of +Scrobbler; only the standard library and `cryptography`. Spec changes land here and are +tested with spec test vectors alone. (Enforced by tests/test_federation_boundary.py.) +""" diff --git a/src/scrobbler/migrations/versions/d6113d27cce6_initial_schema.py b/src/scrobbler/migrations/versions/d6113d27cce6_initial_schema.py index 2157b84..680cf66 100644 --- a/src/scrobbler/migrations/versions/d6113d27cce6_initial_schema.py +++ b/src/scrobbler/migrations/versions/d6113d27cce6_initial_schema.py @@ -12,7 +12,7 @@ import sqlalchemy as sa # revision identifiers, used by Alembic. revision = 'd6113d27cce6' down_revision = None -branch_labels = None +branch_labels = ('core',) depends_on = None diff --git a/src/scrobbler/migrations/versions/federation_0001_federation_branch_root.py b/src/scrobbler/migrations/versions/federation_0001_federation_branch_root.py new file mode 100644 index 0000000..7cbc1fb --- /dev/null +++ b/src/scrobbler/migrations/versions/federation_0001_federation_branch_root.py @@ -0,0 +1,25 @@ +"""federation branch root + +Root of the federation branch: federation_* tables are added in revisions on this +branch (flask db migrate --head federation@head) so they stay independent of core +migrations. Intentionally empty. + +Revision ID: federation_0001 +Revises: +Create Date: 2026-09-25 19:58:27.552417 + +""" +# revision identifiers, used by Alembic. +revision = 'federation_0001' +down_revision = None +branch_labels = ('federation',) +# Federation tables reference users, created by the core's first revision. +depends_on = 'd6113d27cce6' + + +def upgrade(): + pass + + +def downgrade(): + pass diff --git a/tests/conftest.py b/tests/conftest.py index 0346354..0b7739c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -13,7 +13,7 @@ def app(): app = create_app(TestConfig) with app.app_context(): downgrade(revision="base") # clean slate if a previous run was interrupted - upgrade() + upgrade(revision="heads") # core and federation branches yield app db.session.remove() downgrade(revision="base") diff --git a/tests/test_migrations.py b/tests/test_migrations.py new file mode 100644 index 0000000..c777a62 --- /dev/null +++ b/tests/test_migrations.py @@ -0,0 +1,42 @@ +import pytest +from alembic.script import ScriptDirectory +from flask_migrate import downgrade, upgrade +from sqlalchemy import text + +from scrobbler.extensions import db + + +@pytest.fixture +def scripts(app): + return ScriptDirectory(app.extensions["migrate"].directory) + + +def applied() -> set[str]: + return set(db.session.execute(text("SELECT version_num FROM alembic_version")).scalars()) + + +def head_of(scripts: ScriptDirectory, branch: str) -> str: + return scripts.get_revision(f"{branch}@head").revision + + +def test_there_are_exactly_two_branches(scripts): + labels = {label for rev in scripts.walk_revisions() for label in rev.branch_labels} + assert labels == {"core", "federation"} + assert len(scripts.get_heads()) == 2 + + +def test_both_branches_are_applied(app, scripts): + assert applied() == {head_of(scripts, "core"), head_of(scripts, "federation")} + + +def test_federation_branch_can_be_removed_without_touching_core(app, scripts, user): + core, federation = head_of(scripts, "core"), head_of(scripts, "federation") + try: + db.session.commit() + downgrade(revision="federation@base") + assert applied() == {core} + assert db.session.execute(text("SELECT count(*) FROM users")).scalar_one() == 1 + finally: + db.session.rollback() + upgrade(revision="heads") + assert applied() == {core, federation} From eb5802f420951488f815ebd667fb92ca6bdac731 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 20:00:56 +0100 Subject: [PATCH 07/56] Federation boundary tests (phase 0, step 5) Static checks (ast, so imports inside functions and relative imports count): nothing outside scrobbler.federation imports it except create_app; federation.protocol imports no framework or scrobbler code; the rest of federation uses only the core's public surface (events, extensions, worker, services, api.decorators, schemas). The checker is itself tested against deliberate violations and permitted imports. Runtime checks: with federation off no federation views, event receivers or worker tasks exist; enabling it needs a bare domain and an https base URL. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- tests/test_federation_boundary.py | 196 ++++++++++++++++++++++++++++++ 1 file changed, 196 insertions(+) create mode 100644 tests/test_federation_boundary.py diff --git a/tests/test_federation_boundary.py b/tests/test_federation_boundary.py new file mode 100644 index 0000000..0fe5335 --- /dev/null +++ b/tests/test_federation_boundary.py @@ -0,0 +1,196 @@ +"""Keeps scrobbler.federation a separate, replaceable module. + +Rules (see src/scrobbler/federation/README.md): + 1. Nothing outside scrobbler.federation imports it, except create_app() in + scrobbler/__init__.py. + 2. scrobbler.federation.protocol is pure: no Flask, SQLAlchemy, Werkzeug or scrobbler + imports (other than protocol itself). + 3. The rest of scrobbler.federation uses only the core's public surface. + 4. With federation off, nothing of it is registered at runtime. +""" + +import ast +from pathlib import Path + +import pytest + +from scrobbler import create_app, events, worker +from scrobbler.config import TestConfig +from scrobbler.federation.config import FederationConfigError + +SRC = Path(__file__).resolve().parents[1] / "src" +PACKAGE = SRC / "scrobbler" + +FEDERATION = "scrobbler.federation" +PROTOCOL = "scrobbler.federation.protocol" +FRAMEWORKS = ( + "flask", + "flask_sqlalchemy", + "flask_migrate", + "flask_smorest", + "flask_cors", + "sqlalchemy", + "werkzeug", + "alembic", + "marshmallow", +) +CORE_PUBLIC_SURFACE = ( + "scrobbler.events", + "scrobbler.extensions", + "scrobbler.worker", + "scrobbler.services", + "scrobbler.api.decorators", + "scrobbler.schemas", +) + + +def module_name(path: Path) -> str: + parts = list(path.relative_to(SRC).with_suffix("").parts) + if parts[-1] == "__init__": + parts.pop() + return ".".join(parts) + + +def imported_names(module: str, source: str, is_package: bool) -> set[str]: + """Every module a piece of source imports, anywhere in the file. For + `from a import b`, both `a` and `a.b` are included (b may be a submodule).""" + names: set[str] = set() + for node in ast.walk(ast.parse(source)): + if isinstance(node, ast.Import): + names.update(alias.name for alias in node.names) + elif isinstance(node, ast.ImportFrom): + base = node.module or "" + if node.level: # relative import + package = module if is_package else module.rpartition(".")[0] + for _ in range(node.level - 1): + package = package.rpartition(".")[0] + base = f"{package}.{base}" if base else package + names.add(base) + names.update(f"{base}.{alias.name}" for alias in node.names) + return names + + +def within(name: str, prefix: str) -> bool: + return name == prefix or name.startswith(prefix + ".") + + +def violations(module: str, imports: set[str]) -> list[str]: + problems = [] + if within(module, PROTOCOL): + for name in imports: + if any(within(name, fw) for fw in FRAMEWORKS): + problems.append(f"{module} (protocol) imports framework module {name}") + elif within(name, "scrobbler") and not within(name, PROTOCOL): + problems.append(f"{module} (protocol) imports {name}") + elif within(module, FEDERATION): + for name in imports: + if not within(name, "scrobbler") or name == "scrobbler": + continue + if within(name, FEDERATION) or any(within(name, ok) for ok in CORE_PUBLIC_SURFACE): + continue + problems.append(f"{module} imports core internals: {name}") + elif module != "scrobbler": # create_app() may call federation.init_app + problems += [f"{module} imports {name}" for name in imports if within(name, FEDERATION)] + return problems + + +def all_modules(): + for path in sorted(PACKAGE.rglob("*.py")): + if "migrations" in path.parts: + continue + yield module_name(path), path + + +def test_import_boundaries(): + problems = [] + for module, path in all_modules(): + imports = imported_names(module, path.read_text(), path.name == "__init__.py") + problems += violations(module, imports) + assert not problems, "Federation module boundary broken:\n " + "\n ".join(problems) + + +def test_federation_package_is_checked(): + modules = {module for module, _ in all_modules()} + assert {FEDERATION, PROTOCOL, f"{FEDERATION}.config"} <= modules + + +@pytest.mark.parametrize( + ("module", "source", "expected"), + [ + ("scrobbler.services.stats", "from scrobbler.federation import web", "imports"), + ("scrobbler.api.apps", "def f():\n import scrobbler.federation.keys", "imports"), + (PROTOCOL + ".vocab", "import flask", "framework"), + (PROTOCOL + ".vocab", "from sqlalchemy import select", "framework"), + (PROTOCOL + ".vocab", "from scrobbler.models import User", "imports"), + (PROTOCOL + ".vocab", "from ..config import FederationConfig", "imports"), + (FEDERATION + ".inbox", "from scrobbler.models import User", "core internals"), + (FEDERATION + ".inbox", "from scrobbler import metrics", "core internals"), + ], +) +def test_the_checker_catches_violations(module, source, expected): + """Proves the rules above can fail, so a passing run means something.""" + found = violations(module, imported_names(module, source, is_package=False)) + assert found and expected in found[0] + + +@pytest.mark.parametrize( + ("module", "source"), + [ + ("scrobbler", "from scrobbler import federation"), + ( + FEDERATION + ".inbox", + "from scrobbler.services import stats\nfrom scrobbler import events", + ), + (FEDERATION + ".inbox", "from .protocol import vocab\nfrom flask import Blueprint"), + (PROTOCOL + ".signatures.rfc9421", "from ..vocab import note\nimport hashlib"), + ], +) +def test_the_checker_allows_permitted_imports(module, source): + assert violations(module, imported_names(module, source, is_package=False)) == [] + + +# --- Runtime: off means off ----------------------------------------------------------- + + +def _from_federation(obj) -> bool: + return getattr(obj, "__module__", "").startswith(FEDERATION) + + +def test_nothing_is_registered_when_federation_is_off(app): + assert app.extensions["federation"].enabled is False + views = [view for view in app.view_functions.values() if _from_federation(view)] + assert views == [] + for signal in (events.scrobbles_stored, events.now_playing_changed, events.import_finished): + assert not any(_from_federation(r) for r in signal.receivers_for(None)) + assert not any(name.startswith("federation") for name in worker.registered()) + + +class _Enabled(TestConfig): + FEDERATION_ENABLED = "1" + FEDERATION_DOMAIN = "scrobble.example" + FEDERATION_BASE_URL = "https://api.scrobble.example" + + +@pytest.mark.parametrize( + ("overrides", "message"), + [ + ({"FEDERATION_DOMAIN": ""}, "FEDERATION_DOMAIN"), + ({"FEDERATION_DOMAIN": "https://scrobble.example"}, "FEDERATION_DOMAIN"), + ({"FEDERATION_BASE_URL": "http://api.scrobble.example"}, "FEDERATION_BASE_URL"), + ({"FEDERATION_BASE_URL": ""}, "FEDERATION_BASE_URL"), + ], +) +def test_enabling_federation_requires_valid_settings(overrides, message): + config = type("Misconfigured", (_Enabled,), overrides) + with pytest.raises(FederationConfigError, match=message): + create_app(config) + + +def test_federation_can_be_enabled(): + enabled = create_app(_Enabled) + config = enabled.extensions["federation"] + assert (config.enabled, config.domain, config.base_url) == ( + True, + "scrobble.example", + "https://api.scrobble.example", + ) From cae97380fc7c380045525684b91bea603a2a960f Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 20:02:09 +0100 Subject: [PATCH 08/56] Mark ActivityPub phase 0 as done Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/design/activitypub-phase0.md | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/docs/design/activitypub-phase0.md b/docs/design/activitypub-phase0.md index c118d43..d118476 100644 --- a/docs/design/activitypub-phase0.md +++ b/docs/design/activitypub-phase0.md @@ -1,5 +1,14 @@ # ActivityPub phase 0: groundwork +**Status: done** on `feature/activitypub`: + +| Commit | Steps | +|---|---| +| `59ff1bd` | events | +| `098eab0` | worker | +| `c79c42e` | module and migrations | +| `eb5802f` | boundary tests | + This implements phase 0 of [activitypub.md](activitypub.md): the seams that federation will plug into. There's **no user-visible change**. All existing tests must keep passing, and the app behaves exactly as before with federation off, which is the default. ## 1. Domain events: `scrobbler/events.py` From 00ad8e9e6dc4b0aeb5e5c4b747f013dba622593b Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 20:10:08 +0100 Subject: [PATCH 09/56] ActivityPub decisions: UI domain, followers-only posts; phase 1 plan - Handles and actor URLs live on the web UI's domain; the UI's nginx forwards the ActivityPub paths to the API - Posts default to followers only, settable per user, with the privacy caveat about automatic follow approval spelled out - docs/design/activitypub-phase1.md: the discoverable-profile phase, step by step Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/design/activitypub-phase1.md | 116 +++++++++++++++++++++++++++++ docs/design/activitypub.md | 49 ++++++++---- src/scrobbler/federation/README.md | 4 +- 3 files changed, 152 insertions(+), 17 deletions(-) create mode 100644 docs/design/activitypub-phase1.md diff --git a/docs/design/activitypub-phase1.md b/docs/design/activitypub-phase1.md new file mode 100644 index 0000000..1cb98d4 --- /dev/null +++ b/docs/design/activitypub-phase1.md @@ -0,0 +1,116 @@ +# ActivityPub phase 1: discoverable profile + +This implements phase 1 of [activitypub.md](activitypub.md). Handles and actor URLs are on the **UI's domain**, and posts are **followers only by default** (a per-user setting). + +**Outcome:** once an operator enables federation, a user can switch on sharing, and searching `@alice@` from Mastodon finds their profile. Following needs phase 2 (the inbox and deliveries). Until then the actor advertises `manuallyApprovesFollowers: true`, so a follow shows as a pending request rather than failing silently. With federation off, nothing changes. + +Everything below lives in `scrobbler.federation` unless it says otherwise, and the boundary tests keep holding. + +## 1. Data and keys + +- **New dependency**: `cryptography` (Apache-2.0 or BSD). +- **Migration on the `federation` branch** (`flask db migrate --head federation@head`), adding two tables: + - `federation_settings`, keyed by user: + - `enabled` (false) + - `visibility`: `followers` (the default), `unlisted` or `public` + - `manually_approves_followers` (false) + - `discoverable` and `indexable` (both false) + - `display_name`, `bio` + - `created_at` and `updated_at` + - `federation_keys`: + - a user ID, which is null for the instance actor + - the public key PEM + - the private key PEM encrypted with Fernet + - `created_at` +- `keys.py`: + - An RSA-2048 key pair is created the first time a user enables sharing. The instance actor's pair is created on first use. + - Private keys are encrypted with a key derived by HKDF-SHA256 from **`FEDERATION_KEY_SECRET`**. That setting becomes required when federation is on, and is validated at start-up. + - Keys are never regenerated, because followers pin them. + +## 2. Protocol (pure: `federation/protocol/`) + +- `media.py`: the ActivityPub content types (`application/activity+json`, and `application/ld+json` with the ActivityStreams profile), plus a check for whether a request's `Accept` header wants ActivityPub. +- `vocab.py`, which builds dicts with `@context`: + - `person()`: `id`, `preferredUsername`, `name`, `summary`, `url`, `inbox`, `outbox`, `followers`, `following`, `endpoints.sharedInbox`, `publicKey`, `manuallyApprovesFollowers`, `discoverable`, `indexable` + - `application()` for the instance actor + - `ordered_collection()` +- `webfinger.py`: parses `acct:user@domain` resources (case-insensitive, trimmed, rejecting other domains) and builds the JRD: `subject`, `aliases`, a `self` link and a `profile-page` link. +- `nodeinfo.py`: the discovery document and the NodeInfo 2.1 document. +- `hostmeta.py`: the XRD for `/.well-known/host-meta`, which points at WebFinger. + +These are unit-tested against the documented Mastodon shapes and examples from the WebFinger RFC. + +## 3. ActivityPub endpoints (`federation/web.py`) + +| Path | Response | +|---|---| +| `GET /.well-known/webfinger?resource=acct:u@DOMAIN` | JRD for users who opted in. **404 for unknown or non-opted users, with an identical body.** 400 for a malformed or foreign resource. | +| `GET /.well-known/host-meta` | XRD pointing at WebFinger | +| `GET /.well-known/nodeinfo`, `GET /nodeinfo/2.1` | Software `scrobbler`, the version, `activitypub`, and the count of users who opted in | +| `GET /users/` | Actor JSON when the request asks for ActivityPub; otherwise a **302 to the UI profile page**; 404 if not opted in | +| `GET /users//outbox`, `/followers`, `/following` | Empty collections with `totalItems` (filled in phases 2 and 3) | +| `POST /users//inbox`, `POST /inbox` | 202 and discard, for now (phase 2 handles it) | +| `GET /actor` | The instance actor (an `Application`), used later for signed fetches | + +- All IDs and URLs are built from `FEDERATION_BASE_URL`, never from the request, so a proxy misconfiguration can't produce wrong IDs. +- Responses are cacheable: `Cache-Control: max-age=300` on the actor and WebFinger. +- CORS stays unchanged: remote servers don't send CORS requests. + +## 4. UI-facing API (`federation/api.py`, `/api/v1/federation/*`, documented in OpenAPI) + +- **`GET` and `PUT /settings`** (bearer auth): + - Returns `enabled`, `visibility`, `manually_approves_followers`, `discoverable`, `indexable`, `display_name`, `bio`, the read-only `handle` and `profile_url`, and `followers` (0 until phase 2). + - A 404 means the server doesn't federate, and the UI hides the Sharing page. +- **`GET /profiles/`** is **public** (no auth). It returns the profile shown on the UI profile page, for opted-in users only, and 404 otherwise. +- **Registration**: federation registers its smorest blueprint on the core's `Api` object. This means allowing `scrobbler.api` itself (the `Api` instance) in the boundary test's list of permitted imports, alongside `scrobbler.api.decorators`. + +## 5. Web UI (in `frontend/`, not the Python module) + +- **`sharing.html`**, shown in the nav only when `/federation/settings` exists: + - A **Share my listening on the fediverse** switch, showing the handle and the warning that it's permanent. + - A **Who can see posts** choice: *Followers only* (default), *Unlisted* or *Public*. Its help text says to turn on manual approval for real privacy. + - **Approve followers manually**, **List my profile in directories** (`discoverable`) and **Allow search engines** (`indexable`). + - Display name and bio. +- **`profile.html?u=`**: a public page with no login needed, where browsers opening an actor URL land. + - It shows the display name, handle, bio and how to follow ("search for `@alice@host` in your fediverse app"), with a copy button. + - It uses the existing styles, including the dot-matrix display for the handle. + +## 6. Proxying from the UI domain (`deploy/nginx/default.conf.template`) + +- Forward these paths to `${API_INTERNAL_URL}` (default `http://api:8000`, set in the UI image): + - `/.well-known/webfinger`, `/.well-known/nodeinfo`, `/.well-known/host-meta` + - `/nodeinfo/`, `/users/`, `/inbox`, `/actor` +- Pass `Host`, `X-Forwarded-For` and `X-Forwarded-Proto` through. The proto comes from an outer TLS proxy when there is one. +- The API trusts the UI proxy via `FORWARDED_ALLOW_IPS`. +- No changes to the UI's CSP: these are server-to-server requests. +- Compose adds the federation settings to `api` and `worker`, and `API_INTERNAL_URL` to `ui`. + +## 7. Metrics and dashboard + +- `federation/metrics.py` holds federation's own metrics: + - `scrobbler_federation_lookups_total{kind,result}`, where kind is `webfinger`, `actor`, `nodeinfo` or `profile`, and result is `found` or `not_found` + - `scrobbler_federation_sharing_changes_total{change}`, for `enabled` and `disabled` +- Request rate and latency come free from the existing HTTP metrics (endpoint label `federation.*`). +- A new **Federation** Grafana dashboard: lookups by kind and result, sharing changes, and federation endpoint latency. Phases 2 and 3 add delivery and inbox panels. + +## 8. Tests + +- **Protocol**: WebFinger parsing, including other domains, mixed case and garbage; JRD, actor and NodeInfo shapes; `Accept` negotiation. +- **Keys**: encryption round trip, the wrong secret failing, and keys staying stable across enable and disable. +- **Endpoints**, against a second session app with federation on, sharing the same database: + - opted-in users vs 404 + - identical 404s for unknown and non-opted users + - the browser redirect to the profile page + - IDs built from config + - the 202 inbox stub +- **Settings API**: defaults (followers only, not discoverable), validation, and the public profile endpoint. +- **Still holding**: boundary tests, federation off meaning nothing is registered, and the OpenAPI drift test. +- **Manual pass**: Mastodon needs a public HTTPS domain. A tunnel (for example `cloudflared`) to a local stack, then searching the handle from a Mastodon account, confirms the profile and key resolve. GoToSocial in CI comes with phase 2. + +## 9. Docs + +- The federation README gains the proxy paths and `FEDERATION_KEY_SECRET`. +- The main README gets a "Sharing on the fediverse" section. +- The OpenAPI export is regenerated. + +Commit after each numbered section once its tests pass. diff --git a/docs/design/activitypub.md b/docs/design/activitypub.md index b11430e..1e86adc 100644 --- a/docs/design/activitypub.md +++ b/docs/design/activitypub.md @@ -26,7 +26,7 @@ All of it lives in **one self-contained package, `scrobbler.federation`**, behin - **Weekly summary**: on by default once sharing is on. - **Milestones**: on by default. - **Now playing**: off by default, with two ways to show it. See [Now playing](#now-playing). - - **Who can see posts**: *Unlisted* (recommended: followers and profile visitors only, not public timelines), *Public*, or *Followers only*. + - **Who can see posts**: *Followers only* (**the default**), *Unlisted* (anyone who visits the profile, but kept out of public timelines), or *Public*. The help text explains that followers-only is only as private as who can follow: with automatic approval anyone can follow and then see posts, so for real privacy it suggests turning on **Approve followers manually**. - **Approve followers manually** (off by default). - Profile fields: display name, bio, avatar. The avatar defaults to a generated cover-art-style tile. - **Followers**: a list of remote followers, with *Remove*. There are *Approve* and *Decline* buttons when manual approval is on. @@ -119,14 +119,23 @@ src/scrobbler/ ## Protocol pieces -### Identity and domains ("decide later", made configurable) +### Identity and domains -Two settings: +**Decided: the UI's domain**, which is the name users already know. Two settings configure it: -- `FEDERATION_DOMAIN`: the handle's domain, as in `@alice@`. -- `FEDERATION_BASE_URL`: where the actor documents live, as in `https:///users/alice`. +- `FEDERATION_DOMAIN`: the handle's domain, as in `@alice@`. This is the UI's host. +- `FEDERATION_BASE_URL`: where the actor documents live, as in `https:///users/alice`. It's also the UI's origin, so actor links, profile links and the handle all show one domain, and the API hostname stays an internal detail. -They can be the same (simplest) or different. If they differ, the handle domain only has to answer `/.well-known/webfinger` (and ideally `/.well-known/host-meta`). Mastodon supports this split: it follows the WebFinger `self` link to the actor. So the UI's nginx can forward just `/.well-known/webfinger` to the API and keep the API on its own hostname. +The UI's nginx **forwards the ActivityPub paths to the API**: + +- `/.well-known/webfinger`, `/.well-known/nodeinfo`, `/.well-known/host-meta` +- `/nodeinfo/`, `/users/`, `/inbox`, `/actor` + +All other paths are the static UI, as now. None of these paths collide with the UI's pages. The proxy passes `Host` and `X-Forwarded-*` through, and the API must trust them (`FORWARDED_ALLOW_IPS`), so that signature checks, which cover the request target and host, see the URL the remote server actually signed. + +A browser opening an actor URL (`/users/alice` without an ActivityPub `Accept` header) gets a redirect from the API to the UI's profile page. + +The two settings are kept separate even though they're usually the same host: the design still allows handles on one domain and actors on another, should that ever be needed. Mastodon supports that split through WebFinger's `self` link. **Both values become permanent once anyone follows**: actor IDs are how other servers identify the account. Renaming a user or moving domains later needs the `Move` flow and `alsoKnownAs` (see [Later](#later-following-and-listen-activities)). So we should: @@ -213,13 +222,20 @@ Serve `/.well-known/nodeinfo` and `/nodeinfo/2.1`, giving the software name `scr ## What gets posted -Posts are `Note` objects inside `Create` activities: Mastodon shows `Note` as a normal status, while other types are squashed into a title and link. The HTML uses only tags Mastodon keeps (`p`, `a`, `br`, `strong`, `em`, `ul`, `ol`, `li`), and all track and artist text is escaped. Each post also gets hashtags (`#NowPlaying`, `#Scrobbler`) as `Hashtag` tags. Visibility follows the user's setting: +Posts are `Note` objects inside `Create` activities: Mastodon shows `Note` as a normal status, while other types are squashed into a title and link. The HTML uses only tags Mastodon keeps (`p`, `a`, `br`, `strong`, `em`, `ul`, `ol`, `li`), and all track and artist text is escaped. Each post also gets hashtags (`#NowPlaying`, `#Scrobbler`) as `Hashtag` tags. Visibility follows the user's setting, which defaults to **followers only**: | Setting | `to` | `cc` | |---|---|---| -| Public | `as:Public` | followers | +| Followers only (default) | followers | *(none)* | | Unlisted | followers | `as:Public` | -| Followers only | followers | *(none)* | +| Public | `as:Public` | followers | + +What followers-only means in practice: + +- Posts go only to followers' servers, which show them only to followers. +- They don't appear in the public outbox or on the profile for anyone else. +- They can't be boosted. +- Changing the setting affects new posts only: already-published posts keep the visibility they were sent with. ### Weekly summary @@ -250,7 +266,7 @@ A new post for every track would flood followers' timelines. There are two optio 1. **Profile field (recommended default)**: a "Now playing: *Reckoner* by Radiohead" field on the profile. The field is updated with an `Update(Person)` when the track changes, at most once every 5 minutes, and cleared when playback stops. Nothing appears in timelines; followers see it on the profile. This option is cheap and quiet. 2. **Posts (opt-in)**: a `Note` when a track starts, at most one every 30 minutes, and only for tracks played for at least 30 seconds. - - It uses the user's visibility setting, with a suggested default of *followers only* for these. + - It uses the user's visibility setting (followers only by default). - Optionally, the previous now-playing post is deleted when the next one goes out, so only one exists at a time. ## Build or buy @@ -356,12 +372,15 @@ This is the "profiles plus friends' listening" option, deliberately left out of Settled so far: **build it ourselves** (the project is BSD-3-Clause), inside **one replaceable module**. -Still open: +Also settled: -1. **Domain.** Handles on the UI's domain (nginx forwards `/.well-known/webfinger`) or on the API's? Both are supported; this is a deployment choice, but it's permanent once people follow. -2. **Default visibility** for summaries and milestones: *Unlisted* (recommended) or *Public*? -3. **Now-playing default** once a user turns it on: the profile field (recommended), or posts? -4. **Does it need an admin?** Phase 2 assumes domain blocks set in configuration. A real moderation UI (reports, per-domain policies) would be a separate piece of work. +- **Domain: the UI's.** Handles and actor URLs are both on the UI host, and the UI's nginx forwards the ActivityPub paths to the API. +- **Visibility: followers only by default**, and each user can change it on their Sharing settings. + +Still open (neither is needed before phase 3): + +1. **Now-playing default** once a user turns it on: the profile field (recommended), or posts? +2. **Does it need an admin?** Phase 2 assumes domain blocks set in configuration. A real moderation UI (reports, per-domain policies) would be a separate piece of work. ## Sources diff --git a/src/scrobbler/federation/README.md b/src/scrobbler/federation/README.md index b2ffd4a..046c0eb 100644 --- a/src/scrobbler/federation/README.md +++ b/src/scrobbler/federation/README.md @@ -27,8 +27,8 @@ or switched off without touching anything else. Design: `docs/design/activitypub | Variable | Meaning | |---|---| | `FEDERATION_ENABLED` | `1` to turn federation on (default off) | -| `FEDERATION_DOMAIN` | Handle domain: users are `@name@`. **Permanent once anyone follows.** | -| `FEDERATION_BASE_URL` | Public `https://` URL of the API, where actors live (`/users/`) | +| `FEDERATION_DOMAIN` | Handle domain, normally the web UI's host: users are `@name@`. **Permanent once anyone follows.** | +| `FEDERATION_BASE_URL` | Public `https://` URL actors live under (`/users/`). Normally the web UI's origin, with the UI's nginx forwarding the ActivityPub paths to the API. | ## Migrations From 98c65547f3dac68f756573994f2e1a15de6f398a Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 20:19:14 +0100 Subject: [PATCH 10/56] Federation data and actor keys (phase 1, step 1) - federation_settings (per user; off, followers-only, not discoverable by default) and federation_keys (RSA-2048; NULL user = instance actor), on the federation migration branch - Private keys encrypted at rest with Fernet, keyed by HKDF-SHA256 from FEDERATION_KEY_SECRET (now required, 32+ chars, never printed) - Keys are created when a user first enables sharing and never regenerated; sharing.shared_user() treats unknown and non-sharing users identically - One flask-smorest Api per app (get_api(app)), so apps with and without federation never share an OpenAPI spec - Test fixtures for a second, federation-enabled app on the same DB Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- pyproject.toml | 1 + src/scrobbler/api/__init__.py | 9 +- src/scrobbler/federation/__init__.py | 4 + src/scrobbler/federation/config.py | 16 ++- src/scrobbler/federation/keys.py | 66 +++++++++ src/scrobbler/federation/models.py | 48 +++++++ src/scrobbler/federation/sharing.py | 69 +++++++++ ...508576a6c7_federation_settings_and_keys.py | 52 +++++++ tests/conftest.py | 40 ++++++ tests/test_federation_boundary.py | 7 +- tests/test_federation_keys_sharing.py | 72 ++++++++++ uv.lock | 134 ++++++++++++++++++ 12 files changed, 513 insertions(+), 5 deletions(-) create mode 100644 src/scrobbler/federation/keys.py create mode 100644 src/scrobbler/federation/models.py create mode 100644 src/scrobbler/federation/sharing.py create mode 100644 src/scrobbler/migrations/versions/34508576a6c7_federation_settings_and_keys.py create mode 100644 tests/test_federation_keys_sharing.py diff --git a/pyproject.toml b/pyproject.toml index 480ebde..c03ee97 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,6 +7,7 @@ license = "BSD-3-Clause" license-files = ["LICENSE"] requires-python = ">=3.13" dependencies = [ + "cryptography>=50.0.1", "flask>=3.1.3", "flask-cors>=6.0.5", "flask-migrate>=4.1.0", diff --git a/src/scrobbler/api/__init__.py b/src/scrobbler/api/__init__.py index 83716be..ca7615e 100644 --- a/src/scrobbler/api/__init__.py +++ b/src/scrobbler/api/__init__.py @@ -29,11 +29,16 @@ class ScrobblerApi(Api): return response -api = ScrobblerApi() +def get_api(app: Flask) -> ScrobblerApi: + """This app's Api (for registering blueprints and documenting paths).""" + return app.extensions["scrobbler_api"] def init_app(app: Flask) -> None: - api.init_app(app) + # One Api per app: its OpenAPI spec is per app too, so apps with different + # optional modules enabled (e.g. in tests) never share a spec. + api = ScrobblerApi(app) + app.extensions["scrobbler_api"] = api api.spec.components.security_scheme( "bearerAuth", { diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py index b6e95ce..ff3303a 100644 --- a/src/scrobbler/federation/__init__.py +++ b/src/scrobbler/federation/__init__.py @@ -18,6 +18,10 @@ log = logging.getLogger(__name__) def init_app(app: Flask) -> None: + # Tables are always part of the schema (migrations run regardless), so the models + # are always registered; "off" means no routes, receivers or tasks. + from scrobbler.federation import models # noqa: F401 + config = FederationConfig.from_mapping(app.config) app.extensions["federation"] = config if not config.enabled: diff --git a/src/scrobbler/federation/config.py b/src/scrobbler/federation/config.py index a305aff..00fd03e 100644 --- a/src/scrobbler/federation/config.py +++ b/src/scrobbler/federation/config.py @@ -17,6 +17,7 @@ class FederationConfig: enabled: bool = False domain: str = "" # the handle's domain: @user@ base_url: str = "" # where actors live: /users/ + key_secret: str = "" # encrypts actors' private keys at rest @classmethod def from_mapping(cls, config: Mapping) -> "FederationConfig": @@ -30,6 +31,7 @@ class FederationConfig: enabled=_flag(get("FEDERATION_ENABLED", "0")), domain=get("FEDERATION_DOMAIN").strip().lower(), base_url=get("FEDERATION_BASE_URL").strip().rstrip("/"), + key_secret=get("FEDERATION_KEY_SECRET"), ) result.validate() return result @@ -47,5 +49,17 @@ class FederationConfig: if url.scheme != "https" or not url.netloc or url.query or url.fragment: raise FederationConfigError( "FEDERATION_BASE_URL must be the public https:// URL the API is served at " - "(e.g. https://api.scrobble.example) when FEDERATION_ENABLED is on." + "(e.g. https://scrobble.example) when FEDERATION_ENABLED is on." ) + if len(self.key_secret) < 32: + raise FederationConfigError( + "FEDERATION_KEY_SECRET must be at least 32 characters when FEDERATION_ENABLED " + "is on. It encrypts actors' private keys; keep it safe and never change it " + "(e.g. python -c 'import secrets; print(secrets.token_urlsafe(48))')." + ) + + def __repr__(self) -> str: # never print the secret + return ( + f"FederationConfig(enabled={self.enabled}, domain={self.domain!r}, " + f"base_url={self.base_url!r}, key_secret=***)" + ) diff --git a/src/scrobbler/federation/keys.py b/src/scrobbler/federation/keys.py new file mode 100644 index 0000000..919a35b --- /dev/null +++ b/src/scrobbler/federation/keys.py @@ -0,0 +1,66 @@ +"""Actor key pairs: RSA-2048 (what Mastodon's draft signatures need), private keys +encrypted at rest with a key derived from FEDERATION_KEY_SECRET. + +Keys are created once and never regenerated: remote servers pin them. +""" + +import base64 + +from cryptography.fernet import Fernet +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import rsa +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey +from cryptography.hazmat.primitives.kdf.hkdf import HKDF +from flask import current_app + +from scrobbler.extensions import db +from scrobbler.federation.models import FederationKey + +_HKDF_INFO = b"scrobbler federation actor keys v1" + + +def _fernet(secret: str) -> Fernet: + key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None, info=_HKDF_INFO).derive( + secret.encode() + ) + return Fernet(base64.urlsafe_b64encode(key)) + + +def _secret() -> str: + return current_app.extensions["federation"].key_secret + + +def _new_key(user_id: int | None) -> FederationKey: + private = rsa.generate_private_key(public_exponent=65537, key_size=2048) + private_pem = private.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + public_pem = private.public_key().public_bytes( + serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo + ) + return FederationKey( + user_id=user_id, + public_key_pem=public_pem.decode(), + private_key_encrypted=_fernet(_secret()).encrypt(private_pem), + ) + + +def key_for(user_id: int | None) -> FederationKey: + """The actor's key pair, created on first use. user_id=None is the instance actor.""" + query = db.select(FederationKey) + query = query.filter( + FederationKey.user_id.is_(None) if user_id is None else FederationKey.user_id == user_id + ) + key = db.session.scalar(query) + if key is None: + key = _new_key(user_id) + db.session.add(key) + db.session.commit() + return key + + +def private_key(key: FederationKey) -> RSAPrivateKey: + pem = _fernet(_secret()).decrypt(key.private_key_encrypted) + return serialization.load_pem_private_key(pem, password=None) diff --git a/src/scrobbler/federation/models.py b/src/scrobbler/federation/models.py new file mode 100644 index 0000000..7b9f4fa --- /dev/null +++ b/src/scrobbler/federation/models.py @@ -0,0 +1,48 @@ +"""Federation's own tables. All prefixed federation_; the only link to the core schema +is a foreign key to users. Migrations live on the `federation` Alembic branch.""" + +from datetime import UTC, datetime + +from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, LargeBinary, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +from scrobbler.extensions import db + +VISIBILITIES = ("followers", "unlisted", "public") + + +def utcnow() -> datetime: + return datetime.now(UTC) + + +class FederationSettings(db.Model): + __tablename__ = "federation_settings" + + user_id: Mapped[int] = mapped_column( + ForeignKey("users.id", ondelete="CASCADE"), primary_key=True + ) + enabled: Mapped[bool] = mapped_column(Boolean, default=False) + visibility: Mapped[str] = mapped_column(String(16), default="followers") + manually_approves_followers: Mapped[bool] = mapped_column(Boolean, default=False) + discoverable: Mapped[bool] = mapped_column(Boolean, default=False) + indexable: Mapped[bool] = mapped_column(Boolean, default=False) + display_name: Mapped[str | None] = mapped_column(String(100)) + bio: Mapped[str | None] = mapped_column(Text) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + updated_at: Mapped[datetime] = mapped_column( + DateTime(timezone=True), default=utcnow, onupdate=utcnow + ) + + +class FederationKey(db.Model): + """An actor's RSA key pair. user_id is NULL for the instance actor.""" + + __tablename__ = "federation_keys" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[int | None] = mapped_column( + ForeignKey("users.id", ondelete="CASCADE"), unique=True + ) + public_key_pem: Mapped[str] = mapped_column(Text) + private_key_encrypted: Mapped[bytes] = mapped_column(LargeBinary) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) diff --git a/src/scrobbler/federation/sharing.py b/src/scrobbler/federation/sharing.py new file mode 100644 index 0000000..4ea58ae --- /dev/null +++ b/src/scrobbler/federation/sharing.py @@ -0,0 +1,69 @@ +"""Per-user sharing settings: whether a user federates, and how.""" + +from scrobbler.extensions import db +from scrobbler.federation import keys +from scrobbler.federation.models import VISIBILITIES, FederationSettings +from scrobbler.services import accounts + +EDITABLE = ( + "enabled", + "visibility", + "manually_approves_followers", + "discoverable", + "indexable", + "display_name", + "bio", +) + + +def settings_for(user_id: int) -> FederationSettings: + """The user's settings; unsaved defaults if they've never changed them.""" + settings = db.session.get(FederationSettings, user_id) + if settings is None: + settings = FederationSettings( + user_id=user_id, + enabled=False, + visibility="followers", + manually_approves_followers=False, + discoverable=False, + indexable=False, + ) + return settings + + +def update(user_id: int, changes: dict) -> tuple[FederationSettings, bool | None]: + """Apply changes. Returns the settings and True/False if sharing was switched + on/off by this update (None if unchanged).""" + unknown = set(changes) - set(EDITABLE) + if unknown: + raise ValueError(f"not editable: {sorted(unknown)}") + if changes.get("visibility", "followers") not in VISIBILITIES: + raise ValueError("visibility must be one of " + ", ".join(VISIBILITIES)) + settings = settings_for(user_id) + was_enabled = bool(settings.enabled) + for field, value in changes.items(): + setattr(settings, field, value) + db.session.add(settings) + db.session.commit() + if settings.enabled and not was_enabled: + keys.key_for(user_id) # create the key pair before anyone can fetch the actor + toggled = None if settings.enabled == was_enabled else bool(settings.enabled) + return settings, toggled + + +def shared_user(username: str): + """(user, settings) for a user who has switched sharing on, else None. Callers must + treat 'unknown user' and 'not sharing' identically, so accounts can't be probed.""" + user = accounts.find_user(username) + if user is None: + return None + settings = db.session.get(FederationSettings, user.id) + if settings is None or not settings.enabled: + return None + return user, settings + + +def sharing_count() -> int: + return db.session.scalar( + db.select(db.func.count()).select_from(FederationSettings).filter_by(enabled=True) + ) diff --git a/src/scrobbler/migrations/versions/34508576a6c7_federation_settings_and_keys.py b/src/scrobbler/migrations/versions/34508576a6c7_federation_settings_and_keys.py new file mode 100644 index 0000000..0d1f825 --- /dev/null +++ b/src/scrobbler/migrations/versions/34508576a6c7_federation_settings_and_keys.py @@ -0,0 +1,52 @@ +"""federation settings and keys + +Revision ID: 34508576a6c7 +Revises: federation_0001 +Create Date: 2026-09-25 20:18:10.573299 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '34508576a6c7' +down_revision = 'federation_0001' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('federation_keys', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=True), + sa.Column('public_key_pem', sa.Text(), nullable=False), + sa.Column('private_key_encrypted', sa.LargeBinary(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('user_id') + ) + op.create_table('federation_settings', + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('enabled', sa.Boolean(), nullable=False), + sa.Column('visibility', sa.String(length=16), nullable=False), + sa.Column('manually_approves_followers', sa.Boolean(), nullable=False), + sa.Column('discoverable', sa.Boolean(), nullable=False), + sa.Column('indexable', sa.Boolean(), nullable=False), + sa.Column('display_name', sa.String(length=100), nullable=True), + sa.Column('bio', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('user_id') + ) + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.drop_table('federation_settings') + op.drop_table('federation_keys') + # ### end Alembic commands ### diff --git a/tests/conftest.py b/tests/conftest.py index 0b7739c..c5d4949 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -142,3 +142,43 @@ def ui_token(user): def auth(ui_token): """Authorization headers for the default user.""" return {"Authorization": f"Bearer {ui_token}"} + + +# --- Federation --------------------------------------------------------------------- + +from scrobbler.config import TestConfig as _TestConfig # noqa: E402 + + +class FederatedTestConfig(_TestConfig): + FEDERATION_ENABLED = "1" + FEDERATION_DOMAIN = "scrobble.test" + FEDERATION_BASE_URL = "https://scrobble.test" + FEDERATION_KEY_SECRET = "test-only-federation-key-secret-0123456789" + + +@pytest.fixture(scope="session") +def fed_app(app): + """A second app, with federation on, sharing the test database.""" + return create_app(FederatedTestConfig) + + +@pytest.fixture +def fed_client(fed_app): + return fed_app.test_client() + + +@pytest.fixture +def fed_ctx(fed_app): + """Run the test inside the federation app's context (for services using current_app).""" + with fed_app.app_context(): + yield + db.session.remove() + + +@pytest.fixture +def sharing_user(fed_ctx, user): + """The default user, with sharing switched on.""" + from scrobbler.federation import sharing + + sharing.update(user.id, {"enabled": True, "display_name": "Alice", "bio": "Listening."}) + return user diff --git a/tests/test_federation_boundary.py b/tests/test_federation_boundary.py index 0fe5335..1cc2a9c 100644 --- a/tests/test_federation_boundary.py +++ b/tests/test_federation_boundary.py @@ -168,7 +168,8 @@ def test_nothing_is_registered_when_federation_is_off(app): class _Enabled(TestConfig): FEDERATION_ENABLED = "1" FEDERATION_DOMAIN = "scrobble.example" - FEDERATION_BASE_URL = "https://api.scrobble.example" + FEDERATION_BASE_URL = "https://scrobble.example" + FEDERATION_KEY_SECRET = "x" * 32 @pytest.mark.parametrize( @@ -178,6 +179,7 @@ class _Enabled(TestConfig): ({"FEDERATION_DOMAIN": "https://scrobble.example"}, "FEDERATION_DOMAIN"), ({"FEDERATION_BASE_URL": "http://api.scrobble.example"}, "FEDERATION_BASE_URL"), ({"FEDERATION_BASE_URL": ""}, "FEDERATION_BASE_URL"), + ({"FEDERATION_KEY_SECRET": "too-short"}, "FEDERATION_KEY_SECRET"), ], ) def test_enabling_federation_requires_valid_settings(overrides, message): @@ -192,5 +194,6 @@ def test_federation_can_be_enabled(): assert (config.enabled, config.domain, config.base_url) == ( True, "scrobble.example", - "https://api.scrobble.example", + "https://scrobble.example", ) + assert "x" * 32 not in repr(config) diff --git a/tests/test_federation_keys_sharing.py b/tests/test_federation_keys_sharing.py new file mode 100644 index 0000000..2950a2b --- /dev/null +++ b/tests/test_federation_keys_sharing.py @@ -0,0 +1,72 @@ +import pytest +from cryptography.fernet import InvalidToken +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import padding + +from scrobbler.extensions import db +from scrobbler.federation import keys, sharing +from scrobbler.federation.models import FederationKey + + +def test_defaults_are_private(fed_ctx, user): + settings = sharing.settings_for(user.id) + assert (settings.enabled, settings.visibility) == (False, "followers") + assert not (settings.discoverable or settings.indexable or settings.manually_approves_followers) + assert sharing.shared_user("alice") is None + + +def test_enabling_creates_a_key_pair_that_signs(fed_ctx, user): + _, toggled = sharing.update(user.id, {"enabled": True}) + assert toggled is True + key = db.session.scalar(db.select(FederationKey).filter_by(user_id=user.id)) + assert key.public_key_pem.startswith("-----BEGIN PUBLIC KEY-----") + assert b"PRIVATE KEY" not in key.private_key_encrypted # encrypted at rest + + message = b"hello fediverse" + signature = keys.private_key(key).sign(message, padding.PKCS1v15(), hashes.SHA256()) + public = serialization.load_pem_public_key(key.public_key_pem.encode()) + public.verify(signature, message, padding.PKCS1v15(), hashes.SHA256()) # no exception + + +def test_keys_survive_disable_and_enable(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) + first = keys.key_for(user.id).public_key_pem + assert sharing.update(user.id, {"enabled": False})[1] is False + assert sharing.update(user.id, {"enabled": True})[1] is True + assert keys.key_for(user.id).public_key_pem == first + + +def test_the_wrong_secret_cannot_decrypt(fed_ctx, fed_app, user): + sharing.update(user.id, {"enabled": True}) + key = keys.key_for(user.id) + real = fed_app.extensions["federation"] + fed_app.extensions["federation"] = type(real)( + enabled=True, domain=real.domain, base_url=real.base_url, key_secret="y" * 40 + ) + try: + with pytest.raises(InvalidToken): + keys.private_key(key) + finally: + fed_app.extensions["federation"] = real + + +def test_instance_actor_key(fed_ctx): + assert keys.key_for(None).user_id is None + assert keys.key_for(None).id == keys.key_for(None).id # created once + + +def test_shared_user_is_case_insensitive_and_requires_sharing(fed_ctx, user, make_user): + sharing.update(user.id, {"enabled": True}) + make_user(username="bob") # exists, not sharing + assert sharing.shared_user("ALICE")[0].id == user.id + assert sharing.shared_user("bob") is None + assert sharing.shared_user("nobody") is None + assert sharing.sharing_count() == 1 + + +@pytest.mark.parametrize( + "changes", [{"visibility": "everyone"}, {"user_id": 99}, {"enabled": True, "handle": "x"}] +) +def test_invalid_changes_are_rejected(fed_ctx, user, changes): + with pytest.raises(ValueError): + sharing.update(user.id, changes) diff --git a/uv.lock b/uv.lock index adf7c73..411d956 100644 --- a/uv.lock +++ b/uv.lock @@ -73,6 +73,79 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" }, ] +[[package]] +name = "cffi" +version = "2.1.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "pycparser", marker = "implementation_name != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/9e/ef/008a1939e372c06329a3fce4279c02f328488f3526744906eeec3da7ad5f/cffi-2.1.1.tar.gz", hash = "sha256:dd31f52ea1086513bb9df30f8fcee9b8918323ae067a3d5b78bc826a000712be", size = 530807, upload-time = "2026-08-03T21:21:18.939Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/9d/f4/035513d4117049066b4779dc3b7c0c0fdad175fa13731c9f4003f1cd1478/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphoneos.whl", hash = "sha256:b5bdfd1c873d4e093aabc0ca84c4ca6dbc4f752afb5c86f146d9742580c9da2e", size = 194248, upload-time = "2026-08-03T21:19:59.399Z" }, + { url = "https://files.pythonhosted.org/packages/76/af/2aeb4dbb5fc41a04161ae9ff1518de7cec08e164f44a8ce6a4cf7fd2cd1d/cffi-2.1.1-cp313-cp313-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:31348097ff5bbe827ccc41795d4dd099d9f0625e7def00ee653c137a490c2a6c", size = 196908, upload-time = "2026-08-03T21:20:00.746Z" }, + { url = "https://files.pythonhosted.org/packages/a7/46/2e5fdde8555706dd98139a910ca11be02809f3f605ce956f655d0214e100/cffi-2.1.1-cp313-cp313-macosx_10_15_x86_64.whl", hash = "sha256:9d2055050ea716bd38b7f7f1579c275386646b4894c155a3e2f3cd62ed41b7c6", size = 184805, upload-time = "2026-08-03T21:20:02.02Z" }, + { url = "https://files.pythonhosted.org/packages/55/41/4c7042f317b9217502988f0873af87e16ad606dc20f84e546e3e6ce9764c/cffi-2.1.1-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:19ee6127ee34de7d83ce3d371ebc5ed91addbdcc39f9ab15ce4eb35a4e534971", size = 184764, upload-time = "2026-08-03T21:20:03.141Z" }, + { url = "https://files.pythonhosted.org/packages/43/1f/1c3d90d91811c8f86ced9ed637956c54bfe5b79ca98fe976d7f8c8979f6b/cffi-2.1.1-cp313-cp313-manylinux1_i686.manylinux2014_i686.manylinux_2_17_i686.manylinux_2_5_i686.whl", hash = "sha256:6a8dddef476fab96d066d578fc88526767b836ab5ab21754e1d5bf3879c31c7c", size = 214722, upload-time = "2026-08-03T21:20:04.377Z" }, + { url = "https://files.pythonhosted.org/packages/37/6f/3b5ce4c3b2192d250f04908f2bfd91ef34552ec8f7716a5d4abdb8d67bb2/cffi-2.1.1-cp313-cp313-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:f16c709686a78c727bbbf059f92b0bf41c6fc60deec706d2dc19f529175a6125", size = 222369, upload-time = "2026-08-03T21:20:05.544Z" }, + { url = "https://files.pythonhosted.org/packages/02/10/4b3c75dde3d9663c9e02ba05c2668b954f671d4bbe346413ca8c696b295a/cffi-2.1.1-cp313-cp313-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:fcd22650c908d7b7da162bbfaab594a1227a15d1643a98c68b122ac642fa2264", size = 210175, upload-time = "2026-08-03T21:20:06.75Z" }, + { url = "https://files.pythonhosted.org/packages/df/62/14f74b9543e605d17701dc797b815958b8bb70b7624ce1b832ddad48ed6c/cffi-2.1.1-cp313-cp313-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:aa9511c62d14da7aacc9b4bf51f3f697a621e83b2d6919008243c3aad168eea3", size = 208670, upload-time = "2026-08-03T21:20:08.04Z" }, + { url = "https://files.pythonhosted.org/packages/95/95/86342356ff5953b3fb06f7ef7c5bee212d45e770abc7218d451b9148313c/cffi-2.1.1-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:a931079504ecc49efed7744c476a5c343a92fabf66dec2db95edb1b2fdc770e2", size = 221824, upload-time = "2026-08-03T21:20:09.274Z" }, + { url = "https://files.pythonhosted.org/packages/eb/ff/7b3429ff53aafe931ed8a5fc69f481bbef7ba6de87ddcbb63d08f483f613/cffi-2.1.1-cp313-cp313-musllinux_1_2_aarch64.whl", hash = "sha256:a2d7755bef5a12ed488f4ef1f1b69ee9191d7396083b755a5d2295f6edb4768b", size = 225148, upload-time = "2026-08-03T21:20:10.7Z" }, + { url = "https://files.pythonhosted.org/packages/34/34/a95870b9221e09cf4f2ce3178b1a210abdfe63a1bd357da940418d7b8d15/cffi-2.1.1-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:e0bcb7e0f677f543555d2adff3bf19c05f66cdb4796e5ff602442ab2fe3c4ef7", size = 223564, upload-time = "2026-08-03T21:20:12.165Z" }, + { url = "https://files.pythonhosted.org/packages/70/ea/839b50531021a647fb5e929f72cf97bc1ff702b5472166164b5b6e76b851/cffi-2.1.1-cp313-cp313-win32.whl", hash = "sha256:334644fbac4eff73d985a17a91226df55d0f394160c4cfb880e084c8f7161cac", size = 175263, upload-time = "2026-08-03T21:20:13.559Z" }, + { url = "https://files.pythonhosted.org/packages/60/a6/8b149b2c3f2e11aaa1618ef64500b45f50f22c57a977a4dff1aff1f91042/cffi-2.1.1-cp313-cp313-win_amd64.whl", hash = "sha256:1aa5645c30469b09530c4ebca77ebf8f17618293c58f8549cb1a543a50236e7d", size = 185688, upload-time = "2026-08-03T21:20:14.69Z" }, + { url = "https://files.pythonhosted.org/packages/01/9a/11f687cb39d6a3504060d5242f04f48c735afb4d3d533958a20594890cb2/cffi-2.1.1-cp313-cp313-win_arm64.whl", hash = "sha256:63bbfd5ded17c4840ac07cd8f1c21ba9d9708141f840b324f422f41b207e3973", size = 180078, upload-time = "2026-08-03T21:20:15.917Z" }, + { url = "https://files.pythonhosted.org/packages/d3/7b/d6bbf82b8b96e7391438898c42f5bd96dd02030fd5b64937d248220003e2/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphoneos.whl", hash = "sha256:7dbb61fe3a7699468030f71bbe5f8a0e326a151daa91beb11a6fc1f980c55e1c", size = 194064, upload-time = "2026-08-03T21:20:17.148Z" }, + { url = "https://files.pythonhosted.org/packages/94/e6/bcc91b283be94735e268487a054004f0aa19947b6348fa367db53230abc8/cffi-2.1.1-cp314-cp314-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:f24fb43132a4c6b4cb4eb029492919b2db645be6808d738f244fd146c03c32cb", size = 196720, upload-time = "2026-08-03T21:20:18.268Z" }, + { url = "https://files.pythonhosted.org/packages/d9/99/c4b0c17cacdc9c3b8f280026286a9826d6a208c0f047591a3c3ce99b91fd/cffi-2.1.1-cp314-cp314-macosx_10_15_x86_64.whl", hash = "sha256:d28630f5854ab07ab1fd4aba756de52326c82e6be15d414b12793f1975048b54", size = 184964, upload-time = "2026-08-03T21:20:19.708Z" }, + { url = "https://files.pythonhosted.org/packages/b3/a9/9db617d05d7367c1ad0ab00b3aa6e6f9281edd689b4ee9ea0e5a84e89c97/cffi-2.1.1-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:661c298b4821edebead0c91edd2b00374d67ad7c5a1f7a91d4442633b79d6a72", size = 184962, upload-time = "2026-08-03T21:20:20.833Z" }, + { url = "https://files.pythonhosted.org/packages/67/b8/b42132ca113dc567d37684437b46ca1dafc885902b02a110a02d5b511857/cffi-2.1.1-cp314-cp314-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:58acb8ab8e295e6c5ea12f888cbb13cf21511ef2a3303a23f4325c29d17fe5c1", size = 222328, upload-time = "2026-08-03T21:20:22.118Z" }, + { url = "https://files.pythonhosted.org/packages/80/10/c5c0cbf0a657aecf59ef511409734230bf556f05a0d6c9eed7aa5c0a0166/cffi-2.1.1-cp314-cp314-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:456a61fa52d579ebf9df2e9552ead5129855dbaff6c1e5a9b1bc408809bdc062", size = 209985, upload-time = "2026-08-03T21:20:23.401Z" }, + { url = "https://files.pythonhosted.org/packages/d5/6c/bfa0b87b03b9238148beca990292843c9396ba069b54496596594173de7b/cffi-2.1.1-cp314-cp314-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a4f00aa42f75d6e4595e8866e748cc1705adc0cddfeb2ca86d0d03993d63ba03", size = 208530, upload-time = "2026-08-03T21:20:24.628Z" }, + { url = "https://files.pythonhosted.org/packages/e9/02/4e7d553a7ac4b4238b38b3c1b80d486e9d4436f8d2acbf87a0997fe3f402/cffi-2.1.1-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:b0431303acaea1089ad4b3e9ce4e6518193def1118d4073ca848635ee4ea2e96", size = 221525, upload-time = "2026-08-03T21:20:25.758Z" }, + { url = "https://files.pythonhosted.org/packages/82/1d/a4aaf9babd75acb4d5f223bff71533bee748dd770a382619a798960ee9ba/cffi-2.1.1-cp314-cp314-musllinux_1_2_aarch64.whl", hash = "sha256:64faea20f4e2613363a1a9b9c7dd73058f3ecd00133a511e72ad7c511658f527", size = 225053, upload-time = "2026-08-03T21:20:26.985Z" }, + { url = "https://files.pythonhosted.org/packages/81/10/5dc0e7bdd18e22107054288283380fc97a06ae3f1656a106908d666a3c88/cffi-2.1.1-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:5c58fe613dc5e5336357eff555824a314d8e43282600435c8d1cb6a7a2fedd13", size = 223213, upload-time = "2026-08-03T21:20:28.277Z" }, + { url = "https://files.pythonhosted.org/packages/0b/e9/d0061c364cde06ee43168a0d076ac1da512cbc380d44767b844ba34fe2b6/cffi-2.1.1-cp314-cp314-win32.whl", hash = "sha256:1a18a57b58cfb21fc28d72e876acf10eaed67a1ed96226f92af4df681d571c4c", size = 177682, upload-time = "2026-08-03T21:20:44.288Z" }, + { url = "https://files.pythonhosted.org/packages/a7/06/1c3e01e3ba14c39f6d10bfbac52753b7e22259e38088e5cfe1d704918690/cffi-2.1.1-cp314-cp314-win_amd64.whl", hash = "sha256:3222ba5d678f80a030e6afbcc33dc1ae5cb45facabb61cee2c7016b8432fde48", size = 187949, upload-time = "2026-08-03T21:20:45.623Z" }, + { url = "https://files.pythonhosted.org/packages/87/5b/da4e39efe18eeb89cf580ea9cfc66b6a7c3eadb808fc0cc1d3a295cb5a5d/cffi-2.1.1-cp314-cp314-win_arm64.whl", hash = "sha256:ab36d55f9ed2d067327667c2fea18dda018eb628dd6347aa01dda6cf1f5d3836", size = 182947, upload-time = "2026-08-03T21:20:46.955Z" }, + { url = "https://files.pythonhosted.org/packages/23/59/40338bf421c5accea1d45158170c87006ef1cd371b05c077e76476949728/cffi-2.1.1-cp314-cp314t-macosx_10_15_x86_64.whl", hash = "sha256:7750c6449dff7864bb9bb27ddfb0267756189201a3afc911d82b3caacd70dfc3", size = 188504, upload-time = "2026-08-03T21:20:29.495Z" }, + { url = "https://files.pythonhosted.org/packages/7d/47/5ecf1023850036e674c77ec4de86182d309ae344e39e7cba984b7df5d647/cffi-2.1.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:0beceaabe56af686895136a2de78db54ecd8e4046b236b8fd6d6cb61389e9bf2", size = 188259, upload-time = "2026-08-03T21:20:31.291Z" }, + { url = "https://files.pythonhosted.org/packages/2a/9c/92934c3bea9f785b23eba304538c0b4d37a2a96d2431eb3a1bc87a11aa19/cffi-2.1.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:49cbc70e6542d4ccccb936558d1064a8012541e78f821f955cff24e357776c94", size = 223864, upload-time = "2026-08-03T21:20:32.571Z" }, + { url = "https://files.pythonhosted.org/packages/4d/45/ba4c93527bc38616a8bd36488acb69a2212d60486794f0c1f318949bbb76/cffi-2.1.1-cp314-cp314t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:e2d65b31f36619cda3999b78b2aa9632e76b78448e7a56fc4240824200e7c4fc", size = 211538, upload-time = "2026-08-03T21:20:33.808Z" }, + { url = "https://files.pythonhosted.org/packages/80/e9/b6ef565e452acb932fb0cb5443f44a78efbd1233e566f02b5a83855e9115/cffi-2.1.1-cp314-cp314t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:28907ab9bfb6aa13184cfc17c6b8e1023c5ab6fd7076d8c20a35e59fe04f8f29", size = 210688, upload-time = "2026-08-03T21:20:34.974Z" }, + { url = "https://files.pythonhosted.org/packages/9a/95/eff5f0cee78d2eabc7eebffec40d3fc1876b5f3c95582e018bb4b99601f2/cffi-2.1.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:51b31d1c98274844cfd7838ce00bfc27c7423a4dc00fc0772fc3331c2cc90676", size = 223803, upload-time = "2026-08-03T21:20:36.564Z" }, + { url = "https://files.pythonhosted.org/packages/fa/01/579d39fb8bef00a335a23d83757b44feb24cd6345a2c451b64cb67b9c362/cffi-2.1.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:5e7cecbaadb83884793e05828cee59b210b24583b9c7425d0ba6a754fe22eb4e", size = 226763, upload-time = "2026-08-03T21:20:37.816Z" }, + { url = "https://files.pythonhosted.org/packages/8d/b0/0b44f47c60b01b57b6e2bbd92343f13a85a1d93bc46ccf6e47e244acd99c/cffi-2.1.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:25792eac27877609e7bb06d42ff88278a6624fff2ba9bbb523c09616b117e80f", size = 225688, upload-time = "2026-08-03T21:20:38.959Z" }, + { url = "https://files.pythonhosted.org/packages/eb/d2/3b7176cb570a1d3e27faf67b72f591af508036e0d8b2be2ef9af9e8c84bb/cffi-2.1.1-cp314-cp314t-win32.whl", hash = "sha256:8ef53b2de9bcb9197d31854256575d59dbac0cba72ac627bb291ef5eceb74be4", size = 182868, upload-time = "2026-08-03T21:20:40.388Z" }, + { url = "https://files.pythonhosted.org/packages/56/78/31f00c1bcd97c9bbf55f1bfdf5bc809a5de8887473e90bb9960dca825e80/cffi-2.1.1-cp314-cp314t-win_amd64.whl", hash = "sha256:616f097f2fe415bc92a247f02e11f634e1f9e9a83d327e3c915c15089c87869e", size = 194104, upload-time = "2026-08-03T21:20:41.725Z" }, + { url = "https://files.pythonhosted.org/packages/7b/1b/58496f2ed0a35de575250c02a43ab3cc2c04d494a88fed31c1cabc0fd176/cffi-2.1.1-cp314-cp314t-win_arm64.whl", hash = "sha256:ad2c86c495b899d862ea0f4b42891b8713a3bd45dd4105c7fd51c2a72f39f3a5", size = 186402, upload-time = "2026-08-03T21:20:43.042Z" }, + { url = "https://files.pythonhosted.org/packages/c1/8f/9ebe220eab48a093d1a5a5e339ab0dc7316eef3bb04d63c42f0251b61f50/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphoneos.whl", hash = "sha256:dddad92b554513a31f272570678ba307fb9f618f05e3d4a5eacafff9eae03e1d", size = 194043, upload-time = "2026-08-03T21:20:48.179Z" }, + { url = "https://files.pythonhosted.org/packages/ff/69/844bad3ece306c4782c2ecb93597035b6690d48704b803914c199da1e8b3/cffi-2.1.1-cp315-cp315-ios_13_0_arm64_iphonesimulator.whl", hash = "sha256:da0e573f9f97159390c89d9f1a9e41908b66d408cc5b58d08cf3847d844c531b", size = 196737, upload-time = "2026-08-03T21:20:49.457Z" }, + { url = "https://files.pythonhosted.org/packages/1b/8a/af668013284634733f02d683458a0728739c7d6ddb5e14cb0c20832266fe/cffi-2.1.1-cp315-cp315-macosx_10_15_x86_64.whl", hash = "sha256:fb92203a88b3d3053034db775110081c49d28be6551923805e039924093761e4", size = 184933, upload-time = "2026-08-03T21:20:50.639Z" }, + { url = "https://files.pythonhosted.org/packages/0c/75/2f5207ff6d1a613133b23a5203cc0c2a628313b5eb3974d7956ae3c57950/cffi-2.1.1-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:2ae64be792b8966f2c69538199728b290e34726562896df1e5dc8ffd8d8188e8", size = 185002, upload-time = "2026-08-03T21:20:52.173Z" }, + { url = "https://files.pythonhosted.org/packages/e2/31/9e1313b0a6e30e91b3b3d3fff51ae99c857c07738e3afcce1f7334e1b7ab/cffi-2.1.1-cp315-cp315-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:507a24c282e0f42f8ed737cf048572cbf580468da5555764a8331735e9c736b6", size = 222271, upload-time = "2026-08-03T21:20:53.462Z" }, + { url = "https://files.pythonhosted.org/packages/50/e3/f6234a833e6e08c7007003074723c406559eecf9b48dfc97471e5a8eb7a0/cffi-2.1.1-cp315-cp315-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:246fa40ce8645a614ff682e0b70f37134e460eaf93a775e0cbe3cca585a67a80", size = 209919, upload-time = "2026-08-03T21:20:54.783Z" }, + { url = "https://files.pythonhosted.org/packages/0d/fc/5f74e293fced6edb51af3a46c4ccf6c23c9943774ecb375ddbd522c76add/cffi-2.1.1-cp315-cp315-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:471cee653ae88de62096552e6d24ccb4a5adb8c8c9f10b5054d0122c15bf2779", size = 208529, upload-time = "2026-08-03T21:20:56.066Z" }, + { url = "https://files.pythonhosted.org/packages/44/16/29e6d01b388bef055ecd6ca8244b3f4d336bd09e92d5d892187b9601084e/cffi-2.1.1-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:aeae0e330c9f6acd681f647d46cefd30c29f93e3392882e792e82080c9691399", size = 221630, upload-time = "2026-08-03T21:20:57.336Z" }, + { url = "https://files.pythonhosted.org/packages/a4/18/fa7f1f6857d5eb88a4ca99ffcbfb7c387a287ccc154c64a73e86314745d7/cffi-2.1.1-cp315-cp315-musllinux_1_2_aarch64.whl", hash = "sha256:42a494cee34437f05546455144f2b5d9ac09b1face62bcfce597d2e521066688", size = 225134, upload-time = "2026-08-03T21:20:58.675Z" }, + { url = "https://files.pythonhosted.org/packages/e0/9f/e8e3dfa04a1b4c241f8c91faacad872b4d4efd051d49764ad4e2fd4b9fea/cffi-2.1.1-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:cc572dace3f60ef98d7b12ff411d20f5362feb31a0439eab0085bbfd349982d7", size = 223197, upload-time = "2026-08-03T21:20:59.968Z" }, + { url = "https://files.pythonhosted.org/packages/f8/7e/8debeb04f1ab9fe2a6963964cd6f1aaf7192627b83926586a6a4e089c9fa/cffi-2.1.1-cp315-cp315-win32.whl", hash = "sha256:4f42141fc14250de6dde5ee7ea4432be017252d91f19c5ad043c084cea629cac", size = 177683, upload-time = "2026-08-03T21:21:14.901Z" }, + { url = "https://files.pythonhosted.org/packages/e0/31/5158704cc474ab65c1647932e88be78dc0873f47130e253be38bcaf13d01/cffi-2.1.1-cp315-cp315-win_amd64.whl", hash = "sha256:e6e8cff14d6fb0be70a09c0bdc58096f501952d04624ebf867e0e56da2df8960", size = 187897, upload-time = "2026-08-03T21:21:16.108Z" }, + { url = "https://files.pythonhosted.org/packages/cc/4b/b3a2da8570c704ffc0f9762cdc3ec0f02c8573798e0b5cf7f11c82bbb70f/cffi-2.1.1-cp315-cp315-win_arm64.whl", hash = "sha256:27350daa11d4f10c540e6e89dada4c54feb7256ad03e9a4dc075ebad7ba360d1", size = 182935, upload-time = "2026-08-03T21:21:17.271Z" }, + { url = "https://files.pythonhosted.org/packages/d0/ef/5443574510a1207e6f6bc38ba6e1f1de36cb48fef07b2728bb896a21f430/cffi-2.1.1-cp315-cp315t-macosx_10_15_x86_64.whl", hash = "sha256:c26608d2222fb1e94487e4a387d85f13eb55d5ed725cb25a0c589ac4ee60e7bc", size = 188464, upload-time = "2026-08-03T21:21:01.163Z" }, + { url = "https://files.pythonhosted.org/packages/7e/ae/a56fa8c4686ad50e148fcbc8d3ae0d03915ff5c30d795058988c24118cef/cffi-2.1.1-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:4be96343e422f2dfcd12ab5c9f5aebe03f82f737c6bffeca6830b3875cb44aab", size = 188262, upload-time = "2026-08-03T21:21:02.382Z" }, + { url = "https://files.pythonhosted.org/packages/53/b2/6187f46f2912276a3ae284076109cc5c8680482f11f766ccf26db4a86427/cffi-2.1.1-cp315-cp315t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:937c0052c05a31ca1daf18de3158eed4dbfcb9cc107adbea227728d647be701e", size = 223779, upload-time = "2026-08-03T21:21:03.553Z" }, + { url = "https://files.pythonhosted.org/packages/8a/f6/c3ad28bd19f77047a03084424fbd4cbe997303267c14423737324be0385d/cffi-2.1.1-cp315-cp315t-manylinux2014_ppc64le.manylinux_2_17_ppc64le.whl", hash = "sha256:df423d40ee8654634421812bc3b196da3f9bd7d32929da813f8394c4348a5358", size = 211520, upload-time = "2026-08-03T21:21:04.863Z" }, + { url = "https://files.pythonhosted.org/packages/a0/cd/ccac9013a5bd9fd764de118674ab9c805b5ca10c19270d90ee273f8b2240/cffi-2.1.1-cp315-cp315t-manylinux2014_s390x.manylinux_2_17_s390x.whl", hash = "sha256:a730a083190634c65cca36ba5f489531576ebd79bcd5c8e172130f6453127231", size = 210673, upload-time = "2026-08-03T21:21:06.223Z" }, + { url = "https://files.pythonhosted.org/packages/52/86/2976131c639aead931c5bee5aba67e4b09fbeb8018b6f282f70803f923a7/cffi-2.1.1-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:363e05fa78e15116c3c32c210ee36884fd6b9afa6d440e47112c3bd511d64cb6", size = 223835, upload-time = "2026-08-03T21:21:07.539Z" }, + { url = "https://files.pythonhosted.org/packages/ac/0c/33a7aeab2f9c76918c52e084beb39c570db3588133412929e8ec06fab90b/cffi-2.1.1-cp315-cp315t-musllinux_1_2_aarch64.whl", hash = "sha256:770de9db11e84213beec501cfcaa013b019820ca881e03344dea5844f7876d94", size = 226705, upload-time = "2026-08-03T21:21:08.774Z" }, + { url = "https://files.pythonhosted.org/packages/e3/26/2cde30fdde421130bfc18f70395731a6e6b2053c6a1978a5258ff04e72fa/cffi-2.1.1-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:7da0c5eff80f0197f3b3d1232ec5a682a9325f4ae9016a78f5f5ca35f9ced1f5", size = 225539, upload-time = "2026-08-03T21:21:09.911Z" }, + { url = "https://files.pythonhosted.org/packages/6d/cd/a361394c94b2129d604bb846f624a8e88255a3ee33129c434a00d715e64f/cffi-2.1.1-cp315-cp315t-win32.whl", hash = "sha256:06c72bb76605a4b0cd0aad6930b69d4baf7dd5d806cfc409b824191099700e66", size = 182707, upload-time = "2026-08-03T21:21:11.226Z" }, + { url = "https://files.pythonhosted.org/packages/9b/b5/ba2b299993c26577d529b6ae29841f9e15b9fcf004d65f423f4fcf94ade9/cffi-2.1.1-cp315-cp315t-win_amd64.whl", hash = "sha256:d9c275eaacd24aa73f94ffd6de08fc3f932424d8b6c376f4bed7cde376fe7bc3", size = 193772, upload-time = "2026-08-03T21:21:12.39Z" }, + { url = "https://files.pythonhosted.org/packages/aa/29/35e016098c814cd93de9cd320c66b5bfba14dc6ecedd3cb518fa7c408c69/cffi-2.1.1-cp315-cp315t-win_arm64.whl", hash = "sha256:d18e5ac0f2f03f4f518d3e23db0f0cad7faa1da8620e9c09461d443bbf6e6692", size = 186360, upload-time = "2026-08-03T21:21:13.636Z" }, +] + [[package]] name = "click" version = "8.5.0" @@ -91,6 +164,56 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/d1/d6/3965ed04c63042e047cb6a3e6ed1a63a35087b6a609aa3a15ed8ac56c221/colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6", size = 25335, upload-time = "2022-10-25T02:36:20.889Z" }, ] +[[package]] +name = "cryptography" +version = "50.0.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "cffi", marker = "platform_python_implementation != 'PyPy'" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/bb/ad/5d6702db60b1e40b41ef513b6967ff5848f307d50f8449baf1634f5908f1/cryptography-50.0.1.tar.gz", hash = "sha256:5dd9bda1c12b4162f6ff568eeb5e0ff956c28d14406e875cfe8a63a2d414ff20", size = 880381, upload-time = "2026-08-25T19:45:45.499Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/ba/19/797e2aaac9df6a66f1550f49979dc1b1e39ecd2077501c30efa81e8d5d67/cryptography-50.0.1-cp311-abi3-macosx_11_0_arm64.whl", hash = "sha256:b8f852c65863251b9e3a1b8c150ce21e59b522dbb6a7d4bc80e680d38388e986", size = 4010153, upload-time = "2026-08-25T19:44:03.155Z" }, + { url = "https://files.pythonhosted.org/packages/90/34/9ce9a62ed9dc82ca9fd6a34445b6904af56e5f38b3eae2ed32e49c36053d/cryptography-50.0.1-cp311-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:53e279950892dc102c6b4e52af03ae5ea92fac572a1ddab78ca73a997f62b69f", size = 4723133, upload-time = "2026-08-25T19:44:05.461Z" }, + { url = "https://files.pythonhosted.org/packages/57/26/e6d4fc8512a51a5f9ee7bfdbfb853bce1197087df40c9ad993ad370b846f/cryptography-50.0.1-cp311-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:ff838d62ec1bfce4f9ba7fa16f4a7b554cd8d0c299e6be37502161a660c84eef", size = 4712478, upload-time = "2026-08-25T19:44:07.375Z" }, + { url = "https://files.pythonhosted.org/packages/e6/de/d3cdc2815697aae84126cbd6a030ca7b6b452e28a88b501b836bd3aa7a86/cryptography-50.0.1-cp311-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:e74591e283fe6eb956416c929eb58262a719fe0311fd9054c62c3350ed8760d8", size = 4730726, upload-time = "2026-08-25T19:44:09.294Z" }, + { url = "https://files.pythonhosted.org/packages/55/32/38c0d344b98c06d34b5df8946565a9c0d6dbf32c8e0730a7f05f0a3c6cab/cryptography-50.0.1-cp311-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:5fe002589592ed749ce77fe0695fcbd3500dd61d7d6db5858a7544c612fa8e45", size = 5353524, upload-time = "2026-08-25T19:44:11.96Z" }, + { url = "https://files.pythonhosted.org/packages/e1/1b/82f0f0d8858d4432be1af790477edf62aef90324041aa07c57e57bef1af7/cryptography-50.0.1-cp311-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:51593d180cf6d179bde5c5d065bed81386b1f381656ae7d042b7ffc87a9895ad", size = 4746720, upload-time = "2026-08-25T19:44:14.051Z" }, + { url = "https://files.pythonhosted.org/packages/29/ba/042ca458b8c64348c768284b5d23e69b92ed53d057ab779fee628564676d/cryptography-50.0.1-cp311-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:359e62deae718bce96170e223fdcb6357e4fbd3bb7a3a75f4430763532560e49", size = 4361866, upload-time = "2026-08-25T19:44:16.167Z" }, + { url = "https://files.pythonhosted.org/packages/39/3b/e96c1ef71edef71057c7e3c3d982ce8fda554e0c52d0cc19c18845cde3eb/cryptography-50.0.1-cp311-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:e2ca8fd1b6b4b82a1c4cb02841d0837e3c12336c2e24b520ab8ab3b969733d8f", size = 4730028, upload-time = "2026-08-25T19:44:18.085Z" }, + { url = "https://files.pythonhosted.org/packages/e3/38/45abd72ef63f2e7d0754a6cacf97bd8b69512ace7f6130d24c39ece65da2/cryptography-50.0.1-cp311-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:76de83fbd91ac49c0feaaa983d0748fd7a53176afac5fb3bf7478d244f0eb527", size = 5308405, upload-time = "2026-08-25T19:44:20.197Z" }, + { url = "https://files.pythonhosted.org/packages/85/66/6ccca4722987ddedaa7fc9c3f4708af7431f5535666c174350830888c6b7/cryptography-50.0.1-cp311-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:51afcfceb15597cf2635068e4ac9a56b2abde622edde17f37d85fd7b5306497a", size = 4746230, upload-time = "2026-08-25T19:44:22.376Z" }, + { url = "https://files.pythonhosted.org/packages/13/0e/b1f92e013228111413f2e6743948b80bc24dfd3c1b87ba98ceea16f5df89/cryptography-50.0.1-cp311-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:be224a65493ec5b74a158ff22a5522ce4a5ca1e543c647a3a4730d4a09e5f959", size = 4862596, upload-time = "2026-08-25T19:44:24.472Z" }, + { url = "https://files.pythonhosted.org/packages/7e/22/c3654cccc856e9d682817b04ac3ee79731cb09ca6f95996a95c904de2883/cryptography-50.0.1-cp311-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:9ebcdd5519be9b652a46f507817a74591774fc3d6923ac364e4dfa64e36b291b", size = 5014082, upload-time = "2026-08-25T19:44:26.709Z" }, + { url = "https://files.pythonhosted.org/packages/42/8b/cb12b1b60c91b074ca6bf0fdd59aa8f10d8bc5f73af8faece86ef0421b37/cryptography-50.0.1-cp311-abi3-win_amd64.whl", hash = "sha256:aed8db4f6d71c51efb89530e12d9464e7bf2923d46c3205dc794a2a93f8c0648", size = 3842826, upload-time = "2026-08-25T19:44:28.784Z" }, + { url = "https://files.pythonhosted.org/packages/5b/f0/424cb557d99aa86ac55da5e2add02e2882e44047b6264f93ade1b975a993/cryptography-50.0.1-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:30a125032e5642a21ff816e021152bd4e7e94f03eff3f4b7fca41cd22bc3110f", size = 3973525, upload-time = "2026-08-25T19:44:30.7Z" }, + { url = "https://files.pythonhosted.org/packages/4d/72/3a2711d967977ab5fc80b782837c7e8d1ac7445e764c20c381a265c57ef3/cryptography-50.0.1-cp314-cp314t-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:a0b1a59e3a089064a0ec309e9428c8e3ae4e161419d20ac33600767e83fc658a", size = 4708817, upload-time = "2026-08-25T19:44:32.773Z" }, + { url = "https://files.pythonhosted.org/packages/b4/f2/bb1f56e10815b789df0b409a69fa4992ff3d3fef9c72747f4a6b26fed38e/cryptography-50.0.1-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:8921d58f426793c5f1b47f0b59575780de9a095214958d0eb37d909593db8367", size = 4697300, upload-time = "2026-08-25T19:44:35.144Z" }, + { url = "https://files.pythonhosted.org/packages/08/bd/ed5396be499ffcf8807a585bfe38b71a1fbdd1c342b4f9b6d0ef5162a946/cryptography-50.0.1-cp314-cp314t-manylinux_2_28_aarch64.whl", hash = "sha256:a8f40ea47330e71b594a7e246898f93177c259490c63183dbaf9e571d71ed9a5", size = 4716039, upload-time = "2026-08-25T19:44:37.192Z" }, + { url = "https://files.pythonhosted.org/packages/f6/6e/1cf405c5c8e8df7545378048e954792f00b7f2367af8863ce8b8f3e10607/cryptography-50.0.1-cp314-cp314t-manylinux_2_28_ppc64le.whl", hash = "sha256:a255449073358275b64b67d3f595f268bbef70e72b6edb65e0c70c735bf739c9", size = 5332388, upload-time = "2026-08-25T19:44:39.16Z" }, + { url = "https://files.pythonhosted.org/packages/47/92/b4317e8c32c4f47b062f5398bd79106b220a124546f42be83bf32b761e2a/cryptography-50.0.1-cp314-cp314t-manylinux_2_28_x86_64.whl", hash = "sha256:8df2de9102026855887e4587084f6eabd80ed0f345b8ad8a7ac27ab9bf4723e0", size = 4730293, upload-time = "2026-08-25T19:44:41.298Z" }, + { url = "https://files.pythonhosted.org/packages/39/0d/a1e7633e2c744d0f2983320a27e924ef2264c79c56e1a58d5fb0a1cfd413/cryptography-50.0.1-cp314-cp314t-manylinux_2_31_armv7l.whl", hash = "sha256:ac02b07824d4d1001bd4367599f839c19cb171924c796e52c23508ac14c2c0cc", size = 4346031, upload-time = "2026-08-25T19:44:43.245Z" }, + { url = "https://files.pythonhosted.org/packages/88/dd/b215616f9bab3fc18510c78a4e5c9f362d77838503c363dc747c7d4f5c6f/cryptography-50.0.1-cp314-cp314t-manylinux_2_34_aarch64.whl", hash = "sha256:cbf74a81765ee67413503ca6e26dcc4f6f5a519822436cc0a1b97aab6c1b8a17", size = 4715344, upload-time = "2026-08-25T19:44:45.291Z" }, + { url = "https://files.pythonhosted.org/packages/b1/1b/ec3ebd31741d0e963612c4fe43caa39341b9b1e031e469820e42e4c83918/cryptography-50.0.1-cp314-cp314t-manylinux_2_34_ppc64le.whl", hash = "sha256:16c5ecd954b3330ebfb6605eca4fd952da8bef376551d5cc264534e3770a9ee6", size = 5287201, upload-time = "2026-08-25T19:44:47.297Z" }, + { url = "https://files.pythonhosted.org/packages/1a/01/0127d11a762b31a9ee0221894f540318761783f3fdc4bc5d057698caebd5/cryptography-50.0.1-cp314-cp314t-manylinux_2_34_x86_64.whl", hash = "sha256:79bf008d1f9af6071c797ad133e39915dfee7614f18f18f4db9072eb715064a3", size = 4730023, upload-time = "2026-08-25T19:44:49.435Z" }, + { url = "https://files.pythonhosted.org/packages/9e/b9/e7425ebfb599241a0c1d7000f1b466c3062da66c19d9525031315dff7213/cryptography-50.0.1-cp314-cp314t-musllinux_1_2_aarch64.whl", hash = "sha256:330fbb252391c596f1ae42c5754449dc924e6ad012dca8efe0d703f9f2d12ec6", size = 4847362, upload-time = "2026-08-25T19:44:51.94Z" }, + { url = "https://files.pythonhosted.org/packages/2d/fd/60d0ddf4defa12e482c9d5e0f554384d6e8ab25341fd15f060028fd92e6a/cryptography-50.0.1-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:42be3bb70596b3abe4ac097b75be223e8b3ab614a0e5de068e3dcc54d71d6149", size = 4999247, upload-time = "2026-08-25T19:44:53.876Z" }, + { url = "https://files.pythonhosted.org/packages/4d/56/bc4f2b209e766c93372cfcd59b781a0b2b59700f62a969580415b699c2b2/cryptography-50.0.1-cp314-cp314t-win_amd64.whl", hash = "sha256:f74455bb086a85d5e81246412602aaa97ed095e504cd40dd261ef50be42205bf", size = 3825806, upload-time = "2026-08-25T19:44:56.209Z" }, + { url = "https://files.pythonhosted.org/packages/84/a9/ee16a903f13755e914d1eecc482fe64d1f10761c3960e5d8fa6837377aff/cryptography-50.0.1-cp39-abi3-macosx_11_0_arm64.whl", hash = "sha256:ca83d00d9e69cd5eb63f2e69c3a5a59e0cecae5ae14c6ae0b35830fe3b37bad0", size = 4035307, upload-time = "2026-08-25T19:44:58.305Z" }, + { url = "https://files.pythonhosted.org/packages/5e/a5/9ec7e81e8526c0d7a387d73386b2daed3f39e10d81a85930bd1b6bfba65c/cryptography-50.0.1-cp39-abi3-manylinux2014_aarch64.manylinux_2_17_aarch64.whl", hash = "sha256:05ba322c4da95b262a212c345af888ef2c37c88c0509756ea00a0e6d68850f23", size = 4751900, upload-time = "2026-08-25T19:45:00.401Z" }, + { url = "https://files.pythonhosted.org/packages/7e/3c/0e77bd5ffcf078e9dd27d3074aad6c030d9b10d0bf69329d573c927a188c/cryptography-50.0.1-cp39-abi3-manylinux2014_x86_64.manylinux_2_17_x86_64.whl", hash = "sha256:e22dfed744bd4002e909464cb23d2f0b05c6f3113a79ef2e9864a53db737c733", size = 4738357, upload-time = "2026-08-25T19:45:02.786Z" }, + { url = "https://files.pythonhosted.org/packages/27/3a/3c5f80daa4dcd47323c7af8a2fcb90de27a33564d4fcac69846c0972691a/cryptography-50.0.1-cp39-abi3-manylinux_2_28_aarch64.whl", hash = "sha256:4c4188f7c0cf655be5c06342b817ed0f9595b69ffa2b12026e5353eed29dea88", size = 4758474, upload-time = "2026-08-25T19:45:04.889Z" }, + { url = "https://files.pythonhosted.org/packages/6e/2b/214cf0cf93db9628c3c20c896b229f327f6fb1b20e4b3743d8ad3f00af8b/cryptography-50.0.1-cp39-abi3-manylinux_2_28_ppc64le.whl", hash = "sha256:2ebbfb0f1fed745e91796e3e1080a1440423fdae8ece1b995a1d80883a409054", size = 5375862, upload-time = "2026-08-25T19:45:07.163Z" }, + { url = "https://files.pythonhosted.org/packages/d6/51/3f9701867a46b6c1740c9b52fc4d3bed6cbdcfedcc9b6e64305c07f39cff/cryptography-50.0.1-cp39-abi3-manylinux_2_28_x86_64.whl", hash = "sha256:407fe2b6db00939c05c0e945e9914238f2f0a430974839429dafc82b1ee6bee5", size = 4772942, upload-time = "2026-08-25T19:45:09.396Z" }, + { url = "https://files.pythonhosted.org/packages/0d/5c/13ea642e08e2544d0f5396122055f4820cfacb3203562197b5967125ea97/cryptography-50.0.1-cp39-abi3-manylinux_2_31_armv7l.whl", hash = "sha256:2b34d76a652ea2b6faf777c35df230c5637842cd904e04f16230c3f9f03e4361", size = 4383347, upload-time = "2026-08-25T19:45:11.659Z" }, + { url = "https://files.pythonhosted.org/packages/84/d5/7d1fe1cb93f91c428093ff234e128c89ba8ea61a6f26aab406081f9b996e/cryptography-50.0.1-cp39-abi3-manylinux_2_34_aarch64.whl", hash = "sha256:01f41478cf33fc605a6a089cd56d28b45c6c0b45a1928b61797f2621a04bac71", size = 4758050, upload-time = "2026-08-25T19:45:13.745Z" }, + { url = "https://files.pythonhosted.org/packages/dd/04/557fc5ead96a829e0bc812a3b9dc4a52a2f27e4f7f5950da7ff27653a805/cryptography-50.0.1-cp39-abi3-manylinux_2_34_ppc64le.whl", hash = "sha256:fc3ed7ebd2a8c96f5b166de0ab9b624996bef3b07bbeb19364dfb78222c22c80", size = 5332955, upload-time = "2026-08-25T19:45:16.193Z" }, + { url = "https://files.pythonhosted.org/packages/8c/eb/5d7124083e8d8cda8f5b348f544b71ad6f707ad63193758ef4d8e569da02/cryptography-50.0.1-cp39-abi3-manylinux_2_34_x86_64.whl", hash = "sha256:9dde0a357190eb3b1da1bb9ab750e9c85cba82ca5977aa0836cbb94e92611239", size = 4772694, upload-time = "2026-08-25T19:45:18.315Z" }, + { url = "https://files.pythonhosted.org/packages/63/8e/f1f955e0921dd2b6d22eae7e8d24a4c4b638d10735ffbf6a71f99eb0fcb8/cryptography-50.0.1-cp39-abi3-musllinux_1_2_aarch64.whl", hash = "sha256:fd3718b960d0b5dd213cdf03f3bcb7000e69dda0de8b956061947ff6bcff5558", size = 4888413, upload-time = "2026-08-25T19:45:20.4Z" }, + { url = "https://files.pythonhosted.org/packages/1f/ab/89e2b798d2c3925f82e2bb72d5979f3d2f6da2dd22ef4a8cd8b70d920039/cryptography-50.0.1-cp39-abi3-musllinux_1_2_x86_64.whl", hash = "sha256:2a93d05e34d5f67fba6f891fe85d929999baa7195e853923ea6d7576c9e68c5e", size = 5044355, upload-time = "2026-08-25T19:45:22.353Z" }, + { url = "https://files.pythonhosted.org/packages/99/89/87ef49ffe383ef4e147d27b7bf2088fb0b54ea409dd87b5a89442e5828a5/cryptography-50.0.1-cp39-abi3-win_amd64.whl", hash = "sha256:55d16b1ef3ee0958d893a977b19777887e546c9954ea81b200c3301a864013f2", size = 3875429, upload-time = "2026-08-25T19:45:24.418Z" }, +] + [[package]] name = "flask" version = "3.1.3" @@ -527,6 +650,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/98/33/e2a5b36edf8aa422f6fa4b894756eb33dc93b36df5f65121280bb8b929c4/psycopg_binary-3.3.6-cp315-cp315-win_amd64.whl", hash = "sha256:2f122603f36050937982abf9668d8bc4769a79f7c93a65013b1c49f1cab7b56b", size = 3756154, upload-time = "2026-09-18T13:22:51.283Z" }, ] +[[package]] +name = "pycparser" +version = "3.0" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/1b/7d/92392ff7815c21062bea51aa7b87d45576f649f16458d78b7cf94b9ab2e6/pycparser-3.0.tar.gz", hash = "sha256:600f49d217304a5902ac3c37e1281c9fe94e4d0489de643a9504c5cdfdfc6b29", size = 103492, upload-time = "2026-01-21T14:26:51.89Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0c/c3/44f3fbbfa403ea2a7c779186dc20772604442dde72947e7d01069cbe98e3/pycparser-3.0-py3-none-any.whl", hash = "sha256:b727414169a36b7d524c1c3e31839a521725078d7b2ff038656844266160a992", size = 48172, upload-time = "2026-01-21T14:26:50.693Z" }, +] + [[package]] name = "pydantic" version = "2.13.5" @@ -830,6 +962,7 @@ name = "scrobby" version = "0.1.0" source = { editable = "." } dependencies = [ + { name = "cryptography" }, { name = "flask" }, { name = "flask-cors" }, { name = "flask-migrate" }, @@ -852,6 +985,7 @@ dev = [ [package.metadata] requires-dist = [ + { name = "cryptography", specifier = ">=50.0.1" }, { name = "flask", specifier = ">=3.1.3" }, { name = "flask-cors", specifier = ">=6.0.5" }, { name = "flask-migrate", specifier = ">=4.1.0" }, From e890568c54029aff2d9896f78c0813bea4ab9a84 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 20:20:24 +0100 Subject: [PATCH 11/56] Federation protocol building blocks (phase 1, step 2) Pure, framework-free code in federation/protocol: - media: ActivityPub content types and Accept negotiation - vocab: actor URLs, Person and Application actors (Mastodon's extension terms), public keys, collections, plain text to safe HTML - webfinger: acct:/actor-URL resource parsing (other domains and bad usernames rejected) and JRD documents - nodeinfo: discovery and NodeInfo 2.1; hostmeta: XRD pointing at WebFinger Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/federation/protocol/hostmeta.py | 15 ++ src/scrobbler/federation/protocol/media.py | 37 +++++ src/scrobbler/federation/protocol/nodeinfo.py | 19 +++ src/scrobbler/federation/protocol/vocab.py | 147 ++++++++++++++++++ .../federation/protocol/webfinger.py | 44 ++++++ tests/test_federation_protocol.py | 130 ++++++++++++++++ 6 files changed, 392 insertions(+) create mode 100644 src/scrobbler/federation/protocol/hostmeta.py create mode 100644 src/scrobbler/federation/protocol/media.py create mode 100644 src/scrobbler/federation/protocol/nodeinfo.py create mode 100644 src/scrobbler/federation/protocol/vocab.py create mode 100644 src/scrobbler/federation/protocol/webfinger.py create mode 100644 tests/test_federation_protocol.py diff --git a/src/scrobbler/federation/protocol/hostmeta.py b/src/scrobbler/federation/protocol/hostmeta.py new file mode 100644 index 0000000..b35e372 --- /dev/null +++ b/src/scrobbler/federation/protocol/hostmeta.py @@ -0,0 +1,15 @@ +"""/.well-known/host-meta (RFC 6415): points older clients at WebFinger.""" + +from xml.sax.saxutils import quoteattr + +CONTENT_TYPE = "application/xrd+xml" + + +def xrd(base_url: str) -> str: + template = quoteattr(f"{base_url}/.well-known/webfinger?resource={{uri}}") + return ( + '\n' + '\n' + f' \n' + "\n" + ) diff --git a/src/scrobbler/federation/protocol/media.py b/src/scrobbler/federation/protocol/media.py new file mode 100644 index 0000000..eecbbb0 --- /dev/null +++ b/src/scrobbler/federation/protocol/media.py @@ -0,0 +1,37 @@ +"""ActivityPub media types and content negotiation.""" + +ACTIVITY_JSON = "application/activity+json" +AS_PROFILE = "https://www.w3.org/ns/activitystreams" +LD_JSON = f'application/ld+json; profile="{AS_PROFILE}"' +JRD_JSON = "application/jrd+json" + + +def _media_ranges(header: str): + for part in (header or "").split(","): + pieces = [p.strip() for p in part.split(";")] + media = pieces[0].lower() + params = {} + for piece in pieces[1:]: + name, _, value = piece.partition("=") + params[name.strip().lower()] = value.strip().strip('"') + try: + quality = float(params.get("q", "1")) + except ValueError: + quality = 0.0 + yield media, params, quality + + +def is_activitypub(media: str, params: dict) -> bool: + if media == ACTIVITY_JSON: + return True + # ld+json counts when it names the ActivityStreams profile (or no profile at all) + return media == "application/ld+json" and params.get("profile", AS_PROFILE) == AS_PROFILE + + +def wants_activitypub(accept: str | None) -> bool: + """True if an Accept header asks for ActivityPub JSON (rather than HTML).""" + return any(q > 0 and is_activitypub(m, p) for m, p, q in _media_ranges(accept or "")) + + +def is_activitypub_content_type(content_type: str | None) -> bool: + return any(is_activitypub(m, p) for m, p, _ in _media_ranges(content_type or "")) diff --git a/src/scrobbler/federation/protocol/nodeinfo.py b/src/scrobbler/federation/protocol/nodeinfo.py new file mode 100644 index 0000000..7735bd1 --- /dev/null +++ b/src/scrobbler/federation/protocol/nodeinfo.py @@ -0,0 +1,19 @@ +"""NodeInfo 2.1 (https://nodeinfo.diaspora.software/): what software a server runs.""" + +SCHEMA_21 = "http://nodeinfo.diaspora.software/ns/schema/2.1" + + +def discovery(base_url: str) -> dict: + return {"links": [{"rel": SCHEMA_21, "href": f"{base_url}/nodeinfo/2.1"}]} + + +def document(*, version: str, users_total: int, open_registrations: bool) -> dict: + return { + "version": "2.1", + "software": {"name": "scrobbler", "version": version}, + "protocols": ["activitypub"], + "services": {"inbound": [], "outbound": []}, + "openRegistrations": open_registrations, + "usage": {"users": {"total": users_total}, "localPosts": 0}, + "metadata": {}, + } diff --git a/src/scrobbler/federation/protocol/vocab.py b/src/scrobbler/federation/protocol/vocab.py new file mode 100644 index 0000000..d9ce6d1 --- /dev/null +++ b/src/scrobbler/federation/protocol/vocab.py @@ -0,0 +1,147 @@ +"""ActivityStreams / ActivityPub document builders (plain dicts, ready for JSON).""" + +import html +from dataclasses import dataclass + +AS_CONTEXT = "https://www.w3.org/ns/activitystreams" +SECURITY_CONTEXT = "https://w3id.org/security/v1" +PUBLIC = "https://www.w3.org/ns/activitystreams#Public" + +# The extension terms Mastodon and friends understand on actors. +ACTOR_CONTEXT = [ + AS_CONTEXT, + SECURITY_CONTEXT, + { + "manuallyApprovesFollowers": "as:manuallyApprovesFollowers", + "toot": "http://joinmastodon.org/ns#", + "discoverable": "toot:discoverable", + "indexable": "toot:indexable", + "schema": "http://schema.org#", + "PropertyValue": "schema:PropertyValue", + "value": "schema:value", + }, +] + + +@dataclass(frozen=True) +class ActorUrls: + id: str + inbox: str + outbox: str + followers: str + following: str + shared_inbox: str + key_id: str + profile_page: str + + +def actor_urls(base_url: str, username: str, profile_page: str) -> ActorUrls: + actor = f"{base_url}/users/{username}" + return ActorUrls( + id=actor, + inbox=f"{actor}/inbox", + outbox=f"{actor}/outbox", + followers=f"{actor}/followers", + following=f"{actor}/following", + shared_inbox=f"{base_url}/inbox", + key_id=f"{actor}#main-key", + profile_page=profile_page, + ) + + +def text_to_html(text: str | None) -> str: + """Plain text (e.g. a bio) as the small HTML subset Mastodon keeps.""" + if not text or not text.strip(): + return "" + paragraphs = [p for p in text.strip().replace("\r\n", "\n").split("\n\n") if p.strip()] + return "".join( + "

" + "
".join(html.escape(line) for line in p.split("\n")) + "

" + for p in paragraphs + ) + + +def public_key(urls: ActorUrls, public_key_pem: str) -> dict: + return {"id": urls.key_id, "owner": urls.id, "publicKeyPem": public_key_pem} + + +def person( + urls: ActorUrls, + *, + username: str, + name: str, + summary: str | None, + public_key_pem: str, + manually_approves_followers: bool, + discoverable: bool, + indexable: bool, + published: str | None = None, + fields: list[tuple[str, str]] = (), +) -> dict: + """A user's actor document. `fields` are (name, plain-text value) profile fields.""" + doc = { + "@context": ACTOR_CONTEXT, + "id": urls.id, + "type": "Person", + "preferredUsername": username, + "name": name, + "summary": text_to_html(summary), + "url": urls.profile_page, + "inbox": urls.inbox, + "outbox": urls.outbox, + "followers": urls.followers, + "following": urls.following, + "endpoints": {"sharedInbox": urls.shared_inbox}, + "publicKey": public_key(urls, public_key_pem), + "manuallyApprovesFollowers": manually_approves_followers, + "discoverable": discoverable, + "indexable": indexable, + "attachment": [ + {"type": "PropertyValue", "name": field, "value": html.escape(value)} + for field, value in fields + ], + } + if published: + doc["published"] = published + return doc + + +def application( + *, + actor_id: str, + username: str, + inbox: str, + outbox: str, + shared_inbox: str, + key_id: str, + public_key_pem: str, + url: str, +) -> dict: + """The instance actor: signs fetches on the server's behalf.""" + return { + "@context": ACTOR_CONTEXT, + "id": actor_id, + "type": "Application", + "preferredUsername": username, + "name": username, + "url": url, + "inbox": inbox, + "outbox": outbox, + "endpoints": {"sharedInbox": shared_inbox}, + "publicKey": {"id": key_id, "owner": actor_id, "publicKeyPem": public_key_pem}, + "manuallyApprovesFollowers": True, + "discoverable": False, + "indexable": False, + } + + +def ordered_collection(collection_id: str, total: int, items: list | None = None) -> dict: + """A collection. With items=None only the count is published (e.g. followers).""" + doc = { + "@context": AS_CONTEXT, + "id": collection_id, + "type": "OrderedCollection", + "totalItems": total, + } + if items is not None: + doc["orderedItems"] = items + return doc diff --git a/src/scrobbler/federation/protocol/webfinger.py b/src/scrobbler/federation/protocol/webfinger.py new file mode 100644 index 0000000..cf4a09b --- /dev/null +++ b/src/scrobbler/federation/protocol/webfinger.py @@ -0,0 +1,44 @@ +"""WebFinger (RFC 7033): resolving acct:user@domain to an actor.""" + +import re + +from scrobbler.federation.protocol.media import ACTIVITY_JSON + +_USERNAME = re.compile(r"^[A-Za-z0-9_.-]{1,64}$") + + +class ResourceError(ValueError): + """The resource isn't something this server answers for (400, not 404).""" + + +def parse_resource(resource: str | None, *, domain: str, base_url: str) -> str: + """The username in `acct:user@domain` (optionally with a leading @), or in an actor URL + `/users/`. Raises ResourceError for anything else.""" + value = (resource or "").strip() + if value.lower().startswith(f"{base_url.lower()}/users/"): + username = value[len(base_url) + len("/users/") :] + else: + if value.lower().startswith("acct:"): + value = value[5:] + value = value.lstrip("@") + username, at, host = value.rpartition("@") + if not at or host.lower() != domain.lower(): + raise ResourceError("resource must be acct:user@" + domain) + if not _USERNAME.match(username): + raise ResourceError("invalid username") + return username + + +def jrd(*, username: str, domain: str, actor_id: str, profile_page: str) -> dict: + return { + "subject": f"acct:{username}@{domain}", + "aliases": [actor_id, profile_page], + "links": [ + {"rel": "self", "type": ACTIVITY_JSON, "href": actor_id}, + { + "rel": "http://webfinger.net/rel/profile-page", + "type": "text/html", + "href": profile_page, + }, + ], + } diff --git a/tests/test_federation_protocol.py b/tests/test_federation_protocol.py new file mode 100644 index 0000000..35fc76c --- /dev/null +++ b/tests/test_federation_protocol.py @@ -0,0 +1,130 @@ +import xml.etree.ElementTree as ET + +import pytest + +from scrobbler.federation.protocol import hostmeta, media, nodeinfo, vocab, webfinger + +BASE = "https://scrobble.test" + + +@pytest.mark.parametrize( + ("accept", "expected"), + [ + ("application/activity+json", True), + ('application/ld+json; profile="https://www.w3.org/ns/activitystreams"', True), + ("application/ld+json", True), + ('application/ld+json; profile="https://example.com/other"', False), + ("text/html,application/xhtml+xml,*/*;q=0.8", False), + ("application/activity+json;q=0", False), + ("text/html, application/activity+json;q=0.5", True), + ("", False), + (None, False), + ], +) +def test_accept_negotiation(accept, expected): + assert media.wants_activitypub(accept) is expected + + +@pytest.mark.parametrize( + ("resource", "username"), + [ + ("acct:alice@scrobble.test", "alice"), + ("acct:Alice@SCROBBLE.TEST", "Alice"), + ("alice@scrobble.test", "alice"), + ("@alice@scrobble.test", "alice"), + (" acct:alice@scrobble.test ", "alice"), + ("https://scrobble.test/users/alice", "alice"), + ], +) +def test_webfinger_resources(resource, username): + assert webfinger.parse_resource(resource, domain="scrobble.test", base_url=BASE) == username + + +@pytest.mark.parametrize( + "resource", + [ + "acct:alice@elsewhere.example", + "acct:alice", + "", + None, + "acct:al ice@scrobble.test", + "https://elsewhere.example/users/alice", + "https://scrobble.test/users/alice/../../admin", + ], +) +def test_webfinger_rejects_other_resources(resource): + with pytest.raises(webfinger.ResourceError): + webfinger.parse_resource(resource, domain="scrobble.test", base_url=BASE) + + +def test_jrd_shape(): + doc = webfinger.jrd( + username="alice", + domain="scrobble.test", + actor_id=f"{BASE}/users/alice", + profile_page=f"{BASE}/profile.html?u=alice", + ) + assert doc["subject"] == "acct:alice@scrobble.test" + [self_link] = [link for link in doc["links"] if link["rel"] == "self"] + assert self_link == { + "rel": "self", + "type": "application/activity+json", + "href": f"{BASE}/users/alice", + } + + +def test_person_document(): + urls = vocab.actor_urls(BASE, "alice", f"{BASE}/profile.html?u=alice") + doc = vocab.person( + urls, + username="alice", + name="Alice", + summary="Listens a lot.\n\n", + public_key_pem="PEM", + manually_approves_followers=True, + discoverable=False, + indexable=False, + fields=[("Scrobbles", "1,234 & counting")], + ) + assert doc["id"] == f"{BASE}/users/alice" + assert doc["type"] == "Person" + assert doc["inbox"] == f"{BASE}/users/alice/inbox" + assert doc["endpoints"] == {"sharedInbox": f"{BASE}/inbox"} + assert doc["publicKey"] == { + "id": f"{BASE}/users/alice#main-key", + "owner": doc["id"], + "publicKeyPem": "PEM", + } + assert doc["summary"] == "

Listens a lot.

<script>x</script>

" + assert doc["attachment"] == [ + {"type": "PropertyValue", "name": "Scrobbles", "value": "1,234 & counting"} + ] + assert (doc["manuallyApprovesFollowers"], doc["discoverable"], doc["indexable"]) == ( + True, + False, + False, + ) + assert vocab.AS_CONTEXT in doc["@context"] and vocab.SECURITY_CONTEXT in doc["@context"] + + +def test_collections(): + assert vocab.ordered_collection("x", 3) == { + "@context": vocab.AS_CONTEXT, + "id": "x", + "type": "OrderedCollection", + "totalItems": 3, + } + assert vocab.ordered_collection("x", 0, items=[])["orderedItems"] == [] + + +def test_nodeinfo(): + assert nodeinfo.discovery(BASE)["links"][0]["href"] == f"{BASE}/nodeinfo/2.1" + doc = nodeinfo.document(version="0.2.0", users_total=3, open_registrations=True) + assert doc["software"] == {"name": "scrobbler", "version": "0.2.0"} + assert doc["protocols"] == ["activitypub"] + assert doc["usage"]["users"]["total"] == 3 + + +def test_host_meta_points_at_webfinger(): + link = ET.fromstring(hostmeta.xrd(BASE)).find("{http://docs.oasis-open.org/ns/xri/xrd-1.0}Link") + assert link.get("template") == f"{BASE}/.well-known/webfinger?resource={{uri}}" From ce39e8f865525d1fd3b8d64a1815091f123f35b8 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 20:23:02 +0100 Subject: [PATCH 12/56] ActivityPub discovery endpoints (phase 1, step 3) Registered only when federation is enabled: - WebFinger (acct: and actor-URL resources, the instance actor, CORS *) - host-meta, NodeInfo discovery and 2.1 (counts users sharing) - /users/: the Person actor for ActivityPub clients, a redirect to the UI profile page for browsers (for any name, so redirects don't reveal accounts); outbox/followers/following collections - /actor: the instance Application actor - Inboxes accept (202) and count deliveries; size-limited; processing arrives in phase 2. Actors advertise manual approval until then. - Unknown and non-sharing users get byte-identical 404s; all IDs come from FEDERATION_BASE_URL, never the request - Federation metrics: lookups, sharing changes, inbox deliveries - scrobbler.__version__ joins the core's public surface for NodeInfo Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/federation/README.md | 1 + src/scrobbler/federation/__init__.py | 5 +- src/scrobbler/federation/metrics.py | 26 ++++ src/scrobbler/federation/web.py | 199 +++++++++++++++++++++++++++ tests/test_federation_boundary.py | 1 + tests/test_federation_web.py | 134 ++++++++++++++++++ 6 files changed, 365 insertions(+), 1 deletion(-) create mode 100644 src/scrobbler/federation/metrics.py create mode 100644 src/scrobbler/federation/web.py create mode 100644 tests/test_federation_web.py diff --git a/src/scrobbler/federation/README.md b/src/scrobbler/federation/README.md index 046c0eb..3023cd6 100644 --- a/src/scrobbler/federation/README.md +++ b/src/scrobbler/federation/README.md @@ -11,6 +11,7 @@ or switched off without touching anything else. Design: `docs/design/activitypub 2. **`protocol/` is pure**: no Flask, SQLAlchemy, Werkzeug or `scrobbler` imports. Signature schemes, vocabulary and document formats live there. 3. **The rest of this package uses only the core's public surface**: + - `scrobbler.__version__` - `scrobbler.events` - `scrobbler.extensions` (`db`) - `scrobbler.worker` diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py index ff3303a..1d67351 100644 --- a/src/scrobbler/federation/__init__.py +++ b/src/scrobbler/federation/__init__.py @@ -27,4 +27,7 @@ def init_app(app: Flask) -> None: if not config.enabled: return log.info("federation enabled: handles @user@%s, actors at %s", config.domain, config.base_url) - # Phase 1 onwards registers routes, event receivers and worker tasks here. + + from scrobbler.federation import web + + app.register_blueprint(web.bp) diff --git a/src/scrobbler/federation/metrics.py b/src/scrobbler/federation/metrics.py new file mode 100644 index 0000000..b08707c --- /dev/null +++ b/src/scrobbler/federation/metrics.py @@ -0,0 +1,26 @@ +"""Federation's own metrics (the core's HTTP metrics already cover rate/latency).""" + +from prometheus_client import Counter + +lookups_total = Counter( + "scrobbler_federation_lookups_total", + "Fediverse lookups answered: WebFinger, actor, NodeInfo, profile", + ["kind", "result"], +) +sharing_changes_total = Counter( + "scrobbler_federation_sharing_changes_total", + "Users switching fediverse sharing on or off", + ["change"], +) +inbox_requests_total = Counter( + "scrobbler_federation_inbox_requests_total", + "Deliveries received at an inbox (not yet processed: phase 2)", + ["inbox"], +) + +# Every scrobbler_federation_* series name, for the dashboard consistency test. +SERIES = ( + "scrobbler_federation_lookups_total", + "scrobbler_federation_sharing_changes_total", + "scrobbler_federation_inbox_requests_total", +) diff --git a/src/scrobbler/federation/web.py b/src/scrobbler/federation/web.py new file mode 100644 index 0000000..10818f7 --- /dev/null +++ b/src/scrobbler/federation/web.py @@ -0,0 +1,199 @@ +"""The ActivityPub endpoints remote servers call. Served on the UI's domain: its nginx +forwards these paths to the API. Every ID is built from FEDERATION_BASE_URL, never from +the request, so a proxy misconfiguration can't produce wrong IDs.""" + +import json + +from flask import Blueprint, Response, current_app, redirect, request + +from scrobbler.federation import keys, sharing +from scrobbler.federation import metrics as fed_metrics +from scrobbler.federation.protocol import hostmeta, media, nodeinfo, vocab, webfinger + +bp = Blueprint("federation", __name__) + +MAX_INBOX_BYTES = 256 * 1024 +_NOT_FOUND = {"error": "not found"} + + +def _config(): + return current_app.extensions["federation"] + + +def _profile_page(username: str) -> str: + return f"{current_app.config['UI_BASE_URL']}/profile.html?u={username}" + + +def _urls(username: str) -> vocab.ActorUrls: + return vocab.actor_urls(_config().base_url, username, _profile_page(username)) + + +def _json(doc, content_type: str = media.ACTIVITY_JSON, status: int = 200, cache: int = 300): + response = Response(json.dumps(doc), status=status, content_type=content_type) + if status == 200 and cache: + response.headers["Cache-Control"] = f"public, max-age={cache}" + response.headers["Vary"] = "Accept" + return response + + +def _not_found(kind: str): + fed_metrics.lookups_total.labels(kind=kind, result="not_found").inc() + return _json(_NOT_FOUND, content_type="application/json", status=404) + + +def _found(kind: str) -> None: + fed_metrics.lookups_total.labels(kind=kind, result="found").inc() + + +# --- Discovery ----------------------------------------------------------------------- + + +@bp.get("/.well-known/webfinger") +def webfinger_lookup(): + config = _config() + try: + username = webfinger.parse_resource( + request.args.get("resource"), domain=config.domain, base_url=config.base_url + ) + except webfinger.ResourceError as err: + return _json({"error": str(err)}, content_type="application/json", status=400) + + if username.lower() == config.domain: # the instance actor, as Mastodon names it + actor_id, canonical = f"{config.base_url}/actor", config.domain + profile = current_app.config["UI_BASE_URL"] + else: + found = sharing.shared_user(username) + if found is None: + return _not_found("webfinger") + canonical = found[0].username + actor_id, profile = _urls(canonical).id, _profile_page(canonical) + _found("webfinger") + doc = webfinger.jrd( + username=canonical, domain=config.domain, actor_id=actor_id, profile_page=profile + ) + response = _json(doc, content_type=media.JRD_JSON) + response.headers["Access-Control-Allow-Origin"] = "*" # RFC 7033 §5 + return response + + +@bp.get("/.well-known/host-meta") +def host_meta(): + return Response(hostmeta.xrd(_config().base_url), content_type=hostmeta.CONTENT_TYPE) + + +@bp.get("/.well-known/nodeinfo") +def nodeinfo_discovery(): + return _json(nodeinfo.discovery(_config().base_url), content_type="application/json") + + +@bp.get("/nodeinfo/2.1") +def nodeinfo_document(): + from scrobbler import __version__ + + _found("nodeinfo") + doc = nodeinfo.document( + version=__version__, users_total=sharing.sharing_count(), open_registrations=True + ) + schema = f'application/json; profile="{nodeinfo.SCHEMA_21}#"' + return _json(doc, content_type=schema, cache=1800) + + +# --- Actors and collections ------------------------------------------------------------- + + +@bp.get("/users/") +def actor(username: str): + if not media.wants_activitypub(request.headers.get("Accept")): + # A person following a link: show them the profile page (for everyone, so + # redirects don't reveal which accounts exist). + return redirect(_profile_page(username), code=302) + found = sharing.shared_user(username) + if found is None: + return _not_found("actor") + user, settings = found + _found("actor") + urls = _urls(user.username) + doc = vocab.person( + urls, + username=user.username, + name=settings.display_name or user.username, + summary=settings.bio, + public_key_pem=keys.key_for(user.id).public_key_pem, + # Phase 1 can't accept follows yet: advertise approval so follows show as + # requests rather than failing silently. + manually_approves_followers=True, + discoverable=settings.discoverable, + indexable=settings.indexable, + published=settings.created_at.isoformat().replace("+00:00", "Z"), + ) + return _json(doc) + + +def _collection(username: str, which: str, items: list | None): + found = sharing.shared_user(username) + if found is None: + return _not_found("actor") + urls = _urls(found[0].username) + return _json(vocab.ordered_collection(getattr(urls, which), 0, items)) + + +@bp.get("/users//outbox") +def outbox(username: str): + return _collection(username, "outbox", []) + + +@bp.get("/users//followers") +def followers(username: str): + return _collection(username, "followers", None) # count only + + +@bp.get("/users//following") +def following(username: str): + return _collection(username, "following", []) + + +# --- Instance actor ------------------------------------------------------------------- + + +@bp.get("/actor") +def instance_actor(): + config = _config() + actor_id = f"{config.base_url}/actor" + doc = vocab.application( + actor_id=actor_id, + username=config.domain, + inbox=f"{config.base_url}/inbox", + outbox=f"{actor_id}/outbox", + shared_inbox=f"{config.base_url}/inbox", + key_id=f"{actor_id}#main-key", + public_key_pem=keys.key_for(None).public_key_pem, + url=current_app.config["UI_BASE_URL"], + ) + return _json(doc) + + +@bp.get("/actor/outbox") +def instance_outbox(): + return _json(vocab.ordered_collection(f"{_config().base_url}/actor/outbox", 0, [])) + + +# --- Inboxes (phase 2 processes deliveries) ----------------------------------------------- + + +def _accept_delivery(inbox: str): + if (request.content_length or 0) > MAX_INBOX_BYTES: + return _json({"error": "too large"}, content_type="application/json", status=413) + fed_metrics.inbox_requests_total.labels(inbox=inbox).inc() + return Response(status=202) + + +@bp.post("/users//inbox") +def user_inbox(username: str): + if sharing.shared_user(username) is None: + return _not_found("actor") + return _accept_delivery("user") + + +@bp.post("/inbox") +def shared_inbox(): + return _accept_delivery("shared") diff --git a/tests/test_federation_boundary.py b/tests/test_federation_boundary.py index 1cc2a9c..625eb4e 100644 --- a/tests/test_federation_boundary.py +++ b/tests/test_federation_boundary.py @@ -35,6 +35,7 @@ FRAMEWORKS = ( "marshmallow", ) CORE_PUBLIC_SURFACE = ( + "scrobbler.__version__", "scrobbler.events", "scrobbler.extensions", "scrobbler.worker", diff --git a/tests/test_federation_web.py b/tests/test_federation_web.py new file mode 100644 index 0000000..6b97a88 --- /dev/null +++ b/tests/test_federation_web.py @@ -0,0 +1,134 @@ +import xml.etree.ElementTree as ET +from urllib.parse import urlsplit + +import pytest + +AP = {"Accept": "application/activity+json"} +BASE = "https://scrobble.test" + + +def webfinger(client, resource): + return client.get("/.well-known/webfinger", query_string={"resource": resource}) + + +def test_webfinger_finds_sharing_users(fed_client, sharing_user, metric_delta): + found = metric_delta("scrobbler_federation_lookups_total", kind="webfinger", result="found") + response = webfinger(fed_client, "acct:ALICE@scrobble.test") + assert response.status_code == 200 + assert response.content_type == "application/jrd+json" + assert response.headers["Access-Control-Allow-Origin"] == "*" + doc = response.get_json() + assert doc["subject"] == "acct:alice@scrobble.test" + assert { + "rel": "self", + "type": "application/activity+json", + "href": f"{BASE}/users/alice", + } in doc["links"] + assert found.delta == 1 + + +def test_unknown_and_private_users_look_identical(fed_client, fed_ctx, make_user): + make_user(username="bob") # exists, never enabled sharing + unknown = webfinger(fed_client, "acct:nobody@scrobble.test") + private = webfinger(fed_client, "acct:bob@scrobble.test") + assert unknown.status_code == private.status_code == 404 + assert unknown.data == private.data + ap_unknown = fed_client.get("/users/nobody", headers=AP) + ap_private = fed_client.get("/users/bob", headers=AP) + assert ap_unknown.status_code == ap_private.status_code == 404 + assert ap_unknown.data == ap_private.data + + +def test_webfinger_rejects_other_domains(fed_client, sharing_user): + assert webfinger(fed_client, "acct:alice@elsewhere.example").status_code == 400 + assert fed_client.get("/.well-known/webfinger").status_code == 400 + + +def test_webfinger_instance_actor(fed_client, fed_ctx): + doc = webfinger(fed_client, "acct:scrobble.test@scrobble.test").get_json() + assert doc["links"][0]["href"] == f"{BASE}/actor" + + +def test_actor_document(fed_client, sharing_user): + response = fed_client.get("/users/alice", headers=AP) + assert response.status_code == 200 + assert response.content_type == "application/activity+json" + assert response.headers["Vary"] == "Accept" + doc = response.get_json() + assert doc["id"] == f"{BASE}/users/alice" + assert (doc["type"], doc["preferredUsername"], doc["name"]) == ("Person", "alice", "Alice") + assert doc["summary"] == "

Listening.

" + assert doc["publicKey"]["id"] == f"{BASE}/users/alice#main-key" + assert doc["publicKey"]["publicKeyPem"].startswith("-----BEGIN PUBLIC KEY-----") + assert doc["manuallyApprovesFollowers"] is True # follows are requests until phase 2 + assert (doc["discoverable"], doc["indexable"]) == (False, False) + assert doc["url"] == "http://localhost:8080/profile.html?u=alice" + + +def test_ids_come_from_config_not_the_request(fed_client, sharing_user): + doc = fed_client.get("/users/alice", headers={**AP, "Host": "evil.example"}).get_json() + assert urlsplit(doc["id"]).netloc == "scrobble.test" + + +@pytest.mark.parametrize("username", ["alice", "nobody"]) +def test_browsers_are_sent_to_the_profile_page(fed_client, sharing_user, username): + response = fed_client.get(f"/users/{username}", headers={"Accept": "text/html"}) + assert response.status_code == 302 + assert response.headers["Location"] == f"http://localhost:8080/profile.html?u={username}" + + +def test_collections(fed_client, sharing_user): + outbox = fed_client.get("/users/alice/outbox", headers=AP).get_json() + assert (outbox["type"], outbox["totalItems"], outbox["orderedItems"]) == ( + "OrderedCollection", + 0, + [], + ) + followers = fed_client.get("/users/alice/followers", headers=AP).get_json() + assert followers["totalItems"] == 0 and "orderedItems" not in followers + + +def test_nodeinfo(fed_client, sharing_user): + link = fed_client.get("/.well-known/nodeinfo").get_json()["links"][0] + assert link["href"] == f"{BASE}/nodeinfo/2.1" + doc = fed_client.get("/nodeinfo/2.1").get_json() + assert doc["software"]["name"] == "scrobbler" + assert doc["usage"]["users"]["total"] == 1 + + +def test_host_meta(fed_client): + root = ET.fromstring(fed_client.get("/.well-known/host-meta").data) + assert "webfinger" in root[0].get("template") + + +def test_instance_actor(fed_client, fed_ctx): + doc = fed_client.get("/actor", headers=AP).get_json() + assert (doc["type"], doc["id"]) == ("Application", f"{BASE}/actor") + + +def test_inboxes_accept_and_count_deliveries(fed_client, sharing_user, metric_delta): + shared = metric_delta("scrobbler_federation_inbox_requests_total", inbox="shared") + body = b'{"type": "Follow"}' + assert ( + fed_client.post("/inbox", data=body, content_type="application/activity+json").status_code + == 202 + ) + assert ( + fed_client.post( + "/users/alice/inbox", data=body, content_type="application/activity+json" + ).status_code + == 202 + ) + assert fed_client.post("/users/nobody/inbox", data=body).status_code == 404 + too_big = fed_client.post("/inbox", data=b"x" * (256 * 1024 + 1)) + assert too_big.status_code == 413 + assert shared.delta == 1 + + +def test_disabled_app_has_none_of_these_routes(client): + for path in ( + "/.well-known/webfinger?resource=acct:alice@scrobble.test", + "/users/alice", + "/nodeinfo/2.1", + ): + assert client.get(path, headers=AP).status_code == 404 From 0b1046951421ba8d0dd0c6d36ef31a03e5c10e3c Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 20:26:33 +0100 Subject: [PATCH 13/56] 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" ) From c0b9e85519927af13c86bf23690638d4e2e67940 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 20:32:40 +0100 Subject: [PATCH 14/56] Sharing settings and public profile pages (phase 1, step 5) - sharing.html: switch sharing on/off, see the handle (with the "permanent once followed" warning and a note that following comes later), choose who sees posts (followers only by default; help text on why approval matters), follower approval, directory and search opt-ins, display name and bio; save status shown by the button - profile.html?u=: the public page browsers land on from an actor URL: name, handle (with copy), bio and how to follow; never asks the visitor to sign in - "Sharing" appears in the nav only when the server federates (remembered per tab) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- frontend/css/style.css | 101 +++++++++++++++++++++++++++++++++++++++++ frontend/js/layout.js | 33 ++++++++++++++ frontend/js/profile.js | 43 ++++++++++++++++++ frontend/js/sharing.js | 82 +++++++++++++++++++++++++++++++++ frontend/profile.html | 18 ++++++++ frontend/sharing.html | 84 ++++++++++++++++++++++++++++++++++ 6 files changed, 361 insertions(+) create mode 100644 frontend/js/profile.js create mode 100644 frontend/js/sharing.js create mode 100644 frontend/profile.html create mode 100644 frontend/sharing.html diff --git a/frontend/css/style.css b/frontend/css/style.css index be1e45e..4ef8bbc 100644 --- a/frontend/css/style.css +++ b/frontend/css/style.css @@ -844,3 +844,104 @@ input { transition: width 0.4s ease-out; } } + +/* ---- Sharing & profile ---------------------------------------------------- */ +.sharing { + max-width: 44rem; +} + +.share-switch { + display: flex; + align-items: center; + gap: 0.75rem; + font-size: var(--step-1); + font-weight: 650; + margin-bottom: 1rem; +} + +.share-switch input { + width: 1.4rem; + height: 1.4rem; + accent-color: var(--ok); +} + +.handle-panel { + margin-bottom: 2rem; +} + +.handle { + font-size: clamp(1.1rem, 4vw, var(--step-2)); + margin: 0.4rem 0 0.75rem; +} + +.handle-panel .notice { + margin-top: 1rem; +} + +.choices { + border: 0; + border-top: 1px solid var(--rule); + margin: 0 0 1.5rem; + padding: 1.25rem 0 0; + min-inline-size: 0; +} + +.choices legend { + font-weight: 650; + font-size: var(--step-1); + padding: 0 0.5rem 0 0; +} + +.choice { + display: flex; + gap: 0.75rem; + align-items: flex-start; + margin-bottom: 0.9rem; +} + +.choice input { + margin-top: 0.3rem; + accent-color: var(--ink); +} + +.choice label { + display: grid; + gap: 0.1rem; +} + +.choice label .muted { + font-size: var(--step--1); +} + +.choices .hint { + color: var(--ink-soft); + font-size: var(--step--1); + margin-top: 0.5rem; +} + +.field textarea { + min-height: 5rem; + padding: 0.5rem 0.75rem; + border: 1px solid var(--rule); + border-radius: var(--radius-control); + background: var(--paper-raised); + font: inherit; + color: inherit; + resize: vertical; +} + +.field textarea:focus-visible { + border-color: var(--focus); +} + +.profile-bio { + white-space: pre-line; +} + +.profile-follow { + margin: 2rem 0 0.4rem; +} + +.save-row { + align-items: center; +} diff --git a/frontend/js/layout.js b/frontend/js/layout.js index ff2a6e6..feb134d 100644 --- a/frontend/js/layout.js +++ b/frontend/js/layout.js @@ -20,6 +20,7 @@ export async function signedInPage(active) { const header = document.getElementById("site-header"); replace(header, brand(), nav(active)); const user = await api("/auth/me"); + addSharingLink(header.querySelector("nav ul"), active); header.append( h( "div", @@ -61,3 +62,35 @@ async function signOut() { location.href = "login.html"; } } + +// "Sharing" only appears when the server federates. Remembered per tab. +const FEDERATION_KEY = "scrobbler.federation"; + +async function federationAvailable() { + try { + const cached = sessionStorage.getItem(FEDERATION_KEY); + if (cached !== null) return cached === "1"; + } catch { + // Storage unavailable: just ask. + } + let available = false; + try { + await api("/federation/settings"); + available = true; + } catch { + available = false; + } + try { + sessionStorage.setItem(FEDERATION_KEY, available ? "1" : "0"); + } catch { + // Not remembered; asked again next page. + } + return available; +} + +async function addSharingLink(list, active) { + if (!list || !(await federationAvailable())) return; + const href = "sharing.html"; + list.append(h("li", {}, h("a", { href, "aria-current": href === active ? "page" : false }, "Sharing"))); +} + diff --git a/frontend/js/profile.js b/frontend/js/profile.js new file mode 100644 index 0000000..bbf1031 --- /dev/null +++ b/frontend/js/profile.js @@ -0,0 +1,43 @@ +import { api } from "./api.js"; +import { errorBox, h, replace } from "./dom.js"; +import { publicPage } from "./layout.js"; + +const root = document.getElementById("profile"); +const username = new URLSearchParams(location.search).get("u") ?? ""; + +// A public page: never sends visitors to sign in. +publicPage(); + +try { + const profile = await api(`/federation/profiles/${encodeURIComponent(username)}`, { auth: false }); + document.title = `${profile.display_name} · Scrobbler`; + const copy = h("button", { type: "button", class: "button button-quiet" }, "Copy handle"); + copy.addEventListener("click", async () => { + try { + await navigator.clipboard.writeText(profile.handle); + copy.textContent = "Copied"; + } catch { + copy.textContent = "Select and copy it above"; + } + }); + replace( + root, + h("h1", {}, profile.display_name), + h("div", { class: "approve-app handle" }, profile.handle), + profile.bio ? h("p", { class: "lede profile-bio" }, profile.bio) : null, + h("h2", { class: "profile-follow" }, "Follow from the fediverse"), + h( + "p", + { class: "muted" }, + "Search for the handle above in Mastodon or any other fediverse app, then follow.", + ), + h("div", { class: "button-row" }, copy), + ); +} catch (error) { + replace( + root, + error.status === 404 + ? [h("h1", {}, "No profile here"), h("p", { class: "lede" }, "No one on this server shares their listening under that name.")] + : errorBox(error.message), + ); +} diff --git a/frontend/js/sharing.js b/frontend/js/sharing.js new file mode 100644 index 0000000..b9c8757 --- /dev/null +++ b/frontend/js/sharing.js @@ -0,0 +1,82 @@ +import { api, describeError } from "./api.js"; +import { errorBox, h, replace } from "./dom.js"; +import { signedInPage } from "./layout.js"; + +const form = document.getElementById("sharing"); +const messages = document.getElementById("messages"); +const handlePanel = document.getElementById("handle-panel"); +const FIELDS = ["enabled", "visibility", "manually_approves_followers", "discoverable", "indexable", "display_name", "bio"]; + +await signedInPage("sharing.html"); + +let settings; +try { + settings = await api("/federation/settings"); +} catch (error) { + replace( + messages, + error.status === 404 + ? h("p", { class: "notice" }, "This server doesn't share to the fediverse. Ask whoever runs it to turn it on.") + : errorBox(error.message), + ); +} + +if (settings) { + fill(settings); + form.hidden = false; + form.elements.enabled.addEventListener("change", () => showHandle(form.elements.enabled.checked)); + form.addEventListener("submit", save); +} + +function fill(values) { + for (const name of FIELDS) { + const field = form.elements[name]; + if (name === "visibility") { + form.querySelector(`input[name=visibility][value="${values.visibility}"]`).checked = true; + } else if (field.type === "checkbox") { + field.checked = Boolean(values[name]); + } else { + field.value = values[name] ?? ""; + } + } + document.getElementById("handle").textContent = values.handle; + replace( + document.getElementById("profile-link"), + "Your public profile page: ", + h("a", { href: values.profile_url }, values.profile_url.replace(/^https?:\/\//, "")), + ); + showHandle(values.enabled); +} + +function showHandle(on) { + handlePanel.hidden = !on; +} + +async function save(event) { + event.preventDefault(); + const button = form.querySelector("button[type=submit]"); + const changes = { + enabled: form.elements.enabled.checked, + visibility: form.querySelector("input[name=visibility]:checked").value, + manually_approves_followers: form.elements.manually_approves_followers.checked, + discoverable: form.elements.discoverable.checked, + indexable: form.elements.indexable.checked, + display_name: form.elements.display_name.value.trim() || null, + bio: form.elements.bio.value.trim() || null, + }; + const status = document.getElementById("save-status"); + button.disabled = true; + status.textContent = "Saving"; + replace(messages); + try { + const saved = await api("/federation/settings", { method: "PATCH", body: changes }); + fill(saved); + status.textContent = saved.enabled ? `Saved. You're sharing as ${saved.handle}.` : "Saved. Sharing is off."; + } catch (error) { + status.textContent = ""; + replace(messages, errorBox(describeError(error))); + messages.scrollIntoView({ behavior: "smooth", block: "start" }); + } finally { + button.disabled = false; + } +} diff --git a/frontend/profile.html b/frontend/profile.html new file mode 100644 index 0000000..8ebfc48 --- /dev/null +++ b/frontend/profile.html @@ -0,0 +1,18 @@ + + + + + + Profile · Scrobbler + + + + + + + +
+
+
+ + diff --git a/frontend/sharing.html b/frontend/sharing.html new file mode 100644 index 0000000..d220ec5 --- /dev/null +++ b/frontend/sharing.html @@ -0,0 +1,84 @@ + + + + + + Sharing · Scrobbler + + + + + + + +
+

Sharing

+

Let people on Mastodon and other fediverse apps follow your listening.

+
+ +
+ + From 8d12922f6a4264d9983f92a3689191459bc98d5c Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 20:32:40 +0100 Subject: [PATCH 15/56] Serve fediverse paths on the UI's domain (phase 1, step 6) - The UI container forwards /.well-known/{webfinger,nodeinfo,host-meta}, /nodeinfo/, /users/, /inbox and /actor to API_INTERNAL_URL (compose: http://api:8000), passing Host and X-Forwarded-*; unset means no forwarding - The API's name is resolved per request via the container's resolver, so the UI starts before the API and survives API restarts - Compose passes the FEDERATION_* settings to api and worker; .env.example documents them, including FEDERATION_KEY_SECRET - gunicorn: disable the 26.x control socket (the container user has no home directory) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- .env.example | 3 +++ deploy/nginx/default.conf.template | 9 ++++++++ docker-compose.yml | 10 +++++++++ docker/ui-config.sh | 35 +++++++++++++++++++++++++++++- gunicorn.conf.py | 2 ++ 5 files changed, 58 insertions(+), 1 deletion(-) diff --git a/.env.example b/.env.example index 149253d..0d614b5 100644 --- a/.env.example +++ b/.env.example @@ -24,6 +24,9 @@ GRAFANA_PORT=3000 GRAFANA_ADMIN_PASSWORD=admin # ActivityPub federation (in development; off by default). See src/scrobbler/federation/README.md. +# Use the web UI's host and origin: handles become @user@. FEDERATION_ENABLED=0 FEDERATION_DOMAIN= FEDERATION_BASE_URL= +# 32+ characters; encrypts actors' private keys. Keep it safe and never change it. +FEDERATION_KEY_SECRET= diff --git a/deploy/nginx/default.conf.template b/deploy/nginx/default.conf.template index 9b8ef32..b128334 100644 --- a/deploy/nginx/default.conf.template +++ b/deploy/nginx/default.conf.template @@ -1,4 +1,10 @@ # Rendered by the nginx image's envsubst step (API_BASE_URL comes from the environment). + +# Behind a TLS proxy, keep its scheme; otherwise use ours. +map $http_x_forwarded_proto $scrobbler_forwarded_proto { + default $http_x_forwarded_proto; + "" $scheme; +} server { listen 80; server_name _; @@ -17,6 +23,9 @@ server { add_header Referrer-Policy same-origin always; } + # Fediverse paths forwarded to the API (written at start-up; empty if API_INTERNAL_URL is unset). + include /etc/nginx/scrobbler/federation.conf; + location /fonts/ { add_header Cache-Control "public, max-age=2592000, immutable"; } diff --git a/docker-compose.yml b/docker-compose.yml index c9cfe75..adadcb7 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -34,6 +34,10 @@ services: WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2} FORWARDED_ALLOW_IPS: "*" LASTFM_API_KEY: ${LASTFM_API_KEY:-} + FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0} + FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-} + FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-} + FEDERATION_KEY_SECRET: ${FEDERATION_KEY_SECRET:-} ports: - "${API_PORT:-5050}:8000" expose: @@ -53,6 +57,10 @@ services: DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler SECRET_KEY: ${SECRET_KEY:-change-me} LASTFM_API_KEY: ${LASTFM_API_KEY:-} + FEDERATION_ENABLED: ${FEDERATION_ENABLED:-0} + FEDERATION_DOMAIN: ${FEDERATION_DOMAIN:-} + FEDERATION_BASE_URL: ${FEDERATION_BASE_URL:-} + FEDERATION_KEY_SECRET: ${FEDERATION_KEY_SECRET:-} RUN_MIGRATIONS: "0" # the api service applies them expose: - "9101" # metrics: internal network only @@ -69,6 +77,8 @@ services: dockerfile: docker/ui.Dockerfile environment: API_BASE_URL: ${API_BASE_URL:-http://localhost:5050} + # Forward the fediverse paths (/.well-known/webfinger, /users/, /inbox, ...) to the API. + API_INTERNAL_URL: ${API_INTERNAL_URL:-http://api:8000} ports: - "${UI_PORT:-8080}:80" diff --git a/docker/ui-config.sh b/docker/ui-config.sh index 0595b80..53184c8 100755 --- a/docker/ui-config.sh +++ b/docker/ui-config.sh @@ -1,5 +1,6 @@ #!/bin/sh -# Point the UI at the API: rewrite config.js from $API_BASE_URL at container start. +# Container start-up: point the UI at the API, and (when API_INTERNAL_URL is set) +# forward the fediverse paths on this domain to the API. set -e case "$API_BASE_URL" in http://*|https://*) ;; @@ -11,3 +12,35 @@ window.SCROBBLER_CONFIG = { apiBaseUrl: "$url", }; JS + +mkdir -p /etc/nginx/scrobbler +if [ -z "$API_INTERNAL_URL" ]; then + : > /etc/nginx/scrobbler/federation.conf + exit 0 +fi +case "$API_INTERNAL_URL" in + http://*|https://*) ;; + *) echo "API_INTERNAL_URL must look like http://api:8000" >&2; exit 1 ;; +esac +upstream=$(printf '%s' "$API_INTERNAL_URL" | sed 's#/*$##') +case "$upstream" in + *://*/*) echo "API_INTERNAL_URL must not have a path" >&2; exit 1 ;; +esac +# Resolve the API's name per request (not once at start-up), so the UI starts even if +# the API isn't up yet and keeps working when the API container is replaced. +nameserver=$(awk '/^nameserver/ { print $2; exit }' /etc/resolv.conf) +case "$nameserver" in *:*) nameserver="[$nameserver]" ;; esac +cat > /etc/nginx/scrobbler/federation.conf < Date: Fri, 25 Sep 2026 20:34:23 +0100 Subject: [PATCH 16/56] Tests don't inherit optional features from the local environment TestConfig pins FEDERATION_ENABLED off and LASTFM_API_KEY empty, so a developer's .env (e.g. federation switched on to try it locally) can't change what the "feature off" tests see. Tests that need a feature turn it on explicitly (FederatedTestConfig, lastfm_config). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/config.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/scrobbler/config.py b/src/scrobbler/config.py index b29ad68..667c759 100644 --- a/src/scrobbler/config.py +++ b/src/scrobbler/config.py @@ -76,3 +76,7 @@ class TestConfig(Config): "postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test", ) START_METRICS_SERVER = False + # Tests never inherit optional features from a developer's .env or environment; + # tests that need them turn them on explicitly. + LASTFM_API_KEY = "" + FEDERATION_ENABLED = "0" From 913ef67aca1ceb7de54c3cff92ddd2e76c6c26bd Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 20:36:42 +0100 Subject: [PATCH 17/56] Federation dashboard (phase 1, step 7) A fifth provisioned Grafana dashboard: fediverse lookups by kind and result, sharing switched on/off, federation endpoint rates and p95 latency, and inbox deliveries. Dashboard tests now know federation's own metrics, and a new test rejects PromQL string escapes Prometheus can't parse (the endpoint filter first used \. and failed live). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- deploy/grafana/dashboards/federation.json | 327 ++++++++++++++++++++++ tests/test_dashboards.py | 23 +- 2 files changed, 347 insertions(+), 3 deletions(-) create mode 100644 deploy/grafana/dashboards/federation.json diff --git a/deploy/grafana/dashboards/federation.json b/deploy/grafana/dashboards/federation.json new file mode 100644 index 0000000..f075cb5 --- /dev/null +++ b/deploy/grafana/dashboards/federation.json @@ -0,0 +1,327 @@ +{ + "uid": "scrobbler-federation", + "title": "Scrobbler: Federation", + "description": "ActivityPub: how the fediverse finds and talks to users sharing their listening. Empty unless FEDERATION_ENABLED is on.", + "tags": [ + "scrobbler" + ], + "timezone": "browser", + "editable": true, + "graphTooltip": 1, + "refresh": "30s", + "time": { + "from": "now-6h", + "to": "now" + }, + "schemaVersion": 41, + "version": 1, + "templating": { + "list": [] + }, + "annotations": { + "list": [] + }, + "links": [ + { + "type": "dashboards", + "tags": [ + "scrobbler" + ], + "asDropdown": true, + "title": "Scrobbler", + "includeVars": false + } + ], + "panels": [ + { + "type": "row", + "title": "Discovery", + "id": 1, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 0, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Lookups / min by kind", + "description": "WebFinger, actor, NodeInfo and profile-page lookups. 'not_found' covers both unknown users and users not sharing.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (kind, result) (rate(scrobbler_federation_lookups_total[$__rate_interval])) * 60", + "legendFormat": "{{kind}} {{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 2, + "gridPos": { + "x": 0, + "y": 1, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Sharing switched on / off", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (change) (increase(scrobbler_federation_sharing_changes_total[$__rate_interval]))", + "legendFormat": "{{change}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 1, + "fillOpacity": 70, + "showPoints": "never", + "spanNulls": true, + "drawStyle": "bars" + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 3, + "gridPos": { + "x": 12, + "y": 1, + "w": 12, + "h": 8 + } + }, + { + "type": "row", + "title": "Traffic", + "id": 4, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 9, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Federation requests / s by endpoint", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (endpoint) (rate(scrobbler_http_requests_total{endpoint=~\"(federation|Federation)[.].*\"}[$__rate_interval]))", + "legendFormat": "{{endpoint}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "reqps", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 5, + "gridPos": { + "x": 0, + "y": 10, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "p95 latency by endpoint", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le, endpoint) (rate(scrobbler_http_request_duration_seconds_bucket{endpoint=~\"(federation|Federation)[.].*\"}[$__rate_interval])))", + "legendFormat": "{{endpoint}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 6, + "gridPos": { + "x": 12, + "y": 10, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Inbox deliveries / min", + "description": "Activities other servers send us (follows, likes, ...). Accepted but not yet processed until following is implemented.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (inbox) (rate(scrobbler_federation_inbox_requests_total[$__rate_interval])) * 60", + "legendFormat": "{{inbox}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 7, + "gridPos": { + "x": 0, + "y": 18, + "w": 24, + "h": 7 + } + } + ] +} diff --git a/tests/test_dashboards.py b/tests/test_dashboards.py index f2cbc02..339138a 100644 --- a/tests/test_dashboards.py +++ b/tests/test_dashboards.py @@ -7,6 +7,7 @@ import yaml from prometheus_client.metrics import MetricWrapperBase from scrobbler import metrics +from scrobbler.federation import metrics as federation_metrics DEPLOY = Path(__file__).resolve().parents[1] / "deploy" DASHBOARDS = sorted((DEPLOY / "grafana" / "dashboards").glob("*.json")) @@ -16,7 +17,8 @@ METRIC_NAME = re.compile(r"\bscrobbler_[a-z0-9_]+") def defined_series() -> set[str]: """Every series name the service can export.""" names = set(metrics.COLLECTED.values()) - for value in vars(metrics).values(): + modules = (metrics, federation_metrics) + for value in (v for module in modules for v in vars(module).values()): if not isinstance(value, MetricWrapperBase): continue name, kind = value._name, value._type @@ -41,8 +43,14 @@ def exprs(node): yield from exprs(item) -def test_there_are_four_dashboards(): - assert {p.stem for p in DASHBOARDS} == {"api-overview", "lastfm-api", "usage", "database"} +def test_the_expected_dashboards_exist(): + assert {p.stem for p in DASHBOARDS} == { + "api-overview", + "lastfm-api", + "usage", + "database", + "federation", + } def test_dashboard_uids_are_unique(): @@ -75,3 +83,12 @@ def test_alert_rules_only_use_defined_metrics(): for name in METRIC_NAME.findall(rule["expr"]) } assert used <= defined_series(), f"undefined metrics: {sorted(used - defined_series())}" + + +@pytest.mark.parametrize("path", DASHBOARDS, ids=lambda p: p.stem) +def test_queries_have_no_invalid_string_escapes(path): + """PromQL rejects escapes like \\. inside double-quoted strings (Grafana would show a + query error); use a character class such as [.] instead.""" + invalid = re.compile(r'(? Date: Fri, 25 Sep 2026 20:37:30 +0100 Subject: [PATCH 18/56] Document fediverse sharing; mark phase 1 done (phase 1, step 9) README: what sharing does today, how an operator enables it (settings, UI forwarding, HTTPS), and the permanence of handles and the key secret. Federation README: key secret, forwarded paths and module layout. The phase 1 plan is marked done, with the real-Mastodon check still outstanding. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- README.md | 18 ++++++++++++++++++ docs/design/activitypub-phase1.md | 2 ++ src/scrobbler/federation/README.md | 21 +++++++++++++++++++++ 3 files changed, 41 insertions(+) diff --git a/README.md b/README.md index b9b96a2..49b659c 100644 --- a/README.md +++ b/README.md @@ -92,6 +92,24 @@ Imports run in the background in the `worker` service. The page shows progress, Unlike live scrobbles, imports keep plays of any age. They still skip rows with no artist or track, and plays dated in the future. Plays already in your history are skipped, so importing again is safe. +## Sharing on the fediverse (in development) + +Users can make their profile findable from Mastodon and other fediverse apps as `@name@`. Following, and posts (weekly summaries, milestones, now playing), are still being built; see `docs/design/activitypub.md`. Until then, profiles advertise follower approval, so a follow waits as a request rather than failing. + +It's **off unless the server enables it**, and then **off for each user** until they switch it on under **Sharing**. To enable it: + +1. Set these on the API and worker: + - `FEDERATION_ENABLED=1` + - `FEDERATION_DOMAIN`: the UI's host, e.g. `scrobble.example` + - `FEDERATION_BASE_URL`: the UI's origin, e.g. `https://scrobble.example` + - `FEDERATION_KEY_SECRET`: 32 or more random characters +2. Give the UI container `API_INTERNAL_URL` (compose sets `http://api:8000`). It then forwards these paths to the API: `/.well-known/webfinger`, `/.well-known/nodeinfo`, `/.well-known/host-meta`, `/nodeinfo/`, `/users/`, `/inbox` and `/actor`. +3. Serve the UI over HTTPS on that domain. Other servers only talk to HTTPS. + +Handles and actor URLs **can't change once anyone follows** a user, so choose the domain carefully. + +`FEDERATION_KEY_SECRET` encrypts each user's signing key. **Back it up, and never change it**: losing it means users' keys can't be read, and followers would have to follow again. + ## Develop ```sh diff --git a/docs/design/activitypub-phase1.md b/docs/design/activitypub-phase1.md index 1cb98d4..4ef2dc0 100644 --- a/docs/design/activitypub-phase1.md +++ b/docs/design/activitypub-phase1.md @@ -1,5 +1,7 @@ # ActivityPub phase 1: discoverable profile +**Status: done** on `feature/activitypub` (`98c6554` … `913ef67`). The one gap is the manual check with a real Mastodon account through a tunnel: it's still to do, and needs a public HTTPS address. + This implements phase 1 of [activitypub.md](activitypub.md). Handles and actor URLs are on the **UI's domain**, and posts are **followers only by default** (a per-user setting). **Outcome:** once an operator enables federation, a user can switch on sharing, and searching `@alice@` from Mastodon finds their profile. Following needs phase 2 (the inbox and deliveries). Until then the actor advertises `manuallyApprovesFollowers: true`, so a follow shows as a pending request rather than failing silently. With federation off, nothing changes. diff --git a/src/scrobbler/federation/README.md b/src/scrobbler/federation/README.md index 1043ce3..130e183 100644 --- a/src/scrobbler/federation/README.md +++ b/src/scrobbler/federation/README.md @@ -31,6 +31,27 @@ or switched off without touching anything else. Design: `docs/design/activitypub | `FEDERATION_ENABLED` | `1` to turn federation on (default off) | | `FEDERATION_DOMAIN` | Handle domain, normally the web UI's host: users are `@name@`. **Permanent once anyone follows.** | | `FEDERATION_BASE_URL` | Public `https://` URL actors live under (`/users/`). Normally the web UI's origin, with the UI's nginx forwarding the ActivityPub paths to the API. | +| `FEDERATION_KEY_SECRET` | 32+ characters; encrypts actors' private keys at rest (HKDF → Fernet). **Back it up; never change it.** | + +The UI container forwards these paths to the API when `API_INTERNAL_URL` is set (see `docker/ui-config.sh`): + +- `/.well-known/webfinger`, `/.well-known/nodeinfo`, `/.well-known/host-meta` +- `/nodeinfo/`, `/users/`, `/inbox`, `/actor` + +Every ActivityPub ID is built from `FEDERATION_BASE_URL`, never from the incoming request. + +## Layout + +| Module | Holds | +|---|---| +| `protocol/` | Pure protocol code: media types, vocabulary, WebFinger, NodeInfo, host-meta | +| `models.py` | `federation_settings` and `federation_keys` | +| `keys.py` | Key pairs, created once and encrypted at rest | +| `sharing.py` | Per-user settings, and who is sharing | +| `web.py` | The endpoints other servers call | +| `api.py` and `schemas.py` | `/api/v1/federation/*` for the web UI | +| `openapi.py` | OpenAPI descriptions of `web.py`'s endpoints | +| `metrics.py` | Federation's own Prometheus metrics | ## Migrations From 044f25e2fdbc9cb85aa274096e53de264e555d51 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 20:56:59 +0100 Subject: [PATCH 19/56] Plan for ActivityPub phase 2 (followers) Step-by-step plan: both HTTP signature schemes with test vectors, an SSRF-safe outbound client and remote-actor cache, follower/inbox/ delivery tables, network-free inbox intake with worker processing, signed Accept/Reject/Block delivery with retries, follower management API and UI, metrics/alerts, in-process two-instance tests and a GoToSocial interop job in CI. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/design/activitypub-phase2.md | 206 ++++++++++++++++++++++++++++++ 1 file changed, 206 insertions(+) create mode 100644 docs/design/activitypub-phase2.md diff --git a/docs/design/activitypub-phase2.md b/docs/design/activitypub-phase2.md new file mode 100644 index 0000000..c157148 --- /dev/null +++ b/docs/design/activitypub-phase2.md @@ -0,0 +1,206 @@ +# ActivityPub phase 2: followers + +This implements phase 2 of [activitypub.md](activitypub.md), building on [phase 1](activitypub-phase1.md). + +**Outcome:** people on Mastodon, GoToSocial and similar servers can follow a user who shares. Follows are accepted automatically, or wait for the user's approval if they've turned it on. The user sees their followers and can approve, decline, remove or block them. Scrobbler signs everything it sends and checks the signature on everything it receives. Posts come in phase 3; this phase makes the relationship work end to end. + +Everything below is inside `scrobbler.federation`, and the boundary tests keep holding. Federation off still means nothing is registered. + +## 1. HTTP signatures (pure: `protocol/signatures/`) + +- **`base.py`**: + - A `SignedRequest` value (method, URL, headers, body). + - A `SignatureScheme` interface with `sign(request, key_id, private_key)` and `verify(request, public_key_for) -> VerifiedSignature` (the key ID used and the scheme). + - `SignatureError` carries a machine-readable reason: `missing`, `malformed`, `expired`, `digest_mismatch`, `bad_signature` or `unsupported`. + - A registry keyed by scheme name. +- **`draft_cavage.py`**: + - **Signing** (the header shapes are in [Mastodon's security spec](https://docs.joinmastodon.org/spec/security/)): + - `Signature: keyId="…",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="…"` + - `Digest: SHA-256=` for POSTs + - `(request-target)` is the lowercase method plus path and query. + - **Verification**: + - accepts `rsa-sha256` and `hs2019`, which means RSA when the key is RSA + - for POSTs, requires `(request-target)`, `host`, `date` and `digest` to be signed + - `Date` within ±12 hours + - the digest must match the body +- **`rfc9421.py`**: + - **Signing**: `Signature-Input: sig1=("@method" "@target-uri" "content-digest");created=…;keyid="…";alg="rsa-v1_5-sha256"`, with `Signature: sig1=:…:` and `Content-Digest: sha-256=::`. + - **Verification**: + - one signature + - `created` required and within the allowed skew + - `@method` and `@target-uri` covered, and `content-digest` too when there's a body + - A minimal parser for the RFC 8941 structured fields these headers use: inner lists, parameters and byte sequences. +- **Order**: + - Outgoing: `FEDERATION_SIGNATURE_SCHEMES` (default `draft-cavage,rfc9421`) sets the order schemes are tried. The first is used, and the next is tried only if a server answers 401, the same "double-knocking" Mastodon 4.7 does. + - Incoming: whichever scheme is present is verified. +- **Tests**: + - the published test vectors (draft-cavage appendix C; RFC 9421 appendix B for `rsa-v1_5-sha256`) + - sign-then-verify round trips for both schemes + - tampered body, method, path, date and headers + - expired and future dates, missing components, and a wrong key + +## 2. Safe outbound HTTP and remote actors + +- **New dependency**: `httpx` (BSD-3-Clause), for pooled clients, timeouts and response streaming. +- **`net.py`**, the only way federation code talks to other servers: + - **HTTPS only**. + - **SSRF protection**: a host's addresses are resolved once; the request is refused if any is loopback, private, link-local, multicast or otherwise reserved; and the connection goes to the checked address, using the original host name for SNI and `Host`. So a DNS change mid-request can't redirect it. + - At most 3 redirects, each checked the same way. + - Response bodies are capped at 1 MB. + - Timeouts: 10s to connect and 20s to read. + - A `User-Agent` of `Scrobbler/ (+)`. + - `signed_get(url, as_actor)`, which signs with the instance actor by default so "authorized fetch" servers answer; and `signed_post(inbox, activity, as_user)`. +- **`FEDERATION_INSECURE_TESTING=1`** is **for automated tests only**. It allows `http://` and private addresses. It's refused unless the domain ends in `.test` (a reserved top-level domain) and logs a warning every minute while on. It exists so CI can federate with GoToSocial on a private Docker network. +- **`remote.py`**: the remote-actor cache. + - `get_actor(uri, refresh=False)` fetches, validates and stores: the ID must equal the URI it was fetched from, the host must match, it must have an `inbox`, and `publicKey.owner` must equal the actor ID. + - `key_for(key_id)` maps a key ID (`…#main-key`, or a separate key document) to its owner and PEM. + - An actor is refreshed after 24 hours, or once immediately when a signature fails, in case the key was rotated. + +## 3. Data (migration on the `federation` branch) + +| Table | Holds | +|---|---| +| `federation_remote_actors` | URI, inbox, shared inbox, `preferredUsername`, host, display name, public key ID and PEM, `fetched_at`, `gone` | +| `federation_followers` | User, remote actor, state (`pending` or `accepted`), the Follow activity's ID and JSON, created and accepted times. Unique per user and actor. | +| `federation_blocks` | User and remote actor, or a whole domain. Operator domain blocks come from `FEDERATION_BLOCKED_DOMAINS`, not this table. | +| `federation_inbox` | Received deliveries: raw headers (a fixed allow-list), body, the inbox path, `received_at`, status (`queued`, `processed`, `rejected` or `failed`), reason, and the activity ID (unique, for deduplication). Pruned after 30 days. | +| `federation_activities` | Activities we send: UUID, user, type, JSON, and `created_at`. Dereferenceable at `/activities/` when public, so it can be the outbox's source in phase 3. | +| `federation_deliveries` | Activity × inbox: status (`pending`, `delivered`, `failed` or `abandoned`), `attempts`, `next_attempt_at`, the last status code and error | + +## 4. Inbox intake (`web.py`) and processing (a worker task) + +- **Intake stays network-free.** `POST /inbox` and `POST /users//inbox` check the size (256 KB), the content type and that the JSON has `type`, `actor` and `id`, then store the delivery and answer **202**. + - Deliveries from blocked domains are refused with 403. + - Repeated activity IDs are acknowledged but not stored again. + - The UI's nginx rate-limits the inbox paths per client IP (`limit_req`), as a first defence. +- **The `federation.inbox` worker task** processes queued deliveries, oldest first: + 1. **Check the signature** with the scheme present, fetching the key through `remote.key_for`. + - On failure, it refreshes the actor once and retries. + - Then it rejects with a reason, which is counted in metrics. + 2. **Check it's who they say.** The signing key's owner must equal the activity's `actor`, and the activity ID's host must equal the actor's host. + 3. **Dispatch** to a handler registered by activity type: + +| Activity | Handling | +|---|---| +| `Follow` (object = a sharing user) | Store the follower. If manual approval is on, keep it `pending`; otherwise mark it `accepted` and queue an `Accept`. If already accepted (a repeat Follow), queue an `Accept` again. | +| `Undo` of a `Follow` | Remove the follower. The Undo must come from the same actor as the Follow. | +| `Delete` of an actor | Remove it from every user's followers and mark the cached actor gone. | +| `Update` of a `Person` or `Service` | Refresh the cached actor. | +| `Accept` or `Reject` | Recorded; nothing to do until we follow people. | +| `Like`, `Announce`, `Create` | Recorded for metrics only. | +| Anything else | Recorded as unsupported. | + +- **A delivery that errors unexpectedly** is retried twice and then marked `failed` with the error. The worker never stops over it. + +## 5. Sending: activities and deliveries + +- `activities.py` builds and stores our activities: + - **`Accept(Follow)`**: the object is the original Follow, embedded. + - **`Reject(Follow)`**: used both to decline a request and to remove an existing follower. Mastodon drops the relationship on either. + - **`Block`**: sent when a user blocks a follower. +- **Fan-out** turns an activity into delivery rows, one per distinct inbox. Replies to a Follow go to the follower's own inbox. +- **The `federation.deliver` worker task**: + - Sends pending deliveries whose time has come, with signed POSTs through `net.signed_post`, trying the next scheme on a 401. + - **Retries**: 1m, 5m, 30m, 2h, 6h, then every 12h, **abandoning after 2 days**. + - No retry after a 4xx, except 401, 408 and 429. + - **410 Gone** from an actor's inbox removes that follower. + - It runs several deliveries at once (a bounded thread pool, default 4) and processes at most 50 per pass, so the worker stays responsive. +- **Actor changes**: + - The actor now reflects the user's real `manually_approves_followers` setting; phase 1 always said true. + - The followers collection's `totalItems` is the accepted-follower count. +- **Turning sharing off** queues a `Reject` for every follower, then removes them. + +## 6. Managing followers (API and UI) + +- **API** (bearer auth, under `/api/v1/federation`, documented in OpenAPI): + - `GET /followers?state=accepted|pending`, returning handle, display name, actor URL, server and since when. + - `POST /followers/{id}/approve`, which sends `Accept`. + - `POST /followers/{id}/decline` and `POST /followers/{id}/remove`, which send `Reject`. + - `POST /followers/{id}/block`, which sends `Block` and remembers it. + - `GET /blocks` and `DELETE /blocks/{id}` to see and undo blocks. Unblocking doesn't restore the follow. + - The settings response gains accepted and pending follower counts. +- **UI**: + - A new `followers.html` shows requests (Approve / Decline) above followers (Remove / Block, each with a confirm step), and blocked accounts at the bottom. + - Remote names are shown **as plain text only**; no remote HTML or images in this phase. + - The Sharing page shows the follower count and links to the Followers page. + - The "following arrives later" note goes. + +## 7. Configuration + +| Variable | Meaning | +|---|---| +| `FEDERATION_SIGNATURE_SCHEMES` | Outgoing order; default `draft-cavage,rfc9421` | +| `FEDERATION_BLOCKED_DOMAINS` | Comma-separated domains (subdomains included) whose deliveries are refused and whose follows are rejected | +| `FEDERATION_DELIVERY_CONCURRENCY` | Parallel deliveries in the worker (default 4) | +| `FEDERATION_INSECURE_TESTING` | Tests only; see §2 | + +## 8. Metrics, dashboard and alerts + +- **Metrics**: + - `scrobbler_federation_inbox_activities_total{type,result}`, where result is `processed`, `rejected`, `duplicate`, `blocked` or `failed` + - `scrobbler_federation_signatures_total{direction,scheme,result}`, where result is `ok` or a `SignatureError` reason + - `scrobbler_federation_deliveries_total{result}`: `delivered`, `retry`, `abandoned`, `gone` + - `scrobbler_federation_delivery_seconds` (a histogram) + - `scrobbler_federation_queue{queue,status}`, a gauge set by the worker for the inbox and delivery queues + - `scrobbler_federation_followers{state}`, a gauge set by the worker +- **Federation dashboard** gains: + - inbox activity by type and result + - signature failures by reason + - delivery outcomes and latency + - queue depths + - follower totals +- **Alerts**: + - `FederationDeliveryBacklog`: more than 100 pending deliveries for 30 minutes + - `FederationInboxBacklog`: queued inbox items for 15 minutes + - `FederationSignatureFailures`: more than 20% of incoming signatures failing for 15 minutes + +## 9. Tests + +- **Unit tests**: + - signatures (§1) + - the SSRF guard: private and reserved IPs, `http`, redirects to private addresses, the oversized-body cap and timeouts + - remote-actor validation: ID mismatch, key owner mismatch, a missing inbox + - each inbox handler + - the retry schedule and 4xx/410 handling + - addressing +- **In-process federation**: two federation-enabled apps with different `.test` domains serving each other over real HTTP in the test process, with insecure testing on. Scripted remote actors cover the full path: follow → signature check → Accept delivered and verified by the "remote" → Undo. Also covered: + - manual approval + - decline, remove and block + - repeat Follow + - bad signatures rejected with the right reason + - a blocked domain + - turning sharing off +- **A real peer in CI**: a new `federation-interop` job runs Scrobbler (API, worker and UI) and a GoToSocial container on one Docker network. The hosts are `scrobble.test` and `gts.test`, over HTTP, with each side's test-only settings. A script: + 1. creates a GoToSocial user with its admin CLI, + 2. gets a user token by driving GoToSocial's sign-in and OAuth screens with plain HTTP (this part gets a short spike first, since GoToSocial has no password grant), + 3. follows `@alice@scrobble.test`, and checks it's accepted, + 4. unfollows, and checks it's gone, + 5. with manual approval on, checks the request waits until approved through Scrobbler's API. + + The job posts to ntfy like every other job. It doesn't run on pull requests from forks. +- **Manual pass before merging**: follow and unfollow from a real Mastodon account through a tunnel. + +## 10. Docs + +- Update the README and the federation README: following now works, the new settings, and the operator domain blocks. +- Regenerate the OpenAPI export. +- Mark this plan done. + +## Order of work (a commit per step once its tests pass) + +1. Signatures, pure, with test vectors +2. `net.py` and the remote-actor cache +3. Tables and migration +4. Inbox intake and processing, with handlers +5. Outgoing activities and the delivery task +6. Follower management API and UI; the actor reflects the approval setting; turning sharing off +7. Metrics, dashboard and alerts +8. In-process federation tests, and the GoToSocial CI job +9. Docs + +## Notes + +- **Licences**: + - `httpx` is BSD-3-Clause and `cryptography` is Apache-2.0/BSD. + - GoToSocial is AGPL, but it runs only as a separate container in CI to test against. Nothing of it is linked into, or shipped with, Scrobbler, so it has no effect on Scrobbler's licence. +- **Scale**: this is the biggest phase, and signatures plus safe outbound HTTP are where the risk lies. They come first and have the most thorough tests. From a6d3fb6c93c16b80ba6dd135cd96c49b648de3ad Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 21:15:36 +0100 Subject: [PATCH 20/56] HTTP signatures: draft-cavage and RFC 9421 (phase 2, step 1) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Pure code in federation/protocol/signatures, one module per scheme and a registry to pick them by name: - draft-cavage: sign (request-target) host date digest with rsa-sha256; verify rsa-sha256/hs2019, require the ActivityPub minimum, check Digest and a ±12h Date window - RFC 9421: sign @method @target-uri content-digest with rsa-v1_5-sha256 and created/keyid/alg; verify with a generic signature-base builder, created/expires checks and Content-Digest (sha-256/sha-512); includes the RFC 8941 subset these headers use - Failures carry a reason (missing, malformed, expired, digest_mismatch, bad_signature, unsupported, unknown_key, insufficient) for metrics Tested against the published vectors (draft-cavage-12 C.1 and C.2, RFC 9421's rsa-v1_5-sha256 example; test keys extracted from the specs into tests/data), round trips, and tampering with body, URL, method, date, key, coverage and clock. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- .../protocol/signatures/__init__.py | 61 ++++ .../federation/protocol/signatures/base.py | 108 ++++++ .../protocol/signatures/draft_cavage.py | 158 +++++++++ .../federation/protocol/signatures/rfc9421.py | 328 ++++++++++++++++++ tests/data/draft-cavage-test-key.pem | 15 + tests/data/rfc9421-test-key-rsa.pem | 27 ++ tests/test_federation_signatures.py | 274 +++++++++++++++ 7 files changed, 971 insertions(+) create mode 100644 src/scrobbler/federation/protocol/signatures/__init__.py create mode 100644 src/scrobbler/federation/protocol/signatures/base.py create mode 100644 src/scrobbler/federation/protocol/signatures/draft_cavage.py create mode 100644 src/scrobbler/federation/protocol/signatures/rfc9421.py create mode 100644 tests/data/draft-cavage-test-key.pem create mode 100644 tests/data/rfc9421-test-key-rsa.pem create mode 100644 tests/test_federation_signatures.py diff --git a/src/scrobbler/federation/protocol/signatures/__init__.py b/src/scrobbler/federation/protocol/signatures/__init__.py new file mode 100644 index 0000000..0b85dd6 --- /dev/null +++ b/src/scrobbler/federation/protocol/signatures/__init__.py @@ -0,0 +1,61 @@ +"""HTTP signatures for ActivityPub: one module per scheme, chosen by name. + + verify(request, public_key_for) whichever scheme the request carries + sign(request, scheme, key_id, key) headers to add, using the named scheme + +Adding or dropping a scheme is a module here plus an entry in SCHEMES. +""" + +from datetime import UTC, datetime + +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey + +from scrobbler.federation.protocol.signatures.base import ( + PublicKeyFor, + SignatureError, + SignatureScheme, + SignedRequest, + VerifiedSignature, +) +from scrobbler.federation.protocol.signatures.draft_cavage import DraftCavage +from scrobbler.federation.protocol.signatures.rfc9421 import Rfc9421 + +SCHEMES: dict[str, SignatureScheme] = {s.name: s for s in (Rfc9421(), DraftCavage())} + +__all__ = [ + "SCHEMES", + "PublicKeyFor", + "SignatureError", + "SignedRequest", + "VerifiedSignature", + "detect", + "sign", + "verify", +] + + +def detect(request: SignedRequest) -> SignatureScheme: + for scheme in SCHEMES.values(): # RFC 9421 first: its Signature header differs + if scheme.present(request): + return scheme + raise SignatureError("missing") + + +def verify( + request: SignedRequest, public_key_for: PublicKeyFor, now: datetime | None = None +) -> VerifiedSignature: + return detect(request).verify(request, public_key_for, now or datetime.now(UTC)) + + +def sign( + request: SignedRequest, + scheme: str, + key_id: str, + private_key: RSAPrivateKey, + now: datetime | None = None, +) -> dict[str, str]: + try: + chosen = SCHEMES[scheme] + except KeyError: + raise SignatureError("unsupported", f"scheme {scheme}") from None + return chosen.sign(request, key_id, private_key, now or datetime.now(UTC)) diff --git a/src/scrobbler/federation/protocol/signatures/base.py b/src/scrobbler/federation/protocol/signatures/base.py new file mode 100644 index 0000000..3fe5b79 --- /dev/null +++ b/src/scrobbler/federation/protocol/signatures/base.py @@ -0,0 +1,108 @@ +"""Shared pieces of the HTTP signature schemes.""" + +import base64 +import hashlib +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field +from datetime import datetime, timedelta +from urllib.parse import urlsplit + +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey, RSAPublicKey + +MAX_SKEW = timedelta(hours=12) # Mastodon's window + + +class SignatureError(Exception): + """Why a signature couldn't be verified: a short, metric-friendly reason.""" + + REASONS = ( + "missing", + "malformed", + "expired", + "digest_mismatch", + "bad_signature", + "unsupported", + "unknown_key", + "insufficient", # doesn't cover what we require + ) + + def __init__(self, reason: str, detail: str = ""): + assert reason in self.REASONS, reason + self.reason = reason + super().__init__(f"{reason}: {detail}" if detail else reason) + + +@dataclass(frozen=True) +class SignedRequest: + """An HTTP request, as signed or as received.""" + + method: str + url: str # absolute, as the signer addressed it + headers: Mapping[str, str] = field(default_factory=dict) + body: bytes = b"" + + def header(self, name: str) -> str | None: + name = name.lower() + for key, value in self.headers.items(): + if key.lower() == name: + return value + return None + + @property + def path_and_query(self) -> str: + parts = urlsplit(self.url) + return (parts.path or "/") + (f"?{parts.query}" if parts.query else "") + + @property + def host(self) -> str: + return urlsplit(self.url).netloc.lower() + + +@dataclass(frozen=True) +class VerifiedSignature: + scheme: str + key_id: str + + +# key id -> the public key it names (None if it can't be found) +PublicKeyFor = Callable[[str], RSAPublicKey | None] + + +def b64(data: bytes) -> str: + return base64.b64encode(data).decode() + + +def unb64(text: str) -> bytes: + try: + return base64.b64decode(text, validate=True) + except (ValueError, TypeError) as err: + raise SignatureError("malformed", "bad base64") from err + + +def sha256(body: bytes) -> bytes: + return hashlib.sha256(body).digest() + + +def check_time(when: datetime, now: datetime, max_skew: timedelta = MAX_SKEW) -> None: + if abs(now - when) > max_skew: + raise SignatureError("expired", f"signed at {when.isoformat()}") + + +class SignatureScheme: + """Interface each scheme implements.""" + + name: str + + def present(self, request: SignedRequest) -> bool: # pragma: no cover - interface + raise NotImplementedError + + def sign( + self, request: SignedRequest, key_id: str, private_key: RSAPrivateKey, now: datetime + ) -> dict[str, str]: # pragma: no cover - interface + """Headers to add to the request.""" + raise NotImplementedError + + def verify( + self, request: SignedRequest, public_key_for: PublicKeyFor, now: datetime + ) -> VerifiedSignature: # pragma: no cover - interface + raise NotImplementedError diff --git a/src/scrobbler/federation/protocol/signatures/draft_cavage.py b/src/scrobbler/federation/protocol/signatures/draft_cavage.py new file mode 100644 index 0000000..6d3e279 --- /dev/null +++ b/src/scrobbler/federation/protocol/signatures/draft_cavage.py @@ -0,0 +1,158 @@ +"""draft-cavage-http-signatures (version 12): what most of the fediverse still uses. + +Signature: keyId="…",algorithm="rsa-sha256",headers="(request-target) host date digest", + signature="" +""" + +import re +from datetime import UTC, datetime +from email.utils import format_datetime, parsedate_to_datetime + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import padding +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey + +from scrobbler.federation.protocol.signatures.base import ( + PublicKeyFor, + SignatureError, + SignatureScheme, + SignedRequest, + VerifiedSignature, + b64, + check_time, + sha256, + unb64, +) + +NAME = "draft-cavage" +_PARAM = re.compile(r'\s*([a-zA-Z]+)\s*=\s*"([^"]*)"\s*(?:,|$)') +_ALGORITHMS = {"rsa-sha256", "hs2019"} # hs2019: "derive from the key"; ours are RSA +SIGN_GET = ("(request-target)", "host", "date") +SIGN_POST = ("(request-target)", "host", "date", "digest") + + +def _signature_header(request: SignedRequest) -> str | None: + value = request.header("signature") + if value: + return value + authorization = request.header("authorization") or "" + if authorization[:10].lower() == "signature ": + return authorization[10:] + return None + + +def parse(value: str) -> dict[str, str]: + params, position = {}, 0 + while position < len(value): + match = _PARAM.match(value, position) + if not match or match.end() == position: + raise SignatureError("malformed", "unparseable Signature header") + params[match.group(1)] = match.group(2) + position = match.end() + if "keyId" not in params or "signature" not in params: + raise SignatureError("malformed", "keyId and signature are required") + return params + + +def signing_string(request: SignedRequest, headers: list[str], params: dict[str, str]) -> str: + lines = [] + for name in headers: + if name == "(request-target)": + value = f"{request.method.lower()} {request.path_and_query}" + elif name in ("(created)", "(expires)"): + value = params.get(name[1:-1]) + if value is None: + raise SignatureError("malformed", f"{name} signed but not given") + else: + value = request.header(name) + if value is None: + raise SignatureError("malformed", f"signed header {name} is missing") + lines.append(f"{name}: {value.strip()}") + return "\n".join(lines) + + +def digest_header(body: bytes) -> str: + return f"SHA-256={b64(sha256(body))}" + + +def check_digest(request: SignedRequest) -> None: + header = request.header("digest") + if not header: + raise SignatureError("insufficient", "no Digest header") + for part in header.split(","): + algorithm, _, value = part.strip().partition("=") + if algorithm.lower() == "sha-256": + if unb64(value) != sha256(request.body): + raise SignatureError("digest_mismatch") + return + raise SignatureError("unsupported", "no SHA-256 digest") + + +class DraftCavage(SignatureScheme): + name = NAME + + def present(self, request: SignedRequest) -> bool: + return _signature_header(request) is not None and request.header("signature-input") is None + + def sign( + self, request: SignedRequest, key_id: str, private_key: RSAPrivateKey, now: datetime + ) -> dict[str, str]: + added = {"Host": request.host, "Date": format_datetime(now.astimezone(UTC), usegmt=True)} + headers = SIGN_GET + if request.body or request.method.upper() == "POST": + added["Digest"] = digest_header(request.body) + headers = SIGN_POST + signing = SignedRequest( + request.method, request.url, {**request.headers, **added}, request.body + ) + base = signing_string(signing, list(headers), {}) + signature = private_key.sign(base.encode(), padding.PKCS1v15(), hashes.SHA256()) + added["Signature"] = ( + f'keyId="{key_id}",algorithm="rsa-sha256",headers="{" ".join(headers)}",' + f'signature="{b64(signature)}"' + ) + return added + + def verify( + self, + request: SignedRequest, + public_key_for: PublicKeyFor, + now: datetime, + require: tuple[str, ...] | None = None, + ) -> VerifiedSignature: + """Verify the signature. `require` lists the headers that must be covered; + by default the ActivityPub minimum for the request's method.""" + header = _signature_header(request) + if header is None: + raise SignatureError("missing") + params = parse(header) + algorithm = params.get("algorithm", "hs2019").lower() + if algorithm not in _ALGORITHMS: + raise SignatureError("unsupported", f"algorithm {algorithm}") + headers = params.get("headers", "date").lower().split() + + if require is None: + require = SIGN_POST if request.method.upper() == "POST" else SIGN_GET + missing = set(require) - set(headers) + if missing: + raise SignatureError("insufficient", f"not signed: {sorted(missing)}") + if "digest" in headers: + check_digest(request) + if "date" in headers: + try: + check_time(parsedate_to_datetime(request.header("date") or ""), now) + except (TypeError, ValueError) as err: + raise SignatureError("malformed", "bad Date header") from err + + key = public_key_for(params["keyId"]) + if key is None: + raise SignatureError("unknown_key", params["keyId"]) + base = signing_string(request, headers, params) + try: + key.verify( + unb64(params["signature"]), base.encode(), padding.PKCS1v15(), hashes.SHA256() + ) + except InvalidSignature as err: + raise SignatureError("bad_signature") from err + return VerifiedSignature(NAME, params["keyId"]) diff --git a/src/scrobbler/federation/protocol/signatures/rfc9421.py b/src/scrobbler/federation/protocol/signatures/rfc9421.py new file mode 100644 index 0000000..4c2a1de --- /dev/null +++ b/src/scrobbler/federation/protocol/signatures/rfc9421.py @@ -0,0 +1,328 @@ +"""RFC 9421 HTTP Message Signatures, as Mastodon 4.5+ accepts and 4.7+ sends them. + +Signature-Input: sig1=("@method" "@target-uri" "content-digest");created=…;keyid="…" +Signature: sig1=:: +Content-Digest: sha-256=:: + +Includes the small part of RFC 8941 (structured fields) these headers use. +""" + +import hashlib +from dataclasses import dataclass +from datetime import UTC, datetime +from urllib.parse import urlsplit + +from cryptography.exceptions import InvalidSignature +from cryptography.hazmat.primitives import hashes +from cryptography.hazmat.primitives.asymmetric import padding +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPrivateKey + +from scrobbler.federation.protocol.signatures.base import ( + PublicKeyFor, + SignatureError, + SignatureScheme, + SignedRequest, + VerifiedSignature, + b64, + check_time, + unb64, +) + +NAME = "rfc9421" +ALGORITHM = "rsa-v1_5-sha256" +LABEL = "sig1" + +# --- RFC 8941 structured fields (the subset used here) -------------------------------- + + +@dataclass(frozen=True) +class Item: + value: object # str (string or token), int, bool or bytes + params: tuple[tuple[str, object], ...] = () + + +@dataclass(frozen=True) +class InnerList: + items: tuple[Item, ...] + params: tuple[tuple[str, object], ...] = () + + +class _Parser: + def __init__(self, text: str): + self.text, self.pos = text, 0 + + def error(self, message: str): + return SignatureError("malformed", f"{message} at {self.pos}") + + def peek(self) -> str: + return self.text[self.pos] if self.pos < len(self.text) else "" + + def skip(self, chars: str = " \t") -> None: + while self.peek() and self.peek() in chars: + self.pos += 1 + + def key(self) -> str: + start = self.pos + if not (self.peek().islower() or self.peek() == "*"): + raise self.error("expected a key") + while self.peek() and ( + self.peek().islower() or self.peek().isdigit() or self.peek() in "_-.*" + ): + self.pos += 1 + return self.text[start : self.pos] + + def bare_item(self) -> object: + char = self.peek() + if char == '"': + self.pos += 1 + out = [] + while True: + char = self.peek() + if not char: + raise self.error("unterminated string") + self.pos += 1 + if char == "\\": + out.append(self.peek()) + self.pos += 1 + elif char == '"': + return "".join(out) + else: + out.append(char) + if char == ":": + end = self.text.find(":", self.pos + 1) + if end < 0: + raise self.error("unterminated byte sequence") + value = unb64(self.text[self.pos + 1 : end]) + self.pos = end + 1 + return value + if char == "?": + self.pos += 2 + return self.text[self.pos - 1] == "1" + if char == "-" or char.isdigit(): + start = self.pos + self.pos += 1 + while self.peek().isdigit(): + self.pos += 1 + return int(self.text[start : self.pos]) + if char.isalpha() or char == "*": # token + start = self.pos + while self.peek() and self.peek() not in ' \t,;()"=': + self.pos += 1 + return self.text[start : self.pos] + raise self.error("unexpected character") + + def params(self) -> tuple[tuple[str, object], ...]: + out = [] + while self.peek() == ";": + self.pos += 1 + self.skip(" ") + name = self.key() + value: object = True + if self.peek() == "=": + self.pos += 1 + value = self.bare_item() + out.append((name, value)) + return tuple(out) + + def item_or_inner_list(self) -> Item | InnerList: + if self.peek() == "(": + self.pos += 1 + items = [] + while True: + self.skip(" ") + if self.peek() == ")": + self.pos += 1 + return InnerList(tuple(items), self.params()) + items.append(Item(self.bare_item(), self.params())) + if self.peek() not in " )": + raise self.error("bad inner list") + return Item(self.bare_item(), self.params()) + + def dictionary(self) -> dict[str, Item | InnerList]: + out: dict[str, Item | InnerList] = {} + self.skip() + while self.peek(): + name = self.key() + if self.peek() == "=": + self.pos += 1 + out[name] = self.item_or_inner_list() + else: + out[name] = Item(True, self.params()) + self.skip() + if not self.peek(): + break + if self.peek() != ",": + raise self.error("expected ','") + self.pos += 1 + self.skip() + return out + + +def parse_dictionary(text: str) -> dict[str, Item | InnerList]: + return _Parser(text).dictionary() + + +def _serialize_bare(value: object) -> str: + if isinstance(value, bool): + return "?1" if value else "?0" + if isinstance(value, int): + return str(value) + if isinstance(value, bytes): + return f":{b64(value)}:" + text = str(value) + return '"' + text.replace("\\", "\\\\").replace('"', '\\"') + '"' + + +def _serialize_params(params) -> str: + return "".join( + f";{name}" if value is True else f";{name}={_serialize_bare(value)}" + for name, value in params + ) + + +def serialize_inner_list(inner: InnerList) -> str: + items = " ".join(_serialize_bare(i.value) + _serialize_params(i.params) for i in inner.items) + return f"({items}){_serialize_params(inner.params)}" + + +# --- Signature base (RFC 9421 §2.5) ------------------------------------------------------ + + +def _component_value(request: SignedRequest, item: Item) -> str: + name = str(item.value) + if item.params: + raise SignatureError("unsupported", f"component parameters on {name}") + parts = urlsplit(request.url) + if name == "@method": + return request.method.upper() + if name == "@target-uri": + return request.url + if name == "@authority": + return parts.netloc.lower() + if name == "@scheme": + return parts.scheme.lower() + if name == "@request-target": + return request.path_and_query + if name == "@path": + return parts.path or "/" + if name == "@query": + return f"?{parts.query}" + if name.startswith("@"): + raise SignatureError("unsupported", f"component {name}") + value = request.header(name) + if value is None: + raise SignatureError("malformed", f"covered header {name} is missing") + return value.strip() + + +def signature_base(request: SignedRequest, inner: InnerList) -> str: + lines = [f'"{item.value}": {_component_value(request, item)}' for item in inner.items] + lines.append(f'"@signature-params": {serialize_inner_list(inner)}') + return "\n".join(lines) + + +# --- Content-Digest (RFC 9530) ------------------------------------------------------------- + +_DIGESTS = {"sha-256": hashlib.sha256, "sha-512": hashlib.sha512} + + +def content_digest(body: bytes) -> str: + return f"sha-256=:{b64(hashlib.sha256(body).digest())}:" + + +def check_content_digest(request: SignedRequest) -> None: + header = request.header("content-digest") + if not header: + raise SignatureError("insufficient", "no Content-Digest header") + for name, member in parse_dictionary(header).items(): + if name in _DIGESTS and isinstance(member, Item) and isinstance(member.value, bytes): + if member.value != _DIGESTS[name](request.body).digest(): + raise SignatureError("digest_mismatch") + return + raise SignatureError("unsupported", "no sha-256 or sha-512 Content-Digest") + + +# --- The scheme ------------------------------------------------------------------------------ + + +class Rfc9421(SignatureScheme): + name = NAME + + def present(self, request: SignedRequest) -> bool: + return request.header("signature-input") is not None + + def sign( + self, request: SignedRequest, key_id: str, private_key: RSAPrivateKey, now: datetime + ) -> dict[str, str]: + added: dict[str, str] = {} + components = ["@method", "@target-uri"] + if request.body or request.method.upper() == "POST": + added["Content-Digest"] = content_digest(request.body) + components.append("content-digest") + inner = InnerList( + tuple(Item(c) for c in components), + (("created", int(now.timestamp())), ("keyid", key_id), ("alg", ALGORITHM)), + ) + signing = SignedRequest( + request.method, request.url, {**request.headers, **added}, request.body + ) + base = signature_base(signing, inner) + signature = private_key.sign(base.encode(), padding.PKCS1v15(), hashes.SHA256()) + added["Signature-Input"] = f"{LABEL}={serialize_inner_list(inner)}" + added["Signature"] = f"{LABEL}=:{b64(signature)}:" + return added + + def verify( + self, + request: SignedRequest, + public_key_for: PublicKeyFor, + now: datetime, + require: tuple[str, ...] | None = None, + ) -> VerifiedSignature: + """Verify the (first) signature. `require` lists components that must be covered; + by default the ActivityPub minimum: method, target and, with a body, the digest.""" + raw_input, raw_signature = request.header("signature-input"), request.header("signature") + if not raw_input or not raw_signature: + raise SignatureError("missing") + inputs, signatures = parse_dictionary(raw_input), parse_dictionary(raw_signature) + label = next((name for name in inputs if name in signatures), None) + if label is None: + raise SignatureError("malformed", "no Signature for any Signature-Input label") + inner, value = inputs[label], signatures[label] + if ( + not isinstance(inner, InnerList) + or not isinstance(value, Item) + or not isinstance(value.value, bytes) + ): + raise SignatureError("malformed") + params = dict(inner.params) + covered = {str(item.value) for item in inner.items} + + if "keyid" not in params: + raise SignatureError("malformed", "no keyid") + if params.get("alg", ALGORITHM) != ALGORITHM: + raise SignatureError("unsupported", f"alg {params['alg']}") + if require is None: + require = ("@method", "@target-uri") + (("content-digest",) if request.body else ()) + if "created" not in params: + raise SignatureError("insufficient", "no created time") + missing = set(require) - covered + if missing: + raise SignatureError("insufficient", f"not covered: {sorted(missing)}") + if "created" in params: + check_time(datetime.fromtimestamp(int(params["created"]), UTC), now) + if "expires" in params and now.timestamp() > int(params["expires"]): + raise SignatureError("expired", "past expires") + if "content-digest" in covered: + check_content_digest(request) + + key_id = str(params["keyid"]) + key = public_key_for(key_id) + if key is None: + raise SignatureError("unknown_key", key_id) + base = signature_base(request, inner) + try: + key.verify(value.value, base.encode(), padding.PKCS1v15(), hashes.SHA256()) + except InvalidSignature as err: + raise SignatureError("bad_signature") from err + return VerifiedSignature(NAME, key_id) diff --git a/tests/data/draft-cavage-test-key.pem b/tests/data/draft-cavage-test-key.pem new file mode 100644 index 0000000..425518a --- /dev/null +++ b/tests/data/draft-cavage-test-key.pem @@ -0,0 +1,15 @@ +-----BEGIN RSA PRIVATE KEY----- +MIICXgIBAAKBgQDCFENGw33yGihy92pDjZQhl0C36rPJj+CvfSC8+q28hxA161QF +NUd13wuCTUcq0Qd2qsBe/2hFyc2DCJJg0h1L78+6Z4UMR7EOcpfdUE9Hf3m/hs+F +UR45uBJeDK1HSFHD8bHKD6kv8FPGfJTotc+2xjJwoYi+1hqp1fIekaxsyQIDAQAB +AoGBAJR8ZkCUvx5kzv+utdl7T5MnordT1TvoXXJGXK7ZZ+UuvMNUCdN2QPc4sBiA +QWvLw1cSKt5DsKZ8UETpYPy8pPYnnDEz2dDYiaew9+xEpubyeW2oH4Zx71wqBtOK +kqwrXa/pzdpiucRRjk6vE6YY7EBBs/g7uanVpGibOVAEsqH1AkEA7DkjVH28WDUg +f1nqvfn2Kj6CT7nIcE3jGJsZZ7zlZmBmHFDONMLUrXR/Zm3pR5m0tCmBqa5RK95u +412jt1dPIwJBANJT3v8pnkth48bQo/fKel6uEYyboRtA5/uHuHkZ6FQF7OUkGogc +mSJluOdc5t6hI1VsLn0QZEjQZMEOWr+wKSMCQQCC4kXJEsHAve77oP6HtG/IiEn7 +kpyUXRNvFsDE0czpJJBvL/aRFUJxuRK91jhjC68sA7NsKMGg5OXb5I5Jj36xAkEA +gIT7aFOYBFwGgQAQkWNKLvySgKbAZRTeLBacpHMuQdl1DfdntvAyqpAZ0lY0RKmW +G6aFKaqQfOXKCyWoUiVknQJAXrlgySFci/2ueKlIE1QqIiLSZ8V8OlpFLRnb1pzI +7U1yQXnTAEFYM560yJlzUpOb1V4cScGd365tiSMvxLOvTA== +-----END RSA PRIVATE KEY----- diff --git a/tests/data/rfc9421-test-key-rsa.pem b/tests/data/rfc9421-test-key-rsa.pem new file mode 100644 index 0000000..4093d09 --- /dev/null +++ b/tests/data/rfc9421-test-key-rsa.pem @@ -0,0 +1,27 @@ +-----BEGIN RSA PRIVATE KEY----- +MIIEqAIBAAKCAQEAhAKYdtoeoy8zcAcR874L8cnZxKzAGwd7v36APp7Pv6Q2jdsP +BRrwWEBnez6d0UDKDwGbc6nxfEXAy5mbhgajzrw3MOEt8uA5txSKobBpKDeBLOsd +JKFqMGmXCQvEG7YemcxDTRPxAleIAgYYRjTSd/QBwVW9OwNFhekro3RtlinV0a75 +jfZgkne/YiktSvLG34lw2zqXBDTC5NHROUqGTlML4PlNZS5Ri2U4aCNx2rUPRcKI +lE0PuKxI4T+HIaFpv8+rdV6eUgOrB2xeI1dSFFn/nnv5OoZJEIB+VmuKn3DCUcCZ +SFlQPSXSfBDiUGhwOw76WuSSsf1D4b/vLoJ10wIDAQABAoIBAG/JZuSWdoVHbi56 +vjgCgkjg3lkO1KrO3nrdm6nrgA9P9qaPjxuKoWaKO1cBQlE1pSWp/cKncYgD5WxE +CpAnRUXG2pG4zdkzCYzAh1i+c34L6oZoHsirK6oNcEnHveydfzJL5934egm6p8DW ++m1RQ70yUt4uRc0YSor+q1LGJvGQHReF0WmJBZHrhz5e63Pq7lE0gIwuBqL8SMaA +yRXtK+JGxZpImTq+NHvEWWCu09SCq0r838ceQI55SvzmTkwqtC+8AT2zFviMZkKR +Qo6SPsrqItxZWRty2izawTF0Bf5S2VAx7O+6t3wBsQ1sLptoSgX3QblELY5asI0J +YFz7LJECgYkAsqeUJmqXE3LP8tYoIjMIAKiTm9o6psPlc8CrLI9CH0UbuaA2JCOM +cCNq8SyYbTqgnWlB9ZfcAm/cFpA8tYci9m5vYK8HNxQr+8FS3Qo8N9RJ8d0U5Csw +DzMYfRghAfUGwmlWj5hp1pQzAuhwbOXFtxKHVsMPhz1IBtF9Y8jvgqgYHLbmyiu1 +mwJ5AL0pYF0G7x81prlARURwHo0Yf52kEw1dxpx+JXER7hQRWQki5/NsUEtv+8RT +qn2m6qte5DXLyn83b1qRscSdnCCwKtKWUug5q2ZbwVOCJCtmRwmnP131lWRYfj67 +B/xJ1ZA6X3GEf4sNReNAtaucPEelgR2nsN0gKQKBiGoqHWbK1qYvBxX2X3kbPDkv +9C+celgZd2PW7aGYLCHq7nPbmfDV0yHcWjOhXZ8jRMjmANVR/eLQ2EfsRLdW69bn +f3ZD7JS1fwGnO3exGmHO3HZG+6AvberKYVYNHahNFEw5TsAcQWDLRpkGybBcxqZo +81YCqlqidwfeO5YtlO7etx1xLyqa2NsCeG9A86UjG+aeNnXEIDk1PDK+EuiThIUa +/2IxKzJKWl1BKr2d4xAfR0ZnEYuRrbeDQYgTImOlfW6/GuYIxKYgEKCFHFqJATAG +IxHrq1PDOiSwXd2GmVVYyEmhZnbcp8CxaEMQoevxAta0ssMK3w6UsDtvUvYvF22m +qQKBiD5GwESzsFPy3Ga0MvZpn3D6EJQLgsnrtUPZx+z2Ep2x0xc5orneB5fGyF1P +WtP+fG5Q6Dpdz3LRfm+KwBCWFKQjg7uTxcjerhBWEYPmEMKYwTJF5PBG9/ddvHLQ +EQeNC8fHGg4UXU8mhHnSBt3EA10qQJfRDs15M38eG2cYwB1PZpDHScDnDA0= +-----END RSA PRIVATE KEY----- diff --git a/tests/test_federation_signatures.py b/tests/test_federation_signatures.py new file mode 100644 index 0000000..d0016e8 --- /dev/null +++ b/tests/test_federation_signatures.py @@ -0,0 +1,274 @@ +"""HTTP signatures: published test vectors, round trips, and tampering.""" + +import dataclasses +from datetime import UTC, datetime, timedelta +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa + +from scrobbler.federation.protocol import signatures +from scrobbler.federation.protocol.signatures import SignatureError, SignedRequest +from scrobbler.federation.protocol.signatures.draft_cavage import DraftCavage +from scrobbler.federation.protocol.signatures.rfc9421 import Rfc9421, parse_dictionary + +DATA = Path(__file__).parent / "data" + + +def load_key(name): + return serialization.load_pem_private_key((DATA / name).read_bytes(), password=None) + + +def keys_by_id(**keys): + return lambda key_id: keys[key_id].public_key() if key_id in keys else None + + +# --- Published test vectors --------------------------------------------------------------- + +CAVAGE_KEY = load_key("draft-cavage-test-key.pem") +CAVAGE_REQUEST = SignedRequest( + method="POST", + url="https://example.com/foo?param=value&pet=dog", + headers={ + "Host": "example.com", + "Date": "Sun, 05 Jan 2014 21:31:40 GMT", + "Content-Type": "application/json", + "Digest": "SHA-256=X48E9qOokqqrvdts8nOJRJN3OWDUoyWxBf7kbu9DBPE=", + "Content-Length": "18", + }, + body=b'{"hello": "world"}', +) +CAVAGE_NOW = datetime(2014, 1, 5, 21, 31, 40, tzinfo=UTC) + + +def cavage(signature_header): + return dataclasses.replace( + CAVAGE_REQUEST, headers={**CAVAGE_REQUEST.headers, "Signature": signature_header} + ) + + +def test_draft_cavage_default_test_vector(): + """draft-cavage-12, appendix C.1: only the date signed.""" + request = cavage( + 'keyId="Test",algorithm="rsa-sha256",signature="SjWJWbWN7i0wzBvtPl8rbASWz5xQW6mcJmn+' + "ibttBqtifLN7Sazz6m79cNfwwb8DMJ5cou1s7uEGKKCs+FLEEaDV5lp7q25WqS+lavg7T8hc0GppauB6hbg" + 'EKTwblDHYGEtbGmtdHgVCk9SuS13F0hZ8FD0k/5OxEPXe5WozsbM="' + ) + verified = DraftCavage().verify( + request, keys_by_id(Test=CAVAGE_KEY), CAVAGE_NOW, require=("date",) + ) + assert (verified.scheme, verified.key_id) == ("draft-cavage", "Test") + + +def test_draft_cavage_basic_test_vector(): + """draft-cavage-12, appendix C.2: (request-target), host and date.""" + request = cavage( + 'keyId="Test",algorithm="rsa-sha256",headers="(request-target) host date",' + 'signature="qdx+H7PHHDZgy4y/Ahn9Tny9V3GP6YgBPyUXMmoxWtLbHpUnXS2mg2+SbrQDMCJypxBLSPQR2aAjn7' + "ndmw2iicw3HMbe8VfEdKFYRqzic+efkb3nndiv/x1xSHDJWeSWkx3ButlYSuBskLu6kd9Fswtemr3lgdDEmn0" + '4swr2Os0="' + ) + require = ("(request-target)", "host", "date") + verified = DraftCavage().verify( + request, keys_by_id(Test=CAVAGE_KEY), CAVAGE_NOW, require=require + ) + assert verified.key_id == "Test" + # ...but it's not enough for an ActivityPub POST, which must sign the digest + with pytest.raises(SignatureError) as err: + DraftCavage().verify(request, keys_by_id(Test=CAVAGE_KEY), CAVAGE_NOW) + assert err.value.reason == "insufficient" + + +RFC_KEY = load_key("rfc9421-test-key-rsa.pem") + + +def test_rfc9421_rsa_v1_5_sha256_test_vector(): + """RFC 9421 §4.3: the proxy's rsa-v1_5-sha256 signature (test-key-rsa).""" + request = SignedRequest( + method="POST", + url="https://origin.host.internal.example/foo?param=Value&Pet=dog", + headers={ + "Host": "origin.host.internal.example", + "Date": "Tue, 20 Apr 2021 02:07:56 GMT", + "Content-Type": "application/json", + "Content-Length": "18", + "Forwarded": "for=192.0.2.123;host=example.com;proto=https", + "Content-Digest": ( + "sha-512=:WZDPaVn/7XgHaAy8pmojAkGWoRx2UFChF41A2svX+TaPm+AbwAgBWnrIiYllu7BNNyealdVLv" + "RwEmTHWXvJwew==:" + ), + "Signature-Input": ( + 'proxy_sig=("@method" "@authority" "@path" "content-digest" "content-type" ' + '"content-length" "forwarded");created=1618884480;keyid="test-key-rsa";' + 'alg="rsa-v1_5-sha256";expires=1618884540' + ), + "Signature": ( + "proxy_sig=:S6ZzPXSdAMOPjN/6KXfXWNO/f7V6cHm7BXYUh3YD/fRad4BCaRZxP+JH+8XY1I6+8Cy+CM5" + "g92iHgxtRPz+MjniOaYmdkDcnL9cCpXJleXsOckpURl49GwiyUpZ10KHgOEe11sx3G2gxI8S0jnxQB+Pu68" + "U9vVcasqOWAEObtNKKZd8tSFu7LB5YAv0RAGhB8tmpv7sFnIm9y+7X5kXQfi8NMaZaA8i2ZHwpBdg7a6CM" + "fwnnrtflzvZdXAsD3LH2TwevU+/PBPv0B6NMNk93wUs/vfJvye+YuI87HU38lZHowtznbLVdp770I6VHR" + "6WfgS9ddzirrswsE1w5o0LV/g==:" + ), + }, + body=b'{"hello": "world"}', + ) + now = datetime.fromtimestamp(1618884480, UTC) + verified = Rfc9421().verify( + request, keys_by_id(**{"test-key-rsa": RFC_KEY}), now, require=("@method", "@path") + ) + assert verified.key_id == "test-key-rsa" + # Past `expires` the same signature is refused + with pytest.raises(SignatureError) as err: + Rfc9421().verify( + request, + keys_by_id(**{"test-key-rsa": RFC_KEY}), + now + timedelta(minutes=2), + require=("@method", "@path"), + ) + assert err.value.reason == "expired" + + +# --- Round trips with our own keys --------------------------------------------------------- + +KEY = rsa.generate_private_key(public_exponent=65537, key_size=2048) +KEY_ID = "https://remote.example/users/bob#main-key" +NOW = datetime(2026, 9, 25, 12, 0, tzinfo=UTC) +LOOKUP = keys_by_id(**{KEY_ID: KEY}) +BODY = b'{"type": "Follow", "actor": "https://remote.example/users/bob"}' +INBOX = "https://scrobble.example/users/alice/inbox" +SCHEMES = ["draft-cavage", "rfc9421"] + + +def signed(scheme, method="POST", url=INBOX, body=BODY, now=NOW, key=KEY): + request = SignedRequest(method, url, {"Content-Type": "application/activity+json"}, body) + added = signatures.sign(request, scheme, KEY_ID, key, now) + return dataclasses.replace(request, headers={**request.headers, **added}) + + +@pytest.mark.parametrize("scheme", SCHEMES) +def test_round_trip_post(scheme): + request = signed(scheme) + assert signatures.detect(request).name == scheme + verified = signatures.verify(request, LOOKUP, NOW + timedelta(seconds=5)) + assert (verified.scheme, verified.key_id) == (scheme, KEY_ID) + + +@pytest.mark.parametrize("scheme", SCHEMES) +def test_round_trip_get(scheme): + request = signed(scheme, method="GET", url="https://remote.example/users/bob", body=b"") + assert signatures.verify(request, LOOKUP, NOW).scheme == scheme + + +def test_sent_headers_have_the_expected_shapes(): + cavage_headers = signed("draft-cavage").headers + assert cavage_headers["Digest"].startswith("SHA-256=") + assert 'headers="(request-target) host date digest"' in cavage_headers["Signature"] + rfc_headers = signed("rfc9421").headers + assert rfc_headers["Content-Digest"].startswith("sha-256=:") + assert rfc_headers["Signature-Input"].startswith( + 'sig1=("@method" "@target-uri" "content-digest");created=' + ) + assert rfc_headers["Signature"].startswith("sig1=:") and rfc_headers["Signature"].endswith(":") + + +def tamper(request, **changes): + headers = {**request.headers, **changes.pop("headers", {})} + return dataclasses.replace(request, headers=headers, **changes) + + +@pytest.mark.parametrize("scheme", SCHEMES) +@pytest.mark.parametrize( + ("change", "reason"), + [ + ( + {"body": b'{"type": "Follow", "actor": "https://evil.example/users/eve"}'}, + "digest_mismatch", + ), + ({"url": "https://scrobble.example/users/mallory/inbox"}, "bad_signature"), + ({"method": "PUT"}, "bad_signature"), + ], +) +def test_tampering_is_detected(scheme, change, reason): + with pytest.raises(SignatureError) as err: + signatures.verify(tamper(signed(scheme), **change), LOOKUP, NOW) + assert err.value.reason == reason + + +def test_draft_cavage_date_tampering_is_detected(): + request = tamper(signed("draft-cavage"), headers={"Date": "Fri, 25 Sep 2026 12:00:01 GMT"}) + with pytest.raises(SignatureError) as err: + signatures.verify(request, LOOKUP, NOW) + assert err.value.reason == "bad_signature" + + +@pytest.mark.parametrize("scheme", SCHEMES) +@pytest.mark.parametrize("skew", [timedelta(hours=13), -timedelta(hours=13)]) +def test_old_or_future_signatures_are_refused(scheme, skew): + with pytest.raises(SignatureError) as err: + signatures.verify(signed(scheme, now=NOW + skew), LOOKUP, NOW) + assert err.value.reason == "expired" + + +@pytest.mark.parametrize("scheme", SCHEMES) +def test_wrong_key_is_refused(scheme): + other = rsa.generate_private_key(public_exponent=65537, key_size=2048) + with pytest.raises(SignatureError) as err: + signatures.verify(signed(scheme, key=other), LOOKUP, NOW) + assert err.value.reason == "bad_signature" + + +@pytest.mark.parametrize("scheme", SCHEMES) +def test_unknown_key_is_reported(scheme): + with pytest.raises(SignatureError) as err: + signatures.verify(signed(scheme), lambda key_id: None, NOW) + assert err.value.reason == "unknown_key" + + +def test_unsigned_request(): + with pytest.raises(SignatureError) as err: + signatures.verify(SignedRequest("POST", INBOX, {}, BODY), LOOKUP, NOW) + assert err.value.reason == "missing" + + +def test_rfc9421_must_cover_method_target_and_digest(): + request = signed("rfc9421") + weak = tamper( + request, + headers={ + "Signature-Input": request.headers["Signature-Input"].replace(' "content-digest"', "") + }, + ) + with pytest.raises(SignatureError) as err: + signatures.verify(weak, LOOKUP, NOW) + assert err.value.reason == "insufficient" + + +def test_draft_cavage_hs2019_is_accepted(): + request = signed("draft-cavage") + hs2019 = tamper( + request, headers={"Signature": request.headers["Signature"].replace("rsa-sha256", "hs2019")} + ) + assert signatures.verify(hs2019, LOOKUP, NOW).scheme == "draft-cavage" + + +@pytest.mark.parametrize( + "header", + ['keyId="x"', "garbage", 'keyId="x",signature="!!!not base64!!!"'], +) +def test_malformed_draft_cavage_headers(header): + request = SignedRequest( + "GET", INBOX, {"Signature": header, "Date": "Fri, 25 Sep 2026 12:00:00 GMT"} + ) + with pytest.raises(SignatureError) as err: + DraftCavage().verify(request, LOOKUP, NOW, require=()) + assert err.value.reason in ("malformed", "unknown_key") + + +def test_structured_field_parsing(): + parsed = parse_dictionary('sig1=("@method" "@target-uri");created=1;keyid="k\\"q", sig2=:aGk=:') + assert [i.value for i in parsed["sig1"].items] == ["@method", "@target-uri"] + assert dict(parsed["sig1"].params) == {"created": 1, "keyid": 'k"q'} + assert parsed["sig2"].value == b"hi" + with pytest.raises(SignatureError): + parse_dictionary('sig1=("unterminated') From 52b9f0b27b2b490a44aa6db53b86ef0cbec0c04e Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 21:21:00 +0100 Subject: [PATCH 21/56] Safe outbound HTTP and remote actors (phase 2, step 2) - net.py: the only client federation uses, on httpcore (BSD-3-Clause) with a guarded network backend: https only, every resolved address must be public (private, loopback, link-local, CGNAT, multicast and IPv4-mapped forms refused), and the connection goes to the checked address; 3 redirects max (GET only), 1 MB cap, 10s/20s timeouts - outbound.py: signed GETs (instance actor, so authorized-fetch servers answer) and signed POSTs (as the user), trying the configured signature schemes in order and the next only on a 401 - remote.py + federation_remote_actors: fetch, validate (id matches URL and host, actor type, inbox on its host, key owned by the actor), cache for 24h, refresh on demand, 410 marks an actor gone; resolve a key id to its actor, including standalone key documents - Config: FEDERATION_SIGNATURE_SCHEMES, FEDERATION_BLOCKED_DOMAINS, FEDERATION_DELIVERY_CONCURRENCY, and FEDERATION_INSECURE_TESTING (http and private addresses; only allowed for .test domains) - Tests against a real local HTTP server, including verifying that our fetches carry a valid signature Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- pyproject.toml | 1 + src/scrobbler/federation/config.py | 47 +++- src/scrobbler/federation/models.py | 26 ++ src/scrobbler/federation/net.py | 165 +++++++++++ src/scrobbler/federation/outbound.py | 72 +++++ src/scrobbler/federation/remote.py | 125 +++++++++ .../211d4743f081_federation_remote_actors.py | 50 ++++ tests/conftest.py | 60 ++++ tests/test_federation_net_remote.py | 256 ++++++++++++++++++ uv.lock | 24 ++ 10 files changed, 823 insertions(+), 3 deletions(-) create mode 100644 src/scrobbler/federation/net.py create mode 100644 src/scrobbler/federation/outbound.py create mode 100644 src/scrobbler/federation/remote.py create mode 100644 src/scrobbler/migrations/versions/211d4743f081_federation_remote_actors.py create mode 100644 tests/test_federation_net_remote.py diff --git a/pyproject.toml b/pyproject.toml index c03ee97..724e3ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -14,6 +14,7 @@ dependencies = [ "flask-smorest>=0.47.0", "flask-sqlalchemy>=3.1.1", "gunicorn>=26.2.0", + "httpcore>=1.0.9", "prometheus-client>=0.26.0", "psycopg[binary]>=3.3.6", "python-dotenv>=1.2.3", diff --git a/src/scrobbler/federation/config.py b/src/scrobbler/federation/config.py index 00fd03e..464104c 100644 --- a/src/scrobbler/federation/config.py +++ b/src/scrobbler/federation/config.py @@ -1,6 +1,6 @@ import os from collections.abc import Mapping -from dataclasses import dataclass +from dataclasses import dataclass, field from urllib.parse import urlsplit @@ -12,12 +12,25 @@ def _flag(value) -> bool: return str(value).strip().lower() in {"1", "true", "yes", "on"} +def _csv(value: str) -> tuple[str, ...]: + return tuple(part.strip().lower() for part in value.split(",") if part.strip()) + + +KNOWN_SCHEMES = ("draft-cavage", "rfc9421") + + @dataclass(frozen=True) class FederationConfig: enabled: bool = False domain: str = "" # the handle's domain: @user@ base_url: str = "" # where actors live: /users/ key_secret: str = "" # encrypts actors' private keys at rest + signature_schemes: tuple[str, ...] = KNOWN_SCHEMES # outgoing order; next on a 401 + blocked_domains: tuple[str, ...] = field(default=()) + delivery_concurrency: int = 4 + # TESTS ONLY: allow http:// and private addresses so CI can federate on a private + # network. Refused unless the domain is under the reserved .test TLD. + insecure_testing: bool = False @classmethod def from_mapping(cls, config: Mapping) -> "FederationConfig": @@ -27,11 +40,21 @@ class FederationConfig: value = config.get(key) return str(value if value is not None else os.environ.get(key, default)) + try: + concurrency = int(get("FEDERATION_DELIVERY_CONCURRENCY", "4")) + except ValueError: + raise FederationConfigError( + "FEDERATION_DELIVERY_CONCURRENCY must be a number" + ) from None result = cls( enabled=_flag(get("FEDERATION_ENABLED", "0")), domain=get("FEDERATION_DOMAIN").strip().lower(), base_url=get("FEDERATION_BASE_URL").strip().rstrip("/"), key_secret=get("FEDERATION_KEY_SECRET"), + signature_schemes=_csv(get("FEDERATION_SIGNATURE_SCHEMES", ",".join(KNOWN_SCHEMES))), + blocked_domains=_csv(get("FEDERATION_BLOCKED_DOMAINS")), + delivery_concurrency=concurrency, + insecure_testing=_flag(get("FEDERATION_INSECURE_TESTING", "0")), ) result.validate() return result @@ -45,8 +68,14 @@ class FederationConfig: "FEDERATION_ENABLED is on. It becomes part of every handle and can't change " "once people follow." ) + if self.insecure_testing and not self.domain.endswith(".test"): + raise FederationConfigError( + "FEDERATION_INSECURE_TESTING is for automated tests only, and only allowed " + "with a FEDERATION_DOMAIN under .test." + ) url = urlsplit(self.base_url) - if url.scheme != "https" or not url.netloc or url.query or url.fragment: + schemes = ("https", "http") if self.insecure_testing else ("https",) + if url.scheme not in schemes or not url.netloc or url.query or url.fragment: raise FederationConfigError( "FEDERATION_BASE_URL must be the public https:// URL the API is served at " "(e.g. https://scrobble.example) when FEDERATION_ENABLED is on." @@ -57,9 +86,21 @@ class FederationConfig: "is on. It encrypts actors' private keys; keep it safe and never change it " "(e.g. python -c 'import secrets; print(secrets.token_urlsafe(48))')." ) + unknown = set(self.signature_schemes) - set(KNOWN_SCHEMES) + if not self.signature_schemes or unknown: + raise FederationConfigError( + f"FEDERATION_SIGNATURE_SCHEMES must list some of {', '.join(KNOWN_SCHEMES)}" + ) + if not 1 <= self.delivery_concurrency <= 32: + raise FederationConfigError("FEDERATION_DELIVERY_CONCURRENCY must be 1-32") + + def is_blocked(self, host: str) -> bool: + host = host.lower().rstrip(".") + return any(host == d or host.endswith("." + d) for d in self.blocked_domains) def __repr__(self) -> str: # never print the secret return ( f"FederationConfig(enabled={self.enabled}, domain={self.domain!r}, " - f"base_url={self.base_url!r}, key_secret=***)" + f"base_url={self.base_url!r}, key_secret=***, " + f"insecure_testing={self.insecure_testing})" ) diff --git a/src/scrobbler/federation/models.py b/src/scrobbler/federation/models.py index 7b9f4fa..cd3f297 100644 --- a/src/scrobbler/federation/models.py +++ b/src/scrobbler/federation/models.py @@ -46,3 +46,29 @@ class FederationKey(db.Model): public_key_pem: Mapped[str] = mapped_column(Text) private_key_encrypted: Mapped[bytes] = mapped_column(LargeBinary) created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class FederationRemoteActor(db.Model): + """A cached copy of another server's actor (who follows us, and their key).""" + + __tablename__ = "federation_remote_actors" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + uri: Mapped[str] = mapped_column(String(2048), unique=True) + host: Mapped[str] = mapped_column(String(255), index=True) + inbox: Mapped[str] = mapped_column(String(2048)) + shared_inbox: Mapped[str | None] = mapped_column(String(2048)) + username: Mapped[str | None] = mapped_column(String(255)) # preferredUsername + display_name: Mapped[str | None] = mapped_column(String(255)) + public_key_id: Mapped[str] = mapped_column(String(2048), index=True) + public_key_pem: Mapped[str] = mapped_column(Text) + fetched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + gone: Mapped[bool] = mapped_column(Boolean, default=False) + + @property + def handle(self) -> str: + return f"@{self.username or '?'}@{self.host}" + + @property + def delivery_inbox(self) -> str: + return self.shared_inbox or self.inbox diff --git a/src/scrobbler/federation/net.py b/src/scrobbler/federation/net.py new file mode 100644 index 0000000..e6587f6 --- /dev/null +++ b/src/scrobbler/federation/net.py @@ -0,0 +1,165 @@ +"""The only way federation code talks to other servers. + +Guards against server-side request forgery (a remote document or redirect pointing us +at internal services): + * https only (http only with FEDERATION_INSECURE_TESTING, for CI on private networks); + * a host's addresses are resolved once and the request is refused if any is loopback, + private, link-local, multicast or otherwise not globally routable; the connection + then goes to the address that was checked (SNI and Host keep the name), so the name + can't be re-resolved somewhere else mid-request; + * at most 3 redirects, each checked the same way; responses capped at 1 MB; + 10s to connect, 20s to read. +""" + +import ipaddress +import json +import socket +from collections.abc import Callable +from dataclasses import dataclass +from urllib.parse import urljoin, urlsplit + +import httpcore + +from scrobbler.federation.protocol.media import ACTIVITY_JSON, LD_JSON + +MAX_BYTES = 1024 * 1024 +MAX_REDIRECTS = 3 +TIMEOUTS = {"connect": 10.0, "read": 20.0, "write": 20.0, "pool": 10.0} +_REDIRECTS = {301, 302, 303, 307, 308} + +Resolver = Callable[[str, int], list[str]] + + +class FetchError(Exception): + """A request we refused to make or that didn't succeed.""" + + def __init__(self, reason: str, message: str, status: int | None = None): + self.reason, self.status = ( + reason, + status, + ) # reason: blocked, http, too_large, network, invalid + super().__init__(message) + + +@dataclass(frozen=True) +class Response: + status: int + headers: dict[str, str] # lower-cased names + body: bytes + url: str # after redirects + + def json(self) -> dict: + try: + doc = json.loads(self.body) + except (json.JSONDecodeError, UnicodeDecodeError) as err: + raise FetchError("invalid", f"{self.url} didn't return JSON") from err + if not isinstance(doc, dict): + raise FetchError("invalid", f"{self.url} didn't return a JSON object") + return doc + + +def system_resolver(host: str, port: int) -> list[str]: + try: + infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM) + except socket.gaierror as err: + raise FetchError("network", f"can't resolve {host}") from err + return list(dict.fromkeys(info[4][0] for info in infos)) + + +def is_public(address: str) -> bool: + ip = ipaddress.ip_address(address.split("%", 1)[0]) + if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped: + ip = ip.ipv4_mapped + return ip.is_global and not ip.is_multicast and not ip.is_reserved + + +class _GuardedBackend(httpcore.SyncBackend): + def __init__(self, resolver: Resolver, allow_private: bool): + super().__init__() + self.resolver, self.allow_private = resolver, allow_private + + def connect_tcp(self, host, port, timeout=None, local_address=None, socket_options=None): + addresses = self.resolver(host, port) + if not addresses: + raise FetchError("network", f"{host} has no addresses") + if not self.allow_private: + refused = [a for a in addresses if not is_public(a)] + if refused: + raise FetchError("blocked", f"{host} resolves to a non-public address") + return super().connect_tcp(addresses[0], port, timeout, local_address, socket_options) + + +class Client: + def __init__( + self, + user_agent: str, + insecure_testing: bool = False, + resolver: Resolver = system_resolver, + ): + self.user_agent = user_agent + self.insecure_testing = insecure_testing + self._pool = httpcore.ConnectionPool( + network_backend=_GuardedBackend(resolver, allow_private=insecure_testing), + max_connections=32, + keepalive_expiry=30, + ) + + def _check_url(self, url: str) -> None: + parts = urlsplit(url) + schemes = ("https", "http") if self.insecure_testing else ("https",) + if parts.scheme not in schemes or not parts.hostname: + raise FetchError("blocked", f"refusing to fetch {url}") + if parts.username or parts.password: + raise FetchError("blocked", "credentials in URL") + + def request( + self, method: str, url: str, headers: dict[str, str] | None = None, body: bytes = b"" + ) -> Response: + """One request, following redirects for GET only. Doesn't raise for HTTP errors.""" + for _ in range(MAX_REDIRECTS + 1): + self._check_url(url) + response = self._send(method, url, headers or {}, body) + location = response.headers.get("location") + if method == "GET" and response.status in _REDIRECTS and location: + url = urljoin(url, location) + continue + return response + raise FetchError("blocked", "too many redirects") + + def _send(self, method: str, url: str, headers: dict[str, str], body: bytes) -> Response: + sent = {"User-Agent": self.user_agent, **headers} + try: + with self._pool.stream( + method, + url, + headers=list(sent.items()), + content=body or None, + extensions={"timeout": TIMEOUTS}, + ) as response: + chunks, size = [], 0 + for chunk in response.iter_stream(): + size += len(chunk) + if size > MAX_BYTES: + raise FetchError("too_large", f"{url} sent more than {MAX_BYTES} bytes") + chunks.append(chunk) + return Response( + status=response.status, + headers={k.decode().lower(): v.decode("latin-1") for k, v in response.headers}, + body=b"".join(chunks), + url=url, + ) + except httpcore.TimeoutException as err: + raise FetchError("network", f"{url} timed out") from err + except (httpcore.NetworkError, httpcore.ProtocolError, httpcore.UnsupportedProtocol) as err: + raise FetchError("network", f"{url}: {err}") from err + + def get_json(self, url: str, headers: dict[str, str] | None = None) -> dict: + response = self.request( + "GET", url, {"Accept": f"{ACTIVITY_JSON}, {LD_JSON}", **(headers or {})} + ) + if response.status != 200: + raise FetchError("http", f"{url} answered {response.status}", response.status) + return response.json() + + def close(self) -> None: + self._pool.close() diff --git a/src/scrobbler/federation/outbound.py b/src/scrobbler/federation/outbound.py new file mode 100644 index 0000000..021b442 --- /dev/null +++ b/src/scrobbler/federation/outbound.py @@ -0,0 +1,72 @@ +"""Signed requests to other servers, through the SSRF-safe client in net.py.""" + +import json + +from flask import current_app + +from scrobbler.federation import keys +from scrobbler.federation.net import Client, FetchError, Response +from scrobbler.federation.protocol import signatures +from scrobbler.federation.protocol.media import ACTIVITY_JSON, LD_JSON +from scrobbler.federation.protocol.signatures import SignedRequest + + +def client() -> Client: + """One pooled client per app (created on first use).""" + existing = current_app.extensions.get("federation_client") + if existing is None: + from scrobbler import __version__ + + config = current_app.extensions["federation"] + existing = Client( + user_agent=f"Scrobbler/{__version__} (+{config.base_url})", + insecure_testing=config.insecure_testing, + ) + current_app.extensions["federation_client"] = existing + return existing + + +def instance_key_id() -> str: + return f"{current_app.extensions['federation'].base_url}/actor#main-key" + + +def user_key_id(username: str) -> str: + return f"{current_app.extensions['federation'].base_url}/users/{username}#main-key" + + +def _signed_headers(method, url, headers, body, key_id, private_key, scheme) -> dict[str, str]: + request = SignedRequest(method, url, headers, body) + return {**headers, **signatures.sign(request, scheme, key_id, private_key)} + + +def signed_get_json(url: str) -> dict: + """GET an ActivityPub document, signed as the instance actor, so servers using + 'authorized fetch' answer too.""" + private = keys.private_key(keys.key_for(None)) + headers = {"Accept": f"{ACTIVITY_JSON}, {LD_JSON}"} + schemes = current_app.extensions["federation"].signature_schemes + response = None + for scheme in schemes: + signed = _signed_headers("GET", url, headers, b"", instance_key_id(), private, scheme) + response = client().request("GET", url, signed) + if response.status != 401: + break + if response.status != 200: + raise FetchError("http", f"{url} answered {response.status}", response.status) + return response.json() + + +def signed_post(url: str, activity: dict, *, user_id: int, username: str) -> tuple[Response, str]: + """POST an activity to an inbox, signed as the user. Tries the configured signature + schemes in order, moving to the next only when the server answers 401. Returns the + response and the scheme used.""" + body = json.dumps(activity).encode() + private = keys.private_key(keys.key_for(user_id)) + headers = {"Content-Type": LD_JSON, "Accept": ACTIVITY_JSON} + response, used = None, "" + for used in current_app.extensions["federation"].signature_schemes: + signed = _signed_headers("POST", url, headers, body, user_key_id(username), private, used) + response = client().request("POST", url, signed, body) + if response.status != 401: + break + return response, used diff --git a/src/scrobbler/federation/remote.py b/src/scrobbler/federation/remote.py new file mode 100644 index 0000000..8253c4e --- /dev/null +++ b/src/scrobbler/federation/remote.py @@ -0,0 +1,125 @@ +"""Remote actors: fetched with a signed GET, validated, cached for a day. + +Validation (a document must really be the actor it claims to be): + * its `id` equals the URL it was fetched from, and the host matches; + * it's an actor type with an inbox on the same host; + * its `publicKey` is owned by it (`publicKey.owner == id`). +""" + +from datetime import UTC, datetime, timedelta +from urllib.parse import urldefrag, urlsplit + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey + +from scrobbler.extensions import db +from scrobbler.federation import outbound +from scrobbler.federation.models import FederationRemoteActor +from scrobbler.federation.net import FetchError + +ACTOR_TYPES = {"Person", "Service", "Application", "Group", "Organization"} +MAX_AGE = timedelta(hours=24) + + +class ActorError(Exception): + """A remote document that isn't a valid actor (or key).""" + + +def _host(url: str) -> str: + return (urlsplit(url).hostname or "").lower() + + +def _text(value, limit: int) -> str | None: + return value[:limit] if isinstance(value, str) and value else None + + +def _parse_actor(uri: str, doc: dict) -> dict: + if doc.get("id") != uri: + raise ActorError(f"{uri} claims to be {doc.get('id')!r}") + if doc.get("type") not in ACTOR_TYPES: + raise ActorError(f"{uri} isn't an actor ({doc.get('type')!r})") + host = _host(uri) + inbox = doc.get("inbox") + if not isinstance(inbox, str) or _host(inbox) != host: + raise ActorError(f"{uri} has no inbox on its own host") + endpoints = doc.get("endpoints") if isinstance(doc.get("endpoints"), dict) else {} + shared = endpoints.get("sharedInbox") + if not isinstance(shared, str) or _host(shared) != host: + shared = None + key = doc.get("publicKey") + if isinstance(key, list): # some servers list several + key = next((k for k in key if isinstance(k, dict) and k.get("owner") == uri), None) + if not isinstance(key, dict) or key.get("owner") != uri or not key.get("publicKeyPem"): + raise ActorError(f"{uri} has no public key of its own") + key_id = key.get("id") + if not isinstance(key_id, str) or _host(key_id) != host: + raise ActorError(f"{uri}'s key id isn't on its host") + load_public_key(key["publicKeyPem"]) # must parse + return { + "host": host, + "inbox": inbox, + "shared_inbox": shared, + "username": _text(doc.get("preferredUsername"), 255), + "display_name": _text(doc.get("name"), 255), + "public_key_id": key_id, + "public_key_pem": key["publicKeyPem"], + } + + +def load_public_key(pem: str) -> RSAPublicKey: + try: + key = serialization.load_pem_public_key(pem.encode()) + except (ValueError, TypeError) as err: + raise ActorError("unreadable public key") from err + if not isinstance(key, RSAPublicKey): + raise ActorError("only RSA keys are supported") + return key + + +def get_actor(uri: str, refresh: bool = False) -> FederationRemoteActor: + """The actor at `uri`, from cache if fresh. Raises ActorError or FetchError.""" + actor = db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=uri)) + fresh = actor is not None and datetime.now(UTC) - actor.fetched_at < MAX_AGE + if actor is not None and not refresh and (fresh or actor.gone): + return actor + try: + fields = _parse_actor(uri, outbound.signed_get_json(uri)) + except FetchError as err: + if err.status == 410 and actor is not None: # deleted account + actor.gone = True + db.session.commit() + raise + if actor is None: + actor = FederationRemoteActor(uri=uri, **fields) + db.session.add(actor) + else: + for name, value in fields.items(): + setattr(actor, name, value) + actor.gone = False + actor.fetched_at = datetime.now(UTC) + db.session.commit() + return actor + + +def actor_for_key(key_id: str, refresh: bool = False) -> FederationRemoteActor: + """The actor that owns `key_id`: usually `#main-key`, sometimes a separate + key document naming its owner.""" + cached = db.session.scalar(db.select(FederationRemoteActor).filter_by(public_key_id=key_id)) + if cached is not None and not refresh: + return get_actor(cached.uri) + document_url = urldefrag(key_id).url + try: + return _matching(get_actor(document_url, refresh=True), key_id) + except ActorError: + # Not an actor: a standalone key document pointing at its owner + doc = outbound.signed_get_json(document_url) + owner = doc.get("owner") + if doc.get("id") != key_id or not isinstance(owner, str) or _host(owner) != _host(key_id): + raise + return _matching(get_actor(owner, refresh=True), key_id) + + +def _matching(actor: FederationRemoteActor, key_id: str) -> FederationRemoteActor: + if actor.public_key_id != key_id: + raise ActorError(f"{actor.uri} doesn't use key {key_id}") + return actor diff --git a/src/scrobbler/migrations/versions/211d4743f081_federation_remote_actors.py b/src/scrobbler/migrations/versions/211d4743f081_federation_remote_actors.py new file mode 100644 index 0000000..9b7a557 --- /dev/null +++ b/src/scrobbler/migrations/versions/211d4743f081_federation_remote_actors.py @@ -0,0 +1,50 @@ +"""federation remote actors + +Revision ID: 211d4743f081 +Revises: 34508576a6c7 +Create Date: 2026-09-25 21:17:31.469467 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '211d4743f081' +down_revision = '34508576a6c7' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('federation_remote_actors', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('uri', sa.String(length=2048), nullable=False), + sa.Column('host', sa.String(length=255), nullable=False), + sa.Column('inbox', sa.String(length=2048), nullable=False), + sa.Column('shared_inbox', sa.String(length=2048), nullable=True), + sa.Column('username', sa.String(length=255), nullable=True), + sa.Column('display_name', sa.String(length=255), nullable=True), + sa.Column('public_key_id', sa.String(length=2048), nullable=False), + sa.Column('public_key_pem', sa.Text(), nullable=False), + sa.Column('fetched_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('gone', sa.Boolean(), nullable=False), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('uri') + ) + with op.batch_alter_table('federation_remote_actors', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_federation_remote_actors_host'), ['host'], unique=False) + batch_op.create_index(batch_op.f('ix_federation_remote_actors_public_key_id'), ['public_key_id'], unique=False) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('federation_remote_actors', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_federation_remote_actors_public_key_id')) + batch_op.drop_index(batch_op.f('ix_federation_remote_actors_host')) + + op.drop_table('federation_remote_actors') + # ### end Alembic commands ### diff --git a/tests/conftest.py b/tests/conftest.py index c5d4949..a27668a 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -154,6 +154,8 @@ class FederatedTestConfig(_TestConfig): FEDERATION_DOMAIN = "scrobble.test" FEDERATION_BASE_URL = "https://scrobble.test" FEDERATION_KEY_SECRET = "test-only-federation-key-secret-0123456789" + # Lets tests federate with servers on 127.0.0.1 over http (allowed for .test only). + FEDERATION_INSECURE_TESTING = "1" @pytest.fixture(scope="session") @@ -182,3 +184,61 @@ def sharing_user(fed_ctx, user): sharing.update(user.id, {"enabled": True, "display_name": "Alice", "bio": "Listening."}) return user + + +class FakeRemote: + """A tiny HTTP server standing in for another fediverse server. + + `routes[path] = (status, headers, body)`; `requests` records what it received. + """ + + def __init__(self): + import threading + + from werkzeug.serving import make_server + from werkzeug.wrappers import Request, Response + + self.routes: dict = {} + self.requests: list = [] + + @Request.application + def app(request): + self.requests.append( + { + "method": request.method, + "path": request.full_path.rstrip("?"), + "headers": dict(request.headers), + "body": request.get_data(), + } + ) + status, headers, body = self.routes.get(request.path, (404, {}, b"not found")) + if callable(body): + body = body(request) + if isinstance(body, dict | list): + import json as _json + + body, headers = ( + _json.dumps(body).encode(), + {"Content-Type": "application/activity+json", **headers}, + ) + return Response(body, status=status, headers=headers) + + self.server = make_server("127.0.0.1", 0, app, threaded=True) + self.base = f"http://127.0.0.1:{self.server.server_port}" + # A short poll interval: shutdown() waits for the next poll + threading.Thread( + target=self.server.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True + ).start() + + def url(self, path: str) -> str: + return self.base + path + + def close(self): + self.server.shutdown() + + +@pytest.fixture +def remote(): + server = FakeRemote() + yield server + server.close() diff --git a/tests/test_federation_net_remote.py b/tests/test_federation_net_remote.py new file mode 100644 index 0000000..dabdd04 --- /dev/null +++ b/tests/test_federation_net_remote.py @@ -0,0 +1,256 @@ +"""Outbound HTTP safety (net.py) and remote actor fetching (remote.py).""" + +from datetime import UTC, datetime, timedelta + +import pytest +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa + +from scrobbler.extensions import db +from scrobbler.federation import keys, remote +from scrobbler.federation.models import FederationRemoteActor +from scrobbler.federation.net import MAX_BYTES, Client, FetchError, is_public +from scrobbler.federation.protocol import signatures +from scrobbler.federation.protocol.signatures import SignedRequest + +# --- Address checks ---------------------------------------------------------------------- + + +@pytest.mark.parametrize( + ("address", "public"), + [ + ("8.8.8.8", True), + ("2606:4700:4700::1111", True), + ("127.0.0.1", False), + ("10.1.2.3", False), + ("172.16.0.1", False), + ("192.168.1.1", False), + ("169.254.169.254", False), # cloud metadata + ("100.64.0.1", False), # carrier-grade NAT + ("0.0.0.0", False), + ("224.0.0.1", False), + ("::1", False), + ("fc00::1", False), + ("fe80::1", False), + ("::ffff:127.0.0.1", False), # IPv4-mapped loopback + ("::ffff:8.8.8.8", True), + ], +) +def test_is_public(address, public): + assert is_public(address) is public + + +def test_http_is_refused_outside_testing(): + client = Client("test", resolver=lambda host, port: ["93.184.215.14"]) + with pytest.raises(FetchError) as err: + client.request("GET", "http://example.com/users/bob") + assert err.value.reason == "blocked" + + +@pytest.mark.parametrize("addresses", [["10.0.0.5"], ["93.184.215.14", "127.0.0.1"], ["::1"]]) +def test_names_resolving_to_private_addresses_are_refused(addresses): + """Even one private address among several is enough to refuse (no retry elsewhere).""" + client = Client("test", resolver=lambda host, port: addresses) + with pytest.raises(FetchError) as err: + client.request("GET", "https://sneaky.example/users/bob") + assert err.value.reason == "blocked" + + +def test_urls_with_credentials_are_refused(): + with pytest.raises(FetchError): + Client("test").request("GET", "https://user:pass@example.com/") + + +# --- Against a local server (insecure testing allows 127.0.0.1 over http) --------------------- + + +@pytest.fixture +def local_client(): + client = Client("Scrobbler/test", insecure_testing=True) + yield client + client.close() + + +def test_get_json_and_user_agent(local_client, remote): + remote.routes["/doc"] = (200, {}, {"id": "x"}) + assert local_client.get_json(remote.url("/doc")) == {"id": "x"} + assert remote.requests[0]["headers"]["User-Agent"] == "Scrobbler/test" + assert "application/activity+json" in remote.requests[0]["headers"]["Accept"] + + +def test_redirects_are_followed_for_get_up_to_a_limit(local_client, remote): + remote.routes["/a"] = (302, {"Location": "/b"}, b"") + remote.routes["/b"] = (301, {"Location": remote.url("/c")}, b"") + remote.routes["/c"] = (200, {}, {"ok": True}) + assert local_client.get_json(remote.url("/a")) == {"ok": True} + + remote.routes["/loop"] = (302, {"Location": "/loop"}, b"") + with pytest.raises(FetchError) as err: + local_client.request("GET", remote.url("/loop")) + assert err.value.reason == "blocked" + + +def test_posts_do_not_follow_redirects(local_client, remote): + remote.routes["/inbox"] = (307, {"Location": "/elsewhere"}, b"") + assert local_client.request("POST", remote.url("/inbox"), body=b"{}").status == 307 + assert [r["path"] for r in remote.requests] == ["/inbox"] + + +def test_redirect_to_a_refused_url_is_refused(): + client = Client("test", insecure_testing=False, resolver=lambda host, port: ["93.184.215.14"]) + with pytest.raises(FetchError): + client._check_url("http://internal.example/") + + +def test_oversized_responses_are_cut_off(local_client, remote): + remote.routes["/big"] = (200, {}, b"x" * (MAX_BYTES + 1)) + with pytest.raises(FetchError) as err: + local_client.request("GET", remote.url("/big")) + assert err.value.reason == "too_large" + + +def test_http_errors_and_bad_json(local_client, remote): + remote.routes["/gone"] = (410, {}, b"") + with pytest.raises(FetchError) as err: + local_client.get_json(remote.url("/gone")) + assert (err.value.reason, err.value.status) == ("http", 410) + remote.routes["/html"] = (200, {"Content-Type": "text/html"}, b"") + with pytest.raises(FetchError) as err: + local_client.get_json(remote.url("/html")) + assert err.value.reason == "invalid" + + +# --- Remote actors --------------------------------------------------------------------------- + + +def make_key(): + private = rsa.generate_private_key(public_exponent=65537, key_size=2048) + pem = ( + private.public_key() + .public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo) + .decode() + ) + return private, pem + + +def actor_doc(remote, name="bob", pem=None, **overrides): + uri = remote.url(f"/users/{name}") + doc = { + "@context": ["https://www.w3.org/ns/activitystreams"], + "id": uri, + "type": "Person", + "preferredUsername": name, + "name": name.title(), + "inbox": f"{uri}/inbox", + "endpoints": {"sharedInbox": remote.url("/inbox")}, + "publicKey": {"id": f"{uri}#main-key", "owner": uri, "publicKeyPem": pem or make_key()[1]}, + } + doc.update(overrides) + return doc + + +@pytest.fixture +def fed_remote(fed_ctx, remote): + return remote + + +def test_actor_is_fetched_signed_validated_and_cached(fed_remote): + fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote)) + actor = remote.get_actor(fed_remote.url("/users/bob")) + assert (actor.username, actor.display_name, actor.host) == ("bob", "Bob", "127.0.0.1") + assert actor.handle == "@bob@127.0.0.1" + assert actor.delivery_inbox == fed_remote.url("/inbox") + + # The fetch was signed with our instance actor's key, verifiably + sent = fed_remote.requests[0] + request = SignedRequest("GET", fed_remote.url("/users/bob"), sent["headers"], b"") + instance_public = serialization.load_pem_public_key(keys.key_for(None).public_key_pem.encode()) + verified = signatures.verify(request, lambda key_id: instance_public) + assert verified.key_id == "https://scrobble.test/actor#main-key" + + # Cached: a second lookup doesn't fetch again + remote.get_actor(fed_remote.url("/users/bob")) + assert len(fed_remote.requests) == 1 + + +@pytest.mark.parametrize( + "overrides", + [ + {"id": "https://elsewhere.example/users/bob"}, + {"type": "Note"}, + {"inbox": "https://elsewhere.example/inbox"}, + { + "publicKey": { + "id": "x#main-key", + "owner": "https://elsewhere.example/users/eve", + "publicKeyPem": "x", + } + }, + {"publicKey": None}, + ], +) +def test_invalid_actors_are_refused(fed_remote, overrides): + fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote, **overrides)) + with pytest.raises(remote.ActorError): + remote.get_actor(fed_remote.url("/users/bob")) + + +def test_unreadable_key_is_refused(fed_remote): + uri = fed_remote.url("/users/bob") + doc = actor_doc(fed_remote) + doc["publicKey"]["publicKeyPem"] = "not a key" + fed_remote.routes["/users/bob"] = (200, {}, doc) + with pytest.raises(remote.ActorError): + remote.get_actor(uri) + + +def test_refresh_picks_up_a_rotated_key(fed_remote): + uri = fed_remote.url("/users/bob") + fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote, pem=make_key()[1])) + first = remote.get_actor(uri).public_key_pem + new_pem = make_key()[1] + fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote, pem=new_pem)) + assert remote.get_actor(uri).public_key_pem == first # cached + assert remote.get_actor(uri, refresh=True).public_key_pem == new_pem + + +def test_stale_cache_is_refetched(fed_remote): + uri = fed_remote.url("/users/bob") + fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote)) + actor = remote.get_actor(uri) + actor.fetched_at = datetime.now(UTC) - timedelta(hours=25) + db.session.commit() + remote.get_actor(uri) + assert len(fed_remote.requests) == 2 + + +def test_actor_for_key(fed_remote): + fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote)) + actor = remote.actor_for_key(fed_remote.url("/users/bob#main-key")) + assert actor.username == "bob" + with pytest.raises(remote.ActorError): + remote.actor_for_key(fed_remote.url("/users/bob#other-key")) + + +def test_actor_for_a_standalone_key_document(fed_remote): + uri = fed_remote.url("/users/carol") + doc = actor_doc(fed_remote, name="carol") + key_id = fed_remote.url("/keys/carol") + doc["publicKey"]["id"] = key_id + fed_remote.routes["/users/carol"] = (200, {}, doc) + fed_remote.routes["/keys/carol"] = ( + 200, + {}, + {"id": key_id, "owner": uri, "publicKeyPem": doc["publicKey"]["publicKeyPem"]}, + ) + assert remote.actor_for_key(key_id).uri == uri + + +def test_gone_actors_are_marked(fed_remote): + uri = fed_remote.url("/users/bob") + fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote)) + remote.get_actor(uri) + fed_remote.routes["/users/bob"] = (410, {}, b"") + with pytest.raises(FetchError): + remote.get_actor(uri, refresh=True) + assert db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=uri)).gone is True diff --git a/uv.lock b/uv.lock index 411d956..f2e3770 100644 --- a/uv.lock +++ b/uv.lock @@ -73,6 +73,15 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" }, ] +[[package]] +name = "certifi" +version = "2026.7.22" +source = { registry = "https://pypi.org/simple" } +sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" }, +] + [[package]] name = "cffi" version = "2.1.1" @@ -305,6 +314,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, ] +[[package]] +name = "httpcore" +version = "1.0.9" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "certifi" }, + { name = "h11" }, +] +sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" }, +] + [[package]] name = "httpcore2" version = "2.13.1" @@ -969,6 +991,7 @@ dependencies = [ { name = "flask-smorest" }, { name = "flask-sqlalchemy" }, { name = "gunicorn" }, + { name = "httpcore" }, { name = "prometheus-client" }, { name = "psycopg", extra = ["binary"] }, { name = "python-dotenv" }, @@ -992,6 +1015,7 @@ requires-dist = [ { name = "flask-smorest", specifier = ">=0.47.0" }, { name = "flask-sqlalchemy", specifier = ">=3.1.1" }, { name = "gunicorn", specifier = ">=26.2.0" }, + { name = "httpcore", specifier = ">=1.0.9" }, { name = "prometheus-client", specifier = ">=0.26.0" }, { name = "psycopg", extras = ["binary"], specifier = ">=3.3.6" }, { name = "python-dotenv", specifier = ">=1.2.3" }, From d49aa72be1780481f95e4c84ffae3e876934f6c0 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 21:23:15 +0100 Subject: [PATCH 22/56] Federation tables for followers, inbox and deliveries (phase 2, step 3) New tables on the federation migration branch: followers (pending or accepted, with the Follow activity), per-user blocks, the inbox queue (raw deliveries awaiting verification, deduplicated by activity id), our outgoing activities, and deliveries (per inbox, with retry state). Inbox URLs are capped at 1024 characters (remote actors are validated against it) so the delivery unique index stays within Postgres's btree limit; the remote actor inbox columns shrink to match. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/federation/models.py | 123 ++++++++++++++- src/scrobbler/federation/remote.py | 7 +- ...3_federation_followers_inbox_deliveries.py | 148 ++++++++++++++++++ 3 files changed, 272 insertions(+), 6 deletions(-) create mode 100644 src/scrobbler/migrations/versions/a481855fcb93_federation_followers_inbox_deliveries.py diff --git a/src/scrobbler/federation/models.py b/src/scrobbler/federation/models.py index cd3f297..f8db629 100644 --- a/src/scrobbler/federation/models.py +++ b/src/scrobbler/federation/models.py @@ -3,8 +3,20 @@ is a foreign key to users. Migrations live on the `federation` Alembic branch."" from datetime import UTC, datetime -from sqlalchemy import Boolean, DateTime, ForeignKey, Integer, LargeBinary, String, Text -from sqlalchemy.orm import Mapped, mapped_column +from sqlalchemy import ( + JSON, + Boolean, + DateTime, + ForeignKey, + Index, + Integer, + LargeBinary, + String, + Text, + UniqueConstraint, +) +from sqlalchemy.dialects.postgresql import JSONB +from sqlalchemy.orm import Mapped, mapped_column, relationship from scrobbler.extensions import db @@ -56,8 +68,8 @@ class FederationRemoteActor(db.Model): id: Mapped[int] = mapped_column(Integer, primary_key=True) uri: Mapped[str] = mapped_column(String(2048), unique=True) host: Mapped[str] = mapped_column(String(255), index=True) - inbox: Mapped[str] = mapped_column(String(2048)) - shared_inbox: Mapped[str | None] = mapped_column(String(2048)) + inbox: Mapped[str] = mapped_column(String(1024)) + shared_inbox: Mapped[str | None] = mapped_column(String(1024)) username: Mapped[str | None] = mapped_column(String(255)) # preferredUsername display_name: Mapped[str | None] = mapped_column(String(255)) public_key_id: Mapped[str] = mapped_column(String(2048), index=True) @@ -72,3 +84,106 @@ class FederationRemoteActor(db.Model): @property def delivery_inbox(self) -> str: return self.shared_inbox or self.inbox + + +class FederationFollower(db.Model): + """A remote actor following one of our users.""" + + __tablename__ = "federation_followers" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True) + remote_actor_id: Mapped[int] = mapped_column( + ForeignKey("federation_remote_actors.id", ondelete="CASCADE") + ) + state: Mapped[str] = mapped_column(String(16)) # pending or accepted + follow_activity_id: Mapped[str] = mapped_column(String(2048)) + follow_activity: Mapped[dict] = mapped_column(JSON().with_variant(JSONB, "postgresql")) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + accepted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + actor: Mapped[FederationRemoteActor] = relationship(lazy="joined") + + __table_args__ = ( + UniqueConstraint("user_id", "remote_actor_id", name="uq_federation_follower"), + ) + + +class FederationBlock(db.Model): + """A user blocking a remote actor (their follows are refused).""" + + __tablename__ = "federation_blocks" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True) + remote_actor_id: Mapped[int] = mapped_column( + ForeignKey("federation_remote_actors.id", ondelete="CASCADE") + ) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + actor: Mapped[FederationRemoteActor] = relationship(lazy="joined") + + __table_args__ = (UniqueConstraint("user_id", "remote_actor_id", name="uq_federation_block"),) + + +class FederationInboxItem(db.Model): + """A delivery received at an inbox, queued for the worker to verify and process.""" + + __tablename__ = "federation_inbox" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + activity_id: Mapped[str] = mapped_column(String(2048), unique=True) + activity_type: Mapped[str] = mapped_column(String(64)) + actor_uri: Mapped[str] = mapped_column(String(2048)) + inbox_path: Mapped[str] = mapped_column(String(512)) # as received, for the signature + headers: Mapped[dict] = mapped_column(JSON().with_variant(JSONB, "postgresql")) + body: Mapped[bytes] = mapped_column(LargeBinary) + status: Mapped[str] = mapped_column( + String(16), default="queued" + ) # queued, processed, rejected, failed + reason: Mapped[str | None] = mapped_column(String(255)) + attempts: Mapped[int] = mapped_column(Integer, default=0) + received_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + processed_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + __table_args__ = (Index("ix_federation_inbox_status_received", "status", "received_at"),) + + +class FederationActivity(db.Model): + """An activity we sent (Accept, Reject, Block; posts in phase 3).""" + + __tablename__ = "federation_activities" + + id: Mapped[str] = mapped_column(String(36), primary_key=True) # UUID, part of its URL + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True) + activity_type: Mapped[str] = mapped_column(String(64)) + document: Mapped[dict] = mapped_column(JSON().with_variant(JSONB, "postgresql")) + public: Mapped[bool] = mapped_column(Boolean, default=False) # may be fetched by anyone + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + +class FederationDelivery(db.Model): + """One activity to one inbox, with retries.""" + + __tablename__ = "federation_deliveries" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + activity_id: Mapped[str] = mapped_column( + ForeignKey("federation_activities.id", ondelete="CASCADE"), index=True + ) + inbox: Mapped[str] = mapped_column(String(1024)) # keeps the unique index small + # pending, delivered, failed or abandoned + status: Mapped[str] = mapped_column(String(16), default="pending") + attempts: Mapped[int] = mapped_column(Integer, default=0) + next_attempt_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + last_status: Mapped[int | None] = mapped_column(Integer) + last_error: Mapped[str | None] = mapped_column(Text) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + delivered_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + activity: Mapped[FederationActivity] = relationship(lazy="joined") + + __table_args__ = ( + UniqueConstraint("activity_id", "inbox", name="uq_federation_delivery"), + Index("ix_federation_deliveries_due", "status", "next_attempt_at"), + ) diff --git a/src/scrobbler/federation/remote.py b/src/scrobbler/federation/remote.py index 8253c4e..e244236 100644 --- a/src/scrobbler/federation/remote.py +++ b/src/scrobbler/federation/remote.py @@ -19,6 +19,7 @@ from scrobbler.federation.net import FetchError ACTOR_TYPES = {"Person", "Service", "Application", "Group", "Organization"} MAX_AGE = timedelta(hours=24) +MAX_URL = 1024 class ActorError(Exception): @@ -34,17 +35,19 @@ def _text(value, limit: int) -> str | None: def _parse_actor(uri: str, doc: dict) -> dict: + if len(uri) > 2048: + raise ActorError("actor URI too long") if doc.get("id") != uri: raise ActorError(f"{uri} claims to be {doc.get('id')!r}") if doc.get("type") not in ACTOR_TYPES: raise ActorError(f"{uri} isn't an actor ({doc.get('type')!r})") host = _host(uri) inbox = doc.get("inbox") - if not isinstance(inbox, str) or _host(inbox) != host: + if not isinstance(inbox, str) or _host(inbox) != host or len(inbox) > MAX_URL: raise ActorError(f"{uri} has no inbox on its own host") endpoints = doc.get("endpoints") if isinstance(doc.get("endpoints"), dict) else {} shared = endpoints.get("sharedInbox") - if not isinstance(shared, str) or _host(shared) != host: + if not isinstance(shared, str) or _host(shared) != host or len(shared) > MAX_URL: shared = None key = doc.get("publicKey") if isinstance(key, list): # some servers list several diff --git a/src/scrobbler/migrations/versions/a481855fcb93_federation_followers_inbox_deliveries.py b/src/scrobbler/migrations/versions/a481855fcb93_federation_followers_inbox_deliveries.py new file mode 100644 index 0000000..74e77b7 --- /dev/null +++ b/src/scrobbler/migrations/versions/a481855fcb93_federation_followers_inbox_deliveries.py @@ -0,0 +1,148 @@ +"""federation followers inbox deliveries + +Revision ID: a481855fcb93 +Revises: 211d4743f081 +Create Date: 2026-09-25 21:22:22.746321 + +""" +from alembic import op +import sqlalchemy as sa +from sqlalchemy.dialects import postgresql + +# revision identifiers, used by Alembic. +revision = 'a481855fcb93' +down_revision = '211d4743f081' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('federation_inbox', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('activity_id', sa.String(length=2048), nullable=False), + sa.Column('activity_type', sa.String(length=64), nullable=False), + sa.Column('actor_uri', sa.String(length=2048), nullable=False), + sa.Column('inbox_path', sa.String(length=512), nullable=False), + sa.Column('headers', sa.JSON().with_variant(postgresql.JSONB(astext_type=sa.Text()), 'postgresql'), nullable=False), + sa.Column('body', sa.LargeBinary(), nullable=False), + sa.Column('status', sa.String(length=16), nullable=False), + sa.Column('reason', sa.String(length=255), nullable=True), + sa.Column('attempts', sa.Integer(), nullable=False), + sa.Column('received_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('processed_at', sa.DateTime(timezone=True), nullable=True), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('activity_id') + ) + with op.batch_alter_table('federation_inbox', schema=None) as batch_op: + batch_op.create_index('ix_federation_inbox_status_received', ['status', 'received_at'], unique=False) + + op.create_table('federation_activities', + sa.Column('id', sa.String(length=36), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('activity_type', sa.String(length=64), nullable=False), + sa.Column('document', sa.JSON().with_variant(postgresql.JSONB(astext_type=sa.Text()), 'postgresql'), nullable=False), + sa.Column('public', sa.Boolean(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id') + ) + with op.batch_alter_table('federation_activities', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_federation_activities_user_id'), ['user_id'], unique=False) + + op.create_table('federation_blocks', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('remote_actor_id', sa.Integer(), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.ForeignKeyConstraint(['remote_actor_id'], ['federation_remote_actors.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('user_id', 'remote_actor_id', name='uq_federation_block') + ) + with op.batch_alter_table('federation_blocks', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_federation_blocks_user_id'), ['user_id'], unique=False) + + op.create_table('federation_followers', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('remote_actor_id', sa.Integer(), nullable=False), + sa.Column('state', sa.String(length=16), nullable=False), + sa.Column('follow_activity_id', sa.String(length=2048), nullable=False), + sa.Column('follow_activity', sa.JSON().with_variant(postgresql.JSONB(astext_type=sa.Text()), 'postgresql'), nullable=False), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('accepted_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['remote_actor_id'], ['federation_remote_actors.id'], ondelete='CASCADE'), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('user_id', 'remote_actor_id', name='uq_federation_follower') + ) + with op.batch_alter_table('federation_followers', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_federation_followers_user_id'), ['user_id'], unique=False) + + op.create_table('federation_deliveries', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('activity_id', sa.String(length=36), nullable=False), + sa.Column('inbox', sa.String(length=1024), nullable=False), + sa.Column('status', sa.String(length=16), nullable=False), + sa.Column('attempts', sa.Integer(), nullable=False), + sa.Column('next_attempt_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('last_status', sa.Integer(), nullable=True), + sa.Column('last_error', sa.Text(), nullable=True), + sa.Column('created_at', sa.DateTime(timezone=True), nullable=False), + sa.Column('delivered_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['activity_id'], ['federation_activities.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('id'), + sa.UniqueConstraint('activity_id', 'inbox', name='uq_federation_delivery') + ) + with op.batch_alter_table('federation_deliveries', schema=None) as batch_op: + batch_op.create_index(batch_op.f('ix_federation_deliveries_activity_id'), ['activity_id'], unique=False) + batch_op.create_index('ix_federation_deliveries_due', ['status', 'next_attempt_at'], unique=False) + + with op.batch_alter_table('federation_remote_actors', schema=None) as batch_op: + batch_op.alter_column('inbox', + existing_type=sa.VARCHAR(length=2048), + type_=sa.String(length=1024), + existing_nullable=False) + batch_op.alter_column('shared_inbox', + existing_type=sa.VARCHAR(length=2048), + type_=sa.String(length=1024), + existing_nullable=True) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('federation_remote_actors', schema=None) as batch_op: + batch_op.alter_column('shared_inbox', + existing_type=sa.String(length=1024), + type_=sa.VARCHAR(length=2048), + existing_nullable=True) + batch_op.alter_column('inbox', + existing_type=sa.String(length=1024), + type_=sa.VARCHAR(length=2048), + existing_nullable=False) + + with op.batch_alter_table('federation_deliveries', schema=None) as batch_op: + batch_op.drop_index('ix_federation_deliveries_due') + batch_op.drop_index(batch_op.f('ix_federation_deliveries_activity_id')) + + op.drop_table('federation_deliveries') + with op.batch_alter_table('federation_followers', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_federation_followers_user_id')) + + op.drop_table('federation_followers') + with op.batch_alter_table('federation_blocks', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_federation_blocks_user_id')) + + op.drop_table('federation_blocks') + with op.batch_alter_table('federation_activities', schema=None) as batch_op: + batch_op.drop_index(batch_op.f('ix_federation_activities_user_id')) + + op.drop_table('federation_activities') + with op.batch_alter_table('federation_inbox', schema=None) as batch_op: + batch_op.drop_index('ix_federation_inbox_status_received') + + op.drop_table('federation_inbox') + # ### end Alembic commands ### From c1a7dd087767ebe2d0e85514bad498443b238fff Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 21:24:41 +0100 Subject: [PATCH 23/56] Worker tasks are registered per app The task registry was module-global, so tasks registered by an app with federation enabled would also run under an app without it (and break the "federation off registers nothing" guarantee depending on order). Tasks now live on each app (app.extensions["worker_tasks"]); register_task/register_periodic take the app, and the worker runs the current app's tasks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/__init__.py | 2 +- src/scrobbler/services/imports.py | 6 ++--- src/scrobbler/worker.py | 32 ++++++++++++++----------- tests/test_federation_boundary.py | 2 +- tests/test_worker.py | 39 +++++++++++++++++++++++++------ 5 files changed, 56 insertions(+), 25 deletions(-) diff --git a/src/scrobbler/__init__.py b/src/scrobbler/__init__.py index 1433f55..02267e4 100644 --- a/src/scrobbler/__init__.py +++ b/src/scrobbler/__init__.py @@ -46,7 +46,7 @@ def create_app(config_object=None): app.cli.add_command(worker_command) app.cli.add_command(imports_cli) - import_service.register_worker_tasks() + import_service.register_worker_tasks(app) from scrobbler.metrics import db as db_metrics diff --git a/src/scrobbler/services/imports.py b/src/scrobbler/services/imports.py index 58a6978..decfba1 100644 --- a/src/scrobbler/services/imports.py +++ b/src/scrobbler/services/imports.py @@ -580,8 +580,8 @@ def work_once() -> bool: return True -def register_worker_tasks() -> None: +def register_worker_tasks(app) -> None: from scrobbler import worker - worker.register_task("imports", work_once) - worker.register_periodic("imports.requeue_stalled", 60, requeue_stalled) + worker.register_task(app, "imports", work_once) + worker.register_periodic(app, "imports.requeue_stalled", 60, requeue_stalled) diff --git a/src/scrobbler/worker.py b/src/scrobbler/worker.py index c69decb..4ff53b1 100644 --- a/src/scrobbler/worker.py +++ b/src/scrobbler/worker.py @@ -1,10 +1,11 @@ """The background worker: runs tasks that modules register (`flask worker`). -Modules register work at app start-up; the worker itself knows nothing about them. +Modules register work on an app at start-up; the worker itself knows nothing about them. +Each app has its own tasks, so apps with different modules enabled never share them. - register_task(name, fn) fn() -> bool: True if it did some work. - Called repeatedly while there's work. - register_periodic(name, seconds, fn) fn() every `seconds` (and once at start). + register_task(app, name, fn) fn() -> bool: True if it did some work. + Called repeatedly while there's work. + register_periodic(app, name, seconds, fn) fn() every `seconds` (and once at start). A task that raises is logged, counted and rolled back; the other tasks keep running. """ @@ -14,6 +15,8 @@ import time from collections.abc import Callable from dataclasses import dataclass +from flask import Flask, current_app + from scrobbler import metrics from scrobbler.extensions import db @@ -28,19 +31,22 @@ class _Task: next_run: float = 0.0 # monotonic time; 0 = run at the first opportunity -_tasks: dict[str, _Task] = {} +def tasks(app: Flask | None = None) -> dict[str, _Task]: + return (app or current_app).extensions.setdefault("worker_tasks", {}) -def register_task(name: str, fn: Callable[[], bool]) -> None: - _tasks[name] = _Task(name, fn) +def register_task(app: Flask, name: str, fn: Callable[[], bool]) -> None: + tasks(app)[name] = _Task(name, fn) -def register_periodic(name: str, every_seconds: float, fn: Callable[[], object]) -> None: - _tasks[name] = _Task(name, fn, every=every_seconds) +def register_periodic( + app: Flask, name: str, every_seconds: float, fn: Callable[[], object] +) -> None: + tasks(app)[name] = _Task(name, fn, every=every_seconds) -def registered() -> list[str]: - return sorted(_tasks) +def registered(app: Flask | None = None) -> list[str]: + return sorted(tasks(app)) def _call(task: _Task) -> bool: @@ -61,7 +67,7 @@ def run_once() -> bool: task did work (so there may be more waiting).""" now = time.monotonic() worked = False - for task in list(_tasks.values()): + for task in list(tasks().values()): if task.every is not None: if now >= task.next_run: task.next_run = now + task.every @@ -73,7 +79,7 @@ def run_once() -> bool: def run(poll_seconds: float = 2.0, once: bool = False) -> None: """Run until stopped. With once=True, run until there's no more work, then return.""" - for task in _tasks.values(): + for task in tasks().values(): task.next_run = 0.0 while True: if run_once(): diff --git a/tests/test_federation_boundary.py b/tests/test_federation_boundary.py index 09d459c..88a4580 100644 --- a/tests/test_federation_boundary.py +++ b/tests/test_federation_boundary.py @@ -167,7 +167,7 @@ def test_nothing_is_registered_when_federation_is_off(app): assert views == [] for signal in (events.scrobbles_stored, events.now_playing_changed, events.import_finished): assert not any(_from_federation(r) for r in signal.receivers_for(None)) - assert not any(name.startswith("federation") for name in worker.registered()) + assert not any(name.startswith("federation") for name in worker.registered(app)) class _Enabled(TestConfig): diff --git a/tests/test_worker.py b/tests/test_worker.py index 36ae8a4..fb3ab0d 100644 --- a/tests/test_worker.py +++ b/tests/test_worker.py @@ -3,18 +3,43 @@ import pytest from scrobbler import worker +class _Registry: + """The worker module, bound to the test app, with an emptied task registry.""" + + def __init__(self, app): + self.app = app + + def register_task(self, name, fn): + worker.register_task(self.app, name, fn) + + def register_periodic(self, name, every, fn): + worker.register_periodic(self.app, name, every, fn) + + def run(self, **kwargs): + worker.run(**kwargs) + + @pytest.fixture def tasks(app): - """An empty task registry for the test, restored afterwards.""" - saved = dict(worker._tasks) - worker._tasks.clear() - yield worker - worker._tasks.clear() - worker._tasks.update(saved) + """An empty task registry for the test app, restored afterwards.""" + registry = worker.tasks(app) + saved = dict(registry) + registry.clear() + yield _Registry(app) + registry.clear() + registry.update(saved) def test_imports_are_registered_by_the_app(app): - assert {"imports", "imports.requeue_stalled"} <= set(worker.registered()) + assert {"imports", "imports.requeue_stalled"} <= set(worker.registered(app)) + + +def test_apps_have_their_own_tasks(app, fed_app): + worker.register_task(fed_app, "only-on-fed-app", lambda: False) + try: + assert "only-on-fed-app" not in worker.registered(app) + finally: + worker.tasks(fed_app).pop("only-on-fed-app") def test_queue_tasks_run_until_there_is_no_work(tasks, metric_delta): From f312c4b5779f25245aeb0210dd4990d286b2a52a Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 21:29:55 +0100 Subject: [PATCH 24/56] Inbox: intake and verified processing of follows (phase 2, step 4) Intake (in the request, no network): size, content type and shape checks, blocked domains refused (403), duplicates acknowledged once, then stored and answered 202. Processing (federation.inbox worker task): - verify the HTTP signature with either scheme, as of when it arrived, using the cached key and refreshing the sender once on failure (key rotation); a deleted account's Delete still verifies from cache - the signer must be the activity's actor and the activity id must be on the actor's host - handlers: Follow (accept, or pending with manual approval; repeat follows re-accepted; blocked accounts rejected), Undo of a Follow (only by the same actor), Delete of an actor, Update of an actor; anything else recorded - items being processed are marked, retried on transient failures, re-queued if a worker dies, and pruned after 30 days Outgoing Accept/Reject/Block activities are stored with stable ids and queued per inbox for the delivery task (next step). Public activities are fetchable at /activities/. Metrics for inbox activities and signature checks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/openapi.json | 81 ++++- src/scrobbler/federation/__init__.py | 6 + src/scrobbler/federation/activities.py | 70 +++++ src/scrobbler/federation/followers.py | 124 ++++++++ src/scrobbler/federation/ids.py | 36 +++ src/scrobbler/federation/inbox.py | 321 ++++++++++++++++++++ src/scrobbler/federation/metrics.py | 15 +- src/scrobbler/federation/openapi.py | 31 +- src/scrobbler/federation/outbound.py | 14 +- src/scrobbler/federation/protocol/vocab.py | 32 ++ src/scrobbler/federation/remote.py | 4 +- src/scrobbler/federation/web.py | 42 ++- tests/federation_helpers.py | 85 ++++++ tests/test_federation_inbox.py | 327 +++++++++++++++++++++ tests/test_federation_web.py | 19 -- 15 files changed, 1147 insertions(+), 60 deletions(-) create mode 100644 src/scrobbler/federation/activities.py create mode 100644 src/scrobbler/federation/followers.py create mode 100644 src/scrobbler/federation/ids.py create mode 100644 src/scrobbler/federation/inbox.py create mode 100644 tests/federation_helpers.py create mode 100644 tests/test_federation_inbox.py diff --git a/docs/openapi.json b/docs/openapi.json index 3138115..d782bfe 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -2340,17 +2340,26 @@ "ActivityPub" ], "summary": "User inbox", - "description": "Receives activities for one user (signed deliveries).", + "description": "Receives signed activities for one user. They're stored and answered with 202, then verified and processed in the background.", "operationId": "federation_user_inbox", "responses": { "202": { - "description": "Accepted" + "description": "Accepted for processing (also for a repeated activity)" + }, + "400": { + "description": "Not an activity with an id, type and actor" + }, + "403": { + "description": "The sender's domain is blocked" }, "404": { - "description": "Unknown, or not sharing (the two are indistinguishable)" + "description": "No such user sharing (user inbox)" }, "413": { - "description": "Too large" + "description": "Larger than 256 KB" + }, + "415": { + "description": "Not ActivityPub JSON" } }, "parameters": [ @@ -2391,14 +2400,26 @@ "ActivityPub" ], "summary": "Shared inbox", - "description": "Receives activities for any user on this server.", + "description": "Receives signed activities for any user on this server (as for the user inbox).", "operationId": "federation_shared_inbox", "responses": { "202": { - "description": "Accepted" + "description": "Accepted for processing (also for a repeated activity)" + }, + "400": { + "description": "Not an activity with an id, type and actor" + }, + "403": { + "description": "The sender's domain is blocked" + }, + "404": { + "description": "No such user sharing (user inbox)" }, "413": { - "description": "Too large" + "description": "Larger than 256 KB" + }, + "415": { + "description": "Not ActivityPub JSON" } }, "requestBody": { @@ -2411,6 +2432,52 @@ } } } + }, + "/activities/{activity_uuid}": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "Activity", + "description": "One of our activities, when public. Replies to follows aren't public.", + "operationId": "federation_activity", + "responses": { + "200": { + "description": "Activity", + "content": { + "application/activity+json": { + "schema": { + "type": "object" + } + } + } + }, + "404": { + "description": "Not found or not public" + } + }, + "parameters": [ + { + "name": "activity_uuid", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "activity_uuid", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ] } }, "tags": [ diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py index 769b0f1..622b3ac 100644 --- a/src/scrobbler/federation/__init__.py +++ b/src/scrobbler/federation/__init__.py @@ -35,3 +35,9 @@ def init_app(app: Flask) -> None: core_api = get_api(app) core_api.register_blueprint(api.blp, url_prefix="/api/v1/federation") openapi.register(app, core_api) + + from scrobbler import worker + from scrobbler.federation import inbox + + worker.register_task(app, "federation.inbox", inbox.work_once) + worker.register_periodic(app, "federation.inbox.maintenance", 300, inbox.maintenance) diff --git a/src/scrobbler/federation/activities.py b/src/scrobbler/federation/activities.py new file mode 100644 index 0000000..2b5691e --- /dev/null +++ b/src/scrobbler/federation/activities.py @@ -0,0 +1,70 @@ +"""Activities we send: stored (so they have a stable id) and queued for delivery.""" + +import uuid + +from scrobbler.extensions import db +from scrobbler.federation import ids +from scrobbler.federation.models import ( + FederationActivity, + FederationDelivery, + FederationFollower, + FederationRemoteActor, +) +from scrobbler.federation.protocol import vocab + + +def _store(user_id: int, document_for, public: bool = False) -> FederationActivity: + """Create an activity. `document_for(activity_url)` builds its JSON.""" + activity_uuid = str(uuid.uuid4()) + document = document_for(ids.activity_url(activity_uuid)) + activity = FederationActivity( + id=activity_uuid, + user_id=user_id, + activity_type=document["type"], + document=document, + public=public, + ) + db.session.add(activity) + return activity + + +def queue(activity: FederationActivity, inboxes: list[str]) -> list[FederationDelivery]: + deliveries = [ + FederationDelivery(activity_id=activity.id, inbox=inbox) + for inbox in dict.fromkeys(inboxes) # one per distinct inbox + ] + db.session.add_all(deliveries) + return deliveries + + +def accept_follow(username: str, follower: FederationFollower) -> FederationActivity: + activity = _store( + follower.user_id, + lambda url: vocab.accept(url, ids.actor_id(username), follower.follow_activity), + ) + queue(activity, [follower.actor.inbox]) # replies go to their own inbox + return activity + + +def reject_follow(username: str, follower: FederationFollower) -> FederationActivity: + activity = _store( + follower.user_id, + lambda url: vocab.reject(url, ids.actor_id(username), follower.follow_activity), + ) + queue(activity, [follower.actor.inbox]) + return activity + + +def reject_follow_activity( + user_id: int, username: str, follow: dict, actor: FederationRemoteActor +) -> FederationActivity: + """Reject a Follow that never became a follower (e.g. from a blocked account).""" + activity = _store(user_id, lambda url: vocab.reject(url, ids.actor_id(username), follow)) + queue(activity, [actor.inbox]) + return activity + + +def block(user_id: int, username: str, actor: FederationRemoteActor) -> FederationActivity: + activity = _store(user_id, lambda url: vocab.block(url, ids.actor_id(username), actor.uri)) + queue(activity, [actor.inbox]) + return activity diff --git a/src/scrobbler/federation/followers.py b/src/scrobbler/federation/followers.py new file mode 100644 index 0000000..36004c4 --- /dev/null +++ b/src/scrobbler/federation/followers.py @@ -0,0 +1,124 @@ +"""Follower state changes, from incoming activities and from the user's own actions. + +Every change that the other server needs to know about queues an activity (Accept, +Reject or Block); the delivery task sends it. Callers commit. +""" + +from datetime import UTC, datetime + +from scrobbler.extensions import db +from scrobbler.federation import activities +from scrobbler.federation.models import FederationBlock, FederationFollower, FederationRemoteActor + + +def _now() -> datetime: + return datetime.now(UTC) + + +def get(user_id: int, actor: FederationRemoteActor) -> FederationFollower | None: + return db.session.scalar( + db.select(FederationFollower).filter_by(user_id=user_id, remote_actor_id=actor.id) + ) + + +def is_blocked(user_id: int, actor: FederationRemoteActor) -> bool: + return ( + db.session.scalar( + db.select(FederationBlock).filter_by(user_id=user_id, remote_actor_id=actor.id) + ) + is not None + ) + + +def follow_received( + user_id: int, username: str, manual_approval: bool, actor: FederationRemoteActor, follow: dict +) -> str: + """Handle a Follow. Returns what happened: accepted, pending, refollowed or blocked.""" + if is_blocked(user_id, actor): + activities.reject_follow_activity(user_id, username, follow, actor) + return "blocked" + follower = get(user_id, actor) + if follower is not None: + # A repeat Follow (e.g. they lost our Accept): keep the newest activity and + # answer again if we'd already accepted. + follower.follow_activity_id, follower.follow_activity = follow["id"], follow + if follower.state == "accepted": + activities.accept_follow(username, follower) + return "refollowed" + return "pending" + follower = FederationFollower( + user_id=user_id, + remote_actor_id=actor.id, + actor=actor, + state="pending" if manual_approval else "accepted", + follow_activity_id=follow["id"], + follow_activity=follow, + accepted_at=None if manual_approval else _now(), + ) + db.session.add(follower) + db.session.flush() + if not manual_approval: + activities.accept_follow(username, follower) + return "accepted" + return "pending" + + +def undo_follow(user_id: int, actor: FederationRemoteActor) -> bool: + follower = get(user_id, actor) + if follower is None: + return False + db.session.delete(follower) + return True + + +def actor_deleted(actor: FederationRemoteActor) -> int: + """The remote account was deleted: it follows no one here any more.""" + followers = db.session.scalars( + db.select(FederationFollower).filter_by(remote_actor_id=actor.id) + ).all() + for follower in followers: + db.session.delete(follower) + actor.gone = True + return len(followers) + + +# --- The user's own actions -------------------------------------------------------------- + + +def approve(username: str, follower: FederationFollower) -> None: + if follower.state != "pending": + return + follower.state, follower.accepted_at = "accepted", _now() + activities.accept_follow(username, follower) + + +def remove(username: str, follower: FederationFollower) -> None: + """Decline a request or remove a follower: both are a Reject for the other server.""" + activities.reject_follow(username, follower) + db.session.delete(follower) + + +def block(username: str, follower: FederationFollower) -> FederationBlock: + blocked = FederationBlock(user_id=follower.user_id, remote_actor_id=follower.remote_actor_id) + db.session.add(blocked) + activities.block(follower.user_id, username, follower.actor) + db.session.delete(follower) + return blocked + + +def reject_all(user_id: int, username: str) -> int: + """Sharing switched off: tell every follower, then forget them.""" + followers = db.session.scalars(db.select(FederationFollower).filter_by(user_id=user_id)).all() + for follower in followers: + remove(username, follower) + return len(followers) + + +def counts(user_id: int) -> dict[str, int]: + rows = db.session.execute( + db.select(FederationFollower.state, db.func.count()) + .filter_by(user_id=user_id) + .group_by(FederationFollower.state) + ).all() + found = dict(rows) + return {"accepted": found.get("accepted", 0), "pending": found.get("pending", 0)} diff --git a/src/scrobbler/federation/ids.py b/src/scrobbler/federation/ids.py new file mode 100644 index 0000000..8fa139d --- /dev/null +++ b/src/scrobbler/federation/ids.py @@ -0,0 +1,36 @@ +"""Our ActivityPub IDs, all built from FEDERATION_BASE_URL (never the request).""" + +from flask import current_app + + +def base_url() -> str: + return current_app.extensions["federation"].base_url + + +def actor_id(username: str) -> str: + return f"{base_url()}/users/{username}" + + +def key_id(username: str) -> str: + return f"{actor_id(username)}#main-key" + + +def instance_actor_id() -> str: + return f"{base_url()}/actor" + + +def instance_key_id() -> str: + return f"{instance_actor_id()}#main-key" + + +def activity_url(activity_uuid: str) -> str: + return f"{base_url()}/activities/{activity_uuid}" + + +def username_from_actor_id(uri: str | None) -> str | None: + """`/users/` -> name; None for anything else.""" + prefix = f"{base_url()}/users/" + if not uri or not uri.startswith(prefix): + return None + name = uri[len(prefix) :] + return name if name and "/" not in name and "#" not in name and "?" not in name else None diff --git a/src/scrobbler/federation/inbox.py b/src/scrobbler/federation/inbox.py new file mode 100644 index 0000000..2dc735f --- /dev/null +++ b/src/scrobbler/federation/inbox.py @@ -0,0 +1,321 @@ +"""Receiving activities. + +Intake (in the request): cheap checks only, then store and answer 202. No network calls, +so a flood of deliveries can't make us fetch things. + +Processing (the `federation.inbox` worker task): verify the HTTP signature (fetching the +sender's key), check the sender is who the activity says, then dispatch by type. +""" + +import json +import logging +from collections.abc import Callable +from datetime import UTC, datetime, timedelta +from urllib.parse import urlsplit + +from flask import current_app +from sqlalchemy import delete, update +from sqlalchemy.exc import IntegrityError + +from scrobbler.extensions import db +from scrobbler.federation import followers, ids, remote, sharing +from scrobbler.federation import metrics as fed_metrics +from scrobbler.federation.models import FederationInboxItem, FederationRemoteActor +from scrobbler.federation.net import FetchError +from scrobbler.federation.protocol import signatures +from scrobbler.federation.protocol.signatures import SignatureError, SignedRequest +from scrobbler.federation.protocol.vocab import object_id + +log = logging.getLogger(__name__) + +MAX_BYTES = 256 * 1024 +MAX_ATTEMPTS = 3 +KEPT_FOR = timedelta(days=30) +STALE_AFTER = timedelta(minutes=10) +# Only what signature checks need is kept from the request. +KEPT_HEADERS = ( + "host", + "date", + "digest", + "content-digest", + "signature", + "signature-input", + "authorization", + "content-type", + "content-length", +) +# Metric labels are limited to these; anything else is "other". +KNOWN_TYPES = { + "Follow", + "Undo", + "Delete", + "Update", + "Accept", + "Reject", + "Like", + "Announce", + "Create", + "Add", + "Remove", + "Move", + "Block", + "Flag", + "EmojiReact", +} + + +def type_label(activity_type) -> str: + return activity_type if activity_type in KNOWN_TYPES else "other" + + +def _host(url: str) -> str: + return (urlsplit(url).hostname or "").lower() + + +def _config(): + return current_app.extensions["federation"] + + +# --- Intake ------------------------------------------------------------------------------- + + +def receive(inbox_path: str, headers: dict[str, str], body: bytes) -> tuple[int, str]: + """Store a delivery for processing. Returns (HTTP status, outcome).""" + if len(body) > MAX_BYTES: + return 413, "too_large" + try: + doc = json.loads(body) + except (json.JSONDecodeError, UnicodeDecodeError): + doc = None + activity_id = doc.get("id") if isinstance(doc, dict) else None + activity_type = doc.get("type") if isinstance(doc, dict) else None + actor = object_id(doc.get("actor")) if isinstance(doc, dict) else None + if not all(isinstance(v, str) and v for v in (activity_id, activity_type, actor)): + fed_metrics.inbox_activities_total.labels(type="other", result="invalid").inc() + return 400, "invalid" + label = type_label(activity_type) + if len(activity_id) > 2048 or len(actor) > 2048: + fed_metrics.inbox_activities_total.labels(type=label, result="invalid").inc() + return 400, "invalid" + if _config().is_blocked(_host(actor)): + fed_metrics.inbox_activities_total.labels(type=label, result="blocked").inc() + return 403, "blocked" + + kept = {k.lower(): v for k, v in headers.items() if k.lower() in KEPT_HEADERS} + db.session.add( + FederationInboxItem( + activity_id=activity_id, + activity_type=activity_type[:64], + actor_uri=actor, + inbox_path=inbox_path[:512], + headers=kept, + body=body, + ) + ) + try: + db.session.commit() + except IntegrityError: # seen this activity before + db.session.rollback() + fed_metrics.inbox_activities_total.labels(type=label, result="duplicate").inc() + return 202, "duplicate" + fed_metrics.inbox_activities_total.labels(type=label, result="queued").inc() + return 202, "queued" + + +# --- Processing ------------------------------------------------------------------------------- + + +class Rejected(Exception): + """The activity won't be acted on; `reason` says why.""" + + def __init__(self, reason: str): + self.reason = reason + super().__init__(reason) + + +Handler = Callable[[dict, FederationRemoteActor], str] +HANDLERS: dict[str, Handler] = {} + + +def handles(activity_type: str): + def register(fn: Handler) -> Handler: + HANDLERS[activity_type] = fn + return fn + + return register + + +def _verify(item: FederationInboxItem) -> FederationRemoteActor: + """Check the signature (as of when it arrived); return the signing actor.""" + request = SignedRequest("POST", ids.base_url() + item.inbox_path, item.headers, item.body) + try: + scheme = signatures.detect(request).name + except SignatureError: + fed_metrics.signatures_total.labels(direction="in", scheme="none", result="missing").inc() + raise Rejected("signature_missing") from None + signer: dict[str, FederationRemoteActor] = {} + + def public_key_for(refresh: bool): + def lookup(key_id: str): + actor = remote.actor_for_key(key_id, refresh=refresh) + signer["actor"] = actor + return remote.load_public_key(actor.public_key_pem) + + return lookup + + try: + try: + signatures.verify(request, public_key_for(False), now=item.received_at) + except SignatureError as err: + if err.reason not in ("bad_signature", "unknown_key"): + raise + # Maybe they rotated their key: fetch the actor again, once + signatures.verify(request, public_key_for(True), now=item.received_at) + except SignatureError as err: + fed_metrics.signatures_total.labels(direction="in", scheme=scheme, result=err.reason).inc() + raise Rejected(f"signature_{err.reason}") from err + except remote.ActorError as err: + fed_metrics.signatures_total.labels(direction="in", scheme=scheme, result="bad_actor").inc() + raise Rejected("bad_actor") from err + fed_metrics.signatures_total.labels(direction="in", scheme=scheme, result="ok").inc() + return signer["actor"] + + +def _handle(item: FederationInboxItem) -> str: + actor = _verify(item) + doc = json.loads(item.body) + if object_id(doc.get("actor")) != actor.uri: + raise Rejected("actor_mismatch") # signed by someone other than the actor + if _host(doc["id"]) != actor.host: + raise Rejected("id_host_mismatch") + if _config().is_blocked(actor.host): + raise Rejected("blocked_domain") + handler = HANDLERS.get(doc.get("type")) + return handler(doc, actor) if handler else "recorded" + + +def claim_next() -> FederationInboxItem | None: + item = db.session.scalar( + db.select(FederationInboxItem) + .filter_by(status="queued") + .order_by(FederationInboxItem.received_at) + .limit(1) + .with_for_update(skip_locked=True) + ) + if item is None: + db.session.rollback() + return None + item.status = "processing" # processing commits (e.g. caching actors), so mark it + item.attempts += 1 + db.session.commit() + return item + + +def process(item: FederationInboxItem) -> None: + label = type_label(item.activity_type) + try: + outcome = _handle(item) + except Rejected as rejected: + db.session.rollback() + _finish(item, "rejected", rejected.reason) + fed_metrics.inbox_activities_total.labels(type=label, result="rejected").inc() + return + except Exception as err: + db.session.rollback() + transient = isinstance(err, FetchError) and err.reason == "network" + if not transient: + log.exception("inbox item %s failed", item.id) + if item.attempts < MAX_ATTEMPTS: + _finish(item, "queued", f"retrying: {err}"[:255], done=False) + return + _finish(item, "failed", str(err)[:255]) + fed_metrics.inbox_activities_total.labels(type=label, result="failed").inc() + return + db.session.commit() + _finish(item, "processed", outcome) + fed_metrics.inbox_activities_total.labels(type=label, result="processed").inc() + + +def _finish(item: FederationInboxItem, status: str, reason: str, done: bool = True) -> None: + item = db.session.get(FederationInboxItem, item.id) + item.status, item.reason = status, reason + if done: + item.processed_at = datetime.now(UTC) + db.session.commit() + + +def work_once() -> bool: + """Worker task: process the oldest queued delivery.""" + item = claim_next() + if item is None: + return False + process(item) + return True + + +def maintenance() -> None: + """Worker task (periodic): re-queue items a dead worker left behind; drop old ones.""" + now = datetime.now(UTC) + db.session.execute( + update(FederationInboxItem) + .where(FederationInboxItem.status == "processing") + .where(FederationInboxItem.received_at < now - STALE_AFTER) + .values(status="queued") + ) + db.session.execute( + delete(FederationInboxItem) + .where(FederationInboxItem.status != "queued") + .where(FederationInboxItem.received_at < now - KEPT_FOR) + ) + db.session.commit() + + +# --- Handlers ---------------------------------------------------------------------------------- + + +def _local_user(target): + """The sharing user an activity is addressed to, or Rejected.""" + username = ids.username_from_actor_id(object_id(target)) + found = sharing.shared_user(username) if username else None + if found is None: + raise Rejected("not_our_user") + return found + + +@handles("Follow") +def on_follow(doc: dict, actor: FederationRemoteActor) -> str: + user, settings = _local_user(doc.get("object")) + outcome = followers.follow_received( + user.id, user.username, settings.manually_approves_followers, actor, doc + ) + return f"follow_{outcome}" + + +@handles("Undo") +def on_undo(doc: dict, actor: FederationRemoteActor) -> str: + inner = doc.get("object") + if not isinstance(inner, dict) or inner.get("type") != "Follow": + return "undo_ignored" + if object_id(inner.get("actor")) not in (None, actor.uri): + raise Rejected("undo_other_actors_follow") + user, _ = _local_user(inner.get("object")) + return "unfollowed" if followers.undo_follow(user.id, actor) else "undo_not_following" + + +@handles("Delete") +def on_delete(doc: dict, actor: FederationRemoteActor) -> str: + if object_id(doc.get("object")) != actor.uri: + return "delete_ignored" # a post or similar: we don't store remote content + followers.actor_deleted(actor) + return "actor_deleted" + + +@handles("Update") +def on_update(doc: dict, actor: FederationRemoteActor) -> str: + obj = doc.get("object") + if not isinstance(obj, dict) or obj.get("type") not in remote.ACTOR_TYPES: + return "update_ignored" + if object_id(obj) != actor.uri: + raise Rejected("update_other_actor") + remote.get_actor(actor.uri, refresh=True) + return "actor_updated" diff --git a/src/scrobbler/federation/metrics.py b/src/scrobbler/federation/metrics.py index b08707c..091de27 100644 --- a/src/scrobbler/federation/metrics.py +++ b/src/scrobbler/federation/metrics.py @@ -18,9 +18,14 @@ inbox_requests_total = Counter( ["inbox"], ) -# Every scrobbler_federation_* series name, for the dashboard consistency test. -SERIES = ( - "scrobbler_federation_lookups_total", - "scrobbler_federation_sharing_changes_total", - "scrobbler_federation_inbox_requests_total", +inbox_activities_total = Counter( + "scrobbler_federation_inbox_activities_total", + "Activities received: queued, duplicate, blocked or invalid at intake; then processed, " + "rejected or failed", + ["type", "result"], +) +signatures_total = Counter( + "scrobbler_federation_signatures_total", + "HTTP signature checks (in) and signing (out), by scheme and result", + ["direction", "scheme", "result"], ) diff --git a/src/scrobbler/federation/openapi.py b/src/scrobbler/federation/openapi.py index a9c1f05..58ebf64 100644 --- a/src/scrobbler/federation/openapi.py +++ b/src/scrobbler/federation/openapi.py @@ -7,6 +7,14 @@ TAG = "ActivityPub" _AP = {"application/activity+json": {"schema": {"type": "object"}}} _NOT_FOUND = {"description": "Unknown, or not sharing (the two are indistinguishable)"} +_INBOX_RESPONSES = { + "202": {"description": "Accepted for processing (also for a repeated activity)"}, + "400": {"description": "Not an activity with an id, type and actor"}, + "403": {"description": "The sender's domain is blocked"}, + "404": {"description": "No such user sharing (user inbox)"}, + "413": {"description": "Larger than 256 KB"}, + "415": {"description": "Not ActivityPub JSON"}, +} _USERNAME = {"name": "username", "in": "path", "required": True, "schema": {"type": "string"}} # endpoint -> (method, summary, description, extra parameters, responses) @@ -120,20 +128,27 @@ _OPERATIONS = { "federation.user_inbox": ( "post", "User inbox", - "Receives activities for one user (signed deliveries).", + "Receives signed activities for one user. They're stored and answered with 202, then " + "verified and processed in the background.", [_USERNAME], - { - "202": {"description": "Accepted"}, - "404": _NOT_FOUND, - "413": {"description": "Too large"}, - }, + _INBOX_RESPONSES, ), "federation.shared_inbox": ( "post", "Shared inbox", - "Receives activities for any user on this server.", + "Receives signed activities for any user on this server (as for the user inbox).", [], - {"202": {"description": "Accepted"}, "413": {"description": "Too large"}}, + _INBOX_RESPONSES, + ), + "federation.activity": ( + "get", + "Activity", + "One of our activities, when public. Replies to follows aren't public.", + [{"name": "activity_uuid", "in": "path", "required": True, "schema": {"type": "string"}}], + { + "200": {"description": "Activity", "content": _AP}, + "404": {"description": "Not found or not public"}, + }, ), } diff --git a/src/scrobbler/federation/outbound.py b/src/scrobbler/federation/outbound.py index 021b442..d6cb576 100644 --- a/src/scrobbler/federation/outbound.py +++ b/src/scrobbler/federation/outbound.py @@ -4,7 +4,7 @@ import json from flask import current_app -from scrobbler.federation import keys +from scrobbler.federation import ids, keys from scrobbler.federation.net import Client, FetchError, Response from scrobbler.federation.protocol import signatures from scrobbler.federation.protocol.media import ACTIVITY_JSON, LD_JSON @@ -26,14 +26,6 @@ def client() -> Client: return existing -def instance_key_id() -> str: - return f"{current_app.extensions['federation'].base_url}/actor#main-key" - - -def user_key_id(username: str) -> str: - return f"{current_app.extensions['federation'].base_url}/users/{username}#main-key" - - def _signed_headers(method, url, headers, body, key_id, private_key, scheme) -> dict[str, str]: request = SignedRequest(method, url, headers, body) return {**headers, **signatures.sign(request, scheme, key_id, private_key)} @@ -47,7 +39,7 @@ def signed_get_json(url: str) -> dict: schemes = current_app.extensions["federation"].signature_schemes response = None for scheme in schemes: - signed = _signed_headers("GET", url, headers, b"", instance_key_id(), private, scheme) + signed = _signed_headers("GET", url, headers, b"", ids.instance_key_id(), private, scheme) response = client().request("GET", url, signed) if response.status != 401: break @@ -65,7 +57,7 @@ def signed_post(url: str, activity: dict, *, user_id: int, username: str) -> tup headers = {"Content-Type": LD_JSON, "Accept": ACTIVITY_JSON} response, used = None, "" for used in current_app.extensions["federation"].signature_schemes: - signed = _signed_headers("POST", url, headers, body, user_key_id(username), private, used) + signed = _signed_headers("POST", url, headers, body, ids.key_id(username), private, used) response = client().request("POST", url, signed, body) if response.status != 401: break diff --git a/src/scrobbler/federation/protocol/vocab.py b/src/scrobbler/federation/protocol/vocab.py index d9ce6d1..c9b8a94 100644 --- a/src/scrobbler/federation/protocol/vocab.py +++ b/src/scrobbler/federation/protocol/vocab.py @@ -145,3 +145,35 @@ def ordered_collection(collection_id: str, total: int, items: list | None = None if items is not None: doc["orderedItems"] = items return doc + + +def _response(kind: str, activity_id: str, actor_id: str, obj, to: str) -> dict: + return { + "@context": AS_CONTEXT, + "id": activity_id, + "type": kind, + "actor": actor_id, + "object": obj, + "to": [to], + } + + +def accept(activity_id: str, actor_id: str, follow: dict) -> dict: + """Accept a Follow (the original Follow is embedded, as Mastodon expects).""" + return _response("Accept", activity_id, actor_id, follow, follow["actor"]) + + +def reject(activity_id: str, actor_id: str, follow: dict) -> dict: + """Decline a follow request, or end an existing follow.""" + return _response("Reject", activity_id, actor_id, follow, follow["actor"]) + + +def block(activity_id: str, actor_id: str, blocked_actor: str) -> dict: + return _response("Block", activity_id, actor_id, blocked_actor, blocked_actor) + + +def object_id(value) -> str | None: + """An object's id, whether it's given inline (a dict) or as a bare URI.""" + if isinstance(value, dict): + value = value.get("id") + return value if isinstance(value, str) and value else None diff --git a/src/scrobbler/federation/remote.py b/src/scrobbler/federation/remote.py index e244236..1265e0a 100644 --- a/src/scrobbler/federation/remote.py +++ b/src/scrobbler/federation/remote.py @@ -109,7 +109,9 @@ def actor_for_key(key_id: str, refresh: bool = False) -> FederationRemoteActor: key document naming its owner.""" cached = db.session.scalar(db.select(FederationRemoteActor).filter_by(public_key_id=key_id)) if cached is not None and not refresh: - return get_actor(cached.uri) + # Any age will do for checking a signature (a failure refreshes once). This also + # lets a deleted account's Delete verify although its server now answers 410. + return cached document_url = urldefrag(key_id).url try: return _matching(get_actor(document_url, refresh=True), key_id) diff --git a/src/scrobbler/federation/web.py b/src/scrobbler/federation/web.py index 10818f7..ca89b57 100644 --- a/src/scrobbler/federation/web.py +++ b/src/scrobbler/federation/web.py @@ -6,13 +6,14 @@ import json from flask import Blueprint, Response, current_app, redirect, request -from scrobbler.federation import keys, sharing +from scrobbler.extensions import db +from scrobbler.federation import inbox, keys, sharing from scrobbler.federation import metrics as fed_metrics +from scrobbler.federation.models import FederationActivity from scrobbler.federation.protocol import hostmeta, media, nodeinfo, vocab, webfinger bp = Blueprint("federation", __name__) -MAX_INBOX_BYTES = 256 * 1024 _NOT_FOUND = {"error": "not found"} @@ -177,23 +178,46 @@ def instance_outbox(): return _json(vocab.ordered_collection(f"{_config().base_url}/actor/outbox", 0, [])) -# --- Inboxes (phase 2 processes deliveries) ----------------------------------------------- +# --- Inboxes ---------------------------------------------------------------------------- -def _accept_delivery(inbox: str): - if (request.content_length or 0) > MAX_INBOX_BYTES: +def _receive(inbox_path: str, kind: str): + if (request.content_length or 0) > inbox.MAX_BYTES: return _json({"error": "too large"}, content_type="application/json", status=413) - fed_metrics.inbox_requests_total.labels(inbox=inbox).inc() - return Response(status=202) + if not media.is_activitypub_content_type(request.content_type): + return _json( + {"error": "expected ActivityPub JSON"}, content_type="application/json", status=415 + ) + fed_metrics.inbox_requests_total.labels(inbox=kind).inc() + status, outcome = inbox.receive(inbox_path, dict(request.headers), request.get_data()) + if status == 202: + return Response(status=202) + return _json({"error": outcome}, content_type="application/json", status=status) + + +def _path() -> str: + return request.full_path.rstrip("?") @bp.post("/users//inbox") def user_inbox(username: str): if sharing.shared_user(username) is None: return _not_found("actor") - return _accept_delivery("user") + return _receive(_path(), "user") @bp.post("/inbox") def shared_inbox(): - return _accept_delivery("shared") + return _receive(_path(), "shared") + + +# --- Our activities ------------------------------------------------------------------------ + + +@bp.get("/activities/") +def activity(activity_uuid: str): + """Activities are fetchable when public; follow responses aren't.""" + found = db.session.get(FederationActivity, activity_uuid) + if found is None or not found.public: + return _json(_NOT_FOUND, content_type="application/json", status=404) + return _json(found.document) diff --git a/tests/federation_helpers.py b/tests/federation_helpers.py new file mode 100644 index 0000000..62f2250 --- /dev/null +++ b/tests/federation_helpers.py @@ -0,0 +1,85 @@ +"""A scripted remote fediverse account for federation tests.""" + +import dataclasses +import json +import uuid + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa + +from scrobbler.federation.protocol import signatures +from scrobbler.federation.protocol.signatures import SignedRequest + +OUR_BASE = "https://scrobble.test" + + +class RemoteAccount: + """An account on a FakeRemote server: serves its actor document and signs deliveries.""" + + def __init__(self, server, name="bob"): + self.server, self.name = server, name + self.uri = server.url(f"/users/{name}") + self.key_id = f"{self.uri}#main-key" + self.rotate_key() + self.serve() + + def rotate_key(self): + self.private = rsa.generate_private_key(public_exponent=65537, key_size=2048) + + @property + def public_pem(self) -> str: + return ( + self.private.public_key() + .public_bytes( + serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo + ) + .decode() + ) + + def document(self, **overrides) -> dict: + doc = { + "@context": ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/v1"], + "id": self.uri, + "type": "Person", + "preferredUsername": self.name, + "name": self.name.title(), + "inbox": f"{self.uri}/inbox", + "endpoints": {"sharedInbox": self.server.url("/inbox")}, + "publicKey": {"id": self.key_id, "owner": self.uri, "publicKeyPem": self.public_pem}, + } + doc.update(overrides) + return doc + + def serve(self, **overrides): + self.server.routes[f"/users/{self.name}"] = (200, {}, self.document(**overrides)) + + def activity(self, activity_type: str, obj, **extra) -> dict: + return { + "@context": "https://www.w3.org/ns/activitystreams", + "id": self.server.url(f"/activities/{uuid.uuid4()}"), + "type": activity_type, + "actor": self.uri, + "object": obj, + **extra, + } + + def follow(self, username="alice") -> dict: + return self.activity("Follow", f"{OUR_BASE}/users/{username}") + + def deliver( + self, + client, + activity: dict, + path="/users/alice/inbox", + scheme="draft-cavage", + key=None, + key_id=None, + content_type="application/activity+json", + ): + """POST `activity` to our inbox, signed like a real server would.""" + body = json.dumps(activity).encode() + request = SignedRequest("POST", OUR_BASE + path, {"Content-Type": content_type}, body) + if scheme: + added = signatures.sign(request, scheme, key_id or self.key_id, key or self.private) + request = dataclasses.replace(request, headers={**request.headers, **added}) + return client.post(path, data=body, headers=dict(request.headers)) diff --git a/tests/test_federation_inbox.py b/tests/test_federation_inbox.py new file mode 100644 index 0000000..1065538 --- /dev/null +++ b/tests/test_federation_inbox.py @@ -0,0 +1,327 @@ +"""Receiving activities: intake, signature verification, and the handlers.""" + +import json +from datetime import UTC, datetime, timedelta + +import pytest +from cryptography.hazmat.primitives.asymmetric import rsa + +from federation_helpers import RemoteAccount +from scrobbler import worker +from scrobbler.extensions import db +from scrobbler.federation import inbox, sharing +from scrobbler.federation.models import ( + FederationActivity, + FederationBlock, + FederationDelivery, + FederationFollower, + FederationInboxItem, + FederationRemoteActor, +) + + +@pytest.fixture +def bob(sharing_user, remote): + return RemoteAccount(remote, "bob") + + +def process_all(): + worker.run(once=True) + db.session.expire_all() + + +def last_item() -> FederationInboxItem: + return db.session.scalars( + db.select(FederationInboxItem).order_by(FederationInboxItem.id.desc()) + ).first() + + +def followers_of(user): + return db.session.scalars(db.select(FederationFollower).filter_by(user_id=user.id)).all() + + +def sent(activity_type): + return db.session.scalars( + db.select(FederationActivity).filter_by(activity_type=activity_type) + ).all() + + +# --- Intake --------------------------------------------------------------------------------- + + +def test_intake_queues_and_answers_202(fed_client, bob, metric_delta): + queued = metric_delta( + "scrobbler_federation_inbox_activities_total", type="Follow", result="queued" + ) + response = bob.deliver(fed_client, bob.follow()) + assert response.status_code == 202 + item = last_item() + assert (item.status, item.activity_type, item.actor_uri) == ("queued", "Follow", bob.uri) + assert set(item.headers) <= set(inbox.KEPT_HEADERS) + assert queued.delta == 1 + + +def test_duplicates_are_acknowledged_once(fed_client, bob, metric_delta): + duplicate = metric_delta( + "scrobbler_federation_inbox_activities_total", type="Follow", result="duplicate" + ) + follow = bob.follow() + assert bob.deliver(fed_client, follow).status_code == 202 + assert bob.deliver(fed_client, follow).status_code == 202 + assert db.session.scalar(db.select(db.func.count()).select_from(FederationInboxItem)) == 1 + assert duplicate.delta == 1 + + +@pytest.mark.parametrize( + "body", + [b"not json", b"[]", b'{"type": "Follow"}', b'{"id": "x", "type": "Follow", "actor": 7}'], +) +def test_malformed_deliveries_are_400(fed_client, sharing_user, body): + response = fed_client.post("/inbox", data=body, content_type="application/activity+json") + assert response.status_code == 400 + + +def test_wrong_content_type_is_415(fed_client, bob): + assert bob.deliver(fed_client, bob.follow(), content_type="text/plain").status_code == 415 + + +def test_too_large_is_413(fed_client, sharing_user): + response = fed_client.post( + "/inbox", data=b"x" * (inbox.MAX_BYTES + 1), content_type="application/activity+json" + ) + assert response.status_code == 413 + + +def test_blocked_domains_are_refused(fed_client, fed_app, bob): + config = fed_app.extensions["federation"] + fed_app.extensions["federation"] = type(config)( + **{**config.__dict__, "blocked_domains": ("127.0.0.1",)} + ) + try: + assert bob.deliver(fed_client, bob.follow()).status_code == 403 + finally: + fed_app.extensions["federation"] = config + + +# --- Follows ----------------------------------------------------------------------------------- + + +@pytest.mark.parametrize("scheme", ["draft-cavage", "rfc9421"]) +def test_follow_is_accepted(fed_client, bob, sharing_user, scheme, metric_delta): + ok = metric_delta( + "scrobbler_federation_signatures_total", direction="in", scheme=scheme, result="ok" + ) + follow = bob.follow() + bob.deliver(fed_client, follow, scheme=scheme) + process_all() + + assert (last_item().status, last_item().reason) == ("processed", "follow_accepted") + [follower] = followers_of(sharing_user) + assert (follower.state, follower.actor.uri, follower.follow_activity_id) == ( + "accepted", + bob.uri, + follow["id"], + ) + [accept] = sent("Accept") + assert accept.document["actor"] == "https://scrobble.test/users/alice" + assert accept.document["object"] == follow + assert accept.document["to"] == [bob.uri] + [delivery] = db.session.scalars(db.select(FederationDelivery)).all() + assert (delivery.inbox, delivery.status) == (f"{bob.uri}/inbox", "pending") + assert ok.delta == 1 + + +def test_manual_approval_leaves_follow_pending(fed_client, bob, sharing_user): + sharing.update(sharing_user.id, {"manually_approves_followers": True}) + bob.deliver(fed_client, bob.follow()) + process_all() + assert [f.state for f in followers_of(sharing_user)] == ["pending"] + assert sent("Accept") == [] + + +def test_repeat_follow_is_accepted_again(fed_client, bob, sharing_user): + bob.deliver(fed_client, bob.follow()) + process_all() + second = bob.follow() + bob.deliver(fed_client, second) + process_all() + assert last_item().reason == "follow_refollowed" + assert len(followers_of(sharing_user)) == 1 + assert followers_of(sharing_user)[0].follow_activity_id == second["id"] + assert len(sent("Accept")) == 2 + + +def test_follow_for_someone_not_sharing(fed_client, bob, make_user): + make_user(username="carol") + bob.deliver(fed_client, bob.follow("carol"), path="/inbox") + process_all() + assert (last_item().status, last_item().reason) == ("rejected", "not_our_user") + + +def test_blocked_account_gets_rejected(fed_client, bob, sharing_user): + bob.deliver(fed_client, bob.follow()) + process_all() + actor = db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=bob.uri)) + db.session.add(FederationBlock(user_id=sharing_user.id, remote_actor_id=actor.id)) + db.session.delete(followers_of(sharing_user)[0]) + db.session.commit() + bob.deliver(fed_client, bob.follow()) + process_all() + assert last_item().reason == "follow_blocked" + assert followers_of(sharing_user) == [] + assert len(sent("Reject")) == 1 + + +# --- Undo, Delete, Update ----------------------------------------------------------------------- + + +def test_undo_follow(fed_client, bob, sharing_user): + follow = bob.follow() + bob.deliver(fed_client, follow) + process_all() + bob.deliver(fed_client, bob.activity("Undo", follow)) + process_all() + assert last_item().reason == "unfollowed" + assert followers_of(sharing_user) == [] + + +def test_undo_of_someone_elses_follow_is_rejected(fed_client, bob, remote, sharing_user): + carol = RemoteAccount(remote, "carol") + follow = carol.follow() + carol.deliver(fed_client, follow) + process_all() + bob.deliver(fed_client, bob.activity("Undo", follow)) + process_all() + assert (last_item().status, last_item().reason) == ("rejected", "undo_other_actors_follow") + assert len(followers_of(sharing_user)) == 1 + + +def test_deleted_account_stops_following(fed_client, bob, remote, sharing_user): + bob.deliver(fed_client, bob.follow()) + process_all() + remote.routes[f"/users/{bob.name}"] = (410, {}, b"") # the account is gone now + bob.deliver(fed_client, bob.activity("Delete", bob.uri)) + process_all() + assert last_item().reason == "actor_deleted" + assert followers_of(sharing_user) == [] + assert db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=bob.uri)).gone + + +def test_update_refreshes_the_actor(fed_client, bob, sharing_user): + bob.deliver(fed_client, bob.follow()) + process_all() + bob.serve(name="Robert") + bob.deliver(fed_client, bob.activity("Update", bob.document(name="Robert"))) + process_all() + assert last_item().reason == "actor_updated" + assert ( + db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=bob.uri)).display_name + == "Robert" + ) + + +def test_other_activities_are_recorded(fed_client, bob, sharing_user): + bob.deliver(fed_client, bob.activity("Like", "https://scrobble.test/activities/x")) + process_all() + assert (last_item().status, last_item().reason) == ("processed", "recorded") + + +# --- Signatures and identity --------------------------------------------------------------------- + + +def test_unsigned_deliveries_are_rejected(fed_client, bob): + bob.deliver(fed_client, bob.follow(), scheme=None) + process_all() + assert (last_item().status, last_item().reason) == ("rejected", "signature_missing") + + +def test_wrong_key_is_rejected_after_one_refresh(fed_client, bob, remote, metric_delta): + failed = metric_delta( + "scrobbler_federation_signatures_total", + direction="in", + scheme="draft-cavage", + result="bad_signature", + ) + impostor = rsa.generate_private_key(public_exponent=65537, key_size=2048) + bob.deliver(fed_client, bob.follow(), key=impostor) + process_all() + assert (last_item().status, last_item().reason) == ("rejected", "signature_bad_signature") + assert [r["path"] for r in remote.requests].count("/users/bob") == 2 # fetched, then refreshed + assert failed.delta == 1 + + +def test_rotated_key_is_picked_up(fed_client, bob, sharing_user): + bob.deliver(fed_client, bob.follow()) + process_all() + bob.rotate_key() + bob.serve() # the new key is published... + bob.deliver(fed_client, bob.activity("Undo", followers_of(sharing_user)[0].follow_activity)) + process_all() # ...and our cached old key fails once, then we refetch + assert last_item().reason == "unfollowed" + + +def test_signed_by_one_actor_claiming_another_is_rejected(fed_client, bob, remote, sharing_user): + carol = RemoteAccount(remote, "carol") + forged = carol.follow() # carol's Follow... + bob.deliver(fed_client, forged) # ...signed with bob's key + process_all() + assert (last_item().status, last_item().reason) == ("rejected", "actor_mismatch") + assert followers_of(sharing_user) == [] + + +def test_activity_id_on_another_host_is_rejected(fed_client, bob, sharing_user): + follow = bob.follow() + follow["id"] = "https://elsewhere.example/activities/1" + bob.deliver(fed_client, follow) + process_all() + assert (last_item().status, last_item().reason) == ("rejected", "id_host_mismatch") + + +def test_signature_age_is_judged_by_arrival_time(fed_client, bob, sharing_user): + """A backlog mustn't turn valid deliveries into expired ones, and vice versa.""" + bob.deliver(fed_client, bob.follow()) + item = last_item() + item.received_at = datetime.now(UTC) + timedelta(hours=13) + db.session.commit() + process_all() + assert last_item().reason == "signature_expired" + + +# --- Robustness ---------------------------------------------------------------------------------- + + +def test_unreachable_sender_is_retried_then_failed(fed_client, bob, remote): + bob.deliver(fed_client, bob.follow()) + remote.close() # their server is down: fetching the key fails + for _ in range(inbox.MAX_ATTEMPTS): + process_all() + item = last_item() + if item.status != "queued": + break + assert (item.status, item.attempts) == ("failed", inbox.MAX_ATTEMPTS) + + +def test_maintenance_requeues_stale_and_prunes_old(fed_client, bob): + bob.deliver(fed_client, bob.follow()) + item = last_item() + item.status, item.received_at = "processing", datetime.now(UTC) - timedelta(minutes=30) + db.session.commit() + inbox.maintenance() + db.session.expire_all() + assert last_item().status == "queued" + + item = last_item() + item.status, item.received_at = "processed", datetime.now(UTC) - timedelta(days=31) + db.session.commit() + inbox.maintenance() + assert db.session.scalar(db.select(db.func.count()).select_from(FederationInboxItem)) == 0 + + +def test_activities_are_only_fetchable_when_public(fed_client, bob, sharing_user): + bob.deliver(fed_client, bob.follow()) + process_all() + [accept] = sent("Accept") + assert fed_client.get(f"/activities/{accept.id}").status_code == 404 + accept.public = True + db.session.commit() + assert json.loads(fed_client.get(f"/activities/{accept.id}").data)["type"] == "Accept" diff --git a/tests/test_federation_web.py b/tests/test_federation_web.py index 6b97a88..3a2e845 100644 --- a/tests/test_federation_web.py +++ b/tests/test_federation_web.py @@ -106,25 +106,6 @@ def test_instance_actor(fed_client, fed_ctx): assert (doc["type"], doc["id"]) == ("Application", f"{BASE}/actor") -def test_inboxes_accept_and_count_deliveries(fed_client, sharing_user, metric_delta): - shared = metric_delta("scrobbler_federation_inbox_requests_total", inbox="shared") - body = b'{"type": "Follow"}' - assert ( - fed_client.post("/inbox", data=body, content_type="application/activity+json").status_code - == 202 - ) - assert ( - fed_client.post( - "/users/alice/inbox", data=body, content_type="application/activity+json" - ).status_code - == 202 - ) - assert fed_client.post("/users/nobody/inbox", data=body).status_code == 404 - too_big = fed_client.post("/inbox", data=b"x" * (256 * 1024 + 1)) - assert too_big.status_code == 413 - assert shared.delta == 1 - - def test_disabled_app_has_none_of_these_routes(client): for path in ( "/.well-known/webfinger?resource=acct:alice@scrobble.test", From 5897e8217f5044658faf7bcd10d80dda129ffee9 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 21:31:52 +0100 Subject: [PATCH 25/56] Tests: reuse a pool of RSA keys Generating 2048-bit keys for every sharing user and scripted remote account dominated federation test time. Tests only need distinct valid keys, so an autouse fixture hands out a pool of 16 generated once per run (50s -> 40s for the suite). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- tests/conftest.py | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/tests/conftest.py b/tests/conftest.py index a27668a..297e305 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -242,3 +242,33 @@ def remote(): server = FakeRemote() yield server server.close() + + +# --- Fast RSA keys -------------------------------------------------------------------------- +# Generating 2048-bit keys dominates federation test time. Tests only need distinct valid +# keys, so hand out a pool generated once per run (cycling; 16 is plenty per test). + +_KEY_POOL: list = [] + + +def _pooled_rsa_key(public_exponent=65537, key_size=2048, backend=None): + + if len(_KEY_POOL) < 16: + _KEY_POOL.append(_ORIGINAL_GENERATE(public_exponent=public_exponent, key_size=key_size)) + return _KEY_POOL[-1] + _KEY_POOL.append(_KEY_POOL.pop(0)) + return _KEY_POOL[-1] + + +from cryptography.hazmat.primitives.asymmetric import rsa as _rsa_module # noqa: E402 + +_ORIGINAL_GENERATE = _rsa_module.generate_private_key + + +@pytest.fixture(autouse=True) +def _fast_rsa_keys(monkeypatch): + import federation_helpers + from scrobbler.federation import keys as federation_keys + + monkeypatch.setattr(federation_keys.rsa, "generate_private_key", _pooled_rsa_key) + monkeypatch.setattr(federation_helpers.rsa, "generate_private_key", _pooled_rsa_key) From 142dc13fea6f21a5b652ba0253b0cab2f6b321f0 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 21:36:05 +0100 Subject: [PATCH 26/56] Deliver outgoing activities with retries (phase 2, step 5) The federation.deliver worker task sends queued activities: - signed POSTs as the user, draft-cavage first and RFC 9421 after a 401 (double-knocking), several at once (FEDERATION_DELIVERY_ CONCURRENCY), up to 50 per pass - 2xx delivered; 410 removes whoever that inbox belongs to as a follower and marks them gone; other 4xx (except 401/408/429) are abandoned; everything else retries at 1m, 5m, 30m, 2h, 6h, then every 12h, abandoned after 2 days - claiming leases a delivery (pushes its next attempt forward), so a crashed worker's sends become due again on their own; claiming skips the eager join Postgres can't lock through - metrics: deliveries by result, delivery time, outgoing signatures, queue depths and follower totals (gauges set every 30s) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/federation/__init__.py | 4 +- src/scrobbler/federation/delivery.py | 179 +++++++++++++++++++++++ src/scrobbler/federation/metrics.py | 24 +++- tests/conftest.py | 9 +- tests/test_federation_delivery.py | 206 +++++++++++++++++++++++++++ tests/test_federation_inbox.py | 2 +- 6 files changed, 417 insertions(+), 7 deletions(-) create mode 100644 src/scrobbler/federation/delivery.py create mode 100644 tests/test_federation_delivery.py diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py index 622b3ac..d4ab553 100644 --- a/src/scrobbler/federation/__init__.py +++ b/src/scrobbler/federation/__init__.py @@ -37,7 +37,9 @@ def init_app(app: Flask) -> None: openapi.register(app, core_api) from scrobbler import worker - from scrobbler.federation import inbox + from scrobbler.federation import delivery, inbox worker.register_task(app, "federation.inbox", inbox.work_once) + worker.register_task(app, "federation.deliver", delivery.work_once) worker.register_periodic(app, "federation.inbox.maintenance", 300, inbox.maintenance) + worker.register_periodic(app, "federation.gauges", 30, delivery.maintenance) diff --git a/src/scrobbler/federation/delivery.py b/src/scrobbler/federation/delivery.py new file mode 100644 index 0000000..07f9da9 --- /dev/null +++ b/src/scrobbler/federation/delivery.py @@ -0,0 +1,179 @@ +"""Sending queued activities (the `federation.deliver` worker task). + +Each delivery is one activity to one inbox, signed as the user. Failures are retried +with backoff (1m, 5m, 30m, 2h, 6h, then every 12h) and abandoned after 2 days. A claimed +delivery is leased (its next attempt pushed forward), so one a crashed worker was +sending simply becomes due again. +""" + +import logging +import time +from concurrent.futures import ThreadPoolExecutor +from datetime import UTC, datetime, timedelta + +from flask import current_app +from sqlalchemy import func +from sqlalchemy.orm import lazyload + +from scrobbler.extensions import db +from scrobbler.federation import ids, outbound +from scrobbler.federation import metrics as fed_metrics +from scrobbler.federation.models import ( + FederationDelivery, + FederationFollower, + FederationInboxItem, + FederationRemoteActor, +) +from scrobbler.federation.net import FetchError + +log = logging.getLogger(__name__) + +RETRY_DELAYS = [ + timedelta(minutes=1), + timedelta(minutes=5), + timedelta(minutes=30), + timedelta(hours=2), + timedelta(hours=6), +] +LATER_DELAY = timedelta(hours=12) +GIVE_UP_AFTER = timedelta(days=2) +LEASE = timedelta(minutes=10) +BATCH = 50 +RETRYABLE_4XX = {401, 408, 429} + + +def _now() -> datetime: + return datetime.now(UTC) + + +def claim(limit: int = BATCH) -> list[int]: + now = _now() + due = db.session.scalars( + db.select(FederationDelivery) + # No eager join here: Postgres can't lock rows on the nullable side of an outer join + .options(lazyload(FederationDelivery.activity)) + .filter(FederationDelivery.status == "pending", FederationDelivery.next_attempt_at <= now) + .order_by(FederationDelivery.next_attempt_at) + .limit(limit) + .with_for_update(skip_locked=True) + ).all() + for delivery in due: + delivery.next_attempt_at = now + LEASE # our lease while we send + delivery.attempts += 1 + db.session.commit() + return [d.id for d in due] + + +def _retry_or_abandon(delivery: FederationDelivery, error: str, status: int | None) -> str: + delivery.last_status, delivery.last_error = status, error[:1000] + if _now() - delivery.created_at >= GIVE_UP_AFTER: + delivery.status = "abandoned" + return "abandoned" + delay = ( + RETRY_DELAYS[delivery.attempts - 1] + if delivery.attempts <= len(RETRY_DELAYS) + else LATER_DELAY + ) + delivery.next_attempt_at = _now() + delay + return "retry" + + +def _gone(inbox: str) -> None: + """410 from an inbox: whoever it belongs to is gone and follows no one here.""" + actors = db.session.scalars( + db.select(FederationRemoteActor).filter( + (FederationRemoteActor.inbox == inbox) | (FederationRemoteActor.shared_inbox == inbox) + ) + ).all() + for actor in actors: + actor.gone = True + db.session.execute(db.delete(FederationFollower).filter_by(remote_actor_id=actor.id)) + + +def deliver(delivery_id: int) -> str: + """Send one delivery. Returns the outcome (also its metric label).""" + delivery = db.session.get(FederationDelivery, delivery_id) + document = delivery.activity.document + username = ids.username_from_actor_id(document.get("actor")) + started = time.perf_counter() + try: + response, scheme = outbound.signed_post( + delivery.inbox, document, user_id=delivery.activity.user_id, username=username + ) + except FetchError as err: + if err.reason == "blocked": # would never be allowed: don't retry + delivery.status, delivery.last_error = "abandoned", str(err)[:1000] + outcome = "abandoned" + else: + outcome = _retry_or_abandon(delivery, str(err), err.status) + db.session.commit() + return outcome + fed_metrics.delivery_seconds.observe(time.perf_counter() - started) + fed_metrics.signatures_total.labels(direction="out", scheme=scheme, result="sent").inc() + + status = response.status + delivery.last_status = status + if 200 <= status < 300: + delivery.status, delivery.delivered_at, delivery.last_error = "delivered", _now(), None + outcome = "delivered" + elif status == 410: + delivery.status, delivery.last_error = "abandoned", "410 Gone" + _gone(delivery.inbox) + outcome = "gone" + elif 400 <= status < 500 and status not in RETRYABLE_4XX: + delivery.status = "abandoned" + delivery.last_error = f"{status}: {response.body[:500].decode('utf-8', 'replace')}" + outcome = "abandoned" + else: + outcome = _retry_or_abandon(delivery, f"HTTP {status}", status) + db.session.commit() + return outcome + + +def _deliver_in_context(app, delivery_id: int) -> str: + with app.app_context(): + try: + return deliver(delivery_id) + except Exception: + log.exception("delivery %s failed unexpectedly", delivery_id) + db.session.rollback() + return "retry" # the lease expires and it becomes due again + finally: + db.session.remove() + + +def work_once() -> bool: + """Worker task: send a batch of due deliveries, several at a time.""" + claimed = claim() + if not claimed: + return False + app = current_app._get_current_object() + workers = min(current_app.extensions["federation"].delivery_concurrency, len(claimed)) + with ThreadPoolExecutor(max_workers=workers) as pool: + for outcome in pool.map(lambda d: _deliver_in_context(app, d), claimed): + fed_metrics.deliveries_total.labels(result=outcome).inc() + return True + + +QUEUE_STATUSES = { + "inbox": (FederationInboxItem, ("queued", "processing", "processed", "rejected", "failed")), + "deliveries": (FederationDelivery, ("pending", "delivered", "abandoned")), +} + + +def maintenance() -> None: + """Worker task (periodic): publish queue and follower gauges.""" + for queue, (model, statuses) in QUEUE_STATUSES.items(): + counts = dict( + db.session.execute(db.select(model.status, func.count()).group_by(model.status)).all() + ) + for status in statuses: + fed_metrics.queue.labels(queue=queue, status=status).set(counts.get(status, 0)) + states = dict( + db.session.execute( + db.select(FederationFollower.state, func.count()).group_by(FederationFollower.state) + ).all() + ) + for state in ("accepted", "pending"): + fed_metrics.followers.labels(state=state).set(states.get(state, 0)) + db.session.rollback() diff --git a/src/scrobbler/federation/metrics.py b/src/scrobbler/federation/metrics.py index 091de27..1aeea3d 100644 --- a/src/scrobbler/federation/metrics.py +++ b/src/scrobbler/federation/metrics.py @@ -1,6 +1,6 @@ """Federation's own metrics (the core's HTTP metrics already cover rate/latency).""" -from prometheus_client import Counter +from prometheus_client import Counter, Gauge, Histogram lookups_total = Counter( "scrobbler_federation_lookups_total", @@ -29,3 +29,25 @@ signatures_total = Counter( "HTTP signature checks (in) and signing (out), by scheme and result", ["direction", "scheme", "result"], ) +deliveries_total = Counter( + "scrobbler_federation_deliveries_total", + "Outgoing deliveries: delivered, retry, abandoned (gave up or refused) or gone (410)", + ["result"], +) +delivery_seconds = Histogram( + "scrobbler_federation_delivery_seconds", + "Time to deliver one activity to one inbox", + buckets=(0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 20), +) +queue = Gauge( + "scrobbler_federation_queue", + "Inbox items and deliveries by status (set by the worker)", + ["queue", "status"], + multiprocess_mode="max", +) +followers = Gauge( + "scrobbler_federation_followers", + "Followers across all users, by state (set by the worker)", + ["state"], + multiprocess_mode="max", +) diff --git a/tests/conftest.py b/tests/conftest.py index 297e305..4973e20 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -189,7 +189,8 @@ def sharing_user(fed_ctx, user): class FakeRemote: """A tiny HTTP server standing in for another fediverse server. - `routes[path] = (status, headers, body)`; `requests` records what it received. + `routes[path] = (status, headers, body)` or a function(request) returning that; + `requests` records what it received. """ def __init__(self): @@ -211,9 +212,9 @@ class FakeRemote: "body": request.get_data(), } ) - status, headers, body = self.routes.get(request.path, (404, {}, b"not found")) - if callable(body): - body = body(request) + route = self.routes.get(request.path, (404, {}, b"not found")) + # A route is (status, headers, body), or a function of the request returning one + status, headers, body = route(request) if callable(route) else route if isinstance(body, dict | list): import json as _json diff --git a/tests/test_federation_delivery.py b/tests/test_federation_delivery.py new file mode 100644 index 0000000..d6a068f --- /dev/null +++ b/tests/test_federation_delivery.py @@ -0,0 +1,206 @@ +"""Sending activities: signed delivery, retries, double-knocking, gone accounts.""" + +import json +from datetime import UTC, datetime, timedelta + +import pytest +from cryptography.hazmat.primitives import serialization + +from federation_helpers import RemoteAccount +from scrobbler import worker +from scrobbler.extensions import db +from scrobbler.federation import delivery, keys +from scrobbler.federation.models import ( + FederationDelivery, + FederationFollower, + FederationRemoteActor, +) +from scrobbler.federation.protocol import signatures +from scrobbler.federation.protocol.signatures import SignedRequest + + +@pytest.fixture +def bob(sharing_user, remote): + account = RemoteAccount(remote, "bob") + account.inbox_path = f"/users/{account.name}/inbox" + remote.routes[account.inbox_path] = (202, {}, b"") + return account + + +def run_worker(): + worker.run(once=True) + db.session.expire_all() + + +def follow_and_process(fed_client, bob): + bob.deliver(fed_client, bob.follow()) + run_worker() + + +def posts_to(remote, path): + return [r for r in remote.requests if r["method"] == "POST" and r["path"] == path] + + +def the_delivery() -> FederationDelivery: + return db.session.scalars(db.select(FederationDelivery)).one() + + +def test_accept_is_delivered_signed_as_the_user( + fed_client, bob, remote, sharing_user, metric_delta +): + delivered = metric_delta("scrobbler_federation_deliveries_total", result="delivered") + follow_and_process(fed_client, bob) + + [post] = posts_to(remote, bob.inbox_path) + activity = json.loads(post["body"]) + assert (activity["type"], activity["actor"]) == ("Accept", "https://scrobble.test/users/alice") + assert activity["object"]["type"] == "Follow" + + # Bob's server can verify it with Alice's published key + public = serialization.load_pem_public_key( + keys.key_for(sharing_user.id).public_key_pem.encode() + ) + request = SignedRequest("POST", remote.url(bob.inbox_path), post["headers"], post["body"]) + verified = signatures.verify(request, lambda key_id: public) + assert (verified.scheme, verified.key_id) == ( + "draft-cavage", + "https://scrobble.test/users/alice#main-key", + ) + + assert (the_delivery().status, the_delivery().last_status) == ("delivered", 202) + assert delivered.delta == 1 + + +def test_server_errors_are_retried_with_backoff(fed_client, bob, remote, metric_delta): + retries = metric_delta("scrobbler_federation_deliveries_total", result="retry") + remote.routes[bob.inbox_path] = (503, {}, b"busy") + follow_and_process(fed_client, bob) + d = the_delivery() + assert (d.status, d.attempts, d.last_status) == ("pending", 1, 503) + assert timedelta(seconds=50) < d.next_attempt_at - datetime.now(UTC) <= timedelta(minutes=1) + assert retries.delta == 1 + + # Not due yet: nothing is sent + run_worker() + assert len(posts_to(remote, bob.inbox_path)) == 1 + + # When due, the second failure backs off further + d.next_attempt_at = datetime.now(UTC) - timedelta(seconds=1) + db.session.commit() + run_worker() + d = the_delivery() + assert d.attempts == 2 + assert d.next_attempt_at - datetime.now(UTC) > timedelta(minutes=4) + + # Once it recovers, it's delivered + remote.routes[bob.inbox_path] = (200, {}, b"") + d.next_attempt_at = datetime.now(UTC) - timedelta(seconds=1) + db.session.commit() + run_worker() + assert the_delivery().status == "delivered" + + +def test_deliveries_are_abandoned_after_two_days(fed_client, bob, remote, metric_delta): + abandoned = metric_delta("scrobbler_federation_deliveries_total", result="abandoned") + remote.routes[bob.inbox_path] = (500, {}, b"") + follow_and_process(fed_client, bob) + d = the_delivery() + d.created_at = datetime.now(UTC) - timedelta(days=2, minutes=1) + d.next_attempt_at = datetime.now(UTC) - timedelta(seconds=1) + db.session.commit() + run_worker() + assert the_delivery().status == "abandoned" + assert abandoned.delta == 1 + + +@pytest.mark.parametrize( + ("status", "outcome"), [(400, "abandoned"), (403, "abandoned"), (404, "abandoned")] +) +def test_client_errors_are_not_retried(fed_client, bob, remote, status, outcome): + remote.routes[bob.inbox_path] = (status, {}, b"no") + follow_and_process(fed_client, bob) + assert (the_delivery().status, the_delivery().last_status) == (outcome, status) + + +@pytest.mark.parametrize("status", [408, 429]) +def test_throttling_and_timeouts_are_retried(fed_client, bob, remote, status): + remote.routes[bob.inbox_path] = (status, {}, b"") + follow_and_process(fed_client, bob) + assert the_delivery().status == "pending" + + +def test_rfc9421_is_tried_after_a_401(fed_client, bob, remote): + """Double-knocking: a server that only accepts RFC 9421 gets it on the second try.""" + + def rfc9421_only(request): + return (202, {}, b"") if "Signature-Input" in request.headers else (401, {}, b"") + + remote.routes[bob.inbox_path] = rfc9421_only + follow_and_process(fed_client, bob) + first, second = posts_to(remote, bob.inbox_path) + assert "Signature-Input" not in first["headers"] + assert "Signature-Input" in second["headers"] + assert the_delivery().status == "delivered" + + +def test_gone_inbox_removes_the_follower(fed_client, bob, remote, sharing_user, metric_delta): + gone = metric_delta("scrobbler_federation_deliveries_total", result="gone") + remote.routes[bob.inbox_path] = (410, {}, b"") + follow_and_process(fed_client, bob) + assert the_delivery().status == "abandoned" + assert db.session.scalars(db.select(FederationFollower)).all() == [] + assert db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=bob.uri)).gone + assert gone.delta == 1 + + +def test_unreachable_inbox_is_retried(fed_client, bob, remote): + from scrobbler.federation import inbox + + bob.deliver(fed_client, bob.follow()) + inbox.work_once() # processing the Follow needs bob's server... + remote.close() # ...which then goes away before we deliver the Accept + run_worker() + assert (the_delivery().status, the_delivery().attempts) == ("pending", 1) + + +def test_many_deliveries_in_one_pass(fed_client, bob, remote, sharing_user, make_user): + from scrobbler.federation import sharing + + for name in ("carol", "dave", "erin"): + user = make_user(username=name) + sharing.update(user.id, {"enabled": True}) + bob.deliver(fed_client, bob.follow(name), path="/inbox") + run_worker() + assert len(posts_to(remote, bob.inbox_path)) == 3 + assert {d.status for d in db.session.scalars(db.select(FederationDelivery))} == {"delivered"} + + +def test_expired_lease_makes_a_delivery_due_again(fed_client, bob, remote): + """A worker that died mid-send leaves a lease; after it runs out, it's sent again.""" + remote.routes[bob.inbox_path] = (202, {}, b"") + bob.deliver(fed_client, bob.follow()) + from scrobbler.federation import inbox + + inbox.work_once() + [claimed] = delivery.claim() # claimed, then the "worker" dies + d = db.session.get(FederationDelivery, claimed) + assert d.next_attempt_at > datetime.now(UTC) + d.next_attempt_at = datetime.now(UTC) - timedelta(seconds=1) # the lease runs out + db.session.commit() + run_worker() + assert the_delivery().status == "delivered" + + +def test_gauges(fed_client, bob, remote): + from prometheus_client import REGISTRY + + remote.routes[bob.inbox_path] = (503, {}, b"") + follow_and_process(fed_client, bob) + delivery.maintenance() + assert ( + REGISTRY.get_sample_value( + "scrobbler_federation_queue", {"queue": "deliveries", "status": "pending"} + ) + == 1 + ) + assert REGISTRY.get_sample_value("scrobbler_federation_followers", {"state": "accepted"}) == 1 diff --git a/tests/test_federation_inbox.py b/tests/test_federation_inbox.py index 1065538..27dcb0d 100644 --- a/tests/test_federation_inbox.py +++ b/tests/test_federation_inbox.py @@ -127,7 +127,7 @@ def test_follow_is_accepted(fed_client, bob, sharing_user, scheme, metric_delta) assert accept.document["object"] == follow assert accept.document["to"] == [bob.uri] [delivery] = db.session.scalars(db.select(FederationDelivery)).all() - assert (delivery.inbox, delivery.status) == (f"{bob.uri}/inbox", "pending") + assert delivery.inbox == f"{bob.uri}/inbox" # sending is covered in test_federation_delivery assert ok.delta == 1 From a90cd14f5963929a19cf12100b5d7ae4df58f8a0 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 21:42:29 +0100 Subject: [PATCH 27/56] Manage followers from the API and web UI (phase 2, step 6) - /api/v1/federation: list followers and requests, approve (Accept), decline or remove (Reject), block (Block, and future follows are refused), list and remove blocks; settings report follower counts - The actor now reflects the user's real follow-approval setting and the followers collection its accepted count - Turning sharing off sends every follower a Reject and forgets them; while those are being delivered the actor stays fetchable with just its key (no name or bio) so other servers can verify them, and WebFinger already says not found - Web UI: a Followers page (requests with Approve/Decline, followers with Remove/Block behind a confirm step, blocked accounts with Unblock; remote names shown as plain text only), follower counts on the Sharing page, and a confirmation before turning sharing off when that would remove followers Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/openapi.json | 464 ++++++++++++++++++++++++- frontend/css/style.css | 8 + frontend/followers.html | 32 ++ frontend/js/followers.js | 143 ++++++++ frontend/js/sharing.js | 53 ++- frontend/sharing.html | 3 +- src/scrobbler/federation/api.py | 145 +++++++- src/scrobbler/federation/schemas.py | 27 +- src/scrobbler/federation/sharing.py | 21 ++ src/scrobbler/federation/web.py | 31 +- tests/test_federation_followers_api.py | 172 +++++++++ tests/test_federation_web.py | 2 +- 12 files changed, 1083 insertions(+), 18 deletions(-) create mode 100644 frontend/followers.html create mode 100644 frontend/js/followers.js create mode 100644 tests/test_federation_followers_api.py diff --git a/docs/openapi.json b/docs/openapi.json index d782bfe..e053765 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -1942,7 +1942,7 @@ } }, "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.", + "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. Turning sharing off\nremoves all your followers (each is told).", "tags": [ "Federation" ], @@ -1998,6 +1998,391 @@ } ] }, + "/api/v1/federation/followers": { + "get": { + "parameters": [ + { + "in": "query", + "name": "state", + "schema": { + "type": [ + "string", + "null" + ], + "default": null, + "enum": [ + "pending", + "accepted", + null + ] + }, + "required": false + } + ], + "responses": { + "422": { + "$ref": "#/components/responses/UNPROCESSABLE_CONTENT" + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Follower" + } + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Your followers and follow requests", + "description": "Newest first. Filter with `state=pending` (requests) or `state=accepted`.", + "tags": [ + "Federation" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/federation/followers/{follower_id}/approve": { + "post": { + "responses": { + "409": { + "description": "Not a pending request", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "404": { + "description": "No such follower", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Follower" + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Approve a follow request", + "tags": [ + "Federation" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "follower_id", + "required": true, + "schema": { + "type": "integer", + "minimum": 0 + } + } + ] + }, + "/api/v1/federation/followers/{follower_id}/decline": { + "post": { + "responses": { + "404": { + "description": "No such follower", + "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": "Decline a follow request", + "tags": [ + "Federation" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "follower_id", + "required": true, + "schema": { + "type": "integer", + "minimum": 0 + } + } + ] + }, + "/api/v1/federation/followers/{follower_id}/remove": { + "post": { + "responses": { + "404": { + "description": "No such follower", + "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 a follower", + "description": "They stop receiving your posts. They can follow you again; block them to prevent it.", + "tags": [ + "Federation" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "follower_id", + "required": true, + "schema": { + "type": "integer", + "minimum": 0 + } + } + ] + }, + "/api/v1/federation/followers/{follower_id}/block": { + "post": { + "responses": { + "404": { + "description": "No such follower", + "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": "Block a follower", + "description": "Removes them and refuses their future follows.", + "tags": [ + "Federation" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "follower_id", + "required": true, + "schema": { + "type": "integer", + "minimum": 0 + } + } + ] + }, + "/api/v1/federation/blocks": { + "get": { + "responses": { + "200": { + "description": "OK", + "content": { + "application/json": { + "schema": { + "type": "array", + "items": { + "$ref": "#/components/schemas/Block" + } + } + } + } + }, + "401": { + "description": "Not authenticated", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/Error" + } + } + } + }, + "default": { + "$ref": "#/components/responses/DEFAULT_ERROR" + } + }, + "summary": "Accounts you've blocked", + "tags": [ + "Federation" + ], + "security": [ + { + "bearerAuth": [] + } + ] + } + }, + "/api/v1/federation/blocks/{block_id}": { + "delete": { + "responses": { + "404": { + "description": "No such block", + "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": "Unblock an account", + "description": "They can follow you again (they aren't re-added).", + "tags": [ + "Federation" + ], + "security": [ + { + "bearerAuth": [] + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "block_id", + "required": true, + "schema": { + "type": "integer", + "minimum": 0 + } + } + ] + }, "/.well-known/webfinger": { "get": { "tags": [ @@ -3693,7 +4078,12 @@ "followers": { "type": "integer", "readOnly": true, - "description": "0 until following arrives" + "description": "Accepted followers" + }, + "pending_followers": { + "type": "integer", + "readOnly": true, + "description": "Waiting for approval" } }, "additionalProperties": false @@ -3755,7 +4145,12 @@ "followers": { "type": "integer", "readOnly": true, - "description": "0 until following arrives" + "description": "Accepted followers" + }, + "pending_followers": { + "type": "integer", + "readOnly": true, + "description": "Waiting for approval" } }, "additionalProperties": false @@ -3784,6 +4179,69 @@ } }, "additionalProperties": false + }, + "Follower": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "state": { + "type": "string", + "enum": [ + "pending", + "accepted" + ] + }, + "handle": { + "type": "string", + "example": "@bob@mastodon.example" + }, + "display_name": { + "type": [ + "string", + "null" + ] + }, + "actor_url": { + "type": "string" + }, + "server": { + "type": "string", + "example": "mastodon.example" + }, + "since": { + "type": "string", + "format": "date-time", + "description": "When they followed (or asked to)" + } + }, + "additionalProperties": false + }, + "Block": { + "type": "object", + "properties": { + "id": { + "type": "integer" + }, + "handle": { + "type": "string" + }, + "display_name": { + "type": [ + "string", + "null" + ] + }, + "actor_url": { + "type": "string" + }, + "since": { + "type": "string", + "format": "date-time" + } + }, + "additionalProperties": false } }, "responses": { diff --git a/frontend/css/style.css b/frontend/css/style.css index 4ef8bbc..b846e83 100644 --- a/frontend/css/style.css +++ b/frontend/css/style.css @@ -945,3 +945,11 @@ input { .save-row { align-items: center; } + +.follower-summary { + margin-top: 0.25rem; +} + +.confirm-off .button-row { + margin-top: 0.75rem; +} diff --git a/frontend/followers.html b/frontend/followers.html new file mode 100644 index 0000000..b144ec9 --- /dev/null +++ b/frontend/followers.html @@ -0,0 +1,32 @@ + + + + + + Followers · Scrobbler + + + + + + + +
+

Followers

+

People on the fediverse who follow your listening. Sharing settings

+
+ +
+

Followers

+
    +
    + +
    + + diff --git a/frontend/js/followers.js b/frontend/js/followers.js new file mode 100644 index 0000000..ce63df1 --- /dev/null +++ b/frontend/js/followers.js @@ -0,0 +1,143 @@ +import { api } from "./api.js"; +import { errorBox, formatDate, h, replace, timeAgo } from "./dom.js"; +import { signedInPage } from "./layout.js"; + +const messages = document.getElementById("messages"); + +await signedInPage("sharing.html"); +await refresh(); + +async function refresh() { + let followers, blocks; + try { + [followers, blocks] = await Promise.all([api("/federation/followers"), api("/federation/blocks")]); + } catch (error) { + replace( + messages, + error.status === 404 + ? h("p", { class: "notice" }, "This server doesn't share to the fediverse.") + : errorBox(error.message), + ); + return; + } + const requests = followers.filter((f) => f.state === "pending"); + const accepted = followers.filter((f) => f.state === "accepted"); + + document.getElementById("requests-section").hidden = requests.length === 0; + replace(document.getElementById("requests"), requests.map(requestRow)); + replace( + document.getElementById("followers"), + accepted.length + ? accepted.map(followerRow) + : h("li", { class: "empty" }, "No followers yet. People can follow you by searching for your handle."), + ); + document.getElementById("blocks-section").hidden = blocks.length === 0; + replace(document.getElementById("blocks"), blocks.map(blockRow)); +} + +// Remote names and handles are shown as plain text only. +function who(person) { + return h( + "span", + {}, + h("span", { class: "row-title" }, person.display_name || person.handle), + person.display_name ? h("span", { class: "muted" }, ` ${person.handle}`) : null, + ); +} + +async function act(path, done) { + try { + await api(path, { method: "POST" }); + replace(messages, h("p", { class: "notice notice-ok", role: "status" }, done)); + } catch (error) { + replace(messages, errorBox(error.message)); + } + await refresh(); +} + +function requestRow(follower) { + return h( + "li", + {}, + h( + "div", + { class: "row-head" }, + who(follower), + h( + "div", + { class: "confirm" }, + h( + "button", + { type: "button", class: "button", onclick: () => act(`/federation/followers/${follower.id}/approve`, `${follower.handle} now follows you.`) }, + "Approve", + ), + h( + "button", + { type: "button", class: "button button-quiet", onclick: () => act(`/federation/followers/${follower.id}/decline`, `Declined ${follower.handle}.`) }, + "Decline", + ), + ), + ), + h("p", { class: "muted", title: formatDate(follower.since) }, `Asked ${timeAgo(follower.since)}`), + ); +} + +function followerRow(follower) { + const actions = h("div", { class: "confirm" }); + const reset = () => + replace( + actions, + h("button", { type: "button", class: "button button-quiet", onclick: askRemove }, "Remove"), + h("button", { type: "button", class: "button button-quiet", onclick: askBlock }, "Block"), + ); + const confirm = (question, label, path, done) => + replace( + actions, + h("span", { class: "muted" }, question), + h("button", { type: "button", class: "button button-danger", onclick: () => act(path, done) }, label), + h("button", { type: "button", class: "button button-quiet", onclick: reset }, "Cancel"), + ); + const askRemove = () => + confirm( + "They can follow you again later.", + "Remove follower", + `/federation/followers/${follower.id}/remove`, + `Removed ${follower.handle}.`, + ); + const askBlock = () => + confirm( + "They're removed and can't follow you again.", + "Block", + `/federation/followers/${follower.id}/block`, + `Blocked ${follower.handle}.`, + ); + reset(); + return h( + "li", + {}, + h("div", { class: "row-head" }, who(follower), actions), + h("p", { class: "muted", title: formatDate(follower.since) }, `Following since ${timeAgo(follower.since)}`), + ); +} + +function blockRow(block) { + const unblock = async () => { + try { + await api(`/federation/blocks/${block.id}`, { method: "DELETE" }); + replace(messages, h("p", { class: "notice notice-ok", role: "status" }, `Unblocked ${block.handle}.`)); + } catch (error) { + replace(messages, errorBox(error.message)); + } + await refresh(); + }; + return h( + "li", + {}, + h( + "div", + { class: "row-head" }, + who(block), + h("button", { type: "button", class: "button button-quiet", onclick: unblock }, "Unblock"), + ), + ); +} diff --git a/frontend/js/sharing.js b/frontend/js/sharing.js index b9c8757..eaab3d0 100644 --- a/frontend/js/sharing.js +++ b/frontend/js/sharing.js @@ -1,5 +1,5 @@ import { api, describeError } from "./api.js"; -import { errorBox, h, replace } from "./dom.js"; +import { errorBox, h, num, replace } from "./dom.js"; import { signedInPage } from "./layout.js"; const form = document.getElementById("sharing"); @@ -40,6 +40,10 @@ function fill(values) { } } document.getElementById("handle").textContent = values.handle; + const summary = document.getElementById("follower-summary"); + const parts = [`${num(values.followers)} ${values.followers === 1 ? "follower" : "followers"}`]; + if (values.pending_followers) parts.push(`${num(values.pending_followers)} waiting for approval`); + replace(summary, parts.join(", "), ". ", h("a", { href: "followers.html" }, "See followers")); replace( document.getElementById("profile-link"), "Your public profile page: ", @@ -52,8 +56,50 @@ function showHandle(on) { handlePanel.hidden = !on; } +// Turning sharing off removes every follower, so it's confirmed first. +function confirmTurningOff(followerCount) { + return new Promise((resolve) => { + const box = document.getElementById("confirm-off"); + const done = (answer) => { + box.hidden = true; + resolve(answer); + }; + replace( + box, + h( + "p", + {}, + `Turning sharing off removes your ${num(followerCount)} ${followerCount === 1 ? "follower" : "followers"}. `, + "Each is told, and they'd have to follow you again if you turn it back on.", + ), + h( + "div", + { class: "button-row" }, + h("button", { type: "button", class: "button button-danger", onclick: () => done(true) }, "Turn off sharing"), + h( + "button", + { + type: "button", + class: "button button-quiet", + onclick: () => { + form.elements.enabled.checked = true; + showHandle(true); + done(false); + }, + }, + "Keep sharing", + ), + ), + ); + box.hidden = false; + box.scrollIntoView({ behavior: "smooth", block: "center" }); + }); +} + async function save(event) { event.preventDefault(); + const turningOff = settings.enabled && !form.elements.enabled.checked; + if (turningOff && settings.followers > 0 && !(await confirmTurningOff(settings.followers))) return; const button = form.querySelector("button[type=submit]"); const changes = { enabled: form.elements.enabled.checked, @@ -70,8 +116,11 @@ async function save(event) { replace(messages); try { const saved = await api("/federation/settings", { method: "PATCH", body: changes }); + settings = saved; fill(saved); - status.textContent = saved.enabled ? `Saved. You're sharing as ${saved.handle}.` : "Saved. Sharing is off."; + status.textContent = saved.enabled + ? `Saved. You're sharing as ${saved.handle}.` + : "Saved. Sharing is off, and your followers have been told."; } catch (error) { status.textContent = ""; replace(messages, errorBox(describeError(error))); diff --git a/frontend/sharing.html b/frontend/sharing.html index d220ec5..1cade12 100644 --- a/frontend/sharing.html +++ b/frontend/sharing.html @@ -24,7 +24,7 @@

    Your fediverse handle

    People can follow you by searching for this in their app. It can't be changed once people follow you.

    -

    Following arrives in a coming update. Until then people can find your profile, and follows wait as requests.

    +

    @@ -74,6 +74,7 @@
    +
    diff --git a/src/scrobbler/federation/api.py b/src/scrobbler/federation/api.py index 91132c2..8c05cdd 100644 --- a/src/scrobbler/federation/api.py +++ b/src/scrobbler/federation/api.py @@ -4,9 +4,15 @@ from flask import current_app, g from flask_smorest import Blueprint, abort from scrobbler.api.decorators import authenticated +from scrobbler.extensions import db +from scrobbler.federation import followers as follower_state from scrobbler.federation import metrics as fed_metrics from scrobbler.federation import sharing +from scrobbler.federation.models import FederationBlock, FederationFollower from scrobbler.federation.schemas import ( + BlockSchema, + FollowerListArgsSchema, + FollowerSchema, PublicProfileSchema, SharingSettingsSchema, SharingSettingsUpdateSchema, @@ -33,10 +39,12 @@ def _identity(username: str) -> dict: def _settings_body(user, settings) -> dict: + counts = follower_state.counts(user.id) return { **{field: getattr(settings, field) for field in sharing.EDITABLE}, **_identity(user.username), - "followers": 0, + "followers": counts["accepted"], + "pending_followers": counts["pending"], } @@ -60,7 +68,8 @@ 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. + people follow you. Visibility changes apply to new posts only. Turning sharing off + removes all your followers (each is told). """ try: settings, toggled = sharing.update(g.user.id, changes) @@ -68,6 +77,10 @@ def update_settings(changes): 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() + if toggled is False: + # Tell every follower (a Reject each), then forget them + follower_state.reject_all(g.user.id, g.user.username) + db.session.commit() return _settings_body(g.user, settings) @@ -91,3 +104,131 @@ def public_profile(username): "bio": settings.bio, **{k: v for k, v in _identity(user.username).items() if k != "profile_url"}, } + + +# --- Followers --------------------------------------------------------------------------- + + +def _follower_body(follower: FederationFollower) -> dict: + actor = follower.actor + return { + "id": follower.id, + "state": follower.state, + "handle": actor.handle, + "display_name": actor.display_name, + "actor_url": actor.uri, + "server": actor.host, + "since": follower.created_at, + } + + +def _own_follower(follower_id: int) -> FederationFollower: + follower = db.session.get(FederationFollower, follower_id) + if follower is None or follower.user_id != g.user.id: + abort(404, code="not_found", message="No such follower") + return follower + + +@blp.route("/followers", methods=["GET"]) +@authenticated(blp) +@blp.arguments(FollowerListArgsSchema, location="query") +@blp.response(200, FollowerSchema(many=True)) +def list_followers(args): + """Your followers and follow requests + + Newest first. Filter with `state=pending` (requests) or `state=accepted`. + """ + query = db.select(FederationFollower).filter_by(user_id=g.user.id) + if args["state"]: + query = query.filter_by(state=args["state"]) + followers = db.session.scalars(query.order_by(FederationFollower.created_at.desc())).all() + return [_follower_body(f) for f in followers] + + +@blp.route("/followers//approve", methods=["POST"]) +@authenticated(blp) +@blp.response(200, FollowerSchema) +@blp.alt_response(404, schema=ErrorSchema, description="No such follower") +@blp.alt_response(409, schema=ErrorSchema, description="Not a pending request") +def approve_follower(follower_id): + """Approve a follow request""" + follower = _own_follower(follower_id) + if follower.state != "pending": + abort(409, code="not_pending", message="That follower isn't waiting for approval.") + follower_state.approve(g.user.username, follower) + db.session.commit() + return _follower_body(follower) + + +@blp.route("/followers//decline", methods=["POST"]) +@authenticated(blp) +@blp.response(204) +@blp.alt_response(404, schema=ErrorSchema, description="No such follower") +def decline_follower(follower_id): + """Decline a follow request""" + follower_state.remove(g.user.username, _own_follower(follower_id)) + db.session.commit() + + +@blp.route("/followers//remove", methods=["POST"]) +@authenticated(blp) +@blp.response(204) +@blp.alt_response(404, schema=ErrorSchema, description="No such follower") +def remove_follower(follower_id): + """Remove a follower + + They stop receiving your posts. They can follow you again; block them to prevent it. + """ + follower_state.remove(g.user.username, _own_follower(follower_id)) + db.session.commit() + + +@blp.route("/followers//block", methods=["POST"]) +@authenticated(blp) +@blp.response(204) +@blp.alt_response(404, schema=ErrorSchema, description="No such follower") +def block_follower(follower_id): + """Block a follower + + Removes them and refuses their future follows. + """ + follower_state.block(g.user.username, _own_follower(follower_id)) + db.session.commit() + + +@blp.route("/blocks", methods=["GET"]) +@authenticated(blp) +@blp.response(200, BlockSchema(many=True)) +def list_blocks(): + """Accounts you've blocked""" + blocks = db.session.scalars( + db.select(FederationBlock) + .filter_by(user_id=g.user.id) + .order_by(FederationBlock.created_at.desc()) + ).all() + return [ + { + "id": b.id, + "handle": b.actor.handle, + "display_name": b.actor.display_name, + "actor_url": b.actor.uri, + "since": b.created_at, + } + for b in blocks + ] + + +@blp.route("/blocks/", methods=["DELETE"]) +@authenticated(blp) +@blp.response(204) +@blp.alt_response(404, schema=ErrorSchema, description="No such block") +def unblock(block_id): + """Unblock an account + + They can follow you again (they aren't re-added). + """ + block = db.session.get(FederationBlock, block_id) + if block is None or block.user_id != g.user.id: + abort(404, code="not_found", message="No such block") + db.session.delete(block) + db.session.commit() diff --git a/src/scrobbler/federation/schemas.py b/src/scrobbler/federation/schemas.py index 24b3c14..cb1b5d6 100644 --- a/src/scrobbler/federation/schemas.py +++ b/src/scrobbler/federation/schemas.py @@ -23,8 +23,9 @@ class SharingSettingsSchema(Schema): 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"} + followers = fields.Integer(dump_only=True, metadata={"description": "Accepted followers"}) + pending_followers = fields.Integer( + dump_only=True, metadata={"description": "Waiting for approval"} ) @@ -38,3 +39,25 @@ class PublicProfileSchema(Schema): class SharingSettingsUpdateSchema(SharingSettingsSchema): """Any subset of the editable settings (read-only fields are rejected).""" + + +class FollowerSchema(Schema): + id = fields.Integer() + state = fields.String(validate=validate.OneOf(["pending", "accepted"])) + handle = fields.String(metadata={"example": "@bob@mastodon.example"}) + display_name = fields.String(allow_none=True) + actor_url = fields.String() + server = fields.String(metadata={"example": "mastodon.example"}) + since = fields.DateTime(metadata={"description": "When they followed (or asked to)"}) + + +class FollowerListArgsSchema(Schema): + state = fields.String(load_default=None, validate=validate.OneOf(["pending", "accepted"])) + + +class BlockSchema(Schema): + id = fields.Integer() + handle = fields.String() + display_name = fields.String(allow_none=True) + actor_url = fields.String() + since = fields.DateTime() diff --git a/src/scrobbler/federation/sharing.py b/src/scrobbler/federation/sharing.py index 4ea58ae..b0b16ab 100644 --- a/src/scrobbler/federation/sharing.py +++ b/src/scrobbler/federation/sharing.py @@ -67,3 +67,24 @@ def sharing_count() -> int: return db.session.scalar( db.select(db.func.count()).select_from(FederationSettings).filter_by(enabled=True) ) + + +def farewell_user(username: str): + """A user who has stopped sharing but still has messages on their way out (the + Rejects telling followers). Their actor stays fetchable, minimally, so other servers + can verify those messages. None otherwise.""" + from scrobbler.federation.models import FederationActivity, FederationDelivery + + user = accounts.find_user(username) + if user is None: + return None + settings = db.session.get(FederationSettings, user.id) + if settings is None or settings.enabled: + return None + pending = db.session.scalar( + db.select(db.func.count()) + .select_from(FederationDelivery) + .join(FederationActivity, FederationActivity.id == FederationDelivery.activity_id) + .filter(FederationActivity.user_id == user.id, FederationDelivery.status == "pending") + ) + return user if pending else None diff --git a/src/scrobbler/federation/web.py b/src/scrobbler/federation/web.py index ca89b57..44a62e4 100644 --- a/src/scrobbler/federation/web.py +++ b/src/scrobbler/federation/web.py @@ -7,6 +7,7 @@ import json from flask import Blueprint, Response, current_app, redirect, request from scrobbler.extensions import db +from scrobbler.federation import followers as follower_state from scrobbler.federation import inbox, keys, sharing from scrobbler.federation import metrics as fed_metrics from scrobbler.federation.models import FederationActivity @@ -110,7 +111,23 @@ def actor(username: str): return redirect(_profile_page(username), code=302) found = sharing.shared_user(username) if found is None: - return _not_found("actor") + leaving = sharing.farewell_user(username) + if leaving is None: + return _not_found("actor") + # Stopped sharing, but Rejects are still on their way: just enough for other + # servers to verify them. No name, bio or other profile details. + _found("actor") + doc = vocab.person( + _urls(leaving.username), + username=leaving.username, + name=leaving.username, + summary=None, + public_key_pem=keys.key_for(leaving.id).public_key_pem, + manually_approves_followers=True, + discoverable=False, + indexable=False, + ) + return _json(doc, cache=0) user, settings = found _found("actor") urls = _urls(user.username) @@ -120,9 +137,7 @@ def actor(username: str): name=settings.display_name or user.username, summary=settings.bio, public_key_pem=keys.key_for(user.id).public_key_pem, - # Phase 1 can't accept follows yet: advertise approval so follows show as - # requests rather than failing silently. - manually_approves_followers=True, + manually_approves_followers=settings.manually_approves_followers, discoverable=settings.discoverable, indexable=settings.indexable, published=settings.created_at.isoformat().replace("+00:00", "Z"), @@ -130,12 +145,12 @@ def actor(username: str): return _json(doc) -def _collection(username: str, which: str, items: list | None): +def _collection(username: str, which: str, items: list | None, total: int = 0): found = sharing.shared_user(username) if found is None: return _not_found("actor") urls = _urls(found[0].username) - return _json(vocab.ordered_collection(getattr(urls, which), 0, items)) + return _json(vocab.ordered_collection(getattr(urls, which), total, items)) @bp.get("/users//outbox") @@ -145,7 +160,9 @@ def outbox(username: str): @bp.get("/users//followers") def followers(username: str): - return _collection(username, "followers", None) # count only + found = sharing.shared_user(username) + total = follower_state.counts(found[0].id)["accepted"] if found else 0 + return _collection(username, "followers", None, total) # the count, not who @bp.get("/users//following") diff --git a/tests/test_federation_followers_api.py b/tests/test_federation_followers_api.py new file mode 100644 index 0000000..0d6f535 --- /dev/null +++ b/tests/test_federation_followers_api.py @@ -0,0 +1,172 @@ +"""Managing followers: the /api/v1/federation followers and blocks endpoints.""" + +import pytest + +from federation_helpers import RemoteAccount +from scrobbler import worker +from scrobbler.extensions import db +from scrobbler.federation import inbox, sharing +from scrobbler.federation.models import FederationActivity, FederationDelivery, FederationFollower + +AP = {"Accept": "application/activity+json"} + + +@pytest.fixture +def auth_headers(sharing_user): + from scrobbler.services.accounts import issue_ui_token + + return {"Authorization": f"Bearer {issue_ui_token(sharing_user)}"} + + +@pytest.fixture +def accounts(sharing_user, remote): + """Two remote accounts whose inboxes accept everything.""" + made = {} + for name in ("bob", "carol"): + account = RemoteAccount(remote, name) + remote.routes[f"/users/{name}/inbox"] = (202, {}, b"") + made[name] = account + return made + + +def follow(fed_client, account): + account.deliver(fed_client, account.follow()) + while inbox.work_once(): + pass + db.session.expire_all() + + +def sent_types(): + return [ + a.activity_type + for a in db.session.scalars( + db.select(FederationActivity).order_by(FederationActivity.created_at) + ) + ] + + +def api(fed_client, method, path, headers, **kwargs): + return getattr(fed_client, method)(f"/api/v1/federation{path}", headers=headers, **kwargs) + + +def test_followers_are_listed(fed_client, auth_headers, accounts): + follow(fed_client, accounts["bob"]) + [bob] = api(fed_client, "get", "/followers", auth_headers).get_json() + assert (bob["handle"], bob["state"], bob["display_name"]) == ( + "@bob@127.0.0.1", + "accepted", + "Bob", + ) + assert bob["actor_url"] == accounts["bob"].uri + settings = api(fed_client, "get", "/settings", auth_headers).get_json() + assert (settings["followers"], settings["pending_followers"]) == (1, 0) + + +def test_requests_can_be_approved(fed_client, auth_headers, accounts, sharing_user): + sharing.update(sharing_user.id, {"manually_approves_followers": True}) + follow(fed_client, accounts["bob"]) + follow(fed_client, accounts["carol"]) + pending = api(fed_client, "get", "/followers?state=pending", auth_headers).get_json() + assert {p["handle"] for p in pending} == {"@bob@127.0.0.1", "@carol@127.0.0.1"} + assert sent_types() == [] + + bob_id = next(p["id"] for p in pending if p["handle"].startswith("@bob")) + approved = api(fed_client, "post", f"/followers/{bob_id}/approve", auth_headers) + assert approved.get_json()["state"] == "accepted" + assert sent_types() == ["Accept"] + # Approving twice is a conflict, not a second Accept + assert api(fed_client, "post", f"/followers/{bob_id}/approve", auth_headers).status_code == 409 + + +def test_decline_and_remove_send_reject(fed_client, auth_headers, accounts, sharing_user): + sharing.update(sharing_user.id, {"manually_approves_followers": True}) + follow(fed_client, accounts["bob"]) + [request] = api(fed_client, "get", "/followers", auth_headers).get_json() + assert ( + api(fed_client, "post", f"/followers/{request['id']}/decline", auth_headers).status_code + == 204 + ) + assert sent_types() == ["Reject"] + assert api(fed_client, "get", "/followers", auth_headers).get_json() == [] + + sharing.update(sharing_user.id, {"manually_approves_followers": False}) + follow(fed_client, accounts["carol"]) + [carol] = api(fed_client, "get", "/followers", auth_headers).get_json() + assert ( + api(fed_client, "post", f"/followers/{carol['id']}/remove", auth_headers).status_code == 204 + ) + assert sent_types() == ["Reject", "Accept", "Reject"] + + +def test_block_and_unblock(fed_client, auth_headers, accounts): + follow(fed_client, accounts["bob"]) + [bob] = api(fed_client, "get", "/followers", auth_headers).get_json() + assert api(fed_client, "post", f"/followers/{bob['id']}/block", auth_headers).status_code == 204 + assert sent_types()[-1] == "Block" + [block] = api(fed_client, "get", "/blocks", auth_headers).get_json() + assert block["handle"] == "@bob@127.0.0.1" + + follow(fed_client, accounts["bob"]) # tries again: refused + assert api(fed_client, "get", "/followers", auth_headers).get_json() == [] + assert sent_types()[-1] == "Reject" + + assert api(fed_client, "delete", f"/blocks/{block['id']}", auth_headers).status_code == 204 + follow(fed_client, accounts["bob"]) # now allowed + assert len(api(fed_client, "get", "/followers", auth_headers).get_json()) == 1 + + +def test_other_users_followers_are_off_limits( + fed_client, auth_headers, accounts, make_user, fed_app +): + from scrobbler.services.accounts import issue_ui_token + + follow(fed_client, accounts["bob"]) + [bob] = api(fed_client, "get", "/followers", auth_headers).get_json() + other = make_user(username="mallory") + mallory = {"Authorization": f"Bearer {issue_ui_token(other)}"} + for action in ("approve", "decline", "remove", "block"): + assert ( + api(fed_client, "post", f"/followers/{bob['id']}/{action}", mallory).status_code == 404 + ) + assert api(fed_client, "get", "/followers", mallory).get_json() == [] + + +def test_turning_sharing_off_rejects_everyone(fed_client, auth_headers, accounts, remote): + follow(fed_client, accounts["bob"]) + follow(fed_client, accounts["carol"]) + while worker.run_once(): # send the Accepts + pass + api(fed_client, "patch", "/settings", auth_headers, json={"enabled": False}) + db.session.expire_all() + assert db.session.scalars(db.select(FederationFollower)).all() == [] + assert sent_types().count("Reject") == 2 + + # While the Rejects are on their way, other servers can still fetch the key to verify + # them, but nothing else about the profile. + actor = fed_client.get("/users/alice", headers=AP).get_json() + assert actor["publicKey"]["publicKeyPem"].startswith("-----BEGIN PUBLIC KEY-----") + assert (actor["name"], actor["summary"]) == ("alice", "") + assert ( + fed_client.get("/.well-known/webfinger?resource=acct:alice@scrobble.test").status_code + == 404 + ) + + while worker.run_once(): # deliver the Rejects + pass + db.session.expire_all() + assert {d.status for d in db.session.scalars(db.select(FederationDelivery))} == {"delivered"} + assert fed_client.get("/users/alice", headers=AP).status_code == 404 + + +def test_actor_reflects_approval_setting_and_follower_count(fed_client, accounts, sharing_user): + assert ( + fed_client.get("/users/alice", headers=AP).get_json()["manuallyApprovesFollowers"] is False + ) + sharing.update(sharing_user.id, {"manually_approves_followers": True}) + assert ( + fed_client.get("/users/alice", headers=AP).get_json()["manuallyApprovesFollowers"] is True + ) + + sharing.update(sharing_user.id, {"manually_approves_followers": False}) + follow(fed_client, accounts["bob"]) + assert fed_client.get("/users/alice/followers", headers=AP).get_json()["totalItems"] == 1 diff --git a/tests/test_federation_web.py b/tests/test_federation_web.py index 3a2e845..84e21ba 100644 --- a/tests/test_federation_web.py +++ b/tests/test_federation_web.py @@ -60,7 +60,7 @@ def test_actor_document(fed_client, sharing_user): assert doc["summary"] == "

    Listening.

    " assert doc["publicKey"]["id"] == f"{BASE}/users/alice#main-key" assert doc["publicKey"]["publicKeyPem"].startswith("-----BEGIN PUBLIC KEY-----") - assert doc["manuallyApprovesFollowers"] is True # follows are requests until phase 2 + assert doc["manuallyApprovesFollowers"] is False # the user's setting (off by default) assert (doc["discoverable"], doc["indexable"]) == (False, False) assert doc["url"] == "http://localhost:8080/profile.html?u=alice" From ec658a775168ccd2da5697585cd5e73aa4bb4231 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 21:44:34 +0100 Subject: [PATCH 28/56] Federation monitoring: followers, inbox and delivery panels, alerts (phase 2, step 7) Federation dashboard gains follower and request counts, inbox and delivery queue depths, activities received by type and result, incoming signature results by scheme and reason, deliveries by result, delivery latency and outgoing signature schemes. Every query was run against a live Prometheus. Alerts: FederationDeliveryBacklog (>100 waiting for 30m), FederationInboxBacklog (unprocessed for 15m) and FederationSignatureFailures (>20% failing for 15m). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- deploy/grafana/dashboards/federation.json | 652 +++++++++++++++++++++- deploy/prometheus/alerts.yml | 26 + 2 files changed, 669 insertions(+), 9 deletions(-) diff --git a/deploy/grafana/dashboards/federation.json b/deploy/grafana/dashboards/federation.json index f075cb5..760cd9b 100644 --- a/deploy/grafana/dashboards/federation.json +++ b/deploy/grafana/dashboards/federation.json @@ -273,9 +273,22 @@ } }, { - "type": "timeseries", - "title": "Inbox deliveries / min", - "description": "Activities other servers send us (follows, likes, ...). Accepted but not yet processed until following is implemented.", + "type": "row", + "title": "Followers", + "id": 7, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 18, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "stat", + "title": "Followers", + "description": "", "datasource": { "type": "prometheus", "uid": "prometheus" @@ -286,11 +299,577 @@ "type": "prometheus", "uid": "prometheus" }, - "expr": "sum by (inbox) (rate(scrobbler_federation_inbox_requests_total[$__rate_interval])) * 60", - "legendFormat": "{{inbox}}", + "expr": "max(scrobbler_federation_followers{state=\"accepted\"})", + "legendFormat": "__auto", "refId": "A" } ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 8, + "gridPos": { + "x": 0, + "y": 19, + "w": 6, + "h": 5 + } + }, + { + "type": "stat", + "title": "Follow requests waiting", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_federation_followers{state=\"pending\"})", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 9, + "gridPos": { + "x": 6, + "y": 19, + "w": 6, + "h": 5 + } + }, + { + "type": "stat", + "title": "Deliveries waiting", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_federation_queue{queue=\"deliveries\",status=\"pending\"})", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + }, + { + "color": "orange", + "value": 50 + }, + { + "color": "red", + "value": 100 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 10, + "gridPos": { + "x": 12, + "y": 19, + "w": 6, + "h": 5 + } + }, + { + "type": "stat", + "title": "Inbox waiting", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_federation_queue{queue=\"inbox\",status=\"queued\"})", + "legendFormat": "__auto", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "thresholds": { + "mode": "absolute", + "steps": [ + { + "color": "text", + "value": null + }, + { + "color": "orange", + "value": 10 + }, + { + "color": "red", + "value": 50 + } + ] + } + }, + "overrides": [] + }, + "options": { + "reduceOptions": { + "calcs": [ + "lastNotNull" + ], + "fields": "", + "values": false + }, + "colorMode": "value", + "graphMode": "area", + "textMode": "auto", + "justifyMode": "auto" + }, + "id": 11, + "gridPos": { + "x": 18, + "y": 19, + "w": 6, + "h": 5 + } + }, + { + "type": "row", + "title": "Inbox", + "id": 12, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 24, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Activities received / min", + "description": "queued/duplicate/blocked/invalid at intake; processed/rejected/failed after verification.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (type, result) (rate(scrobbler_federation_inbox_activities_total[$__rate_interval])) * 60", + "legendFormat": "{{type}} {{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 13, + "gridPos": { + "x": 0, + "y": 25, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Incoming signatures by result", + "description": "Per minute. Anything but 'ok' is a delivery we refused; bad_signature after a refresh usually means a forged or broken sender.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (scheme, result) (rate(scrobbler_federation_signatures_total{direction=\"in\"}[$__rate_interval])) * 60", + "legendFormat": "{{scheme}} {{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 14, + "gridPos": { + "x": 12, + "y": 25, + "w": 12, + "h": 8 + } + }, + { + "type": "row", + "title": "Deliveries", + "id": 15, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 33, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Deliveries / min by result", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (result) (rate(scrobbler_federation_deliveries_total[$__rate_interval])) * 60", + "legendFormat": "{{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [ + { + "matcher": { + "id": "byName", + "options": "delivered" + }, + "properties": [ + { + "id": "color", + "value": { + "mode": "fixed", + "fixedColor": "green" + } + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "retry" + }, + "properties": [ + { + "id": "color", + "value": { + "mode": "fixed", + "fixedColor": "orange" + } + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "abandoned" + }, + "properties": [ + { + "id": "color", + "value": { + "mode": "fixed", + "fixedColor": "red" + } + } + ] + }, + { + "matcher": { + "id": "byName", + "options": "gone" + }, + "properties": [ + { + "id": "color", + "value": { + "mode": "fixed", + "fixedColor": "purple" + } + } + ] + } + ] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 16, + "gridPos": { + "x": 0, + "y": 34, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Delivery latency", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.50, sum by (le) (rate(scrobbler_federation_delivery_seconds_bucket[$__rate_interval])))", + "legendFormat": "p50", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "histogram_quantile(0.95, sum by (le) (rate(scrobbler_federation_delivery_seconds_bucket[$__rate_interval])))", + "legendFormat": "p95", + "refId": "B" + } + ], + "fieldConfig": { + "defaults": { + "unit": "s", + "custom": { + "lineWidth": 2, + "fillOpacity": 10, + "showPoints": "never", + "spanNulls": true + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 17, + "gridPos": { + "x": 12, + "y": 34, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Queues", + "description": "", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_federation_queue{queue=\"deliveries\",status=\"pending\"})", + "legendFormat": "deliveries waiting", + "refId": "A" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_federation_queue{queue=\"inbox\",status=\"queued\"})", + "legendFormat": "inbox waiting", + "refId": "B" + }, + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "max(scrobbler_federation_queue{queue=\"inbox\",status=\"processing\"})", + "legendFormat": "inbox processing", + "refId": "C" + } + ], "fieldConfig": { "defaults": { "unit": "short", @@ -315,12 +894,67 @@ "sort": "desc" } }, - "id": 7, + "id": 18, "gridPos": { "x": 0, - "y": 18, - "w": 24, - "h": 7 + "y": 42, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Outgoing signatures by scheme", + "description": "Which scheme deliveries were finally sent with. rfc9421 means the first try got a 401 (double-knocking).", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (scheme) (rate(scrobbler_federation_signatures_total{direction=\"out\"}[$__rate_interval])) * 60", + "legendFormat": "{{scheme}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 19, + "gridPos": { + "x": 12, + "y": 42, + "w": 12, + "h": 8 } } ] diff --git a/deploy/prometheus/alerts.yml b/deploy/prometheus/alerts.yml index a0c6cd4..81f451d 100644 --- a/deploy/prometheus/alerts.yml +++ b/deploy/prometheus/alerts.yml @@ -73,6 +73,32 @@ groups: summary: Imports have been waiting for 15 minutes with nothing running description: The import worker is probably stopped or stuck. + - alert: FederationDeliveryBacklog + expr: max(scrobbler_federation_queue{queue="deliveries",status="pending"}) > 100 + for: 30m + labels: {severity: warning} + annotations: + summary: Over 100 fediverse deliveries have been waiting for 30 minutes + description: Check the worker is running and outbound HTTPS works; one slow server can back up retries. + + - alert: FederationInboxBacklog + expr: max(scrobbler_federation_queue{queue="inbox",status="queued"}) > 0 + for: 15m + labels: {severity: warning} + annotations: + summary: Received fediverse activities haven't been processed for 15 minutes + description: The worker is probably stopped, or stuck on something. + + - alert: FederationSignatureFailures + expr: | + sum(rate(scrobbler_federation_signatures_total{direction="in",result!="ok"}[15m])) + / sum(rate(scrobbler_federation_signatures_total{direction="in"}[15m])) > 0.2 + for: 15m + labels: {severity: warning} + annotations: + summary: More than 20% of incoming fediverse signatures are failing + description: Check the Federation dashboard for the reason (e.g. a clock problem shows as 'expired'). + - alert: PostgresDown expr: pg_up == 0 for: 2m From b93cfea5b3f0f16990d51adc41f10a432a43fb1a Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 22:11:39 +0100 Subject: [PATCH 29/56] Interop with a real GoToSocial server, and the fixes it found (phase 2, step 8) scripts/interop/run.sh brings up Scrobbler (API, worker, UI behind a throwaway-TLS Caddy) and GoToSocial 0.22.1 on a private .test network, creates a GoToSocial user, drives its sign-in/OAuth screens for a token, and checks: lookup by handle, follow accepted, unfollow, manual approval and approve, remove, block and unblock, and decline. Found and fixed along the way: - Keys whose id is a path serving the actor (GoToSocial's /main-key) weren't resolved; now all three publishing styles are handled - An Undo of an older Follow arriving after a newer Follow removed the new follower; an Undo now only removes the Follow it names (and Undo referencing a Follow by id is understood) - Rejects embedded the Follow, which some servers (GoToSocial) match by account pair, so a late Reject could cancel a newer request; Rejects now reference the Follow by id - Unblocking didn't tell the other server; it now sends Undo(Block) - Actors publish an (empty) featured collection, which Mastodon and GoToSocial fetch GoToSocial 0.22.1 ignores Reject for already-accepted follows (a TODO in its code, fixed on its main branch); the removal check on its side is skipped until a release has it (GTS_REJECT_ENDS_FOLLOWS=1 enables). Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- deploy/interop/docker-compose.interop.yml | 82 +++++ docs/openapi.json | 48 ++- scripts/interop/compose.sh | 5 + scripts/interop/gotosocial_interop.py | 354 +++++++++++++++++++++ scripts/interop/run.sh | 38 +++ src/scrobbler/federation/activities.py | 19 ++ src/scrobbler/federation/api.py | 6 +- src/scrobbler/federation/followers.py | 23 +- src/scrobbler/federation/inbox.py | 4 +- src/scrobbler/federation/openapi.py | 7 + src/scrobbler/federation/protocol/vocab.py | 25 +- src/scrobbler/federation/remote.py | 30 +- src/scrobbler/federation/web.py | 5 + tests/test_federation_followers_api.py | 4 + tests/test_federation_inbox.py | 38 +++ tests/test_federation_net_remote.py | 23 ++ 16 files changed, 694 insertions(+), 17 deletions(-) create mode 100644 deploy/interop/docker-compose.interop.yml create mode 100755 scripts/interop/compose.sh create mode 100644 scripts/interop/gotosocial_interop.py create mode 100755 scripts/interop/run.sh diff --git a/deploy/interop/docker-compose.interop.yml b/deploy/interop/docker-compose.interop.yml new file mode 100644 index 0000000..6e17017 --- /dev/null +++ b/deploy/interop/docker-compose.interop.yml @@ -0,0 +1,82 @@ +# Federation interop test: Scrobbler and a real GoToSocial server on one private network. +# +# docker compose -f docker-compose.yml -f deploy/interop/docker-compose.interop.yml up -d --build +# ...create the GoToSocial user (see scripts/interop/run.sh), then run the driver. +# +# TEST ONLY: GoToSocial runs over plain HTTP and skips TLS verification; Scrobbler is +# served over HTTPS by a Caddy proxy with a throwaway certificate, and its "insecure +# testing" switch lets it reach GoToSocial over HTTP on this private network. All on the +# reserved .test domain. Never use these settings anywhere else. +name: scrobbler-interop + +x-federation: &federation + DATABASE_URL: postgresql+psycopg://scrobbler:scrobbler@db:5432/scrobbler + FEDERATION_ENABLED: "1" + FEDERATION_DOMAIN: scrobble.test + FEDERATION_BASE_URL: https://scrobble.test + FEDERATION_KEY_SECRET: interop-test-only-secret-0123456789abcdef + FEDERATION_INSECURE_TESTING: "1" + UI_BASE_URL: https://scrobble.test + +networks: + fedi: + ipam: + config: + - subnet: 172.30.0.0/24 + +services: + db: + ports: !reset [] + networks: [fedi] + + api: + environment: *federation + ports: !reset [] + networks: [fedi] + + worker: + environment: *federation + networks: [fedi] + + ui: + environment: + API_BASE_URL: https://scrobble.test + API_INTERNAL_URL: http://api:8000 + ports: !reset [] + networks: [fedi] + + # GoToSocial looks up remote servers over HTTPS: serve scrobble.test with TLS + # (Caddy's internal CA) in front of the UI, which forwards fediverse paths to the API. + tls: + image: caddy:2.10 + command: ["caddy", "reverse-proxy", "--from", "https://scrobble.test", "--to", "http://ui:80", "--internal-certs"] + networks: + fedi: + aliases: [scrobble.test] + + gotosocial: + image: superseriousbusiness/gotosocial:0.22.1 + environment: + GTS_HOST: gts.test + GTS_PROTOCOL: http # local testing only + GTS_PORT: "80" + GTS_DB_TYPE: sqlite + GTS_DB_ADDRESS: /gotosocial/storage/sqlite.db + GTS_HTTP_CLIENT_ALLOW_IPS: 172.30.0.0/24 # let it reach Scrobbler on this network + GTS_HTTP_CLIENT_TLS_INSECURE_SKIP_VERIFY: "true" # Caddy's throwaway certificate + GTS_TRUSTED_PROXIES: 172.30.0.0/24 + GTS_ACCOUNTS_REGISTRATION_OPEN: "false" + GTS_LOG_LEVEL: ${GTS_LOG_LEVEL:-info} + sysctls: + net.ipv4.ip_unprivileged_port_start: 0 # listen on :80 as its non-root user + networks: + fedi: + aliases: [gts.test] + + driver: + image: python:3.13-slim + profiles: [driver] + volumes: + - ./scripts/interop:/interop:ro # relative to the project (first compose file) + command: ["python", "/interop/gotosocial_interop.py"] + networks: [fedi] diff --git a/docs/openapi.json b/docs/openapi.json index e053765..1ecff2a 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -2361,7 +2361,7 @@ } }, "summary": "Unblock an account", - "description": "They can follow you again (they aren't re-added).", + "description": "Their server is told (an Undo of the Block). They can follow you again; they aren't\nre-added.", "tags": [ "Federation" ], @@ -2675,6 +2675,52 @@ } ] }, + "/users/{username}/collections/featured": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "Featured", + "description": "Pinned posts (always empty for now).", + "operationId": "federation_featured", + "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": [ diff --git a/scripts/interop/compose.sh b/scripts/interop/compose.sh new file mode 100755 index 0000000..9674de8 --- /dev/null +++ b/scripts/interop/compose.sh @@ -0,0 +1,5 @@ +#!/usr/bin/env bash +# docker compose for the federation interop stack (Scrobbler + GoToSocial). +set -euo pipefail +root="$(cd "$(dirname "$0")/../.." && pwd)" +exec docker compose -f "$root/docker-compose.yml" -f "$root/deploy/interop/docker-compose.interop.yml" "$@" diff --git a/scripts/interop/gotosocial_interop.py b/scripts/interop/gotosocial_interop.py new file mode 100644 index 0000000..2434d79 --- /dev/null +++ b/scripts/interop/gotosocial_interop.py @@ -0,0 +1,354 @@ +"""Federation interop test: a real GoToSocial account follows a Scrobbler user. + +Runs inside the interop compose network (see deploy/interop/). Standard library only. +Exits non-zero, with a description, on the first thing that doesn't work. +""" + +import html +import http.cookiejar +import json +import os +import re +import sys +import time +import urllib.error +import urllib.parse +import urllib.request + +GTS = "http://gts.test" +SCROBBLER_API = "http://api:8000/api/v1" +GTS_EMAIL = os.environ.get("GTS_EMAIL", "gtsuser@gts.test") +GTS_PASSWORD = os.environ.get("GTS_PASSWORD", "Interop-Test-Password-1") +OOB = "urn:ietf:wg:oauth:2.0:oob" + + +def step(message: str) -> None: + print(f"==> {message}", flush=True) + + +class NoRedirect(urllib.request.HTTPRedirectHandler): + def redirect_request(self, *args, **kwargs): + return None + + +class Browser: + """Just enough of a browser to sign in and authorize an OAuth app.""" + + def __init__(self): + self.jar = http.cookiejar.CookieJar() + self.opener = urllib.request.build_opener( + urllib.request.HTTPCookieProcessor(self.jar), NoRedirect() + ) + + def request(self, method, url, form=None): + data = urllib.parse.urlencode(form).encode() if form is not None else None + req = urllib.request.Request(url, data=data, method=method) + if data is not None: + req.add_header("Content-Type", "application/x-www-form-urlencoded") + try: + with self.opener.open(req, timeout=20) as response: + return response.status, dict(response.headers), response.read().decode() + except urllib.error.HTTPError as err: # includes 3xx, since we don't follow them + return err.code, dict(err.headers), err.read().decode() + + +def api(method, url, token=None, body=None, form=None): + headers = {"Accept": "application/json"} + data = None + if body is not None: + data, headers["Content-Type"] = json.dumps(body).encode(), "application/json" + elif form is not None: + data, headers["Content-Type"] = ( + urllib.parse.urlencode(form).encode(), + "application/x-www-form-urlencoded", + ) + if token: + headers["Authorization"] = f"Bearer {token}" + req = urllib.request.Request(url, data=data, method=method, headers=headers) + try: + with urllib.request.urlopen(req, timeout=20) as response: + raw = response.read() + return response.status, json.loads(raw) if raw else None + except urllib.error.HTTPError as err: + raw = err.read() + try: + return err.code, json.loads(raw) + except json.JSONDecodeError: + return err.code, raw.decode(errors="replace")[:500] + + +def fail(message: str): + print(f"FAILED: {message}", flush=True) + sys.exit(1) + + +def gotosocial_token() -> str: + """Sign in to GoToSocial's web UI and authorize an app (it has no password grant).""" + status, app = api( + "POST", + f"{GTS}/api/v1/apps", + form={ + "client_name": "scrobbler-interop", + "redirect_uris": OOB, + "scopes": "read write follow", + }, + ) + if status != 200: + fail(f"creating a GoToSocial app: {status} {app}") + browser = Browser() + authorize = f"{GTS}/oauth/authorize?" + urllib.parse.urlencode( + { + "response_type": "code", + "client_id": app["client_id"], + "redirect_uri": OOB, + "scope": "read write follow", + } + ) + status, headers, body = browser.request("GET", authorize) + print(f" authorize -> {status} {headers.get('Location', '')}") + status, headers, body = browser.request( + "POST", f"{GTS}/auth/sign_in", {"username": GTS_EMAIL, "password": GTS_PASSWORD} + ) + print(f" sign in -> {status} {headers.get('Location', '')}") + if status not in (302, 303): + fail(f"sign-in didn't redirect: {status} {body[:300]}") + location = urllib.parse.urljoin(GTS, headers.get("Location", "/oauth/authorize")) + status, headers, body = browser.request("GET", location) + print(f" authorize page -> {status} {headers.get('Location', '')}") + if status == 200: + # The consent page: submit its form (with any hidden fields it has) + fields = dict(re.findall(r']*name="([^"]+)"[^>]*value="([^"]*)"', body)) + action = re.search(r']*action="([^"]+)"', body) + target = urllib.parse.urljoin( + GTS, html.unescape(action.group(1)) if action else "/oauth/authorize" + ) + status, headers, body = browser.request( + "POST", target, {k: html.unescape(v) for k, v in fields.items()} + ) + print(f" consent -> {status} {headers.get('Location', '')}") + location = headers.get("Location", "") + code = urllib.parse.parse_qs(urllib.parse.urlsplit(location).query).get("code", [None])[0] + if code is None and status in (302, 303): + # Out-of-band: the code is shown on the page we're sent to + status, headers, body = browser.request("GET", urllib.parse.urljoin(GTS, location)) + match = re.search(r"([^<]+)", body) or re.search( + r'value="([A-Za-z0-9_-]{20,})"', body + ) + code = match.group(1) if match else None + if not code: + fail(f"no authorization code (last response {status}: {body[:300]})") + status, token = api( + "POST", + f"{GTS}/oauth/token", + form={ + "grant_type": "authorization_code", + "code": code, + "client_id": app["client_id"], + "client_secret": app["client_secret"], + "redirect_uri": OOB, + }, + ) + if status != 200: + fail(f"exchanging the code: {status} {token}") + return token["access_token"] + + +def wait_for(description, check, timeout=60): + """Poll `check()` until it returns something truthy.""" + deadline = time.monotonic() + timeout + while time.monotonic() < deadline: + result = check() + if result: + return result + time.sleep(1) + fail(f"timed out waiting for: {description}") + + +class Scrobbler: + def __init__(self, username="alice", password="interop-password-1"): + status, body = api( + "POST", + f"{SCROBBLER_API}/auth/register", + body={ + "username": username, + "email": f"{username}@scrobble.test", + "password": password, + }, + ) + if status == 409: + status, body = api( + "POST", + f"{SCROBBLER_API}/auth/login", + body={ + "username": username, + "password": password, + }, + ) + if status not in (200, 201): + fail(f"signing in to Scrobbler: {status} {body}") + self.token = body["token"] + + def settings(self, **changes): + status, body = api( + "PATCH", f"{SCROBBLER_API}/federation/settings", self.token, body=changes + ) + if status != 200: + fail(f"changing Scrobbler settings: {status} {body}") + return body + + def followers(self, state=None): + query = f"?state={state}" if state else "" + status, body = api("GET", f"{SCROBBLER_API}/federation/followers{query}", self.token) + if status != 200: + fail(f"listing followers: {status} {body}") + return body + + def act(self, follower_id, action): + status, body = api( + "POST", f"{SCROBBLER_API}/federation/followers/{follower_id}/{action}", self.token + ) + if status not in (200, 204): + fail(f"{action} follower: {status} {body}") + + +class GoToSocial: + def __init__(self, token): + self.token = token + + def resolve(self, handle): + status, body = api( + "GET", + f"{GTS}/api/v2/search?" + + urllib.parse.urlencode({"q": handle, "resolve": "true", "type": "accounts"}), + self.token, + ) + if status != 200 or not body.get("accounts"): + fail(f"GoToSocial couldn't find {handle}: {status} {body}") + return body["accounts"][0] + + def follow(self, account_id): + status, body = api( + "POST", f"{GTS}/api/v1/accounts/{account_id}/follow", self.token, body={} + ) + if status != 200: + fail(f"following: {status} {body}") + return body + + def unfollow(self, account_id): + status, body = api( + "POST", f"{GTS}/api/v1/accounts/{account_id}/unfollow", self.token, body={} + ) + if status != 200: + fail(f"unfollowing: {status} {body}") + + def relationship(self, account_id): + status, body = api( + "GET", f"{GTS}/api/v1/accounts/relationships?id[]={account_id}", self.token + ) + if status != 200 or not body: + fail(f"relationship: {status} {body}") + return body[0] + + +def main(): + step("Getting a GoToSocial access token") + gts = GoToSocial(gotosocial_token()) + + step("Alice starts sharing on Scrobbler") + alice = Scrobbler() + alice.settings( + enabled=True, + display_name="Alice Interop", + bio="Testing federation.", + manually_approves_followers=False, + ) + + step("GoToSocial finds @alice@scrobble.test (WebFinger, actor, key)") + account = gts.resolve("@alice@scrobble.test") + print(f" found {account['acct']} ({account['display_name']!r})") + if account["display_name"] != "Alice Interop": + fail(f"unexpected display name {account['display_name']!r}") + account_id = account["id"] + + step("Follow: GoToSocial sees it accepted (our signed Accept verified)") + gts.follow(account_id) + wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"]) + followers = wait_for("Scrobbler to list the follower", lambda: alice.followers("accepted")) + print(f" Scrobbler follower: {followers[0]['handle']}") + if followers[0]["handle"] != "@gtsuser@gts.test": + fail(f"unexpected follower {followers[0]['handle']}") + + step("Unfollow: Scrobbler drops the follower (their signed Undo verified)") + gts.unfollow(account_id) + wait_for("Scrobbler to drop the follower", lambda: not alice.followers()) + + step("Manual approval: the follow waits as a request") + alice.settings(manually_approves_followers=True) + gts.follow(account_id) + wait_for( + "GoToSocial to show a pending request", lambda: gts.relationship(account_id)["requested"] + ) + pending = wait_for("Scrobbler to list the request", lambda: alice.followers("pending")) + if gts.relationship(account_id)["following"]: + fail("following before being approved") + + step("Approve: GoToSocial sees it accepted") + alice.act(pending[0]["id"], "approve") + wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"]) + + step("Remove the follower: Scrobbler drops them and sends a Reject") + alice.act(alice.followers()[0]["id"], "remove") + if alice.followers(): + fail("the follower is still listed after removal") + # GoToSocial 0.22.1 only applies a Reject to *pending* follow requests (its + # federatingdb/reject.go has a TODO for accepted follows; fixed on its main branch). + # Mastodon, and the ActivityPub consensus, drop the follow. Until a GoToSocial + # release includes the fix, their side is checked only when asked to. + if os.environ.get("GTS_REJECT_ENDS_FOLLOWS") == "1": + wait_for( + "GoToSocial to stop following", lambda: not gts.relationship(account_id)["following"] + ) + else: + print(" (skipping GoToSocial's side: its 0.22.1 ignores Reject for accepted follows)") + gts.unfollow(account_id) # tidy up their side for the next step + wait_for( + "GoToSocial to not be following", lambda: not gts.relationship(account_id)["following"] + ) + + step("Block a follower: GoToSocial drops the follow (it honours Block)") + gts.follow(account_id) + pending = wait_for("Scrobbler to list the request", lambda: alice.followers("pending")) + alice.act(pending[0]["id"], "approve") + wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"]) + alice.act(alice.followers()[0]["id"], "block") + wait_for("GoToSocial to stop following", lambda: not gts.relationship(account_id)["following"]) + status, blocks = api("GET", f"{SCROBBLER_API}/federation/blocks", alice.token) + if status != 200 or [b["handle"] for b in blocks] != ["@gtsuser@gts.test"]: + fail(f"the block isn't listed: {status} {blocks}") + wait_for("GoToSocial to see the block", lambda: gts.relationship(account_id)["blocked_by"]) + + step("Unblock: GoToSocial sees the Undo of the Block") + status, _ = api("DELETE", f"{SCROBBLER_API}/federation/blocks/{blocks[0]['id']}", alice.token) + if status != 204: + fail(f"unblocking: {status}") + wait_for( + "GoToSocial to see the unblock", lambda: not gts.relationship(account_id)["blocked_by"] + ) + + step("Decline a request: GoToSocial's request is withdrawn") + gts.follow(account_id) + pending = wait_for("Scrobbler to list the request", lambda: alice.followers("pending")) + alice.act(pending[0]["id"], "decline") + wait_for( + "GoToSocial's request to go away", + lambda: ( + not gts.relationship(account_id)["requested"] + and not gts.relationship(account_id)["following"] + ), + ) + + step("All interop checks passed") + + +if __name__ == "__main__": + main() diff --git a/scripts/interop/run.sh b/scripts/interop/run.sh new file mode 100755 index 0000000..3bfa33b --- /dev/null +++ b/scripts/interop/run.sh @@ -0,0 +1,38 @@ +#!/usr/bin/env bash +# Run the GoToSocial federation interop test end to end, then tear everything down. +# Usage: scripts/interop/run.sh [--keep] (--keep leaves the stack running afterwards) +set -uo pipefail +here="$(cd "$(dirname "$0")" && pwd)" +compose="$here/compose.sh" +keep=0; [ "${1:-}" = "--keep" ] && keep=1 + +cleanup() { [ "$keep" = 1 ] || "$compose" down -v --remove-orphans >/dev/null 2>&1; } +trap cleanup EXIT + +"$compose" down -v --remove-orphans >/dev/null 2>&1 +echo "==> Building and starting Scrobbler + GoToSocial" +"$compose" up -d --build --wait db api ui worker tls gotosocial || { "$compose" ps; exit 1; } + +echo "==> Waiting for GoToSocial" +for _ in $(seq 1 60); do + "$compose" exec -T gotosocial wget -qO- http://127.0.0.1/api/v1/instance >/dev/null 2>&1 && break + sleep 2 +done + +echo "==> Creating the GoToSocial test user" +"$compose" exec -T gotosocial /gotosocial/gotosocial admin account create \ + --username gtsuser --email gtsuser@gts.test --password 'Interop-Test-Password-1' >/dev/null +"$compose" exec -T gotosocial /gotosocial/gotosocial admin account confirm --username gtsuser >/dev/null + +"$compose" run --rm driver +status=$? +if [ $status -ne 0 ]; then + echo "==> Scrobbler federation state" + "$compose" exec -T db psql -U scrobbler -d scrobbler -c \ + "select activity_type, status, reason, attempts from federation_inbox order by id" -c \ + "select a.activity_type, d.status, d.attempts, d.last_status, left(d.last_error, 200) as error + from federation_deliveries d join federation_activities a on a.id = d.activity_id order by d.id" + echo "==> Recent logs" + "$compose" logs --tail 200 worker gotosocial | grep -v "api/v1/accounts/relationships" | tail -40 +fi +exit $status diff --git a/src/scrobbler/federation/activities.py b/src/scrobbler/federation/activities.py index 2b5691e..e1adbc7 100644 --- a/src/scrobbler/federation/activities.py +++ b/src/scrobbler/federation/activities.py @@ -68,3 +68,22 @@ def block(user_id: int, username: str, actor: FederationRemoteActor) -> Federati activity = _store(user_id, lambda url: vocab.block(url, ids.actor_id(username), actor.uri)) queue(activity, [actor.inbox]) return activity + + +def undo_block( + user_id: int, username: str, actor: FederationRemoteActor +) -> FederationActivity | None: + """Tell them they're unblocked: Undo our most recent Block of them (if we sent one).""" + block_activity = db.session.scalars( + db.select(FederationActivity) + .filter_by(user_id=user_id, activity_type="Block") + .filter(FederationActivity.document["object"].as_string() == actor.uri) + .order_by(FederationActivity.created_at.desc()) + ).first() + if block_activity is None: + return None + activity = _store( + user_id, lambda url: vocab.undo(url, ids.actor_id(username), block_activity.document) + ) + queue(activity, [actor.inbox]) + return activity diff --git a/src/scrobbler/federation/api.py b/src/scrobbler/federation/api.py index 8c05cdd..e6283d4 100644 --- a/src/scrobbler/federation/api.py +++ b/src/scrobbler/federation/api.py @@ -5,9 +5,9 @@ from flask_smorest import Blueprint, abort from scrobbler.api.decorators import authenticated from scrobbler.extensions import db +from scrobbler.federation import activities, sharing from scrobbler.federation import followers as follower_state from scrobbler.federation import metrics as fed_metrics -from scrobbler.federation import sharing from scrobbler.federation.models import FederationBlock, FederationFollower from scrobbler.federation.schemas import ( BlockSchema, @@ -225,10 +225,12 @@ def list_blocks(): def unblock(block_id): """Unblock an account - They can follow you again (they aren't re-added). + Their server is told (an Undo of the Block). They can follow you again; they aren't + re-added. """ block = db.session.get(FederationBlock, block_id) if block is None or block.user_id != g.user.id: abort(404, code="not_found", message="No such block") + activities.undo_block(g.user.id, g.user.username, block.actor) # tell their server db.session.delete(block) db.session.commit() diff --git a/src/scrobbler/federation/followers.py b/src/scrobbler/federation/followers.py index 36004c4..4e9a05c 100644 --- a/src/scrobbler/federation/followers.py +++ b/src/scrobbler/federation/followers.py @@ -63,12 +63,29 @@ def follow_received( return "pending" -def undo_follow(user_id: int, actor: FederationRemoteActor) -> bool: +def undo_follow(user_id: int, actor: FederationRemoteActor, follow_id: str | None) -> str: + """Handle an Undo of a Follow. It only removes the follower if it undoes their current + Follow: an Undo of an older one can arrive after a newer Follow (deliveries race).""" follower = get(user_id, actor) if follower is None: - return False + return "undo_not_following" + if follow_id is not None and follow_id != follower.follow_activity_id: + return "undo_stale" db.session.delete(follower) - return True + return "unfollowed" + + +def undo_follow_by_id(actor: FederationRemoteActor, follow_id: str) -> str: + """An Undo naming the Follow only by id: remove whoever follows with that Follow.""" + follower = db.session.scalar( + db.select(FederationFollower).filter_by( + remote_actor_id=actor.id, follow_activity_id=follow_id + ) + ) + if follower is None: + return "undo_not_following" + db.session.delete(follower) + return "unfollowed" def actor_deleted(actor: FederationRemoteActor) -> int: diff --git a/src/scrobbler/federation/inbox.py b/src/scrobbler/federation/inbox.py index 2dc735f..e2f89bd 100644 --- a/src/scrobbler/federation/inbox.py +++ b/src/scrobbler/federation/inbox.py @@ -294,12 +294,14 @@ def on_follow(doc: dict, actor: FederationRemoteActor) -> str: @handles("Undo") def on_undo(doc: dict, actor: FederationRemoteActor) -> str: inner = doc.get("object") + if isinstance(inner, str): # the Follow referenced by id rather than embedded + return followers.undo_follow_by_id(actor, inner) if not isinstance(inner, dict) or inner.get("type") != "Follow": return "undo_ignored" if object_id(inner.get("actor")) not in (None, actor.uri): raise Rejected("undo_other_actors_follow") user, _ = _local_user(inner.get("object")) - return "unfollowed" if followers.undo_follow(user.id, actor) else "undo_not_following" + return followers.undo_follow(user.id, actor, object_id(inner)) @handles("Delete") diff --git a/src/scrobbler/federation/openapi.py b/src/scrobbler/federation/openapi.py index 58ebf64..3a0b6b2 100644 --- a/src/scrobbler/federation/openapi.py +++ b/src/scrobbler/federation/openapi.py @@ -111,6 +111,13 @@ _OPERATIONS = { [_USERNAME], {"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND}, ), + "federation.featured": ( + "get", + "Featured", + "Pinned posts (always empty for now).", + [_USERNAME], + {"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND}, + ), "federation.instance_actor": ( "get", "Instance actor", diff --git a/src/scrobbler/federation/protocol/vocab.py b/src/scrobbler/federation/protocol/vocab.py index c9b8a94..95c4edd 100644 --- a/src/scrobbler/federation/protocol/vocab.py +++ b/src/scrobbler/federation/protocol/vocab.py @@ -16,6 +16,7 @@ ACTOR_CONTEXT = [ "toot": "http://joinmastodon.org/ns#", "discoverable": "toot:discoverable", "indexable": "toot:indexable", + "featured": {"@id": "toot:featured", "@type": "@id"}, "schema": "http://schema.org#", "PropertyValue": "schema:PropertyValue", "value": "schema:value", @@ -30,6 +31,7 @@ class ActorUrls: outbox: str followers: str following: str + featured: str shared_inbox: str key_id: str profile_page: str @@ -43,6 +45,7 @@ def actor_urls(base_url: str, username: str, profile_page: str) -> ActorUrls: outbox=f"{actor}/outbox", followers=f"{actor}/followers", following=f"{actor}/following", + featured=f"{actor}/collections/featured", shared_inbox=f"{base_url}/inbox", key_id=f"{actor}#main-key", profile_page=profile_page, @@ -90,6 +93,7 @@ def person( "outbox": urls.outbox, "followers": urls.followers, "following": urls.following, + "featured": urls.featured, "endpoints": {"sharedInbox": urls.shared_inbox}, "publicKey": public_key(urls, public_key_pem), "manuallyApprovesFollowers": manually_approves_followers, @@ -164,14 +168,31 @@ def accept(activity_id: str, actor_id: str, follow: dict) -> dict: def reject(activity_id: str, actor_id: str, follow: dict) -> dict: - """Decline a follow request, or end an existing follow.""" - return _response("Reject", activity_id, actor_id, follow, follow["actor"]) + """Decline a follow request, or end an existing follow. + + The Follow is referenced by id rather than embedded: some servers match an embedded + Follow by the pair of accounts, so a late Reject of an old Follow would cancel a + newer request between the same accounts. An id matches exactly that Follow.""" + return _response("Reject", activity_id, actor_id, follow["id"], follow["actor"]) def block(activity_id: str, actor_id: str, blocked_actor: str) -> dict: return _response("Block", activity_id, actor_id, blocked_actor, blocked_actor) +def undo(activity_id: str, actor_id: str, undone: dict) -> dict: + """Withdraw one of our earlier activities (e.g. a Block when unblocking).""" + to = undone.get("to") or [] + return { + "@context": AS_CONTEXT, + "id": activity_id, + "type": "Undo", + "actor": actor_id, + "object": undone, + "to": list(to), + } + + def object_id(value) -> str | None: """An object's id, whether it's given inline (a dict) or as a bare URI.""" if isinstance(value, dict): diff --git a/src/scrobbler/federation/remote.py b/src/scrobbler/federation/remote.py index 1265e0a..e3a9ba8 100644 --- a/src/scrobbler/federation/remote.py +++ b/src/scrobbler/federation/remote.py @@ -105,8 +105,10 @@ def get_actor(uri: str, refresh: bool = False) -> FederationRemoteActor: def actor_for_key(key_id: str, refresh: bool = False) -> FederationRemoteActor: - """The actor that owns `key_id`: usually `#main-key`, sometimes a separate - key document naming its owner.""" + """The actor that owns `key_id`. Servers publish keys three ways: + * a fragment of the actor (`#main-key`, Mastodon); + * a URL that serves the actor document itself (`/main-key`, GoToSocial); + * a separate key document naming its `owner`.""" cached = db.session.scalar(db.select(FederationRemoteActor).filter_by(public_key_id=key_id)) if cached is not None and not refresh: # Any age will do for checking a signature (a failure refreshes once). This also @@ -116,12 +118,24 @@ def actor_for_key(key_id: str, refresh: bool = False) -> FederationRemoteActor: try: return _matching(get_actor(document_url, refresh=True), key_id) except ActorError: - # Not an actor: a standalone key document pointing at its owner - doc = outbound.signed_get_json(document_url) - owner = doc.get("owner") - if doc.get("id") != key_id or not isinstance(owner, str) or _host(owner) != _host(key_id): - raise - return _matching(get_actor(owner, refresh=True), key_id) + pass # the key's URL isn't the actor's own URL: find the owner from the document + doc = outbound.signed_get_json(document_url) + if doc.get("id") == key_id and isinstance(doc.get("owner"), str): + owner = doc["owner"] # a standalone key document + elif isinstance(doc.get("id"), str) and _key_id_of(doc) == key_id: + owner = doc["id"] # the actor document, served at the key's URL + else: + raise ActorError(f"can't find who owns key {key_id}") + if _host(owner) != _host(key_id): + raise ActorError(f"key {key_id} claims an owner on another host") + return _matching(get_actor(owner, refresh=True), key_id) + + +def _key_id_of(doc: dict) -> str | None: + key = doc.get("publicKey") + if isinstance(key, list): + key = next((k for k in key if isinstance(k, dict)), None) + return key.get("id") if isinstance(key, dict) else None def _matching(actor: FederationRemoteActor, key_id: str) -> FederationRemoteActor: diff --git a/src/scrobbler/federation/web.py b/src/scrobbler/federation/web.py index 44a62e4..75d0d3c 100644 --- a/src/scrobbler/federation/web.py +++ b/src/scrobbler/federation/web.py @@ -165,6 +165,11 @@ def followers(username: str): return _collection(username, "followers", None, total) # the count, not who +@bp.get("/users//collections/featured") +def featured(username: str): + return _collection(username, "featured", []) # pinned posts: none (yet) + + @bp.get("/users//following") def following(username: str): return _collection(username, "following", []) diff --git a/tests/test_federation_followers_api.py b/tests/test_federation_followers_api.py index 0d6f535..535215e 100644 --- a/tests/test_federation_followers_api.py +++ b/tests/test_federation_followers_api.py @@ -111,6 +111,10 @@ def test_block_and_unblock(fed_client, auth_headers, accounts): assert sent_types()[-1] == "Reject" assert api(fed_client, "delete", f"/blocks/{block['id']}", auth_headers).status_code == 204 + # Their server is told they're unblocked: an Undo of our Block + undo = db.session.scalars(db.select(FederationActivity).filter_by(activity_type="Undo")).one() + assert undo.document["object"]["type"] == "Block" + assert undo.document["object"]["object"] == accounts["bob"].uri follow(fed_client, accounts["bob"]) # now allowed assert len(api(fed_client, "get", "/followers", auth_headers).get_json()) == 1 diff --git a/tests/test_federation_inbox.py b/tests/test_federation_inbox.py index 27dcb0d..ab06acb 100644 --- a/tests/test_federation_inbox.py +++ b/tests/test_federation_inbox.py @@ -185,6 +185,44 @@ def test_undo_follow(fed_client, bob, sharing_user): assert followers_of(sharing_user) == [] +def test_undo_referencing_the_follow_by_id(fed_client, bob, sharing_user): + follow = bob.follow() + bob.deliver(fed_client, follow) + process_all() + bob.deliver(fed_client, bob.activity("Undo", follow["id"])) + process_all() + assert last_item().reason == "unfollowed" + assert followers_of(sharing_user) == [] + + +def test_rejects_reference_the_follow_by_id(fed_client, bob, sharing_user): + """So a late Reject can't be matched to a newer request between the same accounts.""" + from scrobbler.federation import followers + + follow = bob.follow() + bob.deliver(fed_client, follow) + process_all() + followers.remove("alice", followers_of(sharing_user)[0]) + db.session.commit() + [reject] = sent("Reject") + assert reject.document["object"] == follow["id"] + + +def test_a_late_undo_of_an_old_follow_keeps_the_new_one(fed_client, bob, sharing_user): + """Deliveries race: an Undo of an earlier Follow can arrive after a newer Follow + (seen against GoToSocial). Only an Undo of the current Follow removes the follower.""" + old_follow = bob.follow() + bob.deliver(fed_client, old_follow) + process_all() + new_follow = bob.follow() + bob.deliver(fed_client, new_follow) + bob.deliver(fed_client, bob.activity("Undo", old_follow)) # arrives after the new Follow + process_all() + assert last_item().reason == "undo_stale" + [follower] = followers_of(sharing_user) + assert follower.follow_activity_id == new_follow["id"] + + def test_undo_of_someone_elses_follow_is_rejected(fed_client, bob, remote, sharing_user): carol = RemoteAccount(remote, "carol") follow = carol.follow() diff --git a/tests/test_federation_net_remote.py b/tests/test_federation_net_remote.py index dabdd04..854e898 100644 --- a/tests/test_federation_net_remote.py +++ b/tests/test_federation_net_remote.py @@ -254,3 +254,26 @@ def test_gone_actors_are_marked(fed_remote): with pytest.raises(FetchError): remote.get_actor(uri, refresh=True) assert db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=uri)).gone is True + + +def test_actor_for_a_key_url_that_serves_the_actor(fed_remote): + """GoToSocial: the key id is /main-key, and fetching it returns the actor.""" + uri = fed_remote.url("/users/dana") + doc = actor_doc(fed_remote, name="dana") + key_id = f"{uri}/main-key" + doc["publicKey"]["id"] = key_id + fed_remote.routes["/users/dana"] = (200, {}, doc) + fed_remote.routes["/users/dana/main-key"] = (200, {}, doc) # same document + actor = remote.actor_for_key(key_id) + assert (actor.uri, actor.public_key_id) == (uri, key_id) + + +def test_key_owner_on_another_host_is_refused(fed_remote): + key_id = fed_remote.url("/keys/eve") + fed_remote.routes["/keys/eve"] = ( + 200, + {}, + {"id": key_id, "owner": "https://elsewhere.example/users/eve", "publicKeyPem": "x"}, + ) + with pytest.raises(remote.ActorError): + remote.actor_for_key(key_id) From fe95f59fc895cc9f9d45799a59028e8b1ff4d09d Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 22:13:12 +0100 Subject: [PATCH 30/56] CI: run the GoToSocial interop test A federation-interop job runs scripts/interop/run.sh on every push (not for pull requests from forks), with a per-run compose project and subnet so concurrent runs can't collide. Publishing waits for it too. The driver is now an image with the script baked in, and the interop overlay avoids bind mounts, since CI jobs drive the host's Docker from inside a container. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- .dockerignore | 1 + .gitea/workflows/ci.yml | 24 +++++++++++++++++++---- deploy/interop/docker-compose.interop.yml | 16 ++++++++------- deploy/interop/driver.Dockerfile | 5 +++++ scripts/interop/compose.sh | 4 +++- scripts/interop/run.sh | 1 + 6 files changed, 39 insertions(+), 12 deletions(-) create mode 100644 deploy/interop/driver.Dockerfile diff --git a/.dockerignore b/.dockerignore index 9aaa085..867223f 100644 --- a/.dockerignore +++ b/.dockerignore @@ -11,3 +11,4 @@ tests docs deploy/grafana deploy/prometheus +# (scripts/interop is used by the interop driver image) diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 3615b1d..c2b47fa 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -77,10 +77,26 @@ jobs: - name: Dashboards are valid JSON run: for f in deploy/grafana/dashboards/*.json; do python3 -m json.tool "$f" > /dev/null; done + federation-interop: + # A real GoToSocial server follows a Scrobbler user (see scripts/interop/run.sh). + # Not for pull requests from forks: it runs containers on the runner's Docker. + if: github.event_name != 'pull_request' || github.event.pull_request.head.repo.full_name == github.repository + runs-on: ubuntu-latest + timeout-minutes: 20 + steps: + - uses: actions/checkout@v4 + - name: Scrobbler <-> GoToSocial + env: + INTEROP_PROJECT: interop-${{ github.run_id }} + run: | + # A subnet of its own, so concurrent runs can't collide + export INTEROP_SUBNET="172.30.$(( ${{ github.run_number }} % 200 + 20 )).0/24" + scripts/interop/run.sh + # ---- Publishing (main and v* tags only) ------------------------------------- images: - needs: [lint, test, validate-monitoring] + needs: [lint, test, validate-monitoring, federation-interop] if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) runs-on: ubuntu-latest outputs: @@ -123,7 +139,7 @@ jobs: run: docker logout "${{ vars.PKGS_HOST }}" || true assets: - needs: [lint, test, validate-monitoring] + needs: [lint, test, validate-monitoring, federation-interop] if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || startsWith(github.ref, 'refs/tags/v')) runs-on: ubuntu-latest steps: @@ -147,7 +163,7 @@ jobs: done python-package: - needs: [lint, test, validate-monitoring] + needs: [lint, test, validate-monitoring, federation-interop] if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/v') runs-on: ubuntu-latest steps: @@ -164,7 +180,7 @@ jobs: --username api --password "${{ secrets.PKGS_API_KEY }}" notify: - needs: [lint, test, validate-monitoring, images, assets, python-package] + needs: [lint, test, validate-monitoring, federation-interop, images, assets, python-package] if: always() runs-on: ubuntu-latest steps: diff --git a/deploy/interop/docker-compose.interop.yml b/deploy/interop/docker-compose.interop.yml index 6e17017..c6bd88d 100644 --- a/deploy/interop/docker-compose.interop.yml +++ b/deploy/interop/docker-compose.interop.yml @@ -22,11 +22,12 @@ networks: fedi: ipam: config: - - subnet: 172.30.0.0/24 + - subnet: ${INTEROP_SUBNET:-172.30.0.0/24} services: db: ports: !reset [] + volumes: !reset [db-data:/var/lib/postgresql/data] # no bind mounts (CI) networks: [fedi] api: @@ -62,9 +63,9 @@ services: GTS_PORT: "80" GTS_DB_TYPE: sqlite GTS_DB_ADDRESS: /gotosocial/storage/sqlite.db - GTS_HTTP_CLIENT_ALLOW_IPS: 172.30.0.0/24 # let it reach Scrobbler on this network + GTS_HTTP_CLIENT_ALLOW_IPS: ${INTEROP_SUBNET:-172.30.0.0/24} # let it reach Scrobbler on this network GTS_HTTP_CLIENT_TLS_INSECURE_SKIP_VERIFY: "true" # Caddy's throwaway certificate - GTS_TRUSTED_PROXIES: 172.30.0.0/24 + GTS_TRUSTED_PROXIES: ${INTEROP_SUBNET:-172.30.0.0/24} GTS_ACCOUNTS_REGISTRATION_OPEN: "false" GTS_LOG_LEVEL: ${GTS_LOG_LEVEL:-info} sysctls: @@ -74,9 +75,10 @@ services: aliases: [gts.test] driver: - image: python:3.13-slim + build: + context: . + dockerfile: deploy/interop/driver.Dockerfile profiles: [driver] - volumes: - - ./scripts/interop:/interop:ro # relative to the project (first compose file) - command: ["python", "/interop/gotosocial_interop.py"] + environment: + GTS_REJECT_ENDS_FOLLOWS: ${GTS_REJECT_ENDS_FOLLOWS:-0} networks: [fedi] diff --git a/deploy/interop/driver.Dockerfile b/deploy/interop/driver.Dockerfile new file mode 100644 index 0000000..618750c --- /dev/null +++ b/deploy/interop/driver.Dockerfile @@ -0,0 +1,5 @@ +# The interop test driver: the script baked in (CI runners can't bind-mount the workspace +# into sibling containers). +FROM python:3.13-slim +COPY scripts/interop/gotosocial_interop.py /interop/gotosocial_interop.py +CMD ["python", "/interop/gotosocial_interop.py"] diff --git a/scripts/interop/compose.sh b/scripts/interop/compose.sh index 9674de8..7884744 100755 --- a/scripts/interop/compose.sh +++ b/scripts/interop/compose.sh @@ -2,4 +2,6 @@ # docker compose for the federation interop stack (Scrobbler + GoToSocial). set -euo pipefail root="$(cd "$(dirname "$0")/../.." && pwd)" -exec docker compose -f "$root/docker-compose.yml" -f "$root/deploy/interop/docker-compose.interop.yml" "$@" +# INTEROP_PROJECT and INTEROP_SUBNET let concurrent runs (e.g. in CI) stay apart. +exec docker compose -p "${INTEROP_PROJECT:-scrobbler-interop}" \ + -f "$root/docker-compose.yml" -f "$root/deploy/interop/docker-compose.interop.yml" "$@" diff --git a/scripts/interop/run.sh b/scripts/interop/run.sh index 3bfa33b..0600cbb 100755 --- a/scripts/interop/run.sh +++ b/scripts/interop/run.sh @@ -24,6 +24,7 @@ echo "==> Creating the GoToSocial test user" --username gtsuser --email gtsuser@gts.test --password 'Interop-Test-Password-1' >/dev/null "$compose" exec -T gotosocial /gotosocial/gotosocial admin account confirm --username gtsuser >/dev/null +"$compose" build driver >/dev/null "$compose" run --rm driver status=$? if [ $status -ne 0 ]; then From fefdeb90ecf9eca7576e9b63c85a9f2dc1fb6a91 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 22:17:02 +0100 Subject: [PATCH 31/56] Document following on the fediverse; mark phase 2 done (phase 2, step 9) README: following works, the Followers page, optional federation settings and the worker requirement. Federation README: settings, module layout, worker tasks and the interop test. Design doc: what interop testing changed. Phase 2 plan marked done with its deviations (httpcore, no in-process two-instance test, Undo of Block), leaving only the manual Mastodon check. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- README.md | 15 ++++++++++++++- docs/design/activitypub-phase2.md | 8 ++++++++ docs/design/activitypub.md | 10 ++++++++++ src/scrobbler/federation/README.md | 24 ++++++++++++++++++++++-- 4 files changed, 54 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 49b659c..0421f6a 100644 --- a/README.md +++ b/README.md @@ -94,7 +94,12 @@ Unlike live scrobbles, imports keep plays of any age. They still skip rows with ## Sharing on the fediverse (in development) -Users can make their profile findable from Mastodon and other fediverse apps as `@name@`. Following, and posts (weekly summaries, milestones, now playing), are still being built; see `docs/design/activitypub.md`. Until then, profiles advertise follower approval, so a follow waits as a request rather than failing. +Users can make their profile findable from Mastodon and other fediverse apps as `@name@`, and be followed: + +- Follows are accepted automatically, or wait for approval if the user turns that on. +- The **Followers** page lists requests, followers and blocked accounts, with approve, decline, remove, block and unblock. + +Posts (weekly summaries, milestones, now playing) are still being built; see `docs/design/activitypub.md`. Federation is tested in CI against a real GoToSocial server (`scripts/interop/run.sh`). It's **off unless the server enables it**, and then **off for each user** until they switch it on under **Sharing**. To enable it: @@ -110,6 +115,14 @@ Handles and actor URLs **can't change once anyone follows** a user, so choose th `FEDERATION_KEY_SECRET` encrypts each user's signing key. **Back it up, and never change it**: losing it means users' keys can't be read, and followers would have to follow again. +Optional settings: + +- `FEDERATION_BLOCKED_DOMAINS`: comma-separated domains, including subdomains, whose deliveries and follows are refused. +- `FEDERATION_DELIVERY_CONCURRENCY`: parallel outgoing deliveries per worker (default 4). +- `FEDERATION_SIGNATURE_SCHEMES`: the signing order (default `draft-cavage,rfc9421`). + +The worker must be running: it processes incoming activities and delivers outgoing ones. + ## Develop ```sh diff --git a/docs/design/activitypub-phase2.md b/docs/design/activitypub-phase2.md index c157148..6050d80 100644 --- a/docs/design/activitypub-phase2.md +++ b/docs/design/activitypub-phase2.md @@ -1,5 +1,13 @@ # ActivityPub phase 2: followers +**Status: done** on `feature/activitypub` (`a6d3fb6` … `fe95f59`). The GoToSocial interop test passes locally and in CI. Before merging, the plan still calls for a manual pass with a real Mastodon account through a tunnel. + +Where this differed from the plan: + +- **httpcore instead of httpx.** httpcore is the transport layer underneath httpx, and it publicly supports the custom network backend that connecting to a pre-checked address needs. +- **No in-process test with two Scrobbler instances.** Scrobbler can't initiate follows yet, so one instance has nothing to send the other. Scripted remote accounts over real HTTP cover the same paths, and GoToSocial is the real second server. +- **Undo of a Block.** Unblocking needed it: GoToSocial otherwise keeps the block. + This implements phase 2 of [activitypub.md](activitypub.md), building on [phase 1](activitypub-phase1.md). **Outcome:** people on Mastodon, GoToSocial and similar servers can follow a user who shares. Follows are accepted automatically, or wait for the user's approval if they've turned it on. The user sees their followers and can approve, decline, remove or block them. Scrobbler signs everything it sends and checks the signature on everything it receives. Posts come in phase 3; this phase makes the relationship work end to end. diff --git a/docs/design/activitypub.md b/docs/design/activitypub.md index 1e86adc..8f98371 100644 --- a/docs/design/activitypub.md +++ b/docs/design/activitypub.md @@ -391,3 +391,13 @@ Still open (neither is needed before phase 3): - [SocialHub: RFC 9421 HTTP signatures in 2026](https://socialhub.activitypub.rocks/t/rfc-9421-http-signatures-in-2026/8427) - [Funkwhale federation docs](https://docs.funkwhale.audio/develop/developer/federation/index.html): the `Listen` activity with a `Track` object - [Pubby on PyPI](https://pypi.org/project/pubby/): features and AGPL-3.0-or-later licence + +## Lessons from interop testing (phase 2) + +Testing against a real GoToSocial server changed a few details: + +- **Key IDs come in three shapes.** A fragment of the actor (`#main-key`, used by Mastodon), a path that serves the actor document (`/main-key`, used by GoToSocial), or a separate key document with an `owner`. All three are resolved. +- **Rejects reference the Follow by ID rather than embedding it.** Some servers match an embedded Follow by the pair of accounts. A late Reject of an old Follow would then cancel a newer request between the same two accounts. +- **An Undo only removes the Follow it names.** Deliveries race, so an Undo of an older Follow can arrive after a newer one. +- **Unblocking sends an Undo of the Block**, so the other server lets the person follow again. +- **Actors publish a `featured` collection** (empty for now). Mastodon and GoToSocial fetch it. diff --git a/src/scrobbler/federation/README.md b/src/scrobbler/federation/README.md index 130e183..98925e5 100644 --- a/src/scrobbler/federation/README.md +++ b/src/scrobbler/federation/README.md @@ -32,6 +32,10 @@ or switched off without touching anything else. Design: `docs/design/activitypub | `FEDERATION_DOMAIN` | Handle domain, normally the web UI's host: users are `@name@`. **Permanent once anyone follows.** | | `FEDERATION_BASE_URL` | Public `https://` URL actors live under (`/users/`). Normally the web UI's origin, with the UI's nginx forwarding the ActivityPub paths to the API. | | `FEDERATION_KEY_SECRET` | 32+ characters; encrypts actors' private keys at rest (HKDF → Fernet). **Back it up; never change it.** | +| `FEDERATION_SIGNATURE_SCHEMES` | Outgoing signing order; the next scheme is tried only on a 401. Default `draft-cavage,rfc9421` | +| `FEDERATION_BLOCKED_DOMAINS` | Comma-separated domains (subdomains included) refused at the inbox | +| `FEDERATION_DELIVERY_CONCURRENCY` | Parallel deliveries per worker (1-32, default 4) | +| `FEDERATION_INSECURE_TESTING` | **Tests only.** Allows `http://` and private addresses; refused unless the domain is under `.test` | The UI container forwards these paths to the API when `API_INTERNAL_URL` is set (see `docker/ui-config.sh`): @@ -44,15 +48,31 @@ Every ActivityPub ID is built from `FEDERATION_BASE_URL`, never from the incomin | Module | Holds | |---|---| -| `protocol/` | Pure protocol code: media types, vocabulary, WebFinger, NodeInfo, host-meta | -| `models.py` | `federation_settings` and `federation_keys` | +| `protocol/` | Pure protocol code: media types, vocabulary, WebFinger, NodeInfo, host-meta, and `signatures/` (draft-cavage and RFC 9421, one module each) | +| `net.py` | The SSRF-safe HTTP client, the only way out | +| `outbound.py` | Signed GETs (as the instance actor) and POSTs (as a user), with scheme fallback on 401 | +| `remote.py` | Remote actors: fetched, validated, cached; key id to actor | +| `inbox.py` | Intake (no network) and worker processing: signature check, identity checks, handlers by activity type | +| `followers.py` | Follower state: follows, undo, approve, remove, block, sharing off | +| `activities.py` | Activities we send (Accept, Reject, Block, Undo), stored and queued per inbox | +| `delivery.py` | The delivery worker task: leases, retries with backoff, gone inboxes, gauges | +| `models.py` | `federation_*` tables | | `keys.py` | Key pairs, created once and encrypted at rest | | `sharing.py` | Per-user settings, and who is sharing | +| `ids.py` | Our ActivityPub ids, all from `FEDERATION_BASE_URL` | | `web.py` | The endpoints other servers call | | `api.py` and `schemas.py` | `/api/v1/federation/*` for the web UI | | `openapi.py` | OpenAPI descriptions of `web.py`'s endpoints | | `metrics.py` | Federation's own Prometheus metrics | +## Worker tasks + +`federation.inbox` (process received activities), `federation.deliver` (send queued ones), `federation.inbox.maintenance` (re-queue stalled, prune after 30 days) and `federation.gauges` (queue and follower gauges). All are registered only when federation is on. + +## Interop + +`scripts/interop/run.sh` runs Scrobbler against a real GoToSocial server on a private `.test` network and checks the whole follow life cycle. CI runs it on every push. GoToSocial 0.22.1 ignores a Reject of an already-accepted follow (a TODO in its code, fixed on its main branch), so that one check on its side is skipped until a release includes the fix. + ## Migrations Federation's tables (all prefixed `federation_`) live in their own Alembic branch, From bc717c2a068a1655dc21f01994ab42200c5a1465 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 10:58:48 +0100 Subject: [PATCH 32/56] Plan for ActivityPub phase 3 (posts) Weekly summaries (Monday 09:00 in each user's time zone) and milestones, followers-only by default: a core stats-window addition, idempotent posts keyed per week/threshold, Note/Create/Delete with visibility addressing, fan-out to followers' shared inboxes, no retroactive posts (baselines on enabling sharing and after imports), deletable posts and deletion when sharing is switched off, a paged outbox, API/UI, metrics and an alert, and interop checks with GoToSocial. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/design/activitypub-phase3.md | 184 ++++++++++++++++++++++++++++++ 1 file changed, 184 insertions(+) create mode 100644 docs/design/activitypub-phase3.md diff --git a/docs/design/activitypub-phase3.md b/docs/design/activitypub-phase3.md new file mode 100644 index 0000000..245ad30 --- /dev/null +++ b/docs/design/activitypub-phase3.md @@ -0,0 +1,184 @@ +# ActivityPub phase 3: posts + +This implements phase 3 of [activitypub.md](activitypub.md): **weekly summaries** and **milestones**. Now playing is phase 4. It builds on [phase 2](activitypub-phase2.md): followers, signed delivery and retries. + +**Outcome:** + +- A user who shares gets two kinds of post, delivered to their followers: a summary of the past week, every Monday morning in their own time zone, and occasional milestone posts. +- Posts are **followers only by default**, following the user's visibility setting. +- Each kind can be switched off, and any post can be deleted. Turning sharing off deletes the posts from followers' servers. +- Existing history never produces posts retroactively. + +Everything is in `scrobbler.federation` except one small addition to the core stats service (§1), and the boundary tests keep holding. + +## 1. Core: stats over a date range + +- `services.stats` gains top artists, top tracks and play counts for an explicit window (`start`, `end`). Today it only knows the rolling periods (`7day` and so on). +- The existing functions keep working, re-expressed on top of the window version. This is a core change and is tested like one. Federation uses it through the public service, as the boundary rules require. + +## 2. Settings and data (migration on the `federation` branch) + +- **`federation_settings` gains:** + - `timezone`: an IANA name such as `Europe/London`, validated with `zoneinfo`. The Sharing page fills it in from the browser the first time. + - `post_weekly_summary`: default on. + - `post_milestones`: default on. +- **`federation_posts`**, one row per post: + - user, `kind` (`weekly` or `milestone`) + - `key`, unique per user, e.g. `weekly:2026-W39` or `milestone:scrobbles:10000` + - the Note's UUID, the visibility it was sent with, plain-text and HTML content + - `created_at`, and `deleted_at` (a tombstone) + + The unique key makes posting **idempotent**: a worker restart or a repeated check can never post twice. +- **`federation_milestone_marks`**: user plus key, with `posted` true or false. It records thresholds already passed, including ones deliberately *not* posted (see §5). +- **`federation_pending_checks`**: user, `since`, `reason`. It's a small queue, filled by event receivers (§5), so receivers never do real work inside a scrobble request. + +## 3. Vocabulary (pure: `protocol/vocab.py`) + +- **`note(...)`**: a `Note` with: + - `id`, `attributedTo`, `content` (HTML) plus `contentMap` (`{"en": …}`) + - `published`, `url` (the UI post page) + - `to` and `cc` from the visibility setting + - `tag` (`Hashtag` objects: `#Scrobbler`, and `#NowPlaying` in phase 4) + - `sensitive: false` +- **`create(...)`**: `Create` wrapping the Note, with the same addressing. +- **`delete(...)`**: `Delete` whose object is a `Tombstone` of the Note (the same shape Mastodon sends). +- **`ordered_collection_page(...)`**, used for outbox paging. +- **Addressing** comes from one function (`protocol/addressing.py`), unit-tested for each visibility: + - followers only: `to` followers, no `cc` + - unlisted: `to` followers, `cc` Public + - public: `to` Public, `cc` followers +- The HTML uses only tags Mastodon keeps (`p`, `br`, `strong`, `em`, `ol`, `li`), and every artist and track name is escaped. A formatting test covers awkward names (`") == "<script>alert(1)</script>" + + +def test_escape_handles_ampersands_without_double_escaping(): + assert content.escape("Earth, Wind & Fire") == "Earth, Wind & Fire" + + +def test_escape_passes_through_emoji_and_non_latin_text(): + # Emoji and non-Latin scripts aren't HTML-significant, so they pass through untouched. + assert content.escape("Björk 🎵 坂本龍一") == "Björk 🎵 坂本龍一" + + +def test_escape_does_not_break_right_to_left_text(): + name = "محمد <عبده>" # Arabic text with embedded angle brackets + escaped = content.escape(name) + assert "<" not in escaped and ">" not in escaped + assert "محمد" in escaped # the Arabic letters are untouched + + +def test_paragraph_and_numbered_list_only_use_tags_mastodon_keeps(): + assert content.paragraph("hi") == "

    hi

    " + assert content.numbered_list(["a", "b"]) == "
    1. a
    2. b
    " + + +@pytest.mark.parametrize( + ("count", "word"), [(0, "plays"), (1, "play"), (2, "plays"), (312, "plays")] +) +def test_plural(count, word): + assert content.plural(count, "play") == word + + +def test_hashtag_line_matches_the_vocab_hashtag_name(): + from scrobbler.federation.protocol import vocab + + assert content.hashtag_line() == vocab.hashtag(content.HASHTAG)["name"] + + +# --- The weekly summary template (uses the primitives above) -------------------------- + + +def test_build_content_escapes_hostile_names_in_both_text_and_html(): + artists = [TopItem(1, "", 5)] + tracks = [TopItem(1, 'Earth, Wind & Fire\'s "Anthem"', 3, artist="A & B", duration=200)] + text, html = build_content(8, artists, tracks) + + assert " + + + + +
    +
    +
    + + diff --git a/frontend/posts.html b/frontend/posts.html new file mode 100644 index 0000000..a7e2381 --- /dev/null +++ b/frontend/posts.html @@ -0,0 +1,21 @@ + + + + + + Posts · Scrobbler + + + + + + + +
    +

    Posts

    +

    Weekly summaries and milestones sent to the fediverse. Sharing settings

    +
    +
      +
      + + diff --git a/frontend/sharing.html b/frontend/sharing.html index 1cade12..96ac78e 100644 --- a/frontend/sharing.html +++ b/frontend/sharing.html @@ -60,6 +60,29 @@
      +
      + What to post +
      + + +
      +
      + + +
      +
      + + + + Decides when your week ends for the weekly summary. +
      +
      + +
      + +

      See your posts

      +
      +
      Profile
      diff --git a/src/scrobbler/federation/api.py b/src/scrobbler/federation/api.py index a3504b5..cbf967a 100644 --- a/src/scrobbler/federation/api.py +++ b/src/scrobbler/federation/api.py @@ -5,17 +5,21 @@ from flask_smorest import Blueprint, abort from scrobbler.api.decorators import authenticated from scrobbler.extensions import db -from scrobbler.federation import activities, publishing, sharing +from scrobbler.federation import activities, ids, publishing, sharing from scrobbler.federation import followers as follower_state from scrobbler.federation import metrics as fed_metrics -from scrobbler.federation.models import FederationBlock, FederationFollower +from scrobbler.federation.models import FederationBlock, FederationFollower, FederationPost +from scrobbler.federation.publishing import weekly from scrobbler.federation.schemas import ( BlockSchema, FollowerListArgsSchema, FollowerSchema, + PostSchema, + PublicPostSchema, PublicProfileSchema, SharingSettingsSchema, SharingSettingsUpdateSchema, + WeeklyPreviewSchema, ) from scrobbler.schemas import ErrorSchema @@ -86,6 +90,73 @@ def update_settings(changes): return _settings_body(g.user, settings) +@blp.route("/preview/weekly", methods=["GET"]) +@authenticated(blp) +@blp.response(200, WeeklyPreviewSchema) +def preview_weekly(): + """Preview this week's summary + + What it would say right now, for the week still in progress. Never posted or stored. + """ + result = weekly.preview(g.user.id) + if result is None: # pragma: no cover - g.user is always a real, current account + abort(404, code="not_found", message="No such user") + text, html = result + return {"text": text, "html": html} + + +def _post_body(post: FederationPost) -> dict: + return { + "id": post.id, + "kind": post.kind, + "text": post.content_text, + "visibility": post.visibility, + "created_at": post.created_at, + "deleted_at": post.deleted_at, + } + + +@blp.route("/posts", methods=["GET"]) +@authenticated(blp) +@blp.response(200, PostSchema(many=True)) +def list_posts(): + """Your posts + + Newest first, including deleted ones (their text stays visible to you; deleted_at + shows when). + """ + posts = db.session.scalars( + db.select(FederationPost) + .filter_by(user_id=g.user.id) + .order_by(FederationPost.created_at.desc()) + ).all() + return [_post_body(p) for p in posts] + + +def _own_post(post_id: int) -> FederationPost: + post = db.session.get(FederationPost, post_id) + if post is None or post.user_id != g.user.id: + abort(404, code="not_found", message="No such post") + return post + + +@blp.route("/posts/", methods=["DELETE"]) +@authenticated(blp) +@blp.response(204) +@blp.alt_response(404, schema=ErrorSchema, description="No such post") +@blp.alt_response(409, schema=ErrorSchema, description="Already deleted") +def delete_post(post_id): + """Delete a post + + Sends a Delete to whoever received it. + """ + post = _own_post(post_id) + activity = publishing.delete_post(g.user.id, g.user.username, post) + if activity is None: + abort(409, code="already_deleted", message="That post is already deleted.") + db.session.commit() + + @blp.route("/profiles/", methods=["GET"]) @blp.response(200, PublicProfileSchema) @blp.alt_response(404, schema=ErrorSchema, description="No one sharing with that name") @@ -108,6 +179,38 @@ def public_profile(username): } +@blp.route("/profiles//posts/", methods=["GET"]) +@blp.response(200, PublicPostSchema) +@blp.alt_response(404, schema=ErrorSchema, description="Not found, not public, or deleted") +def public_post(username, post_uuid): + """A public or unlisted post + + For the web UI's post page (the browser landing spot for a Note's `url`, since it + can't itself speak ActivityPub). + """ + found = sharing.shared_user(username) + if found is not None: + user, settings = found + post = publishing.find_by_note_id(user.id, ids.note_url(username, post_uuid)) + else: + post = None + if ( + post is None + or post.deleted_at is not None + or post.visibility not in publishing.LISTED_VISIBILITIES + ): + fed_metrics.lookups_total.labels(kind="post", result="not_found").inc() + abort(404, code="not_found", message="No such post.") + fed_metrics.lookups_total.labels(kind="post", result="found").inc() + return { + "text": post.content_text, + "html": post.content_html, + "created_at": post.created_at, + "display_name": settings.display_name or user.username, + **{k: v for k, v in _identity(user.username).items() if k != "actor_url"}, + } + + # --- Followers --------------------------------------------------------------------------- diff --git a/src/scrobbler/federation/ids.py b/src/scrobbler/federation/ids.py index c49ed0a..81807cc 100644 --- a/src/scrobbler/federation/ids.py +++ b/src/scrobbler/federation/ids.py @@ -37,8 +37,9 @@ def note_url(username: str, post_uuid: str) -> str: def post_page_url(username: str, post_uuid: str) -> str: - """Where a browser following the Note's `url` lands, in the web UI.""" - return f"{current_app.config['UI_BASE_URL']}/post.html?id={post_uuid}" + """Where a browser following the Note's `url` lands, in the web UI. Carries the + username too: the UI page has no other way to know whose post to look up.""" + return f"{current_app.config['UI_BASE_URL']}/post.html?u={username}&id={post_uuid}" def username_from_actor_id(uri: str | None) -> str | None: diff --git a/src/scrobbler/federation/protocol/schedule.py b/src/scrobbler/federation/protocol/schedule.py index 0de8c88..1a5f4fc 100644 --- a/src/scrobbler/federation/protocol/schedule.py +++ b/src/scrobbler/federation/protocol/schedule.py @@ -30,6 +30,14 @@ def target_week(now_utc: datetime, tz: ZoneInfo) -> tuple[datetime, datetime, st return start_local.astimezone(UTC), end_local.astimezone(UTC), f"{year}-W{week:02d}" +def current_week_start(now_utc: datetime, tz: ZoneInfo) -> datetime: + """The UTC instant of this week's Monday 00:00 local time - the week still in + progress, not yet postable. For previewing what a summary would say so far.""" + local_now = now_utc.astimezone(tz) + monday = local_now.date() - timedelta(days=local_now.weekday()) + return datetime(monday.year, monday.month, monday.day, tzinfo=tz).astimezone(UTC) + + def resolve_timezone(name: str) -> ZoneInfo: """A user's timezone setting, or UTC for anything that isn't a valid IANA name (a bad or since-removed name in one user's settings must never crash the task for diff --git a/src/scrobbler/federation/publishing/weekly.py b/src/scrobbler/federation/publishing/weekly.py index 697ee17..7f1e273 100644 --- a/src/scrobbler/federation/publishing/weekly.py +++ b/src/scrobbler/federation/publishing/weekly.py @@ -11,7 +11,7 @@ import logging from datetime import UTC, datetime from scrobbler.extensions import db -from scrobbler.federation import publishing +from scrobbler.federation import publishing, sharing from scrobbler.federation.models import FederationSettings from scrobbler.federation.protocol import content, schedule from scrobbler.services import accounts, stats @@ -83,6 +83,22 @@ def check_and_post(settings: FederationSettings, now_utc: datetime) -> str: return "posted" if post is not None else "already_posted" # lost a race with another pass +def preview(user_id: int, now_utc: datetime | None = None) -> tuple[str, str] | None: + """What a weekly summary would say right now, for the week still in progress. Never + stored or posted: for the Sharing page's live preview. None if the account is gone.""" + user = accounts.get_user(user_id) + if user is None: + return None + settings = sharing.settings_for(user_id) + tz = schedule.resolve_timezone(settings.timezone) + now_utc = now_utc or datetime.now(UTC) + start = schedule.current_week_start(now_utc, tz) + count = stats.scrobble_count_between(user, start, now_utc) + top_artists = stats.top_artists_between(user, start, now_utc, limit=TOP_ARTISTS) + top_tracks = stats.top_tracks_between(user, start, now_utc, limit=1) + return build_content(count, top_artists, top_tracks) + + def check_all(now_utc: datetime | None = None) -> None: """Worker task (periodic): check every sharing user with weekly summaries on. One user's failure is logged and doesn't stop the rest from being checked.""" diff --git a/src/scrobbler/federation/schemas.py b/src/scrobbler/federation/schemas.py index cb1b5d6..80a9218 100644 --- a/src/scrobbler/federation/schemas.py +++ b/src/scrobbler/federation/schemas.py @@ -1,6 +1,12 @@ -from marshmallow import Schema, fields, validate +from marshmallow import Schema, ValidationError, fields, validate from scrobbler.federation.models import VISIBILITIES +from scrobbler.federation.protocol.schedule import is_valid_timezone + + +def _valid_timezone(value: str) -> None: + if not is_valid_timezone(value): + raise ValidationError("Not a known time zone.") class SharingSettingsSchema(Schema): @@ -20,6 +26,24 @@ class SharingSettingsSchema(Schema): 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)) + timezone = fields.String( + validate=_valid_timezone, + metadata={ + "description": ( + "IANA time zone, e.g. `Europe/London`. Decides when a week ends for the " + "weekly summary." + ), + "example": "Europe/London", + }, + ) + post_weekly_summary = fields.Boolean( + metadata={"description": "Post a weekly summary of your listening"} + ) + post_milestones = fields.Boolean( + metadata={ + "description": "Post scrobble-count, artist-plays and top-10 milestones as you hit them" + } + ) 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) @@ -61,3 +85,28 @@ class BlockSchema(Schema): display_name = fields.String(allow_none=True) actor_url = fields.String() since = fields.DateTime() + + +class PostSchema(Schema): + id = fields.Integer() + kind = fields.String(metadata={"description": "weekly or milestone"}) + text = fields.String() + visibility = fields.String() + created_at = fields.DateTime() + deleted_at = fields.DateTime(allow_none=True) + + +class WeeklyPreviewSchema(Schema): + text = fields.String() + html = fields.String() + + +class PublicPostSchema(Schema): + """A public or unlisted post, for the web UI's post page (post.html).""" + + text = fields.String() + html = fields.String() + created_at = fields.DateTime() + display_name = fields.String() + handle = fields.String(metadata={"example": "@alice@scrobble.example"}) + profile_url = fields.String() diff --git a/tests/test_federation_api.py b/tests/test_federation_api.py index d88dea6..007ab41 100644 --- a/tests/test_federation_api.py +++ b/tests/test_federation_api.py @@ -1,5 +1,12 @@ +from datetime import UTC, datetime, timedelta + import pytest +from scrobbler.extensions import db +from scrobbler.federation import publishing, sharing +from scrobbler.federation.models import FederationPost +from scrobbler.models import Scrobble + @pytest.fixture def fed_auth(fed_ctx, user): @@ -17,11 +24,38 @@ def test_settings_start_private(fed_client, fed_auth): False, False, ) + assert (body["timezone"], body["post_weekly_summary"], body["post_milestones"]) == ( + "UTC", + True, + True, + ) 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_timezone_and_post_toggles_can_be_changed(fed_client, fed_auth): + response = fed_client.patch( + "/api/v1/federation/settings", + json={"timezone": "Europe/London", "post_weekly_summary": False}, + headers=fed_auth, + ) + assert response.status_code == 200 + body = response.get_json() + assert (body["timezone"], body["post_weekly_summary"], body["post_milestones"]) == ( + "Europe/London", + False, + True, + ) + + +def test_an_unknown_timezone_is_rejected(fed_client, fed_auth): + response = fed_client.patch( + "/api/v1/federation/settings", json={"timezone": "Mars/Phobos"}, headers=fed_auth + ) + assert response.status_code == 422 + + 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( @@ -80,3 +114,115 @@ def test_public_profile(fed_client, sharing_user, make_user): def test_disabled_server_has_no_federation_api(client, auth): assert client.get("/api/v1/federation/settings", headers=auth).status_code == 404 + + +def test_public_post_serves_a_public_or_unlisted_note(fed_client, fed_ctx, sharing_user): + sharing.update(sharing_user.id, {"visibility": "unlisted"}) + post = publishing.publish(sharing_user.id, "alice", "weekly", "a", text="t", html="

      t

      ") + note_uuid = post.activity.document["object"]["id"].rsplit("/", 1)[-1] + + body = fed_client.get(f"/api/v1/federation/profiles/alice/posts/{note_uuid}").get_json() + assert body == { + "text": "t", + "html": "

      t

      ", + "created_at": body["created_at"], + "display_name": "Alice", + "handle": "@alice@scrobble.test", + "profile_url": "http://localhost:8080/profile.html?u=alice", + } + + +def test_public_post_404s_for_followers_only_deleted_or_unknown(fed_client, fed_ctx, sharing_user): + post = publishing.publish(sharing_user.id, "alice", "weekly", "a", text="t", html="

      t

      ") + note_uuid = post.activity.document["object"]["id"].rsplit("/", 1)[-1] + # followers-only (the default) + assert fed_client.get(f"/api/v1/federation/profiles/alice/posts/{note_uuid}").status_code == 404 + + sharing.update(post.user_id, {"visibility": "public"}) + publishing.delete_post(post.user_id, "alice", post) + db.session.commit() + assert fed_client.get(f"/api/v1/federation/profiles/alice/posts/{note_uuid}").status_code == 404 + + assert fed_client.get("/api/v1/federation/profiles/alice/posts/not-a-uuid").status_code == 404 + assert fed_client.get("/api/v1/federation/profiles/nobody/posts/not-a-uuid").status_code == 404 + + +# --- Posts and preview ------------------------------------------------------------------ + + +def test_preview_weekly_reflects_the_week_in_progress(fed_client, fed_auth, fed_ctx, user): + now = datetime.now(UTC) + monday = now.date() - timedelta(days=now.weekday()) + db.session.add( + Scrobble( + user_id=user.id, + artist="Radiohead", + track="Reckoner", + played_at=datetime(monday.year, monday.month, monday.day, 12, tzinfo=UTC), + ) + ) + db.session.commit() + + response = fed_client.get("/api/v1/federation/preview/weekly", headers=fed_auth) + assert response.status_code == 200 + body = response.get_json() + assert "1 play" in body["text"] + assert "

      " in body["html"] + # Never stored or posted + assert db.session.scalar(db.select(db.func.count()).select_from(FederationPost)) == 0 + + +def test_preview_weekly_needs_auth(fed_client): + assert fed_client.get("/api/v1/federation/preview/weekly").status_code == 401 + + +def test_list_posts_newest_first_including_deleted(fed_client, fed_auth, fed_ctx, user): + sharing.update(user.id, {"enabled": True, "visibility": "public"}) + first = publishing.publish(user.id, "alice", "weekly", "a", text="first", html="

      1

      ") + second = publishing.publish(user.id, "alice", "weekly", "b", text="second", html="

      2

      ") + publishing.delete_post(user.id, "alice", second) + db.session.commit() + + body = fed_client.get("/api/v1/federation/posts", headers=fed_auth).get_json() + assert [p["id"] for p in body] == [second.id, first.id] + assert body[0]["text"] == "second" + assert body[0]["deleted_at"] is not None + assert body[1]["deleted_at"] is None + + +def test_list_posts_needs_auth(fed_client): + assert fed_client.get("/api/v1/federation/posts").status_code == 401 + + +def test_delete_post(fed_client, fed_auth, fed_ctx, user): + sharing.update(user.id, {"enabled": True, "visibility": "public"}) + post = publishing.publish(user.id, "alice", "weekly", "a", text="t", html="

      t

      ") + db.session.commit() + + response = fed_client.delete(f"/api/v1/federation/posts/{post.id}", headers=fed_auth) + assert response.status_code == 204 + assert db.session.get(FederationPost, post.id).deleted_at is not None + + +def test_deleting_an_already_deleted_post_conflicts(fed_client, fed_auth, fed_ctx, user): + sharing.update(user.id, {"enabled": True, "visibility": "public"}) + post = publishing.publish(user.id, "alice", "weekly", "a", text="t", html="

      t

      ") + db.session.commit() + fed_client.delete(f"/api/v1/federation/posts/{post.id}", headers=fed_auth) + + response = fed_client.delete(f"/api/v1/federation/posts/{post.id}", headers=fed_auth) + assert response.status_code == 409 + + +def test_deleting_someone_elses_post_is_not_found(fed_client, fed_auth, fed_ctx, user, make_user): + other = make_user(username="bob") + sharing.update(other.id, {"enabled": True, "visibility": "public"}) + post = publishing.publish(other.id, "bob", "weekly", "a", text="t", html="

      t

      ") + db.session.commit() + + response = fed_client.delete(f"/api/v1/federation/posts/{post.id}", headers=fed_auth) + assert response.status_code == 404 + + +def test_deleting_an_unknown_post_is_not_found(fed_client, fed_auth): + assert fed_client.delete("/api/v1/federation/posts/999999", headers=fed_auth).status_code == 404 diff --git a/tests/test_federation_web.py b/tests/test_federation_web.py index fc0b0e7..71b596c 100644 --- a/tests/test_federation_web.py +++ b/tests/test_federation_web.py @@ -170,7 +170,7 @@ def test_post_note_browser_is_redirected_to_the_ui_page(fed_client, fed_ctx, sha note_uuid = post.activity.document["object"]["id"].rsplit("/", 1)[-1] response = fed_client.get(f"/users/alice/posts/{note_uuid}", headers={"Accept": "text/html"}) assert response.status_code == 302 - assert response.headers["Location"] == f"http://localhost:8080/post.html?id={note_uuid}" + assert response.headers["Location"] == f"http://localhost:8080/post.html?u=alice&id={note_uuid}" def test_nodeinfo(fed_client, sharing_user): diff --git a/tests/test_openapi.py b/tests/test_openapi.py index 25c11e6..a71b154 100644 --- a/tests/test_openapi.py +++ b/tests/test_openapi.py @@ -77,6 +77,7 @@ def test_ui_routes_declare_bearer_auth(fed_spec): ("/api/v1/auth/login", "post"), ("/api/v1/auth/register", "post"), ("/api/v1/federation/profiles/{username}", "get"), + ("/api/v1/federation/profiles/{username}/posts/{post_uuid}", "get"), } for path, operations in spec["paths"].items(): if not path.startswith("/api/v1/"): From de1519a06654e7b86d03e7b26af10154f8898ce3 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 16:31:16 +0100 Subject: [PATCH 42/56] Metrics, dashboard and alert for posts (phase 3, step 9) New counters: scrobbler_federation_posts_total{kind,visibility}, post_deletions_total{reason} (manual vs sharing_off), and milestone_checks_total / weekly_total{result}, each incremented at a single point (publish()/_delete(), and a thin public wrapper around each module's check_and_post()) rather than at every call site. Federation dashboard gains a "Posts" row: posts/min by kind and visibility, deletions/min by reason, and weekly/milestone checks by result - the same shape as the existing rows, so a stalled worker (all zero) looks the same as one with nothing to do (all "disabled"/"none"). New alert FederationWeeklySummariesMissing, on scrobbler_worker_tasks_total rather than the new weekly_total metric: weekly_total only increments once check_all() reaches a real sharing user, so on a quiet instance with nobody sharing yet it would sit at zero forever and false-alarm immediately. worker_tasks_total counts every periodic run regardless of whether there was anyone to check, matching the same pattern already used by ImportWorkerDown and FederationInboxBacklog. Verified deploy/prometheus/alerts.yml and prometheus.yml with promtool (via the prom/prometheus image, matching CI's validate-monitoring job). Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- deploy/grafana/dashboards/federation.json | 233 ++++++++++++++++++ deploy/prometheus/alerts.yml | 8 + src/scrobbler/federation/metrics.py | 20 ++ src/scrobbler/federation/publishing/base.py | 11 +- .../federation/publishing/milestones.py | 7 + src/scrobbler/federation/publishing/weekly.py | 7 + tests/test_federation_milestones.py | 6 +- tests/test_federation_publishing.py | 12 +- tests/test_federation_weekly.py | 4 +- 9 files changed, 300 insertions(+), 8 deletions(-) diff --git a/deploy/grafana/dashboards/federation.json b/deploy/grafana/dashboards/federation.json index 760cd9b..d7616af 100644 --- a/deploy/grafana/dashboards/federation.json +++ b/deploy/grafana/dashboards/federation.json @@ -956,6 +956,239 @@ "w": 12, "h": 8 } + }, + { + "type": "row", + "title": "Posts", + "id": 20, + "collapsed": false, + "gridPos": { + "x": 0, + "y": 50, + "w": 24, + "h": 1 + }, + "panels": [] + }, + { + "type": "timeseries", + "title": "Posts / min by kind and visibility", + "description": "Weekly summaries and milestones actually published.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (kind, visibility) (rate(scrobbler_federation_posts_total[$__rate_interval])) * 60", + "legendFormat": "{{kind}} {{visibility}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 21, + "gridPos": { + "x": 0, + "y": 51, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Post deletions / min by reason", + "description": "'manual' from the web UI, 'sharing_off' when a user turns sharing off.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (reason) (rate(scrobbler_federation_post_deletions_total[$__rate_interval])) * 60", + "legendFormat": "{{reason}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 22, + "gridPos": { + "x": 12, + "y": 51, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Weekly summary checks / min by result", + "description": "disabled, skipped_empty, already_posted or posted.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (result) (rate(scrobbler_federation_weekly_total[$__rate_interval])) * 60", + "legendFormat": "{{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 23, + "gridPos": { + "x": 0, + "y": 59, + "w": 12, + "h": 8 + } + }, + { + "type": "timeseries", + "title": "Milestone checks / min by result", + "description": "disabled, none or posted.", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (result) (rate(scrobbler_federation_milestone_checks_total[$__rate_interval])) * 60", + "legendFormat": "{{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 24, + "gridPos": { + "x": 12, + "y": 59, + "w": 12, + "h": 8 + } } ] } diff --git a/deploy/prometheus/alerts.yml b/deploy/prometheus/alerts.yml index 81f451d..1a14936 100644 --- a/deploy/prometheus/alerts.yml +++ b/deploy/prometheus/alerts.yml @@ -89,6 +89,14 @@ groups: summary: Received fediverse activities haven't been processed for 15 minutes description: The worker is probably stopped, or stuck on something. + - alert: FederationWeeklySummariesMissing + expr: sum(increase(scrobbler_worker_tasks_total{task="federation.weekly"}[30m])) == 0 + for: 5m + labels: {severity: warning} + annotations: + summary: The weekly summary check hasn't run in 30 minutes + description: federation.weekly runs every 15 minutes regardless of whether anyone is due a post; the worker is probably stopped or stuck. + - alert: FederationSignatureFailures expr: | sum(rate(scrobbler_federation_signatures_total{direction="in",result!="ok"}[15m])) diff --git a/src/scrobbler/federation/metrics.py b/src/scrobbler/federation/metrics.py index 1aeea3d..75016ec 100644 --- a/src/scrobbler/federation/metrics.py +++ b/src/scrobbler/federation/metrics.py @@ -51,3 +51,23 @@ followers = Gauge( ["state"], multiprocess_mode="max", ) +posts_total = Counter( + "scrobbler_federation_posts_total", + "Posts published: weekly summaries and milestones", + ["kind", "visibility"], +) +post_deletions_total = Counter( + "scrobbler_federation_post_deletions_total", + "Posts deleted, by reason", + ["reason"], +) +milestone_checks_total = Counter( + "scrobbler_federation_milestone_checks_total", + "Milestone checks, by result: disabled, none or posted", + ["result"], +) +weekly_total = Counter( + "scrobbler_federation_weekly_total", + "Weekly summary checks, by result: disabled, skipped_empty, already_posted or posted", + ["result"], +) diff --git a/src/scrobbler/federation/publishing/base.py b/src/scrobbler/federation/publishing/base.py index 6a6f47f..0e0c6a7 100644 --- a/src/scrobbler/federation/publishing/base.py +++ b/src/scrobbler/federation/publishing/base.py @@ -14,6 +14,7 @@ from sqlalchemy.exc import IntegrityError from scrobbler.extensions import db from scrobbler.federation import activities, followers, ids, sharing +from scrobbler.federation import metrics as fed_metrics from scrobbler.federation.models import FederationActivity, FederationPost from scrobbler.federation.protocol import addressing, vocab @@ -141,6 +142,7 @@ def publish( except IntegrityError: # posted with this key by a concurrent pass db.session.rollback() return None + fed_metrics.posts_total.labels(kind=kind, visibility=settings.visibility).inc() return post @@ -150,7 +152,7 @@ def delete_post(user_id: int, username: str, post: FederationPost) -> Federation None if it's already deleted.""" if post.deleted_at is not None: return None - return _delete(user_id, username, post) + return _delete(user_id, username, post, reason="manual") def delete_all_for(user_id: int, username: str) -> int: @@ -161,11 +163,13 @@ def delete_all_for(user_id: int, username: str) -> int: db.select(FederationPost).filter_by(user_id=user_id, deleted_at=None) ).all() for post in posts: - _delete(user_id, username, post) + _delete(user_id, username, post, reason="sharing_off") return len(posts) -def _delete(user_id: int, username: str, post: FederationPost) -> FederationActivity: +def _delete( + user_id: int, username: str, post: FederationPost, *, reason: str +) -> FederationActivity: # The post's own visibility at the time it was posted, not the user's current # setting: a Delete has to reach whoever could have seen the Create. note_id = post.activity.document["object"]["id"] @@ -179,4 +183,5 @@ def _delete(user_id: int, username: str, post: FederationPost) -> FederationActi if inboxes: activities.queue(activity, inboxes) post.deleted_at = _now() + fed_metrics.post_deletions_total.labels(reason=reason).inc() return activity diff --git a/src/scrobbler/federation/publishing/milestones.py b/src/scrobbler/federation/publishing/milestones.py index d21efb0..e28ae30 100644 --- a/src/scrobbler/federation/publishing/milestones.py +++ b/src/scrobbler/federation/publishing/milestones.py @@ -12,6 +12,7 @@ never gets a burst of "congratulations" for plays from years ago. import logging from scrobbler.extensions import db +from scrobbler.federation import metrics as fed_metrics from scrobbler.federation import publishing, sharing from scrobbler.federation.models import FederationMilestoneMark, FederationPendingCheck from scrobbler.federation.protocol import content @@ -132,6 +133,12 @@ def check_and_post(user_id: int) -> str: """For one user, post at most one milestone: the first of scrobble-count, top-10 entry, or artist-plays (in that priority) that has a new, unmarked threshold to report. Returns a result: disabled, none or posted.""" + result = _check_and_post(user_id) + fed_metrics.milestone_checks_total.labels(result=result).inc() + return result + + +def _check_and_post(user_id: int) -> str: settings = sharing.settings_for(user_id) if not (settings.enabled and settings.post_milestones): return "disabled" diff --git a/src/scrobbler/federation/publishing/weekly.py b/src/scrobbler/federation/publishing/weekly.py index 7f1e273..8ed2515 100644 --- a/src/scrobbler/federation/publishing/weekly.py +++ b/src/scrobbler/federation/publishing/weekly.py @@ -11,6 +11,7 @@ import logging from datetime import UTC, datetime from scrobbler.extensions import db +from scrobbler.federation import metrics as fed_metrics from scrobbler.federation import publishing, sharing from scrobbler.federation.models import FederationSettings from scrobbler.federation.protocol import content, schedule @@ -61,6 +62,12 @@ def build_content(count: int, top_artists: list, top_tracks: list) -> tuple[str, def check_and_post(settings: FederationSettings, now_utc: datetime) -> str: """For one user's settings, post their most recent eligible week if it's due and not already posted. Returns a result: disabled, already_posted, skipped_empty or posted.""" + result = _check_and_post(settings, now_utc) + fed_metrics.weekly_total.labels(result=result).inc() + return result + + +def _check_and_post(settings: FederationSettings, now_utc: datetime) -> str: if not settings.post_weekly_summary: return "disabled" user = accounts.get_user(settings.user_id) diff --git a/tests/test_federation_milestones.py b/tests/test_federation_milestones.py index 4387b2e..a33ad1c 100644 --- a/tests/test_federation_milestones.py +++ b/tests/test_federation_milestones.py @@ -52,15 +52,19 @@ def test_nothing_reached_posts_nothing(fed_ctx, user, sharing_settings): assert posts_for(user.id) == [] -def test_a_scrobble_count_threshold_is_posted(fed_ctx, user, sharing_settings, monkeypatch): +def test_a_scrobble_count_threshold_is_posted( + fed_ctx, user, sharing_settings, monkeypatch, metric_delta +): monkeypatch.setattr(milestones, "SCROBBLE_THRESHOLDS", [3]) played(user, "Radiohead", "Reckoner", n=3) + posted = metric_delta("scrobbler_federation_milestone_checks_total", result="posted") outcome = milestones.check_and_post(user.id) assert outcome == "posted" [post] = posts_for(user.id) assert post.key == "milestone:scrobbles:3" assert "3 plays scrobbled" in post.content_text assert marks_for(user.id) == {"scrobbles:3": True} + assert posted.delta == 1 def test_checking_twice_only_posts_once(fed_ctx, user, sharing_settings, monkeypatch): diff --git a/tests/test_federation_publishing.py b/tests/test_federation_publishing.py index e2a6351..cea45ac 100644 --- a/tests/test_federation_publishing.py +++ b/tests/test_federation_publishing.py @@ -32,12 +32,14 @@ def approved_follower(fed_client, remote, sharing_user, name): return account -def test_publish_creates_a_post_and_a_create_activity(fed_ctx, user): +def test_publish_creates_a_post_and_a_create_activity(fed_ctx, user, metric_delta): sharing.update(user.id, {"enabled": True}) + posted = metric_delta("scrobbler_federation_posts_total", kind="weekly", visibility="followers") post = publishing.publish( user.id, "alice", "weekly", "2026-W01", text="312 plays", html="

      312 plays

      " ) assert post is not None + assert posted.delta == 1 assert (post.kind, post.key, post.content_text) == ("weekly", "weekly:2026-W01", "312 plays") assert post.visibility == "followers" assert post.deleted_at is None @@ -138,12 +140,13 @@ def test_publish_with_no_followers_still_creates_the_post(fed_ctx, user): assert deliveries_for(post.activity_id) == [] -def test_delete_post_sends_delete_and_tombstones(fed_client, remote, sharing_user): +def test_delete_post_sends_delete_and_tombstones(fed_client, remote, sharing_user, metric_delta): bob = approved_follower(fed_client, remote, sharing_user, "bob") post = publishing.publish( sharing_user.id, "alice", "weekly", "2026-W01", text="x", html="

      x

      " ) note_id = db.session.get(FederationActivity, post.activity_id).document["object"]["id"] + deleted = metric_delta("scrobbler_federation_post_deletions_total", reason="manual") activity = publishing.delete_post(sharing_user.id, "alice", post) db.session.commit() @@ -152,6 +155,7 @@ def test_delete_post_sends_delete_and_tombstones(fed_client, remote, sharing_use assert activity.document["object"] == {"id": note_id, "type": "Tombstone"} assert db.session.get(FederationPost, post.id).deleted_at is not None assert [d.inbox for d in deliveries_for(activity.id)] == [bob.server.url("/inbox")] + assert deleted.delta == 1 def test_deleting_an_already_deleted_post_is_a_noop(fed_ctx, user): @@ -175,7 +179,7 @@ def test_delete_uses_the_posts_own_visibility_not_the_current_setting(fed_ctx, u assert activity.document["to"] == [PUBLIC] # still addressed as it was posted -def test_delete_all_for_deletes_every_live_post(fed_ctx, user): +def test_delete_all_for_deletes_every_live_post(fed_ctx, user, metric_delta): sharing.update(user.id, {"enabled": True}) a = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="a", html="a") b = publishing.publish(user.id, "alice", "milestone", "scrobbles:1000", text="b", html="b") @@ -183,10 +187,12 @@ def test_delete_all_for_deletes_every_live_post(fed_ctx, user): publishing.delete_post(user.id, "alice", already_deleted) db.session.commit() + sharing_off = metric_delta("scrobbler_federation_post_deletions_total", reason="sharing_off") count = publishing.delete_all_for(user.id, "alice") db.session.commit() assert count == 2 # not the one already deleted + assert sharing_off.delta == 2 assert db.session.get(FederationPost, a.id).deleted_at is not None assert db.session.get(FederationPost, b.id).deleted_at is not None # 3 Deletes total: one from the already_deleted post above, plus a and b just now diff --git a/tests/test_federation_weekly.py b/tests/test_federation_weekly.py index 4f1f7af..892da5e 100644 --- a/tests/test_federation_weekly.py +++ b/tests/test_federation_weekly.py @@ -42,9 +42,10 @@ def test_an_empty_week_is_not_posted(fed_ctx, user, sharing_settings): assert posts_for(user.id) == [] -def test_a_week_with_plays_is_posted(fed_ctx, user, sharing_settings): +def test_a_week_with_plays_is_posted(fed_ctx, user, sharing_settings, metric_delta): a_scrobble_in_the_target_week(user) a_scrobble_in_the_target_week(user, hour=13) + posted = metric_delta("scrobbler_federation_weekly_total", result="posted") outcome = weekly.check_and_post(sharing_settings, GATE) assert outcome == "posted" [post] = posts_for(user.id) @@ -52,6 +53,7 @@ def test_a_week_with_plays_is_posted(fed_ctx, user, sharing_settings): assert "2 plays" in post.content_text activity = db.session.get(FederationActivity, post.activity_id) assert activity.activity_type == "Create" + assert posted.delta == 1 def test_checking_twice_only_posts_once(fed_ctx, user, sharing_settings): From 860d4d0f93d311b5d8ec698d44e9fdcf9fda06ec Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 16:40:34 +0100 Subject: [PATCH 43/56] Admin post-weekly command and GoToSocial post interop checks (phase 3, step 10) `flask federation post-weekly --user --now` posts a user's summary for the week still in progress immediately, ignoring the Monday-09:00 gate - for operators, and so the interop test can produce a real post without waiting on calendar time. Backed by a new weekly.post_now(), sharing _post_for_window() with the normal check_and_post() path so both go through the same has_post/empty-week/ publish logic; only the window (this week so far, vs. the last gated one) differs. Extends the GoToSocial interop driver to a second phase: run.sh seeds one scrobble directly (the driver container has no way to sign a Last.fm-API request, and doesn't need one just to seed data), triggers the CLI command via `docker compose exec api`, then re-runs the driver with --check-posts to confirm the post reaches the already-following GoToSocial account's home timeline as `private` (followers-only, our default) with the expected content, deletes it via the existing DELETE /posts/{id} API, and confirms it disappears from GoToSocial's timeline too. The main flow now ends by re-following instead of the previous test's decline, so the post-check phase has a follower to check against. Verified end to end against a real GoToSocial 0.22.1 container locally before pushing (scripts/interop/run.sh), not just left to CI: private post: '

      My week in music: 1 play

      ...' All post interop checks passed Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- scripts/interop/gotosocial_interop.py | 60 +++++++++++++++++- scripts/interop/run.sh | 38 +++++++++-- src/scrobbler/federation/__init__.py | 2 + src/scrobbler/federation/cli.py | 38 +++++++++++ src/scrobbler/federation/protocol/schedule.py | 11 +++- src/scrobbler/federation/publishing/weekly.py | 26 ++++++++ tests/test_federation_schedule.py | 14 +++++ tests/test_federation_weekly.py | 63 +++++++++++++++++++ 8 files changed, 244 insertions(+), 8 deletions(-) create mode 100644 src/scrobbler/federation/cli.py diff --git a/scripts/interop/gotosocial_interop.py b/scripts/interop/gotosocial_interop.py index 2434d79..4c1a7be 100644 --- a/scripts/interop/gotosocial_interop.py +++ b/scripts/interop/gotosocial_interop.py @@ -210,6 +210,12 @@ class Scrobbler: if status not in (200, 204): fail(f"{action} follower: {status} {body}") + def posts(self): + status, body = api("GET", f"{SCROBBLER_API}/federation/posts", self.token) + if status != 200: + fail(f"listing posts: {status} {body}") + return body + class GoToSocial: def __init__(self, token): @@ -249,6 +255,12 @@ class GoToSocial: fail(f"relationship: {status} {body}") return body[0] + def home_timeline(self): + status, body = api("GET", f"{GTS}/api/v1/timelines/home", self.token) + if status != 200: + fail(f"home timeline: {status} {body}") + return body + def main(): step("Getting a GoToSocial access token") @@ -347,8 +359,54 @@ def main(): ), ) + step("Re-follow: left in place for the post check (run.sh's second driver pass)") + alice.settings(manually_approves_followers=False) + gts.follow(account_id) + wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"]) + step("All interop checks passed") +def check_posts(): + """Second phase, run by run.sh after it triggers `flask federation post-weekly + --now` directly in the api container (this container has no docker access to do that + itself). Checks the post reaches the already-following GoToSocial account's home + timeline as a private (followers-only) status with the expected text, then deletes + it and checks it disappears there too.""" + step("Getting a GoToSocial access token") + gts = GoToSocial(gotosocial_token()) + alice = Scrobbler() # register-or-login: the same account main() set up + account = gts.resolve("@alice@scrobble.test") + account_id = account["id"] + if not gts.relationship(account_id)["following"]: + fail("GoToSocial isn't following alice; run the main interop flow first") + + step("The weekly summary reaches GoToSocial's home timeline") + posted = wait_for( + "the weekly summary in GoToSocial's home timeline", + lambda: next( + (s for s in gts.home_timeline() if s["account"]["acct"] == "alice@scrobble.test"), + None, + ), + ) + if posted["visibility"] != "private": + fail(f"expected private (followers-only) visibility, got {posted['visibility']!r}") + if "My week in music" not in posted["content"]: + fail(f"unexpected content: {posted['content']!r}") + print(f" {posted['visibility']} post: {posted['content'][:80]!r}") + + step("Deleting the post removes it from GoToSocial too") + [post, *_] = alice.posts() + status, body = api("DELETE", f"{SCROBBLER_API}/federation/posts/{post['id']}", alice.token) + if status != 204: + fail(f"deleting the post: {status} {body}") + wait_for( + "the post to disappear from GoToSocial's home timeline", + lambda: not any(s["id"] == posted["id"] for s in gts.home_timeline()), + ) + + step("All post interop checks passed") + + if __name__ == "__main__": - main() + check_posts() if "--check-posts" in sys.argv[1:] else main() diff --git a/scripts/interop/run.sh b/scripts/interop/run.sh index 0600cbb..42e4f4a 100755 --- a/scripts/interop/run.sh +++ b/scripts/interop/run.sh @@ -24,10 +24,7 @@ echo "==> Creating the GoToSocial test user" --username gtsuser --email gtsuser@gts.test --password 'Interop-Test-Password-1' >/dev/null "$compose" exec -T gotosocial /gotosocial/gotosocial admin account confirm --username gtsuser >/dev/null -"$compose" build driver >/dev/null -"$compose" run --rm driver -status=$? -if [ $status -ne 0 ]; then +diagnose() { echo "==> Scrobbler federation state" "$compose" exec -T db psql -U scrobbler -d scrobbler -c \ "select activity_type, status, reason, attempts from federation_inbox order by id" -c \ @@ -35,5 +32,38 @@ if [ $status -ne 0 ]; then from federation_deliveries d join federation_activities a on a.id = d.activity_id order by d.id" echo "==> Recent logs" "$compose" logs --tail 200 worker gotosocial | grep -v "api/v1/accounts/relationships" | tail -40 +} + +"$compose" build driver >/dev/null +"$compose" run --rm driver +status=$? +if [ $status -ne 0 ]; then + diagnose + exit $status +fi + +echo "==> Alice scrobbles something, for the weekly summary to have content" +"$compose" exec -T api python3 -c " +from datetime import UTC, datetime +from scrobbler import create_app +from scrobbler.config import Config +from scrobbler.extensions import db +from scrobbler.models import Scrobble, User + +app = create_app(Config) +with app.app_context(): + user = db.session.scalar(db.select(User).filter_by(username='alice')) + db.session.add(Scrobble(user_id=user.id, artist='Interop Artist', track='Interop Track', played_at=datetime.now(UTC))) + db.session.commit() +" + +echo "==> Posting alice's weekly summary immediately" +"$compose" exec -T api flask --app scrobbler federation post-weekly --user alice --now + +echo "==> Checking the post reaches GoToSocial, then is removed there when deleted" +"$compose" run --rm driver python /interop/gotosocial_interop.py --check-posts +status=$? +if [ $status -ne 0 ]; then + diagnose fi exit $status diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py index 37602b9..5043468 100644 --- a/src/scrobbler/federation/__init__.py +++ b/src/scrobbler/federation/__init__.py @@ -30,11 +30,13 @@ def init_app(app: Flask) -> None: from scrobbler.api import get_api from scrobbler.federation import api, openapi, web + from scrobbler.federation.cli import federation_cli 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) + app.cli.add_command(federation_cli) from scrobbler import events, worker from scrobbler.federation import delivery, inbox diff --git a/src/scrobbler/federation/cli.py b/src/scrobbler/federation/cli.py new file mode 100644 index 0000000..3f68f33 --- /dev/null +++ b/src/scrobbler/federation/cli.py @@ -0,0 +1,38 @@ +"""Fediverse admin commands (`flask federation ...`).""" + +import click +from flask.cli import AppGroup, with_appcontext + +federation_cli = AppGroup("federation", help="Fediverse admin commands.") + + +@federation_cli.command("post-weekly") +@click.option("--user", "username", required=True, help="Username to post for.") +@click.option( + "--now", + "immediately", + is_flag=True, + required=True, + help="Post about the week still in progress right now, ignoring the Monday-09:00 " + "gate (the only mode this command supports, for operators and testing).", +) +@with_appcontext +def post_weekly(username: str, immediately: bool) -> None: + """Post one user's weekly summary immediately.""" + from scrobbler.extensions import db + from scrobbler.federation.publishing import weekly + from scrobbler.services import accounts + + user = accounts.find_user(username) + if user is None: + raise click.ClickException(f"No such user: {username}") + result = weekly.post_now(user.id) + db.session.commit() + if result == "posted": + click.echo(f"Posted a weekly summary for {username}.") + elif result == "already_posted": + click.echo(f"{username} already has a post for this week.") + elif result == "skipped_empty": + click.echo(f"{username} hasn't scrobbled anything this week.") + else: + raise click.ClickException(f"{username} isn't sharing weekly summaries.") diff --git a/src/scrobbler/federation/protocol/schedule.py b/src/scrobbler/federation/protocol/schedule.py index 1a5f4fc..0deb6b4 100644 --- a/src/scrobbler/federation/protocol/schedule.py +++ b/src/scrobbler/federation/protocol/schedule.py @@ -4,12 +4,18 @@ Weeks run Monday 00:00 to Sunday 24:00 *local time*, computed in the zone itself a fixed UTC offset), so the window is correct across a daylight-saving change. """ -from datetime import UTC, datetime, timedelta +from datetime import UTC, date, datetime, timedelta from zoneinfo import ZoneInfo, ZoneInfoNotFoundError POST_HOUR = 9 # local time a week's summary becomes postable, on the following Monday +def week_key(day: date) -> str: + """The ISO year-week key (e.g. "2026-W02") for the week a date falls in.""" + year, week, _ = day.isocalendar() + return f"{year}-W{week:02d}" + + def target_week(now_utc: datetime, tz: ZoneInfo) -> tuple[datetime, datetime, str]: """The [start, end) UTC window, and ISO year-week key (e.g. "2026-W02"), of the most recent Monday-Sunday week whose Monday-POST_HOUR-local posting gate has passed. @@ -26,8 +32,7 @@ def target_week(now_utc: datetime, tz: ZoneInfo) -> tuple[datetime, datetime, st start_local = datetime(week_start.year, week_start.month, week_start.day, tzinfo=tz) end_local = start_local + timedelta(days=7) # wall-clock +7 days: DST-correct on conversion - year, week, _ = week_start.isocalendar() - return start_local.astimezone(UTC), end_local.astimezone(UTC), f"{year}-W{week:02d}" + return start_local.astimezone(UTC), end_local.astimezone(UTC), week_key(week_start) def current_week_start(now_utc: datetime, tz: ZoneInfo) -> datetime: diff --git a/src/scrobbler/federation/publishing/weekly.py b/src/scrobbler/federation/publishing/weekly.py index 8ed2515..8873c1f 100644 --- a/src/scrobbler/federation/publishing/weekly.py +++ b/src/scrobbler/federation/publishing/weekly.py @@ -76,6 +76,10 @@ def _check_and_post(settings: FederationSettings, now_utc: datetime) -> str: tz = schedule.resolve_timezone(settings.timezone) start, end, key = schedule.target_week(now_utc, tz) + return _post_for_window(user, key, start, end) + + +def _post_for_window(user, key: str, start: datetime, end: datetime) -> str: if publishing.has_post(user.id, KIND, key): return "already_posted" # the common case: checked before, nothing new to do @@ -90,6 +94,28 @@ def _check_and_post(settings: FederationSettings, now_utc: datetime) -> str: return "posted" if post is not None else "already_posted" # lost a race with another pass +def post_now(user_id: int, now_utc: datetime | None = None) -> str: + """Post this user's summary immediately, for the week still in progress, ignoring + the Monday-09:00 gate. For operators (`flask federation post-weekly --now`) and the + interop test - not part of the automated pipeline (check_and_post/check_all), so it + isn't itself gated on post_weekly_summary being checked by a worker pass.""" + settings = sharing.settings_for(user_id) + if not (settings.enabled and settings.post_weekly_summary): + result = "disabled" + else: + user = accounts.get_user(user_id) + if user is None: + result = "disabled" + else: + now_utc = now_utc or datetime.now(UTC) + tz = schedule.resolve_timezone(settings.timezone) + start = schedule.current_week_start(now_utc, tz) + key = schedule.week_key(start.astimezone(tz).date()) + result = _post_for_window(user, key, start, now_utc) + fed_metrics.weekly_total.labels(result=result).inc() + return result + + def preview(user_id: int, now_utc: datetime | None = None) -> tuple[str, str] | None: """What a weekly summary would say right now, for the week still in progress. Never stored or posted: for the Sharing page's live preview. None if the account is gone.""" diff --git a/tests/test_federation_schedule.py b/tests/test_federation_schedule.py index d3c286c..3d8f936 100644 --- a/tests/test_federation_schedule.py +++ b/tests/test_federation_schedule.py @@ -82,3 +82,17 @@ def test_resolve_timezone_falls_back_to_utc_for_bad_names(name): def test_resolve_timezone_passes_through_valid_names(): assert schedule.resolve_timezone("Europe/London") == ZoneInfo("Europe/London") assert schedule.resolve_timezone("UTC") == ZoneInfo("UTC") + + +def test_week_key(): + assert schedule.week_key(datetime(2025, 12, 29).date()) == "2026-W01" + assert schedule.week_key(datetime(2026, 1, 5).date()) == "2026-W02" + assert schedule.week_key(datetime(2026, 1, 12).date()) == "2026-W03" + + +def test_current_week_start_is_this_weeks_monday_local(): + tz = ZoneInfo("Europe/London") + # A Wednesday, mid-morning UTC + now = local("UTC", 2026, 1, 7, 10) + start = schedule.current_week_start(now, tz) + assert start.astimezone(tz) == local("Europe/London", 2026, 1, 5) diff --git a/tests/test_federation_weekly.py b/tests/test_federation_weekly.py index 892da5e..4dda2ba 100644 --- a/tests/test_federation_weekly.py +++ b/tests/test_federation_weekly.py @@ -165,3 +165,66 @@ def test_deleting_a_weekly_post_works_like_any_other_post(fed_ctx, user, sharing db.session.commit() assert activity.activity_type == "Delete" assert db.session.get(FederationPost, post.id).deleted_at is not None + + +# --- post_now: for operators (flask federation post-weekly --now) and the interop test --- + +# Wednesday of the same week a_scrobble_in_the_target_week plays into (2026-01-06 is the +# Tuesday of ISO week 2026-W02, Jan 5-11), well before that week's own posting gate. +MID_WEEK = datetime(2026, 1, 7, 15, tzinfo=UTC) + + +def test_post_now_posts_the_week_in_progress(fed_ctx, user, sharing_settings): + a_scrobble_in_the_target_week(user) + outcome = weekly.post_now(user.id, MID_WEEK) + assert outcome == "posted" + [post] = posts_for(user.id) + assert post.key == "weekly:2026-W02" + assert "1 play" in post.content_text + + +def test_post_now_is_idempotent(fed_ctx, user, sharing_settings): + a_scrobble_in_the_target_week(user) + first = weekly.post_now(user.id, MID_WEEK) + second = weekly.post_now(user.id, MID_WEEK) + assert (first, second) == ("posted", "already_posted") + assert len(posts_for(user.id)) == 1 + + +def test_post_now_skips_an_empty_week(fed_ctx, user, sharing_settings): + assert weekly.post_now(user.id, MID_WEEK) == "skipped_empty" + assert posts_for(user.id) == [] + + +def test_post_now_requires_sharing(fed_ctx, user): + a_scrobble_in_the_target_week(user) + assert weekly.post_now(user.id, MID_WEEK) == "disabled" + + +def test_post_now_requires_weekly_summaries_on(fed_ctx, user, sharing_settings): + sharing.update(user.id, {"post_weekly_summary": False}) + a_scrobble_in_the_target_week(user) + assert weekly.post_now(user.id, MID_WEEK) == "disabled" + + +def test_post_weekly_cli_command(fed_app, fed_ctx, user, sharing_settings): + played(user, "Radiohead", "Reckoner", datetime.now(UTC)) + result = fed_app.test_cli_runner().invoke( + args=["federation", "post-weekly", "--user", "alice", "--now"] + ) + assert result.exit_code == 0, result.output + assert "Posted" in result.output + assert len(posts_for(user.id)) == 1 + + +def test_post_weekly_cli_command_requires_the_now_flag(fed_app): + result = fed_app.test_cli_runner().invoke(args=["federation", "post-weekly", "--user", "alice"]) + assert result.exit_code != 0 + + +def test_post_weekly_cli_command_rejects_an_unknown_user(fed_app, fed_ctx): + result = fed_app.test_cli_runner().invoke( + args=["federation", "post-weekly", "--user", "nobody", "--now"] + ) + assert result.exit_code != 0 + assert "No such user" in result.output From e0423d04bca05de7b707f3520eeda910ee873342 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 16:44:32 +0100 Subject: [PATCH 44/56] Docs for phase 3: what gets posted, the publishing plug-ins (step 11) README: the fediverse section now describes what's actually posted (weekly summaries, milestones) and their settings, instead of pointing at "still being built"; notes now playing is the one piece left. federation/README.md: a new Publishing section explains the plug-in shape (base.py owns idempotent publish/delete/fan-out; each kind - weekly.py, milestones.py - only decides when to post and what to say), so adding a third kind later means adding a module, not touching base.py. Worker tasks and layout tables updated for federation.weekly, federation.milestones and cli.py. Interop section covers the new post check. docs/design/activitypub-phase3.md marked done, following the precedent from phases 1-2's own docs, with the three points where implementation diverged from the written plan (the top-10-needs-a-real-top-10 fix, post_now() as a separate window computation, and post_page_url() needing the username). docs/openapi.json unchanged - still current from step 8. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- README.md | 11 +++++-- docs/design/activitypub-phase3.md | 8 ++++++ src/scrobbler/federation/README.md | 46 ++++++++++++++++++++++++++++-- 3 files changed, 60 insertions(+), 5 deletions(-) diff --git a/README.md b/README.md index 0421f6a..1faecda 100644 --- a/README.md +++ b/README.md @@ -92,14 +92,21 @@ Imports run in the background in the `worker` service. The page shows progress, Unlike live scrobbles, imports keep plays of any age. They still skip rows with no artist or track, and plays dated in the future. Plays already in your history are skipped, so importing again is safe. -## Sharing on the fediverse (in development) +## Sharing on the fediverse Users can make their profile findable from Mastodon and other fediverse apps as `@name@`, and be followed: - Follows are accepted automatically, or wait for approval if the user turns that on. - The **Followers** page lists requests, followers and blocked accounts, with approve, decline, remove, block and unblock. -Posts (weekly summaries, milestones, now playing) are still being built; see `docs/design/activitypub.md`. Federation is tested in CI against a real GoToSocial server (`scripts/interop/run.sh`). +Once someone follows, the **Sharing** page's **What to post** section controls what they see: + +- **Weekly summary**: play count and top artist(s), posted once a week (Monday 09:00 in the user's own time zone, for the Monday–Sunday week that just ended). A live preview on the same page shows what it would say so far. +- **Milestones**: total scrobbles, an artist's plays, and a new entry into the all-time top 10 — each posted once, the first time it's reached. History already on file when sharing is turned on, or added by an import, is never posted about retroactively. + +Both are on by default and can be switched off independently. Posts use the same visibility as the profile (followers only by default, or unlisted/public); the **Posts** page lists a user's own posts with delete (sends a `Delete` to whoever received it). "Now playing" isn't posted yet; see `docs/design/activitypub.md`. + +Federation is tested in CI against a real GoToSocial server (`scripts/interop/run.sh`), including that a posted weekly summary reaches a follower's timeline with the right content and visibility, and disappears from it when deleted. It's **off unless the server enables it**, and then **off for each user** until they switch it on under **Sharing**. To enable it: diff --git a/docs/design/activitypub-phase3.md b/docs/design/activitypub-phase3.md index 245ad30..cfe57e3 100644 --- a/docs/design/activitypub-phase3.md +++ b/docs/design/activitypub-phase3.md @@ -1,5 +1,13 @@ # ActivityPub phase 3: posts +**Status: done** on `feature/activitypub` (`bc717c2` … `860d4d0`). The GoToSocial interop test now covers posts too: a weekly summary reaches a follower's home timeline as `private` with the expected content, and disappears from it when deleted. As with phases 1-2, a manual pass with a real Mastodon account through a tunnel is still to do before merging. + +Where this differed from the plan: + +- **A top-10 entry needs a real top 10 first.** With fewer than `TOP_N` distinct artists, every first play of a new artist would trivially "enter the top 10" — caught by a test that used the real (unpatched) thresholds instead of always overriding them down for speed. Nothing is posted until a user actually has that many distinct artists. +- **`post_now()` is a separate path from the normal check.** `flask federation post-weekly --now` and the Sharing page's preview both need the week still *in progress*, not the last one whose Monday-09:00 gate has passed; they share the posting logic (`_post_for_window`) with the normal `check_and_post`, but compute a different window. +- **The Note's `url` needed the username, not just the post's id.** `post.html` (the UI page a browser lands on) has no other way to know whose post to look up; caught while wiring up the UI, not by a test written against the plan. + This implements phase 3 of [activitypub.md](activitypub.md): **weekly summaries** and **milestones**. Now playing is phase 4. It builds on [phase 2](activitypub-phase2.md): followers, signed delivery and retries. **Outcome:** diff --git a/src/scrobbler/federation/README.md b/src/scrobbler/federation/README.md index 98925e5..cfd8b90 100644 --- a/src/scrobbler/federation/README.md +++ b/src/scrobbler/federation/README.md @@ -60,18 +60,58 @@ Every ActivityPub ID is built from `FEDERATION_BASE_URL`, never from the incomin | `keys.py` | Key pairs, created once and encrypted at rest | | `sharing.py` | Per-user settings, and who is sharing | | `ids.py` | Our ActivityPub ids, all from `FEDERATION_BASE_URL` | -| `web.py` | The endpoints other servers call | +| `web.py` | The endpoints other servers call, including a paged outbox and individual posts | | `api.py` and `schemas.py` | `/api/v1/federation/*` for the web UI | | `openapi.py` | OpenAPI descriptions of `web.py`'s endpoints | | `metrics.py` | Federation's own Prometheus metrics | +| `cli.py` | `flask federation ...` admin commands | +| `publishing/` | Posts: shared publish/delete machinery, and one module per kind (see below) | + +## Publishing + +`publishing/base.py` is the only place that knows how to actually post: build the +`Note`/`Create`, store it, address it from the user's current visibility, and fan it out +to accepted followers' inboxes. It's idempotent (one row per `(user, kind:key)`, via +`federation_posts`' unique constraint) and used for both publishing and deleting. + +Each *kind* of post is its own small module that only decides **when** to post and what +the text says, then calls into `base.py`: + +- `publishing/weekly.py`: once a week (`check_and_post`/`check_all`, the + `federation.weekly` worker task), for the Monday–Sunday week whose posting gate has + passed. `post_now()` instead posts the week still in progress immediately, ignoring the + gate — used by `flask federation post-weekly --user --now` and `preview()` (a + read-only variant for the Sharing page's live preview, never stored). +- `publishing/milestones.py`: scrobble-count, artist-plays and top-10-entry thresholds, + each posted once. A live scrobble queues a `FederationPendingCheck` row (collapsing + repeats), drained by the `federation.milestones` worker task. `set_baseline()` marks + every threshold already passed without posting, called when a user turns sharing on + and after an import finishes, so old history never produces a burst of "milestone" + posts. + +Adding a third kind (e.g. now playing) means adding another module here with the same +shape — decide when, build the text, call `publishing.publish()` — not touching +`base.py`. ## Worker tasks -`federation.inbox` (process received activities), `federation.deliver` (send queued ones), `federation.inbox.maintenance` (re-queue stalled, prune after 30 days) and `federation.gauges` (queue and follower gauges). All are registered only when federation is on. +`federation.inbox` (process received activities), `federation.deliver` (send queued +ones), `federation.inbox.maintenance` (re-queue stalled, prune after 30 days), +`federation.gauges` (queue and follower gauges), `federation.milestones` (drain pending +milestone checks) and `federation.weekly` (check every sharing user for a due weekly +summary, every 15 minutes). All are registered only when federation is on. ## Interop -`scripts/interop/run.sh` runs Scrobbler against a real GoToSocial server on a private `.test` network and checks the whole follow life cycle. CI runs it on every push. GoToSocial 0.22.1 ignores a Reject of an already-accepted follow (a TODO in its code, fixed on its main branch), so that one check on its side is skipped until a release includes the fix. +`scripts/interop/run.sh` runs Scrobbler against a real GoToSocial server on a private +`.test` network. `scripts/interop/gotosocial_interop.py` checks the whole follow life +cycle, then `run.sh` seeds a scrobble, runs `flask federation post-weekly --now` directly +in the `api` container, and runs the driver a second time (`--check-posts`) to confirm +the post reaches GoToSocial's home timeline with the right content and `private` +(followers-only) visibility, and disappears from it once deleted. CI runs the whole +thing on every push. GoToSocial 0.22.1 ignores a Reject of an already-accepted follow (a +TODO in its code, fixed on its main branch), so that one check on its side is skipped +until a release includes the fix. ## Migrations From 7d86bad9295d9c14cc9d690c8f0812c6759bf4d3 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 16:54:00 +0100 Subject: [PATCH 45/56] Plan for ActivityPub phase 4 (now playing) Resolves the overview doc's last open decision: now playing builds both options it described, not one or the other - the profile field (recommended default, live on every GET, throttled Update(Person) push every 5 minutes) plus a separate opt-in for actual posts (min 30s played, throttled to one every 30 minutes, previous post deleted when the next goes out). No event receiver or pending-checks queue like milestones needed: a plain periodic scan (federation.now_playing, every 30s) is simplest here, since the throttle windows are minutes-long and there's no history to react to retroactively - unlike milestones, now playing only ever reflects what's playing right now. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/design/activitypub-phase4.md | 106 ++++++++++++++++++++++++++++++ docs/design/activitypub.md | 8 +-- 2 files changed, 110 insertions(+), 4 deletions(-) create mode 100644 docs/design/activitypub-phase4.md diff --git a/docs/design/activitypub-phase4.md b/docs/design/activitypub-phase4.md new file mode 100644 index 0000000..fa27ccb --- /dev/null +++ b/docs/design/activitypub-phase4.md @@ -0,0 +1,106 @@ +# ActivityPub phase 4: now playing + +This implements phase 4 of [activitypub.md](activitypub.md): **now playing**, the last of the "still open" decisions there. It builds on [phase 3](activitypub-phase3.md): publishing, delivery and the web UI for posts. + +Chosen (of the doc's three options): **profile field, plus opt-in posts** — the profile field is what a user gets as soon as they turn now playing on at all; posts are a further, separate opt-in on top of that, matching the doc's own "profile field mode, then optional posts" framing. + +**Outcome:** + +- A sharing user can turn now playing on. While something is genuinely playing, their fediverse profile shows a "Now playing: *Track* by Artist" field, refreshed automatically and cleared a few minutes after playback stops. +- If they also opt into posts, each track they play for at least 30 seconds gets a post to their followers (at most one every 30 minutes), with the previous now-playing post deleted when a new one goes out — so at most one exists at a time. +- Nothing here is retroactive or history-based: it only ever reflects what's playing *right now*, so there's no baseline/import concern like milestones has. + +Everything is in `scrobbler.federation`, using the core's existing `services.scrobbles.get_now_playing()` (no core changes needed this time), and the boundary tests keep holding. + +## 1. Settings and data (migration on the `federation` branch) + +- **`federation_settings` gains `now_playing_mode`**: `off` (default), `profile`, or `posts`. Validated the same way `visibility` is. +- **`federation_now_playing`**, one row per user, the state of what Scrobbler has last told the fediverse (as opposed to `now_playing` in core, which is what's actually playing): + - `profile_key` (nullable) and `profile_updated_at` (nullable): what the last `Update(Person)` said, and when it was sent + - `post_key` (nullable) and `post_posted_at` (nullable): the key of the last now-playing post, and when + + A "key" is `artist\x1ftrack\x1fstarted_at` — including `started_at` means playing the same track again later is a genuinely new now-playing moment, not a stale repeat, and it's what `federation_posts.key` uses too (so posting is idempotent through the same unique-constraint mechanism phase 3 already has, no new machinery needed). + +## 2. Vocabulary (pure: `protocol/vocab.py`) + +- **`update(activity_id, actor_id, actor_object)`**: wraps a document as an `Update`, addressed the same way `undo()` already does (mirrors its shape). +- **`person(...)` already takes `fields`** (phase 1): a "Now playing" field is just one more `(name, value)` pair, `"Track by Artist"`. +- Now-playing posts reuse the existing `note()`/`create()` builders from phase 3, tagged `#NowPlaying` in addition to `#Scrobbler` (already anticipated in the phase 3 plan's vocabulary notes). + +## 3. Live actor vs. pushed updates + +Two different questions, answered two different ways: + +- **`GET /users/` (a pull)** always reflects the truth *right now*: it reads `get_now_playing()` directly and adds the field only while something unexpired is playing. No throttling — a fresh fetch should never lie. +- **`Update(Person)` (a push)**, telling already-following servers proactively so they don't have to poll, is throttled to **once every 5 minutes** (`federation_now_playing.profile_updated_at`). A server that fetches in between sees the live truth anyway via the pull path above; the push is purely so it doesn't have to. + +This split means a fast-changing "now playing" never spams followers' inboxes, while the profile itself is never stale to a server that asks. + +## 4. `publishing/now_playing.py` + +A periodic worker task (`federation.now_playing`, every 30 seconds — well under both throttle windows, so they stay the binding constraint) checks every sharing user with `now_playing_mode != "off"`: + +1. Read `get_now_playing(user)` (core service; federation reaches it through `scrobbler.services.scrobbles`, already inside the public surface) and compute `current_key` (`None` if nothing's playing or it's expired). +2. **Profile** (mode `profile` or `posts`): if `current_key != federation_now_playing.profile_key` and at least 5 minutes have passed since `profile_updated_at` (or it's never been sent), build the actor document with (or without) the now-playing field and send `Update(Person)` to accepted followers' inboxes. Update the stored key and timestamp either way the check runs, so a change that arrives mid-throttle isn't retried every 30 seconds — only reconsidered once the throttle clears. +3. **Posts** (mode `posts` only): if `current_key` is set, has been playing for **at least 30 seconds**, differs from `federation_now_playing.post_key`, and at least 30 minutes have passed since `post_posted_at` (or never posted): publish a `now_playing` post (through the same `publishing.publish()` as weekly/milestones — idempotent on `now_playing:`), then delete the previous now-playing post if one exists, and update the stored key and timestamp. + +No event receiver, no pending-checks queue: unlike milestones, now playing doesn't need to react within a scrobble request, and the throttle windows (5 and 30 minutes) are so much longer than a 30-second poll that a periodic scan (the same shape as `weekly.check_all`) is simplest and cheapest. + +## 5. Endpoints + +- **`GET /users/`**: gains the live now-playing field (§3). No new endpoint. +- **`GET /users//outbox`, `GET /users//posts/`, `/api/v1/federation/posts`, `DELETE /posts/{id}`**: unchanged — `now_playing` posts are just another `kind` in `federation_posts`, so they already show up everywhere phase 3's post endpoints look. +- **`/api/v1/federation/settings`**: gains `now_playing_mode`. + +## 6. Web UI + +- **Sharing page**, a new **Now playing** section: off / profile field / profile field + posts, as a single choice (matching the settings column), with a one-line explanation of the 5-minute and 30-minute throttles. +- **Posts page**: `now_playing` posts show there like any other kind (already handled generically). +- **Profile page**: shows the "Now playing" field when the profile response includes it (the public profile API already returns arbitrary settings-derived fields; this adds one, read from the same live path as the actor document). + +## 7. Metrics, dashboard + +- `scrobbler_federation_profile_updates_total{result}`: `sent` or `throttled`. (Posts already get `scrobbler_federation_posts_total{kind="now_playing",visibility}` for free, phase 3's existing metric.) +- Federation dashboard: a panel on the existing "Posts" row for profile updates/min, and the `kind="now_playing"` series already shows up in the existing posts-by-kind panel without changes. + +## 8. Tests + +- **Vocabulary**: `update()` shape. +- **Actor document**: the live now-playing field appears while playing, is absent once expired, absent when off. +- **`now_playing.py`**: + - profile update sent on a genuine change, throttled within 5 minutes, cleared when playback stops + - post sent only after 30 seconds played, throttled within 30 minutes, previous post deleted when a new one goes out + - `profile` mode never posts; `off` mode does nothing at all + - idempotence (the same key never posted twice, matching phase 3's pattern) +- **Settings API**: `now_playing_mode` validation and round-trip. +- **Interop (GoToSocial)**: extends the existing driver — now playing is turned on, a track is set as playing, and the test confirms GoToSocial's resolved account shows the "Now playing" field after the next `Update(Person)`; posts aren't re-tested here since they go through the same publish/delivery path phase 3 already covers end to end. + +## 9. Docs + +- README: the now-playing section, its modes and throttles. +- Federation README: `now_playing.py` added to the publishing plug-ins list. +- Regenerate the OpenAPI export. +- Mark this plan done. + +## Order of work (a commit per step once its tests pass) + +1. Settings column and `federation_now_playing` table +2. Vocabulary (`update()`) and the live actor now-playing field +3. `publishing/now_playing.py` and its worker task +4. Settings API and schema +5. Web UI (Sharing page section, profile page field) +6. Metrics and dashboard +7. Interop check +8. Docs + +## Defaults I've chosen (easy to change) + +| Choice | Default | +|---|---| +| Now playing | Off by default, per user | +| Profile push throttle | 5 minutes | +| Post throttle | 30 minutes | +| Minimum played before a post | 30 seconds | +| Deleting the previous now-playing post | Always, when a new one goes out | +| Worker poll interval | 30 seconds | +| Hashtags | `#Scrobbler` and `#NowPlaying` | diff --git a/docs/design/activitypub.md b/docs/design/activitypub.md index 8f98371..9a83579 100644 --- a/docs/design/activitypub.md +++ b/docs/design/activitypub.md @@ -357,7 +357,7 @@ Each phase can be released on its own, with its migration, docs, OpenAPI updates 1. **Discoverable profile.** Settings, keys, WebFinger, the actor, NodeInfo and the Sharing page. A user can turn sharing on and be found from Mastodon, but can't be followed yet. 2. **Followers.** Inbox, signature verification (both schemes), the delivery queue with retries and signing, `Accept`, removing and blocking followers, the Followers page, and the GoToSocial CI test. 3. **Posts.** The outbox, weekly summaries, milestones, and deleting posts when sharing is turned off. Adds the Federation dashboard and alerts. -4. **Now playing.** The profile-field mode, then optional posts. +4. **Now playing.** The profile-field mode, then optional posts. See [phase 4](activitypub-phase4.md). ## Later: following and `Listen` activities @@ -376,11 +376,11 @@ Also settled: - **Domain: the UI's.** Handles and actor URLs are both on the UI host, and the UI's nginx forwards the ActivityPub paths to the API. - **Visibility: followers only by default**, and each user can change it on their Sharing settings. +- **Now playing: the profile field, plus opt-in posts** (phase 4) — not just the recommended default, both. -Still open (neither is needed before phase 3): +Still open: -1. **Now-playing default** once a user turns it on: the profile field (recommended), or posts? -2. **Does it need an admin?** Phase 2 assumes domain blocks set in configuration. A real moderation UI (reports, per-domain policies) would be a separate piece of work. +1. **Does it need an admin?** Phase 2 assumes domain blocks set in configuration. A real moderation UI (reports, per-domain policies) would be a separate piece of work. ## Sources From cb8f9c997e00fbd1927a4fe914fe2f7c5e7a7186 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 16:57:34 +0100 Subject: [PATCH 46/56] Settings column and now-playing state table (phase 4, step 1) federation_settings gains now_playing_mode (off/profile/posts, default off), validated in sharing.update() the same way visibility is. New federation_now_playing table: one row per user, tracking what we've last told the fediverse (profile_key/profile_updated_at, post_key/post_posted_at) - separate from core's now_playing table, which is what's actually playing right now. Verified the migration both ways against the local dev database: full downgrade to base and back up to heads on both branches, not just a single-step round trip. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/federation/models.py | 20 +++++++++ src/scrobbler/federation/sharing.py | 6 ++- .../versions/2533b727da79_now_playing.py | 42 +++++++++++++++++++ tests/test_federation_keys_sharing.py | 18 +++++--- 4 files changed, 80 insertions(+), 6 deletions(-) create mode 100644 src/scrobbler/migrations/versions/2533b727da79_now_playing.py diff --git a/src/scrobbler/federation/models.py b/src/scrobbler/federation/models.py index f3690d8..031b295 100644 --- a/src/scrobbler/federation/models.py +++ b/src/scrobbler/federation/models.py @@ -21,6 +21,7 @@ from sqlalchemy.orm import Mapped, mapped_column, relationship from scrobbler.extensions import db VISIBILITIES = ("followers", "unlisted", "public") +NOW_PLAYING_MODES = ("off", "profile", "posts") def utcnow() -> datetime: @@ -44,6 +45,8 @@ class FederationSettings(db.Model): timezone: Mapped[str] = mapped_column(String(64), default="UTC") post_weekly_summary: Mapped[bool] = mapped_column(Boolean, default=True) post_milestones: Mapped[bool] = mapped_column(Boolean, default=True) + # off, profile or posts (posts implies profile too) + now_playing_mode: Mapped[str] = mapped_column(String(16), default="off") created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) updated_at: Mapped[datetime] = mapped_column( DateTime(timezone=True), default=utcnow, onupdate=utcnow @@ -247,3 +250,20 @@ class FederationPendingCheck(db.Model): ) since: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) reason: Mapped[str] = mapped_column(String(32), default="scrobble") + + +class FederationNowPlaying(db.Model): + """What we've last told the fediverse is playing, as opposed to `now_playing` in the + core schema, which is what's actually playing. A "key" is `artist\\x1ftrack\\x1f + started_at`: playing the same track again later is a new now-playing moment, not a + stale repeat, and it doubles as federation_posts.key for the posts side.""" + + __tablename__ = "federation_now_playing" + + user_id: Mapped[int] = mapped_column( + ForeignKey("users.id", ondelete="CASCADE"), primary_key=True + ) + profile_key: Mapped[str | None] = mapped_column(String(512)) + profile_updated_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + post_key: Mapped[str | None] = mapped_column(String(512)) + post_posted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) diff --git a/src/scrobbler/federation/sharing.py b/src/scrobbler/federation/sharing.py index 1f76d9a..fe811c7 100644 --- a/src/scrobbler/federation/sharing.py +++ b/src/scrobbler/federation/sharing.py @@ -2,7 +2,7 @@ from scrobbler.extensions import db from scrobbler.federation import keys -from scrobbler.federation.models import VISIBILITIES, FederationSettings +from scrobbler.federation.models import NOW_PLAYING_MODES, VISIBILITIES, FederationSettings from scrobbler.federation.protocol.schedule import is_valid_timezone from scrobbler.services import accounts @@ -17,6 +17,7 @@ EDITABLE = ( "timezone", "post_weekly_summary", "post_milestones", + "now_playing_mode", ) @@ -36,6 +37,7 @@ def settings_for(user_id: int) -> FederationSettings: timezone="UTC", post_weekly_summary=True, post_milestones=True, + now_playing_mode="off", ) return settings @@ -48,6 +50,8 @@ def update(user_id: int, changes: dict) -> tuple[FederationSettings, bool | None raise ValueError(f"not editable: {sorted(unknown)}") if changes.get("visibility", "followers") not in VISIBILITIES: raise ValueError("visibility must be one of " + ", ".join(VISIBILITIES)) + if changes.get("now_playing_mode", "off") not in NOW_PLAYING_MODES: + raise ValueError("now_playing_mode must be one of " + ", ".join(NOW_PLAYING_MODES)) if "timezone" in changes and not is_valid_timezone(changes["timezone"]): raise ValueError(f"not a known time zone: {changes['timezone']!r}") settings = settings_for(user_id) diff --git a/src/scrobbler/migrations/versions/2533b727da79_now_playing.py b/src/scrobbler/migrations/versions/2533b727da79_now_playing.py new file mode 100644 index 0000000..ef1f370 --- /dev/null +++ b/src/scrobbler/migrations/versions/2533b727da79_now_playing.py @@ -0,0 +1,42 @@ +"""now playing + +Revision ID: 2533b727da79 +Revises: 0b81b61c932a +Create Date: 2026-09-26 16:54:40.320486 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = '2533b727da79' +down_revision = '0b81b61c932a' +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table('federation_now_playing', + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('profile_key', sa.String(length=512), nullable=True), + sa.Column('profile_updated_at', sa.DateTime(timezone=True), nullable=True), + sa.Column('post_key', sa.String(length=512), nullable=True), + sa.Column('post_posted_at', sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'), + sa.PrimaryKeyConstraint('user_id') + ) + with op.batch_alter_table('federation_settings', schema=None) as batch_op: + batch_op.add_column(sa.Column('now_playing_mode', sa.String(length=16), nullable=False, server_default='off')) + + # ### end Alembic commands ### + + +def downgrade(): + # ### commands auto generated by Alembic - please adjust! ### + with op.batch_alter_table('federation_settings', schema=None) as batch_op: + batch_op.drop_column('now_playing_mode') + + op.drop_table('federation_now_playing') + # ### end Alembic commands ### diff --git a/tests/test_federation_keys_sharing.py b/tests/test_federation_keys_sharing.py index eb23128..b9bab40 100644 --- a/tests/test_federation_keys_sharing.py +++ b/tests/test_federation_keys_sharing.py @@ -19,11 +19,12 @@ def test_unsaved_defaults_have_every_field_populated(fed_ctx, user): """settings_for() builds a transient object when a user has never saved settings; its column defaults apply only on INSERT, so every field has to be set by hand.""" settings = sharing.settings_for(user.id) - assert (settings.timezone, settings.post_weekly_summary, settings.post_milestones) == ( - "UTC", - True, - True, - ) + assert ( + settings.timezone, + settings.post_weekly_summary, + settings.post_milestones, + settings.now_playing_mode, + ) == ("UTC", True, True, "off") def test_enabling_creates_a_key_pair_that_signs(fed_ctx, user): @@ -83,6 +84,7 @@ def test_shared_user_is_case_insensitive_and_requires_sharing(fed_ctx, user, mak {"enabled": True, "handle": "x"}, {"timezone": "Mars/Phobos"}, {"timezone": ""}, + {"now_playing_mode": "always"}, ], ) def test_invalid_changes_are_rejected(fed_ctx, user, changes): @@ -93,3 +95,9 @@ def test_invalid_changes_are_rejected(fed_ctx, user, changes): def test_a_valid_timezone_can_be_set(fed_ctx, user): settings, _ = sharing.update(user.id, {"timezone": "Pacific/Auckland"}) assert settings.timezone == "Pacific/Auckland" + + +@pytest.mark.parametrize("mode", ["off", "profile", "posts"]) +def test_now_playing_mode_can_be_set(fed_ctx, user, mode): + settings, _ = sharing.update(user.id, {"now_playing_mode": mode}) + assert settings.now_playing_mode == mode From c38e2e392a1e3a90e06ac4087550df6512f88b40 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 17:03:04 +0100 Subject: [PATCH 47/56] Update(Person) vocabulary and the live now-playing actor field (phase 4, step 2) vocab.update() wraps a document as an Update, addressed explicitly (unlike undo(), which derives `to` from the undone activity - an actor document has no `to` of its own). New actors.py builds the actor document body, shared by GET /users/ (live) and the coming Update(Person) push (throttled) so both render the same shape without web.py depending on the worker-side module or vice versa. now_playing_field() reads core's get_now_playing() directly - never federation's own throttled push state - so a fetch always shows the truth, whatever the last proactive push said. GET /users/ now includes a "Now playing" PropertyValue attachment whenever something unexpired is playing, and omits it otherwise. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/federation/actors.py | 37 ++++++++++++++++++++++ src/scrobbler/federation/protocol/vocab.py | 13 ++++++++ src/scrobbler/federation/web.py | 15 ++------- tests/test_federation_actors.py | 36 +++++++++++++++++++++ tests/test_federation_protocol.py | 9 ++++++ tests/test_federation_web.py | 11 +++++++ 6 files changed, 108 insertions(+), 13 deletions(-) create mode 100644 src/scrobbler/federation/actors.py create mode 100644 tests/test_federation_actors.py diff --git a/src/scrobbler/federation/actors.py b/src/scrobbler/federation/actors.py new file mode 100644 index 0000000..f7d332d --- /dev/null +++ b/src/scrobbler/federation/actors.py @@ -0,0 +1,37 @@ +"""Building a user's actor document: shared by the live `GET /users/` route and the +now-playing `Update(Person)` push, so both render the same shape. + +The now-playing field is always computed live from the core `now_playing` table, never +from federation's own throttled push state (`federation_now_playing`) - a fetch should +never lie, even if the last proactive Update was a few minutes ago. +""" + +from scrobbler.federation import keys +from scrobbler.federation.protocol import vocab +from scrobbler.services.scrobbles import get_now_playing + +NOW_PLAYING_FIELD = "Now playing" + + +def now_playing_field(user) -> list[tuple[str, str]]: + """The actor's now-playing `PropertyValue` field. Empty when nothing's playing + (`get_now_playing` already excludes expired tracks).""" + playing = get_now_playing(user) + if playing is None: + return [] + return [(NOW_PLAYING_FIELD, f"{playing.track} by {playing.artist}")] + + +def build_document(urls: vocab.ActorUrls, user, settings) -> dict: + return vocab.person( + urls, + username=user.username, + name=settings.display_name or user.username, + summary=settings.bio, + public_key_pem=keys.key_for(user.id).public_key_pem, + manually_approves_followers=settings.manually_approves_followers, + discoverable=settings.discoverable, + indexable=settings.indexable, + published=settings.created_at.isoformat().replace("+00:00", "Z"), + fields=now_playing_field(user), + ) diff --git a/src/scrobbler/federation/protocol/vocab.py b/src/scrobbler/federation/protocol/vocab.py index 6705804..d712f07 100644 --- a/src/scrobbler/federation/protocol/vocab.py +++ b/src/scrobbler/federation/protocol/vocab.py @@ -221,6 +221,19 @@ def undo(activity_id: str, actor_id: str, undone: dict) -> dict: } +def update(activity_id: str, actor_id: str, obj: dict, *, to: list[str]) -> dict: + """Tells already-following servers something about the actor changed (their now + playing field, here), so they don't have to re-fetch it to notice.""" + return { + "@context": AS_CONTEXT, + "id": activity_id, + "type": "Update", + "actor": actor_id, + "object": obj, + "to": list(to), + } + + def hashtag(name: str) -> dict: """A Hashtag tag, e.g. #Scrobbler. No href: we don't serve tag pages, and Mastodon still recognises and indexes the tag from `name` alone.""" diff --git a/src/scrobbler/federation/web.py b/src/scrobbler/federation/web.py index d55d8a2..3f0e8c5 100644 --- a/src/scrobbler/federation/web.py +++ b/src/scrobbler/federation/web.py @@ -7,8 +7,8 @@ import json from flask import Blueprint, Response, current_app, redirect, request from scrobbler.extensions import db +from scrobbler.federation import actors, ids, inbox, keys, publishing, sharing from scrobbler.federation import followers as follower_state -from scrobbler.federation import ids, inbox, keys, publishing, sharing from scrobbler.federation import metrics as fed_metrics from scrobbler.federation.models import FederationActivity from scrobbler.federation.protocol import hostmeta, media, nodeinfo, vocab, webfinger @@ -130,18 +130,7 @@ def actor(username: str): return _json(doc, cache=0) user, settings = found _found("actor") - urls = _urls(user.username) - doc = vocab.person( - urls, - username=user.username, - name=settings.display_name or user.username, - summary=settings.bio, - public_key_pem=keys.key_for(user.id).public_key_pem, - manually_approves_followers=settings.manually_approves_followers, - discoverable=settings.discoverable, - indexable=settings.indexable, - published=settings.created_at.isoformat().replace("+00:00", "Z"), - ) + doc = actors.build_document(_urls(user.username), user, settings) return _json(doc) diff --git a/tests/test_federation_actors.py b/tests/test_federation_actors.py new file mode 100644 index 0000000..013a108 --- /dev/null +++ b/tests/test_federation_actors.py @@ -0,0 +1,36 @@ +"""Actor document building (actors.py): shared by the live GET /users/ route and the +now-playing Update(Person) push.""" + +from scrobbler.federation import actors, sharing +from scrobbler.federation.protocol import vocab +from scrobbler.services.scrobbles import TrackInput, update_now_playing + +URLS = vocab.actor_urls( + "https://scrobble.test", "alice", "https://scrobble.test/profile.html?u=alice" +) + + +def test_now_playing_field_is_empty_when_nothing_is_playing(fed_ctx, user): + assert actors.now_playing_field(user) == [] + + +def test_now_playing_field_shows_the_current_track(fed_ctx, user): + update_now_playing(user, TrackInput(artist="Radiohead", track="Reckoner")) + assert actors.now_playing_field(user) == [("Now playing", "Reckoner by Radiohead")] + + +def test_build_document_includes_the_now_playing_field(fed_ctx, user): + sharing.update(user.id, {"enabled": True, "display_name": "Alice", "bio": "Hi."}) + update_now_playing(user, TrackInput(artist="Radiohead", track="Reckoner")) + settings = sharing.settings_for(user.id) + doc = actors.build_document(URLS, user, settings) + assert doc["attachment"] == [ + {"type": "PropertyValue", "name": "Now playing", "value": "Reckoner by Radiohead"} + ] + + +def test_build_document_has_no_now_playing_field_when_idle(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) + settings = sharing.settings_for(user.id) + doc = actors.build_document(URLS, user, settings) + assert doc["attachment"] == [] diff --git a/tests/test_federation_protocol.py b/tests/test_federation_protocol.py index 8030e31..0890a48 100644 --- a/tests/test_federation_protocol.py +++ b/tests/test_federation_protocol.py @@ -209,6 +209,15 @@ def test_delete_is_a_tombstone(): assert (doc["to"], doc["cc"]) == (["FOLLOWERS"], ["PUBLIC"]) +def test_update_wraps_the_actor_document(): + actor_doc = {"id": "actor", "type": "Person", "attachment": []} + doc = vocab.update("activity-id", "actor", actor_doc, to=["FOLLOWERS"]) + assert (doc["type"], doc["id"], doc["actor"]) == ("Update", "activity-id", "actor") + assert doc["object"] == actor_doc + assert doc["to"] == ["FOLLOWERS"] + assert doc["@context"] == vocab.AS_CONTEXT + + def test_nodeinfo(): assert nodeinfo.discovery(BASE)["links"][0]["href"] == f"{BASE}/nodeinfo/2.1" doc = nodeinfo.document(version="0.2.0", users_total=3, open_registrations=True) diff --git a/tests/test_federation_web.py b/tests/test_federation_web.py index 71b596c..32c6d90 100644 --- a/tests/test_federation_web.py +++ b/tests/test_federation_web.py @@ -66,6 +66,17 @@ def test_actor_document(fed_client, sharing_user): assert doc["manuallyApprovesFollowers"] is False # the user's setting (off by default) assert (doc["discoverable"], doc["indexable"]) == (False, False) assert doc["url"] == "http://localhost:8080/profile.html?u=alice" + assert doc["attachment"] == [] # nothing playing + + +def test_actor_document_shows_now_playing_live(fed_client, fed_ctx, sharing_user): + from scrobbler.services.scrobbles import TrackInput, update_now_playing + + update_now_playing(sharing_user, TrackInput(artist="Radiohead", track="Reckoner")) + doc = fed_client.get("/users/alice", headers=AP).get_json() + assert doc["attachment"] == [ + {"type": "PropertyValue", "name": "Now playing", "value": "Reckoner by Radiohead"} + ] def test_ids_come_from_config_not_the_request(fed_client, sharing_user): From 9ab8bd8e031a70e7cb4f668173cc320b0b7fd09e Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 17:06:55 +0100 Subject: [PATCH 48/56] Fix: never show now-playing when now_playing_mode is off now_playing_field() read core's now_playing table unconditionally, so a user who never turned federation's now-playing feature on at all would still leak what they're currently listening to on their public actor document, since core's now_playing table is populated for every user regardless of federation settings. Found while designing step 3 (the periodic push task): querying only sharing users with now_playing_mode != "off" made me notice build_document() itself had no equivalent guard, and the existing tests happened not to catch it (they only combined "nothing playing" with "mode off", and "something playing" with "mode on"). Added the missing combination - something playing, mode off - to both the actors.py unit tests and the web-level actor route test. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/federation/actors.py | 11 +++++++++-- tests/test_federation_actors.py | 15 ++++++++++++++- tests/test_federation_web.py | 11 +++++++++++ 3 files changed, 34 insertions(+), 3 deletions(-) diff --git a/src/scrobbler/federation/actors.py b/src/scrobbler/federation/actors.py index f7d332d..219006d 100644 --- a/src/scrobbler/federation/actors.py +++ b/src/scrobbler/federation/actors.py @@ -15,7 +15,13 @@ NOW_PLAYING_FIELD = "Now playing" def now_playing_field(user) -> list[tuple[str, str]]: """The actor's now-playing `PropertyValue` field. Empty when nothing's playing - (`get_now_playing` already excludes expired tracks).""" + (`get_now_playing` already excludes expired tracks). + + Doesn't look at the user's now_playing_mode: core's now_playing table is populated + for every user regardless of federation settings, so a caller must gate this itself + (build_document does) rather than leak listening activity for users who never turned + now playing on at all. + """ playing = get_now_playing(user) if playing is None: return [] @@ -23,6 +29,7 @@ def now_playing_field(user) -> list[tuple[str, str]]: def build_document(urls: vocab.ActorUrls, user, settings) -> dict: + fields = now_playing_field(user) if settings.now_playing_mode != "off" else [] return vocab.person( urls, username=user.username, @@ -33,5 +40,5 @@ def build_document(urls: vocab.ActorUrls, user, settings) -> dict: discoverable=settings.discoverable, indexable=settings.indexable, published=settings.created_at.isoformat().replace("+00:00", "Z"), - fields=now_playing_field(user), + fields=fields, ) diff --git a/tests/test_federation_actors.py b/tests/test_federation_actors.py index 013a108..9da04d8 100644 --- a/tests/test_federation_actors.py +++ b/tests/test_federation_actors.py @@ -20,7 +20,10 @@ def test_now_playing_field_shows_the_current_track(fed_ctx, user): def test_build_document_includes_the_now_playing_field(fed_ctx, user): - sharing.update(user.id, {"enabled": True, "display_name": "Alice", "bio": "Hi."}) + sharing.update( + user.id, + {"enabled": True, "display_name": "Alice", "bio": "Hi.", "now_playing_mode": "profile"}, + ) update_now_playing(user, TrackInput(artist="Radiohead", track="Reckoner")) settings = sharing.settings_for(user.id) doc = actors.build_document(URLS, user, settings) @@ -30,7 +33,17 @@ def test_build_document_includes_the_now_playing_field(fed_ctx, user): def test_build_document_has_no_now_playing_field_when_idle(fed_ctx, user): + sharing.update(user.id, {"enabled": True, "now_playing_mode": "profile"}) + settings = sharing.settings_for(user.id) + doc = actors.build_document(URLS, user, settings) + assert doc["attachment"] == [] + + +def test_build_document_never_shows_now_playing_when_the_mode_is_off(fed_ctx, user): + """now_playing_mode defaults to off; core's now_playing table is populated for every + user regardless, so a user who's never turned this on must never leak it.""" sharing.update(user.id, {"enabled": True}) + update_now_playing(user, TrackInput(artist="Radiohead", track="Reckoner")) settings = sharing.settings_for(user.id) doc = actors.build_document(URLS, user, settings) assert doc["attachment"] == [] diff --git a/tests/test_federation_web.py b/tests/test_federation_web.py index 32c6d90..f452174 100644 --- a/tests/test_federation_web.py +++ b/tests/test_federation_web.py @@ -72,6 +72,7 @@ def test_actor_document(fed_client, sharing_user): def test_actor_document_shows_now_playing_live(fed_client, fed_ctx, sharing_user): from scrobbler.services.scrobbles import TrackInput, update_now_playing + sharing.update(sharing_user.id, {"now_playing_mode": "profile"}) update_now_playing(sharing_user, TrackInput(artist="Radiohead", track="Reckoner")) doc = fed_client.get("/users/alice", headers=AP).get_json() assert doc["attachment"] == [ @@ -79,6 +80,16 @@ def test_actor_document_shows_now_playing_live(fed_client, fed_ctx, sharing_user ] +def test_actor_document_never_shows_now_playing_when_the_mode_is_off( + fed_client, fed_ctx, sharing_user +): + from scrobbler.services.scrobbles import TrackInput, update_now_playing + + update_now_playing(sharing_user, TrackInput(artist="Radiohead", track="Reckoner")) + doc = fed_client.get("/users/alice", headers=AP).get_json() + assert doc["attachment"] == [] + + def test_ids_come_from_config_not_the_request(fed_client, sharing_user): doc = fed_client.get("/users/alice", headers={**AP, "Host": "evil.example"}).get_json() assert urlsplit(doc["id"]).netloc == "scrobble.test" From ba30d5cb15be47dc652d60702bfcc886a853dd8e Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 17:13:10 +0100 Subject: [PATCH 49/56] Now-playing publisher and worker task (phase 4, step 3) publishing/now_playing.py: a periodic scan (federation.now_playing, every 30s) that pushes a throttled Update(Person) for the profile field (5 minutes) and, for users opted into posts, publishes a Note after a track's been playing 30+ seconds (throttled to 30 minutes), deleting the previous now-playing post once the new one is confirmed published - not before, so a failed publish never leaves a user with none showing. Reuses publishing.publish()/delete_post() unchanged; now_playing is just another post kind. Fixed a real bug before it ever ran against Postgres: the key (artist/track/started_at) was going straight into federation_posts.key (VARCHAR(64)), which routinely overflows for real track and artist names. Hashed instead - it's an idempotency token, not something anyone needs to read. New metric scrobbler_federation_profile_updates_total{result}; posts already get scrobbler_federation_posts_total{kind="now_playing",...} for free from the existing publish() instrumentation. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- src/scrobbler/federation/__init__.py | 3 +- src/scrobbler/federation/metrics.py | 8 +- src/scrobbler/federation/models.py | 7 +- .../federation/publishing/now_playing.py | 155 +++++++++++++ tests/test_federation_now_playing.py | 214 ++++++++++++++++++ 5 files changed, 382 insertions(+), 5 deletions(-) create mode 100644 src/scrobbler/federation/publishing/now_playing.py create mode 100644 tests/test_federation_now_playing.py diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py index 5043468..5eedd3f 100644 --- a/src/scrobbler/federation/__init__.py +++ b/src/scrobbler/federation/__init__.py @@ -40,7 +40,7 @@ def init_app(app: Flask) -> None: from scrobbler import events, worker from scrobbler.federation import delivery, inbox - from scrobbler.federation.publishing import milestones, weekly + from scrobbler.federation.publishing import milestones, now_playing, weekly worker.register_task(app, "federation.inbox", inbox.work_once) worker.register_task(app, "federation.deliver", delivery.work_once) @@ -48,6 +48,7 @@ def init_app(app: Flask) -> None: worker.register_periodic(app, "federation.inbox.maintenance", 300, inbox.maintenance) worker.register_periodic(app, "federation.gauges", 30, delivery.maintenance) worker.register_periodic(app, "federation.weekly", 900, weekly.check_all) + worker.register_periodic(app, "federation.now_playing", 30, now_playing.check_all) # blinker signals are process-wide, not per-app: once any app in a process enables # federation these stay connected for every app in it, including one built with diff --git a/src/scrobbler/federation/metrics.py b/src/scrobbler/federation/metrics.py index 75016ec..a58ce4c 100644 --- a/src/scrobbler/federation/metrics.py +++ b/src/scrobbler/federation/metrics.py @@ -53,7 +53,7 @@ followers = Gauge( ) posts_total = Counter( "scrobbler_federation_posts_total", - "Posts published: weekly summaries and milestones", + "Posts published: weekly summaries, milestones and now-playing", ["kind", "visibility"], ) post_deletions_total = Counter( @@ -71,3 +71,9 @@ weekly_total = Counter( "Weekly summary checks, by result: disabled, skipped_empty, already_posted or posted", ["result"], ) +profile_updates_total = Counter( + "scrobbler_federation_profile_updates_total", + "Now-playing Update(Person) pushes: sent, or throttled (still within the 5-minute " + "window since the last one)", + ["result"], +) diff --git a/src/scrobbler/federation/models.py b/src/scrobbler/federation/models.py index 031b295..e01904e 100644 --- a/src/scrobbler/federation/models.py +++ b/src/scrobbler/federation/models.py @@ -254,9 +254,10 @@ class FederationPendingCheck(db.Model): class FederationNowPlaying(db.Model): """What we've last told the fediverse is playing, as opposed to `now_playing` in the - core schema, which is what's actually playing. A "key" is `artist\\x1ftrack\\x1f - started_at`: playing the same track again later is a new now-playing moment, not a - stale repeat, and it doubles as federation_posts.key for the posts side.""" + core schema, which is what's actually playing. A "key" is a short hash of `artist, + track, started_at` (see publishing/now_playing.py): playing the same track again + later is a new now-playing moment, not a stale repeat, and it doubles as + federation_posts.key for the posts side.""" __tablename__ = "federation_now_playing" diff --git a/src/scrobbler/federation/publishing/now_playing.py b/src/scrobbler/federation/publishing/now_playing.py new file mode 100644 index 0000000..6eeafdd --- /dev/null +++ b/src/scrobbler/federation/publishing/now_playing.py @@ -0,0 +1,155 @@ +"""Now playing: a live field on the actor profile (actors.py handles that part), and +opt-in posts. + +No event receiver or pending-checks queue like milestones has: the throttle windows (5 +minutes for the profile push, 30 for posts) are far longer than a 30-second poll, so a +plain periodic scan - the same shape as weekly.check_all - is simplest and cheapest. +There's no baseline/import concern either: this only ever reflects what's playing right +now, never history. +""" + +import hashlib +import logging +from datetime import UTC, datetime, timedelta + +from flask import current_app + +from scrobbler.extensions import db +from scrobbler.federation import activities, actors, followers, publishing, sharing +from scrobbler.federation import metrics as fed_metrics +from scrobbler.federation.models import FederationNowPlaying, FederationPost, FederationSettings +from scrobbler.federation.protocol import content, vocab +from scrobbler.services import accounts +from scrobbler.services.scrobbles import get_now_playing + +KIND = "now_playing" +PROFILE_THROTTLE = timedelta(minutes=5) +POST_THROTTLE = timedelta(minutes=30) +MIN_PLAYED = timedelta(seconds=30) + +log = logging.getLogger(__name__) + + +def _key(playing) -> str: + """A short, fixed-length identifier for "this track, starting at this instant" - + hashed rather than the raw artist/track/timestamp, since federation_posts.key is only + VARCHAR(64) and real artist and track names routinely blow past that on their own.""" + raw = f"{playing.artist}\x1f{playing.track}\x1f{playing.started_at.isoformat()}" + return hashlib.sha256(raw.encode()).hexdigest()[:16] + + +def _state_for(user_id: int) -> FederationNowPlaying: + state = db.session.get(FederationNowPlaying, user_id) + if state is None: + state = FederationNowPlaying(user_id=user_id) + db.session.add(state) + return state + + +def _due(last: datetime | None, throttle: timedelta, now: datetime) -> bool: + return last is None or now - last >= throttle + + +def _urls_for(username: str) -> vocab.ActorUrls: + config = current_app.extensions["federation"] + profile_page = f"{current_app.config['UI_BASE_URL']}/profile.html?u={username}" + return vocab.actor_urls(config.base_url, username, profile_page) + + +def _push_profile(user, settings) -> None: + urls = _urls_for(user.username) + doc = actors.build_document(urls, user, settings) + activity = activities.store( + user.id, lambda url: vocab.update(url, urls.id, doc, to=[urls.followers]) + ) + inboxes = followers.accepted_inboxes(user.id) + if inboxes: + activities.queue(activity, inboxes) + + +def _build_content(playing) -> tuple[str, str]: + text = "\n".join( + [ + f"Now playing: {playing.track} by {playing.artist}", + f"{content.hashtag_line()} #NowPlaying", + ] + ) + html = content.paragraph( + f"Now playing: {content.escape(playing.track)} by {content.escape(playing.artist)}" + ) + content.paragraph(f"{content.hashtag_line()} #NowPlaying") + return text, html + + +def _post_now_playing(user, playing, key: str, state: FederationNowPlaying, now: datetime) -> str: + text, html = _build_content(playing) + post = publishing.publish( + user.id, user.username, KIND, key, text=text, html=html, tags=("Scrobbler", "NowPlaying") + ) + if post is None: + return "none" + if state.post_key is not None: + previous = db.session.scalar( + db.select(FederationPost).filter_by(user_id=user.id, key=f"{KIND}:{state.post_key}") + ) + if previous is not None and previous.deleted_at is None: + publishing.delete_post(user.id, user.username, previous) + state.post_key = key + state.post_posted_at = now + return "posted" + + +def check_and_post(user_id: int, now_utc: datetime | None = None) -> dict[str, str]: + """For one user: push a throttled profile update and/or post, whichever their + now_playing_mode calls for. Returns {"profile": ..., "post": ...}; "profile" is + "unchanged", "throttled" or "sent", "post" is "off", "none" or "posted".""" + settings = sharing.settings_for(user_id) + if settings.now_playing_mode == "off": + return {"profile": "off", "post": "off"} + user = accounts.get_user(user_id) + if user is None: # the account was deleted; federation_settings should follow, but be safe + return {"profile": "off", "post": "off"} + + now_utc = now_utc or datetime.now(UTC) + playing = get_now_playing(user) + current_key = _key(playing) if playing else None + state = _state_for(user_id) + + profile_result = "unchanged" + if current_key != state.profile_key: + if _due(state.profile_updated_at, PROFILE_THROTTLE, now_utc): + _push_profile(user, settings) + state.profile_key = current_key + state.profile_updated_at = now_utc + profile_result = "sent" + else: + profile_result = "throttled" + fed_metrics.profile_updates_total.labels(result=profile_result).inc() + + post_result = "off" + if settings.now_playing_mode == "posts": + post_result = "none" + if ( + playing is not None + and now_utc - playing.started_at >= MIN_PLAYED + and current_key != state.post_key + and _due(state.post_posted_at, POST_THROTTLE, now_utc) + ): + post_result = _post_now_playing(user, playing, current_key, state, now_utc) + + db.session.commit() + return {"profile": profile_result, "post": post_result} + + +def check_all(now_utc: datetime | None = None) -> None: + """Worker task (periodic, every 30 seconds): check every user with now playing on. + One user's failure is logged and doesn't stop the rest from being checked.""" + now_utc = now_utc or datetime.now(UTC) + user_ids = db.session.scalars( + db.select(FederationSettings.user_id).filter(FederationSettings.now_playing_mode != "off") + ).all() + for user_id in user_ids: + try: + check_and_post(user_id, now_utc) + except Exception: + log.exception("now playing check failed for user %s", user_id) + db.session.rollback() diff --git a/tests/test_federation_now_playing.py b/tests/test_federation_now_playing.py new file mode 100644 index 0000000..094e7e0 --- /dev/null +++ b/tests/test_federation_now_playing.py @@ -0,0 +1,214 @@ +"""Now playing end to end: publishing/now_playing.py against a real database.""" + +from datetime import UTC, datetime, timedelta + +import pytest + +from scrobbler.extensions import db +from scrobbler.federation import sharing +from scrobbler.federation.models import FederationActivity, FederationNowPlaying, FederationPost +from scrobbler.federation.publishing import now_playing +from scrobbler.models import NowPlaying +from scrobbler.services.scrobbles import TrackInput, update_now_playing + + +def play(user, artist="Radiohead", track="Reckoner") -> datetime: + """Sets the track as playing (started_at = now) and returns that now, so tests + always measure elapsed/throttle time relative to when it actually started, not a + fixed constant that would drift from real test-execution time.""" + update_now_playing(user, TrackInput(artist=artist, track=track)) + return datetime.now(UTC) + + +def stop_playing(user): + """Expire (rather than delete) the row, matching how it naturally goes away.""" + db.session.get(NowPlaying, user.id).expires_at = datetime.now(UTC) - timedelta(minutes=1) + db.session.commit() + + +def state_for(user_id): + return db.session.get(FederationNowPlaying, user_id) + + +def updates_for(user_id): + return db.session.scalars( + db.select(FederationActivity).filter_by(user_id=user_id, activity_type="Update") + ).all() + + +def posts_for(user_id): + return db.session.scalars( + db.select(FederationPost).filter_by(user_id=user_id, kind=now_playing.KIND) + ).all() + + +@pytest.fixture +def profile_user(fed_ctx, user): + sharing.update(user.id, {"enabled": True, "now_playing_mode": "profile"}) + return user + + +@pytest.fixture +def posting_user(fed_ctx, user): + sharing.update(user.id, {"enabled": True, "now_playing_mode": "posts"}) + return user + + +def test_off_mode_does_nothing(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) # now_playing_mode defaults to off + now = play(user) + result = now_playing.check_and_post(user.id, now) + assert result == {"profile": "off", "post": "off"} + assert state_for(user.id) is None + assert updates_for(user.id) == [] + + +def test_profile_update_sent_on_a_genuine_change(fed_ctx, profile_user, metric_delta): + now = play(profile_user) + sent = metric_delta("scrobbler_federation_profile_updates_total", result="sent") + result = now_playing.check_and_post(profile_user.id, now) + assert result["profile"] == "sent" + [activity] = updates_for(profile_user.id) + assert activity.document["object"]["attachment"] == [ + {"type": "PropertyValue", "name": "Now playing", "value": "Reckoner by Radiohead"} + ] + assert sent.delta == 1 + + +def test_profile_update_is_a_noop_when_nothing_changed(fed_ctx, profile_user): + now = play(profile_user) + now_playing.check_and_post(profile_user.id, now) + result = now_playing.check_and_post(profile_user.id, now + timedelta(seconds=30)) + assert result["profile"] == "unchanged" + assert len(updates_for(profile_user.id)) == 1 # not sent again + + +def test_profile_update_throttled_within_5_minutes(fed_ctx, profile_user, metric_delta): + now = play(profile_user, track="Reckoner") + now_playing.check_and_post(profile_user.id, now) + play(profile_user, track="Karma Police") # a genuine change + throttled = metric_delta("scrobbler_federation_profile_updates_total", result="throttled") + result = now_playing.check_and_post(profile_user.id, now + timedelta(minutes=2)) + assert result["profile"] == "throttled" + assert len(updates_for(profile_user.id)) == 1 # still just the first + assert throttled.delta == 1 + + +def test_profile_update_sent_again_once_the_throttle_clears(fed_ctx, profile_user): + now = play(profile_user, track="Reckoner") + now_playing.check_and_post(profile_user.id, now) + play(profile_user, track="Karma Police") + result = now_playing.check_and_post(profile_user.id, now + timedelta(minutes=6)) + assert result["profile"] == "sent" + assert len(updates_for(profile_user.id)) == 2 + + +def test_profile_cleared_when_playback_stops(fed_ctx, profile_user): + now = play(profile_user) + now_playing.check_and_post(profile_user.id, now) + stop_playing(profile_user) + result = now_playing.check_and_post(profile_user.id, now + timedelta(minutes=6)) + assert result["profile"] == "sent" + [_, cleared] = updates_for(profile_user.id) + assert cleared.document["object"]["attachment"] == [] + + +def test_profile_mode_never_posts(fed_ctx, profile_user): + now = play(profile_user) + result = now_playing.check_and_post(profile_user.id, now + timedelta(seconds=31)) + assert result["post"] == "off" + assert posts_for(profile_user.id) == [] + + +def test_post_needs_at_least_30_seconds_played(fed_ctx, posting_user): + now = play(posting_user) + result = now_playing.check_and_post(posting_user.id, now + timedelta(seconds=10)) + assert result["post"] == "none" + assert posts_for(posting_user.id) == [] + + +def test_post_sent_after_30_seconds(fed_ctx, posting_user): + now = play(posting_user) + result = now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31)) + assert result["post"] == "posted" + [post] = posts_for(posting_user.id) + assert "Now playing: Reckoner by Radiohead" in post.content_text + activity = db.session.get(FederationActivity, post.activity_id) + assert activity.activity_type == "Create" + assert activity.document["object"]["tag"] == [ + {"type": "Hashtag", "name": "#Scrobbler"}, + {"type": "Hashtag", "name": "#NowPlaying"}, + ] + + +def test_post_throttled_within_30_minutes(fed_ctx, posting_user): + now = play(posting_user, track="Reckoner") + now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31)) + play(posting_user, track="Karma Police") + result = now_playing.check_and_post(posting_user.id, now + timedelta(minutes=10)) + assert result["post"] == "none" + assert len(posts_for(posting_user.id)) == 1 + + +def test_previous_post_deleted_when_a_new_one_goes_out(fed_ctx, posting_user): + now = play(posting_user, track="Reckoner") + now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31)) + [first] = posts_for(posting_user.id) + assert first.deleted_at is None + + play(posting_user, track="Karma Police") + now_playing.check_and_post(posting_user.id, now + timedelta(minutes=31)) + + assert db.session.get(FederationPost, first.id).deleted_at is not None + live = [p for p in posts_for(posting_user.id) if p.deleted_at is None] + assert len(live) == 1 + assert "Karma Police" in live[0].content_text + + +def test_stopping_does_not_post_or_delete(fed_ctx, posting_user): + now = play(posting_user) + now_playing.check_and_post(posting_user.id, now + timedelta(seconds=31)) + stop_playing(posting_user) + result = now_playing.check_and_post(posting_user.id, now + timedelta(minutes=35)) + assert result["post"] == "none" + live = [p for p in posts_for(posting_user.id) if p.deleted_at is None] + assert len(live) == 1 # the one post from before stopping is left alone + + +def test_check_all_covers_every_user_with_now_playing_on(fed_ctx, make_user): + alice = make_user(username="alice_np") + bob = make_user(username="bob_np") + sharing.update(alice.id, {"enabled": True, "now_playing_mode": "profile"}) + sharing.update(bob.id, {"enabled": True}) # stays off + play(alice) + now = play(bob) + + now_playing.check_all(now) + + assert len(updates_for(alice.id)) == 1 + assert updates_for(bob.id) == [] + + +def test_check_all_isolates_one_users_failure(fed_ctx, make_user, monkeypatch): + alice = make_user(username="alice_np2") + sharing.update(alice.id, {"enabled": True, "now_playing_mode": "profile"}) + now = play(alice) + + def boom(user_id, now_utc=None): + raise RuntimeError("boom") + + monkeypatch.setattr(now_playing, "check_and_post", boom) + now_playing.check_all(now) # doesn't raise + assert state_for(alice.id) is None # never got past the monkeypatched call + + +def test_the_task_is_registered_when_federation_is_on(fed_app): + from scrobbler import worker + + assert "federation.now_playing" in worker.registered(fed_app) + + +def test_the_task_is_not_registered_when_federation_is_off(app): + from scrobbler import worker + + assert "federation.now_playing" not in worker.registered(app) From 515acae233d22ec07606d1e6848c034e8a66fc58 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 17:15:51 +0100 Subject: [PATCH 50/56] Settings API and schema for now_playing_mode (phase 4, step 4) now_playing_mode was already in sharing.EDITABLE (step 1), so _settings_body() was already returning it - but SharingSettingsSchema never declared the field, so marshmallow was silently dropping it from every response. Same class of gap phase 3 hit with timezone/ post_weekly_summary/post_milestones. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/openapi.json | 20 +++++++++++++++++++- src/scrobbler/federation/schemas.py | 15 +++++++++++++-- tests/test_federation_api.py | 21 +++++++++++++++++++++ 3 files changed, 53 insertions(+), 3 deletions(-) diff --git a/docs/openapi.json b/docs/openapi.json index 2dcbd33..d863c4f 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -4394,6 +4394,15 @@ "type": "boolean", "description": "Post scrobble-count, artist-plays and top-10 milestones as you hit them" }, + "now_playing_mode": { + "type": "string", + "enum": [ + "off", + "profile", + "posts" + ], + "description": "`off` (default): nothing. `profile`: a \"Now playing\" field on your profile, refreshed at most every 5 minutes and cleared when you stop. `posts`: the profile field, plus a post for each track played 30+ seconds, at most one every 30 minutes, replacing the last one." + }, "handle": { "type": "string", "readOnly": true, @@ -4474,6 +4483,15 @@ "type": "boolean", "description": "Post scrobble-count, artist-plays and top-10 milestones as you hit them" }, + "now_playing_mode": { + "type": "string", + "enum": [ + "off", + "profile", + "posts" + ], + "description": "`off` (default): nothing. `profile`: a \"Now playing\" field on your profile, refreshed at most every 5 minutes and cleared when you stop. `posts`: the profile field, plus a post for each track played 30+ seconds, at most one every 30 minutes, replacing the last one." + }, "handle": { "type": "string", "readOnly": true, @@ -4520,7 +4538,7 @@ }, "kind": { "type": "string", - "description": "weekly or milestone" + "description": "weekly, milestone or now_playing" }, "text": { "type": "string" diff --git a/src/scrobbler/federation/schemas.py b/src/scrobbler/federation/schemas.py index 80a9218..b6fc785 100644 --- a/src/scrobbler/federation/schemas.py +++ b/src/scrobbler/federation/schemas.py @@ -1,6 +1,6 @@ from marshmallow import Schema, ValidationError, fields, validate -from scrobbler.federation.models import VISIBILITIES +from scrobbler.federation.models import NOW_PLAYING_MODES, VISIBILITIES from scrobbler.federation.protocol.schedule import is_valid_timezone @@ -44,6 +44,17 @@ class SharingSettingsSchema(Schema): "description": "Post scrobble-count, artist-plays and top-10 milestones as you hit them" } ) + now_playing_mode = fields.String( + validate=validate.OneOf(NOW_PLAYING_MODES), + metadata={ + "description": ( + '`off` (default): nothing. `profile`: a "Now playing" field on your ' + "profile, refreshed at most every 5 minutes and cleared when you stop. " + "`posts`: the profile field, plus a post for each track played 30+ " + "seconds, at most one every 30 minutes, replacing the last one." + ) + }, + ) 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) @@ -89,7 +100,7 @@ class BlockSchema(Schema): class PostSchema(Schema): id = fields.Integer() - kind = fields.String(metadata={"description": "weekly or milestone"}) + kind = fields.String(metadata={"description": "weekly, milestone or now_playing"}) text = fields.String() visibility = fields.String() created_at = fields.DateTime() diff --git a/tests/test_federation_api.py b/tests/test_federation_api.py index 007ab41..495faf5 100644 --- a/tests/test_federation_api.py +++ b/tests/test_federation_api.py @@ -56,6 +56,27 @@ def test_an_unknown_timezone_is_rejected(fed_client, fed_auth): assert response.status_code == 422 +def test_now_playing_mode_defaults_to_off(fed_client, fed_auth): + body = fed_client.get("/api/v1/federation/settings", headers=fed_auth).get_json() + assert body["now_playing_mode"] == "off" + + +@pytest.mark.parametrize("mode", ["off", "profile", "posts"]) +def test_now_playing_mode_can_be_changed(fed_client, fed_auth, mode): + response = fed_client.patch( + "/api/v1/federation/settings", json={"now_playing_mode": mode}, headers=fed_auth + ) + assert response.status_code == 200 + assert response.get_json()["now_playing_mode"] == mode + + +def test_an_unknown_now_playing_mode_is_rejected(fed_client, fed_auth): + response = fed_client.patch( + "/api/v1/federation/settings", json={"now_playing_mode": "always"}, headers=fed_auth + ) + assert response.status_code == 422 + + 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( From f04e53a972fcce3c51619eed02066d7df7b9281b Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 17:22:02 +0100 Subject: [PATCH 51/56] Web UI for now playing (phase 4, step 5) Sharing page gets a "Now playing" section: off / show on profile / show on profile and post, as a single choice matching the settings column - generalised sharing.js's visibility-only radio-group handling to a small RADIO_GROUPS list so now_playing_mode reuses the same fill/ save logic rather than adding a second special case. Public profile API and profile.html gain a live "now playing" field, sourced from the same actors.now_playing_text() the actor document uses and gated the same way (now_playing_mode off means never showing it, whatever's actually playing). Refactored actors.py along the way: now_playing_field() takes settings directly and does its own off-mode gating, rather than build_document() doing it externally - one place decides whether the field is shown, reused by the actor document, the push Update, and now the public profile API. Verified by hand in a real browser: settings round-trip through the Sharing page's new radio group, the public profile page shows "Now playing: Reckoner by Radiohead" once now_playing_mode is on, and the raw actor document (curl, Accept: application/activity+json) carries the same PropertyValue attachment. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/openapi.json | 7 +++++++ frontend/css/style.css | 8 ++++++++ frontend/js/profile.js | 3 +++ frontend/js/sharing.js | 11 ++++++++--- frontend/sharing.html | 16 ++++++++++++++++ src/scrobbler/federation/actors.py | 29 +++++++++++++++++------------ src/scrobbler/federation/api.py | 5 ++++- src/scrobbler/federation/schemas.py | 3 +++ tests/test_federation_actors.py | 18 ++++++++++++++---- tests/test_federation_api.py | 18 ++++++++++++++++++ 10 files changed, 98 insertions(+), 20 deletions(-) diff --git a/docs/openapi.json b/docs/openapi.json index d863c4f..84633dd 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -4575,6 +4575,13 @@ "null" ] }, + "now_playing": { + "type": [ + "string", + "null" + ], + "description": "\"Track by Artist\", or null" + }, "handle": { "type": "string", "example": "@alice@scrobble.example" diff --git a/frontend/css/style.css b/frontend/css/style.css index 9f4c983..1d80019 100644 --- a/frontend/css/style.css +++ b/frontend/css/style.css @@ -954,6 +954,14 @@ input { white-space: pre-line; } +.now-playing { + padding: 0.6rem 1rem; + border-radius: var(--radius-control); + border-left: 4px solid var(--glow); + background: var(--paper-raised); + margin: 0.75rem 0; +} + .profile-follow { margin: 2rem 0 0.4rem; } diff --git a/frontend/js/profile.js b/frontend/js/profile.js index bbf1031..31a4456 100644 --- a/frontend/js/profile.js +++ b/frontend/js/profile.js @@ -25,6 +25,9 @@ try { h("h1", {}, profile.display_name), h("div", { class: "approve-app handle" }, profile.handle), profile.bio ? h("p", { class: "lede profile-bio" }, profile.bio) : null, + profile.now_playing + ? h("p", { class: "now-playing" }, "Now playing: ", h("strong", {}, profile.now_playing)) + : null, h("h2", { class: "profile-follow" }, "Follow from the fediverse"), h( "p", diff --git a/frontend/js/sharing.js b/frontend/js/sharing.js index 3fe7fb8..fd3f1cf 100644 --- a/frontend/js/sharing.js +++ b/frontend/js/sharing.js @@ -5,6 +5,7 @@ import { signedInPage } from "./layout.js"; const form = document.getElementById("sharing"); const messages = document.getElementById("messages"); const handlePanel = document.getElementById("handle-panel"); +const RADIO_GROUPS = ["visibility", "now_playing_mode"]; const FIELDS = [ "enabled", "visibility", @@ -14,6 +15,7 @@ const FIELDS = [ "post_weekly_summary", "post_milestones", "timezone", + "now_playing_mode", "display_name", "bio", ]; @@ -70,10 +72,12 @@ async function previewWeekly() { function fill(values) { for (const name of FIELDS) { + if (RADIO_GROUPS.includes(name)) { + form.querySelector(`input[name=${name}][value="${values[name]}"]`).checked = true; + continue; + } const field = form.elements[name]; - if (name === "visibility") { - form.querySelector(`input[name=visibility][value="${values.visibility}"]`).checked = true; - } else if (field.type === "checkbox") { + if (field.type === "checkbox") { field.checked = Boolean(values[name]); } else { field.value = values[name] ?? ""; @@ -150,6 +154,7 @@ async function save(event) { post_weekly_summary: form.elements.post_weekly_summary.checked, post_milestones: form.elements.post_milestones.checked, timezone: form.elements.timezone.value.trim() || "UTC", + now_playing_mode: form.querySelector("input[name=now_playing_mode]:checked").value, display_name: form.elements.display_name.value.trim() || null, bio: form.elements.bio.value.trim() || null, }; diff --git a/frontend/sharing.html b/frontend/sharing.html index 96ac78e..65383f8 100644 --- a/frontend/sharing.html +++ b/frontend/sharing.html @@ -83,6 +83,22 @@

      See your posts

      +
      + Now playing +
      + + +
      +
      + + +
      +
      + + +
      +
      +
      Profile
      diff --git a/src/scrobbler/federation/actors.py b/src/scrobbler/federation/actors.py index 219006d..5e5fc07 100644 --- a/src/scrobbler/federation/actors.py +++ b/src/scrobbler/federation/actors.py @@ -13,23 +13,28 @@ from scrobbler.services.scrobbles import get_now_playing NOW_PLAYING_FIELD = "Now playing" -def now_playing_field(user) -> list[tuple[str, str]]: - """The actor's now-playing `PropertyValue` field. Empty when nothing's playing - (`get_now_playing` already excludes expired tracks). - - Doesn't look at the user's now_playing_mode: core's now_playing table is populated - for every user regardless of federation settings, so a caller must gate this itself - (build_document does) rather than leak listening activity for users who never turned - now playing on at all. - """ +def now_playing_text(user) -> str | None: + """ "Track by Artist", or None if nothing unexpired is playing (`get_now_playing` + already excludes expired tracks). Doesn't look at now_playing_mode: core's + now_playing table is populated for every user regardless of federation settings, so + a caller must gate this itself (now_playing_field does) rather than leak listening + activity for users who never turned now playing on at all.""" playing = get_now_playing(user) if playing is None: + return None + return f"{playing.track} by {playing.artist}" + + +def now_playing_field(user, settings) -> list[tuple[str, str]]: + """The actor's now-playing `PropertyValue` field: empty unless now_playing_mode is + on and something's actually playing.""" + if settings.now_playing_mode == "off": return [] - return [(NOW_PLAYING_FIELD, f"{playing.track} by {playing.artist}")] + text = now_playing_text(user) + return [(NOW_PLAYING_FIELD, text)] if text else [] def build_document(urls: vocab.ActorUrls, user, settings) -> dict: - fields = now_playing_field(user) if settings.now_playing_mode != "off" else [] return vocab.person( urls, username=user.username, @@ -40,5 +45,5 @@ def build_document(urls: vocab.ActorUrls, user, settings) -> dict: discoverable=settings.discoverable, indexable=settings.indexable, published=settings.created_at.isoformat().replace("+00:00", "Z"), - fields=fields, + fields=now_playing_field(user, settings), ) diff --git a/src/scrobbler/federation/api.py b/src/scrobbler/federation/api.py index cbf967a..30f7342 100644 --- a/src/scrobbler/federation/api.py +++ b/src/scrobbler/federation/api.py @@ -5,7 +5,7 @@ from flask_smorest import Blueprint, abort from scrobbler.api.decorators import authenticated from scrobbler.extensions import db -from scrobbler.federation import activities, ids, publishing, sharing +from scrobbler.federation import activities, actors, ids, publishing, sharing from scrobbler.federation import followers as follower_state from scrobbler.federation import metrics as fed_metrics from scrobbler.federation.models import FederationBlock, FederationFollower, FederationPost @@ -175,6 +175,9 @@ def public_profile(username): "username": user.username, "display_name": settings.display_name or user.username, "bio": settings.bio, + "now_playing": actors.now_playing_text(user) + if settings.now_playing_mode != "off" + else None, **{k: v for k, v in _identity(user.username).items() if k != "profile_url"}, } diff --git a/src/scrobbler/federation/schemas.py b/src/scrobbler/federation/schemas.py index b6fc785..c4dfba7 100644 --- a/src/scrobbler/federation/schemas.py +++ b/src/scrobbler/federation/schemas.py @@ -68,6 +68,9 @@ class PublicProfileSchema(Schema): username = fields.String() display_name = fields.String() bio = fields.String(allow_none=True) + now_playing = fields.String( + allow_none=True, metadata={"description": '"Track by Artist", or null'} + ) handle = fields.String(metadata={"example": "@alice@scrobble.example"}) actor_url = fields.String() diff --git a/tests/test_federation_actors.py b/tests/test_federation_actors.py index 9da04d8..048368d 100644 --- a/tests/test_federation_actors.py +++ b/tests/test_federation_actors.py @@ -10,13 +10,23 @@ URLS = vocab.actor_urls( ) -def test_now_playing_field_is_empty_when_nothing_is_playing(fed_ctx, user): - assert actors.now_playing_field(user) == [] +def test_now_playing_text_is_none_when_nothing_is_playing(fed_ctx, user): + assert actors.now_playing_text(user) is None -def test_now_playing_field_shows_the_current_track(fed_ctx, user): +def test_now_playing_text_shows_the_current_track(fed_ctx, user): update_now_playing(user, TrackInput(artist="Radiohead", track="Reckoner")) - assert actors.now_playing_field(user) == [("Now playing", "Reckoner by Radiohead")] + assert actors.now_playing_text(user) == "Reckoner by Radiohead" + + +def test_now_playing_field_respects_the_mode(fed_ctx, user): + update_now_playing(user, TrackInput(artist="Radiohead", track="Reckoner")) + off = sharing.settings_for(user.id) + assert actors.now_playing_field(user, off) == [] + + sharing.update(user.id, {"enabled": True, "now_playing_mode": "profile"}) + on = sharing.settings_for(user.id) + assert actors.now_playing_field(user, on) == [("Now playing", "Reckoner by Radiohead")] def test_build_document_includes_the_now_playing_field(fed_ctx, user): diff --git a/tests/test_federation_api.py b/tests/test_federation_api.py index 495faf5..fe7d981 100644 --- a/tests/test_federation_api.py +++ b/tests/test_federation_api.py @@ -126,6 +126,7 @@ def test_public_profile(fed_client, sharing_user, make_user): "username": "alice", "display_name": "Alice", "bio": "Listening.", + "now_playing": None, "handle": "@alice@scrobble.test", "actor_url": "https://scrobble.test/users/alice", } @@ -133,6 +134,23 @@ def test_public_profile(fed_client, sharing_user, make_user): assert fed_client.get("/api/v1/federation/profiles/bob").status_code == 404 +def test_public_profile_shows_now_playing_when_the_mode_is_on(fed_client, fed_ctx, sharing_user): + from scrobbler.services.scrobbles import TrackInput, update_now_playing + + sharing.update(sharing_user.id, {"now_playing_mode": "profile"}) + update_now_playing(sharing_user, TrackInput(artist="Radiohead", track="Reckoner")) + body = fed_client.get("/api/v1/federation/profiles/alice").get_json() + assert body["now_playing"] == "Reckoner by Radiohead" + + +def test_public_profile_hides_now_playing_when_the_mode_is_off(fed_client, fed_ctx, sharing_user): + from scrobbler.services.scrobbles import TrackInput, update_now_playing + + update_now_playing(sharing_user, TrackInput(artist="Radiohead", track="Reckoner")) + body = fed_client.get("/api/v1/federation/profiles/alice").get_json() + assert body["now_playing"] is None + + def test_disabled_server_has_no_federation_api(client, auth): assert client.get("/api/v1/federation/settings", headers=auth).status_code == 404 From f3d2b5d5786e617ca4f3c6b702d777f24febd6cd Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 17:24:17 +0100 Subject: [PATCH 52/56] Dashboard panel for profile updates (phase 4, step 6) One new panel on the Federation dashboard's existing Posts row: profile updates/min by result (sent/throttled). now_playing posts already show up in the Posts / min by kind panel from phase 3, under kind="now_playing" - no changes needed there. No new alert: unlike weekly summaries, now playing is opt-in and most instances will have nobody using it, so there's no "should always be producing something" baseline to alert on the way FederationWeeklySummariesMissing does. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- deploy/grafana/dashboards/federation.json | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/deploy/grafana/dashboards/federation.json b/deploy/grafana/dashboards/federation.json index d7616af..73af914 100644 --- a/deploy/grafana/dashboards/federation.json +++ b/deploy/grafana/dashboards/federation.json @@ -1189,6 +1189,61 @@ "w": 12, "h": 8 } + }, + { + "type": "timeseries", + "title": "Profile updates / min by result", + "description": "Now-playing Update(Person) pushes: sent, or throttled (still within the 5-minute window since the last one). Posts already appear in the Posts / min panel above, under kind=\"now_playing\".", + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "expr": "sum by (result) (rate(scrobbler_federation_profile_updates_total[$__rate_interval])) * 60", + "legendFormat": "{{result}}", + "refId": "A" + } + ], + "fieldConfig": { + "defaults": { + "unit": "short", + "custom": { + "lineWidth": 2, + "fillOpacity": 40, + "showPoints": "never", + "spanNulls": true, + "stacking": { + "mode": "normal", + "group": "A" + } + }, + "min": 0 + }, + "overrides": [] + }, + "options": { + "legend": { + "displayMode": "list", + "placement": "bottom", + "showLegend": true + }, + "tooltip": { + "mode": "multi", + "sort": "desc" + } + }, + "id": 25, + "gridPos": { + "x": 0, + "y": 67, + "w": 12, + "h": 8 + } } ] } From 9883111fa1636e313ce61d5e3aa1fcb99f50d860 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 17:29:31 +0100 Subject: [PATCH 53/56] Now-playing interop check (phase 4, step 7) Extends the GoToSocial driver's second phase: run.sh seeds a now-playing track alongside the scrobble it already seeds for the weekly summary; the driver turns now_playing_mode on via the settings API, then polls GoToSocial's own stored copy of the account (not a fresh resolve() fetch) for a "Now playing" field, confirming the periodic Update(Person) push actually reached and updated their cache - not just that we sent something. Verified against a real GoToSocial 0.22.1 container locally before pushing: Now playing: 'Interop Now Playing by Interop Artist' All post interop checks passed Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- scripts/interop/gotosocial_interop.py | 27 ++++++++++++++++++++++++++- scripts/interop/run.sh | 4 +++- 2 files changed, 29 insertions(+), 2 deletions(-) diff --git a/scripts/interop/gotosocial_interop.py b/scripts/interop/gotosocial_interop.py index 4c1a7be..1de4fcd 100644 --- a/scripts/interop/gotosocial_interop.py +++ b/scripts/interop/gotosocial_interop.py @@ -261,6 +261,15 @@ class GoToSocial: fail(f"home timeline: {status} {body}") return body + def account(self, account_id): + """The account as GoToSocial currently has it stored - not a fresh remote fetch + like resolve()'s ?resolve=true search, so this shows whether a proactive + Update(Person) actually reached and updated their cached copy.""" + status, body = api("GET", f"{GTS}/api/v1/accounts/{account_id}", self.token) + if status != 200: + fail(f"account lookup: {status} {body}") + return body + def main(): step("Getting a GoToSocial access token") @@ -372,7 +381,8 @@ def check_posts(): --now` directly in the api container (this container has no docker access to do that itself). Checks the post reaches the already-following GoToSocial account's home timeline as a private (followers-only) status with the expected text, then deletes - it and checks it disappears there too.""" + it and checks it disappears there too. Also turns now playing on and checks the + profile field GoToSocial has cached is updated by the periodic push.""" step("Getting a GoToSocial access token") gts = GoToSocial(gotosocial_token()) alice = Scrobbler() # register-or-login: the same account main() set up @@ -381,6 +391,9 @@ def check_posts(): if not gts.relationship(account_id)["following"]: fail("GoToSocial isn't following alice; run the main interop flow first") + step("Alice turns now playing on (run.sh already seeded a now-playing track)") + alice.settings(now_playing_mode="profile") + step("The weekly summary reaches GoToSocial's home timeline") posted = wait_for( "the weekly summary in GoToSocial's home timeline", @@ -405,6 +418,18 @@ def check_posts(): lambda: not any(s["id"] == posted["id"] for s in gts.home_timeline()), ) + step("The now-playing field reaches GoToSocial's cached copy of the profile") + field = wait_for( + "a Now playing field on GoToSocial's cached account", + lambda: next( + (f for f in gts.account(account_id)["fields"] if f["name"] == "Now playing"), None + ), + timeout=90, # the push is throttled and only checked every 30s + ) + if "Interop Now Playing" not in field["value"]: + fail(f"unexpected now-playing field: {field['value']!r}") + print(f" Now playing: {field['value']!r}") + step("All post interop checks passed") diff --git a/scripts/interop/run.sh b/scripts/interop/run.sh index 42e4f4a..e99cffe 100755 --- a/scripts/interop/run.sh +++ b/scripts/interop/run.sh @@ -42,19 +42,21 @@ if [ $status -ne 0 ]; then exit $status fi -echo "==> Alice scrobbles something, for the weekly summary to have content" +echo "==> Alice scrobbles something, for the weekly summary to have content, and is playing something now" "$compose" exec -T api python3 -c " from datetime import UTC, datetime from scrobbler import create_app from scrobbler.config import Config from scrobbler.extensions import db from scrobbler.models import Scrobble, User +from scrobbler.services.scrobbles import TrackInput, update_now_playing app = create_app(Config) with app.app_context(): user = db.session.scalar(db.select(User).filter_by(username='alice')) db.session.add(Scrobble(user_id=user.id, artist='Interop Artist', track='Interop Track', played_at=datetime.now(UTC))) db.session.commit() + update_now_playing(user, TrackInput(artist='Interop Artist', track='Interop Now Playing')) " echo "==> Posting alice's weekly summary immediately" From 9f7ada682c737776b50b991a2e32b441724d401b Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 17:32:20 +0100 Subject: [PATCH 54/56] Docs for phase 4: now playing (step 8) README: the Sharing page's Now playing section, its three modes and their throttles. federation/README.md: now_playing.py added to the publishing plug-ins list (with a note on why it's not quite the same shape as weekly.py/milestones.py - a periodic scan covering both the profile push and the opt-in post, rather than an event receiver), actors.py added to the layout table, and the worker tasks / interop sections updated for federation.now_playing and the new profile-field check. docs/design/activitypub-phase4.md marked done, with the two points where implementation diverged from the written plan (the key-hashing fix and the now_playing_mode privacy gate). docs/openapi.json unchanged - still current from step 4. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- README.md | 10 +++++++-- docs/design/activitypub-phase4.md | 7 ++++++ src/scrobbler/federation/README.md | 36 ++++++++++++++++++++---------- 3 files changed, 39 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 1faecda..860120d 100644 --- a/README.md +++ b/README.md @@ -104,9 +104,15 @@ Once someone follows, the **Sharing** page's **What to post** section controls w - **Weekly summary**: play count and top artist(s), posted once a week (Monday 09:00 in the user's own time zone, for the Monday–Sunday week that just ended). A live preview on the same page shows what it would say so far. - **Milestones**: total scrobbles, an artist's plays, and a new entry into the all-time top 10 — each posted once, the first time it's reached. History already on file when sharing is turned on, or added by an import, is never posted about retroactively. -Both are on by default and can be switched off independently. Posts use the same visibility as the profile (followers only by default, or unlisted/public); the **Posts** page lists a user's own posts with delete (sends a `Delete` to whoever received it). "Now playing" isn't posted yet; see `docs/design/activitypub.md`. +Both are on by default and can be switched off independently. Posts use the same visibility as the profile (followers only by default, or unlisted/public); the **Posts** page lists a user's own posts with delete (sends a `Delete` to whoever received it). -Federation is tested in CI against a real GoToSocial server (`scripts/interop/run.sh`), including that a posted weekly summary reaches a follower's timeline with the right content and visibility, and disappears from it when deleted. +The Sharing page's **Now playing** section is a separate, three-way choice: + +- **Off** (default): nothing shown or posted. +- **Show on my profile**: a "Now playing: *Track* by Artist" field on the profile, refreshed at most every 5 minutes while something's playing and cleared a few minutes after it stops. A `GET` of the profile always shows the truth right now; the push is just so already-following servers don't have to ask. +- **Show on my profile and post**: the profile field, plus a post for each track played 30 seconds or more, at most one every 30 minutes, with the previous now-playing post deleted once the new one is confirmed published. + +Federation is tested in CI against a real GoToSocial server (`scripts/interop/run.sh`), including that a posted weekly summary reaches a follower's timeline with the right content and visibility and disappears from it when deleted, and that turning now playing on updates the field GoToSocial has cached for the profile. It's **off unless the server enables it**, and then **off for each user** until they switch it on under **Sharing**. To enable it: diff --git a/docs/design/activitypub-phase4.md b/docs/design/activitypub-phase4.md index fa27ccb..3dab2f3 100644 --- a/docs/design/activitypub-phase4.md +++ b/docs/design/activitypub-phase4.md @@ -1,5 +1,12 @@ # ActivityPub phase 4: now playing +**Status: done** on `feature/activitypub` (`7d86bad` … `9883111`). The GoToSocial interop test now covers now playing too: turning it on updates the "Now playing" field GoToSocial has cached for the profile, via the periodic `Update(Person)` push - not just a fresh fetch showing the live truth, which was already covered by the actor route's own tests. As with phases 1-3, a manual pass with a real Mastodon account through a tunnel is still to do before merging. + +Where this differed from the plan: + +- **The now-playing key had to be hashed, not raw.** `artist\x1ftrack\x1fstarted_at` was going straight into `federation_posts.key` (`VARCHAR(64)`), which real track and artist names routinely overflow. Caught by the first Postgres-backed test that used a real track name, not by anything in the plan itself. +- **`now_playing_field()` needed its own privacy gate.** It read core's `now_playing` table (populated for every user regardless of federation settings) without checking `now_playing_mode` itself, so a user who'd never turned the feature on at all would still leak what they were listening to if a caller forgot to gate it externally. Found while designing the periodic push task, not by a test written against the plan - the existing tests happened to never combine "something playing" with "mode off". Fixed by moving the gate inside `now_playing_field()` itself, so there's exactly one place that can get this wrong. + This implements phase 4 of [activitypub.md](activitypub.md): **now playing**, the last of the "still open" decisions there. It builds on [phase 3](activitypub-phase3.md): publishing, delivery and the web UI for posts. Chosen (of the doc's three options): **profile field, plus opt-in posts** — the profile field is what a user gets as soon as they turn now playing on at all; posts are a further, separate opt-in on top of that, matching the doc's own "profile field mode, then optional posts" framing. diff --git a/src/scrobbler/federation/README.md b/src/scrobbler/federation/README.md index cfd8b90..911f771 100644 --- a/src/scrobbler/federation/README.md +++ b/src/scrobbler/federation/README.md @@ -65,6 +65,7 @@ Every ActivityPub ID is built from `FEDERATION_BASE_URL`, never from the incomin | `openapi.py` | OpenAPI descriptions of `web.py`'s endpoints | | `metrics.py` | Federation's own Prometheus metrics | | `cli.py` | `flask federation ...` admin commands | +| `actors.py` | Builds a user's actor document body; shared by the live `GET /users/` route and the now-playing `Update(Person)` push, so both render the same shape | | `publishing/` | Posts: shared publish/delete machinery, and one module per kind (see below) | ## Publishing @@ -88,30 +89,41 @@ the text says, then calls into `base.py`: every threshold already passed without posting, called when a user turns sharing on and after an import finishes, so old history never produces a burst of "milestone" posts. +- `publishing/now_playing.py`: not quite the same shape as the other two, since it + covers two things at once - a throttled `Update(Person)` push for the profile field + (`actors.py` owns the live version shown on a plain `GET`) and, opt-in, a post per + track played 30+ seconds. Both are driven by one periodic scan + (`federation.now_playing`, every 30 seconds) rather than an event receiver: the + throttle windows (5 and 30 minutes) are far longer than the poll interval, and there's + no history to react to retroactively the way milestones does. -Adding a third kind (e.g. now playing) means adding another module here with the same -shape — decide when, build the text, call `publishing.publish()` — not touching -`base.py`. +Adding a fourth kind means adding another module here with the same shape as +`weekly.py`/`milestones.py` - decide when, build the text, call `publishing.publish()` +- not touching `base.py`. ## Worker tasks `federation.inbox` (process received activities), `federation.deliver` (send queued ones), `federation.inbox.maintenance` (re-queue stalled, prune after 30 days), `federation.gauges` (queue and follower gauges), `federation.milestones` (drain pending -milestone checks) and `federation.weekly` (check every sharing user for a due weekly -summary, every 15 minutes). All are registered only when federation is on. +milestone checks), `federation.weekly` (check every sharing user for a due weekly +summary, every 15 minutes) and `federation.now_playing` (push profile updates and posts +for users with it on, every 30 seconds). All are registered only when federation is on. ## Interop `scripts/interop/run.sh` runs Scrobbler against a real GoToSocial server on a private `.test` network. `scripts/interop/gotosocial_interop.py` checks the whole follow life -cycle, then `run.sh` seeds a scrobble, runs `flask federation post-weekly --now` directly -in the `api` container, and runs the driver a second time (`--check-posts`) to confirm -the post reaches GoToSocial's home timeline with the right content and `private` -(followers-only) visibility, and disappears from it once deleted. CI runs the whole -thing on every push. GoToSocial 0.22.1 ignores a Reject of an already-accepted follow (a -TODO in its code, fixed on its main branch), so that one check on its side is skipped -until a release includes the fix. +cycle, then `run.sh` seeds a scrobble and a now-playing track, runs +`flask federation post-weekly --now` directly in the `api` container, and runs the +driver a second time (`--check-posts`) to confirm: the post reaches GoToSocial's home +timeline with the right content and `private` (followers-only) visibility and +disappears from it once deleted; and, with now playing turned on, GoToSocial's own +stored copy of the account (not a fresh `resolve()` fetch) picks up a "Now playing" +field from the periodic `Update(Person)` push. CI runs the whole thing on every push. +GoToSocial 0.22.1 ignores a Reject of an already-accepted follow (a TODO in its code, +fixed on its main branch), so that one check on its side is skipped until a release +includes the fix. ## Migrations From 9ca2ace8543b8b2584eefebb216f0b7e46967bf7 Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 23:42:58 +0100 Subject: [PATCH 55/56] Manual tunnel test: two real bugs found and fixed, docs marked done Ran the manual pass with a real Mastodon account through a cloudflared tunnel - the one gap every phase doc had flagged as outstanding before merging. WebFinger, actor resolution, follow/unfollow/approve/block, a forced weekly summary posting and deleting, and the now-playing profile field appearing/clearing all worked correctly against mastodon.social and activitypub.academy. Two real bugs found along the way, both fixed here: - docker-compose.yml hardcoded the api/worker services' CORS_ORIGINS to UI_BASE_URL. Pointing UI_BASE_URL at the tunnel host (needed for federation's own identity) silently changed which browser origins the API accepted, blocking the operator's own localhost:8080 UI - .env's own CORS_ORIGINS setting had no effect, since the compose file never referenced it. Now its own variable, same default. - TestConfig wasn't isolating UI_BASE_URL/CORS_ORIGINS from a developer's .env, so the same local change broke six tests that assert on http://localhost:8080 URLs - the same class of gap an earlier session found and fixed for FEDERATION_ENABLED/ LASTFM_API_KEY. Pinned alongside them. Marked the manual pass done in each phase doc (1-4) and the overview. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docker-compose.yml | 2 +- docs/design/activitypub-phase1.md | 2 +- docs/design/activitypub-phase2.md | 2 +- docs/design/activitypub-phase3.md | 2 +- docs/design/activitypub-phase4.md | 6 +++++- docs/design/activitypub.md | 2 +- src/scrobbler/config.py | 6 ++++-- 7 files changed, 14 insertions(+), 8 deletions(-) diff --git a/docker-compose.yml b/docker-compose.yml index adadcb7..a36c6b8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -29,7 +29,7 @@ services: environment: DATABASE_URL: postgresql+psycopg://scrobbler:${POSTGRES_PASSWORD:-scrobbler}@db:5432/scrobbler SECRET_KEY: ${SECRET_KEY:-change-me} - CORS_ORIGINS: ${UI_BASE_URL:-http://localhost:8080} + CORS_ORIGINS: ${CORS_ORIGINS:-http://localhost:8080} UI_BASE_URL: ${UI_BASE_URL:-http://localhost:8080} WEB_CONCURRENCY: ${WEB_CONCURRENCY:-2} FORWARDED_ALLOW_IPS: "*" diff --git a/docs/design/activitypub-phase1.md b/docs/design/activitypub-phase1.md index 4ef2dc0..1d41deb 100644 --- a/docs/design/activitypub-phase1.md +++ b/docs/design/activitypub-phase1.md @@ -1,6 +1,6 @@ # ActivityPub phase 1: discoverable profile -**Status: done** on `feature/activitypub` (`98c6554` … `913ef67`). The one gap is the manual check with a real Mastodon account through a tunnel: it's still to do, and needs a public HTTPS address. +**Status: done** on `feature/activitypub` (`98c6554` … `913ef67`). The manual check with a real Mastodon account through a tunnel (`cloudflared`) is also done: WebFinger, the actor and the key all resolved correctly from mastodon.social and activitypub.academy. This implements phase 1 of [activitypub.md](activitypub.md). Handles and actor URLs are on the **UI's domain**, and posts are **followers only by default** (a per-user setting). diff --git a/docs/design/activitypub-phase2.md b/docs/design/activitypub-phase2.md index 6050d80..eb219e9 100644 --- a/docs/design/activitypub-phase2.md +++ b/docs/design/activitypub-phase2.md @@ -1,6 +1,6 @@ # ActivityPub phase 2: followers -**Status: done** on `feature/activitypub` (`a6d3fb6` … `fe95f59`). The GoToSocial interop test passes locally and in CI. Before merging, the plan still calls for a manual pass with a real Mastodon account through a tunnel. +**Status: done** on `feature/activitypub` (`a6d3fb6` … `fe95f59`). The GoToSocial interop test passes locally and in CI. The manual pass with a real Mastodon account through a tunnel is also done: follow, unfollow, manual approval, and block/unblock all worked correctly. Where this differed from the plan: diff --git a/docs/design/activitypub-phase3.md b/docs/design/activitypub-phase3.md index cfe57e3..3285cd1 100644 --- a/docs/design/activitypub-phase3.md +++ b/docs/design/activitypub-phase3.md @@ -1,6 +1,6 @@ # ActivityPub phase 3: posts -**Status: done** on `feature/activitypub` (`bc717c2` … `860d4d0`). The GoToSocial interop test now covers posts too: a weekly summary reaches a follower's home timeline as `private` with the expected content, and disappears from it when deleted. As with phases 1-2, a manual pass with a real Mastodon account through a tunnel is still to do before merging. +**Status: done** on `feature/activitypub` (`bc717c2` … `860d4d0`). The GoToSocial interop test now covers posts too: a weekly summary reaches a follower's home timeline as `private` with the expected content, and disappears from it when deleted. The manual pass with a real Mastodon account through a tunnel (done alongside phase 4's, see its notes) confirmed a forced weekly summary posted and deleted correctly there too. Where this differed from the plan: diff --git a/docs/design/activitypub-phase4.md b/docs/design/activitypub-phase4.md index 3dab2f3..ccef145 100644 --- a/docs/design/activitypub-phase4.md +++ b/docs/design/activitypub-phase4.md @@ -1,11 +1,15 @@ # ActivityPub phase 4: now playing -**Status: done** on `feature/activitypub` (`7d86bad` … `9883111`). The GoToSocial interop test now covers now playing too: turning it on updates the "Now playing" field GoToSocial has cached for the profile, via the periodic `Update(Person)` push - not just a fresh fetch showing the live truth, which was already covered by the actor route's own tests. As with phases 1-3, a manual pass with a real Mastodon account through a tunnel is still to do before merging. +**Status: done** on `feature/activitypub` (`7d86bad` … `9883111`, plus a `docker-compose.yml` fix from the manual pass below). The GoToSocial interop test now covers now playing too: turning it on updates the "Now playing" field GoToSocial has cached for the profile, via the periodic `Update(Person)` push - not just a fresh fetch showing the live truth, which was already covered by the actor route's own tests. + +The manual pass with a real Mastodon account through a tunnel (the last standing gap after every phase) is also done now, covering phases 1-4 together: WebFinger, actor and follow/unfollow/approve/block against mastodon.social and activitypub.academy over a `cloudflared` tunnel, a forced weekly summary posting and deleting correctly, and the now-playing profile field appearing, clearing, and respecting the 5-minute push throttle. Where this differed from the plan: - **The now-playing key had to be hashed, not raw.** `artist\x1ftrack\x1fstarted_at` was going straight into `federation_posts.key` (`VARCHAR(64)`), which real track and artist names routinely overflow. Caught by the first Postgres-backed test that used a real track name, not by anything in the plan itself. - **`now_playing_field()` needed its own privacy gate.** It read core's `now_playing` table (populated for every user regardless of federation settings) without checking `now_playing_mode` itself, so a user who'd never turned the feature on at all would still leak what they were listening to if a caller forgot to gate it externally. Found while designing the periodic push task, not by a test written against the plan - the existing tests happened to never combine "something playing" with "mode off". Fixed by moving the gate inside `now_playing_field()` itself, so there's exactly one place that can get this wrong. +- **`docker-compose.yml` hardcoded the API's `CORS_ORIGINS` to `UI_BASE_URL`.** Found during the manual pass: pointing `UI_BASE_URL` at the tunnel host (needed for federation's own identity) silently changed which browser origins the API accepted, blocking the operator's own `localhost:8080` UI from calling it at all - an `.env` `CORS_ORIGINS` setting had no effect, since the compose file never referenced it. Fixed by making `CORS_ORIGINS` its own variable, defaulting the same as before. +- **`TestConfig` wasn't isolating `UI_BASE_URL`/`CORS_ORIGINS` either.** The same local `.env` change broke six tests that assert on `http://localhost:8080` URLs, the same way an earlier session found `FEDERATION_ENABLED`/`LASTFM_API_KEY` leaking from a developer's `.env` into the test run. Pinned alongside them. This implements phase 4 of [activitypub.md](activitypub.md): **now playing**, the last of the "still open" decisions there. It builds on [phase 3](activitypub-phase3.md): publishing, delivery and the web UI for posts. diff --git a/docs/design/activitypub.md b/docs/design/activitypub.md index 9a83579..9ae59ff 100644 --- a/docs/design/activitypub.md +++ b/docs/design/activitypub.md @@ -337,7 +337,7 @@ Everything goes on the existing Prometheus and Grafana setup: - visibility addressing - **In-process federation**: two Scrobbler instances in one test process following each other. - **A real peer in CI**: a [GoToSocial](https://gotosocial.org) container, which is a single binary with SQLite. It follows a Scrobbler user and we assert that it receives the `Accept` and the posts. That's much lighter than running Mastodon in CI. -- **Manual pass before release**: +- **Manual pass before release** (done, over a `cloudflared` tunnel - see [phase 4](activitypub-phase4.md)): - follow from a real Mastodon account - check the profile, posts, profile-field updates and unfollowing - check with [verify.funfedi.dev](https://verify.funfedi.dev/) or the [ActivityPub Academy](https://activitypub.academy/) diff --git a/src/scrobbler/config.py b/src/scrobbler/config.py index 667c759..b16a5d0 100644 --- a/src/scrobbler/config.py +++ b/src/scrobbler/config.py @@ -76,7 +76,9 @@ class TestConfig(Config): "postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test", ) START_METRICS_SERVER = False - # Tests never inherit optional features from a developer's .env or environment; - # tests that need them turn them on explicitly. + # Tests never inherit optional features or URLs from a developer's .env or + # environment; tests that need them turn them on, or override them, explicitly. LASTFM_API_KEY = "" FEDERATION_ENABLED = "0" + UI_BASE_URL = "http://localhost:8080" + CORS_ORIGINS = ["http://localhost:8080"] From b941a17e0738010f97b601a0731f71890f21dfac Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Sat, 26 Sep 2026 23:46:48 +0100 Subject: [PATCH 56/56] Split docs into deploy, setup and usage guides README had grown into one long file covering deployment, local development and end-user features together. Split into: - docs/deploy.md: running a real instance - images, configuration, putting it behind TLS (with a minimal Caddy example and the CORS_ORIGINS/UI_BASE_URL distinction the last session's manual test found the hard way), monitoring, backups, releases. - docs/setup.md: working on the code - local dev environment, migrations, tests, the manual fediverse test, CI/CD. - docs/usage.md: accounts and apps, connecting a player, importing history, sharing on the fediverse. README is now a short overview and quick start that links to the three, plus the existing API reference and federation/design docs. Co-Authored-By: Claude Sonnet 5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- README.md | 219 ++++++------------------------------------------- docs/deploy.md | 145 ++++++++++++++++++++++++++++++++ docs/setup.md | 105 ++++++++++++++++++++++++ docs/usage.md | 94 +++++++++++++++++++++ 4 files changed, 367 insertions(+), 196 deletions(-) create mode 100644 docs/deploy.md create mode 100644 docs/setup.md create mode 100644 docs/usage.md diff --git a/README.md b/README.md index 860120d..d2f9dd2 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,10 @@ # Scrobbler -A self-hosted music scrobbling service. It speaks the **Last.fm (Audioscrobbler 2.0) API**, so players and scrobblers that let you set a custom Last.fm server can use it unchanged. It also has a web UI for your listening history. +A self-hosted music scrobbling service. It speaks the **Last.fm (Audioscrobbler 2.0) API**, +so players and scrobblers that let you set a custom Last.fm server can use it unchanged. +It also has a web UI for your listening history, and optional sharing on the fediverse +(ActivityPub) — followable from Mastodon, with weekly summaries, milestones and now +playing. ``` players / scrobblers ──► API /2.0/ Last.fm-compatible @@ -9,208 +13,31 @@ web UI (static files) ──► API /api/v1/ JSON API for the UI Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana ``` -- **API** (`src/scrobbler/`): Flask under gunicorn. It is API-only and serves no pages. -- **Web UI** (`frontend/`): plain HTML, CSS and JavaScript with no build step. Host it anywhere static files can be served. -- **Docs**: OpenAPI at `/api/openapi.json`, Swagger UI at `/api/docs` and ReDoc at `/api/redoc`. A copy of the spec is committed at `docs/openapi.json`. -- **Worker**: `flask worker` runs background work, such as importing Last.fm history from export files or straight from Last.fm. -- **Monitoring**: Prometheus metrics, four provisioned Grafana dashboards, and alert rules. +## Docs -## Run it +- **[Deploy](docs/deploy.md)** — running a real instance: images, configuration, TLS, + monitoring, backups, releases. +- **[Set up](docs/setup.md)** — working on the code: local dev environment, migrations, + tests, CI/CD. +- **[Use](docs/usage.md)** — accounts and apps, connecting a player, importing history, + sharing on the fediverse. +- **API reference**: `/api/openapi.json`, Swagger UI at `/api/docs`, ReDoc at + `/api/redoc` (a copy is committed at `docs/openapi.json`). +- **Federation internals**: `src/scrobbler/federation/README.md`. Design docs for how it + was built: `docs/design/`. + +## Try it ```sh cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD docker compose up -d # db, api (:5050), worker, ui (:8080) -docker compose --profile monitoring up -d # + Prometheus (:9090), Grafana (:3000) ``` -Open http://localhost:8080, create an account, then go to **Apps** and create an app for each player. - -To run the published images instead of building them locally: - -```sh -SCROBBLER_IMAGE_TAG=main docker compose up -d --no-build -``` - -The images are `pkgs.daubney.dev/scrobbler/scrobbler-api` and `pkgs.daubney.dev/scrobbler/scrobbler-ui`. - -### Configuration - -| Variable | Used by | Default | Purpose | -|---|---|---|---| -| `DATABASE_URL` | api | local Postgres | SQLAlchemy URL (`postgresql+psycopg://…`) | -| `SECRET_KEY` | api | `dev-insecure-secret` | Flask secret | -| `CORS_ORIGINS` | api | `http://localhost:8080` | Comma-separated UI origins allowed to call `/api/v1` | -| `UI_BASE_URL` | api | `http://localhost:8080` | Where `/api/auth/` sends users to approve desktop sign-ins | -| `OPENAPI_DOCS_ENABLED` | api | `1` | Set to `0` to hide `/api/docs` and `/api/redoc` | -| `METRICS_PORT` | api | `9100` | Prometheus metrics port (keep it off the public network) | -| `WEB_CONCURRENCY` | api | `2` | gunicorn workers | -| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start | -| `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) | -| `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted | -| `WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port (`IMPORT_WORKER_METRICS_PORT` still works) | -| `API_BASE_URL` | ui image | `http://localhost:5050` | API location, written into `config.js` and the CSP | - -In `docker compose` the host ports are set with `DB_PORT`, `API_PORT`, `UI_PORT`, `PROMETHEUS_PORT` and `GRAFANA_PORT`. - -## Connecting a player - -In the player's scrobbling settings, choose a custom or self-hosted Last.fm server and enter: - -- **API URL**: `https://your-host/2.0/` -- **API key and shared secret**: from an app on the **Apps** page -- **Username and password**: your Scrobbler account - -Two ways of signing in are supported: - -- **Mobile**: `auth.getMobileSession` with a username and password, sent as a POST body over HTTPS. -- **Desktop**: `auth.getToken`, then the user approves at `/api/auth/` (which redirects to the web UI), then `auth.getSession`. - -The legacy `authToken = md5(username + md5(password))` form is **not supported**, because checking it would mean storing unsalted password hashes. pylast's `password_hash` option uses that form. With pylast, use `SessionKeyGenerator` (the desktop flow) instead. - -Supported methods: - -- `auth.getMobileSession`, `auth.getToken`, `auth.getSession` -- `track.scrobble` (up to 50 per request), `track.updateNowPlaying` -- `user.getInfo`, `user.getRecentTracks`, `user.getTopArtists`, `user.getTopAlbums`, `user.getTopTracks` - -`/api/docs` lists the parameters, rules and example responses for each method. - -Scrobbles are ignored (not rejected) if the artist or track is empty, or if the timestamp is more than 14 days old or more than 5 minutes in the future. Sending the same scrobble again is accepted and stored once, so client retries are safe. - -## Importing Last.fm history - -Open **Import** in the web UI. You can import from: - -- **An export file**: - - CSV from [lastfm-to-csv](https://benjaminbenben.com/lastfm-to-csv/), with no header row and artist, album, track and date columns. - - Any CSV or TSV with a header row naming artist, track and a date or Unix-time column. Comma, semicolon and tab delimiters all work. - - A JSON export of `user.getRecentTracks` pages (such as lastfm.ghan.nl's), a single `recenttracks` response, or a flat list of tracks. - - Files can be gzipped. -- **Last.fm directly**: enter a Last.fm username and the worker pages through that account's public history. This option only appears when the server has `LASTFM_API_KEY` set. - -Imports run in the background in the `worker` service. The page shows progress, and an import can be cancelled. - -Unlike live scrobbles, imports keep plays of any age. They still skip rows with no artist or track, and plays dated in the future. Plays already in your history are skipped, so importing again is safe. - -## Sharing on the fediverse - -Users can make their profile findable from Mastodon and other fediverse apps as `@name@`, and be followed: - -- Follows are accepted automatically, or wait for approval if the user turns that on. -- The **Followers** page lists requests, followers and blocked accounts, with approve, decline, remove, block and unblock. - -Once someone follows, the **Sharing** page's **What to post** section controls what they see: - -- **Weekly summary**: play count and top artist(s), posted once a week (Monday 09:00 in the user's own time zone, for the Monday–Sunday week that just ended). A live preview on the same page shows what it would say so far. -- **Milestones**: total scrobbles, an artist's plays, and a new entry into the all-time top 10 — each posted once, the first time it's reached. History already on file when sharing is turned on, or added by an import, is never posted about retroactively. - -Both are on by default and can be switched off independently. Posts use the same visibility as the profile (followers only by default, or unlisted/public); the **Posts** page lists a user's own posts with delete (sends a `Delete` to whoever received it). - -The Sharing page's **Now playing** section is a separate, three-way choice: - -- **Off** (default): nothing shown or posted. -- **Show on my profile**: a "Now playing: *Track* by Artist" field on the profile, refreshed at most every 5 minutes while something's playing and cleared a few minutes after it stops. A `GET` of the profile always shows the truth right now; the push is just so already-following servers don't have to ask. -- **Show on my profile and post**: the profile field, plus a post for each track played 30 seconds or more, at most one every 30 minutes, with the previous now-playing post deleted once the new one is confirmed published. - -Federation is tested in CI against a real GoToSocial server (`scripts/interop/run.sh`), including that a posted weekly summary reaches a follower's timeline with the right content and visibility and disappears from it when deleted, and that turning now playing on updates the field GoToSocial has cached for the profile. - -It's **off unless the server enables it**, and then **off for each user** until they switch it on under **Sharing**. To enable it: - -1. Set these on the API and worker: - - `FEDERATION_ENABLED=1` - - `FEDERATION_DOMAIN`: the UI's host, e.g. `scrobble.example` - - `FEDERATION_BASE_URL`: the UI's origin, e.g. `https://scrobble.example` - - `FEDERATION_KEY_SECRET`: 32 or more random characters -2. Give the UI container `API_INTERNAL_URL` (compose sets `http://api:8000`). It then forwards these paths to the API: `/.well-known/webfinger`, `/.well-known/nodeinfo`, `/.well-known/host-meta`, `/nodeinfo/`, `/users/`, `/inbox` and `/actor`. -3. Serve the UI over HTTPS on that domain. Other servers only talk to HTTPS. - -Handles and actor URLs **can't change once anyone follows** a user, so choose the domain carefully. - -`FEDERATION_KEY_SECRET` encrypts each user's signing key. **Back it up, and never change it**: losing it means users' keys can't be read, and followers would have to follow again. - -Optional settings: - -- `FEDERATION_BLOCKED_DOMAINS`: comma-separated domains, including subdomains, whose deliveries and follows are refused. -- `FEDERATION_DELIVERY_CONCURRENCY`: parallel outgoing deliveries per worker (default 4). -- `FEDERATION_SIGNATURE_SCHEMES`: the signing order (default `draft-cavage,rfc9421`). - -The worker must be running: it processes incoming activities and delivers outgoing ones. - -## Develop - -```sh -docker compose up -d db # Postgres with a scrobbler_test database -uv sync -uv run flask --app scrobbler db upgrade heads -uv run flask --app scrobbler run --port 5050 # API (port 5000 is taken by AirPlay on macOS) -python -m http.server 8080 -d frontend # UI -uv run flask --app scrobbler worker # background work (imports, …) -uv run pytest # needs TEST_DATABASE_URL (see .env.example) -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 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. - -## Monitoring - -The API serves Prometheus metrics on `METRICS_PORT`, summed across gunicorn workers. All series are prefixed `scrobbler_`: - -- **HTTP**: request rate, errors and latency per endpoint -- **Last.fm**: calls, errors by Last.fm error code, and authentication failures by reason -- **Scrobbles**: accepted, duplicate and ignored (with the reason), batch size, and how late scrobbles arrive -- **Database**: query latency and connection-pool use -- **Users**: registered, active, and listening now (computed from the database and cached for 60s) - -Labels never contain users, keys or track names. - -With the `monitoring` profile, Grafana (admin password `GRAFANA_ADMIN_PASSWORD`) has a **Scrobbler** folder with four dashboards: - -- API overview -- Last.fm API -- Usage -- Database - -Alert rules live in `deploy/prometheus/alerts.yml`: - -- API down -- import worker down, or imports left waiting -- 5xx ratio -- p95 latency -- authentication-failure spike -- ignored-scrobble ratio -- database pool saturated -- Postgres down - -They're evaluated by Prometheus and appear in Grafana. Nothing routes them anywhere yet; that needs Alertmanager. - -Tests check that every metric a dashboard or alert uses actually exists. - -## CI/CD (Gitea Actions) - -Everything runs from `.gitea/workflows/ci.yml`: - -- **Every push and PR**: - - lint - - the migrations check - - tests against Postgres - - `promtool` checks of the Prometheus config and alert rules -- **Pushes to `main` and `v*` tags**, once every check has passed: - - both images are pushed to the ProGet `scrobbler` Docker feed. `main` builds are tagged `main` and `sha-`; tags are tagged ``, `latest` and `sha-`. - - the OpenAPI spec, dashboards and Prometheus config are uploaded to the `scrobbler-assets` feed under `scrobbler//` or `scrobbler/main/`. -- **`v*` tags** also publish the wheel and sdist to the `scrobbler-python` PyPI feed, as the `scrobby` distribution. The import name is `scrobbler`. (`scrobbler` on public PyPI is an unrelated project.) -- **Every run** is posted to the `ScrobblingService` topic on notify.daubney.dev. - -The workflow needs these repository secrets and variables: - -- **Secrets**: `PKGS_USER`, `PKGS_PASSWORD`, `PKGS_API_KEY`, `NTFY_USER`, `NTFY_PASSWORD` -- **Variables**: `PKGS_HOST`, `PKGS_DOCKER_FEED`, `PKGS_PYPI_FEED`, `PKGS_ASSET_FEED`, `NTFY_URL`, `NTFY_TOPIC` - -To release, tag `vX.Y.Z` on `main` and push the tag. The tag sets the package and image version. +Open http://localhost:8080, create an account, then go to **Apps** and create an app for +a player. See [docs/deploy.md](docs/deploy.md) for the published images, full +configuration reference and production notes. ## Licence -BSD 3-Clause; see [LICENSE](LICENSE). The fonts vendored in `frontend/fonts/` are under the SIL Open Font License 1.1. +BSD 3-Clause; see [LICENSE](LICENSE). The fonts vendored in `frontend/fonts/` are under +the SIL Open Font License 1.1. diff --git a/docs/deploy.md b/docs/deploy.md new file mode 100644 index 0000000..9f9cd84 --- /dev/null +++ b/docs/deploy.md @@ -0,0 +1,145 @@ +# Deploying Scrobbler + +This covers running a real instance: the published images, configuration, putting it +behind TLS, monitoring, backups and releases. For running the code locally to work on +it, see [setup.md](setup.md). For what the service does once it's running, see +[usage.md](usage.md). + +## Services + +``` +players / scrobblers ──► API /2.0/ Last.fm-compatible +web UI (static files) ──► API /api/v1/ JSON API for the UI + API ──► PostgreSQL +Prometheus ◄── API :9100/metrics, postgres-exporter ──► Grafana +``` + +- **`api`**: Flask under gunicorn. API-only; it serves no HTML pages. +- **`ui`**: nginx serving the static frontend (`frontend/`, no build step). +- **`worker`**: `flask worker` — history imports and background tasks for optional + modules (federation's deliveries, scheduled posts, and so on). +- **`db`**: PostgreSQL. +- With the `monitoring` profile: `prometheus`, `grafana`, `postgres-exporter`. + +## Quick start + +```sh +cp .env.example .env # then set SECRET_KEY and POSTGRES_PASSWORD +SCROBBLER_IMAGE_TAG=main docker compose up -d --no-build # or drop --no-build to build locally +``` + +Open `http://localhost:8080`, create an account, then go to **Apps** and create an app +for each player. Add `--profile monitoring` for Prometheus and Grafana. + +Published images: `pkgs.daubney.dev/scrobbler/scrobbler-api` and +`pkgs.daubney.dev/scrobbler/scrobbler-ui`, tagged `main` (latest push to `main`), +`sha-`, and ``/`latest` for tagged releases. + +## Configuration + +| Variable | Used by | Default | Purpose | +|---|---|---|---| +| `DATABASE_URL` | api | local Postgres | SQLAlchemy URL (`postgresql+psycopg://…`) | +| `SECRET_KEY` | api | `dev-insecure-secret` | Flask secret — set a real one | +| `CORS_ORIGINS` | api | `http://localhost:8080` | Comma-separated origins allowed to call `/api/v1`: wherever browsers actually load the UI from | +| `UI_BASE_URL` | api | `http://localhost:8080` | Where `/api/auth/` sends users to approve desktop sign-ins, and (with federation on) the public identity users are found under | +| `OPENAPI_DOCS_ENABLED` | api | `1` | Set to `0` to hide `/api/docs` and `/api/redoc` | +| `METRICS_PORT` | api | `9100` | Prometheus metrics port — keep it off the public network | +| `WEB_CONCURRENCY` | api | `2` | gunicorn workers | +| `RUN_MIGRATIONS` | api image | `1` | Apply database migrations on start | +| `LASTFM_API_KEY` | api, worker | *(unset)* | Enables importing straight from Last.fm ([get a key](https://www.last.fm/api/account/create)) | +| `IMPORT_MAX_BYTES` | api | 200 MB | Largest export file accepted | +| `WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port | +| `API_BASE_URL` | ui image | `http://localhost:5050` | Where the browser reaches the API — written into `config.js` and the CSP | + +In `docker compose`, host ports are set with `DB_PORT`, `API_PORT`, `UI_PORT`, +`PROMETHEUS_PORT` and `GRAFANA_PORT`. + +`CORS_ORIGINS` and `UI_BASE_URL` answer different questions and can differ: the first is +*which browser origins may call the JSON API*, the second is *where the public identity +and sign-in redirects point*. Don't assume setting one sets the other — `docker-compose.yml` +passes them through independently. + +### Fediverse sharing (optional) + +Off unless the server enables it, and then off for each user until they turn it on: + +1. Set on the **api** and **worker**: + - `FEDERATION_ENABLED=1` + - `FEDERATION_DOMAIN`: the UI's host, e.g. `scrobble.example` + - `FEDERATION_BASE_URL`: the UI's origin, e.g. `https://scrobble.example` + - `FEDERATION_KEY_SECRET`: 32+ random characters +2. Give the **ui** container `API_INTERNAL_URL` (compose sets `http://api:8000`). It + forwards these paths to the API: `/.well-known/webfinger`, `/.well-known/nodeinfo`, + `/.well-known/host-meta`, `/nodeinfo/`, `/users/`, `/inbox` and `/actor`. +3. Serve the UI over **real HTTPS** on that domain — other fediverse servers only talk to + HTTPS, and won't accept a self-signed certificate. + +Handles and actor URLs **can't change once anyone follows a user**, so choose the domain +carefully before enabling this in production. + +`FEDERATION_KEY_SECRET` encrypts every user's signing key. **Back it up, and never +change it**: losing it means users' keys can't be read, and followers would have to +follow again. + +Optional: `FEDERATION_BLOCKED_DOMAINS` (comma-separated, subdomains included), +`FEDERATION_DELIVERY_CONCURRENCY` (default 4), `FEDERATION_SIGNATURE_SCHEMES` (default +`draft-cavage,rfc9421`). The `worker` service must be running — it delivers outgoing +activities and processes incoming ones. + +## Putting it behind TLS + +Scrobbler itself only speaks plain HTTP; something in front of it needs to terminate +TLS. Any reverse proxy works — nginx, Caddy, or a tunnel like Cloudflare Tunnel for +testing without a public IP (see `docs/design/activitypub-phase4.md` for how the +project's own manual federation test used one). A minimal Caddy example, proxying +everything to the `ui` container (which itself forwards the fediverse paths to `api`): + +``` +scrobble.example { + reverse_proxy localhost:8080 +} +``` + +Point `UI_BASE_URL`/`FEDERATION_BASE_URL`/`FEDERATION_DOMAIN` at that same public +`https://scrobble.example` origin. The API (`API_PORT`, default 5050) doesn't need its +own public hostname unless you want browsers to reach it directly instead of through the +UI's proxy — set `API_BASE_URL` accordingly either way, since the browser calls it +directly for `/api/v1`. + +## Monitoring + +The API serves Prometheus metrics on `METRICS_PORT`, summed across gunicorn workers. All +series are prefixed `scrobbler_`: HTTP request rate/errors/latency, Last.fm calls and +auth failures, scrobble outcomes, database query latency and pool use, and gauges for +registered/active/currently-listening users. Labels never contain usernames, API keys or +track names. + +With `--profile monitoring`, Grafana (`GRAFANA_ADMIN_PASSWORD`) provisions a +**Scrobbler** folder with dashboards for API overview, Last.fm API, usage, database and +(with federation on) federation. Alert rules live in `deploy/prometheus/alerts.yml` — +evaluated by Prometheus and visible in Grafana, but nothing routes them anywhere without +Alertmanager. + +## Backups + +Back up, at minimum: + +- The Postgres database (all scrobble history, accounts, federation state). +- `FEDERATION_KEY_SECRET`, if federation is on — it's the only thing that can decrypt + stored signing keys, and it's never derivable from the database alone. + +## Releases + +Gitea Actions (`.gitea/workflows/ci.yml`) builds and publishes on every push to `main` +and on `v*` tags, once lint, tests and the Prometheus config checks all pass: + +- Both images push to the ProGet `scrobbler` Docker feed. +- The OpenAPI spec, dashboards and Prometheus config upload to the `scrobbler-assets` + feed. +- `v*` tags also publish the wheel/sdist to the `scrobbler-python` PyPI feed (as + `scrobby`; `scrobbler` on public PyPI is an unrelated project). + +To release: tag `vX.Y.Z` on `main` and push the tag. That tag sets both the package and +image version. See [setup.md](setup.md) for the secrets/variables the workflow needs and +how to run it locally before tagging. diff --git a/docs/setup.md b/docs/setup.md new file mode 100644 index 0000000..5043dcb --- /dev/null +++ b/docs/setup.md @@ -0,0 +1,105 @@ +# Working on Scrobbler + +Setting up a local development environment. For running a real instance, see +[deploy.md](deploy.md). For what the service does, see [usage.md](usage.md). + +## Prerequisites + +- [uv](https://docs.astral.sh/uv/) for Python dependencies +- Docker, for Postgres (and optionally the full stack) + +## Get running + +```sh +docker compose up -d db # Postgres, with a scrobbler_test database too +uv sync +uv run flask --app scrobbler db upgrade heads +uv run flask --app scrobbler run --port 5050 # API (port 5000 is taken by AirPlay on macOS) +python -m http.server 8080 -d frontend # UI +uv run flask --app scrobbler worker # background work: imports, federation deliveries, … +``` + +`TEST_DATABASE_URL` (see `.env.example`) points the test suite at `scrobbler_test`. + +```sh +uv run pytest +uv run ruff check && uv run ruff format --check +``` + +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, checking that metrics aggregate across +workers. `TestConfig` pins every setting a developer might have in their own `.env` +(`FEDERATION_ENABLED`, `LASTFM_API_KEY`, `UI_BASE_URL`, `CORS_ORIGINS`, …) so a local +`.env` used for manual testing can never change what the test suite exercises — if you +add a new setting that a test might reasonably assert an exact value for, pin it there +too rather than relying on its default. + +## Migrations + +Two Alembic branches, `core` and `federation`, so federation's tables can be changed or +dropped without touching core ones: + +```sh +uv run flask --app scrobbler db migrate --head core@head -m "…" # core models +uv run flask --app scrobbler db migrate --head federation@head -m "…" # federation models +uv run flask --app scrobbler db upgrade heads # apply both +``` + +CI fails if the models and migrations disagree. See +`src/scrobbler/federation/README.md` for more on the federation branch specifically +(it also enforces that federation stays an optional, replaceable module — an +AST-based boundary test checks what it's allowed to import). + +## API docs + +After changing an endpoint: + +```sh +uv run python -m scrobbler.openapi.export docs/openapi.json +``` + +It documents the API with every optional module (federation included) switched on. A +test fails if the committed spec is stale, if any route is missing from it, or if any UI +route is missing its bearer-auth declaration. + +## Useful scripts + +- `uv run python scripts/generate_traffic.py --minutes 5` — sends a realistic mix of + scrobbles and errors, so the Grafana dashboards have something to show. +- `scripts/interop/run.sh` — runs Scrobbler against a real GoToSocial server on a private + network and checks the whole federation follow/post/now-playing life cycle end to end. + CI runs this on every push; run it locally the same way before changing anything in + `scrobbler.federation`. + +## Manual fediverse test + +The interop test above proves the protocol works against one real server on a private +network. It can't prove WebFinger resolves from the public internet, or that a real +Mastodon instance renders things sensibly. Before merging federation changes that touch +anything user-visible, do a manual pass with a real account through a tunnel +(`cloudflared tunnel --url http://localhost:8080` needs no account for a quick HTTPS +URL) — see `docs/design/activitypub-phase4.md` for what was checked and two real bugs +that manual pass caught that no automated test had. + +## CI/CD + +Everything runs from `.gitea/workflows/ci.yml`: + +- **Every push and PR**: lint, the migrations-vs-models check, tests against Postgres, + and `promtool` checks of the Prometheus config and alert rules. +- **Pushes to `main` and tags**, once those all pass: images and assets publish (see + [deploy.md](deploy.md#releases)). +- **Every run** posts to the `ScrobblingService` topic on notify.daubney.dev. + +Repository secrets: `PKGS_USER`, `PKGS_PASSWORD`, `PKGS_API_KEY`, `NTFY_USER`, +`NTFY_PASSWORD`. Variables: `PKGS_HOST`, `PKGS_DOCKER_FEED`, `PKGS_PYPI_FEED`, +`PKGS_ASSET_FEED`, `NTFY_URL`, `NTFY_TOPIC`. + +## Conventions + +- Keep the web UI (`frontend/`) entirely outside the API stack: Flask serves JSON only, + never HTML. +- Every endpoint needs an OpenAPI entry and Prometheus metrics; every new dashboard + metric needs a Grafana panel (or an existing one it plausibly extends). +- Commit at logical checkpoints through a piece of work, not only at the end. +- BSD-3-Clause licensed; avoid GPL/AGPL dependencies. diff --git a/docs/usage.md b/docs/usage.md new file mode 100644 index 0000000..3afcf9a --- /dev/null +++ b/docs/usage.md @@ -0,0 +1,94 @@ +# Using Scrobbler + +What the service does, once it's running. For getting an instance running, see +[deploy.md](deploy.md); for working on the code, see [setup.md](setup.md). + +## Account and apps + +Register in the web UI, then go to **Apps** and create one app per player or scrobbler +client you use — each gets its own API key and shared secret, and can be revoked on its +own from the **Sessions** page without affecting the others. + +## Connecting a player + +In the player's scrobbling settings, choose a custom or self-hosted Last.fm server: + +- **API URL**: `https://your-host/2.0/` +- **API key and shared secret**: from an app on the **Apps** page +- **Username and password**: your Scrobbler account + +Two sign-in flows are supported: + +- **Mobile**: `auth.getMobileSession` with a username and password, sent as a POST body + over HTTPS. +- **Desktop**: `auth.getToken`, then the user approves at `/api/auth/` (redirects to the + web UI), then `auth.getSession`. + +The legacy `authToken = md5(username + md5(password))` form isn't supported — checking +it would mean storing unsalted password hashes. pylast's `password_hash` option uses +that form; use `SessionKeyGenerator` (the desktop flow) instead. + +Supported methods: `auth.getMobileSession`, `auth.getToken`, `auth.getSession`, +`track.scrobble` (up to 50 per request), `track.updateNowPlaying`, `user.getInfo`, +`user.getRecentTracks`, `user.getTopArtists`, `user.getTopAlbums`, `user.getTopTracks`. +`/api/docs` has the full parameters, rules and example responses for each. + +A scrobble is ignored (not rejected) if the artist or track is empty, or the timestamp +is more than 14 days old or more than 5 minutes in the future. Resending the same +scrobble is accepted and stored once, so client retries are safe. + +## Importing history + +Open **Import** in the web UI: + +- **An export file**: + - CSV from [lastfm-to-csv](https://benjaminbenben.com/lastfm-to-csv/), no header row, + artist/album/track/date columns. + - Any CSV or TSV with a header row naming artist, track and a date or Unix-time + column. Comma, semicolon and tab delimiters all work. + - A JSON export of `user.getRecentTracks` pages (such as lastfm.ghan.nl's), a single + `recenttracks` response, or a flat list of tracks. + - Files can be gzipped. +- **Last.fm directly**: enter a Last.fm username and the worker pages through that + account's public history. Only appears when the server has `LASTFM_API_KEY` set. + +Imports run in the background; the page shows progress and can cancel one in flight. +Unlike live scrobbles, imports keep plays of any age (still skipping rows with no artist +or track, or plays dated in the future). Plays already in your history are skipped, so +importing the same export again is safe. + +## Sharing on the fediverse + +Only available when the server has federation enabled (ask whoever runs it, or see +[deploy.md](deploy.md#fediverse-sharing-optional) if that's you). Turn it on under +**Sharing**, and you're findable as `@name@` from Mastodon and other +fediverse apps: + +- Follows are accepted automatically, or wait for your approval if you turn that on. +- **Followers** lists requests, followers and blocked accounts, with approve, decline, + remove, block and unblock. + +Once someone follows, **Sharing**'s **What to post** section controls what they see: + +- **Weekly summary**: play count and top artist(s), posted once a week (Monday 09:00 in + your own time zone, for the week that just ended). A live preview shows what it would + say so far. +- **Milestones**: total scrobbles, an artist's plays, and a new entry into your all-time + top 10 — each posted once, the first time it's reached. History already on file when + you turn sharing on, or added by an import, is never posted about retroactively. + +Both are on by default and can be switched off independently. Posts use the same +visibility as your profile (followers only by default, or unlisted/public); **Posts** +lists your own posts with delete (sends a `Delete` to whoever received it). + +**Now playing** is a separate, three-way choice: + +- **Off** (default): nothing shown or posted. +- **Show on my profile**: a "Now playing: *Track* by Artist" field, refreshed at most + every 5 minutes while something's playing and cleared a few minutes after it stops. +- **Show on my profile and post**: the profile field, plus a post for each track played + 30 seconds or more, at most one every 30 minutes, with the previous now-playing post + deleted once the new one is confirmed published. + +Handles and actor URLs **can't change once anyone follows you**, so if you're the one +who gets to choose the server's domain, choose it carefully.