setup: add and remove peer on setup as runtime test

This commit is contained in:
HeshamTB 2024-03-13 00:26:19 +03:00
parent defd32b3c8
commit 4a1039e5b1

View File

@ -3,6 +3,7 @@ package main
import ( import (
"fmt" "fmt"
"log/slog" "log/slog"
"net"
"net/http" "net/http"
"net/netip" "net/netip"
"os" "os"
@ -244,7 +245,7 @@ func setup() error {
slog.Error(fmt.Sprintf("main.IPPool: %s", err)) slog.Error(fmt.Sprintf("main.IPPool: %s", err))
os.Exit(1) os.Exit(1)
} }
slog.Info(fmt.Sprintf("Init ip pool %s", VPNIPCIDR)) slog.Debug(fmt.Sprintf("Init ip pool %s", VPNIPCIDR))
testVip, err := ipPool.Allocate() testVip, err := ipPool.Allocate()
if err != nil { if err != nil {
@ -252,13 +253,13 @@ func setup() error {
os.Exit(1) os.Exit(1)
} }
slog.Info(fmt.Sprintf("main.testVip: IP Pool Test IP: %s", testVip.String())) slog.Debug(fmt.Sprintf("main.testVip: IP Pool Test IP: %s", testVip.String()))
err = ipPool.Free(testVip) err = ipPool.Free(testVip)
if err != nil { if err != nil {
slog.Error("main.testVip: Could not free test Vip from IPPool!", err) slog.Error("main.testVip: Could not free test Vip from IPPool!", err)
os.Exit(1) os.Exit(1)
} }
slog.Info("main.testVip: Test IP Freed") slog.Debug("main.testVip: Test IP Freed")
IPPool = ipPool IPPool = ipPool
@ -273,6 +274,59 @@ func setup() error {
os.Exit(0) os.Exit(0)
}() }()
err = testWgPeerAdd(wgLink)
if err != nil {
return err
}
return nil
}
func testWgPeerAdd(wgLink *hvpnnode3.WGLink) error {
privateKey, err := wgtypes.GeneratePrivateKey()
if err != nil {
return err
}
publicKey := privateKey.PublicKey()
ip, err := IPPool.Allocate()
if err != nil {
return err
}
peerConfig := wgtypes.PeerConfig{
PublicKey: publicKey,
AllowedIPs: []net.IPNet{
{
IP: ip,
Mask: net.IPv4Mask(255, 255, 255, 255),
},
},
}
wgConfig := wgtypes.Config{
Peers: []wgtypes.PeerConfig{peerConfig},
}
err = wgLink.ConfigureDevice(wgLink.Name, wgConfig)
if err != nil {
return err
}
slog.Debug(fmt.Sprintf("Added test peer %v", peerConfig.PublicKey))
wgConfig.ReplacePeers = true
wgConfig.Peers = []wgtypes.PeerConfig{}
err = wgLink.ConfigureDevice(wgLink.Name, wgConfig)
if err != nil {
return err
}
slog.Debug("Removed test peer")
IPPool.Free(ip)
slog.Debug("Freed test peer ip")
return nil return nil
} }