@contember/engine-actions 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 (75) hide show
  1. package/CLAUDE.md +14 -4
  2. package/dist/development/index.cjs +6 -4
  3. package/dist/development/index.cjs.map +1 -1
  4. package/dist/development/index.js +7 -5
  5. package/dist/development/index.js.map +1 -1
  6. package/dist/development/src/dispatch/WebhookFetcher.cjs +6 -1
  7. package/dist/development/src/dispatch/WebhookFetcher.cjs.map +1 -1
  8. package/dist/development/src/dispatch/WebhookFetcher.js +7 -2
  9. package/dist/development/src/dispatch/WebhookFetcher.js.map +1 -1
  10. package/dist/development/src/dispatch/WebhookTargetHandler.cjs +11 -5
  11. package/dist/development/src/dispatch/WebhookTargetHandler.cjs.map +1 -1
  12. package/dist/development/src/dispatch/WebhookTargetHandler.js +11 -5
  13. package/dist/development/src/dispatch/WebhookTargetHandler.js.map +1 -1
  14. package/dist/development/src/dispatch/redactRequestError.cjs +27 -2
  15. package/dist/development/src/dispatch/redactRequestError.cjs.map +1 -1
  16. package/dist/development/src/dispatch/redactRequestError.js +27 -2
  17. package/dist/development/src/dispatch/redactRequestError.js.map +1 -1
  18. package/dist/development/src/dispatch/truncateText.cjs +12 -0
  19. package/dist/development/src/dispatch/truncateText.cjs.map +1 -0
  20. package/dist/development/src/dispatch/truncateText.js +12 -0
  21. package/dist/development/src/dispatch/truncateText.js.map +1 -0
  22. package/dist/development/src/graphql/schema/actions.graphql.cjs +7 -3
  23. package/dist/development/src/graphql/schema/actions.graphql.cjs.map +1 -1
  24. package/dist/development/src/graphql/schema/actions.graphql.js +7 -3
  25. package/dist/development/src/graphql/schema/actions.graphql.js.map +1 -1
  26. package/dist/production/index.cjs +6 -4
  27. package/dist/production/index.cjs.map +1 -1
  28. package/dist/production/index.js +7 -5
  29. package/dist/production/index.js.map +1 -1
  30. package/dist/production/src/dispatch/WebhookFetcher.cjs +6 -1
  31. package/dist/production/src/dispatch/WebhookFetcher.cjs.map +1 -1
  32. package/dist/production/src/dispatch/WebhookFetcher.js +7 -2
  33. package/dist/production/src/dispatch/WebhookFetcher.js.map +1 -1
  34. package/dist/production/src/dispatch/WebhookTargetHandler.cjs +11 -5
  35. package/dist/production/src/dispatch/WebhookTargetHandler.cjs.map +1 -1
  36. package/dist/production/src/dispatch/WebhookTargetHandler.js +11 -5
  37. package/dist/production/src/dispatch/WebhookTargetHandler.js.map +1 -1
  38. package/dist/production/src/dispatch/redactRequestError.cjs +27 -2
  39. package/dist/production/src/dispatch/redactRequestError.cjs.map +1 -1
  40. package/dist/production/src/dispatch/redactRequestError.js +27 -2
  41. package/dist/production/src/dispatch/redactRequestError.js.map +1 -1
  42. package/dist/production/src/dispatch/truncateText.cjs +12 -0
  43. package/dist/production/src/dispatch/truncateText.cjs.map +1 -0
  44. package/dist/production/src/dispatch/truncateText.js +12 -0
  45. package/dist/production/src/dispatch/truncateText.js.map +1 -0
  46. package/dist/production/src/graphql/schema/actions.graphql.cjs +7 -3
  47. package/dist/production/src/graphql/schema/actions.graphql.cjs.map +1 -1
  48. package/dist/production/src/graphql/schema/actions.graphql.js +7 -3
  49. package/dist/production/src/graphql/schema/actions.graphql.js.map +1 -1
  50. package/dist/tests/cases/unit/truncateText.test.d.ts +2 -0
  51. package/dist/tests/cases/unit/truncateText.test.d.ts.map +1 -0
  52. package/dist/tests/cases/unit/webhookEgress.test.d.ts +2 -0
  53. package/dist/tests/cases/unit/webhookEgress.test.d.ts.map +1 -0
  54. package/dist/tests/tsconfig.tsbuildinfo +1 -1
  55. package/dist/types/dispatch/WebhookFetcher.d.ts +7 -2
  56. package/dist/types/dispatch/WebhookFetcher.d.ts.map +1 -1
  57. package/dist/types/dispatch/WebhookTargetHandler.d.ts.map +1 -1
  58. package/dist/types/dispatch/redactRequestError.d.ts +3 -2
  59. package/dist/types/dispatch/redactRequestError.d.ts.map +1 -1
  60. package/dist/types/dispatch/truncateText.d.ts +6 -0
  61. package/dist/types/dispatch/truncateText.d.ts.map +1 -0
  62. package/dist/types/graphql/schema/actions.graphql.d.ts.map +1 -1
  63. package/dist/types/index.d.ts.map +1 -1
  64. package/dist/types/tsconfig.tsbuildinfo +1 -1
  65. package/package.json +17 -18
  66. package/src/dispatch/WebhookFetcher.ts +11 -3
  67. package/src/dispatch/WebhookTargetHandler.ts +15 -6
  68. package/src/dispatch/redactRequestError.ts +37 -4
  69. package/src/dispatch/truncateText.ts +13 -0
  70. package/src/graphql/schema/actions.graphql.ts +6 -4
  71. package/src/index.ts +6 -4
  72. package/tests/cases/unit/redactRequestError.test.ts +21 -0
  73. package/tests/cases/unit/truncateText.test.ts +25 -0
  74. package/tests/cases/unit/webhookEgress.test.ts +80 -0
  75. package/tests/cases/unit/webhookHandler.test.ts +133 -0
