@contember/engine-http 2.2.0-alpha.17 → 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.
Files changed (221) hide show
  1. package/dist/development/index.cjs +3 -1
  2. package/dist/development/index.cjs.map +1 -1
  3. package/dist/development/index.js +4 -2
  4. package/dist/development/index.js.map +1 -1
  5. package/dist/development/src/MasterContainer.cjs +5 -4
  6. package/dist/development/src/MasterContainer.cjs.map +1 -1
  7. package/dist/development/src/MasterContainer.js +5 -4
  8. package/dist/development/src/MasterContainer.js.map +1 -1
  9. package/dist/development/src/application/PanelApiMount.cjs.map +1 -1
  10. package/dist/development/src/application/PanelApiMount.js.map +1 -1
  11. package/dist/development/src/application/application.cjs +27 -21
  12. package/dist/development/src/application/application.cjs.map +1 -1
  13. package/dist/development/src/application/application.js +27 -21
  14. package/dist/development/src/application/application.js.map +1 -1
  15. package/dist/development/src/application/compression.cjs +99 -0
  16. package/dist/development/src/application/compression.cjs.map +1 -0
  17. package/dist/development/src/application/compression.js +82 -0
  18. package/dist/development/src/application/compression.js.map +1 -0
  19. package/dist/development/src/application/cors.cjs +52 -0
  20. package/dist/development/src/application/cors.cjs.map +1 -0
  21. package/dist/development/src/application/cors.js +52 -0
  22. package/dist/development/src/application/cors.js.map +1 -0
  23. package/dist/development/src/application/requestBody.cjs +242 -0
  24. package/dist/development/src/application/requestBody.cjs.map +1 -0
  25. package/dist/development/src/application/requestBody.js +242 -0
  26. package/dist/development/src/application/requestBody.js.map +1 -0
  27. package/dist/development/src/application/requestBodyMasking.cjs +97 -0
  28. package/dist/development/src/application/requestBodyMasking.cjs.map +1 -0
  29. package/dist/development/src/application/requestBodyMasking.js +97 -0
  30. package/dist/development/src/application/requestBodyMasking.js.map +1 -0
  31. package/dist/development/src/config/configSchema.cjs +36 -1
  32. package/dist/development/src/config/configSchema.cjs.map +1 -1
  33. package/dist/development/src/config/configSchema.js +36 -1
  34. package/dist/development/src/config/configSchema.js.map +1 -1
  35. package/dist/development/src/config/configTemplate.cjs +5 -0
  36. package/dist/development/src/config/configTemplate.cjs.map +1 -1
  37. package/dist/development/src/config/configTemplate.js +5 -0
  38. package/dist/development/src/config/configTemplate.js.map +1 -1
  39. package/dist/development/src/content/ProjectMembershipResolver.cjs +10 -3
  40. package/dist/development/src/content/ProjectMembershipResolver.cjs.map +1 -1
  41. package/dist/development/src/content/ProjectMembershipResolver.js +10 -3
  42. package/dist/development/src/content/ProjectMembershipResolver.js.map +1 -1
  43. package/dist/development/src/graphql/execution.cjs +3 -9
  44. package/dist/development/src/graphql/execution.cjs.map +1 -1
  45. package/dist/development/src/graphql/execution.js +3 -9
  46. package/dist/development/src/graphql/execution.js.map +1 -1
  47. package/dist/development/src/project/ProjectContainer.cjs +1 -1
  48. package/dist/development/src/project/ProjectContainer.js +1 -1
  49. package/dist/development/src/projectGroup/ProjectGroupContainer.cjs +3 -2
  50. package/dist/development/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
  51. package/dist/development/src/projectGroup/ProjectGroupContainer.js +3 -2
  52. package/dist/development/src/projectGroup/ProjectGroupContainer.js.map +1 -1
  53. package/dist/development/src/providers.cjs +2 -2
  54. package/dist/development/src/providers.cjs.map +1 -1
  55. package/dist/development/src/providers.js +2 -2
  56. package/dist/development/src/providers.js.map +1 -1
  57. package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs +2 -2
  58. package/dist/development/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
  59. package/dist/development/src/transfer/ImportExecutor.cjs +33 -5
  60. package/dist/development/src/transfer/ImportExecutor.cjs.map +1 -1
  61. package/dist/development/src/transfer/ImportExecutor.js +33 -5
  62. package/dist/development/src/transfer/ImportExecutor.js.map +1 -1
  63. package/dist/development/src/utils/CryptoWrapper.cjs +11 -0
  64. package/dist/development/src/utils/CryptoWrapper.cjs.map +1 -1
  65. package/dist/development/src/utils/CryptoWrapper.js +11 -0
  66. package/dist/development/src/utils/CryptoWrapper.js.map +1 -1
  67. package/dist/development/src/utils/sentry.cjs +32 -49
  68. package/dist/development/src/utils/sentry.cjs.map +1 -1
  69. package/dist/development/src/utils/sentry.js +33 -33
  70. package/dist/development/src/utils/sentry.js.map +1 -1
  71. package/dist/development/src/utils/serverStartup.cjs +5 -3
  72. package/dist/development/src/utils/serverStartup.cjs.map +1 -1
  73. package/dist/development/src/utils/serverStartup.js +5 -3
  74. package/dist/development/src/utils/serverStartup.js.map +1 -1
  75. package/dist/production/index.cjs +3 -1
  76. package/dist/production/index.cjs.map +1 -1
  77. package/dist/production/index.js +4 -2
  78. package/dist/production/index.js.map +1 -1
  79. package/dist/production/src/MasterContainer.cjs +5 -4
  80. package/dist/production/src/MasterContainer.cjs.map +1 -1
  81. package/dist/production/src/MasterContainer.js +5 -4
  82. package/dist/production/src/MasterContainer.js.map +1 -1
  83. package/dist/production/src/application/PanelApiMount.cjs.map +1 -1
  84. package/dist/production/src/application/PanelApiMount.js.map +1 -1
  85. package/dist/production/src/application/application.cjs +27 -21
  86. package/dist/production/src/application/application.cjs.map +1 -1
  87. package/dist/production/src/application/application.js +27 -21
  88. package/dist/production/src/application/application.js.map +1 -1
  89. package/dist/production/src/application/compression.cjs +99 -0
  90. package/dist/production/src/application/compression.cjs.map +1 -0
  91. package/dist/production/src/application/compression.js +82 -0
  92. package/dist/production/src/application/compression.js.map +1 -0
  93. package/dist/production/src/application/cors.cjs +52 -0
  94. package/dist/production/src/application/cors.cjs.map +1 -0
  95. package/dist/production/src/application/cors.js +52 -0
  96. package/dist/production/src/application/cors.js.map +1 -0
  97. package/dist/production/src/application/requestBody.cjs +242 -0
  98. package/dist/production/src/application/requestBody.cjs.map +1 -0
  99. package/dist/production/src/application/requestBody.js +242 -0
  100. package/dist/production/src/application/requestBody.js.map +1 -0
  101. package/dist/production/src/application/requestBodyMasking.cjs +97 -0
  102. package/dist/production/src/application/requestBodyMasking.cjs.map +1 -0
  103. package/dist/production/src/application/requestBodyMasking.js +97 -0
  104. package/dist/production/src/application/requestBodyMasking.js.map +1 -0
  105. package/dist/production/src/config/configSchema.cjs +36 -1
  106. package/dist/production/src/config/configSchema.cjs.map +1 -1
  107. package/dist/production/src/config/configSchema.js +36 -1
  108. package/dist/production/src/config/configSchema.js.map +1 -1
  109. package/dist/production/src/config/configTemplate.cjs +5 -0
  110. package/dist/production/src/config/configTemplate.cjs.map +1 -1
  111. package/dist/production/src/config/configTemplate.js +5 -0
  112. package/dist/production/src/config/configTemplate.js.map +1 -1
  113. package/dist/production/src/content/ProjectMembershipResolver.cjs +10 -3
  114. package/dist/production/src/content/ProjectMembershipResolver.cjs.map +1 -1
  115. package/dist/production/src/content/ProjectMembershipResolver.js +10 -3
  116. package/dist/production/src/content/ProjectMembershipResolver.js.map +1 -1
  117. package/dist/production/src/graphql/execution.cjs +3 -9
  118. package/dist/production/src/graphql/execution.cjs.map +1 -1
  119. package/dist/production/src/graphql/execution.js +3 -9
  120. package/dist/production/src/graphql/execution.js.map +1 -1
  121. package/dist/production/src/project/ProjectContainer.cjs +1 -1
  122. package/dist/production/src/project/ProjectContainer.js +1 -1
  123. package/dist/production/src/projectGroup/ProjectGroupContainer.cjs +3 -2
  124. package/dist/production/src/projectGroup/ProjectGroupContainer.cjs.map +1 -1
  125. package/dist/production/src/projectGroup/ProjectGroupContainer.js +3 -2
  126. package/dist/production/src/projectGroup/ProjectGroupContainer.js.map +1 -1
  127. package/dist/production/src/providers.cjs +2 -2
  128. package/dist/production/src/providers.cjs.map +1 -1
  129. package/dist/production/src/providers.js +2 -2
  130. package/dist/production/src/providers.js.map +1 -1
  131. package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs +2 -2
  132. package/dist/production/src/transfer/ImportApiMiddlewareFactory.cjs.map +1 -1
  133. package/dist/production/src/transfer/ImportExecutor.cjs +33 -5
  134. package/dist/production/src/transfer/ImportExecutor.cjs.map +1 -1
  135. package/dist/production/src/transfer/ImportExecutor.js +33 -5
  136. package/dist/production/src/transfer/ImportExecutor.js.map +1 -1
  137. package/dist/production/src/utils/CryptoWrapper.cjs +11 -0
  138. package/dist/production/src/utils/CryptoWrapper.cjs.map +1 -1
  139. package/dist/production/src/utils/CryptoWrapper.js +11 -0
  140. package/dist/production/src/utils/CryptoWrapper.js.map +1 -1
  141. package/dist/production/src/utils/sentry.cjs +32 -49
  142. package/dist/production/src/utils/sentry.cjs.map +1 -1
  143. package/dist/production/src/utils/sentry.js +33 -33
  144. package/dist/production/src/utils/sentry.js.map +1 -1
  145. package/dist/production/src/utils/serverStartup.cjs +5 -3
  146. package/dist/production/src/utils/serverStartup.cjs.map +1 -1
  147. package/dist/production/src/utils/serverStartup.js +5 -3
  148. package/dist/production/src/utils/serverStartup.js.map +1 -1
  149. package/dist/tests/cases/unit/compression.test.d.ts +2 -0
  150. package/dist/tests/cases/unit/compression.test.d.ts.map +1 -0
  151. package/dist/tests/cases/unit/cors.test.d.ts +2 -0
  152. package/dist/tests/cases/unit/cors.test.d.ts.map +1 -0
  153. package/dist/tests/cases/unit/requestBody.test.d.ts +2 -0
  154. package/dist/tests/cases/unit/requestBody.test.d.ts.map +1 -0
  155. package/dist/tests/cases/unit/requestBodyLogging.test.d.ts +2 -0
  156. package/dist/tests/cases/unit/requestBodyLogging.test.d.ts.map +1 -0
  157. package/dist/tests/cases/unit/requestBodyMasking.test.d.ts +2 -0
  158. package/dist/tests/cases/unit/requestBodyMasking.test.d.ts.map +1 -0
  159. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  160. package/dist/types/MasterContainer.d.ts +8 -1
  161. package/dist/types/MasterContainer.d.ts.map +1 -1
  162. package/dist/types/application/PanelApiMount.d.ts +2 -0
  163. package/dist/types/application/PanelApiMount.d.ts.map +1 -1
  164. package/dist/types/application/application.d.ts +7 -1
  165. package/dist/types/application/application.d.ts.map +1 -1
  166. package/dist/types/application/compression.d.ts +19 -0
  167. package/dist/types/application/compression.d.ts.map +1 -0
  168. package/dist/types/application/cors.d.ts +10 -0
  169. package/dist/types/application/cors.d.ts.map +1 -0
  170. package/dist/types/application/index.d.ts +1 -0
  171. package/dist/types/application/index.d.ts.map +1 -1
  172. package/dist/types/application/requestBody.d.ts +45 -0
  173. package/dist/types/application/requestBody.d.ts.map +1 -0
  174. package/dist/types/application/requestBodyMasking.d.ts +10 -0
  175. package/dist/types/application/requestBodyMasking.d.ts.map +1 -0
  176. package/dist/types/config/configSchema.d.ts +13 -3
  177. package/dist/types/config/configSchema.d.ts.map +1 -1
  178. package/dist/types/config/configTemplate.d.ts.map +1 -1
  179. package/dist/types/content/ProjectMembershipResolver.d.ts.map +1 -1
  180. package/dist/types/graphql/execution.d.ts.map +1 -1
  181. package/dist/types/projectGroup/ProjectGroupContainer.d.ts.map +1 -1
  182. package/dist/types/transfer/ImportExecutor.d.ts +2 -0
  183. package/dist/types/transfer/ImportExecutor.d.ts.map +1 -1
  184. package/dist/types/tsconfig.tsbuildinfo +1 -1
  185. package/dist/types/utils/CryptoWrapper.d.ts +5 -0
  186. package/dist/types/utils/CryptoWrapper.d.ts.map +1 -1
  187. package/dist/types/utils/sentry.d.ts +13 -6
  188. package/dist/types/utils/sentry.d.ts.map +1 -1
  189. package/dist/types/utils/serverStartup.d.ts.map +1 -1
  190. package/package.json +18 -24
  191. package/src/MasterContainer.ts +5 -3
  192. package/src/application/PanelApiMount.ts +2 -0
  193. package/src/application/application.ts +38 -20
  194. package/src/application/compression.ts +118 -0
  195. package/src/application/cors.ts +61 -0
  196. package/src/application/index.ts +1 -0
  197. package/src/application/requestBody.ts +295 -0
  198. package/src/application/requestBodyMasking.ts +117 -0
  199. package/src/config/configSchema.ts +38 -1
  200. package/src/config/configTemplate.ts +5 -0
  201. package/src/content/ProjectMembershipResolver.ts +13 -5
  202. package/src/graphql/execution.ts +3 -9
  203. package/src/projectGroup/ProjectGroupContainer.ts +1 -0
  204. package/src/providers.ts +2 -2
  205. package/src/transfer/ImportExecutor.ts +37 -5
  206. package/src/tsconfig.json +3 -1
  207. package/src/utils/CryptoWrapper.ts +12 -0
  208. package/src/utils/sentry.ts +42 -39
  209. package/src/utils/serverStartup.ts +7 -5
  210. package/tests/cases/unit/compression.test.ts +172 -0
  211. package/tests/cases/unit/cors.test.ts +106 -0
  212. package/tests/cases/unit/crypto.test.ts +16 -0
  213. package/tests/cases/unit/projectMembershipResolver.test.ts +50 -0
  214. package/tests/cases/unit/requestBody.test.ts +333 -0
  215. package/tests/cases/unit/requestBodyLogging.test.ts +89 -0
  216. package/tests/cases/unit/requestBodyMasking.test.ts +102 -0
  217. package/tests/cases/unit/sentryLoggerHandler.test.ts +74 -20
  218. package/tests/cases/unit/serverConfig.test.ts +42 -0
  219. package/dist/tests/cases/unit/sentryIntegrations.test.d.ts +0 -2
  220. package/dist/tests/cases/unit/sentryIntegrations.test.d.ts.map +0 -1
  221. package/tests/cases/unit/sentryIntegrations.test.ts +0 -15
