manager_test.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316
  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,"pendingHandshakesMaxPerIp":64,` +
  19. `"routeThroughXray":true,"routeXrayPort":50000,` +
  20. `"adTag":" 0123456789abcdef0123456789abcdef ",` +
  21. `"clients":[` +
  22. `{"email":"alice","secret":"` + aliceSecret + `","adTag":"fedcba9876543210fedcba9876543210","enable":true,"totalGB":1073741824,"expiryTime":1893456000000},` +
  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.Secrets[0].QuotaBytes != 1073741824 {
  43. t.Fatalf("totalGB must map to the byte quota, got %d", inst.Secrets[0].QuotaBytes)
  44. }
  45. if inst.Secrets[0].ExpiresUnix != 1893456000 {
  46. t.Fatalf("expiryTime (ms) must map to a unix-second deadline, got %d", inst.Secrets[0].ExpiresUnix)
  47. }
  48. if inst.Port != 8443 || inst.Id != 3 {
  49. t.Fatalf("bad instance %+v", inst)
  50. }
  51. if !inst.Debug || !inst.ProxyProtocolListener || inst.PreferIP != "prefer-ipv4" {
  52. t.Fatalf("scalar options not parsed: %+v", inst)
  53. }
  54. if inst.FrontingIP != "127.0.0.1" || inst.FrontingPort != 9443 || !inst.FrontingProxyProtocol {
  55. t.Fatalf("domain-fronting not parsed: %+v", inst)
  56. }
  57. if inst.ThrottleMaxConnections != 5000 {
  58. t.Fatalf("throttle not parsed: %+v", inst)
  59. }
  60. if inst.PendingHandshakesMaxPerIP != 64 {
  61. t.Fatalf("pending-handshake limit not parsed: %+v", inst)
  62. }
  63. if !inst.RouteThroughXray || inst.XrayRoutePort != 50000 {
  64. t.Fatalf("xray routing not parsed: %+v", inst)
  65. }
  66. if _, ok := InstanceFromInbound(&model.Inbound{Protocol: model.VLESS}); ok {
  67. t.Fatal("non-mtproto inbound should not produce an instance")
  68. }
  69. noSecrets := &model.Inbound{Protocol: model.MTProto, Settings: `{"clients":[{"email":"x","secret":"","enable":true}]}`}
  70. if _, ok := InstanceFromInbound(noSecrets); ok {
  71. t.Fatal("an inbound with no active secret should not produce an instance")
  72. }
  73. badTags := &model.Inbound{Protocol: model.MTProto, Settings: `{"clients":[{"email":"x","secret":"ee00","adTag":"deadbeef","enable":true}]}`}
  74. badInst, ok := InstanceFromInbound(badTags)
  75. if !ok {
  76. t.Fatal("expected a usable instance despite a malformed ad tag")
  77. }
  78. if badInst.Secrets[0].AdTag != "" {
  79. t.Fatalf("a malformed ad tag must be dropped so the generated config stays valid, got %q", badInst.Secrets[0].AdTag)
  80. }
  81. }
  82. func TestRenderConfig(t *testing.T) {
  83. // A bare instance emits only the required keys, api-bind-to, and the
  84. // [secrets] section, with no optional keys and no [domain-fronting].
  85. bare := renderConfig(Instance{
  86. Secrets: []SecretEntry{{Name: "alice", Secret: "ee00"}},
  87. Listen: "0.0.0.0", Port: 8443,
  88. }, 5000, "")
  89. for _, unwanted := range []string{"debug", "proxy-protocol-listener", "prefer-ip", "[domain-fronting]", "[stats.prometheus]", "[throttle]", "[defense.pending-handshakes]", "[secret-ad-tags]", "api-token"} {
  90. if strings.Contains(bare, unwanted) {
  91. t.Fatalf("bare config should not contain %q:\n%s", unwanted, bare)
  92. }
  93. }
  94. if !strings.Contains(bare, `bind-to = "0.0.0.0:8443"`) {
  95. t.Fatalf("missing bind-to:\n%s", bare)
  96. }
  97. if !strings.Contains(bare, `api-bind-to = "127.0.0.1:5000"`) {
  98. t.Fatalf("api-bind-to must always be present:\n%s", bare)
  99. }
  100. if !strings.Contains(bare, "[secrets]") || !strings.Contains(bare, `"alice" = "ee00"`) {
  101. t.Fatalf("secrets block must carry the client secret:\n%s", bare)
  102. }
  103. // A fully configured instance emits every option, the fronting section (as
  104. // host, not the fork-deprecated ip), the throttle block, the per-client
  105. // ad-tag overrides, and [secrets] last.
  106. full := renderConfig(Instance{
  107. Secrets: []SecretEntry{
  108. {Name: "alice", Secret: "ee11"},
  109. {Name: "bob", Secret: "ee22", AdTag: "fedcba9876543210fedcba9876543210"},
  110. },
  111. Listen: "0.0.0.0", Port: 443,
  112. Debug: true, ProxyProtocolListener: true, PreferIP: "only-ipv6",
  113. FrontingIP: "127.0.0.1", FrontingPort: 9443, FrontingProxyProtocol: true,
  114. ThrottleMaxConnections: 5000,
  115. PendingHandshakesMaxPerIP: 64,
  116. PublicIPv4: "1.2.3.4",
  117. PublicIPv6: "2001:db8::1",
  118. }, 6000, "sesame")
  119. for _, want := range []string{
  120. "debug = true\n",
  121. "proxy-protocol-listener = true\n",
  122. `prefer-ip = "only-ipv6"`,
  123. `api-token = "sesame"`,
  124. `public-ipv4 = "1.2.3.4"`,
  125. `public-ipv6 = "2001:db8::1"`,
  126. "[domain-fronting]",
  127. `host = "127.0.0.1"`,
  128. "port = 9443",
  129. "proxy-protocol = true\n",
  130. "[throttle]",
  131. "max-connections = 5000",
  132. "[defense.pending-handshakes]\nmax-per-ip = 64\n",
  133. "[secret-ad-tags]",
  134. `"bob" = "fedcba9876543210fedcba9876543210"`,
  135. } {
  136. if !strings.Contains(full, want) {
  137. t.Fatalf("full config missing %q:\n%s", want, full)
  138. }
  139. }
  140. if strings.Contains(full, `ip = "127.0.0.1"`) {
  141. t.Fatalf("domain-fronting must use host, not the deprecated ip key:\n%s", full)
  142. }
  143. if strings.Contains(full, "ad-tag =") {
  144. t.Fatalf("no global ad-tag must be emitted, tags are per client:\n%s", full)
  145. }
  146. if strings.Contains(full, `"alice" = "0123456789abcdef0123456789abcdef"`) || strings.Contains(full, `"alice" = ""`) {
  147. t.Fatalf("a client without a tag must not appear in [secret-ad-tags]:\n%s", full)
  148. }
  149. // TOML requires top-level keys before any [section] header, and [secrets]
  150. // must be the final section so trailing keys are not swallowed by a table.
  151. if strings.Index(full, "prefer-ip") > strings.Index(full, "[domain-fronting]") {
  152. t.Fatalf("top-level keys must precede the [domain-fronting] section:\n%s", full)
  153. }
  154. if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[domain-fronting]") {
  155. t.Fatalf("[secrets] must be the final section:\n%s", full)
  156. }
  157. if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[throttle]") {
  158. t.Fatalf("[throttle] must precede [secrets]:\n%s", full)
  159. }
  160. if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[defense.pending-handshakes]") {
  161. t.Fatalf("[defense.pending-handshakes] must precede [secrets]:\n%s", full)
  162. }
  163. if strings.LastIndex(full, "[secrets]") < strings.Index(full, "[secret-ad-tags]") {
  164. t.Fatalf("[secret-ad-tags] must precede [secrets]:\n%s", full)
  165. }
  166. }
  167. func TestRenderConfigXrayEgress(t *testing.T) {
  168. // Routing through Xray emits a [network] proxies upstream pointing at the
  169. // loopback SOCKS bridge, before the [secrets] section.
  170. routed := renderConfig(Instance{
  171. Secrets: []SecretEntry{{Name: "a", Secret: "ee22"}},
  172. Listen: "0.0.0.0", Port: 443,
  173. RouteThroughXray: true, XrayRoutePort: 50000,
  174. }, 7000, "")
  175. if !strings.Contains(routed, "[network]") ||
  176. !strings.Contains(routed, `proxies = ["socks5://127.0.0.1:50000"]`) {
  177. t.Fatalf("routed config must emit the SOCKS upstream:\n%s", routed)
  178. }
  179. if strings.Index(routed, "[network]") > strings.Index(routed, "[secrets]") {
  180. t.Fatalf("[network] must precede [secrets]:\n%s", routed)
  181. }
  182. // Without the flag (or without a port) the section is omitted.
  183. for _, inst := range []Instance{
  184. {Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443},
  185. {Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443, RouteThroughXray: true},
  186. } {
  187. if got := renderConfig(inst, 7000, ""); strings.Contains(got, "[network]") {
  188. t.Fatalf("unrouted config must omit [network]:\n%s", got)
  189. }
  190. }
  191. }
  192. func TestRenderConfigSecretLimits(t *testing.T) {
  193. cfg := renderConfig(Instance{
  194. Secrets: []SecretEntry{
  195. {Name: "alice", Secret: "ee11", QuotaBytes: 1073741824, ExpiresUnix: 1893456000},
  196. {Name: "bob", Secret: "ee22", QuotaBytes: 500},
  197. {Name: "carol", Secret: "ee33"},
  198. },
  199. Listen: "0.0.0.0", Port: 443,
  200. }, 6000, "")
  201. for _, want := range []string{
  202. "[secret-limits.\"alice\"]",
  203. `quota = "1073741824B"`,
  204. `expires = "2030-01-01T00:00:00Z"`,
  205. "[secret-limits.\"bob\"]",
  206. `quota = "500B"`,
  207. } {
  208. if !strings.Contains(cfg, want) {
  209. t.Fatalf("limits config missing %q:\n%s", want, cfg)
  210. }
  211. }
  212. if strings.Contains(cfg, "[secret-limits.\"carol\"]") {
  213. t.Fatalf("a client without a limit must not get a table:\n%s", cfg)
  214. }
  215. if strings.LastIndex(cfg, "[secrets]") < strings.Index(cfg, "[secret-limits.\"alice\"]") {
  216. t.Fatalf("[secret-limits] must precede the final [secrets] section:\n%s", cfg)
  217. }
  218. if strings.Contains(cfg, "usage-state-file") {
  219. t.Fatalf("no usage-state-file must be emitted; quota is an in-memory guard:\n%s", cfg)
  220. }
  221. }
  222. func TestSecretsPayloadLimits(t *testing.T) {
  223. body := secretsPayload(Instance{Secrets: []SecretEntry{
  224. {Name: "alice", Secret: "ee11", QuotaBytes: 1073741824, ExpiresUnix: 1893456000},
  225. {Name: "bob", Secret: "ee22"},
  226. }})
  227. if got := body.Secrets["alice"].Quota; got != "1073741824B" {
  228. t.Fatalf("quota must be sent as an exact byte count, got %q", got)
  229. }
  230. if got := body.Secrets["alice"].Expires; got != "2030-01-01T00:00:00Z" {
  231. t.Fatalf("expiry must be sent as RFC3339, got %q", got)
  232. }
  233. if body.Secrets["bob"].Quota != "" || body.Secrets["bob"].Expires != "" {
  234. t.Fatalf("an unlimited client must carry no quota/expiry: %+v", body.Secrets["bob"])
  235. }
  236. }
  237. func TestFingerprintSplit(t *testing.T) {
  238. base := Instance{Secrets: []SecretEntry{{Name: "a", Secret: "ee"}}, Listen: "0.0.0.0", Port: 443}
  239. for name, mutate := range map[string]func(*Instance){
  240. "debug": func(i *Instance) { i.Debug = true },
  241. "listener": func(i *Instance) { i.ProxyProtocolListener = true },
  242. "preferIp": func(i *Instance) { i.PreferIP = "only-ipv4" },
  243. "frontingIP": func(i *Instance) { i.FrontingIP = "127.0.0.1" },
  244. "frontingPort": func(i *Instance) { i.FrontingPort = 9443 },
  245. "frontingProxy": func(i *Instance) { i.FrontingProxyProtocol = true },
  246. "throttle": func(i *Instance) { i.ThrottleMaxConnections = 5000 },
  247. "pendingHandshakes": func(i *Instance) { i.PendingHandshakesMaxPerIP = 64 },
  248. "routeXray": func(i *Instance) { i.RouteThroughXray = true },
  249. "routeXrayPort": func(i *Instance) { i.XrayRoutePort = 50000 },
  250. "port": func(i *Instance) { i.Port = 8443 },
  251. "listen": func(i *Instance) { i.Listen = "127.0.0.1" },
  252. "publicIpv4": func(i *Instance) { i.PublicIPv4 = "1.2.3.4" },
  253. "publicIpv6": func(i *Instance) { i.PublicIPv6 = "2001:db8::1" },
  254. } {
  255. t.Run("structural/"+name, func(t *testing.T) {
  256. changed := base
  257. mutate(&changed)
  258. if base.structuralFingerprint() == changed.structuralFingerprint() {
  259. t.Fatalf("structural fingerprint must change when %s changes", name)
  260. }
  261. if base.secretsFingerprint() != changed.secretsFingerprint() {
  262. t.Fatalf("secrets fingerprint must stay put when %s changes", name)
  263. }
  264. })
  265. }
  266. for name, mutate := range map[string]func(*Instance){
  267. "add": func(i *Instance) { i.Secrets = append(i.Secrets, SecretEntry{Name: "b", Secret: "ff"}) },
  268. "rekey": func(i *Instance) { i.Secrets = []SecretEntry{{Name: "a", Secret: "ee99"}} },
  269. "remove": func(i *Instance) { i.Secrets = nil },
  270. "rename": func(i *Instance) { i.Secrets = []SecretEntry{{Name: "a2", Secret: "ee"}} },
  271. "clientAdTag": func(i *Instance) {
  272. i.Secrets = []SecretEntry{{Name: "a", Secret: "ee", AdTag: "0123456789abcdef0123456789abcdef"}}
  273. },
  274. "quota": func(i *Instance) { i.Secrets = []SecretEntry{{Name: "a", Secret: "ee", QuotaBytes: 1 << 30}} },
  275. "expiry": func(i *Instance) { i.Secrets = []SecretEntry{{Name: "a", Secret: "ee", ExpiresUnix: 1893456000}} },
  276. } {
  277. t.Run("secrets/"+name, func(t *testing.T) {
  278. changed := base
  279. changed.Secrets = append([]SecretEntry(nil), base.Secrets...)
  280. mutate(&changed)
  281. if base.secretsFingerprint() == changed.secretsFingerprint() {
  282. t.Fatalf("secrets fingerprint must change on a %s", name)
  283. }
  284. if base.structuralFingerprint() != changed.structuralFingerprint() {
  285. t.Fatalf("structural fingerprint must stay put on a %s", name)
  286. }
  287. })
  288. }
  289. t.Run("orderInsensitive", func(t *testing.T) {
  290. forward := Instance{Secrets: []SecretEntry{{Name: "alice", Secret: "ee11"}, {Name: "bob", Secret: "ee22"}}}
  291. reversed := Instance{Secrets: []SecretEntry{{Name: "bob", Secret: "ee22"}, {Name: "alice", Secret: "ee11"}}}
  292. if got, want := forward.secretsFingerprint(), "alice=ee11;tag=;q=0;exp=0|bob=ee22;tag=;q=0;exp=0"; got != want {
  293. t.Fatalf("secrets fingerprint must join sorted pairs: got %q, want %q", got, want)
  294. }
  295. if forward.secretsFingerprint() != reversed.secretsFingerprint() {
  296. t.Fatal("secrets fingerprint must not depend on client order")
  297. }
  298. })
  299. }