emailengine-app 2.82.1 → 2.83.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/.ncurc.js +8 -1
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +25 -0
  4. package/data/google-crawlers.json +1 -1
  5. package/lib/account.js +16 -3
  6. package/lib/api-routes/account-routes.js +8 -6
  7. package/lib/api-routes/blocklist-routes.js +4 -4
  8. package/lib/api-routes/oauth2-app-routes.js +5 -2
  9. package/lib/api-routes/route-helpers.js +28 -0
  10. package/lib/api-routes/submit-routes.js +6 -5
  11. package/lib/bounce-detect.js +4 -2
  12. package/lib/egress-filter.js +8 -3
  13. package/lib/email-client/gmail-client.js +3 -1
  14. package/lib/email-client/imap-client.js +2 -1
  15. package/lib/email-client/outlook-client.js +106 -47
  16. package/lib/email-client/outlook-fallback-poll.js +30 -0
  17. package/lib/enum-descriptions.js +3 -1
  18. package/lib/imapproxy/imap-core/README.md +1 -0
  19. package/lib/imapproxy/imap-core/lib/commands/authenticate-plain.js +11 -1
  20. package/lib/imapproxy/proxy-handoff.js +6 -3
  21. package/lib/imapproxy/response-error.js +14 -1
  22. package/lib/oauth/gcp-metadata.js +222 -0
  23. package/lib/oauth/gmail.js +115 -20
  24. package/lib/oauth/mail-ru.js +10 -4
  25. package/lib/oauth/outlook.js +11 -4
  26. package/lib/oauth/token-fetch.js +4 -2
  27. package/lib/oauth/verify-app.js +120 -32
  28. package/lib/oauth2-apps.js +46 -12
  29. package/lib/schemas.js +60 -18
  30. package/lib/tools.js +52 -2
  31. package/lib/ui-routes/admin-entities-routes.js +2 -2
  32. package/lib/ui-routes/auth-routes.js +4 -1
  33. package/lib/ui-routes/gmail-service-auth.js +64 -0
  34. package/lib/ui-routes/oauth-config-routes.js +8 -16
  35. package/lib/ui-routes/outlook-subscription-view.js +36 -0
  36. package/lib/ui-routes/route-helpers.js +2 -14
  37. package/lib/ui-routes/suppression-list-routes.js +2 -2
  38. package/lib/utils/network.js +29 -0
  39. package/lib/webhook-request.js +12 -4
  40. package/lib/webhook-routing.js +34 -11
  41. package/package.json +11 -11
  42. package/sbom.json +1 -1
  43. package/server.js +8 -2
  44. package/static/css/flyonui.css +1 -1
  45. package/static/js/app.js +2 -1
  46. package/static/js/ui.js +6 -1
  47. package/static/licenses.html +18 -28
  48. package/translations/messages.pot +73 -73
  49. package/views/accounts/account.hbs +5 -2
  50. package/views/accounts/edit.hbs +1 -1
  51. package/views/config/imap-proxy.hbs +1 -1
  52. package/views/config/network.hbs +7 -5
  53. package/views/config/oauth/app.hbs +2 -0
  54. package/views/config/smtp.hbs +1 -1
  55. package/views/config/tls.hbs +2 -2
  56. package/views/config/webhooks.hbs +1 -1
  57. package/views/partials/oauth_form.hbs +116 -27
  58. package/workers/api.js +4 -2
  59. package/workers/webhooks.js +18 -7
@@ -8,8 +8,23 @@ const { fetch: fetchCmd } = require('undici');
8
8
 
9
9
  const { ExternalAccountSigner } = require('./external-account-signer');
10
10
  const { fetchTokenRequest } = require('./token-fetch');
11
+ const gcpMetadata = require('./gcp-metadata');
12
+
13
+ // The stored credential each service account authentication method presents. The attached service
14
+ // account (metadataServer) stores none: the metadata server holds it
15
+ const SERVICE_AUTH_CREDENTIALS = {
16
+ serviceKey: 'serviceKey',
17
+ externalAccount: 'externalAccount',
18
+ metadataServer: null
19
+ };
20
+
21
+ const SERVICE_AUTH_METHODS = new Set(Object.keys(SERVICE_AUTH_CREDENTIALS));
11
22
 
12
- const SERVICE_AUTH_METHODS = new Set(['serviceKey', 'externalAccount']);
23
+ // The stored authentication method of a gmailService app. Apps saved before the method was
24
+ // recorded carry none, and those were all key-signed
25
+ function normalizeAuthMethod(authMethod) {
26
+ return SERVICE_AUTH_METHODS.has(authMethod) ? authMethod : 'serviceKey';
27
+ }
13
28
 
