|
| 1 | +package rule |
| 2 | + |
| 3 | +import ( |
| 4 | + "net/http" |
| 5 | + "os" |
| 6 | + "testing" |
| 7 | + |
| 8 | + "github.com/casbin/caswaf/ip" |
| 9 | + "github.com/casbin/caswaf/object" |
| 10 | +) |
| 11 | + |
| 12 | +func init() { |
| 13 | + // Initialize IP database for tests |
| 14 | + // Check if we're in the rule directory and adjust path if needed |
| 15 | + if _, err := os.Stat("../ip/17monipdb.dat"); err == nil { |
| 16 | + os.Chdir("..") |
| 17 | + } |
| 18 | + ip.InitIpDb() |
| 19 | +} |
| 20 | + |
| 21 | +func TestIpRule_IsAbroad(t *testing.T) { |
| 22 | + ipRule := &IpRule{} |
| 23 | + |
| 24 | + tests := []struct { |
| 25 | + name string |
| 26 | + operator string |
| 27 | + value string |
| 28 | + clientIP string |
| 29 | + shouldMatch bool |
| 30 | + shouldError bool |
| 31 | + }{ |
| 32 | + { |
| 33 | + name: "is abroad with empty value - foreign IP", |
| 34 | + operator: "is abroad", |
| 35 | + value: "", |
| 36 | + clientIP: "8.8.8.8", |
| 37 | + shouldMatch: true, |
| 38 | + shouldError: false, |
| 39 | + }, |
| 40 | + { |
| 41 | + name: "is abroad with some value - foreign IP", |
| 42 | + operator: "is abroad", |
| 43 | + value: "1.1.1.1", |
| 44 | + clientIP: "8.8.8.8", |
| 45 | + shouldMatch: true, |
| 46 | + shouldError: false, |
| 47 | + }, |
| 48 | + { |
| 49 | + name: "is abroad with CIDR value - foreign IP", |
| 50 | + operator: "is abroad", |
| 51 | + value: "1.1.1.0/24", |
| 52 | + clientIP: "8.8.8.8", |
| 53 | + shouldMatch: true, |
| 54 | + shouldError: false, |
| 55 | + }, |
| 56 | + } |
| 57 | + |
| 58 | + for _, tt := range tests { |
| 59 | + t.Run(tt.name, func(t *testing.T) { |
| 60 | + expressions := []*object.Expression{ |
| 61 | + { |
| 62 | + Operator: tt.operator, |
| 63 | + Value: tt.value, |
| 64 | + }, |
| 65 | + } |
| 66 | + |
| 67 | + req := &http.Request{ |
| 68 | + RemoteAddr: tt.clientIP + ":1234", |
| 69 | + } |
| 70 | + |
| 71 | + result, err := ipRule.checkRule(expressions, req) |
| 72 | + |
| 73 | + if tt.shouldError && err == nil { |
| 74 | + t.Errorf("Expected error but got none") |
| 75 | + } |
| 76 | + if !tt.shouldError && err != nil { |
| 77 | + t.Errorf("Unexpected error: %v", err) |
| 78 | + } |
| 79 | + |
| 80 | + gotMatch := result != nil |
| 81 | + if gotMatch != tt.shouldMatch { |
| 82 | + t.Errorf("Expected match: %v, got: %v", tt.shouldMatch, gotMatch) |
| 83 | + } |
| 84 | + }) |
| 85 | + } |
| 86 | +} |
0 commit comments