emailengine-app 2.84.2 → 2.86.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.
- package/.ncurc.js +29 -9
- package/.prettierignore +5 -1
- package/.prettierrc.js +2 -0
- package/.release-please-manifest.json +1 -1
- package/CHANGELOG.md +107 -0
- package/Dockerfile +20 -1
- package/ENVIRONMENT.md +139 -0
- package/README.md +2 -2
- package/bin/emailengine.js +434 -408
- package/config/default.toml +2 -0
- package/copy-static-files.sh +41 -14
- package/data/google-crawlers.json +1 -1
- package/data/public_suffix_list.dat +16563 -0
- package/eslint.config.js +81 -99
- package/lib/account-assignment.js +19 -0
- package/lib/account.js +230 -170
- package/lib/api-error-codes.js +49 -0
- package/lib/api-reference/format.js +4 -3
- package/lib/api-reference/model.js +6 -1
- package/lib/api-routes/account-routes.js +255 -38
- package/lib/api-routes/blocklist-routes.js +91 -4
- package/lib/api-routes/delivery-test-routes.js +27 -4
- package/lib/api-routes/export-routes.js +28 -2
- package/lib/api-routes/gateway-routes.js +110 -12
- package/lib/api-routes/index.js +4 -0
- package/lib/api-routes/license-routes.js +2 -2
- package/lib/api-routes/mailbox-routes.js +44 -5
- package/lib/api-routes/message-routes.js +112 -10
- package/lib/api-routes/oauth2-app-routes.js +63 -23
- package/lib/api-routes/outbox-routes.js +97 -52
- package/lib/api-routes/permission-map.js +67 -7
- package/lib/api-routes/scoped-routes.js +74 -0
- package/lib/api-routes/settings-routes.js +34 -6
- package/lib/api-routes/stats-routes.js +5 -1
- package/lib/api-routes/submit-routes.js +337 -309
- package/lib/api-routes/template-routes.js +45 -8
- package/lib/api-routes/token-routes.js +152 -100
- package/lib/api-routes/webhook-delivery-routes.js +262 -0
- package/lib/api-routes/webhook-route-routes.js +132 -6
- package/lib/bounce-detect.js +397 -205
- package/lib/calendar-event.js +81 -1
- package/lib/consts.js +38 -45
- package/lib/db.js +14 -6
- package/lib/delivery-error.js +6 -0
- package/lib/deprecations.js +270 -0
- package/lib/email-client/base-client.js +137 -184
- package/lib/email-client/fallback-poll.js +62 -0
- package/lib/email-client/gmail-client.js +60 -22
- package/lib/email-client/imap/adaptive-idle-store.js +73 -0
- package/lib/email-client/imap/adaptive-idle.js +278 -0
- package/lib/email-client/imap/connection-errors.js +14 -1
- package/lib/email-client/imap/idle-settings.js +31 -5
- package/lib/email-client/imap/listing-diff.js +37 -0
- package/lib/email-client/imap/mailbox.js +372 -242
- package/lib/email-client/imap/subconnection.js +8 -30
- package/lib/email-client/imap/sync-operations.js +220 -127
- package/lib/email-client/imap-client.js +228 -164
- package/lib/email-client/message-builder.js +14 -79
- package/lib/email-client/notification-handler.js +1 -2
- package/lib/email-client/outlook-client.js +372 -338
- package/lib/email-client/smtp-pool-manager.js +16 -13
- package/lib/email-client/sync-state-fields.js +19 -0
- package/lib/encrypt.js +157 -41
- package/lib/enum-descriptions.js +3 -1
- package/lib/env-setting-overrides.js +288 -0
- package/lib/export-worker.js +751 -0
- package/lib/export.js +64 -15
- package/lib/gateway.js +19 -4
- package/lib/get-raw-email.js +25 -107
- package/lib/hapi-request-logger.js +107 -0
- package/lib/health.js +75 -0
- package/lib/imapproxy/imap-core/README.md +6 -5
- package/lib/lock-run.js +119 -0
- package/lib/logger-consts.js +48 -0
- package/lib/logger.js +1 -1
- package/lib/lua/z-head-scores.lua +28 -0
- package/lib/mcp/tools.js +37 -8
- package/lib/network-errors.js +1 -1
- package/lib/node-version.js +24 -0
- package/lib/notify-attachments.js +36 -0
- package/lib/oauth/outlook-mailbox.js +35 -0
- package/lib/oauth/state.js +24 -0
- package/lib/oauth2-apps.js +631 -656
- package/lib/outbox.js +184 -54
- package/lib/parse-message.js +3 -3
- package/lib/pbkdf2-phc.js +1 -1
- package/lib/privileged-settings.js +2 -2
- package/lib/queue-browser/definitions.js +11 -0
- package/lib/queue-browser/index.js +68 -19
- package/lib/queue-job-actions.js +18 -1
- package/lib/queue-retention.js +48 -12
- package/lib/queue-stats.js +11 -2
- package/lib/read-env-value.js +3 -0
- package/lib/redis-memory-warnings.js +99 -0
- package/lib/redis-reconnect.js +29 -0
- package/lib/request-timing.js +23 -0
- package/lib/respawn-backoff.js +35 -0
- package/lib/rewrite-text-nodes.js +19 -59
- package/lib/schemas.js +164 -40
- package/lib/settings.js +6 -2
- package/lib/smtp-auth.js +19 -1
- package/lib/sso.js +1 -1
- package/lib/swagger-options.js +1 -1
- package/lib/thread-diagnostics.js +63 -0
- package/lib/timezones.js +109 -0
- package/lib/tls/provision.js +6 -3
- package/lib/token-audit-log.js +19 -20
- package/lib/token-permission-view.js +7 -6
- package/lib/tools.js +48 -51
- package/lib/totp.js +2 -5
- package/lib/translations.js +1 -2
- package/lib/ui-routes/account-routes.js +475 -454
- package/lib/ui-routes/account-setup.js +99 -0
- package/lib/ui-routes/admin-config-routes.js +152 -100
- package/lib/ui-routes/admin-entities-routes.js +93 -21
- package/lib/ui-routes/auth-routes.js +90 -38
- package/lib/ui-routes/imap-idle-field.js +1 -1
- package/lib/ui-routes/internals-routes.js +5 -0
- package/lib/ui-routes/oauth-config-routes.js +124 -82
- package/lib/ui-routes/outlook-subscription-view.js +1 -1
- package/lib/ui-routes/overridable-fields.js +84 -0
- package/lib/ui-routes/queue-routes.js +8 -5
- package/lib/ui-routes/route-helpers.js +19 -3
- package/lib/ui-routes/settings-page.js +6 -0
- package/lib/ui-routes/tls-config-routes.js +58 -15
- package/lib/utils/back-off.js +82 -0
- package/lib/utils/decode-headers.js +3 -12
- package/lib/utils/filter-empty.js +20 -0
- package/lib/utils/int-setting.js +48 -0
- package/lib/utils/murmurhash3.js +66 -0
- package/lib/utils/public-suffix.js +122 -0
- package/lib/utils/random-id.js +26 -0
- package/lib/utils/tracking-settings.js +35 -0
- package/lib/utils/version.js +74 -0
- package/lib/web-safe-html.js +18 -105
- package/lib/webhook-delivery.js +461 -0
- package/lib/webhook-failures.js +132 -0
- package/lib/webhook-request.js +29 -1
- package/lib/webhook-routing.js +56 -0
- package/lib/webhook-test.js +88 -0
- package/lib/webhooks.js +93 -45
- package/lib/worker-rpc-error.js +2 -1
- package/package.json +37 -38
- package/sbom.json +7902 -1
- package/server.js +784 -518
- package/static/js/ace/ace.js +1 -1
- package/static/licenses.html +225 -1060
- package/translations/messages.pot +62 -63
- package/views/config/ai.hbs +1 -1
- package/views/config/security.hbs +24 -2
- package/views/config/service.hbs +47 -0
- package/views/config/webhooks.hbs +36 -0
- package/views/internals/index.hbs +8 -0
- package/views/partials/queue_retention_note.hbs +12 -8
- package/views/partials/ui/env-managed-alert.hbs +16 -7
- package/views/partials/webhook_form.hbs +1 -1
- package/views/suppression-lists/index.hbs +1 -1
- package/workers/api.js +840 -611
- package/workers/export.js +17 -632
- package/workers/imap.js +13 -0
- package/workers/smtp.js +9 -11
- package/workers/submit.js +1 -1
- package/workers/webhooks.js +18 -448
- package/lib/email-client/outlook-fallback-poll.js +0 -30
package/lib/oauth2-apps.js
CHANGED
|
@@ -13,7 +13,7 @@ const {
|
|
|
13
13
|
const { encrypt, decrypt } = require('./encrypt');
|
|
14
14
|
const Boom = require('@hapi/boom');
|
|
15
15
|
const settings = require('./settings');
|
|
16
|
-
const
|
|
16
|
+
const { runLocked, refuseUnavailableLock, rethrowUnavailableLock, getSharedLock } = require('./lock-run');
|
|
17
17
|
const getSecret = require('./get-secret');
|
|
18
18
|
const { parentPort } = require('worker_threads');
|
|
19
19
|
const { matchesListQuery } = require('./tools');
|
|
@@ -54,6 +54,31 @@ const { MailRuOauth, MAIL_RU_SCOPES } = require('./oauth/mail-ru');
|
|
|
54
54
|
// migrateLegacyApps(); migrated apps keep these IDs, but are otherwise regular apps.
|
|
55
55
|
const LEGACY_KEYS = ['gmail', 'gmailService', 'outlook', 'mailRu'];
|
|
56
56
|
|
|
57
|
+
// Full per-app settings key suffixes ever used by the legacy configuration
|
|
58
|
+
const LEGACY_FIELDS = [
|
|
59
|
+
'Enabled',
|
|
60
|
+
'RedirectUrl',
|
|
61
|
+
'Client',
|
|
62
|
+
'ClientId',
|
|
63
|
+
'ClientSecret',
|
|
64
|
+
'Authority',
|
|
65
|
+
'ExtraScopes',
|
|
66
|
+
'SkipScopes',
|
|
67
|
+
'Key',
|
|
68
|
+
'AuthFlag',
|
|
69
|
+
'AuthMethod',
|
|
70
|
+
'ExternalAccount'
|
|
71
|
+
];
|
|
72
|
+
|
|
73
|
+
// Even older generic service-account keys with no reader left anywhere; dropped without migration
|
|
74
|
+
const LEGACY_ORPHAN_KEYS = ['serviceClient', 'serviceKey', 'serviceExtraScopes'];
|
|
75
|
+
|
|
76
|
+
const LEGACY_CANDIDATE_KEYS = LEGACY_KEYS.flatMap(id => LEGACY_FIELDS.map(field => `${id}${field}`)).concat(LEGACY_ORPHAN_KEYS);
|
|
77
|
+
|
|
78
|
+
// One batched read for every legacy key; settings.getMulti() also decrypts stored secrets
|
|
79
|
+
const readLegacyValues = async () => await settings.getMulti(...LEGACY_CANDIDATE_KEYS);
|
|
80
|
+
const hasLegacyValues = values => Object.values(values).some(value => value !== null);
|
|
81
|
+
|
|
57
82
|
// A successful API request clears the app's auth flag. Checking for one costs a Redis read, so a
|
|
58
83
|
// client checks at most this often; setting a flag is never throttled
|
|
59
84
|
const AUTH_FLAG_CLEAR_INTERVAL = 60 * 1000;
|
|
@@ -140,11 +165,6 @@ const OAUTH_PROVIDERS = {
|
|
|
140
165
|
// Providers that use app-only credentials (no interactive user login)
|
|
141
166
|
const SERVICE_ACCOUNT_PROVIDERS = new Set(['gmailService', 'outlookService']);
|
|
142
167
|
|
|
143
|
-
const lock = new Lock({
|
|
144
|
-
redis,
|
|
145
|
-
namespace: 'ee'
|
|
146
|
-
});
|
|
147
|
-
|
|
148
168
|
function oauth2ProviderData(provider, selector) {
|
|
149
169
|
let caseName = provider.replace(/^./, c => c.toUpperCase());
|
|
150
170
|
|
|
@@ -229,7 +249,7 @@ function oauth2ProviderData(provider, selector) {
|
|
|
229
249
|
providerData.tutorialUrl = 'https://learn.emailengine.app/docs/accounts/microsoft-365/outlook-365';
|
|
230
250
|
providerData.linkImage = '/static/providers/ms_light.svg';
|
|
231
251
|
} else {
|
|
232
|
-
providerData.tutorialUrl = 'https://learn.emailengine.app/docs/accounts/outlook-client-credentials';
|
|
252
|
+
providerData.tutorialUrl = 'https://learn.emailengine.app/docs/accounts/microsoft-365/outlook-client-credentials';
|
|
233
253
|
}
|
|
234
254
|
providerData.imap = {
|
|
235
255
|
host: imapHost,
|
|
@@ -467,221 +487,198 @@ class OAuth2AppsHandler {
|
|
|
467
487
|
// is an idempotent SADD). A Redis lock guards against parallel instances sharing one
|
|
468
488
|
// Redis. Returns the list of migrated app IDs.
|
|
469
489
|
async migrateLegacyApps() {
|
|
470
|
-
// Full per-app settings key suffixes ever used by the legacy configuration
|
|
471
|
-
const FIELDS = [
|
|
472
|
-
'Enabled',
|
|
473
|
-
'RedirectUrl',
|
|
474
|
-
'Client',
|
|
475
|
-
'ClientId',
|
|
476
|
-
'ClientSecret',
|
|
477
|
-
'Authority',
|
|
478
|
-
'ExtraScopes',
|
|
479
|
-
'SkipScopes',
|
|
480
|
-
'Key',
|
|
481
|
-
'AuthFlag',
|
|
482
|
-
'AuthMethod',
|
|
483
|
-
'ExternalAccount'
|
|
484
|
-
];
|
|
485
|
-
|
|
486
|
-
// Even older generic service-account keys with no reader left anywhere; dropped without migration
|
|
487
|
-
const ORPHAN_KEYS = ['serviceClient', 'serviceKey', 'serviceExtraScopes'];
|
|
488
|
-
|
|
489
|
-
const candidateKeys = LEGACY_KEYS.flatMap(id => FIELDS.map(field => `${id}${field}`)).concat(ORPHAN_KEYS);
|
|
490
|
-
|
|
491
|
-
// One batched read for every legacy key; settings.getMulti() also decrypts stored secrets
|
|
492
|
-
const readLegacyValues = async () => await settings.getMulti(...candidateKeys);
|
|
493
|
-
const hasValues = values => Object.values(values).some(value => value !== null);
|
|
494
|
-
|
|
495
490
|
// cheap presence probe before taking the lock
|
|
496
|
-
if (!
|
|
491
|
+
if (!hasLegacyValues(await readLegacyValues())) {
|
|
497
492
|
return [];
|
|
498
493
|
}
|
|
499
494
|
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
495
|
+
return await runLocked(
|
|
496
|
+
getSharedLock(),
|
|
497
|
+
'oauth:legacy:migrate',
|
|
498
|
+
{ ttl: 5 * 60 * 1000, wait: 2 * 60 * 1000 },
|
|
499
|
+
() => this.migrateLegacyAppsLocked(),
|
|
500
|
+
rethrowUnavailableLock(logger, 'Failed to get lock for the legacy OAuth2 app migration', {})
|
|
501
|
+
);
|
|
502
|
+
}
|
|
504
503
|
|
|
504
|
+
// migrateLegacyApps() under the migration lock
|
|
505
|
+
async migrateLegacyAppsLocked() {
|
|
505
506
|
let migrated = [];
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
507
|
+
// re-read inside the lock: another instance may have finished the migration already
|
|
508
|
+
let values = await readLegacyValues();
|
|
509
|
+
if (!hasLegacyValues(values)) {
|
|
510
|
+
return [];
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
const normalizeScopes = value => {
|
|
514
|
+
if (!Array.isArray(value)) {
|
|
515
|
+
value = (value || '').toString().split(/[\s,]+/);
|
|
511
516
|
}
|
|
517
|
+
return value.filter(entry => entry);
|
|
518
|
+
};
|
|
512
519
|
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
520
|
+
// A stored secret whose decryption failed (a rotated or missing service secret) reads
|
|
521
|
+
// back as null through settings.getMulti(), exactly like an absent key. Deleting the
|
|
522
|
+
// source keys in that state would destroy the only copy of the ciphertext, so probe
|
|
523
|
+
// the raw hash to tell the two apart and leave such an app entirely untouched - the
|
|
524
|
+
// migration retries on the next startup, and restoring the correct service secret
|
|
525
|
+
// makes it whole again.
|
|
526
|
+
const encryptedCandidates = LEGACY_CANDIDATE_KEYS.filter(key => settings.encryptedKeys.includes(key));
|
|
527
|
+
const rawEncryptedValues = await this.redis.hmget(this.getSettingsKey(), encryptedCandidates);
|
|
528
|
+
const undecryptable = new Set(encryptedCandidates.filter((key, i) => rawEncryptedValues[i] !== null && values[key] === null));
|
|
529
|
+
|
|
530
|
+
// Apps whose accounts should be (re-)linked, and apps whose source keys may be dropped
|
|
531
|
+
let backfillable = [];
|
|
532
|
+
let clearable = [];
|
|
533
|
+
|
|
534
|
+
for (let legacyKey of LEGACY_KEYS) {
|
|
535
|
+
const v = field => values[`${legacyKey}${field}`];
|
|
536
|
+
|
|
537
|
+
let failedKeys = LEGACY_FIELDS.map(field => `${legacyKey}${field}`).filter(key => undecryptable.has(key));
|
|
538
|
+
if (failedKeys.length) {
|
|
539
|
+
logger.error({
|
|
540
|
+
msg: 'Skipped legacy OAuth2 app migration: stored credentials could not be decrypted. Restore the original service secret and restart',
|
|
541
|
+
app: legacyKey,
|
|
542
|
+
keys: failedKeys
|
|
543
|
+
});
|
|
544
|
+
continue;
|
|
545
|
+
}
|
|
519
546
|
|
|
520
|
-
//
|
|
521
|
-
//
|
|
522
|
-
//
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
let failedKeys = FIELDS.map(field => `${legacyKey}${field}`).filter(key => undecryptable.has(key));
|
|
538
|
-
if (failedKeys.length) {
|
|
539
|
-
logger.error({
|
|
540
|
-
msg: 'Skipped legacy OAuth2 app migration: stored credentials could not be decrypted. Restore the original service secret and restart',
|
|
541
|
-
app: legacyKey,
|
|
542
|
-
keys: failedKeys
|
|
543
|
-
});
|
|
544
|
-
continue;
|
|
545
|
-
}
|
|
547
|
+
// Same visibility rule the legacy listing applied: an app existed when it was
|
|
548
|
+
// enabled or had a client configured. Stray keys without either (e.g. only a
|
|
549
|
+
// redirect URL) never surfaced an app and are just cleaned up.
|
|
550
|
+
let visible = !!(v('Enabled') || v('Client') || v('ClientId'));
|
|
551
|
+
|
|
552
|
+
let exists = await this.redis.hexists(this.getDataKey(), `${legacyKey}:data`);
|
|
553
|
+
|
|
554
|
+
if (visible && !exists) {
|
|
555
|
+
let entry = {
|
|
556
|
+
provider: legacyKey,
|
|
557
|
+
// legacy apps never separated IMAP and API access; they always used IMAP scopes
|
|
558
|
+
baseScopes: 'imap',
|
|
559
|
+
description: 'Migrated from the deprecated settings-based OAuth2 configuration',
|
|
560
|
+
enabled: !!v('Enabled'),
|
|
561
|
+
extraScopes: normalizeScopes(v('ExtraScopes')),
|
|
562
|
+
skipScopes: normalizeScopes(v('SkipScopes'))
|
|
563
|
+
};
|
|
546
564
|
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
if (visible && !exists) {
|
|
555
|
-
let entry = {
|
|
556
|
-
provider: legacyKey,
|
|
557
|
-
// legacy apps never separated IMAP and API access; they always used IMAP scopes
|
|
558
|
-
baseScopes: 'imap',
|
|
559
|
-
description: 'Migrated from the deprecated settings-based OAuth2 configuration',
|
|
560
|
-
enabled: !!v('Enabled'),
|
|
561
|
-
extraScopes: normalizeScopes(v('ExtraScopes')),
|
|
562
|
-
skipScopes: normalizeScopes(v('SkipScopes'))
|
|
563
|
-
};
|
|
564
|
-
|
|
565
|
-
switch (legacyKey) {
|
|
566
|
-
case 'gmail':
|
|
567
|
-
entry.name = 'Gmail';
|
|
568
|
-
entry.clientId = v('ClientId');
|
|
569
|
-
entry.clientSecret = v('ClientSecret');
|
|
570
|
-
entry.redirectUrl = v('RedirectUrl');
|
|
571
|
-
break;
|
|
572
|
-
|
|
573
|
-
case 'gmailService':
|
|
574
|
-
entry.name = 'Gmail service';
|
|
575
|
-
entry.authMethod = normalizeAuthMethod(v('AuthMethod'));
|
|
576
|
-
entry.serviceClient = v('Client');
|
|
577
|
-
entry.serviceKey = v('Key');
|
|
578
|
-
entry.externalAccount = v('ExternalAccount');
|
|
579
|
-
// service apps are always treated as enabled
|
|
580
|
-
entry.enabled = true;
|
|
581
|
-
break;
|
|
582
|
-
|
|
583
|
-
case 'outlook':
|
|
584
|
-
entry.name = 'Outlook (delegated)';
|
|
585
|
-
entry.clientId = v('ClientId');
|
|
586
|
-
entry.clientSecret = v('ClientSecret');
|
|
587
|
-
entry.redirectUrl = v('RedirectUrl');
|
|
588
|
-
entry.authority = v('Authority');
|
|
589
|
-
// legacy config predates sovereign cloud support
|
|
590
|
-
entry.cloud = 'global';
|
|
591
|
-
break;
|
|
592
|
-
|
|
593
|
-
case 'mailRu':
|
|
594
|
-
entry.name = 'Mail.ru';
|
|
595
|
-
entry.clientId = v('ClientId');
|
|
596
|
-
entry.clientSecret = v('ClientSecret');
|
|
597
|
-
entry.redirectUrl = v('RedirectUrl');
|
|
598
|
-
break;
|
|
599
|
-
}
|
|
565
|
+
switch (legacyKey) {
|
|
566
|
+
case 'gmail':
|
|
567
|
+
entry.name = 'Gmail';
|
|
568
|
+
entry.clientId = v('ClientId');
|
|
569
|
+
entry.clientSecret = v('ClientSecret');
|
|
570
|
+
entry.redirectUrl = v('RedirectUrl');
|
|
571
|
+
break;
|
|
600
572
|
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
573
|
+
case 'gmailService':
|
|
574
|
+
entry.name = 'Gmail service';
|
|
575
|
+
entry.authMethod = normalizeAuthMethod(v('AuthMethod'));
|
|
576
|
+
entry.serviceClient = v('Client');
|
|
577
|
+
entry.serviceKey = v('Key');
|
|
578
|
+
entry.externalAccount = v('ExternalAccount');
|
|
579
|
+
// service apps are always treated as enabled
|
|
580
|
+
entry.enabled = true;
|
|
581
|
+
break;
|
|
608
582
|
|
|
609
|
-
|
|
610
|
-
|
|
583
|
+
case 'outlook':
|
|
584
|
+
entry.name = 'Outlook (delegated)';
|
|
585
|
+
entry.clientId = v('ClientId');
|
|
586
|
+
entry.clientSecret = v('ClientSecret');
|
|
587
|
+
entry.redirectUrl = v('RedirectUrl');
|
|
588
|
+
entry.authority = v('Authority');
|
|
589
|
+
// legacy config predates sovereign cloud support
|
|
590
|
+
entry.cloud = 'global';
|
|
591
|
+
break;
|
|
611
592
|
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
593
|
+
case 'mailRu':
|
|
594
|
+
entry.name = 'Mail.ru';
|
|
595
|
+
entry.clientId = v('ClientId');
|
|
596
|
+
entry.clientSecret = v('ClientSecret');
|
|
597
|
+
entry.redirectUrl = v('RedirectUrl');
|
|
598
|
+
break;
|
|
599
|
+
}
|
|
615
600
|
|
|
616
|
-
|
|
617
|
-
|
|
601
|
+
// Absent legacy keys read as nulls; drop them so the stored record looks like a
|
|
602
|
+
// regular app entry (joi does the equivalent stripping for created apps)
|
|
603
|
+
for (let key of Object.keys(entry)) {
|
|
604
|
+
if (entry[key] === null || typeof entry[key] === 'undefined' || entry[key] === '') {
|
|
605
|
+
delete entry[key];
|
|
606
|
+
}
|
|
618
607
|
}
|
|
619
608
|
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
609
|
+
// create() owns the record shape: it encrypts secret fields and stamps `created`
|
|
610
|
+
await this.create(entry, { id: legacyKey });
|
|
611
|
+
|
|
612
|
+
if (v('AuthFlag')) {
|
|
613
|
+
await this.setMeta(legacyKey, { authFlag: v('AuthFlag') });
|
|
625
614
|
}
|
|
626
615
|
|
|
627
|
-
|
|
616
|
+
migrated.push(legacyKey);
|
|
617
|
+
logger.info({ msg: 'Migrated legacy OAuth2 app to the app registry', app: legacyKey, enabled: entry.enabled });
|
|
628
618
|
}
|
|
629
619
|
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
let backfillReq = this.redis.multi();
|
|
637
|
-
let backfillCount = 0;
|
|
638
|
-
|
|
639
|
-
// read account data in pipelined chunks; large legacy installs can hold tens of
|
|
640
|
-
// thousands of accounts and sequential reads would stall startup
|
|
641
|
-
const CHUNK_SIZE = 500;
|
|
642
|
-
for (let i = 0; i < accounts.length; i += CHUNK_SIZE) {
|
|
643
|
-
let chunk = accounts.slice(i, i + CHUNK_SIZE);
|
|
644
|
-
let readReq = this.redis.pipeline();
|
|
645
|
-
for (let account of chunk) {
|
|
646
|
-
readReq = readReq.hget(`${REDIS_PREFIX}iad:${account}`, 'oauth2');
|
|
647
|
-
}
|
|
648
|
-
let rows = await readReq.exec();
|
|
620
|
+
if (visible) {
|
|
621
|
+
// Whether the record was created now or by an earlier interrupted run: as long
|
|
622
|
+
// as the source keys are still around the backfill below has not been confirmed
|
|
623
|
+
// done, and repeating it is a no-op
|
|
624
|
+
backfillable.push(legacyKey);
|
|
625
|
+
}
|
|
649
626
|
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
627
|
+
clearable.push(legacyKey);
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// Backfill the per-app account membership sets that the legacy code never maintained,
|
|
631
|
+
// so account counts and app deletion safety checks see the existing accounts. The
|
|
632
|
+
// per-user binding hash (oapp:h:*) is left to repopulate on the next account update.
|
|
633
|
+
if (backfillable.length) {
|
|
634
|
+
let backfillableSet = new Set(backfillable);
|
|
635
|
+
let accounts = await this.redis.smembers(`${REDIS_PREFIX}ia:accounts`);
|
|
636
|
+
let backfillReq = this.redis.multi();
|
|
637
|
+
let backfillCount = 0;
|
|
638
|
+
|
|
639
|
+
// read account data in pipelined chunks; large legacy installs can hold tens of
|
|
640
|
+
// thousands of accounts and sequential reads would stall startup
|
|
641
|
+
const CHUNK_SIZE = 500;
|
|
642
|
+
for (let i = 0; i < accounts.length; i += CHUNK_SIZE) {
|
|
643
|
+
let chunk = accounts.slice(i, i + CHUNK_SIZE);
|
|
644
|
+
let readReq = this.redis.pipeline();
|
|
645
|
+
for (let account of chunk) {
|
|
646
|
+
readReq = readReq.hget(`${REDIS_PREFIX}iad:${account}`, 'oauth2');
|
|
666
647
|
}
|
|
648
|
+
let rows = await readReq.exec();
|
|
667
649
|
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
650
|
+
for (let j = 0; j < chunk.length; j++) {
|
|
651
|
+
let [err, oauth2Json] = rows[j];
|
|
652
|
+
if (err || !oauth2Json) {
|
|
653
|
+
continue;
|
|
654
|
+
}
|
|
655
|
+
let oauth2Data;
|
|
656
|
+
try {
|
|
657
|
+
oauth2Data = JSON.parse(oauth2Json);
|
|
658
|
+
} catch (parseErr) {
|
|
659
|
+
continue;
|
|
660
|
+
}
|
|
661
|
+
if (oauth2Data && oauth2Data.provider && backfillableSet.has(oauth2Data.provider)) {
|
|
662
|
+
backfillReq = backfillReq.sadd(`${REDIS_PREFIX}oapp:a:${oauth2Data.provider}`, chunk[j]);
|
|
663
|
+
backfillCount++;
|
|
664
|
+
}
|
|
671
665
|
}
|
|
672
666
|
}
|
|
673
667
|
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
668
|
+
if (backfillCount) {
|
|
669
|
+
await backfillReq.exec();
|
|
670
|
+
logger.info({ msg: 'Linked existing accounts to migrated OAuth2 apps', accounts: backfillCount });
|
|
677
671
|
}
|
|
672
|
+
}
|
|
678
673
|
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
674
|
+
// The copy is complete, drop the source settings keys (no-op when unset)
|
|
675
|
+
if (clearable.length) {
|
|
676
|
+
await this.redis.hdel(this.getSettingsKey(), ...clearable.flatMap(legacyKey => LEGACY_FIELDS.map(field => `${legacyKey}${field}`)));
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
let removedOrphans = await this.redis.hdel(this.getSettingsKey(), ...LEGACY_ORPHAN_KEYS);
|
|
680
|
+
if (removedOrphans) {
|
|
681
|
+
logger.info({ msg: 'Removed orphaned legacy OAuth2 service settings', keys: LEGACY_ORPHAN_KEYS });
|
|
685
682
|
}
|
|
686
683
|
|
|
687
684
|
return migrated;
|
|
@@ -892,83 +889,81 @@ class OAuth2AppsHandler {
|
|
|
892
889
|
// deletion gate below (pubSubTopic || pubSubSubscription) so an app that only has a
|
|
893
890
|
// subscription recorded is still locked before its resources are deleted.
|
|
894
891
|
let needsPubSubLock = appData.pubSubTopic || appData.pubSubSubscription || appData.baseScopes === 'pubsub';
|
|
895
|
-
|
|
892
|
+
if (!needsPubSubLock) {
|
|
893
|
+
return await this.removeApp(id, appData);
|
|
894
|
+
}
|
|
896
895
|
|
|
897
|
-
|
|
898
|
-
|
|
896
|
+
let lockKey = ['oauth', 'pubsub', appData.id].join(':');
|
|
897
|
+
return await runLocked(
|
|
898
|
+
getSharedLock(),
|
|
899
|
+
lockKey,
|
|
900
|
+
{ ttl: 5 * 60 * 1000, wait: 2 * 60 * 1000 },
|
|
901
|
+
async () => {
|
|
902
|
+
// Re-read under the lock so the ownership-flag deletion decision below acts on the
|
|
903
|
+
// current record, not the snapshot taken before the lock - a concurrent ensurePubsub /
|
|
904
|
+
// recovery run may have adopted or created a resource in the meantime. Keep the pre-lock
|
|
905
|
+
// snapshot if the app was deleted while waiting, so best-effort GCP cleanup still runs.
|
|
906
|
+
let lockedData = await this.get(id);
|
|
907
|
+
return await this.removeApp(id, lockedData || appData);
|
|
908
|
+
},
|
|
909
|
+
rethrowUnavailableLock(logger, 'Failed to get lock for pubsub app deletion', { lockKey })
|
|
910
|
+
);
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
/**
|
|
914
|
+
* Removes an app's Pub/Sub resources (the ones EmailEngine created) and its records, see del()
|
|
915
|
+
* @param {string} id - App ID
|
|
916
|
+
* @param {Object} appData - The app, as read under the Pub/Sub lock when one is needed
|
|
917
|
+
* @returns {Promise<Object>} `{ id, deleted, accounts }`
|
|
918
|
+
*/
|
|
919
|
+
async removeApp(id, appData) {
|
|
920
|
+
if (appData.pubSubTopic || appData.pubSubSubscription) {
|
|
921
|
+
// try to delete the Pub/Sub resources EmailEngine created (deleteTopic skips any
|
|
922
|
+
// resource marked unmanaged, i.e. adopted from a pre-existing GCP setup)
|
|
899
923
|
try {
|
|
900
|
-
|
|
901
|
-
if (!delLock.success) {
|
|
902
|
-
throw new Error('Failed to get lock for pubsub app deletion');
|
|
903
|
-
}
|
|
924
|
+
await this.deleteTopic(appData);
|
|
904
925
|
} catch (err) {
|
|
905
|
-
logger.error({
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
// snapshot if the app was deleted while waiting, so best-effort GCP cleanup still runs.
|
|
913
|
-
let lockedData = await this.get(id);
|
|
914
|
-
if (lockedData) {
|
|
915
|
-
appData = lockedData;
|
|
926
|
+
logger.error({
|
|
927
|
+
msg: 'Failed to delete existing pubsub topic',
|
|
928
|
+
app: appData.id,
|
|
929
|
+
topic: appData.pubSubTopic,
|
|
930
|
+
subscription: appData.pubSubSubscription,
|
|
931
|
+
err
|
|
932
|
+
});
|
|
916
933
|
}
|
|
917
934
|
}
|
|
918
935
|
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
err
|
|
932
|
-
});
|
|
933
|
-
}
|
|
934
|
-
}
|
|
935
|
-
|
|
936
|
-
let pipeline = this.redis
|
|
937
|
-
.multi()
|
|
938
|
-
.srem(this.getIndexKey(), id)
|
|
939
|
-
.hdel(this.getDataKey(), [`${id}:data`, `${id}:meta`])
|
|
940
|
-
.scard(`${REDIS_PREFIX}oapp:a:${id}`)
|
|
941
|
-
.del(`${REDIS_PREFIX}oapp:a:${id}`)
|
|
942
|
-
.del(`${REDIS_PREFIX}oapp:h:${id}`)
|
|
943
|
-
.srem(this.getSubscribersKey(), id);
|
|
944
|
-
|
|
945
|
-
if (appData.pubSubApp) {
|
|
946
|
-
pipeline = pipeline.srem(this.getPubsubAppKey(appData.pubSubApp), id);
|
|
947
|
-
}
|
|
936
|
+
let pipeline = this.redis
|
|
937
|
+
.multi()
|
|
938
|
+
.srem(this.getIndexKey(), id)
|
|
939
|
+
.hdel(this.getDataKey(), [`${id}:data`, `${id}:meta`])
|
|
940
|
+
.scard(`${REDIS_PREFIX}oapp:a:${id}`)
|
|
941
|
+
.del(`${REDIS_PREFIX}oapp:a:${id}`)
|
|
942
|
+
.del(`${REDIS_PREFIX}oapp:h:${id}`)
|
|
943
|
+
.srem(this.getSubscribersKey(), id);
|
|
944
|
+
|
|
945
|
+
if (appData.pubSubApp) {
|
|
946
|
+
pipeline = pipeline.srem(this.getPubsubAppKey(appData.pubSubApp), id);
|
|
947
|
+
}
|
|
948
948
|
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
949
|
+
if (appData.baseScopes === 'pubsub') {
|
|
950
|
+
pipeline = pipeline.del(this.getPubsubAppKey(id));
|
|
951
|
+
}
|
|
952
952
|
|
|
953
|
-
|
|
953
|
+
let deleteResult = await pipeline.exec();
|
|
954
954
|
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
955
|
+
let errorEntry = deleteResult.find(entry => entry && entry[0]);
|
|
956
|
+
if (errorEntry) {
|
|
957
|
+
throw errorEntry[0];
|
|
958
|
+
}
|
|
959
959
|
|
|
960
|
-
|
|
960
|
+
let deletedDocs = ((deleteResult[0] && deleteResult[0][1]) || 0) + ((deleteResult[1] && deleteResult[1][1]) || 0);
|
|
961
961
|
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
} finally {
|
|
968
|
-
if (delLock?.success) {
|
|
969
|
-
await lock.releaseLock(delLock);
|
|
970
|
-
}
|
|
971
|
-
}
|
|
962
|
+
return {
|
|
963
|
+
id,
|
|
964
|
+
deleted: deletedDocs >= 2,
|
|
965
|
+
accounts: Number(deleteResult[2] && deleteResult[2][1]) || 0
|
|
966
|
+
};
|
|
972
967
|
}
|
|
973
968
|
|
|
974
969
|
// Auth-failure flags of every registered app, for the site-wide admin alert (see the view
|
|
@@ -1234,347 +1229,402 @@ class OAuth2AppsHandler {
|
|
|
1234
1229
|
desiredExpirationPolicy = null;
|
|
1235
1230
|
}
|
|
1236
1231
|
|
|
1237
|
-
let results = {};
|
|
1238
|
-
let ttlPatchFailed = null;
|
|
1239
|
-
|
|
1240
1232
|
if (!project) {
|
|
1241
1233
|
logger.warn({ msg: 'googleProjectId is required for Pub/Sub setup', app: appData.id });
|
|
1242
|
-
return
|
|
1234
|
+
return {};
|
|
1243
1235
|
}
|
|
1244
1236
|
|
|
1245
1237
|
let topicName = `projects/${project}/topics/${topic}`;
|
|
1246
1238
|
let subscriptionName = `projects/${project}/subscriptions/${subscription}`;
|
|
1247
1239
|
|
|
1248
|
-
|
|
1249
|
-
let
|
|
1240
|
+
// Acquire per-app lock to prevent concurrent ensurePubsub races (e.g., user update + background recovery)
|
|
1241
|
+
let lockKey = ['oauth', 'pubsub', appData.id].join(':');
|
|
1242
|
+
return await runLocked(
|
|
1243
|
+
getSharedLock(),
|
|
1244
|
+
lockKey,
|
|
1245
|
+
{ ttl: 5 * 60 * 1000, wait: 2 * 60 * 1000 },
|
|
1246
|
+
() => this.ensurePubsubLocked({ appData, topicName, subscriptionName, desiredExpirationPolicy }),
|
|
1247
|
+
rethrowUnavailableLock(logger, 'Failed to get ensurePubsub lock', { app: appData.id, lockKey })
|
|
1248
|
+
);
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
// ensurePubsub() under the per-app Pub/Sub lock
|
|
1252
|
+
async ensurePubsubLocked({ appData, topicName, subscriptionName, desiredExpirationPolicy }) {
|
|
1253
|
+
const topicUrl = `https://pubsub.googleapis.com/v1/${topicName}`;
|
|
1254
|
+
const subscriptionUrl = `https://pubsub.googleapis.com/v1/${subscriptionName}`;
|
|
1250
1255
|
|
|
1251
1256
|
const member = 'serviceAccount:gmail-api-push@system.gserviceaccount.com';
|
|
1252
1257
|
const role = 'roles/pubsub.publisher';
|
|
1253
1258
|
|
|
1254
|
-
|
|
1255
|
-
let
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1259
|
+
let results = {};
|
|
1260
|
+
let ttlPatchFailed = null;
|
|
1261
|
+
|
|
1262
|
+
// Re-read inside the lock so the "persist only if absent" guards below act on the
|
|
1263
|
+
// current state, not the caller's pre-lock snapshot (which can be stale after a
|
|
1264
|
+
// concurrent ensurePubsub run). Falls back to the passed-in data if the app was
|
|
1265
|
+
// deleted while waiting for the lock (preserves the prior proceed-anyway behavior).
|
|
1266
|
+
let current = (await this.get(appData.id)) || appData;
|
|
1267
|
+
|
|
1268
|
+
// Record a marker for a Pub/Sub resource that already existed in GCP (adopted, not
|
|
1269
|
+
// created by us): mark it unmanaged so deletion never removes it, and surface it in
|
|
1270
|
+
// results on first adoption so the create/update route restarts the pull worker. The
|
|
1271
|
+
// !current guard keeps re-runs no-ops (no redundant writes or restarts).
|
|
1272
|
+
const adoptExistingResource = async (key, value) => {
|
|
1273
|
+
if (!current[key]) {
|
|
1274
|
+
await this.update(appData.id, { [key]: value, [`${key}Managed`]: false }, { partial: true });
|
|
1275
|
+
results[key] = value;
|
|
1268
1276
|
}
|
|
1269
|
-
|
|
1270
|
-
}
|
|
1277
|
+
};
|
|
1271
1278
|
|
|
1272
|
-
|
|
1273
|
-
// Re-read inside the lock so the "persist only if absent" guards below act on the
|
|
1274
|
-
// current state, not the caller's pre-lock snapshot (which can be stale after a
|
|
1275
|
-
// concurrent ensurePubsub run). Falls back to the passed-in data if the app was
|
|
1276
|
-
// deleted while waiting for the lock (preserves the prior proceed-anyway behavior).
|
|
1277
|
-
let current = (await this.get(appData.id)) || appData;
|
|
1278
|
-
|
|
1279
|
-
// Record a marker for a Pub/Sub resource that already existed in GCP (adopted, not
|
|
1280
|
-
// created by us): mark it unmanaged so deletion never removes it, and surface it in
|
|
1281
|
-
// results on first adoption so the create/update route restarts the pull worker. The
|
|
1282
|
-
// !current guard keeps re-runs no-ops (no redundant writes or restarts).
|
|
1283
|
-
const adoptExistingResource = async (key, value) => {
|
|
1284
|
-
if (!current[key]) {
|
|
1285
|
-
await this.update(appData.id, { [key]: value, [`${key}Managed`]: false }, { partial: true });
|
|
1286
|
-
results[key] = value;
|
|
1287
|
-
}
|
|
1288
|
-
};
|
|
1279
|
+
let client = await this.getClient(appData.id);
|
|
1289
1280
|
|
|
1290
|
-
|
|
1281
|
+
// Step 1. Get access token for service client
|
|
1282
|
+
let accessToken = await this.getServiceAccessToken(appData, client);
|
|
1283
|
+
if (!accessToken) {
|
|
1284
|
+
throw new Error('Failed to get access token');
|
|
1285
|
+
}
|
|
1291
1286
|
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
if
|
|
1295
|
-
|
|
1287
|
+
// Step 2. Ensure topic
|
|
1288
|
+
try {
|
|
1289
|
+
// fails if topic does not exist
|
|
1290
|
+
await client.request(accessToken, topicUrl, 'GET');
|
|
1291
|
+
logger.debug({ msg: 'Topic already exists', app: appData.id, topic: topicName });
|
|
1292
|
+
/*
|
|
1293
|
+
{name: 'projects/...'}
|
|
1294
|
+
*/
|
|
1295
|
+
|
|
1296
|
+
// Adopt a pre-existing topic so the Gmail watch can arm (kept unmanaged - we did not create it).
|
|
1297
|
+
await adoptExistingResource('pubSubTopic', topicName);
|
|
1298
|
+
} catch (err) {
|
|
1299
|
+
if (TRANSIENT_NETWORK_CODES.has(err.code)) {
|
|
1300
|
+
logger.warn({ msg: 'Network error checking Pub/Sub topic', app: appData.id, code: err.code });
|
|
1301
|
+
throw err;
|
|
1296
1302
|
}
|
|
1303
|
+
switch (err?.oauthRequest?.response?.error?.code) {
|
|
1304
|
+
case 403:
|
|
1305
|
+
// no permissions
|
|
1306
|
+
if (/Cloud Pub\/Sub API has not been used in project/.test(err?.oauthRequest?.response?.error?.message)) {
|
|
1307
|
+
this.setMetaFireAndForget(appData.id, {
|
|
1308
|
+
authFlag: {
|
|
1309
|
+
message:
|
|
1310
|
+
'Enable the Cloud Pub/Sub API for your project before using the service client. Check the server response below for details.',
|
|
1311
|
+
description: err?.oauthRequest?.response?.error?.message
|
|
1312
|
+
},
|
|
1313
|
+
ttlWarning: null
|
|
1314
|
+
});
|
|
1315
|
+
} else {
|
|
1316
|
+
this.setMetaFireAndForget(appData.id, {
|
|
1317
|
+
authFlag: { message: PUBSUB_PERM_MANAGE },
|
|
1318
|
+
ttlWarning: null
|
|
1319
|
+
});
|
|
1320
|
+
}
|
|
1297
1321
|
|
|
1298
|
-
// Step 2. Ensure topic
|
|
1299
|
-
try {
|
|
1300
|
-
// fails if topic does not exist
|
|
1301
|
-
await client.request(accessToken, topicUrl, 'GET');
|
|
1302
|
-
logger.debug({ msg: 'Topic already exists', app: appData.id, topic: topicName });
|
|
1303
|
-
/*
|
|
1304
|
-
{name: 'projects/...'}
|
|
1305
|
-
*/
|
|
1306
|
-
|
|
1307
|
-
// Adopt a pre-existing topic so the Gmail watch can arm (kept unmanaged - we did not create it).
|
|
1308
|
-
await adoptExistingResource('pubSubTopic', topicName);
|
|
1309
|
-
} catch (err) {
|
|
1310
|
-
if (TRANSIENT_NETWORK_CODES.has(err.code)) {
|
|
1311
|
-
logger.warn({ msg: 'Network error checking Pub/Sub topic', app: appData.id, code: err.code });
|
|
1312
1322
|
throw err;
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
},
|
|
1324
|
-
ttlWarning: null
|
|
1325
|
-
});
|
|
1326
|
-
} else {
|
|
1327
|
-
this.setMetaFireAndForget(appData.id, {
|
|
1328
|
-
authFlag: { message: PUBSUB_PERM_MANAGE },
|
|
1329
|
-
ttlWarning: null
|
|
1330
|
-
});
|
|
1323
|
+
case 404: {
|
|
1324
|
+
// does not exist
|
|
1325
|
+
logger.info({ msg: 'Topic does not exist', app: appData.id, topic: topicName });
|
|
1326
|
+
try {
|
|
1327
|
+
let topicCreateRes = await client.request(accessToken, topicUrl, 'PUT', Buffer.alloc(0));
|
|
1328
|
+
/*
|
|
1329
|
+
{name: 'projects/...'}
|
|
1330
|
+
*/
|
|
1331
|
+
if (!topicCreateRes?.name) {
|
|
1332
|
+
throw new Error('Topic was not created', { cause: err });
|
|
1331
1333
|
}
|
|
1332
1334
|
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
{
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
logger.
|
|
1335
|
+
await this.update(
|
|
1336
|
+
appData.id,
|
|
1337
|
+
{
|
|
1338
|
+
pubSubTopic: topicName,
|
|
1339
|
+
// EmailEngine created this topic, so it may delete it on app removal.
|
|
1340
|
+
pubSubTopicManaged: true
|
|
1341
|
+
},
|
|
1342
|
+
{ partial: true }
|
|
1343
|
+
);
|
|
1344
|
+
|
|
1345
|
+
results.pubSubTopic = topicName;
|
|
1346
|
+
} catch (err) {
|
|
1347
|
+
if (TRANSIENT_NETWORK_CODES.has(err.code)) {
|
|
1348
|
+
logger.warn({ msg: 'Network error creating Pub/Sub topic', app: appData.id, code: err.code });
|
|
1349
|
+
throw err;
|
|
1350
|
+
}
|
|
1351
|
+
switch (err?.oauthRequest?.response?.error?.code) {
|
|
1352
|
+
case 403:
|
|
1353
|
+
// no permissions
|
|
1354
|
+
this.setMetaFireAndForget(appData.id, {
|
|
1355
|
+
authFlag: { message: PUBSUB_PERM_MANAGE },
|
|
1356
|
+
ttlWarning: null
|
|
1357
|
+
});
|
|
1358
|
+
throw err;
|
|
1359
|
+
case 409:
|
|
1360
|
+
// already exists (raced) - adopt it; mark unmanaged to be safe against deletion.
|
|
1361
|
+
logger.info({ msg: 'Topic already exists', app: appData.id, topic: topicName });
|
|
1362
|
+
await adoptExistingResource('pubSubTopic', topicName);
|
|
1363
|
+
break;
|
|
1364
|
+
default:
|
|
1360
1365
|
throw err;
|
|
1361
|
-
}
|
|
1362
|
-
switch (err?.oauthRequest?.response?.error?.code) {
|
|
1363
|
-
case 403:
|
|
1364
|
-
// no permissions
|
|
1365
|
-
this.setMetaFireAndForget(appData.id, {
|
|
1366
|
-
authFlag: { message: PUBSUB_PERM_MANAGE },
|
|
1367
|
-
ttlWarning: null
|
|
1368
|
-
});
|
|
1369
|
-
throw err;
|
|
1370
|
-
case 409:
|
|
1371
|
-
// already exists (raced) - adopt it; mark unmanaged to be safe against deletion.
|
|
1372
|
-
logger.info({ msg: 'Topic already exists', app: appData.id, topic: topicName });
|
|
1373
|
-
await adoptExistingResource('pubSubTopic', topicName);
|
|
1374
|
-
break;
|
|
1375
|
-
default:
|
|
1376
|
-
throw err;
|
|
1377
|
-
}
|
|
1378
1366
|
}
|
|
1379
|
-
break;
|
|
1380
1367
|
}
|
|
1381
|
-
|
|
1382
|
-
throw err;
|
|
1368
|
+
break;
|
|
1383
1369
|
}
|
|
1370
|
+
default:
|
|
1371
|
+
throw err;
|
|
1384
1372
|
}
|
|
1373
|
+
}
|
|
1385
1374
|
|
|
1386
|
-
|
|
1375
|
+
// Step 3. Set up subscriber
|
|
1387
1376
|
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
}
|
|
1377
|
+
try {
|
|
1378
|
+
// fails if topic does not exist
|
|
1379
|
+
let subscriptionData = await client.request(accessToken, subscriptionUrl, 'GET');
|
|
1380
|
+
logger.debug({ msg: 'Subscription already exists', app: appData.id, subscription: subscriptionName });
|
|
1381
|
+
/*
|
|
1382
|
+
{name: 'projects/...'}
|
|
1383
|
+
*/
|
|
1384
|
+
|
|
1385
|
+
// Adopt a pre-existing subscription so the pull worker recognizes it (also stops the
|
|
1386
|
+
// recovery loop in lib/oauth/pubsub/google.js); kept unmanaged - we did not create it.
|
|
1387
|
+
await adoptExistingResource('pubSubSubscription', subscriptionName);
|
|
1388
|
+
|
|
1389
|
+
// Patch existing subscription's expiration policy if it differs from desired
|
|
1390
|
+
// When no explicit TTL is configured, use Google's default (31 days) for comparison
|
|
1391
|
+
let effectivePolicy = desiredExpirationPolicy ?? { ttl: GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL };
|
|
1392
|
+
let currentTtl = subscriptionData?.expirationPolicy?.ttl || null;
|
|
1393
|
+
let desiredTtl = effectivePolicy.ttl || null;
|
|
1394
|
+
|
|
1395
|
+
// Adopted (pre-existing, unmanaged) subscriptions belong to the customer - never
|
|
1396
|
+
// rewrite their lifecycle policy. A subscription is ours to manage only when it is
|
|
1397
|
+
// already recorded as managed (true) or predates ownership tracking (undefined);
|
|
1398
|
+
// a freshly adopted one (marker absent in the pre-lock snapshot) or an explicit
|
|
1399
|
+
// `false` flag is hands-off.
|
|
1400
|
+
let subscriptionManagedByUs = !!current.pubSubSubscription && current.pubSubSubscriptionManaged !== false;
|
|
1401
|
+
|
|
1402
|
+
if (!subscriptionManagedByUs && desiredExpirationPolicy !== null) {
|
|
1403
|
+
// Do not mutate the customer's subscription, but warn when an explicitly
|
|
1404
|
+
// configured expiration is longer than theirs: the subscription may expire on
|
|
1405
|
+
// its own and silently disable Gmail push.
|
|
1406
|
+
let toSeconds = ttl => {
|
|
1407
|
+
let n = ttl ? parseInt(ttl, 10) : NaN;
|
|
1408
|
+
return Number.isFinite(n) ? n : null;
|
|
1409
|
+
};
|
|
1410
|
+
let currentSeconds = toSeconds(currentTtl);
|
|
1411
|
+
let desiredSeconds = toSeconds(desiredTtl);
|
|
1412
|
+
// desiredSeconds === null means EmailEngine wants an indefinite subscription
|
|
1413
|
+
if (currentSeconds !== null && (desiredSeconds === null || currentSeconds < desiredSeconds)) {
|
|
1414
|
+
logger.warn({
|
|
1415
|
+
msg: 'Adopted Pub/Sub subscription expires sooner than the configured expiration; leaving it unchanged',
|
|
1416
|
+
app: appData.id,
|
|
1417
|
+
subscription: subscriptionName,
|
|
1418
|
+
currentTtl,
|
|
1419
|
+
desiredTtl
|
|
1420
|
+
});
|
|
1421
|
+
}
|
|
1422
|
+
} else if (subscriptionManagedByUs && currentTtl !== desiredTtl) {
|
|
1423
|
+
try {
|
|
1424
|
+
await client.request(accessToken, subscriptionUrl, 'PATCH', {
|
|
1425
|
+
subscription: { expirationPolicy: effectivePolicy },
|
|
1426
|
+
updateMask: 'expirationPolicy'
|
|
1427
|
+
});
|
|
1428
|
+
logger.info({
|
|
1429
|
+
msg: 'Updated expiration policy on subscription',
|
|
1430
|
+
app: appData.id,
|
|
1431
|
+
subscription: subscriptionName,
|
|
1432
|
+
desiredTtl
|
|
1433
|
+
});
|
|
1434
|
+
// Update stored TTL after successful patch
|
|
1435
|
+
subscriptionData.expirationPolicy = effectivePolicy;
|
|
1436
|
+
} catch (patchErr) {
|
|
1437
|
+
ttlPatchFailed = patchErr;
|
|
1438
|
+
logger.warn({
|
|
1439
|
+
msg: 'Failed to update expiration policy on subscription',
|
|
1440
|
+
app: appData.id,
|
|
1441
|
+
subscription: subscriptionName,
|
|
1442
|
+
err: patchErr
|
|
1443
|
+
});
|
|
1456
1444
|
}
|
|
1445
|
+
}
|
|
1457
1446
|
|
|
1458
|
-
|
|
1459
|
-
|
|
1460
|
-
|
|
1461
|
-
|
|
1462
|
-
|
|
1463
|
-
|
|
1464
|
-
|
|
1447
|
+
// Store current expiration info in meta
|
|
1448
|
+
await this.setMeta(appData.id, {
|
|
1449
|
+
subscriptionExpiration: subscriptionData?.expirationPolicy?.ttl || null
|
|
1450
|
+
});
|
|
1451
|
+
} catch (err) {
|
|
1452
|
+
if (TRANSIENT_NETWORK_CODES.has(err.code)) {
|
|
1453
|
+
logger.warn({ msg: 'Network error checking Pub/Sub subscription', app: appData.id, code: err.code });
|
|
1454
|
+
throw err;
|
|
1455
|
+
}
|
|
1456
|
+
switch (err?.oauthRequest?.response?.error?.code) {
|
|
1457
|
+
case 403:
|
|
1458
|
+
// no permissions
|
|
1459
|
+
this.setMetaFireAndForget(appData.id, {
|
|
1460
|
+
authFlag: { message: PUBSUB_PERM_VIEW },
|
|
1461
|
+
ttlWarning: null
|
|
1462
|
+
});
|
|
1465
1463
|
throw err;
|
|
1466
|
-
|
|
1467
|
-
|
|
1468
|
-
|
|
1469
|
-
|
|
1470
|
-
|
|
1471
|
-
|
|
1472
|
-
|
|
1473
|
-
}
|
|
1474
|
-
|
|
1475
|
-
|
|
1476
|
-
|
|
1477
|
-
|
|
1478
|
-
|
|
1479
|
-
|
|
1480
|
-
|
|
1481
|
-
|
|
1482
|
-
|
|
1483
|
-
|
|
1484
|
-
|
|
1485
|
-
|
|
1486
|
-
|
|
1487
|
-
|
|
1464
|
+
case 404: {
|
|
1465
|
+
// does not exist
|
|
1466
|
+
logger.info({ msg: 'Subscription does not exist', app: appData.id, subscription: subscriptionName });
|
|
1467
|
+
try {
|
|
1468
|
+
let createPayload = {
|
|
1469
|
+
topic: topicName,
|
|
1470
|
+
ackDeadlineSeconds: GMAIL_PUBSUB_ACK_DEADLINE_SECONDS
|
|
1471
|
+
};
|
|
1472
|
+
if (desiredExpirationPolicy !== null) {
|
|
1473
|
+
createPayload.expirationPolicy = desiredExpirationPolicy;
|
|
1474
|
+
}
|
|
1475
|
+
let subscriptionCreateRes = await client.request(accessToken, subscriptionUrl, 'PUT', createPayload);
|
|
1476
|
+
/*
|
|
1477
|
+
{
|
|
1478
|
+
name: 'projects/webhooks-425411/subscriptions/ee-sub-AAABkE9_uNMAAAAH',
|
|
1479
|
+
topic: 'projects/webhooks-425411/topics/ee-pub-AAABkE9_uNMAAAAH',
|
|
1480
|
+
pushConfig: {},
|
|
1481
|
+
ackDeadlineSeconds: 10,
|
|
1482
|
+
messageRetentionDuration: '604800s',
|
|
1483
|
+
expirationPolicy: { ttl: '2678400s' },
|
|
1484
|
+
state: 'ACTIVE'
|
|
1485
|
+
}
|
|
1486
|
+
*/
|
|
1487
|
+
|
|
1488
|
+
if (!subscriptionCreateRes?.name) {
|
|
1489
|
+
throw new Error('Subscription was not created', { cause: err });
|
|
1490
|
+
}
|
|
1491
|
+
|
|
1492
|
+
await this.update(
|
|
1493
|
+
appData.id,
|
|
1488
1494
|
{
|
|
1489
|
-
|
|
1490
|
-
|
|
1491
|
-
|
|
1492
|
-
|
|
1493
|
-
|
|
1494
|
-
|
|
1495
|
-
|
|
1496
|
-
|
|
1497
|
-
|
|
1498
|
-
|
|
1499
|
-
|
|
1500
|
-
|
|
1501
|
-
|
|
1502
|
-
|
|
1503
|
-
|
|
1504
|
-
|
|
1505
|
-
|
|
1506
|
-
|
|
1507
|
-
|
|
1508
|
-
|
|
1509
|
-
|
|
1510
|
-
{
|
|
1511
|
-
|
|
1512
|
-
|
|
1513
|
-
|
|
1514
|
-
|
|
1515
|
-
|
|
1516
|
-
|
|
1517
|
-
|
|
1518
|
-
|
|
1519
|
-
|
|
1520
|
-
|
|
1521
|
-
logger.warn({ msg: 'Network error creating Pub/Sub subscription', app: appData.id, code: err.code });
|
|
1495
|
+
pubSubSubscription: subscriptionName,
|
|
1496
|
+
// EmailEngine created this subscription, so it may delete it on app removal.
|
|
1497
|
+
pubSubSubscriptionManaged: true
|
|
1498
|
+
},
|
|
1499
|
+
{ partial: true }
|
|
1500
|
+
);
|
|
1501
|
+
|
|
1502
|
+
results.pubSubSubscription = subscriptionName;
|
|
1503
|
+
|
|
1504
|
+
// Store expiration info from the created subscription
|
|
1505
|
+
await this.setMeta(appData.id, {
|
|
1506
|
+
subscriptionExpiration: subscriptionCreateRes?.expirationPolicy?.ttl || null
|
|
1507
|
+
});
|
|
1508
|
+
} catch (err) {
|
|
1509
|
+
if (TRANSIENT_NETWORK_CODES.has(err.code)) {
|
|
1510
|
+
logger.warn({ msg: 'Network error creating Pub/Sub subscription', app: appData.id, code: err.code });
|
|
1511
|
+
throw err;
|
|
1512
|
+
}
|
|
1513
|
+
switch (err?.oauthRequest?.response?.error?.code) {
|
|
1514
|
+
case 403:
|
|
1515
|
+
// no permissions
|
|
1516
|
+
this.setMetaFireAndForget(appData.id, {
|
|
1517
|
+
authFlag: { message: PUBSUB_PERM_MANAGE },
|
|
1518
|
+
ttlWarning: null
|
|
1519
|
+
});
|
|
1520
|
+
throw err;
|
|
1521
|
+
case 409:
|
|
1522
|
+
// already exists (raced) - adopt it; mark unmanaged to be safe against deletion.
|
|
1523
|
+
logger.info({ msg: 'Subscription already exists', app: appData.id, subscription: subscriptionName });
|
|
1524
|
+
await adoptExistingResource('pubSubSubscription', subscriptionName);
|
|
1525
|
+
break;
|
|
1526
|
+
default:
|
|
1522
1527
|
throw err;
|
|
1523
|
-
}
|
|
1524
|
-
switch (err?.oauthRequest?.response?.error?.code) {
|
|
1525
|
-
case 403:
|
|
1526
|
-
// no permissions
|
|
1527
|
-
this.setMetaFireAndForget(appData.id, {
|
|
1528
|
-
authFlag: { message: PUBSUB_PERM_MANAGE },
|
|
1529
|
-
ttlWarning: null
|
|
1530
|
-
});
|
|
1531
|
-
throw err;
|
|
1532
|
-
case 409:
|
|
1533
|
-
// already exists (raced) - adopt it; mark unmanaged to be safe against deletion.
|
|
1534
|
-
logger.info({ msg: 'Subscription already exists', app: appData.id, subscription: subscriptionName });
|
|
1535
|
-
await adoptExistingResource('pubSubSubscription', subscriptionName);
|
|
1536
|
-
break;
|
|
1537
|
-
default:
|
|
1538
|
-
throw err;
|
|
1539
|
-
}
|
|
1540
1528
|
}
|
|
1541
|
-
break;
|
|
1542
1529
|
}
|
|
1543
|
-
|
|
1544
|
-
throw err;
|
|
1530
|
+
break;
|
|
1545
1531
|
}
|
|
1532
|
+
default:
|
|
1533
|
+
throw err;
|
|
1546
1534
|
}
|
|
1535
|
+
}
|
|
1547
1536
|
|
|
1548
|
-
|
|
1537
|
+
// Step 4. Grant access to Gmail publisher
|
|
1549
1538
|
|
|
1550
|
-
|
|
1551
|
-
|
|
1539
|
+
let existingPolicy;
|
|
1540
|
+
let getIamPolicyRes;
|
|
1541
|
+
try {
|
|
1542
|
+
// Check for an existing policy grant
|
|
1543
|
+
getIamPolicyRes = await client.request(accessToken, `${topicUrl}:getIamPolicy`, 'GET');
|
|
1544
|
+
existingPolicy = getIamPolicyRes?.bindings?.find(binding => binding?.role === role && binding?.members?.includes(member));
|
|
1545
|
+
/*
|
|
1546
|
+
{
|
|
1547
|
+
version: 1,
|
|
1548
|
+
etag: 'BwYbtWmb5c0=',
|
|
1549
|
+
bindings: [
|
|
1550
|
+
{
|
|
1551
|
+
role: 'roles/pubsub.publisher',
|
|
1552
|
+
members: [ 'serviceAccount:gmail-api-push@system.gserviceaccount.com' ]
|
|
1553
|
+
}
|
|
1554
|
+
]
|
|
1555
|
+
}
|
|
1556
|
+
*/
|
|
1557
|
+
} catch (err) {
|
|
1558
|
+
if (TRANSIENT_NETWORK_CODES.has(err.code)) {
|
|
1559
|
+
logger.warn({ msg: 'Network error checking Pub/Sub IAM policy', app: appData.id, code: err.code });
|
|
1560
|
+
throw err;
|
|
1561
|
+
}
|
|
1562
|
+
switch (err?.oauthRequest?.response?.error?.code) {
|
|
1563
|
+
case 403:
|
|
1564
|
+
// no permissions
|
|
1565
|
+
this.setMetaFireAndForget(appData.id, {
|
|
1566
|
+
authFlag: { message: PUBSUB_PERM_VIEW },
|
|
1567
|
+
ttlWarning: null
|
|
1568
|
+
});
|
|
1569
|
+
throw err;
|
|
1570
|
+
default:
|
|
1571
|
+
throw err;
|
|
1572
|
+
}
|
|
1573
|
+
}
|
|
1574
|
+
|
|
1575
|
+
if (existingPolicy) {
|
|
1576
|
+
logger.debug({ msg: 'Gmail publisher policy already exists', app: appData.id, topic: topicName });
|
|
1577
|
+
|
|
1578
|
+
// The required publisher binding is already in place (granted manually or by a
|
|
1579
|
+
// prior run). Record the marker so the Gmail watch can arm - it gates on this being
|
|
1580
|
+
// truthy. Store the same {members, role} object shape the create path uses. No
|
|
1581
|
+
// ownership flag: this marker has no deletion side effect (only read at the watch
|
|
1582
|
+
// gate). Only populate results (and write) on first adoption, so a re-run is a no-op
|
|
1583
|
+
// and does not trigger a redundant pull-worker restart.
|
|
1584
|
+
if (!current.pubSubIamPolicy) {
|
|
1585
|
+
results.iamPolicy = { members: [member], role };
|
|
1586
|
+
await this.update(appData.id, { pubSubIamPolicy: results.iamPolicy }, { partial: true });
|
|
1587
|
+
}
|
|
1588
|
+
} else {
|
|
1589
|
+
logger.debug({ msg: 'Granting access to Gmail publisher', app: appData.id, topic: topicName });
|
|
1590
|
+
let existingBindings = (getIamPolicyRes && getIamPolicyRes.bindings) || [];
|
|
1591
|
+
const policyPayload = {
|
|
1592
|
+
policy: {
|
|
1593
|
+
bindings: existingBindings.concat([
|
|
1594
|
+
{
|
|
1595
|
+
members: [member],
|
|
1596
|
+
role
|
|
1597
|
+
}
|
|
1598
|
+
])
|
|
1599
|
+
}
|
|
1600
|
+
};
|
|
1601
|
+
if (getIamPolicyRes && getIamPolicyRes.etag) {
|
|
1602
|
+
policyPayload.policy.etag = getIamPolicyRes.etag;
|
|
1603
|
+
}
|
|
1552
1604
|
try {
|
|
1553
|
-
|
|
1554
|
-
|
|
1555
|
-
|
|
1556
|
-
|
|
1557
|
-
|
|
1558
|
-
|
|
1559
|
-
|
|
1560
|
-
|
|
1605
|
+
await client.request(accessToken, `${topicUrl}:setIamPolicy`, 'POST', policyPayload);
|
|
1606
|
+
results.iamPolicy = {
|
|
1607
|
+
members: [member],
|
|
1608
|
+
role
|
|
1609
|
+
};
|
|
1610
|
+
|
|
1611
|
+
await this.update(
|
|
1612
|
+
appData.id,
|
|
1561
1613
|
{
|
|
1562
|
-
|
|
1563
|
-
|
|
1564
|
-
}
|
|
1565
|
-
|
|
1566
|
-
}
|
|
1567
|
-
*/
|
|
1614
|
+
pubSubIamPolicy: results.iamPolicy
|
|
1615
|
+
},
|
|
1616
|
+
{ partial: true }
|
|
1617
|
+
);
|
|
1568
1618
|
} catch (err) {
|
|
1569
1619
|
if (TRANSIENT_NETWORK_CODES.has(err.code)) {
|
|
1570
|
-
logger.warn({ msg: 'Network error
|
|
1620
|
+
logger.warn({ msg: 'Network error setting Pub/Sub IAM policy', app: appData.id, code: err.code });
|
|
1571
1621
|
throw err;
|
|
1572
1622
|
}
|
|
1573
1623
|
switch (err?.oauthRequest?.response?.error?.code) {
|
|
1574
1624
|
case 403:
|
|
1575
1625
|
// no permissions
|
|
1576
1626
|
this.setMetaFireAndForget(appData.id, {
|
|
1577
|
-
authFlag: { message:
|
|
1627
|
+
authFlag: { message: PUBSUB_PERM_MANAGE },
|
|
1578
1628
|
ttlWarning: null
|
|
1579
1629
|
});
|
|
1580
1630
|
throw err;
|
|
@@ -1582,87 +1632,21 @@ class OAuth2AppsHandler {
|
|
|
1582
1632
|
throw err;
|
|
1583
1633
|
}
|
|
1584
1634
|
}
|
|
1635
|
+
}
|
|
1585
1636
|
|
|
1586
|
-
|
|
1587
|
-
|
|
1588
|
-
|
|
1589
|
-
|
|
1590
|
-
|
|
1591
|
-
|
|
1592
|
-
|
|
1593
|
-
|
|
1594
|
-
|
|
1595
|
-
if (!current.pubSubIamPolicy) {
|
|
1596
|
-
results.iamPolicy = { members: [member], role };
|
|
1597
|
-
await this.update(appData.id, { pubSubIamPolicy: results.iamPolicy }, { partial: true });
|
|
1598
|
-
}
|
|
1599
|
-
} else {
|
|
1600
|
-
logger.debug({ msg: 'Granting access to Gmail publisher', app: appData.id, topic: topicName });
|
|
1601
|
-
let existingBindings = (getIamPolicyRes && getIamPolicyRes.bindings) || [];
|
|
1602
|
-
const policyPayload = {
|
|
1603
|
-
policy: {
|
|
1604
|
-
bindings: existingBindings.concat([
|
|
1605
|
-
{
|
|
1606
|
-
members: [member],
|
|
1607
|
-
role
|
|
1608
|
-
}
|
|
1609
|
-
])
|
|
1610
|
-
}
|
|
1611
|
-
};
|
|
1612
|
-
if (getIamPolicyRes && getIamPolicyRes.etag) {
|
|
1613
|
-
policyPayload.policy.etag = getIamPolicyRes.etag;
|
|
1614
|
-
}
|
|
1615
|
-
try {
|
|
1616
|
-
await client.request(accessToken, `${topicUrl}:setIamPolicy`, 'POST', policyPayload);
|
|
1617
|
-
results.iamPolicy = {
|
|
1618
|
-
members: [member],
|
|
1619
|
-
role
|
|
1620
|
-
};
|
|
1621
|
-
|
|
1622
|
-
await this.update(
|
|
1623
|
-
appData.id,
|
|
1624
|
-
{
|
|
1625
|
-
pubSubIamPolicy: results.iamPolicy
|
|
1626
|
-
},
|
|
1627
|
-
{ partial: true }
|
|
1628
|
-
);
|
|
1629
|
-
} catch (err) {
|
|
1630
|
-
if (TRANSIENT_NETWORK_CODES.has(err.code)) {
|
|
1631
|
-
logger.warn({ msg: 'Network error setting Pub/Sub IAM policy', app: appData.id, code: err.code });
|
|
1632
|
-
throw err;
|
|
1633
|
-
}
|
|
1634
|
-
switch (err?.oauthRequest?.response?.error?.code) {
|
|
1635
|
-
case 403:
|
|
1636
|
-
// no permissions
|
|
1637
|
-
this.setMetaFireAndForget(appData.id, {
|
|
1638
|
-
authFlag: { message: PUBSUB_PERM_MANAGE },
|
|
1639
|
-
ttlWarning: null
|
|
1640
|
-
});
|
|
1641
|
-
throw err;
|
|
1642
|
-
default:
|
|
1643
|
-
throw err;
|
|
1644
|
-
}
|
|
1645
|
-
}
|
|
1646
|
-
}
|
|
1647
|
-
|
|
1648
|
-
// clear auth flag if everything worked; set or clear TTL warning
|
|
1649
|
-
let metaUpdate = { authFlag: null };
|
|
1650
|
-
if (ttlPatchFailed) {
|
|
1651
|
-
metaUpdate.ttlWarning = {
|
|
1652
|
-
message: 'Failed to update expiration policy on subscription',
|
|
1653
|
-
description: [ttlPatchFailed.message, ttlPatchFailed.code].filter(Boolean).join('; ')
|
|
1654
|
-
};
|
|
1655
|
-
} else {
|
|
1656
|
-
metaUpdate.ttlWarning = null;
|
|
1657
|
-
}
|
|
1658
|
-
await this.setMeta(appData.id, metaUpdate);
|
|
1659
|
-
|
|
1660
|
-
return results;
|
|
1661
|
-
} finally {
|
|
1662
|
-
if (ensureLock?.success) {
|
|
1663
|
-
await lock.releaseLock(ensureLock);
|
|
1664
|
-
}
|
|
1637
|
+
// clear auth flag if everything worked; set or clear TTL warning
|
|
1638
|
+
let metaUpdate = { authFlag: null };
|
|
1639
|
+
if (ttlPatchFailed) {
|
|
1640
|
+
metaUpdate.ttlWarning = {
|
|
1641
|
+
message: 'Failed to update expiration policy on subscription',
|
|
1642
|
+
description: [ttlPatchFailed.message, ttlPatchFailed.code].filter(Boolean).join('; ')
|
|
1643
|
+
};
|
|
1644
|
+
} else {
|
|
1645
|
+
metaUpdate.ttlWarning = null;
|
|
1665
1646
|
}
|
|
1647
|
+
await this.setMeta(appData.id, metaUpdate);
|
|
1648
|
+
|
|
1649
|
+
return results;
|
|
1666
1650
|
}
|
|
1667
1651
|
|
|
1668
1652
|
async getClient(id, extraOpts) {
|
|
@@ -1849,27 +1833,22 @@ class OAuth2AppsHandler {
|
|
|
1849
1833
|
|
|
1850
1834
|
let lockKey = ['oauth', 'service', appData.id].join(':');
|
|
1851
1835
|
|
|
1852
|
-
|
|
1853
|
-
|
|
1854
|
-
|
|
1855
|
-
|
|
1856
|
-
|
|
1857
|
-
|
|
1858
|
-
|
|
1859
|
-
|
|
1860
|
-
}
|
|
1861
|
-
} catch (err) {
|
|
1862
|
-
if (!renewLock) {
|
|
1863
|
-
// unexpected lock-layer error; contention was already logged above
|
|
1864
|
-
logger.error({ msg: 'Failed to get renewal lock', app: appData.id, lockKey, err });
|
|
1865
|
-
}
|
|
1866
|
-
let error = Boom.boomify(new Error('Failed to get renewal lock'), { statusCode: 500 });
|
|
1867
|
-
if (err.code) {
|
|
1868
|
-
error.output.payload.code = err.code || 'LockFail';
|
|
1869
|
-
}
|
|
1870
|
-
throw error;
|
|
1871
|
-
}
|
|
1836
|
+
return await runLocked(
|
|
1837
|
+
getSharedLock(),
|
|
1838
|
+
lockKey,
|
|
1839
|
+
{ ttl: 5 * 60 * 1000, wait: 1 * 60 * 1000 },
|
|
1840
|
+
() => this.renewServiceAccessToken(appData, client, { accessToken, accessTokenExpires, now }),
|
|
1841
|
+
refuseUnavailableLock(logger, 'Failed to get renewal lock', { app: appData.id, lockKey })
|
|
1842
|
+
);
|
|
1843
|
+
}
|
|
1872
1844
|
|
|
1845
|
+
/**
|
|
1846
|
+
* The part of getServiceAccessToken() that runs under the renewal lock
|
|
1847
|
+
* @param {Object} appData - The service account app
|
|
1848
|
+
* @param {Object} client - Its OAuth2 client
|
|
1849
|
+
* @param {Object} cached - The cached token as read before the lock, `{ accessToken, accessTokenExpires, now }`
|
|
1850
|
+
*/
|
|
1851
|
+
async renewServiceAccessToken(appData, client, { accessToken, accessTokenExpires, now }) {
|
|
1873
1852
|
try {
|
|
1874
1853
|
// check if already renewed
|
|
1875
1854
|
appData = await this.get(appData.id);
|
|
@@ -1925,10 +1904,6 @@ class OAuth2AppsHandler {
|
|
|
1925
1904
|
err
|
|
1926
1905
|
});
|
|
1927
1906
|
throw err;
|
|
1928
|
-
} finally {
|
|
1929
|
-
if (renewLock?.success) {
|
|
1930
|
-
await lock.releaseLock(renewLock);
|
|
1931
|
-
}
|
|
1932
1907
|
}
|
|
1933
1908
|
}
|
|
1934
1909
|
}
|