From f312c4b5779f25245aeb0210dd4990d286b2a52a Mon Sep 17 00:00:00 2001 From: Matthew Daubney Date: Fri, 25 Sep 2026 21:29:55 +0100 Subject: [PATCH] Inbox: intake and verified processing of follows (phase 2, step 4) Intake (in the request, no network): size, content type and shape checks, blocked domains refused (403), duplicates acknowledged once, then stored and answered 202. Processing (federation.inbox worker task): - verify the HTTP signature with either scheme, as of when it arrived, using the cached key and refreshing the sender once on failure (key rotation); a deleted account's Delete still verifies from cache - the signer must be the activity's actor and the activity id must be on the actor's host - handlers: Follow (accept, or pending with manual approval; repeat follows re-accepted; blocked accounts rejected), Undo of a Follow (only by the same actor), Delete of an actor, Update of an actor; anything else recorded - items being processed are marked, retried on transient failures, re-queued if a worker dies, and pruned after 30 days Outgoing Accept/Reject/Block activities are stored with stable ids and queued per inbox for the delivery task (next step). Public activities are fetchable at /activities/. Metrics for inbox activities and signature checks. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW --- docs/openapi.json | 81 ++++- src/scrobbler/federation/__init__.py | 6 + src/scrobbler/federation/activities.py | 70 +++++ src/scrobbler/federation/followers.py | 124 ++++++++ src/scrobbler/federation/ids.py | 36 +++ src/scrobbler/federation/inbox.py | 321 ++++++++++++++++++++ src/scrobbler/federation/metrics.py | 15 +- src/scrobbler/federation/openapi.py | 31 +- src/scrobbler/federation/outbound.py | 14 +- src/scrobbler/federation/protocol/vocab.py | 32 ++ src/scrobbler/federation/remote.py | 4 +- src/scrobbler/federation/web.py | 42 ++- tests/federation_helpers.py | 85 ++++++ tests/test_federation_inbox.py | 327 +++++++++++++++++++++ tests/test_federation_web.py | 19 -- 15 files changed, 1147 insertions(+), 60 deletions(-) create mode 100644 src/scrobbler/federation/activities.py create mode 100644 src/scrobbler/federation/followers.py create mode 100644 src/scrobbler/federation/ids.py create mode 100644 src/scrobbler/federation/inbox.py create mode 100644 tests/federation_helpers.py create mode 100644 tests/test_federation_inbox.py diff --git a/docs/openapi.json b/docs/openapi.json index 3138115..d782bfe 100644 --- a/docs/openapi.json +++ b/docs/openapi.json @@ -2340,17 +2340,26 @@ "ActivityPub" ], "summary": "User inbox", - "description": "Receives activities for one user (signed deliveries).", + "description": "Receives signed activities for one user. They're stored and answered with 202, then verified and processed in the background.", "operationId": "federation_user_inbox", "responses": { "202": { - "description": "Accepted" + "description": "Accepted for processing (also for a repeated activity)" + }, + "400": { + "description": "Not an activity with an id, type and actor" + }, + "403": { + "description": "The sender's domain is blocked" }, "404": { - "description": "Unknown, or not sharing (the two are indistinguishable)" + "description": "No such user sharing (user inbox)" }, "413": { - "description": "Too large" + "description": "Larger than 256 KB" + }, + "415": { + "description": "Not ActivityPub JSON" } }, "parameters": [ @@ -2391,14 +2400,26 @@ "ActivityPub" ], "summary": "Shared inbox", - "description": "Receives activities for any user on this server.", + "description": "Receives signed activities for any user on this server (as for the user inbox).", "operationId": "federation_shared_inbox", "responses": { "202": { - "description": "Accepted" + "description": "Accepted for processing (also for a repeated activity)" + }, + "400": { + "description": "Not an activity with an id, type and actor" + }, + "403": { + "description": "The sender's domain is blocked" + }, + "404": { + "description": "No such user sharing (user inbox)" }, "413": { - "description": "Too large" + "description": "Larger than 256 KB" + }, + "415": { + "description": "Not ActivityPub JSON" } }, "requestBody": { @@ -2411,6 +2432,52 @@ } } } + }, + "/activities/{activity_uuid}": { + "get": { + "tags": [ + "ActivityPub" + ], + "summary": "Activity", + "description": "One of our activities, when public. Replies to follows aren't public.", + "operationId": "federation_activity", + "responses": { + "200": { + "description": "Activity", + "content": { + "application/activity+json": { + "schema": { + "type": "object" + } + } + } + }, + "404": { + "description": "Not found or not public" + } + }, + "parameters": [ + { + "name": "activity_uuid", + "in": "path", + "required": true, + "schema": { + "type": "string" + } + } + ] + }, + "parameters": [ + { + "in": "path", + "name": "activity_uuid", + "required": true, + "schema": { + "type": "string", + "minLength": 1 + } + } + ] } }, "tags": [ diff --git a/src/scrobbler/federation/__init__.py b/src/scrobbler/federation/__init__.py index 769b0f1..622b3ac 100644 --- a/src/scrobbler/federation/__init__.py +++ b/src/scrobbler/federation/__init__.py @@ -35,3 +35,9 @@ def init_app(app: Flask) -> None: core_api = get_api(app) core_api.register_blueprint(api.blp, url_prefix="/api/v1/federation") openapi.register(app, core_api) + + from scrobbler import worker + from scrobbler.federation import inbox + + worker.register_task(app, "federation.inbox", inbox.work_once) + worker.register_periodic(app, "federation.inbox.maintenance", 300, inbox.maintenance) diff --git a/src/scrobbler/federation/activities.py b/src/scrobbler/federation/activities.py new file mode 100644 index 0000000..2b5691e --- /dev/null +++ b/src/scrobbler/federation/activities.py @@ -0,0 +1,70 @@ +"""Activities we send: stored (so they have a stable id) and queued for delivery.""" + +import uuid + +from scrobbler.extensions import db +from scrobbler.federation import ids +from scrobbler.federation.models import ( + FederationActivity, + FederationDelivery, + FederationFollower, + FederationRemoteActor, +) +from scrobbler.federation.protocol import vocab + + +def _store(user_id: int, document_for, public: bool = False) -> FederationActivity: + """Create an activity. `document_for(activity_url)` builds its JSON.""" + activity_uuid = str(uuid.uuid4()) + document = document_for(ids.activity_url(activity_uuid)) + activity = FederationActivity( + id=activity_uuid, + user_id=user_id, + activity_type=document["type"], + document=document, + public=public, + ) + db.session.add(activity) + return activity + + +def queue(activity: FederationActivity, inboxes: list[str]) -> list[FederationDelivery]: + deliveries = [ + FederationDelivery(activity_id=activity.id, inbox=inbox) + for inbox in dict.fromkeys(inboxes) # one per distinct inbox + ] + db.session.add_all(deliveries) + return deliveries + + +def accept_follow(username: str, follower: FederationFollower) -> FederationActivity: + activity = _store( + follower.user_id, + lambda url: vocab.accept(url, ids.actor_id(username), follower.follow_activity), + ) + queue(activity, [follower.actor.inbox]) # replies go to their own inbox + return activity + + +def reject_follow(username: str, follower: FederationFollower) -> FederationActivity: + activity = _store( + follower.user_id, + lambda url: vocab.reject(url, ids.actor_id(username), follower.follow_activity), + ) + queue(activity, [follower.actor.inbox]) + return activity + + +def reject_follow_activity( + user_id: int, username: str, follow: dict, actor: FederationRemoteActor +) -> FederationActivity: + """Reject a Follow that never became a follower (e.g. from a blocked account).""" + activity = _store(user_id, lambda url: vocab.reject(url, ids.actor_id(username), follow)) + queue(activity, [actor.inbox]) + return activity + + +def block(user_id: int, username: str, actor: FederationRemoteActor) -> FederationActivity: + activity = _store(user_id, lambda url: vocab.block(url, ids.actor_id(username), actor.uri)) + queue(activity, [actor.inbox]) + return activity diff --git a/src/scrobbler/federation/followers.py b/src/scrobbler/federation/followers.py new file mode 100644 index 0000000..36004c4 --- /dev/null +++ b/src/scrobbler/federation/followers.py @@ -0,0 +1,124 @@ +"""Follower state changes, from incoming activities and from the user's own actions. + +Every change that the other server needs to know about queues an activity (Accept, +Reject or Block); the delivery task sends it. Callers commit. +""" + +from datetime import UTC, datetime + +from scrobbler.extensions import db +from scrobbler.federation import activities +from scrobbler.federation.models import FederationBlock, FederationFollower, FederationRemoteActor + + +def _now() -> datetime: + return datetime.now(UTC) + + +def get(user_id: int, actor: FederationRemoteActor) -> FederationFollower | None: + return db.session.scalar( + db.select(FederationFollower).filter_by(user_id=user_id, remote_actor_id=actor.id) + ) + + +def is_blocked(user_id: int, actor: FederationRemoteActor) -> bool: + return ( + db.session.scalar( + db.select(FederationBlock).filter_by(user_id=user_id, remote_actor_id=actor.id) + ) + is not None + ) + + +def follow_received( + user_id: int, username: str, manual_approval: bool, actor: FederationRemoteActor, follow: dict +) -> str: + """Handle a Follow. Returns what happened: accepted, pending, refollowed or blocked.""" + if is_blocked(user_id, actor): + activities.reject_follow_activity(user_id, username, follow, actor) + return "blocked" + follower = get(user_id, actor) + if follower is not None: + # A repeat Follow (e.g. they lost our Accept): keep the newest activity and + # answer again if we'd already accepted. + follower.follow_activity_id, follower.follow_activity = follow["id"], follow + if follower.state == "accepted": + activities.accept_follow(username, follower) + return "refollowed" + return "pending" + follower = FederationFollower( + user_id=user_id, + remote_actor_id=actor.id, + actor=actor, + state="pending" if manual_approval else "accepted", + follow_activity_id=follow["id"], + follow_activity=follow, + accepted_at=None if manual_approval else _now(), + ) + db.session.add(follower) + db.session.flush() + if not manual_approval: + activities.accept_follow(username, follower) + return "accepted" + return "pending" + + +def undo_follow(user_id: int, actor: FederationRemoteActor) -> bool: + follower = get(user_id, actor) + if follower is None: + return False + db.session.delete(follower) + return True + + +def actor_deleted(actor: FederationRemoteActor) -> int: + """The remote account was deleted: it follows no one here any more.""" + followers = db.session.scalars( + db.select(FederationFollower).filter_by(remote_actor_id=actor.id) + ).all() + for follower in followers: + db.session.delete(follower) + actor.gone = True + return len(followers) + + +# --- The user's own actions -------------------------------------------------------------- + + +def approve(username: str, follower: FederationFollower) -> None: + if follower.state != "pending": + return + follower.state, follower.accepted_at = "accepted", _now() + activities.accept_follow(username, follower) + + +def remove(username: str, follower: FederationFollower) -> None: + """Decline a request or remove a follower: both are a Reject for the other server.""" + activities.reject_follow(username, follower) + db.session.delete(follower) + + +def block(username: str, follower: FederationFollower) -> FederationBlock: + blocked = FederationBlock(user_id=follower.user_id, remote_actor_id=follower.remote_actor_id) + db.session.add(blocked) + activities.block(follower.user_id, username, follower.actor) + db.session.delete(follower) + return blocked + + +def reject_all(user_id: int, username: str) -> int: + """Sharing switched off: tell every follower, then forget them.""" + followers = db.session.scalars(db.select(FederationFollower).filter_by(user_id=user_id)).all() + for follower in followers: + remove(username, follower) + return len(followers) + + +def counts(user_id: int) -> dict[str, int]: + rows = db.session.execute( + db.select(FederationFollower.state, db.func.count()) + .filter_by(user_id=user_id) + .group_by(FederationFollower.state) + ).all() + found = dict(rows) + return {"accepted": found.get("accepted", 0), "pending": found.get("pending", 0)} diff --git a/src/scrobbler/federation/ids.py b/src/scrobbler/federation/ids.py new file mode 100644 index 0000000..8fa139d --- /dev/null +++ b/src/scrobbler/federation/ids.py @@ -0,0 +1,36 @@ +"""Our ActivityPub IDs, all built from FEDERATION_BASE_URL (never the request).""" + +from flask import current_app + + +def base_url() -> str: + return current_app.extensions["federation"].base_url + + +def actor_id(username: str) -> str: + return f"{base_url()}/users/{username}" + + +def key_id(username: str) -> str: + return f"{actor_id(username)}#main-key" + + +def instance_actor_id() -> str: + return f"{base_url()}/actor" + + +def instance_key_id() -> str: + return f"{instance_actor_id()}#main-key" + + +def activity_url(activity_uuid: str) -> str: + return f"{base_url()}/activities/{activity_uuid}" + + +def username_from_actor_id(uri: str | None) -> str | None: + """`/users/` -> name; None for anything else.""" + prefix = f"{base_url()}/users/" + if not uri or not uri.startswith(prefix): + return None + name = uri[len(prefix) :] + return name if name and "/" not in name and "#" not in name and "?" not in name else None diff --git a/src/scrobbler/federation/inbox.py b/src/scrobbler/federation/inbox.py new file mode 100644 index 0000000..2dc735f --- /dev/null +++ b/src/scrobbler/federation/inbox.py @@ -0,0 +1,321 @@ +"""Receiving activities. + +Intake (in the request): cheap checks only, then store and answer 202. No network calls, +so a flood of deliveries can't make us fetch things. + +Processing (the `federation.inbox` worker task): verify the HTTP signature (fetching the +sender's key), check the sender is who the activity says, then dispatch by type. +""" + +import json +import logging +from collections.abc import Callable +from datetime import UTC, datetime, timedelta +from urllib.parse import urlsplit + +from flask import current_app +from sqlalchemy import delete, update +from sqlalchemy.exc import IntegrityError + +from scrobbler.extensions import db +from scrobbler.federation import followers, ids, remote, sharing +from scrobbler.federation import metrics as fed_metrics +from scrobbler.federation.models import FederationInboxItem, FederationRemoteActor +from scrobbler.federation.net import FetchError +from scrobbler.federation.protocol import signatures +from scrobbler.federation.protocol.signatures import SignatureError, SignedRequest +from scrobbler.federation.protocol.vocab import object_id + +log = logging.getLogger(__name__) + +MAX_BYTES = 256 * 1024 +MAX_ATTEMPTS = 3 +KEPT_FOR = timedelta(days=30) +STALE_AFTER = timedelta(minutes=10) +# Only what signature checks need is kept from the request. +KEPT_HEADERS = ( + "host", + "date", + "digest", + "content-digest", + "signature", + "signature-input", + "authorization", + "content-type", + "content-length", +) +# Metric labels are limited to these; anything else is "other". +KNOWN_TYPES = { + "Follow", + "Undo", + "Delete", + "Update", + "Accept", + "Reject", + "Like", + "Announce", + "Create", + "Add", + "Remove", + "Move", + "Block", + "Flag", + "EmojiReact", +} + + +def type_label(activity_type) -> str: + return activity_type if activity_type in KNOWN_TYPES else "other" + + +def _host(url: str) -> str: + return (urlsplit(url).hostname or "").lower() + + +def _config(): + return current_app.extensions["federation"] + + +# --- Intake ------------------------------------------------------------------------------- + + +def receive(inbox_path: str, headers: dict[str, str], body: bytes) -> tuple[int, str]: + """Store a delivery for processing. Returns (HTTP status, outcome).""" + if len(body) > MAX_BYTES: + return 413, "too_large" + try: + doc = json.loads(body) + except (json.JSONDecodeError, UnicodeDecodeError): + doc = None + activity_id = doc.get("id") if isinstance(doc, dict) else None + activity_type = doc.get("type") if isinstance(doc, dict) else None + actor = object_id(doc.get("actor")) if isinstance(doc, dict) else None + if not all(isinstance(v, str) and v for v in (activity_id, activity_type, actor)): + fed_metrics.inbox_activities_total.labels(type="other", result="invalid").inc() + return 400, "invalid" + label = type_label(activity_type) + if len(activity_id) > 2048 or len(actor) > 2048: + fed_metrics.inbox_activities_total.labels(type=label, result="invalid").inc() + return 400, "invalid" + if _config().is_blocked(_host(actor)): + fed_metrics.inbox_activities_total.labels(type=label, result="blocked").inc() + return 403, "blocked" + + kept = {k.lower(): v for k, v in headers.items() if k.lower() in KEPT_HEADERS} + db.session.add( + FederationInboxItem( + activity_id=activity_id, + activity_type=activity_type[:64], + actor_uri=actor, + inbox_path=inbox_path[:512], + headers=kept, + body=body, + ) + ) + try: + db.session.commit() + except IntegrityError: # seen this activity before + db.session.rollback() + fed_metrics.inbox_activities_total.labels(type=label, result="duplicate").inc() + return 202, "duplicate" + fed_metrics.inbox_activities_total.labels(type=label, result="queued").inc() + return 202, "queued" + + +# --- Processing ------------------------------------------------------------------------------- + + +class Rejected(Exception): + """The activity won't be acted on; `reason` says why.""" + + def __init__(self, reason: str): + self.reason = reason + super().__init__(reason) + + +Handler = Callable[[dict, FederationRemoteActor], str] +HANDLERS: dict[str, Handler] = {} + + +def handles(activity_type: str): + def register(fn: Handler) -> Handler: + HANDLERS[activity_type] = fn + return fn + + return register + + +def _verify(item: FederationInboxItem) -> FederationRemoteActor: + """Check the signature (as of when it arrived); return the signing actor.""" + request = SignedRequest("POST", ids.base_url() + item.inbox_path, item.headers, item.body) + try: + scheme = signatures.detect(request).name + except SignatureError: + fed_metrics.signatures_total.labels(direction="in", scheme="none", result="missing").inc() + raise Rejected("signature_missing") from None + signer: dict[str, FederationRemoteActor] = {} + + def public_key_for(refresh: bool): + def lookup(key_id: str): + actor = remote.actor_for_key(key_id, refresh=refresh) + signer["actor"] = actor + return remote.load_public_key(actor.public_key_pem) + + return lookup + + try: + try: + signatures.verify(request, public_key_for(False), now=item.received_at) + except SignatureError as err: + if err.reason not in ("bad_signature", "unknown_key"): + raise + # Maybe they rotated their key: fetch the actor again, once + signatures.verify(request, public_key_for(True), now=item.received_at) + except SignatureError as err: + fed_metrics.signatures_total.labels(direction="in", scheme=scheme, result=err.reason).inc() + raise Rejected(f"signature_{err.reason}") from err + except remote.ActorError as err: + fed_metrics.signatures_total.labels(direction="in", scheme=scheme, result="bad_actor").inc() + raise Rejected("bad_actor") from err + fed_metrics.signatures_total.labels(direction="in", scheme=scheme, result="ok").inc() + return signer["actor"] + + +def _handle(item: FederationInboxItem) -> str: + actor = _verify(item) + doc = json.loads(item.body) + if object_id(doc.get("actor")) != actor.uri: + raise Rejected("actor_mismatch") # signed by someone other than the actor + if _host(doc["id"]) != actor.host: + raise Rejected("id_host_mismatch") + if _config().is_blocked(actor.host): + raise Rejected("blocked_domain") + handler = HANDLERS.get(doc.get("type")) + return handler(doc, actor) if handler else "recorded" + + +def claim_next() -> FederationInboxItem | None: + item = db.session.scalar( + db.select(FederationInboxItem) + .filter_by(status="queued") + .order_by(FederationInboxItem.received_at) + .limit(1) + .with_for_update(skip_locked=True) + ) + if item is None: + db.session.rollback() + return None + item.status = "processing" # processing commits (e.g. caching actors), so mark it + item.attempts += 1 + db.session.commit() + return item + + +def process(item: FederationInboxItem) -> None: + label = type_label(item.activity_type) + try: + outcome = _handle(item) + except Rejected as rejected: + db.session.rollback() + _finish(item, "rejected", rejected.reason) + fed_metrics.inbox_activities_total.labels(type=label, result="rejected").inc() + return + except Exception as err: + db.session.rollback() + transient = isinstance(err, FetchError) and err.reason == "network" + if not transient: + log.exception("inbox item %s failed", item.id) + if item.attempts < MAX_ATTEMPTS: + _finish(item, "queued", f"retrying: {err}"[:255], done=False) + return + _finish(item, "failed", str(err)[:255]) + fed_metrics.inbox_activities_total.labels(type=label, result="failed").inc() + return + db.session.commit() + _finish(item, "processed", outcome) + fed_metrics.inbox_activities_total.labels(type=label, result="processed").inc() + + +def _finish(item: FederationInboxItem, status: str, reason: str, done: bool = True) -> None: + item = db.session.get(FederationInboxItem, item.id) + item.status, item.reason = status, reason + if done: + item.processed_at = datetime.now(UTC) + db.session.commit() + + +def work_once() -> bool: + """Worker task: process the oldest queued delivery.""" + item = claim_next() + if item is None: + return False + process(item) + return True + + +def maintenance() -> None: + """Worker task (periodic): re-queue items a dead worker left behind; drop old ones.""" + now = datetime.now(UTC) + db.session.execute( + update(FederationInboxItem) + .where(FederationInboxItem.status == "processing") + .where(FederationInboxItem.received_at < now - STALE_AFTER) + .values(status="queued") + ) + db.session.execute( + delete(FederationInboxItem) + .where(FederationInboxItem.status != "queued") + .where(FederationInboxItem.received_at < now - KEPT_FOR) + ) + db.session.commit() + + +# --- Handlers ---------------------------------------------------------------------------------- + + +def _local_user(target): + """The sharing user an activity is addressed to, or Rejected.""" + username = ids.username_from_actor_id(object_id(target)) + found = sharing.shared_user(username) if username else None + if found is None: + raise Rejected("not_our_user") + return found + + +@handles("Follow") +def on_follow(doc: dict, actor: FederationRemoteActor) -> str: + user, settings = _local_user(doc.get("object")) + outcome = followers.follow_received( + user.id, user.username, settings.manually_approves_followers, actor, doc + ) + return f"follow_{outcome}" + + +@handles("Undo") +def on_undo(doc: dict, actor: FederationRemoteActor) -> str: + inner = doc.get("object") + if not isinstance(inner, dict) or inner.get("type") != "Follow": + return "undo_ignored" + if object_id(inner.get("actor")) not in (None, actor.uri): + raise Rejected("undo_other_actors_follow") + user, _ = _local_user(inner.get("object")) + return "unfollowed" if followers.undo_follow(user.id, actor) else "undo_not_following" + + +@handles("Delete") +def on_delete(doc: dict, actor: FederationRemoteActor) -> str: + if object_id(doc.get("object")) != actor.uri: + return "delete_ignored" # a post or similar: we don't store remote content + followers.actor_deleted(actor) + return "actor_deleted" + + +@handles("Update") +def on_update(doc: dict, actor: FederationRemoteActor) -> str: + obj = doc.get("object") + if not isinstance(obj, dict) or obj.get("type") not in remote.ACTOR_TYPES: + return "update_ignored" + if object_id(obj) != actor.uri: + raise Rejected("update_other_actor") + remote.get_actor(actor.uri, refresh=True) + return "actor_updated" diff --git a/src/scrobbler/federation/metrics.py b/src/scrobbler/federation/metrics.py index b08707c..091de27 100644 --- a/src/scrobbler/federation/metrics.py +++ b/src/scrobbler/federation/metrics.py @@ -18,9 +18,14 @@ inbox_requests_total = Counter( ["inbox"], ) -# Every scrobbler_federation_* series name, for the dashboard consistency test. -SERIES = ( - "scrobbler_federation_lookups_total", - "scrobbler_federation_sharing_changes_total", - "scrobbler_federation_inbox_requests_total", +inbox_activities_total = Counter( + "scrobbler_federation_inbox_activities_total", + "Activities received: queued, duplicate, blocked or invalid at intake; then processed, " + "rejected or failed", + ["type", "result"], +) +signatures_total = Counter( + "scrobbler_federation_signatures_total", + "HTTP signature checks (in) and signing (out), by scheme and result", + ["direction", "scheme", "result"], ) diff --git a/src/scrobbler/federation/openapi.py b/src/scrobbler/federation/openapi.py index a9c1f05..58ebf64 100644 --- a/src/scrobbler/federation/openapi.py +++ b/src/scrobbler/federation/openapi.py @@ -7,6 +7,14 @@ TAG = "ActivityPub" _AP = {"application/activity+json": {"schema": {"type": "object"}}} _NOT_FOUND = {"description": "Unknown, or not sharing (the two are indistinguishable)"} +_INBOX_RESPONSES = { + "202": {"description": "Accepted for processing (also for a repeated activity)"}, + "400": {"description": "Not an activity with an id, type and actor"}, + "403": {"description": "The sender's domain is blocked"}, + "404": {"description": "No such user sharing (user inbox)"}, + "413": {"description": "Larger than 256 KB"}, + "415": {"description": "Not ActivityPub JSON"}, +} _USERNAME = {"name": "username", "in": "path", "required": True, "schema": {"type": "string"}} # endpoint -> (method, summary, description, extra parameters, responses) @@ -120,20 +128,27 @@ _OPERATIONS = { "federation.user_inbox": ( "post", "User inbox", - "Receives activities for one user (signed deliveries).", + "Receives signed activities for one user. They're stored and answered with 202, then " + "verified and processed in the background.", [_USERNAME], - { - "202": {"description": "Accepted"}, - "404": _NOT_FOUND, - "413": {"description": "Too large"}, - }, + _INBOX_RESPONSES, ), "federation.shared_inbox": ( "post", "Shared inbox", - "Receives activities for any user on this server.", + "Receives signed activities for any user on this server (as for the user inbox).", [], - {"202": {"description": "Accepted"}, "413": {"description": "Too large"}}, + _INBOX_RESPONSES, + ), + "federation.activity": ( + "get", + "Activity", + "One of our activities, when public. Replies to follows aren't public.", + [{"name": "activity_uuid", "in": "path", "required": True, "schema": {"type": "string"}}], + { + "200": {"description": "Activity", "content": _AP}, + "404": {"description": "Not found or not public"}, + }, ), } diff --git a/src/scrobbler/federation/outbound.py b/src/scrobbler/federation/outbound.py index 021b442..d6cb576 100644 --- a/src/scrobbler/federation/outbound.py +++ b/src/scrobbler/federation/outbound.py @@ -4,7 +4,7 @@ import json from flask import current_app -from scrobbler.federation import keys +from scrobbler.federation import ids, keys from scrobbler.federation.net import Client, FetchError, Response from scrobbler.federation.protocol import signatures from scrobbler.federation.protocol.media import ACTIVITY_JSON, LD_JSON @@ -26,14 +26,6 @@ def client() -> Client: return existing -def instance_key_id() -> str: - return f"{current_app.extensions['federation'].base_url}/actor#main-key" - - -def user_key_id(username: str) -> str: - return f"{current_app.extensions['federation'].base_url}/users/{username}#main-key" - - def _signed_headers(method, url, headers, body, key_id, private_key, scheme) -> dict[str, str]: request = SignedRequest(method, url, headers, body) return {**headers, **signatures.sign(request, scheme, key_id, private_key)} @@ -47,7 +39,7 @@ def signed_get_json(url: str) -> dict: schemes = current_app.extensions["federation"].signature_schemes response = None for scheme in schemes: - signed = _signed_headers("GET", url, headers, b"", instance_key_id(), private, scheme) + signed = _signed_headers("GET", url, headers, b"", ids.instance_key_id(), private, scheme) response = client().request("GET", url, signed) if response.status != 401: break @@ -65,7 +57,7 @@ def signed_post(url: str, activity: dict, *, user_id: int, username: str) -> tup headers = {"Content-Type": LD_JSON, "Accept": ACTIVITY_JSON} response, used = None, "" for used in current_app.extensions["federation"].signature_schemes: - signed = _signed_headers("POST", url, headers, body, user_key_id(username), private, used) + signed = _signed_headers("POST", url, headers, body, ids.key_id(username), private, used) response = client().request("POST", url, signed, body) if response.status != 401: break diff --git a/src/scrobbler/federation/protocol/vocab.py b/src/scrobbler/federation/protocol/vocab.py index d9ce6d1..c9b8a94 100644 --- a/src/scrobbler/federation/protocol/vocab.py +++ b/src/scrobbler/federation/protocol/vocab.py @@ -145,3 +145,35 @@ def ordered_collection(collection_id: str, total: int, items: list | None = None if items is not None: doc["orderedItems"] = items return doc + + +def _response(kind: str, activity_id: str, actor_id: str, obj, to: str) -> dict: + return { + "@context": AS_CONTEXT, + "id": activity_id, + "type": kind, + "actor": actor_id, + "object": obj, + "to": [to], + } + + +def accept(activity_id: str, actor_id: str, follow: dict) -> dict: + """Accept a Follow (the original Follow is embedded, as Mastodon expects).""" + return _response("Accept", activity_id, actor_id, follow, follow["actor"]) + + +def reject(activity_id: str, actor_id: str, follow: dict) -> dict: + """Decline a follow request, or end an existing follow.""" + return _response("Reject", activity_id, actor_id, follow, follow["actor"]) + + +def block(activity_id: str, actor_id: str, blocked_actor: str) -> dict: + return _response("Block", activity_id, actor_id, blocked_actor, blocked_actor) + + +def object_id(value) -> str | None: + """An object's id, whether it's given inline (a dict) or as a bare URI.""" + if isinstance(value, dict): + value = value.get("id") + return value if isinstance(value, str) and value else None diff --git a/src/scrobbler/federation/remote.py b/src/scrobbler/federation/remote.py index e244236..1265e0a 100644 --- a/src/scrobbler/federation/remote.py +++ b/src/scrobbler/federation/remote.py @@ -109,7 +109,9 @@ def actor_for_key(key_id: str, refresh: bool = False) -> FederationRemoteActor: key document naming its owner.""" cached = db.session.scalar(db.select(FederationRemoteActor).filter_by(public_key_id=key_id)) if cached is not None and not refresh: - return get_actor(cached.uri) + # Any age will do for checking a signature (a failure refreshes once). This also + # lets a deleted account's Delete verify although its server now answers 410. + return cached document_url = urldefrag(key_id).url try: return _matching(get_actor(document_url, refresh=True), key_id) diff --git a/src/scrobbler/federation/web.py b/src/scrobbler/federation/web.py index 10818f7..ca89b57 100644 --- a/src/scrobbler/federation/web.py +++ b/src/scrobbler/federation/web.py @@ -6,13 +6,14 @@ import json from flask import Blueprint, Response, current_app, redirect, request -from scrobbler.federation import keys, sharing +from scrobbler.extensions import db +from scrobbler.federation import inbox, keys, sharing from scrobbler.federation import metrics as fed_metrics +from scrobbler.federation.models import FederationActivity from scrobbler.federation.protocol import hostmeta, media, nodeinfo, vocab, webfinger bp = Blueprint("federation", __name__) -MAX_INBOX_BYTES = 256 * 1024 _NOT_FOUND = {"error": "not found"} @@ -177,23 +178,46 @@ def instance_outbox(): return _json(vocab.ordered_collection(f"{_config().base_url}/actor/outbox", 0, [])) -# --- Inboxes (phase 2 processes deliveries) ----------------------------------------------- +# --- Inboxes ---------------------------------------------------------------------------- -def _accept_delivery(inbox: str): - if (request.content_length or 0) > MAX_INBOX_BYTES: +def _receive(inbox_path: str, kind: str): + if (request.content_length or 0) > inbox.MAX_BYTES: return _json({"error": "too large"}, content_type="application/json", status=413) - fed_metrics.inbox_requests_total.labels(inbox=inbox).inc() - return Response(status=202) + if not media.is_activitypub_content_type(request.content_type): + return _json( + {"error": "expected ActivityPub JSON"}, content_type="application/json", status=415 + ) + fed_metrics.inbox_requests_total.labels(inbox=kind).inc() + status, outcome = inbox.receive(inbox_path, dict(request.headers), request.get_data()) + if status == 202: + return Response(status=202) + return _json({"error": outcome}, content_type="application/json", status=status) + + +def _path() -> str: + return request.full_path.rstrip("?") @bp.post("/users//inbox") def user_inbox(username: str): if sharing.shared_user(username) is None: return _not_found("actor") - return _accept_delivery("user") + return _receive(_path(), "user") @bp.post("/inbox") def shared_inbox(): - return _accept_delivery("shared") + return _receive(_path(), "shared") + + +# --- Our activities ------------------------------------------------------------------------ + + +@bp.get("/activities/") +def activity(activity_uuid: str): + """Activities are fetchable when public; follow responses aren't.""" + found = db.session.get(FederationActivity, activity_uuid) + if found is None or not found.public: + return _json(_NOT_FOUND, content_type="application/json", status=404) + return _json(found.document) diff --git a/tests/federation_helpers.py b/tests/federation_helpers.py new file mode 100644 index 0000000..62f2250 --- /dev/null +++ b/tests/federation_helpers.py @@ -0,0 +1,85 @@ +"""A scripted remote fediverse account for federation tests.""" + +import dataclasses +import json +import uuid + +from cryptography.hazmat.primitives import serialization +from cryptography.hazmat.primitives.asymmetric import rsa + +from scrobbler.federation.protocol import signatures +from scrobbler.federation.protocol.signatures import SignedRequest + +OUR_BASE = "https://scrobble.test" + + +class RemoteAccount: + """An account on a FakeRemote server: serves its actor document and signs deliveries.""" + + def __init__(self, server, name="bob"): + self.server, self.name = server, name + self.uri = server.url(f"/users/{name}") + self.key_id = f"{self.uri}#main-key" + self.rotate_key() + self.serve() + + def rotate_key(self): + self.private = rsa.generate_private_key(public_exponent=65537, key_size=2048) + + @property + def public_pem(self) -> str: + return ( + self.private.public_key() + .public_bytes( + serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo + ) + .decode() + ) + + def document(self, **overrides) -> dict: + doc = { + "@context": ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/v1"], + "id": self.uri, + "type": "Person", + "preferredUsername": self.name, + "name": self.name.title(), + "inbox": f"{self.uri}/inbox", + "endpoints": {"sharedInbox": self.server.url("/inbox")}, + "publicKey": {"id": self.key_id, "owner": self.uri, "publicKeyPem": self.public_pem}, + } + doc.update(overrides) + return doc + + def serve(self, **overrides): + self.server.routes[f"/users/{self.name}"] = (200, {}, self.document(**overrides)) + + def activity(self, activity_type: str, obj, **extra) -> dict: + return { + "@context": "https://www.w3.org/ns/activitystreams", + "id": self.server.url(f"/activities/{uuid.uuid4()}"), + "type": activity_type, + "actor": self.uri, + "object": obj, + **extra, + } + + def follow(self, username="alice") -> dict: + return self.activity("Follow", f"{OUR_BASE}/users/{username}") + + def deliver( + self, + client, + activity: dict, + path="/users/alice/inbox", + scheme="draft-cavage", + key=None, + key_id=None, + content_type="application/activity+json", + ): + """POST `activity` to our inbox, signed like a real server would.""" + body = json.dumps(activity).encode() + request = SignedRequest("POST", OUR_BASE + path, {"Content-Type": content_type}, body) + if scheme: + added = signatures.sign(request, scheme, key_id or self.key_id, key or self.private) + request = dataclasses.replace(request, headers={**request.headers, **added}) + return client.post(path, data=body, headers=dict(request.headers)) diff --git a/tests/test_federation_inbox.py b/tests/test_federation_inbox.py new file mode 100644 index 0000000..1065538 --- /dev/null +++ b/tests/test_federation_inbox.py @@ -0,0 +1,327 @@ +"""Receiving activities: intake, signature verification, and the handlers.""" + +import json +from datetime import UTC, datetime, timedelta + +import pytest +from cryptography.hazmat.primitives.asymmetric import rsa + +from federation_helpers import RemoteAccount +from scrobbler import worker +from scrobbler.extensions import db +from scrobbler.federation import inbox, sharing +from scrobbler.federation.models import ( + FederationActivity, + FederationBlock, + FederationDelivery, + FederationFollower, + FederationInboxItem, + FederationRemoteActor, +) + + +@pytest.fixture +def bob(sharing_user, remote): + return RemoteAccount(remote, "bob") + + +def process_all(): + worker.run(once=True) + db.session.expire_all() + + +def last_item() -> FederationInboxItem: + return db.session.scalars( + db.select(FederationInboxItem).order_by(FederationInboxItem.id.desc()) + ).first() + + +def followers_of(user): + return db.session.scalars(db.select(FederationFollower).filter_by(user_id=user.id)).all() + + +def sent(activity_type): + return db.session.scalars( + db.select(FederationActivity).filter_by(activity_type=activity_type) + ).all() + + +# --- Intake --------------------------------------------------------------------------------- + + +def test_intake_queues_and_answers_202(fed_client, bob, metric_delta): + queued = metric_delta( + "scrobbler_federation_inbox_activities_total", type="Follow", result="queued" + ) + response = bob.deliver(fed_client, bob.follow()) + assert response.status_code == 202 + item = last_item() + assert (item.status, item.activity_type, item.actor_uri) == ("queued", "Follow", bob.uri) + assert set(item.headers) <= set(inbox.KEPT_HEADERS) + assert queued.delta == 1 + + +def test_duplicates_are_acknowledged_once(fed_client, bob, metric_delta): + duplicate = metric_delta( + "scrobbler_federation_inbox_activities_total", type="Follow", result="duplicate" + ) + follow = bob.follow() + assert bob.deliver(fed_client, follow).status_code == 202 + assert bob.deliver(fed_client, follow).status_code == 202 + assert db.session.scalar(db.select(db.func.count()).select_from(FederationInboxItem)) == 1 + assert duplicate.delta == 1 + + +@pytest.mark.parametrize( + "body", + [b"not json", b"[]", b'{"type": "Follow"}', b'{"id": "x", "type": "Follow", "actor": 7}'], +) +def test_malformed_deliveries_are_400(fed_client, sharing_user, body): + response = fed_client.post("/inbox", data=body, content_type="application/activity+json") + assert response.status_code == 400 + + +def test_wrong_content_type_is_415(fed_client, bob): + assert bob.deliver(fed_client, bob.follow(), content_type="text/plain").status_code == 415 + + +def test_too_large_is_413(fed_client, sharing_user): + response = fed_client.post( + "/inbox", data=b"x" * (inbox.MAX_BYTES + 1), content_type="application/activity+json" + ) + assert response.status_code == 413 + + +def test_blocked_domains_are_refused(fed_client, fed_app, bob): + config = fed_app.extensions["federation"] + fed_app.extensions["federation"] = type(config)( + **{**config.__dict__, "blocked_domains": ("127.0.0.1",)} + ) + try: + assert bob.deliver(fed_client, bob.follow()).status_code == 403 + finally: + fed_app.extensions["federation"] = config + + +# --- Follows ----------------------------------------------------------------------------------- + + +@pytest.mark.parametrize("scheme", ["draft-cavage", "rfc9421"]) +def test_follow_is_accepted(fed_client, bob, sharing_user, scheme, metric_delta): + ok = metric_delta( + "scrobbler_federation_signatures_total", direction="in", scheme=scheme, result="ok" + ) + follow = bob.follow() + bob.deliver(fed_client, follow, scheme=scheme) + process_all() + + assert (last_item().status, last_item().reason) == ("processed", "follow_accepted") + [follower] = followers_of(sharing_user) + assert (follower.state, follower.actor.uri, follower.follow_activity_id) == ( + "accepted", + bob.uri, + follow["id"], + ) + [accept] = sent("Accept") + assert accept.document["actor"] == "https://scrobble.test/users/alice" + assert accept.document["object"] == follow + assert accept.document["to"] == [bob.uri] + [delivery] = db.session.scalars(db.select(FederationDelivery)).all() + assert (delivery.inbox, delivery.status) == (f"{bob.uri}/inbox", "pending") + assert ok.delta == 1 + + +def test_manual_approval_leaves_follow_pending(fed_client, bob, sharing_user): + sharing.update(sharing_user.id, {"manually_approves_followers": True}) + bob.deliver(fed_client, bob.follow()) + process_all() + assert [f.state for f in followers_of(sharing_user)] == ["pending"] + assert sent("Accept") == [] + + +def test_repeat_follow_is_accepted_again(fed_client, bob, sharing_user): + bob.deliver(fed_client, bob.follow()) + process_all() + second = bob.follow() + bob.deliver(fed_client, second) + process_all() + assert last_item().reason == "follow_refollowed" + assert len(followers_of(sharing_user)) == 1 + assert followers_of(sharing_user)[0].follow_activity_id == second["id"] + assert len(sent("Accept")) == 2 + + +def test_follow_for_someone_not_sharing(fed_client, bob, make_user): + make_user(username="carol") + bob.deliver(fed_client, bob.follow("carol"), path="/inbox") + process_all() + assert (last_item().status, last_item().reason) == ("rejected", "not_our_user") + + +def test_blocked_account_gets_rejected(fed_client, bob, sharing_user): + bob.deliver(fed_client, bob.follow()) + process_all() + actor = db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=bob.uri)) + db.session.add(FederationBlock(user_id=sharing_user.id, remote_actor_id=actor.id)) + db.session.delete(followers_of(sharing_user)[0]) + db.session.commit() + bob.deliver(fed_client, bob.follow()) + process_all() + assert last_item().reason == "follow_blocked" + assert followers_of(sharing_user) == [] + assert len(sent("Reject")) == 1 + + +# --- Undo, Delete, Update ----------------------------------------------------------------------- + + +def test_undo_follow(fed_client, bob, sharing_user): + follow = bob.follow() + bob.deliver(fed_client, follow) + process_all() + bob.deliver(fed_client, bob.activity("Undo", follow)) + process_all() + assert last_item().reason == "unfollowed" + assert followers_of(sharing_user) == [] + + +def test_undo_of_someone_elses_follow_is_rejected(fed_client, bob, remote, sharing_user): + carol = RemoteAccount(remote, "carol") + follow = carol.follow() + carol.deliver(fed_client, follow) + process_all() + bob.deliver(fed_client, bob.activity("Undo", follow)) + process_all() + assert (last_item().status, last_item().reason) == ("rejected", "undo_other_actors_follow") + assert len(followers_of(sharing_user)) == 1 + + +def test_deleted_account_stops_following(fed_client, bob, remote, sharing_user): + bob.deliver(fed_client, bob.follow()) + process_all() + remote.routes[f"/users/{bob.name}"] = (410, {}, b"") # the account is gone now + bob.deliver(fed_client, bob.activity("Delete", bob.uri)) + process_all() + assert last_item().reason == "actor_deleted" + assert followers_of(sharing_user) == [] + assert db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=bob.uri)).gone + + +def test_update_refreshes_the_actor(fed_client, bob, sharing_user): + bob.deliver(fed_client, bob.follow()) + process_all() + bob.serve(name="Robert") + bob.deliver(fed_client, bob.activity("Update", bob.document(name="Robert"))) + process_all() + assert last_item().reason == "actor_updated" + assert ( + db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=bob.uri)).display_name + == "Robert" + ) + + +def test_other_activities_are_recorded(fed_client, bob, sharing_user): + bob.deliver(fed_client, bob.activity("Like", "https://scrobble.test/activities/x")) + process_all() + assert (last_item().status, last_item().reason) == ("processed", "recorded") + + +# --- Signatures and identity --------------------------------------------------------------------- + + +def test_unsigned_deliveries_are_rejected(fed_client, bob): + bob.deliver(fed_client, bob.follow(), scheme=None) + process_all() + assert (last_item().status, last_item().reason) == ("rejected", "signature_missing") + + +def test_wrong_key_is_rejected_after_one_refresh(fed_client, bob, remote, metric_delta): + failed = metric_delta( + "scrobbler_federation_signatures_total", + direction="in", + scheme="draft-cavage", + result="bad_signature", + ) + impostor = rsa.generate_private_key(public_exponent=65537, key_size=2048) + bob.deliver(fed_client, bob.follow(), key=impostor) + process_all() + assert (last_item().status, last_item().reason) == ("rejected", "signature_bad_signature") + assert [r["path"] for r in remote.requests].count("/users/bob") == 2 # fetched, then refreshed + assert failed.delta == 1 + + +def test_rotated_key_is_picked_up(fed_client, bob, sharing_user): + bob.deliver(fed_client, bob.follow()) + process_all() + bob.rotate_key() + bob.serve() # the new key is published... + bob.deliver(fed_client, bob.activity("Undo", followers_of(sharing_user)[0].follow_activity)) + process_all() # ...and our cached old key fails once, then we refetch + assert last_item().reason == "unfollowed" + + +def test_signed_by_one_actor_claiming_another_is_rejected(fed_client, bob, remote, sharing_user): + carol = RemoteAccount(remote, "carol") + forged = carol.follow() # carol's Follow... + bob.deliver(fed_client, forged) # ...signed with bob's key + process_all() + assert (last_item().status, last_item().reason) == ("rejected", "actor_mismatch") + assert followers_of(sharing_user) == [] + + +def test_activity_id_on_another_host_is_rejected(fed_client, bob, sharing_user): + follow = bob.follow() + follow["id"] = "https://elsewhere.example/activities/1" + bob.deliver(fed_client, follow) + process_all() + assert (last_item().status, last_item().reason) == ("rejected", "id_host_mismatch") + + +def test_signature_age_is_judged_by_arrival_time(fed_client, bob, sharing_user): + """A backlog mustn't turn valid deliveries into expired ones, and vice versa.""" + bob.deliver(fed_client, bob.follow()) + item = last_item() + item.received_at = datetime.now(UTC) + timedelta(hours=13) + db.session.commit() + process_all() + assert last_item().reason == "signature_expired" + + +# --- Robustness ---------------------------------------------------------------------------------- + + +def test_unreachable_sender_is_retried_then_failed(fed_client, bob, remote): + bob.deliver(fed_client, bob.follow()) + remote.close() # their server is down: fetching the key fails + for _ in range(inbox.MAX_ATTEMPTS): + process_all() + item = last_item() + if item.status != "queued": + break + assert (item.status, item.attempts) == ("failed", inbox.MAX_ATTEMPTS) + + +def test_maintenance_requeues_stale_and_prunes_old(fed_client, bob): + bob.deliver(fed_client, bob.follow()) + item = last_item() + item.status, item.received_at = "processing", datetime.now(UTC) - timedelta(minutes=30) + db.session.commit() + inbox.maintenance() + db.session.expire_all() + assert last_item().status == "queued" + + item = last_item() + item.status, item.received_at = "processed", datetime.now(UTC) - timedelta(days=31) + db.session.commit() + inbox.maintenance() + assert db.session.scalar(db.select(db.func.count()).select_from(FederationInboxItem)) == 0 + + +def test_activities_are_only_fetchable_when_public(fed_client, bob, sharing_user): + bob.deliver(fed_client, bob.follow()) + process_all() + [accept] = sent("Accept") + assert fed_client.get(f"/activities/{accept.id}").status_code == 404 + accept.public = True + db.session.commit() + assert json.loads(fed_client.get(f"/activities/{accept.id}").data)["type"] == "Accept" diff --git a/tests/test_federation_web.py b/tests/test_federation_web.py index 6b97a88..3a2e845 100644 --- a/tests/test_federation_web.py +++ b/tests/test_federation_web.py @@ -106,25 +106,6 @@ def test_instance_actor(fed_client, fed_ctx): assert (doc["type"], doc["id"]) == ("Application", f"{BASE}/actor") -def test_inboxes_accept_and_count_deliveries(fed_client, sharing_user, metric_delta): - shared = metric_delta("scrobbler_federation_inbox_requests_total", inbox="shared") - body = b'{"type": "Follow"}' - assert ( - fed_client.post("/inbox", data=body, content_type="application/activity+json").status_code - == 202 - ) - assert ( - fed_client.post( - "/users/alice/inbox", data=body, content_type="application/activity+json" - ).status_code - == 202 - ) - assert fed_client.post("/users/nobody/inbox", data=body).status_code == 404 - too_big = fed_client.post("/inbox", data=b"x" * (256 * 1024 + 1)) - assert too_big.status_code == 413 - assert shared.delta == 1 - - def test_disabled_app_has_none_of_these_routes(client): for path in ( "/.well-known/webfinger?resource=acct:alice@scrobble.test",