| 1 | // SPDX-License-Identifier: AGPL-3.0-or-later |
| 2 | |
| 3 | package ssrf |
| 4 | |
| 5 | import ( |
| 6 | "net" |
| 7 | "strings" |
| 8 | "testing" |
| 9 | ) |
| 10 | |
| 11 | func TestValidateRejectsBadShapes(t *testing.T) { |
| 12 | c := Default() |
| 13 | cases := []struct { |
| 14 | name, url, wantSubstr string |
| 15 | }{ |
| 16 | {"empty", "", "scheme not allowed"}, |
| 17 | {"file scheme", "file:///etc/passwd", "scheme file not allowed"}, |
| 18 | {"ftp scheme", "ftp://example.com/", "scheme ftp not allowed"}, |
| 19 | {"missing host", "http:///path", "missing host"}, |
| 20 | {"non-allowed port", "http://example.com:9999/x", "port 9999"}, |
| 21 | } |
| 22 | for _, tc := range cases { |
| 23 | t.Run(tc.name, func(t *testing.T) { |
| 24 | err := c.Validate(tc.url) |
| 25 | if err == nil { |
| 26 | t.Fatalf("Validate(%q) = nil; want *Error", tc.url) |
| 27 | } |
| 28 | if !strings.Contains(err.Error(), tc.wantSubstr) { |
| 29 | t.Fatalf("Validate(%q) = %q; want substring %q", tc.url, err, tc.wantSubstr) |
| 30 | } |
| 31 | }) |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | func TestValidatePassesGoodShapes(t *testing.T) { |
| 36 | c := Default() |
| 37 | for _, u := range []string{ |
| 38 | "http://example.com/x", |
| 39 | "https://example.com:443/x", |
| 40 | "http://example.com:8080/y", |
| 41 | "https://example.com:8443/y", |
| 42 | } { |
| 43 | if err := c.Validate(u); err != nil { |
| 44 | t.Fatalf("Validate(%q) = %v; want nil", u, err) |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | func TestIsForbiddenIPClassifiesCorrectly(t *testing.T) { |
| 50 | forbidden := []string{ |
| 51 | "127.0.0.1", "127.255.255.254", |
| 52 | "10.0.0.1", "10.255.255.255", |
| 53 | "172.16.0.1", "172.31.255.255", |
| 54 | "192.168.0.1", |
| 55 | "100.64.0.1", |
| 56 | "169.254.169.254", |
| 57 | "0.0.0.0", |
| 58 | "255.255.255.255", |
| 59 | "::1", |
| 60 | "fe80::1", |
| 61 | "fd00::1", |
| 62 | "fc00::1", |
| 63 | } |
| 64 | for _, addr := range forbidden { |
| 65 | ip := net.ParseIP(addr) |
| 66 | if !IsForbiddenIP(ip) { |
| 67 | t.Errorf("IsForbiddenIP(%q) = false; want true", addr) |
| 68 | } |
| 69 | } |
| 70 | for _, addr := range []string{"1.1.1.1", "8.8.8.8", "203.0.113.5", "2001:4860:4860::8888"} { |
| 71 | ip := net.ParseIP(addr) |
| 72 | if IsForbiddenIP(ip) { |
| 73 | t.Errorf("IsForbiddenIP(%q) = true; want false", addr) |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | func TestIs(t *testing.T) { |
| 79 | if !Is(Default().Validate("file:///etc/passwd")) { |
| 80 | t.Fatal("Is should match") |
| 81 | } |
| 82 | if Is(nil) { |
| 83 | t.Fatal("Is(nil) should be false") |
| 84 | } |
| 85 | } |
| 86 |