emailengine-app 2.83.0 → 2.83.2

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 (52) hide show
  1. package/.release-please-manifest.json +1 -1
  2. package/CHANGELOG.md +21 -0
  3. package/data/google-crawlers.json +1 -1
  4. package/gettext-extract.js +95 -15
  5. package/lib/api-reference/format.js +1 -1
  6. package/lib/api-routes/export-routes.js +5 -5
  7. package/lib/api-routes/oauth2-app-routes.js +4 -1
  8. package/lib/api-routes/route-helpers.js +11 -5
  9. package/lib/consts.js +3 -1
  10. package/lib/email-client/base-client.js +44 -20
  11. package/lib/email-client/credential-errors.js +3 -31
  12. package/lib/email-client/smtp-pool-manager.js +25 -6
  13. package/lib/export.js +44 -36
  14. package/lib/imapproxy/imap-core/lib/commands/starttls.js +4 -2
  15. package/lib/imapproxy/imap-core/lib/imap-server.js +44 -11
  16. package/lib/imapproxy/proxy-handoff.js +10 -1
  17. package/lib/logger.js +3 -2
  18. package/lib/message-port-stream.js +23 -0
  19. package/lib/network-errors.js +50 -0
  20. package/lib/oauth/gcp-metadata.js +50 -13
  21. package/lib/oauth/gmail.js +17 -7
  22. package/lib/oauth/mail-ru.js +5 -1
  23. package/lib/oauth/outlook.js +5 -1
  24. package/lib/oauth/pubsub/google.js +3 -2
  25. package/lib/oauth/token-fetch.js +2 -3
  26. package/lib/oauth/verify-app.js +8 -2
  27. package/lib/oauth2-apps.js +26 -6
  28. package/lib/sub-script.js +10 -3
  29. package/lib/swagger-options.js +2 -3
  30. package/lib/tools.js +16 -2
  31. package/lib/ui-routes/oauth-config-routes.js +14 -15
  32. package/lib/ui-routes/oauth-form-context.js +19 -0
  33. package/package.json +10 -10
  34. package/sbom.json +1 -1
  35. package/static/css/flyonui.css +1 -1
  36. package/static/licenses.html +12 -12
  37. package/translations/README.md +3 -2
  38. package/translations/messages.pot +257 -257
  39. package/views/accounts/account.hbs +0 -5
  40. package/views/config/oauth/edit.hbs +0 -10
  41. package/views/config/oauth/new.hbs +0 -10
  42. package/views/partials/oauth_form.hbs +426 -928
  43. package/views/partials/oauth_graph_endpoints.hbs +12 -0
  44. package/views/partials/oauth_pubsub_app_select.hbs +11 -20
  45. package/views/partials/oauth_scope_presets.hbs +21 -0
  46. package/views/partials/ui/choice-tab.hbs +23 -0
  47. package/views/partials/ui/choice-tabs.hbs +32 -0
  48. package/views/partials/ui/radio.hbs +2 -2
  49. package/views/partials/ui/secret-field.hbs +2 -1
  50. package/views/partials/ui/tabs.hbs +1 -2
  51. package/workers/imap.js +10 -3
  52. package/workers/smtp.js +16 -1
@@ -20,6 +20,9 @@ const MAX_PROXY_HEADER_SIZE = 256;
20
20
  // has not produced it by then is not a proxy we are waiting on, and it must not hold an fd forever.
21
21
  const PROXY_HEADER_TIMEOUT = 10 * 1000;
22
22
 
