House rules: primary constructors, a cancellation token on every async call, and the rules fail the build
Build / Build (push) Successful in 30s
Build / Build (push) Successful in 30s
- Services, controllers and jobs take their dependencies through primary constructors and use them directly; where a method already named a local after a dependency, the dependency takes its type's name. - Every async method takes a CancellationToken last and passes it down to MongoDB, HTTP and the job queue. The setup claim is still given back when a request is cancelled. - The federation and media options are read through IOptionsMonitor. - The Mastodon entities keep sending "" for empty strings, and every model field where null means something says so. - The inbox's 503 with Retry-After, which other servers retry, is the one server error left, and says why. - Arasaka.HouseRules.Analyzers checks all of this in every build, here and in PrivaPub.ClientModels as decePubClient builds it. Checked against GoToSocial in the pasture: 64 passed, 0 failed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01W4YtEJrgxG12Pc39Fai8Bd
This commit is contained in:
1 parent
f0a14c737f
commit
0f73f69239
176 files changed
+2789
-3974
No files matched your search
@@ -28,29 +28,18 @@ namespace PrivaPub.Federation.Inbox
|
||||
InboxResult NoSuchRecipient(HttpRequest request);
|
||||
}
|
||||
|
||||
public class InboxReceiver : IInboxReceiver
|
||||
public class InboxReceiver(
|
||||
ILocalActorService localActors,
|
||||
IRemoteActorService remoteActors,
|
||||
IJobQueue queue,
|
||||
IDomainBlocks domainBlocks,
|
||||
ILogger<InboxReceiver> logger,
|
||||
IInteractionLedger ledger = default) : IInboxReceiver
|
||||
{
|
||||
const int KeyRetrySeconds = 300;
|
||||
|
||||
const int MaxBodyBytes = 1024 * 1024;
|
||||
|
||||
readonly ILocalActorService _localActors;
|
||||
readonly IRemoteActorService _remoteActors;
|
||||
readonly IJobQueue _queue;
|
||||
readonly IDomainBlocks _domainBlocks;
|
||||
readonly ILogger<InboxReceiver> _logger;
|
||||
readonly IInteractionLedger _ledger;
|
||||
|
||||
public InboxReceiver(ILocalActorService localActors, IRemoteActorService remoteActors, IJobQueue queue, IDomainBlocks domainBlocks,
|
||||
ILogger<InboxReceiver> logger, IInteractionLedger ledger = default)
|
||||
{
|
||||
_localActors = localActors;
|
||||
_remoteActors = remoteActors;
|
||||
_queue = queue;
|
||||
_domainBlocks = domainBlocks;
|
||||
_logger = logger;
|
||||
_ledger = ledger;
|
||||
}
|
||||
|
||||
sealed class Receipt
|
||||
{
|
||||
@@ -91,10 +80,10 @@ namespace PrivaPub.Federation.Inbox
|
||||
|
||||
void Record(Receipt receipt, InboxResult result, int latencyMs)
|
||||
{
|
||||
if (_ledger == default || result == default)
|
||||
if (ledger == default || result == default)
|
||||
return;
|
||||
var verified = receipt.VerifiedActor != default;
|
||||
_ledger.Record(new InteractionEvent
|
||||
ledger.Record(new InteractionEvent
|
||||
{
|
||||
Channel = Interactions.Receive,
|
||||
Host = verified ? Interactions.HostOf(receipt.VerifiedActor) : receipt.ClaimedHost,
|
||||
@@ -111,6 +100,7 @@ namespace PrivaPub.Federation.Inbox
|
||||
}, verified ? receipt.VerifiedActor : default, hostClaimed: !verified && !receipt.Blocked);
|
||||
}
|
||||
|
||||
[System.Diagnostics.CodeAnalysis.SuppressMessage("HouseRules", "HR0007", Justification = "ActivityPub servers retry a 503 with Retry-After when the signing key cannot be fetched yet; a 4XX would make them drop the activity.")]
|
||||
async Task<InboxResult> Receive(HttpRequest request, LocalActor recipient, Receipt receipt, CancellationToken token)
|
||||
{
|
||||
if (request.ContentLength > MaxBodyBytes)
|
||||
@@ -123,7 +113,7 @@ namespace PrivaPub.Federation.Inbox
|
||||
var body = buffer.ToArray();
|
||||
receipt.Bytes = body.Length;
|
||||
|
||||
JsonNode activity;
|
||||
var activity = default(JsonNode);
|
||||
try
|
||||
{
|
||||
activity = JsonNode.Parse(body);
|
||||
@@ -149,10 +139,10 @@ namespace PrivaPub.Federation.Inbox
|
||||
return new(StatusCodes.Status401Unauthorized, "missing or unreadable Signature header", Reason: "no-signature");
|
||||
receipt.Signature = signature.Scheme;
|
||||
receipt.ClaimedHost ??= HostOf(signature.KeyId);
|
||||
if (_domainBlocks.IsSuspended(HostOf(signature.KeyId)) || _domainBlocks.IsSuspended(HostOf(actorUri)))
|
||||
if (domainBlocks.IsSuspended(HostOf(signature.KeyId)) || domainBlocks.IsSuspended(HostOf(actorUri)))
|
||||
{
|
||||
receipt.Blocked = true;
|
||||
receipt.ClaimedHost = _domainBlocks.IsSuspended(HostOf(actorUri)) ? HostOf(actorUri) : HostOf(signature.KeyId);
|
||||
receipt.ClaimedHost = domainBlocks.IsSuspended(HostOf(actorUri)) ? HostOf(actorUri) : HostOf(signature.KeyId);
|
||||
return new(StatusCodes.Status202Accepted, Reason: "suspended");
|
||||
}
|
||||
|
||||
@@ -160,14 +150,14 @@ namespace PrivaPub.Federation.Inbox
|
||||
if (requestProblem != default)
|
||||
return new(StatusCodes.Status401Unauthorized, requestProblem, Reason: HttpSignatures.ProblemCode(requestProblem));
|
||||
|
||||
var signed = signature.Signed(request, _localActors.BaseAddress);
|
||||
var keyOwner = await _remoteActors.GetActorByKeyId(signature.KeyId, refresh: false, token);
|
||||
var signed = signature.Signed(request, localActors.BaseAddress);
|
||||
var keyOwner = await remoteActors.GetActorByKeyId(signature.KeyId, refresh: false, token);
|
||||
if (keyOwner == default && type == "Delete" && Id(activity["object"]) == actorUri)
|
||||
return new(StatusCodes.Status202Accepted, Reason: "self-delete-unknown-key");
|
||||
if (keyOwner == default || !signature.VerifiedBy(keyOwner.PublicKey, signed))
|
||||
{
|
||||
keyOwner = await _remoteActors.GetActorByKeyId(signature.KeyId, refresh: true, token);
|
||||
if (keyOwner == default && _remoteActors.KeyTemporarilyUnavailable(signature.KeyId))
|
||||
keyOwner = await remoteActors.GetActorByKeyId(signature.KeyId, refresh: true, token);
|
||||
if (keyOwner == default && remoteActors.KeyTemporarilyUnavailable(signature.KeyId))
|
||||
return new(StatusCodes.Status503ServiceUnavailable, "the signing key could not be fetched; try again later", KeyRetrySeconds, "key-unavailable");
|
||||
if (keyOwner == default || !signature.VerifiedBy(keyOwner.PublicKey, signed))
|
||||
return new(StatusCodes.Status401Unauthorized, "the signature does not verify", Reason: "signature-invalid");
|
||||
@@ -178,7 +168,7 @@ namespace PrivaPub.Federation.Inbox
|
||||
receipt.VerifiedActor = keyOwner.ActorURI;
|
||||
var forwardedBy = string.Equals(keyOwner.ActorURI, actorUri, StringComparison.Ordinal) ? default : keyOwner.ActorURI;
|
||||
// (ours come back too, Friendica forwarding our comments in its threads: we know them already)
|
||||
if (forwardedBy != default && (!Forwarded.Takeable(type, activity, actorUri) || Origin.Same(actorUri, _localActors.BaseAddress)))
|
||||
if (forwardedBy != default && (!Forwarded.Takeable(type, activity, actorUri) || Origin.Same(actorUri, localActors.BaseAddress)))
|
||||
return new(StatusCodes.Status202Accepted, Reason: "forwarded-ignored");
|
||||
|
||||
var shapeProblem = await ShapeProblem(type, activity, actorUri, token);
|
||||
@@ -193,21 +183,21 @@ namespace PrivaPub.Federation.Inbox
|
||||
var dedupe = activityId == default ? default : (forwardedBy == default ? "inbox|" : "inbox|forwarded|") + activityId;
|
||||
var queuedPayload = JsonSerializer.Serialize(payload);
|
||||
var host = new Uri(actorUri).Host.ToLowerInvariant();
|
||||
var queued = await _queue.Enqueue(JobKind.ProcessInbox, queuedPayload, host, dedupe, token);
|
||||
var queued = await queue.Enqueue(JobKind.ProcessInbox, queuedPayload, host, dedupe, token);
|
||||
// one id its sender gave two activities is no duplicate (Friendica's ids are uniqid(), a prefix and the
|
||||
// microsecond, which two of its processes answering at once share): what each carries tells them apart, and a
|
||||
// true copy carries the same
|
||||
if (!queued && dedupe != default && CarriesOther(await _queue.Payload(dedupe, token), activity))
|
||||
queued = await _queue.Enqueue(JobKind.ProcessInbox, queuedPayload, host, $"{dedupe}|{Digest(activity)}", token);
|
||||
if (!queued && dedupe != default && CarriesOther(await queue.Payload(dedupe, token), activity))
|
||||
queued = await queue.Enqueue(JobKind.ProcessInbox, queuedPayload, host, $"{dedupe}|{Digest(activity)}", token);
|
||||
// an Undo of a Follow that comes again while the follow it ends exists again is meant for that follow: Mastodon
|
||||
// gives every Undo it sends after reading a roll-call (FEP-8fcf) one id, `{actor}#follows//undo`. It is kept
|
||||
// once per follow, so a retry still counts as a copy
|
||||
if (!queued && dedupe != default && type == "Undo" && await FollowAgain(activity, actorUri, token) is { } follow)
|
||||
queued = await _queue.Enqueue(JobKind.ProcessInbox, queuedPayload, host, $"{dedupe}|{Digest(activity)}|{follow}", token);
|
||||
queued = await queue.Enqueue(JobKind.ProcessInbox, queuedPayload, host, $"{dedupe}|{Digest(activity)}|{follow}", token);
|
||||
// FEP-8fcf: what the sender says of its followers here (FollowingSynchronization)
|
||||
if (queued && forwardedBy == default && FollowersSynchronization.Claim(actorUri, request.Headers[FollowersSynchronization.Header].ToString()) is { } claim)
|
||||
await _queue.Enqueue(JobKind.SynchronizeFollowing, JsonSerializer.Serialize(claim), host, FollowingSynchronization.DedupeKey(claim, activityId), token);
|
||||
_logger.LogInformation("Inbox {Recipient}: {Type} from {Actor} queued", recipient?.Handle ?? "shared", type, actorUri);
|
||||
await queue.Enqueue(JobKind.SynchronizeFollowing, JsonSerializer.Serialize(claim), host, FollowingSynchronization.DedupeKey(claim, activityId), token);
|
||||
logger.LogInformation("Inbox {Recipient}: {Type} from {Actor} queued", recipient?.Handle ?? "shared", type, actorUri);
|
||||
return new(StatusCodes.Status202Accepted, Reason: !queued ? "duplicate" : forwardedBy != default ? "forwarded" : "queued");
|
||||
}
|
||||
|
||||
@@ -215,7 +205,7 @@ namespace PrivaPub.Federation.Inbox
|
||||
async Task<string> FollowAgain(JsonNode activity, string actorUri, CancellationToken token)
|
||||
{
|
||||
if (activity["object"] is not JsonObject inner || Value(inner, "type") != "Follow" || Id(inner["object"]) is not { } targetUri
|
||||
|| await _localActors.FindByUri(targetUri, token) is not { } target)
|
||||
|| await localActors.FindByUri(targetUri, token) is not { } target)
|
||||
return default;
|
||||
var follower = await MongoDB.Entities.DB.Default.Find<Follower>()
|
||||
.Match(f => f.ActorURI == actorUri && f.LocalActorId == target.Id && f.LocalActorKind == target.Kind)
|
||||
@@ -244,7 +234,7 @@ namespace PrivaPub.Federation.Inbox
|
||||
var activityId = Id(activity);
|
||||
// (Funkwhale names its answer after the activity it answers: `<our Follow's id>/accept`)
|
||||
if (activityId != default && !Origin.Same(activityId, actorUri)
|
||||
&& !(type is "Accept" or "Reject" && Id(activity["object"]) is { } answered && Origin.Same(answered, _localActors.BaseAddress)
|
||||
&& !(type is "Accept" or "Reject" && Id(activity["object"]) is { } answered && Origin.Same(answered, localActors.BaseAddress)
|
||||
&& activityId.StartsWith(answered + "/", StringComparison.Ordinal)))
|
||||
return new(StatusCodes.Status400BadRequest, "the activity's id is not on its actor's origin", Reason: "id-cross-origin");
|
||||
|
||||
@@ -253,7 +243,7 @@ namespace PrivaPub.Federation.Inbox
|
||||
{
|
||||
case "Follow":
|
||||
// (by its actor's id, or the profile page Forte names instead)
|
||||
var target = await _localActors.FindByAddress(Id(inner), token);
|
||||
var target = await localActors.FindByAddress(Id(inner), token);
|
||||
if (target is not { IsFederated: true } || target.IsServerActor)
|
||||
return new(StatusCodes.Status404NotFound, "no such local actor", Reason: "unknown-recipient");
|
||||
break;
|
||||
|
||||
Reference in new issue
Block a user