emailengine-app 2.82.1 → 2.83.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 (59) hide show
  1. package/.ncurc.js +8 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +25 -0
  4. package/data/google-crawlers.json +1 -1
  5. package/lib/account.js +16 -3
  6. package/lib/api-routes/account-routes.js +8 -6
  7. package/lib/api-routes/blocklist-routes.js +4 -4
  8. package/lib/api-routes/oauth2-app-routes.js +5 -2
  9. package/lib/api-routes/route-helpers.js +28 -0
  10. package/lib/api-routes/submit-routes.js +6 -5
  11. package/lib/bounce-detect.js +4 -2
  12. package/lib/egress-filter.js +8 -3
  13. package/lib/email-client/gmail-client.js +3 -1
  14. package/lib/email-client/imap-client.js +2 -1
  15. package/lib/email-client/outlook-client.js +106 -47
  16. package/lib/email-client/outlook-fallback-poll.js +30 -0
  17. package/lib/enum-descriptions.js +3 -1
  18. package/lib/imapproxy/imap-core/README.md +1 -0
  19. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +11 -1
  20. package/lib/imapproxy/proxy-handoff.js +6 -3
  21. package/lib/imapproxy/response-error.js +14 -1
  22. package/lib/oauth/gcp-metadata.js +222 -0
  23. package/lib/oauth/gmail.js +115 -20
  24. package/lib/oauth/mail-ru.js +10 -4
  25. package/lib/oauth/outlook.js +11 -4
  26. package/lib/oauth/token-fetch.js +4 -2
  27. package/lib/oauth/verify-app.js +120 -32
  28. package/lib/oauth2-apps.js +46 -12
  29. package/lib/schemas.js +60 -18
  30. package/lib/tools.js +52 -2
  31. package/lib/ui-routes/admin-entities-routes.js +2 -2
  32. package/lib/ui-routes/auth-routes.js +4 -1
  33. package/lib/ui-routes/gmail-service-auth.js +64 -0
  34. package/lib/ui-routes/oauth-config-routes.js +8 -16
  35. package/lib/ui-routes/outlook-subscription-view.js +36 -0
  36. package/lib/ui-routes/route-helpers.js +2 -14
  37. package/lib/ui-routes/suppression-list-routes.js +2 -2
  38. package/lib/utils/network.js +29 -0
  39. package/lib/webhook-request.js +12 -4
  40. package/lib/webhook-routing.js +34 -11
  41. package/package.json +11 -11
  42. package/sbom.json +1 -1
  43. package/server.js +8 -2
  44. package/static/css/flyonui.css +1 -1
  45. package/static/js/app.js +2 -1
  46. package/static/js/ui.js +6 -1
  47. package/static/licenses.html +18 -28
  48. package/translations/messages.pot +73 -73
  49. package/views/accounts/account.hbs +5 -2
  50. package/views/accounts/edit.hbs +1 -1
  51. package/views/config/imap-proxy.hbs +1 -1
  52. package/views/config/network.hbs +7 -5
  53. package/views/config/oauth/app.hbs +2 -0
  54. package/views/config/smtp.hbs +1 -1
  55. package/views/config/tls.hbs +2 -2
  56. package/views/config/webhooks.hbs +1 -1
  57. package/views/partials/oauth_form.hbs +116 -27
  58. package/workers/api.js +4 -2
  59. package/workers/webhooks.js +18 -7
@@ -9,7 +9,8 @@ const { oauth2Apps } = require('../oauth2-apps');
9
9
  const getSecret = require('../get-secret');
10
10
  const msgpack = require('../msgpack');
11
11
  const he = require('he');
12
- const { emitChangeEvent, prepareUrl, collectCidReferences, embedCidImages, truncateTextContents, readEnvValue, getDuration } = require('../tools');
12
+ const { emitChangeEvent, prepareUrl, collectCidReferences, embedCidImages, truncateTextContents } = require('../tools');
13
+ const { parseFallbackPollInterval, FALLBACK_POLL_INTERVAL } = require('./outlook-fallback-poll');
13
14
  const { messageWebSafeHtml, applyWebSafeHtmlOptions } = require('../web-safe-html');
14
15
  const crypto = require('crypto');
15
16
  const { Gateway } = require('../gateway');
@@ -46,41 +47,21 @@ const MAX_BATCH_SIZE = graphApi.MAX_BATCH_SIZE;
46
47
  // Subscription is renewed automatically. But just in case, check once in an hour
47
48
  const RENEW_WATCH_TTL = 60 * 60 * 1000; // 1h
48
49
 
