| 1 | package managedproxy |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "fmt" |
| 7 | "io" |
| 8 | "net/http" |
| 9 | "net/http/httptest" |
| 10 | "net/netip" |
| 11 | "os" |
| 12 | "path/filepath" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | |
| 16 | "github.com/sylvinus/agent-vm/internal/host" |
| 17 | "go.yaml.in/yaml/v3" |
| 18 | ) |
| 19 | |
| 20 | func TestCumulativeImportsPreserveReadableStoreOnOverflow(t *testing.T) { |
| 21 | profile := t.TempDir() |
| 22 | s, err := Load(profile) |
| 23 | if err != nil { |
| 24 | t.Fatal(err) |
| 25 | } |
| 26 | data := []byte("proxies:\n - name: synthetic\n type: socks5\n server: example.com\n port: 1080\n password: " + strings.Repeat("x", 7<<20) + "\n") |
| 27 | for i := 0; i < 4; i++ { |
| 28 | if err := s.Import(fmt.Sprintf("source-%d", i), "", data, "", 0, ""); err != nil { |
| 29 | t.Fatal(err) |
| 30 | } |
| 31 | if err := s.Save(profile); err != nil { |
| 32 | t.Fatal(err) |
| 33 | } |
| 34 | } |
| 35 | path := filepath.Join(Dir(profile), "sources.json") |
| 36 | before, err := os.ReadFile(path) |
| 37 | if err != nil { |
| 38 | t.Fatal(err) |
| 39 | } |
| 40 | if err := s.Import("overflow", "", data, "", 0, ""); err != nil { |
| 41 | t.Fatal("individual import should remain within its input limit", err) |
| 42 | } |
| 43 | if err := s.Save(profile); err == nil { |
| 44 | t.Fatal("cumulative imports saved an unreadable store") |
| 45 | } |
| 46 | after, err := os.ReadFile(path) |
| 47 | if err != nil || !bytes.Equal(before, after) { |
| 48 | t.Fatal("failed save changed the previous file", err) |
| 49 | } |
| 50 | loaded, err := Load(profile) |
| 51 | if err != nil || len(loaded.Sources) != 4 || loaded.Auth != s.Auth { |
| 52 | t.Fatal("previous sources could not be recovered after rejected import", err) |
| 53 | } |
| 54 | |
| 55 | loaded.Sources = loaded.Sources[:3] |
| 56 | if err := loaded.Save(profile); err != nil { |
| 57 | t.Fatal(err) |
| 58 | } |
| 59 | if loaded, err := Load(profile); err != nil || len(loaded.Sources) != 3 { |
| 60 | t.Fatal("source removal failed after rejected import", err) |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | func TestStoreLimitCoversSerializedBytesAndAllowsExactLimit(t *testing.T) { |
| 65 | profile := t.TempDir() |
| 66 | s, _ := Load(profile) |
| 67 | if err := s.Import("source", "", []byte(testNodes), "source", 0, ""); err != nil { |
| 68 | t.Fatal(err) |
| 69 | } |
| 70 | s.Sources[0].Nodes[0].Config["password"] = "" |
| 71 | if err := s.Save(profile); err != nil { |
| 72 | t.Fatal(err) |
| 73 | } |
| 74 | path := filepath.Join(Dir(profile), "sources.json") |
| 75 | base, err := os.Stat(path) |
| 76 | if err != nil { |
| 77 | t.Fatal(err) |
| 78 | } |
| 79 | padding := strings.Repeat("x", maxStoreSize-int(base.Size())) |
| 80 | s.Sources[0].Nodes[0].Config["password"] = padding |
| 81 | if err := s.Save(profile); err != nil { |
| 82 | t.Fatal("exact limit was rejected", err) |
| 83 | } |
| 84 | if info, err := os.Stat(path); err != nil || info.Size() != maxStoreSize { |
| 85 | t.Fatal("fixture did not reach the exact serialized limit", err) |
| 86 | } |
| 87 | if _, err := Load(profile); err != nil { |
| 88 | t.Fatal("exact-size saved store was not readable", err) |
| 89 | } |
| 90 | |
| 91 | |
| 92 | s.Sources[0].Nodes[0].Config["password"] = padding[:len(padding)-1] + "<" |
| 93 | if err := s.Save(profile); err == nil { |
| 94 | t.Fatal("JSON expansion bypassed the persisted-size limit") |
| 95 | } |
| 96 | loaded, err := Load(profile) |
| 97 | if err != nil || loaded.Sources[0].Nodes[0].Config["password"] != padding { |
| 98 | t.Fatal("overflow replaced the exact-size previous store", err) |
| 99 | } |
| 100 | } |
| 101 | |
| 102 | const testNodes = `mixed-port: 7890 |
| 103 | external-controller: 0.0.0.0:9090 |
| 104 | tun: {enable: true} |
| 105 | rules: [MATCH,DIRECT] |
| 106 | proxies: |
| 107 | - {name: edge, type: socks5, server: 127.0.0.1, port: 1080, password: private-secret} |
| 108 | - {name: chained, type: http, server: 127.0.0.1, port: 8080, dialer-proxy: edge} |
| 109 | ` |
| 110 | |
| 111 | func TestImportCompilesOnlyOwnedNetworkBoundary(t *testing.T) { |
| 112 | s, err := Load(t.TempDir()) |
| 113 | if err != nil { |
| 114 | t.Fatal(err) |
| 115 | } |
| 116 | if err = s.Import("test", "", []byte(testNodes), "source", 0, ""); err != nil { |
| 117 | t.Fatal(err) |
| 118 | } |
| 119 | s.Selected = s.Sources[0].Nodes[1].ID |
| 120 | b, err := s.Runtime("/tmp/qa") |
| 121 | if err != nil { |
| 122 | t.Fatal(err) |
| 123 | } |
| 124 | var config map[string]any |
| 125 | if yaml.Unmarshal(b, &config) != nil { |
| 126 | t.Fatal("invalid runtime") |
| 127 | } |
| 128 | if config["mixed-port"] != 17896 || config["allow-lan"] != false || config["ipv6"] != false || config["external-controller"] != nil { |
| 129 | t.Fatalf("import changed boundary: %v", config) |
| 130 | } |
| 131 | if !strings.Contains(string(b), "MATCH,CAGE") || strings.Contains(string(b), "DIRECT") || strings.Contains(string(b), "enable: true\nproxies:") { |
| 132 | t.Fatal("unsafe imported routing") |
| 133 | } |
| 134 | if config["tun"].(map[string]any)["enable"] != false { |
| 135 | t.Fatal("TUN enabled") |
| 136 | } |
| 137 | if config["unified-delay"] != true { |
| 138 | t.Fatal("node latency includes connection setup instead of an established-connection request") |
| 139 | } |
| 140 | if s.Sources[0].Nodes[1].Config["dialer-proxy"] != s.Sources[0].Nodes[0].ID { |
| 141 | t.Fatal("chain not namespaced") |
| 142 | } |
| 143 | profile := t.TempDir() |
| 144 | if err = s.Save(profile); err != nil { |
| 145 | t.Fatal(err) |
| 146 | } |
| 147 | if err := host.CheckPrivateFile(filepath.Join(Dir(profile), "sources.json")); err != nil { |
| 148 | t.Fatalf("source credentials not private: %v", err) |
| 149 | } |
| 150 | loaded, err := Load(profile) |
| 151 | if err != nil || loaded.Endpoint() != s.Endpoint() { |
| 152 | t.Fatal("credentials not stable") |
| 153 | } |
| 154 | } |
| 155 | func TestImportRejectsFilesDirectAndCycles(t *testing.T) { |
| 156 | for _, nodes := range []string{ |
| 157 | `proxies: [{name: test, type: http, server: example.com, port: 80, interface-name: en0}]`, |
| 158 | `proxies: [{name: test, type: socks5, server: example.com, port: 80, dialer-proxy: DIRECT}]`, |
| 159 | `proxies: [{name: test, type: socks5, server: example.com, port: 80, dialer-proxy: test}]`, |
| 160 | `proxies: [{name: test, type: http, server: example.com, port: 80, ws-opts: {private-key: /etc/passwd}}]`, |
| 161 | `proxies: [{name: test, type: mieru, server: example.com, port: 443, transport: TCP, username: test-user, password: test-password, interface-name: en0}]`, |
| 162 | `proxies: [{name: test, type: mieru, server: example.com, port: 443, transport: TCP, username: test-user, password: test-password, tls-opts: {ca: /etc/passwd}}]`, |
| 163 | `proxies: [{name: duplicate, type: http, server: a, port: 80}, {name: duplicate, type: http, server: b, port: 80}]`, |
| 164 | } { |
| 165 | if _, err := Parse([]byte(nodes), "test"); err == nil { |
| 166 | t.Fatal("unsafe import accepted") |
| 167 | } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | func TestAnyTLSIdleSessionOptionsRemainCompatible(t *testing.T) { |
| 172 | _, err := Parse([]byte(`proxies: [{name: qa, type: anytls, server: example.com, port: 443, password: secret, idle-session-check-interval: 30, idle-session-timeout: 30, min-idle-session: 0}]`), "source") |
| 173 | if err != nil { |
| 174 | t.Fatal(err) |
| 175 | } |
| 176 | } |
| 177 | |
| 178 | func TestMieruMixedSubscription(t *testing.T) { |
| 179 | |
| 180 | var data strings.Builder |
| 181 | data.WriteString("proxies:\n") |
| 182 | for i := 0; i < 113; i++ { |
| 183 | fmt.Fprintf(&data, " - {name: vless-%d, type: vless, server: example.com, port: 443, uuid: 00000000-0000-4000-8000-000000000001}\n", i) |
| 184 | } |
| 185 | for i := 0; i < 19; i++ { |
| 186 | fmt.Fprintf(&data, " - {name: mieru-%d, type: mieru, server: example.com, port: 443, username: test-user, password: test-password, transport: TCP, udp: true}\n", i) |
| 187 | } |
| 188 | profile := t.TempDir() |
| 189 | s, err := Load(profile) |
| 190 | if err != nil { |
| 191 | t.Fatal(err) |
| 192 | } |
| 193 | if err := s.Import("mixed", "", []byte(data.String()), "source", 24, ""); err != nil { |
| 194 | t.Fatal(err) |
| 195 | } |
| 196 | if s.Count() != 132 { |
| 197 | t.Fatalf("imported %d nodes, want 132", s.Count()) |
| 198 | } |
| 199 | s.Selected = s.Sources[0].Nodes[113].ID |
| 200 | if err := s.Save(profile); err != nil { |
| 201 | t.Fatal(err) |
| 202 | } |
| 203 | loaded, err := Load(profile) |
| 204 | if err != nil { |
| 205 | t.Fatal(err) |
| 206 | } |
| 207 | node, ok := loaded.Find(s.Selected) |
| 208 | if !ok || node.Type != "mieru" || node.Config["transport"] != "TCP" || node.Config["username"] != "test-user" || node.Config["password"] != "test-password" || node.Config["udp"] != false { |
| 209 | t.Fatal("Mieru options or Cage UDP boundary lost during persistence") |
| 210 | } |
| 211 | other, err := Parse([]byte(data.String()), "source") |
| 212 | if err != nil || other[113].ID != node.ID { |
| 213 | t.Fatal("refresh changed Mieru node identity", err) |
| 214 | } |
| 215 | checkMieruRuntime(t, profile, loaded) |
| 216 | } |
| 217 | |
| 218 | func TestMieruTransportOptions(t *testing.T) { |
| 219 | for _, root := range []string{"proxies", "payload"} { |
| 220 | t.Run(root, func(t *testing.T) { |
| 221 | s, err := Load(t.TempDir()) |
| 222 | if err != nil { |
| 223 | t.Fatal(err) |
| 224 | } |
| 225 | data := root + `: [{name: mieru-udp, type: mieru, server: example.com, port-range: 8000-8010, username: test-user, password: test-password, transport: UDP, multiplexing: MULTIPLEXING_LOW, handshake-mode: HANDSHAKE_STANDARD}]` |
| 226 | if err := s.Import("mieru", "", []byte(data), "source", 0, ""); err != nil { |
| 227 | t.Fatal(err) |
| 228 | } |
| 229 | s.Selected = s.Sources[0].Nodes[0].ID |
| 230 | checkMieruRuntime(t, t.TempDir(), s) |
| 231 | }) |
| 232 | } |
| 233 | } |
| 234 | |
| 235 | func checkMieruRuntime(t *testing.T, profile string, s Store) { |
| 236 | t.Helper() |
| 237 | b, err := s.Runtime(profile) |
| 238 | if err != nil { |
| 239 | t.Fatal(err) |
| 240 | } |
| 241 | var config struct { |
| 242 | Proxies []map[string]any `yaml:"proxies"` |
| 243 | } |
| 244 | if err := yaml.Unmarshal(b, &config); err != nil { |
| 245 | t.Fatal(err) |
| 246 | } |
| 247 | if len(config.Proxies) != s.Count() { |
| 248 | t.Fatal("runtime lost imported nodes") |
| 249 | } |
| 250 | for _, node := range config.Proxies { |
| 251 | if node["type"] == "mieru" && (node["transport"] == nil || node["udp"] != false) { |
| 252 | t.Fatal("runtime lost Mieru transport or enabled guest UDP") |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | |
| 257 | if os.Getenv("CAGE_PROXY_INTEGRATION") == "1" { |
| 258 | if err := Validate(context.Background(), profile, s); err != nil { |
| 259 | t.Fatal(err) |
| 260 | } |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | func TestRefreshIdentityAndInvalidUpdatePreserveNodes(t *testing.T) { |
| 265 | s, _ := Load(t.TempDir()) |
| 266 | if err := s.Import("test", "https://example.com/sub?secret=x", []byte(testNodes), "source", 24, ""); err != nil { |
| 267 | t.Fatal(err) |
| 268 | } |
| 269 | id := s.Sources[0].Nodes[0].ID |
| 270 | if err := s.Import("test", "", []byte("not: a subscription"), "source", 24, ""); err == nil { |
| 271 | t.Fatal("bad source accepted") |
| 272 | } |
| 273 | if s.Sources[0].Nodes[0].ID != id { |
| 274 | t.Fatal("failed update lost nodes") |
| 275 | } |
| 276 | if err := s.Import("test", "", []byte(testNodes), "source", 24, ""); err != nil || s.Sources[0].Nodes[0].ID != id { |
| 277 | t.Fatal("refresh changed node identity") |
| 278 | } |
| 279 | other, _ := Parse([]byte(testNodes), "other") |
| 280 | if other[0].ID == id { |
| 281 | t.Fatal("sources collide") |
| 282 | } |
| 283 | } |
| 284 | func TestSubscriptionFetchAndMetadata(t *testing.T) { |
| 285 | server := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 286 | if r.UserAgent() != "clash.meta/Cage" { |
| 287 | t.Error("incorrect subscription user agent") |
| 288 | } |
| 289 | w.Header().Set("Subscription-Userinfo", "upload=2; download=3; total=100; expire=123; secret=credential") |
| 290 | io.WriteString(w, testNodes) |
| 291 | })) |
| 292 | defer server.Close() |
| 293 | data, usage, err := Fetch(context.Background(), server.Client(), server.URL) |
| 294 | if err != nil || string(data) != testNodes || usage != "upload=2; download=3; total=100; expire=123" { |
| 295 | t.Fatalf("fetch: %s %v", usage, err) |
| 296 | } |
| 297 | if _, _, err = Fetch(context.Background(), server.Client(), "http://example.com"); err == nil { |
| 298 | t.Fatal("insecure subscription accepted") |
| 299 | } |
| 300 | } |
| 301 | func TestBootstrapDoesNotAllowPrivateDestinations(t *testing.T) { |
| 302 | for _, ip := range []string{"127.0.0.1", "10.0.0.1", "169.254.169.254", "100.64.0.1", "198.18.0.1", "::1"} { |
| 303 | if publicIP(netip.MustParseAddr(ip)) { |
| 304 | t.Fatal("infrastructure private destination allowed") |
| 305 | } |
| 306 | } |
| 307 | } |