ip_limit_allowlist_test.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package job
  2. import "testing"
  3. // Addresses in the examples below come from the documentation ranges reserved
  4. // by RFC 5737 and RFC 3849.
  5. func TestIpLimitAllowlistMatchesAddressesAndNetworks(t *testing.T) {
  6. list := parseIpLimitAllowlist("203.0.113.10, 198.51.100.0/24 , 2001:db8::/32, not-an-ip")
  7. for _, ip := range []string{"203.0.113.10", "198.51.100.7", "2001:db8::1"} {
  8. if !list.contains(ip) {
  9. t.Fatalf("%s should be allowlisted", ip)
  10. }
  11. }
  12. for _, ip := range []string{"203.0.113.11", "192.0.2.5", "2001:db9::1", ""} {
  13. if list.contains(ip) {
  14. t.Fatalf("%s must not be allowlisted", ip)
  15. }
  16. }
  17. }
  18. // A typo must not disable the limit for everybody, so an unparsable entry is
  19. // dropped and the rest of the list keeps working.
  20. func TestIpLimitAllowlistIgnoresUnparsableEntries(t *testing.T) {
  21. list := parseIpLimitAllowlist("nonsense, 203.0.113.0/24")
  22. if !list.contains("203.0.113.5") {
  23. t.Fatal("a valid entry stopped working because a neighbouring one was malformed")
  24. }
  25. if list.contains("192.0.2.1") {
  26. t.Fatal("a malformed entry must not widen the allowlist")
  27. }
  28. if parseIpLimitAllowlist("nonsense").empty() != true {
  29. t.Fatal("a list of only malformed entries must be empty, not permissive")
  30. }
  31. }
  32. // The point of the setting: a shared address is neither banned nor counted, so
  33. // the office NAT it protects does not consume the client's limit either.
  34. func TestIpLimitAllowlistSplitKeepsAllowedOutOfTheCount(t *testing.T) {
  35. live := []IPWithTimestamp{
  36. {IP: "203.0.113.10", Timestamp: 1},
  37. {IP: "192.0.2.1", Timestamp: 2},
  38. {IP: "192.0.2.2", Timestamp: 3},
  39. }
  40. list := parseIpLimitAllowlist("203.0.113.10")
  41. limited, allowed := list.split(live)
  42. if len(allowed) != 1 || allowed[0].IP != "203.0.113.10" {
  43. t.Fatalf("allowed = %v, want the allowlisted address alone", allowed)
  44. }
  45. if len(limited) != 2 {
  46. t.Fatalf("limited = %v, want the two ordinary addresses", limited)
  47. }
  48. kept, banned := selectIpsToBan(limited, 2)
  49. if len(banned) != 0 {
  50. t.Fatalf("banned = %v, want none: the allowlisted address must not push an ordinary one over the limit", banned)
  51. }
  52. if len(kept) != 2 {
  53. t.Fatalf("kept = %v, want both ordinary addresses", kept)
  54. }
  55. }
  56. func TestIpLimitAllowlistEmptyListChangesNothing(t *testing.T) {
  57. live := []IPWithTimestamp{{IP: "192.0.2.1", Timestamp: 1}, {IP: "192.0.2.2", Timestamp: 2}}
  58. limited, allowed := parseIpLimitAllowlist("").split(live)
  59. if allowed != nil || len(limited) != 2 {
  60. t.Fatalf("empty allowlist changed the input: limited=%v allowed=%v", limited, allowed)
  61. }
  62. }