emailengine-app 2.82.2 → 2.83.1

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 (70) hide show
  1. package/.ncurc.js +8 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +29 -0
  4. package/data/google-crawlers.json +1 -1
  5. package/lib/account.js +16 -3
  6. package/lib/api-reference/format.js +1 -1
  7. package/lib/api-routes/account-routes.js +8 -6
  8. package/lib/api-routes/blocklist-routes.js +4 -4
  9. package/lib/api-routes/export-routes.js +5 -5
  10. package/lib/api-routes/oauth2-app-routes.js +8 -2
  11. package/lib/api-routes/route-helpers.js +34 -0
  12. package/lib/api-routes/submit-routes.js +6 -5
  13. package/lib/bounce-detect.js +4 -2
  14. package/lib/egress-filter.js +8 -3
  15. package/lib/email-client/gmail-client.js +3 -1
  16. package/lib/email-client/imap-client.js +2 -1
  17. package/lib/email-client/outlook-client.js +11 -2
  18. package/lib/enum-descriptions.js +3 -1
  19. package/lib/imapproxy/imap-core/README.md +1 -0
  20. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +11 -1
  21. package/lib/imapproxy/proxy-handoff.js +6 -3
  22. package/lib/imapproxy/response-error.js +14 -1
  23. package/lib/oauth/gcp-metadata.js +259 -0
  24. package/lib/oauth/gmail.js +121 -20
  25. package/lib/oauth/mail-ru.js +10 -4
  26. package/lib/oauth/outlook.js +11 -4
  27. package/lib/oauth/token-fetch.js +4 -2
  28. package/lib/oauth/verify-app.js +126 -32
  29. package/lib/oauth2-apps.js +67 -13
  30. package/lib/schemas.js +60 -18
  31. package/lib/swagger-options.js +2 -3
  32. package/lib/tools.js +52 -2
  33. package/lib/ui-routes/admin-entities-routes.js +2 -2
  34. package/lib/ui-routes/auth-routes.js +4 -1
  35. package/lib/ui-routes/gmail-service-auth.js +64 -0
  36. package/lib/ui-routes/oauth-config-routes.js +22 -31
  37. package/lib/ui-routes/oauth-form-context.js +19 -0
  38. package/lib/ui-routes/suppression-list-routes.js +2 -2
  39. package/lib/utils/network.js +29 -0
  40. package/lib/webhook-request.js +12 -4
  41. package/lib/webhook-routing.js +34 -11
  42. package/package.json +11 -11
  43. package/sbom.json +1 -1
  44. package/server.js +8 -2
  45. package/static/css/flyonui.css +1 -1
  46. package/static/js/app.js +2 -1
  47. package/static/js/ui.js +6 -1
  48. package/static/licenses.html +18 -28
  49. package/translations/messages.pot +73 -73
  50. package/views/accounts/account.hbs +0 -5
  51. package/views/accounts/edit.hbs +1 -1
  52. package/views/config/imap-proxy.hbs +1 -1
  53. package/views/config/network.hbs +7 -5
  54. package/views/config/oauth/app.hbs +2 -0
  55. package/views/config/oauth/edit.hbs +0 -10
  56. package/views/config/oauth/new.hbs +0 -10
  57. package/views/config/smtp.hbs +1 -1
  58. package/views/config/tls.hbs +2 -2
  59. package/views/config/webhooks.hbs +1 -1
  60. package/views/partials/oauth_form.hbs +493 -906
  61. package/views/partials/oauth_graph_endpoints.hbs +12 -0
  62. package/views/partials/oauth_pubsub_app_select.hbs +11 -20
  63. package/views/partials/oauth_scope_presets.hbs +21 -0
  64. package/views/partials/ui/choice-tab.hbs +23 -0
  65. package/views/partials/ui/choice-tabs.hbs +32 -0
  66. package/views/partials/ui/radio.hbs +2 -2
  67. package/views/partials/ui/secret-field.hbs +2 -1
  68. package/views/partials/ui/tabs.hbs +1 -2
  69. package/workers/api.js +4 -2
  70. 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,74 @@ 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