@@ -0,0 +1,295 @@
1
+ import { IncomingMessage } from 'node:http'
2
+ import { Readable, Transform } from 'node:stream'
3
+ import { createBrotliDecompress, createUnzip } from 'node:zlib'
4
+ import { KoaContext, KoaMiddleware } from './types.js'
5
+
6
+ declare module 'koa' {
7
+ interface Request {
8
+ /** The parsed JSON or form body; `{}` for any other content type. */
9
+ body?: unknown
10
+ }
11
+ }
12
+
13
+ const byteUnits: Readonly<Record<string, number>> = {
14
+ b: 1,
15
+ kb: 1024,
16
+ mb: 1024 ** 2,
17
+ gb: 1024 ** 3,
18
+ tb: 1024 ** 4,
19
+ pb: 1024 ** 5,
20
+ }
21
+
22
+ /** `1048576`, `512kb`, `1.5 MB`: binary units, as `requestBodySize` has always been read. `undefined` when invalid. */
23
+ export const parseByteSize = (value: string): number | undefined => {
24
+ const match = /^(\d+(?:\.\d+)?) *(b|kb|mb|gb|tb|pb)?$/i.exec(value.trim())
25
+ if (!match) {
26
+ return undefined
27
+ }
28
+ const bytes = Math.floor(Number(match[1]) * byteUnits[(match[2] ?? 'b').toLowerCase()])
29
+ return Number.isSafeInteger(bytes) ? bytes : undefined
30
+ }
31
+
32
+ const jsonTypes: ReadonlySet<string> = new Set([
33
+ 'application/json',
34
+ 'application/json-patch+json',
35
+ 'application/vnd.api+json',
36
+ 'application/csp-report',
37
+ 'application/scim+json',
38
+ ])
39
+ const formType = 'application/x-www-form-urlencoded'
40
+
41
+ const mediaTypePattern = /^ *([A-Za-z0-9][A-Za-z0-9!#$&^_-]{0,126})\/([A-Za-z0-9][A-Za-z0-9!#$&^_.+-]{0,126}) *$/
42
+ const mediaTypeParameterPattern =
43
+ /; *[!#$%&'*+\-.0-9A-Z^_`a-z|~]+ *= *(?:"(?:[ !\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+\-.0-9A-Z^_`a-z|~]+) */y
44
+
45
+ /** The lower-cased `type/subtype` of a well-formed Content-Type header; a malformed one matches no parser. */
46
+ export const parseMediaType = (header: string): string | undefined => {
47
+ // clients commonly send a trailing `;`, e.g. `application/json;`
48
+ const value = header.replace(/;$/, '')
49
+ const separator = value.indexOf(';')
50
+ const match = mediaTypePattern.exec(separator === -1 ? value : value.slice(0, separator))
51
+ if (!match) {
52
+ return undefined
53
+ }
54
+ if (separator !== -1) {
55
+ mediaTypeParameterPattern.lastIndex = separator
56
+ while (mediaTypeParameterPattern.lastIndex < value.length) {
57
+ if (!mediaTypeParameterPattern.test(value)) {
58
+ return undefined
59
+ }
60
+ }
61
+ }
62
+ return `${match[1]}/${match[2]}`.toLowerCase()
63
+ }
64
+
65
+ type BodyReadFailure = { readonly status: 400 | 413 | 415 | 500; readonly message?: string }
66
+
67
+ class BodyReadError extends Error {
68
+ constructor(readonly failure: BodyReadFailure) {
69
+ super(failure.message ?? `HTTP ${failure.status}`)
70
+ }
71
+ }
72
+
73
+ const tooLarge: BodyReadFailure = { status: 413, message: 'request entity too large' }
74
+ const aborted: BodyReadFailure = { status: 400, message: 'request aborted' }
75
+
76
+ const createDecompressor = (encoding: string): Transform | undefined => {
77
+ switch (encoding) {
78
+ case 'identity':
79
+ return undefined
80
+ case 'gzip':
81
+ case 'deflate':
82
+ return createUnzip()
83
+ case 'br':
84
+ return createBrotliDecompress()
85
+ default:
86
+ throw new BodyReadError({ status: 415 })
87
+ }
88
+ }
89
+
90
+ /** Compressed data can be a little larger than what it inflates to (stored blocks, headers), never by much. */
91
+ const compressedLimit = (limit: number): number => limit + Math.ceil(limit / 1024) + 1024
92
+
93
+ /**
94
+ * Reads the body as UTF-8 text. `limit` caps the decompressed size, so a compressed body cannot expand past it, and the
95
+ * bytes received, so one cannot send endless input that inflates to nothing. On a failure the request is left paused
96
+ * and unread, as before.
97
+ */
98
+ export const readRequestText = (request: IncomingMessage, limit: number): Promise<string> => {
99
+ const encoding = request.headers['content-encoding'] ?? 'identity'
100
+ const contentLength = request.headers['content-length'] !== undefined ? Number(request.headers['content-length']) : undefined
101
+ const wireLimit = encoding === 'identity' ? limit : compressedLimit(limit)
102
+ if (contentLength !== undefined && contentLength > wireLimit) {
103
+ return Promise.reject(new BodyReadError(tooLarge))
104
+ }
105
+ const declaredLength = encoding === 'identity' ? contentLength : undefined
106
+ // a consumed or closed request emits nothing more, so waiting for it would never settle
107
+ if (request.readableEnded) {
108
+ return Promise.reject(new BodyReadError({ status: 500, message: 'request body was already read' }))
109
+ }
110
+ if (request.destroyed || request.readableAborted || !request.readable) {
111
+ return Promise.reject(new BodyReadError(aborted))
112
+ }
113
+ let decompressor: Transform | undefined
114
+ try {
115
+ decompressor = createDecompressor(encoding)
116
+ } catch (error) {
117
+ return Promise.reject(error)
118
+ }
119
+ const source: Readable = decompressor ? request.pipe(decompressor) : request
120
+
121
+ return new Promise((resolve, reject) => {
122
+ const chunks: Buffer[] = []
123
+ let received = 0
124
+ let receivedCompressed = 0
125
+ let settled = false
126
+
127
+ const cleanup = () => {
128
+ source.off('data', onData)
129
+ source.off('end', onEnd)
130
+ source.off('error', onSourceError)
131
+ request.off('data', onCompressedData)
132
+ request.off('error', onAborted)
133
+ request.off('close', onClose)
134
+ }
135
+ const fail = (failure: BodyReadFailure) => {
136
+ if (settled) {
137
+ return
138
+ }
139
+ settled = true
140
+ cleanup()
141
+ if (decompressor) {
142
+ request.unpipe(decompressor)
143
+ decompressor.destroy()
144
+ }
145
+ source.pause()
146
+ reject(new BodyReadError(failure))
147
+ }
148
+ const onData = (chunk: Buffer) => {
149
+ received += chunk.length
150
+ if (received > limit) {
151
+ fail(tooLarge)
152
+ } else {
153
+ chunks.push(chunk)
154
+ }
155
+ }
156
+ const onCompressedData = (chunk: Buffer) => {
157
+ receivedCompressed += chunk.length
158
+ if (receivedCompressed > wireLimit) {
159
+ fail(tooLarge)
160
+ }
161
+ }
162
+ const onEnd = () => {
163
+ if (declaredLength !== undefined && received !== declaredLength) {
164
+ fail({ status: 400, message: 'request size did not match content length' })
165
+ return
166
+ }
167
+ settled = true
168
+ cleanup()
169
+ // strips a UTF-8 BOM and replaces invalid sequences, as the previous parser did
170
+ resolve(new TextDecoder().decode(Buffer.concat(chunks)))
171
+ }
172
+ const onSourceError = () => fail(decompressor === undefined ? aborted : { status: 400, message: 'request body could not be decompressed' })
173
+ const onAborted = () => fail(aborted)
174
+ const onClose = () => {
175
+ if (!request.complete) {
176
+ fail(aborted)
177
+ }
178
+ }
179
+
180
+ source.on('data', onData)
181
+ source.on('end', onEnd)
182
+ source.on('error', onSourceError)
183
+ if (decompressor) {
184
+ request.on('data', onCompressedData)
185
+ }
186
+ request.on('error', onAborted)
187
+ request.on('close', onClose)
188
+ })
189
+ }
190
+
191
+ const strictJsonStart = /^[ \t\n\r]*[[{]/
192
+ // any spelling of a `"__proto__":` key, escapes included; only then is the parsed value scanned
193
+ const suspectProtoKey =
194
+ /"(?:_|\\u005[Ff])(?:_|\\u005[Ff])(?:p|\\u0070)(?:r|\\u0072)(?:o|\\u006[Ff])(?:t|\\u0074)(?:o|\\u006[Ff])(?:_|\\u005[Ff])(?:_|\\u005[Ff])"\s*:/
195
+
196
+ const hasOwnProtoKey = (root: object): boolean => {
197
+ const pending: object[] = [root]
198
+ for (let node = pending.pop(); node !== undefined; node = pending.pop()) {
199
+ if (Object.hasOwn(node, '__proto__')) {
200
+ return true
201
+ }
202
+ for (const value of Object.values(node)) {
203
+ if (typeof value === 'object' && value !== null) {
204
+ pending.push(value)
205
+ }
206
+ }
207
+ }
208
+ return false
209
+ }
210
+
211
+ type JsonParseResult = { readonly ok: true; readonly value: unknown } | { readonly ok: false }
212
+
213
+ /** Only an object or an array, and no `__proto__` key anywhere (prototype poisoning). An empty body is `{}`. */
214
+ export const parseJsonBody = (text: string): JsonParseResult => {
215
+ if (text === '') {
216
+ return { ok: true, value: {} }
217
+ }
218
+ if (!strictJsonStart.test(text)) {
219
+ return { ok: false }
220
+ }
221
+ let value: unknown
222
+ try {
223
+ value = JSON.parse(text)
224
+ } catch {
225
+ return { ok: false }
226
+ }
227
+ if (typeof value === 'object' && value !== null && suspectProtoKey.test(text) && hasOwnProtoKey(value)) {
228
+ return { ok: false }
229
+ }
230
+ return { ok: true, value }
231
+ }
232
+
233
+ const maxFormParameters = 1000
234
+
235
+ /**
236
+ * Flat `application/x-www-form-urlencoded`: a repeated key collects its values into an array. Only the first 1000
237
+ * pairs are read, and keys naming an `Object.prototype` member (`__proto__`, `constructor`, …) are dropped.
238
+ */
239
+ export const parseFormBody = (text: string): Record<string, string | string[]> => {
240
+ const result: Record<string, string | string[]> = {}
241
+ let count = 0
242
+ for (const [key, value] of new URLSearchParams(text)) {
243
+ if (++count > maxFormParameters) {
244
+ break
245
+ }
246
+ if (key === '' || Object.hasOwn(Object.prototype, key)) {
247
+ continue
248
+ }
249
+ const existing = result[key]
250
+ result[key] = existing === undefined ? value : [...(Array.isArray(existing) ? existing : [existing]), value]
251
+ }
252
+ return result
253
+ }
254
+
255
+ export const defaultJsonBodyLimit = 1024 ** 2
256
+ export const defaultFormBodyLimit = 56 * 1024
257
+
258
+ /** Bytes after decompression. */
259
+ export interface RequestBodyLimits {
260
+ readonly json: number
261
+ readonly form: number
262
+ }
263
+
264
+ const parseBody = async (ctx: KoaContext<unknown>, limits: RequestBodyLimits): Promise<unknown> => {
265
+ const type = parseMediaType(ctx.get('Content-Type'))
266
+ if (type !== undefined && jsonTypes.has(type)) {
267
+ const parsed = parseJsonBody(await readRequestText(ctx.req, limits.json))
268
+ return parsed.ok ? parsed.value : ctx.throw(400)
269
+ }
270
+ if (type === formType) {
271
+ return parseFormBody(await readRequestText(ctx.req, limits.form))
272
+ }
273
+ return {}
274
+ }
275
+
276
+ /**
277
+ * Parses JSON and form bodies into `ctx.request.body`, unless an earlier middleware set it. Other content types are not
278
+ * read, so a handler can still stream the request (the import API reads `application/x-ndjson` itself).
279
+ */
280
+ export const createRequestBodyMiddleware = (limits: RequestBodyLimits): KoaMiddleware<unknown> => async (ctx, next) => {
281
+ if (ctx.request.body !== undefined) {
282
+ return await next()
283
+ }
284
+ try {
285
+ ctx.request.body = await parseBody(ctx, limits)
286
+ } catch (error) {
287
+ if (error instanceof BodyReadError) {
288
+ const { status, message } = error.failure
289
+ // without a message the response carries the status text, e.g. `Unsupported Media Type`
290
+ return message === undefined ? ctx.throw(status) : ctx.throw(status, message)
291
+ }
292
+ throw error
293
+ }
294
+ await next()
295
+ }
@@ -0,0 +1,117 @@
1
+ import { ASTVisitor, Kind, parse, print, ValueNode, visit } from 'graphql'
2
+ import { maskSecrets, REDACTED, SECRET_ARGUMENTS_BY_FIELD, SECRET_FIELD_NAMES } from '@contember/engine-tenant-api'
3
+
4
+ const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null && !Array.isArray(value)
5
+
6
+ // A query that names none of these cannot reference a secret argument (GraphQL names have no escapes), so it is kept unparsed.
7
+ const secretNamePattern = new RegExp([...SECRET_FIELD_NAMES, ...Object.keys(SECRET_ARGUMENTS_BY_FIELD)].join('|'))
8
+
9
+ type MaskedQuery = {
10
+ readonly query: string
11
+ /** Variables bound to a secret argument; `all` when the query could not be read. */
12
+ readonly secretVariables: ReadonlySet<string> | 'all'
13
+ }
14
+
15
+ const maskQuery = (query: string): MaskedQuery => {
16
+ if (!secretNamePattern.test(query)) {
17
+ return { query, secretVariables: new Set() }
18
+ }
19
+ let document
20
+ try {
21
+ document = parse(query)
22
+ } catch {
23
+ // An unparsable query may still inline a secret literal or bind one to any variable.
24
+ return { query: REDACTED, secretVariables: 'all' }
25
+ }
26
+ const secretVariables = new Set<string>()
27
+ let redacted = false
28
+ const collectVariables: ASTVisitor = {
29
+ Variable: node => {
30
+ secretVariables.add(node.name.value)
31
+ },
32
+ }
33
+ const redact = (value: ValueNode): ValueNode => {
34
+ visit(value, collectVariables)
35
+ if (value.kind === Kind.VARIABLE) {
36
+ return value
37
+ }
38
+ redacted = true
39
+ return { kind: Kind.STRING, value: REDACTED }
40
+ }
41
+ const withLiteralsMasked = visit(document, {
42
+ Field: node => {
43
+ const secretArguments = SECRET_ARGUMENTS_BY_FIELD[node.name.value]
44
+ if (secretArguments === undefined || node.arguments === undefined) {
45
+ return undefined
46
+ }
47
+ return { ...node, arguments: node.arguments.map(arg => secretArguments.has(arg.name.value) ? { ...arg, value: redact(arg.value) } : arg) }
48
+ },
49
+ Argument: node => SECRET_FIELD_NAMES.has(node.name.value) ? { ...node, value: redact(node.value) } : undefined,
50
+ ObjectField: node => SECRET_FIELD_NAMES.has(node.name.value) ? { ...node, value: redact(node.value) } : undefined,
51
+ })
52
+ // Variable definitions precede the selections that reveal which variables are secret, hence a second pass.
53
+ const masked = visit(withLiteralsMasked, {
54
+ VariableDefinition: node => {
55
+ if (node.defaultValue === undefined || !secretVariables.has(node.variable.name.value)) {
56
+ return undefined
57
+ }
58
+ redacted = true
59
+ return { ...node, defaultValue: { kind: Kind.STRING, value: REDACTED } }
60
+ },
61
+ })
62
+ // Re-printing changes the formatting, so the query is kept verbatim unless a literal was masked.
63
+ return { query: redacted ? print(masked) : query, secretVariables }
64
+ }
65
+
66
+ const maskVariables = (variables: unknown, secretVariables: ReadonlySet<string> | 'all'): unknown => {
67
+ if (typeof variables === 'string') {
68
+ // GraphQL over GET sends the variables as a JSON string.
69
+ try {
70
+ return maskVariables(JSON.parse(variables), secretVariables)
71
+ } catch {
72
+ return REDACTED
73
+ }
74
+ }
75
+ if (secretVariables === 'all') {
76
+ return maskSecrets(variables, true)
77
+ }
78
+ if (!isRecord(variables)) {
79
+ return maskSecrets(variables)
80
+ }
81
+ return Object.fromEntries(Object.entries(variables).map(([name, value]) => [name, maskSecrets(value, secretVariables.has(name))]))
82
+ }
83
+
84
+ const maskGraphQLRequest = (body: unknown): unknown => {
85
+ if (Array.isArray(body)) {
86
+ return body.map(maskGraphQLRequest)
87
+ }
88
+ if (!isRecord(body) || typeof body.query !== 'string') {
89
+ return maskSecrets(body)
90
+ }
91
+ const { query, secretVariables } = maskQuery(body.query)
92
+ return Object.fromEntries(
93
+ Object.entries(body).map(([key, value]) => {
94
+ if (key === 'query') {
95
+ return [key, query]
96
+ }
97
+ return [key, key === 'variables' ? maskVariables(value, secretVariables) : maskSecrets(value, SECRET_FIELD_NAMES.has(key))]
98
+ }),
99
+ )
100
+ }
101
+
102
+ /**
103
+ * A request body (or the parsed query string) as logs and error reports may carry it: on a route that receives
104
+ * credentials, passwords, OTP codes, tokens and secrets are replaced by a marker, both as GraphQL variables and as
105
+ * literals inlined in the query. Other routes (content, system, transfer) carry project data, which the credential
106
+ * names would only over-mask (`code`, `token` are common column names), so their bodies are logged as sent.
107
+ */
108
+ export const maskRequestBody = (body: unknown, carriesCredentials: boolean): unknown => carriesCredentials ? maskGraphQLRequest(body) : body
109
+
110
+ /** The request URI as it may be logged: on a route that receives credentials, the query string is masked. */
111
+ export const maskRequestUri = (uri: string | undefined, carriesCredentials: boolean): string | undefined => {
112
+ if (uri === undefined || !carriesCredentials) {
113
+ return uri
114
+ }
115
+ const queryStart = uri.indexOf('?')
116
+ return queryStart === -1 ? uri : `${uri.slice(0, queryStart)}?${REDACTED}`
117
+ }
@@ -3,6 +3,8 @@ import { MailerOptions } from '@contember/engine-tenant-api'
3
3
  import { validateRequestMemoryBudgetOptions } from '@contember/database'
4
4
  import { upperCaseFirst } from '../utils/strings.js'
5
5
  import ipaddr from 'ipaddr.js'
6
+ import { EgressError, EgressPolicy } from '@contember/engine-common'
7
+ import { parseByteSize } from '../application/requestBody.js'
6
8
 
7
9
  const dbConfigRequired = {
8
10
  host: Typesafe.string,
@@ -150,6 +152,33 @@ export const telemetryConfigSchema = Typesafe.partial({
150
152
  }),
151
153
  })
152
154
 
155
+ const egressConfigSchema = Typesafe.transform(
156
+ Typesafe.partial({
157
+ guard: Typesafe.boolean,
158
+ allowHttp: Typesafe.boolean,
159
+ allowlist: (val: unknown, path: PropertyKey[] = []): string[] | undefined => {
160
+ if (val === undefined || val === null || val === '') {
161
+ return undefined
162
+ }
163
+ const raw = Array.isArray(val) ? val : String(val).split(',')
164
+ const entries = raw.map(it => String(it).trim()).filter(Boolean)
165
+ return entries.length > 0 ? entries : undefined
166
+ },
167
+ }),
168
+ (value, input, path) => {
169
+ try {
170
+ // Rejects a malformed allowlist at startup rather than at the first outgoing request.
171
+ new EgressPolicy({ allowHttp: value.allowHttp ?? false, allowlist: value.allowlist ?? [] })
172
+ } catch (e) {
173
+ if (e instanceof EgressError) {
174
+ return Typesafe.fail(path, e.message)
175
+ }
176
+ throw e
177
+ }
178
+ return value
179
+ },
180
+ )
181
+
153
182
  export const serverConfigSchema = Typesafe.partial({
154
183
  port: Typesafe.number,
155
184
  http: Typesafe.partial({
@@ -165,7 +194,13 @@ export const serverConfigSchema = Typesafe.partial({
165
194
  const optionsError = validateRequestMemoryBudgetOptions({ warnBytes, maxBytes })
166
195
  return optionsError ? Typesafe.fail(path, optionsError) : { warnBytes, maxBytes }
167
196
  },
168
- requestBodySize: Typesafe.string,
197
+ requestBodySize: (input: unknown, path: PropertyKey[] = []): number | undefined => {
198
+ const value = Typesafe.string(input, path)
199
+ if (value === '') {
200
+ return undefined
201
+ }
202
+ return parseByteSize(value) ?? Typesafe.fail(path, 'expected a size such as 1048576, 512kb or 10mb')
203
+ },
169
204
  // Allows clients to opt in (via the X-Contember-Force-Ok request header) to receiving HTTP 200
170
205
  // for GraphQL API responses, keeping error info in the JSON body. Defaults to enabled; set to
171
206
  // false to forbid the header entirely. Accepts boolean-ish strings ('true'/'1'/'on'/...).
@@ -281,6 +316,8 @@ export const serverConfigSchema = Typesafe.partial({
281
316
  }),
282
317
  ),
283
318
  telemetry: telemetryConfigSchema,
319
+ // Restrictions on outgoing requests to tenant-chosen URLs (Actions webhooks, OIDC identity providers). Opt-in.
320
+ egress: egressConfigSchema,
284
321
  projectGroup: (val: unknown, path: PropertyKey[] = []) =>
285
322
  Typesafe.valueAt(val, ['domainMapping']) === undefined
286
323
  ? undefined
@@ -148,6 +148,11 @@ export const configTemplate: any = {
148
148
  },
149
149
  },
150
150
  },
151
+ egress: {
152
+ guard: '%?env.CONTEMBER_EGRESS_GUARD::bool%',
153
+ allowHttp: '%?env.CONTEMBER_EGRESS_ALLOW_HTTP::bool%',
154
+ allowlist: '%?env.CONTEMBER_EGRESS_ALLOWLIST::string%',
155
+ },
151
156
  test: {
152
157
  transactions: '%?env.CONTEMBER_TEST_TRANSACTIONS::bool%',
153
158
  transactionTtlSeconds: '%?env.CONTEMBER_TEST_TRANSACTION_TTL_SECONDS::number%',
@@ -83,23 +83,31 @@ export class ProjectMembershipResolver {
83
83
  }
84
84
  try {
85
85
  return assumeMembershipValueType(value).memberships
86
- } catch (e: any) {
87
- throw new HttpErrorResponse(400, `Invalid format of "assume membership": ${e.message}`)
86
+ } catch (e) {
87
+ throw new HttpErrorResponse(400, `Invalid format of "assume membership": ${e instanceof Error ? e.message : String(e)}`)
88
88
  }
89
89
  }
90
90
 
91
91
  private readAssumeMembershipJson(req: HttpRequest): unknown {
92
92
  if (typeof req.body === 'object' && req.body !== null && 'assumeMembership' in req.body) {
93
- return (req.body as any).assumeMembership
93
+ return req.body.assumeMembership
94
94
  }
95
95
  const value = req.get(assumeMembershipHeader).trim()
96
- return value !== '' ? JSON.parse(value) : null
96
+ if (value === '') {
97
+ return null
98
+ }
99
+ try {
100
+ return JSON.parse(value)
101
+ } catch {
102
+ throw new HttpErrorResponse(400, `Invalid JSON in ${assumeMembershipHeader} header`)
103
+ }
97
104
  }
98
105
 
99
106
  private verifyAssumedRoles(explicitMemberships: readonly Acl.Membership[], acl: Acl.Schema, assumedMemberships: readonly Acl.Membership[]) {
107
+ // A stored membership whose role the ACL no longer defines grants nothing, so it may assume nothing either.
100
108
  const membershipMatcher = new MembershipMatcher(explicitMemberships.map(it => ({
101
109
  ...it,
102
- matchRule: acl.roles[it.role].content?.assumeMembership ?? {},
110
+ matchRule: Object.hasOwn(acl.roles, it.role) ? acl.roles[it.role].content?.assumeMembership ?? {} : {},
103
111
  })))
104
112
 
105
113
  for (const assumed of assumedMemberships) {
@@ -10,7 +10,7 @@ import {
10
10
  validate,
11
11
  validateSchema,
12
12
  } from 'graphql'
13
- import { LRUCache } from 'lru-cache'
13
+ import { LRUCache } from '@contember/utilities'
14
14
  import { createHash } from 'node:crypto'
15
15
  import { Request, Response } from 'koa'
16
16
  import { logger } from '@contember/logger'
@@ -58,14 +58,8 @@ export const createGraphQLQueryHandler = <Context>({
58
58
  getMemoryBudget,
59
59
  }: FactoryArgs<Context>): GraphQLQueryHandler<Context> => {
60
60
  let schemaValidated = false
61
- const hitCache = new LRUCache<string, true>({
62
- max: hitCacheMax,
63
- ttl: hitCacheMaxAgeSeconds * 1000,
64
- })
65
- const documentCache = new LRUCache<string, DocumentNode>({
66
- max: documentCacheMax,
67
- ttl: documentCacheMaxAgeSeconds * 1000,
68
- })
61
+ const hitCache = new LRUCache<string, true>(hitCacheMax, { ttl: hitCacheMaxAgeSeconds * 1000 })
62
+ const documentCache = new LRUCache<string, DocumentNode>(documentCacheMax, { ttl: documentCacheMaxAgeSeconds * 1000 })
69
63
  let lastPrune = Date.now()
70
64
 
71
65
  return async ({ request, response, createContext }) => {
@@ -134,6 +134,7 @@ export class ProjectGroupContainerFactory {
134
134
  encrypt: cryptoWrapper.encrypt.bind(cryptoWrapper),
135
135
  encryptionEnabled: cryptoWrapper.enabled,
136
136
  },
137
+ dataSigner: cryptoWrapper.enabled ? (purpose, value) => cryptoWrapper.sign(purpose, value) : null,
137
138
  })
138
139
  },
139
140
  )
package/src/providers.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { v4 as uuidv4, v7 as uuidv7 } from 'uuid'
1
+ import { generateUuidV4, generateUuidV7 } from '@contember/utilities'
2
2
  import bcrypt from 'bcryptjs'
3
3
  import crypto, { BinaryLike } from 'node:crypto'
4
4
 
5
5
  export const createProviders = () => ({
6
- uuid: ({ version = 4 }: { version?: 4 | 7 } = {}) => version === 4 ? uuidv4() : uuidv7(),
6
+ uuid: ({ version = 4 }: { version?: 4 | 7 } = {}) => version === 4 ? generateUuidV4() : generateUuidV7(),
7
7
  now: () => new Date(),
8
8
  bcrypt: async (value: string) => await bcrypt.hash(value, 10),
9
9
  bcryptCompare: (data: any, hash: string) => bcrypt.compare(data, hash),