emailengine-app 2.87.2 → 2.89.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.
Files changed (71) hide show
  1. package/.ncurc.js +24 -44
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +37 -0
  4. package/ENVIRONMENT.md +26 -23
  5. package/LICENSE_EMAILENGINE.txt +20 -12
  6. package/app.json +3 -3
  7. package/bin/emailengine.js +7 -11
  8. package/data/google-crawlers.json +1 -1
  9. package/data/public_suffix_list.dat +155 -16
  10. package/lib/account.js +69 -49
  11. package/lib/admin-password.js +85 -0
  12. package/lib/api-routes/license-routes.js +9 -0
  13. package/lib/api-token-auth.js +21 -5
  14. package/lib/calendar-event.js +15 -3
  15. package/lib/consts.js +5 -0
  16. package/lib/db.js +1 -0
  17. package/lib/email-client/base-client.js +36 -15
  18. package/lib/email-client/gmail-client.js +20 -6
  19. package/lib/email-client/imap/connection-errors.js +30 -1
  20. package/lib/email-client/imap/session-expiry.js +83 -0
  21. package/lib/email-client/imap-client.js +12 -2
  22. package/lib/email-client/smtp-pool-manager.js +66 -8
  23. package/lib/export.js +147 -22
  24. package/lib/graph-notifications.js +60 -0
  25. package/lib/imap-proxy-auth.js +52 -18
  26. package/lib/imapproxy/imap-core/lib/commands/id.js +4 -2
  27. package/lib/imapproxy/imap-core/lib/imap-command.js +44 -4
  28. package/lib/imapproxy/imap-server.js +10 -1
  29. package/lib/imapproxy/proxy-handoff.js +100 -5
  30. package/lib/license-subscription.js +244 -0
  31. package/lib/node-version.js +99 -12
  32. package/lib/oauth/gmail.js +18 -0
  33. package/lib/oauth/outlook-identity.js +54 -12
  34. package/lib/prepared-password.js +38 -0
  35. package/lib/queue-browser/index.js +6 -6
  36. package/lib/queue-job-actions.js +59 -4
  37. package/lib/read-env-value.js +46 -21
  38. package/lib/redis-url.js +23 -0
  39. package/lib/response-stream.js +69 -1
  40. package/lib/revocation-events.js +79 -0
  41. package/lib/schemas.js +18 -2
  42. package/lib/settings.js +50 -24
  43. package/lib/sso.js +23 -0
  44. package/lib/submit-penalty.js +24 -0
  45. package/lib/submit-processor.js +10 -2
  46. package/lib/tokens.js +6 -0
  47. package/lib/tools.js +90 -18
  48. package/lib/ui-routes/admin-config-routes.js +3 -276
  49. package/lib/ui-routes/auth-routes.js +13 -64
  50. package/lib/ui-routes/dashboard-routes.js +4 -0
  51. package/lib/ui-routes/license-routes.js +326 -0
  52. package/lib/web-safe-html.js +74 -1
  53. package/lib/webhook-delivery.js +21 -20
  54. package/lib/webhook-penalty.js +18 -17
  55. package/lib/webhooks.js +18 -0
  56. package/list-generate.js +56 -19
  57. package/package.json +28 -31
  58. package/sbom.json +373 -964
  59. package/scan.js +2 -0
  60. package/server.js +273 -100
  61. package/static/css/flyonui.css +2 -2
  62. package/static/js/ui.js +11 -4
  63. package/static/licenses.html +1108 -504
  64. package/translations/messages.pot +18 -18
  65. package/views/config/license.hbs +43 -16
  66. package/views/dashboard.hbs +9 -0
  67. package/views/partials/side_menu.hbs +1 -1
  68. package/views/upgrade.hbs +25 -0
  69. package/workers/api.js +108 -107
  70. package/workers/imap.js +4 -6
  71. package/lib/net-tos-guard.js +0 -42
