check_client_ip_job_test.go 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package job
  2. import (
  3. "reflect"
  4. "testing"
  5. )
  6. func TestMergeClientIps_EvictsStaleOldEntries(t *testing.T) {
  7. // #4077: after a ban expires, a single IP that reconnects used to get
  8. // banned again immediately because a long-disconnected IP stayed in the
  9. // DB with an ancient timestamp and kept "protecting" itself against
  10. // eviction. Guard against that regression here.
  11. old := []IPWithTimestamp{
  12. {IP: "1.1.1.1", Timestamp: 100}, // stale — client disconnected long ago
  13. {IP: "2.2.2.2", Timestamp: 1900}, // fresh — still connecting
  14. }
  15. new := []IPWithTimestamp{
  16. {IP: "2.2.2.2", Timestamp: 2000}, // same IP, newer log line
  17. }
  18. got := mergeClientIps(old, new, 1000)
  19. want := map[string]int64{"2.2.2.2": 2000}
  20. if !reflect.DeepEqual(got, want) {
  21. t.Fatalf("stale 1.1.1.1 should have been dropped\ngot: %v\nwant: %v", got, want)
  22. }
  23. }
  24. func TestMergeClientIps_KeepsFreshOldEntriesUnchanged(t *testing.T) {
  25. // Backwards-compat: entries that aren't stale are still carried forward,
  26. // so enforcement survives access-log rotation.
  27. old := []IPWithTimestamp{
  28. {IP: "1.1.1.1", Timestamp: 1500},
  29. }
  30. got := mergeClientIps(old, nil, 1000)
  31. want := map[string]int64{"1.1.1.1": 1500}
  32. if !reflect.DeepEqual(got, want) {
  33. t.Fatalf("fresh old IP should have been retained\ngot: %v\nwant: %v", got, want)
  34. }
  35. }
  36. func TestMergeClientIps_PrefersLaterTimestampForSameIp(t *testing.T) {
  37. old := []IPWithTimestamp{{IP: "1.1.1.1", Timestamp: 1500}}
  38. new := []IPWithTimestamp{{IP: "1.1.1.1", Timestamp: 1700}}
  39. got := mergeClientIps(old, new, 1000)
  40. if got["1.1.1.1"] != 1700 {
  41. t.Fatalf("expected latest timestamp 1700, got %d", got["1.1.1.1"])
  42. }
  43. }
  44. func TestMergeClientIps_DropsStaleNewEntries(t *testing.T) {
  45. // A log line with a clock-skewed old timestamp must not resurrect a
  46. // stale IP past the cutoff.
  47. new := []IPWithTimestamp{{IP: "1.1.1.1", Timestamp: 500}}
  48. got := mergeClientIps(nil, new, 1000)
  49. if len(got) != 0 {
  50. t.Fatalf("stale new IP should have been dropped, got %v", got)
  51. }
  52. }
  53. func TestMergeClientIps_NoStaleCutoffStillWorks(t *testing.T) {
  54. // Defensive: a zero cutoff (e.g. during very first run on a fresh
  55. // install) must not over-evict.
  56. old := []IPWithTimestamp{{IP: "1.1.1.1", Timestamp: 100}}
  57. new := []IPWithTimestamp{{IP: "2.2.2.2", Timestamp: 200}}
  58. got := mergeClientIps(old, new, 0)
  59. want := map[string]int64{"1.1.1.1": 100, "2.2.2.2": 200}
  60. if !reflect.DeepEqual(got, want) {
  61. t.Fatalf("zero cutoff should keep everything\ngot: %v\nwant: %v", got, want)
  62. }
  63. }