@contember/engine-http 2.2.0-alpha.18 → 2.2.0-alpha.19
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/development/index.cjs +0 -1
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +1 -2
- package/dist/development/src/application/application.cjs +8 -9
- package/dist/development/src/application/application.cjs.map +1 -1
- package/dist/development/src/application/application.js +8 -9
- package/dist/development/src/application/application.js.map +1 -1
- package/dist/development/src/application/compression.cjs +99 -0
- package/dist/development/src/application/compression.cjs.map +1 -0
- package/dist/development/src/application/compression.js +82 -0
- package/dist/development/src/application/compression.js.map +1 -0
- package/dist/development/src/application/cors.cjs +52 -0
- package/dist/development/src/application/cors.cjs.map +1 -0
- package/dist/development/src/application/cors.js +52 -0
- package/dist/development/src/application/cors.js.map +1 -0
- package/dist/development/src/application/requestBody.cjs +242 -0
- package/dist/development/src/application/requestBody.cjs.map +1 -0
- package/dist/development/src/application/requestBody.js +242 -0
- package/dist/development/src/application/requestBody.js.map +1 -0
- package/dist/development/src/config/configSchema.cjs +8 -1
- package/dist/development/src/config/configSchema.cjs.map +1 -1
- package/dist/development/src/config/configSchema.js +8 -1
- package/dist/development/src/config/configSchema.js.map +1 -1
- package/dist/development/src/graphql/execution.cjs +3 -9
- package/dist/development/src/graphql/execution.cjs.map +1 -1
- package/dist/development/src/graphql/execution.js +3 -9
- package/dist/development/src/graphql/execution.js.map +1 -1
- package/dist/development/src/project/ProjectContainer.cjs +1 -1
- package/dist/development/src/project/ProjectContainer.js +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.cjs +1 -1
- package/dist/development/src/projectGroup/ProjectGroupContainer.js +1 -1
- package/dist/development/src/providers.cjs +2 -2
- package/dist/development/src/providers.cjs.map +1 -1
- package/dist/development/src/providers.js +2 -2
- package/dist/development/src/providers.js.map +1 -1
- package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs +2 -2
- package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
- package/dist/development/src/transfer/ImportExecutor.cjs +18 -3
- package/dist/development/src/transfer/ImportExecutor.cjs.map +1 -1
- package/dist/development/src/transfer/ImportExecutor.js +18 -3
- package/dist/development/src/transfer/ImportExecutor.js.map +1 -1
- package/dist/development/src/utils/sentry.cjs +31 -49
- package/dist/development/src/utils/sentry.cjs.map +1 -1
- package/dist/development/src/utils/sentry.js +32 -33
- package/dist/development/src/utils/sentry.js.map +1 -1
- package/dist/development/src/utils/serverStartup.cjs +5 -3
- package/dist/development/src/utils/serverStartup.cjs.map +1 -1
- package/dist/development/src/utils/serverStartup.js +5 -3
- package/dist/development/src/utils/serverStartup.js.map +1 -1
- package/dist/production/index.cjs +0 -1
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +1 -2
- package/dist/production/src/application/application.cjs +8 -9
- package/dist/production/src/application/application.cjs.map +1 -1
- package/dist/production/src/application/application.js +8 -9
- package/dist/production/src/application/application.js.map +1 -1
- package/dist/production/src/application/compression.cjs +99 -0
- package/dist/production/src/application/compression.cjs.map +1 -0
- package/dist/production/src/application/compression.js +82 -0
- package/dist/production/src/application/compression.js.map +1 -0
- package/dist/production/src/application/cors.cjs +52 -0
- package/dist/production/src/application/cors.cjs.map +1 -0
- package/dist/production/src/application/cors.js +52 -0
- package/dist/production/src/application/cors.js.map +1 -0
- package/dist/production/src/application/requestBody.cjs +242 -0
- package/dist/production/src/application/requestBody.cjs.map +1 -0
- package/dist/production/src/application/requestBody.js +242 -0
- package/dist/production/src/application/requestBody.js.map +1 -0
- package/dist/production/src/config/configSchema.cjs +8 -1
- package/dist/production/src/config/configSchema.cjs.map +1 -1
- package/dist/production/src/config/configSchema.js +8 -1
- package/dist/production/src/config/configSchema.js.map +1 -1
- package/dist/production/src/graphql/execution.cjs +3 -9
- package/dist/production/src/graphql/execution.cjs.map +1 -1
- package/dist/production/src/graphql/execution.js +3 -9
- package/dist/production/src/graphql/execution.js.map +1 -1
- package/dist/production/src/project/ProjectContainer.cjs +1 -1
- package/dist/production/src/project/ProjectContainer.js +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.cjs +1 -1
- package/dist/production/src/projectGroup/ProjectGroupContainer.js +1 -1
- package/dist/production/src/providers.cjs +2 -2
- package/dist/production/src/providers.cjs.map +1 -1
- package/dist/production/src/providers.js +2 -2
- package/dist/production/src/providers.js.map +1 -1
- package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs +2 -2
- package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
- package/dist/production/src/transfer/ImportExecutor.cjs +18 -3
- package/dist/production/src/transfer/ImportExecutor.cjs.map +1 -1
- package/dist/production/src/transfer/ImportExecutor.js +18 -3
- package/dist/production/src/transfer/ImportExecutor.js.map +1 -1
- package/dist/production/src/utils/sentry.cjs +31 -49
- package/dist/production/src/utils/sentry.cjs.map +1 -1
- package/dist/production/src/utils/sentry.js +32 -33
- package/dist/production/src/utils/sentry.js.map +1 -1
- package/dist/production/src/utils/serverStartup.cjs +5 -3
- package/dist/production/src/utils/serverStartup.cjs.map +1 -1
- package/dist/production/src/utils/serverStartup.js +5 -3
- package/dist/production/src/utils/serverStartup.js.map +1 -1
- package/dist/tests/cases/unit/compression.test.d.ts +2 -0
- package/dist/tests/cases/unit/compression.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/cors.test.d.ts +2 -0
- package/dist/tests/cases/unit/cors.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/requestBody.test.d.ts +2 -0
- package/dist/tests/cases/unit/requestBody.test.d.ts.map +1 -0
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/MasterContainer.d.ts +1 -1
- package/dist/types/application/application.d.ts.map +1 -1
- package/dist/types/application/compression.d.ts +19 -0
- package/dist/types/application/compression.d.ts.map +1 -0
- package/dist/types/application/cors.d.ts +10 -0
- package/dist/types/application/cors.d.ts.map +1 -0
- package/dist/types/application/requestBody.d.ts +45 -0
- package/dist/types/application/requestBody.d.ts.map +1 -0
- package/dist/types/config/configSchema.d.ts +3 -3
- package/dist/types/config/configSchema.d.ts.map +1 -1
- package/dist/types/graphql/execution.d.ts.map +1 -1
- package/dist/types/transfer/ImportExecutor.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/dist/types/utils/sentry.d.ts +13 -6
- package/dist/types/utils/sentry.d.ts.map +1 -1
- package/dist/types/utils/serverStartup.d.ts.map +1 -1
- package/package.json +18 -24
- package/src/application/application.ts +8 -9
- package/src/application/compression.ts +118 -0
- package/src/application/cors.ts +61 -0
- package/src/application/requestBody.ts +295 -0
- package/src/config/configSchema.ts +8 -1
- package/src/graphql/execution.ts +3 -9
- package/src/providers.ts +2 -2
- package/src/transfer/ImportExecutor.ts +21 -3
- package/src/tsconfig.json +3 -1
- package/src/utils/sentry.ts +42 -39
- package/src/utils/serverStartup.ts +7 -5
- package/tests/cases/unit/compression.test.ts +172 -0
- package/tests/cases/unit/cors.test.ts +106 -0
- package/tests/cases/unit/requestBody.test.ts +333 -0
- package/tests/cases/unit/sentryLoggerHandler.test.ts +74 -20
- package/tests/cases/unit/serverConfig.test.ts +19 -0
- package/dist/tests/cases/unit/sentryIntegrations.test.d.ts +0 -2
- package/dist/tests/cases/unit/sentryIntegrations.test.d.ts.map +0 -1
- package/tests/cases/unit/sentryIntegrations.test.ts +0 -15
|
@@ -0,0 +1,333 @@
|
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
|
|
2
|
+
import Koa from 'koa'
|
|
3
|
+
import { IncomingHttpHeaders, IncomingMessage, request, Server } from 'node:http'
|
|
4
|
+
import { AddressInfo, connect, Socket } from 'node:net'
|
|
5
|
+
import { brotliCompressSync, deflateSync, gzipSync } from 'node:zlib'
|
|
6
|
+
import {
|
|
7
|
+
createRequestBodyMiddleware,
|
|
8
|
+
parseByteSize,
|
|
9
|
+
parseFormBody,
|
|
10
|
+
parseJsonBody,
|
|
11
|
+
parseMediaType,
|
|
12
|
+
readRequestText,
|
|
13
|
+
} from '../../../src/application/requestBody.js'
|
|
14
|
+
|
|
15
|
+
describe('parseByteSize', () => {
|
|
16
|
+
test('reads plain bytes and binary units', () => {
|
|
17
|
+
expect(parseByteSize('0')).toBe(0)
|
|
18
|
+
expect(parseByteSize('100')).toBe(100)
|
|
19
|
+
expect(parseByteSize('100b')).toBe(100)
|
|
20
|
+
expect(parseByteSize('56kb')).toBe(56 * 1024)
|
|
21
|
+
expect(parseByteSize('1mb')).toBe(1048576)
|
|
22
|
+
expect(parseByteSize('1.5 MB')).toBe(1572864)
|
|
23
|
+
expect(parseByteSize(' 2gb ')).toBe(2 * 1024 ** 3)
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
test('rejects anything else', () => {
|
|
27
|
+
for (const value of ['', 'mb', '-1', '+1mb', '1e3', '0x10', '10 megabytes', '1.mb', '99999pb']) {
|
|
28
|
+
expect(parseByteSize(value)).toBeUndefined()
|
|
29
|
+
}
|
|
30
|
+
})
|
|
31
|
+
})
|
|
32
|
+
|
|
33
|
+
describe('parseMediaType', () => {
|
|
34
|
+
test('lower-cases the type and drops valid parameters', () => {
|
|
35
|
+
expect(parseMediaType('application/json')).toBe('application/json')
|
|
36
|
+
expect(parseMediaType('Application/JSON')).toBe('application/json')
|
|
37
|
+
expect(parseMediaType('application/json; charset=utf-8')).toBe('application/json')
|
|
38
|
+
expect(parseMediaType('application/json;charset="utf-8"')).toBe('application/json')
|
|
39
|
+
expect(parseMediaType('application/json ; charset=utf-8')).toBe('application/json')
|
|
40
|
+
expect(parseMediaType('text/plain; a=1; b="x\\"y"')).toBe('text/plain')
|
|
41
|
+
})
|
|
42
|
+
|
|
43
|
+
test('accepts one trailing semicolon', () => {
|
|
44
|
+
expect(parseMediaType('application/json;')).toBe('application/json')
|
|
45
|
+
})
|
|
46
|
+
|
|
47
|
+
test('rejects malformed values', () => {
|
|
48
|
+
for (const value of ['', 'json', 'application/json, text/plain', 'application/json; charset', 'application/json;;', 'a/b; x="open', '/json']) {
|
|
49
|
+
expect(parseMediaType(value)).toBeUndefined()
|
|
50
|
+
}
|
|
51
|
+
})
|
|
52
|
+
})
|
|
53
|
+
|
|
54
|
+
describe('parseJsonBody', () => {
|
|
55
|
+
test('accepts objects and arrays, and an empty body as {}', () => {
|
|
56
|
+
expect(parseJsonBody('{"a":1}')).toEqual({ ok: true, value: { a: 1 } })
|
|
57
|
+
expect(parseJsonBody(' \n\t[1]')).toEqual({ ok: true, value: [1] })
|
|
58
|
+
expect(parseJsonBody('')).toEqual({ ok: true, value: {} })
|
|
59
|
+
})
|
|
60
|
+
|
|
61
|
+
test('rejects other JSON values and invalid JSON', () => {
|
|
62
|
+
for (const text of ['1', '"a"', 'null', 'true', '{bad', '\v{}']) {
|
|
63
|
+
expect(parseJsonBody(text)).toEqual({ ok: false })
|
|
64
|
+
}
|
|
65
|
+
})
|
|
66
|
+
|
|
67
|
+
test('rejects a __proto__ key at any depth, in any escaped spelling', () => {
|
|
68
|
+
expect(parseJsonBody('{"__proto__":{"admin":true}}')).toEqual({ ok: false })
|
|
69
|
+
expect(parseJsonBody('{"a":[{"b":{"\\u005f\\u005fproto\\u005F_" : 1}}]}')).toEqual({ ok: false })
|
|
70
|
+
})
|
|
71
|
+
|
|
72
|
+
test('keeps a __proto__ string value and other prototype-like keys', () => {
|
|
73
|
+
expect(parseJsonBody('{"a":"\\"__proto__\\":"}')).toEqual({ ok: true, value: { a: '"__proto__":' } })
|
|
74
|
+
expect(parseJsonBody('{"constructor":{"prototype":{}}}')).toEqual({ ok: true, value: { constructor: { prototype: {} } } })
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
test('scans deeply nested input without overflowing the stack', () => {
|
|
78
|
+
const depth = 100_000
|
|
79
|
+
const text = `${'['.repeat(depth)}{"__proto__":1}${']'.repeat(depth)}`
|
|
80
|
+
expect(parseJsonBody(text)).toEqual({ ok: false })
|
|
81
|
+
})
|
|
82
|
+
})
|
|
83
|
+
|
|
84
|
+
describe('parseFormBody', () => {
|
|
85
|
+
test('decodes pairs and collects repeated keys', () => {
|
|
86
|
+
expect(parseFormBody('a=1&b=x+y&b=%E2%9C%93&c')).toEqual({ a: '1', b: ['x y', '✓'], c: '' })
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
test('drops prototype keys and empty keys', () => {
|
|
90
|
+
const parsed = parseFormBody('__proto__=1&constructor=2&toString=3&=4&ok=5')
|
|
91
|
+
expect(parsed).toEqual({ ok: '5' })
|
|
92
|
+
expect(Object.getPrototypeOf(parsed)).toBe(Object.prototype)
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
test('reads at most 1000 pairs', () => {
|
|
96
|
+
const parsed = parseFormBody(Array.from({ length: 1500 }, (_, i) => `k${i}=${i}`).join('&'))
|
|
97
|
+
expect(Object.keys(parsed)).toHaveLength(1000)
|
|
98
|
+
expect(parsed.k999).toBe('999')
|
|
99
|
+
})
|
|
100
|
+
})
|
|
101
|
+
|
|
102
|
+
type Response = { status: number; headers: IncomingHttpHeaders; body: string }
|
|
103
|
+
|
|
104
|
+
const send = (port: number, headers: Record<string, string>, body?: string | Buffer, method = 'POST', path = '/'): Promise<Response> =>
|
|
105
|
+
new Promise((resolve, reject) => {
|
|
106
|
+
const req = request({ host: '127.0.0.1', port, path, method, headers }, res => {
|
|
107
|
+
let text = ''
|
|
108
|
+
res.setEncoding('utf8')
|
|
109
|
+
res.on('data', chunk => text += chunk)
|
|
110
|
+
res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: res.headers, body: text }))
|
|
111
|
+
})
|
|
112
|
+
req.on('error', reject)
|
|
113
|
+
req.end(body)
|
|
114
|
+
})
|
|
115
|
+
|
|
116
|
+
/** Writes a raw HTTP request and resolves with the response's status line. */
|
|
117
|
+
const sendRaw = (port: number, raw: string | Buffer): Promise<string> =>
|
|
118
|
+
new Promise((resolve, reject) => {
|
|
119
|
+
const socket = connect(port, '127.0.0.1')
|
|
120
|
+
let response = ''
|
|
121
|
+
socket.on('data', chunk => {
|
|
122
|
+
response += chunk
|
|
123
|
+
if (response.includes('\r\n')) {
|
|
124
|
+
resolve(response.slice(0, response.indexOf('\r\n')))
|
|
125
|
+
socket.destroy()
|
|
126
|
+
}
|
|
127
|
+
})
|
|
128
|
+
socket.on('error', reject)
|
|
129
|
+
socket.write(raw)
|
|
130
|
+
})
|
|
131
|
+
|
|
132
|
+
/** Raw, because the HTTP client adds a Content-Length to a chunked body. */
|
|
133
|
+
const sendChunked = (port: number, contentType: string, body: string | Buffer, extraHeaders: readonly string[] = []): Promise<string> => {
|
|
134
|
+
const headers = ['POST / HTTP/1.1', 'Host: localhost', `Content-Type: ${contentType}`, 'Transfer-Encoding: chunked', ...extraHeaders, '', '']
|
|
135
|
+
return sendRaw(
|
|
136
|
+
port,
|
|
137
|
+
Buffer.concat([Buffer.from(`${headers.join('\r\n')}${Buffer.byteLength(body).toString(16)}\r\n`), Buffer.from(body), Buffer.from('\r\n0\r\n\r\n')]),
|
|
138
|
+
)
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const waitFor = async (condition: () => boolean): Promise<void> => {
|
|
142
|
+
const deadline = Date.now() + 2000
|
|
143
|
+
while (!condition() && Date.now() < deadline) {
|
|
144
|
+
await new Promise(resolve => setTimeout(resolve, 10))
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
describe('request body middleware', () => {
|
|
149
|
+
let server: Server
|
|
150
|
+
let port: number
|
|
151
|
+
const errors: Error[] = []
|
|
152
|
+
let streamedBody: string | undefined
|
|
153
|
+
|
|
154
|
+
beforeAll(async () => {
|
|
155
|
+
const koa = new Koa()
|
|
156
|
+
koa.silent = true
|
|
157
|
+
koa.on('error', error => errors.push(error))
|
|
158
|
+
koa.use(createRequestBodyMiddleware({ json: 1000, form: 50 }))
|
|
159
|
+
koa.use(async ctx => {
|
|
160
|
+
if (ctx.get('Content-Type') === 'application/x-ndjson') {
|
|
161
|
+
let text = ''
|
|
162
|
+
for await (const chunk of ctx.req) {
|
|
163
|
+
text += chunk
|
|
164
|
+
}
|
|
165
|
+
streamedBody = text
|
|
166
|
+
}
|
|
167
|
+
ctx.body = { body: ctx.request.body }
|
|
168
|
+
})
|
|
169
|
+
server = koa.listen(0)
|
|
170
|
+
await new Promise(resolve => server.once('listening', resolve))
|
|
171
|
+
port = (server.address() as AddressInfo).port
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
afterAll(() => {
|
|
175
|
+
server.close()
|
|
176
|
+
})
|
|
177
|
+
|
|
178
|
+
const json = { 'Content-Type': 'application/json' }
|
|
179
|
+
|
|
180
|
+
test('parses JSON and form bodies', async () => {
|
|
181
|
+
expect((await send(port, json, '{"a":1}')).body).toBe('{"body":{"a":1}}')
|
|
182
|
+
expect((await send(port, { 'Content-Type': 'application/x-www-form-urlencoded' }, 'a=1')).body).toBe('{"body":{"a":"1"}}')
|
|
183
|
+
expect((await send(port, { 'Content-Type': 'application/vnd.api+json' }, '{"b":2}')).body).toBe('{"body":{"b":2}}')
|
|
184
|
+
})
|
|
185
|
+
|
|
186
|
+
test('other content types are not read', async () => {
|
|
187
|
+
expect((await send(port, { 'Content-Type': 'text/plain' }, '{"a":1}')).body).toBe('{"body":{}}')
|
|
188
|
+
expect((await send(port, {}, undefined, 'GET')).body).toBe('{"body":{}}')
|
|
189
|
+
const response = await send(port, { 'Content-Type': 'application/x-ndjson' }, '{"a":1}\n{"a":2}\n')
|
|
190
|
+
expect(response.body).toBe('{"body":{}}')
|
|
191
|
+
expect(streamedBody).toBe('{"a":1}\n{"a":2}\n')
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
test('invalid JSON and a __proto__ key are 400', async () => {
|
|
195
|
+
expect(await send(port, json, '{bad')).toMatchObject({ status: 400, body: 'Bad Request' })
|
|
196
|
+
expect(await send(port, json, '"str"')).toMatchObject({ status: 400 })
|
|
197
|
+
expect(await send(port, json, '{"__proto__":{}}')).toMatchObject({ status: 400 })
|
|
198
|
+
})
|
|
199
|
+
|
|
200
|
+
test('limits are 413, by Content-Length and by the bytes received', async () => {
|
|
201
|
+
const tooLong = `{"a":"${'x'.repeat(1000)}"}`
|
|
202
|
+
expect(await send(port, json, tooLong)).toMatchObject({ status: 413, body: 'request entity too large' })
|
|
203
|
+
expect(await sendChunked(port, 'application/json', tooLong)).toStartWith('HTTP/1.1 413 ')
|
|
204
|
+
expect(await sendChunked(port, 'application/json', '{"a":1}')).toStartWith('HTTP/1.1 200 ')
|
|
205
|
+
// a declared length over the limit is refused before any of the body arrives
|
|
206
|
+
const declaredOnly = ['POST / HTTP/1.1', 'Host: localhost', 'Content-Type: application/json', 'Content-Length: 2000', '', '']
|
|
207
|
+
expect(await sendRaw(port, declaredOnly.join('\r\n'))).toStartWith('HTTP/1.1 413 ')
|
|
208
|
+
expect(await send(port, { 'Content-Type': 'application/x-www-form-urlencoded' }, `a=${'x'.repeat(50)}`)).toMatchObject({ status: 413 })
|
|
209
|
+
expect(await send(port, json, `{"a":"${'x'.repeat(992)}"}`)).toMatchObject({ status: 200 })
|
|
210
|
+
})
|
|
211
|
+
|
|
212
|
+
test('compressed bodies are decompressed, and the limit applies after decompression', async () => {
|
|
213
|
+
expect((await send(port, { ...json, 'Content-Encoding': 'gzip' }, gzipSync('{"g":1}'))).body).toBe('{"body":{"g":1}}')
|
|
214
|
+
expect((await send(port, { ...json, 'Content-Encoding': 'deflate' }, deflateSync('{"d":1}'))).body).toBe('{"body":{"d":1}}')
|
|
215
|
+
expect((await send(port, { ...json, 'Content-Encoding': 'br' }, brotliCompressSync('{"b":1}'))).body).toBe('{"body":{"b":1}}')
|
|
216
|
+
const bomb = gzipSync(`{"a":"${'x'.repeat(100_000)}"}`)
|
|
217
|
+
expect(bomb.length).toBeLessThan(1000)
|
|
218
|
+
expect(await send(port, { ...json, 'Content-Encoding': 'gzip' }, bomb)).toMatchObject({ status: 413 })
|
|
219
|
+
})
|
|
220
|
+
|
|
221
|
+
test('compressed input is capped too, even when it inflates to nothing', async () => {
|
|
222
|
+
// 200 empty gzip members: about 4 KB on the wire, 0 bytes decompressed
|
|
223
|
+
const emptyMembers = Buffer.concat(Array.from({ length: 200 }, () => gzipSync('')))
|
|
224
|
+
expect(await send(port, { ...json, 'Content-Encoding': 'gzip' }, emptyMembers)).toMatchObject({ status: 413 })
|
|
225
|
+
expect(await sendChunked(port, 'application/json', emptyMembers, ['Content-Encoding: gzip'])).toStartWith('HTTP/1.1 413 ')
|
|
226
|
+
expect((await send(port, { ...json, 'Content-Encoding': 'gzip' }, Buffer.concat([gzipSync(''), gzipSync('{"a":1}')]))).body).toBe(
|
|
227
|
+
'{"body":{"a":1}}',
|
|
228
|
+
)
|
|
229
|
+
})
|
|
230
|
+
|
|
231
|
+
test('an unknown encoding is 415, a corrupt one 400', async () => {
|
|
232
|
+
expect(await send(port, { ...json, 'Content-Encoding': 'compress' }, '{}')).toMatchObject({ status: 415, body: 'Unsupported Media Type' })
|
|
233
|
+
expect(await send(port, { ...json, 'Content-Encoding': 'gzip' }, 'not gzip')).toMatchObject({ status: 400 })
|
|
234
|
+
})
|
|
235
|
+
|
|
236
|
+
test('a body cut short fails with 400 instead of hanging', async () => {
|
|
237
|
+
errors.length = 0
|
|
238
|
+
for (const encoding of [undefined, 'gzip']) {
|
|
239
|
+
const socket = connect(port, '127.0.0.1')
|
|
240
|
+
const headers = [`POST / HTTP/1.1`, 'Host: localhost', 'Content-Type: application/json', 'Content-Length: 800']
|
|
241
|
+
const prefix = encoding ? gzipSync('{"a":"' + 'x'.repeat(10)).subarray(0, 10) : Buffer.from('{"a":')
|
|
242
|
+
socket.write([...headers, ...(encoding ? [`Content-Encoding: ${encoding}`] : []), '', ''].join('\r\n'))
|
|
243
|
+
socket.write(prefix)
|
|
244
|
+
await new Promise(resolve => setTimeout(resolve, 50))
|
|
245
|
+
socket.destroy()
|
|
246
|
+
}
|
|
247
|
+
await waitFor(() => errors.length >= 2)
|
|
248
|
+
expect(errors.map(it => [Reflect.get(it, 'status'), it.message])).toEqual([[400, 'request aborted'], [400, 'request aborted']])
|
|
249
|
+
})
|
|
250
|
+
})
|
|
251
|
+
|
|
252
|
+
describe('readRequestText on a request that cannot emit anymore', () => {
|
|
253
|
+
test('a closed request is 400 at once', async () => {
|
|
254
|
+
const closed = new IncomingMessage(new Socket())
|
|
255
|
+
closed.headers = {}
|
|
256
|
+
closed.destroy()
|
|
257
|
+
await expect(readRequestText(closed, 100)).rejects.toMatchObject({ failure: { status: 400, message: 'request aborted' } })
|
|
258
|
+
})
|
|
259
|
+
|
|
260
|
+
test('a consumed request is 500 at once', async () => {
|
|
261
|
+
const consumed = new IncomingMessage(new Socket())
|
|
262
|
+
consumed.headers = {}
|
|
263
|
+
consumed.push('{}')
|
|
264
|
+
consumed.push(null)
|
|
265
|
+
consumed.resume()
|
|
266
|
+
await new Promise(resolve => consumed.once('end', resolve))
|
|
267
|
+
await expect(readRequestText(consumed, 100)).rejects.toMatchObject({ failure: { status: 500 } })
|
|
268
|
+
})
|
|
269
|
+
|
|
270
|
+
test('an unknown encoding rejects rather than throws', async () => {
|
|
271
|
+
const compressed = new IncomingMessage(new Socket())
|
|
272
|
+
compressed.headers = { 'content-encoding': 'compress' }
|
|
273
|
+
await expect(readRequestText(compressed, 100)).rejects.toMatchObject({ failure: { status: 415 } })
|
|
274
|
+
})
|
|
275
|
+
})
|
|
276
|
+
|
|
277
|
+
describe('request body middleware after other middlewares', () => {
|
|
278
|
+
let server: Server
|
|
279
|
+
let port: number
|
|
280
|
+
const errors: Error[] = []
|
|
281
|
+
const completed: string[] = []
|
|
282
|
+
|
|
283
|
+
beforeAll(async () => {
|
|
284
|
+
const koa = new Koa()
|
|
285
|
+
koa.silent = true
|
|
286
|
+
koa.on('error', error => errors.push(error))
|
|
287
|
+
koa.use(async (ctx, next) => {
|
|
288
|
+
if (ctx.path === '/slow') {
|
|
289
|
+
await new Promise(resolve => setTimeout(resolve, 100))
|
|
290
|
+
} else if (ctx.path === '/consumed') {
|
|
291
|
+
for await (const _ of ctx.req) {
|
|
292
|
+
// drained by an earlier middleware
|
|
293
|
+
}
|
|
294
|
+
} else if (ctx.path === '/preset') {
|
|
295
|
+
ctx.request.body = { preset: true }
|
|
296
|
+
}
|
|
297
|
+
await next()
|
|
298
|
+
})
|
|
299
|
+
koa.use(createRequestBodyMiddleware({ json: 1000, form: 50 }))
|
|
300
|
+
koa.use(async ctx => {
|
|
301
|
+
completed.push(ctx.path)
|
|
302
|
+
ctx.body = { body: ctx.request.body }
|
|
303
|
+
})
|
|
304
|
+
server = koa.listen(0)
|
|
305
|
+
await new Promise(resolve => server.once('listening', resolve))
|
|
306
|
+
port = (server.address() as AddressInfo).port
|
|
307
|
+
})
|
|
308
|
+
|
|
309
|
+
afterAll(() => {
|
|
310
|
+
server.close()
|
|
311
|
+
})
|
|
312
|
+
|
|
313
|
+
const json = { 'Content-Type': 'application/json' }
|
|
314
|
+
|
|
315
|
+
test('a body set earlier is kept', async () => {
|
|
316
|
+
expect((await send(port, json, '{"a":1}', 'POST', '/preset')).body).toBe('{"body":{"preset":true}}')
|
|
317
|
+
})
|
|
318
|
+
|
|
319
|
+
test('a body already read is a 500, not a pending request', async () => {
|
|
320
|
+
expect(await send(port, json, '{"a":1}', 'POST', '/consumed')).toMatchObject({ status: 500 })
|
|
321
|
+
})
|
|
322
|
+
|
|
323
|
+
test('a client gone before the parser runs does not leave the request pending', async () => {
|
|
324
|
+
errors.length = 0
|
|
325
|
+
const socket = connect(port, '127.0.0.1')
|
|
326
|
+
socket.write(['POST /slow HTTP/1.1', 'Host: localhost', 'Content-Type: application/json', 'Content-Length: 7', '', '{"a":1}'].join('\r\n'))
|
|
327
|
+
await new Promise(resolve => setTimeout(resolve, 20))
|
|
328
|
+
socket.destroy()
|
|
329
|
+
// Node reports the abort (400); Bun still delivers the buffered body, so the request completes
|
|
330
|
+
await waitFor(() => errors.length > 0 || completed.includes('/slow'))
|
|
331
|
+
expect(errors.length > 0 || completed.includes('/slow')).toBe(true)
|
|
332
|
+
})
|
|
333
|
+
})
|
|
@@ -1,31 +1,85 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import * as Sentry from '@sentry/node'
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
3
2
|
import { createLogger, LogLevels } from '@contember/logger'
|
|
3
|
+
import { createSentryClient, SentryEvent } from '@contember/sentry-client'
|
|
4
|
+
import { LoggerRequestBody } from '../../../src/application/index.js'
|
|
4
5
|
import { SentryLoggerHandler } from '../../../src/utils/sentry.js'
|
|
5
6
|
|
|
6
|
-
const
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
Sentry.init({
|
|
7
|
+
const setup = () => {
|
|
8
|
+
const events: SentryEvent[] = []
|
|
9
|
+
const client = createSentryClient({
|
|
10
10
|
dsn: 'https://public@sentry.invalid/1',
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
11
|
+
contextLines: 0,
|
|
12
|
+
// a fake ingest: the event is the third line of the envelope
|
|
13
|
+
fetch: async (_url, init) => {
|
|
14
|
+
events.push(JSON.parse(String(init.body).split('\n')[2]))
|
|
15
|
+
return new Response('{}')
|
|
15
16
|
},
|
|
16
17
|
})
|
|
17
|
-
|
|
18
|
+
const logger = createLogger(new SentryLoggerHandler(LogLevels.warn, client))
|
|
19
|
+
return { logger, events, flush: () => client.flush(2000) }
|
|
20
|
+
}
|
|
18
21
|
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
})
|
|
22
|
+
describe('SentryLoggerHandler', () => {
|
|
23
|
+
test('tags an event with both the project group and the project', async () => {
|
|
24
|
+
const { logger, events, flush } = setup()
|
|
25
|
+
logger.child({ projectGroup: 'group', project: 'blog' }).warn(new Error('Webhook request failed'))
|
|
26
|
+
await flush()
|
|
27
|
+
|
|
28
|
+
expect(events).toHaveLength(1)
|
|
29
|
+
expect(events[0].tags).toEqual({ projectGroup: 'group', project: 'blog' })
|
|
30
|
+
})
|
|
31
|
+
|
|
32
|
+
test('reports the request of the log entry', async () => {
|
|
33
|
+
const { logger, events, flush } = setup()
|
|
34
|
+
const requestLogger = logger.child({
|
|
35
|
+
module: 'content',
|
|
36
|
+
requestId: 'r1',
|
|
37
|
+
user: 'identity-1',
|
|
38
|
+
uri: '/content/blog/live',
|
|
39
|
+
traceId: '0af7651916cd43dd8448eb211c80319c',
|
|
40
|
+
spanId: 'b7ad6b7169203331',
|
|
41
|
+
[LoggerRequestBody]: { query: '{ listArticle { id } }', variables: { password: '***' } },
|
|
42
|
+
})
|
|
43
|
+
requestLogger.error(new TypeError('Query failed'))
|
|
44
|
+
await flush()
|
|
45
|
+
|
|
46
|
+
expect(events).toHaveLength(1)
|
|
47
|
+
expect(events[0]).toMatchObject({
|
|
48
|
+
level: 'error',
|
|
49
|
+
tags: { module: 'content' },
|
|
50
|
+
user: { id: 'identity-1' },
|
|
51
|
+
extra: { requestId: 'r1' },
|
|
52
|
+
request: { url: '/content/blog/live', data: { query: '{ listArticle { id } }', variables: { password: '***' } } },
|
|
53
|
+
contexts: { trace: { trace_id: '0af7651916cd43dd8448eb211c80319c', span_id: 'b7ad6b7169203331' } },
|
|
54
|
+
})
|
|
55
|
+
expect(events[0].exception?.values.at(-1)).toMatchObject({ type: 'TypeError', value: 'Query failed' })
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
test('reports the request URI the request logger set', async () => {
|
|
59
|
+
const { logger, events, flush } = setup()
|
|
60
|
+
logger.child({ uri: '/tenant?token=********' }).error(new Error('Sign-in failed'))
|
|
61
|
+
await flush()
|
|
22
62
|
|
|
23
|
-
|
|
24
|
-
|
|
63
|
+
expect(events[0].request?.url).toBe('/tenant?token=********')
|
|
64
|
+
})
|
|
25
65
|
|
|
26
|
-
|
|
27
|
-
|
|
66
|
+
test('maps the log level', async () => {
|
|
67
|
+
const { logger, events, flush } = setup()
|
|
68
|
+
logger.warn(new Error('warn'))
|
|
69
|
+
logger.error(new Error('error'))
|
|
70
|
+
logger.crit(new Error('crit'))
|
|
71
|
+
await flush()
|
|
28
72
|
|
|
29
|
-
|
|
30
|
-
|
|
73
|
+
expect(events.map(it => it.level)).toEqual(['warning', 'error', 'fatal'])
|
|
74
|
+
expect(events.every(it => it.contexts?.trace === undefined)).toBe(true)
|
|
75
|
+
})
|
|
76
|
+
|
|
77
|
+
test('ignores entries without an error and entries below warn', async () => {
|
|
78
|
+
const { logger, events, flush } = setup()
|
|
79
|
+
logger.warn('only a message')
|
|
80
|
+
logger.info(new Error('info'))
|
|
81
|
+
await flush()
|
|
82
|
+
|
|
83
|
+
expect(events).toEqual([])
|
|
84
|
+
})
|
|
31
85
|
})
|
|
@@ -163,3 +163,22 @@ test('egress: read from CONTEMBER_EGRESS_GUARD, _ALLOW_HTTP and _ALLOWLIST', asy
|
|
|
163
163
|
test('egress: an invalid allowlist entry is refused at startup', () => {
|
|
164
164
|
expect(() => serverConfigSchema({ egress: { guard: true, allowlist: '10.0.0.0/40' } })).toThrow('Invalid egress allowlist entry')
|
|
165
165
|
})
|
|
166
|
+
|
|
167
|
+
const requestBodySize = (val: unknown): unknown => serverConfigSchema({ http: { requestBodySize: val } }).http?.requestBodySize
|
|
168
|
+
|
|
169
|
+
test('requestBodySize: parsed into bytes with binary units', () => {
|
|
170
|
+
expect(requestBodySize('1048576')).toBe(1048576)
|
|
171
|
+
expect(requestBodySize('512kb')).toBe(512 * 1024)
|
|
172
|
+
expect(requestBodySize('10MB')).toBe(10 * 1024 * 1024)
|
|
173
|
+
expect(requestBodySize('1.5 mb')).toBe(1572864)
|
|
174
|
+
})
|
|
175
|
+
|
|
176
|
+
test('requestBodySize: empty means the default', () => {
|
|
177
|
+
expect(requestBodySize('')).toBeUndefined()
|
|
178
|
+
})
|
|
179
|
+
|
|
180
|
+
test('requestBodySize: a malformed size fails instead of disabling the limit', () => {
|
|
181
|
+
for (const value of ['abc', '10 megabytes', '-1mb', '1e6', 'mb']) {
|
|
182
|
+
expect(() => requestBodySize(value)).toThrow()
|
|
183
|
+
}
|
|
184
|
+
})
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"sentryIntegrations.test.d.ts","sourceRoot":"","sources":["../../../../tests/cases/unit/sentryIntegrations.test.ts"],"names":[],"mappings":""}
|
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
import { expect, test } from 'bun:test'
|
|
2
|
-
import * as Sentry from '@sentry/node'
|
|
3
|
-
import { filterSentryIntegrations } from '../../../src/utils/sentry.js'
|
|
4
|
-
|
|
5
|
-
test('outgoing requests are not instrumented, so their URLs stay out of breadcrumbs and spans', () => {
|
|
6
|
-
const defaults = Sentry.getDefaultIntegrations({}).map(it => it.name)
|
|
7
|
-
expect(defaults).toContain('Undici')
|
|
8
|
-
|
|
9
|
-
const kept = filterSentryIntegrations(Sentry.getDefaultIntegrations({})).map(it => it.name)
|
|
10
|
-
|
|
11
|
-
expect(kept).toContain('LinkedErrors')
|
|
12
|
-
for (const name of ['Undici', 'Http', 'Console']) {
|
|
13
|
-
expect(kept).not.toContain(name)
|
|
14
|
-
}
|
|
15
|
-
})
|