Files
ssh-netbox-wrapper/cmd/netssh/insights_test.go
T
Sebastian UnterschützandClaude Opus 5.5 1660bb3098
Test / test (pull_request) Successful in 4m15s
feat: NetBox insights, host tools and configurable TUI
- info/open/whois: NetBox details (site, nested locations, rack units,
  role, platform, tenant, IPs per interface), web page, reverse IP lookup
- cache status, site, role, platform, tenant, location chain and rack;
  ask before connecting to hosts in ssh.warn_status (--force skips)
- ssh rules and command restrictions match site/role/platform/tenant/status
- tui.columns selects what the TUI shows; optional TCP reachability column;
  detail view (Ctrl+L), NetBox page (Ctrl+G), status/location filters
- resolver.fallback tries other strategies' addresses when unreachable
- copy-id, known-hosts reset and address-change notices
- export ansible (YAML/INI) and export ssh-config
- token: keyring stores NetBox tokens in the system keyring
- fix stale menu number in testenv configure test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:33:59 +01:00

560 lines
18 KiB
Go

package main
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"go.yaml.in/yaml/v3"
"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/resolver"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/secret"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
// insightEnv writes a config and a cache with two NetBox hosts and a static host.
func insightEnv(t *testing.T, yamlConfig string) string {
t.Helper()
configDir := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", configDir)
t.Setenv("XDG_CACHE_HOME", t.TempDir())
path := filepath.Join(t.TempDir(), "hosts.json")
t.Setenv("NETSSH_CACHE_PATH", path)
t.Setenv("NETSSH_SHELL_ALIAS", "")
if err := os.WriteFile(filepath.Join(configDir, "netssh.yaml"), []byte(yamlConfig), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
c := cache.New(cfg.CachePath(), 3600)
c.Upsert(cache.Entry{Name: "prod/web01", IP: "10.0.0.1", Kind: "vm", Tags: []string{"prod", "Web Server"}, ID: 11, Status: "active",
Site: &config.Ref{Name: "FSN 1", Slug: "fsn1"}, Role: &config.Ref{Name: "Web", Slug: "web"}, Platform: &config.Ref{Name: "Ubuntu 24.04", Slug: "ubuntu-24-04"}})
c.Upsert(cache.Entry{Name: "lab/web01", IP: "10.9.0.1", Kind: "vm", ID: 12, Status: "planned"})
c.Upsert(cache.Entry{Name: "prod/sw1", IP: "10.0.0.2", Kind: "device", ID: 13, Status: "active", Platform: &config.Ref{Name: "Junos", Slug: "junos"},
Location: []config.Ref{{Name: "Building A", Slug: "building-a"}, {Name: "Room 2.04", Slug: "room-2-04"}}, Rack: "R12", Position: "20"})
if err := c.Save(); err != nil {
t.Fatal(err)
}
return path
}
const insightConfig = `netboxes:
- name: prod
url: https://nb.example
token: t
- name: lab
url: https://lab.example
token: t
ssh:
default_user: admin
rules:
- match: {platform: junos}
proxy_jump: jump.example
options: {KexAlgorithms: +diffie-hellman-group14-sha1}
hosts:
- name: router
address: 192.168.1.1
port: 2222
tags: [home]
`
func TestExportAnsibleYAML(t *testing.T) {
insightEnv(t, insightConfig)
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
keys, _ := parseGroupBy("tag,site,platform,status")
hosts, err := exportHosts(cfg, exportFilter{})
if err != nil {
t.Fatal(err)
}
data, err := buildInventory(hosts, keys, true).yaml()
if err != nil {
t.Fatal(err)
}
var inv struct {
All struct {
Hosts map[string]map[string]any `yaml:"hosts"`
Children map[string]struct {
Hosts map[string]any `yaml:"hosts"`
} `yaml:"children"`
} `yaml:"all"`
}
if err := yaml.Unmarshal(data, &inv); err != nil {
t.Fatalf("invalid YAML: %v\n%s", err, data)
}
web := inv.All.Hosts["prod-web01"]
if web["ansible_host"] != "10.0.0.1" || web["ansible_user"] != "admin" || web["netbox_site"] != "FSN 1" || web["netbox_id"] != 11 {
t.Fatalf("prod-web01 vars wrong: %+v\n%s", web, data)
}
if tags, _ := web["netbox_tags"].([]any); len(tags) != 2 {
t.Fatalf("tags should stay a list: %#v", web["netbox_tags"])
}
if _, ok := inv.All.Hosts["lab-web01"]; !ok {
t.Fatalf("duplicate hostnames must be qualified: %v", inv.All.Hosts)
}
sw := inv.All.Hosts["sw1"]
if sw["ansible_ssh_common_args"] != "-o ProxyJump=jump.example" {
t.Fatalf("jump host missing for platform rule: %+v", sw)
}
router := inv.All.Hosts["router"]
if router["ansible_port"] != 2222 || router["ansible_host"] != "192.168.1.1" {
t.Fatalf("static host wrong: %+v", router)
}
for _, group := range []string{"tag_prod", "tag_web_server", "site_fsn1", "platform_junos", "status_planned", "tag_home"} {
if _, ok := inv.All.Children[group]; !ok {
t.Errorf("group %s missing in\n%s", group, data)
}
}
if _, ok := inv.All.Children["platform_junos"].Hosts["sw1"]; !ok {
t.Fatal("sw1 not in platform_junos")
}
}
func TestExportAnsibleINI(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
hosts, err := exportHosts(cfg, exportFilter{instance: "prod"})
if err != nil {
t.Fatal(err)
}
keys, _ := parseGroupBy("tag,role")
out := string(buildInventory(hosts, keys, true).ini())
for _, want := range []string{
"[all]\nsw1 ansible_host=10.0.0.2 ansible_user=admin ansible_ssh_common_args=\"-o ProxyJump=jump.example\"",
`web01 ansible_host=10.0.0.1`,
`netbox_site="FSN 1"`,
`netbox_tags="prod,Web Server"`,
"\n[role_web]\nweb01\n",
"\n[tag_prod]\nweb01\n",
} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in\n%s", want, out)
}
}
if strings.Contains(out, "lab") || strings.Contains(out, "router") {
t.Fatalf("--instance prod not applied:\n%s", out)
}
}
func TestExportFiltersAndGroupByValidation(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
hosts, err := exportHosts(cfg, exportFilter{status: "active", noStatic: true})
if err != nil {
t.Fatal(err)
}
if len(hosts) != 2 {
t.Fatalf("status filter: %+v", hosts)
}
if _, err := parseGroupBy("site,color"); err == nil {
t.Fatal("unknown group-by accepted")
}
if keys, err := parseGroupBy("none"); err != nil || keys != nil {
t.Fatal("none should disable groups")
}
if _, err := exportHosts(cfg, exportFilter{tag: "missing"}); err == nil {
t.Fatal("empty export should fail")
}
}
func TestExportSSHConfig(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
hosts, err := exportHosts(cfg, exportFilter{})
if err != nil {
t.Fatal(err)
}
var b bytes.Buffer
writeSSHConfig(&b, hosts, map[string]string{"prod/sw1": "sw"})
out := b.String()
for _, want := range []string{
"\nHost sw1 sw\n HostName 10.0.0.2\n User admin\n ProxyJump jump.example\n kexalgorithms +diffie-hellman-group14-sha1\n",
"\nHost router\n HostName 192.168.1.1\n User admin\n Port 2222\n",
"\nHost prod-web01\n HostName 10.0.0.1\n",
} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in\n%s", want, out)
}
}
}
func TestCopyIDArgv(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
h, err := resolveTargetE(cfg, "prod/sw1", false)
if err != nil {
t.Fatal(err)
}
argv, err := copyIDArgv(cfg, h, copyIDFlags{identity: "/k.pub"})
if err != nil {
t.Fatal(err)
}
got := internalssh.Quote(argv)
for _, want := range []string{"ssh-copy-id -i /k.pub", "-o ProxyJump=jump.example", "-o kexalgorithms=+diffie-hellman-group14-sha1", "admin@10.0.0.2"} {
if !strings.Contains(got, want) {
t.Errorf("missing %q in %s", want, got)
}
}
if strings.Contains(got, " -J ") {
t.Fatalf("ssh-copy-id has no -J: %s", got)
}
router, _ := resolveTargetE(cfg, "router", false)
argv, _ = copyIDArgv(cfg, router, copyIDFlags{user: "root", noJump: true, check: true})
if got := internalssh.Quote(argv); !strings.Contains(got, "-n") || !strings.Contains(got, "-p 2222") || !strings.HasSuffix(got, "root@192.168.1.1") {
t.Fatalf("static host argv wrong: %s", got)
}
}
func TestRunCopyIDContinuesAfterFailure(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
var ran []string
old := runCopyIDCommand
runCopyIDCommand = func(argv []string) error {
ran = append(ran, argv[len(argv)-1])
if strings.Contains(argv[len(argv)-1], "10.0.0.2") {
return errors.New("permission denied")
}
return nil
}
t.Cleanup(func() { runCopyIDCommand = old })
stubTerminal(t, false)
err := runCopyID(cfg, []string{"prod/sw1", "router"}, copyIDFlags{})
if err == nil || !strings.Contains(err.Error(), "1 of 2 hosts") || len(ran) != 2 {
t.Fatalf("err %v, ran %v", err, ran)
}
}
func stubTerminal(t *testing.T, tty bool) {
t.Helper()
old := stdinIsTerminal
stdinIsTerminal = func() bool { return tty }
t.Cleanup(func() { stdinIsTerminal = old })
}
func TestConfirmStatusWarnsWithoutTerminal(t *testing.T) {
stubTerminal(t, false)
cfg := &config.Config{}
if err := confirmStatus(cfg, resolvedHost{Name: "web", Status: "offline"}, false); err != nil {
t.Fatalf("non-interactive status check must not fail: %v", err)
}
if err := confirmStatus(cfg, resolvedHost{Name: "web", Status: "active"}, false); err != nil {
t.Fatal(err)
}
}
func TestKnownHostsKeysAndFile(t *testing.T) {
keys := knownHostsKeys("prod/web01", []string{"10.0.0.1", "10.0.0.1", "10.0.0.9"}, 2222)
want := []string{"web01", "[web01]:2222", "10.0.0.1", "[10.0.0.1]:2222", "10.0.0.9", "[10.0.0.9]:2222"}
if strings.Join(keys, " ") != strings.Join(want, " ") {
t.Fatalf("got %v", keys)
}
if keys := knownHostsKeys("web", []string{"10.0.0.1"}, 22); strings.Join(keys, " ") != "web 10.0.0.1" {
t.Fatalf("got %v", keys)
}
t.Setenv("HOME", "/home/u")
if f := knownHostsFile(config.SSHOptions{Options: map[string]string{"userknownhostsfile": "~/.ssh/lab_hosts ~/.ssh/other"}}); f != "/home/u/.ssh/lab_hosts" {
t.Fatalf("file %q", f)
}
if f := knownHostsFile(config.SSHOptions{Options: map[string]string{"userknownhostsfile": "/dev/null"}}); f != "" {
t.Fatalf("file %q", f)
}
}
func TestKnownHostsResetRemovesNameAndAddresses(t *testing.T) {
insightEnv(t, insightConfig)
var removed []string
old := removeKnownHosts
removeKnownHosts = func(keys []string, file string) error { removed = append(removed, keys...); return nil }
t.Cleanup(func() { removeKnownHosts = old })
cmd := rootCmd()
cmd.SetArgs([]string{"known-hosts", "reset", "--yes", "router"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if strings.Join(removed, " ") != "router [router]:2222 192.168.1.1 [192.168.1.1]:2222" {
t.Fatalf("removed %v", removed)
}
}
func TestConnectPort(t *testing.T) {
for _, tc := range []struct {
client internalssh.Client
args []string
want int
}{
{internalssh.SSH, []string{"-p", "2222", "web"}, 2222},
{internalssh.SSH, []string{"-p2200", "web"}, 2200},
{internalssh.SSH, []string{"-o", "Port=2022", "web"}, 2022},
{internalssh.SFTP, []string{"-P", "23", "web"}, 23},
{internalssh.SSH, []string{"web", "-p", "1"}, 22},
} {
dest := 0
for i, a := range tc.args {
if a == "web" {
dest = i
}
}
if got := connectPort(tc.client, tc.args, []int{dest}); got != tc.want {
t.Errorf("%v: got %d, want %d", tc.args, got, tc.want)
}
}
}
func TestApplyFallback(t *testing.T) {
up := map[string]bool{"10.0.0.2": true}
oldProbe, oldCandidates := fallbackProbe, fallbackCandidates
fallbackProbe = func(address string, port int, _ time.Duration) bool { return up[address] && port == 22 }
fallbackCandidates = func(*config.Config, resolvedHost) ([]resolver.Candidate, error) {
return []resolver.Candidate{{Address: "10.0.0.1", Strategy: "management_subnet"}, {Address: "10.0.0.2", Strategy: "primary_ip"}}, nil
}
t.Cleanup(func() { fallbackProbe, fallbackCandidates = oldProbe, oldCandidates })
host := resolvedHost{Name: "web", Kind: "vm", IP: "10.0.0.1"}
cfg := &config.Config{}
if got := applyFallback(cfg, host, config.SSHOptions{}, internalssh.WrapperFlags{}, 22); got.IP != "10.0.0.1" {
t.Fatal("fallback ran while disabled")
}
cfg.Resolver.Fallback = true
if got := applyFallback(cfg, host, config.SSHOptions{}, internalssh.WrapperFlags{}, 22); got.IP != "10.0.0.2" {
t.Fatalf("fallback did not switch: %s", got.IP)
}
if got := applyFallback(cfg, host, config.SSHOptions{ProxyJump: "jump"}, internalssh.WrapperFlags{}, 22); got.IP != "10.0.0.1" {
t.Fatal("hosts behind a jump host must not be probed")
}
if got := applyFallback(cfg, host, config.SSHOptions{ProxyJump: "jump"}, internalssh.WrapperFlags{NoJump: true}, 22); got.IP != "10.0.0.2" {
t.Fatal("--no-jump should allow the fallback")
}
up = map[string]bool{}
if got := applyFallback(cfg, host, config.SSHOptions{}, internalssh.WrapperFlags{}, 22); got.IP != "10.0.0.1" {
t.Fatal("must keep the chosen address when nothing answers")
}
}
func TestReachableProbe(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Skip(err)
}
port := ln.Addr().(*net.TCPAddr).Port
if !reachable("127.0.0.1", port, time.Second) {
t.Fatal("listening port reported unreachable")
}
ln.Close()
if reachable("127.0.0.1", port, 200*time.Millisecond) {
t.Fatal("closed port reported reachable")
}
}
func TestWhoisAddresses(t *testing.T) {
old := lookupHost
lookupHost = func(_ context.Context, host string) ([]string, error) {
if host == "mail.example.com" {
return []string{"192.0.2.25"}, nil
}
return nil, errors.New("no such host")
}
t.Cleanup(func() { lookupHost = old })
for in, want := range map[string]string{"10.0.0.1": "10.0.0.1", "10.0.0.0/24": "10.0.0.0", "mail.example.com": "192.0.2.25"} {
got, err := whoisAddresses(context.Background(), in)
if err != nil || len(got) != 1 || got[0] != want {
t.Errorf("%s: %v %v", in, got, err)
}
}
if _, err := whoisAddresses(context.Background(), "nope.invalid"); err == nil {
t.Fatal("unresolvable name accepted")
}
}
func TestWhoisCommandUsesNetBoxAndCache(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/ipam/ip-addresses/":
fmt.Fprint(w, `{"count":1,"results":[{"address":"10.0.0.1/24","dns_name":"web01.example.com","assigned_object":{"name":"eth0","virtual_machine":{"id":11,"name":"web01"}}}]}`)
case "/api/ipam/prefixes/":
fmt.Fprint(w, `{"count":1,"results":[{"prefix":"10.0.0.0/24","description":"servers"}]}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
insightEnv(t, fmt.Sprintf("netboxes:\n - name: prod\n url: %s\n token: t\n", srv.URL))
var out bytes.Buffer
cmd := rootCmd()
cmd.SetOut(&out)
cmd.SetArgs([]string{"whois", "10.0.0.1"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
for _, want := range []string{"prod/web01 (vm) eth0", "dns web01.example.com", "10.0.0.0/24 (prod)", `"servers"`, "Cache prod/web01"} {
if !strings.Contains(out.String(), want) {
t.Errorf("missing %q in\n%s", want, out.String())
}
}
}
func TestOpenPrintsNetBoxURL(t *testing.T) {
insightEnv(t, insightConfig)
var out bytes.Buffer
cmd := rootCmd()
cmd.SetOut(&out)
cmd.SetArgs([]string{"open", "--print", "prod/sw1"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if strings.TrimSpace(out.String()) != "https://nb.example/dcim/devices/13/" {
t.Fatalf("got %q", out.String())
}
cmd = rootCmd()
cmd.SetArgs([]string{"open", "--print", "router"})
if err := cmd.Execute(); err == nil || !strings.Contains(err.Error(), "static host") {
t.Fatalf("static host: %v", err)
}
}
func TestTokenMigrateAndResolve(t *testing.T) {
secret.MockInit()
insightEnv(t, insightConfig)
var saved config.Config
old := saveConfig
saveConfig = func(cfg config.Config) error { saved = cfg; return nil }
t.Cleanup(func() { saveConfig = old })
tokenMu.Lock()
tokenCache = map[string]string{}
tokenMu.Unlock()
var out bytes.Buffer
cmd := rootCmd()
cmd.SetOut(&out)
cmd.SetArgs([]string{"token", "migrate"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if len(saved.NetBoxes) != 2 || !config.IsKeyringToken(saved.NetBoxes[0].Token) || !config.IsKeyringToken(saved.NetBoxes[1].Token) {
t.Fatalf("tokens not replaced: %+v", saved.NetBoxes)
}
token, err := resolveToken(saved.NetBoxes[0])
if err != nil || token != "t" {
t.Fatalf("token %q, %v", token, err)
}
cmd = rootCmd()
cmd.SetIn(strings.NewReader("nbt_secret\n"))
cmd.SetOut(&out)
cmd.SetArgs([]string{"token", "set", "lab"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
stored, err := secret.Get("lab")
if err != nil || stored != "nbt_secret" {
t.Fatalf("stored %q, %v", stored, err)
}
for _, n := range saved.NetBoxes {
if n.Name == "lab" && n.TokenVersion != 2 {
t.Fatalf("token version not detected: %+v", n)
}
}
cmd = rootCmd()
cmd.SetArgs([]string{"token", "set"})
if err := cmd.Execute(); err == nil {
t.Fatal("ambiguous instance accepted")
}
}
func TestCacheRefreshStoresAttributesAndReportsChangedAddresses(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/dcim/devices/":
fmt.Fprint(w, `{"count":1,"results":[{"id":5,"name":"sw1","primary_ip4":{"address":"192.0.2.5/24"},
"status":{"value":"offline"},"site":{"name":"FSN1","slug":"fsn1"},"role":{"name":"Switch","slug":"switch"},"platform":{"name":"Junos","slug":"junos"}}]}`)
case "/api/virtualization/virtual-machines/", "/api/ipam/ip-addresses/":
fmt.Fprint(w, `{"count":0,"results":[]}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
path := prepareRefreshTest(t, srv.URL, "[primary_ip]")
c := cache.New(path, 3600)
c.Upsert(cache.Entry{Name: "sw1", IP: "192.0.2.99", Kind: "device"})
if err := c.Save(); err != nil {
t.Fatal(err)
}
stdout := captureStdout(t, func() {
cmd := rootCmd()
cmd.SetArgs([]string{"cache", "refresh"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
})
if !strings.Contains(stdout, "sw1: 192.0.2.99 → 192.0.2.5") || !strings.Contains(stdout, "known-hosts reset") {
t.Fatalf("address change not reported:\n%s", stdout)
}
if err := c.Load(); err != nil {
t.Fatal(err)
}
got, _ := c.Get("sw1")
if got.ID != 5 || got.Status != "offline" || cache.RefOf(got.Site).Slug != "fsn1" || cache.RefOf(got.Platform).Slug != "junos" || cache.RefOf(got.Role).Name != "Switch" {
t.Fatalf("attributes not cached: %+v", got)
}
cfg, _ := config.Load()
h, _ := resolveTargetE(cfg, "sw1", false)
if h.Status != "offline" || h.Platform.Slug != "junos" || h.ID != 5 {
t.Fatalf("resolved host lacks attributes: %+v", h)
}
}
func captureStdout(t *testing.T, fn func()) string {
t.Helper()
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
old := os.Stdout
os.Stdout = w
done := make(chan string)
go func() {
var b bytes.Buffer
_, _ = b.ReadFrom(r)
done <- b.String()
}()
defer func() { os.Stdout = old }()
fn()
w.Close()
os.Stdout = old
return <-done
}
func TestExportLocationVarsAndGroups(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
hosts, err := exportHosts(cfg, exportFilter{instance: "prod", kind: "device"})
if err != nil {
t.Fatal(err)
}
keys, _ := parseGroupBy("location,rack")
out := string(buildInventory(hosts, keys, true).ini())
for _, want := range []string{`netbox_location="Building A/Room 2.04"`, "netbox_rack=R12", "netbox_position=20",
"\n[location_building_a]\nsw1\n", "\n[location_room_2_04]\nsw1\n", "\n[rack_r12]\nsw1\n"} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in\n%s", want, out)
}
}
}