+ 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
+ }
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.';
118
+ case 'EMetadataServer':
119
+ if (err.wrongFlavor) {
120
+ 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.';
121
+ }
122
+ if (err.statusCode === 404) {
123
+ 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.';
124
+ }
125
+ if (err.statusCode === 403) {
126
+ return 'The metadata server refused the request. On GKE, the Kubernetes service account must be bound to a Google service account through Workload Identity.';
127
+ }
128
+ return 'The metadata server did not issue a token. Retry in a moment; if it persists, check the service account attached to this instance.';
129
+ default:
130
+ return 'The metadata server answered without a usable access token.';
131
+ }
132
+ }
133
+
134
+ // Read-only proof that the token can do what a Pub/Sub app needs: reading the app's own topic. A
135
+ // token is not the same as access: the role may be missing, and on Compute Engine the VM's access
136
+ // scopes cap the token whatever roles the service account holds. The topic itself rather than a
137
+ // project listing, because the least-privilege role the documentation offers grants topics.get
138
+ // and not topics.list, and because a topic that was never created is worth reporting too
139
+ async function pubSubAccessProbe(appData, client, accessToken, steps) {
140
+ if (!appData.googleProjectId) {
141
+ steps.push(
142
+ mkStep('pubsub', 'Pub/Sub access', 'skip', 'No Google Cloud project ID is configured', {
143
+ hint: 'Set the Google Cloud Project ID in the app settings. EmailEngine creates the Pub/Sub topic and subscription in that project.'
144
+ })
145
+ );
146
+ return;
147
+ }
148
+
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}`;
154
+
155
+ try {
156
+ await client.request(accessToken, `https://pubsub.googleapis.com/v1/${topicName}`, 'get');
157
+ steps.push(mkStep('pubsub', 'Pub/Sub access', 'ok', `Pub/Sub topic ${topicName} is reachable`));
158
+ } catch (err) {
159
+ let status = err.statusCode;
160
+ let detail = describeResponse(err) || err.message;
161
+ let hint;
162
+ if (status === 403 && /scope/i.test(detail)) {
163
+ hint =
164
+ '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.';
165
+ } else if (status === 403) {
166
+ hint = `The service account is not allowed to manage Pub/Sub in project ${appData.googleProjectId}. Grant it the "Pub/Sub Admin" role.`;
167
+ } else if (status === 404) {
168
+ 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.`;
169
+ } else {
170
+ hint = 'The Pub/Sub API request failed. Check the project ID and that the Cloud Pub/Sub API is enabled.';
171
+ }
172
+ steps.push(mkStep('pubsub', 'Pub/Sub access', 'fail', detail, { hint }));
173
+ }
174
+ }
175
+
106
176
  // Maps GmailOauth.refreshToken (jwt-bearer) failures, using checkForFlags codes.
107
177
  function mapTokenError(err, account, appData, steps) {
108
178
  let flag = err.tokenRequest && err.tokenRequest.flag;
@@ -174,62 +244,86 @@ async function imapProbe(appData, account, accessToken, steps) {
174
244
 
175
245
  async function verifyGmailService(appData, opts, steps) {
176
246
  let { account, testConnection } = opts;
177
- let authMethod = appData.authMethod === 'externalAccount' ? 'externalAccount' : 'serviceKey';
247
+ let authMethod = normalizeAuthMethod(appData.authMethod);
178
248
 
179
249
  // Step 1 - configuration. getClient builds the signer, which validates the external
180
250
  // account JSON and the service-account-email match (or fails if creds are missing).
181
251
  let client;
182
252
  try {
183
253
  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
- );
254
+ let configMessage =
255
+ authMethod === 'metadataServer'
256
+ ? `Attached service account, read from the metadata server at ${gcpMetadata.resolveMetadataOrigin()}`
257
+ : authMethod === 'externalAccount'
258
+ ? 'External account configuration is valid'
259
+ : 'Service account key is present';
260
+ steps.push(mkStep('config', 'Configuration', 'ok', configMessage));
192
261
  } catch (err) {
193
262
  steps.push(
194
263
  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).'
264
+ hint:
265
+ err.code === 'EMetadataConfig'
266
+ ? metadataServerHint(err)
267
+ : 'Complete the service account credentials in the app settings (service client, email and key/external account configuration).'
196
268
  })
197
269
  );
198
270
  return finalize(appData, authMethod, steps, account);
199
271
  }
200
272
 
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'));
273
+ let isMetadataServer = authMethod === 'metadataServer';
274
+
275
+ // Step 2 - signing chain (no mailbox/email needed; signJwt signs an arbitrary payload). The
276
+ // attached service account has none: the metadata server issues the token itself
277
+ if (!isMetadataServer) {
278
+ try {
279
+ await client.generateServiceRequest(account || 'verify-probe@example.com', false);
280
+ if (authMethod === 'externalAccount') {
281
+ steps.push(mkStep('subjectToken', 'Read OIDC subject token', 'ok', 'Subject token read from the credential source'));
282
+ steps.push(mkStep('sts', 'STS token exchange', 'ok', 'Federated access token obtained from Google STS'));
283
+ steps.push(mkStep('signJwt', 'Sign assertion (signJwt)', 'ok', 'Assertion signed via IAM signJwt'));
284
+ } else {
285
+ steps.push(mkStep('sign', 'Sign assertion with service key', 'ok', 'Assertion signed locally with the service account key'));
286
+ }
287
+ } catch (err) {
288
+ mapSigningError(err, authMethod, steps);
289
+ return finalize(appData, authMethod, steps, account);
210
290
  }
211
- } catch (err) {
212
- mapSigningError(err, authMethod, steps);
213
- return finalize(appData, authMethod, steps, account);
214
291
  }
215
292
 
216
293
  // Pub/Sub apps authenticate as the service account itself (principal mode), not by
217
294
  // impersonating a user, so they need no mailbox address and no domain-wide delegation.
218
295
  if (appData.baseScopes === 'pubsub') {
296
+ let label = isMetadataServer ? 'Service account token (metadata server)' : 'Service account token';
297
+ let accessToken;
219
298
  try {
220
- let resp = await client.refreshToken({ isPrincipal: true });
299
+ // The attached service account is named by the metadata server, not the app record, so
300
+ // its email is read beside the token to say who EmailEngine acts as; its failure is ignored
301
+ let [resp, serviceAccountEmail] = await Promise.all([
302
+ client.refreshToken({ isPrincipal: true }),
303
+ isMetadataServer ? gcpMetadata.fetchServiceAccountEmail().catch(() => null) : null
304
+ ]);
221
305
  if (!resp || !resp.access_token) {
222
306
  throw Object.assign(new Error('No access token returned by the token endpoint'), { code: 'ETokenRefresh' });
223
307
  }
224
- steps.push(mkStep('token', 'Service account token', 'ok', 'App-only access token obtained for the service account'));
308
+ accessToken = resp.access_token;
309
+ let message = isMetadataServer
310
+ ? `Access token issued for ${serviceAccountEmail || 'the attached service account'}`
311
+ : 'App-only access token obtained for the service account';
312
+ steps.push(mkStep('token', label, 'ok', message));
225
313
  } catch (err) {
226
314
  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 }));
315
+ let hint;
316
+ if (isMetadataServer) {
317
+ hint = metadataServerHint(err);
318
+ } else if (flag && flag.code === 'INVALID_SERVICE_CLIENT_EMAIL') {
319
+ hint = 'The service account is invalid or unrecognized. Verify the service account email and client ID in the app settings.';
320
+ } else {
321
+ hint = 'The service account could not obtain its own access token. Verify the service account email and client ID in the app settings.';
322
+ }
323
+ steps.push(mkStep('token', label, 'fail', describeResponse(err) || err.message, { hint }));
324
+ return finalize(appData, authMethod, steps, account);
232
325
  }
326
+ await pubSubAccessProbe(appData, client, accessToken, steps);
233
327
  return finalize(appData, authMethod, steps, account);
234
328
  }
235
329
 
@@ -409,4 +503,4 @@ async function verifyOAuth2App(appId, opts) {
409
503
  module.exports = { verifyOAuth2App };
410
504
 
411
505
  // Exported for tests only; describeResponse reflects remote content into the verify report.
412
- module.exports.__test__ = { describeResponse, MAX_REMOTE_DETAIL_LENGTH };
506
+ 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,41 @@ 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
+
75
+ // Drops the credentials a gmailService app's method does not use, so nothing is stored that the app
76
+ // would never present
77
+ function withoutOtherCredentials(data, authMethod) {
78
+ let result = Object.assign({}, data);
79
+ for (let field of Object.values(SERVICE_AUTH_CREDENTIALS)) {
80
+ if (field && field !== SERVICE_AUTH_CREDENTIALS[authMethod]) {
81
+ delete result[field];
82
+ }
83
+ }
84
+ if (authMethod === 'metadataServer') {
85
+ for (let field of SERVICE_ACCOUNT_IDENTITY_FIELDS) {
86
+ delete result[field];
87
+ }
88
+ }
89
+ return result;
90
+ }
91
+
92
+ // The Pub/Sub topic and subscription a Pub/Sub app uses, by name within its project
93
+ function pubSubResourceNames(appData) {
94
+ return {
95
+ topic: appData.googleTopicName || `ee-pub-${appData.id}`,
96
+ subscription: appData.googleSubscriptionName || `ee-sub-${appData.id}`
97
+ };
98
+ }
99
+
100
+ // Whether a stored app's authentication method can no longer change: every saved gmailService app
101
+ function isAuthMethodLocked(appData) {
102
+ return !!appData && appData.provider === 'gmailService';
103
+ }
104
+
70
105
  // Workload Identity Federation signers, per app id. The signer caches the federated token and
71
106
  // deduplicates concurrent refreshes, which only helps when it outlives the GmailOauth client
72
107
  // built for each token renewal: without this every account ran its own STS exchange every hour.
@@ -128,7 +163,12 @@ function oauth2ProviderData(provider, selector) {
128
163
  // field and not on the provider, so a service account delegated gmail.modify is as API-based
129
164
  // as an interactive app. The form guards the controls that only make sense in that mode - the
130
165
  // scope presets, the Pub/Sub service account - on this rather than on one provider name.
131
- 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)
132
172
  };
133
173
 
134
174
  switch (provider) {
@@ -532,7 +572,7 @@ class OAuth2AppsHandler {
532
572
 
533
573
  case 'gmailService':
534
574
  entry.name = 'Gmail service';
535
- entry.authMethod = v('AuthMethod') === 'externalAccount' ? 'externalAccount' : 'serviceKey';
575
+ entry.authMethod = normalizeAuthMethod(v('AuthMethod'));
536
576
  entry.serviceClient = v('Client');
537
577
  entry.serviceKey = v('Key');
538
578
  entry.externalAccount = v('ExternalAccount');
@@ -685,6 +725,10 @@ class OAuth2AppsHandler {
685
725
  // opts.id is internal-only: migrateLegacyApps() preserves the historical legacy app IDs
686
726
  const id = (opts && opts.id) || (await this.generateId());
687
727
 
728
+ if (data && data.provider === 'gmailService') {
729
+ data = withoutOtherCredentials(data, normalizeAuthMethod(data.authMethod));
730
+ }
731
+
688
732
  let encryptedValues = {};
689
733
  for (let key of ENCRYPTED_APP_KEYS) {
690
734
  if (data[key]) {
@@ -758,11 +802,13 @@ class OAuth2AppsHandler {
758
802
  externalAccountSigners.delete(id);
759
803
  }
760
804
 
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' });
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
807
+ // to serviceKey, which would otherwise turn an attached service account app into a keyless
808
+ // key-signed one
809
+ let lockedAuthMethod = isAuthMethodLocked(existingData) ? normalizeAuthMethod(existingData.authMethod) : null;
810
+ if (lockedAuthMethod) {
811
+ data = Object.assign({}, data || {}, { authMethod: lockedAuthMethod });
766
812
  }
767
813
 
768
814
  let oldPubSubApp = existingData.pubSubApp || null;
@@ -779,6 +825,11 @@ class OAuth2AppsHandler {
779
825
  created: existingData.created,
780
826
  updated: new Date().toISOString()
781
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
+ }
782
833
 
783
834
  let updates = {
784
835
  [`${id}:data`]: msgpack.encode(entry)
@@ -1167,8 +1218,7 @@ class OAuth2AppsHandler {
1167
1218
  async ensurePubsub(appData) {
1168
1219
  let project = appData.googleProjectId;
1169
1220
 
1170
- let topic = appData.googleTopicName || `ee-pub-${appData.id}`;
1171
- let subscription = appData.googleSubscriptionName || `ee-sub-${appData.id}`;
1221
+ let { topic, subscription } = pubSubResourceNames(appData);
1172
1222
 
1173
1223
  // Determine desired expirationPolicy from setting
1174
1224
  let gmailSubscriptionTtl = await settings.get('gmailSubscriptionTtl');
@@ -1659,7 +1709,7 @@ class OAuth2AppsHandler {
1659
1709
  let serviceClient = appData.serviceClient;
1660
1710
 
1661
1711
  let serviceClientEmail = appData.serviceClientEmail;
1662
- let authMethod = appData.authMethod === 'externalAccount' ? 'externalAccount' : 'serviceKey';
1712
+ let authMethod = normalizeAuthMethod(appData.authMethod);
1663
1713
  let serviceKey = appData.serviceKey ? await this.decrypt(appData.serviceKey) : null;
1664
1714
  let externalAccount = appData.externalAccount ? await this.decrypt(appData.externalAccount) : null;
1665
1715
 
@@ -1668,7 +1718,9 @@ class OAuth2AppsHandler {
1668
1718
  let googleProjectId = appData.googleProjectId;
1669
1719
  let workspaceAccounts = appData.googleWorkspaceAccounts;
1670
1720
 
1671
- let credentialsReady = serviceClient && (authMethod === 'externalAccount' ? !!externalAccount : !!serviceKey);
1721
+ // A method with no stored credential (the attached service account) is always ready
1722
+ let credential = SERVICE_AUTH_CREDENTIALS[authMethod];
1723
+ let credentialsReady = !credential || (serviceClient && !!{ serviceKey, externalAccount }[credential]);
1672
1724
  if (!credentialsReady) {
1673
1725
  let error = Boom.boomify(new Error('OAuth2 credentials not set up for Gmail'), { statusCode: 400 });
1674
1726
  throw error;
@@ -1898,5 +1950,7 @@ module.exports = {
1898
1950
  SERVICE_ACCOUNT_PROVIDERS,
1899
1951
  oauth2ProviderData,
1900
1952
  formatExtraScopes,
1901
- isApiBasedApp
1953
+ isApiBasedApp,
1954
+ isAuthMethodLocked,
1955
+ pubSubResourceNames
1902
1956
  };
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,
@@ -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