LoginRateLimiterTests.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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', function (done) {
  26. this.LoginRateLimiter.processLoginRequest(this.email, (err, allow) => {
  27. if (err) {
  28. return done(err)
  29. }
  30. expect(this.rateLimiter.consume).to.have.been.calledWith(this.email)
  31. done()
  32. })
  33. })
  34. describe('when login is allowed', function () {
  35. it('should call pass allow=true', function (done) {
  36. this.LoginRateLimiter.processLoginRequest(this.email, (err, allow) => {
  37. expect(err).to.equal(null)
  38. expect(allow).to.equal(true)
  39. done()
  40. })
  41. })
  42. })
  43. describe('when login is blocked', function () {
  44. beforeEach(function () {
  45. this.rateLimiter.consume.rejects({ remainingPoints: 0 })
  46. })
  47. it('should call pass allow=false', function (done) {
  48. this.LoginRateLimiter.processLoginRequest(this.email, (err, allow) => {
  49. expect(err).to.equal(null)
  50. expect(allow).to.equal(false)
  51. done()
  52. })
  53. })
  54. })
  55. describe('when consume produces an error', function () {
  56. beforeEach(function () {
  57. this.rateLimiter.consume.rejects(new Error('woops'))
  58. })
  59. it('should produce an error', function (done) {
  60. this.LoginRateLimiter.processLoginRequest(this.email, (err, allow) => {
  61. expect(err).to.not.equal(null)
  62. expect(err).to.be.instanceof(Error)
  63. done()
  64. })
  65. })
  66. })
  67. })
  68. describe('recordSuccessfulLogin', function () {
  69. it('should clear the rate limit', function (done) {
  70. this.LoginRateLimiter.recordSuccessfulLogin(this.email, () => {
  71. expect(this.rateLimiter.delete).to.have.been.calledWith(this.email)
  72. done()
  73. })
  74. })
  75. })
  76. })