emailengine-app 2.85.0 → 2.87.0
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/.ncurc.js +24 -6
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +97 -0
- package/DOCKER_DEPLOYMENT.md +2 -1
- package/Dockerfile +16 -3
- package/ENVIRONMENT.md +139 -0
- package/README.md +5 -1
- package/config/default.toml +2 -0
- package/copy-static-files.sh +4 -2
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +4 -3
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +285 -195
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +91 -32
- package/lib/api-routes/blocklist-routes.js +68 -2
- package/lib/api-routes/delivery-test-routes.js +1 -1
- package/lib/api-routes/gateway-routes.js +82 -10
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +3 -3
- package/lib/api-routes/message-routes.js +15 -7
- package/lib/api-routes/oauth2-app-routes.js +15 -8
- package/lib/api-routes/outbox-routes.js +77 -66
- package/lib/api-routes/permission-map.js +55 -6
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +11 -4
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +25 -5
- package/lib/api-routes/template-routes.js +7 -6
- package/lib/api-routes/token-routes.js +11 -5
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +119 -4
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -46
- package/lib/db.js +14 -6
- package/lib/delivery-error.js +6 -0
- package/lib/deprecations.js +270 -0
- package/lib/email-client/base-client.js +134 -158
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +59 -11
- package/lib/email-client/imap/adaptive-idle-store.js +73 -0
- package/lib/email-client/imap/adaptive-idle.js +278 -0
- package/lib/email-client/imap/connection-errors.js +14 -1
- package/lib/email-client/imap/idle-settings.js +31 -5
- package/lib/email-client/imap/listing-diff.js +37 -0
- package/lib/email-client/imap/mailbox.js +380 -227
- package/lib/email-client/imap/subconnection.js +7 -29
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +227 -163
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/outlook-client.js +378 -338
- package/lib/email-client/smtp-pool-manager.js +16 -13
- package/lib/email-client/sync-state-fields.js +19 -0
- package/lib/encrypt.js +157 -41
- package/lib/enum-descriptions.js +3 -1
- package/lib/env-setting-overrides.js +288 -0
- package/lib/export-worker.js +751 -0
- package/lib/export.js +64 -15
- package/lib/field-usage.js +1 -1
- package/lib/gateway.js +17 -1
- package/lib/get-raw-email.js +35 -108
- package/lib/health.js +75 -0
- package/lib/lock-run.js +119 -0
- package/lib/logger-consts.js +48 -0
- package/lib/logger.js +1 -1
- package/lib/lua/z-head-scores.lua +28 -0
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +20 -1
- package/lib/oauth/gmail.js +54 -29
- package/lib/oauth2-apps.js +630 -655
- package/lib/otp.js +66 -0
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/privileged-settings.js +2 -2
- package/lib/queue-browser/definitions.js +11 -0
- package/lib/queue-browser/index.js +68 -19
- package/lib/queue-job-actions.js +18 -1
- package/lib/queue-retention.js +48 -12
- package/lib/queue-stats.js +11 -2
- package/lib/read-env-value.js +3 -0
- package/lib/redis-memory-warnings.js +99 -0
- package/lib/redis-reconnect.js +29 -0
- package/lib/request-timing.js +23 -0
- package/lib/respawn-backoff.js +35 -0
- package/lib/rewrite-text-nodes.js +19 -59
- package/lib/schemas.js +225 -41
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/swagger-options.js +2 -2
- package/lib/thread-diagnostics.js +18 -1
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +4 -3
- package/lib/tools.js +8 -41
- package/lib/ui-routes/admin-config-routes.js +64 -90
- package/lib/ui-routes/admin-entities-routes.js +2 -14
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/outlook-subscription-view.js +1 -1
- package/lib/ui-routes/overridable-fields.js +84 -0
- package/lib/ui-routes/queue-routes.js +8 -5
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/utils/decode-headers.js +3 -12
- package/lib/utils/filter-empty.js +20 -0
- package/lib/utils/int-setting.js +48 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/web-safe-html.js +18 -105
- package/lib/webhook-delivery.js +461 -0
- package/lib/webhook-failures.js +132 -0
- package/lib/webhook-request.js +29 -1
- package/lib/webhook-routing.js +30 -1
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +59 -41
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +28 -26
- package/sbom.json +600 -678
- package/server.js +149 -76
- package/static/css/flyonui.css +1 -1
- package/static/js/ace/ace.js +1 -1
- package/static/js/ee-client.js +650 -196
- package/static/licenses.html +49 -59
- package/translations/messages.pot +26 -26
- package/views/config/security.hbs +22 -0
- package/views/config/service.hbs +44 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/layout/app.hbs +9 -6
- package/views/legal.hbs +8 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/workers/api.js +112 -37
- package/workers/export.js +16 -631
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/webhooks.js +18 -432
- package/lib/email-client/outlook-fallback-poll.js +0 -30
|
@@ -0,0 +1,461 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The notify queue's job processor: decides whether and where a queued webhook event is delivered,
|
|
4
|
+
// sends it, and records the outcome. It used to be written inline in workers/webhooks.js, which a
|
|
5
|
+
// test cannot import (requiring it starts a BullMQ worker and talks to the parent thread), so its
|
|
6
|
+
// decisions were only tested through the helpers it calls. Everything with a side effect is passed
|
|
7
|
+
// in, see createWebhookProcessor().
|
|
8
|
+
|
|
9
|
+
const { UnrecoverableError, DelayedError } = require('bullmq');
|
|
10
|
+
|
|
11
|
+
const { redactUrlCredentials, splitUrlCredentials } = require('./tools');
|
|
12
|
+
const { sendWebhookRequest, isUnrecoverableWebhookError, baseDeliveryHeaders, signDelivery } = require('./webhook-request');
|
|
13
|
+
const { willBeFinalAttempt } = require('./delivery-error');
|
|
14
|
+
const { penaltyKey, penaltyFor } = require('./webhook-penalty');
|
|
15
|
+
const {
|
|
16
|
+
resolveTargetUrl,
|
|
17
|
+
isDeliverableRoute,
|
|
18
|
+
eventAllowed,
|
|
19
|
+
defaultRouteTakes,
|
|
20
|
+
headerLevels,
|
|
21
|
+
deliveryCustomHeaders,
|
|
22
|
+
isRouteMappingMissing
|
|
23
|
+
} = require('./webhook-routing');
|
|
24
|
+
const { REDIS_PREFIX, ACCOUNT_DELETED_NOTIFY, DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('./consts');
|
|
25
|
+
|
|
26
|
+
// The payload fields of `data` that are logged as they are; anything else only marks it partial
|
|
27
|
+
const LOGGED_DATA_KEYS = new Set(['id', 'uid', 'path', 'messageId']);
|
|
28
|
+
|
|
29
|
+
const getAccountKey = account => `${REDIS_PREFIX}iad:${account}`;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Log context shared by every line about one job
|
|
33
|
+
* @param {Object} job - BullMQ job
|
|
34
|
+
* @returns {Object} Fields to spread into a log entry
|
|
35
|
+
*/
|
|
36
|
+
const jobLogFields = job => ({ action: 'webhook', queue: job.queue.name, job: job.id, event: job.name, account: job.data.account });
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The job payload reduced to what is safe and useful to log: everything except `data`, of which
|
|
40
|
+
* only the identifying fields are kept
|
|
41
|
+
* @param {Object} payload - Job data
|
|
42
|
+
* @returns {Object} Loggable copy
|
|
43
|
+
*/
|
|
44
|
+
function filterLogData(payload) {
|
|
45
|
+
let filteredData = {};
|
|
46
|
+
for (let key of Object.keys(payload)) {
|
|
47
|
+
if (key !== 'data') {
|
|
48
|
+
filteredData[key] = payload[key];
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
let filteredSubData = {};
|
|
53
|
+
let isPartial = false;
|
|
54
|
+
for (let dataKey of Object.keys(payload.data || {})) {
|
|
55
|
+
if (LOGGED_DATA_KEYS.has(dataKey)) {
|
|
56
|
+
filteredSubData[dataKey] = payload.data[dataKey];
|
|
57
|
+
} else {
|
|
58
|
+
isPartial = true;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (isPartial) {
|
|
62
|
+
if (Object.keys(filteredSubData).length) {
|
|
63
|
+
filteredSubData.partial = true;
|
|
64
|
+
} else {
|
|
65
|
+
filteredSubData = true;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
filteredData[key] = filteredSubData;
|
|
69
|
+
}
|
|
70
|
+
return filteredData;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Loads the custom route a job was queued for. Removes `_route` from the payload, so it is never
|
|
75
|
+
* delivered
|
|
76
|
+
* @returns {Promise<Object>} `{ skip }` when nothing is to be sent, otherwise `{ customRoute, customMapping }`
|
|
77
|
+
*/
|
|
78
|
+
async function loadCustomRoute(job, deps) {
|
|
79
|
+
if (!job.data._route || !job.data._route.id) {
|
|
80
|
+
return {};
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
let customRoute = await deps.webhooks.getMeta(job.data._route.id);
|
|
84
|
+
let customMapping = job.data._route.mapping;
|
|
85
|
+
let mappingMissing = isRouteMappingMissing(job.data._route);
|
|
86
|
+
delete job.data._route;
|
|
87
|
+
|
|
88
|
+
if (!isDeliverableRoute(customRoute)) {
|
|
89
|
+
return { skip: true };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
if (mappingMissing) {
|
|
93
|
+
deps.logger.warn({
|
|
94
|
+
msg: 'Custom webhook route has no mapped payload, not sending',
|
|
95
|
+
...jobLogFields(job),
|
|
96
|
+
code: 'missing_mapping',
|
|
97
|
+
route: customRoute.id
|
|
98
|
+
});
|
|
99
|
+
return { skip: true };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
return { customRoute, customMapping };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Parses the account's custom header list. A value that does not parse is ignored, as before
|
|
107
|
+
* @returns {Object[]|undefined} Header entries
|
|
108
|
+
*/
|
|
109
|
+
function parseAccountHeaders(json, job, logger) {
|
|
110
|
+
if (!json) {
|
|
111
|
+
return undefined;
|
|
112
|
+
}
|
|
113
|
+
try {
|
|
114
|
+
return JSON.parse(json);
|
|
115
|
+
} catch (err) {
|
|
116
|
+
// do not log the header values, they may carry authentication secrets
|
|
117
|
+
logger.debug({ msg: 'Failed to parse custom webhook headers', ...jobLogFields(job), jsonLength: json.length, err });
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Delays the job while its target is penalised; see lib/webhook-penalty.js. The attempt count is
|
|
124
|
+
* not spent by the wait
|
|
125
|
+
* @returns {Promise<string|null>} The target's penalty key, for recordFailure()
|
|
126
|
+
* @throws {DelayedError} When the job was moved to the delayed set
|
|
127
|
+
*/
|
|
128
|
+
async function waitOutPenalty(job, token, webhooks, deps) {
|
|
129
|
+
const targetPenaltyKey = penaltyKey(webhooks);
|
|
130
|
+
if (!targetPenaltyKey) {
|
|
131
|
+
return null;
|
|
132
|
+
}
|
|
133
|
+
let remaining = await deps.redis.pttl(targetPenaltyKey);
|
|
134
|
+
if (remaining > 0) {
|
|
135
|
+
deps.logger.debug({
|
|
136
|
+
msg: 'Webhook target is penalised, delaying delivery',
|
|
137
|
+
...jobLogFields(job),
|
|
138
|
+
code: 'target_penalised',
|
|
139
|
+
webhooks: redactUrlCredentials(webhooks),
|
|
140
|
+
delay: remaining
|
|
141
|
+
});
|
|
142
|
+
await job.moveToDelayed(Date.now() + remaining, token);
|
|
143
|
+
throw new DelayedError();
|
|
144
|
+
}
|
|
145
|
+
return targetPenaltyKey;
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/**
|
|
149
|
+
* Decides whether a job is delivered and, if it is, where and with which header lists. Every
|
|
150
|
+
* check that can skip a job runs here, in the order the inline processor ran them
|
|
151
|
+
* @returns {Promise<Object|null>} Delivery plan, or null when the job is completed without sending
|
|
152
|
+
*/
|
|
153
|
+
async function planDelivery(job, token, deps) {
|
|
154
|
+
const { redis, settings, logger, openAccountField } = deps;
|
|
155
|
+
let accountKey = getAccountKey(job.data.account);
|
|
156
|
+
|
|
157
|
+
// Keep the route id reachable for the completed/failed event handlers, which see this same
|
|
158
|
+
// job instance after _route has been deleted from the payload. Stashed before the early
|
|
159
|
+
// returns below so a job that never reaches delivery still reports which route queued it.
|
|
160
|
+
if (job.data._route && job.data._route.id) {
|
|
161
|
+
job.__routeId = job.data._route.id;
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// One round trip for the existence check and the two account fields a delivery may need.
|
|
165
|
+
// The fields are opened where they are used, below.
|
|
166
|
+
let [accountExists, storedWebhooks, storedCustomHeaders] = await redis.hmget(accountKey, 'account', 'webhooks', 'webhooksCustomHeaders');
|
|
167
|
+
if (!accountExists && job.name !== ACCOUNT_DELETED_NOTIFY) {
|
|
168
|
+
logger.debug({ msg: 'Account not found', ...jobLogFields(job), code: 'account_not_found' });
|
|
169
|
+
return null;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
if (!(await settings.get('webhooksEnabled'))) {
|
|
173
|
+
logger.debug({ msg: 'Webhooks are disabled', ...jobLogFields(job), code: 'webhooks_disabled' });
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
let { skip, customRoute, customMapping } = await loadCustomRoute(job, deps);
|
|
178
|
+
if (skip) {
|
|
179
|
+
return null;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
let accountWebhooks = await openAccountField('webhooks', storedWebhooks, job.data.account);
|
|
183
|
+
|
|
184
|
+
// the global setting is only fetched when neither a custom route nor the account override decides the target
|
|
185
|
+
let target = resolveTargetUrl(customRoute && customRoute.targetUrl, accountWebhooks, null);
|
|
186
|
+
if (!target.url) {
|
|
187
|
+
target = resolveTargetUrl(null, null, await settings.get('webhooks'));
|
|
188
|
+
}
|
|
189
|
+
let webhooks = target.url;
|
|
190
|
+
if (!webhooks) {
|
|
191
|
+
// A skipped delivery still reports the job as completed, so without this line a
|
|
192
|
+
// missing target is indistinguishable from a successful delivery - it reads as the
|
|
193
|
+
// receiver being slow rather than as nothing having been sent
|
|
194
|
+
logger.debug({ msg: 'Webhook URL is not set', ...jobLogFields(job), code: 'no_target_url' });
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const targetPenaltyKey = await waitOutPenalty(job, token, webhooks, deps);
|
|
199
|
+
|
|
200
|
+
// Only the header lists that travel to this target are loaded; lib/webhook-routing.js
|
|
201
|
+
// holds the rule and the reasons
|
|
202
|
+
let levels = headerLevels(target.source);
|
|
203
|
+
let accountHeadersJson = levels.includes('account') ? await openAccountField('webhooksCustomHeaders', storedCustomHeaders, job.data.account) : null;
|
|
204
|
+
let accountCustomHeaders = parseAccountHeaders(accountHeadersJson, job, logger);
|
|
205
|
+
|
|
206
|
+
if (!customRoute) {
|
|
207
|
+
// custom routes have their own mappings; the default route follows webhookEvents and
|
|
208
|
+
// inboxNewOnly, by the same rule pushToQueue() applied before queueing
|
|
209
|
+
let { webhookEvents, inboxNewOnly } = await settings.getMulti('webhookEvents', 'inboxNewOnly');
|
|
210
|
+
if (!defaultRouteTakes(job.name, job.data, { webhookEvents, inboxNewOnly })) {
|
|
211
|
+
logger.trace({
|
|
212
|
+
msg: 'Webhook event not taken by the default route',
|
|
213
|
+
...jobLogFields(job),
|
|
214
|
+
code: eventAllowed(webhookEvents, job.name) ? 'inbox_new_only' : 'event_not_whitelisted',
|
|
215
|
+
webhookEvents
|
|
216
|
+
});
|
|
217
|
+
return null;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return {
|
|
222
|
+
accountKey,
|
|
223
|
+
customRoute,
|
|
224
|
+
customMapping,
|
|
225
|
+
accountWebhooks,
|
|
226
|
+
target,
|
|
227
|
+
// never log the raw target URL, it may embed basic auth credentials
|
|
228
|
+
redactedWebhooks: redactUrlCredentials(webhooks),
|
|
229
|
+
accountCustomHeaders,
|
|
230
|
+
targetPenaltyKey
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
/**
|
|
235
|
+
* Builds the request: the body, and every header that goes with it, the signature last
|
|
236
|
+
* @returns {Promise<Object>} `{ url, headers, body }`
|
|
237
|
+
*/
|
|
238
|
+
async function buildRequest(job, plan, deps) {
|
|
239
|
+
let { url: parsed, authorization } = splitUrlCredentials(plan.target.url);
|
|
240
|
+
let headers = Object.assign(baseDeliveryHeaders(authorization), {
|
|
241
|
+
'X-EE-Wh-Id': (job.id || '').toString(),
|
|
242
|
+
'X-EE-Wh-Attempts-Made': (job.attemptsMade || 0).toString(),
|
|
243
|
+
'X-EE-Wh-Queued-Time': Math.round(Math.max(0, (Date.now() - job.timestamp) / 1000)) + 's'
|
|
244
|
+
});
|
|
245
|
+
|
|
246
|
+
if (plan.customRoute) {
|
|
247
|
+
headers['X-EE-Wh-Custom-Route'] = plan.customRoute.id;
|
|
248
|
+
}
|
|
249
|
+
Object.assign(
|
|
250
|
+
headers,
|
|
251
|
+
deliveryCustomHeaders(plan.target.source, {
|
|
252
|
+
route: plan.customRoute && plan.customRoute.customHeaders,
|
|
253
|
+
global: headerLevels(plan.target.source).includes('global') ? await deps.settings.get('webhooksCustomHeaders') : null,
|
|
254
|
+
account: plan.accountCustomHeaders
|
|
255
|
+
})
|
|
256
|
+
);
|
|
257
|
+
|
|
258
|
+
let webhookPayload = plan.customMapping || job.data;
|
|
259
|
+
if (webhookPayload.eventId) {
|
|
260
|
+
headers['X-EE-Wh-Event-Id'] = webhookPayload.eventId;
|
|
261
|
+
webhookPayload.eventId = undefined; // not included in JSON
|
|
262
|
+
}
|
|
263
|
+
let body = Buffer.from(JSON.stringify(webhookPayload));
|
|
264
|
+
|
|
265
|
+
// Explicitly set Content-Length to prevent undici mismatch errors
|
|
266
|
+
headers['Content-Length'] = body.length.toString();
|
|
267
|
+
|
|
268
|
+
signDelivery(headers, body, await deps.getServiceSecret());
|
|
269
|
+
|
|
270
|
+
return { url: parsed.toString(), headers, body };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Writes the error flag of whichever level decided the target: the custom route, the account
|
|
275
|
+
* override or the global setting. An empty flag clears it, by removing the field: every successful
|
|
276
|
+
* delivery clears, and a removal of a field that is not there changes nothing, so Redis neither
|
|
277
|
+
* writes nor replicates it. Never throws, a missed flag write must not change the outcome of the
|
|
278
|
+
* delivery
|
|
279
|
+
*/
|
|
280
|
+
async function writeErrorFlag(plan, flag, deps) {
|
|
281
|
+
try {
|
|
282
|
+
if (plan.customRoute || plan.accountWebhooks) {
|
|
283
|
+
const [key, field] = plan.customRoute
|
|
284
|
+
? [deps.webhooks.getWebhooksContentKey(), `${plan.customRoute.id}:webhookErrorFlag`]
|
|
285
|
+
: [plan.accountKey, 'webhookErrorFlag'];
|
|
286
|
+
await (flag ? deps.redis.hset(key, field, JSON.stringify(flag)) : deps.redis.hdel(key, field));
|
|
287
|
+
} else if (flag) {
|
|
288
|
+
await deps.settings.set('webhookErrorFlag', flag);
|
|
289
|
+
} else {
|
|
290
|
+
await deps.settings.clear('webhookErrorFlag');
|
|
291
|
+
}
|
|
292
|
+
} catch (err) {
|
|
293
|
+
// ignore
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/**
|
|
298
|
+
* Records a failed attempt everywhere it is read back: the target penalty, the job's progress
|
|
299
|
+
* field (for the queue browser), the log, the error flag and the metrics
|
|
300
|
+
*/
|
|
301
|
+
async function recordFailure(job, plan, request, err, duration, deps) {
|
|
302
|
+
const { redis, logger } = deps;
|
|
303
|
+
|
|
304
|
+
// egress and redirect failures are thrown as UnrecoverableError, so they are final as well
|
|
305
|
+
let isFinalAttempt = willBeFinalAttempt(job) || isUnrecoverableWebhookError(err);
|
|
306
|
+
|
|
307
|
+
// A target that held the attempt until it timed out is penalised so the next deliveries to
|
|
308
|
+
// it do not each cost the same wait
|
|
309
|
+
let penalty = penaltyFor(err, deps.timeout || DEFAULT_WEBHOOK_REQUEST_TIMEOUT);
|
|
310
|
+
if (penalty && plan.targetPenaltyKey) {
|
|
311
|
+
try {
|
|
312
|
+
await redis.set(plan.targetPenaltyKey, '1', 'PX', penalty);
|
|
313
|
+
} catch (penaltyErr) {
|
|
314
|
+
// a missed penalty costs the queue one more timeout, nothing else
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// BullMQ keeps only the message of a failure on the job. The code and the HTTP status
|
|
319
|
+
// are what explain it, so they are recorded the way the submit worker records its own
|
|
320
|
+
// delivery errors, for the queue browser to read back
|
|
321
|
+
try {
|
|
322
|
+
await job.updateProgress({ status: 'error', error: { message: err.message, code: err.code, statusCode: err.statusCode }, duration });
|
|
323
|
+
} catch (progressErr) {
|
|
324
|
+
// ignore
|
|
325
|
+
}
|
|
326
|
+
|
|
327
|
+
logger[isFinalAttempt ? 'error' : 'warn']({
|
|
328
|
+
msg: 'Failed posting webhook',
|
|
329
|
+
...jobLogFields(job),
|
|
330
|
+
code: 'result_fail',
|
|
331
|
+
webhooks: plan.redactedWebhooks,
|
|
332
|
+
requestBodySize: request.body.length,
|
|
333
|
+
accountWebhooks: !!plan.accountWebhooks,
|
|
334
|
+
route: plan.customRoute && plan.customRoute.id,
|
|
335
|
+
err
|
|
336
|
+
});
|
|
337
|
+
|
|
338
|
+
await writeErrorFlag(
|
|
339
|
+
plan,
|
|
340
|
+
{
|
|
341
|
+
event: job.name,
|
|
342
|
+
message: err.message,
|
|
343
|
+
time: Date.now(),
|
|
344
|
+
// stored without credentials: the flag is read back through the webhook route
|
|
345
|
+
// listing, the account page and the settings API. A route's own URL is the target
|
|
346
|
+
url: plan.redactedWebhooks,
|
|
347
|
+
code: err.code,
|
|
348
|
+
statusCode: err.statusCode
|
|
349
|
+
},
|
|
350
|
+
deps
|
|
351
|
+
);
|
|
352
|
+
|
|
353
|
+
deps.metrics('webhooks', 'inc', { event: job.name, status: 'fail' });
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Sends a planned delivery and records the outcome
|
|
358
|
+
* @returns {Promise<Object>} The job's return value, stored by BullMQ
|
|
359
|
+
*/
|
|
360
|
+
async function deliver(job, plan, deps) {
|
|
361
|
+
const { logger } = deps;
|
|
362
|
+
|
|
363
|
+
// the redacted target stays reachable for the failed event handler
|
|
364
|
+
job.__redactedTargetUrl = plan.redactedWebhooks;
|
|
365
|
+
|
|
366
|
+
logger.trace({
|
|
367
|
+
msg: 'Processing webhook',
|
|
368
|
+
...jobLogFields(job),
|
|
369
|
+
code: 'processing',
|
|
370
|
+
webhooks: plan.redactedWebhooks,
|
|
371
|
+
accountWebhooks: !!plan.accountWebhooks,
|
|
372
|
+
data: filterLogData(job.data),
|
|
373
|
+
route: plan.customRoute && plan.customRoute.id
|
|
374
|
+
});
|
|
375
|
+
|
|
376
|
+
let request = await buildRequest(job, plan, deps);
|
|
377
|
+
|
|
378
|
+
let start = Date.now();
|
|
379
|
+
let duration;
|
|
380
|
+
try {
|
|
381
|
+
let status;
|
|
382
|
+
try {
|
|
383
|
+
status = await sendWebhookRequest(deps.fetch, request.url, {
|
|
384
|
+
method: 'post',
|
|
385
|
+
body: request.body,
|
|
386
|
+
headers: request.headers,
|
|
387
|
+
dispatcher: deps.dispatcher,
|
|
388
|
+
timeout: deps.timeout,
|
|
389
|
+
validateTarget: deps.validateTarget
|
|
390
|
+
});
|
|
391
|
+
duration = Date.now() - start;
|
|
392
|
+
} catch (err) {
|
|
393
|
+
duration = Date.now() - start;
|
|
394
|
+
throw err.cause || err;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
logger.trace({
|
|
398
|
+
msg: 'Webhook posted',
|
|
399
|
+
...jobLogFields(job),
|
|
400
|
+
code: 'result_success',
|
|
401
|
+
webhooks: plan.redactedWebhooks,
|
|
402
|
+
requestBodySize: request.body.length,
|
|
403
|
+
accountWebhooks: !!plan.accountWebhooks,
|
|
404
|
+
status,
|
|
405
|
+
route: plan.customRoute && plan.customRoute.id
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
await writeErrorFlag(plan, null, deps);
|
|
409
|
+
deps.metrics('webhooks', 'inc', { event: job.name, status: 'success' });
|
|
410
|
+
|
|
411
|
+
// Stored by BullMQ as the job's return value in the same write that completes it, so
|
|
412
|
+
// a retained completed job shows what the endpoint answered and how long it took
|
|
413
|
+
return { status: 'delivered', statusCode: status, duration };
|
|
414
|
+
} catch (err) {
|
|
415
|
+
await recordFailure(job, plan, request, err, duration, deps);
|
|
416
|
+
|
|
417
|
+
// Spending the remaining attempts on an unrecoverable failure only delays the operator
|
|
418
|
+
// seeing the real reason in the error flag. Fail the job now and keep the message.
|
|
419
|
+
if (isUnrecoverableWebhookError(err)) {
|
|
420
|
+
// UnrecoverableError copies the message only, and the failed-event handler logs the
|
|
421
|
+
// error it is given, so carry the code over or that log loses the actual reason
|
|
422
|
+
let unrecoverableErr = new UnrecoverableError(err.message);
|
|
423
|
+
unrecoverableErr.code = err.code;
|
|
424
|
+
throw unrecoverableErr;
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
throw err;
|
|
428
|
+
} finally {
|
|
429
|
+
if (duration) {
|
|
430
|
+
deps.metrics('webhookReq', 'observe', duration);
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/**
|
|
436
|
+
* Creates the notify queue's job processor
|
|
437
|
+
* @param {Object} deps
|
|
438
|
+
* @param {Object} deps.redis - ioredis client (hmget, pttl, set, hset)
|
|
439
|
+
* @param {Object} deps.settings - lib/settings (get, getMulti, set, clear)
|
|
440
|
+
* @param {Object} deps.webhooks - lib/webhooks instance (getMeta, getWebhooksContentKey)
|
|
441
|
+
* @param {Object} deps.logger - pino logger
|
|
442
|
+
* @param {Function} deps.metrics - (key, method, ...args) metrics reporter
|
|
443
|
+
* @param {Function} deps.openAccountField - (field, value, account) decrypts an account field
|
|
444
|
+
* @param {Function} deps.getServiceSecret - Resolves the HMAC signing secret
|
|
445
|
+
* @param {Function} deps.fetch - fetch implementation
|
|
446
|
+
* @param {Object} [deps.dispatcher] - undici dispatcher
|
|
447
|
+
* @param {number|false} [deps.timeout] - Attempt timeout in ms, false for the default
|
|
448
|
+
* @param {Function} [deps.validateTarget] - Egress policy check
|
|
449
|
+
* @returns {Function} async (job, token) => result
|
|
450
|
+
*/
|
|
451
|
+
function createWebhookProcessor(deps) {
|
|
452
|
+
return async function processWebhookJob(job, token) {
|
|
453
|
+
let plan = await planDelivery(job, token, deps);
|
|
454
|
+
if (!plan) {
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
return await deliver(job, plan, deps);
|
|
458
|
+
};
|
|
459
|
+
}
|
|
460
|
+
|
|
461
|
+
module.exports = { createWebhookProcessor, filterLogData };
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// The webhook deliveries that failed for good, for the REST API: list them, put one back into the
|
|
4
|
+
// queue, or remove it. The admin queue browser (lib/queue-browser) offers the same over the whole
|
|
5
|
+
// notify queue; this is the failed set only, in the shape an integrator replaying the events a
|
|
6
|
+
// receiver outage cost it needs, and optionally held to one account so a token bound to that
|
|
7
|
+
// account reaches only its own deliveries.
|
|
8
|
+
//
|
|
9
|
+
// A listing carries what a delivery was about (event, account, folder, message, the route that
|
|
10
|
+
// sent it and why it failed), never the event payload itself, which can hold up to notifyTextSize
|
|
11
|
+
// of message text.
|
|
12
|
+
|
|
13
|
+
const { notifyQueue } = require('./db');
|
|
14
|
+
const { QUEUES_BY_NAME, listJobs } = require('./queue-browser');
|
|
15
|
+
const { retryFailedJob, assertJobState, getAccountJob } = require('./queue-job-actions');
|
|
16
|
+
const { statusError } = require('./utils/status-error');
|
|
17
|
+
|
|
18
|
+
const NOTIFY_QUEUE = QUEUES_BY_NAME.get('notify');
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The API form of a failed delivery, from the queue browser's formatted entry
|
|
22
|
+
* @param {Object} entry - Entry from listJobs()
|
|
23
|
+
* @returns {Object}
|
|
24
|
+
*/
|
|
25
|
+
function formatFailedDelivery(entry) {
|
|
26
|
+
return {
|
|
27
|
+
id: entry.id,
|
|
28
|
+
event: entry.event,
|
|
29
|
+
eventId: entry.eventId,
|
|
30
|
+
account: entry.account,
|
|
31
|
+
path: entry.path,
|
|
32
|
+
messageId: entry.messageId,
|
|
33
|
+
route: entry.routeId ? { id: entry.routeId, name: entry.routeName || null } : null,
|
|
34
|
+
created: entry.created,
|
|
35
|
+
failed: entry.finishedOn,
|
|
36
|
+
attemptsMade: entry.attemptsMade,
|
|
37
|
+
attempts: entry.attempts,
|
|
38
|
+
error: entry.failure
|
|
39
|
+
? {
|
|
40
|
+
message: entry.failure.reason,
|
|
41
|
+
code: entry.failure.code,
|
|
42
|
+
statusCode: entry.failure.statusCode,
|
|
43
|
+
permanent: entry.failure.permanent
|
|
44
|
+
}
|
|
45
|
+
: null
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* One page of failed deliveries, most recent first. With an account the failed set is scanned from
|
|
51
|
+
* its head for that account's deliveries, as far as the queue browser scans a filtered listing, and
|
|
52
|
+
* the result says when the scan stopped short of the end.
|
|
53
|
+
*
|
|
54
|
+
* @param {Object} options
|
|
55
|
+
* @param {string} [options.account] - Only deliveries of this account
|
|
56
|
+
* @param {number} [options.page] - Zero-based page
|
|
57
|
+
* @param {number} [options.pageSize] - Entries per page
|
|
58
|
+
* @param {Object} options.logger - Logger instance
|
|
59
|
+
* @returns {Promise<Object>} `{ total, page, pages, scanLimited, deliveries }`
|
|
60
|
+
*/
|
|
61
|
+
async function list(options) {
|
|
62
|
+
const result = await listJobs({
|
|
63
|
+
queue: NOTIFY_QUEUE,
|
|
64
|
+
state: 'failed',
|
|
65
|
+
page: options.page,
|
|
66
|
+
pageSize: options.pageSize,
|
|
67
|
+
account: options.account,
|
|
68
|
+
logger: options.logger
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
return {
|
|
72
|
+
total: result.total,
|
|
73
|
+
page: result.page,
|
|
74
|
+
pages: result.total ? result.pages : 0,
|
|
75
|
+
scanLimited: result.scanLimited,
|
|
76
|
+
deliveries: result.entries.map(formatFailedDelivery)
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Puts a failed delivery back into the queue with a fresh set of attempts.
|
|
82
|
+
*
|
|
83
|
+
* @param {Object} options
|
|
84
|
+
* @param {string} options.id - Job ID
|
|
85
|
+
* @param {string} [options.account] - Account the delivery has to belong to
|
|
86
|
+
* @param {Object} options.logger - Logger instance
|
|
87
|
+
* @returns {Promise<Object|false>} `{ retried: true, id }`, or false when there is no such delivery
|
|
88
|
+
* @throws {Error} 409 NotFailed when the delivery is not in the failed state
|
|
89
|
+
*/
|
|
90
|
+
async function retry(options) {
|
|
91
|
+
const job = await getAccountJob(notifyQueue, options.id, options.account);
|
|
92
|
+
if (!job) {
|
|
93
|
+
return false;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
await assertJobState(job, 'failed', NOTIFY_QUEUE.noun, 'retried');
|
|
97
|
+
await retryFailedJob(job, NOTIFY_QUEUE.noun);
|
|
98
|
+
|
|
99
|
+
options.logger.info({ msg: 'Retrying failed webhook delivery', job: job.id, event: job.name, account: job.data && job.data.account });
|
|
100
|
+
return { retried: true, id: String(job.id) };
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/**
|
|
104
|
+
* Removes a failed delivery from the queue.
|
|
105
|
+
*
|
|
106
|
+
* @param {Object} options
|
|
107
|
+
* @param {string} options.id - Job ID
|
|
108
|
+
* @param {string} [options.account] - Account the delivery has to belong to
|
|
109
|
+
* @param {Object} options.logger - Logger instance
|
|
110
|
+
* @returns {Promise<Object|false>} `{ deleted: true, id }`, or false when there is no such delivery
|
|
111
|
+
* @throws {Error} 409 NotFailed when the delivery is not in the failed state
|
|
112
|
+
*/
|
|
113
|
+
async function del(options) {
|
|
114
|
+
const job = await getAccountJob(notifyQueue, options.id, options.account);
|
|
115
|
+
if (!job) {
|
|
116
|
+
return false;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
await assertJobState(job, 'failed', NOTIFY_QUEUE.noun, 'removed');
|
|
120
|
+
|
|
121
|
+
try {
|
|
122
|
+
await job.remove();
|
|
123
|
+
} catch (err) {
|
|
124
|
+
// retried and picked up by a worker between the check and the removal
|
|
125
|
+
throw statusError('The webhook delivery is being processed and cannot be removed', 'Locked', 409);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
options.logger.info({ msg: 'Removed failed webhook delivery', job: job.id, event: job.name, account: job.data && job.data.account });
|
|
129
|
+
return { deleted: true, id: String(job.id) };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
module.exports = { list, retry, del, formatFailedDelivery };
|
package/lib/webhook-request.js
CHANGED
|
@@ -1,8 +1,36 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
+
const { createHmac } = require('crypto');
|
|
4
|
+
const packageData = require('../package.json');
|
|
3
5
|
const { DEFAULT_WEBHOOK_REQUEST_TIMEOUT } = require('./consts');
|
|
4
6
|
const { readBodyCapped } = require('./egress-fetch');
|
|
5
7
|
|
|
8
|
+
/**
|
|
9
|
+
* The headers every webhook request starts from, a real delivery and a test probe alike
|
|
10
|
+
* @param {string} [authorization] - Basic auth taken from the target URL
|
|
11
|
+
* @returns {Object}
|
|
12
|
+
*/
|
|
13
|
+
function baseDeliveryHeaders(authorization) {
|
|
14
|
+
const headers = {
|
|
15
|
+
'Content-Type': 'application/json',
|
|
16
|
+
'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
|
|
17
|
+
};
|
|
18
|
+
if (authorization) {
|
|
19
|
+
headers.Authorization = authorization;
|
|
20
|
+
}
|
|
21
|
+
return headers;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Signs a request body into X-EE-Wh-Signature, the header a receiver verifies with the service secret
|
|
26
|
+
* @param {Object} headers - Request headers, modified in place
|
|
27
|
+
* @param {Buffer|string} body - The exact bytes that are sent
|
|
28
|
+
* @param {string} secret - The service secret
|
|
29
|
+
*/
|
|
30
|
+
function signDelivery(headers, body, secret) {
|
|
31
|
+
headers['X-EE-Wh-Signature'] = createHmac('sha256', secret).update(body).digest('base64url');
|
|
32
|
+
}
|
|
33
|
+
|
|
6
34
|
// How much of a response body is read before the connection is dropped instead. The body is never
|
|
7
35
|
// used, it is read only so the pooled socket can be reused, and undici inflates a compressed one,
|
|
8
36
|
// so a receiver answering a POST with an endless or a bomb body would otherwise be buffered in
|
|
@@ -121,4 +149,4 @@ function isUnrecoverableWebhookError(err) {
|
|
|
121
149
|
return !!err && (err.code === 'EEGRESSBLOCKED' || err.code === 'EREDIRECTNOTFOLLOWED');
|
|
122
150
|
}
|
|
123
151
|
|
|
124
|
-
module.exports = { sendWebhookRequest, isUnrecoverableWebhookError, MAX_DRAIN_BYTES };
|
|
152
|
+
module.exports = { sendWebhookRequest, isUnrecoverableWebhookError, baseDeliveryHeaders, signDelivery, MAX_DRAIN_BYTES };
|
package/lib/webhook-routing.js
CHANGED
|
@@ -4,7 +4,15 @@
|
|
|
4
4
|
// and the admin account page's routing card resolve targets and gates through the helpers
|
|
5
5
|
// here, so the debug view cannot drift from what the worker actually does.
|
|
6
6
|
|
|
7
|
-
const {
|
|
7
|
+
const {
|
|
8
|
+
MESSAGE_NEW_NOTIFY,
|
|
9
|
+
DEFAULT_WEBHOOK_ATTEMPTS,
|
|
10
|
+
MAX_WEBHOOK_ATTEMPTS,
|
|
11
|
+
DEFAULT_WEBHOOK_RETRY_DELAY,
|
|
12
|
+
MIN_WEBHOOK_RETRY_DELAY,
|
|
13
|
+
MAX_WEBHOOK_RETRY_DELAY
|
|
14
|
+
} = require('./consts');
|
|
15
|
+
const { boundedInt } = require('./utils/int-setting');
|
|
8
16
|
|
|
9
17
|
// Precedence: custom route target, then the per-account webhooks override, then the global
|
|
10
18
|
// webhooks setting. Returns the winning URL and which configuration level provided it.
|
|
@@ -167,7 +175,28 @@ function describeEffectiveRouting(opts) {
|
|
|
167
175
|
};
|
|
168
176
|
}
|
|
169
177
|
|
|
178
|
+
/**
|
|
179
|
+
* The attempts and backoff a webhook delivery job is queued with, from the webhooksDeliveryAttempts
|
|
180
|
+
* and webhooksRetryDelay settings. Read when an event is queued, so a change applies to the events
|
|
181
|
+
* queued after it, never to the deliveries already waiting.
|
|
182
|
+
*
|
|
183
|
+
* @param {Object} [values] - The two settings, as settings.getMulti() returns them
|
|
184
|
+
* @returns {{attempts: number, backoff: Object}} BullMQ job options
|
|
185
|
+
*/
|
|
186
|
+
function webhookRetryPolicy(values) {
|
|
187
|
+
values = values || {};
|
|
188
|
+
return {
|
|
189
|
+
attempts: boundedInt(values.webhooksDeliveryAttempts, DEFAULT_WEBHOOK_ATTEMPTS, 1, MAX_WEBHOOK_ATTEMPTS),
|
|
190
|
+
backoff: {
|
|
191
|
+
type: 'exponential',
|
|
192
|
+
delay: boundedInt(values.webhooksRetryDelay, DEFAULT_WEBHOOK_RETRY_DELAY, MIN_WEBHOOK_RETRY_DELAY, MAX_WEBHOOK_RETRY_DELAY),
|
|
193
|
+
jitter: 0.2 // 20% randomization to prevent thundering herd
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
}
|
|
197
|
+
|
|
170
198
|
module.exports = {
|
|
199
|
+
webhookRetryPolicy,
|
|
171
200
|
resolveTargetUrl,
|
|
172
201
|
isDeliverableRoute,
|
|
173
202
|
eventAllowed,
|