Inbox: intake and verified processing of follows (phase 2, step 4)
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 14s
CI / test (push) Successful in 1m57s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s
CI / validate-monitoring (push) Successful in 8s
CI / lint (push) Successful in 14s
CI / test (push) Successful in 1m57s
CI / images (push) Skipped
CI / assets (push) Skipped
CI / python-package (push) Skipped
CI / notify (push) Successful in 6s
Intake (in the request, no network): size, content type and shape checks, blocked domains refused (403), duplicates acknowledged once, then stored and answered 202. Processing (federation.inbox worker task): - verify the HTTP signature with either scheme, as of when it arrived, using the cached key and refreshing the sender once on failure (key rotation); a deleted account's Delete still verifies from cache - the signer must be the activity's actor and the activity id must be on the actor's host - handlers: Follow (accept, or pending with manual approval; repeat follows re-accepted; blocked accounts rejected), Undo of a Follow (only by the same actor), Delete of an actor, Update of an actor; anything else recorded - items being processed are marked, retried on transient failures, re-queued if a worker dies, and pruned after 30 days Outgoing Accept/Reject/Block activities are stored with stable ids and queued per inbox for the delivery task (next step). Public activities are fetchable at /activities/<uuid>. Metrics for inbox activities and signature checks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01MK52BGoJbPhZ1vSFuKcGUW
This commit is contained in:
1 parent
c1a7dd0877
commit
f312c4b577
15 files changed
+1147
-60
No files matched your search
@@ -0,0 +1,85 @@
|
||||
"""A scripted remote fediverse account for federation tests."""
|
||||
|
||||
import dataclasses
|
||||
import json
|
||||
import uuid
|
||||
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
|
||||
from scrobbler.federation.protocol import signatures
|
||||
from scrobbler.federation.protocol.signatures import SignedRequest
|
||||
|
||||
OUR_BASE = "https://scrobble.test"
|
||||
|
||||
|
||||
class RemoteAccount:
|
||||
"""An account on a FakeRemote server: serves its actor document and signs deliveries."""
|
||||
|
||||
def __init__(self, server, name="bob"):
|
||||
self.server, self.name = server, name
|
||||
self.uri = server.url(f"/users/{name}")
|
||||
self.key_id = f"{self.uri}#main-key"
|
||||
self.rotate_key()
|
||||
self.serve()
|
||||
|
||||
def rotate_key(self):
|
||||
self.private = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
|
||||
@property
|
||||
def public_pem(self) -> str:
|
||||
return (
|
||||
self.private.public_key()
|
||||
.public_bytes(
|
||||
serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo
|
||||
)
|
||||
.decode()
|
||||
)
|
||||
|
||||
def document(self, **overrides) -> dict:
|
||||
doc = {
|
||||
"@context": ["https://www.w3.org/ns/activitystreams", "https://w3id.org/security/v1"],
|
||||
"id": self.uri,
|
||||
"type": "Person",
|
||||
"preferredUsername": self.name,
|
||||
"name": self.name.title(),
|
||||
"inbox": f"{self.uri}/inbox",
|
||||
"endpoints": {"sharedInbox": self.server.url("/inbox")},
|
||||
"publicKey": {"id": self.key_id, "owner": self.uri, "publicKeyPem": self.public_pem},
|
||||
}
|
||||
doc.update(overrides)
|
||||
return doc
|
||||
|
||||
def serve(self, **overrides):
|
||||
self.server.routes[f"/users/{self.name}"] = (200, {}, self.document(**overrides))
|
||||
|
||||
def activity(self, activity_type: str, obj, **extra) -> dict:
|
||||
return {
|
||||
"@context": "https://www.w3.org/ns/activitystreams",
|
||||
"id": self.server.url(f"/activities/{uuid.uuid4()}"),
|
||||
"type": activity_type,
|
||||
"actor": self.uri,
|
||||
"object": obj,
|
||||
**extra,
|
||||
}
|
||||
|
||||
def follow(self, username="alice") -> dict:
|
||||
return self.activity("Follow", f"{OUR_BASE}/users/{username}")
|
||||
|
||||
def deliver(
|
||||
self,
|
||||
client,
|
||||
activity: dict,
|
||||
path="/users/alice/inbox",
|
||||
scheme="draft-cavage",
|
||||
key=None,
|
||||
key_id=None,
|
||||
content_type="application/activity+json",
|
||||
):
|
||||
"""POST `activity` to our inbox, signed like a real server would."""
|
||||
body = json.dumps(activity).encode()
|
||||
request = SignedRequest("POST", OUR_BASE + path, {"Content-Type": content_type}, body)
|
||||
if scheme:
|
||||
added = signatures.sign(request, scheme, key_id or self.key_id, key or self.private)
|
||||
request = dataclasses.replace(request, headers={**request.headers, **added})
|
||||
return client.post(path, data=body, headers=dict(request.headers))
|
||||
@@ -0,0 +1,327 @@
|
||||
"""Receiving activities: intake, signature verification, and the handlers."""
|
||||
|
||||
import json
|
||||
from datetime import UTC, datetime, timedelta
|
||||
|
||||
import pytest
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa
|
||||
|
||||
from federation_helpers import RemoteAccount
|
||||
from scrobbler import worker
|
||||
from scrobbler.extensions import db
|
||||
from scrobbler.federation import inbox, sharing
|
||||
from scrobbler.federation.models import (
|
||||
FederationActivity,
|
||||
FederationBlock,
|
||||
FederationDelivery,
|
||||
FederationFollower,
|
||||
FederationInboxItem,
|
||||
FederationRemoteActor,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def bob(sharing_user, remote):
|
||||
return RemoteAccount(remote, "bob")
|
||||
|
||||
|
||||
def process_all():
|
||||
worker.run(once=True)
|
||||
db.session.expire_all()
|
||||
|
||||
|
||||
def last_item() -> FederationInboxItem:
|
||||
return db.session.scalars(
|
||||
db.select(FederationInboxItem).order_by(FederationInboxItem.id.desc())
|
||||
).first()
|
||||
|
||||
|
||||
def followers_of(user):
|
||||
return db.session.scalars(db.select(FederationFollower).filter_by(user_id=user.id)).all()
|
||||
|
||||
|
||||
def sent(activity_type):
|
||||
return db.session.scalars(
|
||||
db.select(FederationActivity).filter_by(activity_type=activity_type)
|
||||
).all()
|
||||
|
||||
|
||||
# --- Intake ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_intake_queues_and_answers_202(fed_client, bob, metric_delta):
|
||||
queued = metric_delta(
|
||||
"scrobbler_federation_inbox_activities_total", type="Follow", result="queued"
|
||||
)
|
||||
response = bob.deliver(fed_client, bob.follow())
|
||||
assert response.status_code == 202
|
||||
item = last_item()
|
||||
assert (item.status, item.activity_type, item.actor_uri) == ("queued", "Follow", bob.uri)
|
||||
assert set(item.headers) <= set(inbox.KEPT_HEADERS)
|
||||
assert queued.delta == 1
|
||||
|
||||
|
||||
def test_duplicates_are_acknowledged_once(fed_client, bob, metric_delta):
|
||||
duplicate = metric_delta(
|
||||
"scrobbler_federation_inbox_activities_total", type="Follow", result="duplicate"
|
||||
)
|
||||
follow = bob.follow()
|
||||
assert bob.deliver(fed_client, follow).status_code == 202
|
||||
assert bob.deliver(fed_client, follow).status_code == 202
|
||||
assert db.session.scalar(db.select(db.func.count()).select_from(FederationInboxItem)) == 1
|
||||
assert duplicate.delta == 1
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[b"not json", b"[]", b'{"type": "Follow"}', b'{"id": "x", "type": "Follow", "actor": 7}'],
|
||||
)
|
||||
def test_malformed_deliveries_are_400(fed_client, sharing_user, body):
|
||||
response = fed_client.post("/inbox", data=body, content_type="application/activity+json")
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_wrong_content_type_is_415(fed_client, bob):
|
||||
assert bob.deliver(fed_client, bob.follow(), content_type="text/plain").status_code == 415
|
||||
|
||||
|
||||
def test_too_large_is_413(fed_client, sharing_user):
|
||||
response = fed_client.post(
|
||||
"/inbox", data=b"x" * (inbox.MAX_BYTES + 1), content_type="application/activity+json"
|
||||
)
|
||||
assert response.status_code == 413
|
||||
|
||||
|
||||
def test_blocked_domains_are_refused(fed_client, fed_app, bob):
|
||||
config = fed_app.extensions["federation"]
|
||||
fed_app.extensions["federation"] = type(config)(
|
||||
**{**config.__dict__, "blocked_domains": ("127.0.0.1",)}
|
||||
)
|
||||
try:
|
||||
assert bob.deliver(fed_client, bob.follow()).status_code == 403
|
||||
finally:
|
||||
fed_app.extensions["federation"] = config
|
||||
|
||||
|
||||
# --- Follows -----------------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("scheme", ["draft-cavage", "rfc9421"])
|
||||
def test_follow_is_accepted(fed_client, bob, sharing_user, scheme, metric_delta):
|
||||
ok = metric_delta(
|
||||
"scrobbler_federation_signatures_total", direction="in", scheme=scheme, result="ok"
|
||||
)
|
||||
follow = bob.follow()
|
||||
bob.deliver(fed_client, follow, scheme=scheme)
|
||||
process_all()
|
||||
|
||||
assert (last_item().status, last_item().reason) == ("processed", "follow_accepted")
|
||||
[follower] = followers_of(sharing_user)
|
||||
assert (follower.state, follower.actor.uri, follower.follow_activity_id) == (
|
||||
"accepted",
|
||||
bob.uri,
|
||||
follow["id"],
|
||||
)
|
||||
[accept] = sent("Accept")
|
||||
assert accept.document["actor"] == "https://scrobble.test/users/alice"
|
||||
assert accept.document["object"] == follow
|
||||
assert accept.document["to"] == [bob.uri]
|
||||
[delivery] = db.session.scalars(db.select(FederationDelivery)).all()
|
||||
assert (delivery.inbox, delivery.status) == (f"{bob.uri}/inbox", "pending")
|
||||
assert ok.delta == 1
|
||||
|
||||
|
||||
def test_manual_approval_leaves_follow_pending(fed_client, bob, sharing_user):
|
||||
sharing.update(sharing_user.id, {"manually_approves_followers": True})
|
||||
bob.deliver(fed_client, bob.follow())
|
||||
process_all()
|
||||
assert [f.state for f in followers_of(sharing_user)] == ["pending"]
|
||||
assert sent("Accept") == []
|
||||
|
||||
|
||||
def test_repeat_follow_is_accepted_again(fed_client, bob, sharing_user):
|
||||
bob.deliver(fed_client, bob.follow())
|
||||
process_all()
|
||||
second = bob.follow()
|
||||
bob.deliver(fed_client, second)
|
||||
process_all()
|
||||
assert last_item().reason == "follow_refollowed"
|
||||
assert len(followers_of(sharing_user)) == 1
|
||||
assert followers_of(sharing_user)[0].follow_activity_id == second["id"]
|
||||
assert len(sent("Accept")) == 2
|
||||
|
||||
|
||||
def test_follow_for_someone_not_sharing(fed_client, bob, make_user):
|
||||
make_user(username="carol")
|
||||
bob.deliver(fed_client, bob.follow("carol"), path="/inbox")
|
||||
process_all()
|
||||
assert (last_item().status, last_item().reason) == ("rejected", "not_our_user")
|
||||
|
||||
|
||||
def test_blocked_account_gets_rejected(fed_client, bob, sharing_user):
|
||||
bob.deliver(fed_client, bob.follow())
|
||||
process_all()
|
||||
actor = db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=bob.uri))
|
||||
db.session.add(FederationBlock(user_id=sharing_user.id, remote_actor_id=actor.id))
|
||||
db.session.delete(followers_of(sharing_user)[0])
|
||||
db.session.commit()
|
||||
bob.deliver(fed_client, bob.follow())
|
||||
process_all()
|
||||
assert last_item().reason == "follow_blocked"
|
||||
assert followers_of(sharing_user) == []
|
||||
assert len(sent("Reject")) == 1
|
||||
|
||||
|
||||
# --- Undo, Delete, Update -----------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_undo_follow(fed_client, bob, sharing_user):
|
||||
follow = bob.follow()
|
||||
bob.deliver(fed_client, follow)
|
||||
process_all()
|
||||
bob.deliver(fed_client, bob.activity("Undo", follow))
|
||||
process_all()
|
||||
assert last_item().reason == "unfollowed"
|
||||
assert followers_of(sharing_user) == []
|
||||
|
||||
|
||||
def test_undo_of_someone_elses_follow_is_rejected(fed_client, bob, remote, sharing_user):
|
||||
carol = RemoteAccount(remote, "carol")
|
||||
follow = carol.follow()
|
||||
carol.deliver(fed_client, follow)
|
||||
process_all()
|
||||
bob.deliver(fed_client, bob.activity("Undo", follow))
|
||||
process_all()
|
||||
assert (last_item().status, last_item().reason) == ("rejected", "undo_other_actors_follow")
|
||||
assert len(followers_of(sharing_user)) == 1
|
||||
|
||||
|
||||
def test_deleted_account_stops_following(fed_client, bob, remote, sharing_user):
|
||||
bob.deliver(fed_client, bob.follow())
|
||||
process_all()
|
||||
remote.routes[f"/users/{bob.name}"] = (410, {}, b"") # the account is gone now
|
||||
bob.deliver(fed_client, bob.activity("Delete", bob.uri))
|
||||
process_all()
|
||||
assert last_item().reason == "actor_deleted"
|
||||
assert followers_of(sharing_user) == []
|
||||
assert db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=bob.uri)).gone
|
||||
|
||||
|
||||
def test_update_refreshes_the_actor(fed_client, bob, sharing_user):
|
||||
bob.deliver(fed_client, bob.follow())
|
||||
process_all()
|
||||
bob.serve(name="Robert")
|
||||
bob.deliver(fed_client, bob.activity("Update", bob.document(name="Robert")))
|
||||
process_all()
|
||||
assert last_item().reason == "actor_updated"
|
||||
assert (
|
||||
db.session.scalar(db.select(FederationRemoteActor).filter_by(uri=bob.uri)).display_name
|
||||
== "Robert"
|
||||
)
|
||||
|
||||
|
||||
def test_other_activities_are_recorded(fed_client, bob, sharing_user):
|
||||
bob.deliver(fed_client, bob.activity("Like", "https://scrobble.test/activities/x"))
|
||||
process_all()
|
||||
assert (last_item().status, last_item().reason) == ("processed", "recorded")
|
||||
|
||||
|
||||
# --- Signatures and identity ---------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_unsigned_deliveries_are_rejected(fed_client, bob):
|
||||
bob.deliver(fed_client, bob.follow(), scheme=None)
|
||||
process_all()
|
||||
assert (last_item().status, last_item().reason) == ("rejected", "signature_missing")
|
||||
|
||||
|
||||
def test_wrong_key_is_rejected_after_one_refresh(fed_client, bob, remote, metric_delta):
|
||||
failed = metric_delta(
|
||||
"scrobbler_federation_signatures_total",
|
||||
direction="in",
|
||||
scheme="draft-cavage",
|
||||
result="bad_signature",
|
||||
)
|
||||
impostor = rsa.generate_private_key(public_exponent=65537, key_size=2048)
|
||||
bob.deliver(fed_client, bob.follow(), key=impostor)
|
||||
process_all()
|
||||
assert (last_item().status, last_item().reason) == ("rejected", "signature_bad_signature")
|
||||
assert [r["path"] for r in remote.requests].count("/users/bob") == 2 # fetched, then refreshed
|
||||
assert failed.delta == 1
|
||||
|
||||
|
||||
def test_rotated_key_is_picked_up(fed_client, bob, sharing_user):
|
||||
bob.deliver(fed_client, bob.follow())
|
||||
process_all()
|
||||
bob.rotate_key()
|
||||
bob.serve() # the new key is published...
|
||||
bob.deliver(fed_client, bob.activity("Undo", followers_of(sharing_user)[0].follow_activity))
|
||||
process_all() # ...and our cached old key fails once, then we refetch
|
||||
assert last_item().reason == "unfollowed"
|
||||
|
||||
|
||||
def test_signed_by_one_actor_claiming_another_is_rejected(fed_client, bob, remote, sharing_user):
|
||||
carol = RemoteAccount(remote, "carol")
|
||||
forged = carol.follow() # carol's Follow...
|
||||
bob.deliver(fed_client, forged) # ...signed with bob's key
|
||||
process_all()
|
||||
assert (last_item().status, last_item().reason) == ("rejected", "actor_mismatch")
|
||||
assert followers_of(sharing_user) == []
|
||||
|
||||
|
||||
def test_activity_id_on_another_host_is_rejected(fed_client, bob, sharing_user):
|
||||
follow = bob.follow()
|
||||
follow["id"] = "https://elsewhere.example/activities/1"
|
||||
bob.deliver(fed_client, follow)
|
||||
process_all()
|
||||
assert (last_item().status, last_item().reason) == ("rejected", "id_host_mismatch")
|
||||
|
||||
|
||||
def test_signature_age_is_judged_by_arrival_time(fed_client, bob, sharing_user):
|
||||
"""A backlog mustn't turn valid deliveries into expired ones, and vice versa."""
|
||||
bob.deliver(fed_client, bob.follow())
|
||||
item = last_item()
|
||||
item.received_at = datetime.now(UTC) + timedelta(hours=13)
|
||||
db.session.commit()
|
||||
process_all()
|
||||
assert last_item().reason == "signature_expired"
|
||||
|
||||
|
||||
# --- Robustness ----------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_unreachable_sender_is_retried_then_failed(fed_client, bob, remote):
|
||||
bob.deliver(fed_client, bob.follow())
|
||||
remote.close() # their server is down: fetching the key fails
|
||||
for _ in range(inbox.MAX_ATTEMPTS):
|
||||
process_all()
|
||||
item = last_item()
|
||||
if item.status != "queued":
|
||||
break
|
||||
assert (item.status, item.attempts) == ("failed", inbox.MAX_ATTEMPTS)
|
||||
|
||||
|
||||
def test_maintenance_requeues_stale_and_prunes_old(fed_client, bob):
|
||||
bob.deliver(fed_client, bob.follow())
|
||||
item = last_item()
|
||||
item.status, item.received_at = "processing", datetime.now(UTC) - timedelta(minutes=30)
|
||||
db.session.commit()
|
||||
inbox.maintenance()
|
||||
db.session.expire_all()
|
||||
assert last_item().status == "queued"
|
||||
|
||||
item = last_item()
|
||||
item.status, item.received_at = "processed", datetime.now(UTC) - timedelta(days=31)
|
||||
db.session.commit()
|
||||
inbox.maintenance()
|
||||
assert db.session.scalar(db.select(db.func.count()).select_from(FederationInboxItem)) == 0
|
||||
|
||||
|
||||
def test_activities_are_only_fetchable_when_public(fed_client, bob, sharing_user):
|
||||
bob.deliver(fed_client, bob.follow())
|
||||
process_all()
|
||||
[accept] = sent("Accept")
|
||||
assert fed_client.get(f"/activities/{accept.id}").status_code == 404
|
||||
accept.public = True
|
||||
db.session.commit()
|
||||
assert json.loads(fed_client.get(f"/activities/{accept.id}").data)["type"] == "Accept"
|
||||
@@ -106,25 +106,6 @@ def test_instance_actor(fed_client, fed_ctx):
|
||||
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",
|
||||
|
||||
Reference in new issue
Block a user