Skip to content
9 changes: 9 additions & 0 deletions .changeset/notification-response-size-cap.md
Original file line number Diff line number Diff line change
@@ -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.
156 changes: 113 additions & 43 deletions src/services/notification-channels.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string> = {}) => ({
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<void> => {
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<void>((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<string, string>): Promise<void> => {
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,
Expand Down Expand Up @@ -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 (
Expand All @@ -56,40 +147,26 @@ 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<void> => {
if (!target.url) {
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 (
Expand All @@ -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 => {
Expand Down
Loading
Loading