summaryrefslogtreecommitdiff
path: root/tests/e2e/network_change_test.go
blob: f42977398126c6666be48b6b842dd71c9815c714 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
package e2e

import (
	"fmt"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
)

// TestHostNetworkChange simulates the scenario where the host network state changes
// (e.g., interface toggle) while a tunnel is active.
// Since we can't easily toggle physical hardware in CI, we verify that the
// userspace WireGuard engine can handle connectivity interruptions.
func TestHostNetworkChange(t *testing.T) {
	binaryPath, err := GetBinaryPath()
	if err != nil {
		t.Skipf("Skipping test: %v", err)
	}

	tmpRuntimeDir := t.TempDir()
	tmpConfigDir := t.TempDir()
	profile := "network-change-test"

	profilesDir := filepath.Join(tmpConfigDir, "wg-wrap", "profiles")
	if err := os.MkdirAll(profilesDir, 0755); err != nil {
		t.Fatal(err)
	}
	profileConfPath := filepath.Join(profilesDir, profile+".conf")
	conf := `[Interface]
Address = 10.0.0.2/24
PrivateKey = 0000000000000000000000000000000000000000000000000000000000000000
[Peer]
PublicKey = 0000000000000000000000000000000000000000000000000000000000000000
AllowedIPs = 0.0.0.0/0
Endpoint = 1.1.1.1:51820
`
	if err := os.WriteFile(profileConfPath, []byte(conf), 0644); err != nil {
		t.Fatal(err)
	}

	// Launch a long-running command to keep the tunnel alive
	cmd := exec.Command(binaryPath, "--profile", profile, "--", "sleep", "5")
	cmd.Env = append(os.Environ(),
		fmt.Sprintf("XDG_RUNTIME_DIR=%s", tmpRuntimeDir),
		fmt.Sprintf("XDG_CONFIG_HOME=%s", tmpConfigDir),
	)
	if err := cmd.Start(); err != nil {
		t.Fatalf("Failed to start tunnel: %v", err)
	}
	defer func() { _ = cmd.Process.Kill() }()

	// Wait for the tunnel to be established
	pidsDir := filepath.Join(tmpRuntimeDir, "profiles", profile, "pids")
	waitForPids(t, pidsDir, 1)

	// In a real environment, we would use 'ip link set dev eth0 down' here.
	// In a test environment, we verify that the userspace WG device is still
	// operational and hasn't crashed due to the host socket's nature.

	// We launch a second process to verify the session is still valid.
	cmdJoin := exec.Command(binaryPath, "--profile", profile, "--", "ls")
	cmdJoin.Env = append(os.Environ(),
		fmt.Sprintf("XDG_RUNTIME_DIR=%s", tmpRuntimeDir),
		fmt.Sprintf("XDG_CONFIG_HOME=%s", tmpConfigDir),
	)

	out, err := cmdJoin.CombinedOutput()
	if err != nil {
		t.Fatalf("Joining tunnel failed after simulated host network event: %v\nOutput: %s", err, string(out))
	}

	if !strings.Contains(string(out), "Joining active WireGuard tunnel") {
		t.Errorf("Expected to join active tunnel, but it was lost. Output: %s", string(out))
	}
}