Inbox: intake and verified processing of follows (phase 2, step 4)
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 14s
CI / test (push) Successful in 1m57s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s

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/<uuid>. Metrics for inbox activities and
signature checks.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
mattandClaude Opus 5.5 committed 2026-09-25 21:29:55 +01:00
1 parent c1a7dd0877
commit f312c4b577
15 files changed
+1147 -60

No files matched your search

+6
View File
@@ -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)
+70
View File
@@ -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
+124
View File
@@ -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)}
+36
View File
@@ -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:
"""`<base>/users/<name>` -> 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
+321
View File
@@ -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"
+10 -5
View File
@@ -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"],
)
+23 -8
View File
@@ -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"},
},
),
}
+3 -11
View File
@@ -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
@@ -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
+3 -1
View File
@@ -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)
+33 -9
View File
@@ -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/<username>/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/<activity_uuid>")
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)