Interop with a real GoToSocial server, and the fixes it found (phase 2, step 8)
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 10s
CI / test (push) Successful in 2m16s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s

scripts/interop/run.sh brings up Scrobbler (API, worker, UI behind a
throwaway-TLS Caddy) and GoToSocial 0.22.1 on a private .test network,
creates a GoToSocial user, drives its sign-in/OAuth screens for a token,
and checks: lookup by handle, follow accepted, unfollow, manual approval
and approve, remove, block and unblock, and decline.

Found and fixed along the way:
- Keys whose id is a path serving the actor (GoToSocial's
  <actor>/main-key) weren't resolved; now all three publishing styles
  are handled
- An Undo of an older Follow arriving after a newer Follow removed the
  new follower; an Undo now only removes the Follow it names (and Undo
  referencing a Follow by id is understood)
- Rejects embedded the Follow, which some servers (GoToSocial) match by
  account pair, so a late Reject could cancel a newer request; Rejects
  now reference the Follow by id
- Unblocking didn't tell the other server; it now sends Undo(Block)
- Actors publish an (empty) featured collection, which Mastodon and
  GoToSocial fetch

GoToSocial 0.22.1 ignores Reject for already-accepted follows (a TODO
in its code, fixed on its main branch); the removal check on its side
is skipped until a release has it (GTS_REJECT_ENDS_FOLLOWS=1 enables).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
mattandClaude Opus 5.5 committed 2026-09-25 22:11:39 +01:00
1 parent ec658a7751
commit b93cfea5b3
16 files changed
+694 -17

No files matched your search

