ingress_reject_access_sampler.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. package middleware
  2. import (
  3. "sync"
  4. "time"
  5. )
  6. const (
  7. ingressRejectAccessLogLimit = 20
  8. ingressRejectAccessLogWindow = time.Second
  9. ingressRejectDroppedSummaryPeriod = 30 * time.Second
  10. )
  11. type ingressRejectAccessSampler struct {
  12. mu sync.Mutex
  13. limit int
  14. window time.Duration
  15. summaryPeriod time.Duration
  16. windowStart time.Time
  17. emitted int
  18. dropped uint64
  19. lastSummary time.Time
  20. }
  21. func newIngressRejectAccessSampler(limit int, window, summaryPeriod time.Duration) *ingressRejectAccessSampler {
  22. return &ingressRejectAccessSampler{limit: limit, window: window, summaryPeriod: summaryPeriod}
  23. }
  24. // allow applies one process-wide fixed-window budget. It stores no attacker
  25. // dimensions, so memory remains constant even for rotating keys and addresses.
  26. func (s *ingressRejectAccessSampler) allow(now time.Time) (allowed bool, droppedSummary uint64) {
  27. if s == nil || s.limit <= 0 || s.window <= 0 {
  28. return false, 0
  29. }
  30. s.mu.Lock()
  31. defer s.mu.Unlock()
  32. if s.windowStart.IsZero() || now.Sub(s.windowStart) >= s.window || now.Before(s.windowStart) {
  33. s.windowStart = now
  34. s.emitted = 0
  35. }
  36. if s.emitted < s.limit {
  37. s.emitted++
  38. return true, 0
  39. }
  40. s.dropped++
  41. if s.summaryPeriod > 0 && (s.lastSummary.IsZero() || now.Sub(s.lastSummary) >= s.summaryPeriod) {
  42. droppedSummary = s.dropped
  43. s.dropped = 0
  44. s.lastSummary = now
  45. }
  46. return false, droppedSummary
  47. }
  48. var globalIngressRejectAccessSampler = newIngressRejectAccessSampler(
  49. ingressRejectAccessLogLimit,
  50. ingressRejectAccessLogWindow,
  51. ingressRejectDroppedSummaryPeriod,
  52. )