server_test.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. package wireguard_test
  2. import (
  3. "context"
  4. "github.com/stretchr/testify/assert"
  5. "runtime/debug"
  6. "testing"
  7. "github.com/xtls/xray-core/core"
  8. "github.com/xtls/xray-core/proxy/wireguard"
  9. )
  10. // TestWireGuardServerInitializationError verifies that an error during TUN initialization
  11. // (triggered by an empty SecretKey) in the WireGuard server does not cause a panic and returns an error instead.
  12. func TestWireGuardServerInitializationError(t *testing.T) {
  13. // Create a minimal core instance with default features
  14. config := &core.Config{}
  15. instance, err := core.New(config)
  16. if err != nil {
  17. t.Fatalf("Failed to create core instance: %v", err)
  18. }
  19. // Set the Xray instance in the context
  20. ctx := context.WithValue(context.Background(), core.XrayKey(1), instance)
  21. // Define the server configuration with an empty SecretKey to trigger error
  22. conf := &wireguard.DeviceConfig{
  23. IsClient: false,
  24. Endpoint: []string{"10.0.0.1/32"},
  25. Mtu: 1420,
  26. SecretKey: "", // Empty SecretKey to trigger error
  27. Peers: []*wireguard.PeerConfig{
  28. {
  29. PublicKey: "some_public_key",
  30. AllowedIps: []string{"10.0.0.2/32"},
  31. },
  32. },
  33. }
  34. // Use defer to catch any panic and fail the test explicitly
  35. defer func() {
  36. if r := recover(); r != nil {
  37. t.Errorf("TUN initialization panicked: %v", r)
  38. debug.PrintStack()
  39. }
  40. }()
  41. // Attempt to initialize the WireGuard server
  42. _, err = wireguard.NewServer(ctx, conf)
  43. // Check that an error is returned
  44. assert.ErrorContains(t, err, "failed to set private_key: hex string does not fit the slice")
  45. }