Skip to content

Node.js based forum software built for the modern web

feat(activitypub): verify incoming rfc 9421 signatures

Julian Lam872c61782877
diff --git a/src/activitypub/signatures.js b/src/activitypub/signatures.js
index 665842ad57..f224fac60b 100644
--- a/src/activitypub/signatures.js
+++ b/src/activitypub/signatures.js
@@ -8,16 +8,18 @@ const {
genDraftSignatureHeader,
genDraftSigningString,
importPrivateKey,
+ importPublicKey,
verifyDraftSignature,
parseDraftRequest,
- parseRFC9421Request,
- verifyRFC9421Signature,
RFC9421SignatureBaseFactory,
getWebcrypto,
} = require('@misskey-dev/node-http-message-signatures');
const Signatures = module.exports;
+// Clock skew tolerance for RFC 9421 created/expires parameters (seconds)
+const RFC9421_CLOCK_SKEW = 300;
+
// Calculates RFC 9530 Digest header string for request payloads.
Signatures.calculateDigest = (body) => {
if (!body) return null;
@@ -115,7 +117,7 @@ Signatures.signRfc9421 = async ({ key, keyId }, url, method = 'GET', digest = nu
// Sign
const signatureBuffer = await (await getWebcrypto()).subtle.sign(
- getSignAlgorithm(privateKey),
+ getKeyAlgorithm(privateKey),
privateKey,
new TextEncoder().encode(signatureBase),
);
@@ -126,7 +128,8 @@ Signatures.signRfc9421 = async ({ key, keyId }, url, method = 'GET', digest = nu
date,
...(digest && { digest }),
'signature-input': signatureInput,
- signature: `sig1=("${signature}")`,
+ // RFC 9421 2.3: the Signature value is an unquoted base64 byte sequence
+ signature: `sig1=${signature}`,
};
} catch (err) {
winston.error(`[activitypub/signatures] Sign (RFC 9421) error: ${err.message}`);
@@ -134,13 +137,13 @@ Signatures.signRfc9421 = async ({ key, keyId }, url, method = 'GET', digest = nu
}
};
-function getSignAlgorithm(key) {
+function getKeyAlgorithm(key) {
const { name, namedCurve } = key.algorithm;
- if (name === 'RSASSA-PKCS1-v1_5') {
- return { name, hash: 'SHA-256' };
+ if (name === 'RSASSA-PKCS1-v1_5' || name === 'RSA') {
+ return { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' };
}
- if (name === 'ECDSA') {
- return { name, hash: 'SHA-256', namedCurve };
+ if (name === 'ECDSA' || name === 'EC') {
+ return { name: 'ECDSA', hash: 'SHA-256', namedCurve };
}
if (name === 'Ed25519' || name === 'Ed448') {
return { name };
@@ -150,12 +153,15 @@ function getSignAlgorithm(key) {
function getDraftAlgoString(key) {
const { name } = key.algorithm;
- if (name === 'RSA') {
+ if (name === 'RSASSA-PKCS1-v1_5' || name === 'RSA') {
return 'rsa-sha256';
}
- if (name === 'EC') {
+ if (name === 'ECDSA' || name === 'EC') {
return 'ecdsa-p256-sha256';
}
+ if (name === 'Ed25519' || name === 'Ed448') {
+ return 'ed25519-sha512';
+ }
return 'rsa-sha256';
}
@@ -203,6 +209,30 @@ Signatures.verify = async (req, fetchPublicKeyFn) => {
}
};
+// Extracts the key identifier from request signature headers.
+// Supports both the draft `keyId` parameter (last occurrence wins, matching
+// the draft parser) and the RFC 9421 `keyid` parameter in Signature-Input.
+Signatures.getKeyId = (headers) => {
+ if (headers['signature-input']) {
+ const match = String(headers['signature-input']).match(/keyid\s*=\s*"((?:[^"\\]|\\.)*)"/i);
+ if (match) {
+ return match[1];
+ }
+ }
+
+ if (headers.signature) {
+ const segments = String(headers.signature).split(',');
+ for (let i = segments.length - 1; i >= 0; i--) {
+ const match = segments[i].match(/^\s*keyId\s*=\s*"((?:[^"\\]|\\.)*)"\s*$/i);
+ if (match) {
+ return match[1];
+ }
+ }
+ }
+
+ return null;
+};
+
function getRequestUrl(req) {
const relativePath = nconf.get('relative_path') || '';
let requestPath = req.originalUrl || req.url || req.path || '/';
@@ -275,38 +305,108 @@ async function tryVerifyRFC9421(req, fetchPublicKeyFn) {
headers: req.headers,
};
- // Parse RFC 9421 request signature
- const parsed = parseRFC9421Request(requestObj);
- const keyId = parsed?.value?.keyId || parsed?.keyId;
-
- if (!parsed || !keyId) {
+ // The base factory parses the Signature-Input structured field (a
+ // dictionary of label → [component list, parameters]) on construction
+ const base = new RFC9421SignatureBaseFactory(requestObj);
+ const signatures = parseSignatureHeader(req.headers.signature);
+ if (!signatures.size) {
return false;
}
- if (req.headers.digest) {
- const signedHeaders = ((parsed.value?.params?.headers ?? []) || [])
- .map(h => h.toLowerCase());
- if (!signedHeaders.includes('digest')) {
- winston.warn('[activitypub/signatures] Digest header present but not included in signed headers (RFC 9421)');
- return false;
+
+ const now = Math.floor(Date.now() / 1000);
+
+ // Verify each labeled signature — any one verifying is sufficient
+ for (const [label, [components, params = new Map()]] of base.requestSignatureInput) {
+ // Parameter values are stored bare (no nested params for sig parameters)
+ const keyid = params.get('keyid');
+ if (typeof keyid !== 'string' || !keyid) {
+ continue;
}
- }
- // Fetch public key PEM
- const publicKeyPem = await fetchPublicKeyFn(keyId, req.ip);
- if (!publicKeyPem) {
- throw new Error(`Public key not found for keyId: ${keyId}`);
- }
+ // RFC 9421 2.6.1: check created/expires within clock skew
+ const created = params.get('created');
+ if (typeof created === 'number' && (Math.abs(now - created) > RFC9421_CLOCK_SKEW)) {
+ continue;
+ }
+ const expires = params.get('expires');
+ if (typeof expires === 'number' && (expires + RFC9421_CLOCK_SKEW < now)) {
+ continue;
+ }
- const result = await verifyRFC9421Signature(
- parsed,
- publicKeyPem,
- msg => winston.warn(`[activitypub/signatures] verifyRFC9421Signature error: ${msg}`)
- );
+ // When Digest header is present, it must be covered by the signature.
+ // In RFC 9421 the signed components are the first element of the value array.
+ if (req.headers.digest) {
+ const signedHeaders = components.map(([name]) => name.toLowerCase());
+ if (!signedHeaders.includes('digest')) {
+ continue; // this signature doesn't cover the digest; try the next one
+ }
+ }
- return !!result;
+ const signature = signatures.get(label);
+ if (!signature) {
+ continue;
+ }
+
+ // Fetch public key PEM
+ // eslint-disable-next-line no-await-in-loop
+ const publicKeyPem = await fetchPublicKeyFn(keyid, req.ip);
+ if (!publicKeyPem) {
+ throw new Error(`Public key not found for keyId: ${keyid}`);
+ }
+
+ // eslint-disable-next-line no-await-in-loop
+ const verified = await verifySignatureValue({
+ signatureBase: base.generate(label),
+ signature,
+ publicKeyPem,
+ });
+ if (verified) {
+ return true;
+ }
+ }
+
+ return false;
} catch (err) {
winston.debug(`[activitypub/signatures] RFC 9421 verification failed: ${err.message}`);
return false;
}
-}
\ No newline at end of file
+}
+
+// Verifies an RFC 9421 signature value against a signature base using WebCrypto
+async function verifySignatureValue({ signatureBase, signature, publicKeyPem }) {
+ const publicKey = await importPublicKey(publicKeyPem, ['verify']);
+ const webcrypto = await getWebcrypto();
+ return await webcrypto.subtle.verify(
+ getKeyAlgorithm(publicKey),
+ publicKey,
+ Buffer.from(signature, 'base64'),
+ new TextEncoder().encode(signatureBase),
+ );
+}
+
+// Parses the Signature header (an RFC 8941 dictionary of label → base64 value)
+// into a Map of label → signature value
+function parseSignatureHeader(headerValue) {
+ const signatures = new Map();
+ for (const member of String(headerValue).split(',')) {
+ const eq = member.indexOf('=');
+ if (eq <= 0) {
+ continue;
+ }
+ const label = member.slice(0, eq).trim();
+ let value = member.slice(eq + 1).trim();
+ if (value.startsWith('"')) {
+ const end = value.indexOf('"', 1);
+ if (end === -1) {
+ continue;
+ }
+ value = value.slice(1, end);
+ }
+ if (!/^[0-9A-Za-z+/]*={0,2}$/.test(value)) {
+ continue;
+ }
+ signatures.set(label, value);
+ }
+ return signatures;
+}
diff --git a/src/middleware/activitypub.js b/src/middleware/activitypub.js
index d36433e18d..1bc9b411f4 100644
--- a/src/middleware/activitypub.js
+++ b/src/middleware/activitypub.js
@@ -59,10 +59,10 @@ middleware.verify = async function (req, res, next) {
return next();
}
- // Set calling user
- const keyId = req.headers.signature.split(',').filter(line => line.trim().startsWith('keyId="'));
- if (keyId.length) {
- req.uid = keyId.at(-1).trim().slice(7, -1).replace(/#.*$/, '');
+ // Set calling user (keyId may be a draft `keyId` or RFC 9421 `keyid` parameter)
+ const keyId = activitypub.signatures.getKeyId(req.headers);
+ if (keyId) {
+ req.uid = keyId.replace(/#.*$/, '');
}
activitypub.helpers.log('[middleware/activitypub] HTTP signature verification passed.');
@@ -143,12 +143,7 @@ middleware.assertPayload = helpers.try(async function (req, res, next) {
], ['id']);
compare = compare.reduce((keyId, { id }) => keyId || id || '', '').replace(/#[\w-]+$/, '');
- const { signature } = req.headers;
- let keyId = new Map(signature.split(',').filter(Boolean).map((v) => {
- const index = v.indexOf('=');
- return [v.substring(0, index).trim(), v.slice(index + 1)];
- })).get('keyId');
- keyId = (keyId || '').slice(1, -1).replace(/#[\w-]+$/, '');
+ const keyId = (activitypub.signatures.getKeyId(req.headers) || '').replace(/#[\w-]+$/, '');
if (compare !== keyId) {
activitypub.helpers.log('[middleware/activitypub] Key ownership cross-check failed.');
return res.sendStatus(403);
diff --git a/test/activitypub/middleware.js b/test/activitypub/middleware.js
index 3867d88dae..a8b60ff42d 100644
--- a/test/activitypub/middleware.js
+++ b/test/activitypub/middleware.js
@@ -98,6 +98,24 @@ describe('middleware.verify', () => {
assert.strictEqual(response.statusCode, 400);
});
+ it('should call next() and set req.uid when an RFC 9421 signature is valid', async () => {
+ const path = `/user/${username}/inbox`;
+ const body = { foo: 'bar' };
+ const endpoint = `${nconf.get('url')}${path}`;
+ const hash = createHash('sha256');
+ hash.update(JSON.stringify(body));
+ const checksum = `SHA-256=${hash.digest('base64')}`;
+ const signedHeaders = await activitypub.signatures.signRfc9421(keyData, endpoint, 'POST', checksum);
+ const req = buildReq('POST', path, signedHeaders);
+ req.body = body;
+ const res = buildRes();
+ const { nextCalled, res: response } = await runMiddleware(req, res);
+
+ assert.strictEqual(nextCalled, true);
+ assert.strictEqual(response.statusCode, null);
+ assert.strictEqual(req.uid, `${nconf.get('url')}/uid/${uid}`);
+ });
+
it('should reject with 401 when no signature is present', async () => {
const path = `/user/${username}/inbox`;
const req = buildReq('POST', path, {});
diff --git a/test/activitypub/sendWorker.js b/test/activitypub/sendWorker.js
index 9a38fcf317..861862f20a 100644
--- a/test/activitypub/sendWorker.js
+++ b/test/activitypub/sendWorker.js
@@ -94,7 +94,11 @@ describe('sendWorker', () => {
try {
if (entry.hasRfc) {
const base = new RFC9421SignatureBaseFactory({ method: req.method, url: fullUrl, headers: req.headers });
- const sigB64 = req.headers.signature.match(/^sig1=\("(.*)"\)$/)[1];
+ // Signature values are unquoted base64 (RFC 9421 2.3); strip an optional quote for leniency
+ let sigB64 = String(req.headers.signature).replace(/^sig1=/, '');
+ if (sigB64.startsWith('"') && sigB64.endsWith('"')) {
+ sigB64 = sigB64.slice(1, -1);
+ }
const pub = await importPublicKey(pubPem, ['verify']);
entry.rfcValid = await webcrypto.subtle.verify(
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
diff --git a/test/activitypub/signatures.js b/test/activitypub/signatures.js
index 49cf1d4d6c..d8c27ac645 100644
--- a/test/activitypub/signatures.js
+++ b/test/activitypub/signatures.js
@@ -146,5 +146,132 @@ describe('http signature signing and verification', () => {
const verified = await activitypub.verify(req);
assert.strictEqual(verified, true);
});
+
+ it('should return true when a valid RFC 9421 signature is passed in', async () => {
+ const endpoint = `${nconf.get('url')}/user/${username}/inbox`;
+ const path = `/user/${username}/inbox`;
+ const keyData = await activitypub.getPrivateKey('uid', uid);
+ const { date, 'signature-input': signatureInput, signature } =
+ await activitypub.signatures.signRfc9421(keyData, endpoint, 'GET');
+ const { host } = nconf.get('url_parsed');
+ const req = {
+ ...mockReqBase,
+ ...{
+ url: path,
+ path,
+ headers: { date, 'signature-input': signatureInput, signature, host },
+ },
+ };
+
+ const verified = await activitypub.verify(req);
+ assert.strictEqual(verified, true);
+ });
+
+ it('should return true when an RFC 9421 signature with digest is passed in', async () => {
+ const endpoint = `${nconf.get('url')}/user/${username}/inbox`;
+ const path = `/user/${username}/inbox`;
+ const payload = { foo: 'bar' };
+ const keyData = await activitypub.getPrivateKey('uid', uid);
+ const hash = createHash('sha256');
+ hash.update(JSON.stringify(payload));
+ const checksum = `SHA-256=${hash.digest('base64')}`;
+ const { date, digest, 'signature-input': signatureInput, signature } =
+ await activitypub.signatures.signRfc9421(keyData, endpoint, 'POST', checksum);
+ const { host } = nconf.get('url_parsed');
+ const req = {
+ ...mockReqBase,
+ ...{
+ method: 'POST',
+ url: path,
+ path,
+ body: payload,
+ headers: { date, digest, 'signature-input': signatureInput, signature, host },
+ },
+ };
+
+ const verified = await activitypub.verify(req);
+ assert.strictEqual(verified, true);
+ });
+
+ it('should return false when an RFC 9421 signature does not verify', async () => {
+ const endpoint = `${nconf.get('url')}/user/${username}/inbox`;
+ const path = `/user/${username}/inbox`;
+ const keyData = await activitypub.getPrivateKey('uid', uid);
+ const { date, 'signature-input': signatureInput, signature } =
+ await activitypub.signatures.signRfc9421(keyData, endpoint, 'GET');
+ const { host } = nconf.get('url_parsed');
+ const req = {
+ ...mockReqBase,
+ ...{
+ url: path,
+ path,
+ headers: {
+ // Tamper with a covered component (date)
+ date: 'Wed, 01 Jan 2020 00:00:00 GMT',
+ 'signature-input': signatureInput,
+ signature,
+ host,
+ },
+ },
+ };
+
+ const verified = await activitypub.verify(req);
+ assert.strictEqual(verified, false);
+ });
+ });
+
+ describe('.getKeyId()', () => {
+ it('should extract the keyId from a draft signature header', () => {
+ const headers = {
+ signature: 'keyId="https://example.org/user/test#key",algorithm="rsa-sha256",headers="(request-target) host date",signature="abc="',
+ };
+ assert.strictEqual(activitypub.signatures.getKeyId(headers), 'https://example.org/user/test#key');
+ });
+
+ it('should use the last keyId when a draft signature header contains duplicates', () => {
+ const headers = {
+ signature: 'keyId="https://example.org/a#key",keyId="https://example.org/b#key",signature="abc="',
+ };
+ assert.strictEqual(activitypub.signatures.getKeyId(headers), 'https://example.org/b#key');
+ });
+
+ it('should extract the keyid from an RFC 9421 Signature-Input header', () => {
+ const headers = {
+ 'signature-input': 'sig1=("@request-target" "host" "date");created=1787933487;keyid="https://example.org/user/test#key"',
+ signature: 'sig1="abc="',
+ };
+ assert.strictEqual(activitypub.signatures.getKeyId(headers), 'https://example.org/user/test#key');
+ });
+
+ it('should return null when no key identifier is present', () => {
+ assert.strictEqual(activitypub.signatures.getKeyId({ signature: 'signature="abc="' }), null);
+ assert.strictEqual(activitypub.signatures.getKeyId({}), null);
+ });
+ });
+
+ describe('draft signatures with non-RSA keys', () => {
+ it('should sign and verify a draft signature made with an EC key', async () => {
+ const { generateKeyPairSync } = require('crypto');
+ const kp = generateKeyPairSync('ec', { namedCurve: 'P-256' });
+ const privPem = kp.privateKey.export({ format: 'pem', type: 'pkcs8' }).toString();
+ const pubPem = kp.publicKey.export({ format: 'pem', type: 'spki' }).toString();
+ const keyId = 'https://example.org/ec-actor#key';
+ const endpoint = `${nconf.get('url')}/uid/999/inbox`;
+ const headers = await activitypub.signatures.sign({ key: privPem, keyId }, endpoint, 'GET');
+
+ // The header must advertise an EC algorithm, not rsa-sha256
+ assert(headers.signature.includes('algorithm="ecdsa-p256-sha256"'),
+ `unexpected draft algorithm string: ${headers.signature}`);
+
+ const req = {
+ method: 'GET',
+ url: '/uid/999/inbox',
+ path: '/uid/999/inbox',
+ headers: { ...headers, host: nconf.get('url_parsed').host },
+ };
+
+ const verified = await activitypub.signatures.verify(req, async () => pubPem);
+ assert.strictEqual(verified, true);
+ });
});
});