LoginRateLimiterTests.js 2.3 KB

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