emailengine-app 2.82.2 → 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 (55) hide show
  1. package/.ncurc.js +8 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +18 -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 +11 -2
  16. package/lib/enum-descriptions.js +3 -1
  17. package/lib/imapproxy/imap-core/README.md +1 -0
  18. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +11 -1
  19. package/lib/imapproxy/proxy-handoff.js +6 -3
  20. package/lib/imapproxy/response-error.js +14 -1
  21. package/lib/oauth/gcp-metadata.js +222 -0
  22. package/lib/oauth/gmail.js +115 -20
  23. package/lib/oauth/mail-ru.js +10 -4
  24. package/lib/oauth/outlook.js +11 -4
  25. package/lib/oauth/token-fetch.js +4 -2
  26. package/lib/oauth/verify-app.js +120 -32
  27. package/lib/oauth2-apps.js +46 -12
  28. package/lib/schemas.js +60 -18
  29. package/lib/tools.js +52 -2
  30. package/lib/ui-routes/admin-entities-routes.js +2 -2
  31. package/lib/ui-routes/auth-routes.js +4 -1
  32. package/lib/ui-routes/gmail-service-auth.js +64 -0
  33. package/lib/ui-routes/oauth-config-routes.js +8 -16
  34. package/lib/ui-routes/suppression-list-routes.js +2 -2
  35. package/lib/utils/network.js +29 -0
  36. package/lib/webhook-request.js +12 -4
  37. package/lib/webhook-routing.js +34 -11
  38. package/package.json +11 -11
  39. package/sbom.json +1 -1
  40. package/server.js +8 -2
  41. package/static/css/flyonui.css +1 -1
  42. package/static/js/app.js +2 -1
  43. package/static/js/ui.js +6 -1
  44. package/static/licenses.html +18 -28
  45. package/translations/messages.pot +73 -73
  46. package/views/accounts/edit.hbs +1 -1
  47. package/views/config/imap-proxy.hbs +1 -1
  48. package/views/config/network.hbs +7 -5
  49. package/views/config/oauth/app.hbs +2 -0
  50. package/views/config/smtp.hbs +1 -1
  51. package/views/config/tls.hbs +2 -2
  52. package/views/config/webhooks.hbs +1 -1
  53. package/views/partials/oauth_form.hbs +116 -27
  54. package/workers/api.js +4 -2
  55. package/workers/webhooks.js +18 -7
@@ -7,7 +7,9 @@
7
7
  // is reimplemented here.
8
8
 
9
9
  const { createImapClient } = require('../create-imap-client');
10
- const { oauth2Apps, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS } = require('../oauth2-apps');
10
+ const { oauth2Apps, oauth2ProviderData, SERVICE_ACCOUNT_PROVIDERS, pubSubResourceNames } = require('../oauth2-apps');
11
+ const { normalizeAuthMethod } = require('./gmail');
12
+ const gcpMetadata = require('./gcp-metadata');
11
13
  const packageData = require('../../package.json');
12
14
 
13
15
  // A single diagnostic step. status: 'ok' | 'fail' | 'skip'.
@@ -42,7 +44,7 @@ function truncateDetail(value) {
42
44
  }
43
45
 
