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/.env.example b/.env.example index ffd6774..0d614b5 100644 --- a/.env.example +++ b/.env.example @@ -22,3 +22,11 @@ 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. +# 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/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 515c14f..c2b47fa 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 @@ -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/README.md b/README.md index ca193b5..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,164 +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`. -- **Import worker**: `flask imports worker` imports Last.fm history in the background, 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 | -| `IMPORT_WORKER_METRICS_PORT` | worker | `9101` | The worker's Prometheus metrics port | -| `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. - -## Develop - -```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 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 pytest # needs TEST_DATABASE_URL (see .env.example) -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. -- **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. - -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/deploy/grafana/dashboards/federation.json b/deploy/grafana/dashboards/federation.json new file mode 100644 index 0000000..73af914 --- /dev/null +++ b/deploy/grafana/dashboards/federation.json @@ -0,0 +1,1249 @@ +{ + "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": "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" + }, + "targets": [ + { + "datasource": { + "type": "prometheus", + "uid": "prometheus" + }, + "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", + "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": 18, + "gridPos": { + "x": 0, + "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 + } + }, + { + "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 + } + }, + { + "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 + } + } + ] +} 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/deploy/interop/docker-compose.interop.yml b/deploy/interop/docker-compose.interop.yml new file mode 100644 index 0000000..c6bd88d --- /dev/null +++ b/deploy/interop/docker-compose.interop.yml @@ -0,0 +1,84 @@ +# 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: ${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: + 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: ${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: ${INTEROP_SUBNET:-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: + build: + context: . + dockerfile: deploy/interop/driver.Dockerfile + profiles: [driver] + 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/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/deploy/prometheus/alerts.yml b/deploy/prometheus/alerts.yml index a0c6cd4..1a14936 100644 --- a/deploy/prometheus/alerts.yml +++ b/deploy/prometheus/alerts.yml @@ -73,6 +73,40 @@ 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: 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])) + / 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 diff --git a/docker-compose.yml b/docker-compose.yml index 31dff55..a36c6b8 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -29,11 +29,15 @@ 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: "*" 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: @@ -42,17 +46,21 @@ 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} 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/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/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 <`, 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/design/activitypub-phase0.md b/docs/design/activitypub-phase0.md new file mode 100644 index 0000000..d118476 --- /dev/null +++ b/docs/design/activitypub-phase0.md @@ -0,0 +1,90 @@ +# 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` + +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. diff --git a/docs/design/activitypub-phase1.md b/docs/design/activitypub-phase1.md new file mode 100644 index 0000000..1d41deb --- /dev/null +++ b/docs/design/activitypub-phase1.md @@ -0,0 +1,118 @@ +# ActivityPub phase 1: discoverable profile + +**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). + +**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-phase2.md b/docs/design/activitypub-phase2.md new file mode 100644 index 0000000..eb219e9 --- /dev/null +++ b/docs/design/activitypub-phase2.md @@ -0,0 +1,214 @@ +# ActivityPub phase 2: followers + +**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: + +- **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. + +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. diff --git a/docs/design/activitypub-phase3.md b/docs/design/activitypub-phase3.md new file mode 100644 index 0000000..3285cd1 --- /dev/null +++ b/docs/design/activitypub-phase3.md @@ -0,0 +1,192 @@ +# 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. 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: + +- **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:** + +- 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 (` + + + + +
+

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/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/post.js b/frontend/js/post.js new file mode 100644 index 0000000..930e91c --- /dev/null +++ b/frontend/js/post.js @@ -0,0 +1,40 @@ +import { api } from "./api.js"; +import { errorBox, formatDate, h, replace } from "./dom.js"; +import { publicPage } from "./layout.js"; + +const root = document.getElementById("post"); +const params = new URLSearchParams(location.search); +const username = params.get("u") ?? ""; +const postId = params.get("id") ?? ""; + +// A public page: never sends visitors to sign in. +publicPage(); + +try { + const post = await api( + `/federation/profiles/${encodeURIComponent(username)}/posts/${encodeURIComponent(postId)}`, + { auth: false }, + ); + document.title = `${post.display_name} · Scrobbler`; + replace( + root, + h( + "p", + { class: "muted" }, + h("a", { href: post.profile_url }, post.display_name), + ` · ${post.handle}`, + ), + h("p", { style: "white-space: pre-line" }, post.text), + h("p", { class: "muted", title: formatDate(post.created_at) }, `Posted ${formatDate(post.created_at)}`), + ); +} catch (error) { + replace( + root, + error.status === 404 + ? [ + h("h1", {}, "No post here"), + h("p", { class: "lede" }, "This post doesn't exist, isn't public, or has been deleted."), + ] + : errorBox(error.message), + ); +} diff --git a/frontend/js/posts.js b/frontend/js/posts.js new file mode 100644 index 0000000..5323730 --- /dev/null +++ b/frontend/js/posts.js @@ -0,0 +1,80 @@ +import { api } from "./api.js"; +import { errorBox, formatDate, h, replace, timeAgo } from "./dom.js"; +import { signedInPage } from "./layout.js"; + +const messages = document.getElementById("messages"); +const KIND_LABEL = { weekly: "Weekly summary", milestone: "Milestone" }; +const VISIBILITY_LABEL = { followers: "Followers only", unlisted: "Unlisted", public: "Public" }; + +await signedInPage("sharing.html"); +await refresh(); + +async function refresh() { + let posts; + try { + posts = await api("/federation/posts"); + } catch (error) { + replace( + messages, + error.status === 404 + ? h("p", { class: "notice" }, "This server doesn't share to the fediverse.") + : errorBox(error.message), + ); + return; + } + replace( + document.getElementById("posts"), + posts.length + ? posts.map(postRow) + : h( + "li", + { class: "empty" }, + "Nothing posted yet. Weekly summaries and milestones appear here once you're sharing.", + ), + ); +} + +function postRow(post) { + const actions = h("div", { class: "confirm" }); + const reset = () => + replace( + actions, + post.deleted_at + ? null + : h("button", { type: "button", class: "button button-quiet", onclick: askDelete }, "Delete"), + ); + const askDelete = () => + replace( + actions, + h("span", { class: "muted" }, "Delivered followers keep a copy; this only removes it from their timeline."), + h("button", { type: "button", class: "button button-danger", onclick: doDelete }, "Delete post"), + h("button", { type: "button", class: "button button-quiet", onclick: reset }, "Cancel"), + ); + const doDelete = async () => { + try { + await api(`/federation/posts/${post.id}`, { method: "DELETE" }); + replace(messages, h("p", { class: "notice notice-ok", role: "status" }, "Post deleted.")); + } catch (error) { + replace(messages, errorBox(error.message)); + } + await refresh(); + }; + reset(); + return h( + "li", + {}, + h( + "div", + { class: "row-head" }, + h("span", { class: "row-title" }, KIND_LABEL[post.kind] ?? post.kind), + actions, + ), + h("p", { style: "white-space: pre-line" }, post.text), + h( + "p", + { class: "muted", title: formatDate(post.created_at) }, + `${VISIBILITY_LABEL[post.visibility] ?? post.visibility} · Posted ${timeAgo(post.created_at)}`, + post.deleted_at ? ` · Deleted ${timeAgo(post.deleted_at)}` : null, + ), + ); +} diff --git a/frontend/js/profile.js b/frontend/js/profile.js new file mode 100644 index 0000000..31a4456 --- /dev/null +++ b/frontend/js/profile.js @@ -0,0 +1,46 @@ +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, + 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", + { 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..fd3f1cf --- /dev/null +++ b/frontend/js/sharing.js @@ -0,0 +1,179 @@ +import { api, describeError } from "./api.js"; +import { errorBox, h, num, 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 RADIO_GROUPS = ["visibility", "now_playing_mode"]; +const FIELDS = [ + "enabled", + "visibility", + "manually_approves_followers", + "discoverable", + "indexable", + "post_weekly_summary", + "post_milestones", + "timezone", + "now_playing_mode", + "display_name", + "bio", +]; + +fillTimezoneChoices(); +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); + document.getElementById("preview-weekly").addEventListener("click", previewWeekly); +} + +// Free text (validated server-side), with autocomplete from the browser's own IANA list +// when it can supply one; a picker where that's available, a plain field otherwise. +function fillTimezoneChoices() { + if (typeof Intl.supportedValuesOf !== "function") return; + const datalist = document.getElementById("timezones"); + replace(datalist, Intl.supportedValuesOf("timeZone").map((zone) => h("option", { value: zone }))); +} + +async function previewWeekly() { + const box = document.getElementById("weekly-preview"); + const button = document.getElementById("preview-weekly"); + button.disabled = true; + try { + const preview = await api("/federation/preview/weekly"); + replace( + box, + h("p", { class: "muted" }, "What this week's summary would say so far:"), + h("p", { style: "white-space: pre-line" }, preview.text), + ); + box.hidden = false; + } catch (error) { + replace(messages, errorBox(error.message)); + } finally { + button.disabled = false; + } +} + +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 (field.type === "checkbox") { + field.checked = Boolean(values[name]); + } else { + field.value = values[name] ?? ""; + } + } + 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: ", + h("a", { href: values.profile_url }, values.profile_url.replace(/^https?:\/\//, "")), + ); + showHandle(values.enabled); +} + +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, + 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, + 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, + }; + 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 }); + settings = saved; + fill(saved); + 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))); + messages.scrollIntoView({ behavior: "smooth", block: "start" }); + } finally { + button.disabled = false; + } +} diff --git a/frontend/post.html b/frontend/post.html new file mode 100644 index 0000000..d41f3fe --- /dev/null +++ b/frontend/post.html @@ -0,0 +1,18 @@ + + + + + + Post · Scrobbler + + + + + + + +
    +
    +
    + + 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/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..65383f8 --- /dev/null +++ b/frontend/sharing.html @@ -0,0 +1,124 @@ + + + + + + Sharing · Scrobbler + + + + + + + +
      +

      Sharing

      +

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

      +
      + +
      + + diff --git a/gunicorn.conf.py b/gunicorn.conf.py index 5f37b57..31378e8 100644 --- a/gunicorn.conf.py +++ b/gunicorn.conf.py @@ -12,6 +12,8 @@ bind = os.environ.get("BIND", "0.0.0.0:8000") workers = int(os.environ.get("WEB_CONCURRENCY", "2")) accesslog = "-" forwarded_allow_ips = os.environ.get("FORWARDED_ALLOW_IPS", "127.0.0.1") +# gunicorn 26's control socket lives in $HOME, which the container user doesn't have. +control_socket_disable = True def on_starting(server): diff --git a/pyproject.toml b/pyproject.toml index 480ebde..724e3ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -7,12 +7,14 @@ 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", "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/scripts/interop/compose.sh b/scripts/interop/compose.sh new file mode 100755 index 0000000..7884744 --- /dev/null +++ b/scripts/interop/compose.sh @@ -0,0 +1,7 @@ +#!/usr/bin/env bash +# docker compose for the federation interop stack (Scrobbler + GoToSocial). +set -euo pipefail +root="$(cd "$(dirname "$0")/../.." && pwd)" +# 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/gotosocial_interop.py b/scripts/interop/gotosocial_interop.py new file mode 100644 index 0000000..1de4fcd --- /dev/null +++ b/scripts/interop/gotosocial_interop.py @@ -0,0 +1,437 @@ +"""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}") + + 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): + 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 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 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") + 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("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. 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 + 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("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", + 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("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") + + +if __name__ == "__main__": + check_posts() if "--check-posts" in sys.argv[1:] else main() diff --git a/scripts/interop/run.sh b/scripts/interop/run.sh new file mode 100755 index 0000000..e99cffe --- /dev/null +++ b/scripts/interop/run.sh @@ -0,0 +1,71 @@ +#!/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 + +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 \ + "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 +} + +"$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, 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" +"$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/__init__.py b/src/scrobbler/__init__.py index e90c2a8..02267e4 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"]}}, @@ -37,9 +41,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(app) from scrobbler.metrics import db as db_metrics 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/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..b16a5d0 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 @@ -73,3 +76,9 @@ class TestConfig(Config): "postgresql+psycopg://scrobbler:scrobbler@localhost:5432/scrobbler_test", ) START_METRICS_SERVER = False + # 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"] 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/federation/README.md b/src/scrobbler/federation/README.md new file mode 100644 index 0000000..911f771 --- /dev/null +++ b/src/scrobbler/federation/README.md @@ -0,0 +1,141 @@ +# `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.__version__` + - `scrobbler.api.get_api` (to register federation's API blueprint and document its paths) + - `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, 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`): + +- `/.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, 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, 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 | +| `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 + +`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. +- `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 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), `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 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 + +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..5eedd3f --- /dev/null +++ b/src/scrobbler/federation/__init__.py @@ -0,0 +1,59 @@ +"""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: + # 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: + return + log.info("federation enabled: handles @user@%s, actors at %s", config.domain, config.base_url) + + 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 + 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) + worker.register_task(app, "federation.milestones", milestones.work_once) + 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 + # federation off (see test_federation_boundary.py for why "off" is instead enforced + # by each receiver checking its own app's config). weak=False because the receivers + # are plain module functions meant to live as long as the process does. + events.scrobbles_stored.connect(milestones.on_scrobbles_stored, weak=False) + events.import_finished.connect(milestones.on_import_finished, weak=False) diff --git a/src/scrobbler/federation/activities.py b/src/scrobbler/federation/activities.py new file mode 100644 index 0000000..296bd0c --- /dev/null +++ b/src/scrobbler/federation/activities.py @@ -0,0 +1,92 @@ +"""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. + + Public: used both for our own narrow activity types below (Accept, Reject, Block, + Undo) and, from publishing/base.py, for Create/Delete of posts.""" + 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 + + +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/actors.py b/src/scrobbler/federation/actors.py new file mode 100644 index 0000000..5e5fc07 --- /dev/null +++ b/src/scrobbler/federation/actors.py @@ -0,0 +1,49 @@ +"""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_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 [] + text = now_playing_text(user) + return [(NOW_PLAYING_FIELD, text)] if text else [] + + +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, settings), + ) diff --git a/src/scrobbler/federation/api.py b/src/scrobbler/federation/api.py new file mode 100644 index 0000000..30f7342 --- /dev/null +++ b/src/scrobbler/federation/api.py @@ -0,0 +1,344 @@ +"""/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.extensions import db +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 +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 + +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: + counts = follower_state.counts(user.id) + return { + **{field: getattr(settings, field) for field in sharing.EDITABLE}, + **_identity(user.username), + "followers": counts["accepted"], + "pending_followers": counts["pending"], + } + + +@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. Turning sharing off + deletes your posts and removes all your followers (each is told). + """ + 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() + if toggled is False: + # Delete every live post first: reject_all removes the followers that + # accepted_inboxes() needs to know where to send the Deletes. + publishing.delete_all_for(g.user.id, g.user.username) + follower_state.reject_all(g.user.id, g.user.username) + db.session.commit() + 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") +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, + "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"}, + } + + +@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 --------------------------------------------------------------------------- + + +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 + + 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/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/config.py b/src/scrobbler/federation/config.py new file mode 100644 index 0000000..464104c --- /dev/null +++ b/src/scrobbler/federation/config.py @@ -0,0 +1,106 @@ +import os +from collections.abc import Mapping +from dataclasses import dataclass, field +from urllib.parse import urlsplit + + +class FederationConfigError(ValueError): + pass + + +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": + """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)) + + 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 + + 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." + ) + 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) + 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." + ) + 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))')." + ) + 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"insecure_testing={self.insecure_testing})" + ) 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/followers.py b/src/scrobbler/federation/followers.py new file mode 100644 index 0000000..0e18c84 --- /dev/null +++ b/src/scrobbler/federation/followers.py @@ -0,0 +1,150 @@ +"""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, 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 "undo_not_following" + if follow_id is not None and follow_id != follower.follow_activity_id: + return "undo_stale" + db.session.delete(follower) + 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: + """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)} + + +def accepted_inboxes(user_id: int) -> list[str]: + """Delivery inbox (their shared one, or their own) of every accepted follower, for + fanning out a post. Pending followers are excluded: they haven't been let in yet.""" + accepted = db.session.scalars( + db.select(FederationFollower).filter_by(user_id=user_id, state="accepted") + ).all() + return [follower.actor.delivery_inbox for follower in accepted] diff --git a/src/scrobbler/federation/ids.py b/src/scrobbler/federation/ids.py new file mode 100644 index 0000000..81807cc --- /dev/null +++ b/src/scrobbler/federation/ids.py @@ -0,0 +1,51 @@ +"""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 followers_url(username: str) -> str: + return f"{actor_id(username)}/followers" + + +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 note_url(username: str, post_uuid: str) -> str: + """The Note's ActivityPub id (served at /users//posts/).""" + return f"{actor_id(username)}/posts/{post_uuid}" + + +def post_page_url(username: str, post_uuid: str) -> str: + """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: + """`/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..e2f89bd --- /dev/null +++ b/src/scrobbler/federation/inbox.py @@ -0,0 +1,323 @@ +"""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 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 followers.undo_follow(user.id, actor, object_id(inner)) + + +@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/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/metrics.py b/src/scrobbler/federation/metrics.py new file mode 100644 index 0000000..a58ce4c --- /dev/null +++ b/src/scrobbler/federation/metrics.py @@ -0,0 +1,79 @@ +"""Federation's own metrics (the core's HTTP metrics already cover rate/latency).""" + +from prometheus_client import Counter, Gauge, Histogram + +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"], +) + +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"], +) +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", +) +posts_total = Counter( + "scrobbler_federation_posts_total", + "Posts published: weekly summaries, milestones and now-playing", + ["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"], +) +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 new file mode 100644 index 0000000..e01904e --- /dev/null +++ b/src/scrobbler/federation/models.py @@ -0,0 +1,270 @@ +"""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 ( + 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 + +VISIBILITIES = ("followers", "unlisted", "public") +NOW_PLAYING_MODES = ("off", "profile", "posts") + + +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) + # An IANA zone name (validated with zoneinfo), used to decide when a Monday starts. + 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 + ) + + +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) + + +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(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) + 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 + + +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"), + ) + + +class FederationPost(db.Model): + """A published Note (weekly summary or milestone), wrapped in the Create activity it + was sent with. One row per (user, key): the unique constraint is what makes posting + idempotent, since a key like `weekly:2026-W39` can only be inserted once.""" + + __tablename__ = "federation_posts" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True) + kind: Mapped[str] = mapped_column(String(16)) # weekly or milestone + key: Mapped[str] = mapped_column(String(64)) # e.g. weekly:2026-W39, milestone:scrobbles:10000 + activity_id: Mapped[str] = mapped_column( + ForeignKey("federation_activities.id", ondelete="CASCADE"), unique=True + ) + visibility: Mapped[str] = mapped_column(String(16)) # as posted; unaffected by later changes + content_text: Mapped[str] = mapped_column(Text) + content_html: Mapped[str] = mapped_column(Text) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + deleted_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True)) + + activity: Mapped[FederationActivity] = relationship(lazy="joined") + + __table_args__ = (UniqueConstraint("user_id", "key", name="uq_federation_post_key"),) + + +class FederationMilestoneMark(db.Model): + """A milestone threshold a user has reached. `posted=False` for thresholds passed + silently (the baseline set when a user enables sharing, or after an import finishes) + so they're marked done without ever producing a post.""" + + __tablename__ = "federation_milestone_marks" + + id: Mapped[int] = mapped_column(Integer, primary_key=True) + user_id: Mapped[int] = mapped_column(ForeignKey("users.id", ondelete="CASCADE"), index=True) + key: Mapped[str] = mapped_column(String(64)) # e.g. scrobbles:10000, artist:radiohead:500 + posted: Mapped[bool] = mapped_column(Boolean, default=False) + created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) + + __table_args__ = (UniqueConstraint("user_id", "key", name="uq_federation_milestone_mark"),) + + +class FederationPendingCheck(db.Model): + """A user whose milestones need checking, queued by the scrobbles_stored event + receiver and drained by the worker. One row per user: further scrobbles before the + worker gets to it just update `since`, so scrobbling stays fast and the receiver never + does real work inside a scrobble request.""" + + __tablename__ = "federation_pending_checks" + + user_id: Mapped[int] = mapped_column( + ForeignKey("users.id", ondelete="CASCADE"), primary_key=True + ) + 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 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" + + 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/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/openapi.py b/src/scrobbler/federation/openapi.py new file mode 100644 index 0000000..7d109fb --- /dev/null +++ b/src/scrobbler/federation/openapi.py @@ -0,0 +1,211 @@ +"""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)"} +_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) +_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 public and unlisted posts (followers-only posts are never listed " + "here, since this endpoint isn't authenticated). Without `page`, an " + "OrderedCollection pointing at the first page; with it, an OrderedCollectionPage " + "of up to 20 `Create`s, newest first.", + [ + _USERNAME, + { + "name": "page", + "in": "query", + "required": False, + "schema": {"type": "integer", "minimum": 1}, + }, + ], + { + "200": { + "description": "OrderedCollection or OrderedCollectionPage", + "content": _AP, + }, + "404": _NOT_FOUND, + }, + ), + "federation.post_note": ( + "get", + "Post", + "One public or unlisted post's `Note`, when asked for ActivityPub JSON; browsers " + "are redirected to the web UI's post page. Followers-only and deleted posts " + "answer 404 here (they're delivered directly to followers instead).", + [ + _USERNAME, + {"name": "post_uuid", "in": "path", "required": True, "schema": {"type": "string"}}, + ], + { + "200": {"description": "Note", "content": _AP}, + "302": {"description": "Redirect to the post page (non-ActivityPub Accept)"}, + "404": {"description": "Not found, not listed, or deleted"}, + }, + ), + "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.featured": ( + "get", + "Featured", + "Pinned posts (always empty for now).", + [_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 signed activities for one user. They're stored and answered with 202, then " + "verified and processed in the background.", + [_USERNAME], + _INBOX_RESPONSES, + ), + "federation.shared_inbox": ( + "post", + "Shared inbox", + "Receives signed activities for any user on this server (as for the user inbox).", + [], + _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"}, + }, + ), +} + + +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/outbound.py b/src/scrobbler/federation/outbound.py new file mode 100644 index 0000000..d6cb576 --- /dev/null +++ b/src/scrobbler/federation/outbound.py @@ -0,0 +1,64 @@ +"""Signed requests to other servers, through the SSRF-safe client in net.py.""" + +import json + +from flask import current_app + +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 +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 _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"", ids.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, ids.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/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/federation/protocol/addressing.py b/src/scrobbler/federation/protocol/addressing.py new file mode 100644 index 0000000..b47dd48 --- /dev/null +++ b/src/scrobbler/federation/protocol/addressing.py @@ -0,0 +1,26 @@ +"""to/cc addressing for our posts, by visibility.""" + +from scrobbler.federation.protocol.vocab import PUBLIC + +VISIBILITIES = ("followers", "unlisted", "public") + + +def address(visibility: str, followers_url: str) -> tuple[list[str], list[str]]: + """(to, cc) for a Note/Create/Delete with this visibility. + + followers: to followers, no cc (never reaches a public timeline or search). + unlisted: to followers, cc Public (visible to anyone who looks, not pushed to feeds). + public: to Public, cc followers (the normal public-post shape). + """ + if visibility not in VISIBILITIES: + raise ValueError(f"unknown visibility: {visibility!r}") + if visibility == "public": + return [PUBLIC], [followers_url] + if visibility == "unlisted": + return [followers_url], [PUBLIC] + return [followers_url], [] + + +def is_public_or_unlisted(visibility: str) -> bool: + """Whether a post at this visibility may be listed in the public outbox.""" + return visibility in ("public", "unlisted") diff --git a/src/scrobbler/federation/protocol/content.py b/src/scrobbler/federation/protocol/content.py new file mode 100644 index 0000000..ec27501 --- /dev/null +++ b/src/scrobbler/federation/protocol/content.py @@ -0,0 +1,31 @@ +"""Safe post content: plain text and matching HTML, shared by every post kind so +they're formatted consistently and every track/artist name is escaped the same way. + +Only the tags Mastodon keeps: p, strong, em, ol, li. No br is needed here since each +line of a post is its own paragraph. +""" + +import html + +HASHTAG = "Scrobbler" + + +def escape(text: str) -> str: + """HTML-escape a name (artist, track, ...) for embedding in generated markup.""" + return html.escape(text, quote=False) + + +def paragraph(inner_html: str) -> str: + return f"

      {inner_html}

      " + + +def numbered_list(items_html: list[str]) -> str: + return "
        " + "".join(f"
      1. {item}
      2. " for item in items_html) + "
      " + + +def hashtag_line() -> str: + return f"#{HASHTAG}" + + +def plural(count: int, word: str) -> str: + return word if count == 1 else f"{word}s" 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/schedule.py b/src/scrobbler/federation/protocol/schedule.py new file mode 100644 index 0000000..0deb6b4 --- /dev/null +++ b/src/scrobbler/federation/protocol/schedule.py @@ -0,0 +1,64 @@ +"""Pure date/time math for scheduled posts: which week is due, in a user's own zone. + +Weeks run Monday 00:00 to Sunday 24:00 *local time*, computed in the zone itself (not as +a fixed UTC offset), so the window is correct across a daylight-saving change. +""" + +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. + + Always resolves to exactly one week, so a worker that was down for a while catches up + with a single post (the latest eligible week), not one per week it missed. + """ + local_now = now_utc.astimezone(tz) + gate_monday = local_now.date() - timedelta(days=local_now.weekday()) + gate = datetime(gate_monday.year, gate_monday.month, gate_monday.day, POST_HOUR, tzinfo=tz) + if local_now < gate: + gate_monday -= timedelta(days=7) + week_start = gate_monday - timedelta(days=7) + + 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 + return start_local.astimezone(UTC), end_local.astimezone(UTC), week_key(week_start) + + +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 + everyone else).""" + try: + return ZoneInfo(name) + except (ZoneInfoNotFoundError, ValueError): + return ZoneInfo("UTC") + + +def is_valid_timezone(name: str) -> bool: + """For validating user input (reject a bad name with an error), as opposed to + resolve_timezone's silent fallback (never crash the periodic task over one user's + stale setting).""" + try: + ZoneInfo(name) + except (ZoneInfoNotFoundError, ValueError): + return False + return True 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/src/scrobbler/federation/protocol/vocab.py b/src/scrobbler/federation/protocol/vocab.py new file mode 100644 index 0000000..d712f07 --- /dev/null +++ b/src/scrobbler/federation/protocol/vocab.py @@ -0,0 +1,302 @@ +"""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", + "featured": {"@id": "toot:featured", "@type": "@id"}, + "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 + featured: 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", + featured=f"{actor}/collections/featured", + 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, + "featured": urls.featured, + "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, first: str | None = None +) -> dict: + """A collection. With items=None only the count is published (e.g. followers). With + `first`, the collection just points at its first page rather than listing items + itself (e.g. the outbox, paged by ordered_collection_page).""" + doc = { + "@context": AS_CONTEXT, + "id": collection_id, + "type": "OrderedCollection", + "totalItems": total, + } + if items is not None: + doc["orderedItems"] = items + if first: + doc["first"] = first + return doc + + +def ordered_collection_page( + page_id: str, + *, + part_of: str, + items: list, + next_page: str | None = None, + prev_page: str | None = None, +) -> dict: + doc = { + "@context": AS_CONTEXT, + "id": page_id, + "type": "OrderedCollectionPage", + "partOf": part_of, + "orderedItems": items, + } + if next_page: + doc["next"] = next_page + if prev_page: + doc["prev"] = prev_page + 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. + + 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 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.""" + return {"type": "Hashtag", "name": f"#{name}"} + + +def note( + note_id: str, + *, + actor_id: str, + content_html: str, + published: str, + url: str, + to: list[str], + cc: list[str], + tags: list[str] = (), +) -> dict: + """A post (weekly summary or milestone). No `@context`: it's always embedded in the + Create that carries the same addressing, as Mastodon does.""" + return { + "id": note_id, + "type": "Note", + "attributedTo": actor_id, + "content": content_html, + "contentMap": {"en": content_html}, + "published": published, + "url": url, + "to": list(to), + "cc": list(cc), + "tag": [hashtag(t) for t in tags], + "sensitive": False, + } + + +def create(activity_id: str, actor_id: str, obj: dict, *, to: list[str], cc: list[str]) -> dict: + """Wraps a Note (or other object) for publishing, with the same addressing.""" + return { + "@context": AS_CONTEXT, + "id": activity_id, + "type": "Create", + "actor": actor_id, + "object": obj, + "published": obj.get("published"), + "to": list(to), + "cc": list(cc), + } + + +def delete(activity_id: str, actor_id: str, note_id: str, *, to: list[str], cc: list[str]) -> dict: + """Withdraws one of our Notes, as a Tombstone (the shape Mastodon sends).""" + return { + "@context": AS_CONTEXT, + "id": activity_id, + "type": "Delete", + "actor": actor_id, + "object": {"id": note_id, "type": "Tombstone"}, + "to": list(to), + "cc": list(cc), + } + + +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/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/src/scrobbler/federation/publishing/__init__.py b/src/scrobbler/federation/publishing/__init__.py new file mode 100644 index 0000000..eb0c8c6 --- /dev/null +++ b/src/scrobbler/federation/publishing/__init__.py @@ -0,0 +1,26 @@ +"""Posts to followers: weekly summaries (weekly.py) and milestones (milestones.py), and +later now-playing. Shared machinery — idempotent publishing, addressing, fan-out and +deletion — lives in base.py. +""" + +from scrobbler.federation.publishing.base import ( + LISTED_VISIBILITIES, + OUTBOX_PAGE_SIZE, + delete_all_for, + delete_post, + find_by_note_id, + has_post, + outbox_page, + publish, +) + +__all__ = [ + "LISTED_VISIBILITIES", + "OUTBOX_PAGE_SIZE", + "delete_all_for", + "delete_post", + "find_by_note_id", + "has_post", + "outbox_page", + "publish", +] diff --git a/src/scrobbler/federation/publishing/base.py b/src/scrobbler/federation/publishing/base.py new file mode 100644 index 0000000..0e0c6a7 --- /dev/null +++ b/src/scrobbler/federation/publishing/base.py @@ -0,0 +1,187 @@ +"""Publishing posts: building and storing the Note/Create, fanning out to accepted +followers, and deleting. + +Each post kind (weekly.py, milestones.py, and later now-playing) decides *when* to post +and builds the text; this module handles what every post shares: idempotence (one row +per (user, key), enforced by federation_posts' unique constraint), addressing from the +user's current visibility, storage, delivery and deletion. +""" + +import uuid +from datetime import UTC, datetime + +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 + +DEFAULT_TAGS = ("Scrobbler",) +OUTBOX_PAGE_SIZE = 20 +LISTED_VISIBILITIES = ("public", "unlisted") # followers-only posts aren't listed unauthenticated + + +def _now() -> datetime: + return datetime.now(UTC) + + +def _listed(user_id: int): + return ( + FederationPost.user_id == user_id, + FederationPost.deleted_at.is_(None), + FederationPost.visibility.in_(LISTED_VISIBILITIES), + ) + + +def outbox_page( + user_id: int, page: int, per_page: int = OUTBOX_PAGE_SIZE +) -> tuple[list[dict], int]: + """Create documents for a user's outbox: public and unlisted posts only, newest + first, paged. `page` is 1-based.""" + conditions = _listed(user_id) + total = db.session.scalar( + db.select(db.func.count()).select_from(FederationPost).filter(*conditions) + ) + rows = db.session.scalars( + db.select(FederationActivity) + .join(FederationPost, FederationPost.activity_id == FederationActivity.id) + .filter(*conditions) + .order_by(FederationActivity.created_at.desc()) + .limit(per_page) + .offset((page - 1) * per_page) + ).all() + return [row.document for row in rows], total + + +def find_by_note_id(user_id: int, note_id: str) -> FederationPost | None: + """The post whose Note has this id (the URL served at /users//posts/).""" + return db.session.scalar( + db.select(FederationPost) + .join(FederationActivity, FederationActivity.id == FederationPost.activity_id) + .filter( + FederationPost.user_id == user_id, + FederationActivity.document["object"]["id"].as_string() == note_id, + ) + ) + + +def has_post(user_id: int, kind: str, key: str) -> bool: + """Whether a post with this (user, kind, key) already exists (posted or since + deleted). Lets a caller skip expensive work — computing stats, say — before deciding + whether to call publish() at all.""" + full_key = f"{kind}:{key}" + return ( + db.session.scalar(db.select(FederationPost.id).filter_by(user_id=user_id, key=full_key)) + is not None + ) + + +def publish( + user_id: int, + username: str, + kind: str, + key: str, + *, + text: str, + html: str, + tags: tuple[str, ...] = DEFAULT_TAGS, +) -> FederationPost | None: + """Post `text`/`html` for the user, keyed by `kind:key`. + + Idempotent: a second call with the same (user, kind, key) is a no-op, including when + two worker passes race each other (caught as a duplicate-key error, not raised). + Returns None, without posting, if the user isn't sharing or the key already exists. + """ + settings = sharing.settings_for(user_id) + if not settings.enabled: + return None + full_key = f"{kind}:{key}" + already = db.session.scalar( + db.select(FederationPost.id).filter_by(user_id=user_id, key=full_key) + ) + if already: + return None + + published = _now().isoformat().replace("+00:00", "Z") + post_uuid = str(uuid.uuid4()) + to, cc = addressing.address(settings.visibility, ids.followers_url(username)) + note_doc = vocab.note( + ids.note_url(username, post_uuid), + actor_id=ids.actor_id(username), + content_html=html, + published=published, + url=ids.post_page_url(username, post_uuid), + to=to, + cc=cc, + tags=list(tags), + ) + # activity.id is a Python-generated UUID (see activities.store), so it's already + # usable below without a flush. + activity = activities.store( + user_id, + lambda url: vocab.create(url, ids.actor_id(username), note_doc, to=to, cc=cc), + public=addressing.is_public_or_unlisted(settings.visibility), + ) + post = FederationPost( + user_id=user_id, + kind=kind, + key=full_key, + activity_id=activity.id, + visibility=settings.visibility, + content_text=text, + content_html=html, + ) + db.session.add(post) + inboxes = followers.accepted_inboxes(user_id) + if inboxes: + activities.queue(activity, inboxes) + try: + db.session.commit() + 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 + + +def delete_post(user_id: int, username: str, post: FederationPost) -> FederationActivity | None: + """Delete one post: sends Delete to the same inboxes the Create went to, and + tombstones the row (kept, so its key can never be reused). The caller commits. + None if it's already deleted.""" + if post.deleted_at is not None: + return None + return _delete(user_id, username, post, reason="manual") + + +def delete_all_for(user_id: int, username: str) -> int: + """Sharing switched off: delete every live post before the Rejects go out (call this + before followers.reject_all — it needs accepted_inboxes() to still have somewhere to + send the Deletes). The caller commits. Returns how many were deleted.""" + posts = db.session.scalars( + db.select(FederationPost).filter_by(user_id=user_id, deleted_at=None) + ).all() + for post in posts: + _delete(user_id, username, post, reason="sharing_off") + return len(posts) + + +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"] + to, cc = addressing.address(post.visibility, ids.followers_url(username)) + activity = activities.store( + user_id, + lambda url: vocab.delete(url, ids.actor_id(username), note_id, to=to, cc=cc), + public=addressing.is_public_or_unlisted(post.visibility), + ) + inboxes = followers.accepted_inboxes(user_id) + 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 new file mode 100644 index 0000000..e28ae30 --- /dev/null +++ b/src/scrobbler/federation/publishing/milestones.py @@ -0,0 +1,241 @@ +"""Milestones: total scrobbles, plays of one artist, and entries into a user's all-time +top 10 — each posted once, the first time it's reached. + +Checked only for a user's own live scrobbles (never for imports, which would otherwise +flood years of history through as if it just happened): the `scrobbles_stored` receiver +below queues a FederationPendingCheck row, drained by the `federation.milestones` worker +task. Enabling sharing, and finishing an import, instead call `set_baseline` — every +threshold already passed is marked done without posting, so a new or returning sharer +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 +from scrobbler.services import accounts, stats + +log = logging.getLogger(__name__) + +KIND = "milestone" + +SCROBBLE_THRESHOLDS = [1000, 5000, 10000, *range(25000, 500_000, 25000)] +ARTIST_THRESHOLDS = [100, 500, 1000] +TOP_N = 10 +# A top-10 entry and an artist-plays threshold are only ever checked against a user's +# current top ARTIST_SCAN artists: crossing 100+ plays for one artist keeps it well +# within a generous slice, and scanning a user's entire artist list on every scrobble +# would be unbounded. A crossing that (rarely) falls outside this slice is simply +# missed rather than triggering a full unpaginated scan. +ARTIST_SCAN = 20 + + +def _existing_marks(user_id: int) -> set[str]: + rows = db.session.scalars(db.select(FederationMilestoneMark.key).filter_by(user_id=user_id)) + return set(rows) + + +def _mark(user_id: int, key: str, *, posted: bool) -> None: + db.session.add(FederationMilestoneMark(user_id=user_id, key=key, posted=posted)) + + +def _scrobbles_content(threshold: int) -> tuple[str, str]: + words = content.plural(threshold, "play") + headline = f"{threshold:,} {words} scrobbled" + text = "\n".join([headline, content.hashtag_line()]) + html = content.paragraph(f"{content.escape(headline)}") + content.paragraph( + content.hashtag_line() + ) + return text, html + + +def _artist_content(artist: str, threshold: int) -> tuple[str, str]: + words = content.plural(threshold, "play") + headline = f"{threshold:,} {words} of {artist}" + text = "\n".join([headline, content.hashtag_line()]) + html = content.paragraph( + f"{threshold:,} {words} of {content.escape(artist)}" + ) + content.paragraph(content.hashtag_line()) + return text, html + + +def _top10_content(artist: str, rank: int) -> tuple[str, str]: + headline = f"{artist} entered my all-time top 10 (#{rank})" + text = "\n".join([headline, content.hashtag_line()]) + html = content.paragraph(f"{content.escape(headline)}") + content.paragraph( + content.hashtag_line() + ) + return text, html + + +def _scrobble_milestone(user, existing: set[str]) -> tuple[str, str, str] | None: + """(key, text, html) for the highest not-yet-marked scrobble-count threshold this + user has reached, marking every lower one reached at the same time silently. None if + none has been reached.""" + count = stats.summary(user)["scrobbles"] + reached = [t for t in SCROBBLE_THRESHOLDS if t <= count and f"scrobbles:{t}" not in existing] + if not reached: + return None + for threshold in reached[:-1]: + _mark(user.id, f"scrobbles:{threshold}", posted=False) + top = reached[-1] + text, html = _scrobbles_content(top) + return f"scrobbles:{top}", text, html + + +def _artist_milestone(user, existing: set[str]) -> tuple[str, str, str] | None: + """(key, text, html) for the highest not-yet-marked plays-of-one-artist threshold + reached by any artist in the user's current top ARTIST_SCAN. Only one post per + check, even if more than one artist or threshold qualifies at once.""" + top_artists = stats.top_artists(user, per_page=ARTIST_SCAN).items + best: tuple[str, str, int, int] | None = None # (key, artist, threshold, playcount) + for artist in top_artists: + name = artist.name.lower() + reached = [ + t + for t in ARTIST_THRESHOLDS + if t <= artist.playcount and f"artist:{name}:{t}" not in existing + ] + for threshold in reached[:-1]: + _mark(user.id, f"artist:{name}:{threshold}", posted=False) + if reached and (best is None or reached[-1] > best[2]): + best = (f"artist:{name}:{reached[-1]}", artist.name, reached[-1], artist.playcount) + if best is None: + return None + key, artist_name, threshold, _ = best + text, html = _artist_content(artist_name, threshold) + return key, text, html + + +def _top10_milestone(user, existing: set[str]) -> tuple[str, str, str] | None: + """(key, text, html) for the highest-ranked, not-yet-marked new entry into the + user's current all-time top 10. Only one post per check. + + Nothing is posted until the user actually has TOP_N distinct artists: with fewer + than that, every first play of a new artist would trivially "enter the top 10", + which isn't a real milestone. + """ + page = stats.top_artists(user, per_page=TOP_N) + if page.total < TOP_N: + return None + for artist in page.items: # already ranked best first + key = f"top10:{artist.name.lower()}" + if key not in existing: + text, html = _top10_content(artist.name, artist.rank) + return key, text, html + return None + + +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" + user = accounts.get_user(user_id) + if user is None: # the account was deleted; federation_settings should follow, but be safe + return "disabled" + + existing = _existing_marks(user_id) + found = ( + _scrobble_milestone(user, existing) + or _top10_milestone(user, existing) + or _artist_milestone(user, existing) + ) + if found is None: + return "none" + key, text, html = found + post = publishing.publish(user.id, user.username, KIND, key, text=text, html=html) + if post is not None: + _mark(user.id, key, posted=True) + return "posted" if post is not None else "none" # lost a race with another pass + + +def set_baseline(user_id: int) -> None: + """Mark every threshold this user has already passed, without posting: called when + a user enables sharing, and after an import finishes, so history already on file + never produces a flood of retroactive "milestone" posts.""" + user = accounts.get_user(user_id) + if user is None: + return + existing = _existing_marks(user_id) + count = stats.summary(user)["scrobbles"] + for threshold in SCROBBLE_THRESHOLDS: + if threshold <= count and f"scrobbles:{threshold}" not in existing: + _mark(user_id, f"scrobbles:{threshold}", posted=False) + top_artists = stats.top_artists(user, per_page=max(TOP_N, ARTIST_SCAN)) + has_top10 = top_artists.total >= TOP_N + for artist in top_artists.items: + name = artist.name.lower() + if has_top10 and artist.rank <= TOP_N and f"top10:{name}" not in existing: + _mark(user_id, f"top10:{name}", posted=False) + for threshold in ARTIST_THRESHOLDS: + if threshold <= artist.playcount and f"artist:{name}:{threshold}" not in existing: + _mark(user_id, f"artist:{name}:{threshold}", posted=False) + db.session.commit() + + +def on_scrobbles_stored(sender, *, scrobbles, source, **kwargs) -> None: + """Queue a milestone check for the user's own live scrobbles. Imports are never + live listening, so they're excluded here and instead handled by set_baseline via + on_import_finished.""" + if source != "scrobble" or not scrobbles: + return + settings = sharing.settings_for(sender.id) + if not (settings.enabled and settings.post_milestones): + return + if db.session.get(FederationPendingCheck, sender.id) is None: + db.session.add(FederationPendingCheck(user_id=sender.id)) + db.session.commit() + + +def on_import_finished(sender, *, job, **kwargs) -> None: + """An import just finished: mark whatever it added as baseline, silently, rather + than queuing a live check that would post about years-old history.""" + settings = sharing.settings_for(sender.id) + if not settings.enabled: # skip the computation for users who've never touched federation + return + set_baseline(sender.id) + + +def work_once() -> bool: + """Claim one pending user (oldest first) and check them. On failure, the row is + requeued at the back rather than retried immediately, so one persistently-failing + user's checks (a pure DB read — unlike delivery, there's no external server to fail + against) can't head-of-line-block everyone behind them.""" + row = db.session.execute( + db.select(FederationPendingCheck) + .order_by(FederationPendingCheck.since) + .limit(1) + .with_for_update(skip_locked=True) + ).scalar_one_or_none() + if row is None: + return False + user_id = row.user_id + try: + check_and_post(user_id) + except Exception: + log.exception("milestone check failed for user %s", user_id) + db.session.rollback() + db.session.execute( + db.update(FederationPendingCheck) + .where(FederationPendingCheck.user_id == user_id) + .values(since=db.func.now()) + ) + db.session.commit() + return True + db.session.execute( + db.delete(FederationPendingCheck).where(FederationPendingCheck.user_id == user_id) + ) + db.session.commit() + return True 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/src/scrobbler/federation/publishing/weekly.py b/src/scrobbler/federation/publishing/weekly.py new file mode 100644 index 0000000..8873c1f --- /dev/null +++ b/src/scrobbler/federation/publishing/weekly.py @@ -0,0 +1,149 @@ +"""Weekly summaries: for each sharing user with them on, once the Monday-09:00-local +posting gate has passed (see protocol/schedule.target_week), post about the Monday- +Sunday week that just ended. + +Empty weeks aren't posted. Since the target week only ever moves forward — once its own +gate has passed, it never becomes the target again — an empty week is never reconsidered +either, without needing a separate "skipped" marker. +""" + +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 +from scrobbler.services import accounts, stats + +KIND = "weekly" +TOP_ARTISTS = 3 + +log = logging.getLogger(__name__) + + +def build_content(count: int, top_artists: list, top_tracks: list) -> tuple[str, str]: + headline = f"My week in music: {count} {content.plural(count, 'play')}" + text_lines = [headline] + html_parts = [content.paragraph(f"{content.escape(headline)}")] + + if top_artists: + text_lines.append( + "Top artists: " + + " ".join(f"{i}. {a.name} ({a.playcount})" for i, a in enumerate(top_artists, 1)) + ) + html_parts.append( + content.numbered_list( + [ + f"{content.escape(a.name)} — {a.playcount} " + f"{content.plural(a.playcount, 'play')}" + for a in top_artists + ] + ) + ) + + if top_tracks: + top = top_tracks[0] + words = content.plural(top.playcount, "play") + text_lines.append(f"Most played: {top.name} by {top.artist} ({top.playcount} {words})") + html_parts.append( + content.paragraph( + f"Most played: {content.escape(top.name)} by " + f"{content.escape(top.artist)} ({top.playcount} {words})" + ) + ) + + text_lines.append(content.hashtag_line()) + html_parts.append(content.paragraph(content.hashtag_line())) + return "\n".join(text_lines), "".join(html_parts) + + +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) + if user is None: # the account was deleted; federation_settings should follow, but be safe + return "disabled" + + 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 + + count = stats.scrobble_count_between(user, start, end) + if count == 0: + return "skipped_empty" + + top_artists = stats.top_artists_between(user, start, end, limit=TOP_ARTISTS) + top_tracks = stats.top_tracks_between(user, start, end, limit=1) + text, html = build_content(count, top_artists, top_tracks) + post = publishing.publish(user.id, user.username, KIND, key, text=text, html=html) + 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.""" + 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.""" + now_utc = now_utc or datetime.now(UTC) + settings_rows = db.session.scalars( + db.select(FederationSettings).filter_by(enabled=True, post_weekly_summary=True) + ).all() + for settings in settings_rows: + try: + check_and_post(settings, now_utc) + except Exception: + log.exception("weekly summary check failed for user %s", settings.user_id) + db.session.rollback() + else: + db.session.commit() diff --git a/src/scrobbler/federation/remote.py b/src/scrobbler/federation/remote.py new file mode 100644 index 0000000..e3a9ba8 --- /dev/null +++ b/src/scrobbler/federation/remote.py @@ -0,0 +1,144 @@ +"""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) +MAX_URL = 1024 + + +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 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 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 or len(shared) > MAX_URL: + 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`. 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 + # 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) + except ActorError: + 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: + 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/federation/schemas.py b/src/scrobbler/federation/schemas.py new file mode 100644 index 0000000..c4dfba7 --- /dev/null +++ b/src/scrobbler/federation/schemas.py @@ -0,0 +1,126 @@ +from marshmallow import Schema, ValidationError, fields, validate + +from scrobbler.federation.models import NOW_PLAYING_MODES, 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): + 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)) + 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" + } + ) + 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) + followers = fields.Integer(dump_only=True, metadata={"description": "Accepted followers"}) + pending_followers = fields.Integer( + dump_only=True, metadata={"description": "Waiting for approval"} + ) + + +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() + + +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() + + +class PostSchema(Schema): + id = fields.Integer() + kind = fields.String(metadata={"description": "weekly, milestone or now_playing"}) + 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/src/scrobbler/federation/sharing.py b/src/scrobbler/federation/sharing.py new file mode 100644 index 0000000..fe811c7 --- /dev/null +++ b/src/scrobbler/federation/sharing.py @@ -0,0 +1,108 @@ +"""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 NOW_PLAYING_MODES, VISIBILITIES, FederationSettings +from scrobbler.federation.protocol.schedule import is_valid_timezone +from scrobbler.services import accounts + +EDITABLE = ( + "enabled", + "visibility", + "manually_approves_followers", + "discoverable", + "indexable", + "display_name", + "bio", + "timezone", + "post_weekly_summary", + "post_milestones", + "now_playing_mode", +) + + +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: + # Not added to the session: the model's column defaults apply on INSERT, not + # here, so every field a caller might read has to be set explicitly. + settings = FederationSettings( + user_id=user_id, + enabled=False, + visibility="followers", + manually_approves_followers=False, + discoverable=False, + indexable=False, + timezone="UTC", + post_weekly_summary=True, + post_milestones=True, + now_playing_mode="off", + ) + 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)) + 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) + 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 + from scrobbler.federation.publishing import milestones + + milestones.set_baseline(user_id) # history already on file isn't a "milestone" + 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) + ) + + +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 new file mode 100644 index 0000000..3f0e8c5 --- /dev/null +++ b/src/scrobbler/federation/web.py @@ -0,0 +1,278 @@ +"""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.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 metrics as fed_metrics +from scrobbler.federation.models import FederationActivity +from scrobbler.federation.protocol import hostmeta, media, nodeinfo, vocab, webfinger + +bp = Blueprint("federation", __name__) + +_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: + 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") + doc = actors.build_document(_urls(user.username), user, settings) + return _json(doc) + + +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), total, items)) + + +@bp.get("/users//outbox") +def outbox(username: str): + found = sharing.shared_user(username) + if found is None: + return _not_found("actor") + urls = _urls(found[0].username) + page_param = request.args.get("page") + if page_param is None: + total = publishing.outbox_page(found[0].id, page=1)[1] + return _json(vocab.ordered_collection(urls.outbox, total, first=f"{urls.outbox}?page=1")) + + try: + page = max(int(page_param), 1) + except ValueError: + page = 1 + per_page = publishing.OUTBOX_PAGE_SIZE + items, total = publishing.outbox_page(found[0].id, page, per_page=per_page) + next_page = f"{urls.outbox}?page={page + 1}" if page * per_page < total else None + prev_page = f"{urls.outbox}?page={page - 1}" if page > 1 else None + return _json( + vocab.ordered_collection_page( + f"{urls.outbox}?page={page}", + part_of=urls.outbox, + items=items, + next_page=next_page, + prev_page=prev_page, + ) + ) + + +@bp.get("/users//posts/") +def post_note(username: str, post_uuid: str): + if not media.wants_activitypub(request.headers.get("Accept")): + # Same reasoning as actor(): redirect everyone, so the response can't be used to + # probe which posts exist. + return redirect(ids.post_page_url(username, post_uuid), code=302) + found = sharing.shared_user(username) + if found is None: + return _not_found("post") + post = publishing.find_by_note_id(found[0].id, ids.note_url(username, post_uuid)) + if ( + post is None + or post.deleted_at is not None + or post.visibility not in publishing.LISTED_VISIBILITIES + ): + return _not_found("post") + return _json(post.activity.document["object"], cache=60) + + +@bp.get("/users//followers") +def followers(username: str): + 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//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", []) + + +# --- 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 ---------------------------------------------------------------------------- + + +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) + 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 _receive(_path(), "user") + + +@bp.post("/inbox") +def shared_inbox(): + 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/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/migrations/versions/0b81b61c932a_federation_posts_and_milestones.py b/src/scrobbler/migrations/versions/0b81b61c932a_federation_posts_and_milestones.py new file mode 100644 index 0000000..6ca051e --- /dev/null +++ b/src/scrobbler/migrations/versions/0b81b61c932a_federation_posts_and_milestones.py @@ -0,0 +1,99 @@ +"""federation posts and milestones + +Revision ID: 0b81b61c932a +Revises: a481855fcb93 +Create Date: 2026-09-26 11:34:52.240684 + +""" + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = "0b81b61c932a" +down_revision = "a481855fcb93" +branch_labels = None +depends_on = None + + +def upgrade(): + # ### commands auto generated by Alembic - please adjust! ### + op.create_table( + "federation_milestone_marks", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column("key", sa.String(length=64), nullable=False), + sa.Column("posted", 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"), + sa.UniqueConstraint("user_id", "key", name="uq_federation_milestone_mark"), + ) + with op.batch_alter_table("federation_milestone_marks", schema=None) as batch_op: + batch_op.create_index( + batch_op.f("ix_federation_milestone_marks_user_id"), ["user_id"], unique=False + ) + + op.create_table( + "federation_pending_checks", + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column("since", sa.DateTime(timezone=True), nullable=False), + sa.Column("reason", sa.String(length=32), nullable=False), + sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("user_id"), + ) + op.create_table( + "federation_posts", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column("kind", sa.String(length=16), nullable=False), + sa.Column("key", sa.String(length=64), nullable=False), + sa.Column("activity_id", sa.String(length=36), nullable=False), + sa.Column("visibility", sa.String(length=16), nullable=False), + sa.Column("content_text", sa.Text(), nullable=False), + sa.Column("content_html", sa.Text(), nullable=False), + sa.Column("created_at", sa.DateTime(timezone=True), nullable=False), + sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True), + sa.ForeignKeyConstraint(["activity_id"], ["federation_activities.id"], ondelete="CASCADE"), + sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"), + sa.PrimaryKeyConstraint("id"), + sa.UniqueConstraint("activity_id"), + sa.UniqueConstraint("user_id", "key", name="uq_federation_post_key"), + ) + with op.batch_alter_table("federation_posts", schema=None) as batch_op: + batch_op.create_index(batch_op.f("ix_federation_posts_user_id"), ["user_id"], unique=False) + + # server_default backfills existing rows (any user who's already touched their + # sharing settings); the model's Python-side default covers new ones. + with op.batch_alter_table("federation_settings", schema=None) as batch_op: + batch_op.add_column( + sa.Column("timezone", sa.String(length=64), nullable=False, server_default="UTC") + ) + batch_op.add_column( + sa.Column("post_weekly_summary", sa.Boolean(), nullable=False, server_default=sa.true()) + ) + batch_op.add_column( + sa.Column("post_milestones", sa.Boolean(), nullable=False, server_default=sa.true()) + ) + + # ### 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("post_milestones") + batch_op.drop_column("post_weekly_summary") + batch_op.drop_column("timezone") + + with op.batch_alter_table("federation_posts", schema=None) as batch_op: + batch_op.drop_index(batch_op.f("ix_federation_posts_user_id")) + + op.drop_table("federation_posts") + op.drop_table("federation_pending_checks") + with op.batch_alter_table("federation_milestone_marks", schema=None) as batch_op: + batch_op.drop_index(batch_op.f("ix_federation_milestone_marks_user_id")) + + op.drop_table("federation_milestone_marks") + # ### end Alembic commands ### 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/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/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/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 ### 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/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/src/scrobbler/services/accounts.py b/src/scrobbler/services/accounts.py index c5e3bc2..66e65e2 100644 --- a/src/scrobbler/services/accounts.py +++ b/src/scrobbler/services/accounts.py @@ -40,6 +40,10 @@ def find_user(username: str) -> User | None: return db.session.scalar(db.select(User).where(func.lower(User.username) == username.lower())) +def get_user(user_id: int) -> User | None: + return db.session.get(User, user_id) + + def register(username: str, email: str, password: str) -> User: if not USERNAME_RE.match(username): raise AccountError( diff --git a/src/scrobbler/services/imports.py b/src/scrobbler/services/imports.py index f6a39b6..decfba1 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,17 +566,22 @@ 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: - 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(app) -> None: + from scrobbler import worker + + worker.register_task(app, "imports", work_once) + worker.register_periodic(app, "imports.requeue_stalled", 60, requeue_stalled) 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/src/scrobbler/services/stats.py b/src/scrobbler/services/stats.py index 6134696..6328c8d 100644 --- a/src/scrobbler/services/stats.py +++ b/src/scrobbler/services/stats.py @@ -47,13 +47,20 @@ def since(period: str, now: datetime | None = None) -> datetime | None: return None if days is None else (now or datetime.now(UTC)) - timedelta(days=days) -def _user_scrobbles(user: User, period: str = "overall"): +def _between(user: User, start: datetime | None, end: datetime | None): + """user_id plus an optional window: start inclusive, end exclusive.""" conditions = [Scrobble.user_id == user.id] - if (start := since(period)) is not None: + if start is not None: conditions.append(Scrobble.played_at >= start) + if end is not None: + conditions.append(Scrobble.played_at < end) return conditions +def _user_scrobbles(user: User, period: str = "overall"): + return _between(user, since(period), None) + + def _display(column): """Most common spelling within a case-insensitive group. Ties go to the capitalised spelling: the C collation sorts uppercase first, regardless of the server locale.""" @@ -162,6 +169,54 @@ def listen_counts(user: User, period: str = "1month", bucket: str = "day") -> li return [{"start": day, "count": count} for day, count in counts.items()] +def scrobble_count_between(user: User, start: datetime, end: datetime) -> int: + """Total plays in [start, end).""" + return db.session.scalar(select(func.count()).where(*_between(user, start, end))) or 0 + + +def top_artists_between( + user: User, start: datetime, end: datetime, limit: int = 10 +) -> list[TopItem]: + """Top artists in [start, end), unpaginated (callers like weekly summaries want a + handful, not a full listing).""" + key = func.lower(Scrobble.artist) + plays = func.count().label("plays") + query = ( + select(_display(Scrobble.artist), plays) + .where(*_between(user, start, end)) + .group_by(key) + .order_by(plays.desc(), key) + .limit(limit) + ) + rows = db.session.execute(query).all() + return [TopItem(i + 1, name, count) for i, (name, count) in enumerate(rows)] + + +def top_tracks_between( + user: User, start: datetime, end: datetime, limit: int = 10 +) -> list[TopItem]: + """Top tracks in [start, end), unpaginated.""" + keys = (func.lower(Scrobble.track), func.lower(Scrobble.artist)) + plays = func.count().label("plays") + query = ( + select( + _display(Scrobble.track), + _display(Scrobble.artist), + func.max(Scrobble.duration), + plays, + ) + .where(*_between(user, start, end)) + .group_by(*keys) + .order_by(plays.desc(), *keys) + .limit(limit) + ) + rows = db.session.execute(query).all() + return [ + TopItem(i + 1, name, count, artist=artist, duration=duration) + for i, (name, artist, duration, count) in enumerate(rows) + ] + + def summary(user: User) -> dict: row = db.session.execute( select( diff --git a/src/scrobbler/worker.py b/src/scrobbler/worker.py new file mode 100644 index 0000000..4ff53b1 --- /dev/null +++ b/src/scrobbler/worker.py @@ -0,0 +1,89 @@ +"""The background worker: runs tasks that modules register (`flask worker`). + +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(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. +""" + +import logging +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 + +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 + + +def tasks(app: Flask | None = None) -> dict[str, _Task]: + return (app or current_app).extensions.setdefault("worker_tasks", {}) + + +def register_task(app: Flask, name: str, fn: Callable[[], bool]) -> None: + tasks(app)[name] = _Task(name, fn) + + +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(app: Flask | None = None) -> list[str]: + return sorted(tasks(app)) + + +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/conftest.py b/tests/conftest.py index 0346354..4973e20 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") @@ -142,3 +142,134 @@ 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" + # Lets tests federate with servers on 127.0.0.1 over http (allowed for .test only). + FEDERATION_INSECURE_TESTING = "1" + + +@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 + + +class FakeRemote: + """A tiny HTTP server standing in for another fediverse server. + + `routes[path] = (status, headers, body)` or a function(request) returning that; + `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(), + } + ) + 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 + + 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() + + +# --- 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) 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/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_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'(? 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_text_is_none_when_nothing_is_playing(fed_ctx, user): + assert actors.now_playing_text(user) is None + + +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_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): + 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) + 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, "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_api.py b/tests/test_federation_api.py new file mode 100644 index 0000000..fe7d981 --- /dev/null +++ b/tests/test_federation_api.py @@ -0,0 +1,267 @@ +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): + 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["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_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( + "/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.", + "now_playing": None, + "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_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 + + +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_boundary.py b/tests/test_federation_boundary.py new file mode 100644 index 0000000..4e0f0f2 --- /dev/null +++ b/tests/test_federation_boundary.py @@ -0,0 +1,220 @@ +"""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.extensions import db +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.__version__", + "scrobbler.api.get_api", + "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: + # 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 + 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"), + (FEDERATION + ".api", "from scrobbler.api import apps", "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"), + (FEDERATION, "from scrobbler.api import get_api"), + (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 == [] + assert not any(name.startswith("federation") for name in worker.registered(app)) + + +def test_federation_event_receivers_are_no_ops_when_this_app_is_off(app, make_user): + """Receivers connect to blinker's process-wide signals, which have no notion of + "app": once any app in this test process enables federation (fed_app, or the + create_app(_Enabled) calls below), the signal keeps those receivers connected for + the rest of the run, whatever this test's own `app` says. So "off" can't be shown by + an absence of receivers — it's enforced by each receiver checking *this app's own* + config at call time. Firing an event inside this off app's context must therefore + still be a no-op, whatever else has already run in the process.""" + from scrobbler.federation.models import FederationPendingCheck + + assert app.extensions["federation"].enabled is False + user = make_user() + events.send(events.scrobbles_stored, user, scrobbles=["placeholder"], source="scrobble") + events.send(events.import_finished, user, job=None) + assert db.session.get(FederationPendingCheck, user.id) is None + + +class _Enabled(TestConfig): + FEDERATION_ENABLED = "1" + FEDERATION_DOMAIN = "scrobble.example" + FEDERATION_BASE_URL = "https://scrobble.example" + FEDERATION_KEY_SECRET = "x" * 32 + + +@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"), + ({"FEDERATION_KEY_SECRET": "too-short"}, "FEDERATION_KEY_SECRET"), + ], +) +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://scrobble.example", + ) + assert "x" * 32 not in repr(config) diff --git a/tests/test_federation_content.py b/tests/test_federation_content.py new file mode 100644 index 0000000..13af7dc --- /dev/null +++ b/tests/test_federation_content.py @@ -0,0 +1,101 @@ +"""Safe post content (protocol/content.py): escaping, and the weekly summary template +built on top of it (publishing/weekly.py's build_content).""" + +import pytest + +from scrobbler.federation.protocol import content +from scrobbler.federation.publishing.weekly import build_content +from scrobbler.services.stats import TopItem + + +def test_escape_neutralises_markup(): + assert content.escape("") == "<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 "", + 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"] == [] + assert vocab.ordered_collection("x", 5, first="x?page=1")["first"] == "x?page=1" + assert "orderedItems" not in vocab.ordered_collection("x", 5, first="x?page=1") + + +def test_ordered_collection_page(): + page = vocab.ordered_collection_page( + f"{BASE}/users/alice/outbox?page=2", + part_of=f"{BASE}/users/alice/outbox", + items=["a", "b"], + next_page=f"{BASE}/users/alice/outbox?page=3", + ) + assert page["type"] == "OrderedCollectionPage" + assert page["partOf"] == f"{BASE}/users/alice/outbox" + assert page["orderedItems"] == ["a", "b"] + assert page["next"] == f"{BASE}/users/alice/outbox?page=3" + assert "prev" not in page + + with_prev = vocab.ordered_collection_page("x", part_of="y", items=[], prev_page="z") + assert with_prev["prev"] == "z" and "next" not in with_prev + + +@pytest.mark.parametrize( + ("visibility", "to", "cc"), + [ + ("followers", ["FOLLOWERS"], []), + ("unlisted", ["FOLLOWERS"], [vocab.PUBLIC]), + ("public", [vocab.PUBLIC], ["FOLLOWERS"]), + ], +) +def test_addressing(visibility, to, cc): + assert addressing.address(visibility, "FOLLOWERS") == (to, cc) + + +def test_addressing_rejects_unknown_visibility(): + with pytest.raises(ValueError, match="visibility"): + addressing.address("everyone", "FOLLOWERS") + + +def test_is_public_or_unlisted(): + assert addressing.is_public_or_unlisted("public") is True + assert addressing.is_public_or_unlisted("unlisted") is True + assert addressing.is_public_or_unlisted("followers") is False + + +def test_hashtag(): + assert vocab.hashtag("Scrobbler") == {"type": "Hashtag", "name": "#Scrobbler"} + + +def test_note(): + doc = vocab.note( + f"{BASE}/users/alice/posts/1", + actor_id=f"{BASE}/users/alice", + content_html="

      Hello

      ", + published="2026-01-05T09:00:00Z", + url=f"{BASE}/post.html?id=1", + to=["FOLLOWERS"], + cc=[], + tags=["Scrobbler"], + ) + assert doc["type"] == "Note" + assert doc["attributedTo"] == f"{BASE}/users/alice" + assert doc["content"] == "

      Hello

      " + assert doc["contentMap"] == {"en": "

      Hello

      "} + assert (doc["to"], doc["cc"]) == (["FOLLOWERS"], []) + assert doc["tag"] == [{"type": "Hashtag", "name": "#Scrobbler"}] + assert doc["sensitive"] is False + assert "@context" not in doc # carried by the wrapping Create instead + + +def test_create_wraps_a_note_with_the_same_addressing(): + inner = vocab.note( + "note-id", + actor_id="actor", + content_html="

      x

      ", + published="2026-01-05T00:00:00Z", + url="url", + to=["FOLLOWERS"], + cc=["PUBLIC"], + ) + doc = vocab.create("activity-id", "actor", inner, to=["FOLLOWERS"], cc=["PUBLIC"]) + assert (doc["type"], doc["id"], doc["actor"]) == ("Create", "activity-id", "actor") + assert doc["object"] == inner + assert (doc["to"], doc["cc"]) == (["FOLLOWERS"], ["PUBLIC"]) + assert doc["published"] == "2026-01-05T00:00:00Z" + assert doc["@context"] == vocab.AS_CONTEXT + + +def test_delete_is_a_tombstone(): + doc = vocab.delete("activity-id", "actor", "note-id", to=["FOLLOWERS"], cc=["PUBLIC"]) + assert doc["type"] == "Delete" + assert doc["object"] == {"id": "note-id", "type": "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) + 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}}" diff --git a/tests/test_federation_publishing.py b/tests/test_federation_publishing.py new file mode 100644 index 0000000..cea45ac --- /dev/null +++ b/tests/test_federation_publishing.py @@ -0,0 +1,222 @@ +"""Publishing core: idempotent posting, addressing, fan-out and deletion.""" + +import pytest + +from federation_helpers import RemoteAccount +from scrobbler.extensions import db +from scrobbler.federation import followers as follower_state +from scrobbler.federation import inbox, publishing, sharing +from scrobbler.federation.models import FederationActivity, FederationDelivery, FederationPost + + +def all_activities(): + return db.session.scalars( + db.select(FederationActivity).order_by(FederationActivity.created_at) + ).all() + + +def deliveries_for(activity_id): + return db.session.scalars( + db.select(FederationDelivery).filter_by(activity_id=activity_id) + ).all() + + +def approved_follower(fed_client, remote, sharing_user, name): + """A remote account following sharing_user, already accepted.""" + account = RemoteAccount(remote, name) + remote.routes[f"/users/{name}/inbox"] = (202, {}, b"") + account.deliver(fed_client, account.follow()) + while inbox.work_once(): + pass + db.session.expire_all() + return account + + +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 + + [activity] = all_activities() + assert activity.id == post.activity_id + assert activity.activity_type == "Create" + assert activity.document["object"]["type"] == "Note" + assert activity.document["object"]["content"] == "

      312 plays

      " + assert activity.document["object"]["contentMap"] == {"en": "

      312 plays

      "} + assert activity.document["object"]["tag"] == [{"type": "Hashtag", "name": "#Scrobbler"}] + assert activity.public is False # followers-only, the default + + +def test_publish_is_idempotent(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) + first = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="a", html="a") + second = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="b", html="b") + assert first is not None + assert second is None + assert db.session.scalar(db.select(db.func.count()).select_from(FederationPost)) == 1 + # The first call's content wins; a later call never overwrites it + assert db.session.get(FederationPost, first.id).content_text == "a" + + +def test_publish_keys_are_scoped_to_kind_and_user(fed_ctx, user, make_user): + sharing.update(user.id, {"enabled": True}) + same_key_different_kind = publishing.publish( + user.id, "alice", "milestone", "2026-W01", text="x", html="x" + ) + assert publishing.publish(user.id, "alice", "weekly", "2026-W01", text="y", html="y") + assert same_key_different_kind is not None # "weekly:2026-W01" != "milestone:2026-W01" + + other = make_user(username="bob") + sharing.update(other.id, {"enabled": True}) + assert publishing.publish(other.id, "bob", "weekly", "2026-W01", text="z", html="z") + assert db.session.scalar(db.select(db.func.count()).select_from(FederationPost)) == 3 + + +def test_publish_refuses_when_not_sharing(fed_ctx, user): + assert publishing.publish(user.id, "alice", "weekly", "2026-W01", text="x", html="x") is None + sharing.update(user.id, {"enabled": True}) + sharing.update(user.id, {"enabled": False}) + assert publishing.publish(user.id, "alice", "weekly", "2026-W02", text="x", html="x") is None + assert db.session.scalar(db.select(db.func.count()).select_from(FederationPost)) == 0 + + +@pytest.mark.parametrize( + ("visibility", "to", "cc"), + [ + ("followers", "FOLLOWERS", []), + ("unlisted", "FOLLOWERS", "PUBLIC"), + ("public", "PUBLIC", "FOLLOWERS"), + ], +) +def test_publish_addresses_by_the_users_visibility(fed_ctx, user, visibility, to, cc): + from scrobbler.federation.protocol.vocab import PUBLIC + + sharing.update(user.id, {"enabled": True, "visibility": visibility}) + post = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="x", html="

      x

      ") + activity = db.session.get(FederationActivity, post.activity_id) + expected_to = [PUBLIC] if to == "PUBLIC" else ["https://scrobble.test/users/alice/followers"] + expected_cc = ( + [] + if cc == [] + else [PUBLIC] + if cc == "PUBLIC" + else ["https://scrobble.test/users/alice/followers"] + ) + assert activity.document["to"] == expected_to + assert activity.document["cc"] == expected_cc + assert activity.document["object"]["to"] == expected_to # the Note matches the Create + assert activity.document["object"]["cc"] == expected_cc + assert activity.public is (visibility != "followers") + + +def test_publish_fans_out_only_to_accepted_followers(fed_client, remote, sharing_user): + bob = approved_follower(fed_client, remote, sharing_user, "bob") + # A pending request: not yet let in, so it shouldn't receive posts + sharing.update(sharing_user.id, {"manually_approves_followers": True}) + carol = RemoteAccount(remote, "carol") + remote.routes["/users/carol/inbox"] = (202, {}, b"") + carol.deliver(fed_client, carol.follow()) + while inbox.work_once(): + pass + db.session.expire_all() + assert follower_state.counts(sharing_user.id) == {"accepted": 1, "pending": 1} + + post = publishing.publish(sharing_user.id, "alice", "weekly", "2026-W01", text="x", html="x") + deliveries = deliveries_for(post.activity_id) + assert [d.inbox for d in deliveries] == [bob.server.url("/inbox")] + + +def test_publish_with_no_followers_still_creates_the_post(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) + post = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="x", html="x") + assert post is not None + assert deliveries_for(post.activity_id) == [] + + +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() + + assert activity is not None + assert activity.activity_type == "Delete" + 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): + sharing.update(user.id, {"enabled": True}) + post = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="x", html="x") + first = publishing.delete_post(user.id, "alice", post) + db.session.commit() + second = publishing.delete_post(user.id, "alice", post) + assert first is not None + assert second is None + assert len([a for a in all_activities() if a.activity_type == "Delete"]) == 1 + + +def test_delete_uses_the_posts_own_visibility_not_the_current_setting(fed_ctx, user): + from scrobbler.federation.protocol.vocab import PUBLIC + + sharing.update(user.id, {"enabled": True, "visibility": "public"}) + post = publishing.publish(user.id, "alice", "weekly", "2026-W01", text="x", html="x") + sharing.update(user.id, {"visibility": "followers"}) # changed after posting + activity = publishing.delete_post(user.id, "alice", post) + assert activity.document["to"] == [PUBLIC] # still addressed as it was posted + + +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") + already_deleted = publishing.publish(user.id, "alice", "weekly", "2026-W02", text="c", html="c") + 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 + assert len([act for act in all_activities() if act.activity_type == "Delete"]) == 3 + + +def test_turning_sharing_off_deletes_posts_before_rejecting(fed_client, remote, sharing_user): + bob = approved_follower(fed_client, remote, sharing_user, "bob") + from scrobbler.services.accounts import issue_ui_token + + auth = {"Authorization": f"Bearer {issue_ui_token(sharing_user)}"} + publishing.publish(sharing_user.id, "alice", "weekly", "2026-W01", text="x", html="x") + db.session.commit() + + response = fed_client.patch( + "/api/v1/federation/settings", json={"enabled": False}, headers=auth + ) + assert response.status_code == 200 + types = [a.activity_type for a in all_activities()] + assert types.count("Delete") == 1 + assert types.count("Reject") == 1 + assert types.index("Delete") < types.index("Reject") # Delete queued before the Reject + + [post] = db.session.scalars(db.select(FederationPost)).all() + assert post.deleted_at is not None + delete_activity = next(a for a in all_activities() if a.activity_type == "Delete") + assert [d.inbox for d in deliveries_for(delete_activity.id)] == [bob.server.url("/inbox")] diff --git a/tests/test_federation_schedule.py b/tests/test_federation_schedule.py new file mode 100644 index 0000000..3d8f936 --- /dev/null +++ b/tests/test_federation_schedule.py @@ -0,0 +1,98 @@ +"""Pure week-boundary math for scheduled posts (protocol/schedule.py).""" + +from datetime import UTC, datetime, timedelta +from zoneinfo import ZoneInfo + +import pytest + +from scrobbler.federation.protocol import schedule + +# Confirmed with date().isocalendar(): 2025-12-29, 2026-01-05 and 2026-01-12 are Mondays, +# ISO weeks 2026-W01, 2026-W02 and 2026-W03 respectively (the first spans the year +# boundary: Dec 29 2025 is in ISO week 2026-W01). +STABLE_ZONES = ["UTC", "Europe/London", "Pacific/Auckland", "America/Los_Angeles"] + + +def local(zone: str, *args) -> datetime: + return datetime(*args, tzinfo=ZoneInfo(zone)) + + +@pytest.mark.parametrize("zone", STABLE_ZONES) +def test_just_before_the_gate_targets_the_week_before_last(zone): + now = local(zone, 2026, 1, 12, 8, 59).astimezone(UTC) + start, end, key = schedule.target_week(now, ZoneInfo(zone)) + assert (start, end, key) == ( + local(zone, 2025, 12, 29, 0, 0).astimezone(UTC), + local(zone, 2026, 1, 5, 0, 0).astimezone(UTC), + "2026-W01", + ) + + +@pytest.mark.parametrize("zone", STABLE_ZONES) +def test_at_the_gate_targets_the_week_that_just_ended(zone): + now = local(zone, 2026, 1, 12, 9, 0).astimezone(UTC) + start, end, key = schedule.target_week(now, ZoneInfo(zone)) + assert (start, end, key) == ( + local(zone, 2026, 1, 5, 0, 0).astimezone(UTC), + local(zone, 2026, 1, 12, 0, 0).astimezone(UTC), + "2026-W02", + ) + + +@pytest.mark.parametrize("zone", STABLE_ZONES) +def test_any_time_until_the_next_gate_targets_the_same_week(zone): + """The whole week between two Monday-09:00 gates targets the same week just ended.""" + midweek = local(zone, 2026, 1, 14, 15, 30).astimezone(UTC) # a Wednesday afternoon + _, _, key = schedule.target_week(midweek, ZoneInfo(zone)) + assert key == "2026-W02" + + +def test_target_week_across_a_daylight_saving_change(): + """Europe/London springs forward on 2026-03-29: the week Mon 23 Mar - Mon 30 Mar is + only 6 days 23 hours of real (UTC) time, even though it's a full 7 local days.""" + tz = ZoneInfo("Europe/London") + gate = datetime(2026, 3, 30, 9, 0, tzinfo=tz).astimezone(UTC) # 08:00 UTC (BST = UTC+1) + + start, end, key = schedule.target_week(gate, tz) + assert key == "2026-W13" + assert start == datetime(2026, 3, 23, 0, 0, tzinfo=UTC) # still GMT + assert end == datetime(2026, 3, 29, 23, 0, tzinfo=UTC) # BST has started: UTC+1 + assert end - start == timedelta(days=6, hours=23) + + just_before = gate - timedelta(minutes=1) + _, _, earlier_key = schedule.target_week(just_before, tz) + assert earlier_key == "2026-W12" + + +def test_a_worker_down_for_weeks_only_targets_the_most_recent_one(): + """target_week is a pure function of `now`: however much time has passed, it always + names exactly one week (the latest eligible one), never a backlog of several.""" + tz = ZoneInfo("UTC") + # A month after 2026-W02 (confirmed above); Feb 2 2026 is the Monday of ISO week 6. + right_after_an_outage = datetime(2026, 2, 2, 10, 0, tzinfo=UTC) + _, _, key = schedule.target_week(right_after_an_outage, tz) + assert key == "2026-W05" # the week that ended just before "now" (Jan 26 - Feb 2) + + +@pytest.mark.parametrize("name", ["not/a/zone", "", "Mars/Phobos", "utc but wrong"]) +def test_resolve_timezone_falls_back_to_utc_for_bad_names(name): + assert schedule.resolve_timezone(name) == ZoneInfo("UTC") + + +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_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') diff --git a/tests/test_federation_web.py b/tests/test_federation_web.py new file mode 100644 index 0000000..f452174 --- /dev/null +++ b/tests/test_federation_web.py @@ -0,0 +1,222 @@ +import xml.etree.ElementTree as ET +from urllib.parse import urlsplit + +import pytest + +from scrobbler.extensions import db +from scrobbler.federation import publishing, sharing + +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 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 + + 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"] == [ + {"type": "PropertyValue", "name": "Now playing", "value": "Reckoner by Radiohead"} + ] + + +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" + + +@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["first"]) == ( + "OrderedCollection", + 0, + f"{BASE}/users/alice/outbox?page=1", + ) + assert "orderedItems" not in outbox # paged: points at the first page instead + followers = fed_client.get("/users/alice/followers", headers=AP).get_json() + assert followers["totalItems"] == 0 and "orderedItems" not in followers + + +def test_outbox_paging_lists_public_and_unlisted_but_not_followers_only( + fed_client, fed_ctx, sharing_user +): + sharing.update(sharing_user.id, {"visibility": "public"}) + publishing.publish(sharing_user.id, "alice", "weekly", "a", text="first", html="

      first

      ") + sharing.update(sharing_user.id, {"visibility": "unlisted"}) + publishing.publish(sharing_user.id, "alice", "weekly", "b", text="second", html="

      second

      ") + sharing.update(sharing_user.id, {"visibility": "followers"}) + publishing.publish(sharing_user.id, "alice", "weekly", "c", text="third", html="

      third

      ") + + root = fed_client.get("/users/alice/outbox", headers=AP).get_json() + assert root["totalItems"] == 2 # the followers-only one isn't counted here + + page = fed_client.get("/users/alice/outbox?page=1", headers=AP).get_json() + assert page["type"] == "OrderedCollectionPage" + assert page["partOf"] == f"{BASE}/users/alice/outbox" + # Newest first: "second" (unlisted) was published after "first" (public). + assert [item["object"]["content"] for item in page["orderedItems"]] == [ + "

      second

      ", + "

      first

      ", + ] + assert "next" not in page + assert "prev" not in page + + +def test_outbox_paging_links(fed_client, fed_ctx, sharing_user, monkeypatch): + monkeypatch.setattr(publishing, "OUTBOX_PAGE_SIZE", 1) + sharing.update(sharing_user.id, {"visibility": "public"}) + for key in ("a", "b"): + publishing.publish(sharing_user.id, "alice", "weekly", key, text="t", html="

      t

      ") + + first = fed_client.get("/users/alice/outbox?page=1", headers=AP).get_json() + assert len(first["orderedItems"]) == 1 + assert first["next"] == f"{BASE}/users/alice/outbox?page=2" + assert "prev" not in first + + second = fed_client.get("/users/alice/outbox?page=2", headers=AP).get_json() + assert len(second["orderedItems"]) == 1 + assert "next" not in second + assert second["prev"] == f"{BASE}/users/alice/outbox?page=1" + + +def test_outbox_missing_user_is_not_found(fed_client, fed_ctx): + assert fed_client.get("/users/nobody/outbox", headers=AP).status_code == 404 + assert fed_client.get("/users/nobody/outbox?page=1", headers=AP).status_code == 404 + + +def test_post_note_serves_a_public_note(fed_client, fed_ctx, sharing_user): + sharing.update(sharing_user.id, {"visibility": "public"}) + post = publishing.publish(sharing_user.id, "alice", "weekly", "a", text="t", html="

      t

      ") + + note_uuid = post.activity.document["object"]["id"].rsplit("/", 1)[-1] + response = fed_client.get(f"/users/alice/posts/{note_uuid}", headers=AP) + assert response.status_code == 200 + doc = response.get_json() + assert (doc["type"], doc["content"]) == ("Note", "

      t

      ") + + +def test_post_note_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): not listed to an unauthenticated fetch + assert fed_client.get(f"/users/alice/posts/{note_uuid}", headers=AP).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"/users/alice/posts/{note_uuid}", headers=AP).status_code == 404 + + assert fed_client.get("/users/alice/posts/not-a-real-uuid", headers=AP).status_code == 404 + assert fed_client.get("/users/nobody/posts/not-a-real-uuid", headers=AP).status_code == 404 + + +def test_post_note_browser_is_redirected_to_the_ui_page(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] + 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?u=alice&id={note_uuid}" + + +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_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 diff --git a/tests/test_federation_weekly.py b/tests/test_federation_weekly.py new file mode 100644 index 0000000..4dda2ba --- /dev/null +++ b/tests/test_federation_weekly.py @@ -0,0 +1,230 @@ +"""Weekly summaries end to end: publishing/weekly.py against a real database.""" + +from datetime import UTC, datetime + +import pytest + +from scrobbler.extensions import db +from scrobbler.federation import publishing, sharing +from scrobbler.federation.models import FederationActivity, FederationPost +from scrobbler.federation.publishing import weekly +from scrobbler.models import Scrobble + +# 2026-01-05 and 2026-01-12 are Mondays (ISO weeks 2026-W02 and 2026-W03); confirmed in +# test_federation_schedule.py. The gate for W02 (Monday 2026-01-12 09:00 UTC) is when a +# summary of that week becomes postable. +GATE = datetime(2026, 1, 12, 9, 0, tzinfo=UTC) + + +def played(user, artist, track, when, album=None): + db.session.add( + Scrobble(user_id=user.id, artist=artist, track=track, album=album, played_at=when) + ) + + +def a_scrobble_in_the_target_week(user, hour=12): + played(user, "Radiohead", "Reckoner", datetime(2026, 1, 6, hour, tzinfo=UTC)) + + +@pytest.fixture +def sharing_settings(fed_ctx, user): + _, _ = sharing.update(user.id, {"enabled": True}) + return sharing.settings_for(user.id) + + +def posts_for(user_id): + return db.session.scalars(db.select(FederationPost).filter_by(user_id=user_id)).all() + + +def test_an_empty_week_is_not_posted(fed_ctx, user, sharing_settings): + outcome = weekly.check_and_post(sharing_settings, GATE) + assert outcome == "skipped_empty" + assert posts_for(user.id) == [] + + +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) + assert (post.kind, post.key) == ("weekly", "weekly:2026-W02") + 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): + a_scrobble_in_the_target_week(user) + first = weekly.check_and_post(sharing_settings, GATE) + second = weekly.check_and_post(sharing_settings, GATE) + assert (first, second) == ("posted", "already_posted") + assert len(posts_for(user.id)) == 1 + + +def test_before_the_gate_nothing_is_posted_yet(fed_ctx, user, sharing_settings): + a_scrobble_in_the_target_week(user) + just_before_gate = GATE.replace(minute=59, hour=8) + outcome = weekly.check_and_post(sharing_settings, just_before_gate) + # Before the gate, the target is the *previous* week (empty), so this is skipped — + # not an error, and the play in the now-current week isn't lost, just not due yet. + assert outcome == "skipped_empty" + assert posts_for(user.id) == [] + + +def test_weekly_summaries_can_be_switched_off(fed_ctx, user, sharing_settings): + a_scrobble_in_the_target_week(user) + sharing.update(user.id, {"post_weekly_summary": False}) + outcome = weekly.check_and_post(sharing.settings_for(user.id), GATE) + assert outcome == "disabled" + assert posts_for(user.id) == [] + + +def test_a_user_who_stopped_sharing_is_not_posted_for(fed_ctx, user): + sharing.update(user.id, {"enabled": True}) + a_scrobble_in_the_target_week(user) + settings = sharing.settings_for(user.id) # a stale copy: still says "sharing" + sharing.update(user.id, {"enabled": False}) + # check_and_post's own has_post()/enabled check can't catch this: the settings + # object it was handed is stale. publish() re-reads settings itself and refuses — + # defence in depth against exactly this race between a worker pass starting and a + # user disabling sharing mid-pass. + outcome = weekly.check_and_post(settings, GATE) + assert outcome == "already_posted" # no post resulted, whatever the exact label + assert posts_for(user.id) == [] + + +def test_a_worker_down_for_weeks_posts_only_the_latest_week(fed_ctx, user, sharing_settings): + # Plays spread across three different weeks + played(user, "A", "Old", datetime(2025, 12, 22, 12, tzinfo=UTC)) # weeks before 2026-W02 + played(user, "B", "Older", datetime(2025, 12, 29, 12, tzinfo=UTC)) + a_scrobble_in_the_target_week(user) # 2026-W02: the only week that should be posted + + much_later = datetime(2026, 3, 1, 12, tzinfo=UTC) + weekly.check_and_post(sharing_settings, much_later) + # Nothing posted: the target week by March is nowhere near W02 or the empty ones + assert posts_for(user.id) == [] + + weekly.check_and_post(sharing_settings, GATE) + [post] = posts_for(user.id) + assert post.key == "weekly:2026-W02" + + +def test_check_all_covers_every_sharing_user_and_isolates_failures(fed_ctx, make_user): + alice = make_user(username="alice_weekly") + bob = make_user(username="bob_weekly") + sharing.update(alice.id, {"enabled": True}) + sharing.update(bob.id, {"enabled": True}) + # Simulate a since-invalid stored value (e.g. a renamed IANA zone), bypassing + # update()'s own validation, to prove resolve_timezone()'s fallback keeps the task + # going for this user instead of raising and skipping everyone after them. + bob_settings = sharing.settings_for(bob.id) + bob_settings.timezone = "not-a-real-zone" + db.session.commit() + a_scrobble_in_the_target_week(alice) + a_scrobble_in_the_target_week(bob) + + weekly.check_all(GATE) + + assert len(posts_for(alice.id)) == 1 + assert len(posts_for(bob.id)) == 1 # a bad stored timezone doesn't stop the post either + + +def test_check_all_skips_users_without_weekly_summaries_or_not_sharing(fed_ctx, make_user): + off = make_user(username="off") + sharing.update(off.id, {"enabled": True, "post_weekly_summary": False}) + never_shared = make_user(username="never_shared") + a_scrobble_in_the_target_week(off) + a_scrobble_in_the_target_week(never_shared) + + weekly.check_all(GATE) + + assert posts_for(off.id) == [] + assert posts_for(never_shared.id) == [] + + +def test_the_task_is_registered_when_federation_is_on(fed_app): + from scrobbler import worker + + assert "federation.weekly" in worker.registered(fed_app) + + +def test_the_task_is_not_registered_when_federation_is_off(app): + from scrobbler import worker + + assert "federation.weekly" not in worker.registered(app) + + +def test_deleting_a_weekly_post_works_like_any_other_post(fed_ctx, user, sharing_settings): + a_scrobble_in_the_target_week(user) + weekly.check_and_post(sharing_settings, GATE) + [post] = posts_for(user.id) + activity = publishing.delete_post(user.id, "alice", post) + 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 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_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} diff --git a/tests/test_openapi.py b/tests/test_openapi.py index 8e84d9f..a71b154 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,14 @@ 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"), + ("/api/v1/federation/profiles/{username}/posts/{post_uuid}", "get"), + } for path, operations in spec["paths"].items(): if not path.startswith("/api/v1/"): continue @@ -67,9 +97,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" ) diff --git a/tests/test_stats.py b/tests/test_stats.py index 184311a..e16642a 100644 --- a/tests/test_stats.py +++ b/tests/test_stats.py @@ -171,3 +171,85 @@ def test_me_summary(client, auth, history): def test_me_requires_auth(client): for path in ("recent", "top/artists", "counts", "summary", "now-playing"): assert client.get(f"/api/v1/me/{path}").status_code == 401 + + +# --- Explicit windows (start inclusive, end exclusive) -------------------------------- +# Used by federation's weekly summaries (phase 3): a fixed window, not "N days back". + +WINDOW_START = datetime(2026, 1, 5, tzinfo=UTC) # a Monday +WINDOW_END = datetime(2026, 1, 12, tzinfo=UTC) # the following Monday + + +def played(user, artist, track, when): + db.session.add(Scrobble(user_id=user.id, artist=artist, track=track, played_at=when)) + + +@pytest.fixture +def windowed_history(user): + # Inside the window + played(user, "Radiohead", "Reckoner", WINDOW_START + timedelta(days=1)) + played(user, "Radiohead", "Nude", WINDOW_START + timedelta(days=2)) + played(user, "Björk", "Jóga", WINDOW_START + timedelta(days=3)) + # Exactly at the start boundary: included (inclusive) + played(user, "Radiohead", "Nude", WINDOW_START) + # Exactly at the end boundary: excluded (exclusive) + played(user, "Portishead", "Roads", WINDOW_END) + # Well outside the window on both sides + played(user, "Old Artist", "Old Track", WINDOW_START - timedelta(days=10)) + played(user, "Future Artist", "Future Track", WINDOW_END + timedelta(days=10)) + db.session.commit() + + +def test_scrobble_count_between(user, windowed_history): + from scrobbler.services import stats + + assert stats.scrobble_count_between(user, WINDOW_START, WINDOW_END) == 4 + + +def test_top_artists_between(user, windowed_history): + from scrobbler.services import stats + + items = stats.top_artists_between(user, WINDOW_START, WINDOW_END) + assert [(i.rank, i.name, i.playcount) for i in items] == [(1, "Radiohead", 3), (2, "Björk", 1)] + + +def test_top_tracks_between(user, windowed_history): + from scrobbler.services import stats + + items = stats.top_tracks_between(user, WINDOW_START, WINDOW_END) + assert items[0].name == "Nude" + assert items[0].artist == "Radiohead" + assert items[0].playcount == 2 + + +def test_between_window_has_no_plays_outside_it(user): + from scrobbler.services import stats + + empty_start = WINDOW_END + timedelta(days=100) + empty_end = empty_start + timedelta(days=7) + assert stats.scrobble_count_between(user, empty_start, empty_end) == 0 + assert stats.top_artists_between(user, empty_start, empty_end) == [] + assert stats.top_tracks_between(user, empty_start, empty_end) == [] + + +def test_between_is_scoped_to_the_user(user, make_user, windowed_history): + from scrobbler.services import stats + + other = make_user(username="mallory") + add(other, "Someone Else", "Track", days_ago=(NOW - WINDOW_START).total_seconds() / 86400 - 1) + db.session.commit() + assert stats.scrobble_count_between(user, WINDOW_START, WINDOW_END) == 4 + assert stats.scrobble_count_between(other, WINDOW_START, WINDOW_END) == 1 + + +def test_rolling_periods_are_unaffected_by_the_window_refactor(client, api_app, history): + """_user_scrobbles(user, period) now delegates to _between(); this pins its old + behaviour (unbounded end, inclusive start) so the refactor can't silently change it.""" + response = client.get( + f"/2.0/?method=user.getTopArtists&user=alice&period=7day&api_key={api_app.api_key}" + ) + top = ET.fromstring(response.data).find("topartists") + assert [(a.find("name").text, a.find("playcount").text) for a in top] == [ + ("Radiohead", "3"), + ("Björk", "2"), + ] diff --git a/tests/test_ui_auth.py b/tests/test_ui_auth.py index 7e9bc8b..6aa3c0a 100644 --- a/tests/test_ui_auth.py +++ b/tests/test_ui_auth.py @@ -2,6 +2,7 @@ from datetime import UTC, datetime, timedelta from scrobbler.extensions import db from scrobbler.models import UiToken +from scrobbler.services import accounts def register(client, username="bob", password="correct horse", email=None): @@ -98,3 +99,8 @@ def test_cors_allows_only_the_configured_ui_origin(client, app): "/api/v1/auth/me", headers={"Origin": "https://evil.example", **preflight} ) assert "Access-Control-Allow-Origin" not in evil.headers + + +def test_get_user_by_id(app, user): + assert accounts.get_user(user.id).username == user.username + assert accounts.get_user(user.id + 999) is None 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..fb3ab0d --- /dev/null +++ b/tests/test_worker.py @@ -0,0 +1,91 @@ +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 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(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): + 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 diff --git a/uv.lock b/uv.lock index adf7c73..f2e3770 100644 --- a/uv.lock +++ b/uv.lock @@ -73,6 +73,88 @@ 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" +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 +173,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" @@ -182,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" @@ -527,6 +672,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,12 +984,14 @@ name = "scrobby" version = "0.1.0" source = { editable = "." } dependencies = [ + { name = "cryptography" }, { name = "flask" }, { name = "flask-cors" }, { name = "flask-migrate" }, { name = "flask-smorest" }, { name = "flask-sqlalchemy" }, { name = "gunicorn" }, + { name = "httpcore" }, { name = "prometheus-client" }, { name = "psycopg", extra = ["binary"] }, { name = "python-dotenv" }, @@ -852,12 +1008,14 @@ 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" }, { 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" },