Safe outbound HTTP and remote actors (phase 2, step 2)
CI / validate-monitoring (push) Successful in 7s
CI / lint (push) Successful in 10s
CI / test (push) Successful in 1m22s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 5s

- net.py: the only client federation uses, on httpcore (BSD-3-Clause)
  with a guarded network backend: https only, every resolved address
  must be public (private, loopback, link-local, CGNAT, multicast and
  IPv4-mapped forms refused), and the connection goes to the checked
  address; 3 redirects max (GET only), 1 MB cap, 10s/20s timeouts
- outbound.py: signed GETs (instance actor, so authorized-fetch servers
  answer) and signed POSTs (as the user), trying the configured
  signature schemes in order and the next only on a 401
- remote.py + federation_remote_actors: fetch, validate (id matches
  URL and host, actor type, inbox on its host, key owned by the actor),
  cache for 24h, refresh on demand, 410 marks an actor gone; resolve a
  key id to its actor, including standalone key documents
- Config: FEDERATION_SIGNATURE_SCHEMES, FEDERATION_BLOCKED_DOMAINS,
  FEDERATION_DELIVERY_CONCURRENCY, and FEDERATION_INSECURE_TESTING
  (http and private addresses; only allowed for .test domains)
- Tests against a real local HTTP server, including verifying that our
  fetches carry a valid signature

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:21:00 +01:00
1 parent a6d3fb6c93
commit 52b9f0b27b
10 files changed
+823 -3

No files matched your search

