rack_attack.rb 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. # Copyright (C) 2012-2023 Zammad Foundation, https://zammad-foundation.org/
  2. #
  3. # Throttle password reset requests
  4. #
  5. API_V1_USERS__PASSWORD_RESET_PATH = '/api/v1/users/password_reset'.freeze
  6. Rack::Attack.throttle('limit password reset requests per username', limit: 3, period: 1.minute.to_i) do |req|
  7. if req.path.start_with?(API_V1_USERS__PASSWORD_RESET_PATH) && req.post?
  8. # Normalize to protect against rate limit bypasses.
  9. req.params['username'].to_s.downcase.gsub(%r{\s+}, '')
  10. end
  11. end
  12. Rack::Attack.throttle('limit password reset requests per source IP address', limit: 3, period: 1.minute.to_i) do |req|
  13. if req.path.start_with?(API_V1_USERS__PASSWORD_RESET_PATH) && req.post?
  14. req.ip
  15. end
  16. end
  17. #
  18. # Throttle admin auth requests
  19. #
  20. API_V1_USERS__ADMIN_PASSWORD_AUTH_PATH = '/api/v1/users/admin_password_auth'.freeze
  21. Rack::Attack.throttle('limit admi auth requests per username', limit: 3, period: 1.minute.to_i) do |req|
  22. if req.path.start_with?(API_V1_USERS__ADMIN_PASSWORD_AUTH_PATH) && req.post?
  23. # Normalize to protect against rate limit bypasses.
  24. req.params['username'].to_s.downcase.gsub(%r{\s+}, '')
  25. end
  26. end
  27. Rack::Attack.throttle('limit admin requests per source IP address', limit: 3, period: 1.minute.to_i) do |req|
  28. if req.path.start_with?(API_V1_USERS__ADMIN_PASSWORD_AUTH_PATH) && req.post?
  29. req.ip
  30. end
  31. end
  32. #
  33. # Throttle form submit requests
  34. #
  35. API_V1_FORM_SUBMIT_PATH = '/api/v1/form_submit'.freeze
  36. form_limit_by_ip_per_hour_proc = proc { Setting.get('form_ticket_create_by_ip_per_hour') || 20 }
  37. Rack::Attack.throttle('form submits per IP and hour', limit: form_limit_by_ip_per_hour_proc, period: 1.hour.to_i) do |req|
  38. if req.path.start_with?(API_V1_FORM_SUBMIT_PATH)
  39. req.ip
  40. end
  41. end
  42. form_limit_by_ip_per_day_proc = proc { Setting.get('form_ticket_create_by_ip_per_day') || 240 }
  43. Rack::Attack.throttle('form submits per IP and day', limit: form_limit_by_ip_per_day_proc, period: 1.day.to_i) do |req|
  44. if req.path.start_with?(API_V1_FORM_SUBMIT_PATH)
  45. req.ip
  46. end
  47. end
  48. form_limit_per_day_proc = proc { Setting.get('form_ticket_create_per_day') || 5000 }
  49. Rack::Attack.throttle('form submits per day', limit: form_limit_per_day_proc, period: 1.day.to_i) do |req|
  50. if req.path.start_with?(API_V1_FORM_SUBMIT_PATH)
  51. req.path
  52. end
  53. end