Gitfed
bastien-mrq/sssh / internal / connect / jumps_test.go
package connect

import (
	"git.neuromancer.ovh/bastien-mrq/sssh/internal/host"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"testing"
)

func TestJumpConfig(t *testing.T) {
	ssh, err := exec.LookPath("ssh")
	if err != nil {
		t.Skip("OpenSSH unavailable")
	}
	home := t.TempDir()
	t.Setenv("HOME", home)
	if err := os.Mkdir(filepath.Join(home, ".ssh"), 0700); err != nil {
		t.Fatal(err)
	}
	if err := os.WriteFile(filepath.Join(home, ".ssh", "config"), []byte("Host bastion\n ServerAliveInterval 17\n"), 0600); err != nil {
		t.Fatal(err)
	}
	config, cleanup, err := JumpConfig([]host.Host{{Name: "bastion", Host: "10.0.0.1", User: "alice", Port: 2222, Identity: "~/key with spaces"}})
	if err != nil {
		t.Fatal(err)
	}
	defer cleanup()
	info, err := os.Stat(config)
	if err != nil || info.Mode().Perm() != 0600 {
		t.Fatalf("config permissions: %v", err)
	}
	out, err := exec.Command(ssh, "-G", "-F", config, "bastion").Output()
	if err != nil {
		t.Fatal(err)
	}
	for _, want := range []string{"hostname 10.0.0.1", "user alice", "port 2222", "identityfile " + home + "/key with spaces", "serveraliveinterval 17"} {
		if !strings.Contains(string(out), want) {
			t.Errorf("missing %q", want)
		}
	}
	cleanup()
	if _, err := os.Stat(config); !os.IsNotExist(err) {
		t.Fatalf("config not removed: %v", err)
	}
}
func TestJumpConfigRejectsInjection(t *testing.T) {
	for _, h := range []host.Host{{Name: "*", Host: "example"}, {Name: "safe", Host: "example\nProxyCommand bad"}, {Name: "safe", Host: "example", Identity: "key\nMatch all"}} {
		if _, cleanup, err := JumpConfig([]host.Host{h}); err == nil {
			cleanup()
			t.Fatalf("accepted config injection: %+v", h)
		}
	}
}