package/package.json CHANGED
@@ -22,27 +22,26 @@
22
22
  }
23
23
  },
24
24
  "dependencies": {
25
- "@contember/authorization": "2.2.0-alpha.17",
26
- "@contember/database": "2.2.0-alpha.17",
27
- "@contember/database-migrations": "2.2.0-alpha.17",
28
- "@contember/engine-common": "2.2.0-alpha.17",
29
- "@contember/engine-content-api": "2.2.0-alpha.17",
30
- "@contember/engine-http": "2.2.0-alpha.17",
31
- "@contember/engine-plugins": "2.2.0-alpha.17",
32
- "@contember/engine-system-api": "2.2.0-alpha.17",
33
- "@contember/engine-tenant-api": "2.2.0-alpha.17",
34
- "@contember/graphql-utils": "2.2.0-alpha.17",
35
- "@contember/logger": "2.2.0-alpha.17",
36
- "@contember/schema": "2.2.0-alpha.17",
37
- "@contember/schema-utils": "2.2.0-alpha.17",
38
- "@contember/telemetry": "2.2.0-alpha.17",
39
- "@contember/typesafe": "2.2.0-alpha.17",
25
+ "@contember/authorization": "2.2.0-alpha.19",
26
+ "@contember/database": "2.2.0-alpha.19",
27
+ "@contember/database-migrations": "2.2.0-alpha.19",
28
+ "@contember/engine-common": "2.2.0-alpha.19",
29
+ "@contember/engine-content-api": "2.2.0-alpha.19",
30
+ "@contember/engine-http": "2.2.0-alpha.19",
31
+ "@contember/engine-plugins": "2.2.0-alpha.19",
32
+ "@contember/engine-system-api": "2.2.0-alpha.19",
33
+ "@contember/engine-tenant-api": "2.2.0-alpha.19",
34
+ "@contember/graphql-utils": "2.2.0-alpha.19",
35
+ "@contember/logger": "2.2.0-alpha.19",
36
+ "@contember/schema": "2.2.0-alpha.19",
37
+ "@contember/schema-utils": "2.2.0-alpha.19",
38
+ "@contember/telemetry": "2.2.0-alpha.19",
39
+ "@contember/typesafe": "2.2.0-alpha.19",
40
40
  "@graphql-tools/schema": "^10.0.31",
41
- "graphql-tag": "^2.12.6",
42
41
  "prom-client": "^12.0.0"
43
42
  },
44
43
  "devDependencies": {
45
- "@contember/database-tester": "2.2.0-alpha.17",
44
+ "@contember/database-tester": "2.2.0-alpha.19",
46
45
  "@types/bun": "^1.3.10",
47
46
  "@types/ws": "^8.18.1",
48
47
  "graphql": "^16.13.1"
@@ -52,7 +51,7 @@
52
51
  "pg": "^8.20.0"
53
52
  },
54
53
  "type": "module",
