@contember/engine-actions 2.2.0-alpha.16 → 2.2.0-alpha.18
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 +22 -4
- package/dist/development/index.cjs +6 -4
- package/dist/development/index.cjs.map +1 -1
- package/dist/development/index.js +7 -5
- package/dist/development/index.js.map +1 -1
- package/dist/development/src/dispatch/WebhookFetcher.cjs +6 -1
- package/dist/development/src/dispatch/WebhookFetcher.cjs.map +1 -1
- package/dist/development/src/dispatch/WebhookFetcher.js +7 -2
- package/dist/development/src/dispatch/WebhookFetcher.js.map +1 -1
- package/dist/development/src/dispatch/WebhookTargetHandler.cjs +25 -12
- package/dist/development/src/dispatch/WebhookTargetHandler.cjs.map +1 -1
- package/dist/development/src/dispatch/WebhookTargetHandler.js +25 -12
- 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/index.cjs +6 -4
- package/dist/production/index.cjs.map +1 -1
- package/dist/production/index.js +7 -5
- package/dist/production/index.js.map +1 -1
- package/dist/production/src/dispatch/WebhookFetcher.cjs +6 -1
- package/dist/production/src/dispatch/WebhookFetcher.cjs.map +1 -1
- package/dist/production/src/dispatch/WebhookFetcher.js +7 -2
- package/dist/production/src/dispatch/WebhookFetcher.js.map +1 -1
- package/dist/production/src/dispatch/WebhookTargetHandler.cjs +25 -12
- package/dist/production/src/dispatch/WebhookTargetHandler.cjs.map +1 -1
- package/dist/production/src/dispatch/WebhookTargetHandler.js +25 -12
- 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/cases/unit/webhookEgress.test.d.ts +2 -0
- package/dist/tests/cases/unit/webhookEgress.test.d.ts.map +1 -0
- package/dist/tests/tsconfig.tsbuildinfo +1 -1
- package/dist/types/dispatch/WebhookFetcher.d.ts +7 -2
- package/dist/types/dispatch/WebhookFetcher.d.ts.map +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/index.d.ts.map +1 -1
- package/dist/types/tsconfig.tsbuildinfo +1 -1
- package/package.json +17 -17
- package/src/dispatch/WebhookFetcher.ts +11 -3
- package/src/dispatch/WebhookTargetHandler.ts +33 -13
- package/src/dispatch/redactRequestError.ts +65 -0
- package/src/dispatch/truncateText.ts +13 -0
- package/src/index.ts +6 -4
- package/tests/cases/unit/redactRequestError.test.ts +66 -0
- package/tests/cases/unit/truncateText.test.ts +25 -0
- package/tests/cases/unit/webhookEgress.test.ts +80 -0
- package/tests/cases/unit/webhookHandler.test.ts +180 -0
package/package.json
CHANGED
|
@@ -22,27 +22,27 @@
|
|
|
22
22
|
}
|
|
23
23
|
},
|
|
24
24
|
"dependencies": {
|
|
25
|
-
"@contember/authorization": "2.2.0-alpha.
|
|
26
|
-
"@contember/database": "2.2.0-alpha.
|
|
27
|
-
"@contember/database-migrations": "2.2.0-alpha.
|
|
28
|
-
"@contember/engine-common": "2.2.0-alpha.
|
|
29
|
-
"@contember/engine-content-api": "2.2.0-alpha.
|
|
30
|
-
"@contember/engine-http": "2.2.0-alpha.
|
|
31
|
-
"@contember/engine-plugins": "2.2.0-alpha.
|
|
32
|
-
"@contember/engine-system-api": "2.2.0-alpha.
|
|
33
|
-
"@contember/engine-tenant-api": "2.2.0-alpha.
|
|
34
|
-
"@contember/graphql-utils": "2.2.0-alpha.
|
|
35
|
-
"@contember/logger": "2.2.0-alpha.
|
|
36
|
-
"@contember/schema": "2.2.0-alpha.
|
|
37
|
-
"@contember/schema-utils": "2.2.0-alpha.
|
|
38
|
-
"@contember/telemetry": "2.2.0-alpha.
|
|
39
|
-
"@contember/typesafe": "2.2.0-alpha.
|
|
25
|
+
"@contember/authorization": "2.2.0-alpha.18",
|
|
26
|
+
"@contember/database": "2.2.0-alpha.18",
|
|
27
|
+
"@contember/database-migrations": "2.2.0-alpha.18",
|
|
28
|
+
"@contember/engine-common": "2.2.0-alpha.18",
|
|
29
|
+
"@contember/engine-content-api": "2.2.0-alpha.18",
|
|
30
|
+
"@contember/engine-http": "2.2.0-alpha.18",
|
|
31
|
+
"@contember/engine-plugins": "2.2.0-alpha.18",
|
|
32
|
+
"@contember/engine-system-api": "2.2.0-alpha.18",
|
|
33
|
+
"@contember/engine-tenant-api": "2.2.0-alpha.18",
|
|
34
|
+
"@contember/graphql-utils": "2.2.0-alpha.18",
|
|
35
|
+
"@contember/logger": "2.2.0-alpha.18",
|
|
36
|
+
"@contember/schema": "2.2.0-alpha.18",
|
|
37
|
+
"@contember/schema-utils": "2.2.0-alpha.18",
|
|
38
|
+
"@contember/telemetry": "2.2.0-alpha.18",
|
|
39
|
+
"@contember/typesafe": "2.2.0-alpha.18",
|
|
40
40
|
"@graphql-tools/schema": "^10.0.31",
|
|
41
41
|
"graphql-tag": "^2.12.6",
|
|
42
42
|
"prom-client": "^12.0.0"
|
|
43
43
|
},
|
|
44
44
|
"devDependencies": {
|
|
45
|
-
"@contember/database-tester": "2.2.0-alpha.
|
|
45
|
+
"@contember/database-tester": "2.2.0-alpha.18",
|
|
46
46
|
"@types/bun": "^1.3.10",
|
|
47
47
|
"@types/ws": "^8.18.1",
|
|
48
48
|
"graphql": "^16.13.1"
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
"pg": "^8.20.0"
|
|
53
53
|
},
|
|
54
54
|
"type": "module",
|
|
55
|
-
"version": "2.2.0-alpha.
|
|
55
|
+
"version": "2.2.0-alpha.18",
|
|
56
56
|
"repository": {
|
|
57
57
|
"type": "git",
|
|
58
58
|
"url": "git+https://github.com/contember/contember.git",
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { EgressFetch, EgressGuard, EgressRequestInit } from '@contember/engine-common'
|
|
2
|
+
|
|
1
3
|
export type FetcherResponse = {
|
|
2
4
|
readonly headers: Headers
|
|
3
5
|
readonly ok: boolean
|
|
@@ -7,12 +9,15 @@ export type FetcherResponse = {
|
|
|
7
9
|
}
|
|
8
10
|
|
|
9
11
|
export interface WebhookFetcher {
|
|
10
|
-
fetch(url: string, init:
|
|
12
|
+
fetch(url: string, init: EgressRequestInit): Promise<FetcherResponse>
|
|
11
13
|
}
|
|
12
14
|
|
|
13
15
|
export class WebhookFetcherNative implements WebhookFetcher {
|
|
14
|
-
|
|
15
|
-
|
|
16
|
+
constructor(private readonly fetchImpl: EgressFetch) {
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
async fetch(url: string, init: EgressRequestInit): Promise<FetcherResponse> {
|
|
20
|
+
const response = await this.fetchImpl(url, init)
|
|
16
21
|
return {
|
|
17
22
|
ok: response.ok,
|
|
18
23
|
headers: response.headers,
|
|
@@ -22,3 +27,6 @@ export class WebhookFetcherNative implements WebhookFetcher {
|
|
|
22
27
|
}
|
|
23
28
|
}
|
|
24
29
|
}
|
|
30
|
+
|
|
31
|
+
/** Webhooks go through the egress guard when the operator enabled it, otherwise through the global `fetch`. */
|
|
32
|
+
export const createWebhookFetcher = (egressGuard: EgressGuard | null): WebhookFetcher => new WebhookFetcherNative(egressGuard?.fetch ?? fetch)
|
|
@@ -6,8 +6,13 @@ import { FetcherResponse, WebhookFetcher } from './WebhookFetcher.js'
|
|
|
6
6
|
import { Logger } from '@contember/logger'
|
|
7
7
|
import { formatTraceparent, INVALID_TRACE_ID, Tracer } from '@contember/telemetry'
|
|
8
8
|
import { replaceActionsVariables } from '@contember/schema-utils'
|
|
9
|
+
import { redactRequestError } from './redactRequestError.js'
|
|
10
|
+
import { truncateText } from './truncateText.js'
|
|
9
11
|
|
|
10
12
|
const DEFAULT_TIMEOUT_MS = 30_000 // 30 seconds
|
|
13
|
+
const LOGGED_RESPONSE_MAX_LENGTH = 500
|
|
14
|
+
// keeps an HTML error page from bloating actions_event.log, which gains one attempt per retry
|
|
15
|
+
const STORED_RESPONSE_MAX_LENGTH = 4_096
|
|
11
16
|
|
|
12
17
|
const ResponseType = Typesafe.noExtraProps(Typesafe.object({
|
|
13
18
|
failures: Typesafe.array(
|
|
@@ -24,11 +29,12 @@ const ResponseType = Typesafe.noExtraProps(Typesafe.object({
|
|
|
24
29
|
|
|
25
30
|
type EventResponseFactory = (eventRow: EventRow) => { ok: boolean; code?: number; response?: string; errorMessage?: string; durationMs?: number }
|
|
26
31
|
|
|
32
|
+
/** Carries the name and code of a failed request, and a reason only when it was redacted. Never the cause, which may quote credentials. */
|
|
27
33
|
class WebhookRequestError extends Error {
|
|
28
34
|
public readonly code?: string | number
|
|
29
35
|
|
|
30
|
-
constructor(error: unknown) {
|
|
31
|
-
super('Webhook request failed')
|
|
36
|
+
constructor(error: unknown, redactedReason?: string) {
|
|
37
|
+
super(redactedReason === undefined ? 'Webhook request failed' : `Webhook request failed: ${redactedReason}`)
|
|
32
38
|
try {
|
|
33
39
|
if (error instanceof Error) {
|
|
34
40
|
this.name = error.name
|
|
@@ -63,6 +69,8 @@ export class UndefinedVariableError extends Error {
|
|
|
63
69
|
type ResolvedRequest = {
|
|
64
70
|
url: string
|
|
65
71
|
headers: Record<string, string>
|
|
72
|
+
/** The resolved URL, header values and interpolated variable values, which an error message must not quote. */
|
|
73
|
+
secrets: ReadonlySet<string>
|
|
66
74
|
}
|
|
67
75
|
|
|
68
76
|
export type WebhookTargetHandlerOptions = {
|
|
@@ -117,16 +125,18 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
117
125
|
events,
|
|
118
126
|
target,
|
|
119
127
|
logger,
|
|
128
|
+
secrets: request.secrets,
|
|
120
129
|
})
|
|
121
130
|
} catch (e) {
|
|
122
|
-
|
|
123
|
-
const errorMessages = this.extractErrorMessages(e)
|
|
131
|
+
// Request errors may quote the resolved URL or a header value, so only a redacted reason is logged and stored.
|
|
132
|
+
const errorMessages = this.extractErrorMessages(e).map(it => redactRequestError(it, request.secrets))
|
|
133
|
+
const errorMessage = errorMessages.length ? errorMessages.join('; ') : undefined
|
|
134
|
+
logger.warn(new WebhookRequestError(e, errorMessage), { target: target.name })
|
|
124
135
|
const result = {
|
|
125
136
|
ok: false,
|
|
126
|
-
errorMessage
|
|
137
|
+
errorMessage,
|
|
127
138
|
durationMs: getDuration(),
|
|
128
139
|
}
|
|
129
|
-
eventResponseFactory = () => ({ ok: false, errorMessage: errorMessages.length ? errorMessages.join('; ') : undefined })
|
|
130
140
|
|
|
131
141
|
return events.map(it => ({ target, row: it, result }))
|
|
132
142
|
}
|
|
@@ -135,24 +145,28 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
135
145
|
return events.map(it => ({ target, row: it, result: { durationMs, ...eventResponseFactory(it) } }))
|
|
136
146
|
}
|
|
137
147
|
|
|
138
|
-
private createResponseFactory({ response, events, target, logger }: {
|
|
148
|
+
private createResponseFactory({ response, events, target, logger, secrets }: {
|
|
139
149
|
response: FetcherResponse
|
|
140
150
|
events: EventRow[]
|
|
141
151
|
target: Actions.WebhookTarget
|
|
142
152
|
logger: Logger
|
|
153
|
+
secrets: ReadonlySet<string>
|
|
143
154
|
}): EventResponseFactory {
|
|
155
|
+
const storedResponse = truncateText(response.responseText, STORED_RESPONSE_MAX_LENGTH)
|
|
144
156
|
if (!response.ok) {
|
|
145
157
|
// The target is identified by name only: its URL and headers may carry credentials.
|
|
158
|
+
// The one target payload that is logged: the error body, redacted (it may echo the request) and then cut short.
|
|
146
159
|
logger.warn('Webhook target responded with an error status', {
|
|
147
160
|
target: target.name,
|
|
148
161
|
status: response.status,
|
|
149
162
|
statusText: response.statusText,
|
|
163
|
+
response: truncateText(redactRequestError(response.responseText, secrets), LOGGED_RESPONSE_MAX_LENGTH),
|
|
150
164
|
events: events.map(it => it.id),
|
|
151
165
|
})
|
|
152
166
|
return () => ({
|
|
153
167
|
ok: false,
|
|
154
168
|
code: response.status,
|
|
155
|
-
response:
|
|
169
|
+
response: storedResponse,
|
|
156
170
|
errorMessage: response.statusText,
|
|
157
171
|
})
|
|
158
172
|
}
|
|
@@ -191,14 +205,14 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
191
205
|
return () => ({
|
|
192
206
|
ok: false,
|
|
193
207
|
code: response.status,
|
|
194
|
-
response:
|
|
208
|
+
response: storedResponse,
|
|
195
209
|
errorMessage: 'Invalid response: undefined events IDs: ' + missingEvents.join('; '),
|
|
196
210
|
})
|
|
197
211
|
}
|
|
198
212
|
|
|
199
213
|
const failedIds = events.filter(it => failedEvents[it.id]).map(it => it.id)
|
|
200
214
|
if (failedIds.length) {
|
|
201
|
-
// Per-event errors come from
|
|
215
|
+
// Per-event errors come from a 2xx payload, which stays in the event log; only an error-status body is logged.
|
|
202
216
|
logger.warn('Webhook target reported failed events', {
|
|
203
217
|
target: target.name,
|
|
204
218
|
status: response.status,
|
|
@@ -217,7 +231,7 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
217
231
|
}
|
|
218
232
|
}
|
|
219
233
|
} catch (e: any) {
|
|
220
|
-
// The parser message quotes
|
|
234
|
+
// The parser message quotes a 2xx payload, so it stays in the event log; only an error-status body is logged.
|
|
221
235
|
logger.warn('Webhook target returned a malformed response', {
|
|
222
236
|
target: target.name,
|
|
223
237
|
status: response.status,
|
|
@@ -226,7 +240,7 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
226
240
|
return () => ({
|
|
227
241
|
ok: false,
|
|
228
242
|
code: response.status,
|
|
229
|
-
response:
|
|
243
|
+
response: storedResponse,
|
|
230
244
|
errorMessage: 'Invalid response: ' + e.message,
|
|
231
245
|
})
|
|
232
246
|
}
|
|
@@ -320,6 +334,7 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
320
334
|
/** Throws {@link UndefinedVariableError} naming every variable without a value, an empty one included. */
|
|
321
335
|
private resolveVariables(target: Actions.WebhookTarget, variables: VariablesMap): ResolvedRequest {
|
|
322
336
|
const undefinedVariables = new Set<string>()
|
|
337
|
+
const secrets = new Set<string>()
|
|
323
338
|
const resolve = (subject: string) =>
|
|
324
339
|
replaceActionsVariables(subject, name => {
|
|
325
340
|
const value = resolveVariable(variables, name)
|
|
@@ -327,6 +342,7 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
327
342
|
undefinedVariables.add(name)
|
|
328
343
|
return ''
|
|
329
344
|
}
|
|
345
|
+
secrets.add(value)
|
|
330
346
|
return value
|
|
331
347
|
})
|
|
332
348
|
const url = resolve(target.url)
|
|
@@ -334,7 +350,11 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
|
|
|
334
350
|
if (undefinedVariables.size > 0) {
|
|
335
351
|
throw new UndefinedVariableError([...undefinedVariables])
|
|
336
352
|
}
|
|
337
|
-
|
|
353
|
+
secrets.add(url)
|
|
354
|
+
for (const value of Object.values(headers)) {
|
|
355
|
+
secrets.add(value)
|
|
356
|
+
}
|
|
357
|
+
return { url, headers, secrets }
|
|
338
358
|
}
|
|
339
359
|
}
|
|
340
360
|
|
|
@@ -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
|
+
}
|
package/src/index.ts
CHANGED
|
@@ -27,7 +27,7 @@ import { VariablesQueryResolver } from './graphql/resolvers/query/VariablesQuery
|
|
|
27
27
|
import { VariablesManager } from './model/VariablesManager.js'
|
|
28
28
|
import { AccessEvaluator, Authorizator } from '@contember/authorization'
|
|
29
29
|
import { ActionsPermissionsFactory } from './authorization/index.js'
|
|
30
|
-
import {
|
|
30
|
+
import { createWebhookFetcher } from './dispatch/WebhookFetcher.js'
|
|
31
31
|
import { ActionsMetrics } from './ActionsMetrics.js'
|
|
32
32
|
|
|
33
33
|
export {
|
|
@@ -74,8 +74,9 @@ export default class ActionsPlugin implements Plugin {
|
|
|
74
74
|
.addService('actions_eventRepository', () => {
|
|
75
75
|
return new EventsRepository()
|
|
76
76
|
})
|
|
77
|
-
.addService('actions_eventDispatcher', ({ actions_eventRepository, actions_variableManager, tracer, serverConfig }) => {
|
|
78
|
-
const
|
|
77
|
+
.addService('actions_eventDispatcher', ({ actions_eventRepository, actions_variableManager, tracer, serverConfig, egressGuard }) => {
|
|
78
|
+
const webhookFetcher = createWebhookFetcher(egressGuard)
|
|
79
|
+
const webhookTargetHandler = new WebhookTargetHandler(webhookFetcher, tracer, {
|
|
79
80
|
propagateToWebhooks: serverConfig.telemetry?.traces?.propagateToWebhooks ?? true,
|
|
80
81
|
})
|
|
81
82
|
const targetHandlerResolver = new TargetHandlerResolver(webhookTargetHandler)
|
|
@@ -127,7 +128,7 @@ export default class ActionsPlugin implements Plugin {
|
|
|
127
128
|
debugMode,
|
|
128
129
|
actions_dispatchWorkerSupervisorFactory,
|
|
129
130
|
)
|
|
130
|
-
it.addRoute('actions', '/actions/:projectSlug', actionsMiddlewareFactory.create())
|
|
131
|
+
it.addRoute('actions', '/actions/:projectSlug', actionsMiddlewareFactory.create(), { carriesCredentials: true })
|
|
131
132
|
it.addWebsocketRoute('actions', '/actions/_worker', actionsWebsocketMiddlewareFactory.create())
|
|
132
133
|
// Does nothing unless the panel is served; when it is, the panel's access gate applies
|
|
133
134
|
// and the UI learns the actions module has an API to talk to.
|
|
@@ -135,6 +136,7 @@ export default class ActionsPlugin implements Plugin {
|
|
|
135
136
|
name: 'actions',
|
|
136
137
|
path: 'actions/:projectSlug',
|
|
137
138
|
controller: actionsMiddlewareFactory.create(),
|
|
139
|
+
carriesCredentials: true,
|
|
138
140
|
})
|
|
139
141
|
},
|
|
140
142
|
)
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { expect, test } from 'bun:test'
|
|
2
|
+
import { redactRequestError } from '../../../src/dispatch/redactRequestError.js'
|
|
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.js'
|
|
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
|
+
})
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { afterAll, beforeAll, describe, expect, test } from 'bun:test'
|
|
2
|
+
import http from 'node:http'
|
|
3
|
+
import { createEgressGuard } from '@contember/engine-common'
|
|
4
|
+
import { createLogger, TestLoggerHandler } from '@contember/logger'
|
|
5
|
+
import { Actions } from '@contember/schema'
|
|
6
|
+
import { noopTracer } from '@contember/telemetry'
|
|
7
|
+
import { createWebhookFetcher } from '../../../src/dispatch/WebhookFetcher.js'
|
|
8
|
+
import { WebhookTargetHandler } from '../../../src/dispatch/WebhookTargetHandler.js'
|
|
9
|
+
import { createTestEvent } from '../../src/event.js'
|
|
10
|
+
|
|
11
|
+
describe('webhook delivery and the egress guard', () => {
|
|
12
|
+
let server: http.Server
|
|
13
|
+
let port: number
|
|
14
|
+
let received = 0
|
|
15
|
+
// The test preload replaces the global `fetch` with a DOM one; the engine runs with the runtime's own.
|
|
16
|
+
let preloadFetch: typeof fetch
|
|
17
|
+
|
|
18
|
+
beforeAll(async () => {
|
|
19
|
+
preloadFetch = globalThis.fetch
|
|
20
|
+
globalThis.fetch = Bun.fetch
|
|
21
|
+
server = http.createServer((req, res) => {
|
|
22
|
+
received++
|
|
23
|
+
req.resume()
|
|
24
|
+
res.writeHead(200).end()
|
|
25
|
+
})
|
|
26
|
+
// All interfaces: `localhost` may resolve to ::1 first.
|
|
27
|
+
await new Promise<void>(resolve => server.listen(0, resolve))
|
|
28
|
+
const address = server.address()
|
|
29
|
+
if (address === null || typeof address === 'string') {
|
|
30
|
+
throw new Error('expected a TCP address')
|
|
31
|
+
}
|
|
32
|
+
port = address.port
|
|
33
|
+
})
|
|
34
|
+
|
|
35
|
+
afterAll(() => {
|
|
36
|
+
globalThis.fetch = preloadFetch
|
|
37
|
+
server.close()
|
|
38
|
+
})
|
|
39
|
+
|
|
40
|
+
const deliver = async (guard: ReturnType<typeof createEgressGuard>) => {
|
|
41
|
+
const handler = new WebhookTargetHandler(createWebhookFetcher(guard), noopTracer, { propagateToWebhooks: false })
|
|
42
|
+
const target: Actions.AnyTarget = { name: 'local_target', type: 'webhook', url: `http://localhost:${port}/hook` }
|
|
43
|
+
const [handled] = await handler.handle({
|
|
44
|
+
logger: createLogger(new TestLoggerHandler()),
|
|
45
|
+
target,
|
|
46
|
+
events: [createTestEvent(0)],
|
|
47
|
+
variables: {},
|
|
48
|
+
})
|
|
49
|
+
return handled.result
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
test('without the guard (the default), a local http webhook is delivered', async () => {
|
|
53
|
+
const before = received
|
|
54
|
+
const result = await deliver(createEgressGuard(undefined))
|
|
55
|
+
expect(result.ok).toBe(true)
|
|
56
|
+
expect(result.code).toBe(200)
|
|
57
|
+
expect(received).toBe(before + 1)
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
test('with the guard, a webhook to a non-public address fails as a delivery error', async () => {
|
|
61
|
+
const before = received
|
|
62
|
+
const result = await deliver(createEgressGuard({ guard: true, allowHttp: true }))
|
|
63
|
+
expect(result.ok).toBe(false)
|
|
64
|
+
expect(result.errorMessage).toContain('resolves to the non-public address')
|
|
65
|
+
expect(received).toBe(before)
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
test('with the guard, an http webhook is refused unless http is allowed', async () => {
|
|
69
|
+
const result = await deliver(createEgressGuard({ guard: true, allowlist: ['localhost'] }))
|
|
70
|
+
expect(result.ok).toBe(false)
|
|
71
|
+
expect(result.errorMessage).toContain('Only https:// URLs are allowed')
|
|
72
|
+
})
|
|
73
|
+
|
|
74
|
+
test('with the guard, an allow-listed internal host is delivered', async () => {
|
|
75
|
+
const before = received
|
|
76
|
+
const result = await deliver(createEgressGuard({ guard: true, allowHttp: true, allowlist: ['localhost'] }))
|
|
77
|
+
expect(result.ok).toBe(true)
|
|
78
|
+
expect(received).toBe(before + 1)
|
|
79
|
+
})
|
|
80
|
+
})
|