summaryrefslogtreecommitdiff
path: root/tests/e2e/e2e_test.go
blob: 98711e42b170dd7a00092f6173cacb3542c05dd0 (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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
package e2e

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

func TestDataPlaneConnectivity(t *testing.T) {
	// 1. Determine binary path
	binaryPath := EnsureBinary(t)

	// 2. Setup isolated config & runtime folders for testing
	tmpDir := t.TempDir()
	profile := "e2e-dataplane-test"

	// Create a dummy peer UDP listener inside our test harness
	// to simulate the remote WireGuard peer. We'll listen on a random port.
	addr, err := net.ResolveUDPAddr("udp", "127.0.0.1:0")
	if err != nil {
		t.Fatalf("Failed to resolve UDP address: %v", err)
	}
	conn, err := net.ListenUDP("udp", addr)
	if err != nil {
		t.Fatalf("Failed to start mock remote WG UDP listener: %v", err)
	}
	defer func() { _ = conn.Close() }()

	localPort := conn.LocalAddr().(*net.UDPAddr).Port

	// Generate profile with valid Base64 keys
	clientPrivKey := "YXNkZmFzZGZhc2RmYXNkZmFzZGZhc2RmYXNkZmFzZGY=" // 32-bytes base64
	peerPubKey := "YXNkZmFzZGZhc2RmYXNkZmFzZGZhc2RmYXNkZmFzZGY="

	confContent := fmt.Sprintf(`[Interface]
PrivateKey = %s
Address = 10.0.0.2/24

[Peer]
PublicKey = %s
Endpoint = 127.0.0.1:%d
AllowedIPs = 10.0.0.0/24
`, clientPrivKey, peerPubKey, localPort)

	profilesDir := filepath.Join(tmpDir, "wg-wrap", "profiles")
	if err := os.MkdirAll(profilesDir, 0755); err != nil {
		t.Fatalf("Failed to create temporary profiles dir: %v", err)
	}
	profilePath := filepath.Join(profilesDir, profile+".conf")
	if err := os.WriteFile(profilePath, []byte(confContent), 0644); err != nil {
		t.Fatalf("Failed to write temporary test profile: %v", err)
	}

	// 3. Launch wg-wrap with a command that triggers traffic
	cmd := exec.Command(binaryPath, "run", "--profile", profile, "--", "ping", "-c", "1", "-W", "1", "10.0.0.1")
	cmd.Env = append(os.Environ(),
		fmt.Sprintf("XDG_CONFIG_HOME=%s", tmpDir),
		fmt.Sprintf("XDG_RUNTIME_DIR=%s", tmpDir),
	)

	packetChan := make(chan []byte, 1)
	go func() {
		buf := make([]byte, 2048)
		_ = conn.SetReadDeadline(time.Now().Add(3 * time.Second))
		n, _, err := conn.ReadFrom(buf)
		if err == nil && n > 0 {
			packetChan <- buf[:n]
		} else {
			packetChan <- nil
		}
	}()

	if err := cmd.Run(); err != nil {
		t.Logf("wg-wrap command returned error (expected since mock peer doesn't reply): %v", err)
	}

	select {
	case packet := <-packetChan:
		if packet == nil {
			t.Error("Mock remote WG UDP listener did not receive any packet from wg-wrap")
		} else {
			t.Logf("Mock remote WG UDP listener successfully received packet of size %d", len(packet))
		}
	case <-time.After(4 * time.Second):
		t.Error("Timed out waiting for WireGuard packet from wg-wrap")
	}

	t.Log("Successfully created tunnel namespace and ran isolated command rootlessly.")
}

func TestNetworkIsolation(t *testing.T) {
	binaryPath := EnsureBinary(t)

	cmd := exec.Command(binaryPath, "test-ns")
	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("wg-wrap test-ns failed: %v\nOutput: %s", err, string(out))
	}

	if !strings.Contains(string(out), "Isolation Verified: OK") {
		t.Errorf("Expected 'Isolation Verified: OK', got: %q", string(out))
	}
}