+82
View File
@@ -0,0 +1,82 @@
# Federation interop test: Scrobbler and a real GoToSocial server on one private network.
#
# docker compose -f docker-compose.yml -f deploy/interop/docker-compose.interop.yml up -d --build
# ...create the GoToSocial user (see scripts/interop/run.sh), then run the driver.
#
# TEST ONLY: GoToSocial runs over plain HTTP and skips TLS verification; Scrobbler is
# served over HTTPS by a Caddy proxy with a throwaway certificate, and its "insecure
# testing" switch lets it reach GoToSocial over HTTP on this private network. All on the
# reserved .test domain. Never use these settings anywhere else.
name: scrobbler-interop
x-federation: &federation
DATABASE_URL: postgresql+psycopg://scrobbler:scrobbler@db:5432/scrobbler
FEDERATION_ENABLED: "1"
FEDERATION_DOMAIN: scrobble.test
FEDERATION_BASE_URL: https://scrobble.test
FEDERATION_KEY_SECRET: interop-test-only-secret-0123456789abcdef
FEDERATION_INSECURE_TESTING: "1"
UI_BASE_URL: https://scrobble.test
networks:
fedi:
ipam:
config:
- subnet: 172.30.0.0/24
services:
db:
ports: !reset []
networks: [fedi]
api:
environment: *federation
ports: !reset []
networks: [fedi]
worker:
environment: *federation
networks: [fedi]
ui:
environment:
API_BASE_URL: https://scrobble.test
API_INTERNAL_URL: http://api:8000
ports: !reset []
networks: [fedi]
# GoToSocial looks up remote servers over HTTPS: serve scrobble.test with TLS
# (Caddy's internal CA) in front of the UI, which forwards fediverse paths to the API.
tls:
image: caddy:2.10
command: ["caddy", "reverse-proxy", "--from", "https://scrobble.test", "--to", "http://ui:80", "--internal-certs"]
networks:
fedi:
aliases: [scrobble.test]
gotosocial:
image: superseriousbusiness/gotosocial:0.22.1
environment:
GTS_HOST: gts.test
GTS_PROTOCOL: http # local testing only
GTS_PORT: "80"
GTS_DB_TYPE: sqlite
GTS_DB_ADDRESS: /gotosocial/storage/sqlite.db
GTS_HTTP_CLIENT_ALLOW_IPS: 172.30.0.0/24 # let it reach Scrobbler on this network
GTS_HTTP_CLIENT_TLS_INSECURE_SKIP_VERIFY: "true" # Caddy's throwaway certificate
GTS_TRUSTED_PROXIES: 172.30.0.0/24
GTS_ACCOUNTS_REGISTRATION_OPEN: "false"
GTS_LOG_LEVEL: ${GTS_LOG_LEVEL:-info}
sysctls:
net.ipv4.ip_unprivileged_port_start: 0 # listen on :80 as its non-root user
networks:
fedi:
aliases: [gts.test]
driver:
image: python:3.13-slim
profiles: [driver]
volumes:
- ./scripts/interop:/interop:ro # relative to the project (first compose file)
command: ["python", "/interop/gotosocial_interop.py"]
networks: [fedi]
+47 -1
View File
@@ -2361,7 +2361,7 @@
}
},
"summary": "Unblock an account",
"description": "They can follow you again (they aren't re-added).",
"description": "Their server is told (an Undo of the Block). They can follow you again; they aren't\nre-added.",
"tags": [
"Federation"
],
@@ -2675,6 +2675,52 @@
}
]
},
"/users/{username}/collections/featured": {
"get": {
"tags": [
"ActivityPub"
],
"summary": "Featured",
"description": "Pinned posts (always empty for now).",
"operationId": "federation_featured",
"responses": {
"200": {
"description": "OrderedCollection",
"content": {
"application/activity+json": {
"schema": {
"type": "object"
}
}
}
},
"404": {
"description": "Unknown, or not sharing (the two are indistinguishable)"
}
},
"parameters": [
{
"name": "username",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
}
]
},
"parameters": [
{
"in": "path",
"name": "username",
"required": true,
"schema": {
"type": "string",
"minLength": 1
}
}
]
},
"/actor": {
"get": {
"tags": [
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
# docker compose for the federation interop stack (Scrobbler + GoToSocial).
set -euo pipefail
root="$(cd "$(dirname "$0")/../.." && pwd)"
exec docker compose -f "$root/docker-compose.yml" -f "$root/deploy/interop/docker-compose.interop.yml" "$@"
+354
View File
@@ -0,0 +1,354 @@
"""Federation interop test: a real GoToSocial account follows a Scrobbler user.
Runs inside the interop compose network (see deploy/interop/). Standard library only.
Exits non-zero, with a description, on the first thing that doesn't work.
"""
import html
import http.cookiejar
import json
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
GTS = "http://gts.test"
SCROBBLER_API = "http://api:8000/api/v1"
GTS_EMAIL = os.environ.get("GTS_EMAIL", "gtsuser@gts.test")
GTS_PASSWORD = os.environ.get("GTS_PASSWORD", "Interop-Test-Password-1")
OOB = "urn:ietf:wg:oauth:2.0:oob"
def step(message: str) -> None:
print(f"==> {message}", flush=True)
class NoRedirect(urllib.request.HTTPRedirectHandler):
def redirect_request(self, *args, **kwargs):
return None
class Browser:
"""Just enough of a browser to sign in and authorize an OAuth app."""
def __init__(self):
self.jar = http.cookiejar.CookieJar()
self.opener = urllib.request.build_opener(
urllib.request.HTTPCookieProcessor(self.jar), NoRedirect()
)
def request(self, method, url, form=None):
data = urllib.parse.urlencode(form).encode() if form is not None else None
req = urllib.request.Request(url, data=data, method=method)
if data is not None:
req.add_header("Content-Type", "application/x-www-form-urlencoded")
try:
with self.opener.open(req, timeout=20) as response:
return response.status, dict(response.headers), response.read().decode()
except urllib.error.HTTPError as err: # includes 3xx, since we don't follow them
return err.code, dict(err.headers), err.read().decode()
def api(method, url, token=None, body=None, form=None):
headers = {"Accept": "application/json"}
data = None
if body is not None:
data, headers["Content-Type"] = json.dumps(body).encode(), "application/json"
elif form is not None:
data, headers["Content-Type"] = (
urllib.parse.urlencode(form).encode(),
"application/x-www-form-urlencoded",
)
if token:
headers["Authorization"] = f"Bearer {token}"
req = urllib.request.Request(url, data=data, method=method, headers=headers)
try:
with urllib.request.urlopen(req, timeout=20) as response:
raw = response.read()
return response.status, json.loads(raw) if raw else None
except urllib.error.HTTPError as err:
raw = err.read()
try:
return err.code, json.loads(raw)
except json.JSONDecodeError:
return err.code, raw.decode(errors="replace")[:500]
def fail(message: str):
print(f"FAILED: {message}", flush=True)
sys.exit(1)
def gotosocial_token() -> str:
"""Sign in to GoToSocial's web UI and authorize an app (it has no password grant)."""
status, app = api(
"POST",
f"{GTS}/api/v1/apps",
form={
"client_name": "scrobbler-interop",
"redirect_uris": OOB,
"scopes": "read write follow",
},
)
if status != 200:
fail(f"creating a GoToSocial app: {status} {app}")
browser = Browser()
authorize = f"{GTS}/oauth/authorize?" + urllib.parse.urlencode(
{
"response_type": "code",
"client_id": app["client_id"],
"redirect_uri": OOB,
"scope": "read write follow",
}
)
status, headers, body = browser.request("GET", authorize)
print(f" authorize -> {status} {headers.get('Location', '')}")
status, headers, body = browser.request(
"POST", f"{GTS}/auth/sign_in", {"username": GTS_EMAIL, "password": GTS_PASSWORD}
)
print(f" sign in -> {status} {headers.get('Location', '')}")
if status not in (302, 303):
fail(f"sign-in didn't redirect: {status} {body[:300]}")
location = urllib.parse.urljoin(GTS, headers.get("Location", "/oauth/authorize"))
status, headers, body = browser.request("GET", location)
print(f" authorize page -> {status} {headers.get('Location', '')}")
if status == 200:
# The consent page: submit its form (with any hidden fields it has)
fields = dict(re.findall(r'<input[^>]*name="([^"]+)"[^>]*value="([^"]*)"', body))
action = re.search(r'<form[^>]*action="([^"]+)"', body)
target = urllib.parse.urljoin(
GTS, html.unescape(action.group(1)) if action else "/oauth/authorize"
)
status, headers, body = browser.request(
"POST", target, {k: html.unescape(v) for k, v in fields.items()}
)
print(f" consent -> {status} {headers.get('Location', '')}")
location = headers.get("Location", "")
code = urllib.parse.parse_qs(urllib.parse.urlsplit(location).query).get("code", [None])[0]
if code is None and status in (302, 303):
# Out-of-band: the code is shown on the page we're sent to
status, headers, body = browser.request("GET", urllib.parse.urljoin(GTS, location))
match = re.search(r"<code>([^<]+)</code>", body) or re.search(
r'value="([A-Za-z0-9_-]{20,})"', body
)
code = match.group(1) if match else None
if not code:
fail(f"no authorization code (last response {status}: {body[:300]})")
status, token = api(
"POST",
f"{GTS}/oauth/token",
form={
"grant_type": "authorization_code",
"code": code,
"client_id": app["client_id"],
"client_secret": app["client_secret"],
"redirect_uri": OOB,
},
)
if status != 200:
fail(f"exchanging the code: {status} {token}")
return token["access_token"]
def wait_for(description, check, timeout=60):
"""Poll `check()` until it returns something truthy."""
deadline = time.monotonic() + timeout
while time.monotonic() < deadline:
result = check()
if result:
return result
time.sleep(1)
fail(f"timed out waiting for: {description}")
class Scrobbler:
def __init__(self, username="alice", password="interop-password-1"):
status, body = api(
"POST",
f"{SCROBBLER_API}/auth/register",
body={
"username": username,
"email": f"{username}@scrobble.test",
"password": password,
},
)
if status == 409:
status, body = api(
"POST",
f"{SCROBBLER_API}/auth/login",
body={
"username": username,
"password": password,
},
)
if status not in (200, 201):
fail(f"signing in to Scrobbler: {status} {body}")
self.token = body["token"]
def settings(self, **changes):
status, body = api(
"PATCH", f"{SCROBBLER_API}/federation/settings", self.token, body=changes
)
if status != 200:
fail(f"changing Scrobbler settings: {status} {body}")
return body
def followers(self, state=None):
query = f"?state={state}" if state else ""
status, body = api("GET", f"{SCROBBLER_API}/federation/followers{query}", self.token)
if status != 200:
fail(f"listing followers: {status} {body}")
return body
def act(self, follower_id, action):
status, body = api(
"POST", f"{SCROBBLER_API}/federation/followers/{follower_id}/{action}", self.token
)
if status not in (200, 204):
fail(f"{action} follower: {status} {body}")
class GoToSocial:
def __init__(self, token):
self.token = token
def resolve(self, handle):
status, body = api(
"GET",
f"{GTS}/api/v2/search?"
+ urllib.parse.urlencode({"q": handle, "resolve": "true", "type": "accounts"}),
self.token,
)
if status != 200 or not body.get("accounts"):
fail(f"GoToSocial couldn't find {handle}: {status} {body}")
return body["accounts"][0]
def follow(self, account_id):
status, body = api(
"POST", f"{GTS}/api/v1/accounts/{account_id}/follow", self.token, body={}
)
if status != 200:
fail(f"following: {status} {body}")
return body
def unfollow(self, account_id):
status, body = api(
"POST", f"{GTS}/api/v1/accounts/{account_id}/unfollow", self.token, body={}
)
if status != 200:
fail(f"unfollowing: {status} {body}")
def relationship(self, account_id):
status, body = api(
"GET", f"{GTS}/api/v1/accounts/relationships?id[]={account_id}", self.token
)
if status != 200 or not body:
fail(f"relationship: {status} {body}")
return body[0]
def main():
step("Getting a GoToSocial access token")
gts = GoToSocial(gotosocial_token())
step("Alice starts sharing on Scrobbler")
alice = Scrobbler()
alice.settings(
enabled=True,
display_name="Alice Interop",
bio="Testing federation.",
manually_approves_followers=False,
)
step("GoToSocial finds @alice@scrobble.test (WebFinger, actor, key)")
account = gts.resolve("@alice@scrobble.test")
print(f" found {account['acct']} ({account['display_name']!r})")
if account["display_name"] != "Alice Interop":
fail(f"unexpected display name {account['display_name']!r}")
account_id = account["id"]
step("Follow: GoToSocial sees it accepted (our signed Accept verified)")
gts.follow(account_id)
wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"])
followers = wait_for("Scrobbler to list the follower", lambda: alice.followers("accepted"))
print(f" Scrobbler follower: {followers[0]['handle']}")
if followers[0]["handle"] != "@gtsuser@gts.test":
fail(f"unexpected follower {followers[0]['handle']}")
step("Unfollow: Scrobbler drops the follower (their signed Undo verified)")
gts.unfollow(account_id)
wait_for("Scrobbler to drop the follower", lambda: not alice.followers())
step("Manual approval: the follow waits as a request")
alice.settings(manually_approves_followers=True)
gts.follow(account_id)
wait_for(
"GoToSocial to show a pending request", lambda: gts.relationship(account_id)["requested"]
)
pending = wait_for("Scrobbler to list the request", lambda: alice.followers("pending"))
if gts.relationship(account_id)["following"]:
fail("following before being approved")
step("Approve: GoToSocial sees it accepted")
alice.act(pending[0]["id"], "approve")
wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"])
step("Remove the follower: Scrobbler drops them and sends a Reject")
alice.act(alice.followers()[0]["id"], "remove")
if alice.followers():
fail("the follower is still listed after removal")
# GoToSocial 0.22.1 only applies a Reject to *pending* follow requests (its
# federatingdb/reject.go has a TODO for accepted follows; fixed on its main branch).
# Mastodon, and the ActivityPub consensus, drop the follow. Until a GoToSocial
# release includes the fix, their side is checked only when asked to.
if os.environ.get("GTS_REJECT_ENDS_FOLLOWS") == "1":
wait_for(
"GoToSocial to stop following", lambda: not gts.relationship(account_id)["following"]
)
else:
print(" (skipping GoToSocial's side: its 0.22.1 ignores Reject for accepted follows)")
gts.unfollow(account_id) # tidy up their side for the next step
wait_for(
"GoToSocial to not be following", lambda: not gts.relationship(account_id)["following"]
)
step("Block a follower: GoToSocial drops the follow (it honours Block)")
gts.follow(account_id)
pending = wait_for("Scrobbler to list the request", lambda: alice.followers("pending"))
alice.act(pending[0]["id"], "approve")
wait_for("GoToSocial to be following", lambda: gts.relationship(account_id)["following"])
alice.act(alice.followers()[0]["id"], "block")
wait_for("GoToSocial to stop following", lambda: not gts.relationship(account_id)["following"])
status, blocks = api("GET", f"{SCROBBLER_API}/federation/blocks", alice.token)
if status != 200 or [b["handle"] for b in blocks] != ["@gtsuser@gts.test"]:
fail(f"the block isn't listed: {status} {blocks}")
wait_for("GoToSocial to see the block", lambda: gts.relationship(account_id)["blocked_by"])
step("Unblock: GoToSocial sees the Undo of the Block")
status, _ = api("DELETE", f"{SCROBBLER_API}/federation/blocks/{blocks[0]['id']}", alice.token)
if status != 204:
fail(f"unblocking: {status}")
wait_for(
"GoToSocial to see the unblock", lambda: not gts.relationship(account_id)["blocked_by"]
)
step("Decline a request: GoToSocial's request is withdrawn")
gts.follow(account_id)
pending = wait_for("Scrobbler to list the request", lambda: alice.followers("pending"))
alice.act(pending[0]["id"], "decline")
wait_for(
"GoToSocial's request to go away",
lambda: (
not gts.relationship(account_id)["requested"]
and not gts.relationship(account_id)["following"]
),
)
step("All interop checks passed")
if __name__ == "__main__":
main()
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env bash
# Run the GoToSocial federation interop test end to end, then tear everything down.
# Usage: scripts/interop/run.sh [--keep] (--keep leaves the stack running afterwards)
set -uo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
compose="$here/compose.sh"
keep=0; [ "${1:-}" = "--keep" ] && keep=1
cleanup() { [ "$keep" = 1 ] || "$compose" down -v --remove-orphans >/dev/null 2>&1; }
trap cleanup EXIT
"$compose" down -v --remove-orphans >/dev/null 2>&1
echo "==> Building and starting Scrobbler + GoToSocial"
"$compose" up -d --build --wait db api ui worker tls gotosocial || { "$compose" ps; exit 1; }
echo "==> Waiting for GoToSocial"
for _ in $(seq 1 60); do
"$compose" exec -T gotosocial wget -qO- http://127.0.0.1/api/v1/instance >/dev/null 2>&1 && break
sleep 2
done
echo "==> Creating the GoToSocial test user"
"$compose" exec -T gotosocial /gotosocial/gotosocial admin account create \
--username gtsuser --email gtsuser@gts.test --password 'Interop-Test-Password-1' >/dev/null
"$compose" exec -T gotosocial /gotosocial/gotosocial admin account confirm --username gtsuser >/dev/null
"$compose" run --rm driver
status=$?
if [ $status -ne 0 ]; then
echo "==> Scrobbler federation state"
"$compose" exec -T db psql -U scrobbler -d scrobbler -c \
"select activity_type, status, reason, attempts from federation_inbox order by id" -c \
"select a.activity_type, d.status, d.attempts, d.last_status, left(d.last_error, 200) as error
from federation_deliveries d join federation_activities a on a.id = d.activity_id order by d.id"
echo "==> Recent logs"
"$compose" logs --tail 200 worker gotosocial | grep -v "api/v1/accounts/relationships" | tail -40
fi
exit $status
+19
View File
@@ -68,3 +68,22 @@ def block(user_id: int, username: str, actor: FederationRemoteActor) -> Federati
activity = _store(user_id, lambda url: vocab.block(url, ids.actor_id(username), actor.uri))
queue(activity, [actor.inbox])
return activity
def undo_block(
user_id: int, username: str, actor: FederationRemoteActor
) -> FederationActivity | None:
"""Tell them they're unblocked: Undo our most recent Block of them (if we sent one)."""
block_activity = db.session.scalars(
db.select(FederationActivity)
.filter_by(user_id=user_id, activity_type="Block")
.filter(FederationActivity.document["object"].as_string() == actor.uri)
.order_by(FederationActivity.created_at.desc())
).first()
if block_activity is None:
return None
activity = _store(
user_id, lambda url: vocab.undo(url, ids.actor_id(username), block_activity.document)
)
queue(activity, [actor.inbox])
return activity
+4 -2
View File
@@ -5,9 +5,9 @@ from flask_smorest import Blueprint, abort
from scrobbler.api.decorators import authenticated
from scrobbler.extensions import db
from scrobbler.federation import activities, sharing
from scrobbler.federation import followers as follower_state
from scrobbler.federation import metrics as fed_metrics
from scrobbler.federation import sharing
from scrobbler.federation.models import FederationBlock, FederationFollower
from scrobbler.federation.schemas import (
BlockSchema,
@@ -225,10 +225,12 @@ def list_blocks():
def unblock(block_id):
"""Unblock an account
They can follow you again (they aren't re-added).
Their server is told (an Undo of the Block). They can follow you again; they aren't
re-added.
"""
block = db.session.get(FederationBlock, block_id)
if block is None or block.user_id != g.user.id:
abort(404, code="not_found", message="No such block")
activities.undo_block(g.user.id, g.user.username, block.actor) # tell their server
db.session.delete(block)
db.session.commit()
+20 -3
View File
@@ -63,12 +63,29 @@ def follow_received(
return "pending"
def undo_follow(user_id: int, actor: FederationRemoteActor) -> bool:
def undo_follow(user_id: int, actor: FederationRemoteActor, follow_id: str | None) -> str:
"""Handle an Undo of a Follow. It only removes the follower if it undoes their current
Follow: an Undo of an older one can arrive after a newer Follow (deliveries race)."""
follower = get(user_id, actor)
if follower is None:
return False
return "undo_not_following"
if follow_id is not None and follow_id != follower.follow_activity_id:
return "undo_stale"
db.session.delete(follower)
return True
return "unfollowed"
def undo_follow_by_id(actor: FederationRemoteActor, follow_id: str) -> str:
"""An Undo naming the Follow only by id: remove whoever follows with that Follow."""
follower = db.session.scalar(
db.select(FederationFollower).filter_by(
remote_actor_id=actor.id, follow_activity_id=follow_id
)
)
if follower is None:
return "undo_not_following"
db.session.delete(follower)
return "unfollowed"
def actor_deleted(actor: FederationRemoteActor) -> int:
+3 -1
View File
@@ -294,12 +294,14 @@ def on_follow(doc: dict, actor: FederationRemoteActor) -> str:
@handles("Undo")
def on_undo(doc: dict, actor: FederationRemoteActor) -> str:
inner = doc.get("object")
if isinstance(inner, str): # the Follow referenced by id rather than embedded
return followers.undo_follow_by_id(actor, inner)
if not isinstance(inner, dict) or inner.get("type") != "Follow":
return "undo_ignored"
if object_id(inner.get("actor")) not in (None, actor.uri):
raise Rejected("undo_other_actors_follow")
user, _ = _local_user(inner.get("object"))
return "unfollowed" if followers.undo_follow(user.id, actor) else "undo_not_following"
return followers.undo_follow(user.id, actor, object_id(inner))
@handles("Delete")
+7
View File
@@ -111,6 +111,13 @@ _OPERATIONS = {
[_USERNAME],
{"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND},
),
"federation.featured": (
"get",
"Featured",
"Pinned posts (always empty for now).",
[_USERNAME],
{"200": {"description": "OrderedCollection", "content": _AP}, "404": _NOT_FOUND},
),
"federation.instance_actor": (
"get",
"Instance actor",
+23 -2
View File
@@ -16,6 +16,7 @@ ACTOR_CONTEXT = [
"toot": "http://joinmastodon.org/ns#",
"discoverable": "toot:discoverable",
"indexable": "toot:indexable",
"featured": {"@id": "toot:featured", "@type": "@id"},
"schema": "http://schema.org#",
"PropertyValue": "schema:PropertyValue",
"value": "schema:value",
@@ -30,6 +31,7 @@ class ActorUrls:
outbox: str
followers: str
following: str
featured: str
shared_inbox: str
key_id: str
profile_page: str
@@ -43,6 +45,7 @@ def actor_urls(base_url: str, username: str, profile_page: str) -> ActorUrls:
outbox=f"{actor}/outbox",
followers=f"{actor}/followers",
following=f"{actor}/following",
featured=f"{actor}/collections/featured",
shared_inbox=f"{base_url}/inbox",
key_id=f"{actor}#main-key",
profile_page=profile_page,
@@ -90,6 +93,7 @@ def person(
"outbox": urls.outbox,
"followers": urls.followers,
"following": urls.following,
"featured": urls.featured,
"endpoints": {"sharedInbox": urls.shared_inbox},
"publicKey": public_key(urls, public_key_pem),
"manuallyApprovesFollowers": manually_approves_followers,
@@ -164,14 +168,31 @@ def accept(activity_id: str, actor_id: str, follow: dict) -> dict:
def reject(activity_id: str, actor_id: str, follow: dict) -> dict:
"""Decline a follow request, or end an existing follow."""
return _response("Reject", activity_id, actor_id, follow, follow["actor"])
"""Decline a follow request, or end an existing follow.
The Follow is referenced by id rather than embedded: some servers match an embedded
Follow by the pair of accounts, so a late Reject of an old Follow would cancel a
newer request between the same accounts. An id matches exactly that Follow."""
return _response("Reject", activity_id, actor_id, follow["id"], follow["actor"])
def block(activity_id: str, actor_id: str, blocked_actor: str) -> dict:
return _response("Block", activity_id, actor_id, blocked_actor, blocked_actor)
def undo(activity_id: str, actor_id: str, undone: dict) -> dict:
"""Withdraw one of our earlier activities (e.g. a Block when unblocking)."""
to = undone.get("to") or []
return {
"@context": AS_CONTEXT,
"id": activity_id,
"type": "Undo",
"actor": actor_id,
"object": undone,
"to": list(to),
}
def object_id(value) -> str | None:
"""An object's id, whether it's given inline (a dict) or as a bare URI."""
if isinstance(value, dict):
+22 -8
View File
@@ -105,8 +105,10 @@ def get_actor(uri: str, refresh: bool = False) -> FederationRemoteActor:
def actor_for_key(key_id: str, refresh: bool = False) -> FederationRemoteActor:
"""The actor that owns `key_id`: usually `<actor>#main-key`, sometimes a separate
key document naming its owner."""
"""The actor that owns `key_id`. Servers publish keys three ways:
* a fragment of the actor (`<actor>#main-key`, Mastodon);
* a URL that serves the actor document itself (`<actor>/main-key`, GoToSocial);
* a separate key document naming its `owner`."""
cached = db.session.scalar(db.select(FederationRemoteActor).filter_by(public_key_id=key_id))
if cached is not None and not refresh:
# Any age will do for checking a signature (a failure refreshes once). This also
@@ -116,12 +118,24 @@ def actor_for_key(key_id: str, refresh: bool = False) -> FederationRemoteActor:
try:
return _matching(get_actor(document_url, refresh=True), key_id)
except ActorError:
# Not an actor: a standalone key document pointing at its owner
doc = outbound.signed_get_json(document_url)
owner = doc.get("owner")
if doc.get("id") != key_id or not isinstance(owner, str) or _host(owner) != _host(key_id):
raise
return _matching(get_actor(owner, refresh=True), key_id)
pass # the key's URL isn't the actor's own URL: find the owner from the document
doc = outbound.signed_get_json(document_url)
if doc.get("id") == key_id and isinstance(doc.get("owner"), str):
owner = doc["owner"] # a standalone key document
elif isinstance(doc.get("id"), str) and _key_id_of(doc) == key_id:
owner = doc["id"] # the actor document, served at the key's URL
else:
raise ActorError(f"can't find who owns key {key_id}")
if _host(owner) != _host(key_id):
raise ActorError(f"key {key_id} claims an owner on another host")
return _matching(get_actor(owner, refresh=True), key_id)
def _key_id_of(doc: dict) -> str | None:
key = doc.get("publicKey")
if isinstance(key, list):
key = next((k for k in key if isinstance(k, dict)), None)
return key.get("id") if isinstance(key, dict) else None
def _matching(actor: FederationRemoteActor, key_id: str) -> FederationRemoteActor:
+5
View File
@@ -165,6 +165,11 @@ def followers(username: str):
return _collection(username, "followers", None, total) # the count, not who
@bp.get("/users/<username>/collections/featured")
def featured(username: str):
return _collection(username, "featured", []) # pinned posts: none (yet)
@bp.get("/users/<username>/following")
def following(username: str):
return _collection(username, "following", [])
+4
View File
@@ -111,6 +111,10 @@ def test_block_and_unblock(fed_client, auth_headers, accounts):
assert sent_types()[-1] == "Reject"
assert api(fed_client, "delete", f"/blocks/{block['id']}", auth_headers).status_code == 204
# Their server is told they're unblocked: an Undo of our Block
undo = db.session.scalars(db.select(FederationActivity).filter_by(activity_type="Undo")).one()
assert undo.document["object"]["type"] == "Block"
assert undo.document["object"]["object"] == accounts["bob"].uri
follow(fed_client, accounts["bob"]) # now allowed
assert len(api(fed_client, "get", "/followers", auth_headers).get_json()) == 1
+38
View File
@@ -185,6 +185,44 @@ def test_undo_follow(fed_client, bob, sharing_user):
assert followers_of(sharing_user) == []
def test_undo_referencing_the_follow_by_id(fed_client, bob, sharing_user):
follow = bob.follow()
bob.deliver(fed_client, follow)
process_all()
bob.deliver(fed_client, bob.activity("Undo", follow["id"]))
process_all()
assert last_item().reason == "unfollowed"
assert followers_of(sharing_user) == []
def test_rejects_reference_the_follow_by_id(fed_client, bob, sharing_user):
"""So a late Reject can't be matched to a newer request between the same accounts."""
from scrobbler.federation import followers
follow = bob.follow()
bob.deliver(fed_client, follow)
process_all()
followers.remove("alice", followers_of(sharing_user)[0])
db.session.commit()
[reject] = sent("Reject")
assert reject.document["object"] == follow["id"]
def test_a_late_undo_of_an_old_follow_keeps_the_new_one(fed_client, bob, sharing_user):
"""Deliveries race: an Undo of an earlier Follow can arrive after a newer Follow
(seen against GoToSocial). Only an Undo of the current Follow removes the follower."""
old_follow = bob.follow()
bob.deliver(fed_client, old_follow)
process_all()
new_follow = bob.follow()
bob.deliver(fed_client, new_follow)
bob.deliver(fed_client, bob.activity("Undo", old_follow)) # arrives after the new Follow
process_all()
assert last_item().reason == "undo_stale"
[follower] = followers_of(sharing_user)
assert follower.follow_activity_id == new_follow["id"]
def test_undo_of_someone_elses_follow_is_rejected(fed_client, bob, remote, sharing_user):
carol = RemoteAccount(remote, "carol")
follow = carol.follow()
+23
View File
@@ -254,3 +254,26 @@ def test_gone_actors_are_marked(fed_remote):
with pytest.raises(FetchError):
remote.get_actor(uri, refresh=True)
assert db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=uri)).gone is True
def test_actor_for_a_key_url_that_serves_the_actor(fed_remote):
"""GoToSocial: the key id is <actor>/main-key, and fetching it returns the actor."""
uri = fed_remote.url("/users/dana")
doc = actor_doc(fed_remote, name="dana")
key_id = f"{uri}/main-key"
doc["publicKey"]["id"] = key_id
fed_remote.routes["/users/dana"] = (200, {}, doc)
fed_remote.routes["/users/dana/main-key"] = (200, {}, doc) # same document
actor = remote.actor_for_key(key_id)
assert (actor.uri, actor.public_key_id) == (uri, key_id)
def test_key_owner_on_another_host_is_refused(fed_remote):
key_id = fed_remote.url("/keys/eve")
fed_remote.routes["/keys/eve"] = (
200,
{},
{"id": key_id, "owner": "https://elsewhere.example/users/eve", "publicKeyPem": "x"},
)
with pytest.raises(remote.ActorError):
remote.actor_for_key(key_id)