@contember/engine-actions 2.1.0-rc.6 → 2.1.0-rc.8
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/CLAUDE.md +11 -3
- package/dist/development/src/dispatch/WebhookTargetHandler.cjs +30 -17
- package/dist/development/src/dispatch/WebhookTargetHandler.cjs.map +1 -1
- package/dist/development/src/dispatch/WebhookTargetHandler.js +30 -17
- package/dist/development/src/dispatch/WebhookTargetHandler.js.map +1 -1
- package/dist/development/src/dispatch/redactRequestError.cjs +49 -0
- package/dist/development/src/dispatch/redactRequestError.cjs.map +1 -0
- package/dist/development/src/dispatch/redactRequestError.js +49 -0
- package/dist/development/src/dispatch/redactRequestError.js.map +1 -0
- package/dist/development/src/dispatch/truncateText.cjs +12 -0
- package/dist/development/src/dispatch/truncateText.cjs.map +1 -0
- package/dist/development/src/dispatch/truncateText.js +12 -0
- package/dist/development/src/dispatch/truncateText.js.map +1 -0
- package/dist/production/src/dispatch/WebhookTargetHandler.cjs +30 -17
- package/dist/production/src/dispatch/WebhookTargetHandler.cjs.map +1 -1
- package/dist/production/src/dispatch/WebhookTargetHandler.js +30 -17
- package/dist/production/src/dispatch/WebhookTargetHandler.js.map +1 -1
- package/dist/production/src/dispatch/redactRequestError.cjs +49 -0
- package/dist/production/src/dispatch/redactRequestError.cjs.map +1 -0
- package/dist/production/src/dispatch/redactRequestError.js +49 -0
- package/dist/production/src/dispatch/redactRequestError.js.map +1 -0
- package/dist/production/src/dispatch/truncateText.cjs +12 -0
- package/dist/production/src/dispatch/truncateText.cjs.map +1 -0
- package/dist/production/src/dispatch/truncateText.js +12 -0
- package/dist/production/src/dispatch/truncateText.js.map +1 -0
- package/dist/tests/cases/unit/redactRequestError.test.d.ts +2 -0
- package/dist/tests/cases/unit/redactRequestError.test.d.ts.map +1 -0
- package/dist/tests/cases/unit/truncateText.test.d.ts +2 -0
- package/dist/tests/cases/unit/truncateText.test.d.ts.map +1 -0
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/dispatch/WebhookTargetHandler.d.ts +1 -1
- package/dist/types/dispatch/WebhookTargetHandler.d.ts.map +1 -1
- package/dist/types/dispatch/redactRequestError.d.ts +8 -0
- package/dist/types/dispatch/redactRequestError.d.ts.map +1 -0
- package/dist/types/dispatch/truncateText.d.ts +6 -0
- package/dist/types/dispatch/truncateText.d.ts.map +1 -0
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +15 -15
- package/src/dispatch/WebhookTargetHandler.ts +47 -25
- package/src/dispatch/redactRequestError.ts +65 -0
- package/src/dispatch/truncateText.ts +13 -0
- package/tests/cases/unit/redactRequestError.test.ts +66 -0
- package/tests/cases/unit/truncateText.test.ts +25 -0
- package/tests/cases/unit/webhookHandler.test.ts +189 -0
package/package.json
CHANGED
|
@@ -22,20 +22,20 @@
|
|
|
22
22
|
}
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@contember/authorization": "2.1.0-rc.
|
|
26
|
-
"@contember/database": "2.1.0-rc.
|
|
27
|
-
"@contember/database-migrations": "2.1.0-rc.
|
|
28
|
-
"@contember/engine-common": "2.1.0-rc.
|
|
29
|
-
"@contember/engine-content-api": "2.1.0-rc.
|
|
30
|
-
"@contember/engine-http": "2.1.0-rc.
|
|
31
|
-
"@contember/engine-plugins": "2.1.0-rc.
|
|
32
|
-
"@contember/engine-system-api": "2.1.0-rc.
|
|
33
|
-
"@contember/engine-tenant-api": "2.1.0-rc.
|
|
34
|
-
"@contember/graphql-utils": "2.1.0-rc.
|
|
35
|
-
"@contember/logger": "2.1.0-rc.
|
|
36
|
-
"@contember/schema": "2.1.0-rc.
|
|
37
|
-
"@contember/schema-utils": "2.1.0-rc.
|
|
38
|
-
"@contember/typesafe": "2.1.0-rc.
|
|
25
|
+
"@contember/authorization": "2.1.0-rc.8",
|
|
26
|
+
"@contember/database": "2.1.0-rc.8",
|
|
27
|
+
"@contember/database-migrations": "2.1.0-rc.8",
|
|
28
|
+
"@contember/engine-common": "2.1.0-rc.8",
|
|
29
|
+
"@contember/engine-content-api": "2.1.0-rc.8",
|
|
30
|
+
"@contember/engine-http": "2.1.0-rc.8",
|
|
31
|
+
"@contember/engine-plugins": "2.1.0-rc.8",
|
|
32
|
+
"@contember/engine-system-api": "2.1.0-rc.8",
|
|
33
|
+
"@contember/engine-tenant-api": "2.1.0-rc.8",
|
|
34
|
+
"@contember/graphql-utils": "2.1.0-rc.8",
|
|
35
|
+
"@contember/logger": "2.1.0-rc.8",
|
|
36
|
+
"@contember/schema": "2.1.0-rc.8",
|
|
37
|
+
"@contember/schema-utils": "2.1.0-rc.8",
|
|
38
|
+
"@contember/typesafe": "2.1.0-rc.8",
|
|
39
39
|
"@graphql-tools/schema": "^10.0.31",
|
|
40
40
|
"graphql-tag": "^2.12.6"
|
|
41
41
|
},
|
|
@@ -49,7 +49,7 @@
|
|
|
49
49
|
"pg": "^8.20.0"
|
|
50
50
|
},
|
|
51
51
|
"type": "module",
|
|
52
|
-
"version": "2.1.0-rc.
|
|
52
|
+
"version": "2.1.0-rc.8",
|
|
53
53
|
"repository": {
|
|
54
54
|
"type": "git",
|
|
55
55
|
"url": "git+https://github.com/contember/contember.git",
|
|
@@ -4,8 +4,13 @@ import { VariablesMap } from '../model/VariablesManager'
|
|
|
4
4
|
import * as Typesafe from '@contember/typesafe'
|
|
5
5
|
import { FetcherResponse, WebhookFetcher } from './WebhookFetcher'
|
|
6
6
|
import { Logger } from '@contember/logger'
|
|
7
|
+
import { redactRequestError } from './redactRequestError'
|
|
8
|
+
import { truncateText } from './truncateText'
|
|
7
9
|
|
|
8
10
|
const DEFAULT_TIMEOUT_MS = 30_000 // 30 seconds
|
|
11
|
+
const LOGGED_RESPONSE_MAX_LENGTH = 500
|
|
12
|
+
// keeps an HTML error page from bloating actions_event.log, which gains one attempt per retry
|
|
13
|
+
const STORED_RESPONSE_MAX_LENGTH = 4_096
|
|
9
14
|
|
|
10
15
|
const ResponseType = Typesafe.noExtraProps(Typesafe.object({
|
|
11
16
|
failures: Typesafe.array(
|
|
@@ -22,6 +27,13 @@ const ResponseType = Typesafe.noExtraProps(Typesafe.object({
|
|
|
22
27
|
|
|
23
28
|
type EventResponseFactory = (eventRow: EventRow) => { ok: boolean; code?: number; response?: string; errorMessage?: string; durationMs?: number }
|
|
24
29
|
|
|
30
|
+
type ResolvedRequest = {
|
|
31
|
+
url: string
|
|
32
|
+
headers: Record<string, string>
|
|
33
|
+
/** The resolved URL, header values and interpolated variable values, which a logged response body must not quote. */
|
|
34
|
+
secrets: ReadonlySet<string>
|
|
35
|
+
}
|
|
36
|
+
|
|
25
37
|
export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget> {
|
|
26
38
|
constructor(
|
|
27
39
|
private readonly fetcher: WebhookFetcher,
|
|
@@ -36,13 +48,15 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
36
48
|
|
|
37
49
|
let eventResponseFactory: EventResponseFactory
|
|
38
50
|
try {
|
|
39
|
-
const
|
|
51
|
+
const request = this.resolveRequest(target, variables)
|
|
52
|
+
const response = await this.fetch(timeoutMs ?? DEFAULT_TIMEOUT_MS, target, request, events)
|
|
40
53
|
|
|
41
54
|
eventResponseFactory = this.createResponseFactory({
|
|
42
55
|
response: response,
|
|
43
56
|
events,
|
|
44
57
|
target,
|
|
45
58
|
logger,
|
|
59
|
+
secrets: request.secrets,
|
|
46
60
|
})
|
|
47
61
|
} catch (e) {
|
|
48
62
|
logger.warn(e)
|
|
@@ -61,24 +75,28 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
61
75
|
return events.map(it => ({ target, row: it, result: { durationMs, ...eventResponseFactory(it) } }))
|
|
62
76
|
}
|
|
63
77
|
|
|
64
|
-
private createResponseFactory({ response, events, target, logger }: {
|
|
78
|
+
private createResponseFactory({ response, events, target, logger, secrets }: {
|
|
65
79
|
response: FetcherResponse
|
|
66
80
|
events: EventRow[]
|
|
67
81
|
target: Actions.WebhookTarget
|
|
68
82
|
logger: Logger
|
|
83
|
+
secrets: ReadonlySet<string>
|
|
69
84
|
}): EventResponseFactory {
|
|
85
|
+
const storedResponse = truncateText(response.responseText, STORED_RESPONSE_MAX_LENGTH)
|
|
70
86
|
if (!response.ok) {
|
|
71
87
|
// The target is identified by name only: its URL and headers may carry credentials.
|
|
88
|
+
// The one target payload that is logged: the error body, redacted (it may echo the request) and then cut short.
|
|
72
89
|
logger.warn('Webhook target responded with an error status', {
|
|
73
90
|
target: target.name,
|
|
74
91
|
status: response.status,
|
|
75
92
|
statusText: response.statusText,
|
|
93
|
+
response: truncateText(redactRequestError(response.responseText, secrets), LOGGED_RESPONSE_MAX_LENGTH),
|
|
76
94
|
events: events.map(it => it.id),
|
|
77
95
|
})
|
|
78
96
|
return () => ({
|
|
79
97
|
ok: false,
|
|
80
98
|
code: response.status,
|
|
81
|
-
response:
|
|
99
|
+
response: storedResponse,
|
|
82
100
|
errorMessage: response.statusText,
|
|
83
101
|
})
|
|
84
102
|
}
|
|
@@ -117,14 +135,14 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
117
135
|
return () => ({
|
|
118
136
|
ok: false,
|
|
119
137
|
code: response.status,
|
|
120
|
-
response:
|
|
138
|
+
response: storedResponse,
|
|
121
139
|
errorMessage: 'Invalid response: undefined events IDs: ' + missingEvents.join('; '),
|
|
122
140
|
})
|
|
123
141
|
}
|
|
124
142
|
|
|
125
143
|
const failedIds = events.filter(it => failedEvents[it.id]).map(it => it.id)
|
|
126
144
|
if (failedIds.length) {
|
|
127
|
-
// Per-event errors come from
|
|
145
|
+
// Per-event errors come from a 2xx payload, which stays in the event log; only an error-status body is logged.
|
|
128
146
|
logger.warn('Webhook target reported failed events', {
|
|
129
147
|
target: target.name,
|
|
130
148
|
status: response.status,
|
|
@@ -143,7 +161,7 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
143
161
|
}
|
|
144
162
|
}
|
|
145
163
|
} catch (e: any) {
|
|
146
|
-
// The parser message quotes
|
|
164
|
+
// The parser message quotes a 2xx payload, so it stays in the event log; only an error-status body is logged.
|
|
147
165
|
logger.warn('Webhook target returned a malformed response', {
|
|
148
166
|
target: target.name,
|
|
149
167
|
status: response.status,
|
|
@@ -152,7 +170,7 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
152
170
|
return () => ({
|
|
153
171
|
ok: false,
|
|
154
172
|
code: response.status,
|
|
155
|
-
response:
|
|
173
|
+
response: storedResponse,
|
|
156
174
|
errorMessage: 'Invalid response: ' + e.message,
|
|
157
175
|
})
|
|
158
176
|
}
|
|
@@ -168,29 +186,23 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
168
186
|
return errorMessages
|
|
169
187
|
}
|
|
170
188
|
|
|
171
|
-
private async fetch(timeoutMs: number, target: Actions.WebhookTarget,
|
|
189
|
+
private async fetch(timeoutMs: number, target: Actions.WebhookTarget, request: ResolvedRequest, events: EventRow[]): Promise<FetcherResponse> {
|
|
172
190
|
return await withTimeout(timeoutMs, async abortController => {
|
|
173
|
-
return await this.doFetch(target,
|
|
191
|
+
return await this.doFetch(target, request, abortController, events)
|
|
174
192
|
})
|
|
175
193
|
}
|
|
176
194
|
|
|
177
195
|
private async doFetch(
|
|
178
196
|
target: Actions.WebhookTarget,
|
|
179
|
-
|
|
197
|
+
request: ResolvedRequest,
|
|
180
198
|
abortController: AbortController,
|
|
181
199
|
events: EventRow[],
|
|
182
200
|
): Promise<FetcherResponse> {
|
|
183
|
-
|
|
184
|
-
const resolvedHeaders = Object.fromEntries(
|
|
185
|
-
Object.entries(target.headers ?? {})
|
|
186
|
-
.map(([key, value]) => [key, this.resolveVariables(value, variables)]),
|
|
187
|
-
)
|
|
188
|
-
|
|
189
|
-
return await this.fetcher.fetch(resolvedUrl, {
|
|
201
|
+
return await this.fetcher.fetch(request.url, {
|
|
190
202
|
method: 'POST',
|
|
191
203
|
headers: {
|
|
192
204
|
['User-Agent']: 'Contember Actions',
|
|
193
|
-
...
|
|
205
|
+
...request.headers,
|
|
194
206
|
['Content-type']: 'application/json',
|
|
195
207
|
},
|
|
196
208
|
signal: abortController.signal,
|
|
@@ -229,13 +241,23 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
229
241
|
}
|
|
230
242
|
}
|
|
231
243
|
|
|
232
|
-
private
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
244
|
+
private resolveRequest(target: Actions.WebhookTarget, variables: VariablesMap): ResolvedRequest {
|
|
245
|
+
const secrets = new Set<string>()
|
|
246
|
+
const resolve = (subject: string) =>
|
|
247
|
+
subject.replace(/\{\{([\w_]+)}}/gm, (_, name) => {
|
|
248
|
+
if (!variables[name]) {
|
|
249
|
+
throw new Error(`Undefined variable ${name}`)
|
|
250
|
+
}
|
|
251
|
+
secrets.add(variables[name])
|
|
252
|
+
return variables[name]
|
|
253
|
+
})
|
|
254
|
+
const url = resolve(target.url)
|
|
255
|
+
const headers = Object.fromEntries(Object.entries(target.headers ?? {}).map(([key, value]) => [key, resolve(value)]))
|
|
256
|
+
secrets.add(url)
|
|
257
|
+
for (const value of Object.values(headers)) {
|
|
258
|
+
secrets.add(value)
|
|
259
|
+
}
|
|
260
|
+
return { url, headers, secrets }
|
|
239
261
|
}
|
|
240
262
|
}
|
|
241
263
|
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
// scheme, optional userinfo up to the last @ of the authority, host and port, then path, query and fragment;
|
|
2
|
+
// a URL ends at whitespace or a quote, and starts only where a run of scheme characters starts, which keeps the scan linear
|
|
3
|
+
const urlPattern = /(?<![a-z\d+.-])([a-z][a-z\d+.-]*:\/\/)(?:([^\s/?#"'`<>]*)@)?([^\s/?#"'`<>]*)([^\s"'`<>]*)/gi
|
|
4
|
+
|
|
5
|
+
const redactedMarker = '[redacted]'
|
|
6
|
+
|
|
7
|
+
// fetch strips HTTP whitespace around a header value before quoting it in an error
|
|
8
|
+
const trimHttpWhitespace = (value: string): string => value.replace(/^[\t\n\r ]+/, '').replace(/[\t\n\r ]+$/, '')
|
|
9
|
+
|
|
10
|
+
// a server quoting the request often names only its path or query, where a token written into the target URL lives
|
|
11
|
+
const urlParts = (value: string): string[] => {
|
|
12
|
+
let url: URL
|
|
13
|
+
try {
|
|
14
|
+
url = new URL(value)
|
|
15
|
+
} catch {
|
|
16
|
+
return []
|
|
17
|
+
}
|
|
18
|
+
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
|
|
19
|
+
return []
|
|
20
|
+
}
|
|
21
|
+
// the query without its ? only as key=value pairs, so a bare-word query does not redact that word everywhere
|
|
22
|
+
const query = url.search.includes('=') ? [url.search.slice(1)] : []
|
|
23
|
+
return [url.pathname + url.search, url.pathname, url.search, ...query, ...url.searchParams.values()].filter(it => it.length > 1)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const percentEncode = (value: string): string[] => {
|
|
27
|
+
try {
|
|
28
|
+
return [encodeURIComponent(value)]
|
|
29
|
+
} catch {
|
|
30
|
+
// a lone surrogate cannot be encoded, so it cannot be quoted encoded either
|
|
31
|
+
return []
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const variantsOf = (secret: string): string[] => {
|
|
36
|
+
const forms = [secret, trimHttpWhitespace(secret), ...urlParts(secret)]
|
|
37
|
+
// JSON encoders may escape a slash as \/
|
|
38
|
+
return [...forms, ...forms.flatMap(percentEncode), ...forms.map(it => it.replaceAll('/', '\\/'))]
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Removes what may carry a credential from a message about a failed webhook request, or from a target's error response:
|
|
43
|
+
* every occurrence of the given secrets, also with surrounding HTTP whitespace stripped, percent-encoded or with escaped slashes,
|
|
44
|
+
* the path, query and query values of a secret URL on their own, and then the userinfo, path, query and fragment of every URL still quoted.
|
|
45
|
+
* The scheme, host and port of such a URL stay for diagnostics.
|
|
46
|
+
*/
|
|
47
|
+
export const redactRequestError = (message: string, secrets: Iterable<string>): string => {
|
|
48
|
+
const variants = new Set<string>()
|
|
49
|
+
for (const secret of secrets) {
|
|
50
|
+
for (const variant of variantsOf(secret)) {
|
|
51
|
+
variants.add(variant)
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
// the longest first, so a secret containing a shorter one is not left partly visible
|
|
55
|
+
const sortedSecrets = [...variants].filter(it => it !== '').sort((a, b) => b.length - a.length)
|
|
56
|
+
let redacted = message
|
|
57
|
+
for (const secret of sortedSecrets) {
|
|
58
|
+
redacted = redacted.replaceAll(secret, redactedMarker)
|
|
59
|
+
}
|
|
60
|
+
return redacted.replace(urlPattern, (_, scheme: string, userinfo: string | undefined, host: string, rest: string) => {
|
|
61
|
+
const redactedUserinfo = userinfo === undefined ? '' : `${redactedMarker}@`
|
|
62
|
+
const redactedRest = rest === '' || rest === '/' ? rest : `/${redactedMarker}`
|
|
63
|
+
return `${scheme}${redactedUserinfo}${host}${redactedRest}`
|
|
64
|
+
})
|
|
65
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
const isHighSurrogate = (code: number): boolean => code >= 0xd800 && code <= 0xdbff
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Keeps at most `maxLength` UTF-16 code units of the text and appends a marker with the original length.
|
|
5
|
+
* A surrogate pair is never split: jsonb rejects a lone surrogate, which would fail the whole event log write.
|
|
6
|
+
*/
|
|
7
|
+
export const truncateText = (text: string, maxLength: number): string => {
|
|
8
|
+
if (text.length <= maxLength) {
|
|
9
|
+
return text
|
|
10
|
+
}
|
|
11
|
+
const end = maxLength > 0 && isHighSurrogate(text.charCodeAt(maxLength - 1)) ? maxLength - 1 : maxLength
|
|
12
|
+
return `${text.slice(0, end)}… [truncated, ${text.length} characters in total]`
|
|
13
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { redactRequestError } from '../../../src/dispatch/redactRequestError'
|
|
3
|
+
|
|
4
|
+
test('keeps a message without a URL or a secret', () => {
|
|
5
|
+
expect(redactRequestError('getaddrinfo ENOTFOUND example.com', [])).toBe('getaddrinfo ENOTFOUND example.com')
|
|
6
|
+
})
|
|
7
|
+
|
|
8
|
+
test('keeps only the scheme, host and port of a URL', () => {
|
|
9
|
+
expect(redactRequestError('Failed to parse URL from https://user:pw@example.com:8443/a/b?c=d#e', []))
|
|
10
|
+
.toBe('Failed to parse URL from https://[redacted]@example.com:8443/[redacted]')
|
|
11
|
+
expect(redactRequestError('Invalid URL http://example.com/?token=abc.', [])).toBe('Invalid URL http://example.com/[redacted]')
|
|
12
|
+
expect(redactRequestError('Unable to connect to http://example.com/ or http://example.org', []))
|
|
13
|
+
.toBe('Unable to connect to http://example.com/ or http://example.org')
|
|
14
|
+
})
|
|
15
|
+
|
|
16
|
+
test('redacts every URL, a quoted one included', () => {
|
|
17
|
+
expect(redactRequestError('Redirect from "https://a.example/x?t=1" to https://b.example/y', []))
|
|
18
|
+
.toBe('Redirect from "https://a.example/[redacted]" to https://b.example/[redacted]')
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
test('redacts every occurrence of a secret, the longest first', () => {
|
|
22
|
+
expect(redactRequestError('expected abc, got abcdef and abc', ['abc', 'abcdef', ''])).toBe('expected [redacted], got [redacted] and [redacted]')
|
|
23
|
+
expect(redactRequestError('invalid header value "Bearer abc"', ['Bearer abc', 'abc'])).toBe('invalid header value "[redacted]"')
|
|
24
|
+
})
|
|
25
|
+
|
|
26
|
+
test('redacts a password containing @, / or ?', () => {
|
|
27
|
+
expect(redactRequestError('Request cannot be constructed from a URL that includes credentials: https://user:p@ss@example.com/hooks', []))
|
|
28
|
+
.toBe('Request cannot be constructed from a URL that includes credentials: https://[redacted]@example.com/[redacted]')
|
|
29
|
+
// such a password ends the authority early, so only the known value redacts all of it
|
|
30
|
+
expect(redactRequestError('Failed to parse URL from https://user:pa/s?s@example.com/hooks', ['pa/s?s']))
|
|
31
|
+
.toBe('Failed to parse URL from https://[redacted]@example.com/[redacted]')
|
|
32
|
+
})
|
|
33
|
+
|
|
34
|
+
test('redacts a secret quoted without its surrounding whitespace', () => {
|
|
35
|
+
expect(redactRequestError('Headers.append: "Bearer abc\ndef" is an invalid header value.', [' Bearer abc\ndef\n', 'abc\ndef\n']))
|
|
36
|
+
.toBe('Headers.append: "[redacted]" is an invalid header value.')
|
|
37
|
+
})
|
|
38
|
+
|
|
39
|
+
test('redacts the path and query of a secret URL quoted on their own', () => {
|
|
40
|
+
const url = 'https://hooks.example.com/services/T0/B0/static-token?key=abc'
|
|
41
|
+
expect(redactRequestError('Cannot POST /services/T0/B0/static-token', [url])).toBe('Cannot POST [redacted]')
|
|
42
|
+
expect(redactRequestError('{"path":"/services/T0/B0/static-token?key=abc"}', [url])).toBe('{"path":"[redacted]"}')
|
|
43
|
+
expect(redactRequestError('bad query key=abc', [url])).toBe('bad query [redacted]')
|
|
44
|
+
expect(redactRequestError('{"error":"invalid apiKey STATICKEY"}', ['https://hooks.example.com/hook?apiKey=STATICKEY&v=2']))
|
|
45
|
+
.toBe('{"error":"invalid apiKey [redacted]"}')
|
|
46
|
+
// a bare-word query is no key=value pair, so the word stays elsewhere in the message
|
|
47
|
+
expect(redactRequestError('invalid header value', ['https://hooks.example.com/hook?id'])).toBe('invalid header value')
|
|
48
|
+
// a bare slash would redact every slash in the message
|
|
49
|
+
expect(redactRequestError('Cannot POST /', ['https://hooks.example.com/'])).toBe('Cannot POST /')
|
|
50
|
+
})
|
|
51
|
+
|
|
52
|
+
test('redacts a secret quoted with escaped slashes or percent-encoded', () => {
|
|
53
|
+
const url = 'https://hooks.example.com/p/static-token'
|
|
54
|
+
expect(redactRequestError('{"url":"https:\\/\\/hooks.example.com\\/p\\/static-token"}', [url])).toBe('{"url":"[redacted]"}')
|
|
55
|
+
expect(redactRequestError('{"path":"\\/p\\/static-token"}', [url])).toBe('{"path":"[redacted]"}')
|
|
56
|
+
expect(redactRequestError('redirect=https%3A%2F%2Fhooks.example.com%2Fp%2Fstatic-token', [url])).toBe('redirect=[redacted]')
|
|
57
|
+
expect(redactRequestError('{"auth":"Bearer a\\/b"}', ['Bearer a/b'])).toBe('{"auth":"[redacted]"}')
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
test('scans a long message without a URL in linear time', () => {
|
|
61
|
+
const start = performance.now()
|
|
62
|
+
expect(redactRequestError('a-'.repeat(100_000), [])).toHaveLength(200_000)
|
|
63
|
+
expect(redactRequestError('a.'.repeat(100_000), [])).toHaveLength(200_000)
|
|
64
|
+
// the quadratic scan took seconds on a tenth of this
|
|
65
|
+
expect(performance.now() - start).toBeLessThan(1_000)
|
|
66
|
+
})
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { describe, expect, test } from 'bun:test'
|
|
2
|
+
import { truncateText } from '../../../src/dispatch/truncateText'
|
|
3
|
+
|
|
4
|
+
describe('truncateText', () => {
|
|
5
|
+
test('keeps a text up to the limit unchanged', () => {
|
|
6
|
+
expect(truncateText('', 5)).toBe('')
|
|
7
|
+
expect(truncateText('abcd', 5)).toBe('abcd')
|
|
8
|
+
expect(truncateText('abcde', 5)).toBe('abcde')
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
test('cuts a text one past the limit and marks the original length', () => {
|
|
12
|
+
expect(truncateText('abcdef', 5)).toBe('abcde… [truncated, 6 characters in total]')
|
|
13
|
+
})
|
|
14
|
+
|
|
15
|
+
test('does not split a surrogate pair at the boundary', () => {
|
|
16
|
+
// '😀' is two UTF-16 code units, the limit falls between them
|
|
17
|
+
const truncated = truncateText('abcd😀xyz', 5)
|
|
18
|
+
expect(truncated).toBe('abcd… [truncated, 9 characters in total]')
|
|
19
|
+
expect(() => encodeURIComponent(truncated)).not.toThrow()
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
test('keeps a surrogate pair ending exactly at the limit', () => {
|
|
23
|
+
expect(truncateText('abc😀xyz', 5)).toBe('abc😀… [truncated, 8 characters in total]')
|
|
24
|
+
})
|
|
25
|
+
})
|
|
@@ -137,6 +137,62 @@ describe('webhook request', () => {
|
|
|
137
137
|
assert.equal(fetchCalled, true)
|
|
138
138
|
})
|
|
139
139
|
})
|
|
140
|
+
describe('webhook variables', () => {
|
|
141
|
+
test('interpolates variables into the URL and headers', async () => {
|
|
142
|
+
const requests: { url: string; headers: HeadersInit | undefined }[] = []
|
|
143
|
+
const webhookHandler = new WebhookTargetHandler({
|
|
144
|
+
fetch(url: string, init: RequestInit): Promise<FetcherResponse> {
|
|
145
|
+
requests.push({ url, headers: init.headers })
|
|
146
|
+
return okResponse
|
|
147
|
+
},
|
|
148
|
+
})
|
|
149
|
+
const target: Actions.AnyTarget = {
|
|
150
|
+
name: 'test_target',
|
|
151
|
+
type: 'webhook',
|
|
152
|
+
url: 'https://hooks.example.com/{{path}}',
|
|
153
|
+
headers: { Authorization: 'Bearer {{token}}' },
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
await webhookHandler.handle({
|
|
157
|
+
logger: createLogger(new TestLoggerHandler()),
|
|
158
|
+
target,
|
|
159
|
+
events: [createTestEvent(0)],
|
|
160
|
+
variables: { path: 'p', token: 't' },
|
|
161
|
+
})
|
|
162
|
+
|
|
163
|
+
assert.deepStrictEqual(requests, [{
|
|
164
|
+
url: 'https://hooks.example.com/p',
|
|
165
|
+
headers: { ['User-Agent']: 'Contember Actions', Authorization: 'Bearer t', ['Content-type']: 'application/json' },
|
|
166
|
+
}])
|
|
167
|
+
})
|
|
168
|
+
|
|
169
|
+
test('an undefined variable fails the attempt without a request', async () => {
|
|
170
|
+
let fetchCalled = false
|
|
171
|
+
const webhookHandler = new WebhookTargetHandler({
|
|
172
|
+
fetch(): Promise<FetcherResponse> {
|
|
173
|
+
fetchCalled = true
|
|
174
|
+
return okResponse
|
|
175
|
+
},
|
|
176
|
+
})
|
|
177
|
+
const target: Actions.AnyTarget = { name: 'test_target', type: 'webhook', url: 'https://hooks.example.com/{{path}}' }
|
|
178
|
+
const event = createTestEvent(0)
|
|
179
|
+
|
|
180
|
+
const result = await webhookHandler.handle({
|
|
181
|
+
logger: createLogger(new TestLoggerHandler()),
|
|
182
|
+
target,
|
|
183
|
+
events: [event],
|
|
184
|
+
variables: {},
|
|
185
|
+
})
|
|
186
|
+
|
|
187
|
+
assert.equal(fetchCalled, false)
|
|
188
|
+
assert.deepStrictEqual(dropDuration(result), [{
|
|
189
|
+
row: event,
|
|
190
|
+
target,
|
|
191
|
+
result: { ok: false, errorMessage: 'Undefined variable path', durationMs: -1 },
|
|
192
|
+
}])
|
|
193
|
+
})
|
|
194
|
+
})
|
|
195
|
+
|
|
140
196
|
describe('webhook response', () => {
|
|
141
197
|
test('successful response', async () => {
|
|
142
198
|
const testLoggerHandler = new TestLoggerHandler()
|
|
@@ -258,10 +314,118 @@ describe('webhook response', () => {
|
|
|
258
314
|
target: 'test_target',
|
|
259
315
|
status: 500,
|
|
260
316
|
statusText: 'Err',
|
|
317
|
+
response: 'Failed to something',
|
|
261
318
|
events: [event1.id, event2.id],
|
|
262
319
|
})
|
|
263
320
|
})
|
|
264
321
|
|
|
322
|
+
test('a long error body is cut short in the log and in the stored attempt', async () => {
|
|
323
|
+
const testLoggerHandler = new TestLoggerHandler()
|
|
324
|
+
const responseText = 'a'.repeat(10_000)
|
|
325
|
+
const webhookHandler = new WebhookTargetHandler({
|
|
326
|
+
fetch: () =>
|
|
327
|
+
Promise.resolve({
|
|
328
|
+
ok: false,
|
|
329
|
+
headers: new Headers(),
|
|
330
|
+
responseText,
|
|
331
|
+
status: 502,
|
|
332
|
+
statusText: 'Bad Gateway',
|
|
333
|
+
}),
|
|
334
|
+
})
|
|
335
|
+
const target: Actions.AnyTarget = { name: 'test_target', type: 'webhook', url: 'http://localhost' }
|
|
336
|
+
const event = createTestEvent(0)
|
|
337
|
+
|
|
338
|
+
const [handled] = await webhookHandler.handle({ logger: createLogger(testLoggerHandler), target, events: [event], variables: {} })
|
|
339
|
+
|
|
340
|
+
assert.equal(handled.result.response, `${'a'.repeat(4_096)}… [truncated, 10000 characters in total]`)
|
|
341
|
+
const warnings = testLoggerHandler.messages.filter(it => it.level.name === 'warn')
|
|
342
|
+
assert.equal(warnings.length, 1)
|
|
343
|
+
assert.equal(warnings[0].ownAttributes.response, `${'a'.repeat(500)}… [truncated, 10000 characters in total]`)
|
|
344
|
+
})
|
|
345
|
+
|
|
346
|
+
test('an error body echoing the request is logged without its credentials', async () => {
|
|
347
|
+
const testLoggerHandler = new TestLoggerHandler()
|
|
348
|
+
const webhookHandler = new WebhookTargetHandler({
|
|
349
|
+
fetch: () =>
|
|
350
|
+
Promise.resolve({
|
|
351
|
+
ok: false,
|
|
352
|
+
headers: new Headers(),
|
|
353
|
+
responseText: 'Unauthorized: Bearer secret-token for https://hooks.example.com/p/secret-path',
|
|
354
|
+
status: 401,
|
|
355
|
+
statusText: 'Unauthorized',
|
|
356
|
+
}),
|
|
357
|
+
})
|
|
358
|
+
const target: Actions.AnyTarget = {
|
|
359
|
+
name: 'test_target',
|
|
360
|
+
type: 'webhook',
|
|
361
|
+
url: 'https://hooks.example.com/p/{{path}}',
|
|
362
|
+
headers: { Authorization: 'Bearer {{token}}' },
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
await webhookHandler.handle({
|
|
366
|
+
logger: createLogger(testLoggerHandler),
|
|
367
|
+
target,
|
|
368
|
+
events: [createTestEvent(0)],
|
|
369
|
+
variables: { path: 'secret-path', token: 'secret-token' },
|
|
370
|
+
})
|
|
371
|
+
|
|
372
|
+
const warnings = testLoggerHandler.messages.filter(it => it.level.name === 'warn')
|
|
373
|
+
assert.equal(warnings.length, 1)
|
|
374
|
+
assert.equal(warnings[0].ownAttributes.response, 'Unauthorized: [redacted] for [redacted]')
|
|
375
|
+
})
|
|
376
|
+
|
|
377
|
+
test('an error body quoting the path of a target URL with a static token is logged without it', async () => {
|
|
378
|
+
const testLoggerHandler = new TestLoggerHandler()
|
|
379
|
+
const webhookHandler = new WebhookTargetHandler({
|
|
380
|
+
fetch: () =>
|
|
381
|
+
Promise.resolve({
|
|
382
|
+
ok: false,
|
|
383
|
+
headers: new Headers(),
|
|
384
|
+
responseText: 'Cannot POST /services/T0/B0/static-token',
|
|
385
|
+
status: 404,
|
|
386
|
+
statusText: 'Not Found',
|
|
387
|
+
}),
|
|
388
|
+
})
|
|
389
|
+
const target: Actions.AnyTarget = { name: 'test_target', type: 'webhook', url: 'https://hooks.example.com/services/T0/B0/static-token' }
|
|
390
|
+
|
|
391
|
+
await webhookHandler.handle({ logger: createLogger(testLoggerHandler), target, events: [createTestEvent(0)], variables: {} })
|
|
392
|
+
|
|
393
|
+
const warnings = testLoggerHandler.messages.filter(it => it.level.name === 'warn')
|
|
394
|
+
assert.equal(warnings.length, 1)
|
|
395
|
+
assert.equal(warnings[0].ownAttributes.response, 'Cannot POST [redacted]')
|
|
396
|
+
})
|
|
397
|
+
|
|
398
|
+
test('an error body is redacted before it is cut, so a secret across the cut does not leak in part', async () => {
|
|
399
|
+
const testLoggerHandler = new TestLoggerHandler()
|
|
400
|
+
const webhookHandler = new WebhookTargetHandler({
|
|
401
|
+
fetch: () =>
|
|
402
|
+
Promise.resolve({
|
|
403
|
+
ok: false,
|
|
404
|
+
headers: new Headers(),
|
|
405
|
+
responseText: `${'x'.repeat(495)}secret-token`,
|
|
406
|
+
status: 401,
|
|
407
|
+
statusText: 'Unauthorized',
|
|
408
|
+
}),
|
|
409
|
+
})
|
|
410
|
+
const target: Actions.AnyTarget = {
|
|
411
|
+
name: 'test_target',
|
|
412
|
+
type: 'webhook',
|
|
413
|
+
url: 'https://hooks.example.com',
|
|
414
|
+
headers: { Authorization: '{{token}}' },
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
await webhookHandler.handle({
|
|
418
|
+
logger: createLogger(testLoggerHandler),
|
|
419
|
+
target,
|
|
420
|
+
events: [createTestEvent(0)],
|
|
421
|
+
variables: { token: 'secret-token' },
|
|
422
|
+
})
|
|
423
|
+
|
|
424
|
+
const warnings = testLoggerHandler.messages.filter(it => it.level.name === 'warn')
|
|
425
|
+
assert.equal(warnings.length, 1)
|
|
426
|
+
assert.equal(warnings[0].ownAttributes.response, `${'x'.repeat(495)}[reda… [truncated, 505 characters in total]`)
|
|
427
|
+
})
|
|
428
|
+
|
|
265
429
|
test('invalid partial response', async () => {
|
|
266
430
|
const testLoggerHandler = new TestLoggerHandler()
|
|
267
431
|
const logger = createLogger(testLoggerHandler)
|
|
@@ -333,6 +497,31 @@ describe('webhook response', () => {
|
|
|
333
497
|
})
|
|
334
498
|
})
|
|
335
499
|
|
|
500
|
+
test('a long malformed response is capped in the stored attempt', async () => {
|
|
501
|
+
const responseText = `{"failures": ${'x'.repeat(10_000)}`
|
|
502
|
+
const webhookHandler = new WebhookTargetHandler({
|
|
503
|
+
fetch: () =>
|
|
504
|
+
Promise.resolve({
|
|
505
|
+
ok: true,
|
|
506
|
+
headers: new Headers([['content-type', 'application/json']]),
|
|
507
|
+
responseText,
|
|
508
|
+
status: 200,
|
|
509
|
+
statusText: 'OK',
|
|
510
|
+
}),
|
|
511
|
+
})
|
|
512
|
+
const target: Actions.AnyTarget = { name: 'test_target', type: 'webhook', url: 'http://localhost' }
|
|
513
|
+
|
|
514
|
+
const [handled] = await webhookHandler.handle({
|
|
515
|
+
logger: createLogger(new TestLoggerHandler()),
|
|
516
|
+
target,
|
|
517
|
+
events: [createTestEvent(0)],
|
|
518
|
+
variables: {},
|
|
519
|
+
})
|
|
520
|
+
|
|
521
|
+
assert.equal(handled.result.ok, false)
|
|
522
|
+
assert.equal(handled.result.response, `${responseText.slice(0, 4_096)}… [truncated, ${responseText.length} characters in total]`)
|
|
523
|
+
})
|
|
524
|
+
|
|
336
525
|
test('response naming events outside the batch', async () => {
|
|
337
526
|
const testLoggerHandler = new TestLoggerHandler()
|
|
338
527
|
const logger = createLogger(testLoggerHandler)
|