emailengine-app 2.85.0 → 2.87.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 (137) hide show
  1. package/.ncurc.js +24 -6
  2. package/.release-please-manifest.json +1 -1
  3. package/CHANGELOG.md +97 -0
  4. package/DOCKER_DEPLOYMENT.md +2 -1
  5. package/Dockerfile +16 -3
  6. package/ENVIRONMENT.md +139 -0
  7. package/README.md +5 -1
  8. package/config/default.toml +2 -0
  9. package/copy-static-files.sh +4 -2
  10. package/data/google-crawlers.json +1 -1
  11. package/data/public_suffix_list.dat +4 -3
  12. package/lib/account-assignment.js +19 -0
  13. package/lib/account.js +285 -195
  14. package/lib/api-error-codes.js +49 -0
  15. package/lib/api-reference/model.js +6 -1
  16. package/lib/api-routes/account-routes.js +91 -32
  17. package/lib/api-routes/blocklist-routes.js +68 -2
  18. package/lib/api-routes/delivery-test-routes.js +1 -1
  19. package/lib/api-routes/gateway-routes.js +82 -10
  20. package/lib/api-routes/index.js +4 -0
  21. package/lib/api-routes/license-routes.js +2 -2
  22. package/lib/api-routes/mailbox-routes.js +3 -3
  23. package/lib/api-routes/message-routes.js +15 -7
  24. package/lib/api-routes/oauth2-app-routes.js +15 -8
  25. package/lib/api-routes/outbox-routes.js +77 -66
  26. package/lib/api-routes/permission-map.js +55 -6
  27. package/lib/api-routes/scoped-routes.js +74 -0
  28. package/lib/api-routes/settings-routes.js +11 -4
  29. package/lib/api-routes/stats-routes.js +5 -1
  30. package/lib/api-routes/submit-routes.js +25 -5
  31. package/lib/api-routes/template-routes.js +7 -6
  32. package/lib/api-routes/token-routes.js +11 -5
  33. package/lib/api-routes/webhook-delivery-routes.js +262 -0
  34. package/lib/api-routes/webhook-route-routes.js +119 -4
  35. package/lib/calendar-event.js +81 -1
  36. package/lib/consts.js +38 -46
  37. package/lib/db.js +14 -6
  38. package/lib/delivery-error.js +6 -0
  39. package/lib/deprecations.js +270 -0
  40. package/lib/email-client/base-client.js +134 -158
  41. package/lib/email-client/fallback-poll.js +62 -0
  42. package/lib/email-client/gmail-client.js +59 -11
  43. package/lib/email-client/imap/adaptive-idle-store.js +73 -0
  44. package/lib/email-client/imap/adaptive-idle.js +278 -0
  45. package/lib/email-client/imap/connection-errors.js +14 -1
  46. package/lib/email-client/imap/idle-settings.js +31 -5
  47. package/lib/email-client/imap/listing-diff.js +37 -0
  48. package/lib/email-client/imap/mailbox.js +380 -227
  49. package/lib/email-client/imap/subconnection.js +7 -29
  50. package/lib/email-client/imap/sync-operations.js +220 -127
  51. package/lib/email-client/imap-client.js +227 -163
  52. package/lib/email-client/message-builder.js +14 -79
  53. package/lib/email-client/outlook-client.js +378 -338
  54. package/lib/email-client/smtp-pool-manager.js +16 -13
  55. package/lib/email-client/sync-state-fields.js +19 -0
  56. package/lib/encrypt.js +157 -41
  57. package/lib/enum-descriptions.js +3 -1
  58. package/lib/env-setting-overrides.js +288 -0
  59. package/lib/export-worker.js +751 -0
  60. package/lib/export.js +64 -15
  61. package/lib/field-usage.js +1 -1
  62. package/lib/gateway.js +17 -1
  63. package/lib/get-raw-email.js +35 -108
  64. package/lib/health.js +75 -0
  65. package/lib/lock-run.js +119 -0
  66. package/lib/logger-consts.js +48 -0
  67. package/lib/logger.js +1 -1
  68. package/lib/lua/z-head-scores.lua +28 -0
  69. package/lib/network-errors.js +1 -1
  70. package/lib/node-version.js +24 -0
  71. package/lib/notify-attachments.js +20 -1
  72. package/lib/oauth/gmail.js +54 -29
  73. package/lib/oauth2-apps.js +630 -655
  74. package/lib/otp.js +66 -0
  75. package/lib/outbox.js +184 -54
  76. package/lib/parse-message.js +3 -3
  77. package/lib/privileged-settings.js +2 -2
  78. package/lib/queue-browser/definitions.js +11 -0
  79. package/lib/queue-browser/index.js +68 -19
  80. package/lib/queue-job-actions.js +18 -1
  81. package/lib/queue-retention.js +48 -12
  82. package/lib/queue-stats.js +11 -2
  83. package/lib/read-env-value.js +3 -0
  84. package/lib/redis-memory-warnings.js +99 -0
  85. package/lib/redis-reconnect.js +29 -0
  86. package/lib/request-timing.js +23 -0
  87. package/lib/respawn-backoff.js +35 -0
  88. package/lib/rewrite-text-nodes.js +19 -59
  89. package/lib/schemas.js +225 -41
  90. package/lib/settings.js +6 -2
  91. package/lib/smtp-auth.js +19 -1
  92. package/lib/swagger-options.js +2 -2
  93. package/lib/thread-diagnostics.js +18 -1
  94. package/lib/tls/provision.js +6 -3
  95. package/lib/token-audit-log.js +19 -20
  96. package/lib/token-permission-view.js +4 -3
  97. package/lib/tools.js +8 -41
  98. package/lib/ui-routes/admin-config-routes.js +64 -90
  99. package/lib/ui-routes/admin-entities-routes.js +2 -14
  100. package/lib/ui-routes/imap-idle-field.js +1 -1
  101. package/lib/ui-routes/outlook-subscription-view.js +1 -1
  102. package/lib/ui-routes/overridable-fields.js +84 -0
  103. package/lib/ui-routes/queue-routes.js +8 -5
  104. package/lib/ui-routes/settings-page.js +6 -0
  105. package/lib/utils/decode-headers.js +3 -12
  106. package/lib/utils/filter-empty.js +20 -0
  107. package/lib/utils/int-setting.js +48 -0
  108. package/lib/utils/tracking-settings.js +35 -0
  109. package/lib/web-safe-html.js +18 -105
  110. package/lib/webhook-delivery.js +461 -0
  111. package/lib/webhook-failures.js +132 -0
  112. package/lib/webhook-request.js +29 -1
  113. package/lib/webhook-routing.js +30 -1
  114. package/lib/webhook-test.js +88 -0
  115. package/lib/webhooks.js +59 -41
  116. package/lib/worker-rpc-error.js +2 -1
  117. package/package.json +28 -26
  118. package/sbom.json +600 -678
  119. package/server.js +149 -76
  120. package/static/css/flyonui.css +1 -1
  121. package/static/js/ace/ace.js +1 -1
  122. package/static/js/ee-client.js +650 -196
  123. package/static/licenses.html +49 -59
  124. package/translations/messages.pot +26 -26
  125. package/views/config/security.hbs +22 -0
  126. package/views/config/service.hbs +44 -0
  127. package/views/config/webhooks.hbs +36 -0
  128. package/views/layout/app.hbs +9 -6
  129. package/views/legal.hbs +8 -0
  130. package/views/partials/queue_retention_note.hbs +12 -8
  131. package/views/partials/ui/env-managed-alert.hbs +16 -7
  132. package/workers/api.js +112 -37
  133. package/workers/export.js +16 -631
  134. package/workers/imap.js +13 -0
  135. package/workers/smtp.js +9 -11
  136. package/workers/webhooks.js +18 -432
  137. package/lib/email-client/outlook-fallback-poll.js +0 -30