@@ -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
- // A pool that was already replaced under this key must not take its successor out of the map
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
- const [nextCursor, batch] = await redis.scan(cursor, 'MATCH', pattern, 'COUNT', 100);
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
- await redis.multi().hmset(exportKey, exportData).expire(exportKey, ttl).exec();
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 pattern = `${escapeRedisGlob(REDIS_PREFIX)}exp:${escapeRedisGlob(account)}:${EXPORT_ID_PREFIX}*`;
550
- const keys = await scanKeys(pattern);
551
-
552
- const exports = [];
553
- for (const key of keys) {
554
- const data = await redis.hgetall(key);
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.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId)).exec();
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.multi().del(exportKey).del(queueKey).srem(ACTIVE_EXPORTS_KEY, buildActiveEntry(account, exportId)).exec();
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 };
@@ -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
- async function verifyCredentials(auth, session) {
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
- return async function authenticate(auth, session) {
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
- if (isApiBasedApp(verified.accountData?._app)) {
128
- let respErr = new Error('IMAP is not supported for API-based accounts');
129
- respErr.authenticationFailed = true;
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 = (val.value || '').toString().toLowerCase().trim();
37
+ key = value.toString().toLowerCase().trim();
36
38
  } else {
37
39
  if (allowedKeys.indexOf(key) >= 0) {
38
- clientId[key] = (val.value || '').toString();
40
+ clientId[key] = value.toString();
39
41
  }
40
42
  key = false;
41
43
  }
@@ -381,7 +381,7 @@ class IMAPCommand {
381
381
  };
382
382
 
383
383
  if (!handler.authenticates) {
384
- return handler.handler.call(this.connection, this.parsed, complete, next);
384
+ return this.runHandler(handler, complete, next);
385
385
  }
386
386
 
387
387
  // One credential check at a time per connection. A client that pipelines several
@@ -394,9 +394,8 @@ class IMAPCommand {
394
394
  return complete(null, { response: 'NO', message: 'Authentication already in progress' });
395
395
  }
396
396
  this.connection._authInFlight = true;
397
- handler.handler.call(
398
- this.connection,
399
- this.parsed,
397
+ this.runHandler(
398
+ handler,
400
399
  (err, response) => {
401
400
  if (err || !response || response.response !== 'OK') {
402
401
  this.connection._authInFlight = false;
@@ -452,6 +451,34 @@ class IMAPCommand {
452
451
  return callback();
453
452
  }
454
453
 
454
+ // Runs a command handler. A handler that throws synchronously runs on a stream continuation
455
+ // (setImmediate or a literal's 'end'), where nothing above it catches, so the exception would
456
+ // reach the worker's uncaughtException handler and stop the whole proxy. Answer it as a bad
457
+ // command instead, counted like a parser error.
458
+ runHandler(handler, complete, next) {
459
+ try {
460
+ return handler.handler.call(this.connection, this.parsed, complete, next);
461
+ } catch (err) {
462
+ if (handler.authenticates) {
463
+ this.connection._authInFlight = false;
464
+ }
465
+ this.connection.logger.error(
466
+ {
467
+ err,
468
+ tnx: 'command',
469
+ cid: this.connection.id,
470
+ command: this.command
471
+ },
472
+ 'Command handler failed'
473
+ );
474
+ this.connection.send(this.tag + ' BAD Invalid arguments');
475
+ if (!this.countBadResponses()) {
476
+ return;
477
+ }
478
+ return next();
479
+ }
480
+ }
481
+
455
482
  validateCommand(parsed, handler, callback) {
456
483
  let schema = handler.schema || [];
457
484
  let maxArgs = schema.length;
@@ -486,6 +513,19 @@ class IMAPCommand {
486
513
  return callback(err);
487
514
  }
488
515
 
516
+ // A NIL or a list where a string is declared. Only the leading required arguments are
517
+ // checked: there the position in the schema is the position in the command, while an
518
+ // optional argument further along shifts every argument after it.
519
+ for (let i = 0; i < schema.length && !schema[i].optional; i++) {
520
+ let attr = parsed.attributes[i];
521
+ if (schema[i].type === 'string' && (!attr || Array.isArray(attr))) {
522
+ let err = new Error('Invalid arguments');
523
+ err.responseCode = 400;
524
+ err.code = 'InvalidArguments';
525
+ return callback(err);
526
+ }
527
+ }
528
+
489
529
  callback();
490
530
  }
491
531
 
@@ -22,6 +22,7 @@ const { getLocalAddress } = require('../utils/network');
22
22
 
23
23
  const { redis } = require('../db');
24
24
  const { createImapProxyAuthHandler, classifyCredentialFailure } = require('../imap-proxy-auth');
25
+ const { onRevocation } = require('../revocation-events');
25
26
  const settings = require('../settings');
26
27
 
27
28
  const { createCertHandler } = require('../cert-handler');
@@ -259,7 +260,15 @@ const createServer = function (options = {}) {
259
260
  logger,
260
261
  serverLogger,
261
262
  metrics,
262
- logRaw: EENGINE_LOG_RAW
263
+ logRaw: EENGINE_LOG_RAW,
264
+ recheck: authenticateImapProxy.recheck
265
+ });
266
+
267
+ // A revoked token, a deleted or changed account or a rotated proxy password ends the sessions
268
+ // it opened now rather than at the next periodic re-check
269
+ onRevocation(detail => {
270
+ // A change naming an account re-checks that account's sessions; anything else, all of them
271
+ server.onAuth.recheckSessions({ account: detail.account }).catch(err => logger.error({ msg: 'Proxy session re-check failed', err }));
263
272
  });
264
273
 
265
274
  return server;