23
+ // How long an implicit TLS client has to complete its handshake
24
+ const TLS_HANDSHAKE_TIMEOUT = 30 * 1000;
25
+
23
26
  /**
24
27
  * Creates a IMAP server instance.
25
28
  *
@@ -258,6 +261,20 @@ class IMAPServer extends EventEmitter {
258
261
  socket.once('close', () => {
259
262
  this._socketCount--;
260
263
  });
264
+
265
+ // The non-PROXY path hands the socket over a tick later, with no error listener on it until
266
+ // then; a reset in that window would be uncaught and take down the whole worker
267
+ socket.on('error', err => {
268
+ this.logger.debug(
269
+ {
270
+ tnx: 'connect',
271
+ remoteAddress: socket.remoteAddress,
272
+ err
273
+ },
274
+ 'Socket error on accepted connection: %s',
275
+ err && err.message
276
+ );
277
+ });
261
278
  return true;
262
279
  }
263
280
 
@@ -414,10 +431,24 @@ class IMAPServer extends EventEmitter {
414
431
 
415
432
  let remoteAddress = socket.remoteAddress;
416
433
 
417
- let errorTimer = false;
434
+ // A client-side failure to establish the session, logged quietly
435
+ let socketError = message => {
436
+ let err = new Error(message);
437
+ err.responseCode = 500;
438
+ err.code = 'SocketError';
439
+ err.report = false;
440
+ err.meta = {
441
+ protocol: 'imap',
442
+ stage: 'connect',
443
+ remoteAddress
444
+ };
445
+ return err;
446
+ };
447
+
448
+ let handshakeTimer = false;
418
449
  let returned = false;
419
450
  let onError = err => {
420
- clearTimeout(errorTimer);
451
+ clearTimeout(handshakeTimer);
421
452
  if (returned) {
422
453
  return;
423
454
  }
@@ -435,15 +466,7 @@ class IMAPServer extends EventEmitter {
435
466
  };
436
467
  }
437
468
  if (!err || !err.message) {
438
- err = new Error('Socket closed while initiating TLS');
439
- err.responseCode = 500;
440
- err.code = 'SocketError';
441
- err.report = false;
442
- err.meta = {
443
- protocol: 'imap',
444
- stage: 'connect',
445
- remoteAddress
446
- };
469
+ err = socketError('Socket closed while initiating TLS');
447
470
  }
448
471
  callback(err);
449
472
  };
@@ -466,7 +489,17 @@ class IMAPServer extends EventEmitter {
466
489
  tlsSocket.once('clientError', onError);
467
490
  tlsSocket.once('tlsClientError', onError);
468
491
 
492
+ // Without this a client that never completes the handshake holds its socket and its
493
+ // maxConnections slot for good: the PROXY header timeout is already cleared, and the
494
+ // session's own socket timeout only starts after the handshake
495
+ handshakeTimer = setTimeout(() => {
496
+ onError(socketError('TLS handshake timed out'));
497
+ tlsSocket.destroy();
498
+ socket.destroy();
499
+ }, Number(this.options.tlsHandshakeTimeout) || TLS_HANDSHAKE_TIMEOUT);
500
+
469
501
  tlsSocket.on('secure', () => {
502
+ clearTimeout(handshakeTimer);
470
503
  socket.removeListener('error', onError);
471
504
  tlsSocket.removeListener('close', onCloseError);
472
505
  tlsSocket.removeListener('error', onError);
@@ -200,8 +200,9 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
200
200
  // stored account data (the login name is the same id, kept as a fallback).
201
201
  const account = (accountData && accountData.account) || login.username;
202
202
 
203
+ let downstream;
203
204
  try {
204
- const downstream = await createProxy({ imapConfig, id: session.id, logger: logger.child({ property: 'upstream', account }) });
205
+ downstream = await createProxy({ imapConfig, id: session.id, logger: logger.child({ property: 'upstream', account }) });
205
206
 
206
207
  session.onProxy = upstream => attachProxy({ session, account, downstream, upstream });
207
208
 
@@ -215,6 +216,14 @@ function createProxyAuthHandler({ onAuth, createProxy, logger, serverLogger, met
215
216
  );
216
217
  }
217
218
  } catch (err) {
219
+ // The client is refused, so an upstream session already opened has no one to serve
220
+ if (downstream && downstream.imapClient) {
221
+ try {
222
+ downstream.imapClient.close();
223
+ } catch (closeErr) {
224
+ logger.warn({ msg: 'Failed to close upstream connection', account, cid: session.id, err: closeErr });
225
+ }
226
+ }
218
227
  throw loginFailure(err, { account, cid: session.id }, { response: 'Upstream authentication failed', fault: 'Failed to create proxy' });
219
228
  }
220
229
 
package/lib/logger.js CHANGED
@@ -7,7 +7,8 @@ if (!process.env.EE_ENV_LOADED) {
7
7
 
8
8
  const config = require('@zone-eu/wild-config');
9
9
  const pino = require('pino');
10
- const { TRANSIENT_NETWORK_CODES, REDACTED_LOG_KEYS } = require('./consts');
10
+ const { REDACTED_LOG_KEYS } = require('./consts');
11
+ const { isTransientNetworkError } = require('./network-errors');
11
12
 
12
13
  config.log = config.log || {
13
14
  level: 'trace'
@@ -21,7 +22,7 @@ config.log.level = config.log.level || 'trace';
21
22
  // error tracking, where they pile up as useless "fetch failed" reports. Genuine
22
23
  // TypeError/RangeError bugs have no network errno cause and still get reported.
23
24
  function isTransientFetchError(err) {
24
- return err && err.name === 'TypeError' && err.cause && TRANSIENT_NETWORK_CODES.has(err.cause.code);
25
+ return err && err.name === 'TypeError' && isTransientNetworkError(err);
25
26
  }
26
27
 
27
28
  let logger = pino({
@@ -15,6 +15,11 @@ const { Writable, Readable, pipeline } = require('stream');
15
15
  const DEFAULT_CREDIT_WINDOW = 1024 * 1024;
16
16
  const ACK_BATCH_FRACTION = 4;
17
17
 
18
+ // How long a write may wait for credit before the transfer is abandoned. A consumer that stops
19
+ // reading without disconnecting never cancels, and the IMAP download feeding this writer would
20
+ // hold the account's mailbox lock for as long as its socket lived.
21
+ const DEFAULT_STALL_TIMEOUT = 5 * 60 * 1000;
22
+
18
23
  class MessagePortWritable extends Writable {
19
24
  constructor(messagePort, opts) {
20
25
  super();
@@ -24,6 +29,9 @@ class MessagePortWritable extends Writable {
24
29
  this.credit = (opts && opts.creditWindow) || DEFAULT_CREDIT_WINDOW;
25
30
  this.pendingWrite = null;
26
31
 
32
+ this.stallTimeout = (opts && opts.stallTimeout) || DEFAULT_STALL_TIMEOUT;
33
+ this.stallTimer = null;
34
+
27
35
  // The reader side posts { cancel: true } when it is torn down (e.g. the
28
36
  // HTTP client aborted the download). Stop the transfer so the upstream
29
37
  // source - and the IMAP lock it holds - is released.
@@ -37,7 +45,11 @@ class MessagePortWritable extends Writable {
37
45
  if (this.pendingWrite && this.credit > 0) {
38
46
  let done = this.pendingWrite;
39
47
  this.pendingWrite = null;
48
+ clearTimeout(this.stallTimer);
40
49
  done();
50
+ } else if (this.pendingWrite) {
51
+ // Credit is still short, but the reader did take something: that is progress
52
+ this.stallTimer.refresh();
41
53
  }
42
54
  }
43
55
  };
@@ -110,6 +122,12 @@ class MessagePortWritable extends Writable {
110
122
  }
111
123
  // Out of credit: the next write waits until the reader has taken some of what was sent
112
124
  this.pendingWrite = done;
125
+ this.stallTimer = setTimeout(() => {
126
+ let err = new Error('Message stream consumer stopped reading');
127
+ err.code = 'ConsumerStalled';
128
+ this.destroy(err);
129
+ }, this.stallTimeout);
130
+ this.stallTimer.unref();
113
131
  }
114
132
 
115
133
  _final(done) {
@@ -121,6 +139,7 @@ class MessagePortWritable extends Writable {
121
139
  _destroy(err, done) {
122
140
  // A write waiting for credit is abandoned with the stream; destroy() does not wait for it
123
141
  this.pendingWrite = null;
142
+ clearTimeout(this.stallTimer);
124
143
 
125
144
  // Abnormal termination: tell the reader so a truncated transfer is not
126
145
  // mistaken for a complete message, then release the port.
@@ -278,6 +297,10 @@ function pipeToMessagePort(source, writable, logger) {
278
297
  }
279
298
  return;
280
299
  }
300
+ if (err.code === 'ConsumerStalled') {
301
+ logger.warn?.({ msg: 'Message stream transfer abandoned, the consumer stopped reading', err });
302
+ return;
303
+ }
281
304
  if (typeof logger.error === 'function') {
282
305
  logger.error({ msg: 'Message stream transfer failed', err });
283
306
  }
@@ -0,0 +1,50 @@
1
+ 'use strict';
2
+
3
+ // How a failed outbound HTTP request is told apart from a refused or broken one. undici raises
4
+ // every connection failure as a generic TypeError ("fetch failed", "terminated") with the real
5
+ // DNS/socket/timeout error on err.cause, so a check of err.code alone misses all of them.
6
+ //
7
+ // Dependency-free apart from consts, so lib/logger.js can use it without a require cycle.
8
+
9
+ const { TRANSIENT_NETWORK_CODES } = require('./consts');
10
+
11
+ // How far down a cause chain the transient check looks. A chain is not guaranteed to be finite - an
12
+ // error may cite itself - so the walk is bounded rather than trusting it to end.
13
+ const MAX_CAUSE_DEPTH = 5;
14
+
15
+ /**
16
+ * Failing to reach a remote endpoint is a connection problem, not a rejected credential or a bug.
17
+ *
18
+ * The whole cause chain is searched, not one level: a caller that wraps an undici failure in an
19
+ * error of its own pushes the code one level deeper (lib/oauth/external-account-signer.js does
20
+ * exactly that for its Workload Identity Federation requests).
21
+ *
22
+ * @param {Error} err - The error to check
23
+ * @returns {boolean} True if the error, or anything it was caused by, is a transient network failure
24
+ */
25
+ function isTransientNetworkError(err) {
26
+ for (let cause = err, depth = 0; cause && typeof cause === 'object' && depth < MAX_CAUSE_DEPTH; cause = cause.cause, depth++) {
27
+ if (TRANSIENT_NETWORK_CODES.has(cause.code)) {
28
+ return true;
29
+ }
30
+ }
31
+
32
+ return false;
33
+ }
34
+
35
+ /**
36
+ * Copies the code of an undici failure from err.cause onto the error itself, so callers that read
37
+ * err.code (and the webhook and log payloads built from it) see ECONNRESET or UND_ERR_BODY_TIMEOUT
38
+ * rather than nothing. Leaves an error that already carries a code alone.
39
+ *
40
+ * @param {Error} err - The error thrown by fetch()
41
+ * @returns {Error} The same error
42
+ */
43
+ function promoteCauseCode(err) {
44
+ if (err && !err.code && err.cause && err.cause.code) {
45
+ err.code = err.cause.code;
46
+ }
47
+ return err;
48
+ }
49
+
50
+ module.exports = { isTransientNetworkError, promoteCauseCode };
@@ -14,12 +14,13 @@
14
14
  // `Metadata-Flavor` header and the http scheme are fixed, so this never becomes a general fetcher.