55
- "version": "2.2.0-alpha.17",
54
+ "version": "2.2.0-alpha.19",
56
55
  "repository": {
57
56
  "type": "git",
58
57
  "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: RequestInit): Promise<FetcherResponse>
12
+ fetch(url: string, init: EgressRequestInit): Promise<FetcherResponse>
11
13
  }
12
14
 
13
15
  export class WebhookFetcherNative implements WebhookFetcher {
14
- async fetch(url: string, init: RequestInit): Promise<FetcherResponse> {
15
- const response = await fetch(url, init)
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)
@@ -7,8 +7,12 @@ 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
9
  import { redactRequestError } from './redactRequestError.js'
10
+ import { truncateText } from './truncateText.js'
10
11
 
11
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
12
16
 
13
17
  const ResponseType = Typesafe.noExtraProps(Typesafe.object({
14
18
  failures: Typesafe.array(
@@ -121,6 +125,7 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
121
125
  events,
122
126
  target,
123
127
  logger,
128
+ secrets: request.secrets,
124
129
  })
125
130
  } catch (e) {
126
131
  // Request errors may quote the resolved URL or a header value, so only a redacted reason is logged and stored.
@@ -140,24 +145,28 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
140
145
  return events.map(it => ({ target, row: it, result: { durationMs, ...eventResponseFactory(it) } }))
141
146
  }
142
147
 
143
- private createResponseFactory({ response, events, target, logger }: {
148
+ private createResponseFactory({ response, events, target, logger, secrets }: {
144
149
  response: FetcherResponse
145
150
  events: EventRow[]
146
151
  target: Actions.WebhookTarget
147
152
  logger: Logger
153
+ secrets: ReadonlySet<string>
148
154
  }): EventResponseFactory {
155
+ const storedResponse = truncateText(response.responseText, STORED_RESPONSE_MAX_LENGTH)
149
156
  if (!response.ok) {
150
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.
151
159
  logger.warn('Webhook target responded with an error status', {
152
160
  target: target.name,
153
161
  status: response.status,
154
162
  statusText: response.statusText,
163
+ response: truncateText(redactRequestError(response.responseText, secrets), LOGGED_RESPONSE_MAX_LENGTH),
155
164
  events: events.map(it => it.id),
156
165
  })
157
166
  return () => ({
158
167
  ok: false,
159
168
  code: response.status,
160
- response: response.responseText,
169
+ response: storedResponse,
161
170
  errorMessage: response.statusText,
162
171
  })
163
172
  }
@@ -196,14 +205,14 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
196
205
  return () => ({
197
206
  ok: false,
198
207
  code: response.status,
199
- response: response.responseText,
208
+ response: storedResponse,
200
209
  errorMessage: 'Invalid response: undefined events IDs: ' + missingEvents.join('; '),
201
210
  })
202
211
  }
203
212
 
204
213
  const failedIds = events.filter(it => failedEvents[it.id]).map(it => it.id)
205
214
  if (failedIds.length) {
206
- // Per-event errors come from the target's payload and stay in the event log, not here.
215
+ // Per-event errors come from a 2xx payload, which stays in the event log; only an error-status body is logged.
207
216
  logger.warn('Webhook target reported failed events', {
208
217
  target: target.name,
209
218
  status: response.status,
@@ -222,7 +231,7 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
222
231
  }
223
232
  }
224
233
  } catch (e: any) {
225
- // The parser message quotes the offending payload, so it stays in the event log only.
234
+ // The parser message quotes a 2xx payload, so it stays in the event log; only an error-status body is logged.
226
235
  logger.warn('Webhook target returned a malformed response', {
227
236
  target: target.name,
228
237
  status: response.status,
@@ -231,7 +240,7 @@ export class WebhookTargetHandler implements InvokeHandler<Actions.WebhookTarget
231
240
  return () => ({
232
241
  ok: false,
233
242
  code: response.status,
234
- response: response.responseText,
243
+ response: storedResponse,
235
244
  errorMessage: 'Invalid response: ' + e.message,
236
245
  })
237
246
  }
@@ -7,16 +7,49 @@ const redactedMarker = '[redacted]'
7
7
  // fetch strips HTTP whitespace around a header value before quoting it in an error
8
8
  const trimHttpWhitespace = (value: string): string => value.replace(/^[\t\n\r ]+/, '').replace(/[\t\n\r ]+$/, '')
9
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
+
10
41
  /**
11
- * Removes what may carry a credential from a message about a failed webhook request: every occurrence of the given secrets,
12
- * also with surrounding HTTP whitespace stripped, and then the userinfo, path, query and fragment of every URL it still quotes.
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.
13
45
  * The scheme, host and port of such a URL stay for diagnostics.
14
46
  */
15
47
  export const redactRequestError = (message: string, secrets: Iterable<string>): string => {
16
48
  const variants = new Set<string>()
17
49
  for (const secret of secrets) {
18
- variants.add(secret)
19
- variants.add(trimHttpWhitespace(secret))
50
+ for (const variant of variantsOf(secret)) {
51
+ variants.add(variant)
52
+ }
20
53
  }
21
54
  // the longest first, so a secret containing a shorter one is not left partly visible
22
55
  const sortedSecrets = [...variants].filter(it => it !== '').sort((a, b) => b.length - a.length)
@@ -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
+ }
@@ -1,7 +1,7 @@
1
- import { gql } from 'graphql-tag'
2
- import { DocumentNode } from 'graphql'
1
+ import { DocumentNode, parse } from 'graphql'
3
2
 
4
- export const schema: DocumentNode = gql`
3
+ export const schema: DocumentNode = parse(
4
+ /* GraphQL */ `
5
5
  scalar DateTime
6
6
  scalar Json
7
7
  scalar UUID
@@ -114,4 +114,6 @@ export const schema: DocumentNode = gql`
114
114
  ENVIRONMENT
115
115
  }
116
116
 
117
- `
117
+ `,
118
+ { noLocation: true },
119
+ )
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 { WebhookFetcherNative } from './dispatch/WebhookFetcher.js'
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 webhookTargetHandler = new WebhookTargetHandler(new WebhookFetcherNative(), tracer, {
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
  )
@@ -36,6 +36,27 @@ test('redacts a secret quoted without its surrounding whitespace', () => {
36
36
  .toBe('Headers.append: "[redacted]" is an invalid header value.')
37
37
  })
38
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
+
39
60
  test('scans a long message without a URL in linear time', () => {
40
61
  const start = performance.now()
41
62
  expect(redactRequestError('a-'.repeat(100_000), [])).toHaveLength(200_000)
@@ -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
+ })
@@ -364,10 +364,118 @@ describe('webhook response', () => {
364
364
  target: 'test_target',
365
365
  status: 500,
366
366
  statusText: 'Err',
367
+ response: 'Failed to something',
367
368
  events: [event1.id, event2.id],
368
369
  })
369
370
  })
370
371
 
372
+ test('a long error body is cut short in the log and in the stored attempt', async () => {
373
+ const testLoggerHandler = new TestLoggerHandler()
374
+ const responseText = 'a'.repeat(10_000)
375
+ const webhookHandler = createHandler({
376
+ fetch: () =>
377
+ Promise.resolve({
378
+ ok: false,
379
+ headers: new Headers(),
380
+ responseText,
381
+ status: 502,
382
+ statusText: 'Bad Gateway',
383
+ }),
384
+ })
385
+ const target: Actions.AnyTarget = { name: 'test_target', type: 'webhook', url: 'http://localhost' }
386
+ const event = createTestEvent(0)
387
+
388
+ const [handled] = await webhookHandler.handle({ logger: createLogger(testLoggerHandler), target, events: [event], variables: {} })
389
+
390
+ assert.equal(handled.result.response, `${'a'.repeat(4_096)}… [truncated, 10000 characters in total]`)
391
+ const warnings = testLoggerHandler.messages.filter(it => it.level.name === 'warn')
392
+ assert.equal(warnings.length, 1)
393
+ assert.equal(warnings[0].ownAttributes.response, `${'a'.repeat(500)}… [truncated, 10000 characters in total]`)
394
+ })
395
+
396
+ test('an error body echoing the request is logged without its credentials', async () => {
397
+ const testLoggerHandler = new TestLoggerHandler()
398
+ const webhookHandler = createHandler({
399
+ fetch: () =>
400
+ Promise.resolve({
401
+ ok: false,
402
+ headers: new Headers(),
403
+ responseText: 'Unauthorized: Bearer secret-token for https://hooks.example.com/p/secret-path',
404
+ status: 401,
405
+ statusText: 'Unauthorized',
406
+ }),
407
+ })
408
+ const target: Actions.AnyTarget = {
409
+ name: 'test_target',
410
+ type: 'webhook',
411
+ url: 'https://hooks.example.com/p/{{path}}',
412
+ headers: { Authorization: 'Bearer {{token}}' },
413
+ }
414
+
415
+ await webhookHandler.handle({
416
+ logger: createLogger(testLoggerHandler),
417
+ target,
418
+ events: [createTestEvent(0)],
419
+ variables: { path: 'secret-path', token: 'secret-token' },
420
+ })
421
+
422
+ const warnings = testLoggerHandler.messages.filter(it => it.level.name === 'warn')
423
+ assert.equal(warnings.length, 1)
424
+ assert.equal(warnings[0].ownAttributes.response, 'Unauthorized: [redacted] for [redacted]')
425
+ })
426
+
427
+ test('an error body quoting the path of a target URL with a static token is logged without it', async () => {
428
+ const testLoggerHandler = new TestLoggerHandler()
429
+ const webhookHandler = createHandler({
430
+ fetch: () =>
431
+ Promise.resolve({
432
+ ok: false,
433
+ headers: new Headers(),
434
+ responseText: 'Cannot POST /services/T0/B0/static-token',
435
+ status: 404,
436
+ statusText: 'Not Found',
437
+ }),
438
+ })
439
+ const target: Actions.AnyTarget = { name: 'test_target', type: 'webhook', url: 'https://hooks.example.com/services/T0/B0/static-token' }
440
+
441
+ await webhookHandler.handle({ logger: createLogger(testLoggerHandler), target, events: [createTestEvent(0)], variables: {} })
442
+
443
+ const warnings = testLoggerHandler.messages.filter(it => it.level.name === 'warn')
444
+ assert.equal(warnings.length, 1)
445
+ assert.equal(warnings[0].ownAttributes.response, 'Cannot POST [redacted]')
446
+ })
447
+
448
+ test('an error body is redacted before it is cut, so a secret across the cut does not leak in part', async () => {
449
+ const testLoggerHandler = new TestLoggerHandler()
450
+ const webhookHandler = createHandler({
451
+ fetch: () =>
452
+ Promise.resolve({
453
+ ok: false,
454
+ headers: new Headers(),
455
+ responseText: `${'x'.repeat(495)}secret-token`,
456
+ status: 401,
457
+ statusText: 'Unauthorized',
458
+ }),
459
+ })
460
+ const target: Actions.AnyTarget = {
461
+ name: 'test_target',
462
+ type: 'webhook',
463
+ url: 'https://hooks.example.com',
464
+ headers: { Authorization: '{{token}}' },
465
+ }
466
+
467
+ await webhookHandler.handle({
468
+ logger: createLogger(testLoggerHandler),
469
+ target,
470
+ events: [createTestEvent(0)],
471
+ variables: { token: 'secret-token' },
472
+ })
473
+
474
+ const warnings = testLoggerHandler.messages.filter(it => it.level.name === 'warn')
475
+ assert.equal(warnings.length, 1)
476
+ assert.equal(warnings[0].ownAttributes.response, `${'x'.repeat(495)}[reda… [truncated, 505 characters in total]`)
477
+ })
478
+
371
479
  test('invalid partial response', async () => {
372
480
  const testLoggerHandler = new TestLoggerHandler()
373
481
  const logger = createLogger(testLoggerHandler)
@@ -439,6 +547,31 @@ describe('webhook response', () => {
439
547
  })
440
548
  })
441
549
 
550
+ test('a long malformed response is capped in the stored attempt', async () => {
551
+ const responseText = `{"failures": ${'x'.repeat(10_000)}`
552
+ const webhookHandler = createHandler({
553
+ fetch: () =>
554
+ Promise.resolve({
555
+ ok: true,
556
+ headers: new Headers([['content-type', 'application/json']]),
557
+ responseText,
558
+ status: 200,
559
+ statusText: 'OK',
560
+ }),
561
+ })
562
+ const target: Actions.AnyTarget = { name: 'test_target', type: 'webhook', url: 'http://localhost' }
563
+
564
+ const [handled] = await webhookHandler.handle({
565
+ logger: createLogger(new TestLoggerHandler()),
566
+ target,
567
+ events: [createTestEvent(0)],
568
+ variables: {},
569
+ })
570
+
571
+ assert.equal(handled.result.ok, false)
572
+ assert.equal(handled.result.response, `${responseText.slice(0, 4_096)}… [truncated, ${responseText.length} characters in total]`)
573
+ })
574
+
442
575
  test('response naming events outside the batch', async () => {
443
576
  const testLoggerHandler = new TestLoggerHandler()
444
577
  const logger = createLogger(testLoggerHandler)