Skip to content

Node.js based forum software built for the modern web

feat(activitypub): sign activities with rfc 9421, fall back to draft

Julian Lam32494377343b
diff --git a/src/activitypub/sendWorker.js b/src/activitypub/sendWorker.js
index 0589fb1af0..760a66004e 100644
--- a/src/activitypub/sendWorker.js
+++ b/src/activitypub/sendWorker.js
@@ -4,6 +4,7 @@ const { fetch, Agent } = require('undici');
const { check, lookup } = require('../ssrf');
const Signatures = require('./signatures');
const nconf = require('nconf');
+const winston = require('winston');
const { version } = require('../../package.json');
const agent = new Agent({
@@ -16,6 +17,50 @@ const agent = new Agent({
const MAX_BODY_SIZE = 10 * 1024 * 1024; // 10MB response limit
+async function post({ uri, headers, payload, userAgent }) {
+ // POST — redirect: 'manual' prevents SSRF via HTTP redirect
+ // 10s timeout to prevent stuck tasks
+ const timeoutSignal = AbortSignal.timeout(10000);
+
+ const response = await fetch(uri, {
+ method: 'POST',
+ headers: {
+ ...headers,
+ 'content-type': 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
+ 'user-agent': userAgent,
+ },
+ body: payload,
+ signal: timeoutSignal,
+ redirect: 'manual',
+ dispatcher: agent,
+ });
+
+ // Validate Content-Length to prevent memory exhaustion
+ const contentLength = response.headers.get('content-length');
+ if (contentLength && parseInt(contentLength, 10) > MAX_BODY_SIZE) {
+ return { success: false, error: 'Response body exceeds 10MB limit' };
+ }
+
+ if (String(response.status).startsWith('2')) {
+ return { success: true };
+ }
+
+ let bodyText = '';
+ try {
+ bodyText = await response.text();
+ } catch (e) { /* ignore */ }
+
+ return { success: false, error: `HTTP ${response.status}: ${bodyText}` };
+}
+
+async function attemptSend({ uri, headers, payload, userAgent }) {
+ try {
+ return await post({ uri, headers, payload, userAgent });
+ } catch (e) {
+ return { success: false, error: e.message || 'unknown error' };
+ }
+}
+
async function send({ id, uri, payload, digest, key, keyId }) {
const userAgent = `NodeBB/${version.split('.').shift()}.x (${nconf.get('url')})`;
@@ -31,42 +76,22 @@ async function send({ id, uri, payload, digest, key, keyId }) {
return { id, success: false, error: 'SSRF check failed — reserved IP address' };
}
- // Sign
- const headers = await Signatures.sign({ key, keyId }, uri, 'POST', digest);
-
- // POST — redirect: 'manual' prevents SSRF via HTTP redirect
- // 10s timeout to prevent stuck tasks
- const timeoutSignal = AbortSignal.timeout(10000);
-
- const response = await fetch(uri, {
- method: 'POST',
- headers: {
- ...headers,
- 'content-type': 'application/ld+json; profile="https://www.w3.org/ns/activitystreams"',
- 'user-agent': userAgent,
- },
- body: payload,
- signal: timeoutSignal,
- redirect: 'manual',
- dispatcher: agent,
- });
-
- // Validate Content-Length to prevent memory exhaustion
- const contentLength = response.headers.get('content-length');
- if (contentLength && parseInt(contentLength, 10) > MAX_BODY_SIZE) {
- return { id, success: false, error: 'Response body exceeds 10MB limit' };
+ // Sign with RFC 9421
+ const rfcHeaders = await Signatures.signRfc9421({ key, keyId }, uri, 'POST', digest);
+ const rfcResult = await attemptSend({ uri, headers: rfcHeaders, payload, userAgent });
+ if (rfcResult.success) {
+ return { id, success: true };
}
- if (String(response.status).startsWith('2')) {
+ // Fall back to signing with the draft method if the RFC 9421 request failed
+ winston.warn(`[activitypub/sendWorker] RFC 9421 request failed (${rfcResult.error}); retrying with draft signature`);
+ const draftHeaders = await Signatures.sign({ key, keyId }, uri, 'POST', digest);
+ const draftResult = await attemptSend({ uri, headers: draftHeaders, payload, userAgent });
+ if (draftResult.success) {
return { id, success: true };
}
- let bodyText = '';
- try {
- bodyText = await response.text();
- } catch (e) { /* ignore */ }
-
- return { id, success: false, error: `HTTP ${response.status}: ${bodyText}` };
+ return { id, success: false, error: draftResult.error };
} catch (e) {
return { id, success: false, error: e.message || 'unknown error' };
}
diff --git a/src/activitypub/signatures.js b/src/activitypub/signatures.js
index fefe53ab92..665842ad57 100644
--- a/src/activitypub/signatures.js
+++ b/src/activitypub/signatures.js
@@ -12,6 +12,8 @@ const {
parseDraftRequest,
parseRFC9421Request,
verifyRFC9421Signature,
+ RFC9421SignatureBaseFactory,
+ getWebcrypto,
} = require('@misskey-dev/node-http-message-signatures');
const Signatures = module.exports;
@@ -74,6 +76,78 @@ Signatures.sign = async ({ key, keyId }, url, method = 'GET', digest = null) =>
}
};
+Signatures.signRfc9421 = async ({ key, keyId }, url, method = 'GET', digest = null) => {
+ const parsedUrl = new URL(url);
+ const date = new Date().toUTCString();
+ const created = Math.floor(Date.now() / 1000);
+
+ // Headers required for signing
+ const headersToSign = {
+ date,
+ host: parsedUrl.host,
+ };
+
+ if (digest) {
+ headersToSign.digest = digest;
+ }
+
+ // Determine signed components list
+ const components = ['@request-target', 'host', 'date'];
+ if (digest) {
+ components.push('digest');
+ }
+
+ // Build Signature-Input header
+ const signatureInput = `sig1=("${components.join('" "')}");created=${created};keyid="${keyId}"`;
+ headersToSign['signature-input'] = signatureInput;
+
+ try {
+ // Import private key
+ const privateKey = await importPrivateKey(key, ['sign']);
+
+ // Build signature base
+ const base = new RFC9421SignatureBaseFactory({
+ method,
+ url: parsedUrl.href,
+ headers: headersToSign,
+ });
+ const signatureBase = base.generate('sig1');
+
+ // Sign
+ const signatureBuffer = await (await getWebcrypto()).subtle.sign(
+ getSignAlgorithm(privateKey),
+ privateKey,
+ new TextEncoder().encode(signatureBase),
+ );
+
+ const signature = Buffer.from(signatureBuffer).toString('base64');
+
+ return {
+ date,
+ ...(digest && { digest }),
+ 'signature-input': signatureInput,
+ signature: `sig1=("${signature}")`,
+ };
+ } catch (err) {
+ winston.error(`[activitypub/signatures] Sign (RFC 9421) error: ${err.message}`);
+ throw err;
+ }
+};
+
+function getSignAlgorithm(key) {
+ const { name, namedCurve } = key.algorithm;
+ if (name === 'RSASSA-PKCS1-v1_5') {
+ return { name, hash: 'SHA-256' };
+ }
+ if (name === 'ECDSA') {
+ return { name, hash: 'SHA-256', namedCurve };
+ }
+ if (name === 'Ed25519' || name === 'Ed448') {
+ return { name };
+ }
+ throw new Error(`Unsupported key algorithm: ${name}`);
+}
+
function getDraftAlgoString(key) {
const { name } = key.algorithm;
if (name === 'RSA') {
diff --git a/test/activitypub/sendWorker.js b/test/activitypub/sendWorker.js
index fdabd87df9..9a38fcf317 100644
--- a/test/activitypub/sendWorker.js
+++ b/test/activitypub/sendWorker.js
@@ -53,6 +53,137 @@ describe('sendWorker', () => {
});
});
+ describe('RFC 9421 signing with draft fallback', () => {
+ const http = require('http');
+ const { createHash, generateKeyPairSync, webcrypto } = require('crypto');
+ const {
+ RFC9421SignatureBaseFactory,
+ importPublicKey,
+ parseDraftRequest,
+ verifyDraftSignature,
+ } = require('@misskey-dev/node-http-message-signatures');
+
+ let innerPool;
+ let server;
+ let port;
+ let requests;
+ let pubPem;
+ let privPem;
+ const keyId = 'https://nodebb.test/actor#key';
+
+ before(async () => {
+ const kp = generateKeyPairSync('rsa', { modulusLength: 2048, publicExponent: 0x10001 });
+ privPem = kp.privateKey.export({ format: 'pem', type: 'pkcs8' }).toString();
+ pubPem = kp.publicKey.export({ format: 'pem', type: 'spki' }).toString();
+ });
+
+ beforeEach(async () => {
+ requests = [];
+
+ server = http.createServer((req, res) => {
+ const chunks = [];
+ req.on('data', (c) => chunks.push(c));
+ req.on('end', async () => {
+ const raw = Buffer.concat(chunks);
+ const fullUrl = `http://127.0.0.1:${port}${req.url}`;
+ const entry = {
+ hasRfc: !!req.headers['signature-input'],
+ isDraft: typeof req.headers.signature === 'string' && req.headers.signature.includes('keyId="'),
+ digestOk: req.headers.digest === `SHA-256=${createHash('sha256').update(raw).digest('base64')}`,
+ };
+ try {
+ if (entry.hasRfc) {
+ const base = new RFC9421SignatureBaseFactory({ method: req.method, url: fullUrl, headers: req.headers });
+ const sigB64 = req.headers.signature.match(/^sig1=\("(.*)"\)$/)[1];
+ 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'),
+ new TextEncoder().encode(base.generate('sig1')),
+ );
+ } else if (entry.isDraft) {
+ const parsed = parseDraftRequest({ method: req.method, url: fullUrl, headers: req.headers });
+ entry.draftValid = await verifyDraftSignature(parsed.value, pubPem);
+ }
+ } catch (e) {
+ entry.verifyError = e.message;
+ }
+ requests.push(entry);
+ const accepted = (server.mode === 'rfc' && entry.hasRfc && entry.rfcValid === true) ||
+ (server.mode === 'draft' && entry.isDraft && entry.draftValid === true);
+ res.writeHead(accepted ? 202 : 401, { 'content-type': 'application/json' });
+ res.end(JSON.stringify({ accepted }));
+ });
+ });
+ await new Promise((resolve) => {
+ server.listen(0, '127.0.0.1', resolve);
+ });
+ port = server.address().port;
+
+ innerPool = workerpool.pool(path.join(__dirname, '../../src/activitypub/sendWorker.js'), {
+ minWorkers: 1,
+ maxWorkers: 1,
+ workerType: 'process',
+ forkOpts: {
+ silent: true,
+ execArgv: ['--require', require.resolve('./ssrf-allow-localhost')],
+ },
+ });
+ });
+
+ afterEach((done) => {
+ Promise.all([
+ innerPool ? innerPool.terminate(true, 1000) : Promise.resolve(),
+ new Promise((resolve) => server.close(resolve)),
+ ]).then(() => done()).catch(() => done());
+ });
+
+ function task(mode) {
+ const payload = JSON.stringify({ id: 'https://nodebb.test/activities/1', type: 'Create' });
+ return {
+ id: `rfc-fallback-${mode}`,
+ uri: `http://127.0.0.1:${port}/inbox`,
+ payload,
+ digest: `SHA-256=${createHash('sha256').update(payload).digest('base64')}`,
+ key: privPem,
+ keyId,
+ };
+ }
+
+ it('should sign with RFC 9421 and not fall back when the server accepts it', async () => {
+ server.mode = 'rfc';
+ const result = await innerPool.exec('send', [task('rfc')], { timeout: 30000 });
+
+ assert.strictEqual(result.success, true);
+ assert.strictEqual(requests.length, 1);
+ assert(requests[0].hasRfc, 'request should carry a signature-input header');
+ assert.strictEqual(requests[0].rfcValid, true, 'RFC 9421 signature should verify');
+ assert.strictEqual(requests[0].digestOk, true, 'digest should match payload');
+ });
+
+ it('should fall back to a draft signature when the server rejects RFC 9421', async () => {
+ server.mode = 'draft';
+ const result = await innerPool.exec('send', [task('draft')], { timeout: 30000 });
+
+ assert.strictEqual(result.success, true);
+ assert.strictEqual(requests.length, 2);
+ assert(requests[0].hasRfc, 'first attempt should use RFC 9421');
+ assert(requests[1].isDraft, 'fallback attempt should use the draft signature');
+ assert.strictEqual(requests[1].draftValid, true, 'draft signature should verify');
+ assert.strictEqual(requests[1].digestOk, true, 'digest should match payload');
+ });
+
+ it('should fail when the server rejects both signature schemes', async () => {
+ server.mode = 'none';
+ const result = await innerPool.exec('send', [task('none')], { timeout: 30000 });
+
+ assert.strictEqual(result.success, false);
+ assert.strictEqual(requests.length, 2);
+ assert(result.error.includes('401'));
+ });
+ });
+
describe('SSRF protection', () => {
it('should reject localhost URLs', async () => {
const result = await pool.exec('send', [{
diff --git a/test/activitypub/ssrf-allow-localhost.js b/test/activitypub/ssrf-allow-localhost.js
new file mode 100644
index 0000000000..fb74222889
--- /dev/null
+++ b/test/activitypub/ssrf-allow-localhost.js
@@ -0,0 +1,5 @@
+'use strict';
+
+// Preload for sendWorker test workers: allows the worker process to send to
+// localhost (SSRF bypass) so tests can use a local HTTP server.
+require(require('path').join(__dirname, '..', '..', 'src', 'ssrf')).allowList.add('127.0.0.1');