SessionTests.mjs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431
  1. import { expect } from 'chai'
  2. import { setTimeout } from 'node:timers/promises'
  3. import UserHelper from './helpers/User.mjs'
  4. import redis from './helpers/redis.mjs'
  5. import Metrics from './helpers/metrics.mjs'
  6. import UserSessionsRedis from '../../../app/src/Features/User/UserSessionsRedis.mjs'
  7. import UserAnalyticsDataCache from '../../../app/src/Features/Analytics/UserAnalyticsDataCache.mjs'
  8. import Features from '../../../app/src/infrastructure/Features.mjs'
  9. const rclient = UserSessionsRedis.client()
  10. const UserPromises = UserHelper.promises
  11. describe('Sessions', function () {
  12. beforeEach(async function () {
  13. this.timeout(20000)
  14. this.user1 = new UserPromises()
  15. this.site_admin = new UserPromises({ email: 'admin@example.com' })
  16. await this.user1.login()
  17. await this.user1.logout()
  18. })
  19. describe('one session', function () {
  20. it('should have one session in UserSessions set', async function () {
  21. await redis.clearUserSessions(this.user1)
  22. // login, should add session to set
  23. await this.user1.login()
  24. const sessions = await redis.getUserSessions(this.user1)
  25. expect(sessions.length).to.equal(1)
  26. expect(sessions[0].slice(0, 5)).to.equal('sess:')
  27. // should be able to access project list page
  28. const statusCode = await this.user1.getProjectListPage()
  29. expect(statusCode).to.equal(200)
  30. // logout, should remove session from set
  31. await this.user1.logout()
  32. const sessionsAfterLogout = await redis.getUserSessions(this.user1)
  33. expect(sessionsAfterLogout.length).to.equal(0)
  34. })
  35. it('should update audit log on logout', async function () {
  36. await redis.clearUserSessions(this.user1)
  37. // login
  38. await this.user1.login()
  39. // logout, should add logout audit log entry (happens in background)
  40. await this.user1.logout()
  41. // poll for audit log entry since it's written in the background
  42. const findAuditLogEntry = async () => {
  43. for (let attempts = 0; attempts < 10; attempts++) {
  44. const auditLog = await this.user1.getAuditLogWithoutNoise()
  45. const logoutEntries = auditLog.filter(
  46. entry => entry.operation === 'logout'
  47. )
  48. // If we found the logout entry, we're done
  49. if (logoutEntries.length > 0) {
  50. return logoutEntries
  51. }
  52. await setTimeout(25)
  53. }
  54. throw new Error('Logout audit log entry not found after 10 attempts')
  55. }
  56. const logoutEntries = await findAuditLogEntry()
  57. expect(logoutEntries.length).to.be.greaterThan(0)
  58. const lastLogout = logoutEntries[logoutEntries.length - 1]
  59. expect(lastLogout.operation).to.equal('logout')
  60. expect(lastLogout.ipAddress).to.exist
  61. expect(lastLogout.initiatorId).to.exist
  62. expect(lastLogout.timestamp).to.exist
  63. })
  64. })
  65. describe('two sessions', function () {
  66. beforeEach(function () {
  67. // set up second session for this user
  68. this.user2 = new UserPromises()
  69. this.user2.email = this.user1.email
  70. this.user2.emails = this.user1.emails
  71. this.user2.password = this.user1.password
  72. })
  73. it('should have two sessions in UserSessions set', async function () {
  74. await redis.clearUserSessions(this.user1)
  75. // login, should add session to set
  76. await this.user1.login()
  77. const sessions1 = await redis.getUserSessions(this.user1)
  78. expect(sessions1.length).to.equal(1)
  79. expect(sessions1[0].slice(0, 5)).to.equal('sess:')
  80. // login again, should add the second session to set
  81. await this.user2.login()
  82. const sessions2 = await redis.getUserSessions(this.user1)
  83. expect(sessions2.length).to.equal(2)
  84. expect(sessions2[0].slice(0, 5)).to.equal('sess:')
  85. expect(sessions2[1].slice(0, 5)).to.equal('sess:')
  86. // both should be able to access project list page
  87. const statusCode1 = await this.user1.getProjectListPage()
  88. expect(statusCode1).to.equal(200)
  89. const statusCode2 = await this.user2.getProjectListPage()
  90. expect(statusCode2).to.equal(200)
  91. // logout first session, should remove session from set
  92. await this.user1.logout()
  93. const sessions3 = await redis.getUserSessions(this.user1)
  94. expect(sessions3.length).to.equal(1)
  95. // first session should not have access to project list page
  96. const statusCode3 = await this.user1.getProjectListPage()
  97. expect(statusCode3).to.equal(302)
  98. // second session should still have access to settings
  99. const statusCode4 = await this.user2.getProjectListPage()
  100. expect(statusCode4).to.equal(200)
  101. // logout second session, should remove last session from set
  102. await this.user2.logout()
  103. const sessions4 = await redis.getUserSessions(this.user1)
  104. expect(sessions4.length).to.equal(0)
  105. // second session should not have access to project list page
  106. const statusCode5 = await this.user2.getProjectListPage()
  107. expect(statusCode5).to.equal(302)
  108. })
  109. })
  110. describe('three sessions, password reset', function () {
  111. beforeEach(function () {
  112. // set up second session for this user
  113. this.user2 = new UserPromises()
  114. this.user2.email = this.user1.email
  115. this.user2.emails = this.user1.emails
  116. this.user2.password = this.user1.password
  117. this.user3 = new UserPromises()
  118. this.user3.email = this.user1.email
  119. this.user3.emails = this.user1.emails
  120. this.user3.password = this.user1.password
  121. })
  122. it('should erase both sessions when password is reset', async function () {
  123. await redis.clearUserSessions(this.user1)
  124. // login, should add session to set
  125. await this.user1.login()
  126. const sessions1 = await redis.getUserSessions(this.user1)
  127. expect(sessions1.length).to.equal(1)
  128. expect(sessions1[0].slice(0, 5)).to.equal('sess:')
  129. // login again, should add the second session to set
  130. await this.user2.login()
  131. const sessions2 = await redis.getUserSessions(this.user1)
  132. expect(sessions2.length).to.equal(2)
  133. expect(sessions2[0].slice(0, 5)).to.equal('sess:')
  134. expect(sessions2[1].slice(0, 5)).to.equal('sess:')
  135. // login third session, should add the second session to set
  136. await this.user3.login()
  137. const sessions3 = await redis.getUserSessions(this.user1)
  138. expect(sessions3.length).to.equal(3)
  139. expect(sessions3[0].slice(0, 5)).to.equal('sess:')
  140. expect(sessions3[1].slice(0, 5)).to.equal('sess:')
  141. // password reset from second session, should erase two of the three sessions
  142. await this.user2.changePassword(`password${Date.now()}`)
  143. const sessions4 = await redis.getUserSessions(this.user2)
  144. expect(sessions4.length).to.equal(1)
  145. // users one and three should not be able to access project list page
  146. const statusCode1 = await this.user1.getProjectListPage()
  147. expect(statusCode1).to.equal(302)
  148. const statusCode3 = await this.user3.getProjectListPage()
  149. expect(statusCode3).to.equal(302)
  150. // user two should still be logged in, and able to access project list page
  151. const statusCode2 = await this.user2.getProjectListPage()
  152. expect(statusCode2).to.equal(200)
  153. // logout second session, should remove last session from set
  154. await this.user2.logout()
  155. const sessions5 = await redis.getUserSessions(this.user1)
  156. expect(sessions5.length).to.equal(0)
  157. })
  158. })
  159. describe('three sessions, sessions page', function () {
  160. beforeEach(async function () {
  161. // set up second session for this user
  162. this.user2 = new UserPromises()
  163. this.user2.email = this.user1.email
  164. this.user2.emails = this.user1.emails
  165. this.user2.password = this.user1.password
  166. this.user3 = new UserPromises()
  167. this.user3.email = this.user1.email
  168. this.user3.emails = this.user1.emails
  169. this.user3.password = this.user1.password
  170. await this.user2.login()
  171. })
  172. it('should allow the user to erase the other two sessions', async function () {
  173. await redis.clearUserSessions(this.user1)
  174. // login, should add session to set
  175. await this.user1.login()
  176. const sessions1 = await redis.getUserSessions(this.user1)
  177. expect(sessions1.length).to.equal(1)
  178. expect(sessions1[0].slice(0, 5)).to.equal('sess:')
  179. // login again, should add the second session to set
  180. await this.user2.login()
  181. const sessions2 = await redis.getUserSessions(this.user1)
  182. expect(sessions2.length).to.equal(2)
  183. expect(sessions2[0].slice(0, 5)).to.equal('sess:')
  184. expect(sessions2[1].slice(0, 5)).to.equal('sess:')
  185. // login third session, should add the second session to set
  186. await this.user3.login()
  187. const sessions3 = await redis.getUserSessions(this.user1)
  188. expect(sessions3.length).to.equal(3)
  189. expect(sessions3[0].slice(0, 5)).to.equal('sess:')
  190. expect(sessions3[1].slice(0, 5)).to.equal('sess:')
  191. // check the sessions page
  192. const { response: sessionsPageResponse } = await this.user2.doRequest(
  193. 'GET',
  194. '/user/sessions'
  195. )
  196. expect(sessionsPageResponse.statusCode).to.equal(200)
  197. // clear sessions from second session, should erase two of the three sessions
  198. await this.user2.getCsrfToken()
  199. await this.user2.doRequest('POST', '/user/sessions/clear')
  200. const sessions4 = await redis.getUserSessions(this.user2)
  201. expect(sessions4.length).to.equal(1)
  202. // users one and three should not be able to access project list page
  203. const statusCode1 = await this.user1.getProjectListPage()
  204. expect(statusCode1).to.equal(302)
  205. const statusCode3 = await this.user3.getProjectListPage()
  206. expect(statusCode3).to.equal(302)
  207. // user two should still be logged in, and able to access project list page
  208. const statusCode2 = await this.user2.getProjectListPage()
  209. expect(statusCode2).to.equal(200)
  210. // logout second session, should remove last session from set
  211. await this.user2.logout()
  212. const sessions5 = await redis.getUserSessions(this.user1)
  213. expect(sessions5.length).to.equal(0)
  214. // the user audit log should have been updated
  215. const auditLog = await this.user1.getAuditLogWithoutNoise()
  216. expect(auditLog).to.exist
  217. // find the clear-sessions entry
  218. const clearSessionsEntries = auditLog.filter(
  219. entry => entry.operation === 'clear-sessions'
  220. )
  221. expect(clearSessionsEntries.length).to.equal(1)
  222. expect(clearSessionsEntries[0].operation).to.equal('clear-sessions')
  223. expect(clearSessionsEntries[0].ipAddress).to.exist
  224. expect(clearSessionsEntries[0].initiatorId).to.exist
  225. expect(clearSessionsEntries[0].timestamp).to.exist
  226. expect(clearSessionsEntries[0].info.sessions.length).to.equal(2)
  227. })
  228. })
  229. describe('validationToken', function () {
  230. const User = UserHelper.promises
  231. async function tryWithValidationToken(validationToken) {
  232. const user = new User()
  233. await user.login()
  234. await checkSessionIsValid(user)
  235. const [, sid] = user.sessionCookie().value.match(/^s:(.+?)\./)
  236. const key = `sess:${sid}`
  237. const sess = JSON.parse(await rclient.get(key))
  238. expect(sess.validationToken).to.equal('v1:' + sid.slice(-4))
  239. sess.validationToken = validationToken
  240. await rclient.set(key, JSON.stringify(sess))
  241. {
  242. // The current code destroys the session and throws an error/500.
  243. // Check for login redirect on page reload.
  244. await user.doRequest('GET', '/project')
  245. const { response } = await user.doRequest('GET', '/project')
  246. expect(response.statusCode).to.equal(302)
  247. expect(response.headers.location).to.equal('/login?')
  248. }
  249. }
  250. async function getOtherUsersValidationToken() {
  251. const otherUser = new User()
  252. await otherUser.login()
  253. await checkSessionIsValid(otherUser)
  254. const { validationToken } = await otherUser.getSession()
  255. expect(validationToken).to.match(/^v1:.{4}$/)
  256. return validationToken
  257. }
  258. async function checkSessionIsValid(user) {
  259. const { response } = await user.doRequest('GET', '/project')
  260. expect(response.statusCode).to.equal(200)
  261. }
  262. it('should reject the redis value when missing', async function () {
  263. await tryWithValidationToken(undefined)
  264. })
  265. it('should reject the redis value when empty', async function () {
  266. await tryWithValidationToken('')
  267. })
  268. it('should reject the redis value when out of sync', async function () {
  269. await tryWithValidationToken(await getOtherUsersValidationToken())
  270. })
  271. it('should ignore overwrites in app code', async function () {
  272. const otherUsersValidationToken = await getOtherUsersValidationToken()
  273. const user = new User()
  274. await user.login()
  275. await checkSessionIsValid(user)
  276. const { validationToken: token1 } = await user.getSession()
  277. const allowedUpdateValue = 'allowed-update-value'
  278. await user.setInSession({
  279. validationToken: otherUsersValidationToken,
  280. // also update another field to check that the write operation went through
  281. allowedUpdate: allowedUpdateValue,
  282. })
  283. const { validationToken: token2, allowedUpdate } = await user.getSession()
  284. expect(allowedUpdate).to.equal(allowedUpdateValue)
  285. expect(token1).to.equal(token2)
  286. await checkSessionIsValid(user)
  287. })
  288. })
  289. describe('analyticsIdMiddleware', function () {
  290. async function getCacheMetric() {
  291. const hit = await Metrics.promises.getMetric(
  292. s => s.includes('analyticsIdMiddleware') && s.includes('hit')
  293. )
  294. const miss = await Metrics.promises.getMetric(
  295. s => s.includes('analyticsIdMiddleware') && s.includes('miss')
  296. )
  297. return { hit, miss }
  298. }
  299. let usersAnalyticsId
  300. beforeEach(function () {
  301. if (!Features.hasFeature('saas')) {
  302. this.skip()
  303. }
  304. usersAnalyticsId = this.user1.analyticsId
  305. expect(usersAnalyticsId).to.match(/^[0-9a-f-]{36}$/)
  306. })
  307. it('should resolve to the users analyticsId', async function () {
  308. await this.user1.login()
  309. const session = await this.user1.getSession()
  310. expect(session.analyticsId).to.equal(usersAnalyticsId)
  311. })
  312. it('should not lookup the users analyticsId after login', async function () {
  313. const prev = await getCacheMetric()
  314. await this.user1.login()
  315. for (let i = 0; i < 5; i++) {
  316. await this.user1.doRequest('GET', '/project')
  317. }
  318. const current = await getCacheMetric()
  319. expect(current).to.deep.equal(prev)
  320. const session = await this.user1.getSession()
  321. expect(session.analyticsId).to.equal(usersAnalyticsId)
  322. })
  323. it('should lookup the users analyticsId for old session', async function () {
  324. usersAnalyticsId = this.user1._id
  325. await this.user1.mongoUpdate({
  326. $set: { analyticsId: usersAnalyticsId },
  327. })
  328. const prev = await getCacheMetric()
  329. await this.user1.login()
  330. let session = await this.user1.getSession()
  331. await this.user1.setInSession({
  332. analyticsId: null,
  333. passport: {
  334. ...session.passport,
  335. user: {
  336. ...session.passport.user,
  337. analyticsId: null,
  338. },
  339. },
  340. })
  341. await UserAnalyticsDataCache.reset()
  342. for (let i = 0; i < 5; i++) {
  343. await this.user1.doRequest('GET', '/project')
  344. }
  345. const current = await getCacheMetric()
  346. expect(current).to.deep.equal({
  347. hit: prev.hit,
  348. miss: prev.miss + 1,
  349. })
  350. session = await this.user1.getSession()
  351. expect(session.analyticsId).to.equal(usersAnalyticsId)
  352. })
  353. })
  354. })