15
15
  //
16
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.
17
+ // to stay testable as a pure helper. lib/read-env-value.js is the leaf it splits out for that.
18
18
 
19
19
  const timers = require('timers/promises');
20
20
  const { fetch: undiciFetch, Agent } = require('undici');
21
21
  const packageData = require('../../package.json');
22
22
  const { makeError } = require('./external-account-config');
23
+ const { readEnvValue } = require('../read-env-value');
23
24
 
24
25
  // Google recommends the DNS name over 169.254.169.254, and it fails safer: it resolves only on
25
26
  // Google Cloud, so on any other host the request ends at once with ENOTFOUND, instead of waiting
@@ -64,14 +65,13 @@ const metadataAgent = new Agent({
64
65
  * query, credentials) is refused rather than replaced by the default: an override that is quietly
65
66
  * ignored sends a test setup to the real metadata server, which is the worse way to fail.
66
67
  *
67
- * @param {Object} [env=process.env] - environment to read
68
+ * @param {Object} [env] - environment to read (tests); the process environment, through readEnvValue(), when omitted
68
69
  * @returns {string} the origin, e.g. `http://metadata.google.internal`
69
70
  */
70
71
  function resolveMetadataOrigin(env) {
71
- env = env || process.env;
72
-
73
72
  for (let key of METADATA_HOST_ENV_KEYS) {
74
- let raw = (env[key] || '').toString().trim();
73
+ // readEnvValue() so the <KEY>_FILE form works here as it does for every other value
74
+ let raw = ((env ? env[key] : readEnvValue(key)) || '').toString().trim();
75
75
  if (!raw) {
76
76
  continue;
77
77
  }
@@ -94,14 +94,44 @@ function resolveMetadataOrigin(env) {
94
94
  return `http://${DEFAULT_METADATA_HOST}`;
95
95
  }
96
96
 
97
+ function isTimeoutError(err) {
98
+ return !!err && (err.name === 'TimeoutError' || err.name === 'AbortError');
99
+ }
100
+
97
101
  function describeNetworkError(err) {
98
102
  let cause = (err && err.cause) || err;
99
- if (cause && (cause.name === 'TimeoutError' || cause.name === 'AbortError')) {
103
+ if (isTimeoutError(cause)) {
100
104
  return `no answer within ${Math.round(REQUEST_TIMEOUT / 1000)}s`;
101
105
  }
102
106
  return (cause && (cause.code || cause.message)) || 'connection failed';
103
107
  }
104
108
 
109
+ // Network failures that say the metadata server was there but slow or interrupted, as opposed to
110
+ // absent (ENOTFOUND off Google Cloud) or refusing (ECONNREFUSED at a wrong override). Deliberately
111
+ // not consts.TRANSIENT_NETWORK_CODES, which counts both of those as transient
112
+ const METADATA_TRANSIENT_CODES = new Set([
113
+ 'ECONNRESET',
114
+ 'ETIMEDOUT',
115
+ 'EPIPE',
116
+ 'UND_ERR_CONNECT_TIMEOUT',
117
+ 'UND_ERR_HEADERS_TIMEOUT',
118
+ 'UND_ERR_BODY_TIMEOUT',
119
+ 'UND_ERR_SOCKET'
120
+ ]);
121
+
122
+ /**
123
+ * Whether a failure from this module is worth retrying as is: the metadata server answered 5xx past
124
+ * the maintenance retry, or the request timed out or was cut off. Everything else (no metadata server,
125
+ * no service account, a wrong override, a refused request) needs the operator. Decided where the error
126
+ * is thrown, which is where the underlying failure is in hand.
127
+ *
128
+ * @param {Error} err - an error thrown by fetchAccessToken() and friends
129
+ * @returns {boolean}
130
+ */
131
+ function isTransientMetadataError(err) {
132
+ return !!(err && err.transient);
133
+ }
134
+
105
135
  /**
106
136
  * GETs one metadata path and returns the response text.
107
137
  *
@@ -130,8 +160,10 @@ async function metadataRequest(path, opts) {
130
160
  });
131
161
  body = await res.text();
132
162
  } catch (err) {
163
+ let cause = err.cause || err;
133
164
  throw makeError(`The metadata server at ${origin} could not be reached (${describeNetworkError(err)})`, 'EMetadataUnreachable', null, {
134
- cause: err
165
+ cause: err,
166
+ transient: isTimeoutError(cause) || METADATA_TRANSIENT_CODES.has(cause.code)
135
167
  });
136
168
  }
137
169
 
@@ -140,12 +172,9 @@ async function metadataRequest(path, opts) {
140
172
  continue;
141
173
  }
142
174
 
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
-
175
+ // Before the status: the metadata server flavors its error answers too, and a 404 from a
176
+ // parking host or a cluster's search domain must read as "not the metadata server", not as
177
+ // "no service account attached"
149
178
  if (res.headers.get(FLAVOR_HEADER) !== FLAVOR_VALUE) {
150
179
  throw makeError(
151
180
  `The server at ${origin} is not a Google Cloud metadata server (no "${FLAVOR_HEADER}: ${FLAVOR_VALUE}" header)`,
@@ -157,6 +186,13 @@ async function metadataRequest(path, opts) {
157
186
  );
158
187
  }
159
188
 
189
+ if (!res.ok) {
190
+ throw makeError(`The metadata server at ${origin} returned HTTP ${res.status} for ${path}`, 'EMetadataServer', res.status, {
191
+ responseText: body.slice(0, MAX_RESPONSE_TEXT),
192
+ transient: res.status >= 500
193
+ });
194
+ }
195
+
160
196
  return body;
161
197
  }
162
198
  }
@@ -216,6 +252,7 @@ async function describeAttachedIdentity(opts) {
216
252
 
217
253
  module.exports = {
218
254
  resolveMetadataOrigin,
255
+ isTransientMetadataError,
219
256
  fetchAccessToken,
220
257
  fetchServiceAccountEmail,
221
258
  describeAttachedIdentity
@@ -5,6 +5,7 @@ const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError, pa
5
5
  const crypto = require('crypto');
6
6
 
7
7
  const { fetch: fetchCmd } = require('undici');
8
+ const { promoteCauseCode } = require('../network-errors');
8
9
 
9
10
  const { ExternalAccountSigner } = require('./external-account-signer');
10
11
  const { fetchTokenRequest } = require('./token-fetch');
@@ -661,12 +662,18 @@ class GmailOauth {
661
662
  });
662
663
  }
663
664
 
664
- let flag = {
665
- message: `Failed to get an access token for the attached service account: ${err.message}`,
666
- code: 'METADATA_SERVER'
667
- };
668
- await this.setFlag(flag);
669
- err.tokenRequest = { provider: this.provider, signer: this.authMethod, status: err.statusCode, flag };
665
+ err.tokenRequest = { provider: this.provider, signer: this.authMethod, status: err.statusCode };
666
+
667
+ // A maintenance 503 or a timeout is retried on the next renewal and needs nobody, so it
668
+ // does not flag the app, the same as a network failure on the token endpoint paths
669
+ if (!gcpMetadata.isTransientMetadataError(err)) {
670
+ let flag = {
671
+ message: `Failed to get an access token for the attached service account: ${err.message}`,
672
+ code: 'METADATA_SERVER'
673
+ };
674
+ await this.setFlag(flag);
675
+ err.tokenRequest.flag = flag;
676
+ }
670
677
  throw err;
671
678
  }
672
679
 
@@ -727,7 +734,10 @@ class GmailOauth {
727
734
 
728
735
  let startTime = Date.now();
729
736
 
730
- let res = await fetchCmd(url, reqData);
737
+ let res = await fetchCmd(url, reqData).catch(err => {
738
+ // undici puts the network code on err.cause; callers read err.code
739
+ throw promoteCauseCode(err);
740
+ });
731
741
 
732
742
  let reqTime = Date.now() - startTime;
733
743
 
@@ -2,6 +2,7 @@
2
2
 
3
3
  const packageData = require('../../package.json');
4
4
  const { fetch: fetchCmd } = require('undici');
5
+ const { promoteCauseCode } = require('../network-errors');
5
6
  const { fetchTokenRequest } = require('./token-fetch');
6
7
  const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError } = require('../tools');
7
8
 
@@ -304,7 +305,10 @@ class MailRuOauth {
304
305
  const requestUrl = new URL(url);
305
306
  requestUrl.searchParams.set('access_token', accessToken);
306
307
 
307
- let res = await fetchCmd(requestUrl.href, reqData);
308
+ let res = await fetchCmd(requestUrl.href, reqData).catch(err => {
309
+ // undici puts the network code on err.cause; callers read err.code
310
+ throw promoteCauseCode(err);
311
+ });
308
312
 
309
313
  if (!res.ok) {
310
314
  let err = new Error('OAuth2 request failed');
@@ -4,6 +4,7 @@ const packageData = require('../../package.json');
4
4
  const { formatPartialSecretKey, structuredClone, httpAgent, formatTokenError, parseRetryAfter } = require('../tools');
5
5
 
6
6
  const { fetch: fetchCmd } = require('undici');
7
+ const { promoteCauseCode } = require('../network-errors');
7
8
  const { fetchTokenRequest } = require('./token-fetch');
8
9
 
9
10
  // Individual MS Graph API scope names for detection
@@ -594,7 +595,10 @@ class OutlookOauth {
594
595
  }
595
596
 
596
597
  let startTime = Date.now();
597
- let res = await fetchCmd(url, reqData);
598
+ let res = await fetchCmd(url, reqData).catch(err => {
599
+ // undici puts the network code on err.cause; callers read err.code
600
+ throw promoteCauseCode(err);
601
+ });
598
602
  let reqTime = Date.now() - startTime;
599
603
 
600
604
  if (!res.ok) {
@@ -1,7 +1,8 @@
1
1
  'use strict';
2
2
 
3
3
  const { redis } = require('../../db');
4
- const { REDIS_PREFIX, TRANSIENT_NETWORK_CODES } = require('../../consts');
4
+ const { REDIS_PREFIX } = require('../../consts');
5
+ const { isTransientNetworkError } = require('../../network-errors');
5
6
  const logger = require('../../logger').child({
6
7
  component: 'google-subscriber'
7
8
  });
@@ -298,7 +299,7 @@ class PubSubInstance {
298
299
  throw err;
299
300
  }
300
301
  // Transient network errors are expected for long-polling connections
301
- if (TRANSIENT_NETWORK_CODES.has(err.code)) {
302
+ if (isTransientNetworkError(err)) {
302
303
  logger.warn({ msg: 'Transient error pulling subscription messages', app: this.app, code: err.code });
303
304
  err.retryDelay = 5000;
304
305
  err.eeLogged = true;
@@ -2,6 +2,7 @@
2
2
 
3
3
  const { fetch: fetchCmd } = require('undici');
4
4
  const { httpAgent } = require('../tools');
5
+ const { promoteCauseCode } = require('../network-errors');
5
6
 
6
7
  /**
7
8
  * Performs a token-endpoint request, and says which endpoint failed when the request never got there.
@@ -35,9 +36,7 @@ async function fetchTokenRequest(url, options, context, route) {
35
36
  } catch (err) {
36
37
  // The cause carries the actionable code. Promoted onto the error itself so the connectError
37
38
  // webhook has something to report - the transient check consults both, so no verdict changes.
38
- if (!err.code && err.cause && err.cause.code) {
39
- err.code = err.cause.code;
40
- }
39
+ promoteCauseCode(err);
41
40
 
42
41
  err.tokenRequest = Object.assign({ url, method: (options && options.method) || 'get', error: err.message, errorCode: err.code }, context);
43
42
  err.message = `Token request to ${url} failed${err.code ? ` [${err.code}]` : ''}: ${(err.cause && err.cause.message) || err.message}`;
@@ -111,6 +111,9 @@ function metadataServerHint(err) {
111
111
  case 'EMetadataConfig':
112
112
  return 'The metadata server override in the environment is not a host name or host:port. Correct or remove EENGINE_GCP_METADATA_HOST (or GCE_METADATA_HOST).';
113
113
  case 'EMetadataUnreachable':
114
+ if (err.transient) {
115
+ return 'The metadata server did not answer in time or dropped the connection. Retry in a moment; if it persists, check the network path to metadata.google.internal from this host.';
116
+ }
114
117
  return 'EmailEngine is not running on Google Cloud, or the metadata server cannot be reached from it. The attached service account is only available on Compute Engine, GKE with Workload Identity enabled on the node pool, and Cloud Run. The request never goes through the configured proxy.';
115
118
  case 'EMetadataServer':
116
119
  if (err.wrongFlavor) {
@@ -143,8 +146,11 @@ async function pubSubAccessProbe(appData, client, accessToken, steps) {
143
146
  return;
144
147
  }
145
148
 
146
- // the name ensurePubsub() creates; both parts are pattern-validated, so neither can leave the path
147
- let topicName = `projects/${appData.googleProjectId}/topics/${pubSubResourceNames(appData).topic}`;
149
+ // The stored topic is the one the Gmail watches publish to, and it does not always follow the
150
+ // current project and topic name (an adopted topic is kept as recorded), so it is the one to
151
+ // probe. Before the first setup there is none, and the name that setup creates is probed instead
152
+ // (both parts pattern-validated, so neither can leave the path)
153
+ let topicName = appData.pubSubTopic || `projects/${appData.googleProjectId}/topics/${pubSubResourceNames(appData).topic}`;
148
154
 
149
155
  try {
150
156
  await client.request(accessToken, `https://pubsub.googleapis.com/v1/${topicName}`, 'get');
@@ -67,6 +67,11 @@ const authFlagClearChecks = new Map();
67
67
  // Used when a token response carries no usable expires_in (Google's service tokens live an hour)
68
68
  const DEFAULT_SERVICE_TOKEN_TTL = 3600;
69
69
 
70
+ // The service account fields the attached service account never reads: the metadata server alone
71
+ // decides which account the tokens belong to, so a stored address would name a principal the app
72
+ // does not act as, and operators granting roles to it would grant them to the wrong one
73
+ const SERVICE_ACCOUNT_IDENTITY_FIELDS = ['serviceClient', 'serviceClientEmail'];
74
+
70
75
  // Drops the credentials a gmailService app's method does not use, so nothing is stored that the app
71
76
  // would never present
72
77
  function withoutOtherCredentials(data, authMethod) {
@@ -76,6 +81,11 @@ function withoutOtherCredentials(data, authMethod) {
76
81
  delete result[field];
77
82
  }
78
83
  }
84
+ if (authMethod === 'metadataServer') {
85
+ for (let field of SERVICE_ACCOUNT_IDENTITY_FIELDS) {
86
+ delete result[field];
87
+ }
88
+ }
79
89
  return result;
80
90
  }
81
91
 
@@ -153,7 +163,12 @@ function oauth2ProviderData(provider, selector) {
153
163
  // field and not on the provider, so a service account delegated gmail.modify is as API-based
154
164
  // as an interactive app. The form guards the controls that only make sense in that mode - the
155
165
  // scope presets, the Pub/Sub service account - on this rather than on one provider name.
156
- gmailApi: GMAIL_PROVIDERS.has(provider)
166
+ gmailApi: GMAIL_PROVIDERS.has(provider),
167
+ // The two Microsoft providers share their fields (client ID label, Azure cloud), and the two
168
+ // app-only providers share their account rules; the admin form reads these instead of
169
+ // repeating each provider name
170
+ microsoft: provider === 'outlook' || provider === 'outlookService',
171
+ serviceAccount: SERVICE_ACCOUNT_PROVIDERS.has(provider)
157
172
  };
158
173
 
159
174
  switch (provider) {
@@ -787,13 +802,13 @@ class OAuth2AppsHandler {
787
802
  externalAccountSigners.delete(id);
788
803
  }
789
804
 
790
- // The authentication method is fixed once an app is saved: pin the stored one and drop the
791
- // other methods' credentials. The admin form's update schema defaults an omitted authMethod
805
+ // The authentication method is fixed once an app is saved: pin the stored one, and drop the
806
+ // other methods' credentials from the merged record below. The admin form's update schema defaults an omitted authMethod
792
807
  // to serviceKey, which would otherwise turn an attached service account app into a keyless
793
808
  // key-signed one
794
- if (isAuthMethodLocked(existingData)) {
795
- let authMethod = normalizeAuthMethod(existingData.authMethod);
796
- data = withoutOtherCredentials(Object.assign({}, data || {}, { authMethod }), authMethod);
809
+ let lockedAuthMethod = isAuthMethodLocked(existingData) ? normalizeAuthMethod(existingData.authMethod) : null;
810
+ if (lockedAuthMethod) {
811
+ data = Object.assign({}, data || {}, { authMethod: lockedAuthMethod });
797
812
  }
798
813
 
799
814
  let oldPubSubApp = existingData.pubSubApp || null;
@@ -810,6 +825,11 @@ class OAuth2AppsHandler {
810
825
  created: existingData.created,
811
826
  updated: new Date().toISOString()
812
827
  });
828
+ if (lockedAuthMethod) {
829
+ // on the merged record rather than the update alone, so a field saved before the method's
830
+ // rules were this strict is cleared by the next write instead of kept forever
831
+ entry = withoutOtherCredentials(entry, lockedAuthMethod);
832
+ }
813
833
 
814
834
  let updates = {
815
835
  [`${id}:data`]: msgpack.encode(entry)
package/lib/sub-script.js CHANGED
@@ -12,13 +12,16 @@ const crypto = require('crypto');
12
12
  const vm = require('vm');
13
13
  const logger = require('./logger');
14
14
  const settings = require('./settings');
15
- const { httpAgent } = require('./tools');
15
+ const { httpAgent, LRUCache } = require('./tools');
16
16
 
17
17
  const { SUBSCRIPT_RUNTIME_TIMEOUT } = require('./consts');
18
18
 
19
19
  const { fetch: fetchCmd } = require('undici');
20
20
 
21
- const fnCache = new Map();
21
+ // Every edit of a filter, map or pre-processing script compiles a new source, in every thread that
22
+ // runs it, so the cache is bounded. An evicted script is only recompiled: a SubScript keeps its own
23
+ // reference to what it compiled
24
+ const fnCache = new LRUCache(256);
22
25
 
23
26
  function getCompiledScript(code) {
24
27
  let fnHash = crypto.createHash('sha256').update(code).digest('hex');
@@ -124,4 +127,8 @@ class SubScript {
124
127
  }
125
128
  }
126
129
 
127
- module.exports = { SubScript };
130
+ module.exports = {
131
+ SubScript,
132
+ // Exported for testing
133
+ fnCache
134
+ };
@@ -162,9 +162,8 @@ Full documentation: https://learn.emailengine.app/`
162
162
  description: 'Perform bulk operations on multiple messages simultaneously, such as marking as read, moving, or deleting'
163
163
  },
164
164
  {
165
- name: 'Export (Beta)',
166
- description:
167
- 'Bulk export messages from email accounts. This feature is in beta and the API may change in future releases. Export files are encrypted at rest when a service secret is configured.'
165
+ name: 'Export',
166
+ description: 'Bulk export messages from email accounts. Export files are encrypted at rest when a service secret is configured.'
168
167
  }
169
168
  ],
170
169