manager_test.go 11 KB

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