+44 -3
View File
@@ -1,6 +1,6 @@
import os
from collections.abc import Mapping
from dataclasses import dataclass
from dataclasses import dataclass, field
from urllib.parse import urlsplit
@@ -12,12 +12,25 @@ def _flag(value) -> bool:
return str(value).strip().lower() in {"1", "true", "yes", "on"}
def _csv(value: str) -> tuple[str, ...]:
return tuple(part.strip().lower() for part in value.split(",") if part.strip())
KNOWN_SCHEMES = ("draft-cavage", "rfc9421")
@dataclass(frozen=True)
class FederationConfig:
enabled: bool = False
domain: str = "" # the handle's domain: @user@<domain>
base_url: str = "" # where actors live: <base_url>/users/<username>
key_secret: str = "" # encrypts actors' private keys at rest
signature_schemes: tuple[str, ...] = KNOWN_SCHEMES # outgoing order; next on a 401
blocked_domains: tuple[str, ...] = field(default=())
delivery_concurrency: int = 4
# TESTS ONLY: allow http:// and private addresses so CI can federate on a private
# network. Refused unless the domain is under the reserved .test TLD.
insecure_testing: bool = False
@classmethod
def from_mapping(cls, config: Mapping) -> "FederationConfig":
@@ -27,11 +40,21 @@ class FederationConfig:
value = config.get(key)
return str(value if value is not None else os.environ.get(key, default))
try:
concurrency = int(get("FEDERATION_DELIVERY_CONCURRENCY", "4"))
except ValueError:
raise FederationConfigError(
"FEDERATION_DELIVERY_CONCURRENCY must be a number"
) from None
result = cls(
enabled=_flag(get("FEDERATION_ENABLED", "0")),
domain=get("FEDERATION_DOMAIN").strip().lower(),
base_url=get("FEDERATION_BASE_URL").strip().rstrip("/"),
key_secret=get("FEDERATION_KEY_SECRET"),
signature_schemes=_csv(get("FEDERATION_SIGNATURE_SCHEMES", ",".join(KNOWN_SCHEMES))),
blocked_domains=_csv(get("FEDERATION_BLOCKED_DOMAINS")),
delivery_concurrency=concurrency,
insecure_testing=_flag(get("FEDERATION_INSECURE_TESTING", "0")),
)
result.validate()
return result
@@ -45,8 +68,14 @@ class FederationConfig:
"FEDERATION_ENABLED is on. It becomes part of every handle and can't change "
"once people follow."
)
if self.insecure_testing and not self.domain.endswith(".test"):
raise FederationConfigError(
"FEDERATION_INSECURE_TESTING is for automated tests only, and only allowed "
"with a FEDERATION_DOMAIN under .test."
)
url = urlsplit(self.base_url)
if url.scheme != "https" or not url.netloc or url.query or url.fragment:
schemes = ("https", "http") if self.insecure_testing else ("https",)
if url.scheme not in schemes or not url.netloc or url.query or url.fragment:
raise FederationConfigError(
"FEDERATION_BASE_URL must be the public https:// URL the API is served at "
"(e.g. https://scrobble.example) when FEDERATION_ENABLED is on."
@@ -57,9 +86,21 @@ class FederationConfig:
"is on. It encrypts actors' private keys; keep it safe and never change it "
"(e.g. python -c 'import secrets; print(secrets.token_urlsafe(48))')."
)
unknown = set(self.signature_schemes) - set(KNOWN_SCHEMES)
if not self.signature_schemes or unknown:
raise FederationConfigError(
f"FEDERATION_SIGNATURE_SCHEMES must list some of {', '.join(KNOWN_SCHEMES)}"
)
if not 1 <= self.delivery_concurrency <= 32:
raise FederationConfigError("FEDERATION_DELIVERY_CONCURRENCY must be 1-32")
def is_blocked(self, host: str) -> bool:
host = host.lower().rstrip(".")
return any(host == d or host.endswith("." + d) for d in self.blocked_domains)
def __repr__(self) -> str: # never print the secret
return (
f"FederationConfig(enabled={self.enabled}, domain={self.domain!r}, "
f"base_url={self.base_url!r}, key_secret=***)"
f"base_url={self.base_url!r}, key_secret=***, "
f"insecure_testing={self.insecure_testing})"
)
+26
View File
@@ -46,3 +46,29 @@ class FederationKey(db.Model):
public_key_pem: Mapped[str] = mapped_column(Text)
private_key_encrypted: Mapped[bytes] = mapped_column(LargeBinary)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
class FederationRemoteActor(db.Model):
"""A cached copy of another server's actor (who follows us, and their key)."""
__tablename__ = "federation_remote_actors"
id: Mapped[int] = mapped_column(Integer, primary_key=True)
uri: Mapped[str] = mapped_column(String(2048), unique=True)
host: Mapped[str] = mapped_column(String(255), index=True)
inbox: Mapped[str] = mapped_column(String(2048))
shared_inbox: Mapped[str | None] = mapped_column(String(2048))
username: Mapped[str | None] = mapped_column(String(255)) # preferredUsername
display_name: Mapped[str | None] = mapped_column(String(255))
public_key_id: Mapped[str] = mapped_column(String(2048), index=True)
public_key_pem: Mapped[str] = mapped_column(Text)
fetched_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow)
gone: Mapped[bool] = mapped_column(Boolean, default=False)
@property
def handle(self) -> str:
return f"@{self.username or '?'}@{self.host}"
@property
def delivery_inbox(self) -> str:
return self.shared_inbox or self.inbox
+165
View File
@@ -0,0 +1,165 @@
"""The only way federation code talks to other servers.
Guards against server-side request forgery (a remote document or redirect pointing us
at internal services):
* https only (http only with FEDERATION_INSECURE_TESTING, for CI on private networks);
* a host's addresses are resolved once and the request is refused if any is loopback,
private, link-local, multicast or otherwise not globally routable; the connection
then goes to the address that was checked (SNI and Host keep the name), so the name
can't be re-resolved somewhere else mid-request;
* at most 3 redirects, each checked the same way; responses capped at 1 MB;
10s to connect, 20s to read.
"""
import ipaddress
import json
import socket
from collections.abc import Callable
from dataclasses import dataclass
from urllib.parse import urljoin, urlsplit
import httpcore
from scrobbler.federation.protocol.media import ACTIVITY_JSON, LD_JSON
MAX_BYTES = 1024 * 1024
MAX_REDIRECTS = 3
TIMEOUTS = {"connect": 10.0, "read": 20.0, "write": 20.0, "pool": 10.0}
_REDIRECTS = {301, 302, 303, 307, 308}
Resolver = Callable[[str, int], list[str]]
class FetchError(Exception):
"""A request we refused to make or that didn't succeed."""
def __init__(self, reason: str, message: str, status: int | None = None):
self.reason, self.status = (
reason,
status,
) # reason: blocked, http, too_large, network, invalid
super().__init__(message)
@dataclass(frozen=True)
class Response:
status: int
headers: dict[str, str] # lower-cased names
body: bytes
url: str # after redirects
def json(self) -> dict:
try:
doc = json.loads(self.body)
except (json.JSONDecodeError, UnicodeDecodeError) as err:
raise FetchError("invalid", f"{self.url} didn't return JSON") from err
if not isinstance(doc, dict):
raise FetchError("invalid", f"{self.url} didn't return a JSON object")
return doc
def system_resolver(host: str, port: int) -> list[str]:
try:
infos = socket.getaddrinfo(host, port, type=socket.SOCK_STREAM)
except socket.gaierror as err:
raise FetchError("network", f"can't resolve {host}") from err
return list(dict.fromkeys(info[4][0] for info in infos))
def is_public(address: str) -> bool:
ip = ipaddress.ip_address(address.split("%", 1)[0])
if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped:
ip = ip.ipv4_mapped
return ip.is_global and not ip.is_multicast and not ip.is_reserved
class _GuardedBackend(httpcore.SyncBackend):
def __init__(self, resolver: Resolver, allow_private: bool):
super().__init__()
self.resolver, self.allow_private = resolver, allow_private
def connect_tcp(self, host, port, timeout=None, local_address=None, socket_options=None):
addresses = self.resolver(host, port)
if not addresses:
raise FetchError("network", f"{host} has no addresses")
if not self.allow_private:
refused = [a for a in addresses if not is_public(a)]
if refused:
raise FetchError("blocked", f"{host} resolves to a non-public address")
return super().connect_tcp(addresses[0], port, timeout, local_address, socket_options)
class Client:
def __init__(
self,
user_agent: str,
insecure_testing: bool = False,
resolver: Resolver = system_resolver,
):
self.user_agent = user_agent
self.insecure_testing = insecure_testing
self._pool = httpcore.ConnectionPool(
network_backend=_GuardedBackend(resolver, allow_private=insecure_testing),
max_connections=32,
keepalive_expiry=30,
)
def _check_url(self, url: str) -> None:
parts = urlsplit(url)
schemes = ("https", "http") if self.insecure_testing else ("https",)
if parts.scheme not in schemes or not parts.hostname:
raise FetchError("blocked", f"refusing to fetch {url}")
if parts.username or parts.password:
raise FetchError("blocked", "credentials in URL")
def request(
self, method: str, url: str, headers: dict[str, str] | None = None, body: bytes = b""
) -> Response:
"""One request, following redirects for GET only. Doesn't raise for HTTP errors."""
for _ in range(MAX_REDIRECTS + 1):
self._check_url(url)
response = self._send(method, url, headers or {}, body)
location = response.headers.get("location")
if method == "GET" and response.status in _REDIRECTS and location:
url = urljoin(url, location)
continue
return response
raise FetchError("blocked", "too many redirects")
def _send(self, method: str, url: str, headers: dict[str, str], body: bytes) -> Response:
sent = {"User-Agent": self.user_agent, **headers}
try:
with self._pool.stream(
method,
url,
headers=list(sent.items()),
content=body or None,
extensions={"timeout": TIMEOUTS},
) as response:
chunks, size = [], 0
for chunk in response.iter_stream():
size += len(chunk)
if size > MAX_BYTES:
raise FetchError("too_large", f"{url} sent more than {MAX_BYTES} bytes")
chunks.append(chunk)
return Response(
status=response.status,
headers={k.decode().lower(): v.decode("latin-1") for k, v in response.headers},
body=b"".join(chunks),
url=url,
)
except httpcore.TimeoutException as err:
raise FetchError("network", f"{url} timed out") from err
except (httpcore.NetworkError, httpcore.ProtocolError, httpcore.UnsupportedProtocol) as err:
raise FetchError("network", f"{url}: {err}") from err
def get_json(self, url: str, headers: dict[str, str] | None = None) -> dict:
response = self.request(
"GET", url, {"Accept": f"{ACTIVITY_JSON}, {LD_JSON}", **(headers or {})}
)
if response.status != 200:
raise FetchError("http", f"{url} answered {response.status}", response.status)
return response.json()
def close(self) -> None:
self._pool.close()
+72
View File
@@ -0,0 +1,72 @@
"""Signed requests to other servers, through the SSRF-safe client in net.py."""
import json
from flask import current_app
from scrobbler.federation import keys
from scrobbler.federation.net import Client, FetchError, Response
from scrobbler.federation.protocol import signatures
from scrobbler.federation.protocol.media import ACTIVITY_JSON, LD_JSON
from scrobbler.federation.protocol.signatures import SignedRequest
def client() -> Client:
"""One pooled client per app (created on first use)."""
existing = current_app.extensions.get("federation_client")
if existing is None:
from scrobbler import __version__
config = current_app.extensions["federation"]
existing = Client(
user_agent=f"Scrobbler/{__version__} (+{config.base_url})",
insecure_testing=config.insecure_testing,
)
current_app.extensions["federation_client"] = existing
return existing
def 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)}
def signed_get_json(url: str) -> dict:
"""GET an ActivityPub document, signed as the instance actor, so servers using
'authorized fetch' answer too."""
private = keys.private_key(keys.key_for(None))
headers = {"Accept": f"{ACTIVITY_JSON}, {LD_JSON}"}
schemes = current_app.extensions["federation"].signature_schemes
response = None
for scheme in schemes:
signed = _signed_headers("GET", url, headers, b"", instance_key_id(), private, scheme)
response = client().request("GET", url, signed)
if response.status != 401:
break
if response.status != 200:
raise FetchError("http", f"{url} answered {response.status}", response.status)
return response.json()
def signed_post(url: str, activity: dict, *, user_id: int, username: str) -> tuple[Response, str]:
"""POST an activity to an inbox, signed as the user. Tries the configured signature
schemes in order, moving to the next only when the server answers 401. Returns the
response and the scheme used."""
body = json.dumps(activity).encode()
private = keys.private_key(keys.key_for(user_id))
headers = {"Content-Type": LD_JSON, "Accept": ACTIVITY_JSON}
response, used = None, ""
for used in current_app.extensions["federation"].signature_schemes:
signed = _signed_headers("POST", url, headers, body, user_key_id(username), private, used)
response = client().request("POST", url, signed, body)
if response.status != 401:
break
return response, used
+125
View File
@@ -0,0 +1,125 @@
"""Remote actors: fetched with a signed GET, validated, cached for a day.
Validation (a document must really be the actor it claims to be):
* its `id` equals the URL it was fetched from, and the host matches;
* it's an actor type with an inbox on the same host;
* its `publicKey` is owned by it (`publicKey.owner == id`).
"""
from datetime import UTC, datetime, timedelta
from urllib.parse import urldefrag, urlsplit
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric.rsa import RSAPublicKey
from scrobbler.extensions import db
from scrobbler.federation import outbound
from scrobbler.federation.models import FederationRemoteActor
from scrobbler.federation.net import FetchError
ACTOR_TYPES = {"Person", "Service", "Application", "Group", "Organization"}
MAX_AGE = timedelta(hours=24)
class ActorError(Exception):
"""A remote document that isn't a valid actor (or key)."""
def _host(url: str) -> str:
return (urlsplit(url).hostname or "").lower()
def _text(value, limit: int) -> str | None:
return value[:limit] if isinstance(value, str) and value else None
def _parse_actor(uri: str, doc: dict) -> dict:
if doc.get("id") != uri:
raise ActorError(f"{uri} claims to be {doc.get('id')!r}")
if doc.get("type") not in ACTOR_TYPES:
raise ActorError(f"{uri} isn't an actor ({doc.get('type')!r})")
host = _host(uri)
inbox = doc.get("inbox")
if not isinstance(inbox, str) or _host(inbox) != host:
raise ActorError(f"{uri} has no inbox on its own host")
endpoints = doc.get("endpoints") if isinstance(doc.get("endpoints"), dict) else {}
shared = endpoints.get("sharedInbox")
if not isinstance(shared, str) or _host(shared) != host:
shared = None
key = doc.get("publicKey")
if isinstance(key, list): # some servers list several
key = next((k for k in key if isinstance(k, dict) and k.get("owner") == uri), None)
if not isinstance(key, dict) or key.get("owner") != uri or not key.get("publicKeyPem"):
raise ActorError(f"{uri} has no public key of its own")
key_id = key.get("id")
if not isinstance(key_id, str) or _host(key_id) != host:
raise ActorError(f"{uri}'s key id isn't on its host")
load_public_key(key["publicKeyPem"]) # must parse
return {
"host": host,
"inbox": inbox,
"shared_inbox": shared,
"username": _text(doc.get("preferredUsername"), 255),
"display_name": _text(doc.get("name"), 255),
"public_key_id": key_id,
"public_key_pem": key["publicKeyPem"],
}
def load_public_key(pem: str) -> RSAPublicKey:
try:
key = serialization.load_pem_public_key(pem.encode())
except (ValueError, TypeError) as err:
raise ActorError("unreadable public key") from err
if not isinstance(key, RSAPublicKey):
raise ActorError("only RSA keys are supported")
return key
def get_actor(uri: str, refresh: bool = False) -> FederationRemoteActor:
"""The actor at `uri`, from cache if fresh. Raises ActorError or FetchError."""
actor = db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=uri))
fresh = actor is not None and datetime.now(UTC) - actor.fetched_at < MAX_AGE
if actor is not None and not refresh and (fresh or actor.gone):
return actor
try:
fields = _parse_actor(uri, outbound.signed_get_json(uri))
except FetchError as err:
if err.status == 410 and actor is not None: # deleted account
actor.gone = True
db.session.commit()
raise
if actor is None:
actor = FederationRemoteActor(uri=uri, **fields)
db.session.add(actor)
else:
for name, value in fields.items():
setattr(actor, name, value)
actor.gone = False
actor.fetched_at = datetime.now(UTC)
db.session.commit()
return actor
def actor_for_key(key_id: str, refresh: bool = False) -> FederationRemoteActor:
"""The actor that owns `key_id`: usually `<actor>#main-key`, sometimes 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:
return get_actor(cached.uri)
document_url = urldefrag(key_id).url
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)
def _matching(actor: FederationRemoteActor, key_id: str) -> FederationRemoteActor:
if actor.public_key_id != key_id:
raise ActorError(f"{actor.uri} doesn't use key {key_id}")
return actor
@@ -0,0 +1,50 @@
"""federation remote actors
Revision ID: 211d4743f081
Revises: 34508576a6c7
Create Date: 2026-09-25 21:17:31.469467
"""
from alembic import op
import sqlalchemy as sa
# revision identifiers, used by Alembic.
revision = '211d4743f081'
down_revision = '34508576a6c7'
branch_labels = None
depends_on = None
def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('federation_remote_actors',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('uri', sa.String(length=2048), nullable=False),
sa.Column('host', sa.String(length=255), nullable=False),
sa.Column('inbox', sa.String(length=2048), nullable=False),
sa.Column('shared_inbox', sa.String(length=2048), nullable=True),
sa.Column('username', sa.String(length=255), nullable=True),
sa.Column('display_name', sa.String(length=255), nullable=True),
sa.Column('public_key_id', sa.String(length=2048), nullable=False),
sa.Column('public_key_pem', sa.Text(), nullable=False),
sa.Column('fetched_at', sa.DateTime(timezone=True), nullable=False),
sa.Column('gone', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('uri')
)
with op.batch_alter_table('federation_remote_actors', schema=None) as batch_op:
batch_op.create_index(batch_op.f('ix_federation_remote_actors_host'), ['host'], unique=False)
batch_op.create_index(batch_op.f('ix_federation_remote_actors_public_key_id'), ['public_key_id'], unique=False)
# ### end Alembic commands ###
def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
with op.batch_alter_table('federation_remote_actors', schema=None) as batch_op:
batch_op.drop_index(batch_op.f('ix_federation_remote_actors_public_key_id'))
batch_op.drop_index(batch_op.f('ix_federation_remote_actors_host'))
op.drop_table('federation_remote_actors')
# ### end Alembic commands ###