Gitfed
bastien-mrq/sssh / internal / vpn / vpn_test.go
package vpn

import (
	"bufio"
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"net"
	"os"
	"path/filepath"
	"strings"
	"testing"
	"time"
)

// Faux OpenVPN isolé : le même exécutable de test, sans réseau VPN ni sudo.
func TestVPNHelper(t *testing.T) {
	mode := os.Getenv("SSSH_VPN_TEST_MODE")
	if mode == "" {
		return
	}
	args := os.Args
	if path := os.Getenv("SSSH_VPN_TEST_ARGS"); path != "" {
		data, _ := json.Marshal(args)
		_ = os.WriteFile(path, data, 0600)
	}
	var socket string
	for i, arg := range args {
		if arg == "--management" && i+1 < len(args) {
			socket = args[i+1]
		}
	}
	conn, err := net.Dial("unix", socket)
	if err != nil {
		os.Exit(8)
	}
	defer conn.Close()
	fmt.Fprintln(conn, ">INFO:OpenVPN Management Interface")
	fmt.Fprintln(conn, ">HOLD:Waiting for hold release:0")
	sc := bufio.NewScanner(conn)
	usernameOK := false
	connected := func() { fmt.Fprintln(conn, ">STATE:1,CONNECTED,SUCCESS,10.0.0.1,127.0.0.1") }
	for sc.Scan() {
		line := sc.Text()
		switch {
		case line == "state on" || line == "hold off":
			fmt.Fprintln(conn, "SUCCESS: command succeeded")
		case line == "hold release":
			switch mode {
			case "hang":
			case "auth":
				fmt.Fprintln(conn, ">PASSWORD:Need 'Auth' username/password")
			case "reject":
				fmt.Fprintln(conn, ">PASSWORD:Verification Failed: 'Auth'")
			case "die":
				os.Exit(9)
			default:
				connected()
				if mode == "loss" {
					go func() {
						for {
							if _, err := os.Stat(os.Getenv("SSSH_VPN_TEST_LOSE")); err == nil {
								fmt.Fprintln(conn, ">STATE:2,RECONNECTING,connection-reset")
								return
							}
							time.Sleep(10 * time.Millisecond)
						}
					}()
				}
			}
		case strings.HasPrefix(line, "username "):
			usernameOK = line == `username "Auth" "domain\\user"`
		case strings.HasPrefix(line, "password "):
			if !usernameOK || line != `password "Auth" "a\"b\\c"` {
				os.Exit(7)
			}
			connected()
		case line == "signal SIGTERM":
			os.Exit(0)
		}
	}
	os.Exit(0)
}

