SAMLIdentityManager.test.mjs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785
  1. import { vi, expect } from 'vitest'
  2. import mongodb from 'mongodb-legacy'
  3. import sinon from 'sinon'
  4. import Errors from '../../../../app/src/Features/Errors/Errors.js'
  5. const { ObjectId } = mongodb
  6. const modulePath = '../../../../app/src/Features/User/SAMLIdentityManager.mjs'
  7. vi.mock('../../../../app/src/Features/Errors/Errors.js', () =>
  8. vi.importActual('../../../../app/src/Features/Errors/Errors.js')
  9. )
  10. describe('SAMLIdentityManager', function () {
  11. const linkedEmail = 'another@example.com'
  12. beforeEach(async function (ctx) {
  13. ctx.userId = '6005c75b12cbcaf771f4a105'
  14. ctx.user = {
  15. _id: ctx.userId,
  16. email: 'not-linked@overleaf.com',
  17. emails: [{ email: 'not-linked@overleaf.com' }],
  18. samlIdentifiers: [],
  19. }
  20. ctx.auditLog = {
  21. initiatorId: ctx.userId,
  22. ipAddress: '0:0:0:0',
  23. }
  24. ctx.userAlreadyLinked = {
  25. _id: '6005c7a012cbcaf771f4a106',
  26. email: 'linked@overleaf.com',
  27. emails: [{ email: 'linked@overleaf.com', samlProviderId: '1' }],
  28. samlIdentifiers: [{ externalUserId: 'linked-id', providerId: '1' }],
  29. }
  30. ctx.userEmailExists = {
  31. _id: '6005c7a012cbcaf771f4a107',
  32. email: 'exists@overleaf.com',
  33. emails: [{ email: 'exists@overleaf.com' }],
  34. samlIdentifiers: [],
  35. }
  36. ctx.institution = {
  37. name: 'Overleaf University',
  38. }
  39. ctx.InstitutionsAPI = {
  40. promises: {
  41. addEntitlement: sinon.stub().resolves(),
  42. removeEntitlement: sinon.stub().resolves(),
  43. },
  44. }
  45. ctx.logger = {
  46. error: sinon.stub(),
  47. }
  48. vi.doMock('@overleaf/logger', () => ({
  49. default: ctx.logger,
  50. }))
  51. vi.doMock('mongodb-legacy', () => ({
  52. default: { ObjectId },
  53. }))
  54. vi.doMock('../../../../app/src/Features/Email/EmailHandler', () => ({
  55. default: (ctx.EmailHandler = {
  56. sendEmail: sinon.stub().yields(),
  57. }),
  58. }))
  59. vi.doMock(
  60. '../../../../app/src/Features/Notifications/NotificationsBuilder',
  61. () => ({
  62. default: (ctx.NotificationsBuilder = {
  63. promises: {
  64. redundantPersonalSubscription: sinon
  65. .stub()
  66. .returns({ create: sinon.stub().resolves() }),
  67. },
  68. }),
  69. })
  70. )
  71. vi.doMock(
  72. '../../../../app/src/Features/Subscription/SubscriptionLocator',
  73. () => ({
  74. default: (ctx.SubscriptionLocator = {
  75. promises: {
  76. getUserIndividualSubscription: sinon.stub().resolves(),
  77. },
  78. }),
  79. })
  80. )
  81. vi.doMock('../../../../app/src/models/User', () => ({
  82. User: (ctx.User = {
  83. findOneAndUpdate: sinon.stub().returns({
  84. exec: sinon.stub().resolves(ctx.user),
  85. }),
  86. findOne: sinon.stub().returns({
  87. exec: sinon.stub().resolves(),
  88. }),
  89. updateOne: sinon.stub().returns({
  90. exec: sinon.stub().resolves(),
  91. }),
  92. }),
  93. }))
  94. vi.doMock('../../../../app/src/Features/User/UserAuditLogHandler', () => ({
  95. default: (ctx.UserAuditLogHandler = {
  96. promises: {
  97. addEntry: sinon.stub().resolves(),
  98. },
  99. }),
  100. }))
  101. vi.doMock('../../../../app/src/Features/User/UserGetter', () => ({
  102. default: (ctx.UserGetter = {
  103. getUser: sinon.stub(),
  104. promises: {
  105. getUser: sinon.stub().resolves(ctx.user),
  106. getUserByAnyEmail: sinon.stub().resolves(),
  107. getUserFullEmails: sinon.stub().resolves(),
  108. },
  109. }),
  110. }))
  111. vi.doMock('../../../../app/src/Features/User/UserUpdater', () => ({
  112. default: (ctx.UserUpdater = {
  113. addEmailAddress: sinon.stub(),
  114. promises: {
  115. addEmailAddress: sinon.stub().resolves(),
  116. confirmEmail: sinon.stub().resolves(),
  117. updateUser: sinon.stub().resolves(),
  118. },
  119. }),
  120. }))
  121. vi.doMock(
  122. '../../../../app/src/Features/Institutions/InstitutionsAPI',
  123. () => ({
  124. default: ctx.InstitutionsAPI,
  125. })
  126. )
  127. ctx.SAMLIdentityManager = (await import(modulePath)).default
  128. })
  129. describe('getUser', function () {
  130. it('should throw an error if missing all of: provider ID, external user ID, attribute', async function (ctx) {
  131. let error
  132. try {
  133. await ctx.SAMLIdentityManager.getUser(undefined, undefined, undefined)
  134. } catch (e) {
  135. error = e
  136. } finally {
  137. expect(error).to.exist
  138. expect(error.message).to.equal(
  139. 'invalid arguments: providerId: undefined, externalUserId: undefined, userIdAttribute: undefined'
  140. )
  141. }
  142. })
  143. it('should throw an error if missing provider ID', async function (ctx) {
  144. let error
  145. try {
  146. await ctx.SAMLIdentityManager.getUser(undefined, 'id123', 'someAttr')
  147. } catch (e) {
  148. error = e
  149. } finally {
  150. expect(error).to.exist
  151. expect(error.message).to.equal(
  152. 'invalid arguments: providerId: undefined, externalUserId: id123, userIdAttribute: someAttr'
  153. )
  154. }
  155. })
  156. it('should throw an error if missing external user ID', async function (ctx) {
  157. let error
  158. try {
  159. await ctx.SAMLIdentityManager.getUser('123', null, 'someAttr')
  160. } catch (e) {
  161. error = e
  162. } finally {
  163. expect(error).to.exist
  164. }
  165. })
  166. it('should throw an error if missing attribute', async function (ctx) {
  167. let error
  168. try {
  169. await ctx.SAMLIdentityManager.getUser('123', 'id123', undefined)
  170. } catch (e) {
  171. error = e
  172. } finally {
  173. expect(error).to.exist
  174. expect(error.message).to.equal(
  175. 'invalid arguments: providerId: 123, externalUserId: id123, userIdAttribute: undefined'
  176. )
  177. }
  178. })
  179. })
  180. describe('linkAccounts', function () {
  181. describe('errors', function () {
  182. beforeEach(function (ctx) {
  183. // first call is to get userWithProvider; should be falsy
  184. ctx.UserGetter.promises.getUser.onFirstCall().resolves()
  185. ctx.UserGetter.promises.getUser.onSecondCall().resolves(ctx.user)
  186. })
  187. it('should throw an error if missing all data', async function (ctx) {
  188. let error
  189. try {
  190. await ctx.SAMLIdentityManager.linkAccounts(null, null, null)
  191. } catch (e) {
  192. error = e
  193. } finally {
  194. expect(error).to.exist
  195. }
  196. })
  197. describe('linking data', function () {
  198. const requiredData = {
  199. externalUserId: 'someUniqueId',
  200. institutionEmail: 'user@example.com',
  201. providerId: '123',
  202. userIdAttribute: 'attribute',
  203. }
  204. for (const [data] of Object.entries(requiredData)) {
  205. const testData = { ...requiredData }
  206. delete testData[data]
  207. let error
  208. it(`should throw an error when missing ${data}`, async function (ctx) {
  209. try {
  210. await ctx.SAMLIdentityManager.linkAccounts('123', testData, {})
  211. } catch (e) {
  212. error = e
  213. } finally {
  214. expect(error).to.exist
  215. expect(error.message).to.contain(
  216. 'missing data when linking institution SSO'
  217. )
  218. }
  219. })
  220. }
  221. })
  222. describe('when email is already associated with another Overleaf account', function () {
  223. beforeEach(function (ctx) {
  224. ctx.UserGetter.promises.getUserByAnyEmail.resolves(
  225. ctx.userEmailExists
  226. )
  227. })
  228. it('should throw an EmailExistsError error', async function (ctx) {
  229. let error
  230. try {
  231. await ctx.SAMLIdentityManager.linkAccounts(
  232. '6005c75b12cbcaf771f4a105',
  233. {
  234. externalUserId: 'not-linked-id',
  235. institutionEmail: 'exists@overleaf.com',
  236. universityId: 'provider-id',
  237. universityName: 'provider-name',
  238. hasEntitlement: true,
  239. userIdAttribute: 'someAttribute',
  240. },
  241. {
  242. intiatorId: '6005c75b12cbcaf771f4a105',
  243. ip: '0:0:0:0',
  244. }
  245. )
  246. } catch (e) {
  247. error = e
  248. } finally {
  249. expect(error).to.be.instanceof(Errors.EmailExistsError)
  250. expect(ctx.User.findOneAndUpdate).to.not.have.been.called
  251. }
  252. })
  253. })
  254. describe('when email is not affiliated', function () {
  255. beforeEach(function (ctx) {
  256. ctx.UserGetter.promises.getUserByAnyEmail.resolves(ctx.user)
  257. ctx.UserGetter.promises.getUserFullEmails.resolves([
  258. {
  259. email: 'not-affiliated@overleaf.com',
  260. },
  261. ])
  262. })
  263. it('should throw SAMLEmailNotAffiliatedError', async function (ctx) {
  264. let error
  265. try {
  266. await ctx.SAMLIdentityManager.linkAccounts(
  267. '6005c75b12cbcaf771f4a105',
  268. {
  269. externalUserId: 'not-linked-id',
  270. institutionEmail: 'not-affiliated@overleaf.com',
  271. universityId: 'provider-id',
  272. universityName: 'provider-name',
  273. hasEntitlement: true,
  274. userIdAttribute: 'someAttribute',
  275. },
  276. {
  277. intiatorId: 'user-id-1',
  278. ip: '0:0:0:0',
  279. }
  280. )
  281. } catch (e) {
  282. error = e
  283. } finally {
  284. expect(error).to.be.instanceof(Errors.SAMLEmailNotAffiliatedError)
  285. expect(ctx.User.findOneAndUpdate).to.not.have.been.called
  286. }
  287. })
  288. })
  289. describe('when email is affiliated with another institution', function () {
  290. beforeEach(function (ctx) {
  291. ctx.UserGetter.promises.getUserByAnyEmail.resolves(ctx.user)
  292. ctx.UserGetter.promises.getUserFullEmails.resolves([
  293. {
  294. email: 'affiliated@overleaf.com',
  295. affiliation: { institution: { id: '987' } },
  296. },
  297. ])
  298. })
  299. it('should throw SAMLEmailAffiliatedWithAnotherInstitutionError', async function (ctx) {
  300. let error
  301. try {
  302. await ctx.SAMLIdentityManager.linkAccounts(
  303. '6005c75b12cbcaf771f4a105',
  304. {
  305. externalUserId: 'not-linked-id',
  306. institutionEmail: 'affiliated@overleaf.com',
  307. universityId: 'provider-id',
  308. universityName: 'provider-name',
  309. hasEntitlement: true,
  310. userIdAttribute: 'someAttribute',
  311. },
  312. {
  313. intiatorId: 'user-id-1',
  314. ip: '0:0:0:0',
  315. }
  316. )
  317. } catch (e) {
  318. error = e
  319. } finally {
  320. expect(error).to.be.instanceof(
  321. Errors.SAMLEmailAffiliatedWithAnotherInstitutionError
  322. )
  323. expect(ctx.User.findOneAndUpdate).to.not.have.been.called
  324. }
  325. })
  326. })
  327. describe('when institution identifier is already associated with another Overleaf account', function () {
  328. beforeEach(function (ctx) {
  329. ctx.UserGetter.promises.getUserByAnyEmail.resolves(
  330. ctx.userAlreadyLinked
  331. )
  332. })
  333. it('should throw an SAMLIdentityExistsError error', async function (ctx) {
  334. let error
  335. try {
  336. await ctx.SAMLIdentityManager.linkAccounts(
  337. '6005c75b12cbcaf771f4a105',
  338. {
  339. externalUserId: 'already-linked-id',
  340. institutionEmail: 'linked@overleaf.com',
  341. universityId: 'provider-id',
  342. universityName: 'provider-name',
  343. hasEntitlement: true,
  344. userIdAttribute: 'someAttribute',
  345. },
  346. {
  347. intiatorId: '6005c75b12cbcaf771f4a105',
  348. ip: '0:0:0:0',
  349. }
  350. )
  351. } catch (e) {
  352. error = e
  353. } finally {
  354. expect(error).to.be.instanceof(Errors.SAMLIdentityExistsError)
  355. expect(ctx.User.findOneAndUpdate).to.not.have.been.called
  356. }
  357. })
  358. })
  359. describe('when institution provider is already associated with the user', function () {
  360. beforeEach(function (ctx) {
  361. // first call is to get userWithProvider; resolves with any user
  362. ctx.UserGetter.promises.getUser.onFirstCall().resolves(ctx.user)
  363. })
  364. it('should throw an SAMLAlreadyLinkedError error', async function (ctx) {
  365. let error
  366. try {
  367. await ctx.SAMLIdentityManager.linkAccounts(
  368. '6005c75b12cbcaf771f4a105',
  369. {
  370. externalUserId: 'already-linked-id',
  371. institutionEmail: 'linked@overleaf.com',
  372. universityId: 123456,
  373. universityName: 'provider-name',
  374. hasEntitlement: true,
  375. userIdAttribute: 'someAttribute',
  376. },
  377. {
  378. intiatorId: '6005c75b12cbcaf771f4a105',
  379. ip: '0:0:0:0',
  380. }
  381. )
  382. } catch (e) {
  383. error = e
  384. } finally {
  385. expect(
  386. ctx.UserGetter.promises.getUser
  387. ).to.have.been.calledWithMatch({
  388. _id: new ObjectId('6005c75b12cbcaf771f4a105'),
  389. 'samlIdentifiers.providerId': '123456',
  390. })
  391. expect(error).to.be.instanceof(Errors.SAMLAlreadyLinkedError)
  392. expect(ctx.User.findOneAndUpdate).to.not.have.been.called
  393. }
  394. })
  395. })
  396. it('should pass back errors via UserAuditLogHandler', async function (ctx) {
  397. let error
  398. const anError = new Error('oops')
  399. ctx.UserAuditLogHandler.promises.addEntry.rejects(anError)
  400. try {
  401. await ctx.SAMLIdentityManager.linkAccounts(
  402. ctx.user._id,
  403. {
  404. externalUserId: 'externalUserId',
  405. institutionEmail: ctx.user.email,
  406. universityId: '1',
  407. universityName: 'Overleaf University',
  408. hasEntitlement: false,
  409. userIdAttribute: 'someAttribute',
  410. },
  411. {
  412. intiatorId: '6005c75b12cbcaf771f4a105',
  413. ipAddress: '0:0:0:0',
  414. }
  415. )
  416. } catch (e) {
  417. error = e
  418. } finally {
  419. expect(error).to.exist
  420. expect(error).to.equal(anError)
  421. expect(ctx.EmailHandler.sendEmail).to.not.have.been.called
  422. expect(ctx.User.updateOne).to.not.have.been.called
  423. }
  424. })
  425. })
  426. describe('success', function () {
  427. beforeEach(function (ctx) {
  428. // first call is to get userWithProvider; should be falsy
  429. ctx.UserGetter.promises.getUser.onFirstCall().resolves()
  430. ctx.UserGetter.promises.getUser.onSecondCall().resolves(ctx.user)
  431. })
  432. it('should update the user audit log', async function (ctx) {
  433. const auditLog = {
  434. initiatorId: '6005c75b12cbcaf771f4a105',
  435. ipAddress: '0:0:0:0',
  436. }
  437. await ctx.SAMLIdentityManager.linkAccounts(
  438. ctx.user._id,
  439. {
  440. externalUserId: 'externalUserId',
  441. institutionEmail: ctx.user.email,
  442. universityId: '1',
  443. universityName: 'Overleaf University',
  444. hasEntitlement: false,
  445. userIdAttribute: 'uniqueId',
  446. },
  447. auditLog
  448. )
  449. expect(
  450. ctx.UserAuditLogHandler.promises.addEntry
  451. ).to.have.been.calledWith(
  452. ctx.user._id,
  453. 'link-institution-sso',
  454. auditLog.initiatorId,
  455. auditLog.ipAddress,
  456. {
  457. institutionEmail: ctx.user.email,
  458. providerId: '1',
  459. providerName: 'Overleaf University',
  460. userIdAttribute: 'uniqueId',
  461. externalUserId: 'externalUserId',
  462. }
  463. )
  464. })
  465. it('should send an email notification', async function (ctx) {
  466. await ctx.SAMLIdentityManager.linkAccounts(
  467. ctx.user._id,
  468. {
  469. externalUserId: 'externalUserId',
  470. institutionEmail: ctx.user.email,
  471. universityId: '1',
  472. universityName: 'Overleaf University',
  473. hasEntitlement: false,
  474. userIdAttribute: 'someAttribute',
  475. },
  476. {
  477. intiatorId: '6005c75b12cbcaf771f4a105',
  478. ipAddress: '0:0:0:0',
  479. }
  480. )
  481. expect(ctx.User.findOneAndUpdate).to.have.been.called
  482. expect(ctx.EmailHandler.sendEmail).to.have.been.calledOnce
  483. const emailArgs = ctx.EmailHandler.sendEmail.lastCall.args
  484. expect(emailArgs[0]).to.equal('securityAlert')
  485. expect(emailArgs[1].to).to.equal(ctx.user.email)
  486. expect(emailArgs[1].actionDescribed).to.contain('was linked')
  487. expect(emailArgs[1].message[0]).to.contain('Linked')
  488. expect(emailArgs[1].message[0]).to.contain(ctx.user.email)
  489. })
  490. })
  491. })
  492. describe('unlinkAccounts', function () {
  493. it('should update the audit log', async function (ctx) {
  494. await ctx.SAMLIdentityManager.unlinkAccounts(
  495. ctx.user._id,
  496. linkedEmail,
  497. ctx.user.email,
  498. '1',
  499. 'Overleaf University',
  500. ctx.auditLog
  501. )
  502. expect(
  503. ctx.UserAuditLogHandler.promises.addEntry
  504. ).to.have.been.calledOnce.and.calledWithMatch(
  505. ctx.user._id,
  506. 'unlink-institution-sso',
  507. ctx.auditLog.initiatorId,
  508. ctx.auditLog.ipAddress,
  509. {
  510. institutionEmail: linkedEmail,
  511. providerId: '1',
  512. providerName: 'Overleaf University',
  513. }
  514. )
  515. })
  516. it('should remove the identifier', async function (ctx) {
  517. await ctx.SAMLIdentityManager.unlinkAccounts(
  518. ctx.user._id,
  519. linkedEmail,
  520. ctx.user.email,
  521. '1',
  522. 'Overleaf University',
  523. ctx.auditLog
  524. )
  525. const query = {
  526. _id: ctx.user._id,
  527. }
  528. const update = {
  529. $pull: {
  530. samlIdentifiers: {
  531. providerId: '1',
  532. },
  533. },
  534. }
  535. expect(ctx.User.updateOne).to.have.been.calledOnce.and.calledWithMatch(
  536. query,
  537. update
  538. )
  539. })
  540. it('should send an email notification', async function (ctx) {
  541. await ctx.SAMLIdentityManager.unlinkAccounts(
  542. ctx.user._id,
  543. linkedEmail,
  544. ctx.user.email,
  545. '1',
  546. 'Overleaf University',
  547. ctx.auditLog
  548. )
  549. expect(ctx.User.updateOne).to.have.been.called
  550. expect(ctx.EmailHandler.sendEmail).to.have.been.calledOnce
  551. const emailArgs = ctx.EmailHandler.sendEmail.lastCall.args
  552. expect(emailArgs[0]).to.equal('securityAlert')
  553. expect(emailArgs[1].to).to.equal(ctx.user.email)
  554. expect(emailArgs[1].actionDescribed).to.contain('was unlinked')
  555. expect(emailArgs[1].message[0]).to.contain('No longer linked')
  556. expect(emailArgs[1].message[0]).to.contain(linkedEmail)
  557. })
  558. describe('errors', function () {
  559. it('should pass back errors via UserAuditLogHandler', async function (ctx) {
  560. let error
  561. const anError = new Error('oops')
  562. ctx.UserAuditLogHandler.promises.addEntry.rejects(anError)
  563. try {
  564. await ctx.SAMLIdentityManager.unlinkAccounts(
  565. ctx.user._id,
  566. linkedEmail,
  567. ctx.user.email,
  568. '1',
  569. 'Overleaf University',
  570. ctx.auditLog
  571. )
  572. } catch (e) {
  573. error = e
  574. } finally {
  575. expect(error).to.exist
  576. expect(error).to.equal(anError)
  577. expect(ctx.EmailHandler.sendEmail).to.not.have.been.called
  578. expect(ctx.User.updateOne).to.not.have.been.called
  579. }
  580. })
  581. })
  582. })
  583. describe('entitlementAttributeMatches', function () {
  584. it('should return true when entitlement matches on string', function (ctx) {
  585. ctx.SAMLIdentityManager.entitlementAttributeMatches(
  586. 'foo bar',
  587. 'bar'
  588. ).should.equal(true)
  589. })
  590. it('should return false when entitlement does not match on string', function (ctx) {
  591. ctx.SAMLIdentityManager.entitlementAttributeMatches(
  592. 'foo bar',
  593. 'bam'
  594. ).should.equal(false)
  595. })
  596. it('should return false on an invalid matcher', function (ctx) {
  597. ctx.SAMLIdentityManager.entitlementAttributeMatches(
  598. 'foo bar',
  599. '('
  600. ).should.equal(false)
  601. })
  602. it('should log error on an invalid matcher', function (ctx) {
  603. ctx.SAMLIdentityManager.entitlementAttributeMatches('foo bar', '(')
  604. ctx.logger.error.firstCall.args[0].err.message.should.equal(
  605. 'Invalid regular expression: /(/: Unterminated group'
  606. )
  607. })
  608. it('should return true when entitlement matches on array', function (ctx) {
  609. ctx.SAMLIdentityManager.entitlementAttributeMatches(
  610. ['foo', 'bar'],
  611. 'bar'
  612. ).should.equal(true)
  613. })
  614. it('should return false when entitlement does not match array', function (ctx) {
  615. ctx.SAMLIdentityManager.entitlementAttributeMatches(
  616. ['foo', 'bar'],
  617. 'bam'
  618. ).should.equal(false)
  619. })
  620. })
  621. describe('migrateIdentifier', function () {
  622. const userId = '5efb8b6e9b647b0027e4c0b0'
  623. const externalUserId = '987zyx'
  624. const providerId = 123
  625. const hasEntitlement = false
  626. const institutionEmail = 'someone@email.com'
  627. const providerName = 'Example University'
  628. const auditLog = {
  629. initiatorId: userId,
  630. ipAddress: '0.0.0.0',
  631. migration: {
  632. from: 'uniqueId',
  633. to: 'newUniqueId',
  634. },
  635. }
  636. const userIdAttribute = 'newUniqueId'
  637. it('should remove the old identifier and add the new identifier', async function (ctx) {
  638. ctx.UserGetter.promises.getUser.resolves()
  639. ctx.UserGetter.promises.getUserByAnyEmail
  640. .withArgs(institutionEmail)
  641. .resolves({ _id: userId, emails: [{ email: institutionEmail }] })
  642. ctx.UserGetter.promises.getUserFullEmails.withArgs(userId).resolves([
  643. {
  644. email: institutionEmail,
  645. affiliation: { institution: { id: providerId } },
  646. },
  647. ])
  648. await ctx.SAMLIdentityManager.migrateIdentifier(
  649. userId,
  650. externalUserId,
  651. providerId,
  652. hasEntitlement,
  653. institutionEmail,
  654. providerName,
  655. auditLog,
  656. userIdAttribute
  657. )
  658. expect(ctx.User.updateOne).to.have.been.calledOnce
  659. const query = {
  660. _id: userId,
  661. 'samlIdentifiers.providerId': providerId.toString(),
  662. }
  663. const update = {
  664. $set: {
  665. 'samlIdentifiers.$.externalUserId': externalUserId,
  666. 'samlIdentifiers.$.userIdAttribute': userIdAttribute,
  667. },
  668. }
  669. expect(ctx.User.updateOne.lastCall.args).to.deep.equal([query, update])
  670. })
  671. })
  672. describe('unlinkNotMigrated', function () {
  673. const userId = '5efb8b6e9b647b0027e4c0b0'
  674. const providerId = '123'
  675. const institutionEmail = 'someone@email.com'
  676. const providerName = 'Example University'
  677. const auditLog = {
  678. ipAddress: 'N/A',
  679. }
  680. it('should remove the identifier om samlIdentifiers and samlProviderId on the email', async function (ctx) {
  681. ctx.User.findOneAndUpdate = sinon.stub().returns({
  682. exec: sinon.stub().resolves({
  683. _id: userId,
  684. emails: [{ email: institutionEmail, samlProviderId: providerId }],
  685. }),
  686. })
  687. await ctx.SAMLIdentityManager.unlinkNotMigrated(
  688. userId,
  689. providerId,
  690. providerName,
  691. auditLog
  692. )
  693. expect(ctx.User.findOneAndUpdate).to.have.been.calledOnce
  694. const query = {
  695. _id: userId,
  696. 'emails.samlProviderId': providerId,
  697. }
  698. const update = {
  699. $pull: {
  700. samlIdentifiers: {
  701. providerId,
  702. },
  703. },
  704. $unset: {
  705. 'emails.$.samlProviderId': 1,
  706. },
  707. }
  708. expect(ctx.User.findOneAndUpdate.lastCall.args).to.deep.equal([
  709. query,
  710. update,
  711. ])
  712. expect(ctx.UserAuditLogHandler.promises.addEntry).to.have.been.calledOnce
  713. expect(
  714. ctx.UserAuditLogHandler.promises.addEntry.lastCall.args
  715. ).to.deep.equal([
  716. userId,
  717. 'unlink-institution-sso-not-migrated',
  718. undefined,
  719. 'N/A',
  720. { providerId, providerName },
  721. ])
  722. expect(ctx.InstitutionsAPI.promises.removeEntitlement).to.have.been
  723. .calledOnce
  724. expect(
  725. ctx.InstitutionsAPI.promises.removeEntitlement.lastCall.args
  726. ).to.deep.equal([userId, institutionEmail])
  727. })
  728. })
  729. })