@@ -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 Lock = require('ioredfour');
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
 
@@ -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 (!hasValues(await readLegacyValues())) {
491
+ if (!hasLegacyValues(await readLegacyValues())) {
497
492
  return [];
498
493
  }
499
494
 
500
- let migrateLock = await lock.waitAcquireLock('oauth:legacy:migrate', 5 * 60 * 1000, 2 * 60 * 1000);
501
- if (!migrateLock.success) {
502
- throw new Error('Failed to get lock for the legacy OAuth2 app migration');
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
- try {
507
- // re-read inside the lock: another instance may have finished the migration already
508
- let values = await readLegacyValues();
509
- if (!hasValues(values)) {
510
- return [];
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
- const normalizeScopes = value => {
514
- if (!Array.isArray(value)) {
515
- value = (value || '').toString().split(/[\s,]+/);
516
- }
517
- return value.filter(entry => entry);
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
- // 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 = candidateKeys.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 = 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
- // 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
- };
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
- // 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
- }
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
- // create() owns the record shape: it encrypts secret fields and stamps `created`
610
- await this.create(entry, { id: legacyKey });
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
- if (v('AuthFlag')) {
613
- await this.setMeta(legacyKey, { authFlag: v('AuthFlag') });
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
- migrated.push(legacyKey);
617
- logger.info({ msg: 'Migrated legacy OAuth2 app to the app registry', app: legacyKey, enabled: entry.enabled });
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
- 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);
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
- clearable.push(legacyKey);
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
- // 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');
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
- 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
- }
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
- if (backfillCount) {
669
- await backfillReq.exec();
670
- logger.info({ msg: 'Linked existing accounts to migrated OAuth2 apps', accounts: backfillCount });
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
- // 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 => FIELDS.map(field => `${legacyKey}${field}`)));
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
- let removedOrphans = await this.redis.hdel(this.getSettingsKey(), ...ORPHAN_KEYS);
680
- if (removedOrphans) {
681
- logger.info({ msg: 'Removed orphaned legacy OAuth2 service settings', keys: ORPHAN_KEYS });
682
- }
683
- } finally {
684
- await lock.releaseLock(migrateLock);
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
- let delLock;
892
+ if (!needsPubSubLock) {
893
+ return await this.removeApp(id, appData);
894
+ }
896
895
 
897
- if (needsPubSubLock) {
898
- let lockKey = ['oauth', 'pubsub', appData.id].join(':');
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
- delLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 2 * 60 * 1000);
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({ msg: 'Failed to acquire lock for pubsub app deletion', lockKey, err });
906
- throw err;
907
- }
908
-
909
- // Re-read under the lock so the ownership-flag deletion decision below acts on the
910
- // current record, not the snapshot taken before the lock - a concurrent ensurePubsub /
911
- // recovery run may have adopted or created a resource in the meantime. Keep the pre-lock
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
- try {
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)
923
- try {
924
- await this.deleteTopic(appData);
925
- } catch (err) {
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
- });
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
- if (appData.baseScopes === 'pubsub') {
950
- pipeline = pipeline.del(this.getPubsubAppKey(id));
951
- }
949
+ if (appData.baseScopes === 'pubsub') {
950
+ pipeline = pipeline.del(this.getPubsubAppKey(id));
951
+ }
952
952
 
953
- let deleteResult = await pipeline.exec();
953
+ let deleteResult = await pipeline.exec();
954
954
 
955
- let errorEntry = deleteResult.find(entry => entry && entry[0]);
956
- if (errorEntry) {
957
- throw errorEntry[0];
958
- }
955
+ let errorEntry = deleteResult.find(entry => entry && entry[0]);
956
+ if (errorEntry) {
957
+ throw errorEntry[0];
958
+ }
959
959
 
960
- let deletedDocs = ((deleteResult[0] && deleteResult[0][1]) || 0) + ((deleteResult[1] && deleteResult[1][1]) || 0);
960
+ let deletedDocs = ((deleteResult[0] && deleteResult[0][1]) || 0) + ((deleteResult[1] && deleteResult[1][1]) || 0);
961
961
 
962
- return {
963
- id,
964
- deleted: deletedDocs >= 2,
965
- accounts: Number(deleteResult[2] && deleteResult[2][1]) || 0
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 results;
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
- let topicUrl = `https://pubsub.googleapis.com/v1/${topicName}`;
1249
- let subscriptionUrl = `https://pubsub.googleapis.com/v1/${subscriptionName}`;
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
- // Acquire per-app lock to prevent concurrent ensurePubsub races (e.g., user update + background recovery)
1255
- let lockKey = ['oauth', 'pubsub', appData.id].join(':');
1256
- let ensureLock;
1257
- try {
1258
- ensureLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 2 * 60 * 1000);
1259
- if (!ensureLock.success) {
1260
- // contention: timed out waiting for the current lock holder
1261
- logger.warn({ msg: 'Failed to get ensurePubsub lock, timed out waiting for the current holder', app: appData.id, lockKey });
1262
- throw new Error('Failed to get ensurePubsub lock');
1263
- }
1264
- } catch (err) {
1265
- if (!ensureLock) {
1266
- // unexpected lock-layer error; contention was already logged above
1267
- logger.error({ msg: 'Failed to get ensurePubsub lock', app: appData.id, lockKey, err });
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
- throw err;
1270
- }
1277
+ };
1271
1278
 
1272
- try {
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
- let client = await this.getClient(appData.id);
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
- // Step 1. Get access token for service client
1293
- let accessToken = await this.getServiceAccessToken(appData, client);
1294
- if (!accessToken) {
1295
- throw new Error('Failed to get access token');
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
- switch (err?.oauthRequest?.response?.error?.code) {
1315
- case 403:
1316
- // no permissions
1317
- if (/Cloud Pub\/Sub API has not been used in project/.test(err?.oauthRequest?.response?.error?.message)) {
1318
- this.setMetaFireAndForget(appData.id, {
1319
- authFlag: {
1320
- message:
1321
- 'Enable the Cloud Pub/Sub API for your project before using the service client. Check the server response below for details.',
1322
- description: err?.oauthRequest?.response?.error?.message
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
- throw err;
1334
- case 404: {
1335
- // does not exist
1336
- logger.info({ msg: 'Topic does not exist', app: appData.id, topic: topicName });
1337
- try {
1338
- let topicCreateRes = await client.request(accessToken, topicUrl, 'PUT', Buffer.alloc(0));
1339
- /*
1340
- {name: 'projects/...'}
1341
- */
1342
- if (!topicCreateRes?.name) {
1343
- throw new Error('Topic was not created', { cause: err });
1344
- }
1345
-
1346
- await this.update(
1347
- appData.id,
1348
- {
1349
- pubSubTopic: topicName,
1350
- // EmailEngine created this topic, so it may delete it on app removal.
1351
- pubSubTopicManaged: true
1352
- },
1353
- { partial: true }
1354
- );
1355
-
1356
- results.pubSubTopic = topicName;
1357
- } catch (err) {
1358
- if (TRANSIENT_NETWORK_CODES.has(err.code)) {
1359
- logger.warn({ msg: 'Network error creating Pub/Sub topic', app: appData.id, code: err.code });
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
- default:
1382
- throw err;
1368
+ break;
1383
1369
  }
1370
+ default:
1371
+ throw err;
1384
1372
  }
1373
+ }
1385
1374
 
1386
- // Step 3. Set up subscriber
1375
+ // Step 3. Set up subscriber
1387
1376
 
1388
- try {
1389
- // fails if topic does not exist
1390
- let subscriptionData = await client.request(accessToken, subscriptionUrl, 'GET');
1391
- logger.debug({ msg: 'Subscription already exists', app: appData.id, subscription: subscriptionName });
1392
- /*
1393
- {name: 'projects/...'}
1394
- */
1395
-
1396
- // Adopt a pre-existing subscription so the pull worker recognizes it (also stops the
1397
- // recovery loop in lib/oauth/pubsub/google.js); kept unmanaged - we did not create it.
1398
- await adoptExistingResource('pubSubSubscription', subscriptionName);
1399
-
1400
- // Patch existing subscription's expiration policy if it differs from desired
1401
- // When no explicit TTL is configured, use Google's default (31 days) for comparison
1402
- let effectivePolicy = desiredExpirationPolicy ?? { ttl: GMAIL_PUBSUB_DEFAULT_EXPIRATION_TTL };
1403
- let currentTtl = subscriptionData?.expirationPolicy?.ttl || null;
1404
- let desiredTtl = effectivePolicy.ttl || null;
1405
-
1406
- // Adopted (pre-existing, unmanaged) subscriptions belong to the customer - never
1407
- // rewrite their lifecycle policy. A subscription is ours to manage only when it is
1408
- // already recorded as managed (true) or predates ownership tracking (undefined);
1409
- // a freshly adopted one (marker absent in the pre-lock snapshot) or an explicit
1410
- // `false` flag is hands-off.
1411
- let subscriptionManagedByUs = !!current.pubSubSubscription && current.pubSubSubscriptionManaged !== false;
1412
-
1413
- if (!subscriptionManagedByUs && desiredExpirationPolicy !== null) {
1414
- // Do not mutate the customer's subscription, but warn when an explicitly
1415
- // configured expiration is longer than theirs: the subscription may expire on
1416
- // its own and silently disable Gmail push.
1417
- let toSeconds = ttl => {
1418
- let n = ttl ? parseInt(ttl, 10) : NaN;
1419
- return Number.isFinite(n) ? n : null;
1420
- };
1421
- let currentSeconds = toSeconds(currentTtl);
1422
- let desiredSeconds = toSeconds(desiredTtl);
1423
- // desiredSeconds === null means EmailEngine wants an indefinite subscription
1424
- if (currentSeconds !== null && (desiredSeconds === null || currentSeconds < desiredSeconds)) {
1425
- logger.warn({
1426
- msg: 'Adopted Pub/Sub subscription expires sooner than the configured expiration; leaving it unchanged',
1427
- app: appData.id,
1428
- subscription: subscriptionName,
1429
- currentTtl,
1430
- desiredTtl
1431
- });
1432
- }
1433
- } else if (subscriptionManagedByUs && currentTtl !== desiredTtl) {
1434
- try {
1435
- await client.request(accessToken, subscriptionUrl, 'PATCH', {
1436
- subscription: { expirationPolicy: effectivePolicy },
1437
- updateMask: 'expirationPolicy'
1438
- });
1439
- logger.info({
1440
- msg: 'Updated expiration policy on subscription',
1441
- app: appData.id,
1442
- subscription: subscriptionName,
1443
- desiredTtl
1444
- });
1445
- // Update stored TTL after successful patch
1446
- subscriptionData.expirationPolicy = effectivePolicy;
1447
- } catch (patchErr) {
1448
- ttlPatchFailed = patchErr;
1449
- logger.warn({
1450
- msg: 'Failed to update expiration policy on subscription',
1451
- app: appData.id,
1452
- subscription: subscriptionName,
1453
- err: patchErr
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
- // Store current expiration info in meta
1459
- await this.setMeta(appData.id, {
1460
- subscriptionExpiration: subscriptionData?.expirationPolicy?.ttl || null
1461
- });
1462
- } catch (err) {
1463
- if (TRANSIENT_NETWORK_CODES.has(err.code)) {
1464
- logger.warn({ msg: 'Network error checking Pub/Sub subscription', app: appData.id, code: err.code });
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
- switch (err?.oauthRequest?.response?.error?.code) {
1468
- case 403:
1469
- // no permissions
1470
- this.setMetaFireAndForget(appData.id, {
1471
- authFlag: { message: PUBSUB_PERM_VIEW },
1472
- ttlWarning: null
1473
- });
1474
- throw err;
1475
- case 404: {
1476
- // does not exist
1477
- logger.info({ msg: 'Subscription does not exist', app: appData.id, subscription: subscriptionName });
1478
- try {
1479
- let createPayload = {
1480
- topic: topicName,
1481
- ackDeadlineSeconds: GMAIL_PUBSUB_ACK_DEADLINE_SECONDS
1482
- };
1483
- if (desiredExpirationPolicy !== null) {
1484
- createPayload.expirationPolicy = desiredExpirationPolicy;
1485
- }
1486
- let subscriptionCreateRes = await client.request(accessToken, subscriptionUrl, 'PUT', createPayload);
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
- name: 'projects/webhooks-425411/subscriptions/ee-sub-AAABkE9_uNMAAAAH',
1490
- topic: 'projects/webhooks-425411/topics/ee-pub-AAABkE9_uNMAAAAH',
1491
- pushConfig: {},
1492
- ackDeadlineSeconds: 10,
1493
- messageRetentionDuration: '604800s',
1494
- expirationPolicy: { ttl: '2678400s' },
1495
- state: 'ACTIVE'
1496
- }
1497
- */
1498
-
1499
- if (!subscriptionCreateRes?.name) {
1500
- throw new Error('Subscription was not created', { cause: err });
1501
- }
1502
-
1503
- await this.update(
1504
- appData.id,
1505
- {
1506
- pubSubSubscription: subscriptionName,
1507
- // EmailEngine created this subscription, so it may delete it on app removal.
1508
- pubSubSubscriptionManaged: true
1509
- },
1510
- { partial: true }
1511
- );
1512
-
1513
- results.pubSubSubscription = subscriptionName;
1514
-
1515
- // Store expiration info from the created subscription
1516
- await this.setMeta(appData.id, {
1517
- subscriptionExpiration: subscriptionCreateRes?.expirationPolicy?.ttl || null
1518
- });
1519
- } catch (err) {
1520
- if (TRANSIENT_NETWORK_CODES.has(err.code)) {
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
- default:
1544
- throw err;
1530
+ break;
1545
1531
  }
1532
+ default:
1533
+ throw err;
1546
1534
  }
1535
+ }
1547
1536
 
1548
- // Step 4. Grant access to Gmail publisher
1537
+ // Step 4. Grant access to Gmail publisher
1549
1538
 
1550
- let existingPolicy;
1551
- let getIamPolicyRes;
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
- // Check for an existing policy grant
1554
- getIamPolicyRes = await client.request(accessToken, `${topicUrl}:getIamPolicy`, 'GET');
1555
- existingPolicy = getIamPolicyRes?.bindings?.find(binding => binding?.role === role && binding?.members?.includes(member));
1556
- /*
1557
- {
1558
- version: 1,
1559
- etag: 'BwYbtWmb5c0=',
1560
- bindings: [
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
- role: 'roles/pubsub.publisher',
1563
- members: [ 'serviceAccount:gmail-api-push@system.gserviceaccount.com' ]
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 checking Pub/Sub IAM policy', app: appData.id, code: err.code });
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: PUBSUB_PERM_VIEW },
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
- if (existingPolicy) {
1587
- logger.debug({ msg: 'Gmail publisher policy already exists', app: appData.id, topic: topicName });
1588
-
1589
- // The required publisher binding is already in place (granted manually or by a
1590
- // prior run). Record the marker so the Gmail watch can arm - it gates on this being
1591
- // truthy. Store the same {members, role} object shape the create path uses. No
1592
- // ownership flag: this marker has no deletion side effect (only read at the watch
1593
- // gate). Only populate results (and write) on first adoption, so a re-run is a no-op
1594
- // and does not trigger a redundant pull-worker restart.
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
- let renewLock;
1853
-
1854
- try {
1855
- renewLock = await lock.waitAcquireLock(lockKey, 5 * 60 * 1000, 1 * 60 * 1000);
1856
- if (!renewLock.success) {
1857
- // contention: timed out waiting for the current lock holder
1858
- logger.warn({ msg: 'Failed to get renewal lock, timed out waiting for the current holder', app: appData.id, lockKey });
1859
- throw new Error('Failed to get renewal lock');
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
  }