diff --git a/.changeset/notification-response-size-cap.md b/.changeset/notification-response-size-cap.md new file mode 100644 index 000000000..f67d26fab --- /dev/null +++ b/.changeset/notification-response-size-cap.md @@ -0,0 +1,9 @@ +--- +'nostream': patch +--- + +fix(notifications): never buffer the response a notification delivery gets back + +A delivery is a POST whose only interesting part is the status code, but axios advertised every encoding it can decode, decompressed whatever a receiver sent back and buffered the whole result while nothing read it. A receiver answering with a small gzip body that decodes to hundreds of megabytes therefore spent the delivery worker's heap for a value nobody consumed (security issue #1257). + +Deliveries now ask for `accept-encoding: identity`, take the response as a stream so no body is buffered or parsed at all, and drain at most 8 KiB of it before dropping the socket. Success is the status and only the status: no response size can turn a notification the receiver accepted into a `FAILED` row the outbox then retries. The request side stays unbounded on purpose, because a `settings.changed` envelope carries the changed values and a blacklist edit alone can produce a body past any small cap. diff --git a/src/services/notification-channels.ts b/src/services/notification-channels.ts index 7f49ec8f5..2201c613e 100644 --- a/src/services/notification-channels.ts +++ b/src/services/notification-channels.ts @@ -9,6 +9,101 @@ import { const REQUEST_TIMEOUT_MS = 15_000 +// A delivery is a POST whose only interesting part is the status code. Axios would +// otherwise advertise every encoding it can decode, gunzip whatever a receiver sends +// back and buffer the whole result, so a small compressed body that decodes to +// hundreds of megabytes would be charged to this worker's heap for a value nobody +// consumes. The response is therefore taken as a stream and discarded here, and +// `accept-encoding: identity` stops a receiver from compressing it in the first place. +// +// Discarding is bounded rather than deferred: a receiver only owes us a status, and +// making the delivery fail because its body is large would record a notification it +// accepted as failed, which the outbox then retries — a duplicate. +const RESPONSE_DRAIN_LIMIT_BYTES = 8 * 1024 + +// A streamed response settles at its headers, so axios's own timeout is spent by the +// time the drain starts: a receiver that answers and then stalls would hold this +// promise open forever. The drain gets a deadline of its own. +const RESPONSE_DRAIN_TIMEOUT_MS = 2_000 + +// The request side is deliberately left unbounded: a `settings.changed` envelope +// carries the changed values, so editing a blacklist alone can produce a body far +// past any small cap, and capping it would drop deliveries that work today. + +const deliveryRequestOptions = (headers: Record = {}) => ({ + timeout: REQUEST_TIMEOUT_MS, + headers: { ...headers, 'accept-encoding': 'identity' }, + // Success is the status and only the status. `stream` settles as soon as the + // headers arrive, so no body is ever buffered or parsed — which also means a + // receiver answering with HTML, gzip or a large echo cannot fail a delivery it + // already accepted. + responseType: 'stream' as const, + decompress: false, + validateStatus: (status: number) => status >= 200 && status < 300, +}) + +const discardResponseBody = async (data: unknown): Promise => { + const body = data as + | (NodeJS.ReadableStream & { + destroy?: () => void + off?: (event: string, listener: (...args: never[]) => void) => void + }) + | undefined + + if (!body || typeof body.on !== 'function') { + return + } + + await new Promise((resolve) => { + let drained = 0 + let finished = false + let deadline: NodeJS.Timeout | undefined + + const onData = (chunk: { length: number }) => { + drained += chunk.length + if (drained >= RESPONSE_DRAIN_LIMIT_BYTES) { + finish() + } + } + + // Only this function's listeners are removed: the rest of the stream's + // bookkeeping belongs to Node and axios. + const finish = () => { + if (finished) { + return + } + finished = true + clearTimeout(deadline) + body.off?.('data', onData as (...args: never[]) => void) + body.off?.('end', finish) + body.off?.('error', finish) + body.on?.('error', () => { + // the socket is being dropped on purpose + }) + body.destroy?.() + resolve() + } + + deadline = setTimeout(finish, RESPONSE_DRAIN_TIMEOUT_MS) + body.on('data', onData) + body.on('end', finish) + body.on('error', finish) + }) +} + +const postDelivery = async (url: string, body: unknown, headers?: Record): Promise => { + try { + const response = await axios.post(url, body, deliveryRequestOptions(headers)) + await discardResponseBody(response?.data) + } catch (error) { + // A rejected status settles with its body still attached and unread, so without + // this the socket stays open for every failed attempt — and every retry of it. + const rejected = (error as { response?: { data?: unknown } } | undefined)?.response + await discardResponseBody(rejected?.data) + throw error + } +} + export const deliverToTarget = async ( target: OperatorNotificationTarget, envelope: OperatorNotificationEnvelope, @@ -39,11 +134,7 @@ const deliverHttp = async (target: OperatorNotificationTarget, envelope: Operato headers['x-nostream-signature'] = `sha256=${digest}` } - await axios.post(target.url, body, { - timeout: REQUEST_TIMEOUT_MS, - headers, - validateStatus: (status) => status >= 200 && status < 300, - }) + await postDelivery(target.url, body, headers) } const deliverDiscord = async ( @@ -56,14 +147,7 @@ const deliverDiscord = async ( const content = `[${envelope.event}] ${envelope.relay}\n\`\`\`json\n${JSON.stringify(envelope.data, null, 2).slice(0, 1800)}\n\`\`\`` - await axios.post( - target.url, - { content }, - { - timeout: REQUEST_TIMEOUT_MS, - validateStatus: (status) => status >= 200 && status < 300, - }, - ) + await postDelivery(target.url, { content }) } const deliverSlack = async (target: OperatorNotificationTarget, envelope: OperatorNotificationEnvelope): Promise => { @@ -71,25 +155,18 @@ const deliverSlack = async (target: OperatorNotificationTarget, envelope: Operat throw new Error('Slack notification target requires webhook url') } - await axios.post( - target.url, - { - text: `[${envelope.event}] ${envelope.relay}`, - blocks: [ - { - type: 'section', - text: { - type: 'mrkdwn', - text: `*${envelope.event}* on \`${envelope.relay}\`\n\`\`\`${JSON.stringify(envelope.data).slice(0, 2800)}\`\`\``, - }, + await postDelivery(target.url, { + text: `[${envelope.event}] ${envelope.relay}`, + blocks: [ + { + type: 'section', + text: { + type: 'mrkdwn', + text: `*${envelope.event}* on \`${envelope.relay}\`\n\`\`\`${JSON.stringify(envelope.data).slice(0, 2800)}\`\`\``, }, - ], - }, - { - timeout: REQUEST_TIMEOUT_MS, - validateStatus: (status) => status >= 200 && status < 300, - }, - ) + }, + ], + }) } const deliverTelegram = async ( @@ -103,18 +180,11 @@ const deliverTelegram = async ( const text = `[${envelope.event}] ${envelope.relay}\n${JSON.stringify(envelope.data).slice(0, 3500)}` const url = `https://api.telegram.org/bot${target.botToken}/sendMessage` - await axios.post( - url, - { - chat_id: target.chatId, - text, - disable_web_page_preview: true, - }, - { - timeout: REQUEST_TIMEOUT_MS, - validateStatus: (status) => status >= 200 && status < 300, - }, - ) + await postDelivery(url, { + chat_id: target.chatId, + text, + disable_web_page_preview: true, + }) } export const validateTargetConfig = (target: OperatorNotificationTarget): string | undefined => { diff --git a/test/unit/services/notification-channels.spec.ts b/test/unit/services/notification-channels.spec.ts index de25af2e0..a81315627 100644 --- a/test/unit/services/notification-channels.spec.ts +++ b/test/unit/services/notification-channels.spec.ts @@ -1,6 +1,9 @@ import chai from 'chai' +import http from 'http' +import { AddressInfo } from 'net' import Sinon from 'sinon' import sinonChai from 'sinon-chai' +import zlib from 'zlib' // eslint-disable-next-line @typescript-eslint/no-var-requires const axios = require('axios') @@ -99,3 +102,188 @@ describe('notification-channels', () => { expect(validateTargetConfig({ id: 'x', type: 'telegram', enabled: true, botToken: 't' })).to.match(/chatId/) }) }) + +describe('notification-channels response handling', () => { + // What a receiver answers is kept well away from what a delivery means: the body + // is never buffered, so these bodies are sized against what an early copy of this + // change would have capped rather than against anything the code now reads. + const LARGE_BODY_BYTES = 256 * 1024 + + let server: http.Server + let url: string + let requests: http.IncomingMessage[] + let respond: (request: http.IncomingMessage, response: http.ServerResponse) => void + + const target = () => ({ id: 'http-1', type: 'http', enabled: true, url }) + + beforeEach(async () => { + requests = [] + respond = (_request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }) + response.end('{"ok":true}') + } + + server = http.createServer((request, response) => { + requests.push(request) + response.on('error', () => { + // an oversized response is dropped from this side once it has been drained + }) + respond(request, response) + }) + server.on('clientError', () => { + // dropping the socket is how a drained response ends + }) + + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)) + url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/hook` + }) + + afterEach(async () => { + server.closeAllConnections() + await new Promise((resolve) => server.close(() => resolve())) + }) + + it('reports a normal 2xx response as sent and asks the receiver for no compressed response', async () => { + await deliverToTarget(target() as any, envelope) + + expect(requests).to.have.lengthOf(1) + expect(requests[0].headers['accept-encoding']).to.equal('identity') + }) + + it('sends a request body larger than any response it would read in full', async () => { + // A settings change carries the changed values, so a blacklist edit alone can + // produce a body well past this size. Capping the request would drop those + // deliveries, which is why the request side stays unbounded. + const body = { ...envelope, data: { blacklist: Array.from({ length: 2_000 }, () => 'a'.repeat(64)) } } + let received = 0 + respond = (request, response) => { + request.on('data', (chunk: Buffer) => { + received += chunk.length + }) + request.on('end', () => { + response.writeHead(200, { 'content-type': 'application/json' }) + response.end('{"ok":true}') + }) + } + + await deliverToTarget(target() as any, body) + + expect(JSON.stringify(body).length).to.be.above(64 * 1024) + expect(received).to.equal(JSON.stringify(body).length) + }) + + it('reports a 2xx as sent when the response body is larger than it will read', async () => { + respond = (_request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }) + const chunk = Buffer.alloc(8 * 1024, 0x61) + let written = 0 + const write = () => { + while (written < LARGE_BODY_BYTES) { + if (!response.write(chunk)) { + response.once('drain', write) + return + } + written += chunk.length + } + response.end() + } + write() + } + + await deliverToTarget(target() as any, envelope) + + expect(requests).to.have.lengthOf(1) + }) + + it('stops reading the body once it has drained enough, rather than waiting for the end', async () => { + let serverFinished = false + respond = (_request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }) + response.write(Buffer.alloc(8 * 1024, 0x61)) + setTimeout(() => { + serverFinished = true + try { + response.end('tail') + } catch { + // the client has already dropped this socket + } + }, 200) + } + + await deliverToTarget(target() as any, envelope) + + expect(serverFinished).to.equal(false) + }) + + // The drain deadline is two seconds, so this test is slower than mocha's default. + it('does not wait forever on a receiver that answers and then stalls', async function () { + this.timeout(6_000) + + // A streamed response settles at its headers, so the request timeout is already + // spent when the drain starts: the drain carries its own deadline. + respond = (_request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }) + response.write('{"ok"') + } + + const startedAt = Date.now() + await deliverToTarget(target() as any, envelope) + const elapsed = Date.now() - startedAt + + expect(elapsed).to.be.below(4_000) + expect(requests).to.have.lengthOf(1) + }) + + it('closes the response stream of a failed delivery instead of leaving its socket open', async () => { + let bodyFinished = false + let closedBeforeTheBodyEnded = false + respond = (_request, response) => { + response.writeHead(500, { 'content-type': 'text/plain' }) + response.on('close', () => { + if (!bodyFinished) { + closedBeforeTheBodyEnded = true + } + }) + response.write(Buffer.alloc(8 * 1024, 0x61)) + setTimeout(() => { + bodyFinished = true + try { + response.end('tail') + } catch { + // the client has already dropped this socket + } + }, 400) + } + + let error: Error | undefined + try { + await deliverToTarget(target() as any, envelope) + } catch (caught) { + error = caught as Error + } + + expect(error).to.be.instanceOf(Error) + await new Promise((resolve) => setTimeout(resolve, 150)) + expect(closedBeforeTheBodyEnded).to.equal(true) + }) + + it('does not decompress a compressed response', async () => { + const decoded = Buffer.alloc(4 * 64 * 1024, 0x62) + const encoded = zlib.gzipSync(decoded) + + respond = (_request, response) => { + response.writeHead(200, { 'content-encoding': 'gzip', 'content-type': 'application/json' }) + response.end(encoded) + } + + const unzip = Sinon.spy(zlib, 'createUnzip') + try { + await deliverToTarget(target() as any, envelope) + } finally { + unzip.restore() + } + + expect(requests).to.have.lengthOf(1) + expect(unzip).to.not.have.been.called + }) +})