summaryrefslogtreecommitdiff
path: root/pkg/wgconf/wgconf_test.go
blob: 805aeaac2a783e3e4a6801506e69c7394ab5d636 (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
package wgconf

import (
	"os"
	"path/filepath"
	"testing"
)

func TestParseConfig(t *testing.T) {
	content := `[Interface]
PrivateKey = ABC123XYZ
Address = 10.0.0.1/24
DNS = 1.1.1.1

[Peer]
PublicKey = DEF456UVW
Endpoint = 1.2.3.4:51820
AllowedIPs = 0.0.0.0/0

[Peer]
PublicKey = GHI789TSR
Endpoint = 5.6.7.8:51820
AllowedIPs = 192.168.1.0/24, 192.168.2.0/24`

	tmpFile := filepath.Join(t.TempDir(), "test.conf")
	if err := os.WriteFile(tmpFile, []byte(content), 0644); err != nil {
		t.Fatal(err)
	}

	cfg, err := Parse(tmpFile)
	if err != nil {
		t.Fatalf("Parse failed: %v", err)
	}

	if cfg.PrivateKey != "ABC123XYZ" {
		t.Errorf("expected PrivateKey ABC123XYZ, got %s", cfg.PrivateKey)
	}
	if cfg.Address != "10.0.0.1/24" {
		t.Errorf("expected Address 10.0.0.1/24, got %s", cfg.Address)
	}
	if cfg.DNS != "1.1.1.1" {
		t.Errorf("expected DNS 1.1.1.1, got %s", cfg.DNS)
	}
	if len(cfg.Peers) != 2 {
		t.Fatalf("expected 2 peers, got %d", len(cfg.Peers))
	}

	p1 := cfg.Peers[0]
	if p1.PublicKey != "DEF456UVW" || p1.Endpoint != "1.2.3.4:51820" || len(p1.AllowedIPs) != 1 || p1.AllowedIPs[0] != "0.0.0.0/0" {
		t.Errorf("Peer 1 mismatch: %+v", p1)
	}

	p2 := cfg.Peers[1]
	if p2.PublicKey != "GHI789TSR" || p2.Endpoint != "5.6.7.8:51820" || len(p2.AllowedIPs) != 2 || p2.AllowedIPs[0] != "192.168.1.0/24" {
		t.Errorf("Peer 2 mismatch: %+v", p2)
	}
}

func TestParseInvalidConfig(t *testing.T) {
	content := `[Interface]
InvalidLineWithoutEquals`
	tmpFile := filepath.Join(t.TempDir(), "invalid.conf")
	if err := os.WriteFile(tmpFile, []byte(content), 0644); err != nil {
		t.Fatal(err)
	}

	_, err := Parse(tmpFile)
	if err == nil {
		t.Error("expected error for invalid line format, got nil")
	}
}