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

+1
View File
@@ -14,6 +14,7 @@ dependencies = [
"flask-smorest>=0.47.0", "flask-smorest>=0.47.0",
"flask-sqlalchemy>=3.1.1", "flask-sqlalchemy>=3.1.1",
"gunicorn>=26.2.0", "gunicorn>=26.2.0",
"httpcore>=1.0.9",
"prometheus-client>=0.26.0", "prometheus-client>=0.26.0",
"psycopg[binary]>=3.3.6", "psycopg[binary]>=3.3.6",
"python-dotenv>=1.2.3", "python-dotenv>=1.2.3",
+44 -3
View File
@@ -1,6 +1,6 @@
import os import os
from collections.abc import Mapping from collections.abc import Mapping
from dataclasses import dataclass from dataclasses import dataclass, field
from urllib.parse import urlsplit from urllib.parse import urlsplit
@@ -12,12 +12,25 @@ def _flag(value) -> bool:
return str(value).strip().lower() in {"1", "true", "yes", "on"} 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) @dataclass(frozen=True)
class FederationConfig: class FederationConfig:
enabled: bool = False enabled: bool = False
domain: str = "" # the handle's domain: @user@<domain> domain: str = "" # the handle's domain: @user@<domain>
base_url: str = "" # where actors live: <base_url>/users/<username> base_url: str = "" # where actors live: <base_url>/users/<username>
key_secret: str = "" # encrypts actors' private keys at rest 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 @classmethod
def from_mapping(cls, config: Mapping) -> "FederationConfig": def from_mapping(cls, config: Mapping) -> "FederationConfig":
@@ -27,11 +40,21 @@ class FederationConfig:
value = config.get(key) value = config.get(key)
return str(value if value is not None else os.environ.get(key, default)) 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( result = cls(
enabled=_flag(get("FEDERATION_ENABLED", "0")), enabled=_flag(get("FEDERATION_ENABLED", "0")),
domain=get("FEDERATION_DOMAIN").strip().lower(), domain=get("FEDERATION_DOMAIN").strip().lower(),
base_url=get("FEDERATION_BASE_URL").strip().rstrip("/"), base_url=get("FEDERATION_BASE_URL").strip().rstrip("/"),
key_secret=get("FEDERATION_KEY_SECRET"), 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() result.validate()
return result return result
@@ -45,8 +68,14 @@ class FederationConfig:
"FEDERATION_ENABLED is on. It becomes part of every handle and can't change " "FEDERATION_ENABLED is on. It becomes part of every handle and can't change "
"once people follow." "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) 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( raise FederationConfigError(
"FEDERATION_BASE_URL must be the public https:// URL the API is served at " "FEDERATION_BASE_URL must be the public https:// URL the API is served at "
"(e.g. https://scrobble.example) when FEDERATION_ENABLED is on." "(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 " "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))')." "(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 def __repr__(self) -> str: # never print the secret
return ( return (
f"FederationConfig(enabled={self.enabled}, domain={self.domain!r}, " 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) public_key_pem: Mapped[str] = mapped_column(Text)
private_key_encrypted: Mapped[bytes] = mapped_column(LargeBinary) private_key_encrypted: Mapped[bytes] = mapped_column(LargeBinary)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utcnow) 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 ###
+60
View File
@@ -154,6 +154,8 @@ class FederatedTestConfig(_TestConfig):
FEDERATION_DOMAIN = "scrobble.test" FEDERATION_DOMAIN = "scrobble.test"
FEDERATION_BASE_URL = "https://scrobble.test" FEDERATION_BASE_URL = "https://scrobble.test"
FEDERATION_KEY_SECRET = "test-only-federation-key-secret-0123456789" FEDERATION_KEY_SECRET = "test-only-federation-key-secret-0123456789"
# Lets tests federate with servers on 127.0.0.1 over http (allowed for .test only).
FEDERATION_INSECURE_TESTING = "1"
@pytest.fixture(scope="session") @pytest.fixture(scope="session")
@@ -182,3 +184,61 @@ def sharing_user(fed_ctx, user):
sharing.update(user.id, {"enabled": True, "display_name": "Alice", "bio": "Listening."}) sharing.update(user.id, {"enabled": True, "display_name": "Alice", "bio": "Listening."})
return user return user
class FakeRemote:
"""A tiny HTTP server standing in for another fediverse server.
`routes[path] = (status, headers, body)`; `requests` records what it received.
"""
def __init__(self):
import threading
from werkzeug.serving import make_server
from werkzeug.wrappers import Request, Response
self.routes: dict = {}
self.requests: list = []
@Request.application
def app(request):
self.requests.append(
{
"method": request.method,
"path": request.full_path.rstrip("?"),
"headers": dict(request.headers),
"body": request.get_data(),
}
)
status, headers, body = self.routes.get(request.path, (404, {}, b"not found"))
if callable(body):
body = body(request)
if isinstance(body, dict | list):
import json as _json
body, headers = (
_json.dumps(body).encode(),
{"Content-Type": "application/activity+json", **headers},
)
return Response(body, status=status, headers=headers)
self.server = make_server("127.0.0.1", 0, app, threaded=True)
self.base = f"http://127.0.0.1:{self.server.server_port}"
# A short poll interval: shutdown() waits for the next poll
threading.Thread(
target=self.server.serve_forever, kwargs={"poll_interval": 0.02}, daemon=True
).start()
def url(self, path: str) -> str:
return self.base + path
def close(self):
self.server.shutdown()
@pytest.fixture
def remote():
server = FakeRemote()
yield server
server.close()
+256
View File
@@ -0,0 +1,256 @@
"""Outbound HTTP safety (net.py) and remote actor fetching (remote.py)."""
from datetime import UTC, datetime, timedelta
import pytest
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from scrobbler.extensions import db
from scrobbler.federation import keys, remote
from scrobbler.federation.models import FederationRemoteActor
from scrobbler.federation.net import MAX_BYTES, Client, FetchError, is_public
from scrobbler.federation.protocol import signatures
from scrobbler.federation.protocol.signatures import SignedRequest
# --- Address checks ----------------------------------------------------------------------
@pytest.mark.parametrize(
("address", "public"),
[
("8.8.8.8", True),
("2606:4700:4700::1111", True),
("127.0.0.1", False),
("10.1.2.3", False),
("172.16.0.1", False),
("192.168.1.1", False),
("169.254.169.254", False), # cloud metadata
("100.64.0.1", False), # carrier-grade NAT
("0.0.0.0", False),
("224.0.0.1", False),
("::1", False),
("fc00::1", False),
("fe80::1", False),
("::ffff:127.0.0.1", False), # IPv4-mapped loopback
("::ffff:8.8.8.8", True),
],
)
def test_is_public(address, public):
assert is_public(address) is public
def test_http_is_refused_outside_testing():
client = Client("test", resolver=lambda host, port: ["93.184.215.14"])
with pytest.raises(FetchError) as err:
client.request("GET", "http://example.com/users/bob")
assert err.value.reason == "blocked"
@pytest.mark.parametrize("addresses", [["10.0.0.5"], ["93.184.215.14", "127.0.0.1"], ["::1"]])
def test_names_resolving_to_private_addresses_are_refused(addresses):
"""Even one private address among several is enough to refuse (no retry elsewhere)."""
client = Client("test", resolver=lambda host, port: addresses)
with pytest.raises(FetchError) as err:
client.request("GET", "https://sneaky.example/users/bob")
assert err.value.reason == "blocked"
def test_urls_with_credentials_are_refused():
with pytest.raises(FetchError):
Client("test").request("GET", "https://user:pass@example.com/")
# --- Against a local server (insecure testing allows 127.0.0.1 over http) ---------------------
@pytest.fixture
def local_client():
client = Client("Scrobbler/test", insecure_testing=True)
yield client
client.close()
def test_get_json_and_user_agent(local_client, remote):
remote.routes["/doc"] = (200, {}, {"id": "x"})
assert local_client.get_json(remote.url("/doc")) == {"id": "x"}
assert remote.requests[0]["headers"]["User-Agent"] == "Scrobbler/test"
assert "application/activity+json" in remote.requests[0]["headers"]["Accept"]
def test_redirects_are_followed_for_get_up_to_a_limit(local_client, remote):
remote.routes["/a"] = (302, {"Location": "/b"}, b"")
remote.routes["/b"] = (301, {"Location": remote.url("/c")}, b"")
remote.routes["/c"] = (200, {}, {"ok": True})
assert local_client.get_json(remote.url("/a")) == {"ok": True}
remote.routes["/loop"] = (302, {"Location": "/loop"}, b"")
with pytest.raises(FetchError) as err:
local_client.request("GET", remote.url("/loop"))
assert err.value.reason == "blocked"
def test_posts_do_not_follow_redirects(local_client, remote):
remote.routes["/inbox"] = (307, {"Location": "/elsewhere"}, b"")
assert local_client.request("POST", remote.url("/inbox"), body=b"{}").status == 307
assert [r["path"] for r in remote.requests] == ["/inbox"]
def test_redirect_to_a_refused_url_is_refused():
client = Client("test", insecure_testing=False, resolver=lambda host, port: ["93.184.215.14"])
with pytest.raises(FetchError):
client._check_url("http://internal.example/")
def test_oversized_responses_are_cut_off(local_client, remote):
remote.routes["/big"] = (200, {}, b"x" * (MAX_BYTES + 1))
with pytest.raises(FetchError) as err:
local_client.request("GET", remote.url("/big"))
assert err.value.reason == "too_large"
def test_http_errors_and_bad_json(local_client, remote):
remote.routes["/gone"] = (410, {}, b"")
with pytest.raises(FetchError) as err:
local_client.get_json(remote.url("/gone"))
assert (err.value.reason, err.value.status) == ("http", 410)
remote.routes["/html"] = (200, {"Content-Type": "text/html"}, b"<html>")
with pytest.raises(FetchError) as err:
local_client.get_json(remote.url("/html"))
assert err.value.reason == "invalid"
# --- Remote actors ---------------------------------------------------------------------------
def make_key():
private = rsa.generate_private_key(public_exponent=65537, key_size=2048)
pem = (
private.public_key()
.public_bytes(serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo)
.decode()
)
return private, pem
def actor_doc(remote, name="bob", pem=None, **overrides):
uri = remote.url(f"/users/{name}")
doc = {
"@context": ["https://www.w3.org/ns/activitystreams"],
"id": uri,
"type": "Person",
"preferredUsername": name,
"name": name.title(),
"inbox": f"{uri}/inbox",
"endpoints": {"sharedInbox": remote.url("/inbox")},
"publicKey": {"id": f"{uri}#main-key", "owner": uri, "publicKeyPem": pem or make_key()[1]},
}
doc.update(overrides)
return doc
@pytest.fixture
def fed_remote(fed_ctx, remote):
return remote
def test_actor_is_fetched_signed_validated_and_cached(fed_remote):
fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote))
actor = remote.get_actor(fed_remote.url("/users/bob"))
assert (actor.username, actor.display_name, actor.host) == ("bob", "Bob", "127.0.0.1")
assert actor.handle == "@bob@127.0.0.1"
assert actor.delivery_inbox == fed_remote.url("/inbox")
# The fetch was signed with our instance actor's key, verifiably
sent = fed_remote.requests[0]
request = SignedRequest("GET", fed_remote.url("/users/bob"), sent["headers"], b"")
instance_public = serialization.load_pem_public_key(keys.key_for(None).public_key_pem.encode())
verified = signatures.verify(request, lambda key_id: instance_public)
assert verified.key_id == "https://scrobble.test/actor#main-key"
# Cached: a second lookup doesn't fetch again
remote.get_actor(fed_remote.url("/users/bob"))
assert len(fed_remote.requests) == 1
@pytest.mark.parametrize(
"overrides",
[
{"id": "https://elsewhere.example/users/bob"},
{"type": "Note"},
{"inbox": "https://elsewhere.example/inbox"},
{
"publicKey": {
"id": "x#main-key",
"owner": "https://elsewhere.example/users/eve",
"publicKeyPem": "x",
}
},
{"publicKey": None},
],
)
def test_invalid_actors_are_refused(fed_remote, overrides):
fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote, **overrides))
with pytest.raises(remote.ActorError):
remote.get_actor(fed_remote.url("/users/bob"))
def test_unreadable_key_is_refused(fed_remote):
uri = fed_remote.url("/users/bob")
doc = actor_doc(fed_remote)
doc["publicKey"]["publicKeyPem"] = "not a key"
fed_remote.routes["/users/bob"] = (200, {}, doc)
with pytest.raises(remote.ActorError):
remote.get_actor(uri)
def test_refresh_picks_up_a_rotated_key(fed_remote):
uri = fed_remote.url("/users/bob")
fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote, pem=make_key()[1]))
first = remote.get_actor(uri).public_key_pem
new_pem = make_key()[1]
fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote, pem=new_pem))
assert remote.get_actor(uri).public_key_pem == first # cached
assert remote.get_actor(uri, refresh=True).public_key_pem == new_pem
def test_stale_cache_is_refetched(fed_remote):
uri = fed_remote.url("/users/bob")
fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote))
actor = remote.get_actor(uri)
actor.fetched_at = datetime.now(UTC) - timedelta(hours=25)
db.session.commit()
remote.get_actor(uri)
assert len(fed_remote.requests) == 2
def test_actor_for_key(fed_remote):
fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote))
actor = remote.actor_for_key(fed_remote.url("/users/bob#main-key"))
assert actor.username == "bob"
with pytest.raises(remote.ActorError):
remote.actor_for_key(fed_remote.url("/users/bob#other-key"))
def test_actor_for_a_standalone_key_document(fed_remote):
uri = fed_remote.url("/users/carol")
doc = actor_doc(fed_remote, name="carol")
key_id = fed_remote.url("/keys/carol")
doc["publicKey"]["id"] = key_id
fed_remote.routes["/users/carol"] = (200, {}, doc)
fed_remote.routes["/keys/carol"] = (
200,
{},
{"id": key_id, "owner": uri, "publicKeyPem": doc["publicKey"]["publicKeyPem"]},
)
assert remote.actor_for_key(key_id).uri == uri
def test_gone_actors_are_marked(fed_remote):
uri = fed_remote.url("/users/bob")
fed_remote.routes["/users/bob"] = (200, {}, actor_doc(fed_remote))
remote.get_actor(uri)
fed_remote.routes["/users/bob"] = (410, {}, b"")
with pytest.raises(FetchError):
remote.get_actor(uri, refresh=True)
assert db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=uri)).gone is True
Generated
+24
View File
@@ -73,6 +73,15 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" }, { url = "https://files.pythonhosted.org/packages/10/cb/f2ad4230dc2eb1a74edf38f1a38b9b52277f75bef262d8908e60d957e13c/blinker-1.9.0-py3-none-any.whl", hash = "sha256:ba0efaa9080b619ff2f3459d1d500c57bddea4a6b424b60a91141db6fd2f08bc", size = 8458, upload-time = "2024-11-08T17:25:46.184Z" },
] ]
[[package]]
name = "certifi"
version = "2026.7.22"
source = { registry = "https://pypi.org/simple" }
sdist = { url = "https://files.pythonhosted.org/packages/a3/c2/24167ea9858356b47a87a50d39908bfdb72ceeefe0041586e704e5376b3a/certifi-2026.7.22.tar.gz", hash = "sha256:741e2c3b351ddf169a738da9f2c048608ff7f2c5cc02f1ebc6b118bb090d5d55", size = 138112, upload-time = "2026-07-22T03:35:12.644Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/0b/a7/71ac2cff56fec219ed242bb11b8efb69fcc4bec75db06fb7bfe35de520e6/certifi-2026.7.22-py3-none-any.whl", hash = "sha256:62f22742b58a1a33014a2b6b706588a8d7e2a88ae7bd1a6ebe8c992928483775", size = 136983, upload-time = "2026-07-22T03:35:11.276Z" },
]
[[package]] [[package]]
name = "cffi" name = "cffi"
version = "2.1.1" version = "2.1.1"
@@ -305,6 +314,19 @@ wheels = [
{ url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" }, { url = "https://files.pythonhosted.org/packages/04/4b/29cac41a4d98d144bf5f6d33995617b185d14b22401f75ca86f384e87ff1/h11-0.16.0-py3-none-any.whl", hash = "sha256:63cf8bbe7522de3bf65932fda1d9c2772064ffb3dae62d55932da54b31cb6c86", size = 37515, upload-time = "2025-04-24T03:35:24.344Z" },
] ]
[[package]]
name = "httpcore"
version = "1.0.9"
source = { registry = "https://pypi.org/simple" }
dependencies = [
{ name = "certifi" },
{ name = "h11" },
]
sdist = { url = "https://files.pythonhosted.org/packages/06/94/82699a10bca87a5556c9c59b5963f2d039dbd239f25bc2a63907a05a14cb/httpcore-1.0.9.tar.gz", hash = "sha256:6e34463af53fd2ab5d807f399a9b45ea31c3dfa2276f15a2c3f00afff6e176e8", size = 85484, upload-time = "2025-04-24T22:06:22.219Z" }
wheels = [
{ url = "https://files.pythonhosted.org/packages/7e/f5/f66802a942d491edb555dd61e3a9961140fd64c90bce1eafd741609d334d/httpcore-1.0.9-py3-none-any.whl", hash = "sha256:2d400746a40668fc9dec9810239072b40b4484b640a8c38fd654a024c7a1bf55", size = 78784, upload-time = "2025-04-24T22:06:20.566Z" },
]
[[package]] [[package]]
name = "httpcore2" name = "httpcore2"
version = "2.13.1" version = "2.13.1"
@@ -969,6 +991,7 @@ dependencies = [
{ name = "flask-smorest" }, { name = "flask-smorest" },
{ name = "flask-sqlalchemy" }, { name = "flask-sqlalchemy" },
{ name = "gunicorn" }, { name = "gunicorn" },
{ name = "httpcore" },
{ name = "prometheus-client" }, { name = "prometheus-client" },
{ name = "psycopg", extra = ["binary"] }, { name = "psycopg", extra = ["binary"] },
{ name = "python-dotenv" }, { name = "python-dotenv" },
@@ -992,6 +1015,7 @@ requires-dist = [
{ name = "flask-smorest", specifier = ">=0.47.0" }, { name = "flask-smorest", specifier = ">=0.47.0" },
{ name = "flask-sqlalchemy", specifier = ">=3.1.1" }, { name = "flask-sqlalchemy", specifier = ">=3.1.1" },
{ name = "gunicorn", specifier = ">=26.2.0" }, { name = "gunicorn", specifier = ">=26.2.0" },
{ name = "httpcore", specifier = ">=1.0.9" },
{ name = "prometheus-client", specifier = ">=0.26.0" }, { name = "prometheus-client", specifier = ">=0.26.0" },
{ name = "psycopg", extras = ["binary"], specifier = ">=3.3.6" }, { name = "psycopg", extras = ["binary"], specifier = ">=3.3.6" },
{ name = "python-dotenv", specifier = ">=1.2.3" }, { name = "python-dotenv", specifier = ">=1.2.3" },