14
29
  class LocalKeySigner {
15
30
  constructor(opts) {
@@ -234,14 +249,20 @@ function workspaceDomainOf(idTokenPayload) {
234
249
 
235
250
  class GmailOauth {
236
251
  constructor(opts) {
252
+ // The network route of the account this client acts for (see getAccountHttpRoute()). Every
253
+ // token and API request it makes takes that route; null for an app-level client.
254
+ this.route = opts.route || null;
255
+
237
256
  const defaultBaseScopes = (opts.baseScopes && GMAIL_SCOPES[opts.baseScopes]) || GMAIL_SCOPES.imap;
238
257
 
239
258
  let requestedScopes = [].concat(opts.scopes || defaultBaseScopes);
240
259
 
241
260
  // Only include OpenID Connect scopes for regular OAuth (not service accounts)
242
261
  // Service accounts use JWT-based authentication and don't need OpenID scopes
243
- // These are non-privileged scopes that provide email and profile info for 3-legged OAuth
244
- if (!opts.serviceClient) {
262
+ // These are non-privileged scopes that provide email and profile info for 3-legged OAuth.
263
+ // An app using the attached service account names no service client, the metadata server
264
+ // knows which account it is, but it is a service app all the same
265
+ if (!opts.serviceClient && opts.authMethod !== 'metadataServer') {
245
266
  const openidScopes = OPENID_SCOPES;
246
267
 
247
268
  // Add OpenID scopes if not already present
@@ -285,9 +306,12 @@ class GmailOauth {
285
306
  }
286
307
  this.authMethod = authMethod;
287
308
 
288
- // Only build a signer when this is a service-account-mode app.
289
- // 3-legged OAuth has no serviceClient and never reaches generateServiceRequest.
290
- if (this.serviceClient) {
309
+ // Only build a signer when this is a service-account-mode app that signs an assertion.
310
+ // 3-legged OAuth has no serviceClient and never reaches generateServiceRequest, and the
311
+ // metadata server hands out the access token itself, so there is nothing to sign
312
+ this.metadataClient = opts.metadataClient || gcpMetadata;
313
+
314
+ if (this.serviceClient && this.authMethod !== 'metadataServer') {
291
315
  if (this.authMethod === 'externalAccount') {
292
316
  // The signer caches the federated token and deduplicates concurrent refreshes, which
293
317
  // only pays off when it outlives this client: every token renewal builds a new
@@ -399,12 +423,17 @@ class GmailOauth {
399
423
  body: tokenRequest.body
400
424
  };
401
425
 
402
- let res = await fetchTokenRequest(requestUrl, fetchOpts, {
403
- grant: 'authorization_code',
404
- provider: this.provider,
405
- clientId: this.clientId,
406
- serviceClient: this.serviceClient
407
- });
426
+ let res = await fetchTokenRequest(
427
+ requestUrl,
428
+ fetchOpts,
429
+ {
430
+ grant: 'authorization_code',
431
+ provider: this.provider,
432
+ clientId: this.clientId,
433
+ serviceClient: this.serviceClient
434
+ },
435
+ this.route
436
+ );
408
437
 
409
438
  let responseJson;
410
439
  try {
@@ -477,6 +506,10 @@ class GmailOauth {
477
506
  async refreshToken(opts) {
478
507
  opts = opts || {};
479
508
 
509
+ if (this.authMethod === 'metadataServer') {
510
+ return await this.refreshFromMetadataServer(opts);
511
+ }
512
+
480
513
  const url = new URL(this.tokenUrl);
481
514
 
482
515
  if (this.serviceClient) {
@@ -514,12 +547,17 @@ class GmailOauth {
514
547
  body: bodyString
515
548
  };
516
549
 
517
- let res = await fetchTokenRequest(requestUrl, fetchOpts, {
518
- grant: 'refresh_token',
519
- provider: this.provider,
520
- clientId: this.clientId,
521
- serviceClient: this.serviceClient
522
- });
550
+ let res = await fetchTokenRequest(
551
+ requestUrl,
552
+ fetchOpts,
553
+ {
554
+ grant: 'refresh_token',
555
+ provider: this.provider,
556
+ clientId: this.clientId,
557
+ serviceClient: this.serviceClient
558
+ },
559
+ this.route
560
+ );
523
561
 
524
562
  let responseJson;
525
563
  try {
@@ -594,6 +632,61 @@ class GmailOauth {
594
632
  return responseJson;
595
633
  }
596
634
 
635
+ // The attached service account's token comes straight from the metadata server. That token is
636
+ // the service account's own, and nothing can turn it into a Workspace user's: domain-wide
637
+ // delegation needs an assertion signed as the service account, which this method has no way to
638
+ // produce. The schema keeps the method to Pub/Sub apps; this refuses a delegated request anyway
639
+ async refreshFromMetadataServer(opts) {
640
+ if (!opts.isPrincipal) {
641
+ let err = new Error('An app using the attached service account can only request a token for the service account itself');
642
+ err.code = 'EDelegationUnsupported';
643
+ throw err;
644
+ }
645
+
646
+ let response;
647
+ try {
648
+ response = await this.metadataClient.fetchAccessToken();
649
+ } catch (err) {
650
+ // Same level as the token endpoint requests; the caller logs the error itself
651
+ if (this.logger) {
652
+ this.logger.info({
653
+ msg: 'OAuth2 authentication request',
654
+ action: 'oauth2Fetch',
655
+ fn: 'refreshFromMetadataServer',
656
+ provider: this.provider,
657
+ success: false,
658
+ status: err.statusCode,
659
+ code: err.code,
660
+ error: err.message
661
+ });
662
+ }
663
+
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 };
670
+ throw err;
671
+ }
672
+
673
+ if (this.logger) {
674
+ this.logger.info({
675
+ msg: 'OAuth2 authentication request',
676
+ action: 'oauth2Fetch',
677
+ fn: 'refreshFromMetadataServer',
678
+ provider: this.provider,
679
+ success: true,
680
+ response: formatFetchResponse(response, this.logRaw)
681
+ });
682
+ }
683
+
684
+ // clear potential auth flag
685
+ await this.setFlag();
686
+
687
+ return response;
688
+ }
689
+
597
690
  async request(accessToken, url, method, payload, options) {
598
691
  options = options || {};
599
692
 
@@ -608,7 +701,7 @@ class GmailOauth {
608
701
  // what Gmail answered, and that is decided by the request layer above this one
609
702
  // (lib/email-client/api-retry.js); a transport that retried on its own replayed sends
610
703
  // after a socket drop and multiplied throttled calls
611
- dispatcher: httpAgent.fetch,
704
+ dispatcher: httpAgent.forRoute(this.route).fetch,
612
705
  signal: options.signal || undefined
613
706
  };
614
707
 
@@ -812,7 +905,7 @@ class GmailOauth {
812
905
  };
813
906
 
814
907
  try {
815
- let res = await fetchCmd(this.revokeUrl, Object.assign(fetchOpts, { dispatcher: httpAgent.retry }));
908
+ let res = await fetchCmd(this.revokeUrl, Object.assign(fetchOpts, { dispatcher: httpAgent.forRoute(this.route).retry }));
816
909
 
817
910
  let responseText;
818
911
  try {
@@ -862,3 +955,5 @@ module.exports.OPENID_SCOPES = OPENID_SCOPES;
862
955
  module.exports.LocalKeySigner = LocalKeySigner;
863
956
  module.exports.parseExternalAccountConfig = parseExternalAccountConfig;
864
957
  module.exports.SERVICE_AUTH_METHODS = SERVICE_AUTH_METHODS;
958
+ module.exports.SERVICE_AUTH_CREDENTIALS = SERVICE_AUTH_CREDENTIALS;
959
+ module.exports.normalizeAuthMethod = normalizeAuthMethod;
@@ -52,6 +52,10 @@ const formatFetchResponse = (responseObj, logRaw) => {
52
52
 
53
53
  class MailRuOauth {
54
54
  constructor(opts) {
55
+ // The network route of the account this client acts for (see getAccountHttpRoute()). Every
56
+ // token and API request it makes takes that route; null for an app-level client.
57
+ this.route = opts.route || null;
58
+
55
59
  this.scopes = [].concat(opts.scopes || MAIL_RU_SCOPES);
56
60
  this.clientId = opts.clientId;
57
61
  this.clientSecret = opts.clientSecret;
@@ -121,7 +125,8 @@ class MailRuOauth {
121
125
  },
122
126
  body: tokenRequest.body
123
127
  },
124
- { grant: 'authorization_code', provider: this.provider, clientId: this.clientId }
128
+ { grant: 'authorization_code', provider: this.provider, clientId: this.clientId },
129
+ this.route
125
130
  );
126
131
 
127
132
  let responseJson;
@@ -208,7 +213,8 @@ class MailRuOauth {
208
213
  },
209
214
  body: bodyString
210
215
  },
211
- { grant: 'refresh_token', provider: this.provider, clientId: this.clientId }
216
+ { grant: 'refresh_token', provider: this.provider, clientId: this.clientId },
217
+ this.route
212
218
  );
213
219
 
214
220
  let responseJson;
@@ -276,7 +282,7 @@ class MailRuOauth {
276
282
  headers: {
277
283
  'User-Agent': `${packageData.name}/${packageData.version} (+${packageData.homepage})`
278
284
  },
279
- dispatcher: httpAgent.retry
285
+ dispatcher: httpAgent.forRoute(this.route).retry
280
286
  };
281
287
 
282
288
  if (payload) {
@@ -290,7 +296,7 @@ class MailRuOauth {
290
296
  reqData.body = payload;
291
297
  if (payload.length > 0) {
292
298
  // Non-empty buffers use non-retry dispatcher to prevent ArrayBuffer detachment
293
- reqData.dispatcher = httpAgent.fetch;
299
+ reqData.dispatcher = httpAgent.forRoute(this.route).fetch;
294
300
  }
295
301
  }
296
302
  }
@@ -161,6 +161,10 @@ const formatFetchResponse = (responseObj, logRaw) => {
161
161
 
162
162
  class OutlookOauth {
163
163
  constructor(opts) {
164
+ // The network route of the account this client acts for (see getAccountHttpRoute()). Every
165
+ // token and API request it makes takes that route; null for an app-level client.
166
+ this.route = opts.route || null;
167
+
164
168
  this.cloud = opts.cloud || 'global';
165
169
 
166
170
  const defaultBaseScopes = (opts.baseScopes && outlookScopes(this.cloud)[opts.baseScopes]) || outlookScopes(this.cloud).imap;
@@ -280,7 +284,8 @@ class OutlookOauth {
280
284
  },
281
285
  body: tokenRequest.body
282
286
  },
283
- { grant: 'authorization_code', provider: this.provider, clientId: this.clientId, authority: this.authority }
287
+ { grant: 'authorization_code', provider: this.provider, clientId: this.clientId, authority: this.authority },
288
+ this.route
284
289
  );
285
290
 
286
291
  let responseJson;
@@ -384,7 +389,8 @@ class OutlookOauth {
384
389
  },
385
390
  body: bodyString
386
391
  },
387
- { grant: 'refresh_token', provider: this.provider, clientId: this.clientId, authority: this.authority }
392
+ { grant: 'refresh_token', provider: this.provider, clientId: this.clientId, authority: this.authority },
393
+ this.route
388
394
  );
389
395
 
390
396
  let responseJson;
@@ -478,7 +484,8 @@ class OutlookOauth {
478
484
  },
479
485
  body: bodyString
480
486
  },
481
- { grant: 'client_credentials', provider: this.provider, clientId: this.clientId, authority: this.authority }
487
+ { grant: 'client_credentials', provider: this.provider, clientId: this.clientId, authority: this.authority },
488
+ this.route
482
489
  );
483
490
 
484
491
  let responseJson;
@@ -559,7 +566,7 @@ class OutlookOauth {
559
566
  // (lib/email-client/api-retry.js); a transport that retried on its own replayed sends
560
567
  // after a socket drop (a repeated draft /send then failed with 404, reporting a sent
561
568
  // message as failed) and multiplied throttled calls
562
- dispatcher: httpAgent.fetch
569
+ dispatcher: httpAgent.forRoute(this.route).fetch
563
570
  };
564
571
 
565
572
  if (options.headers) {
@@ -23,13 +23,15 @@ const { httpAgent } = require('../tools');
23
23
  * @param {Object} options - fetch options; the retrying dispatcher is applied here and cannot be overridden
24
24
  * @param {Object} context - what to record about the attempt, as the rejected-response path records it.
25
25
  * The method is read from `options`, so the two cannot disagree
26
+ * @param {Object} [route] - the account's network route ({ proxy, localAddress }, see getAccountHttpRoute()),
27
+ * so a token request leaves the way the account's other traffic does
26
28
  * @returns {Promise<Response>} the response, whatever its status
27
29
  */
28
- async function fetchTokenRequest(url, options, context) {
30
+ async function fetchTokenRequest(url, options, context, route) {
29
31
  try {
30
32
  // The dispatcher is applied last, so this helper really is the one place that decides it -
31
33
  // with the default first, a caller that passed one would silently lose the retrying agent
32
- return await fetchCmd(url, Object.assign({}, options, { dispatcher: httpAgent.retry }));
34
+ return await fetchCmd(url, Object.assign({}, options, { dispatcher: httpAgent.forRoute(route).retry }));
33
35
  } catch (err) {
34
36
  // The cause carries the actionable code. Promoted onto the error itself so the connectError
35
37
  // webhook has something to report - the transient check consults both, so no verdict changes.
@@ -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
  };