Skip to content

Commit df8b432

Browse files
chappie-daemonchappie-daemon
authored andcommitted
fix(notifications): drain the response instead of capping it
A 2xx with a body past the cap rejected the delivery promise, so the dispatcher recorded a notification the receiver had accepted as FAILED and the outbox retried it. The response is now taken as a stream and drained for at most 8 KiB before the socket is dropped, which keeps the heap flat without ever letting a response decide whether a delivery succeeded.
1 parent 49169cb commit df8b432

3 files changed

Lines changed: 110 additions & 68 deletions

File tree

‎.changeset/notification-response-size-cap.md‎

Lines changed: 3 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,8 @@
22
'nostream': patch
33
---
44

5-
fix(notifications): cap the response a notification delivery will read
5+
fix(notifications): never buffer the response a notification delivery gets back
66

7-
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).
7+
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).
88

9-
Delivery requests now carry `accept-encoding: identity`, `decompress: false`, an empty transform list so the body is never parsed, and a 64 KiB `maxContentLength` that aborts a response as soon as it runs past it. The request side stays unbounded on purpose: a `settings.changed` envelope carries the changed values, so a blacklist edit alone can produce a body past any small cap, and capping it would drop deliveries that work today.
10-
11-
The empty transform list also closes a second bug: a receiver that compressed unsolicited used to fail the delivery at `JSON.parse` even though it had answered 2xx.
9+
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.

‎src/services/notification-channels.ts‎

