manager_test.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. package mtproto
  2. import (
  3. "strings"
  4. "testing"
  5. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  6. )
  7. func TestInstanceFromInbound(t *testing.T) {
  8. aliceSecret := "ee0123456789abcdef0123456789abcdef6578616d706c652e636f6d"
  9. ib := &model.Inbound{
  10. Id: 3,
  11. Tag: "inbound-3",
  12. Listen: "0.0.0.0",
  13. Port: 8443,
  14. Protocol: model.MTProto,
  15. Settings: `{"fakeTlsDomain":"example.com",` +
  16. `"debug":true,"proxyProtocolListener":true,"preferIp":"prefer-ipv4",` +
  17. `"domainFronting":{"ip":"127.0.0.1","port":9443,"proxyProtocol":true},` +
  18. `"throttleMaxConnections":5000,` +
  19. `"routeThroughXray":true,"routeXrayPort":50000,` +
  20. `"adTag":" 0123456789abcdef0123456789abcdef ",` +
  21. `"clients":[` +
  22. `{"email":"alice","secret":"` + aliceSecret + `","adTag":"fedcba9876543210fedcba9876543210","enable":true},` +
  23. `{"email":"bob","secret":"","enable":true},` +
  24. `{"email":"carol","secret":"eeaa","enable":false}]}`,
  25. }
  26. inst, ok := InstanceFromInbound(ib)
  27. if !ok {
  28. t.Fatal("expected a usable instance")
  29. }
  30. if len(inst.Secrets) != 1 {
  31. t.Fatalf("only the enabled client with a secret should be served, got %d: %+v", len(inst.Secrets), inst.Secrets)
  32. }
  33. if inst.Secrets[0].Name != "alice" {
  34. t.Fatalf("secret name should be the client email, got %q", inst.Secrets[0].Name)
  35. }
  36. if inst.Secrets[0].Secret != aliceSecret {
  37. t.Fatalf("a valid secret must be preserved, got %q", inst.Secrets[0].Secret)
  38. }
  39. if inst.Secrets[0].AdTag != "fedcba9876543210fedcba9876543210" {
  40. t.Fatalf("the client ad-tag must be parsed, got %q", inst.Secrets[0].AdTag)
  41. }
  42. if inst.Port != 8443 || inst.Id != 3 {
  43. t.Fatalf("bad instance %+v", inst)
  44. }
  45. if !inst.Debug || !inst.ProxyProtocolListener || inst.PreferIP != "prefer-ipv4" {
  46. t.Fatalf("scalar options not parsed: %+v", inst)
  47. }
  48. if inst.FrontingIP != "127.0.0.1" || inst.FrontingPort != 9443 || !inst.FrontingProxyProtocol {
  49. t.Fatalf("domain-fronting not parsed: %+v", inst)
  50. }
  51. if inst.ThrottleMaxConnections != 5000 {
  52. t.Fatalf("throttle not parsed: %+v", inst)
  53. }
  54. if !inst.RouteThroughXray || inst.XrayRoutePort != 50000 {
  55. t.Fatalf("xray routing not parsed: %+v", inst)
  56. }
  57. if _, ok := InstanceFromInbound(&model.Inbound{Protocol: model.VLESS}); ok {
  58. t.Fatal("non-mtproto inbound should not produce an instance")
  59. }
  60. noSecrets := &model.Inbound{Protocol: model.MTProto, Settings: `{"clients":[{"email":"x","secret":"","enable":true}]}`}
  61. if _, ok := InstanceFromInbound(noSecrets); ok {
  62. t.Fatal("an inbound with no active secret should not produce an instance")
  63. }
  64. badTags := &model.Inbound{Protocol: model.MTProto, Settings: `{"clients":[{"email":"x","secret":"ee00","adTag":"deadbeef","enable":true}]}`}
  65. badInst, ok := InstanceFromInbound(badTags)
  66. if !ok {
  67. t.Fatal("expected a usable instance despite a malformed ad tag")
  68. }
  69. if badInst.Secrets[0].AdTag != "" {
  70. t.Fatalf("a malformed ad tag must be dropped so the generated config stays valid, got %q", badInst.Secrets[0].AdTag)
  71. }
  72. }
  73. func TestRenderConfig(t *testing.T) {
  74. // A bare instance emits only the required keys, api-bind-to, and the
  75. // [secrets] section, with no optional keys and no [domain-fronting].
  76. bare := renderConfig(Instance{
  77. Secrets: []SecretEntry{{Name: "alice", Secret: "ee00"}},
  78. Listen: "0.0.0.0", Port: 8443,
  79. }, 5000, "")
  80. for _, unwanted := range []string{"debug", "proxy-protocol-listener", "prefer-ip", "[domain-fronting]", "[stats.prometheus]", "[throttle]", "[secret-ad-tags]", "api-token"} {
  81. if strings.Contains(bare, unwanted) {
  82. t.Fatalf("bare config should not contain %q:\n%s", unwanted, bare)
  83. }
  84. }
  85. if !strings.Contains(bare, `bind-to = "0.0.0.0:8443"`) {
  86. t.Fatalf("missing bind-to:\n%s", bare)
  87. }
  88. if !strings.Contains(bare, `api-bind-to = "127.0.0.1:5000"`) {
  89. t.Fatalf("api-bind-to must always be present:\n%s", bare)
  90. }
  91. if !strings.Contains(bare, "[secrets]") || !strings.Contains(bare, `"alice" = "ee00"`) {
  92. t.Fatalf("secrets block must carry the client secret:\n%s", bare)
  93. }
  94. // A fully configured instance emits every option, the fronting section (as
  95. // host, not the fork-deprecated ip), the throttle block, the per-client
  96. // ad-tag overrides, and [secrets] last.
  97. full := renderConfig(Instance{
  98. Secrets: []SecretEntry{
  99. {Name: "alice", Secret: "ee11"},
  100. {Name: "bob", Secret: "ee22", AdTag: "fedcba9876543210fedcba9876543210"},
  101. },
  102. Listen: "0.0.0.0", Port: 443,
  103. Debug: true, ProxyProtocolListener: true, PreferIP: "only-ipv6",
  104. FrontingIP: "127.0.0.1", FrontingPort: 9443, FrontingProxyProtocol: true,
  105. ThrottleMaxConnections: 5000,
  106. PublicIPv4: "1.2.3.4",
  107. PublicIPv6: "2001:db8::1",
  108. }, 6000, "sesame")
  109. for _, want := range []string{
  110. "debug = true\n",
  111. "proxy-protocol-listener = true\n",
  112. `prefer-ip = "only-ipv6"`,
  113. `api-token = "sesame"`,
  114. `public-ipv4 = "1.2.3.4"`,
  115. `public-ipv6 = "2001:db8::1"`,
  116. "[domain-fronting]",
  117. `host = "127.0.0.1"`,
  118. "port = 9443",
  119. "proxy-protocol = true\n",
  120. "[throttle]",
  121. "max-connections = 5000",
  122. "[secret-ad-tags]",
  123. `"bob" = "fedcba9876543210fedcba9876543210"`,
  124. } {
  125. if !strings.Contains(full, want) {
  126. t.Fatalf("full config missing %q:\n%s", want, full)
  127. }
  128. }
  129. if strings.Contains(full, `ip = "127.0.0.1"`) {
  130. t.Fatalf("domain-fronting must use host, not the deprecated ip key:\n%s", full)
  131. }
  132. if strings.Contains(full, "ad-tag =") {
  133. t.Fatalf("no global ad-tag must be emitted, tags are per client:\n%s", full)
  134. }
  135. if strings.Contains(full, `"alice" = "0123456789abcdef0123456789abcdef"`) || strings.Contains(full, `"alice" = ""`) {
  136. t.Fatalf("a client without a tag must not appear in [secret-ad-tags]:\n%s", full)
  137. }
  138. // TOML requires top-level keys before any [section] header, and [secrets]
  139. // must be the final section so trailing keys are not swallowed by a table.
  140. if strings.Index(full, "prefer-ip") > strings.Index(full, "[domain-fronting]") {
  141. t.Fatalf("top-level keys must precede the [domain-fronting] section:\n%s", full)
  142. }
  143. if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[domain-fronting]") {
  144. t.Fatalf("[secrets] must be the final section:\n%s", full)
  145. }
  146. if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[throttle]") {
  147. t.Fatalf("[throttle] must precede [secrets]:\n%s", full)
  148. }
  149. if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[secret-ad-tags]") {
  150. t.Fatalf("[secret-ad-tags] must precede [secrets]:\n%s", full)
  151. }
  152. }
  153. func TestRenderConfigXrayEgress(t *testing.T) {
  154. // Routing through Xray emits a [network] proxies upstream pointing at the
  155. // loopback SOCKS bridge, before the [secrets] section.
  156. routed := renderConfig(Instance{
  157. Secrets: []SecretEntry{{Name: "a", Secret: "ee22"}},
  158. Listen: "0.0.0.0", Port: 443,
  159. RouteThroughXray: true, XrayRoutePort: 50000,
  160. }, 7000, "")
  161. if !strings.Contains(routed, "[network]") ||
  162. !strings.Contains(routed, `proxies = ["socks5://127.0.0.1:50000"]`) {
  163. t.Fatalf("routed config must emit the SOCKS upstream:\n%s", routed)
  164. }
  165. if strings.Index(routed, "[network]") > strings.Index(routed, "[secrets]") {
  166. t.Fatalf("[network] must precede [secrets]:\n%s", routed)
  167. }
  168. // Without the flag (or without a port) the section is omitted.
  169. for _, inst := range []Instance{
  170. {Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443},
  171. {Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443, RouteThroughXray: true},
  172. } {
  173. if got := renderConfig(inst, 7000, ""); strings.Contains(got, "[network]") {
  174. t.Fatalf("unrouted config must omit [network]:\n%s", got)
  175. }
  176. }
  177. }
  178. func TestFingerprintSplit(t *testing.T) {
  179. base := Instance{Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443}
  180. for name, mutate := range map[string]func(*Instance){
  181. "debug": func(i *Instance) { i.Debug = true },
  182. "listener": func(i *Instance) { i.ProxyProtocolListener = true },
  183. "preferIp": func(i *Instance) { i.PreferIP = "only-ipv4" },
  184. "frontingIP": func(i *Instance) { i.FrontingIP = "127.0.0.1" },
  185. "frontingPort": func(i *Instance) { i.FrontingPort = 9443 },
  186. "frontingProxy": func(i *Instance) { i.FrontingProxyProtocol = true },
  187. "throttle": func(i *Instance) { i.ThrottleMaxConnections = 5000 },
  188. "routeXray": func(i *Instance) { i.RouteThroughXray = true },
  189. "routeXrayPort": func(i *Instance) { i.XrayRoutePort = 50000 },
  190. "port": func(i *Instance) { i.Port = 8443 },
  191. "listen": func(i *Instance) { i.Listen = "127.0.0.1" },
  192. "publicIpv4": func(i *Instance) { i.PublicIPv4 = "1.2.3.4" },
  193. "publicIpv6": func(i *Instance) { i.PublicIPv6 = "2001:db8::1" },
  194. } {
  195. t.Run("structural/"+name, func(t *testing.T) {
  196. changed := base
  197. mutate(&changed)
  198. if base.structuralFingerprint() == changed.structuralFingerprint() {
  199. t.Fatalf("structural fingerprint must change when %s changes", name)
  200. }
  201. if base.secretsFingerprint() != changed.secretsFingerprint() {
  202. t.Fatalf("secrets fingerprint must stay put when %s changes", name)
  203. }
  204. })
  205. }
  206. for name, mutate := range map[string]func(*Instance){
  207. "add": func(i *Instance) { i.Secrets = append(i.Secrets, SecretEntry{Name: "b", Secret: "ff"}) },
  208. "rekey": func(i *Instance) { i.Secrets = []SecretEntry{{Name: "a", Secret: "ee99"}} },
  209. "remove": func(i *Instance) { i.Secrets = nil },
  210. "rename": func(i *Instance) { i.Secrets = []SecretEntry{{Name: "a2", Secret: "ee"}} },
  211. "clientAdTag": func(i *Instance) {
  212. i.Secrets = []SecretEntry{{Name: "a", Secret: "ee", AdTag: "0123456789abcdef0123456789abcdef"}}
  213. },
  214. } {
  215. t.Run("secrets/"+name, func(t *testing.T) {
  216. changed := base
  217. changed.Secrets = append([]SecretEntry(nil), base.Secrets...)
  218. mutate(&changed)
  219. if base.secretsFingerprint() == changed.secretsFingerprint() {
  220. t.Fatalf("secrets fingerprint must change on a %s", name)
  221. }
  222. if base.structuralFingerprint() != changed.structuralFingerprint() {
  223. t.Fatalf("structural fingerprint must stay put on a %s", name)
  224. }
  225. })
  226. }
  227. t.Run("orderInsensitive", func(t *testing.T) {
  228. forward := Instance{Secrets: []SecretEntry{{Name: "alice", Secret: "ee11"}, {Name: "bob", Secret: "ee22"}}}
  229. reversed := Instance{Secrets: []SecretEntry{{Name: "bob", Secret: "ee22"}, {Name: "alice", Secret: "ee11"}}}
  230. if got, want := forward.secretsFingerprint(), "alice=ee11;tag=|bob=ee22;tag="; got != want {
  231. t.Fatalf("secrets fingerprint must join sorted pairs: got %q, want %q", got, want)
  232. }
  233. if forward.secretsFingerprint() != reversed.secretsFingerprint() {
  234. t.Fatal("secrets fingerprint must not depend on client order")
  235. }
  236. })
  237. }