ActivityPub discovery endpoints (phase 1, step 3)
Registered only when federation is enabled: - WebFinger (acct: and actor-URL resources, the instance actor, CORS *) - host-meta, NodeInfo discovery and 2.1 (counts users sharing) - /users/<name>: the Person actor for ActivityPub clients, a redirect to the UI profile page for browsers (for any name, so redirects don't reveal accounts); outbox/followers/following collections - /actor: the instance Application actor - Inboxes accept (202) and count deliveries; size-limited; processing arrives in phase 2. Actors advertise manual approval until then. - Unknown and non-sharing users get byte-identical 404s; all IDs come from FEDERATION_BASE_URL, never the request - Federation metrics: lookups, sharing changes, inbox deliveries - scrobbler.__version__ joins the core's public surface for NodeInfo Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
1 parent
e890568c54
commit
ce39e8f865
6 files changed
+365
-1
No files matched your search
@@ -11,6 +11,7 @@ or switched off without touching anything else. Design: `docs/design/activitypub
|
||||
2. **`protocol/` is pure**: no Flask, SQLAlchemy, Werkzeug or `scrobbler` imports.
|
||||
Signature schemes, vocabulary and document formats live there.
|
||||
3. **The rest of this package uses only the core's public surface**:
|
||||
- `scrobbler.__version__`
|
||||
- `scrobbler.events`
|
||||
- `scrobbler.extensions` (`db`)
|
||||
- `scrobbler.worker`
|
||||
|
||||
@@ -27,4 +27,7 @@ def init_app(app: Flask) -> None:
|
||||
if not config.enabled:
|
||||
return
|
||||
log.info("federation enabled: handles @user@%s, actors at %s", config.domain, config.base_url)
|
||||
# Phase 1 onwards registers routes, event receivers and worker tasks here.
|
||||
|
||||
from scrobbler.federation import web
|
||||
|
||||
app.register_blueprint(web.bp)
|
||||
@@ -0,0 +1,26 @@
|
||||
"""Federation's own metrics (the core's HTTP metrics already cover rate/latency)."""
|
||||
|
||||
from prometheus_client import Counter
|
||||
|
||||
lookups_total = Counter(
|
||||
"scrobbler_federation_lookups_total",
|
||||
"Fediverse lookups answered: WebFinger, actor, NodeInfo, profile",
|
||||
["kind", "result"],
|
||||
)
|
||||
sharing_changes_total = Counter(
|
||||
"scrobbler_federation_sharing_changes_total",
|
||||
"Users switching fediverse sharing on or off",
|
||||
["change"],
|
||||
)
|
||||
inbox_requests_total = Counter(
|
||||
"scrobbler_federation_inbox_requests_total",
|
||||
"Deliveries received at an inbox (not yet processed: phase 2)",
|
||||
["inbox"],
|
||||
)
|
||||
|
||||
# Every scrobbler_federation_* series name, for the dashboard consistency test.
|
||||
SERIES = (
|
||||
"scrobbler_federation_lookups_total",
|
||||
"scrobbler_federation_sharing_changes_total",
|
||||
"scrobbler_federation_inbox_requests_total",
|
||||
)
|
||||
@@ -0,0 +1,199 @@
|
||||
"""The ActivityPub endpoints remote servers call. Served on the UI's domain: its nginx
|
||||
forwards these paths to the API. Every ID is built from FEDERATION_BASE_URL, never from
|
||||
the request, so a proxy misconfiguration can't produce wrong IDs."""
|
||||
|
||||
import json
|
||||
|
||||
from flask import Blueprint, Response, current_app, redirect, request
|
||||
|
||||
from scrobbler.federation import keys, sharing
|
||||
from scrobbler.federation import metrics as fed_metrics
|
||||
from scrobbler.federation.protocol import hostmeta, media, nodeinfo, vocab, webfinger
|
||||
|
||||
bp = Blueprint("federation", __name__)
|
||||
|
||||
MAX_INBOX_BYTES = 256 * 1024
|
||||
_NOT_FOUND = {"error": "not found"}
|
||||
|
||||
|
||||
def _config():
|
||||
return current_app.extensions["federation"]
|
||||
|
||||
|
||||
def _profile_page(username: str) -> str:
|
||||
return f"{current_app.config['UI_BASE_URL']}/profile.html?u={username}"
|
||||
|
||||
|
||||
def _urls(username: str) -> vocab.ActorUrls:
|
||||
return vocab.actor_urls(_config().base_url, username, _profile_page(username))
|
||||
|
||||
|
||||
def _json(doc, content_type: str = media.ACTIVITY_JSON, status: int = 200, cache: int = 300):
|
||||
response = Response(json.dumps(doc), status=status, content_type=content_type)
|
||||
if status == 200 and cache:
|
||||
response.headers["Cache-Control"] = f"public, max-age={cache}"
|
||||
response.headers["Vary"] = "Accept"
|
||||
return response
|
||||
|
||||
|
||||
def _not_found(kind: str):
|
||||
fed_metrics.lookups_total.labels(kind=kind, result="not_found").inc()
|
||||
return _json(_NOT_FOUND, content_type="application/json", status=404)
|
||||
|
||||
|
||||
def _found(kind: str) -> None:
|
||||
fed_metrics.lookups_total.labels(kind=kind, result="found").inc()
|
||||
|
||||
|
||||
# --- Discovery -----------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.get("/.well-known/webfinger")
|
||||
def webfinger_lookup():
|
||||
config = _config()
|
||||
try:
|
||||
username = webfinger.parse_resource(
|
||||
request.args.get("resource"), domain=config.domain, base_url=config.base_url
|
||||
)
|
||||
except webfinger.ResourceError as err:
|
||||
return _json({"error": str(err)}, content_type="application/json", status=400)
|
||||
|
||||
if username.lower() == config.domain: # the instance actor, as Mastodon names it
|
||||
actor_id, canonical = f"{config.base_url}/actor", config.domain
|
||||
profile = current_app.config["UI_BASE_URL"]
|
||||
else:
|
||||
found = sharing.shared_user(username)
|
||||
if found is None:
|
||||
return _not_found("webfinger")
|
||||
canonical = found[0].username
|
||||
actor_id, profile = _urls(canonical).id, _profile_page(canonical)
|
||||
_found("webfinger")
|
||||
doc = webfinger.jrd(
|
||||
username=canonical, domain=config.domain, actor_id=actor_id, profile_page=profile
|
||||
)
|
||||
response = _json(doc, content_type=media.JRD_JSON)
|
||||
response.headers["Access-Control-Allow-Origin"] = "*" # RFC 7033 §5
|
||||
return response
|
||||
|
||||
|
||||
@bp.get("/.well-known/host-meta")
|
||||
def host_meta():
|
||||
return Response(hostmeta.xrd(_config().base_url), content_type=hostmeta.CONTENT_TYPE)
|
||||
|
||||
|
||||
@bp.get("/.well-known/nodeinfo")
|
||||
def nodeinfo_discovery():
|
||||
return _json(nodeinfo.discovery(_config().base_url), content_type="application/json")
|
||||
|
||||
|
||||
@bp.get("/nodeinfo/2.1")
|
||||
def nodeinfo_document():
|
||||
from scrobbler import __version__
|
||||
|
||||
_found("nodeinfo")
|
||||
doc = nodeinfo.document(
|
||||
version=__version__, users_total=sharing.sharing_count(), open_registrations=True
|
||||
)
|
||||
schema = f'application/json; profile="{nodeinfo.SCHEMA_21}#"'
|
||||
return _json(doc, content_type=schema, cache=1800)
|
||||
|
||||
|
||||
# --- Actors and collections -------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.get("/users/<username>")
|
||||
def actor(username: str):
|
||||
if not media.wants_activitypub(request.headers.get("Accept")):
|
||||
# A person following a link: show them the profile page (for everyone, so
|
||||
# redirects don't reveal which accounts exist).
|
||||
return redirect(_profile_page(username), code=302)
|
||||
found = sharing.shared_user(username)
|
||||
if found is None:
|
||||
return _not_found("actor")
|
||||
user, settings = found
|
||||
_found("actor")
|
||||
urls = _urls(user.username)
|
||||
doc = vocab.person(
|
||||
urls,
|
||||
username=user.username,
|
||||
name=settings.display_name or user.username,
|
||||
summary=settings.bio,
|
||||
public_key_pem=keys.key_for(user.id).public_key_pem,
|
||||
# Phase 1 can't accept follows yet: advertise approval so follows show as
|
||||
# requests rather than failing silently.
|
||||
manually_approves_followers=True,
|
||||
discoverable=settings.discoverable,
|
||||
indexable=settings.indexable,
|
||||
published=settings.created_at.isoformat().replace("+00:00", "Z"),
|
||||
)
|
||||
return _json(doc)
|
||||
|
||||
|
||||
def _collection(username: str, which: str, items: list | None):
|
||||
found = sharing.shared_user(username)
|
||||
if found is None:
|
||||
return _not_found("actor")
|
||||
urls = _urls(found[0].username)
|
||||
return _json(vocab.ordered_collection(getattr(urls, which), 0, items))
|
||||
|
||||
|
||||
@bp.get("/users/<username>/outbox")
|
||||
def outbox(username: str):
|
||||
return _collection(username, "outbox", [])
|
||||
|
||||
|
||||
@bp.get("/users/<username>/followers")
|
||||
def followers(username: str):
|
||||
return _collection(username, "followers", None) # count only
|
||||
|
||||
|
||||
@bp.get("/users/<username>/following")
|
||||
def following(username: str):
|
||||
return _collection(username, "following", [])
|
||||
|
||||
|
||||
# --- Instance actor -------------------------------------------------------------------
|
||||
|
||||
|
||||
@bp.get("/actor")
|
||||
def instance_actor():
|
||||
config = _config()
|
||||
actor_id = f"{config.base_url}/actor"
|
||||
doc = vocab.application(
|
||||
actor_id=actor_id,
|
||||
username=config.domain,
|
||||
inbox=f"{config.base_url}/inbox",
|
||||
outbox=f"{actor_id}/outbox",
|
||||
shared_inbox=f"{config.base_url}/inbox",
|
||||
key_id=f"{actor_id}#main-key",
|
||||
public_key_pem=keys.key_for(None).public_key_pem,
|
||||
url=current_app.config["UI_BASE_URL"],
|
||||
)
|
||||
return _json(doc)
|
||||
|
||||
|
||||
@bp.get("/actor/outbox")
|
||||
def instance_outbox():
|
||||
return _json(vocab.ordered_collection(f"{_config().base_url}/actor/outbox", 0, []))
|
||||
|
||||
|
||||
# --- Inboxes (phase 2 processes deliveries) -----------------------------------------------
|
||||
|
||||
|
||||
def _accept_delivery(inbox: str):
|
||||
if (request.content_length or 0) > MAX_INBOX_BYTES:
|
||||
return _json({"error": "too large"}, content_type="application/json", status=413)
|
||||
fed_metrics.inbox_requests_total.labels(inbox=inbox).inc()
|
||||
return Response(status=202)
|
||||
|
||||
|
||||
@bp.post("/users/<username>/inbox")
|
||||
def user_inbox(username: str):
|
||||
if sharing.shared_user(username) is None:
|
||||
return _not_found("actor")
|
||||
return _accept_delivery("user")
|
||||
|
||||
|
||||
@bp.post("/inbox")
|
||||
def shared_inbox():
|
||||
return _accept_delivery("shared")
|
||||
@@ -35,6 +35,7 @@ FRAMEWORKS = (
|
||||
"marshmallow",
|
||||
)
|
||||
CORE_PUBLIC_SURFACE = (
|
||||
"scrobbler.__version__",
|
||||
"scrobbler.events",
|
||||
"scrobbler.extensions",
|
||||
"scrobbler.worker",
|
||||
|
||||
@@ -0,0 +1,134 @@
|
||||
import xml.etree.ElementTree as ET
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
import pytest
|
||||
|
||||
AP = {"Accept": "application/activity+json"}
|
||||
BASE = "https://scrobble.test"
|
||||
|
||||
|
||||
def webfinger(client, resource):
|
||||
return client.get("/.well-known/webfinger", query_string={"resource": resource})
|
||||
|
||||
|
||||
def test_webfinger_finds_sharing_users(fed_client, sharing_user, metric_delta):
|
||||
found = metric_delta("scrobbler_federation_lookups_total", kind="webfinger", result="found")
|
||||
response = webfinger(fed_client, "acct:ALICE@scrobble.test")
|
||||
assert response.status_code == 200
|
||||
assert response.content_type == "application/jrd+json"
|
||||
assert response.headers["Access-Control-Allow-Origin"] == "*"
|
||||
doc = response.get_json()
|
||||
assert doc["subject"] == "acct:alice@scrobble.test"
|
||||
assert {
|
||||
"rel": "self",
|
||||
"type": "application/activity+json",
|
||||
"href": f"{BASE}/users/alice",
|
||||
} in doc["links"]
|
||||
assert found.delta == 1
|
||||
|
||||
|
||||
def test_unknown_and_private_users_look_identical(fed_client, fed_ctx, make_user):
|
||||
make_user(username="bob") # exists, never enabled sharing
|
||||
unknown = webfinger(fed_client, "acct:nobody@scrobble.test")
|
||||
private = webfinger(fed_client, "acct:bob@scrobble.test")
|
||||
assert unknown.status_code == private.status_code == 404
|
||||
assert unknown.data == private.data
|
||||
ap_unknown = fed_client.get("/users/nobody", headers=AP)
|
||||
ap_private = fed_client.get("/users/bob", headers=AP)
|
||||
assert ap_unknown.status_code == ap_private.status_code == 404
|
||||
assert ap_unknown.data == ap_private.data
|
||||
|
||||
|
||||
def test_webfinger_rejects_other_domains(fed_client, sharing_user):
|
||||
assert webfinger(fed_client, "acct:alice@elsewhere.example").status_code == 400
|
||||
assert fed_client.get("/.well-known/webfinger").status_code == 400
|
||||
|
||||
|
||||
def test_webfinger_instance_actor(fed_client, fed_ctx):
|
||||
doc = webfinger(fed_client, "acct:scrobble.test@scrobble.test").get_json()
|
||||
assert doc["links"][0]["href"] == f"{BASE}/actor"
|
||||
|
||||
|
||||
def test_actor_document(fed_client, sharing_user):
|
||||
response = fed_client.get("/users/alice", headers=AP)
|
||||
assert response.status_code == 200
|
||||
assert response.content_type == "application/activity+json"
|
||||
assert response.headers["Vary"] == "Accept"
|
||||
doc = response.get_json()
|
||||
assert doc["id"] == f"{BASE}/users/alice"
|
||||
assert (doc["type"], doc["preferredUsername"], doc["name"]) == ("Person", "alice", "Alice")
|
||||
assert doc["summary"] == "<p>Listening.</p>"
|
||||
assert doc["publicKey"]["id"] == f"{BASE}/users/alice#main-key"
|
||||
assert doc["publicKey"]["publicKeyPem"].startswith("-----BEGIN PUBLIC KEY-----")
|
||||
assert doc["manuallyApprovesFollowers"] is True # follows are requests until phase 2
|
||||
assert (doc["discoverable"], doc["indexable"]) == (False, False)
|
||||
assert doc["url"] == "http://localhost:8080/profile.html?u=alice"
|
||||
|
||||
|
||||
def test_ids_come_from_config_not_the_request(fed_client, sharing_user):
|
||||
doc = fed_client.get("/users/alice", headers={**AP, "Host": "evil.example"}).get_json()
|
||||
assert urlsplit(doc["id"]).netloc == "scrobble.test"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("username", ["alice", "nobody"])
|
||||
def test_browsers_are_sent_to_the_profile_page(fed_client, sharing_user, username):
|
||||
response = fed_client.get(f"/users/{username}", headers={"Accept": "text/html"})
|
||||
assert response.status_code == 302
|
||||
assert response.headers["Location"] == f"http://localhost:8080/profile.html?u={username}"
|
||||
|
||||
|
||||
def test_collections(fed_client, sharing_user):
|
||||
outbox = fed_client.get("/users/alice/outbox", headers=AP).get_json()
|
||||
assert (outbox["type"], outbox["totalItems"], outbox["orderedItems"]) == (
|
||||
"OrderedCollection",
|
||||
0,
|
||||
[],
|
||||
)
|
||||
followers = fed_client.get("/users/alice/followers", headers=AP).get_json()
|
||||
assert followers["totalItems"] == 0 and "orderedItems" not in followers
|
||||
|
||||
|
||||
def test_nodeinfo(fed_client, sharing_user):
|
||||
link = fed_client.get("/.well-known/nodeinfo").get_json()["links"][0]
|
||||
assert link["href"] == f"{BASE}/nodeinfo/2.1"
|
||||
doc = fed_client.get("/nodeinfo/2.1").get_json()
|
||||
assert doc["software"]["name"] == "scrobbler"
|
||||
assert doc["usage"]["users"]["total"] == 1
|
||||
|
||||
|
||||
def test_host_meta(fed_client):
|
||||
root = ET.fromstring(fed_client.get("/.well-known/host-meta").data)
|
||||
assert "webfinger" in root[0].get("template")
|
||||
|
||||
|
||||
def test_instance_actor(fed_client, fed_ctx):
|
||||
doc = fed_client.get("/actor", headers=AP).get_json()
|
||||
assert (doc["type"], doc["id"]) == ("Application", f"{BASE}/actor")
|
||||
|
||||
|
||||
def test_inboxes_accept_and_count_deliveries(fed_client, sharing_user, metric_delta):
|
||||
shared = metric_delta("scrobbler_federation_inbox_requests_total", inbox="shared")
|
||||
body = b'{"type": "Follow"}'
|
||||
assert (
|
||||
fed_client.post("/inbox", data=body, content_type="application/activity+json").status_code
|
||||
== 202
|
||||
)
|
||||
assert (
|
||||
fed_client.post(
|
||||
"/users/alice/inbox", data=body, content_type="application/activity+json"
|
||||
).status_code
|
||||
== 202
|
||||
)
|
||||
assert fed_client.post("/users/nobody/inbox", data=body).status_code == 404
|
||||
too_big = fed_client.post("/inbox", data=b"x" * (256 * 1024 + 1))
|
||||
assert too_big.status_code == 413
|
||||
assert shared.delta == 1
|
||||
|
||||
|
||||
def test_disabled_app_has_none_of_these_routes(client):
|
||||
for path in (
|
||||
"/.well-known/webfinger?resource=acct:alice@scrobble.test",
|
||||
"/users/alice",
|
||||
"/nodeinfo/2.1",
|
||||
):
|
||||
assert client.get(path, headers=AP).status_code == 404
|
||||
Reference in new issue
Block a user