LoginRateLimiter.test.mjs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. import { vi, expect } from 'vitest'
  2. import sinon from 'sinon'
  3. const modulePath = '../../../../app/src/Features/Security/LoginRateLimiter'
  4. describe('LoginRateLimiter', function () {
  5. beforeEach(async function (ctx) {
  6. ctx.email = 'bob@bob.com'
  7. ctx.rateLimiter = {
  8. consume: sinon.stub().resolves(),
  9. delete: sinon.stub().resolves(),
  10. }
  11. ctx.RateLimiter = {
  12. RateLimiter: sinon.stub().withArgs('login').returns(ctx.rateLimiter),
  13. }
  14. vi.doMock(
  15. '../../../../app/src/infrastructure/RateLimiter',
  16. () => ctx.RateLimiter
  17. )
  18. ctx.LoginRateLimiter = (await import(modulePath)).default
  19. })
  20. describe('processLoginRequest', function () {
  21. it('should consume points', async function (ctx) {
  22. await ctx.LoginRateLimiter.promises.processLoginRequest(ctx.email)
  23. expect(ctx.rateLimiter.consume).to.have.been.calledWith(ctx.email)
  24. })
  25. describe('when login is allowed', function () {
  26. it('should call pass allow=true', async function (ctx) {
  27. const allow = await ctx.LoginRateLimiter.promises.processLoginRequest(
  28. ctx.email
  29. )
  30. expect(allow).to.equal(true)
  31. })
  32. })
  33. describe('when login is blocked', function () {
  34. beforeEach(function (ctx) {
  35. ctx.rateLimiter.consume.rejects({ remainingPoints: 0 })
  36. })
  37. it('should call pass allow=false', async function (ctx) {
  38. const allow = await ctx.LoginRateLimiter.promises.processLoginRequest(
  39. ctx.email
  40. )
  41. expect(allow).to.equal(false)
  42. })
  43. })
  44. describe('when consume produces an error', function () {
  45. beforeEach(function (ctx) {
  46. ctx.rateLimiter.consume.rejects(new Error('woops'))
  47. })
  48. it('should produce an error', async function (ctx) {
  49. let error
  50. try {
  51. await ctx.LoginRateLimiter.promises.processLoginRequest(ctx.email)
  52. } catch (err) {
  53. error = err
  54. }
  55. expect(error).to.exist
  56. })
  57. })
  58. })
  59. describe('recordSuccessfulLogin', function () {
  60. it('should clear the rate limit', async function (ctx) {
  61. await ctx.LoginRateLimiter.promises.recordSuccessfulLogin(ctx.email)
  62. expect(ctx.rateLimiter.delete).to.have.been.calledWith(ctx.email)
  63. })
  64. })
  65. })