Skip to content

Node.js based forum software built for the modern web

refactor: upgrade HTTP signature logic to RFC 9421 standard

Julian Lamfb27a6579397
diff --git a/src/activitypub/index.js b/src/activitypub/index.js
index d4994f6298..947962bd6b 100644
--- a/src/activitypub/index.js
+++ b/src/activitypub/index.js
@@ -2,11 +2,8 @@
const nconf = require('nconf');
const winston = require('winston');
-const { createHash, getHashes, sign, verify } = require('crypto');
+const { createHash } = require('crypto');
const { cpus } = require('os');
-const { promisify } = require('util');
-const signAsync = promisify(sign);
-const verifyAsync = promisify(verify);
const request = require('../request');
const db = require('../database');
@@ -19,8 +16,6 @@ const utils = require('../utils');
const ttl = require('../cache/ttl');
const lru = require('../cache/lru');
const batch = require('../batch');
-const crypto = require('crypto');
-
const requestCache = ttl({
name: 'ap-request-cache',
max: 5000,
@@ -71,6 +66,8 @@ ActivityPub._constants = Object.freeze({
ActivityPub._cache = requestCache;
ActivityPub._sent = new Map(); // used only in local tests
+const signatures = require('./signatures');
+
ActivityPub.helpers = require('./helpers');
ActivityPub.inbox = require('./inbox');
ActivityPub.mocks = require('./mocks');
@@ -292,101 +289,22 @@ ActivityPub.fetchPublicKey = async (uri, ip) => {
};
ActivityPub.sign = async ({ key, keyId }, url, digest) => {
- // Returns string for use in 'Signature' header
- const { host, pathname } = new URL(url);
- const date = new Date().toUTCString();
-
- let headers = '(request-target) host date';
- let signed_string = `(request-target): ${digest ? 'post' : 'get'} ${pathname}\nhost: ${host}\ndate: ${date}`;
-
- // Calculate payload hash if payload present
- if (digest) {
- headers += ' digest';
- signed_string += `\ndigest: ${digest}`;
- }
-
- // Sign string using private key
- let signature = await signAsync('sha256', Buffer.from(signed_string), key);
- signature = signature.toString('base64');
-
- // Construct signature header
- return {
- date,
- ...(digest && { digest }),
- signature: `keyId="${keyId}",headers="${headers}",signature="${signature}",algorithm="hs2019"`,
- };
+ // Determines HTTP method based on digest presence
+ const method = digest ? 'POST' : 'GET';
+ return await signatures.sign({ key, keyId }, url, method, digest);
};
ActivityPub.verify = async (req) => {
ActivityPub.helpers.log('[activitypub/verify] Starting signature verification...');
- if (!req.headers.hasOwnProperty('signature')) {
- ActivityPub.helpers.log('[activitypub/verify] Failed, no signature header.');
- return false;
- }
-
- // Verify the signature string via public key
- try {
- // Break the signature apart
- let { keyId, headers, signature, algorithm, created, expires } = req.headers.signature.split(',').reduce((memo, cur) => {
- const split = cur.split('="');
- const key = split.shift();
- const value = split.join('="');
- memo[key] = value.slice(0, -1);
- return memo;
- }, {});
-
- const acceptableHashes = getHashes();
- if (algorithm === 'hs2019' || !acceptableHashes.includes(algorithm)) {
- algorithm = 'sha256';
- }
- // Verify Digest header matches request body
- if (headers.includes('digest')) {
- const receivedDigest = req.headers.digest;
- const bodyData = req.rawBody || (typeof req.body === 'string' ? req.body : JSON.stringify(req.body));
- const bodyDigest = `SHA-256=${createHash('sha256').update(bodyData).digest('base64')}`;
- if (receivedDigest !== bodyDigest) {
- ActivityPub.helpers.log('[activitypub/verify] Failed, digest mismatch.');
- return false;
- }
- }
-
- // Re-construct signature string
- const signed_string = headers.split(' ').reduce((memo, cur) => {
- switch (cur) {
- case '(request-target)': {
- memo.push(`${cur}: ${String(req.method).toLowerCase()} ${req.baseUrl}${req.path}`);
- break;
- }
-
- case '(created)': {
- memo.push(`${cur}: ${created}`);
- break;
- }
-
- case '(expires)': {
- memo.push(`${cur}: ${expires}`);
- break;
- }
-
- default: {
- memo.push(`${cur}: ${req.headers[cur]}`);
- break;
- }
- }
-
- return memo;
- }, []).join('\n');
-
- // Retrieve public key from remote instance
- ActivityPub.helpers.log(`[activitypub/verify] Retrieving pubkey for ${keyId}`);
- const publicKeyPem = await ActivityPub.fetchPublicKey(keyId, req.ip);
-
- return await verifyAsync('sha256', Buffer.from(signed_string), publicKeyPem, Buffer.from(signature, 'base64'));
- } catch (e) {
- ActivityPub.helpers.log('[activitypub/verify] Failed, key retrieval or verification failure.');
- return false;
+ const isValid = await signatures.verify(req, ActivityPub.fetchPublicKey);
+ if (!isValid) {
+ ActivityPub.helpers.log('[activitypub/verify] Signature verification failed.');
+ } else {
+ ActivityPub.helpers.log('[activitypub/verify] Signature verification succeeded.');
}
+
+ return isValid;
};
ActivityPub.get = async (type, id, uri, options) => {
@@ -540,7 +458,7 @@ ActivityPub.send = async (type, id, targets, payload) => {
await Promise.all(inboxBatch.map(async (uri) => {
const ok = await ActivityPub._sendMessage(uri, keyData, payload, digest);
if (!ok) {
- const queueId = crypto.createHash('sha256').update(`${type}:${id}:${uri}`).digest('hex');
+ const queueId = createHash('sha256').update(`${type}:${id}:${uri}`).digest('hex');
const nextTryOn = Date.now() + oneMinute;
retryQueueAdd.push(['ap:retry:queue', nextTryOn, queueId]);
retryQueuedSet.push([`ap:retry:queue:${queueId}`, {
diff --git a/src/activitypub/signatures.js b/src/activitypub/signatures.js
new file mode 100644
index 0000000000..8c5f3be180
--- /dev/null
+++ b/src/activitypub/signatures.js
@@ -0,0 +1,206 @@
+'use strict';
+
+const nconf = require('nconf');
+const winston = require('winston');
+const { createHash } = require('crypto');
+const {
+ genDraftSignature,
+ genDraftSignatureHeader,
+ genDraftSigningString,
+ importPrivateKey,
+ verifyDraftSignature,
+ parseDraftRequest,
+ parseRFC9421Request,
+ verifyRFC9421Signature,
+ parseAndImportPublicKey,
+} = require('@misskey-dev/node-http-message-signatures');
+
+const Signatures = module.exports;
+
+Signatures.calculateDigest = (body) => {
+ if (!body) return null;
+ const bodyData = typeof body === 'string' || Buffer.isBuffer(body) ?
+ body :
+ JSON.stringify(body);
+
+ const hash = createHash('sha256').update(bodyData).digest('base64');
+ return `SHA-256=${hash}`;
+};
+
+Signatures.sign = async ({ key, keyId }, url, method = 'GET', digest = null) => {
+ const parsedUrl = new URL(url);
+ const date = new Date().toUTCString();
+
+ // Headers required for signing
+ const headersToSign = {
+ date,
+ host: parsedUrl.host,
+ };
+
+ if (digest) {
+ headersToSign.digest = digest;
+ }
+
+ try {
+ // Import private key
+ const privateKey = await importPrivateKey(key, ['sign']);
+
+ // Determine signed headers list
+ const signedHeaders = digest ?
+ ['(request-target)', 'host', 'date', 'digest'] :
+ ['(request-target)', 'host', 'date'];
+
+ // Build signing string
+ const signingString = genDraftSigningString(
+ { method, url: parsedUrl.href, headers: headersToSign },
+ signedHeaders,
+ { keyId },
+ );
+
+ // Sign
+ const signature = await genDraftSignature(privateKey, signingString);
+
+ // Construct signature header
+ const signatureHeader = genDraftSignatureHeader(signedHeaders, keyId, signature, getDraftAlgoString(privateKey));
+
+ return {
+ date,
+ ...(digest && { digest }),
+ signature: signatureHeader,
+ };
+ } catch (err) {
+ winston.error(`[activitypub/signatures] Sign error: ${err.message}`);
+ throw err;
+ }
+};
+
+function getDraftAlgoString(key) {
+ const { name } = key.algorithm;
+ if (name === 'RSA') {
+ return 'rsa-sha256';
+ }
+ if (name === 'EC') {
+ return 'ecdsa-p256-sha256';
+ }
+ return 'rsa-sha256';
+}
+
+Signatures.verify = async (req, fetchPublicKeyFn) => {
+ try {
+ const { headers } = req;
+
+ // 1. Check if signature header exists (either RFC 9421 or draft format)
+ const hasSignature = headers.hasOwnProperty('signature') || headers.hasOwnProperty('signature-input');
+ if (!hasSignature) {
+ return false;
+ }
+
+ // 2. Digest check for requests with body (POST/PUT)
+ if (headers.digest) {
+ const bodyData = req.rawBody || (typeof req.body === 'string' ? req.body : JSON.stringify(req.body));
+ if (!bodyData) return false;
+
+ const computedDigest = Signatures.calculateDigest(bodyData);
+ if (headers.digest !== computedDigest) {
+ winston.warn('[activitypub/signatures] Digest mismatch during request verification');
+ return false;
+ }
+ }
+
+ // 3. Try draft signature verification first (legacy Cavage/hs2019)
+ const draftVerified = await tryVerifyDraft(req, fetchPublicKeyFn);
+ if (draftVerified) {
+ return true;
+ }
+
+ // 4. Try RFC 9421 signature verification
+ const rfcVerified = await tryVerifyRFC9421(req, fetchPublicKeyFn);
+ if (rfcVerified) {
+ return true;
+ }
+
+ // Neither verification method succeeded
+ return false;
+ } catch (err) {
+ winston.warn(`[activitypub/signatures] Verification failed: ${err.message}`);
+ return false;
+ }
+};
+
+async function tryVerifyDraft(req, fetchPublicKeyFn) {
+ try {
+ if (!req.headers.signature) {
+ return false;
+ }
+
+ // Build absolute URL required by the library parser
+ const fullUrl = new URL(req.originalUrl || req.url, nconf.get('url')).href;
+ const requestObj = {
+ method: req.method,
+ url: fullUrl,
+ headers: req.headers,
+ };
+
+ // Parse the draft request
+ const parsed = parseDraftRequest(requestObj);
+ if (!parsed || !parsed.value || !parsed.value.keyId) {
+ return false;
+ }
+
+ // Fetch public key PEM
+ const publicKeyPem = await fetchPublicKeyFn(parsed.value.keyId, req.ip);
+ if (!publicKeyPem) {
+ throw new Error(`Public key not found for keyId: ${parsed.value.keyId}`);
+ }
+
+ // Import public key into CryptoKey format required by library
+ const publicKey = await parseAndImportPublicKey(publicKeyPem);
+
+ // Verify signature using imported public key object
+ const result = await verifyDraftSignature(parsed.value, publicKey);
+
+ return !!result;
+ } catch (err) {
+ winston.debug(`[activitypub/signatures] Draft verification failed: ${err.message}`);
+ return false;
+ }
+}
+
+async function tryVerifyRFC9421(req, fetchPublicKeyFn) {
+ try {
+ if (!req.headers['signature-input'] || !req.headers.signature) {
+ return false;
+ }
+
+ // Build absolute URL required by the library parser
+ const fullUrl = new URL(req.originalUrl || req.url, nconf.get('url')).href;
+ const requestObj = {
+ method: req.method,
+ url: fullUrl,
+ headers: req.headers,
+ };
+
+ // Parse RFC 9421 request signature
+ const parsed = parseRFC9421Request(requestObj);
+ if (!parsed || !parsed.value || !parsed.value.keyId) {
+ return false;
+ }
+
+ // Fetch public key PEM
+ const publicKeyPem = await fetchPublicKeyFn(parsed.value.keyId, req.ip);
+ if (!publicKeyPem) {
+ throw new Error(`Public key not found for keyId: ${parsed.value.keyId}`);
+ }
+
+ // Import public key into CryptoKey format required by library
+ const publicKey = await parseAndImportPublicKey(publicKeyPem);
+
+ // Verify RFC 9421 signature using imported public key object
+ const result = await verifyRFC9421Signature(parsed.value, publicKey);
+
+ return !!result;
+ } catch (err) {
+ winston.debug(`[activitypub/signatures] RFC 9421 verification failed: ${err.message}`);
+ return false;
+ }
+}
\ No newline at end of file