Node.js based forum software built for the modern web
feat: add rate limiter to fetchPublicKey, one failing request at a time
Julian Lamd393de7a9826
diff --git a/public/language/en-GB/error.json b/public/language/en-GB/error.jsonindex 83d4272595..867a3426c6 100644--- a/public/language/en-GB/error.json+++ b/public/language/en-GB/error.json@@ -308,5 +308,6 @@"activitypub.pubKey-not-found": "Unable to resolve public key, so payload verification cannot take place.","activitypub.origin-mismatch": "The received object's origin does not match the sender's origin","activitypub.not-implemented": "The request was denied because it or an aspect of it is not implemented by the recipient server",- "activitypub.orphan": "The received object is not associated with any known local user."+ "activitypub.orphan": "The received object is not associated with any known local user.",+ "activitypub.rate-limited": "Your IP address has been rate-limited."}diff --git a/src/activitypub/index.js b/src/activitypub/index.jsindex 667527aa69..da5405cd07 100644--- a/src/activitypub/index.js+++ b/src/activitypub/index.js@@ -203,7 +203,7 @@ ActivityPub.getPrivateKey = async (type, id) => {return { key: privateKey, keyId };};-ActivityPub.fetchPublicKey = async (uri) => {+ActivityPub.fetchPublicKey = async (uri, ip) => {const cached = publicKeyCache.get(uri);if (cached !== undefined) {if (cached === null) {@@ -223,6 +223,15 @@ ActivityPub.fetchPublicKey = async (uri) => {throw new Error('[[error:activitypub.invalid-id]]');}+ // Rate limiting check - only if not cached+ const lockId = `pubkey:${ip}`;+ let lockStatus = await db.incrObjectField('locks', lockId);+ lockStatus = lockStatus <= 1;+ if (!lockStatus) {+ winston.warn(`[activitypub/fetchPublicKey] Rate limit exceeded for IP ${ip}`);+ throw new Error('[[error:activitypub.rate-limited]]');+ }+try {// Use requests.get with built-in SSRF protections// Set reasonable timeout and response size limit@@ -257,6 +266,8 @@ ActivityPub.fetchPublicKey = async (uri) => {throw new Error('[[error:activitypub.invalid-id]]');}throw err;+ } finally {+ await db.deleteObjectField('locks', lockId);}};@@ -338,7 +349,7 @@ ActivityPub.verify = async (req) => {// Retrieve public key from remote instanceActivityPub.helpers.log(`[activitypub/verify] Retrieving pubkey for ${keyId}`);- const publicKeyPem = await ActivityPub.fetchPublicKey(keyId);+ const publicKeyPem = await ActivityPub.fetchPublicKey(keyId, req.ip);return await verifyAsync('sha256', Buffer.from(signed_string), publicKeyPem, Buffer.from(signature, 'base64'));} catch (e) {