1
0

model_wireguard_test.go 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package model
  2. import (
  3. "reflect"
  4. "testing"
  5. )
  6. func TestClientToRecordRoundTripWireGuard(t *testing.T) {
  7. c := &Client{
  8. Email: "[email protected]",
  9. Enable: true,
  10. PrivateKey: "cGVlci1wcml2YXRlLWtleS1iYXNlNjQtMzJieXRlcw==",
  11. PublicKey: "cGVlci1wdWJsaWMta2V5LWJhc2U2NC0zMmJ5dGVzISE=",
  12. AllowedIPs: []string{"10.0.0.2/32", "fd00::2/128"},
  13. PreSharedKey: "cHNrLWJhc2U2NC0zMmJ5dGVzLXBsYWNlaG9sZGVyISE=",
  14. KeepAlive: 25,
  15. }
  16. rec := c.ToRecord()
  17. if rec.AllowedIPs != "10.0.0.2/32,fd00::2/128" {
  18. t.Fatalf("AllowedIPs CSV = %q, want %q", rec.AllowedIPs, "10.0.0.2/32,fd00::2/128")
  19. }
  20. got := rec.ToClient()
  21. for _, f := range []struct {
  22. name string
  23. a, b any
  24. }{
  25. {"PrivateKey", c.PrivateKey, got.PrivateKey},
  26. {"PublicKey", c.PublicKey, got.PublicKey},
  27. {"PreSharedKey", c.PreSharedKey, got.PreSharedKey},
  28. {"KeepAlive", c.KeepAlive, got.KeepAlive},
  29. } {
  30. if f.a != f.b {
  31. t.Errorf("%s round-trip = %v, want %v", f.name, f.b, f.a)
  32. }
  33. }
  34. if !reflect.DeepEqual(got.AllowedIPs, c.AllowedIPs) {
  35. t.Errorf("AllowedIPs round-trip = %v, want %v", got.AllowedIPs, c.AllowedIPs)
  36. }
  37. }
  38. func TestClientRecordEmptyAllowedIPs(t *testing.T) {
  39. rec := &ClientRecord{Email: "[email protected]", AllowedIPs: ""}
  40. if got := rec.ToClient().AllowedIPs; got != nil {
  41. t.Fatalf("empty CSV → AllowedIPs = %v, want nil", got)
  42. }
  43. rec.AllowedIPs = " 10.0.0.5/32 , ,"
  44. if got := rec.ToClient().AllowedIPs; !reflect.DeepEqual(got, []string{"10.0.0.5/32"}) {
  45. t.Fatalf("trimmed CSV → AllowedIPs = %v, want [10.0.0.5/32]", got)
  46. }
  47. }
  48. func TestMergeClientRecordWireGuardKeysPreserved(t *testing.T) {
  49. existing := &ClientRecord{
  50. Email: "[email protected]",
  51. PrivateKey: "existing-private",
  52. PublicKey: "existing-public",
  53. AllowedIPs: "10.0.0.7/32",
  54. UpdatedAt: 100,
  55. }
  56. incomingEmpty := &ClientRecord{Email: "[email protected]", UpdatedAt: 200}
  57. MergeClientRecord(existing, incomingEmpty)
  58. if existing.PrivateKey != "existing-private" || existing.PublicKey != "existing-public" {
  59. t.Fatalf("empty incoming wiped keys: priv=%q pub=%q", existing.PrivateKey, existing.PublicKey)
  60. }
  61. if existing.AllowedIPs != "10.0.0.7/32" {
  62. t.Fatalf("empty incoming wiped allowedIPs: %q", existing.AllowedIPs)
  63. }
  64. incomingNewer := &ClientRecord{
  65. Email: "[email protected]",
  66. AllowedIPs: "10.0.0.8/32",
  67. UpdatedAt: 300,
  68. }
  69. MergeClientRecord(existing, incomingNewer)
  70. if existing.AllowedIPs != "10.0.0.8/32" {
  71. t.Fatalf("newer allowedIPs not applied: %q", existing.AllowedIPs)
  72. }
  73. }