Skip to content

Node.js based forum software built for the modern web

fix(activitypub): emit rfc 9421 signatures as rfc 8941 byte sequences

Julian Lambb199f4511ee
diff --git a/src/activitypub/signatures.js b/src/activitypub/signatures.js
index f224fac60b..2ad68287d7 100644
--- a/src/activitypub/signatures.js
+++ b/src/activitypub/signatures.js
@@ -94,7 +94,9 @@ Signatures.signRfc9421 = async ({ key, keyId }, url, method = 'GET', digest = nu
}
// Determine signed components list
- const components = ['@request-target', 'host', 'date'];
+ // @method + @target-uri (not @request-target) so that verifiers requiring
+ // those components explicitly (e.g. Mitra) can validate the signature
+ const components = ['@method', '@target-uri', 'host', 'date'];
if (digest) {
components.push('digest');
}
@@ -128,8 +130,9 @@ Signatures.signRfc9421 = async ({ key, keyId }, url, method = 'GET', digest = nu
date,
...(digest && { digest }),
'signature-input': signatureInput,
- // RFC 9421 2.3: the Signature value is an unquoted base64 byte sequence
- signature: `sig1=${signature}`,
+ // RFC 9421 2.3: the Signature value is a structured-field byte
+ // sequence (":base64:" per RFC 8941/9651)
+ signature: `sig1=:${signature}:`,
};
} catch (err) {
winston.error(`[activitypub/signatures] Sign (RFC 9421) error: ${err.message}`);
@@ -396,7 +399,10 @@ function parseSignatureHeader(headerValue) {
}
const label = member.slice(0, eq).trim();
let value = member.slice(eq + 1).trim();
- if (value.startsWith('"')) {
+ // RFC 8941/9651 byte sequence (colon-delimited base64) — the format RFC 9421 senders use
+ if (value.startsWith(':') && value.endsWith(':') && value.length > 2) {
+ value = value.slice(1, -1);
+ } else if (value.startsWith('"')) {
const end = value.indexOf('"', 1);
if (end === -1) {
continue;
diff --git a/test/activitypub/sendWorker.js b/test/activitypub/sendWorker.js
index 861862f20a..66ebb8a0a1 100644
--- a/test/activitypub/sendWorker.js
+++ b/test/activitypub/sendWorker.js
@@ -56,6 +56,7 @@ describe('sendWorker', () => {
describe('RFC 9421 signing with draft fallback', () => {
const http = require('http');
const { createHash, generateKeyPairSync, webcrypto } = require('crypto');
+ const sfv = require('structured-headers');
const {
RFC9421SignatureBaseFactory,
importPublicKey,
@@ -94,16 +95,18 @@ describe('sendWorker', () => {
try {
if (entry.hasRfc) {
const base = new RFC9421SignatureBaseFactory({ method: req.method, url: fullUrl, headers: req.headers });
- // 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);
+ // Parse the Signature header as a strict RFC 8941/9651 dictionary
+ // (like Mitra's sfv parser) — the value must be a byte sequence
+ const sigDict = sfv.parseDictionary(String(req.headers.signature));
+ const sigItem = sigDict.get('sig1');
+ if (!sigItem || !sfv.isByteSequence(sigItem[0])) {
+ throw new Error('Signature value is not a byte sequence');
}
const pub = await importPublicKey(pubPem, ['verify']);
entry.rfcValid = await webcrypto.subtle.verify(
{ name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
pub,
- Buffer.from(sigB64, 'base64'),
+ Buffer.from(sigItem[0].base64Value, 'base64'),
new TextEncoder().encode(base.generate('sig1')),
);
} else if (entry.isDraft) {
diff --git a/test/activitypub/signatures.js b/test/activitypub/signatures.js
index d8c27ac645..9749618e6c 100644
--- a/test/activitypub/signatures.js
+++ b/test/activitypub/signatures.js
@@ -3,6 +3,7 @@
const assert = require('assert');
const nconf = require('nconf');
const { createHash } = require('crypto');
+const { importPublicKey, getWebcrypto } = require('@misskey-dev/node-http-message-signatures');
const db = require('../mocks/databasemock');
const user = require('../../src/user');
@@ -220,6 +221,69 @@ describe('http signature signing and verification', () => {
});
});
+ describe('.signRfc9421()', () => {
+ let uid;
+ const username = utils.generateUUID().slice(0, 10);
+
+ before(async () => {
+ uid = await user.create({ username });
+ });
+
+ it('should produce a structured-field byte sequence Signature header', async () => {
+ const endpoint = `${nconf.get('url')}/user/${username}/inbox`;
+ const keyData = await activitypub.getPrivateKey('uid', uid);
+ const { signature } = await activitypub.signatures.signRfc9421(keyData, endpoint, 'GET');
+ // RFC 8941/9651 byte sequence: ":" + base64 + ":"
+ assert.match(signature, /^sig1=:[0-9A-Za-z+/]+={0,2}:$/);
+ });
+
+ it('should cover the @method and @target-uri components', async () => {
+ const endpoint = `${nconf.get('url')}/user/${username}/inbox`;
+ const keyData = await activitypub.getPrivateKey('uid', uid);
+ const { 'signature-input': signatureInput } =
+ await activitypub.signatures.signRfc9421(keyData, endpoint, 'GET');
+ const componentIds = [...signatureInput.matchAll(/"([^"]*)"/g)].map((m) => m[1]);
+ assert(componentIds.includes('@method'));
+ assert(componentIds.includes('@target-uri'));
+ });
+
+ it('should produce a signature that verifies against an independent signature base reconstruction', async () => {
+ // Reconstructs the signature base by hand per RFC 9421 2.5 (matching
+ // independent implementations such as Mitra) instead of trusting the
+ // base factory on both sides
+ const endpoint = `${nconf.get('url')}/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 paramsMatch = signatureInput.match(/^sig1=(\([^)]*\));created=(\d+);keyid="([^"]*)"$/);
+ assert(paramsMatch, `unexpected Signature-Input format: ${signatureInput}`);
+ const [, componentsInnerList, created, keyId] = paramsMatch;
+ const componentIds = [...componentsInnerList.matchAll(/"([^"]*)"/g)].map((m) => m[1]);
+ const componentValues = {
+ '@method': 'GET',
+ '@target-uri': endpoint,
+ host,
+ date,
+ };
+ const lines = componentIds.map((id) => `"${id}": ${componentValues[id]}`);
+ lines.push(`"@signature-params": ${componentsInnerList};created=${created};keyid="${keyId}"`);
+ const expectedBase = lines.join('\n');
+
+ const publicKeyPem = await activitypub.getPublicKey('uid', uid);
+ const publicKey = await importPublicKey(publicKeyPem, ['verify']);
+ const webcrypto = await getWebcrypto();
+ const verified = await webcrypto.subtle.verify(
+ { name: 'RSASSA-PKCS1-v1_5', hash: 'SHA-256' },
+ publicKey,
+ Buffer.from(signature.slice('sig1=:'.length, -1), 'base64'),
+ new TextEncoder().encode(expectedBase),
+ );
+ assert.strictEqual(verified, true);
+ });
+ });
+
describe('.getKeyId()', () => {
it('should extract the keyId from a draft signature header', () => {
const headers = {