SAMLIdentityManagerTests.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  1. const sinon = require('sinon')
  2. const chai = require('chai')
  3. const { expect } = chai
  4. const SandboxedModule = require('sandboxed-module')
  5. const modulePath = '../../../../app/src/Features/User/SAMLIdentityManager.js'
  6. describe('SAMLIdentityManager', function() {
  7. beforeEach(function() {
  8. this.Errors = {
  9. EmailExistsError: sinon.stub(),
  10. NotFoundError: sinon.stub(),
  11. SAMLIdentityExistsError: sinon.stub()
  12. }
  13. this.userId = 'user-id-1'
  14. this.user = {
  15. _id: this.userId,
  16. email: 'not-linked@overleaf.com',
  17. emails: [{ email: 'not-linked@overleaf.com' }],
  18. samlIdentifiers: []
  19. }
  20. this.auditLog = {
  21. initiatorId: this.userId,
  22. ipAddress: '0:0:0:0'
  23. }
  24. this.userAlreadyLinked = {
  25. _id: 'user-id-2',
  26. email: 'linked@overleaf.com',
  27. emails: [{ email: 'linked@overleaf.com', samlProviderId: '1' }],
  28. samlIdentifiers: [{ externalUserId: 'linked-id', providerId: '1' }]
  29. }
  30. this.userEmailExists = {
  31. _id: 'user-id-3',
  32. email: 'exists@overleaf.com',
  33. emails: [{ email: 'exists@overleaf.com' }],
  34. samlIdentifiers: []
  35. }
  36. this.institution = {
  37. name: 'Overleaf University'
  38. }
  39. this.InstitutionsAPI = {
  40. promises: {
  41. addEntitlement: sinon.stub().resolves(),
  42. removeEntitlement: sinon.stub().resolves()
  43. }
  44. }
  45. this.logger = {
  46. error: sinon.stub(),
  47. warn: sinon.stub()
  48. }
  49. this.SAMLIdentityManager = SandboxedModule.require(modulePath, {
  50. globals: {
  51. console: console
  52. },
  53. requires: {
  54. '../Email/EmailHandler': (this.EmailHandler = {
  55. sendEmail: sinon.stub().yields()
  56. }),
  57. '../Errors/Errors': this.Errors,
  58. '../Notifications/NotificationsBuilder': (this.NotificationsBuilder = {
  59. promises: {
  60. redundantPersonalSubscription: sinon
  61. .stub()
  62. .returns({ create: sinon.stub().resolves() })
  63. }
  64. }),
  65. '../Subscription/SubscriptionLocator': (this.SubscriptionLocator = {
  66. promises: {
  67. getUserIndividualSubscription: sinon.stub().resolves()
  68. }
  69. }),
  70. '../../models/User': {
  71. User: (this.User = {
  72. findOneAndUpdate: sinon.stub().returns({
  73. exec: sinon.stub().resolves()
  74. }),
  75. findOne: sinon.stub().returns({
  76. exec: sinon.stub().resolves()
  77. }),
  78. update: sinon.stub().returns({
  79. exec: sinon.stub().resolves()
  80. })
  81. })
  82. },
  83. '../User/UserAuditLogHandler': (this.UserAuditLogHandler = {
  84. promises: {
  85. addEntry: sinon.stub().resolves()
  86. }
  87. }),
  88. '../User/UserGetter': (this.UserGetter = {
  89. getUser: sinon.stub(),
  90. promises: {
  91. getUser: sinon.stub().resolves(this.user),
  92. getUserByAnyEmail: sinon.stub().resolves()
  93. }
  94. }),
  95. '../User/UserUpdater': (this.UserUpdater = {
  96. addEmailAddress: sinon.stub(),
  97. promises: {
  98. addEmailAddress: sinon.stub().resolves(),
  99. confirmEmail: sinon.stub().resolves(),
  100. updateUser: sinon.stub().resolves()
  101. }
  102. }),
  103. '../Institutions/InstitutionsAPI': this.InstitutionsAPI,
  104. 'logger-sharelatex': this.logger
  105. }
  106. })
  107. })
  108. describe('getUser', function() {
  109. it('should throw an error if missing provider ID and/or external user ID', async function() {
  110. let error
  111. try {
  112. await this.SAMLIdentityManager.getUser(null, null)
  113. } catch (e) {
  114. error = e
  115. } finally {
  116. expect(error).to.exist
  117. }
  118. })
  119. })
  120. describe('linkAccounts', function() {
  121. describe('errors', function() {
  122. it('should throw an error if missing data', async function() {
  123. let error
  124. try {
  125. await this.SAMLIdentityManager.linkAccounts(
  126. null,
  127. null,
  128. null,
  129. null,
  130. null
  131. )
  132. } catch (e) {
  133. error = e
  134. } finally {
  135. expect(error).to.exist
  136. }
  137. })
  138. describe('when email is already associated with another Overleaf account', function() {
  139. beforeEach(function() {
  140. this.UserGetter.promises.getUserByAnyEmail.resolves(
  141. this.userEmailExists
  142. )
  143. })
  144. it('should throw an EmailExistsError error', async function() {
  145. let error
  146. try {
  147. await this.SAMLIdentityManager.linkAccounts(
  148. 'user-id-1',
  149. 'not-linked-id',
  150. 'exists@overleaf.com',
  151. 'provider-id',
  152. 'provider-name',
  153. true,
  154. {
  155. intiatorId: 'user-id-1',
  156. ip: '0:0:0:0'
  157. }
  158. )
  159. } catch (e) {
  160. error = e
  161. } finally {
  162. expect(error).to.be.instanceof(this.Errors.EmailExistsError)
  163. expect(this.User.findOneAndUpdate).to.not.have.been.called
  164. }
  165. })
  166. })
  167. describe('when institution identifier is already associated with another Overleaf account', function() {
  168. beforeEach(function() {
  169. this.UserGetter.promises.getUserByAnyEmail.resolves(
  170. this.userAlreadyLinked
  171. )
  172. })
  173. it('should throw an SAMLIdentityExistsError error', async function() {
  174. let error
  175. try {
  176. await this.SAMLIdentityManager.linkAccounts(
  177. 'user-id-1',
  178. 'already-linked-id',
  179. 'linked@overleaf.com',
  180. 'provider-id',
  181. 'provider-name',
  182. true,
  183. {
  184. intiatorId: 'user-id-1',
  185. ip: '0:0:0:0'
  186. }
  187. )
  188. } catch (e) {
  189. error = e
  190. } finally {
  191. expect(error).to.be.instanceof(this.Errors.SAMLIdentityExistsError)
  192. expect(this.User.findOneAndUpdate).to.not.have.been.called
  193. }
  194. })
  195. })
  196. it('should pass back errors via UserAuditLogHandler', async function() {
  197. let error
  198. const anError = new Error('oops')
  199. this.UserAuditLogHandler.promises.addEntry.rejects(anError)
  200. try {
  201. await this.SAMLIdentityManager.linkAccounts(
  202. this.user._id,
  203. 'externalUserId',
  204. this.user.email,
  205. '1',
  206. 'Overleaf University',
  207. undefined,
  208. {
  209. intiatorId: 'user-id-1',
  210. ipAddress: '0:0:0:0'
  211. }
  212. )
  213. } catch (e) {
  214. error = e
  215. } finally {
  216. expect(error).to.exist
  217. expect(error).to.equal(anError)
  218. expect(this.EmailHandler.sendEmail).to.not.have.been.called
  219. expect(this.User.update).to.not.have.been.called
  220. }
  221. })
  222. })
  223. describe('success', function() {
  224. it('should update the user audit log', function() {
  225. const auditLog = {
  226. intiatorId: 'user-id-1',
  227. ip: '0:0:0:0'
  228. }
  229. this.SAMLIdentityManager.linkAccounts(
  230. this.user._id,
  231. 'externalUserId',
  232. this.user.email,
  233. '1',
  234. 'Overleaf University',
  235. undefined,
  236. auditLog,
  237. () => {
  238. expect(
  239. this.UserAuditLogHandler.promises.addEntry
  240. ).to.have.been.calledWith(
  241. this.user._id,
  242. 'link-institution-sso',
  243. auditLog.initiatorId,
  244. auditLog.ip,
  245. {
  246. institutionEmail: this.user.email,
  247. providerId: '1',
  248. providerName: 'Overleaf University'
  249. }
  250. )
  251. }
  252. )
  253. })
  254. it('should send an email notification', function() {
  255. this.SAMLIdentityManager.linkAccounts(
  256. this.user._id,
  257. 'externalUserId',
  258. this.user.email,
  259. '1',
  260. 'Overleaf University',
  261. undefined,
  262. {
  263. intiatorId: 'user-id-1',
  264. ipAddress: '0:0:0:0'
  265. },
  266. () => {
  267. expect(this.User.update).to.have.been.called
  268. expect(this.EmailHandler.sendEmail).to.have.been.called
  269. }
  270. )
  271. })
  272. })
  273. })
  274. describe('unlinkAccounts', function() {
  275. const linkedEmail = 'another@example.com'
  276. it('should update the audit log', async function() {
  277. await this.SAMLIdentityManager.unlinkAccounts(
  278. this.user._id,
  279. linkedEmail,
  280. this.user.email,
  281. '1',
  282. 'Overleaf University',
  283. this.auditLog
  284. )
  285. expect(
  286. this.UserAuditLogHandler.promises.addEntry
  287. ).to.have.been.calledOnce.and.calledWithMatch(
  288. this.user._id,
  289. 'unlink-institution-sso',
  290. this.auditLog.initiatorId,
  291. this.auditLog.ipAddress,
  292. {
  293. institutionEmail: linkedEmail,
  294. providerId: '1',
  295. providerName: 'Overleaf University'
  296. }
  297. )
  298. })
  299. it('should remove the identifier', async function() {
  300. await this.SAMLIdentityManager.unlinkAccounts(
  301. this.user._id,
  302. linkedEmail,
  303. this.user.email,
  304. '1',
  305. 'Overleaf University',
  306. this.auditLog
  307. )
  308. const query = {
  309. _id: this.user._id
  310. }
  311. const update = {
  312. $pull: {
  313. samlIdentifiers: {
  314. providerId: '1'
  315. }
  316. }
  317. }
  318. expect(this.User.update).to.have.been.calledOnce.and.calledWithMatch(
  319. query,
  320. update
  321. )
  322. })
  323. it('should send an email notification', async function() {
  324. await this.SAMLIdentityManager.unlinkAccounts(
  325. this.user._id,
  326. linkedEmail,
  327. this.user.email,
  328. '1',
  329. 'Overleaf University',
  330. this.auditLog
  331. )
  332. expect(this.User.update).to.have.been.called
  333. expect(this.EmailHandler.sendEmail).to.have.been.calledOnce
  334. const emailArgs = this.EmailHandler.sendEmail.lastCall.args
  335. expect(emailArgs[0]).to.equal('securityAlert')
  336. expect(emailArgs[1].to).to.equal(this.user.email)
  337. })
  338. describe('errors', function() {
  339. it('should pass back errors via UserAuditLogHandler', async function() {
  340. let error
  341. const anError = new Error('oops')
  342. this.UserAuditLogHandler.promises.addEntry.rejects(anError)
  343. try {
  344. await this.SAMLIdentityManager.unlinkAccounts(
  345. this.user._id,
  346. linkedEmail,
  347. this.user.email,
  348. '1',
  349. 'Overleaf University',
  350. this.auditLog
  351. )
  352. } catch (e) {
  353. error = e
  354. } finally {
  355. expect(error).to.exist
  356. expect(error).to.equal(anError)
  357. expect(this.EmailHandler.sendEmail).to.not.have.been.called
  358. expect(this.User.update).to.not.have.been.called
  359. }
  360. })
  361. })
  362. })
  363. describe('entitlementAttributeMatches', function() {
  364. it('should return true when entitlement matches on string', function() {
  365. this.SAMLIdentityManager.entitlementAttributeMatches(
  366. 'foo bar',
  367. 'bar'
  368. ).should.equal(true)
  369. })
  370. it('should return false when entitlement does not match on string', function() {
  371. this.SAMLIdentityManager.entitlementAttributeMatches(
  372. 'foo bar',
  373. 'bam'
  374. ).should.equal(false)
  375. })
  376. it('should return false on an invalid matcher', function() {
  377. this.SAMLIdentityManager.entitlementAttributeMatches(
  378. 'foo bar',
  379. '('
  380. ).should.equal(false)
  381. })
  382. it('should log error on an invalid matcher', function() {
  383. this.SAMLIdentityManager.entitlementAttributeMatches('foo bar', '(')
  384. this.logger.error.firstCall.args[0].err.message.should.equal(
  385. 'Invalid regular expression: /(/: Unterminated group'
  386. )
  387. })
  388. it('should return true when entitlement matches on array', function() {
  389. this.SAMLIdentityManager.entitlementAttributeMatches(
  390. ['foo', 'bar'],
  391. 'bar'
  392. ).should.equal(true)
  393. })
  394. it('should return false when entitlement does not match array', function() {
  395. this.SAMLIdentityManager.entitlementAttributeMatches(
  396. ['foo', 'bar'],
  397. 'bam'
  398. ).should.equal(false)
  399. })
  400. })
  401. describe('redundantSubscription', function() {
  402. const userId = '1bv'
  403. const providerId = 123
  404. const providerName = 'University Name'
  405. describe('with a personal subscription', function() {
  406. beforeEach(function() {
  407. this.SubscriptionLocator.promises.getUserIndividualSubscription.resolves(
  408. {
  409. planCode: 'professional'
  410. }
  411. )
  412. })
  413. it('should create redundant personal subscription notification ', async function() {
  414. try {
  415. await this.SAMLIdentityManager.redundantSubscription(
  416. userId,
  417. providerId,
  418. providerName
  419. )
  420. } catch (error) {
  421. expect(error).to.not.exist
  422. }
  423. expect(this.NotificationsBuilder.promises.redundantPersonalSubscription)
  424. .to.have.been.calledOnce
  425. })
  426. })
  427. describe('without a personal subscription', function() {
  428. it('should create redundant personal subscription notification ', async function() {
  429. try {
  430. await this.SAMLIdentityManager.redundantSubscription(
  431. userId,
  432. providerId,
  433. providerName
  434. )
  435. } catch (error) {
  436. expect(error).to.not.exist
  437. }
  438. expect(this.NotificationsBuilder.promises.redundantPersonalSubscription)
  439. .to.not.have.been.called
  440. })
  441. })
  442. })
  443. })