Lines changed: 70 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -9,15 +9,17 @@ import {
99

1010
const REQUEST_TIMEOUT_MS = 15_000
1111

12-
// A delivery is a POST whose only interesting part is the status code: nothing
13-
// reads the response body. Axios would otherwise advertise every encoding it can
14-
// decode, gunzip whatever a receiver sends back, and buffer the result, so a small
15-
// compressed body that decodes to hundreds of megabytes would be charged to this
16-
// worker's heap for a value nobody consumes. Three settings close that: the adapter
17-
// aborts once the bytes received reach `maxContentLength`, `decompress: false`
18-
// stops a receiver's `content-encoding` from being acted on, and an explicit
19-
// `accept-encoding: identity` stops axios from inviting one in the first place.
20-
export const MAX_RESPONSE_BYTES = 64 * 1024
12+
// A delivery is a POST whose only interesting part is the status code. Axios would
13+
// otherwise advertise every encoding it can decode, gunzip whatever a receiver sends
14+
// back and buffer the whole result, so a small compressed body that decodes to
15+
// hundreds of megabytes would be charged to this worker's heap for a value nobody
16+
// consumes. The response is therefore taken as a stream and discarded here, and
17+
// `accept-encoding: identity` stops a receiver from compressing it in the first place.
18+
//
19+
// Discarding is bounded rather than deferred: a receiver only owes us a status, and
20+
// making the delivery fail because its body is large would record a notification it
21+
// accepted as failed, which the outbox then retries — a duplicate.
22+
const RESPONSE_DRAIN_LIMIT_BYTES = 8 * 1024
2123

2224
// The request side is deliberately left unbounded: a `settings.changed` envelope
2325
// carries the changed values, so editing a blacklist alone can produce a body far
@@ -26,16 +28,51 @@ export const MAX_RESPONSE_BYTES = 64 * 1024
2628
const deliveryRequestOptions = (headers: Record<string, string> = {}) => ({
2729
timeout: REQUEST_TIMEOUT_MS,
2830
headers: { ...headers, 'accept-encoding': 'identity' },
29-
maxContentLength: MAX_RESPONSE_BYTES,
31+
// Success is the status and only the status. `stream` settles as soon as the
32+
// headers arrive, so no body is ever buffered or parsed — which also means a
33+
// receiver answering with HTML, gzip or a large echo cannot fail a delivery it
34+
// already accepted.
35+
responseType: 'stream' as const,
3036
decompress: false,
31-
// `responseType` defaults to json, and axios would parse the body before
32-
// returning. An explicit empty transform list keeps the bytes raw, so a
33-
// receiver that answers with HTML or gzip cannot fail a delivery that already
34-
// succeeded by status.
35-
transformResponse: [],
3637
validateStatus: (status: number) => status >= 200 && status < 300,
3738
})
3839

40+
const discardResponseBody = async (data: unknown): Promise<void> => {
41+
const body = data as
42+
| (NodeJS.ReadableStream & { destroy?: () => void; removeAllListeners?: () => void })
43+
| undefined
44+
45+
if (!body || typeof body.on !== 'function') {
46+
return
47+
}
48+
49+
await new Promise<void>((resolve) => {
50+
let drained = 0
51+
const finish = () => {
52+
body.removeAllListeners?.()
53+
body.on?.('error', () => {
54+
// the socket is being dropped on purpose
55+
})
56+
body.destroy?.()
57+
resolve()
58+
}
59+
60+
body.on('data', (chunk: { length: number }) => {
61+
drained += chunk.length
62+
if (drained >= RESPONSE_DRAIN_LIMIT_BYTES) {
63+
finish()
64+
}
65+
})
66+
body.on('end', finish)
67+
body.on('error', finish)
68+
})
69+
}
70+
71+
const postDelivery = async (url: string, body: unknown, headers?: Record<string, string>): Promise<void> => {
72+
const response = await axios.post(url, body, deliveryRequestOptions(headers))
73+
await discardResponseBody(response?.data)
74+
}
75+
3976
export const deliverToTarget = async (
4077
target: OperatorNotificationTarget,
4178
envelope: OperatorNotificationEnvelope,
@@ -66,7 +103,7 @@ const deliverHttp = async (target: OperatorNotificationTarget, envelope: Operato
66103
headers['x-nostream-signature'] = `sha256=${digest}`
67104
}
68105

69-
await axios.post(target.url, body, deliveryRequestOptions(headers))
106+
await postDelivery(target.url, body, headers)
70107
}
71108

72109
const deliverDiscord = async (
@@ -79,34 +116,26 @@ const deliverDiscord = async (
79116

80117
const content = `[${envelope.event}] ${envelope.relay}\n\`\`\`json\n${JSON.stringify(envelope.data, null, 2).slice(0, 1800)}\n\`\`\``
81118

82-
await axios.post(
83-
target.url,
84-
{ content },
85-
deliveryRequestOptions(),
86-
)
119+
await postDelivery(target.url, { content })
87120
}
88121

89122
const deliverSlack = async (target: OperatorNotificationTarget, envelope: OperatorNotificationEnvelope): Promise<void> => {
90123
if (!target.url) {
91124
throw new Error('Slack notification target requires webhook url')
92125
}
93126

94-
await axios.post(
95-
target.url,
96-
{
97-
text: `[${envelope.event}] ${envelope.relay}`,
98-
blocks: [
99-
{
100-
type: 'section',
101-
text: {
102-
type: 'mrkdwn',
103-
text: `*${envelope.event}* on \`${envelope.relay}\`\n\`\`\`${JSON.stringify(envelope.data).slice(0, 2800)}\`\`\``,
104-
},
127+
await postDelivery(target.url, {
128+
text: `[${envelope.event}] ${envelope.relay}`,
129+
blocks: [
130+
{
131+
type: 'section',
132+
text: {
133+
type: 'mrkdwn',
134+
text: `*${envelope.event}* on \`${envelope.relay}\`\n\`\`\`${JSON.stringify(envelope.data).slice(0, 2800)}\`\`\``,
105135
},
106-
],
107-
},
108-
deliveryRequestOptions(),
109-
)
136+
},
137+
],
138+
})
110139
}
111140

112141
const deliverTelegram = async (
@@ -120,15 +149,11 @@ const deliverTelegram = async (
120149
const text = `[${envelope.event}] ${envelope.relay}\n${JSON.stringify(envelope.data).slice(0, 3500)}`
121150
const url = `https://api.telegram.org/bot${target.botToken}/sendMessage`
122151

123-
await axios.post(
124-
url,
125-
{
126-
chat_id: target.chatId,
127-
text,
128-
disable_web_page_preview: true,
129-
},
130-
deliveryRequestOptions(),
131-
)
152+
await postDelivery(url, {
153+
chat_id: target.chatId,
154+
text,
155+
disable_web_page_preview: true,
156+
})
132157
}
133158

134159
export const validateTargetConfig = (target: OperatorNotificationTarget): string | undefined => {

‎test/unit/services/notification-channels.spec.ts‎

Lines changed: 37 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@ const axios = require('axios')
1010
// eslint-disable-next-line @typescript-eslint/no-var-requires
1111
const { OperatorNotificationEventType } = require('../../../src/@types/operator-notifications')
1212
// eslint-disable-next-line @typescript-eslint/no-var-requires
13-
const { MAX_RESPONSE_BYTES, deliverToTarget, validateTargetConfig } = require('../../../src/services/notification-channels')
13+
const { deliverToTarget, validateTargetConfig } = require('../../../src/services/notification-channels')
1414

1515
chai.use(sinonChai)
1616

@@ -104,6 +104,11 @@ describe('notification-channels', () => {
104104
})
105105

106106
describe('notification-channels response handling', () => {
107+
// What a receiver answers is kept well away from what a delivery means: the body
108+
// is never buffered, so these bodies are sized against what an early copy of this
109+
// change would have capped rather than against anything the code now reads.
110+
const LARGE_BODY_BYTES = 256 * 1024
111+
107112
let server: http.Server
108113
let url: string
109114
let requests: http.IncomingMessage[]
@@ -121,12 +126,12 @@ describe('notification-channels response handling', () => {
121126
server = http.createServer((request, response) => {
122127
requests.push(request)
123128
response.on('error', () => {
124-
// the delivery aborts the request when a body runs past the cap
129+
// an oversized response is dropped from this side once it has been drained
125130
})
126131
respond(request, response)
127132
})
128133
server.on('clientError', () => {
129-
// a destroyed socket is the expected ending for the oversized cases
134+
// dropping the socket is how a drained response ends
130135
})
131136

132137
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
@@ -145,10 +150,10 @@ describe('notification-channels response handling', () => {
145150
expect(requests[0].headers['accept-encoding']).to.equal('identity')
146151
})
147152

148-
it('sends a request body larger than the response cap in full', async () => {
153+
it('sends a request body larger than any response it would read in full', async () => {
149154
// A settings change carries the changed values, so a blacklist edit alone can
150-
// produce a body well past 64 KiB. Capping the request would drop those
151-
// deliveries silently, which is why only the response side is bounded.
155+
// produce a body well past this size. Capping the request would drop those
156+
// deliveries, which is why the request side stays unbounded.
152157
const body = { ...envelope, data: { blacklist: Array.from({ length: 2_000 }, () => 'a'.repeat(64)) } }
153158
let received = 0
154159
respond = (request, response) => {
@@ -163,17 +168,17 @@ describe('notification-channels response handling', () => {
163168

164169
await deliverToTarget(target() as any, body)
165170

166-
expect(JSON.stringify(body).length).to.be.above(MAX_RESPONSE_BYTES)
171+
expect(JSON.stringify(body).length).to.be.above(64 * 1024)
167172
expect(received).to.equal(JSON.stringify(body).length)
168173
})
169174

170-
it('aborts a response that runs past the cap instead of buffering it', async () => {
175+
it('reports a 2xx as sent when the response body is larger than it will read', async () => {
171176
respond = (_request, response) => {
172177
response.writeHead(200, { 'content-type': 'application/json' })
173178
const chunk = Buffer.alloc(8 * 1024, 0x61)
174179
let written = 0
175180
const write = () => {
176-
while (written < 4 * MAX_RESPONSE_BYTES) {
181+
while (written < LARGE_BODY_BYTES) {
177182
if (!response.write(chunk)) {
178183
response.once('drain', write)
179184
return
@@ -185,20 +190,34 @@ describe('notification-channels response handling', () => {
185190
write()
186191
}
187192

188-
let error: Error | undefined
189-
try {
190-
await deliverToTarget(target() as any, envelope)
191-
} catch (caught) {
192-
error = caught as Error
193+
await deliverToTarget(target() as any, envelope)
194+
195+
expect(requests).to.have.lengthOf(1)
196+
})
197+
198+
it('stops reading the body once it has drained enough, rather than waiting for the end', async () => {
199+
let serverFinished = false
200+
respond = (_request, response) => {
201+
response.writeHead(200, { 'content-type': 'application/json' })
202+
response.write(Buffer.alloc(8 * 1024, 0x61))
203+
setTimeout(() => {
204+
serverFinished = true
205+
try {
206+
response.end('tail')
207+
} catch {
208+
// the client has already dropped this socket
209+
}
210+
}, 200)
193211
}
194212

195-
expect(error?.message).to.match(new RegExp(`maxContentLength size of ${MAX_RESPONSE_BYTES} exceeded`))
213+
await deliverToTarget(target() as any, envelope)
214+
215+
expect(serverFinished).to.equal(false)
196216
})
197217

198-
it('does not decompress a response, so a small compressed body cannot inflate into the cap', async () => {
199-
const decoded = Buffer.alloc(4 * MAX_RESPONSE_BYTES, 0x62)
218+
it('does not decompress a compressed response', async () => {
219+
const decoded = Buffer.alloc(4 * 64 * 1024, 0x62)
200220
const encoded = zlib.gzipSync(decoded)
201-
expect(encoded.length).to.be.below(MAX_RESPONSE_BYTES)
202221

203222
respond = (_request, response) => {
204223
response.writeHead(200, { 'content-encoding': 'gzip', 'content-type': 'application/json' })

0 commit comments

Comments
 (0)