emailengine-app 2.87.1 → 2.88.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/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +31 -0
- package/ENVIRONMENT.md +26 -23
- package/LICENSE_EMAILENGINE.txt +20 -12
- package/app.json +3 -3
- package/bin/emailengine.js +7 -11
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +48 -10
- package/lib/account.js +69 -49
- package/lib/admin-password.js +85 -0
- package/lib/api-routes/license-routes.js +9 -0
- package/lib/api-token-auth.js +21 -5
- package/lib/calendar-event.js +15 -3
- package/lib/consts.js +5 -0
- package/lib/db.js +1 -0
- package/lib/dbsc/index.js +292 -0
- package/lib/dbsc/jwt.js +157 -0
- package/lib/dbsc/protocol.js +132 -0
- package/lib/dbsc/store.js +136 -0
- package/lib/email-client/base-client.js +36 -15
- package/lib/email-client/gmail-client.js +20 -6
- package/lib/email-client/imap/connection-errors.js +30 -1
- package/lib/email-client/imap/session-expiry.js +83 -0
- package/lib/email-client/imap-client.js +12 -2
- package/lib/email-client/smtp-pool-manager.js +66 -8
- package/lib/export.js +147 -22
- package/lib/graph-notifications.js +60 -0
- package/lib/imap-proxy-auth.js +52 -18
- package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
- package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
- package/lib/imapproxy/imap-server.js +10 -1
- package/lib/imapproxy/proxy-handoff.js +100 -5
- package/lib/license-subscription.js +238 -0
- package/lib/oauth/gmail.js +18 -0
- package/lib/oauth/outlook-identity.js +54 -12
- package/lib/prepared-password.js +38 -0
- package/lib/privileged-settings.js +6 -0
- package/lib/queue-browser/index.js +6 -6
- package/lib/queue-job-actions.js +59 -4
- package/lib/read-env-value.js +46 -21
- package/lib/redis-url.js +23 -0
- package/lib/response-stream.js +69 -1
- package/lib/revocation-events.js +79 -0
- package/lib/routes-ui.js +4 -1
- package/lib/schemas.js +26 -2
- package/lib/session-default.js +13 -3
- package/lib/settings.js +47 -24
- package/lib/sso.js +23 -0
- package/lib/submit-penalty.js +24 -0
- package/lib/submit-processor.js +10 -2
- package/lib/tokens.js +6 -0
- package/lib/tools.js +86 -15
- package/lib/ui-routes/admin-config-routes.js +30 -281
- package/lib/ui-routes/auth-routes.js +17 -64
- package/lib/ui-routes/dbsc-routes.js +43 -0
- package/lib/ui-routes/license-routes.js +326 -0
- package/lib/web-safe-html.js +29 -0
- package/lib/webhook-delivery.js +21 -20
- package/lib/webhook-penalty.js +18 -17
- package/lib/webhooks.js +18 -0
- package/package.json +18 -18
- package/sbom.json +294 -294
- package/scan.js +2 -0
- package/server.js +253 -80
- package/static/css/flyonui.css +2 -2
- package/static/js/ui.js +11 -4
- package/static/licenses.html +27 -27
- package/translations/messages.pot +17 -17
- package/views/config/license.hbs +43 -16
- package/views/config/security.hbs +37 -0
- package/views/partials/side_menu.hbs +1 -1
- package/workers/api.js +128 -109
- package/workers/imap.js +4 -6
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// Exchange Online ties an IMAP session to the lifetime of the OAuth2 access token it logged in
|
|
4
|
+
// with. Once that token expires, the next command on the session (typically the DONE that ends
|
|
5
|
+
// IDLE so an API request can run) is answered with `* BYE Session invalidated -
|
|
6
|
+
// AccessTokenExpired`, and whatever request was in flight fails with it. Renewing the stored token
|
|
7
|
+
// does nothing for a session that is already open: IMAP has no way to authenticate again inside an
|
|
8
|
+
// authenticated session, so the session has to be replaced before its token runs out.
|
|
9
|
+
//
|
|
10
|
+
// ImapFlow does the replacing (its `sessionExpires` option, from 2.11.0): from `sessionExpiryLead`
|
|
11
|
+
// before the expiry it closes the connection the first time nothing runs on it, and shortly before
|
|
12
|
+
// the expiry it closes it regardless. The close handlers reconnect a primary connection or a
|
|
13
|
+
// subconnection, and a command connection is opened again for the next request. What stays here is
|
|
14
|
+
// deciding which sessions that applies to and making sure each login starts with a token that has
|
|
15
|
+
// enough life left, only for the providers listed below (a Gmail session outlives its token, and
|
|
16
|
+
// reconnecting those every hour would only cost a resync).
|
|
17
|
+
|
|
18
|
+
const { OAUTH_TOKEN_MIN_VALIDITY } = require('../../consts');
|
|
19
|
+
|
|
20
|
+
// Providers whose IMAP sessions end when the access token used to log in expires
|
|
21
|
+
const TOKEN_BOUND_SESSION_PROVIDERS = new Set(['outlook']);
|
|
22
|
+
|
|
23
|
+
// How long before the token expires the connection starts looking for a moment to close
|
|
24
|
+
const REAUTH_LEAD = 5 * 60 * 1000;
|
|
25
|
+
|
|
26
|
+
// Up to this much is added to the lead at random. Accounts that logged in together (a worker
|
|
27
|
+
// restart) renew together and would otherwise all reconnect in the same few seconds one token
|
|
28
|
+
// lifetime later, and every lifetime after that
|
|
29
|
+
const REAUTH_JITTER = 2 * 60 * 1000;
|
|
30
|
+
|
|
31
|
+
// A session that would have to be replaced sooner than this after logging in gets no deadline. Only
|
|
32
|
+
// a provider handing out short tokens gets there, and replacing such a session on every login would
|
|
33
|
+
// turn into a reconnect loop; it ends the way it did before, with the server's BYE. Longer than
|
|
34
|
+
// STABLE_CONNECTION_TIME, so the close handler reconnects the replaced primary at once instead of
|
|
35
|
+
// throttling it as a connection that died young
|
|
36
|
+
const REAUTH_MIN_DELAY = 6 * 60 * 1000;
|
|
37
|
+
|
|
38
|
+
// How much lifetime a token must have left to be used for a login on such a provider. Above the
|
|
39
|
+
// longest lead plus REAUTH_MIN_DELAY with a minute to spare, so a session that logs in with a token
|
|
40
|
+
// it got this way always gets a deadline. Kept close to that sum, because command connections and
|
|
41
|
+
// subconnections log in too, and every renewal they cause moves the next replacement of the primary
|
|
42
|
+
// connection earlier
|
|
43
|
+
const LOGIN_MIN_VALIDITY = 15 * 60 * 1000;
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* How much lifetime a stored access token needs to be used as is
|
|
47
|
+
* @param {string} provider - OAuth2 app provider (`outlook`, `gmail`, ...)
|
|
48
|
+
* @param {string} target - What the token is for (`imap`, `smtp`, `api`)
|
|
49
|
+
* @returns {number} Milliseconds
|
|
50
|
+
*/
|
|
51
|
+
function minTokenValidity(provider, target) {
|
|
52
|
+
return target === 'imap' && TOKEN_BOUND_SESSION_PROVIDERS.has(provider) ? LOGIN_MIN_VALIDITY : OAUTH_TOKEN_MIN_VALIDITY;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* The ImapFlow options that close a session before the token it logs in with expires, or null when
|
|
57
|
+
* the session does not end with its token (or the token is too short-lived to bother)
|
|
58
|
+
* @param {string} provider - OAuth2 app provider
|
|
59
|
+
* @param {Date|string|number} expires - Expiry of the token the session logs in with
|
|
60
|
+
* @param {number} now - Current epoch milliseconds
|
|
61
|
+
* @param {Function} [random=Math.random] - Source of the jitter, for tests
|
|
62
|
+
* @returns {{sessionExpires: number, sessionExpiryLead: number}|null}
|
|
63
|
+
*/
|
|
64
|
+
function sessionExpiryOptions(provider, expires, now, random = Math.random) {
|
|
65
|
+
if (!TOKEN_BOUND_SESSION_PROVIDERS.has(provider) || !expires) {
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
const sessionExpires = new Date(expires).getTime();
|
|
69
|
+
const sessionExpiryLead = REAUTH_LEAD + Math.round(random() * REAUTH_JITTER);
|
|
70
|
+
if (!Number.isFinite(sessionExpires) || sessionExpires - sessionExpiryLead - now < REAUTH_MIN_DELAY) {
|
|
71
|
+
return null;
|
|
72
|
+
}
|
|
73
|
+
return { sessionExpires, sessionExpiryLead };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
module.exports = {
|
|
77
|
+
LOGIN_MIN_VALIDITY,
|
|
78
|
+
REAUTH_LEAD,
|
|
79
|
+
REAUTH_JITTER,
|
|
80
|
+
REAUTH_MIN_DELAY,
|
|
81
|
+
minTokenValidity,
|
|
82
|
+
sessionExpiryOptions
|
|
83
|
+
};
|
|
@@ -29,6 +29,7 @@ const { ReconnectBackoff } = require('./reconnect-backoff');
|
|
|
29
29
|
const { isRefusedImapLogin, imapResponseText } = require('./imap/login-failure');
|
|
30
30
|
const { knownUidNext, planStaleViewProbe, evaluateStaleViewProbe } = require('./imap/stale-view');
|
|
31
31
|
const { applyIdleSettings, commandSocketTimeout } = require('./imap/idle-settings');
|
|
32
|
+
const { sessionExpiryOptions } = require('./imap/session-expiry');
|
|
32
33
|
const { learnedInterval, recordClose } = require('./imap/adaptive-idle-store');
|
|
33
34
|
|
|
34
35
|
// How long a learned IDLE interval read for one connection is reused for the account's others
|
|
@@ -1689,11 +1690,14 @@ class IMAPClient extends BaseClient {
|
|
|
1689
1690
|
// the same method is also called by subconnections, so do not mark the primary connection as failing if something happens
|
|
1690
1691
|
ctx = ctx || this;
|
|
1691
1692
|
let imapConnectionConfig;
|
|
1693
|
+
// ImapFlow's sessionExpires/sessionExpiryLead, for a session that ends with its token
|
|
1694
|
+
let sessionOptions = null;
|
|
1692
1695
|
|
|
1693
1696
|
if (accountData.oauth2 && accountData.oauth2.auth) {
|
|
1694
1697
|
// OAuth2 authentication configuration
|
|
1695
|
-
const { oauth2User, accessToken, oauth2App } = await this.loadOAuth2AccountCredentials(accountData, ctx, 'imap');
|
|
1698
|
+
const { oauth2User, accessToken, oauth2App, expires } = await this.loadOAuth2AccountCredentials(accountData, ctx, 'imap');
|
|
1696
1699
|
const providerData = oauth2ProviderData(oauth2App.provider, oauth2App.cloud);
|
|
1700
|
+
sessionOptions = sessionExpiryOptions(oauth2App.provider, expires, Date.now());
|
|
1697
1701
|
|
|
1698
1702
|
imapConnectionConfig = Object.assign(
|
|
1699
1703
|
{
|
|
@@ -1714,6 +1718,8 @@ class IMAPClient extends BaseClient {
|
|
|
1714
1718
|
// If authentication server is set then it overrides authentication data
|
|
1715
1719
|
if (await useAuthServerForConnection(imapConnectionConfig, ctx.logger, { account: this.account, target: 'imap' })) {
|
|
1716
1720
|
imapConnectionConfig.auth = await this.resolveAuthServerCredentials('imap', ctx);
|
|
1721
|
+
// the expiry of the stored token says nothing about the one the session logs in with
|
|
1722
|
+
sessionOptions = null;
|
|
1717
1723
|
}
|
|
1718
1724
|
|
|
1719
1725
|
// Configure TLS settings
|
|
@@ -1760,7 +1766,11 @@ class IMAPClient extends BaseClient {
|
|
|
1760
1766
|
vendor: (await settings.get('imapClientVendor')) || this.imapConfig.clientInfo.vendor,
|
|
1761
1767
|
'support-url': (await settings.get('imapClientSupportUrl')) || this.imapConfig.clientInfo['support-url']
|
|
1762
1768
|
}
|
|
1763
|
-
}
|
|
1769
|
+
},
|
|
1770
|
+
// Exchange Online ends the session when its token expires; ImapFlow closes the connection
|
|
1771
|
+
// before that while nothing runs on it, and the close handlers open a new one (see
|
|
1772
|
+
// session-expiry.js). Applies to every connection built from this configuration
|
|
1773
|
+
sessionOptions
|
|
1764
1774
|
);
|
|
1765
1775
|
|
|
1766
1776
|
this.resyncDelay = imapConfig.resyncDelay * 1000;
|
|
@@ -39,20 +39,23 @@ function generatePoolKey(smtpSettings) {
|
|
|
39
39
|
return crypto.createHash('sha256').update(serializedSettings).digest('hex');
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
+
// Removes a transporter from the pool map, unless the key already names its successor: a pool
|
|
43
|
+
// that was replaced under this key must not take the live one out of the map on a late event, or
|
|
44
|
+
// that one is no longer reused nor closed by the idle sweep
|
|
45
|
+
function forgetTransporter(poolKey, transporter) {
|
|
46
|
+
if (SMTP_POOLS.get(poolKey) === transporter) {
|
|
47
|
+
SMTP_POOLS.delete(poolKey);
|
|
48
|
+
SMTP_POOL_LAST_USED.delete(poolKey);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
|
|
42
52
|
/**
|
|
43
53
|
* Sets up event handlers for a new transporter
|
|
44
54
|
* @param {Object} transporter - Nodemailer transport instance
|
|
45
55
|
* @param {string} poolKey - Pool key for this transport
|
|
46
56
|
*/
|
|
47
57
|
function setupTransporterHandlers(transporter, poolKey) {
|
|
48
|
-
|
|
49
|
-
// on a late event, or the live transporter is no longer reused nor closed by the idle sweep
|
|
50
|
-
const forget = () => {
|
|
51
|
-
if (SMTP_POOLS.get(poolKey) === transporter) {
|
|
52
|
-
SMTP_POOLS.delete(poolKey);
|
|
53
|
-
SMTP_POOL_LAST_USED.delete(poolKey);
|
|
54
|
-
}
|
|
55
|
-
};
|
|
58
|
+
const forget = () => forgetTransporter(poolKey, transporter);
|
|
56
59
|
|
|
57
60
|
// Handle connection pool cleanup when idle
|
|
58
61
|
transporter.once('clear', () => {
|
|
@@ -129,6 +132,16 @@ function getMailTransport(smtpSettings) {
|
|
|
129
132
|
return transporter;
|
|
130
133
|
}
|
|
131
134
|
|
|
135
|
+
// Closes a transporter including the connections in the middle of a delivery, which the pool's plain
|
|
136
|
+
// close() leaves running; close({ force: true }) is available since nodemailer 10.4.0
|
|
137
|
+
function forceCloseTransporter(transporter) {
|
|
138
|
+
try {
|
|
139
|
+
transporter.close({ force: true });
|
|
140
|
+
} catch (err) {
|
|
141
|
+
logger.error({ msg: 'Failed to close pooled transporter', err });
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
|
|
132
145
|
/**
|
|
133
146
|
* Closes a pooled connection by key
|
|
134
147
|
* @param {string} poolKey - The pool key to close
|
|
@@ -214,8 +227,53 @@ function getPoolSize() {
|
|
|
214
227
|
return SMTP_POOLS.size;
|
|
215
228
|
}
|
|
216
229
|
|
|
230
|
+
// The longest one delivery may take, whatever the server does. socketTimeout only notices a silent
|
|
231
|
+
// server: one that trickles a byte at a time keeps the socket alive forever, and the submit worker
|
|
232
|
+
// that waits on the delivery held its only slot for the whole ten minute call timeout, delaying
|
|
233
|
+
// every other account's mail behind it. Below that timeout, so the delivery fails here first and the
|
|
234
|
+
// connection is closed rather than left running, and long enough for a large message on a slow
|
|
235
|
+
// link. What keeps a stalling server from costing this once per message is the account penalty
|
|
236
|
+
// the failure sets (lib/submit-penalty.js).
|
|
237
|
+
const SMTP_SEND_DEADLINE = 8 * 60 * 1000;
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Sends a message through the pooled transport for the settings, within a total deadline. On expiry
|
|
241
|
+
* the pooled connection is closed and the send rejects with code ETIMEDOUT and `deadlineExceeded`.
|
|
242
|
+
* @param {Object} smtpSettings - SMTP configuration settings
|
|
243
|
+
* @param {Object} message - nodemailer message
|
|
244
|
+
* @param {number} [deadline] - milliseconds
|
|
245
|
+
* @returns {Promise<Object>} sendMail() info
|
|
246
|
+
*/
|
|
247
|
+
async function sendWithDeadline(smtpSettings, message, deadline = SMTP_SEND_DEADLINE) {
|
|
248
|
+
// through the export, so a test can stand in a transport
|
|
249
|
+
const transporter = module.exports.getMailTransport(smtpSettings);
|
|
250
|
+
let timer;
|
|
251
|
+
const expired = new Promise((resolve, reject) => {
|
|
252
|
+
timer = setTimeout(() => {
|
|
253
|
+
// the transporter this send went through, which the key may no longer name by now
|
|
254
|
+
forceCloseTransporter(transporter);
|
|
255
|
+
forgetTransporter(generatePoolKey(smtpSettings), transporter);
|
|
256
|
+
const err = new Error(`SMTP delivery did not complete within ${Math.round(deadline / 1000)} seconds`);
|
|
257
|
+
err.code = 'ETIMEDOUT';
|
|
258
|
+
err.deadlineExceeded = true;
|
|
259
|
+
// Not retried: nothing tells whether the server already has the whole message (a
|
|
260
|
+
// server can stall after the final dot as well as before it), and a retry of that one
|
|
261
|
+
// delivers it twice. The message ends as failed and keeps its content, so an operator
|
|
262
|
+
// can retry it from the outbox once the server behaves.
|
|
263
|
+
err.permanent = true;
|
|
264
|
+
reject(err);
|
|
265
|
+
}, deadline);
|
|
266
|
+
});
|
|
267
|
+
try {
|
|
268
|
+
return await Promise.race([transporter.sendMail(message), expired]);
|
|
269
|
+
} finally {
|
|
270
|
+
clearTimeout(timer);
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
217
274
|
module.exports = {
|
|
218
275
|
getMailTransport,
|
|
276
|
+
sendWithDeadline,
|
|
219
277
|
closePooledConnection,
|
|
220
278
|
getPoolSize,
|
|
221
279
|
// Exported for testing
|
package/lib/export.js
CHANGED
|
@@ -22,7 +22,8 @@ const {
|
|
|
22
22
|
DEFAULT_EXPORT_MAX_AGE,
|
|
23
23
|
DEFAULT_EXPORT_MAX_CONCURRENT,
|
|
24
24
|
DEFAULT_EXPORT_MAX_GLOBAL_CONCURRENT,
|
|
25
|
-
DEFAULT_EXPORT_MAX_MESSAGE_SIZE
|
|
25
|
+
DEFAULT_EXPORT_MAX_MESSAGE_SIZE,
|
|
26
|
+
REDIS_BATCH_DELETE_SIZE
|
|
26
27
|
} = require('./consts');
|
|
27
28
|
|
|
28
29
|
const EXPORT_ID_PREFIX = 'exp_';
|
|
@@ -323,7 +324,8 @@ async function scanKeys(pattern) {
|
|
|
323
324
|
const keys = [];
|
|
324
325
|
let cursor = '0';
|
|
325
326
|
do {
|
|
326
|
-
|
|
327
|
+
// the batch size the account-key scan of an account deletion uses, which this runs beside
|
|
328
|
+
const [nextCursor, batch] = await redis.scan(cursor, 'MATCH', pattern, 'COUNT', REDIS_BATCH_DELETE_SIZE);
|
|
327
329
|
cursor = nextCursor;
|
|
328
330
|
keys.push(...batch);
|
|
329
331
|
} while (cursor !== '0');
|
|
@@ -343,6 +345,67 @@ function getExportQueueKey(account, exportId) {
|
|
|
343
345
|
// arbitrary file write, and an operator picks a deployment path through the environment anyway. This
|
|
344
346
|
// used to consult an `exportPath` setting first, which no schema declares and so nothing could ever
|
|
345
347
|
// have written.
|
|
348
|
+
// The export ids of each account, so listing an account's exports and removing them with the account
|
|
349
|
+
// read one set instead of scanning the whole keyspace. A separate key family on purpose: a key under
|
|
350
|
+
// `exp:` could be matched by the record pattern the startup backfill scans for.
|
|
351
|
+
function getExportIndexKey(account) {
|
|
352
|
+
return `${REDIS_PREFIX}expidx:${account}`;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// Set once the startup backfill has indexed the exports created before the index existed
|
|
356
|
+
const EXPORT_INDEX_BACKFILL_KEY = `${REDIS_PREFIX}migration:exportIndex`;
|
|
357
|
+
|
|
358
|
+
/**
|
|
359
|
+
* The export records of one account, read through the account's export index. Ids whose record
|
|
360
|
+
* expired meanwhile are dropped from the index on the way, which is what keeps an index without an
|
|
361
|
+
* expiry of its own from growing.
|
|
362
|
+
*
|
|
363
|
+
* @param {string} account - Account id
|
|
364
|
+
* @returns {Promise<Object[]>} The stored records
|
|
365
|
+
*/
|
|
366
|
+
async function accountExportRecords(account) {
|
|
367
|
+
const indexKey = getExportIndexKey(account);
|
|
368
|
+
const exportIds = await redis.smembers(indexKey);
|
|
369
|
+
const records = [];
|
|
370
|
+
const expired = [];
|
|
371
|
+
for (const exportId of exportIds) {
|
|
372
|
+
const data = await redis.hgetall(getExportKey(account, exportId));
|
|
373
|
+
if (data && data.exportId) {
|
|
374
|
+
records.push(data);
|
|
375
|
+
} else {
|
|
376
|
+
expired.push(exportId);
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
if (expired.length) {
|
|
380
|
+
await redis.srem(indexKey, ...expired);
|
|
381
|
+
}
|
|
382
|
+
return records;
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
/**
|
|
386
|
+
* Indexes the exports created before the per-account index existed. Runs once at startup (the
|
|
387
|
+
* completion key is written last, so an interrupted run is repeated, and every write is idempotent).
|
|
388
|
+
* Without it an export made before the upgrade would be missing from the index, and so would survive
|
|
389
|
+
* the deletion of its account.
|
|
390
|
+
*
|
|
391
|
+
* @returns {Promise<number>} How many export records were indexed
|
|
392
|
+
*/
|
|
393
|
+
async function backfillExportIndex() {
|
|
394
|
+
if (await redis.exists(EXPORT_INDEX_BACKFILL_KEY)) {
|
|
395
|
+
return 0;
|
|
396
|
+
}
|
|
397
|
+
let indexed = 0;
|
|
398
|
+
for (const key of await scanKeys(`${escapeRedisGlob(REDIS_PREFIX)}exp:*:${EXPORT_ID_PREFIX}*`)) {
|
|
399
|
+
const [account, exportId] = await redis.hmget(key, 'account', 'exportId');
|
|
400
|
+
if (account && exportId && key === getExportKey(account, exportId)) {
|
|
401
|
+
await redis.sadd(getExportIndexKey(account), exportId);
|
|
402
|
+
indexed++;
|
|
403
|
+
}
|
|
404
|
+
}
|
|
405
|
+
await redis.set(EXPORT_INDEX_BACKFILL_KEY, new Date().toISOString());
|
|
406
|
+
return indexed;
|
|
407
|
+
}
|
|
408
|
+
|
|
346
409
|
async function getExportPath() {
|
|
347
410
|
return readEnvValue('EENGINE_EXPORT_PATH') || os.tmpdir();
|
|
348
411
|
}
|
|
@@ -475,7 +538,13 @@ class Export {
|
|
|
475
538
|
|
|
476
539
|
const ttl = Math.ceil(maxAge / 1000);
|
|
477
540
|
|
|
478
|
-
|
|
541
|
+
// The index has no expiry of its own: an export's retention is restarted when it starts and
|
|
542
|
+
// completes, so an index expiring with the export it was created for dropped an export
|
|
543
|
+
// that outlived it, and account deletion then left that export behind. Ids of expired
|
|
544
|
+
// records are pruned whenever the index is read, including here.
|
|
545
|
+
const indexKey = getExportIndexKey(account);
|
|
546
|
+
await accountExportRecords(account);
|
|
547
|
+
await redis.multi().hmset(exportKey, exportData).expire(exportKey, ttl).sadd(indexKey, exportId).exec();
|
|
479
548
|
|
|
480
549
|
await exportQueue.add('export', { account, exportId }, { jobId: exportId, removeOnComplete: true, removeOnFail: true });
|
|
481
550
|
} catch (err) {
|
|
@@ -546,23 +615,12 @@ class Export {
|
|
|
546
615
|
const page = Number(options.page) || 0;
|
|
547
616
|
const pageSize = Number(options.pageSize) || 20;
|
|
548
617
|
|
|
549
|
-
const
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
// the glob also matches the exports of an account whose id begins with this one and
|
|
556
|
-
// a colon, so the record's own account field decides
|
|
557
|
-
if (data && data.exportId && data.account === account) {
|
|
558
|
-
exports.push({
|
|
559
|
-
exportId: data.exportId,
|
|
560
|
-
status: data.status,
|
|
561
|
-
created: data.created ? new Date(Number(data.created)).toISOString() : undefined,
|
|
562
|
-
expiresAt: data.expiresAt ? new Date(Number(data.expiresAt)).toISOString() : undefined
|
|
563
|
-
});
|
|
564
|
-
}
|
|
565
|
-
}
|
|
618
|
+
const exports = (await accountExportRecords(account)).map(data => ({
|
|
619
|
+
exportId: data.exportId,
|
|
620
|
+
status: data.status,
|
|
621
|
+
created: data.created ? new Date(Number(data.created)).toISOString() : undefined,
|
|
622
|
+
expiresAt: data.expiresAt ? new Date(Number(data.expiresAt)).toISOString() : undefined
|
|
623
|
+
}));
|
|
566
624
|
|
|
567
625
|
exports.sort((a, b) => new Date(b.created) - new Date(a.created));
|
|
568
626
|
|
|
@@ -601,7 +659,13 @@ class Export {
|
|
|
601
659
|
// Active exports: worker will clean up when it detects cancellation
|
|
602
660
|
// Non-active exports: clean up immediately
|
|
603
661
|
if (!isActive) {
|
|
604
|
-
await redis
|
|
662
|
+
await redis
|
|
663
|
+
.multi()
|
|
664
|
+
.del(exportKey)
|
|
665
|
+
.del(queueKey)
|
|
666
|
+
.srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId))
|
|
667
|
+
.srem(getExportIndexKey(account), exportId)
|
|
668
|
+
.exec();
|
|
605
669
|
|
|
606
670
|
await Export.removeFile(exportId, data);
|
|
607
671
|
}
|
|
@@ -610,6 +674,28 @@ class Export {
|
|
|
610
674
|
return true;
|
|
611
675
|
}
|
|
612
676
|
|
|
677
|
+
/**
|
|
678
|
+
* Removes every export of an account, the way deleting each one through the API would: a queued
|
|
679
|
+
* export is dropped with its job, a running one is cancelled (its worker removes the file), and a
|
|
680
|
+
* finished one goes with its file. Called when the account is deleted. The records used to stay
|
|
681
|
+
* for their whole retention window, still downloadable by an instance-wide credential, and a
|
|
682
|
+
* new account registered under the same id inherited them.
|
|
683
|
+
*
|
|
684
|
+
* @param {string} account - Account id
|
|
685
|
+
* @returns {Promise<number>} How many exports were removed
|
|
686
|
+
*/
|
|
687
|
+
static async deleteForAccount(account) {
|
|
688
|
+
let removed = 0;
|
|
689
|
+
for (const { exportId } of await accountExportRecords(account)) {
|
|
690
|
+
if (await Export.delete(account, exportId)) {
|
|
691
|
+
removed++;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
// A running export is only marked cancelled and keeps its id in the index until its worker,
|
|
695
|
+
// or complete(), fail() or the restart sweep, removes it (see discardIfCancelled())
|
|
696
|
+
return removed;
|
|
697
|
+
}
|
|
698
|
+
|
|
613
699
|
/**
|
|
614
700
|
* Unlinks the export's own file, if its record names one. The path is derived from the id,
|
|
615
701
|
* never taken as stored (see exportFilePath()); a file that is already gone is not an error.
|
|
@@ -771,6 +857,10 @@ class Export {
|
|
|
771
857
|
}
|
|
772
858
|
|
|
773
859
|
static async complete(account, exportId) {
|
|
860
|
+
if (await Export.discardIfCancelled(account, exportId)) {
|
|
861
|
+
return;
|
|
862
|
+
}
|
|
863
|
+
|
|
774
864
|
const exportKey = getExportKey(account, exportId);
|
|
775
865
|
const queueKey = getExportQueueKey(account, exportId);
|
|
776
866
|
|
|
@@ -800,6 +890,10 @@ class Export {
|
|
|
800
890
|
return;
|
|
801
891
|
}
|
|
802
892
|
|
|
893
|
+
if (await Export.discardIfCancelled(account, exportId, exportData)) {
|
|
894
|
+
return;
|
|
895
|
+
}
|
|
896
|
+
|
|
803
897
|
await redis
|
|
804
898
|
.multi()
|
|
805
899
|
.hmset(exportKey, {
|
|
@@ -817,7 +911,36 @@ class Export {
|
|
|
817
911
|
const exportKey = getExportKey(account, exportId);
|
|
818
912
|
const queueKey = getExportQueueKey(account, exportId);
|
|
819
913
|
|
|
820
|
-
await redis
|
|
914
|
+
await redis
|
|
915
|
+
.multi()
|
|
916
|
+
.del(exportKey)
|
|
917
|
+
.del(queueKey)
|
|
918
|
+
.srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId))
|
|
919
|
+
.srem(getExportIndexKey(account), exportId)
|
|
920
|
+
.exec();
|
|
921
|
+
}
|
|
922
|
+
|
|
923
|
+
/**
|
|
924
|
+
* Removes an export, record and file, when it was cancelled while running. Deleting a running
|
|
925
|
+
* export (directly, or with its account) only marks it cancelled and leaves the removal to its
|
|
926
|
+
* worker, but a worker past its last cancellation check finished it through complete() or fail()
|
|
927
|
+
* instead, and a restart turned it into a failed export: in each case the record and the file of
|
|
928
|
+
* an export that was asked to go stayed for the whole retention window.
|
|
929
|
+
*
|
|
930
|
+
* @param {string} account
|
|
931
|
+
* @param {string} exportId
|
|
932
|
+
* @param {Object} [data] - The stored record, when the caller already read it
|
|
933
|
+
* @returns {Promise<boolean>} true when the export was cancelled and is now gone
|
|
934
|
+
*/
|
|
935
|
+
static async discardIfCancelled(account, exportId, data) {
|
|
936
|
+
data = data || (await redis.hgetall(getExportKey(account, exportId)));
|
|
937
|
+
if (!data || data.status !== 'cancelled') {
|
|
938
|
+
return false;
|
|
939
|
+
}
|
|
940
|
+
await Export.deleteFully(account, exportId);
|
|
941
|
+
await Export.removeFile(exportId, data);
|
|
942
|
+
logger.info({ msg: 'Removed an export cancelled while it ran', account, exportId });
|
|
943
|
+
return true;
|
|
821
944
|
}
|
|
822
945
|
|
|
823
946
|
static async markInterruptedAsFailed() {
|
|
@@ -929,6 +1052,8 @@ module.exports = {
|
|
|
929
1052
|
calculateScore,
|
|
930
1053
|
getExportKey,
|
|
931
1054
|
getExportQueueKey,
|
|
1055
|
+
getExportIndexKey,
|
|
1056
|
+
backfillExportIndex,
|
|
932
1057
|
getExportPath,
|
|
933
1058
|
getExportMaxAge,
|
|
934
1059
|
isTransientError,
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
const { constantTimeEqual } = require('./tools');
|
|
4
|
+
|
|
5
|
+
// The two MS Graph subscription routes are unauthenticated and deliberately carry no payload
|
|
6
|
+
// schema: they must answer 202 to anything, because a 400 would make Graph tear the subscription
|
|
7
|
+
// down, and the validation handshake posts an empty body. So the payload is arbitrary JSON and
|
|
8
|
+
// every read of it has to be defensive.
|
|
9
|
+
const graphNotificationEntries = payload => (Array.isArray(payload && payload.value) ? payload.value.filter(entry => entry && typeof entry === 'object') : []);
|
|
10
|
+
|
|
11
|
+
// How many entries of an unverified Graph notification body are named in its log record
|
|
12
|
+
const MAX_LOGGED_GRAPH_ENTRIES = 5;
|
|
13
|
+
|
|
14
|
+
// One record per request for the entries that failed validation, rather than one per entry. The
|
|
15
|
+
// endpoint is unauthenticated and a body of up to 1 MB can hold thousands of empty entries, and each
|
|
16
|
+
// record carries the request's own fields, so one request used to write hundreds of megabytes of log.
|
|
17
|
+
function logRejectedGraphEntries(request, rejected, fields) {
|
|
18
|
+
if (!rejected.length) {
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
request.logger.warn(
|
|
22
|
+
Object.assign({ account: request.query.account, rejected: rejected.length, sample: rejected.slice(0, MAX_LOGGED_GRAPH_ENTRIES) }, fields)
|
|
23
|
+
);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Splits the entries of a notification body into the ones that belong to the account's
|
|
28
|
+
* subscription (its id and its client state both match) and the ones that do not.
|
|
29
|
+
*
|
|
30
|
+
* @param {Object[]} entries - graphNotificationEntries() result
|
|
31
|
+
* @param {Object} subscription - The account's stored subscription (`id`, `clientState`)
|
|
32
|
+
* @param {Function} describe - (entry) => extra fields to log for a rejected entry
|
|
33
|
+
* @returns {{ valid: Object[], rejected: Object[] }}
|
|
34
|
+
*/
|
|
35
|
+
function partitionGraphEntries(entries, subscription, describe) {
|
|
36
|
+
const valid = [];
|
|
37
|
+
const rejected = [];
|
|
38
|
+
for (const entry of entries) {
|
|
39
|
+
const subscriptionIdMatch = entry.subscriptionId === subscription.id;
|
|
40
|
+
const clientStateMatch = constantTimeEqual(entry.clientState, subscription.clientState);
|
|
41
|
+
if (subscriptionIdMatch && clientStateMatch) {
|
|
42
|
+
valid.push(entry);
|
|
43
|
+
} else {
|
|
44
|
+
rejected.push(Object.assign({ subscriptionIdMatch, clientStateMatch, receivedSubscriptionId: entry.subscriptionId }, describe(entry)));
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
return { valid, rejected };
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
// A notification for an account that has no subscription stored: one record naming a few entries
|
|
51
|
+
function logUnknownGraphSubscription(request, entries) {
|
|
52
|
+
request.logger.warn({
|
|
53
|
+
msg: 'Subscription not found for account',
|
|
54
|
+
account: request.query.account,
|
|
55
|
+
entries: entries.length,
|
|
56
|
+
subscriptionIds: entries.slice(0, MAX_LOGGED_GRAPH_ENTRIES).map(entry => entry.subscriptionId)
|
|
57
|
+
});
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
module.exports = { graphNotificationEntries, partitionGraphEntries, logRejectedGraphEntries, logUnknownGraphSubscription, MAX_LOGGED_GRAPH_ENTRIES };
|
package/lib/imap-proxy-auth.js
CHANGED
|
@@ -77,7 +77,11 @@ function classifyCredentialFailure(err) {
|
|
|
77
77
|
function createImapProxyAuthHandler({ call }) {
|
|
78
78
|
// The credential check proper. Everything it throws is a refusal the client caused, which
|
|
79
79
|
// is what the failure budget in authenticate() counts.
|
|
80
|
-
|
|
80
|
+
//
|
|
81
|
+
// With `recheck` the credential already opened a session and is being asked whether it still
|
|
82
|
+
// admits it: no use of a token is recorded, and an account that can not be loaded for any
|
|
83
|
+
// reason but "not found" throws as it is, so the caller can tell a fault from a revocation.
|
|
84
|
+
async function verifyCredentials(auth, session, { recheck = false } = {}) {
|
|
81
85
|
let account = auth.username;
|
|
82
86
|
|
|
83
87
|
let imapPassword = await settings.get('imapProxyServerPassword');
|
|
@@ -87,7 +91,8 @@ function createImapProxyAuthHandler({ call }) {
|
|
|
87
91
|
password: auth.password,
|
|
88
92
|
account: auth.username,
|
|
89
93
|
requiredScope: 'imap-proxy',
|
|
90
|
-
remoteAddress: session.remoteAddress
|
|
94
|
+
remoteAddress: session.remoteAddress,
|
|
95
|
+
recheck
|
|
91
96
|
});
|
|
92
97
|
|
|
93
98
|
if (!result.authenticated) {
|
|
@@ -101,6 +106,9 @@ function createImapProxyAuthHandler({ call }) {
|
|
|
101
106
|
accountData = await accountObject.loadAccountData();
|
|
102
107
|
} catch (err) {
|
|
103
108
|
if (!err.output || err.output.statusCode !== 404) {
|
|
109
|
+
if (recheck) {
|
|
110
|
+
throw err;
|
|
111
|
+
}
|
|
104
112
|
// only log non-obvious errors
|
|
105
113
|
logger.error({ msg: 'Failed to load account data', account: auth.username, err });
|
|
106
114
|
}
|
|
@@ -115,7 +123,21 @@ function createImapProxyAuthHandler({ call }) {
|
|
|
115
123
|
return { accountObject, accountData };
|
|
116
124
|
}
|
|
117
125
|
|
|
118
|
-
|
|
126
|
+
// Whether the account is one the proxy may serve at all, past the credential check
|
|
127
|
+
function accountRefusal(accountData) {
|
|
128
|
+
if (isApiBasedApp(accountData?._app)) {
|
|
129
|
+
return 'IMAP is not supported for API-based accounts';
|
|
130
|
+
}
|
|
131
|
+
// An account whose IMAP the operator switched off (send-only), or that the auth-failure
|
|
132
|
+
// safety net parked, is not reachable through the proxy either: a proxy session is an
|
|
133
|
+
// IMAP connection made with the account's credentials, the very thing both switches stop
|
|
134
|
+
if (isImapDisabled(accountData)) {
|
|
135
|
+
return authFailureDisabledAt(accountData) ? 'Account is disabled after repeated authentication failures' : 'IMAP is disabled for this account';
|
|
136
|
+
}
|
|
137
|
+
return null;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
async function authenticate(auth, session) {
|
|
119
141
|
let verified = await withAuthFailureBudget(
|
|
120
142
|
{ remoteAddress: session.remoteAddress, account: auth.username, password: auth.password },
|
|
121
143
|
() => verifyCredentials(auth, session),
|
|
@@ -124,21 +146,9 @@ function createImapProxyAuthHandler({ call }) {
|
|
|
124
146
|
|
|
125
147
|
// Past the credential check: a refusal from here on is about the account, not about
|
|
126
148
|
// what the client presented, so it does not count against the client's budget
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
respErr
|
|
130
|
-
respErr.serverResponseCode = 'ACCOUNTDISABLED';
|
|
131
|
-
respErr.responseStatus = 'NO';
|
|
132
|
-
throw respErr;
|
|
133
|
-
}
|
|
134
|
-
|
|
135
|
-
// An account whose IMAP the operator switched off (send-only), or that the auth-failure
|
|
136
|
-
// safety net parked, is not reachable through the proxy either: a proxy session is an
|
|
137
|
-
// IMAP connection made with the account's credentials, the very thing both switches stop
|
|
138
|
-
if (isImapDisabled(verified.accountData)) {
|
|
139
|
-
let respErr = new Error(
|
|
140
|
-
authFailureDisabledAt(verified.accountData) ? 'Account is disabled after repeated authentication failures' : 'IMAP is disabled for this account'
|
|
141
|
-
);
|
|
149
|
+
let refusal = accountRefusal(verified.accountData);
|
|
150
|
+
if (refusal) {
|
|
151
|
+
let respErr = new Error(refusal);
|
|
142
152
|
respErr.authenticationFailed = true;
|
|
143
153
|
respErr.serverResponseCode = 'ACCOUNTDISABLED';
|
|
144
154
|
respErr.responseStatus = 'NO';
|
|
@@ -146,7 +156,31 @@ function createImapProxyAuthHandler({ call }) {
|
|
|
146
156
|
}
|
|
147
157
|
|
|
148
158
|
return verified;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Asks whether the credential that opened a proxy session still admits it: the shared
|
|
163
|
+
* password or the token, the account, and the switches that keep an account off the proxy.
|
|
164
|
+
* A login used to be checked once, so a session outlived a deleted token, a deleted or
|
|
165
|
+
* disabled account and a rotated password for as long as the client kept it open.
|
|
166
|
+
*
|
|
167
|
+
* @returns {Promise<Boolean>} false when the session must end; throws on a fault that says
|
|
168
|
+
* nothing about the credential (the caller keeps the session)
|
|
169
|
+
*/
|
|
170
|
+
authenticate.recheck = async (auth, session) => {
|
|
171
|
+
let verified;
|
|
172
|
+
try {
|
|
173
|
+
verified = await verifyCredentials(auth, session, { recheck: true });
|
|
174
|
+
} catch (err) {
|
|
175
|
+
if (err.authenticationFailed) {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
throw err;
|
|
179
|
+
}
|
|
180
|
+
return !accountRefusal(verified.accountData);
|
|
149
181
|
};
|
|
182
|
+
|
|
183
|
+
return authenticate;
|
|
150
184
|
}
|
|
151
185
|
|
|
152
186
|
// Only what the proxy server and its tests reach for: the two taggers are reached through
|
|
@@ -31,11 +31,13 @@ module.exports = {
|
|
|
31
31
|
// Log ID information proviced by the client
|
|
32
32
|
if (Array.isArray(command.attributes[0])) {
|
|
33
33
|
command.attributes[0].forEach(val => {
|
|
34
|
+
// RFC 2971 allows NIL for a value, which the parser renders as null
|
|
35
|
+
let value = (val && val.value) || '';
|
|
34
36
|
if (key === false) {
|
|
35
|
-
key =
|
|
37
|
+
key = value.toString().toLowerCase().trim();
|
|
36
38
|
} else {
|
|
37
39
|
if (allowedKeys.indexOf(key) >= 0) {
|
|
38
|
-
clientId[key] =
|
|
40
|
+
clientId[key] = value.toString();
|
|
39
41
|
}
|
|
40
42
|
key = false;
|
|
41
43
|
}
|