UserUpdater.test.mjs 36 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246
  1. import { vi, expect } from 'vitest'
  2. import { setTimeout } from 'node:timers/promises'
  3. import path from 'node:path'
  4. import sinon from 'sinon'
  5. import mongodb from 'mongodb-legacy'
  6. import tk from 'timekeeper'
  7. import MongoHelpers from '../../../../app/src/Features/Helpers/Mongo.mjs'
  8. import Errors from '../../../../app/src/Features/Errors/Errors.js'
  9. const { normalizeQuery } = MongoHelpers
  10. const { ObjectId } = mongodb
  11. const MODULE_PATH = path.join(
  12. import.meta.dirname,
  13. '../../../../app/src/Features/User/UserUpdater'
  14. )
  15. vi.mock('../../../../app/src/Features/Errors/Errors.js', () =>
  16. vi.importActual('../../../../app/src/Features/Errors/Errors.js')
  17. )
  18. describe('UserUpdater', function () {
  19. beforeEach(async function (ctx) {
  20. tk.freeze(Date.now())
  21. ctx.user = {
  22. _id: new ObjectId(),
  23. name: 'bob',
  24. email: 'hello@world.com',
  25. emails: [{ email: 'hello@world.com' }],
  26. }
  27. ctx.db = {
  28. users: {
  29. updateOne: sinon.stub().resolves({ matchedCount: 1, modifiedCount: 1 }),
  30. },
  31. }
  32. ctx.mongodb = {
  33. db: ctx.db,
  34. ObjectId,
  35. }
  36. ctx.UserGetter = {
  37. promises: {
  38. ensureUniqueEmailAddress: sinon.stub().resolves(),
  39. getUser: sinon.stub(),
  40. getUserByMainEmail: sinon.stub(),
  41. getUserFullEmails: sinon.stub(),
  42. getUserEmail: sinon.stub(),
  43. },
  44. }
  45. ctx.UserGetter.promises.getUser.withArgs(ctx.user._id).resolves(ctx.user)
  46. ctx.UserGetter.promises.getUserByMainEmail
  47. .withArgs(ctx.user.email)
  48. .resolves(ctx.user)
  49. ctx.UserGetter.promises.getUserFullEmails
  50. .withArgs(ctx.user._id)
  51. .resolves(ctx.user.emails)
  52. ctx.UserGetter.promises.getUserEmail
  53. .withArgs(ctx.user._id)
  54. .resolves(ctx.user.email)
  55. ctx.NewsletterManager = {
  56. promises: {
  57. changeEmail: sinon.stub().resolves(),
  58. },
  59. }
  60. ctx.AnalyticsManager = {
  61. recordEventForUserInBackground: sinon.stub(),
  62. }
  63. ctx.InstitutionsAPI = {
  64. promises: {
  65. addAffiliation: sinon.stub().resolves(),
  66. removeAffiliation: sinon.stub().resolves(),
  67. getUserAffiliations: sinon.stub().resolves(),
  68. },
  69. }
  70. ctx.EmailHandler = {
  71. promises: {
  72. sendEmail: sinon.stub().resolves(),
  73. },
  74. }
  75. ctx.Features = {
  76. hasFeature: sinon.stub().returns(false),
  77. }
  78. ctx.FeaturesUpdater = {
  79. promises: {
  80. refreshFeatures: sinon.stub().resolves(),
  81. },
  82. }
  83. ctx.UserAuditLogHandler = {
  84. promises: {
  85. addEntry: sinon.stub().resolves(),
  86. },
  87. }
  88. ctx.SubscriptionLocator = {
  89. promises: {
  90. getUserIndividualSubscription: sinon.stub().resolves(),
  91. },
  92. }
  93. ctx.NotificationsBuilder = {
  94. promises: {
  95. redundantPersonalSubscription: sinon
  96. .stub()
  97. .returns({ create: () => {} }),
  98. },
  99. }
  100. ctx.Modules = {
  101. promises: {
  102. hooks: {
  103. fire: sinon.stub().resolves([]),
  104. },
  105. },
  106. }
  107. ctx.UserSessionsManager = {
  108. promises: {
  109. removeSessionsFromRedis: sinon.stub().resolves(),
  110. },
  111. }
  112. ctx.AsyncLocalStorage = {
  113. removeItem: sinon.stub(),
  114. }
  115. vi.doMock('../../../../app/src/Features/Helpers/Mongo', () => ({
  116. default: { normalizeQuery },
  117. }))
  118. vi.doMock('../../../../app/src/infrastructure/mongodb', () => ctx.mongodb)
  119. vi.doMock('../../../../app/src/Features/User/UserGetter', () => ({
  120. default: ctx.UserGetter,
  121. }))
  122. vi.doMock(
  123. '../../../../app/src/Features/Institutions/InstitutionsAPI',
  124. () => ({
  125. default: ctx.InstitutionsAPI,
  126. })
  127. )
  128. vi.doMock('../../../../app/src/Features/Email/EmailHandler', () => ({
  129. default: ctx.EmailHandler,
  130. }))
  131. vi.doMock('../../../../app/src/infrastructure/Features', () => ({
  132. default: ctx.Features,
  133. }))
  134. vi.doMock(
  135. '../../../../app/src/Features/Subscription/FeaturesUpdater',
  136. () => ({
  137. default: ctx.FeaturesUpdater,
  138. })
  139. )
  140. vi.doMock('@overleaf/settings', () => ({
  141. default: (ctx.settings = {}),
  142. }))
  143. vi.doMock(
  144. '../../../../app/src/Features/Newsletter/NewsletterManager',
  145. () => ({
  146. default: ctx.NewsletterManager,
  147. })
  148. )
  149. vi.doMock(
  150. '../../../../app/src/Features/Subscription/RecurlyWrapper',
  151. () => ({
  152. default: ctx.RecurlyWrapper,
  153. })
  154. )
  155. vi.doMock('../../../../app/src/Features/User/UserAuditLogHandler', () => ({
  156. default: ctx.UserAuditLogHandler,
  157. }))
  158. vi.doMock(
  159. '../../../../app/src/Features/Analytics/AnalyticsManager',
  160. () => ({
  161. default: ctx.AnalyticsManager,
  162. })
  163. )
  164. vi.doMock(
  165. '../../../../app/src/Features/Subscription/SubscriptionLocator',
  166. () => ({
  167. default: ctx.SubscriptionLocator,
  168. })
  169. )
  170. vi.doMock(
  171. '../../../../app/src/Features/Notifications/NotificationsBuilder',
  172. () => ({
  173. default: ctx.NotificationsBuilder,
  174. })
  175. )
  176. vi.doMock('../../../../app/src/infrastructure/Modules', () => ({
  177. default: ctx.Modules,
  178. }))
  179. vi.doMock('../../../../app/src/Features/User/UserSessionsManager', () => ({
  180. default: ctx.UserSessionsManager,
  181. }))
  182. vi.doMock(
  183. '../../../../app/src/Features/User/ThirdPartyIdentityManager',
  184. () => ({
  185. default: ctx.ThirdPartyIdentityManager,
  186. })
  187. )
  188. vi.doMock('../../../../app/src/infrastructure/AsyncLocalStorage', () => ({
  189. default: ctx.AsyncLocalStorage,
  190. }))
  191. ctx.UserUpdater = (await import(MODULE_PATH)).default
  192. ctx.newEmail = 'bob@bob.com'
  193. })
  194. afterEach(function () {
  195. return tk.reset()
  196. })
  197. describe('addAffiliationForNewUser', function () {
  198. it('should not remove affiliationUnchecked flag if v1 returns an error', async function (ctx) {
  199. ctx.InstitutionsAPI.promises.addAffiliation.rejects()
  200. await expect(
  201. ctx.UserUpdater.promises.addAffiliationForNewUser(
  202. ctx.user._id,
  203. ctx.newEmail
  204. )
  205. ).to.be.rejected
  206. sinon.assert.notCalled(ctx.db.users.updateOne)
  207. })
  208. it('should remove affiliationUnchecked flag if v1 does not return an error', async function (ctx) {
  209. await ctx.UserUpdater.promises.addAffiliationForNewUser(
  210. ctx.user._id,
  211. ctx.newEmail
  212. )
  213. sinon.assert.calledOnce(ctx.db.users.updateOne)
  214. sinon.assert.calledWithMatch(
  215. ctx.db.users.updateOne,
  216. { _id: ctx.user._id, 'emails.email': ctx.newEmail },
  217. { $unset: { 'emails.$.affiliationUnchecked': 1 } }
  218. )
  219. })
  220. it('should not throw if removing affiliationUnchecked flag errors', async function (ctx) {
  221. ctx.db.users.updateOne.rejects(new Error('nope'))
  222. await ctx.UserUpdater.promises.addAffiliationForNewUser(
  223. ctx.user._id,
  224. ctx.newEmail
  225. )
  226. })
  227. it('calls to remove userFullEmails from AsyncLocalStorage', async function (ctx) {
  228. await ctx.UserUpdater.promises.addAffiliationForNewUser(
  229. ctx.user._id,
  230. ctx.newEmail
  231. )
  232. expect(ctx.AsyncLocalStorage.removeItem).to.have.been.calledWith(
  233. 'userFullEmails'
  234. )
  235. })
  236. })
  237. describe('changeEmailAddress', function () {
  238. beforeEach(async function (ctx) {
  239. ctx.auditLog = {
  240. initiatorId: 'abc123',
  241. ipAddress: '0:0:0:0',
  242. }
  243. // After the email changed, make sure that UserGetter.getUser() returns a
  244. // user with the new email.
  245. ctx.UserGetter.promises.getUser
  246. .withArgs(ctx.user._id)
  247. .onCall(1)
  248. .resolves({
  249. ...ctx.user,
  250. emails: [...ctx.user.emails, { email: ctx.newEmail }],
  251. })
  252. // The main email changes as a result of the email change
  253. ctx.UserGetter.promises.getUserByMainEmail
  254. .withArgs(ctx.user.email)
  255. .resolves(null)
  256. ctx.user.emails.push({ email: ctx.newEmail })
  257. await ctx.UserUpdater.promises.changeEmailAddress(
  258. ctx.user._id,
  259. ctx.newEmail,
  260. ctx.auditLog
  261. )
  262. })
  263. it('adds the new email', function (ctx) {
  264. expect(ctx.db.users.updateOne).to.have.been.calledWith(
  265. { _id: ctx.user._id, 'emails.email': { $ne: ctx.newEmail } },
  266. {
  267. $push: {
  268. emails: sinon.match({ email: ctx.newEmail }),
  269. },
  270. }
  271. )
  272. })
  273. it('adds the new affiliation', function (ctx) {
  274. ctx.InstitutionsAPI.promises.addAffiliation.should.have.been.calledWith(
  275. ctx.user._id,
  276. ctx.newEmail
  277. )
  278. })
  279. it('removes the old email', function (ctx) {
  280. expect(ctx.db.users.updateOne).to.have.been.calledWith(
  281. { _id: ctx.user._id, email: { $ne: ctx.user.email } },
  282. { $pull: { emails: { email: ctx.user.email } } }
  283. )
  284. })
  285. it('removes the affiliation', function (ctx) {
  286. expect(
  287. ctx.InstitutionsAPI.promises.removeAffiliation
  288. ).to.have.been.calledWith(ctx.user._id, ctx.user.email)
  289. })
  290. it('refreshes features', function (ctx) {
  291. sinon.assert.calledWith(
  292. ctx.FeaturesUpdater.promises.refreshFeatures,
  293. ctx.user._id
  294. )
  295. })
  296. it('sets the default email', function (ctx) {
  297. expect(ctx.db.users.updateOne).to.have.been.calledWith(
  298. { _id: ctx.user._id, 'emails.email': ctx.newEmail },
  299. {
  300. $set: sinon.match({
  301. email: ctx.newEmail,
  302. }),
  303. }
  304. )
  305. })
  306. it('sets the new email in the newsletter', function (ctx) {
  307. expect(
  308. ctx.NewsletterManager.promises.changeEmail
  309. ).to.have.been.calledWith(ctx.user, ctx.newEmail)
  310. expect(ctx.Modules.promises.hooks.fire).to.have.been.calledWith(
  311. 'updateAccountEmailAddress',
  312. ctx.user._id,
  313. ctx.newEmail
  314. )
  315. })
  316. it('validates email', async function (ctx) {
  317. await expect(
  318. ctx.UserUpdater.promises.changeEmailAddress(
  319. ctx.user._id,
  320. 'foo',
  321. ctx.auditLog
  322. )
  323. ).to.be.rejected
  324. })
  325. })
  326. describe('addEmailAddress', function () {
  327. it('adds the email', async function (ctx) {
  328. await ctx.UserUpdater.promises.addEmailAddress(
  329. ctx.user._id,
  330. ctx.newEmail,
  331. {},
  332. { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
  333. )
  334. ctx.UserGetter.promises.ensureUniqueEmailAddress.should.have.been.called
  335. const reversedHostname = ctx.newEmail
  336. .split('@')[1]
  337. .split('')
  338. .reverse()
  339. .join('')
  340. ctx.db.users.updateOne.should.have.been.calledWith(
  341. { _id: ctx.user._id, 'emails.email': { $ne: ctx.newEmail } },
  342. {
  343. $push: {
  344. emails: {
  345. email: ctx.newEmail,
  346. createdAt: sinon.match.date,
  347. reversedHostname,
  348. },
  349. },
  350. }
  351. )
  352. })
  353. it('adds the affiliation', async function (ctx) {
  354. const affiliationOptions = {
  355. university: { id: 1 },
  356. role: 'Prof',
  357. department: 'Math',
  358. }
  359. await ctx.UserUpdater.promises.addEmailAddress(
  360. ctx.user._id,
  361. ctx.newEmail,
  362. affiliationOptions,
  363. { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
  364. )
  365. ctx.InstitutionsAPI.promises.addAffiliation.should.have.been.calledWith(
  366. ctx.user._id,
  367. ctx.newEmail,
  368. affiliationOptions
  369. )
  370. })
  371. it('handles affiliation errors', async function (ctx) {
  372. ctx.InstitutionsAPI.promises.addAffiliation.rejects(new Error('nope'))
  373. await expect(
  374. ctx.UserUpdater.promises.addEmailAddress(
  375. ctx.user._id,
  376. ctx.newEmail,
  377. {},
  378. { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
  379. )
  380. ).to.be.rejected
  381. ctx.db.users.updateOne.should.not.have.been.called
  382. })
  383. it('validates the email', async function (ctx) {
  384. expect(
  385. ctx.UserUpdater.promises.addEmailAddress(
  386. ctx.user._id,
  387. 'bar',
  388. {},
  389. { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
  390. )
  391. ).to.be.rejected
  392. })
  393. it('updates the audit log', async function (ctx) {
  394. ctx.ip = '127:0:0:0'
  395. await ctx.UserUpdater.promises.addEmailAddress(
  396. ctx.user._id,
  397. ctx.newEmail,
  398. {},
  399. { initiatorId: ctx.user._id, ipAddress: ctx.ip }
  400. )
  401. ctx.InstitutionsAPI.promises.addAffiliation.calledOnce.should.equal(true)
  402. const { args } = ctx.UserAuditLogHandler.promises.addEntry.lastCall
  403. expect(args[0]).to.equal(ctx.user._id)
  404. expect(args[1]).to.equal('add-email')
  405. expect(args[2]).to.equal(ctx.user._id)
  406. expect(args[3]).to.equal(ctx.ip)
  407. expect(args[4]).to.deep.equal({ newSecondaryEmail: ctx.newEmail })
  408. })
  409. describe('errors', function () {
  410. describe('via UserAuditLogHandler', function () {
  411. const anError = new Error('oops')
  412. beforeEach(function (ctx) {
  413. ctx.UserAuditLogHandler.promises.addEntry.rejects(anError)
  414. })
  415. it('should not add email and should return error', async function (ctx) {
  416. await expect(
  417. ctx.UserUpdater.promises.addEmailAddress(
  418. ctx.user._id,
  419. ctx.newEmail,
  420. {},
  421. { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
  422. )
  423. ).to.be.rejectedWith(anError)
  424. expect(ctx.db.users.updateOne).to.not.have.been.called
  425. })
  426. })
  427. })
  428. it('calls to remove userFullEmails from AsyncLocalStorage', async function (ctx) {
  429. await ctx.UserUpdater.promises.addEmailAddress(
  430. ctx.user._id,
  431. ctx.newEmail,
  432. {},
  433. { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
  434. )
  435. expect(ctx.AsyncLocalStorage.removeItem).to.have.been.calledWith(
  436. 'userFullEmails'
  437. )
  438. })
  439. })
  440. describe('removeEmailAddress', function () {
  441. beforeEach(function (ctx) {
  442. ctx.auditLog = { initiatorId: ctx.user._id, ipAddress: '127:0:0:0' }
  443. })
  444. it('removes the email', async function (ctx) {
  445. await ctx.UserUpdater.promises.removeEmailAddress(
  446. ctx.user._id,
  447. ctx.newEmail,
  448. ctx.auditLog
  449. )
  450. expect(ctx.db.users.updateOne).to.have.been.calledWith(
  451. { _id: ctx.user._id, email: { $ne: ctx.newEmail } },
  452. { $pull: { emails: { email: ctx.newEmail } } }
  453. )
  454. })
  455. it('removes the affiliation', async function (ctx) {
  456. await ctx.UserUpdater.promises.removeEmailAddress(
  457. ctx.user._id,
  458. ctx.newEmail,
  459. ctx.auditLog
  460. )
  461. expect(ctx.InstitutionsAPI.promises.removeAffiliation).to.have.been
  462. .calledOnce
  463. const { args } = ctx.InstitutionsAPI.promises.removeAffiliation.lastCall
  464. args[0].should.equal(ctx.user._id)
  465. args[1].should.equal(ctx.newEmail)
  466. })
  467. it('refreshes features', async function (ctx) {
  468. await ctx.UserUpdater.promises.removeEmailAddress(
  469. ctx.user._id,
  470. ctx.newEmail,
  471. ctx.auditLog
  472. )
  473. sinon.assert.calledWith(
  474. ctx.FeaturesUpdater.promises.refreshFeatures,
  475. ctx.user._id
  476. )
  477. })
  478. it('handles Mongo errors', async function (ctx) {
  479. const anError = new Error('nope')
  480. ctx.db.users.updateOne.rejects(anError)
  481. await expect(
  482. ctx.UserUpdater.promises.removeEmailAddress(
  483. ctx.user._id,
  484. ctx.newEmail,
  485. ctx.auditLog
  486. )
  487. ).to.be.rejected
  488. expect(ctx.FeaturesUpdater.promises.refreshFeatures).not.to.have.been
  489. .called
  490. })
  491. it('handles missed update', async function (ctx) {
  492. ctx.db.users.updateOne.resolves({ matchedCount: 0 })
  493. await expect(
  494. ctx.UserUpdater.promises.removeEmailAddress(
  495. ctx.user._id,
  496. ctx.newEmail,
  497. ctx.auditLog
  498. )
  499. ).to.be.rejectedWith('Cannot remove email')
  500. expect(ctx.FeaturesUpdater.promises.refreshFeatures).not.to.have.been
  501. .called
  502. })
  503. it('handles an affiliation error', async function (ctx) {
  504. const anError = new Error('nope')
  505. ctx.InstitutionsAPI.promises.removeAffiliation.rejects(anError)
  506. await expect(
  507. ctx.UserUpdater.promises.removeEmailAddress(
  508. ctx.user._id,
  509. ctx.newEmail,
  510. ctx.auditLog
  511. )
  512. ).to.be.rejected
  513. expect(ctx.db.users.updateOne).not.to.have.been.called
  514. expect(ctx.FeaturesUpdater.promises.refreshFeatures).not.to.have.been
  515. .called
  516. })
  517. it('throws an error when removing the primary email', async function (ctx) {
  518. await expect(
  519. ctx.UserUpdater.promises.removeEmailAddress(
  520. ctx.user._id,
  521. ctx.user.email,
  522. ctx.auditLog
  523. )
  524. ).to.be.rejectedWith('cannot remove primary email')
  525. expect(ctx.db.users.updateOne).not.to.have.been.called
  526. expect(ctx.FeaturesUpdater.promises.refreshFeatures).not.to.have.been
  527. .called
  528. })
  529. it('validates the email', function (ctx) {
  530. expect(
  531. ctx.UserUpdater.promises.removeEmailAddress(
  532. ctx.user._id,
  533. 'baz',
  534. ctx.auditLog
  535. )
  536. ).to.be.rejectedWith('invalid email')
  537. })
  538. it('skips email validation when skipParseEmail included', async function (ctx) {
  539. const skipParseEmail = true
  540. await ctx.UserUpdater.promises.removeEmailAddress(
  541. ctx.user._id,
  542. 'baz',
  543. ctx.auditLog,
  544. skipParseEmail
  545. )
  546. })
  547. it('throws an error when skipParseEmail included but email is not a string', async function (ctx) {
  548. const skipParseEmail = true
  549. await expect(
  550. ctx.UserUpdater.promises.removeEmailAddress(
  551. ctx.user._id,
  552. 1,
  553. ctx.auditLog,
  554. skipParseEmail
  555. )
  556. ).to.be.rejectedWith('email must be a string')
  557. })
  558. it('logs the removal to the audit log', async function (ctx) {
  559. await ctx.UserUpdater.promises.removeEmailAddress(
  560. ctx.user._id,
  561. ctx.newEmail,
  562. ctx.auditLog
  563. )
  564. expect(ctx.UserAuditLogHandler.promises.addEntry).to.have.been.calledWith(
  565. ctx.user._id,
  566. 'remove-email',
  567. ctx.auditLog.initiatorId,
  568. ctx.auditLog.ipAddress,
  569. {
  570. removedEmail: ctx.newEmail,
  571. }
  572. )
  573. })
  574. it('logs the removal from script to the audit log', async function (ctx) {
  575. ctx.auditLog = {
  576. initiatorId: undefined,
  577. ipAddress: '0.0.0.0',
  578. extraInfo: {
  579. script: true,
  580. },
  581. }
  582. await ctx.UserUpdater.promises.removeEmailAddress(
  583. ctx.user._id,
  584. ctx.newEmail,
  585. ctx.auditLog
  586. )
  587. expect(ctx.UserAuditLogHandler.promises.addEntry).to.have.been.calledWith(
  588. ctx.user._id,
  589. 'remove-email',
  590. ctx.auditLog.initiatorId,
  591. ctx.auditLog.ipAddress,
  592. {
  593. removedEmail: ctx.newEmail,
  594. script: true,
  595. }
  596. )
  597. })
  598. it('calls to remove userFullEmails from AsyncLocalStorage', async function (ctx) {
  599. await ctx.UserUpdater.promises.removeEmailAddress(
  600. ctx.user._id,
  601. ctx.newEmail,
  602. ctx.auditLog
  603. )
  604. expect(ctx.AsyncLocalStorage.removeItem).to.have.been.calledWith(
  605. 'userFullEmails'
  606. )
  607. })
  608. })
  609. describe('setDefaultEmailAddress', function () {
  610. function setUserEmails(test, emails) {
  611. test.user.emails = emails
  612. test.UserGetter.promises.getUserFullEmails
  613. .withArgs(test.user._id)
  614. .resolves(emails)
  615. }
  616. beforeEach(function (ctx) {
  617. ctx.auditLog = {
  618. initiatorId: ctx.user,
  619. ipAddress: '0:0:0:0',
  620. }
  621. setUserEmails(ctx, [
  622. {
  623. email: ctx.newEmail,
  624. confirmedAt: new Date(),
  625. },
  626. ])
  627. })
  628. it('set default', async function (ctx) {
  629. await ctx.UserUpdater.promises.setDefaultEmailAddress(
  630. ctx.user._id,
  631. ctx.newEmail,
  632. false,
  633. ctx.auditLog
  634. )
  635. expect(ctx.db.users.updateOne).to.have.been.calledWith(
  636. { _id: ctx.user._id, 'emails.email': ctx.newEmail },
  637. {
  638. $set: {
  639. email: ctx.newEmail,
  640. lastPrimaryEmailCheck: sinon.match.date,
  641. },
  642. }
  643. )
  644. })
  645. it('sets the changed email in the newsletter', async function (ctx) {
  646. await ctx.UserUpdater.promises.setDefaultEmailAddress(
  647. ctx.user._id,
  648. ctx.newEmail,
  649. false,
  650. ctx.auditLog
  651. )
  652. expect(
  653. ctx.NewsletterManager.promises.changeEmail
  654. ).to.have.been.calledWith(ctx.user, ctx.newEmail)
  655. expect(ctx.Modules.promises.hooks.fire).to.have.been.calledWith(
  656. 'updateAccountEmailAddress',
  657. ctx.user._id,
  658. ctx.newEmail
  659. )
  660. })
  661. it('handles Mongo errors', async function (ctx) {
  662. ctx.db.users.updateOne = sinon.stub().rejects(Error('nope'))
  663. await expect(
  664. ctx.UserUpdater.promises.setDefaultEmailAddress(
  665. ctx.user._id,
  666. ctx.newEmail,
  667. false,
  668. ctx.auditLog
  669. )
  670. ).to.be.rejected
  671. })
  672. it('handles missed updates', async function (ctx) {
  673. ctx.db.users.updateOne.resolves({ matchedCount: 0 })
  674. await expect(
  675. ctx.UserUpdater.promises.setDefaultEmailAddress(
  676. ctx.user._id,
  677. ctx.newEmail,
  678. false,
  679. ctx.auditLog
  680. )
  681. ).to.be.rejected
  682. })
  683. it('validates the email', async function (ctx) {
  684. await expect(
  685. ctx.UserUpdater.promises.setDefaultEmailAddress(
  686. ctx.user._id,
  687. '.edu',
  688. false,
  689. ctx.auditLog
  690. )
  691. ).to.be.rejected
  692. })
  693. it('updates the audit log', async function (ctx) {
  694. await ctx.UserUpdater.promises.setDefaultEmailAddress(
  695. ctx.user._id,
  696. ctx.newEmail,
  697. false,
  698. ctx.auditLog
  699. )
  700. expect(ctx.UserAuditLogHandler.promises.addEntry).to.have.been.calledWith(
  701. ctx.user._id,
  702. 'change-primary-email',
  703. ctx.auditLog.initiatorId,
  704. ctx.auditLog.ipAddress,
  705. {
  706. newPrimaryEmail: ctx.newEmail,
  707. oldPrimaryEmail: ctx.user.email,
  708. }
  709. )
  710. })
  711. it('blocks email update if audit log returns an error', async function (ctx) {
  712. ctx.UserAuditLogHandler.promises.addEntry.rejects(new Error('oops'))
  713. await expect(
  714. ctx.UserUpdater.promises.setDefaultEmailAddress(
  715. ctx.user._id,
  716. ctx.newEmail,
  717. false,
  718. ctx.auditLog
  719. )
  720. ).to.be.rejected
  721. expect(ctx.db.users.updateOne).to.not.have.been.called
  722. })
  723. it('calls to remove userFullEmails from AsyncLocalStorage', async function (ctx) {
  724. await ctx.UserUpdater.promises.setDefaultEmailAddress(
  725. ctx.user._id,
  726. ctx.newEmail,
  727. false,
  728. ctx.auditLog
  729. )
  730. expect(ctx.AsyncLocalStorage.removeItem).to.have.been.calledWith(
  731. 'userFullEmails'
  732. )
  733. })
  734. describe('when email not confirmed', function () {
  735. beforeEach(function (ctx) {
  736. setUserEmails(ctx, [
  737. {
  738. email: ctx.newEmail,
  739. confirmedAt: null,
  740. },
  741. ])
  742. })
  743. it('should throw an error', async function (ctx) {
  744. await expect(
  745. ctx.UserUpdater.promises.setDefaultEmailAddress(
  746. ctx.user._id,
  747. ctx.newEmail,
  748. false,
  749. ctx.auditLog
  750. )
  751. ).to.be.rejectedWith(Errors.UnconfirmedEmailError)
  752. expect(ctx.db.users.updateOne).to.not.have.been.called
  753. expect(ctx.NewsletterManager.promises.changeEmail).to.not.have.been
  754. .called
  755. })
  756. })
  757. describe('when email does not belong to user', function () {
  758. beforeEach(function (ctx) {
  759. setUserEmails(ctx, [])
  760. ctx.UserUpdater.promises.updateUser = sinon.stub()
  761. })
  762. it('should callback with error', function (ctx) {
  763. ctx.UserUpdater.setDefaultEmailAddress(
  764. ctx.user._id,
  765. ctx.newEmail,
  766. false,
  767. ctx.auditLog,
  768. error => {
  769. expect(error).to.exist
  770. expect(error.name).to.equal('Error')
  771. ctx.UserUpdater.promises.updateUser.callCount.should.equal(0)
  772. ctx.NewsletterManager.promises.changeEmail.callCount.should.equal(0)
  773. }
  774. )
  775. })
  776. })
  777. describe('security alert', function () {
  778. it('should be sent to old and new email when sendSecurityAlert=true', async function (ctx) {
  779. await ctx.UserUpdater.promises.setDefaultEmailAddress(
  780. ctx.user._id,
  781. ctx.newEmail,
  782. false,
  783. ctx.auditLog,
  784. true
  785. )
  786. // Emails are sent asynchronously. Wait a bit.
  787. await setTimeout(100)
  788. ctx.EmailHandler.promises.sendEmail.callCount.should.equal(2)
  789. for (const recipient of [ctx.user.email, ctx.newEmail]) {
  790. expect(ctx.EmailHandler.promises.sendEmail).to.have.been.calledWith(
  791. 'securityAlert',
  792. sinon.match({ to: recipient })
  793. )
  794. }
  795. })
  796. it('should send to the most recently (re-)confirmed emails grouped by institution and by domain for unaffiliated emails', async function (ctx) {
  797. setUserEmails(ctx, [
  798. {
  799. email: '1@a1.uni',
  800. confirmedAt: new Date(2020, 0, 1),
  801. reConfirmedAt: new Date(2021, 2, 11),
  802. lastConfirmedAt: new Date(2021, 2, 11),
  803. default: false,
  804. affiliation: {
  805. institution: {
  806. id: 123,
  807. name: 'A1 University',
  808. },
  809. cachedConfirmedAt: '2020-01-01T18:25:01.639Z',
  810. cachedReconfirmedAt: '2021-03-11T18:25:01.639Z',
  811. },
  812. },
  813. {
  814. email: '2@a1.uni',
  815. confirmedAt: new Date(2019, 0, 1),
  816. reConfirmedAt: new Date(2022, 2, 11),
  817. lastConfirmedAt: new Date(2022, 2, 11),
  818. default: false,
  819. affiliation: {
  820. institution: {
  821. id: 123,
  822. name: 'A1 University',
  823. },
  824. cachedConfirmedAt: '2019-01-01T18:25:01.639Z',
  825. cachedReconfirmedAt: '2022-03-11T18:25:01.639Z',
  826. },
  827. },
  828. {
  829. email: '2020@foo.bar',
  830. confirmedAt: new Date(2020, 6, 1),
  831. lastConfirmedAt: new Date(2020, 6, 1),
  832. },
  833. {
  834. email: '2021@foo.bar',
  835. confirmedAt: new Date(2021, 6, 1),
  836. lastConfirmedAt: new Date(2021, 6, 1),
  837. },
  838. {
  839. email: ctx.user.email,
  840. confirmedAt: new Date(2021, 6, 1),
  841. lastConfirmedAt: new Date(2021, 6, 1),
  842. },
  843. {
  844. email: ctx.newEmail,
  845. confirmedAt: new Date(2021, 6, 1),
  846. lastConfirmedAt: new Date(2021, 6, 1),
  847. },
  848. ])
  849. await ctx.UserUpdater.promises.setDefaultEmailAddress(
  850. ctx.user._id,
  851. ctx.newEmail,
  852. false,
  853. ctx.auditLog,
  854. true
  855. )
  856. // Emails are sent asynchronously. Wait a bit.
  857. await setTimeout(100)
  858. ctx.EmailHandler.promises.sendEmail.callCount.should.equal(4)
  859. for (const recipient of [
  860. ctx.user.email,
  861. ctx.newEmail,
  862. '2@a1.uni',
  863. '2021@foo.bar',
  864. ]) {
  865. expect(ctx.EmailHandler.promises.sendEmail).to.have.been.calledWith(
  866. 'securityAlert',
  867. sinon.match({ to: recipient })
  868. )
  869. }
  870. })
  871. it('should send to the most recently (re-)confirmed emails grouped by institution and by domain for unaffiliated emails (multiple institutions and unaffiliated email domains)', async function (ctx) {
  872. setUserEmails(ctx, [
  873. {
  874. email: '1@a1.uni',
  875. confirmedAt: new Date(2020, 0, 1),
  876. reConfirmedAt: new Date(2021, 2, 11),
  877. lastConfirmedAt: new Date(2021, 2, 11),
  878. default: false,
  879. affiliation: {
  880. institution: {
  881. id: 123,
  882. name: 'A1 University',
  883. },
  884. cachedConfirmedAt: '2020-01-01T18:25:01.639Z',
  885. cachedReconfirmedAt: '2021-03-11T18:25:01.639Z',
  886. },
  887. },
  888. {
  889. email: '1@b2.uni',
  890. confirmedAt: new Date(2019, 0, 1),
  891. reConfirmedAt: new Date(2022, 2, 11),
  892. lastConfirmedAt: new Date(2022, 2, 11),
  893. default: false,
  894. affiliation: {
  895. institution: {
  896. id: 234,
  897. name: 'B2 University',
  898. },
  899. cachedConfirmedAt: '2019-01-01T18:25:01.639Z',
  900. cachedReconfirmedAt: '2022-03-11T18:25:01.639Z',
  901. },
  902. },
  903. {
  904. email: '2020@foo.bar',
  905. confirmedAt: new Date(2020, 6, 1),
  906. lastConfirmedAt: new Date(2020, 6, 1),
  907. },
  908. {
  909. email: '2021@bar.foo',
  910. confirmedAt: new Date(2021, 6, 1),
  911. lastConfirmedAt: new Date(2021, 6, 1),
  912. },
  913. {
  914. email: ctx.user.email,
  915. confirmedAt: new Date(2021, 6, 1),
  916. lastConfirmedAt: new Date(2021, 6, 1),
  917. },
  918. {
  919. email: ctx.newEmail,
  920. confirmedAt: new Date(2021, 6, 1),
  921. lastConfirmedAt: new Date(2021, 6, 1),
  922. },
  923. ])
  924. await ctx.UserUpdater.promises.setDefaultEmailAddress(
  925. ctx.user._id,
  926. ctx.newEmail,
  927. false,
  928. ctx.auditLog,
  929. true
  930. )
  931. // Emails are sent asynchronously. Wait a bit.
  932. await setTimeout(100)
  933. ctx.EmailHandler.promises.sendEmail.callCount.should.equal(6)
  934. for (const recipient of [
  935. ctx.user.email,
  936. ctx.newEmail,
  937. '1@a1.uni',
  938. '1@b2.uni',
  939. '2020@foo.bar',
  940. '2021@bar.foo',
  941. ]) {
  942. expect(ctx.EmailHandler.promises.sendEmail).to.have.been.calledWith(
  943. 'securityAlert',
  944. sinon.match({ to: recipient })
  945. )
  946. }
  947. })
  948. describe('errors', function () {
  949. const anError = new Error('oops')
  950. describe('EmailHandler', function () {
  951. beforeEach(function (ctx) {
  952. ctx.EmailHandler.promises.sendEmail.rejects(anError)
  953. })
  954. it('should log but not pass back the error', async function (ctx) {
  955. await ctx.UserUpdater.promises.setDefaultEmailAddress(
  956. ctx.user._id,
  957. ctx.newEmail,
  958. false,
  959. ctx.auditLog,
  960. true
  961. )
  962. const loggerCall = ctx.logger.error.mock.calls[0]
  963. expect(loggerCall[0]).to.deep.equal({
  964. error: anError,
  965. userId: ctx.user._id,
  966. })
  967. expect(loggerCall[1]).to.contain(
  968. 'could not send security alert email when primary email changed'
  969. )
  970. })
  971. })
  972. })
  973. })
  974. })
  975. describe('confirmEmail', function () {
  976. it('should update the email record', async function (ctx) {
  977. await ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.user.email)
  978. expect(ctx.db.users.updateOne).to.have.been.calledWith(
  979. {
  980. _id: ctx.user._id,
  981. 'emails.email': ctx.user.email,
  982. },
  983. {
  984. $set: {
  985. 'emails.$.reconfirmedAt': new Date(),
  986. },
  987. $min: {
  988. 'emails.$.confirmedAt': new Date(),
  989. },
  990. }
  991. )
  992. })
  993. it('adds affiliation', async function (ctx) {
  994. await ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
  995. ctx.InstitutionsAPI.promises.addAffiliation.calledOnce.should.equal(true)
  996. sinon.assert.calledWith(
  997. ctx.InstitutionsAPI.promises.addAffiliation,
  998. ctx.user._id,
  999. ctx.newEmail,
  1000. { confirmedAt: new Date() }
  1001. )
  1002. })
  1003. it('handles errors', async function (ctx) {
  1004. ctx.db.users.updateOne.rejects(new Error('nope'))
  1005. await expect(
  1006. ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
  1007. ).to.be.rejected
  1008. })
  1009. it('handle missed update', async function (ctx) {
  1010. ctx.db.users.updateOne.resolves({ matchedCount: 0 })
  1011. await expect(
  1012. ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
  1013. ).to.be.rejected
  1014. })
  1015. it('validates email', async function (ctx) {
  1016. expect(ctx.UserUpdater.promises.confirmEmail(ctx.user._id, '@')).to.be
  1017. .rejected
  1018. })
  1019. it('handles affiliation errors', async function (ctx) {
  1020. ctx.InstitutionsAPI.promises.addAffiliation.rejects(new Error('nope'))
  1021. await expect(
  1022. ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
  1023. ).to.be.rejected
  1024. expect(ctx.db.users.updateOne).to.not.have.been.called
  1025. })
  1026. it('refreshes features', async function (ctx) {
  1027. await ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
  1028. sinon.assert.calledWith(
  1029. ctx.FeaturesUpdater.promises.refreshFeatures,
  1030. ctx.user._id
  1031. )
  1032. })
  1033. it('should not call redundantPersonalSubscription when user is not on a commons license', async function (ctx) {
  1034. ctx.InstitutionsAPI.promises.getUserAffiliations.resolves([])
  1035. ctx.SubscriptionLocator.promises.getUserIndividualSubscription.resolves({
  1036. planCode: 'personal',
  1037. groupPlan: false,
  1038. })
  1039. await ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
  1040. sinon.assert.notCalled(
  1041. ctx.NotificationsBuilder.promises.redundantPersonalSubscription
  1042. )
  1043. })
  1044. it('calls to remove userFullEmails from AsyncLocalStorage', async function (ctx) {
  1045. await ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
  1046. expect(ctx.AsyncLocalStorage.removeItem).to.have.been.called
  1047. expect(ctx.AsyncLocalStorage.removeItem).to.have.been.calledWith(
  1048. 'userFullEmails'
  1049. )
  1050. })
  1051. describe('with institution licence and subscription', function () {
  1052. beforeEach(async function (ctx) {
  1053. ctx.affiliation = {
  1054. email: ctx.newEmail,
  1055. licence: 'pro_plus',
  1056. institution: {
  1057. id: 123,
  1058. name: 'Institution',
  1059. },
  1060. }
  1061. ctx.InstitutionsAPI.promises.getUserAffiliations.resolves([
  1062. ctx.affiliation,
  1063. { email: 'other@email.edu' },
  1064. ])
  1065. ctx.SubscriptionLocator.promises.getUserIndividualSubscription.resolves(
  1066. {
  1067. planCode: 'personal',
  1068. groupPlan: false,
  1069. }
  1070. )
  1071. })
  1072. it('creates redundant subscription notification', async function (ctx) {
  1073. await ctx.UserUpdater.promises.confirmEmail(ctx.user._id, ctx.newEmail)
  1074. sinon.assert.calledWith(
  1075. ctx.InstitutionsAPI.promises.getUserAffiliations,
  1076. ctx.user._id
  1077. )
  1078. sinon.assert.calledWith(
  1079. ctx.SubscriptionLocator.promises.getUserIndividualSubscription,
  1080. ctx.user._id
  1081. )
  1082. sinon.assert.calledWith(
  1083. ctx.NotificationsBuilder.promises.redundantPersonalSubscription,
  1084. {
  1085. institutionId: 123,
  1086. institutionName: 'Institution',
  1087. },
  1088. { _id: ctx.user._id }
  1089. )
  1090. })
  1091. })
  1092. })
  1093. describe('suspendUser', function () {
  1094. beforeEach(function (ctx) {
  1095. ctx.auditLog = {
  1096. initiatorId: 'abc123',
  1097. ip: '0.0.0.0',
  1098. }
  1099. })
  1100. it('should suspend the user', async function (ctx) {
  1101. await ctx.UserUpdater.promises.suspendUser(ctx.user._id, ctx.auditLog)
  1102. expect(ctx.db.users.updateOne).to.have.been.calledWith(
  1103. { _id: ctx.user._id, suspended: { $ne: true } },
  1104. { $set: { suspended: true } }
  1105. )
  1106. })
  1107. it('should remove sessions from redis', async function (ctx) {
  1108. await ctx.UserUpdater.promises.suspendUser(ctx.user._id, ctx.auditLog)
  1109. expect(
  1110. ctx.UserSessionsManager.promises.removeSessionsFromRedis
  1111. ).to.have.been.calledWith({ _id: ctx.user._id })
  1112. })
  1113. it('should log the suspension to the audit log', async function (ctx) {
  1114. await ctx.UserUpdater.promises.suspendUser(ctx.user._id, ctx.auditLog)
  1115. expect(ctx.UserAuditLogHandler.promises.addEntry).to.have.been.calledWith(
  1116. ctx.user._id,
  1117. 'account-suspension',
  1118. ctx.auditLog.initiatorId,
  1119. ctx.auditLog.ip,
  1120. {}
  1121. )
  1122. })
  1123. it('should fire the removeDropbox hook', async function (ctx) {
  1124. await ctx.UserUpdater.promises.suspendUser(ctx.user._id, ctx.auditLog)
  1125. expect(ctx.Modules.promises.hooks.fire).to.have.been.calledWith(
  1126. 'removeDropbox',
  1127. ctx.user._id,
  1128. 'account-suspension'
  1129. )
  1130. })
  1131. it('should handle not finding a record to update', async function (ctx) {
  1132. ctx.db.users.updateOne.resolves({ matchedCount: 0 })
  1133. await expect(
  1134. ctx.UserUpdater.promises.suspendUser(ctx.user._id, ctx.auditLog)
  1135. ).to.be.rejectedWith(Errors.NotFoundError)
  1136. })
  1137. })
  1138. })