44
46
  function describeResponse(err) {
45
- let resp = err && (err.response || (err.tokenRequest && err.tokenRequest.response));
47
+ let resp = err && (err.response || (err.tokenRequest && err.tokenRequest.response) || (err.oauthRequest && err.oauthRequest.response));
46
48
  if (resp && typeof resp === 'object') {
47
49
  // Google API errors nest the detail under error.message; OAuth/STS errors
48
50
  // use top-level string error/error_description fields.
@@ -103,6 +105,68 @@ function mapSigningError(err, authMethod, steps) {
103
105
  );
104
106
  }
105
107
 
108
+ // Maps a metadata server failure (lib/oauth/gcp-metadata.js) onto the hint that fixes it
109
+ function metadataServerHint(err) {
110
+ switch (err.code) {
111
+ case 'EMetadataConfig':
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
+ case 'EMetadataUnreachable':
114
+ 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
+ case 'EMetadataServer':
116
+ if (err.wrongFlavor) {
117
+ return 'Something other than the Google Cloud metadata server answered at this address. Check EENGINE_GCP_METADATA_HOST (or GCE_METADATA_HOST), and that no proxy or other service intercepts metadata.google.internal.';
118
+ }
119
+ if (err.statusCode === 404) {
120
+ return 'No service account is attached to this instance. Attach one to the VM, the GKE Kubernetes service account (Workload Identity) or the Cloud Run service.';
121
+ }
122
+ if (err.statusCode === 403) {
123
+ return 'The metadata server refused the request. On GKE, the Kubernetes service account must be bound to a Google service account through Workload Identity.';
124
+ }
125
+ return 'The metadata server did not issue a token. Retry in a moment; if it persists, check the service account attached to this instance.';
126
+ default:
127
+ return 'The metadata server answered without a usable access token.';
128
+ }
129
+ }
130
+
131
+ // Read-only proof that the token can do what a Pub/Sub app needs: reading the app's own topic. A
132
+ // token is not the same as access: the role may be missing, and on Compute Engine the VM's access
133
+ // scopes cap the token whatever roles the service account holds. The topic itself rather than a
134
+ // project listing, because the least-privilege role the documentation offers grants topics.get
135
+ // and not topics.list, and because a topic that was never created is worth reporting too
136
+ async function pubSubAccessProbe(appData, client, accessToken, steps) {
137
+ if (!appData.googleProjectId) {
138
+ steps.push(
139
+ mkStep('pubsub', 'Pub/Sub access', 'skip', 'No Google Cloud project ID is configured', {
140
+ hint: 'Set the Google Cloud Project ID in the app settings. EmailEngine creates the Pub/Sub topic and subscription in that project.'
141
+ })
142
+ );
143
+ return;
144
+ }
145
+
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}`;
148
+
149
+ try {
150
+ await client.request(accessToken, `https://pubsub.googleapis.com/v1/${topicName}`, 'get');
151
+ steps.push(mkStep('pubsub', 'Pub/Sub access', 'ok', `Pub/Sub topic ${topicName} is reachable`));
152
+ } catch (err) {
153
+ let status = err.statusCode;
154
+ let detail = describeResponse(err) || err.message;
155
+ let hint;
156
+ if (status === 403 && /scope/i.test(detail)) {
157
+ hint =
158
+ 'The access token does not carry a scope that covers Pub/Sub. On Compute Engine, give the VM the "cloud-platform" access scope (or allow full access to all Cloud APIs); the roles of the service account cannot widen what the access scopes allow.';
159
+ } else if (status === 403) {
160
+ hint = `The service account is not allowed to manage Pub/Sub in project ${appData.googleProjectId}. Grant it the "Pub/Sub Admin" role.`;
161
+ } else if (status === 404) {
162
+ hint = `The topic does not exist. EmailEngine creates it when the application is saved, so the application page should show why that failed; also check that project ${appData.googleProjectId} exists and has the Cloud Pub/Sub API enabled.`;
163
+ } else {
164
+ hint = 'The Pub/Sub API request failed. Check the project ID and that the Cloud Pub/Sub API is enabled.';
165
+ }
166
+ steps.push(mkStep('pubsub', 'Pub/Sub access', 'fail', detail, { hint }));
167
+ }
168
+ }
169
+
106
170
  // Maps GmailOauth.refreshToken (jwt-bearer) failures, using checkForFlags codes.