49
- const DEFAULT_FALLBACK_POLL_INTERVAL = 10 * 60 * 1000;
50
- const MIN_FALLBACK_POLL_INTERVAL = 10 * 1000;
51
-
52
- /**
53
- * Reads EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL: a duration, 0 switching the periodic pass off.
54
- * Anything unreadable gets the default, and a positive value is never shorter than ten seconds, so
55
- * a typo cannot point every account at Graph in a loop
56
- * @param {*} value - The raw environment value
57
- * @returns {number} Milliseconds, 0 when the pass is off
58
- */
59
- function parseFallbackPollInterval(value) {
60
- // blank is "unset", which getDuration() would read as 0, the value that switches the pass off
61
- const raw = String(value ?? '').trim();
62
- const duration = raw ? getDuration(raw) : DEFAULT_FALLBACK_POLL_INTERVAL;
63
- if (!Number.isFinite(duration) || duration < 0) {
64
- return DEFAULT_FALLBACK_POLL_INTERVAL;
65
- }
66
- return duration && Math.max(duration, MIN_FALLBACK_POLL_INTERVAL);
67
- }
68
-
69
50
  // When the announced set (see OutlookClient.getAnnouncedKey()) started being kept, the point a
70
51
  // recovery pass never looks back past. Renamed along with the set when it became keyed by folder,
71
52
  // so the first pass after an upgrade does not take the messages recorded in the old format for
72
53
  // unannounced ones and announce hours of mail again
73
54
  const ANNOUNCED_SINCE_FIELD = 'outlookAnnouncedInSince';
74
55
 
75
- // See setupFallbackPollTimer()
76
- const FALLBACK_POLL_INTERVAL = parseFallbackPollInterval(readEnvValue('EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL'));
77
-
78
56
  // The `serverResponseCode` a failed change subscription is reported with, and the marker that
79
57
  // tells the report apart from anything else the account may have stored. Only this client reads
80
58
  // it: reportSubscriptionFailure() writes it, clearSubscriptionFailure() lifts it, and
81
59
  // isSelfClearedErrorState() is what keeps a login from taking it along
82
60
  const SUBSCRIPTION_SETUP_ERROR_CODE = 'SubscriptionSetupError';
83
61
 
62
+ // What the stored subscription state says while no Service URL is set, see recordMissingServiceUrl()
63
+ const MISSING_SERVICE_URL_ERROR = 'Subscription failed: the Service URL is not set';
64
+
84
65
  // Graph accepts only x- prefixed names in internetMessageHeaders and rejects the whole message
85
66
  // over any other one, so the threading headers of a reply or a forward are set through the
86
67
  // MAPI properties Exchange builds them from (PidTagInReplyToId, PidTagInternetReferences)
