419 lines
14 KiB
Go
419 lines
14 KiB
Go
package hook_test
|
|
|
|
import (
|
|
"os"
|
|
"os/exec"
|
|
"path/filepath"
|
|
"strings"
|
|
"testing"
|
|
|
|
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
|
|
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
|
|
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
|
|
)
|
|
|
|
func TestAliasesPath_UnderCacheDir(t *testing.T) {
|
|
dir := t.TempDir()
|
|
orig := os.Getenv("XDG_CACHE_HOME")
|
|
os.Setenv("XDG_CACHE_HOME", dir)
|
|
defer os.Setenv("XDG_CACHE_HOME", orig)
|
|
|
|
p := hook.AliasesPath()
|
|
if !strings.HasPrefix(p, dir) {
|
|
t.Errorf("AliasesPath should be under XDG_CACHE_HOME, got %q", p)
|
|
}
|
|
if !strings.HasSuffix(p, "aliases.sh") {
|
|
t.Errorf("AliasesPath should end with aliases.sh, got %q", p)
|
|
}
|
|
}
|
|
|
|
func TestFishAliasesPath_UnderConfigDir(t *testing.T) {
|
|
dir := t.TempDir()
|
|
orig := os.Getenv("XDG_CONFIG_HOME")
|
|
os.Setenv("XDG_CONFIG_HOME", dir)
|
|
defer os.Setenv("XDG_CONFIG_HOME", orig)
|
|
|
|
p := hook.FishAliasesPath()
|
|
if !strings.HasPrefix(p, dir) {
|
|
t.Errorf("FishAliasesPath should be under XDG_CONFIG_HOME, got %q", p)
|
|
}
|
|
if !strings.HasSuffix(p, "netssh.fish") {
|
|
t.Errorf("FishAliasesPath should end with netssh.fish, got %q", p)
|
|
}
|
|
}
|
|
|
|
// TestWriteAliasFiles_ShFile verifies the bash/zsh file is always written.
|
|
func TestWriteAliasFiles_ShFile(t *testing.T) {
|
|
cacheDir := t.TempDir()
|
|
orig := os.Getenv("XDG_CACHE_HOME")
|
|
os.Setenv("XDG_CACHE_HOME", cacheDir)
|
|
defer os.Setenv("XDG_CACHE_HOME", orig)
|
|
|
|
entries := []hook.AliasEntry{
|
|
{Name: "web01", Host: "web01.example.com"},
|
|
{Name: "db01", Host: "db01.example.com"},
|
|
}
|
|
if err := hook.WriteAliasFiles(entries); err != nil {
|
|
t.Fatalf("WriteAliasFiles: %v", err)
|
|
}
|
|
|
|
data, err := os.ReadFile(hook.AliasesPath())
|
|
if err != nil {
|
|
t.Fatalf("aliases.sh not created: %v", err)
|
|
}
|
|
content := string(data)
|
|
|
|
for _, want := range []string{
|
|
"alias web01='netssh web01.example.com'",
|
|
"alias db01='netssh db01.example.com'",
|
|
} {
|
|
if !strings.Contains(content, want) {
|
|
t.Errorf("aliases.sh missing %q\ncontent:\n%s", want, content)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestWriteAliasFiles_FishFile verifies the fish file is written when fish config dir exists.
|
|
func TestWriteAliasFiles_FishFile(t *testing.T) {
|
|
configDir := t.TempDir()
|
|
orig := os.Getenv("XDG_CONFIG_HOME")
|
|
os.Setenv("XDG_CONFIG_HOME", configDir)
|
|
defer os.Setenv("XDG_CONFIG_HOME", orig)
|
|
|
|
// Create the fish config directory so WriteAliasFiles knows fish is set up.
|
|
fishDir := filepath.Join(configDir, "fish")
|
|
os.MkdirAll(fishDir, 0o755)
|
|
|
|
cacheDir := t.TempDir()
|
|
origCache := os.Getenv("XDG_CACHE_HOME")
|
|
os.Setenv("XDG_CACHE_HOME", cacheDir)
|
|
defer os.Setenv("XDG_CACHE_HOME", origCache)
|
|
|
|
entries := []hook.AliasEntry{{Name: "web01", Host: "web01.example.com"}}
|
|
if err := hook.WriteAliasFiles(entries); err != nil {
|
|
t.Fatalf("WriteAliasFiles: %v", err)
|
|
}
|
|
|
|
data, err := os.ReadFile(hook.FishAliasesPath())
|
|
if err != nil {
|
|
t.Fatalf("netssh.fish not created: %v", err)
|
|
}
|
|
if !strings.Contains(string(data), "alias web01 'netssh web01.example.com'") {
|
|
t.Errorf("fish alias file missing expected line\ncontent:\n%s", string(data))
|
|
}
|
|
}
|
|
|
|
// TestWriteAliasFiles_SkipsFishWhenNotConfigured verifies that fish file is NOT written
|
|
// when fish is not set up (no ~/.config/fish directory).
|
|
func TestWriteAliasFiles_SkipsFishWhenNotConfigured(t *testing.T) {
|
|
configDir := t.TempDir() // no fish subdir
|
|
orig := os.Getenv("XDG_CONFIG_HOME")
|
|
os.Setenv("XDG_CONFIG_HOME", configDir)
|
|
defer os.Setenv("XDG_CONFIG_HOME", orig)
|
|
|
|
cacheDir := t.TempDir()
|
|
origCache := os.Getenv("XDG_CACHE_HOME")
|
|
os.Setenv("XDG_CACHE_HOME", cacheDir)
|
|
defer os.Setenv("XDG_CACHE_HOME", origCache)
|
|
|
|
entries := []hook.AliasEntry{{Name: "web01", Host: "web01.example.com"}}
|
|
if err := hook.WriteAliasFiles(entries); err != nil {
|
|
t.Fatalf("WriteAliasFiles: %v", err)
|
|
}
|
|
|
|
if _, err := os.Stat(hook.FishAliasesPath()); err == nil {
|
|
t.Error("fish alias file should not be created when fish is not configured")
|
|
}
|
|
}
|
|
|
|
// TestWriteAliasFiles_EmptyEntries verifies an empty (but valid) file is written.
|
|
func TestWriteAliasFiles_EmptyEntries(t *testing.T) {
|
|
cacheDir := t.TempDir()
|
|
orig := os.Getenv("XDG_CACHE_HOME")
|
|
os.Setenv("XDG_CACHE_HOME", cacheDir)
|
|
defer os.Setenv("XDG_CACHE_HOME", orig)
|
|
|
|
if err := hook.WriteAliasFiles(nil); err != nil {
|
|
t.Fatalf("WriteAliasFiles with nil entries: %v", err)
|
|
}
|
|
data, err := os.ReadFile(hook.AliasesPath())
|
|
if err != nil {
|
|
t.Fatalf("aliases.sh not created: %v", err)
|
|
}
|
|
// Should contain only the header comment, no alias lines.
|
|
if strings.Contains(string(data), "alias ") {
|
|
t.Error("aliases.sh should have no alias lines for empty entries")
|
|
}
|
|
}
|
|
|
|
// --- InstallAliasesSource ---
|
|
|
|
func TestInstallAliasesSource_Fresh(t *testing.T) {
|
|
profile := writeProfile(t, "existing line\n")
|
|
|
|
installed, err := hook.InstallAliasesSource(profile)
|
|
if err != nil {
|
|
t.Fatalf("InstallAliasesSource: %v", err)
|
|
}
|
|
if !installed {
|
|
t.Error("should report installed=true on first install")
|
|
}
|
|
|
|
data, _ := os.ReadFile(profile)
|
|
if !strings.Contains(string(data), hook.AliasesMarker) {
|
|
t.Error("profile should contain aliases source line")
|
|
}
|
|
}
|
|
|
|
func TestInstallAliasesSource_Idempotent(t *testing.T) {
|
|
profile := writeProfile(t, "")
|
|
|
|
hook.InstallAliasesSource(profile)
|
|
installed, err := hook.InstallAliasesSource(profile)
|
|
if err != nil {
|
|
t.Fatalf("second InstallAliasesSource: %v", err)
|
|
}
|
|
if installed {
|
|
t.Error("second call should report installed=false")
|
|
}
|
|
|
|
data, _ := os.ReadFile(profile)
|
|
if count := strings.Count(string(data), hook.AliasesMarker); count != 1 {
|
|
t.Errorf("aliases source line should appear once, got %d", count)
|
|
}
|
|
}
|
|
|
|
// TestUninstall_AlsoRemovesAliasesSourceLine verifies that Uninstall removes both lines.
|
|
func TestUninstall_AlsoRemovesAliasesSourceLine(t *testing.T) {
|
|
content := "export PATH=$PATH\n" +
|
|
hook.Line + "\n" +
|
|
hook.AliasesSourceLine + "\n" +
|
|
"export FOO=bar\n"
|
|
profile := writeProfile(t, content)
|
|
|
|
removed, err := hook.Uninstall(profile)
|
|
if err != nil {
|
|
t.Fatalf("Uninstall: %v", err)
|
|
}
|
|
if !removed {
|
|
t.Error("should report removed=true")
|
|
}
|
|
|
|
data, _ := os.ReadFile(profile)
|
|
s := string(data)
|
|
if strings.Contains(s, hook.Marker) {
|
|
t.Error("shell-init line should be removed")
|
|
}
|
|
if strings.Contains(s, hook.AliasesMarker) {
|
|
t.Error("aliases source line should be removed")
|
|
}
|
|
if !strings.Contains(s, "export PATH") || !strings.Contains(s, "export FOO") {
|
|
t.Error("other content should be preserved")
|
|
}
|
|
}
|
|
|
|
func TestCommandAliasGenerationAndCollision(t *testing.T) {
|
|
cfg := config.Config{Shell: config.ShellConfig{Alias: "j"}}
|
|
entries := hook.BuildAliasEntries([]cache.Entry{{Name: "j"}, {Name: "netssh"}, {Name: "web-01"}}, cfg)
|
|
if len(entries) != 2 {
|
|
t.Fatalf("entries: %+v", entries)
|
|
}
|
|
if got := entries[0].Definition("bash"); got != "alias j='netssh'" {
|
|
t.Fatal(got)
|
|
}
|
|
if got := entries[0].Definition("fish"); got != "alias j 'netssh'" {
|
|
t.Fatal(got)
|
|
}
|
|
if got := entries[1].Definition("bash"); got != "alias web-01='netssh web-01'" {
|
|
t.Fatal(got)
|
|
}
|
|
}
|
|
|
|
func TestAliasesIncludeInstanceName(t *testing.T) {
|
|
cfg := config.Config{Shortcuts: config.ShortcutsConfig{Domains: []string{".example.com"}}}
|
|
entries := hook.BuildAliasEntries([]cache.Entry{{Name: "office/web01.example.com"}, {Name: "lab/web01.example.com"}}, cfg)
|
|
if len(entries) != 2 {
|
|
t.Fatalf("missing qualified aliases: %+v", entries)
|
|
}
|
|
got := map[string]string{}
|
|
for _, entry := range entries {
|
|
got[entry.Name] = entry.Host
|
|
}
|
|
if got["office_web01"] != "office/web01.example.com" || got["lab_web01"] != "lab/web01.example.com" {
|
|
t.Fatalf("alias lost source: %+v", entries)
|
|
}
|
|
}
|
|
|
|
func TestAliasesUseRewriteRules(t *testing.T) {
|
|
cfg := config.Config{Shortcuts: config.ShortcutsConfig{
|
|
Domains: []string{".hoster.de"},
|
|
Rewrites: []config.ShortcutRewrite{{Pattern: `^([a-z]+)[0-9]+-`, Replace: "$1"}},
|
|
}}
|
|
entries := hook.BuildAliasEntries([]cache.Entry{{Name: "fsn1-bx1.hoster.de"}}, cfg)
|
|
if len(entries) != 1 || entries[0].Definition("bash") != "alias fsnbx1='netssh fsn1-bx1.hoster.de'" {
|
|
t.Fatalf("entries: %+v", entries)
|
|
}
|
|
}
|
|
|
|
func TestAliasesOptionalInstancePrefix(t *testing.T) {
|
|
cfg := config.Config{
|
|
NetBoxes: []config.NetBoxConfig{
|
|
{Name: "OFFICE", DisablePrefix: true},
|
|
{Name: "lab"},
|
|
},
|
|
Shortcuts: config.ShortcutsConfig{
|
|
Domains: []string{".example.com"},
|
|
Rewrites: []config.ShortcutRewrite{{Pattern: "^web-", Replace: "app"}},
|
|
},
|
|
}
|
|
entries := hook.BuildAliasEntries([]cache.Entry{
|
|
{Name: "office/web-01.example.com"},
|
|
{Name: "lab/web-01.example.com"},
|
|
}, cfg)
|
|
got := map[string]string{}
|
|
for _, e := range entries {
|
|
got[e.Name] = e.Host
|
|
// Both output formats must keep the fully qualified destination.
|
|
for _, shell := range []string{"bash", "zsh", "fish"} {
|
|
if !strings.Contains(e.Definition(shell), e.Host) {
|
|
t.Fatalf("%s alias lost its target: %s", shell, e.Definition(shell))
|
|
}
|
|
}
|
|
}
|
|
if len(got) != 2 || got["app01"] != "office/web-01.example.com" || got["lab_app01"] != "lab/web-01.example.com" {
|
|
t.Fatalf("unexpected aliases: %+v", entries)
|
|
}
|
|
}
|
|
|
|
func TestAliasesWithoutPrefixCollisions(t *testing.T) {
|
|
cfg := config.Config{
|
|
NetBoxes: []config.NetBoxConfig{
|
|
{Name: "office", DisablePrefix: true},
|
|
{Name: "lab", DisablePrefix: true},
|
|
},
|
|
Shell: config.ShellConfig{Alias: "j"},
|
|
Shortcuts: config.ShortcutsConfig{Domains: []string{".example.com"}},
|
|
}
|
|
for _, tc := range []struct {
|
|
name string
|
|
hosts []string
|
|
want map[string]string
|
|
}{
|
|
{"two instances", []string{"office/web.example.com", "lab/web.example.com"},
|
|
map[string]string{"j": "", "office_web": "office/web.example.com", "lab_web": "lab/web.example.com"}},
|
|
{"static host", []string{"office/web.example.com", "web"},
|
|
map[string]string{"j": "", "office_web": "office/web.example.com", "web": "web"}},
|
|
{"command aliases", []string{"office/j", "office/netssh"},
|
|
map[string]string{"j": "", "office_j": "office/j", "office_netssh": "office/netssh"}},
|
|
{"reserved qualified alias", []string{"office/lab_web", "lab/web"},
|
|
map[string]string{"j": "", "office_lab_web": "office/lab_web", "web": "lab/web"}},
|
|
{"invalid bare alias", []string{"office/123.example.com"},
|
|
map[string]string{"j": "", "office_123": "office/123.example.com"}},
|
|
{"normalized names", []string{"office/web.example.com", "office/web"},
|
|
map[string]string{"j": "", "office_web": "office/web"}},
|
|
} {
|
|
t.Run(tc.name, func(t *testing.T) {
|
|
var input []cache.Entry
|
|
for _, host := range tc.hosts {
|
|
input = append(input, cache.Entry{Name: host})
|
|
}
|
|
entries := hook.BuildAliasEntries(input, cfg)
|
|
if len(entries) != len(tc.want) {
|
|
t.Fatalf("aliases: %+v, want %+v", entries, tc.want)
|
|
}
|
|
for _, e := range entries {
|
|
if host, ok := tc.want[e.Name]; !ok || host != e.Host {
|
|
t.Fatalf("unexpected alias: %+v", e)
|
|
}
|
|
}
|
|
})
|
|
}
|
|
}
|
|
|
|
func TestCustomCommandAliases(t *testing.T) {
|
|
cfg := config.Config{
|
|
NetBoxes: []config.NetBoxConfig{{Name: "office", DisablePrefix: true}},
|
|
Shortcuts: config.ShortcutsConfig{Rewrites: []config.ShortcutRewrite{{Pattern: "^xzi-groß", Replace: "xg"}}},
|
|
Commands: map[string]config.HostCommand{
|
|
"mtr": {AliasPrefix: "m", Args: []string{"mtr", "{address}"}},
|
|
"ping": {AliasPrefix: "p", Args: []string{"ping", "{address}"}},
|
|
"manual": {Args: []string{"echo", "{host}"}},
|
|
},
|
|
}
|
|
entries := hook.BuildAliasEntries([]cache.Entry{{Name: "office/xzi-groß1", IP: "10.0.0.1"}}, cfg)
|
|
got := map[string]hook.AliasEntry{}
|
|
for _, e := range entries {
|
|
got[e.Name] = e
|
|
}
|
|
if len(entries) != 3 || got["mxg1"].Command != "mtr" || got["pxg1"].Command != "ping" {
|
|
t.Fatalf("unexpected aliases: %+v", entries)
|
|
}
|
|
if got["mxg1"].Host != "office/xzi-groß1" {
|
|
t.Fatal("instance lost")
|
|
}
|
|
for _, shell := range []string{"bash", "zsh", "fish"} {
|
|
def := got["mxg1"].Definition(shell)
|
|
if !strings.Contains(def, "netssh run") || !strings.Contains(def, "office/xzi-groß1") || strings.Contains(def, "10.0.0.1") {
|
|
t.Fatalf("%s alias must resolve at invocation: %s", shell, def)
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCustomCommandAliasesPreserveExistingNames(t *testing.T) {
|
|
cfg := config.Config{
|
|
Shell: config.ShellConfig{Alias: "mfoo"},
|
|
Commands: map[string]config.HostCommand{
|
|
"mtr": {AliasPrefix: "m", Args: []string{"mtr", "{address}"}},
|
|
"ping": {AliasPrefix: "mp", Args: []string{"ping", "{address}"}},
|
|
},
|
|
}
|
|
entries := hook.BuildAliasEntries([]cache.Entry{
|
|
{Name: "foo"}, {Name: "web"}, {Name: "mweb"}, {Name: "x"}, {Name: "px"},
|
|
}, cfg)
|
|
for _, e := range entries {
|
|
if e.Name == "mfoo" && (e.Host != "" || e.Command != "") {
|
|
t.Fatal("command alias overwritten")
|
|
}
|
|
if e.Name == "mweb" && (e.Host != "mweb" || e.Command != "") {
|
|
t.Fatal("SSH alias overwritten")
|
|
}
|
|
if e.Name == "mpx" {
|
|
t.Fatal("ambiguous custom alias generated")
|
|
}
|
|
}
|
|
}
|
|
|
|
func TestCustomAliasShellArgumentQuoting(t *testing.T) {
|
|
dir := t.TempDir()
|
|
if err := os.WriteFile(filepath.Join(dir, "netssh"), []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"), 0700); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
|
|
entry := hook.AliasEntry{Name: "mxg1", Host: "office/xzi-groß1'$(oops)", Command: "mtr"}
|
|
for _, shell := range []string{"bash", "zsh", "fish"} {
|
|
t.Run(shell, func(t *testing.T) {
|
|
path, err := exec.LookPath(shell)
|
|
if err != nil {
|
|
t.Skip("shell not installed")
|
|
}
|
|
// A separate parse models invoking an alias after sourcing the file.
|
|
script := entry.Definition(shell) + "\neval 'mxg1 --report'\n"
|
|
args := []string{"-c", script}
|
|
if shell == "bash" {
|
|
args = []string{"--noprofile", "--norc", "-O", "expand_aliases", "-c", script}
|
|
}
|
|
if shell == "zsh" {
|
|
args = []string{"-f", "-c", script}
|
|
}
|
|
if shell == "fish" {
|
|
args = []string{"--no-config", "-c", script}
|
|
}
|
|
out, err := exec.Command(path, args...).CombinedOutput()
|
|
want := "run\nmtr\n--\n" + entry.Host + "\n--report\n"
|
|
if err != nil || string(out) != want {
|
|
t.Fatalf("%q (%v), want %q", out, err, want)
|
|
}
|
|
})
|
|
}
|
|
}
|