1
0

golden_fixtures_xray_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. package service
  2. import (
  3. "crypto/ecdsa"
  4. "crypto/elliptic"
  5. "crypto/rand"
  6. "crypto/x509"
  7. "crypto/x509/pkix"
  8. "encoding/json"
  9. "encoding/pem"
  10. "maps"
  11. "math/big"
  12. "os"
  13. "path/filepath"
  14. "sort"
  15. "strings"
  16. "testing"
  17. "time"
  18. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  19. "github.com/xtls/xray-core/infra/conf"
  20. )
  21. // The frontend's golden fixtures are the panel's model of an xray config: the
  22. // Zod snapshots pin what the forms parse and emit. Parsing proves the panel
  23. // agrees with itself, not that xray-core would accept the result, so every
  24. // fixture is also built here through the very config builders the panel hands
  25. // its config to — conf.InboundDetourConfig for the full-config and AddInbound
  26. // paths, conf.RouterConfig for ApplyRoutingConfig, conf.DNSConfig for the dns
  27. // section. A fixture xray-core refuses is a config the panel would let an
  28. // admin save and then fail to start the core with, taking every inbound down.
  29. //
  30. // mtproto is excluded: it is served by the bundled mtg-multi sidecar, not by
  31. // xray, so xray-core has no config id for it.
  32. func goldenFixtureDir(t *testing.T, category string) string {
  33. t.Helper()
  34. dir, err := filepath.Abs(filepath.Join("..", "..", "..", "frontend", "src", "test", "golden", "fixtures", category))
  35. if err != nil {
  36. t.Fatalf("resolve fixture dir: %v", err)
  37. }
  38. return dir
  39. }
  40. // goldenFixtures returns every fixture in a category as name -> decoded object.
  41. func goldenFixtures(t *testing.T, category string) map[string]map[string]any {
  42. t.Helper()
  43. dir := goldenFixtureDir(t, category)
  44. entries, err := os.ReadDir(dir)
  45. if err != nil {
  46. t.Fatalf("read %s: %v", dir, err)
  47. }
  48. out := make(map[string]map[string]any)
  49. names := make([]string, 0, len(entries))
  50. for _, entry := range entries {
  51. if filepath.Ext(entry.Name()) != ".json" {
  52. continue
  53. }
  54. names = append(names, entry.Name())
  55. }
  56. sort.Strings(names)
  57. if len(names) == 0 {
  58. t.Fatalf("no fixtures under %s", dir)
  59. }
  60. for _, name := range names {
  61. raw, err := os.ReadFile(filepath.Join(dir, name))
  62. if err != nil {
  63. t.Fatalf("read %s: %v", name, err)
  64. }
  65. var obj map[string]any
  66. if err := json.Unmarshal(raw, &obj); err != nil {
  67. t.Fatalf("unmarshal %s: %v", name, err)
  68. }
  69. out[strings.TrimSuffix(name, ".json")] = obj
  70. }
  71. return out
  72. }
  73. // writeTestCertificate writes a self-signed certificate and key, returning both
  74. // paths. The TLS fixtures point certificateFile/keyFile at deployment paths
  75. // that do not exist here, and xray-core reads them while building.
  76. func writeTestCertificate(t *testing.T) (certPath, keyPath string) {
  77. t.Helper()
  78. key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  79. if err != nil {
  80. t.Fatalf("generate key: %v", err)
  81. }
  82. template := x509.Certificate{
  83. SerialNumber: big.NewInt(1),
  84. Subject: pkix.Name{CommonName: "golden-fixture.test"},
  85. NotBefore: time.Now().Add(-time.Hour),
  86. NotAfter: time.Now().Add(24 * time.Hour),
  87. DNSNames: []string{"golden-fixture.test"},
  88. }
  89. der, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
  90. if err != nil {
  91. t.Fatalf("create certificate: %v", err)
  92. }
  93. keyDER, err := x509.MarshalECPrivateKey(key)
  94. if err != nil {
  95. t.Fatalf("marshal key: %v", err)
  96. }
  97. dir := t.TempDir()
  98. certPath = filepath.Join(dir, "fixture.crt")
  99. keyPath = filepath.Join(dir, "fixture.key")
  100. certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})
  101. keyPEM := pem.EncodeToMemory(&pem.Block{Type: "EC PRIVATE KEY", Bytes: keyDER})
  102. if err := os.WriteFile(certPath, certPEM, 0o600); err != nil {
  103. t.Fatalf("write certificate: %v", err)
  104. }
  105. if err := os.WriteFile(keyPath, keyPEM, 0o600); err != nil {
  106. t.Fatalf("write key: %v", err)
  107. }
  108. return certPath, keyPath
  109. }
  110. // repointCertificateFiles rewrites every certificateFile/keyFile reference to
  111. // the generated pair, so a fixture is judged on its shape rather than on paths
  112. // that only exist on a deployed server.
  113. func repointCertificateFiles(node any, certPath, keyPath string) {
  114. switch value := node.(type) {
  115. case map[string]any:
  116. for key, child := range value {
  117. switch key {
  118. case "certificateFile":
  119. if _, ok := child.(string); ok {
  120. value[key] = certPath
  121. continue
  122. }
  123. case "keyFile":
  124. if _, ok := child.(string); ok {
  125. value[key] = keyPath
  126. continue
  127. }
  128. }
  129. repointCertificateFiles(child, certPath, keyPath)
  130. }
  131. case []any:
  132. for _, child := range value {
  133. repointCertificateFiles(child, certPath, keyPath)
  134. }
  135. }
  136. }
  137. // assertXrayAccepts fails unless xray-core built the fixture. Fixtures naming
  138. // geoip:/geosite: need the dat files the panel ships next to the xray binary;
  139. // where they are absent the loader fails on the missing file rather than on the
  140. // fixture, so those are skipped instead of reported as broken.
  141. func assertXrayAccepts(t *testing.T, subject string, err error) {
  142. t.Helper()
  143. if err == nil {
  144. return
  145. }
  146. if isMissingGeoAssetErr(err) {
  147. t.Skipf("geo data files not available, cannot judge %s: %v", subject, err)
  148. }
  149. t.Fatalf("xray-core refuses %s: %v", subject, err)
  150. }
  151. func buildGoldenInbound(t *testing.T, inbound map[string]any) error {
  152. t.Helper()
  153. certPath, keyPath := writeTestCertificate(t)
  154. repointCertificateFiles(inbound, certPath, keyPath)
  155. raw, err := json.Marshal(inbound)
  156. if err != nil {
  157. t.Fatalf("marshal inbound: %v", err)
  158. }
  159. detour := new(conf.InboundDetourConfig)
  160. if err := json.Unmarshal(raw, detour); err != nil {
  161. return err
  162. }
  163. _, err = detour.Build()
  164. return err
  165. }
  166. // TestGoldenInboundFixturesBuildInXray wraps each protocol fixture in a minimal
  167. // inbound and builds it.
  168. func TestGoldenInboundFixturesBuildInXray(t *testing.T) {
  169. for name, fixture := range goldenFixtures(t, "inbound") {
  170. if protocol, _ := fixture["protocol"].(string); protocol == string(model.MTProto) {
  171. continue
  172. }
  173. t.Run(name, func(t *testing.T) {
  174. inbound := map[string]any{
  175. "tag": "golden-in",
  176. "listen": "127.0.0.1",
  177. "port": 8443,
  178. "protocol": fixture["protocol"],
  179. "settings": fixture["settings"],
  180. }
  181. assertXrayAccepts(t, "this fixture", buildGoldenInbound(t, inbound))
  182. })
  183. }
  184. }
  185. // TestGoldenInboundFullFixturesBuildInXray runs the complete panel Inbound
  186. // model through GenXrayInboundConfig, the conversion both the full-config and
  187. // the live AddInbound paths use, and builds the result.
  188. func TestGoldenInboundFullFixturesBuildInXray(t *testing.T) {
  189. for name, fixture := range goldenFixtures(t, "inbound-full") {
  190. protocol, _ := fixture["protocol"].(string)
  191. if protocol == string(model.MTProto) {
  192. continue
  193. }
  194. t.Run(name, func(t *testing.T) {
  195. section := func(key string) string {
  196. value, ok := fixture[key]
  197. if !ok || value == nil {
  198. return ""
  199. }
  200. raw, err := json.Marshal(value)
  201. if err != nil {
  202. t.Fatalf("marshal %s: %v", key, err)
  203. }
  204. return string(raw)
  205. }
  206. port := 0
  207. if p, ok := fixture["port"].(float64); ok {
  208. port = int(p)
  209. }
  210. listen, _ := fixture["listen"].(string)
  211. tag, _ := fixture["tag"].(string)
  212. ib := &model.Inbound{
  213. Protocol: model.Protocol(protocol),
  214. Port: port,
  215. Listen: listen,
  216. Tag: tag,
  217. Settings: section("settings"),
  218. StreamSettings: section("streamSettings"),
  219. Sniffing: section("sniffing"),
  220. }
  221. raw, err := json.Marshal(ib.GenXrayInboundConfig())
  222. if err != nil {
  223. t.Fatalf("marshal generated inbound: %v", err)
  224. }
  225. var generated map[string]any
  226. if err := json.Unmarshal(raw, &generated); err != nil {
  227. t.Fatalf("decode generated inbound: %v", err)
  228. }
  229. assertXrayAccepts(t, "the generated inbound", buildGoldenInbound(t, generated))
  230. })
  231. }
  232. }
  233. // TestGoldenStreamFixturesBuildInXray attaches the transport fragments — whole
  234. // stream sections, the security block, sockopt and finalmask — to an inbound.
  235. func TestGoldenStreamFixturesBuildInXray(t *testing.T) {
  236. for _, category := range []string{"stream", "security", "sockopt", "finalmask"} {
  237. for name, fixture := range goldenFixtures(t, category) {
  238. t.Run(category+"/"+name, func(t *testing.T) {
  239. stream := map[string]any{"network": "tcp"}
  240. switch category {
  241. case "stream":
  242. stream = fixture
  243. case "security":
  244. maps.Copy(stream, fixture)
  245. case "sockopt":
  246. stream["sockopt"] = fixture
  247. case "finalmask":
  248. stream["finalmask"] = fixture
  249. }
  250. inbound := map[string]any{
  251. "tag": "golden-in", "listen": "127.0.0.1", "port": 8443, "protocol": "vless",
  252. "settings": map[string]any{
  253. "clients": []any{map[string]any{"id": "b831381d-6324-4d53-ad4f-8cda48b30811", "email": "golden"}},
  254. "decryption": "none",
  255. },
  256. "streamSettings": stream,
  257. }
  258. assertXrayAccepts(t, "this fixture", buildGoldenInbound(t, inbound))
  259. })
  260. }
  261. }
  262. }
  263. func buildGoldenRouting(routing map[string]any) error {
  264. raw, err := json.Marshal(routing)
  265. if err != nil {
  266. return err
  267. }
  268. router := new(conf.RouterConfig)
  269. if err := json.Unmarshal(raw, router); err != nil {
  270. return err
  271. }
  272. _, err = router.Build()
  273. return err
  274. }
  275. // TestGoldenRoutingFixturesBuildInXray builds the rule and balancer fixtures
  276. // through the router config ApplyRoutingConfig hands to the running core.
  277. func TestGoldenRoutingFixturesBuildInXray(t *testing.T) {
  278. for name, rule := range goldenFixtures(t, "rule") {
  279. t.Run("rule/"+name, func(t *testing.T) {
  280. assertXrayAccepts(t, "this rule", buildGoldenRouting(map[string]any{
  281. "domainStrategy": "AsIs",
  282. "rules": []any{rule},
  283. "balancers": []any{map[string]any{"tag": "balancer-load", "selector": []any{"proxy-"}}},
  284. }))
  285. })
  286. }
  287. for name, balancer := range goldenFixtures(t, "balancer") {
  288. t.Run("balancer/"+name, func(t *testing.T) {
  289. assertXrayAccepts(t, "this balancer", buildGoldenRouting(map[string]any{
  290. "domainStrategy": "AsIs",
  291. "balancers": []any{balancer},
  292. "rules": []any{map[string]any{
  293. "type": "field", "port": "443", "balancerTag": balancer["tag"],
  294. }},
  295. }))
  296. })
  297. }
  298. }
  299. // TestGoldenDNSFixturesBuildInXray builds the dns section, and each dns-server
  300. // fixture inside one.
  301. func TestGoldenDNSFixturesBuildInXray(t *testing.T) {
  302. build := func(dns map[string]any) error {
  303. raw, err := json.Marshal(dns)
  304. if err != nil {
  305. return err
  306. }
  307. dnsConf := new(conf.DNSConfig)
  308. if err := json.Unmarshal(raw, dnsConf); err != nil {
  309. return err
  310. }
  311. _, err = dnsConf.Build()
  312. return err
  313. }
  314. for name, fixture := range goldenFixtures(t, "dns") {
  315. t.Run("dns/"+name, func(t *testing.T) {
  316. assertXrayAccepts(t, "this dns section", build(fixture))
  317. })
  318. }
  319. for name, server := range goldenFixtures(t, "dns-server") {
  320. t.Run("dns-server/"+name, func(t *testing.T) {
  321. assertXrayAccepts(t, "this dns server", build(map[string]any{"servers": []any{server}}))
  322. })
  323. }
  324. }
  325. func isMissingGeoAssetErr(err error) bool {
  326. msg := err.Error()
  327. return strings.Contains(msg, "geoip.dat") || strings.Contains(msg, "geosite.dat")
  328. }