UserDeleterTests.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629
  1. const { expect } = require('chai')
  2. const sinon = require('sinon')
  3. const tk = require('timekeeper')
  4. const moment = require('moment')
  5. const SandboxedModule = require('sandboxed-module')
  6. const Errors = require('../../../../app/src/Features/Errors/Errors')
  7. const ObjectId = require('mongoose').Types.ObjectId
  8. const { User } = require('../helpers/models/User')
  9. const { DeletedUser } = require('../helpers/models/DeletedUser')
  10. const modulePath = '../../../../app/src/Features/User/UserDeleter.js'
  11. describe('UserDeleter', function () {
  12. beforeEach(function () {
  13. tk.freeze(Date.now())
  14. this.userId = new ObjectId()
  15. this.ipAddress = '1.2.3.4'
  16. this.UserMock = sinon.mock(User)
  17. this.DeletedUserMock = sinon.mock(DeletedUser)
  18. this.mockedUser = sinon.mock(
  19. new User({
  20. _id: this.userId,
  21. email: 'bob@bob.com',
  22. lastLoggedIn: Date.now() + 1000,
  23. signUpDate: Date.now() + 2000,
  24. loginCount: 10,
  25. overleaf: {
  26. id: 1234,
  27. },
  28. refered_users: ['wombat', 'potato'],
  29. refered_user_count: 2,
  30. referal_id: ['giraffe'],
  31. })
  32. )
  33. this.user = this.mockedUser.object
  34. this.NewsletterManager = {
  35. promises: {
  36. unsubscribe: sinon.stub().resolves(),
  37. },
  38. }
  39. this.ProjectDeleter = {
  40. promises: {
  41. deleteUsersProjects: sinon.stub().resolves(),
  42. },
  43. }
  44. this.SubscriptionHandler = {
  45. promises: {
  46. cancelSubscription: sinon.stub().resolves(),
  47. },
  48. }
  49. this.SubscriptionUpdater = {
  50. promises: {
  51. removeUserFromAllGroups: sinon.stub().resolves(),
  52. },
  53. }
  54. this.SubscriptionLocator = {
  55. promises: {
  56. getUsersSubscription: sinon.stub().resolves(),
  57. },
  58. }
  59. this.UserMembershipsHandler = {
  60. promises: {
  61. removeUserFromAllEntities: sinon.stub().resolves(),
  62. },
  63. }
  64. this.UserSessionsManager = {
  65. promises: {
  66. removeSessionsFromRedis: sinon.stub().resolves(),
  67. },
  68. }
  69. this.InstitutionsApi = {
  70. promises: {
  71. deleteAffiliations: sinon.stub().resolves(),
  72. },
  73. }
  74. this.UserAuditLogEntry = {
  75. deleteMany: sinon.stub().returns({ exec: sinon.stub().resolves() }),
  76. }
  77. this.Modules = {
  78. promises: { hooks: { fire: sinon.stub().resolves() } },
  79. }
  80. this.Feedback = {
  81. deleteMany: sinon.stub().returns({ exec: sinon.stub().resolves() }),
  82. }
  83. this.OnboardingDataCollectionManager = {
  84. deleteOnboardingDataCollection: sinon.stub().resolves(),
  85. }
  86. this.EmailHandler = {
  87. promises: {
  88. sendEmail: sinon.stub().resolves(),
  89. },
  90. }
  91. this.UserAuditLogHandler = {
  92. promises: {
  93. addEntry: sinon.stub().resolves(),
  94. },
  95. }
  96. this.UserDeleter = SandboxedModule.require(modulePath, {
  97. requires: {
  98. '../../models/User': { User },
  99. '../../models/DeletedUser': { DeletedUser },
  100. '../../models/Feedback': { Feedback: this.Feedback },
  101. '../Newsletter/NewsletterManager': this.NewsletterManager,
  102. './UserSessionsManager': this.UserSessionsManager,
  103. '../Subscription/SubscriptionHandler': this.SubscriptionHandler,
  104. '../Subscription/SubscriptionUpdater': this.SubscriptionUpdater,
  105. '../Subscription/SubscriptionLocator': this.SubscriptionLocator,
  106. '../UserMembership/UserMembershipsHandler': this.UserMembershipsHandler,
  107. '../Project/ProjectDeleter': this.ProjectDeleter,
  108. '../Institutions/InstitutionsAPI': this.InstitutionsApi,
  109. '../../models/UserAuditLogEntry': {
  110. UserAuditLogEntry: this.UserAuditLogEntry,
  111. },
  112. './UserAuditLogHandler': this.UserAuditLogHandler,
  113. '../../infrastructure/Modules': this.Modules,
  114. '../OnboardingDataCollection/OnboardingDataCollectionManager':
  115. this.OnboardingDataCollectionManager,
  116. '../Email/EmailHandler': this.EmailHandler,
  117. },
  118. })
  119. })
  120. afterEach(function () {
  121. this.DeletedUserMock.restore()
  122. this.UserMock.restore()
  123. this.mockedUser.restore()
  124. tk.reset()
  125. })
  126. describe('deleteUser', function () {
  127. beforeEach(function () {
  128. this.UserMock.expects('findById')
  129. .withArgs(this.userId)
  130. .chain('exec')
  131. .resolves(this.user)
  132. })
  133. describe('when the user can be deleted', function () {
  134. beforeEach(function () {
  135. this.deletedUser = {
  136. user: this.user,
  137. deleterData: {
  138. deletedAt: new Date(),
  139. deletedUserId: this.userId,
  140. deleterIpAddress: this.ipAddress,
  141. deleterId: undefined,
  142. deletedUserLastLoggedIn: this.user.lastLoggedIn,
  143. deletedUserSignUpDate: this.user.signUpDate,
  144. deletedUserLoginCount: this.user.loginCount,
  145. deletedUserReferralId: this.user.referal_id,
  146. deletedUserReferredUsers: this.user.refered_users,
  147. deletedUserReferredUserCount: this.user.refered_user_count,
  148. deletedUserOverleafId: this.user.overleaf.id,
  149. },
  150. }
  151. })
  152. describe('when only the ip address is passed', function () {
  153. beforeEach(function () {
  154. this.DeletedUserMock.expects('updateOne')
  155. .withArgs(
  156. { 'deleterData.deletedUserId': this.userId },
  157. this.deletedUser,
  158. { upsert: true }
  159. )
  160. .chain('exec')
  161. .resolves()
  162. })
  163. describe('when unsubscribing in Mailchimp succeeds', function () {
  164. beforeEach(function () {
  165. this.UserMock.expects('deleteOne')
  166. .withArgs({ _id: this.userId })
  167. .chain('exec')
  168. .resolves()
  169. })
  170. it('should find and the user in mongo by its id', async function () {
  171. await this.UserDeleter.promises.deleteUser(this.userId, {
  172. ipAddress: this.ipAddress,
  173. })
  174. this.UserMock.verify()
  175. })
  176. it('should delete the user from mailchimp', async function () {
  177. await this.UserDeleter.promises.deleteUser(this.userId, {
  178. ipAddress: this.ipAddress,
  179. })
  180. expect(
  181. this.NewsletterManager.promises.unsubscribe
  182. ).to.have.been.calledWith(this.user, { delete: true })
  183. })
  184. it('should delete all the projects of a user', async function () {
  185. await this.UserDeleter.promises.deleteUser(this.userId, {
  186. ipAddress: this.ipAddress,
  187. })
  188. expect(
  189. this.ProjectDeleter.promises.deleteUsersProjects
  190. ).to.have.been.calledWith(this.userId)
  191. })
  192. it("should cancel the user's subscription", async function () {
  193. await this.UserDeleter.promises.deleteUser(this.userId, {
  194. ipAddress: this.ipAddress,
  195. })
  196. expect(
  197. this.SubscriptionHandler.promises.cancelSubscription
  198. ).to.have.been.calledWith(this.user)
  199. })
  200. it('should delete user affiliations', async function () {
  201. await this.UserDeleter.promises.deleteUser(this.userId, {
  202. ipAddress: this.ipAddress,
  203. })
  204. expect(
  205. this.InstitutionsApi.promises.deleteAffiliations
  206. ).to.have.been.calledWith(this.userId)
  207. })
  208. it('should fire the deleteUser hook for modules', async function () {
  209. await this.UserDeleter.promises.deleteUser(this.userId, {
  210. ipAddress: this.ipAddress,
  211. })
  212. expect(this.Modules.promises.hooks.fire).to.have.been.calledWith(
  213. 'deleteUser',
  214. this.userId
  215. )
  216. })
  217. it('should stop the user sessions', async function () {
  218. await this.UserDeleter.promises.deleteUser(this.userId, {
  219. ipAddress: this.ipAddress,
  220. })
  221. expect(
  222. this.UserSessionsManager.promises.removeSessionsFromRedis
  223. ).to.have.been.calledWith(this.user)
  224. })
  225. it('should remove user from group subscriptions', async function () {
  226. await this.UserDeleter.promises.deleteUser(this.userId, {
  227. ipAddress: this.ipAddress,
  228. })
  229. expect(
  230. this.SubscriptionUpdater.promises.removeUserFromAllGroups
  231. ).to.have.been.calledWith(this.userId)
  232. })
  233. it('should remove user memberships', async function () {
  234. await this.UserDeleter.promises.deleteUser(this.userId, {
  235. ipAddress: this.ipAddress,
  236. })
  237. expect(
  238. this.UserMembershipsHandler.promises.removeUserFromAllEntities
  239. ).to.have.been.calledWith(this.userId)
  240. })
  241. it('rejects if the user is a subscription admin', async function () {
  242. this.SubscriptionLocator.promises.getUsersSubscription.rejects({
  243. _id: 'some-subscription',
  244. })
  245. await expect(this.UserDeleter.promises.deleteUser(this.userId, {}))
  246. .to.be.rejected
  247. })
  248. it('should create a deletedUser', async function () {
  249. await this.UserDeleter.promises.deleteUser(this.userId, {
  250. ipAddress: this.ipAddress,
  251. })
  252. this.DeletedUserMock.verify()
  253. })
  254. it('should email the user', async function () {
  255. await this.UserDeleter.promises.deleteUser(this.userId, {
  256. ipAddress: this.ipAddress,
  257. })
  258. const emailOptions = {
  259. to: 'bob@bob.com',
  260. action: 'account deleted',
  261. actionDescribed: 'your Overleaf account was deleted',
  262. }
  263. expect(
  264. this.EmailHandler.promises.sendEmail
  265. ).to.have.been.calledWith('securityAlert', emailOptions)
  266. })
  267. it('should add an audit log entry', async function () {
  268. await this.UserDeleter.promises.deleteUser(this.userId, {
  269. ipAddress: this.ipAddress,
  270. })
  271. expect(
  272. this.UserAuditLogHandler.promises.addEntry
  273. ).to.have.been.calledWith(
  274. this.userId,
  275. 'delete-account',
  276. this.userId,
  277. this.ipAddress
  278. )
  279. })
  280. })
  281. describe('when unsubscribing from mailchimp fails', function () {
  282. beforeEach(function () {
  283. this.NewsletterManager.promises.unsubscribe.rejects(
  284. new Error('something went wrong')
  285. )
  286. })
  287. it('should return an error and not delete the user', async function () {
  288. await expect(
  289. this.UserDeleter.promises.deleteUser(this.userId, {
  290. ipAddress: this.ipAddress,
  291. })
  292. ).to.be.rejected
  293. this.UserMock.verify()
  294. })
  295. })
  296. describe('when called as a callback', function () {
  297. beforeEach(function () {
  298. this.UserMock.expects('deleteOne')
  299. .withArgs({ _id: this.userId })
  300. .chain('exec')
  301. .resolves()
  302. })
  303. it('should delete the user', function (done) {
  304. this.UserDeleter.deleteUser(
  305. this.userId,
  306. { ipAddress: this.ipAddress },
  307. err => {
  308. expect(err).not.to.exist
  309. this.UserMock.verify()
  310. this.DeletedUserMock.verify()
  311. done()
  312. }
  313. )
  314. })
  315. })
  316. })
  317. describe('when a user and IP address are specified', function () {
  318. beforeEach(function () {
  319. this.ipAddress = '1.2.3.4'
  320. this.deleterId = new ObjectId()
  321. this.deletedUser.deleterData.deleterIpAddress = this.ipAddress
  322. this.deletedUser.deleterData.deleterId = this.deleterId
  323. this.DeletedUserMock.expects('updateOne')
  324. .withArgs(
  325. { 'deleterData.deletedUserId': this.userId },
  326. this.deletedUser,
  327. { upsert: true }
  328. )
  329. .chain('exec')
  330. .resolves()
  331. this.UserMock.expects('deleteOne')
  332. .withArgs({ _id: this.userId })
  333. .chain('exec')
  334. .resolves()
  335. })
  336. it('should add the deleted user id and ip address to the deletedUser', async function () {
  337. await this.UserDeleter.promises.deleteUser(this.userId, {
  338. deleterUser: { _id: this.deleterId },
  339. ipAddress: this.ipAddress,
  340. })
  341. this.DeletedUserMock.verify()
  342. })
  343. it('should add an audit log entry', async function () {
  344. await this.UserDeleter.promises.deleteUser(this.userId, {
  345. deleterUser: { _id: this.deleterId },
  346. ipAddress: this.ipAddress,
  347. })
  348. expect(
  349. this.UserAuditLogHandler.promises.addEntry
  350. ).to.have.been.calledWith(
  351. this.userId,
  352. 'delete-account',
  353. this.deleterId,
  354. this.ipAddress
  355. )
  356. })
  357. describe('when called as a callback', function () {
  358. it('should delete the user', function (done) {
  359. this.UserDeleter.deleteUser(
  360. this.userId,
  361. {
  362. deleterUser: { _id: this.deleterId },
  363. ipAddress: this.ipAddress,
  364. },
  365. err => {
  366. expect(err).not.to.exist
  367. this.UserMock.verify()
  368. this.DeletedUserMock.verify()
  369. done()
  370. }
  371. )
  372. })
  373. })
  374. })
  375. })
  376. describe('when the user cannot be deleted because they are a subscription admin', function () {
  377. beforeEach(function () {
  378. this.SubscriptionLocator.promises.getUsersSubscription.resolves({
  379. _id: 'some-subscription',
  380. })
  381. })
  382. it('fails with a SubscriptionAdminDeletionError', async function () {
  383. await expect(
  384. this.UserDeleter.promises.deleteUser(this.userId)
  385. ).to.be.rejectedWith(Errors.SubscriptionAdminDeletionError)
  386. })
  387. it('should not create a deletedUser', async function () {
  388. await expect(this.UserDeleter.promises.deleteUser(this.userId)).to.be
  389. .rejected
  390. this.DeletedUserMock.verify()
  391. })
  392. it('should not remove the user from mongo', async function () {
  393. await expect(this.UserDeleter.promises.deleteUser(this.userId)).to.be
  394. .rejected
  395. this.UserMock.verify()
  396. })
  397. })
  398. })
  399. describe('ensureCanDeleteUser', function () {
  400. it('should not return error when user can be deleted', async function () {
  401. this.SubscriptionLocator.promises.getUsersSubscription.resolves(null)
  402. let error
  403. try {
  404. await this.UserDeleter.promises.ensureCanDeleteUser(this.user)
  405. } catch (e) {
  406. error = e
  407. } finally {
  408. expect(error).not.to.exist
  409. }
  410. })
  411. it('should return custom error when user is group admin', async function () {
  412. this.SubscriptionLocator.promises.getUsersSubscription.resolves({
  413. _id: '123abc',
  414. })
  415. let error
  416. try {
  417. await this.UserDeleter.promises.ensureCanDeleteUser(this.user)
  418. } catch (e) {
  419. error = e
  420. } finally {
  421. expect(error).to.be.instanceof(Errors.SubscriptionAdminDeletionError)
  422. }
  423. })
  424. it('propagates errors', async function () {
  425. this.SubscriptionLocator.promises.getUsersSubscription.rejects(
  426. new Error('Some error')
  427. )
  428. let error
  429. try {
  430. await this.UserDeleter.promises.ensureCanDeleteUser(this.user)
  431. } catch (e) {
  432. error = e
  433. } finally {
  434. expect(error).to.be.instanceof(Error)
  435. }
  436. })
  437. })
  438. describe('expireDeletedUsersAfterDuration', function () {
  439. const userId1 = new ObjectId()
  440. const userId2 = new ObjectId()
  441. beforeEach(function () {
  442. this.deletedUsers = [
  443. {
  444. user: { _id: userId1 },
  445. deleterData: { deletedUserId: userId1 },
  446. save: sinon.stub().resolves(),
  447. },
  448. {
  449. user: { _id: userId2 },
  450. deleterData: { deletedUserId: userId2 },
  451. save: sinon.stub().resolves(),
  452. },
  453. ]
  454. this.DeletedUserMock.expects('find')
  455. .withArgs({
  456. 'deleterData.deletedAt': {
  457. $lt: new Date(moment().subtract(90, 'days')),
  458. },
  459. user: {
  460. $ne: null,
  461. },
  462. })
  463. .chain('exec')
  464. .resolves(this.deletedUsers)
  465. for (const deletedUser of this.deletedUsers) {
  466. this.DeletedUserMock.expects('findOne')
  467. .withArgs({
  468. 'deleterData.deletedUserId': deletedUser.deleterData.deletedUserId,
  469. })
  470. .chain('exec')
  471. .resolves(deletedUser)
  472. }
  473. })
  474. it('clears data from all deleted users', async function () {
  475. await this.UserDeleter.promises.expireDeletedUsersAfterDuration()
  476. for (const deletedUser of this.deletedUsers) {
  477. expect(deletedUser.user).to.be.undefined
  478. expect(deletedUser.save.called).to.be.true
  479. }
  480. })
  481. it('deletes audit logs for all deleted users', async function () {
  482. await this.UserDeleter.promises.expireDeletedUsersAfterDuration()
  483. for (const deletedUser of this.deletedUsers) {
  484. expect(this.UserAuditLogEntry.deleteMany).to.have.been.calledWith({
  485. userId: deletedUser.deleterData.deletedUserId,
  486. })
  487. }
  488. })
  489. })
  490. describe('expireDeletedUser', function () {
  491. beforeEach(function () {
  492. this.mockedDeletedUser = sinon.mock(
  493. new DeletedUser({
  494. user: this.user,
  495. deleterData: {
  496. deleterIpAddress: '1.1.1.1',
  497. deletedUserId: this.userId,
  498. },
  499. })
  500. )
  501. this.deletedUser = this.mockedDeletedUser.object
  502. this.mockedDeletedUser.expects('save').resolves()
  503. this.DeletedUserMock.expects('findOne')
  504. .withArgs({ 'deleterData.deletedUserId': this.userId })
  505. .chain('exec')
  506. .resolves(this.deletedUser)
  507. })
  508. afterEach(function () {
  509. this.mockedDeletedUser.restore()
  510. })
  511. it('should find the user by user ID', async function () {
  512. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  513. this.DeletedUserMock.verify()
  514. })
  515. it('should remove the user data from mongo', async function () {
  516. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  517. expect(this.deletedUser.user).not.to.exist
  518. })
  519. it('should remove the IP address from mongo', async function () {
  520. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  521. expect(this.deletedUser.deleterData.ipAddress).not.to.exist
  522. })
  523. it('should not delete other deleterData fields', async function () {
  524. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  525. expect(this.deletedUser.deleterData.deletedUserId).to.equal(this.userId)
  526. })
  527. it('should save the record to mongo', async function () {
  528. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  529. this.mockedDeletedUser.verify()
  530. })
  531. it('should fire the expireDeletedUser hook for modules', async function () {
  532. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  533. expect(this.Modules.promises.hooks.fire).to.have.been.calledWith(
  534. 'expireDeletedUser',
  535. this.userId
  536. )
  537. })
  538. it('should delete Feeback', async function () {
  539. await this.UserDeleter.promises.expireDeletedUser(this.userId)
  540. expect(this.Feedback.deleteMany).to.have.been.calledWith({
  541. userId: this.userId,
  542. })
  543. })
  544. describe('when called as a callback', function () {
  545. it('should expire the user', function (done) {
  546. this.UserDeleter.expireDeletedUser(this.userId, err => {
  547. expect(err).not.to.exist
  548. this.DeletedUserMock.verify()
  549. this.mockedDeletedUser.verify()
  550. expect(this.deletedUser.user).not.to.exist
  551. expect(this.deletedUser.deleterData.ipAddress).not.to.exist
  552. done()
  553. })
  554. })
  555. })
  556. })
  557. })