manager_test.go 13 KB

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