107
171
  function mapTokenError(err, account, appData, steps) {
108
172
  let flag = err.tokenRequest && err.tokenRequest.flag;
@@ -174,62 +238,86 @@ async function imapProbe(appData, account, accessToken, steps) {
174
238
 
175
239
  async function verifyGmailService(appData, opts, steps) {
176
240
  let { account, testConnection } = opts;
177
- let authMethod = appData.authMethod === 'externalAccount' ? 'externalAccount' : 'serviceKey';
241
+ let authMethod = normalizeAuthMethod(appData.authMethod);
178
242
 
179
243
  // Step 1 - configuration. getClient builds the signer, which validates the external
180
244
  // account JSON and the service-account-email match (or fails if creds are missing).
181
245
  let client;
182
246
  try {
183
247
  client = await oauth2Apps.getClient(appData.id, { setFlag: async () => {} });
184
- steps.push(
185
- mkStep(
186
- 'config',
187
- 'Configuration',
188
- 'ok',
189
- authMethod === 'externalAccount' ? 'External account configuration is valid' : 'Service account key is present'
190
- )
191
- );
248
+ let configMessage =
249
+ authMethod === 'metadataServer'
250
+ ? `Attached service account, read from the metadata server at ${gcpMetadata.resolveMetadataOrigin()}`
251
+ : authMethod === 'externalAccount'
252
+ ? 'External account configuration is valid'
253
+ : 'Service account key is present';
254
+ steps.push(mkStep('config', 'Configuration', 'ok', configMessage));
192
255
  } catch (err) {
193
256
  steps.push(
194
257
  mkStep('config', 'Configuration', 'fail', err.message, {
195
- hint: 'Complete the service account credentials in the app settings (service client, email and key/external account configuration).'
258
+ hint:
259
+ err.code === 'EMetadataConfig'
260
+ ? metadataServerHint(err)
261
+ : 'Complete the service account credentials in the app settings (service client, email and key/external account configuration).'
196
262
  })
197
263
  );
198
264
  return finalize(appData, authMethod, steps, account);
199
265
  }
200
266
 
201
- // Step 2 - signing chain (no mailbox/email needed; signJwt signs an arbitrary payload).
202
- try {
203
- await client.generateServiceRequest(account || 'verify-probe@example.com', false);
204
- if (authMethod === 'externalAccount') {
205
- steps.push(mkStep('subjectToken', 'Read OIDC subject token', 'ok', 'Subject token read from the credential source'));
206
- steps.push(mkStep('sts', 'STS token exchange', 'ok', 'Federated access token obtained from Google STS'));
207
- steps.push(mkStep('signJwt', 'Sign assertion (signJwt)', 'ok', 'Assertion signed via IAM signJwt'));
208
- } else {
209
- steps.push(mkStep('sign', 'Sign assertion with service key', 'ok', 'Assertion signed locally with the service account key'));
267
+ let isMetadataServer = authMethod === 'metadataServer';
268
+
269
+ // Step 2 - signing chain (no mailbox/email needed; signJwt signs an arbitrary payload). The
270
+ // attached service account has none: the metadata server issues the token itself
271
+ if (!isMetadataServer) {
272
+ try {
273
+ await client.generateServiceRequest(account || 'verify-probe@example.com', false);
274
+ if (authMethod === 'externalAccount') {
275
+ steps.push(mkStep('subjectToken', 'Read OIDC subject token', 'ok', 'Subject token read from the credential source'));
276
+ steps.push(mkStep('sts', 'STS token exchange', 'ok', 'Federated access token obtained from Google STS'));
277
+ steps.push(mkStep('signJwt', 'Sign assertion (signJwt)', 'ok', 'Assertion signed via IAM signJwt'));
278
+ } else {
279
+ steps.push(mkStep('sign', 'Sign assertion with service key', 'ok', 'Assertion signed locally with the service account key'));
280
+ }
281
+ } catch (err) {
282
+ mapSigningError(err, authMethod, steps);
283
+ return finalize(appData, authMethod, steps, account);
210
284
  }
211
- } catch (err) {
212
- mapSigningError(err, authMethod, steps);
213
- return finalize(appData, authMethod, steps, account);
214
285
  }
215
286
 
216
287
  // Pub/Sub apps authenticate as the service account itself (principal mode), not by
217
288
  // impersonating a user, so they need no mailbox address and no domain-wide delegation.
218
289
  if (appData.baseScopes === 'pubsub') {
290
+ let label = isMetadataServer ? 'Service account token (metadata server)' : 'Service account token';
291
+ let accessToken;
219
292
  try {
220
- let resp = await client.refreshToken({ isPrincipal: true });
293
+ // The attached service account is named by the metadata server, not the app record, so
294
+ // its email is read beside the token to say who EmailEngine acts as; its failure is ignored
295
+ let [resp, serviceAccountEmail] = await Promise.all([
296
+ client.refreshToken({ isPrincipal: true }),
297
+ isMetadataServer ? gcpMetadata.fetchServiceAccountEmail().catch(() => null) : null
298
+ ]);
221
299
  if (!resp || !resp.access_token) {
222
300
  throw Object.assign(new Error('No access token returned by the token endpoint'), { code: 'ETokenRefresh' });
223
301
  }
224
- steps.push(mkStep('token', 'Service account token', 'ok', 'App-only access token obtained for the service account'));
302
+ accessToken = resp.access_token;
303
+ let message = isMetadataServer
304
+ ? `Access token issued for ${serviceAccountEmail || 'the attached service account'}`
305
+ : 'App-only access token obtained for the service account';
306
+ steps.push(mkStep('token', label, 'ok', message));
225
307
  } catch (err) {
226
308
  let flag = err.tokenRequest && err.tokenRequest.flag;
227
- let hint =
228
- flag && flag.code === 'INVALID_SERVICE_CLIENT_EMAIL'
229
- ? 'The service account is invalid or unrecognized. Verify the service account email and client ID in the app settings.'
230
- : 'The service account could not obtain its own access token. Verify the service account email and client ID in the app settings.';
231
- steps.push(mkStep('token', 'Service account token', 'fail', describeResponse(err) || err.message, { hint }));
309
+ let hint;
310
+ if (isMetadataServer) {
311
+ hint = metadataServerHint(err);
312
+ } else if (flag && flag.code === 'INVALID_SERVICE_CLIENT_EMAIL') {
313
+ hint = 'The service account is invalid or unrecognized. Verify the service account email and client ID in the app settings.';
314
+ } else {
315
+ hint = 'The service account could not obtain its own access token. Verify the service account email and client ID in the app settings.';
316
+ }
317
+ steps.push(mkStep('token', label, 'fail', describeResponse(err) || err.message, { hint }));
318
+ return finalize(appData, authMethod, steps, account);
232
319
  }
320
+ await pubSubAccessProbe(appData, client, accessToken, steps);
233
321
  return finalize(appData, authMethod, steps, account);
234
322
  }
235
323
 
@@ -409,4 +497,4 @@ async function verifyOAuth2App(appId, opts) {
409
497
  module.exports = { verifyOAuth2App };
410
498
 
411
499
  // Exported for tests only; describeResponse reflects remote content into the verify report.
412
- module.exports.__test__ = { describeResponse, MAX_REMOTE_DETAIL_LENGTH };
500
+ module.exports.__test__ = { describeResponse, metadataServerHint, MAX_REMOTE_DETAIL_LENGTH };
@@ -44,7 +44,7 @@ function recordTokenMetric(status, provider, statusCode) {
44
44
  }
45
45
 
46
46
  const { OutlookOauth, outlookScopes } = require('./oauth/outlook');
47
- const { GmailOauth, GMAIL_SCOPES, GMAIL_PROVIDERS, parseExternalAccountConfig } = require('./oauth/gmail');
47
+ const { GmailOauth, GMAIL_SCOPES, GMAIL_PROVIDERS, parseExternalAccountConfig, normalizeAuthMethod, SERVICE_AUTH_CREDENTIALS } = require('./oauth/gmail');
48
48
  const { ExternalAccountSigner } = require('./oauth/external-account-signer');
49
49
  const { formatExtraScopes } = require('./oauth/scope-list');
50
50
  const crypto = require('crypto');
@@ -67,6 +67,31 @@ 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
+ // Drops the credentials a gmailService app's method does not use, so nothing is stored that the app
71
+ // would never present
72
+ function withoutOtherCredentials(data, authMethod) {
73
+ let result = Object.assign({}, data);
74
+ for (let field of Object.values(SERVICE_AUTH_CREDENTIALS)) {
75
+ if (field && field !== SERVICE_AUTH_CREDENTIALS[authMethod]) {
76
+ delete result[field];
77
+ }
78
+ }
79
+ return result;
80
+ }
81
+
82
+ // The Pub/Sub topic and subscription a Pub/Sub app uses, by name within its project
83
+ function pubSubResourceNames(appData) {
84
+ return {
85
+ topic: appData.googleTopicName || `ee-pub-${appData.id}`,
86
+ subscription: appData.googleSubscriptionName || `ee-sub-${appData.id}`
87
+ };
88
+ }
89
+
90
+ // Whether a stored app's authentication method can no longer change: every saved gmailService app
91
+ function isAuthMethodLocked(appData) {
92
+ return !!appData && appData.provider === 'gmailService';
93
+ }
94
+
70
95
  // Workload Identity Federation signers, per app id. The signer caches the federated token and
71
96
  // deduplicates concurrent refreshes, which only helps when it outlives the GmailOauth client
72
97
  // built for each token renewal: without this every account ran its own STS exchange every hour.
@@ -532,7 +557,7 @@ class OAuth2AppsHandler {
532
557
 
533
558
  case 'gmailService':
534
559
  entry.name = 'Gmail service';
535
- entry.authMethod = v('AuthMethod') === 'externalAccount' ? 'externalAccount' : 'serviceKey';
560
+ entry.authMethod = normalizeAuthMethod(v('AuthMethod'));
536
561
  entry.serviceClient = v('Client');
537
562
  entry.serviceKey = v('Key');
538
563
  entry.externalAccount = v('ExternalAccount');
@@ -685,6 +710,10 @@ class OAuth2AppsHandler {
685
710
  // opts.id is internal-only: migrateLegacyApps() preserves the historical legacy app IDs
686
711
  const id = (opts && opts.id) || (await this.generateId());
687
712
 
713
+ if (data && data.provider === 'gmailService') {
714
+ data = withoutOtherCredentials(data, normalizeAuthMethod(data.authMethod));
715
+ }
716
+
688
717
  let encryptedValues = {};
689
718
  for (let key of ENCRYPTED_APP_KEYS) {
690
719
  if (data[key]) {
@@ -758,11 +787,13 @@ class OAuth2AppsHandler {
758
787
  externalAccountSigners.delete(id);
759
788
  }
760
789
 
761
- // The authentication method is fixed once an app has been configured with
762
- // a credential - never allow switching between serviceKey and externalAccount
763
- // (WIF). Pin the stored method, ignoring any incoming change.
764
- if (existingData.provider === 'gmailService' && (existingData.serviceKey || existingData.externalAccount)) {
765
- data = Object.assign({}, data || {}, { authMethod: existingData.authMethod === 'externalAccount' ? 'externalAccount' : 'serviceKey' });
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
792
+ // to serviceKey, which would otherwise turn an attached service account app into a keyless
793
+ // key-signed one
794
+ if (isAuthMethodLocked(existingData)) {
795
+ let authMethod = normalizeAuthMethod(existingData.authMethod);
796
+ data = withoutOtherCredentials(Object.assign({}, data || {}, { authMethod }), authMethod);
766
797
  }
767
798
 
768
799
  let oldPubSubApp = existingData.pubSubApp || null;
@@ -1167,8 +1198,7 @@ class OAuth2AppsHandler {
1167
1198
  async ensurePubsub(appData) {
1168
1199
  let project = appData.googleProjectId;
1169
1200
 
1170
- let topic = appData.googleTopicName || `ee-pub-${appData.id}`;
1171
- let subscription = appData.googleSubscriptionName || `ee-sub-${appData.id}`;
1201
+ let { topic, subscription } = pubSubResourceNames(appData);
1172
1202
 
1173
1203
  // Determine desired expirationPolicy from setting
1174
1204
  let gmailSubscriptionTtl = await settings.get('gmailSubscriptionTtl');
@@ -1659,7 +1689,7 @@ class OAuth2AppsHandler {
1659
1689
  let serviceClient = appData.serviceClient;
1660
1690
 
1661
1691
  let serviceClientEmail = appData.serviceClientEmail;
1662
- let authMethod = appData.authMethod === 'externalAccount' ? 'externalAccount' : 'serviceKey';
1692
+ let authMethod = normalizeAuthMethod(appData.authMethod);
1663
1693
  let serviceKey = appData.serviceKey ? await this.decrypt(appData.serviceKey) : null;
1664
1694
  let externalAccount = appData.externalAccount ? await this.decrypt(appData.externalAccount) : null;
1665
1695
 
@@ -1668,7 +1698,9 @@ class OAuth2AppsHandler {
1668
1698
  let googleProjectId = appData.googleProjectId;
1669
1699
  let workspaceAccounts = appData.googleWorkspaceAccounts;
1670
1700
 
1671
- let credentialsReady = serviceClient && (authMethod === 'externalAccount' ? !!externalAccount : !!serviceKey);
1701
+ // A method with no stored credential (the attached service account) is always ready
1702
+ let credential = SERVICE_AUTH_CREDENTIALS[authMethod];
1703
+ let credentialsReady = !credential || (serviceClient && !!{ serviceKey, externalAccount }[credential]);
1672
1704
  if (!credentialsReady) {
1673
1705
  let error = Boom.boomify(new Error('OAuth2 credentials not set up for Gmail'), { statusCode: 400 });
1674
1706
  throw error;
@@ -1898,5 +1930,7 @@ module.exports = {
1898
1930
  SERVICE_ACCOUNT_PROVIDERS,
1899
1931
  oauth2ProviderData,
1900
1932
  formatExtraScopes,
1901
- isApiBasedApp
1933
+ isApiBasedApp,
1934
+ isAuthMethodLocked,
1935
+ pubSubResourceNames
1902
1936
  };
package/lib/schemas.js CHANGED
@@ -164,7 +164,9 @@ const settingsSchema = {
164
164
  .example('Bearer <token>')
165
165
  }).label('WebhooksCustomHeader')
166
166
  )
167
- .description('Additional HTTP headers to include with every webhook request for authentication or tracking')
167
+ .description(
168
+ "Additional HTTP headers to include with webhook requests for authentication or tracking. The global list is sent to the global webhook URL only, an account-level list accompanies that account's deliveries"
169
+ )
168
170
  .label('WebhooksCustomHeaders'),
169
171
 
170
172
  notifyHeaders: Joi.array()
@@ -406,14 +408,16 @@ const settingsSchema = {
406
408
  imapStrategy: Joi.string()
407
409
  .empty('')
408
410
  .valid(...ADDRESS_STRATEGIES.map(entry => entry.key))
409
- .description('IP address selection strategy for outbound IMAP connections when multiple local addresses are available')
411
+ .description(
412
+ 'IP address selection strategy for mailbox access when multiple local addresses are available: IMAP sessions, Gmail API and MS Graph requests, and the OAuth2 token requests of every account. The key keeps its historical name'
413
+ )
410
414
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.addressStrategy })
411
415
  .label('ImapStrategy'),
412
416
 
413
417
  smtpStrategy: Joi.string()
414
418
  .empty('')
415
419
  .valid(...ADDRESS_STRATEGIES.map(entry => entry.key))
416
- .description('IP address selection strategy for outbound SMTP connections when multiple local addresses are available')
420
+ .description('IP address selection strategy for sending over SMTP when multiple local addresses are available')
417
421
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.addressStrategy })
418
422
  .label('SmtpStrategy'),
419
423
 
@@ -437,7 +441,9 @@ const settingsSchema = {
437
441
  .empty('')
438
442
  .example('0.0.0.0')
439
443
  .description('IP address to bind the SMTP server to (empty = all interfaces)'),
440
- smtpServerProxy: formBoolean().description('Enable PROXY protocol support for the SMTP server'),
444
+ smtpServerProxy: formBoolean().description(
445
+ 'Enable PROXY protocol support for the SMTP server. The PROXY header is accepted from any peer, so the port must only be reachable through the proxy'
446
+ ),
441
447
  smtpServerAuthEnabled: formBoolean().description('Require SMTP authentication for incoming connections'),
442
448
  smtpServerPassword: Joi.string()
443
449
  .empty('')
@@ -489,7 +495,9 @@ const settingsSchema = {
489
495
  .empty('')
490
496
  .example('0.0.0.0')
491
497
  .description('IP address to bind the IMAP proxy to (empty = all interfaces)'),
492
- imapProxyServerProxy: formBoolean().description('Enable PROXY protocol support for the IMAP proxy'),
498
+ imapProxyServerProxy: formBoolean().description(
499
+ 'Enable PROXY protocol support for the IMAP proxy. The PROXY header is accepted from any peer, so the port must only be reachable through the proxy'
500
+ ),
493
501
  imapProxyServerPassword: Joi.string()
494
502
  .empty('')
495
503
  .allow(null)
@@ -624,9 +632,22 @@ const settingsSchema = {
624
632
  .description('How long a finished export is kept before it is deleted, in milliseconds (default: 24 hours)')
625
633
  };
626
634
 
635
+ // The per-account proxy. Covers every outbound connection made for the account, as the instance-wide
636
+ // proxy does for all of them (see getAccountHttpRoute() in lib/utils/network.js)
637
+ const accountProxySchema = settingsSchema.proxyUrl
638
+ .description(
639
+ 'Proxy for this account, used instead of the instance-wide proxy: its IMAP and SMTP connections and, for an OAuth2 account, its token requests and Gmail API or MS Graph API calls'
640
+ )
641
+ .label('AccountProxyURL');
642
+
643
+ // A message sender or recipient address. joi's default 64 octet local part limit is dropped, since
644
+ // real services issue longer addresses their own MX accepts (ClickUp task addresses run to 65 octets);
645
+ // the 254 overall cap joi applied before is kept, and domain label limits still apply.
646
+ const mailboxAddressSchema = Joi.string().email({ ignoreLength: true }).max(254);
647
+
627
648
  const addressSchema = Joi.object({
628
649
  name: Joi.string().trim().empty('').max(256).example('Some Name').description('Display name for the email address'),
629
- address: Joi.string().email({ ignoreLength: false }).example('user@example.com').required().description('Email address')
650
+ address: mailboxAddressSchema.example('user@example.com').required().description('Email address')
630
651
  })
631
652
  .description('Email address with optional display name')
632
653
  .label('EmailAddress');
@@ -1647,6 +1668,14 @@ const accountSchemas = {
1647
1668
  )
1648
1669
  };
1649
1670
 
1671
+ // The service account fields every gmailService app names, except one using the attached service
1672
+ // account, which the metadata server identifies
1673
+ const requiredUnlessMetadataServer = Joi.when('authMethod', {
1674
+ is: 'metadataServer',
1675
+ then: Joi.optional(),
1676
+ otherwise: Joi.required()
1677
+ });
1678
+
1650
1679
  const googleProjectIdSchema = Joi.string()
1651
1680
  .trim()
1652
1681
  .allow('', false, null)
@@ -1766,7 +1795,7 @@ const oauthCreateSchema = {
1766
1795
  .max(256)
1767
1796
  .when('provider', {
1768
1797
  is: 'gmailService',
1769
- then: Joi.required(),
1798
+ then: requiredUnlessMetadataServer,
1770
1799
  otherwise: Joi.optional().valid(false, null)
1771
1800
  })
1772
1801
  .example('7103296518315821565203')
@@ -1784,7 +1813,7 @@ const oauthCreateSchema = {
1784
1813
  .email()
1785
1814
  .when('provider', {
1786
1815
  is: 'gmailService',
1787
- then: Joi.required(),
1816
+ then: requiredUnlessMetadataServer,
1788
1817
  otherwise: Joi.optional().valid(false, null)
1789
1818
  })
1790
1819
  .example('name@project-123.iam.gserviceaccount.com')
@@ -1797,7 +1826,8 @@ const oauthCreateSchema = {
1797
1826
  .when('provider', {
1798
1827
  is: 'gmailService',
1799
1828
  then: Joi.when('authMethod', {
1800
- is: 'externalAccount',
1829
+ // a schema `is` is not required by default, so a missing authMethod would match
1830
+ is: Joi.valid('externalAccount', 'metadataServer').required(),
1801
1831
  then: Joi.optional().allow(''),
1802
1832
  otherwise: Joi.required()
1803
1833
  }),
@@ -1807,14 +1837,24 @@ const oauthCreateSchema = {
1807
1837
  .description('Service account private key in PEM format'),
1808
1838
 
1809
1839
  authMethod: Joi.string()
1810
- .valid('serviceKey', 'externalAccount')
1840
+ .valid('serviceKey', 'externalAccount', 'metadataServer')
1811
1841
  .when('provider', {
1812
1842
  is: 'gmailService',
1813
1843
  then: Joi.optional().default('serviceKey'),
1814
1844
  otherwise: Joi.optional().valid(false, null)
1815
1845
  })
1846
+ // The metadata server's token is the attached service account's own and cannot impersonate
1847
+ // a Workspace user, so it only serves an app that acts as the service account: Pub/Sub.
1848
+ // Joi.override replaces the allowed list instead of adding to it, so the refusal is one
1849
+ // error with its reason rather than a generic "must be one of" next to it
1850
+ .when('baseScopes', {
1851
+ is: Joi.exist().valid('pubsub'),
1852
+ otherwise: Joi.valid(Joi.override, 'serviceKey', 'externalAccount', false, null).messages({
1853
+ 'any.only': '{{#label}} must be one of [serviceKey, externalAccount]. metadataServer is only available to a Cloud Pub/Sub application'
1854
+ })
1855
+ })
1816
1856
  .example('externalAccount')
1817
- .description('How token requests for the Gmail service account are signed')
1857
+ .description('How the Gmail service account authenticates')
1818
1858
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.gmailAuthMethod }),
1819
1859
 
1820
1860
  externalAccount: Joi.string()
@@ -1961,7 +2001,7 @@ const oauthUpdateSchema = {
1961
2001
  .max(256)
1962
2002
  .when('provider', {
1963
2003
  is: 'gmailService',
1964
- then: Joi.required(),
2004
+ then: requiredUnlessMetadataServer,
1965
2005
  otherwise: Joi.optional().valid(false, null)
1966
2006
  })
1967
2007
  .description('OAuth2 Service Client ID'),
@@ -1979,7 +2019,7 @@ const oauthUpdateSchema = {
1979
2019
  .email()
1980
2020
  .when('provider', {
1981
2021
  is: 'gmailService',
1982
- then: Joi.required(),
2022
+ then: requiredUnlessMetadataServer,
1983
2023
  otherwise: Joi.optional().valid(false, null)
1984
2024
  })
1985
2025
  .example('name@project-123.iam.gserviceaccount.com')
@@ -1997,13 +2037,13 @@ const oauthUpdateSchema = {
1997
2037
  .description('OAuth2 Secret Service Key'),
1998
2038
 
1999
2039
  authMethod: Joi.string()
2000
- .valid('serviceKey', 'externalAccount')
2040
+ .valid('serviceKey', 'externalAccount', 'metadataServer')
2001
2041
  .when('provider', {
2002
2042
  is: 'gmailService',
2003
2043
  then: Joi.optional().default('serviceKey'),
2004
2044
  otherwise: Joi.forbidden()
2005
2045
  })
2006
- .description('How token requests for the Gmail service account are signed')
2046
+ .description('How the Gmail service account authenticates')
2007
2047
  .meta({ enumDescriptions: ENUM_DESCRIPTIONS.gmailAuthMethod }),
2008
2048
 
2009
2049
  externalAccount: Joi.string()
@@ -2233,8 +2273,8 @@ const outboxEntrySchema = Joi.object({
2233
2273
 
2234
2274
  messageId: Joi.string().max(996).example('<test123@example.com>').description('Message-ID header value'),
2235
2275
  envelope: Joi.object({
2236
- from: Joi.string().email().allow('').example('sender@example.com'),
2237
- to: Joi.array().items(Joi.string().email().required().example('recipient@example.com')).label('OutboxEnvelopeTo')
2276
+ from: mailboxAddressSchema.allow('').example('sender@example.com'),
2277
+ to: Joi.array().items(mailboxAddressSchema.required().example('recipient@example.com')).label('OutboxEnvelopeTo')
2238
2278
  })
2239
2279
  .description('SMTP envelope information')
2240
2280
  .label('OutboxEnvelope'),
@@ -2355,7 +2395,7 @@ const idempotencyKeySchema = Joi.string()
2355
2395
  .min(0)
2356
2396
  .max(1024)
2357
2397
  .optional()
2358
- .replace(/^\s*"\s*|\s*"\s*$|/g, '')
2398
+ .replace(/^\s*"\s*|\s*"\s*$/g, '')
2359
2399
  .replace(/\\([\\"])/g, '$1')
2360
2400
  .example('submit-12345')
2361
2401
  .description('Unique key to prevent duplicate processing of the same request')
@@ -2648,6 +2688,8 @@ module.exports = {
2648
2688
  settingsSchema,
2649
2689
  accountSchemas,
2650
2690
  addressSchema,
2691
+ mailboxAddressSchema,
2692
+ accountProxySchema,
2651
2693
  settingsQuerySchema,
2652
2694
  isHiddenSetting,
2653
2695
  imapSchema,
package/lib/tools.js CHANGED
@@ -56,6 +56,7 @@ const { getLocalAddress } = require('./utils/network');
56
56
 
57
57
  const { fetch: fetchCmd, Agent, RetryAgent, ProxyAgent, Dispatcher } = require('undici');
58
58
  const tls = require('tls');
59
+ const net = require('net');
59
60
  const { SocksClient } = require('socks');
60
61
  const { createWebhookLookup, WEBHOOK_EGRESS_POLICY } = require('./webhook-egress');
61
62
  const { readEnvValue } = require('./read-env-value');
@@ -247,9 +248,9 @@ function createSocksAgent(proxyUrl, agentOpts) {
247
248
  );
248
249
  }
249
250
 
250
- function buildFetchDispatcher(proxyUrl) {
251
+ function buildFetchDispatcher(proxyUrl, extraOpts) {
251
252
  if (!proxyUrl) {
252
- return new Agent(AGENT_OPTS);
253
+ return new Agent(Object.assign({}, AGENT_OPTS, extraOpts));
253
254
  }
254
255
 
255
256
  let scheme = new URL(proxyUrl).protocol.replace(/:$/, '').toLowerCase();
@@ -270,6 +271,54 @@ function installDispatchers(proxyUrl, existingWebhook) {
270
271
  httpAgent.proxyUrl = proxyUrl;
271
272
  }
272
273
 
274
+ // Dispatchers for the network route of one account (see getAccountHttpRoute() in lib/utils/network.js),
275
+ // shared by every account on the same route. An entry nobody has used for ROUTE_DISPATCHER_IDLE_MS is
276
+ // closed and dropped on the next miss. Not a size bound: a route in use keeps its warm sockets however
277
+ // many accounts each have their own proxy, and close() is graceful, so a request still in flight on a
278
+ // dropped entry finishes first.
279
+ const ROUTE_DISPATCHER_IDLE_MS = 60 * 60 * 1000;
280
+ const routeDispatchers = new Map();
281
+
282
+ /**
283
+ * Returns the { fetch, retry } dispatcher pair for a network route.
284
+ *
285
+ * @param {Object} [route] - { proxy, localAddress }, both optional
286
+ * @returns {Object} { fetch, retry } - the shared dispatchers when the route asks for nothing special
287
+ */
288
+ function dispatchersForRoute(route) {
289
+ let proxy = (route && route.proxy) || null;
290
+ // A local address only applies to a direct connection. With the instance-wide HTTP proxy in
291
+ // use the proxy makes the connection, the same way it does for IMAP and SMTP.
292
+ let localAddress = (!proxy && !httpAgent.proxyUrl && route && route.localAddress) || null;
293
+
294
+ if (!proxy && !localAddress) {
295
+ return { fetch: httpAgent.fetch, retry: httpAgent.retry };
296
+ }
297
+
298
+ let now = Date.now();
299
+ let key = proxy ? `proxy:${proxy}` : `local:${localAddress}`;
300
+ let entry = routeDispatchers.get(key);
301
+
302
+ if (!entry) {
303
+ for (let [staleKey, stale] of routeDispatchers) {
304
+ if (now - stale.used > ROUTE_DISPATCHER_IDLE_MS) {
305
+ routeDispatchers.delete(staleKey);
306
+ stale.fetch.close().catch(() => false);
307
+ }
308
+ }
309
+
310
+ // undici takes the source address as an Agent option (inside `connect` it is overwritten);
311
+ // the family keeps an IPv4 source address from being paired with an IPv6 destination
312
+ let fetchDispatcher = buildFetchDispatcher(proxy, localAddress && { localAddress, connect: { family: net.isIPv6(localAddress) ? 6 : 4 } });
313
+ entry = { fetch: fetchDispatcher, retry: new RetryAgent(fetchDispatcher, RETRY_OPTS) };
314
+ routeDispatchers.set(key, entry);
315
+ }
316
+
317
+ entry.used = now;
318
+ return entry;
319
+ }
320
+ httpAgent.forRoute = dispatchersForRoute;
321
+
273
322
  // The main thread resolves the proxy from settings before it spawns anything (reloadHttpProxyAgent()
274
323
  // in server.js) and hands the result to every worker in workerData, so a worker's dispatchers are
275
324
  // right from its first line of code and no worker has to sequence its startup behind a settings
@@ -2808,6 +2857,7 @@ MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEV3QUiYsp13nD9suD1/ZkEXnuMoSg
2808
2857
  },
2809
2858
 
2810
2859
  httpAgent,
2860
+ ROUTE_DISPATCHER_IDLE_MS,
2811
2861
  reloadHttpProxyAgent,
2812
2862
  maybeReloadHttpProxyAgent,
2813
2863
  resolveHttpProxy,
@@ -8,7 +8,7 @@ const tokens = require('../tokens');
8
8
  const { redis } = require('../db');
9
9
  const getSecret = require('../get-secret');
10
10
  const { failAction, verifyAccountInfo, formatPartialSecretKey } = require('../tools');
11
- const { templateSchemas, accountIdSchema, tokenPermissionsSchema, formBoolean } = require('../schemas');
11
+ const { templateSchemas, accountIdSchema, tokenPermissionsSchema, formBoolean, mailboxAddressSchema } = require('../schemas');
12
12
  const tokenPermissionView = require('../token-permission-view');
13
13
  const { PRIVILEGED_SETTINGS_SUMMARY } = require('../privileged-settings');
14
14
  const { Account, accountExists, accountSummary } = require('../account');
@@ -1430,7 +1430,7 @@ return payload;`)
1430
1430
  .example('AAAAAQAACnA')
1431
1431
  .required()
1432
1432
  .description('Template ID'),
1433
- to: Joi.string().email().required().description('Recipient address'),
1433
+ to: mailboxAddressSchema.required().description('Recipient address'),
1434
1434
  params: Joi.object().description('Optional handlebars values').unknown()
1435
1435
  })
1436
1436
  }