func fakeVPN(t *testing.T, mode string) (Profile, string) {
	t.Helper()
	dir := t.TempDir()
	t.Setenv("HOME", dir)
	t.Setenv("XDG_CACHE_HOME", filepath.Join(dir, "cache"))
	t.Setenv("SSSH_VPN_TEST_MODE", mode)
	t.Setenv("SSSH_VPN_TEST_EXE", os.Args[0])
	t.Setenv("SSSH_VPN_TEST_ARGS", filepath.Join(dir, "args"))
	t.Setenv("SSSH_VPN_TEST_LOSE", filepath.Join(dir, "lose"))
	t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
	scripts := map[string]string{
		"openvpn": "#!/bin/sh\nexec \"$SSSH_VPN_TEST_EXE\" -test.run=^TestVPNHelper$ -- \"$@\"\n",
		"sudo":    "#!/bin/sh\nif [ \"$1\" = -v ]; then exit 0; fi\nif [ \"$1\" != -n ] || [ \"$2\" != -- ]; then exit 77; fi\nshift 2\nexec \"$@\"\n",
	}
	for name, script := range scripts {
		if err := os.WriteFile(filepath.Join(dir, name), []byte(script), 0700); err != nil {
			t.Fatal(err)
		}
	}
	config := filepath.Join(dir, "profile.ovpn")
	if err := os.WriteFile(config, []byte("client\ndev tun\n"), 0600); err != nil {
		t.Fatal(err)
	}
	return Profile{Config: config}, dir
}
func startFake(t *testing.T, p Profile, c *Credentials) *Session {
	t.Helper()
	s, err := Start(context.Background(), "test", p, c)
	if err != nil {
		t.Fatal(err)
	}
	t.Cleanup(func() {
		if err := s.Stop(); err != nil {
			t.Error(err)
		}
	})
	return s
}
func TestSessionLifecycle(t *testing.T) {
	p, dir := fakeVPN(t, "auth")
	s := startFake(t, p, &Credentials{Username: `domain\user`, Password: `a"b\c`})
	if err := s.WaitReady(context.Background(), 3*time.Second); err != nil {
		t.Fatal(err)
	}
	for path, mode := range map[string]os.FileMode{s.runtimeDir: 0700, filepath.Join(s.runtimeDir, "management.sock"): 0600, s.sessionDir: 0700, s.LogPath: 0600} {
		// Le listener retire son socket après accept ; le répertoire reste privé.
		info, err := os.Stat(path)
		if os.IsNotExist(err) && strings.HasSuffix(path, "management.sock") {
			continue
		}
		if err != nil {
			t.Fatal(err)
		}
		if info.Mode().Perm() != mode {
			t.Fatalf("permissions %s: %v", path, info.Mode())
		}
	}
	if other, err := Start(context.Background(), "test", p, nil); err == nil {
		other.Stop()
		t.Fatal("concurrent profile accepted")
	}
	data, err := os.ReadFile(filepath.Join(dir, "args"))
	if err != nil {
		t.Fatal(err)
	}
	for _, secret := range []string{"domain", `a\\\"b`} {
		if strings.Contains(string(data), secret) {
			t.Fatal("credentials leaked into arguments")
		}
	}
	if err := s.Stop(); err != nil {
		t.Fatal(err)
	}
	if err := s.Stop(); err != nil {
		t.Fatal(err)
	}
	if _, err := os.Stat(s.runtimeDir); !os.IsNotExist(err) {
		t.Fatalf("runtime directory not removed: %v", err)
	}
	// Le verrou est libéré, et une nouvelle session a ses propres logs.
	s2 := startFake(t, p, &Credentials{Username: `domain\user`, Password: `a"b\c`})
	if s2.LogPath == s.LogPath {
		t.Fatal("shared log path")
	}
	if err := s2.WaitReady(context.Background(), 3*time.Second); err != nil {
		t.Fatal(err)
	}
}
func TestReachableDoesNotBypassVPN(t *testing.T) {
	p, _ := fakeVPN(t, "hang")
	l, err := net.Listen("tcp", "127.0.0.1:0")
	if err != nil {
		t.Fatal(err)
	}
	defer l.Close()
	p.Check = l.Addr().String()
	s := startFake(t, p, nil)
	if err := s.WaitReady(context.Background(), 200*time.Millisecond); !errors.Is(err, context.DeadlineExceeded) {
		t.Fatalf("reachable target bypassed VPN: %v", err)
	}
}
func TestSessionFailures(t *testing.T) {
	for _, mode := range []string{"reject", "die", "loss"} {
		t.Run(mode, func(t *testing.T) {
			p, dir := fakeVPN(t, mode)
			s := startFake(t, p, nil)
			err := s.WaitReady(context.Background(), 3*time.Second)
			if mode != "loss" {
				if err == nil {
					t.Fatal("failed VPN became ready")
				}
				return
			}
			if err != nil {
				t.Fatal(err)
			}
			if err := os.WriteFile(filepath.Join(dir, "lose"), nil, 0600); err != nil {
				t.Fatal(err)
			}
			ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
			defer cancel()
			if err := s.Watch(ctx); err == nil || errors.Is(err, context.DeadlineExceeded) {
				t.Fatalf("loss not detected: %v", err)
			}
		})
	}
}
func TestCustomProfileCleanup(t *testing.T) {
	_, dir := fakeVPN(t, "unused")
	t.Setenv("SSSH_TEST_DOWN", filepath.Join(dir, "down"))
	p := Profile{Up: "exit 4", Down: `printf 'down\n' >> "$SSSH_TEST_DOWN"`}
	if _, err := Start(context.Background(), "custom", p, nil); err == nil {
		t.Fatal("up failure ignored")
	}
	p.Up = "true"
	s := startFake(t, p, nil)
	if err := s.WaitReady(context.Background(), time.Second); err != nil {
		t.Fatal(err)
	}
	if err := s.Stop(); err != nil {
		t.Fatal(err)
	}
	if err := s.Stop(); err != nil {
		t.Fatal(err)
	}
	data, err := os.ReadFile(filepath.Join(dir, "down"))
	if err != nil {
		t.Fatal(err)
	}
	if string(data) != "down\ndown\n" {
		t.Fatalf("cleanup count: %q", data)
	}
}
func TestCanceledStart(t *testing.T) {
	p, _ := fakeVPN(t, "hang")
	ctx, cancel := context.WithCancel(context.Background())
	cancel()
	if _, err := Start(ctx, "test", p, nil); !errors.Is(err, context.Canceled) {
		t.Fatalf("canceled start: %v", err)
	}
}
func TestValidation(t *testing.T) {
	for _, name := range []string{"../escape", "a\nb", "a\"b", "", "-bad"} {
		if err := ValidateName(name); err == nil {
			t.Errorf("accepted profile %q", name)
		}
	}
	for _, c := range []Credentials{{Username: "a\ncommand", Password: "b"}, {Username: "a", Password: "b\rcommand"}, {Username: "a", Password: ""}} {
		if err := c.Validate(); err == nil {
			t.Errorf("accepted invalid credentials")
		}
	}
	for _, p := range []Profile{{Up: "true"}, {Config: "x", Up: "true"}, {Config: "x", Check: "host:0"}, {Config: "x", Check: "host"}} {
		if err := p.Validate("test"); err == nil {
			t.Errorf("accepted profile %+v", p)
		}
	}
	dir := t.TempDir()
	for _, directive := range []string{"daemon", "--daemon", "config other.ovpn", "management localhost 1234", "log /tmp/vpn.log"} {
		path := filepath.Join(dir, "p.ovpn")
		os.WriteFile(path, []byte(directive), 0600)
		if err := validateConfig(path); err == nil {
			t.Errorf("accepted conflicting directive %q", directive)
		}
	}
}