| 1 | package managedproxy |
| 2 | |
| 3 | import ( |
| 4 | "strings" |
| 5 | "testing" |
| 6 | |
| 7 | "go.yaml.in/yaml/v3" |
| 8 | ) |
| 9 | |
| 10 | func TestPhysicalInterfaceFollowsHardwareRouteAndSkipsTUN(t *testing.T) { |
| 11 | hardware := "Hardware Port: Wi-Fi\nDevice: en0\nHardware Port: USB Ethernet\nDevice: en7\n" |
| 12 | nwi := "IPv4 network interface information\n utun7 : flags : 0x7\n reach : 0x00000002 (Reachable)\n en7 : flags : 0x7\n reach : 0x00000002 (Reachable)\n en0 : flags : 0x7\n reach : 0x00000002 (Reachable)\nIPv6 network interface information\n" |
| 13 | for _, tc := range []struct { |
| 14 | name, route, want string |
| 15 | usable map[string]bool |
| 16 | }{ |
| 17 | {"wifi default", "interface: en0", "en0", map[string]bool{"en0": true, "en7": true, "utun7": true}}, |
| 18 | {"ethernet default", "interface: en7", "en7", map[string]bool{"en0": true, "en7": true}}, |
| 19 | {"TUN default uses physical priority", "interface: utun7", "en7", map[string]bool{"en0": true, "en7": true, "utun7": true}}, |
| 20 | {"unavailable ethernet", "interface: en7", "en0", map[string]bool{"en0": true}}, |
| 21 | {"no physical connection", "interface: utun7", "", map[string]bool{"utun7": true}}, |
| 22 | } { |
| 23 | t.Run(tc.name, func(t *testing.T) { |
| 24 | got, err := selectPhysicalInterface(tc.route, hardware, nwi, tc.usable) |
| 25 | if got != tc.want || (err != nil) != (tc.want == "") { |
| 26 | t.Fatalf("got %q, %v; want %q", got, err, tc.want) |
| 27 | } |
| 28 | }) |
| 29 | } |
| 30 | if _, err := selectPhysicalInterface("interface: en0", hardware, strings.ReplaceAll(nwi, "(Reachable)", "(Not Reachable)"), map[string]bool{"en0": true, "en7": true}); err == nil { |
| 31 | t.Fatal("selected an unreachable interface") |
| 32 | } |
| 33 | } |
| 34 | |
| 35 | func TestBindingPreservesProxyChainAndReplacesStaleNodeBinding(t *testing.T) { |
| 36 | data := []byte("interface-name: en0\nrules: ['MATCH,exit']\nproxies:\n - {name: entry, type: socks5, server: 203.0.113.1, port: 1080, password: secret, interface-name: en0}\n - {name: exit, type: http, server: 203.0.113.2, port: 443, dialer-proxy: entry}\n") |
| 37 | bound, err := BindInterface(data, "en7") |
| 38 | if err != nil { |
| 39 | t.Fatal(err) |
| 40 | } |
| 41 | var config map[string]any |
| 42 | if err := yaml.Unmarshal(bound, &config); err != nil { |
| 43 | t.Fatal(err) |
| 44 | } |
| 45 | nodes := config["proxies"].([]any) |
| 46 | if config["interface-name"] != "en7" || nodes[0].(map[string]any)["interface-name"] != "en7" || nodes[0].(map[string]any)["password"] != "secret" || nodes[1].(map[string]any)["dialer-proxy"] != "entry" || config["rules"].([]any)[0] != "MATCH,exit" { |
| 47 | t.Fatal("binding changed the proxy chain or kept a stale interface") |
| 48 | } |
| 49 | if _, err := BindInterface(data, ""); err == nil { |
| 50 | t.Fatal("unbound fallback accepted") |
| 51 | } |
| 52 | } |