@@ -327,6 +308,10 @@ class OutlookClient extends BaseClient {
327
308
 
328
309
  await this.getClient(true);
329
310
  await this.prepareDelegatedAccount();
311
+ if (this.delegatedAccountObject) {
312
+ // the delegate is only known now, and its token decides the route
313
+ await this.getClient(true);
314
+ }
330
315
 
331
316
  let accountData = await this.accountObject.loadAccountData();
332
317
 
@@ -2945,14 +2930,21 @@ class OutlookClient extends BaseClient {
2945
2930
  }
2946
2931
 
2947
2932
  /**
2948
- * Reports that the account has no working change subscription left to fall back on - and for a
2949
- * Graph account there is no fallback: unlike the Gmail client there is no polling timer, so a
2950
- * subscription that cannot be established means the account never sees new mail again. Both the
2951
- * creation and the renewal paths retry with backoff and then give up; giving up used to write a
2952
- * log line and nothing else, so the account went on reporting `connected`. A tenant that
2953
- * disables the Exchange Online service principal (AADSTS500014) hits this without ever failing a
2954
- * token refresh, so no authentication error fires either - reported in the field after nine
2955
- * months of accounts looking healthy and syncing nothing.
2933
+ * Reports that the account has no working change subscription left. Both the creation and the
2934
+ * renewal paths retry with backoff and then give up here.
2935
+ *
2936
+ * What that means depends on whether the mailbox can still be read. When it can, the periodic
2937
+ * recovery pass (setupFallbackPollTimer()) keeps finding new messages without a subscription,
2938
+ * so the account stays `connected` - the same treatment a Gmail account with a dead Pub/Sub
2939
+ * watch gets - and the failure stays visible on the stored subscription state, which the API
2940
+ * and the account page report. Changes to and deletions of existing messages are only ever
2941
+ * learned from notifications, so they go unreported until a subscription works again.
2942
+ *
2943
+ * When the mailbox cannot be read, or the periodic pass is switched off, nothing syncs at all,
2944
+ * and the account is reported as a `connectError`. Before that existed, giving up wrote a log
2945
+ * line and nothing else: a tenant that disables the Exchange Online service principal
2946
+ * (AADSTS500014) fails every Graph mail call without ever failing a token refresh, and was
2947
+ * reported in the field after nine months of accounts looking healthy and syncing nothing.
2956
2948
  *
2957
2949
  * Sent as `connectError` rather than `authenticationError` on purpose: the credential is fine,
2958
2950
  * and re-authorizing does not lift a disabled service principal. It also keeps the failure away
@@ -2960,9 +2952,9 @@ class OutlookClient extends BaseClient {
2960
2952
  * offer the operator only a re-authorization that cannot help.
2961
2953
  *
2962
2954
  * NB! `connectError` is not in VALID_STATES, so this also makes the account's own operations
2963
- * (reading a message, moving one) answer 503 until a subscription works again. That is the
2964
- * intended reading for an account that cannot sync at all, and it is the only reading this
2965
- * state machine offers - there is no degraded-but-usable state.
2955
+ * (reading a message, moving one) answer 503 until the mailbox can be read again. The hourly
2956
+ * renewOrCreateSubscription() pass comes back through here while the subscription keeps
2957
+ * failing, so an account moves between the two outcomes as the tenant changes.
2966
2958
  *
2967
2959
  * setErrorState() suppresses a repeat of the same code, so a permanently broken tenant produces
2968
2960
  * one webhook per distinct failure rather than one per renewal cycle
@@ -2972,7 +2964,21 @@ class OutlookClient extends BaseClient {
2972
2964
  * @returns {Promise<void>}
2973
2965
  */
2974
2966
  async reportSubscriptionFailure(stage, state, retryCount) {
2975
- this.logger.error({ msg: `Max subscription ${stage} retries exceeded`, account: this.account, retryCount });
2967
+ const probe = await this.probeMailboxWithoutSubscription();
2968
+ if (probe.readable) {
2969
+ this.logger.warn({
2970
+ msg: `MS Graph subscription ${stage} failed, new messages are found by the periodic recovery pass until it works`,
2971
+ account: this.account,
2972
+ retryCount,
2973
+ error: state?.error
2974
+ });
2975
+
2976
+ // An earlier pass may have reported the account while its mailbox could not be read
2977
+ await this.clearSubscriptionFailure();
2978
+ return;
2979
+ }
2980
+
2981
+ this.logger.error({ msg: `Max subscription ${stage} retries exceeded`, account: this.account, retryCount, err: probe.err });
2976
2982
 
2977
2983
  try {
2978
2984
  await this.notify(false, CONNECT_ERROR_NOTIFY, {
@@ -2987,6 +2993,25 @@ class OutlookClient extends BaseClient {
2987
2993
  }
2988
2994
  }
2989
2995
 
2996
+ /**
2997
+ * Whether the periodic recovery pass can stand in for the subscription: it has to be on, and
2998
+ * Graph has to list the resource the pass reads. Any failure counts, a transient one included;
2999
+ * the next hourly pass asks again
3000
+ * @returns {Promise<{readable: boolean, err?: Error}>}
3001
+ */
3002
+ async probeMailboxWithoutSubscription() {
3003
+ if (!this.fallbackPollInterval) {
3004
+ return { readable: false };
3005
+ }
3006
+
3007
+ try {
3008
+ await this.request(`/${this.oauth2UserPath}/messages`, 'get', { $select: 'id', $top: 1 });
3009
+ return { readable: true };
3010
+ } catch (err) {
3011
+ return { readable: false, err };
3012
+ }
3013
+ }
3014
+
2990
3015
  /**
2991
3016
  * A failed change subscription is this client's own report to lift. A tenant that disabled the
2992
3017
  * Exchange Online service principal keeps refreshing tokens and logging in perfectly while no
@@ -3002,9 +3027,9 @@ class OutlookClient extends BaseClient {
3002
3027
  /**
3003
3028
  * Lifts the error state reportSubscriptionFailure() left behind, once a subscription is working
3004
3029
  * again - which is every path that concludes there is a working one, not only a renewal that
3005
- * had to make a request. A subscription 60 hours from expiry is checked hourly and renewed
3006
- * once, so an account reported while it had one would have stayed in `connectError` for two
3007
- * days with notifications arriving the whole time.
3030
+ * had to make a request - or once the mailbox can be read without one. A subscription 60 hours
3031
+ * from expiry is checked hourly and renewed once, so an account reported while it had one would
3032
+ * have stayed in `connectError` for two days with notifications arriving the whole time.
3008
3033
  *
3009
3034
  * Only touches a failure this client reported, so an unrelated error state is left for whatever
3010
3035
  * owns it. A report this process wrote is visible in `this.state`; the one way a standing
@@ -3109,10 +3134,15 @@ class OutlookClient extends BaseClient {
3109
3134
  if (this.oAuth2Client && !force) {
3110
3135
  return this.oAuth2Client;
3111
3136
  }
3112
- let accountData = await (this.delegatedAccountObject || this.accountObject).loadAccountData();
3137
+ let accountObject = this.delegatedAccountObject || this.accountObject;
3138
+ let accountData = await accountObject.loadAccountData();
3113
3139
  this.oAuth2Client = await oauth2Apps.getClient(accountData.oauth2?.provider || accountData._app?.id, {
3114
3140
  logger: this.logger,
3115
- logRaw: this.options.logRaw
3141
+ logRaw: this.options.logRaw,
3142
+ // bound for the connection, like the proxy of an IMAP session: a change applies on
3143
+ // reconnect. The route of the account whose token is used, so a delegated mailbox is
3144
+ // reached the same way that token is refreshed.
3145
+ route: await accountObject.getHttpRoute(accountData)
3116
3146
  });
3117
3147
  return this.oAuth2Client;
3118
3148
  }
@@ -3170,17 +3200,18 @@ class OutlookClient extends BaseClient {
3170
3200
  * revoked - exhausts them within minutes and leaves the account with no subscription at all.
3171
3201
  * This pass used to read that count, find it at the cap and give up, waiting for a reconnect
3172
3202
  * that only a worker restart, an account update or a re-authorization brings; a tenant that
3173
- * fixed the cause an hour later was never noticed. A failed subscription reports
3174
- * `connectError`, which pauses the periodic recovery pass too, so an account left unsubscribed
3175
- * syncs nothing at all while it waits. The counters are cleared before anything else is attempted, so an hour that could have
3203
+ * fixed the cause an hour later was never noticed. It is also what moves an account between
3204
+ * the two outcomes of reportSubscriptionFailure() while the subscription keeps failing.
3205
+ *
3206
+ * The counters are cleared before anything else is attempted, so an hour that could have
3176
3207
  * recovered gets the fast ladder back instead of one attempt every hour forever - a renewal
3177
3208
  * ladder as much as a creation one, since a subscription inside the renew window whose retries
3178
3209
  * are spent is not recreated by this pass at all and would otherwise never get another.
3179
3210
  *
3180
3211
  * A failing account is not heard twice, but it is logged twice: reportSubscriptionFailure()
3181
3212
  * stores the same serverResponseCode every pass, which is what setErrorState() suppresses a
3182
- * repeat notification on, while the log line it writes recurs hourly. The account stays in
3183
- * `connectError` until a creation actually succeeds.
3213
+ * repeat notification on, while the log line it writes recurs hourly. A reported account stays
3214
+ * in `connectError` until a creation succeeds or its mailbox can be listed again.
3184
3215
  *
3185
3216
  * @returns {Promise<void>}
3186
3217
  */
@@ -3682,6 +3713,33 @@ class OutlookClient extends BaseClient {
3682
3713
  }
3683
3714
  }
3684
3715
 
3716
+ /**
3717
+ * A subscription cannot be created without a Service URL, since Graph has nowhere to deliver
3718
+ * notifications to. That used to be a log line and nothing else, so the account page showed no
3719
+ * subscription problem at all; it is recorded on the stored subscription state now, which the
3720
+ * API and the page report. It is not reported as an account error: one instance-wide setting
3721
+ * would put every Outlook account into `connectError` at once, while each of them keeps finding
3722
+ * new messages through the periodic recovery pass. A subscription that already exists is left
3723
+ * alone, since it keeps notifying the address it was created with and renewing it needs no
3724
+ * Service URL, and an unchanged record is not written again on every hourly pass
3725
+ * @returns {Promise<void>}
3726
+ */
3727
+ async recordMissingServiceUrl() {
3728
+ try {
3729
+ const outlookSubscription = await this.getStoredSubscription();
3730
+ if (outlookSubscription.id || outlookSubscription.state?.error === MISSING_SERVICE_URL_ERROR) {
3731
+ return;
3732
+ }
3733
+
3734
+ outlookSubscription.state = { state: 'error', error: MISSING_SERVICE_URL_ERROR, time: Date.now() };
3735
+ await this.saveStoredSubscription(outlookSubscription);
3736
+ this.subscriptionState = 'failed';
3737
+ } catch (err) {
3738
+ // Best effort: init() awaits ensureSubscription()
3739
+ this.logger.error({ msg: 'Failed to record the missing Service URL', account: this.account, err });
3740
+ }
3741
+ }
3742
+
3685
3743
  /**
3686
3744
  * Ensure webhook subscription exists and is valid
3687
3745
  * Creates new subscription or renews existing one
@@ -3695,7 +3753,8 @@ class OutlookClient extends BaseClient {
3695
3753
  let notificationBaseUrl = (await settings.get('notificationBaseUrl')) || serviceUrl || '';
3696
3754
 
3697
3755
  if (!serviceUrl) {
3698
- this.logger.error({ msg: 'Cannot create MS Graph subscription, service URL is not set' });
3756
+ this.logger.error({ msg: 'Cannot create MS Graph subscription, service URL is not set', account: this.account });
3757
+ await this.recordMissingServiceUrl();
3699
3758
  return false;
3700
3759
  }
3701
3760
 
@@ -0,0 +1,30 @@
1
+ 'use strict';
2
+
3
+ const { readEnvValue, getDuration } = require('../tools');
4
+
5
+ const DEFAULT_FALLBACK_POLL_INTERVAL = 10 * 60 * 1000;
6
+ const MIN_FALLBACK_POLL_INTERVAL = 10 * 1000;
7
+
8
+ /**
9
+ * Reads EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL: a duration, 0 switching the periodic pass off.
10
+ * Anything unreadable gets the default, and a positive value is never shorter than ten seconds, so
11
+ * a typo cannot point every account at Graph in a loop
12
+ * @param {*} value - The raw environment value
13
+ * @returns {number} Milliseconds, 0 when the pass is off
14
+ */
15
+ function parseFallbackPollInterval(value) {
16
+ // blank is "unset", which getDuration() would read as 0, the value that switches the pass off
17
+ const raw = String(value ?? '').trim();
18
+ const duration = raw ? getDuration(raw) : DEFAULT_FALLBACK_POLL_INTERVAL;
19
+ if (!Number.isFinite(duration) || duration < 0) {
20
+ return DEFAULT_FALLBACK_POLL_INTERVAL;
21
+ }
22
+ return duration && Math.max(duration, MIN_FALLBACK_POLL_INTERVAL);
23
+ }
24
+
25
+ // The interval of the periodic missed-notification recovery pass (OutlookClient.setupFallbackPollTimer()).
26
+ // Its own module so the admin UI, which runs in the API worker, reads the same value the account
27
+ // workers run with
28
+ const FALLBACK_POLL_INTERVAL = parseFallbackPollInterval(readEnvValue('EENGINE_OUTLOOK_FALLBACK_POLL_INTERVAL'));
29
+
30
+ module.exports = { parseFallbackPollInterval, FALLBACK_POLL_INTERVAL };
@@ -227,7 +227,9 @@ const ENUM_DESCRIPTIONS = {
227
227
 
228
228
  gmailAuthMethod: {
229
229
  serviceKey: 'Sign token requests with an uploaded service account key',
230
- externalAccount: 'Sign token requests through Workload Identity Federation, with no key to store'
230
+ externalAccount: 'Sign token requests through Workload Identity Federation, with no key to store',
231
+ metadataServer:
232
+ 'Use the service account attached to the Google Cloud VM, GKE workload or Cloud Run service EmailEngine runs on, read from the metadata server. Cloud Pub/Sub applications only, and not available to a token with restricted permissions'
231
233
  }
232
234
  };
233
235
 
@@ -32,6 +32,7 @@ means re-applying these.
32
32
  | `31f6a590` | 2026-07-26 | Fix the dead teardown guard in the notification listener |
33
33
  | `74856cf6` | 2026-09-02 | Drop the built-in self-signed key/certificate pair from `tls-options.js`; a listener with TLS and no certificate is refused at startup instead of served with a key that ships in every copy |
34
34
  | `2db748fc` | 2026-09-28 | Cap list nesting depth in the parser and guard the debug-log compile; check the command state before accepting a literal and cap literal count/bytes per command; `maxConnections`; error listener and timeout while waiting for the PROXY header; hand bytes pipelined after LOGIN to the proxy (`unbind()` returns `head` and `closed`); lazy indexer load in `imap-tools.js`; indexer `drain` wait and quoted-printable decoding fixes; removed the unused root `memory-notifier.js` |
35
+ | `8b89a612` | 2026-10-07 | `AUTHENTICATE PLAIN` answers an `onAuth` error that names no IMAP response with `NO [TEMPFAIL]` the way LOGIN does, instead of reflecting its message as BAD |
35
36
 
36
37
  Earlier local changes (`09085d12`, `0a389560`, `7e2e94f3`, `04c2aa90`, `1d6df05e`, `612d9f96`,
37
38
  `13edec58`, `2e0bf1ce`, `b9a3e06c`, `b58a827e`, `1813f089`) are maintenance: dependency swaps
@@ -74,6 +74,13 @@ function authenticate(connection, token, requireClientToken, callback) {
74
74
  connection.session,
75
75
  (err, response) => {
76
76
  if (err) {
77
+ // An error naming its IMAP response is answered as that response. Anything else is
78
+ // an internal fault whose message belongs in the log and not on the wire, and that
79
+ // is answered the way LOGIN answers it - handing the error back would send its text
80
+ // as BAD and count it against the connection's bad-command budget
81
+ if (err.response) {
82
+ return callback(null, err);
83
+ }
77
84
  connection._server.logger.info(
78
85
  {
79
86
  err,
@@ -88,7 +95,10 @@ function authenticate(connection, token, requireClientToken, callback) {
88
95
  'PLAIN',
89
96
  err.message
90
97
  );
91
- return callback(err);
98
+ return callback(null, {
99
+ response: 'NO',
100
+ code: 'TEMPFAIL'
101
+ });
92
102
  }
93
103
 
94
104
  if (!response || !response.user) {
@@ -6,7 +6,7 @@
6
6
 
7
7
  const { PassThrough } = require('stream');
8
8
  const { imapHandler } = require('./imap-core/index.js');
9
- const { isImapResponseError, toImapResponseError } = require('./response-error');
9
+ const { isImapResponseError, toImapResponseError, faultResponseError } = require('./response-error');
10
10
 
11
11
  class PassThroughLogger extends PassThrough {
12
12
  constructor(opts = {}) {
@@ -52,14 +52,17 @@ class PassThroughLogger extends PassThrough {
52
52
  */
53
53
  function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, metrics, logRaw }) {
54
54
  // A refusal or a temporary failure the client is told to retry is a warning and reaches the
55
- // client as the IMAP response it carries; anything else is a proxy fault
55
+ // client as the IMAP response it carries; anything else is a proxy fault, logged here and
56
+ // answered with a generic response so its text never reaches the client. Handing the fault
57
+ // itself to imap-core sent that text as BAD, which also counted against the connection's
58
+ // bad-command budget.
56
59
  const loginFailure = (err, fields, messages) => {
57
60
  if (isImapResponseError(err)) {
58
61
  serverLogger.warn(Object.assign({ msg: messages.response }, fields, { err }));
59
62
  return toImapResponseError(err);
60
63
  }
61
64
  serverLogger.error(Object.assign({ msg: messages.fault }, fields, { err }));
62
- return err;
65
+ return faultResponseError();
63
66
  };
64
67
 
65
68
  // Wires the two legs together once imap-core hands over the client socket
@@ -30,4 +30,17 @@ function toImapResponseError(err) {
30
30
  return error;
31
31
  }
32
32
 
33
- module.exports = { isImapResponseError, toImapResponseError };
33
+ /**
34
+ * The response an internal proxy fault is answered with. The fault's own text (an upstream or a
35
+ * Redis error, a configuration problem) belongs in the log and not on the wire: a client that has
36
+ * not logged in is told that the service is temporarily unavailable, with RFC 5530's code for it.
37
+ *
38
+ * @returns {Error} A new error carrying the response line to send
39
+ */
40
+ function faultResponseError() {
41
+ let error = new Error('[UNAVAILABLE] Temporary failure, try again later');
42
+ error.response = 'NO';
43
+ return error;
44
+ }
45
+
46
+ module.exports = { isImapResponseError, toImapResponseError, faultResponseError };
@@ -0,0 +1,222 @@
1
+ 'use strict';
2
+
3
+ // The Google Cloud metadata server: the credentials of the service account attached to the
4
+ // Compute Engine VM, GKE pod (Workload Identity) or Cloud Run service EmailEngine runs on. Used by
5
+ // the `metadataServer` authentication method of a Cloud Pub/Sub app, which stores no secret at all.
6
+ //
7
+ // The host is fixed in code and can only be moved from the environment. It is deliberately not an
8
+ // application or settings field: these requests bypass the HTTP proxy and the webhook egress policy
9
+ // (the metadata server is reachable only from this host, and 169.254.169.254 is exactly what the
10
+ // default egress policy blocks), and the verify report echoes what came back. A host that an API
11
+ // token with `oauth2` or `settings` write could choose would turn that into a probe of the
12
+ // instance's own network. The environment belongs to whoever deployed the instance, who already
13
+ // holds the encryption secret and the Redis URL. Only the host moves: the paths, the
14
+ // `Metadata-Flavor` header and the http scheme are fixed, so this never becomes a general fetcher.
15
+ //
16
+ // No dependency on lib/tools.js on purpose: that module opens Redis on require, and this one has
17
+ // to stay testable as a pure helper.
18
+
19
+ const timers = require('timers/promises');
20
+ const { fetch: undiciFetch, Agent } = require('undici');
21
+ const packageData = require('../../package.json');
22
+ const { makeError } = require('./external-account-config');
23
+
24
+ // Google recommends the DNS name over 169.254.169.254, and it fails safer: it resolves only on
25
+ // Google Cloud, so on any other host the request ends at once with ENOTFOUND, instead of waiting
26
+ // out a connect timeout or reaching another cloud's instance metadata service at the same address
27
+ const DEFAULT_METADATA_HOST = 'metadata.google.internal';
28
+
29
+ // EmailEngine's own name first; GCE_METADATA_HOST is what every Google client library reads, so an
30
+ // existing emulator or metadata proxy setup keeps working without a second variable
31
+ const METADATA_HOST_ENV_KEYS = ['EENGINE_GCP_METADATA_HOST', 'GCE_METADATA_HOST'];
32
+
33
+ const TOKEN_PATH = '/computeMetadata/v1/instance/service-accounts/default/token';
34
+ const EMAIL_PATH = '/computeMetadata/v1/instance/service-accounts/default/email';
35
+ const PROJECT_ID_PATH = '/computeMetadata/v1/project/project-id';
36
+
37
+ // Required on every request, and sent back by the metadata server on its answers. Checking the
38
+ // answer is what tells the Google metadata server from something else listening at the address
39
+ const FLAVOR_HEADER = 'Metadata-Flavor';
40
+ const FLAVOR_VALUE = 'Google';
41
+
42
+ const REQUEST_TIMEOUT = 10 * 1000;
43
+
44
+ // Google documents sub-second 503 answers during host maintenance, so one quick retry covers them
45
+ const MAINTENANCE_RETRY_DELAY = 500;
46
+
47
+ // Upper bound on response text kept on an error, which the verify report can surface
48
+ const MAX_RESPONSE_TEXT = 512;
49
+
50
+ const USER_AGENT = `${packageData.name}/${packageData.version} (+${packageData.homepage})`;
51
+
52
+ // Never the shared proxy dispatcher: a proxy cannot reach the metadata server, and the request
53
+ // would hand it the access token that comes back
54
+ const metadataAgent = new Agent({
55
+ connectTimeout: 3 * 1000,
56
+ headersTimeout: REQUEST_TIMEOUT,
57
+ bodyTimeout: REQUEST_TIMEOUT
58
+ });
59
+
60
+ /**
61
+ * Resolves the origin the metadata server is reached at.
62
+ *
63
+ * An override takes `host`, `host:port` or `http://host[:port]`. Anything else (https, a path, a
64
+ * query, credentials) is refused rather than replaced by the default: an override that is quietly
65
+ * ignored sends a test setup to the real metadata server, which is the worse way to fail.
66
+ *
67
+ * @param {Object} [env=process.env] - environment to read
68
+ * @returns {string} the origin, e.g. `http://metadata.google.internal`
69
+ */
70
+ function resolveMetadataOrigin(env) {
71
+ env = env || process.env;
72
+
73
+ for (let key of METADATA_HOST_ENV_KEYS) {
74
+ let raw = (env[key] || '').toString().trim();
75
+ if (!raw) {
76
+ continue;
77
+ }
78
+
79
+ let candidate = /^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `http://${raw}`;
80
+ let url;
81
+ try {
82
+ url = new URL(candidate);
83
+ } catch (err) {
84
+ url = null;
85
+ }
86
+
87
+ if (!url || url.protocol !== 'http:' || !url.hostname || url.username || url.password || url.pathname !== '/' || url.search || url.hash) {
88
+ throw makeError(`${key} must be a host name or host:port of the metadata server, got ${JSON.stringify(raw)}`, 'EMetadataConfig');
89
+ }
90
+
91
+ return url.origin;
92
+ }
93
+
94
+ return `http://${DEFAULT_METADATA_HOST}`;
95
+ }
96
+
97
+ function describeNetworkError(err) {
98
+ let cause = (err && err.cause) || err;
99
+ if (cause && (cause.name === 'TimeoutError' || cause.name === 'AbortError')) {
100
+ return `no answer within ${Math.round(REQUEST_TIMEOUT / 1000)}s`;
101
+ }
102
+ return (cause && (cause.code || cause.message)) || 'connection failed';
103
+ }
104
+
105
+ /**
106
+ * GETs one metadata path and returns the response text.
107
+ *
108
+ * @param {string} path - one of the fixed metadata paths
109
+ * @param {Object} [opts]
110
+ * @param {Object} [opts.env] - environment to resolve the host from (tests)
111
+ * @param {Function} [opts.fetchImpl] - fetch implementation (tests)
112
+ * @returns {Promise<string>}
113
+ */
114
+ async function metadataRequest(path, opts) {
115
+ opts = opts || {};
116
+ const fetchImpl = opts.fetchImpl || undiciFetch;
117
+
118
+ let origin = resolveMetadataOrigin(opts.env);
119
+
120
+ for (let attempt = 0; ; attempt++) {
121
+ let res;
122
+ let body;
123
+ try {
124
+ res = await fetchImpl(origin + path, {
125
+ method: 'GET',
126
+ headers: { [FLAVOR_HEADER]: FLAVOR_VALUE, 'User-Agent': USER_AGENT },
127
+ redirect: 'error',
128
+ dispatcher: metadataAgent,
129
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT)
130
+ });
131
+ body = await res.text();
132
+ } catch (err) {
133
+ throw makeError(`The metadata server at ${origin} could not be reached (${describeNetworkError(err)})`, 'EMetadataUnreachable', null, {
134
+ cause: err
135
+ });
136
+ }
137
+
138
+ if (res.status === 503 && attempt === 0) {
139
+ await timers.setTimeout(MAINTENANCE_RETRY_DELAY);
140
+ continue;
141
+ }
142
+
143
+ if (!res.ok) {
144
+ throw makeError(`The metadata server at ${origin} returned HTTP ${res.status} for ${path}`, 'EMetadataServer', res.status, {
145
+ responseText: body.slice(0, MAX_RESPONSE_TEXT)
146
+ });
147
+ }
148
+
149
+ if (res.headers.get(FLAVOR_HEADER) !== FLAVOR_VALUE) {
150
+ throw makeError(
151
+ `The server at ${origin} is not a Google Cloud metadata server (no "${FLAVOR_HEADER}: ${FLAVOR_VALUE}" header)`,
152
+ 'EMetadataServer',
153
+ null,
154
+ {
155
+ wrongFlavor: true
156
+ }
157
+ );
158
+ }
159
+
160
+ return body;
161
+ }
162
+ }
163
+
164
+ /**
165
+ * Fetches an access token for the attached service account.
166
+ *
167
+ * The metadata server caches the token itself and hands out the same one until five minutes before
168
+ * it expires, so asking again is cheap; the caller still caches it like any other service token.
169
+ *
170
+ * @param {Object} [opts] - see metadataRequest()
171
+ * @returns {Promise<{ access_token: string, expires_in: number, token_type: string }>}
172
+ */
173
+ async function fetchAccessToken(opts) {
174
+ let body = await metadataRequest(TOKEN_PATH, opts);
175
+
176
+ let data;
177
+ try {
178
+ data = JSON.parse(body);
179
+ } catch (err) {
180
+ data = null;
181
+ }
182
+
183
+ if (!data || typeof data.access_token !== 'string' || !data.access_token) {
184
+ throw makeError('The metadata server answered without an access token', 'EMetadataResponse');
185
+ }
186
+
187
+ let expiresIn = Number(data.expires_in);
188
+
189
+ return {
190
+ access_token: data.access_token,
191
+ expires_in: Number.isFinite(expiresIn) && expiresIn > 0 ? expiresIn : undefined,
192
+ token_type: data.token_type || 'Bearer'
193
+ };
194
+ }
195
+
196
+ /**
197
+ * Reads the attached service account's email address.
198
+ *
199
+ * @param {Object} [opts] - see metadataRequest()
200
+ * @returns {Promise<string>}
201
+ */
202
+ async function fetchServiceAccountEmail(opts) {
203
+ return (await metadataRequest(EMAIL_PATH, opts)).trim();
204
+ }
205
+
206
+ /**
207
+ * Reads the attached service account's email address and the project id.
208
+ *
209
+ * @param {Object} [opts] - see metadataRequest()
210
+ * @returns {Promise<{ serviceAccountEmail: string, projectId: string }>}
211
+ */
212
+ async function describeAttachedIdentity(opts) {
213
+ let [serviceAccountEmail, projectId] = await Promise.all([fetchServiceAccountEmail(opts), metadataRequest(PROJECT_ID_PATH, opts)]);
214
+ return { serviceAccountEmail, projectId: projectId.trim() };
215
+ }
216
+
217
+ module.exports = {
218
+ resolveMetadataOrigin,
219
+ fetchAccessToken,
220
+ fetchServiceAccountEmail,
221
+ describeAttachedIdentity
222
+ };