Node.js based forum software built for the modern web
fix(activitypub): harden split-domain vouching and self-link fallback
Julian Lam934ad5eea40a
diff --git a/public/language/en-GB/admin/settings/activitypub.json b/public/language/en-GB/admin/settings/activitypub.jsonindex 9e9671ad15..27f6ae1238 100644--- a/public/language/en-GB/admin/settings/activitypub.json+++ b/public/language/en-GB/admin/settings/activitypub.json@@ -14,7 +14,7 @@"allowLoopback": "Allow loopback processing","allowLoopback-help": "Useful for debugging purposes only. You should probably leave this disabled.","allowSplitDomain": "Allow split-domain federation",- "allowSplitDomain-help": "Enable to allow actors whose WebFinger handle domain differs from their ActivityPub document domain. This is useful for instances that separate identity (WebFinger) from content hosting (ActivityPub).",+ "allowSplitDomain-help": "Enable to allow actors whose WebFinger handle domain differs from their ActivityPub document domain. This is useful for instances that separate identity (WebFinger) from content hosting (ActivityPub). Note: the canonical (WebFinger) domain is the trust anchor — its WebFinger record must reference the actor document, and, when both sides publish a public key, the keys must match. Handles verified without a key match rely on the URL reference alone, so treat split-domain handles from domains with weak WebFinger hygiene with caution.","parentTraversalDepth": "Parent traversal depth","parentTraversalDepth-help": "Maximum number of times to traverse up the reply chain when building context. (Default: 50)",diff --git a/src/activitypub/actors.js b/src/activitypub/actors.jsindex 612b02f9fc..fd1528ac04 100644--- a/src/activitypub/actors.js+++ b/src/activitypub/actors.js@@ -154,7 +154,13 @@ Actors.assert = async (ids, options = {}) => {}// Two-way WebFinger verification (includes backreference + optional split-domain forward check).- const verdict = await activitypub.helpers.verifyActorWebfinger(actor.id, actor);+ // The self-attested self-link fallback is only allowed for actors/groups+ // with an existing persisted record (audit F-4)+ const knownActor = await db.exists(`userRemote:${actor.id}`) ||+ await db.exists(`categoryRemote:${actor.id}`);+ const verdict = await activitypub.helpers.verifyActorWebfinger(actor.id, actor, {+ allowSelfLinkFallback: knownActor,+ });if (!verdict || !verdict.ok) {activitypub.helpers.log(`[activitypub/actors] Webfinger verification failed (${verdict?.reason || 'unknown'}) for ${actor.id}`);return null;@@ -348,7 +354,12 @@ Actors.assertGroup = async (ids, options = {}) => {}// Two-way WebFinger verification (backreference check for security).- const verdict = await activitypub.helpers.verifyActorWebfinger(actor.id, actor);+ // The self-attested self-link fallback is only allowed for groups with an+ // existing persisted record (audit F-4)+ const knownGroup = await db.exists(`categoryRemote:${actor.id}`);+ const verdict = await activitypub.helpers.verifyActorWebfinger(actor.id, actor, {+ allowSelfLinkFallback: knownGroup,+ });if (!verdict || !verdict.ok) {activitypub.helpers.log(`[activitypub/actors] Webfinger verification failed (${verdict?.reason || 'unknown'}) for ${actor.id}`);return null;diff --git a/src/activitypub/helpers.js b/src/activitypub/helpers.jsindex 1a658d0224..a0f3f58717 100644--- a/src/activitypub/helpers.js+++ b/src/activitypub/helpers.js@@ -29,11 +29,20 @@ const webfingerCache = ttl({max: 5000,ttl: 1000 * 60 * 60 * 24, // 24 hours});+// Recent transport-level webfinger query failures (network error / non-200) —+// a broken or revoked webfinger endpoint must not be re-queried on every+// interaction (audit F-4)+const failedWebfingerQueryCache = ttl({+ name: 'ap-webfinger-query-failures',+ max: 5000,+ ttl: 1000 * 60 * 10, // 10 minutes+});const sha256 = payload => crypto.createHash('sha256').update(payload).digest('hex');const Helpers = module.exports;Helpers._webfingerCache = webfingerCache; // exported for tests+Helpers._failedWebfingerQueryCache = failedWebfingerQueryCache; // exported for testsHelpers._test = (method, args) => {// because I am lazy and I probably wrote some variant of this below code 1000 times already@@ -145,6 +154,11 @@ Helpers.query = async (id, { strict = true } = {}) => {return false;}+ // Short-circuit recent transport-level failures for this exact id (audit F-4)+ if (failedWebfingerQueryCache.has(id)) {+ return false;+ }+const cached = webfingerCache.get(id);// A cached entry that carries a hostname only answers queries for the domain// it was fetched from — entries stored under this key while querying a@@ -171,10 +185,12 @@ Helpers.query = async (id, { strict = true } = {}) => {timeout: 5000,}));} catch (e) {+ failedWebfingerQueryCache.set(id, true);return false;}if (response.statusCode !== 200) {+ failedWebfingerQueryCache.set(id, true);return false;}@@ -262,7 +278,7 @@ Helpers.query = async (id, { strict = true } = {}) => {return payload;};-Helpers.verifyActorWebfinger = async (actorId, actor) => {+Helpers.verifyActorWebfinger = async (actorId, actor, { allowSelfLinkFallback = false } = {}) => {if (!Helpers.isUri(actorId)) {return false;}@@ -282,9 +298,10 @@ Helpers.verifyActorWebfinger = async (actorId, actor) => {let backref = await Helpers.query(`${preferredUsername}@${idHostname}`, { strict: false });// Fallback for legacy actors (pre-split-domain): if WebFinger query fails, check- // the actor document for a self-link pointing to its own URI. This handles actors- // that were asserted before split-domain logic required WebFinger backreferences.- if (!backref && Helpers._hasValidSelfLink(actorId, actor)) {+ // the actor document for a self-link pointing to its own URI. Self-attested,+ // so only allowed for actors with a persisted record — first-time assertions+ // require a live webfinger backref (audit F-4).+ if (!backref && allowSelfLinkFallback && Helpers._hasValidSelfLink(actorId, actor)) {backref = {actorUri: actorId,subject: `acct:${preferredUsername}@${idHostname}`,@@ -337,6 +354,24 @@ Helpers.verifyActorWebfinger = async (actorId, actor) => {return { ok: false, splitDomain: false, canonicalHandle: null, reason: 'forward-mismatch' };}+ // Cross-check the key the identity domain published against the actor+ // document's key. A mismatch means the canonical domain is vouching for a key+ // it does not hold → reject. Absent keys cannot be compared (some split-domain+ // deployments do not expose the content-domain key in the identity domain's+ // webfinger) → proceed with keyVerified: false (audit F-3).+ let keyVerified = false;+ const forwardPem = forwardResult.publicKey?.publicKeyPem;+ const actorPem = actor.publicKey?.publicKeyPem;+ if (typeof forwardPem === 'string' && forwardPem.trim() &&+ typeof actorPem === 'string' && actorPem.trim()) {+ if (forwardPem.trim() !== actorPem.trim()) {+ return { ok: false, splitDomain: false, canonicalHandle: null, reason: 'key-mismatch' };+ }+ keyVerified = true;+ } else {+ winston.warn(`[activitypub] Split-domain actor ${actorId} verified without key comparison (key missing from forward webfinger or actor document)`);+ }+const blocked = await activitypub.instances.isAllowed(normalizedSubjectHost);if (!blocked.allowed) {return {@@ -352,6 +387,7 @@ Helpers.verifyActorWebfinger = async (actorId, actor) => {splitDomain: true,canonicalHandle: `${preferredUsername}@${normalizedSubjectHost}`,reason: 'split-domain',+ keyVerified,};};diff --git a/test/activitypub/split-domain.js b/test/activitypub/split-domain.jsindex e0b9a4b30b..f705f0ed22 100644--- a/test/activitypub/split-domain.js+++ b/test/activitypub/split-domain.js@@ -5,6 +5,7 @@ const nconf = require('nconf');const meta = require('../../src/meta');const utils = require('../../src/utils');const request = require('../../src/request');+const db = require('../../src/database');const activitypub = require('../../src/activitypub');@@ -65,6 +66,7 @@ Helpers.seedActor = (actorUri, overrides = {}) => {Helpers.reset = () => {activitypub._cache.reset();activitypub.helpers._webfingerCache.reset();+ activitypub.helpers._failedWebfingerQueryCache.reset();nconf.set('activitypubAllowSplitDomain', 1);meta.config.activitypubAllowSplitDomain = 1;nconf.set('activitypubAllowLoopback', 0);@@ -164,8 +166,10 @@ describe('verifyActorWebfinger', () => {const { domainB, username, actorUri } = Helpers.genSplitDomain();// Seed actor with a link array containing rel=self (simulates real AP actor docs)const actor = Helpers.seedActor(actorUri, { preferredUsername: username, link: [{ rel: 'self', href: actorUri, type: 'application/activity+json' }] });+ // allowSelfLinkFallback: true simulates an actor with a persisted record+ // (first-time assertions require a live webfinger backref, audit F-4)const verdict = await activitypub.helpers.verifyActorWebfinger(- actorUri, activitypub._cache.get(`0;${actorUri}`));+ actorUri, activitypub._cache.get(`0;${actorUri}`), { allowSelfLinkFallback: true });assert.ok(verdict);assert.ok(verdict.ok);assert.equal(verdict.canonicalHandle, `${username}@${domainB}`);@@ -288,7 +292,10 @@ describe('Actors.assert - hostname mismatch', () => {it('upgrades same-domain legacy actors via self-link fallback', async () => {const { domainB, username, actorUri } = Helpers.genSplitDomain();// Seed actor with link array (rel=self) — simulates real AP actor doc- const actor = Helpers.seedActor(actorUri, { preferredUsername: username, link: [{ rel: 'self', href: actorUri, type: 'application/activity+json' }] });+ Helpers.seedActor(actorUri, { preferredUsername: username, link: [{ rel: 'self', href: actorUri, type: 'application/activity+json' }] });+ // Persisted record — the actor was asserted before webfinger verification+ // existed, so the self-attested fallback is allowed (audit F-4)+ await db.setObject(`userRemote:${actorUri}`, { username: 'legacy_actor' });const result = await activitypub.actors.assert([actorUri]);assert.ok(Array.isArray(result));assert.equal(result.length, 1);@@ -616,3 +623,180 @@ describe('preferredUsername / hostname validation (audit F-2)', () => {assert.equal(getCalled, 1);});});++// ============================================================================++describe('Split-domain key cross-check (audit F-3)', () => {+ beforeEach(Helpers.reset);++ const seedKeys = (domainA, domainB, username, actorUri, forwardPem) => {+ activitypub.helpers._webfingerCache.set(`${username}@${domainB}`, {+ actorUri, username, hostname: domainB,+ subject: `acct:${username}@${domainA}`, splitDomain: true, subjectHostname: domainA,+ publicKey: forwardPem ? { id: `https://${domainA}/${username}#key`, owner: `acct:${username}@${domainA}`, publicKeyPem: forwardPem } : null,+ _raw: { links: [{ rel: 'self', href: actorUri, type: 'application/activity+json' }] },+ });+ activitypub.helpers._webfingerCache.set(`${username}@${domainA}`, {+ actorUri, username, hostname: domainA,+ subject: `acct:${username}@${domainA}`, splitDomain: false, subjectHostname: domainA,+ publicKey: forwardPem ? { id: `https://${domainA}/${username}#key`, owner: `acct:${username}@${domainA}`, publicKeyPem: forwardPem } : null,+ _raw: { links: [{ rel: 'self', href: actorUri, type: 'application/activity+json' }] },+ });+ };++ it('rejects when the forward webfinger key differs from the actor document key', async () => {+ const { domainA, domainB, username, actorUri } = Helpers.genSplitDomain();+ seedKeys(domainA, domainB, username, actorUri, 'FORWARD-KEY-PEM');+ const actor = Helpers.seedActor(actorUri, {+ preferredUsername: username,+ publicKey: { id: `${actorUri}#key`, owner: actorUri, publicKeyPem: 'ACTOR-DOC-KEY-PEM' },+ });+ const verdict = await activitypub.helpers.verifyActorWebfinger(actorUri, actor);+ assert.ok(verdict);+ assert.equal(verdict.ok, false);+ assert.equal(verdict.reason, 'key-mismatch');+ });++ it('accepts with keyVerified: true when the keys match', async () => {+ const { domainA, domainB, username, actorUri } = Helpers.genSplitDomain();+ seedKeys(domainA, domainB, username, actorUri, 'SAME-KEY-PEM');+ const actor = Helpers.seedActor(actorUri, {+ preferredUsername: username,+ publicKey: { id: `${actorUri}#key`, owner: actorUri, publicKeyPem: 'SAME-KEY-PEM' },+ });+ const verdict = await activitypub.helpers.verifyActorWebfinger(actorUri, actor);+ assert.ok(verdict);+ assert.equal(verdict.ok, true);+ assert.equal(verdict.reason, 'split-domain');+ assert.equal(verdict.keyVerified, true);+ });++ it('accepts with keyVerified: false when the forward webfinger carries no key', async () => {+ const { domainA, domainB, username, actorUri } = Helpers.genSplitDomain();+ seedKeys(domainA, domainB, username, actorUri, null);+ const actor = Helpers.seedActor(actorUri, {+ preferredUsername: username,+ publicKey: { id: `${actorUri}#key`, owner: actorUri, publicKeyPem: 'ACTOR-DOC-KEY-PEM' },+ });+ const verdict = await activitypub.helpers.verifyActorWebfinger(actorUri, actor);+ assert.ok(verdict);+ assert.equal(verdict.ok, true);+ assert.equal(verdict.keyVerified, false);+ });+});++// ============================================================================++describe('Self-link fallback gating (audit F-4)', () => {+ let originalGet;++ beforeEach(Helpers.reset);++ afterEach(() => {+ if (originalGet) {+ request.get = originalGet;+ originalGet = null;+ }+ });++ const seedSelfLinkedActor = (domainB, username, actorUri) => Helpers.seedActor(actorUri, {+ preferredUsername: username,+ link: [{ rel: 'self', href: actorUri, type: 'application/activity+json' }],+ });++ it('rejects first-time actors with a valid self-link when webfinger is unavailable', async () => {+ const { domainB, username, actorUri } = Helpers.genSplitDomain();+ const actor = seedSelfLinkedActor(domainB, username, actorUri);+ originalGet = request.get;+ request.get = async () => ({+ body: {},+ response: { statusCode: 404, headers: { 'content-type': 'application/jrd+json' } },+ });+ const verdict = await activitypub.helpers.verifyActorWebfinger(actorUri, actor);+ assert.ok(verdict);+ assert.equal(verdict.ok, false);+ assert.equal(verdict.reason, 'no-backreference');+ });++ it('accepts known actors via self-link fallback when webfinger is unavailable', async () => {+ const { domainB, username, actorUri } = Helpers.genSplitDomain();+ const actor = seedSelfLinkedActor(domainB, username, actorUri);+ originalGet = request.get;+ request.get = async () => ({+ body: {},+ response: { statusCode: 404, headers: { 'content-type': 'application/jrd+json' } },+ });+ const verdict = await activitypub.helpers.verifyActorWebfinger(actorUri, actor, { allowSelfLinkFallback: true });+ assert.ok(verdict);+ assert.equal(verdict.ok, true);+ assert.equal(verdict.splitDomain, false);+ assert.equal(verdict.canonicalHandle, `${username}@${domainB}`);+ });+});++// ============================================================================++describe('Webfinger failure negative cache (audit F-4)', () => {+ let originalGet;+ let getCalled;++ beforeEach(Helpers.reset);++ afterEach(() => {+ if (originalGet) {+ request.get = originalGet;+ originalGet = null;+ }+ });++ it('short-circuits repeated queries after a transport failure', async () => {+ const { domainB } = Helpers.genSplitDomain();+ getCalled = 0;+ originalGet = request.get;+ request.get = async () => {+ getCalled += 1;+ return {+ body: {},+ response: { statusCode: 404, headers: { 'content-type': 'application/jrd+json' } },+ };+ };++ const r1 = await activitypub.helpers.query(`user@${domainB}`, { strict: false });+ assert.equal(r1, false);+ assert.equal(getCalled, 1);++ // Second query within the failure window: no additional network call+ const r2 = await activitypub.helpers.query(`user@${domainB}`, { strict: false });+ assert.equal(r2, false);+ assert.equal(getCalled, 1);+ });++ it('does not negative-cache strict policy rejections of split-domain responses', async () => {+ const { domainA, domainB, username, actorUri } = Helpers.genSplitDomain();+ getCalled = 0;+ originalGet = request.get;+ request.get = async () => {+ getCalled += 1;+ return {+ body: {+ subject: `acct:${username}@${domainA}`,+ links: [{ rel: 'self', type: 'application/activity+json', href: actorUri }],+ publicKey: null,+ },+ response: { statusCode: 200, headers: { 'content-type': 'application/jrd+json' } },+ };+ };++ // Strict query rejects split-domain responses by policy (no cache write)+ const r1 = await activitypub.helpers.query(`${username}@${domainB}`);+ assert.equal(r1, false);+ assert.equal(getCalled, 1);++ // A subsequent non-strict query must still be answered (fresh fetch → payload),+ // not short-circuited by a failure entry+ const r2 = await activitypub.helpers.query(`${username}@${domainB}`, { strict: false });+ assert.ok(r2);+ assert.equal(r2.splitDomain, true);+ assert.equal(getCalled, 2);+ });+});