| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738 |
- const { ObjectId } = require('mongodb')
- const sinon = require('sinon')
- const { expect } = require('chai')
- const SandboxedModule = require('sandboxed-module')
- const Errors = require('../../../../app/src/Features/Errors/Errors')
- const modulePath = '../../../../app/src/Features/User/SAMLIdentityManager.js'
- describe('SAMLIdentityManager', function () {
- const linkedEmail = 'another@example.com'
- beforeEach(function () {
- this.userId = '6005c75b12cbcaf771f4a105'
- this.user = {
- _id: this.userId,
- email: 'not-linked@overleaf.com',
- emails: [{ email: 'not-linked@overleaf.com' }],
- samlIdentifiers: [],
- }
- this.auditLog = {
- initiatorId: this.userId,
- ipAddress: '0:0:0:0',
- }
- this.userAlreadyLinked = {
- _id: '6005c7a012cbcaf771f4a106',
- email: 'linked@overleaf.com',
- emails: [{ email: 'linked@overleaf.com', samlProviderId: '1' }],
- samlIdentifiers: [{ externalUserId: 'linked-id', providerId: '1' }],
- }
- this.userEmailExists = {
- _id: '6005c7a012cbcaf771f4a107',
- email: 'exists@overleaf.com',
- emails: [{ email: 'exists@overleaf.com' }],
- samlIdentifiers: [],
- }
- this.institution = {
- name: 'Overleaf University',
- }
- this.InstitutionsAPI = {
- promises: {
- addEntitlement: sinon.stub().resolves(),
- removeEntitlement: sinon.stub().resolves(),
- },
- }
- this.SAMLIdentityManager = SandboxedModule.require(modulePath, {
- requires: {
- '../Email/EmailHandler': (this.EmailHandler = {
- sendEmail: sinon.stub().yields(),
- }),
- '../Notifications/NotificationsBuilder': (this.NotificationsBuilder = {
- promises: {
- redundantPersonalSubscription: sinon
- .stub()
- .returns({ create: sinon.stub().resolves() }),
- },
- }),
- '../Subscription/SubscriptionLocator': (this.SubscriptionLocator = {
- promises: {
- getUserIndividualSubscription: sinon.stub().resolves(),
- },
- }),
- '../../models/User': {
- User: (this.User = {
- findOneAndUpdate: sinon.stub().returns({
- exec: sinon.stub().resolves(this.user),
- }),
- findOne: sinon.stub().returns({
- exec: sinon.stub().resolves(),
- }),
- updateOne: sinon.stub().returns({
- exec: sinon.stub().resolves(),
- }),
- }),
- },
- '../User/UserAuditLogHandler': (this.UserAuditLogHandler = {
- promises: {
- addEntry: sinon.stub().resolves(),
- },
- }),
- '../User/UserGetter': (this.UserGetter = {
- getUser: sinon.stub(),
- promises: {
- getUser: sinon.stub().resolves(this.user),
- getUserByAnyEmail: sinon.stub().resolves(),
- getUserFullEmails: sinon.stub().resolves(),
- },
- }),
- '../User/UserUpdater': (this.UserUpdater = {
- addEmailAddress: sinon.stub(),
- promises: {
- addEmailAddress: sinon.stub().resolves(),
- confirmEmail: sinon.stub().resolves(),
- updateUser: sinon.stub().resolves(),
- },
- }),
- '../Institutions/InstitutionsAPI': this.InstitutionsAPI,
- },
- })
- })
- describe('getUser', function () {
- it('should throw an error if missing all of: provider ID, external user ID, attribute', async function () {
- let error
- try {
- await this.SAMLIdentityManager.getUser(undefined, undefined, undefined)
- } catch (e) {
- error = e
- } finally {
- expect(error).to.exist
- expect(error.message).to.equal(
- 'invalid arguments: providerId: undefined, externalUserId: undefined, userIdAttribute: undefined'
- )
- }
- })
- it('should throw an error if missing provider ID', async function () {
- let error
- try {
- await this.SAMLIdentityManager.getUser(undefined, 'id123', 'someAttr')
- } catch (e) {
- error = e
- } finally {
- expect(error).to.exist
- expect(error.message).to.equal(
- 'invalid arguments: providerId: undefined, externalUserId: id123, userIdAttribute: someAttr'
- )
- }
- })
- it('should throw an error if missing external user ID', async function () {
- let error
- try {
- await this.SAMLIdentityManager.getUser('123', null, 'someAttr')
- } catch (e) {
- error = e
- } finally {
- expect(error).to.exist
- }
- })
- it('should throw an error if missing attribute', async function () {
- let error
- try {
- await this.SAMLIdentityManager.getUser('123', 'id123', undefined)
- } catch (e) {
- error = e
- } finally {
- expect(error).to.exist
- expect(error.message).to.equal(
- 'invalid arguments: providerId: 123, externalUserId: id123, userIdAttribute: undefined'
- )
- }
- })
- })
- describe('linkAccounts', function () {
- describe('errors', function () {
- beforeEach(function () {
- // first call is to get userWithProvider; should be falsy
- this.UserGetter.promises.getUser.onFirstCall().resolves()
- this.UserGetter.promises.getUser.onSecondCall().resolves(this.user)
- })
- it('should throw an error if missing all data', async function () {
- let error
- try {
- await this.SAMLIdentityManager.linkAccounts(null, null, null)
- } catch (e) {
- error = e
- } finally {
- expect(error).to.exist
- }
- })
- describe('linking data', function () {
- const requiredData = {
- externalUserId: 'someUniqueId',
- institutionEmail: 'user@example.com',
- providerId: '123',
- userIdAttribute: 'attribute',
- }
- for (const [data] of Object.entries(requiredData)) {
- const testData = { ...requiredData }
- delete testData[data]
- let error
- it(`should throw an error when missing ${data}`, async function () {
- try {
- await this.SAMLIdentityManager.linkAccounts('123', testData, {})
- } catch (e) {
- error = e
- } finally {
- expect(error).to.exist
- expect(error.message).to.contain(
- 'missing data when linking institution SSO'
- )
- }
- })
- }
- })
- describe('when email is already associated with another Overleaf account', function () {
- beforeEach(function () {
- this.UserGetter.promises.getUserByAnyEmail.resolves(
- this.userEmailExists
- )
- })
- it('should throw an EmailExistsError error', async function () {
- let error
- try {
- await this.SAMLIdentityManager.linkAccounts(
- '6005c75b12cbcaf771f4a105',
- {
- externalUserId: 'not-linked-id',
- institutionEmail: 'exists@overleaf.com',
- universityId: 'provider-id',
- universityName: 'provider-name',
- hasEntitlement: true,
- userIdAttribute: 'someAttribute',
- },
- {
- intiatorId: '6005c75b12cbcaf771f4a105',
- ip: '0:0:0:0',
- }
- )
- } catch (e) {
- error = e
- } finally {
- expect(error).to.be.instanceof(Errors.EmailExistsError)
- expect(this.User.findOneAndUpdate).to.not.have.been.called
- }
- })
- })
- describe('when email is not affiliated', function () {
- beforeEach(function () {
- this.UserGetter.promises.getUserByAnyEmail.resolves(this.user)
- this.UserGetter.promises.getUserFullEmails.resolves([
- {
- email: 'not-affiliated@overleaf.com',
- },
- ])
- })
- it('should throw SAMLEmailNotAffiliatedError', async function () {
- let error
- try {
- await this.SAMLIdentityManager.linkAccounts(
- '6005c75b12cbcaf771f4a105',
- {
- externalUserId: 'not-linked-id',
- institutionEmail: 'not-affiliated@overleaf.com',
- universityId: 'provider-id',
- universityName: 'provider-name',
- hasEntitlement: true,
- userIdAttribute: 'someAttribute',
- },
- {
- intiatorId: 'user-id-1',
- ip: '0:0:0:0',
- }
- )
- } catch (e) {
- error = e
- } finally {
- expect(error).to.be.instanceof(Errors.SAMLEmailNotAffiliatedError)
- expect(this.User.findOneAndUpdate).to.not.have.been.called
- }
- })
- })
- describe('when email is affiliated with another institution', function () {
- beforeEach(function () {
- this.UserGetter.promises.getUserByAnyEmail.resolves(this.user)
- this.UserGetter.promises.getUserFullEmails.resolves([
- {
- email: 'affiliated@overleaf.com',
- affiliation: { institution: { id: '987' } },
- },
- ])
- })
- it('should throw SAMLEmailAffiliatedWithAnotherInstitutionError', async function () {
- let error
- try {
- await this.SAMLIdentityManager.linkAccounts(
- '6005c75b12cbcaf771f4a105',
- {
- externalUserId: 'not-linked-id',
- institutionEmail: 'affiliated@overleaf.com',
- universityId: 'provider-id',
- universityName: 'provider-name',
- hasEntitlement: true,
- userIdAttribute: 'someAttribute',
- },
- {
- intiatorId: 'user-id-1',
- ip: '0:0:0:0',
- }
- )
- } catch (e) {
- error = e
- } finally {
- expect(error).to.be.instanceof(
- Errors.SAMLEmailAffiliatedWithAnotherInstitutionError
- )
- expect(this.User.findOneAndUpdate).to.not.have.been.called
- }
- })
- })
- describe('when institution identifier is already associated with another Overleaf account', function () {
- beforeEach(function () {
- this.UserGetter.promises.getUserByAnyEmail.resolves(
- this.userAlreadyLinked
- )
- })
- it('should throw an SAMLIdentityExistsError error', async function () {
- let error
- try {
- await this.SAMLIdentityManager.linkAccounts(
- '6005c75b12cbcaf771f4a105',
- {
- externalUserId: 'already-linked-id',
- institutionEmail: 'linked@overleaf.com',
- universityId: 'provider-id',
- universityName: 'provider-name',
- hasEntitlement: true,
- userIdAttribute: 'someAttribute',
- },
- {
- intiatorId: '6005c75b12cbcaf771f4a105',
- ip: '0:0:0:0',
- }
- )
- } catch (e) {
- error = e
- } finally {
- expect(error).to.be.instanceof(Errors.SAMLIdentityExistsError)
- expect(this.User.findOneAndUpdate).to.not.have.been.called
- }
- })
- })
- describe('when institution provider is already associated with the user', function () {
- beforeEach(function () {
- // first call is to get userWithProvider; resolves with any user
- this.UserGetter.promises.getUser.onFirstCall().resolves(this.user)
- })
- it('should throw an SAMLAlreadyLinkedError error', async function () {
- let error
- try {
- await this.SAMLIdentityManager.linkAccounts(
- '6005c75b12cbcaf771f4a105',
- {
- externalUserId: 'already-linked-id',
- institutionEmail: 'linked@overleaf.com',
- universityId: 123456,
- universityName: 'provider-name',
- hasEntitlement: true,
- userIdAttribute: 'someAttribute',
- },
- {
- intiatorId: '6005c75b12cbcaf771f4a105',
- ip: '0:0:0:0',
- }
- )
- } catch (e) {
- error = e
- } finally {
- expect(
- this.UserGetter.promises.getUser
- ).to.have.been.calledWithMatch({
- _id: new ObjectId('6005c75b12cbcaf771f4a105'),
- 'samlIdentifiers.providerId': '123456',
- })
- expect(error).to.be.instanceof(Errors.SAMLAlreadyLinkedError)
- expect(this.User.findOneAndUpdate).to.not.have.been.called
- }
- })
- })
- it('should pass back errors via UserAuditLogHandler', async function () {
- let error
- const anError = new Error('oops')
- this.UserAuditLogHandler.promises.addEntry.rejects(anError)
- try {
- await this.SAMLIdentityManager.linkAccounts(
- this.user._id,
- {
- externalUserId: 'externalUserId',
- institutionEmail: this.user.email,
- universityId: '1',
- universityName: 'Overleaf University',
- hasEntitlement: false,
- userIdAttribute: 'someAttribute',
- },
- {
- intiatorId: '6005c75b12cbcaf771f4a105',
- ipAddress: '0:0:0:0',
- }
- )
- } catch (e) {
- error = e
- } finally {
- expect(error).to.exist
- expect(error).to.equal(anError)
- expect(this.EmailHandler.sendEmail).to.not.have.been.called
- expect(this.User.updateOne).to.not.have.been.called
- }
- })
- })
- describe('success', function () {
- beforeEach(function () {
- // first call is to get userWithProvider; should be falsy
- this.UserGetter.promises.getUser.onFirstCall().resolves()
- this.UserGetter.promises.getUser.onSecondCall().resolves(this.user)
- })
- it('should update the user audit log', async function () {
- const auditLog = {
- initiatorId: '6005c75b12cbcaf771f4a105',
- ipAddress: '0:0:0:0',
- }
- await this.SAMLIdentityManager.linkAccounts(
- this.user._id,
- {
- externalUserId: 'externalUserId',
- institutionEmail: this.user.email,
- universityId: '1',
- universityName: 'Overleaf University',
- hasEntitlement: false,
- userIdAttribute: 'uniqueId',
- },
- auditLog
- )
- expect(
- this.UserAuditLogHandler.promises.addEntry
- ).to.have.been.calledWith(
- this.user._id,
- 'link-institution-sso',
- auditLog.initiatorId,
- auditLog.ipAddress,
- {
- institutionEmail: this.user.email,
- providerId: '1',
- providerName: 'Overleaf University',
- userIdAttribute: 'uniqueId',
- }
- )
- })
- it('should send an email notification', async function () {
- await this.SAMLIdentityManager.linkAccounts(
- this.user._id,
- {
- externalUserId: 'externalUserId',
- institutionEmail: this.user.email,
- universityId: '1',
- universityName: 'Overleaf University',
- hasEntitlement: false,
- userIdAttribute: 'someAttribute',
- },
- {
- intiatorId: '6005c75b12cbcaf771f4a105',
- ipAddress: '0:0:0:0',
- }
- )
- expect(this.User.findOneAndUpdate).to.have.been.called
- expect(this.EmailHandler.sendEmail).to.have.been.calledOnce
- const emailArgs = this.EmailHandler.sendEmail.lastCall.args
- expect(emailArgs[0]).to.equal('securityAlert')
- expect(emailArgs[1].to).to.equal(this.user.email)
- expect(emailArgs[1].actionDescribed).to.contain('was linked')
- expect(emailArgs[1].message[0]).to.contain('Linked')
- expect(emailArgs[1].message[0]).to.contain(this.user.email)
- })
- })
- })
- describe('unlinkAccounts', function () {
- it('should update the audit log', async function () {
- await this.SAMLIdentityManager.unlinkAccounts(
- this.user._id,
- linkedEmail,
- this.user.email,
- '1',
- 'Overleaf University',
- this.auditLog
- )
- expect(
- this.UserAuditLogHandler.promises.addEntry
- ).to.have.been.calledOnce.and.calledWithMatch(
- this.user._id,
- 'unlink-institution-sso',
- this.auditLog.initiatorId,
- this.auditLog.ipAddress,
- {
- institutionEmail: linkedEmail,
- providerId: '1',
- providerName: 'Overleaf University',
- }
- )
- })
- it('should remove the identifier', async function () {
- await this.SAMLIdentityManager.unlinkAccounts(
- this.user._id,
- linkedEmail,
- this.user.email,
- '1',
- 'Overleaf University',
- this.auditLog
- )
- const query = {
- _id: this.user._id,
- }
- const update = {
- $pull: {
- samlIdentifiers: {
- providerId: '1',
- },
- },
- }
- expect(this.User.updateOne).to.have.been.calledOnce.and.calledWithMatch(
- query,
- update
- )
- })
- it('should send an email notification', async function () {
- await this.SAMLIdentityManager.unlinkAccounts(
- this.user._id,
- linkedEmail,
- this.user.email,
- '1',
- 'Overleaf University',
- this.auditLog
- )
- expect(this.User.updateOne).to.have.been.called
- expect(this.EmailHandler.sendEmail).to.have.been.calledOnce
- const emailArgs = this.EmailHandler.sendEmail.lastCall.args
- expect(emailArgs[0]).to.equal('securityAlert')
- expect(emailArgs[1].to).to.equal(this.user.email)
- expect(emailArgs[1].actionDescribed).to.contain('was unlinked')
- expect(emailArgs[1].message[0]).to.contain('No longer linked')
- expect(emailArgs[1].message[0]).to.contain(linkedEmail)
- })
- describe('errors', function () {
- it('should pass back errors via UserAuditLogHandler', async function () {
- let error
- const anError = new Error('oops')
- this.UserAuditLogHandler.promises.addEntry.rejects(anError)
- try {
- await this.SAMLIdentityManager.unlinkAccounts(
- this.user._id,
- linkedEmail,
- this.user.email,
- '1',
- 'Overleaf University',
- this.auditLog
- )
- } catch (e) {
- error = e
- } finally {
- expect(error).to.exist
- expect(error).to.equal(anError)
- expect(this.EmailHandler.sendEmail).to.not.have.been.called
- expect(this.User.updateOne).to.not.have.been.called
- }
- })
- })
- })
- describe('entitlementAttributeMatches', function () {
- it('should return true when entitlement matches on string', function () {
- this.SAMLIdentityManager.entitlementAttributeMatches(
- 'foo bar',
- 'bar'
- ).should.equal(true)
- })
- it('should return false when entitlement does not match on string', function () {
- this.SAMLIdentityManager.entitlementAttributeMatches(
- 'foo bar',
- 'bam'
- ).should.equal(false)
- })
- it('should return false on an invalid matcher', function () {
- this.SAMLIdentityManager.entitlementAttributeMatches(
- 'foo bar',
- '('
- ).should.equal(false)
- })
- it('should log error on an invalid matcher', function () {
- this.SAMLIdentityManager.entitlementAttributeMatches('foo bar', '(')
- this.logger.error.firstCall.args[0].err.message.should.equal(
- 'Invalid regular expression: /(/: Unterminated group'
- )
- })
- it('should return true when entitlement matches on array', function () {
- this.SAMLIdentityManager.entitlementAttributeMatches(
- ['foo', 'bar'],
- 'bar'
- ).should.equal(true)
- })
- it('should return false when entitlement does not match array', function () {
- this.SAMLIdentityManager.entitlementAttributeMatches(
- ['foo', 'bar'],
- 'bam'
- ).should.equal(false)
- })
- })
- describe('migrateIdentifier', function () {
- const userId = '5efb8b6e9b647b0027e4c0b0'
- const externalUserId = '987zyx'
- const providerId = 123
- const hasEntitlement = false
- const institutionEmail = 'someone@email.com'
- const providerName = 'Example University'
- const auditLog = {
- initiatorId: userId,
- ipAddress: '0.0.0.0',
- migration: {
- from: 'uniqueId',
- to: 'newUniqueId',
- },
- }
- const userIdAttribute = 'newUniqueId'
- it('should remove the old identifier and add the new identifier', async function () {
- this.UserGetter.promises.getUser.resolves()
- this.UserGetter.promises.getUserByAnyEmail
- .withArgs(institutionEmail)
- .resolves({ _id: userId, emails: [{ email: institutionEmail }] })
- this.UserGetter.promises.getUserFullEmails.withArgs(userId).resolves([
- {
- email: institutionEmail,
- affiliation: { institution: { id: providerId } },
- },
- ])
- await this.SAMLIdentityManager.migrateIdentifier(
- userId,
- externalUserId,
- providerId,
- hasEntitlement,
- institutionEmail,
- providerName,
- auditLog,
- userIdAttribute
- )
- expect(this.User.updateOne).to.have.been.calledOnce
- const query = {
- _id: userId,
- 'samlIdentifiers.providerId': providerId.toString(),
- }
- const update = {
- $set: {
- 'samlIdentifiers.$.externalUserId': externalUserId,
- 'samlIdentifiers.$.userIdAttribute': userIdAttribute,
- },
- }
- expect(this.User.updateOne.lastCall.args).to.deep.equal([query, update])
- })
- })
- describe('unlinkNotMigrated', function () {
- const userId = '5efb8b6e9b647b0027e4c0b0'
- const providerId = '123'
- const institutionEmail = 'someone@email.com'
- const providerName = 'Example University'
- const auditLog = {
- ipAddress: 'N/A',
- }
- it('should remove the identifier om samlIdentifiers and samlProviderId on the email', async function () {
- this.User.findOneAndUpdate = sinon.stub().returns({
- exec: sinon.stub().resolves({
- _id: userId,
- emails: [{ email: institutionEmail, samlProviderId: providerId }],
- }),
- })
- await this.SAMLIdentityManager.unlinkNotMigrated(
- userId,
- providerId,
- providerName,
- auditLog
- )
- expect(this.User.findOneAndUpdate).to.have.been.calledOnce
- const query = {
- _id: userId,
- 'emails.samlProviderId': providerId,
- }
- const update = {
- $pull: {
- samlIdentifiers: {
- providerId,
- },
- },
- $unset: {
- 'emails.$.samlProviderId': 1,
- },
- }
- expect(this.User.findOneAndUpdate.lastCall.args).to.deep.equal([
- query,
- update,
- ])
- expect(this.UserAuditLogHandler.promises.addEntry).to.have.been.calledOnce
- expect(
- this.UserAuditLogHandler.promises.addEntry.lastCall.args
- ).to.deep.equal([
- userId,
- 'unlink-institution-sso-not-migrated',
- undefined,
- 'N/A',
- { providerId, providerName },
- ])
- expect(this.InstitutionsAPI.promises.removeEntitlement).to.have.been
- .calledOnce
- expect(
- this.InstitutionsAPI.promises.removeEntitlement.lastCall.args
- ).to.deep.equal([userId, institutionEmail])
- })
- })
- })
|