func TestDNSIsolation(t *testing.T) {
	binaryPath := EnsureBinary(t)

	// 1. Start Mock DNS Server
	dnsServer, port := StartMockDNSServer(t)
	defer dnsServer.Close()

	// 2. Setup isolated config
	tmpDir := t.TempDir()
	profile := "test-dns-isolation"
	clientPrivKey := "YXNkZmFzZGZhc2RmYXNkZmFzZGZhc2RmYXNkZmFzZGY="
	peerPubKey := "YXNkZmFzZGZhc2RmYXNkZmFzZGZhc2RmYXNkZmFzZGY="
	dnsServerIP := "10.0.0.1"

	confContent := fmt.Sprintf(`[Interface]
PrivateKey = %s
Address = 10.0.0.2/24

[Peer]
PublicKey = %s
Endpoint = 127.0.0.1:%d
AllowedIPs = 10.0.0.0/24
`, clientPrivKey, peerPubKey, port)

	profilesDir := filepath.Join(tmpDir, "wg-wrap", "profiles")
	_ = os.MkdirAll(profilesDir, 0755)
	profilePath := filepath.Join(profilesDir, profile+".conf")
	_ = os.WriteFile(profilePath, []byte(confContent), 0644)

	// 3. Test /etc/resolv.conf modification
	expectedDNS := "1.1.1.1"
	cmd := exec.Command(binaryPath, "run", "--profile", profile, "--dns-server", expectedDNS, "--", "cat", "/etc/resolv.conf")
	cmd.Env = append(os.Environ(),
		fmt.Sprintf("XDG_CONFIG_HOME=%s", tmpDir),
		fmt.Sprintf("XDG_RUNTIME_DIR=%s", tmpDir),
	)

	out, err := cmd.CombinedOutput()
	if err != nil {
		t.Fatalf("Failed to run resolv.conf check: %v\nOutput: %s", err, string(out))
	}

	if !strings.Contains(string(out), "nameserver "+expectedDNS) {
		t.Errorf("Expected /etc/resolv.conf to contain %s, but got: %q", expectedDNS, string(out))
	}

	// 4. Test Data Path: Send a ping to trigger Handshake on the mock server
	cmdQuery := exec.Command(binaryPath, "run", "--profile", profile, "--", "ping", "-c", "1", "-W", "1", dnsServerIP)
	cmdQuery.Env = cmd.Env

	packetReceived := make(chan bool, 1)
	go func() {
		success, _ := dnsServer.ListenAndRespond(5 * time.Second)
		packetReceived <- <-success
	}()

	if err := cmdQuery.Run(); err != nil {
		t.Logf("Note: query command failed as expected (since we didn't implement a full DNS stack), but we check if packet arrived: %v", err)
	}

	select {
	case received := <-packetReceived:
		if !received {
			t.Error("Mock DNS server did not receive the UDP packet through the tunnel")
		}
	case <-time.After(5 * time.Second):
		t.Error("Timed out waiting for DNS packet to reach mock server")
	}
}

func TestDNSPrecedence(t *testing.T) {
	binaryPath := EnsureBinary(t)

	tmpDir := t.TempDir()
	profileName := "test-dns-precedence"
	clientPrivKey := "YXNkZmFzZGZhc2RmYXNkZmFzZGZhc2RmYXNkZmFzZGY="
	peerPubKey := "YXNkZmFzZGZhc2RmYXNkZmFzZGZhc2RmYXNkZmFzZGY="

	tests := []struct {
		name        string
		configDNS   string
		cliDNS      string
		expectedDNS string
	}{
		{
			name:        "Fallback to safe DNS (1.1.1.1) when none is specified",
			configDNS:   "",
			cliDNS:      "",
			expectedDNS: "1.1.1.1",
		},
		{
			name:        "Use .conf specified DNS when no CLI flag is provided",
			configDNS:   "8.8.4.4",
			cliDNS:      "",
			expectedDNS: "8.8.4.4",
		},
		{
			name:        "CLI flag overrides .conf specified DNS",
			configDNS:   "8.8.4.4",
			cliDNS:      "9.9.9.9",
			expectedDNS: "9.9.9.9",
		},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			// Write the profile conf with or without the DNS field
			var dnsLine string
			if tt.configDNS != "" {
				dnsLine = "DNS = " + tt.configDNS
			}

			confContent := fmt.Sprintf(`[Interface]
PrivateKey = %s
Address = 10.0.0.2/24
%s

[Peer]
PublicKey = %s
Endpoint = 127.0.0.1:51820
AllowedIPs = 10.0.0.0/24
`, clientPrivKey, dnsLine, peerPubKey)

			profilesDir := filepath.Join(tmpDir, "wg-wrap", "profiles")
			_ = os.MkdirAll(profilesDir, 0755)
			profilePath := filepath.Join(profilesDir, profileName+".conf")
			_ = os.WriteFile(profilePath, []byte(confContent), 0644)

			// Prepare command args
			args := []string{"run", "--profile", profileName}
			if tt.cliDNS != "" {
				args = append(args, "--dns-server", tt.cliDNS)
			}
			args = append(args, "--", "cat", "/etc/resolv.conf")

			cmd := exec.Command(binaryPath, args...)
			cmd.Env = append(os.Environ(),
				fmt.Sprintf("XDG_CONFIG_HOME=%s", tmpDir),
				fmt.Sprintf("XDG_RUNTIME_DIR=%s", tmpDir),
			)

			out, err := cmd.CombinedOutput()
			if err != nil {
				t.Fatalf("Failed to execute resolv.conf check: %v\nOutput: %s", err, string(out))
			}

			if !strings.Contains(string(out), "nameserver "+tt.expectedDNS) {
				t.Errorf("Expected /etc/resolv.conf to contain nameserver %s, but got: %q", tt.expectedDNS, string(out))
			}
		})
	}
}

func TestMTUFragmentation(t *testing.T) {
	binaryPath := EnsureBinary(t)

	cmd := exec.Command(binaryPath, "run", "--profile", "default", "--", "true")
	if err := cmd.Run(); err != nil {
		t.Errorf("expected command to pass, got: %v", err)
	}
}

func TestExitCodePropagation(t *testing.T) {
	binaryPath := EnsureBinary(t)

	// Run a command that exits with code 42
	cmd := exec.Command(binaryPath, "run", "--profile", "default", "--", "sh", "-c", "exit 42")
	err := cmd.Run()
	if err == nil {
		t.Fatalf("expected command to fail with exit status 42, but it succeeded")
	}

	exitErr, ok := err.(*exec.ExitError)
	if !ok {
		t.Fatalf("expected error of type *exec.ExitError, got %T: %v", err, err)
	}

	if exitErr.ExitCode() != 42 {
		t.Errorf("expected exit code 42, got %d", exitErr.ExitCode())
	}
}