v1
Test / test (push) Successful in 3m36s
Release / release (push) Successful in 7m31s

This commit is contained in:
Sebastian Unterschütz committed 2026-11-17 19:00:44 +01:00
commit 8d4915543e
132 files changed
+20628

No files matched your search

+197
View File
@@ -0,0 +1,197 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strconv"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
type connectionTestHost struct {
ID int `json:"id"`
Name string `json:"name"`
PrimaryIP4 *struct {
Address string `json:"address"`
} `json:"primary_ip4,omitempty"`
}
func connectionTestServer(t *testing.T, devices, vms []connectionTestHost) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
var hosts []connectionTestHost
switch r.URL.Path {
case "/api/dcim/devices/":
hosts = devices
case "/api/virtualization/virtual-machines/":
hosts = vms
case "/api/ipam/ip-addresses/":
fmt.Fprint(w, `{"count":0,"results":[]}`)
return
default:
http.NotFound(w, r)
return
}
query := strings.ToLower(r.URL.Query().Get("name__ic"))
matched := make([]connectionTestHost, 0)
for _, host := range hosts {
if strings.Contains(strings.ToLower(host.Name), query) {
matched = append(matched, host)
}
}
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
if limit <= 0 {
limit = 50
}
start, end := min(offset, len(matched)), min(offset+limit, len(matched))
json.NewEncoder(w).Encode(map[string]any{"count": len(matched), "results": matched[start:end]})
}))
t.Cleanup(srv.Close)
return srv
}
func TestFindSSHHostBeyondFirstPage(t *testing.T) {
var devices []connectionTestHost
for i := range 50 {
devices = append(devices, connectionTestHost{ID: i + 1, Name: fmt.Sprintf("web-extra-%02d", i)})
}
devices = append(devices, connectionTestHost{ID: 51, Name: "web"})
srv := connectionTestServer(t, devices, nil)
host, err := findSSHHost(context.Background(), netbox.NewClient(srv.URL, "token", 0), "web", nil)
if err != nil || host.ID != 51 {
t.Fatalf("host beyond first page not resolved: %+v, %v", host, err)
}
}
func TestFindSSHHostDomainExpansion(t *testing.T) {
for _, domain := range []string{"example.com", ".example.com", " .example.com "} {
t.Run(domain, func(t *testing.T) {
srv := connectionTestServer(t, []connectionTestHost{{ID: 1, Name: "web.example.com"}}, nil)
host, err := findSSHHost(context.Background(), netbox.NewClient(srv.URL, "token", 0), "web", []string{domain})
if err != nil || host.Name != "web.example.com" {
t.Fatalf("domain expansion failed: %+v, %v", host, err)
}
})
}
}
func TestFindSSHHostRejectsAmbiguity(t *testing.T) {
srv := connectionTestServer(t, []connectionTestHost{{ID: 1, Name: "web"}, {ID: 2, Name: "web.example.com"}}, []connectionTestHost{{ID: 3, Name: "web"}})
_, err := findSSHHost(context.Background(), netbox.NewClient(srv.URL, "token", 0), "web", []string{"example.com"})
if err == nil || errors.Is(err, netbox.ErrHostNotFound) || !strings.Contains(err.Error(), "2 exact matches") {
t.Fatalf("ambiguous name accepted or expanded: %v", err)
}
}
func TestFindSSHHostDoesNotHideAPIErrors(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "unavailable", http.StatusServiceUnavailable)
}))
defer srv.Close()
_, err := findSSHHost(context.Background(), netbox.NewClient(srv.URL, "token", 0), "web", []string{"example.com"})
if err == nil || errors.Is(err, netbox.ErrHostNotFound) {
t.Fatalf("API failure hidden as missing host: %v", err)
}
}
func TestFindSSHHostNotFound(t *testing.T) {
srv := connectionTestServer(t, nil, nil)
_, err := findSSHHost(context.Background(), netbox.NewClient(srv.URL, "token", 0), "missing", []string{"example.com"})
if !errors.Is(err, netbox.ErrHostNotFound) {
t.Fatalf("want missing-host error, got %v", err)
}
}
func TestCacheRefreshHonorsResolverAndRemovesUnsafeEntries(t *testing.T) {
for _, tc := range []struct {
name, strategies string
wantCached bool
}{
{"management only", "[management_subnet]", false},
{"explicit primary fallback", "[management_subnet, primary_ip]", true},
} {
t.Run(tc.name, func(t *testing.T) {
host := connectionTestHost{ID: 1, Name: "web", PrimaryIP4: &struct {
Address string `json:"address"`
}{Address: "192.0.2.1/24"}}
srv := connectionTestServer(t, []connectionTestHost{host}, nil)
path := prepareRefreshTest(t, srv.URL, tc.strategies)
c := cache.New(path, 3600)
c.Upsert(cache.Entry{Name: "web", IP: "192.0.2.99", Kind: "device"})
if err := c.Save(); err != nil {
t.Fatal(err)
}
cmd := rootCmd()
cmd.SetArgs([]string{"cache", "refresh"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if err := c.Load(); err != nil {
t.Fatal(err)
}
got, fresh := c.Get("web")
if tc.wantCached {
if !fresh || got.IP != "192.0.2.1" {
t.Fatalf("explicit fallback failed: %+v", got)
}
} else if got.Name != "" {
t.Fatalf("unsafe primary IP retained: %+v", got)
}
})
}
}
func TestCacheRefreshSkipsAmbiguousNames(t *testing.T) {
host := connectionTestHost{ID: 1, Name: "web", PrimaryIP4: &struct {
Address string `json:"address"`
}{Address: "192.0.2.1/24"}}
vm := host
vm.ID = 2
srv := connectionTestServer(t, []connectionTestHost{host}, []connectionTestHost{vm})
path := prepareRefreshTest(t, srv.URL, "[primary_ip]")
c := cache.New(path, 3600)
c.Upsert(cache.Entry{Name: "web", IP: "192.0.2.99", Kind: "device"})
if err := c.Save(); err != nil {
t.Fatal(err)
}
cmd := rootCmd()
cmd.SetArgs([]string{"cache", "refresh"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if err := c.Load(); err != nil {
t.Fatal(err)
}
if len(c.All()) != 0 {
t.Fatalf("ambiguous host cached: %+v", c.All())
}
}
func prepareRefreshTest(t *testing.T, baseURL, strategies 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_NETBOX_URL", baseURL)
t.Setenv("NETSSH_NETBOX_TOKEN", "token")
t.Setenv("NETSSH_SHELL_ALIAS", "")
data := fmt.Sprintf("resolver:\n strategies: %s\n management_subnets: [10.0.0.0/8]\n", strategies)
if err := os.WriteFile(filepath.Join(configDir, "netssh.yaml"), []byte(data), 0o600); err != nil {
t.Fatal(err)
}
return path
}
+163
View File
@@ -0,0 +1,163 @@
package main
import (
"fmt"
"os"
"strings"
"text/tabwriter"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/setup"
)
func hostsCmd() *cobra.Command {
var showAliases bool
cmd := &cobra.Command{
Use: "hosts",
Short: "Manage static hosts that are not in NetBox",
Long: `Static hosts are defined under hosts: in the config. They are found before
NetBox, work offline, and support shortcuts, rules (kind: static), aliases,
completion, sftp, scp, and tunnels like NetBox hosts.`,
RunE: func(cmd *cobra.Command, args []string) error { return listHosts(showAliases) },
}
cmd.AddCommand(hostsListCmd(), hostsAddCmd(), hostsRemoveCmd())
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
return cmd
}
func hostsListCmd() *cobra.Command {
var showAliases bool
cmd := &cobra.Command{
Use: "list",
Short: "List static hosts",
RunE: func(cmd *cobra.Command, args []string) error { return listHosts(showAliases) },
}
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
return cmd
}
func listHosts(showAliases bool) error {
cfg, err := config.Load()
if err != nil {
return err
}
if len(cfg.Hosts) == 0 {
fmt.Println("No static hosts. Add one with: netssh hosts add NAME ADDRESS")
return nil
}
withAliases := showAliases || cfg.Shortcuts.Show
var aliases map[string]string
if withAliases {
// Aliases are unique across all hosts, so compute them with the cache.
c := newCache(cfg)
_ = c.Load()
aliases = shortcutAliases(c.All(), *cfg)
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
if withAliases {
fmt.Fprintln(w, "NAME\tALIAS\tADDRESS\tUSER\tPORT\tTAGS")
} else {
fmt.Fprintln(w, "NAME\tADDRESS\tUSER\tPORT\tTAGS")
}
for _, host := range cfg.Hosts {
port := ""
if host.Port > 0 {
port = fmt.Sprint(host.Port)
}
if withAliases {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", host.Name, orDash(aliases[strings.ToLower(host.Name)]), host.Address, host.User, port, strings.Join(host.Tags, ","))
continue
}
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", host.Name, host.Address, host.User, port, strings.Join(host.Tags, ","))
}
return w.Flush()
}
func hostsAddCmd() *cobra.Command {
var host config.StaticHost
var replace bool
cmd := &cobra.Command{
Use: "add NAME ADDRESS",
Short: "Add a static host (or replace one with --replace)",
Example: ` netssh hosts add router 192.168.1.1 --user admin
netssh hosts add backup backup.example.org --port 2222 --tag offsite`,
Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
host.Name, host.Address = args[0], args[1]
if existing := cfg.StaticHost(host.Name); existing != nil {
if !replace {
return fmt.Errorf("static host %q already exists; use --replace to overwrite it", existing.Name)
}
host.SSH = existing.SSH // keep SSH options set in the config or wizard
*existing = host
} else {
cfg.Hosts = append(cfg.Hosts, host)
}
return saveHosts(cfg)
},
}
cmd.Flags().StringVar(&host.User, "user", "", "Login user (default: ssh.default_user)")
cmd.Flags().IntVar(&host.Port, "port", 0, "SSH port (default: ssh.default_port or 22)")
cmd.Flags().StringSliceVar(&host.Tags, "tag", nil, "Tag for ssh.rules (repeatable)")
cmd.Flags().BoolVar(&replace, "replace", false, "Overwrite an existing static host")
return cmd
}
func hostsRemoveCmd() *cobra.Command {
return &cobra.Command{
Use: "remove NAME",
Aliases: []string{"rm"},
Short: "Remove a static host",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
for i, host := range cfg.Hosts {
if strings.EqualFold(host.Name, args[0]) {
cfg.Hosts = append(cfg.Hosts[:i], cfg.Hosts[i+1:]...)
return saveHosts(cfg)
}
}
return fmt.Errorf("no static host %q", args[0])
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
cfg, err := config.Load()
if err != nil || len(args) > 0 {
return nil, cobra.ShellCompDirectiveNoFileComp
}
var names []string
for _, host := range cfg.Hosts {
if strings.HasPrefix(strings.ToLower(host.Name), strings.ToLower(toComplete)) {
names = append(names, host.Name)
}
}
return names, cobra.ShellCompDirectiveNoFileComp
},
}
}
// saveHosts writes the config and regenerates the shell aliases.
func saveHosts(cfg *config.Config) error {
if err := setup.Save(*cfg); err != nil {
return err
}
loaded, err := config.Load()
if err != nil {
return err
}
c := newCache(loaded)
_ = c.Load()
if err := hook.WriteAliasFiles(hook.BuildAliasEntries(c.All(), *loaded)); err != nil {
fmt.Fprintf(os.Stderr, "warning: could not write alias files: %v\n", err)
}
return nil
}
+130
View File
@@ -0,0 +1,130 @@
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
// prepareConfig writes data as the only config, with empty cache and home.
func prepareConfig(t *testing.T, data string) string {
t.Helper()
dir := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", dir)
t.Setenv("XDG_CACHE_HOME", t.TempDir())
t.Setenv("NETSSH_NETBOX_URL", "")
t.Setenv("NETSSH_NETBOX_TOKEN", "")
t.Setenv("NETSSH_CACHE_PATH", filepath.Join(t.TempDir(), "hosts.json"))
t.Setenv("NETSSH_SHELL_ALIAS", "")
path := filepath.Join(dir, "netssh.yaml")
if err := os.WriteFile(path, []byte(data), 0o600); err != nil {
t.Fatal(err)
}
return path
}
const staticOnlyConfig = `ssh:
default_user: ops
rules:
- match: {kind: static, tag: home}
host_key_checking: accept-new
shortcuts:
domains: [.lan]
hosts:
- name: router.lan
address: 192.168.1.1
user: admin
port: 2222
tags: [home]
- name: nas
address: nas.example.org
ssh:
proxy_jump: jh.example.com
`
// Static hosts work without any NetBox and with their own user, port, tags, and options.
func TestStaticHostsWithoutNetBox(t *testing.T) {
prepareConfig(t, staticOnlyConfig)
for _, tc := range []struct {
args []string
want string
}{
{[]string{"--dry-run", "router.lan"}, "ssh -p 2222 -l admin -o StrictHostKeyChecking=accept-new 192.168.1.1"},
{[]string{"--dry-run", "router"}, "ssh -p 2222 -l admin -o StrictHostKeyChecking=accept-new 192.168.1.1"}, // shortcut
{[]string{"--dry-run", "-l", "root", "nas", "uptime"}, "ssh -l root -J jh.example.com nas.example.org uptime"},
{[]string{"sftp", "--dry-run", "router:/etc"}, "sftp -P 2222 -o User=admin -o StrictHostKeyChecking=accept-new 192.168.1.1:/etc"},
{[]string{"scp", "--dry-run", "a.txt", "nas:/tmp/"}, "scp -o User=ops -J jh.example.com a.txt nas.example.org:/tmp/"},
} {
out, err := runNetssh(t, tc.args...)
if err != nil || out != tc.want {
t.Errorf("%v:\n got %s (%v)\n want %s", tc.args, out, err, tc.want)
}
}
if out, err := runNetssh(t, "--dry-run", "unknown"); err == nil || !strings.Contains(out, "no NetBox is configured") {
t.Errorf("unknown host: %s (%v)", out, err)
}
if out, _ := runNetssh(t, "__complete", "rou"); !strings.HasPrefix(out, "router.lan\n") {
t.Errorf("completion: %q", out)
}
if out, _ := runNetssh(t, "alias", "--shell", "bash"); !strings.Contains(out, "alias router='netssh router.lan'") || !strings.Contains(out, "alias nas='netssh nas'") {
t.Errorf("aliases: %s", out)
}
}
func TestHostsCommand(t *testing.T) {
path := prepareConfig(t, "hosts:\n - {name: nas, address: nas.example.org, ssh: {proxy_jump: jh}}\n")
steps := []struct {
args []string
wantErr string
}{
{[]string{"hosts", "add", "router", "192.168.1.1", "--user", "admin", "--port", "2222", "--tag", "home", "--tag", "lab"}, ""},
{[]string{"hosts", "add", "router", "10.0.0.1"}, "already exists"},
{[]string{"hosts", "add", "nas", "10.0.0.5", "--replace"}, ""},
{[]string{"hosts", "add", "bad name", "10.0.0.1"}, "must start with"},
{[]string{"hosts", "remove", "missing"}, "no static host"},
}
for _, step := range steps {
out, err := runNetssh(t, step.args...)
if step.wantErr == "" && err != nil || step.wantErr != "" && !strings.Contains(out, step.wantErr) {
t.Fatalf("%v: %s (%v)", step.args, out, err)
}
}
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
router, nas := cfg.StaticHost("router"), cfg.StaticHost("nas")
if router == nil || router.User != "admin" || router.Port != 2222 || strings.Join(router.Tags, ",") != "home,lab" {
t.Fatalf("router: %+v", router)
}
if nas == nil || nas.Address != "10.0.0.5" || nas.SSH.ProxyJump != "jh" {
t.Fatalf("--replace must keep SSH options: %+v", nas)
}
out, err := runNetssh(t, "hosts", "list")
if err != nil || !strings.Contains(out, "router 192.168.1.1 admin 2222 home,lab") {
t.Fatalf("list:\n%s (%v)", out, err)
}
if out, err := runNetssh(t, "hosts", "rm", "router"); err != nil {
t.Fatalf("remove: %s (%v)", out, err)
}
data, _ := os.ReadFile(path)
if strings.Contains(string(data), "router") || strings.Contains(string(data), "netbox:") {
t.Fatalf("config after remove:\n%s", data)
}
}
// The hostname strategy passes the NetBox name (plus domain) instead of an IP.
func TestHostnameStrategyConnects(t *testing.T) {
srv := connectionTestServer(t, []connectionTestHost{{ID: 1, Name: "web01"}, multiHost("db01", "10.0.0.7")}, nil)
prepareConfig(t, fmt.Sprintf("netbox:\n url: %q\n token: t\nresolver:\n strategies: [primary_ip, hostname]\n hostname_domain: example.com\n", srv.URL))
for host, want := range map[string]string{"web01": "ssh web01.example.com", "db01": "ssh 10.0.0.7"} {
if out, err := runNetssh(t, "--dry-run", host); err != nil || out != want {
t.Errorf("%s: got %s (%v), want %s", host, out, err, want)
}
}
}
+163
View File
@@ -0,0 +1,163 @@
package main
import (
"sort"
"strings"
"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"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/shortcuts"
)
// newCache opens the host cache with the config's static hosts.
func newCache(cfg *config.Config) *cache.Cache {
return cache.New(cfg.CachePath(), cfg.Cache.TTL).WithStatic(cfg.Hosts)
}
func newNetBoxClient(cfg *config.Config) *netbox.Client {
if len(cfg.NetBoxes) > 0 {
sources := make([]netbox.Source, 0, len(cfg.NetBoxes))
for _, source := range cfg.NetBoxes {
sources = append(sources, netbox.Source{Name: source.Name, URL: source.URL, Token: source.Token, TokenVersion: source.TokenVersion})
}
return netbox.NewMultiClient(sources)
}
if cfg.NetBox.URL == "" {
return nil
}
return netbox.NewClient(cfg.NetBox.URL, cfg.NetBox.Token, cfg.NetBox.TokenVersion)
}
// shortcutAliases maps each target (lowercased) to the shell alias generated for
// it, but only where shortcuts actually shorten the displayed name: an alias that
// merely replaces dots with underscores ("web01_example_com") adds nothing.
// The aliases are the same ones netssh alias and the shell hook define.
func shortcutAliases(entries []cache.Entry, cfg config.Config) map[string]string {
out := make(map[string]string)
if !cfg.Shortcuts.Enabled() {
return out
}
plain := strings.NewReplacer(".", "_", "/", "_")
for _, alias := range hook.BuildAliasEntries(append([]cache.Entry(nil), entries...), cfg) {
if alias.Host == "" {
continue // the command alias for netssh itself
}
if alias.Name == plain.Replace(strings.ToLower(cfg.HostLabel(alias.Host))) {
continue
}
out[strings.ToLower(alias.Host)] = alias.Name
}
return out
}
func normalizeTarget(cfg config.ShortcutsConfig, qualified bool) func(string) string {
return func(target string) string {
source, name := netbox.SplitTarget(target)
name = shortcuts.Normalize(name, cfg)
if qualified && source != "" {
return source + "/" + name
}
return name
}
}
// hostCompletions returns the cached hosts matching toComplete in a form that
// starts with the typed text, because bash and fish only accept such
// candidates. Without an instance prefix, a hostname that is unique across
// all instances is offered bare ("web01"), so it completes like with a single
// NetBox; connecting to it still checks every instance for ambiguity.
// Names present in several instances stay qualified ("prod/web01").
// Hosts whose full name does not match are offered by their configured
// shortcut instead ("fsnb" → "fsnbx1" for fsn1-bx1.example.com).
//
// With shortcuts.show, shortcuts are also offered for hosts whose full name
// matches, so "fsn" lists both fsn1-bx1.example.com and fsnbx1.
func hostCompletions(entries []cache.Entry, toComplete string, sc config.ShortcutsConfig) []string {
prefix := strings.ToLower(toComplete)
qualifiedInput := strings.Contains(prefix, "/")
instances := make(map[string]int)
for _, e := range entries {
_, name := netbox.SplitTarget(e.Name)
instances[strings.ToLower(name)]++
}
var unmatched []cache.Entry
var names []string
for _, e := range entries {
source, name := netbox.SplitTarget(e.Name)
target := strings.ToLower(e.Name)
switch {
case source != "" && !qualifiedInput && strings.HasPrefix(strings.ToLower(name), prefix):
if instances[strings.ToLower(name)] == 1 {
names = append(names, name)
} else {
names = append(names, e.Name)
}
case strings.HasPrefix(target, prefix):
names = append(names, e.Name)
default:
unmatched = append(unmatched, e)
}
}
if sc.Enabled() {
candidates := unmatched
if sc.Show {
candidates = entries
}
offered := make(map[string]bool, len(names))
for _, name := range names {
offered[strings.ToLower(name)] = true
}
for _, name := range shortcutCompletions(entries, candidates, prefix, sc) {
if !offered[name] {
offered[name] = true
names = append(names, name)
}
}
}
sort.Strings(names)
return names
}
// shortcutCompletions offers the shortcut of each unmatched host when it starts
// with prefix and selects exactly one host, qualified by instance if needed.
func shortcutCompletions(all, unmatched []cache.Entry, prefix string, sc config.ShortcutsConfig) []string {
bare := make(map[string]int)
qualified := make(map[string]int)
short := func(e cache.Entry) (string, string) {
source, name := netbox.SplitTarget(e.Name)
s := shortcuts.Normalize(name, sc)
if source == "" {
return s, s
}
return s, strings.ToLower(source) + "/" + s
}
for _, e := range all {
b, q := short(e)
bare[b]++
qualified[q]++
}
seen := make(map[string]bool)
var out []string
for _, e := range unmatched {
b, q := short(e)
candidate := ""
switch {
case strings.Contains(prefix, "/"):
if qualified[q] == 1 && strings.HasPrefix(q, prefix) {
candidate = q
}
case !strings.HasPrefix(b, prefix):
case bare[b] == 1:
candidate = b
case q != b && qualified[q] == 1:
candidate = q // like full names: zsh accepts it, bash/fish ignore it
}
if candidate != "" && !seen[candidate] {
seen[candidate] = true
out = append(out, candidate)
}
}
return out
}
+319
View File
@@ -0,0 +1,319 @@
package main
import (
"bytes"
"fmt"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func prepareInstancesTest(t *testing.T, officeURL, labURL string) *config.Config {
t.Helper()
dir := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", dir)
t.Setenv("XDG_CACHE_HOME", t.TempDir())
t.Setenv("NETSSH_NETBOX_URL", "")
t.Setenv("NETSSH_NETBOX_TOKEN", "")
t.Setenv("NETSSH_CACHE_PATH", filepath.Join(t.TempDir(), "hosts.json"))
t.Setenv("NETSSH_SHELL_ALIAS", "")
data := fmt.Sprintf("netboxes:\n - name: office\n url: %q\n token: office-token\n - name: lab\n url: %q\n token: lab-token\nresolver:\n strategies: [primary_ip]\n", officeURL, labURL)
if err := os.WriteFile(filepath.Join(dir, "netssh.yaml"), []byte(data), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
return cfg
}
func multiHost(name, ip string) connectionTestHost {
return connectionTestHost{ID: 1, Name: name, PrimaryIP4: &struct {
Address string `json:"address"`
}{Address: ip + "/24"}}
}
func TestRefreshStoresSameHostnameFromBothInstances(t *testing.T) {
office := connectionTestServer(t, []connectionTestHost{multiHost("web", "10.0.0.1")}, nil)
lab := connectionTestServer(t, []connectionTestHost{multiHost("web", "10.0.0.2")}, nil)
cfg := prepareInstancesTest(t, office.URL, lab.URL)
cmd := rootCmd()
cmd.SetArgs([]string{"cache", "refresh"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
c := cache.New(cfg.CachePath(), cfg.Cache.TTL)
if err := c.Load(); err != nil {
t.Fatal(err)
}
for name, ip := range map[string]string{"office/web": "10.0.0.1", "lab/web": "10.0.0.2"} {
got, fresh := c.Get(name)
if !fresh || got.IP != ip {
t.Fatalf("cache source collision: %+v, fresh=%v", got, fresh)
}
}
if len(c.All()) != 2 || c.NeedsRefresh(time.Hour) {
t.Fatal("full refresh is incomplete")
}
}
func TestRefreshFailureAndPerInstanceRefresh(t *testing.T) {
office := connectionTestServer(t, []connectionTestHost{multiHost("web", "10.0.0.1")}, nil)
failed := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "offline", 503) }))
defer failed.Close()
cfg := prepareInstancesTest(t, office.URL, failed.URL)
c := cache.New(cfg.CachePath(), cfg.Cache.TTL)
c.Upsert(cache.Entry{Name: "lab/old", Kind: "device", IP: "10.0.0.2"})
if err := c.Save(); err != nil {
t.Fatal(err)
}
cmd := rootCmd()
cmd.SetArgs([]string{"cache", "refresh"})
if err := cmd.Execute(); err == nil {
t.Fatal("failed instance marked as full refresh")
}
if err := c.Load(); err != nil {
t.Fatal(err)
}
if len(c.All()) != 1 || !c.NeedsRefresh(time.Hour) {
t.Fatal("partial refresh changed cache or full-refresh stamp")
}
cmd = rootCmd()
cmd.SetArgs([]string{"cache", "refresh", "--instance", "office"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if err := c.Load(); err != nil {
t.Fatal(err)
}
if len(c.All()) != 2 || !c.NeedsRefresh(time.Hour) {
t.Fatal("per-instance refresh lost other source or updated full stamp")
}
}
func TestLocalNotesCLIKeepsInstancesSeparate(t *testing.T) {
cfg := prepareInstancesTest(t, "https://office.example", "https://lab.example")
c := cache.New(cfg.CachePath(), cfg.Cache.TTL)
for _, name := range []string{"office/web", "lab/web"} {
c.Upsert(cache.Entry{Name: name, Kind: "device", IP: "10.0.0.1"})
}
if err := c.Save(); err != nil {
t.Fatal(err)
}
run := func(args ...string) (string, error) {
var out bytes.Buffer
cmd := rootCmd()
cmd.SetArgs(append([]string{"notes"}, args...))
cmd.SetOut(&out)
cmd.SetErr(&out)
err := cmd.Execute()
return out.String(), err
}
for _, source := range []string{"office", "lab"} {
if _, err := run("set", source+"/web", source+" note"); err != nil {
t.Fatal(err)
}
}
for _, source := range []string{"office", "lab"} {
got, err := run("show", source+"/web")
if err != nil || got != source+" note" {
t.Fatalf("CLI notes crossed sources: %q, %v", got, err)
}
}
if _, err := run("set", "web", "wrong note"); err == nil {
t.Fatal("ambiguous note target accepted")
}
}
func TestMultiInstanceWrapperHelper(t *testing.T) {
if target := os.Getenv("NETSSH_TEST_MULTI_TARGET"); target != "" {
runSSHWrapper([]string{target})
return
}
}
func TestWrapperRoutesQualifiedTargetsAndRejectsAmbiguity(t *testing.T) {
office := connectionTestServer(t, []connectionTestHost{multiHost("web", "10.0.0.1")}, nil)
lab := connectionTestServer(t, []connectionTestHost{multiHost("web", "10.0.0.2")}, nil)
cfg := prepareInstancesTest(t, office.URL, lab.URL)
c := cache.New(cfg.CachePath(), 3600)
if err := c.SetRefreshed(); err != nil {
t.Fatal(err)
}
bin := t.TempDir()
if err := os.WriteFile(filepath.Join(bin, "ssh"), []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"), 0o755); err != nil {
t.Fatal(err)
}
for target, want := range map[string]string{"office/web": "10.0.0.1", "lab/web": "10.0.0.2", "web": "ambiguous"} {
cmd := exec.Command(os.Args[0], "-test.run=^TestMultiInstanceWrapperHelper$")
cmd.Env = append(os.Environ(), "NETSSH_TEST_MULTI_TARGET="+target, "PATH="+bin+":"+os.Getenv("PATH"))
out, err := cmd.CombinedOutput()
if want == "ambiguous" {
if err == nil || !strings.Contains(string(out), "2 exact matches") {
t.Fatalf("ambiguous connection accepted: %s, %v", out, err)
}
} else if err != nil || !strings.Contains(string(out), want+"\n") {
t.Fatalf("wrong SSH destination for %s: %s, %v", target, out, err)
}
}
}
func TestQualifiedShortcutDoesNotMatchOtherInstance(t *testing.T) {
cfg := config.ShortcutsConfig{Domains: []string{".example.com"}, StripHyphens: true}
normalize := normalizeTarget(cfg, true)
if normalize("office/web-01.example.com") != normalize("office/web01") {
t.Fatal("qualified shortcut does not normalize")
}
if normalize("office/web01") == normalize("lab/web01") {
t.Fatal("qualified shortcut lost instance")
}
}
func TestRefreshCachesIndependentDevicesAndVMs(t *testing.T) {
office := connectionTestServer(t, []connectionTestHost{multiHost("router", "10.1.0.1")}, []connectionTestHost{multiHost("app", "10.1.0.2")})
lab := connectionTestServer(t, []connectionTestHost{multiHost("switch", "10.2.0.1")}, []connectionTestHost{multiHost("test-vm", "10.2.0.2")})
cfg := prepareInstancesTest(t, office.URL, lab.URL)
cmd := rootCmd()
cmd.SetArgs([]string{"cache", "refresh"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
c := cache.New(cfg.CachePath(), cfg.Cache.TTL)
if err := c.Load(); err != nil {
t.Fatal(err)
}
want := map[string]struct{ kind, ip string }{
"office/router": {"device", "10.1.0.1"}, "office/app": {"vm", "10.1.0.2"},
"lab/switch": {"device", "10.2.0.1"}, "lab/test-vm": {"vm", "10.2.0.2"},
}
if len(c.All()) != len(want) {
t.Fatalf("missing inventory entries: %+v", c.All())
}
for name, entry := range want {
got, fresh := c.Get(name)
if !fresh || got.Kind != entry.kind || got.IP != entry.ip {
t.Fatalf("wrong cached host %s: %+v", name, got)
}
}
}
func TestHostCompletionsMatchTypedText(t *testing.T) {
entries := []cache.Entry{
{Name: "prod/fsn1-bx1.example.com"},
{Name: "prod/fsn1-bx2.example.com"},
{Name: "stg/fsn1-bx2.example.com"},
{Name: "stg/hel1-tb1.example.com"},
{Name: "prod/HEL1-TB2"},
}
for _, tc := range []struct {
input string
want []string
}{
// Unique names are bare; names in both instances stay qualified.
{"fsn1", []string{"fsn1-bx1.example.com", "prod/fsn1-bx2.example.com", "stg/fsn1-bx2.example.com"}},
{"hel1", []string{"HEL1-TB2", "hel1-tb1.example.com"}},
{"prod/", []string{"prod/HEL1-TB2", "prod/fsn1-bx1.example.com", "prod/fsn1-bx2.example.com"}},
{"stg/fsn", []string{"stg/fsn1-bx2.example.com"}},
// An instance name typed without the slash completes qualified targets.
{"st", []string{"stg/fsn1-bx2.example.com", "stg/hel1-tb1.example.com"}},
} {
if got := hostCompletions(entries, tc.input, config.ShortcutsConfig{}); !reflect.DeepEqual(got, tc.want) {
t.Errorf("%q: got %v, want %v", tc.input, got, tc.want)
}
}
// Single-instance caches are unchanged.
if got := hostCompletions([]cache.Entry{{Name: "web01"}, {Name: "db01"}}, "w", config.ShortcutsConfig{}); !reflect.DeepEqual(got, []string{"web01"}) {
t.Errorf("single instance: %v", got)
}
}
var fsnRewrite = config.ShortcutsConfig{
Domains: []string{".hoster.de"},
Rewrites: []config.ShortcutRewrite{{Pattern: `^([a-z]+)[0-9]+-`, Replace: "$1"}},
}
func TestHostCompletionsOfferShortcuts(t *testing.T) {
entries := []cache.Entry{
{Name: "prod/fsn1-bx1.hoster.de"},
{Name: "prod/fsn1-db1.hoster.de"},
{Name: "stg/fsn1-db1.hoster.de"},
{Name: "prod/web01.hoster.de"},
}
for _, tc := range []struct {
input string
want []string
}{
{"fsnb", []string{"fsnbx1"}},
// Shortcut shared by two instances stays qualified.
{"fsnd", []string{"prod/fsndb1", "stg/fsndb1"}},
{"prod/fsn", []string{"prod/fsn1-bx1.hoster.de", "prod/fsn1-db1.hoster.de"}},
{"stg/fsnd", []string{"stg/fsndb1"}},
// A matching full name is not repeated as shortcut.
{"web", []string{"web01.hoster.de"}},
} {
if got := hostCompletions(entries, tc.input, fsnRewrite); !reflect.DeepEqual(got, tc.want) {
t.Errorf("%q: got %v, want %v", tc.input, got, tc.want)
}
}
// Two hosts of the same instance with one shortcut cannot be selected by it.
same := []cache.Entry{{Name: "fsn1-bx1.hoster.de"}, {Name: "fsn2-bx1.hoster.de"}}
if got := hostCompletions(same, "fsnb", fsnRewrite); len(got) != 0 {
t.Errorf("ambiguous shortcut offered: %v", got)
}
}
func TestShortcutTestOutput(t *testing.T) {
var out bytes.Buffer
printShortcutTest(&out, "fsn1-bx1.hoster.de", []cache.Entry{{Name: "fsn1-bx1.hoster.de"}, {Name: "fsn2-bx1.hoster.de"}, {Name: "web01.hoster.de"}}, fsnRewrite)
want := "fsn1-bx1.hoster.de → fsnbx1\nambiguous, matches 2 hosts:\n fsn1-bx1.hoster.de\n fsn2-bx1.hoster.de\n"
if out.String() != want {
t.Fatalf("got:\n%s", out.String())
}
}
// Rewrite rules alone must enable the shortcut lookup; NetBox is unreachable,
// so only the cached host can answer.
func TestWrapperConnectsByRewriteShortcut(t *testing.T) {
dir := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", dir)
t.Setenv("XDG_CACHE_HOME", t.TempDir())
t.Setenv("NETSSH_NETBOX_URL", "")
t.Setenv("NETSSH_NETBOX_TOKEN", "")
t.Setenv("NETSSH_CACHE_PATH", filepath.Join(t.TempDir(), "hosts.json"))
t.Setenv("NETSSH_SHELL_ALIAS", "")
data := "netbox:\n url: http://127.0.0.1:1\n token: t\nshortcuts:\n rewrites:\n - pattern: '^([a-z]+)[0-9]+-'\n replace: '$1'\n"
if err := os.WriteFile(filepath.Join(dir, "netssh.yaml"), []byte(data), 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: "fsn1-bx1.hoster.de", IP: "10.0.0.9", Kind: "device"})
if err := c.Save(); err != nil {
t.Fatal(err)
}
bin := t.TempDir()
if err := os.WriteFile(filepath.Join(bin, "ssh"), []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"), 0o755); err != nil {
t.Fatal(err)
}
cmd := exec.Command(os.Args[0], "-test.run=^TestMultiInstanceWrapperHelper$")
cmd.Env = append(os.Environ(), "NETSSH_TEST_MULTI_TARGET=fsnbx1.hoster.de", "PATH="+bin+":"+os.Getenv("PATH"))
out, err := cmd.CombinedOutput()
if err != nil || !strings.Contains(string(out), "10.0.0.9\n") {
t.Fatalf("shortcut not resolved from cache: %s, %v", out, err)
}
}
+1073
View File
File diff suppressed because it is too large. Load diff
+414
View File
@@ -0,0 +1,414 @@
package main
import (
"context"
"errors"
"fmt"
"os"
"os/exec"
"path/filepath"
"regexp"
"sort"
"strings"
"time"
"github.com/spf13/cobra"
"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/multiplex"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
// maxHostsWithoutConfirm guards against opening hundreds of panes by accident.
const maxHostsWithoutConfirm = 24
// multiFlags are the options shared by netssh multi and the TUI.
type multiFlags struct {
kind, user, jump, multiplexer string
noJump, sync, dryRun, yes bool
}
func multiCmd() *cobra.Command {
var f multiFlags
var useTmux, useZellij bool
cmd := &cobra.Command{
Use: "multi [flags] HOST|tag:TAG|cluster:NAME|@GROUP...",
Short: "Open several hosts side by side in tmux or zellij",
Long: `Open one pane per host in a tmux window or zellij tab. Hosts are given as
names (shortcuts, instance/host, static hosts) or selectors:
tag:TAG all hosts with this NetBox tag, and static hosts with this tag
cluster:NAME devices of a NetBox virtualization cluster (--kind vm|all for VMs)
@GROUP a group from the config (groups:)
Broadcast typing to all panes of a window with --sync, or toggle it later with
netssh sync. Inside tmux or zellij the panes open in the current session.`,
Example: ` netssh multi web01 web02 db01
netssh multi cluster:pve-fsn1
netssh multi --kind vm cluster:pve-fsn1
netssh multi --sync tag:k8s-worker
netssh multi @k8s`,
Args: cobra.MinimumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
if useTmux && useZellij {
return errors.New("--tmux and --zellij are mutually exclusive")
}
if useTmux {
f.multiplexer = multiplex.Tmux
} else if useZellij {
f.multiplexer = multiplex.Zellij
}
return runMulti(loadConfigOrSetup(), args, f)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
cfg, err := config.Load()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
return multiCompletions(cfg, toComplete)
},
}
cmd.Flags().StringVar(&f.kind, "kind", "", "Host kind for tag: and cluster: — device, vm, or all (default: all for tags, device for clusters)")
cmd.Flags().BoolVar(&f.sync, "sync", false, "Start with typing broadcast to all panes")
cmd.Flags().BoolVar(&useTmux, "tmux", false, "Use tmux")
cmd.Flags().BoolVar(&useZellij, "zellij", false, "Use zellij")
cmd.Flags().StringVarP(&f.user, "user", "l", "", "Login user for every host")
cmd.Flags().StringVar(&f.jump, "jump", "", "Jump host for every host")
cmd.Flags().BoolVar(&f.noJump, "no-jump", false, "Disable jump hosts")
cmd.Flags().BoolVar(&f.dryRun, "dry-run", false, "Print the hosts and multiplexer commands")
cmd.Flags().BoolVarP(&f.yes, "yes", "y", false, fmt.Sprintf("Open more than %d hosts without asking", maxHostsWithoutConfirm))
_ = cmd.RegisterFlagCompletionFunc("kind", cobra.FixedCompletions([]cobra.Completion{"device", "vm", "all"}, cobra.ShellCompDirectiveNoFileComp))
return cmd
}
func syncCmd() *cobra.Command {
var pane bool
cmd := &cobra.Command{
Use: "sync [--pane]",
Short: "Toggle typing into all panes of the current tmux window or zellij tab",
Long: `Toggle broadcast in the current tmux window or zellij tab. With --pane,
exclude the current tmux pane from broadcast, or include it again.
In windows opened by netssh multi, tmux also has keys for this:
prefix S (all panes) and prefix e (this pane); see multi.sync_key and
multi.solo_key. In zellij, use Ctrl+t then s.`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
state, err := multiplex.ToggleSync(multiplex.System{}, pane)
if err != nil {
return err
}
fmt.Fprintln(os.Stderr, "netssh: "+state)
return nil
},
}
cmd.Flags().BoolVar(&pane, "pane", false, "Exclude the current tmux pane from broadcast, or include it again")
return cmd
}
// runMulti expands selectors and opens one pane per host.
func runMulti(cfg *config.Config, selectors []string, f multiFlags) error {
if f.jump != "" && f.noJump {
return errors.New("--jump and --no-jump are mutually exclusive")
}
switch f.kind {
case "", "device", "vm", "all":
default:
return fmt.Errorf("--kind must be device, vm, or all")
}
c := newCache(cfg)
_ = c.Load()
targets, warnings, err := expandSelectors(cfg, c, selectors, f.kind)
for _, warning := range warnings {
fmt.Fprintln(os.Stderr, "netssh: warning: "+warning)
}
if err != nil {
return err
}
if len(targets) > maxHostsWithoutConfirm && !f.yes && !f.dryRun {
return fmt.Errorf("%d hosts selected; pass --yes to open them all", len(targets))
}
var runner multiplex.Runner = multiplex.System{}
if f.dryRun {
fmt.Printf("# %d hosts: %s\n", len(targets), strings.Join(targets, " "))
runner = &multiplex.DryRun{W: os.Stdout}
}
requested := f.multiplexer
if requested == "" {
requested = cfg.Multi.Multiplexer
}
kind, err := multiplex.Detect(requested, runner)
if err != nil {
return err
}
if !f.dryRun {
// Checked once here; the panes skip it (NETSSH_NO_REFRESH).
maybeBackgroundRefresh(cfg, c)
}
panes := make([]multiplex.Pane, 0, len(targets))
for _, target := range targets {
panes = append(panes, multiplex.Pane{Title: target, Argv: paneArgv(target, f)})
}
layoutDir := filepath.Dir(cfg.Cache.Path)
if err := os.MkdirAll(layoutDir, 0o700); err != nil {
return err
}
syncKey, soloKey := cfg.Multi.Keys()
return multiplex.Open(kind, panes, multiplex.Options{
SyncKey: syncKey,
SoloKey: soloKey,
Label: multiLabel(selectors),
Sync: f.sync,
PerWindow: cfg.Multi.PanesPerWindowOrDefault(),
LayoutDir: layoutDir,
Hint: func(s string) { fmt.Fprintln(os.Stderr, "netssh: "+s) },
}, runner)
}
// paneArgv runs netssh for one host. Panes of an existing tmux or zellij
// session inherit that server's environment, so the paths that select the
// config and cache are passed explicitly; NETSSH_* values are not, because
// arguments are visible to other users (tokens).
func paneArgv(target string, f multiFlags) []string {
self, err := os.Executable()
if err != nil {
self = "netssh"
}
env, err := exec.LookPath("env")
if err != nil {
env = "/usr/bin/env"
}
argv := []string{env, "NETSSH_NO_REFRESH=1"}
for _, key := range []string{"HOME", "XDG_CONFIG_HOME", "XDG_CACHE_HOME"} {
if value, ok := os.LookupEnv(key); ok {
argv = append(argv, key+"="+value)
}
}
argv = append(argv, self)
switch {
case f.jump != "":
argv = append(argv, "--jump", f.jump)
case f.noJump:
argv = append(argv, "--no-jump")
}
if f.user != "" {
argv = append(argv, "-l", f.user)
}
return append(argv, target)
}
var unsafeLabel = regexp.MustCompile(`[^A-Za-z0-9_-]+`)
// multiLabel names the window, session, or tab after a single selector.
func multiLabel(selectors []string) string {
if len(selectors) != 1 {
return "multi"
}
s := selectors[0]
for _, prefix := range []string{"@", "tag:", "cluster:"} {
s = strings.TrimPrefix(s, prefix)
}
if s = strings.Trim(unsafeLabel.ReplaceAllString(s, "-"), "-"); s == "" {
return "multi"
}
return s
}
// expander resolves selectors into an ordered list of unique host targets.
type expander struct {
cfg *config.Config
cache *cache.Cache
kind string
client *netbox.Client
seen map[string]bool
visiting map[string]bool
targets []string
warnings []string
}
func expandSelectors(cfg *config.Config, c *cache.Cache, selectors []string, kind string) ([]string, []string, error) {
e := &expander{cfg: cfg, cache: c, kind: kind, seen: map[string]bool{}, visiting: map[string]bool{}}
for _, selector := range selectors {
if err := e.expand(selector); err != nil {
return nil, e.warnings, err
}
}
if len(e.targets) == 0 {
return nil, e.warnings, errors.New("no hosts selected")
}
return e.targets, e.warnings, nil
}
func (e *expander) add(target string) {
key := strings.ToLower(target)
if !e.seen[key] {
e.seen[key] = true
e.targets = append(e.targets, target)
}
}
func (e *expander) expand(selector string) error {
switch {
case strings.HasPrefix(selector, "@"):
return e.group(strings.ToLower(strings.TrimPrefix(selector, "@")))
case strings.HasPrefix(selector, "tag:"):
return e.query(selector, netbox.SearchOptions{Tag: strings.TrimPrefix(selector, "tag:")}, "all")
case strings.HasPrefix(selector, "cluster:"):
return e.query(selector, netbox.SearchOptions{Cluster: strings.TrimPrefix(selector, "cluster:")}, "device")
case selector == "":
return nil
}
e.add(selector)
return nil
}
func (e *expander) group(name string) error {
members, ok := e.cfg.Groups[name]
if !ok {
names := make([]string, 0, len(e.cfg.Groups))
for group := range e.cfg.Groups {
names = append(names, "@"+group)
}
sort.Strings(names)
if len(names) == 0 {
return fmt.Errorf("unknown group @%s; no groups are configured (groups:)", name)
}
return fmt.Errorf("unknown group @%s; available: %s", name, strings.Join(names, ", "))
}
if e.visiting[name] {
return fmt.Errorf("group @%s contains itself", name)
}
e.visiting[name] = true
defer delete(e.visiting, name)
for _, member := range members {
if err := e.expand(member); err != nil {
return err
}
}
return nil
}
// query expands tag: and cluster: through NetBox, plus static hosts for tags;
// if NetBox fails, the cache answers with a warning.
func (e *expander) query(selector string, opts netbox.SearchOptions, defaultKind string) error {
kind := e.kind
if kind == "" {
kind = defaultKind
}
if kind != "all" {
opts.Kind = kind
}
before := len(e.targets)
if opts.Tag != "" && (kind == "all" || kind == config.StaticKind) {
for _, host := range e.cfg.Hosts {
if hasTag(host.Tags, opts.Tag) {
e.add(host.Name)
}
}
}
if e.cfg.HasNetBox() {
if e.client == nil {
e.client = newNetBoxClient(e.cfg)
}
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
entries, err := e.client.SearchAll(ctx, "", opts)
cancel()
if err != nil {
e.warnings = append(e.warnings, fmt.Sprintf("%s: NetBox unavailable, using the cache: %v", selector, err))
entries = e.fromCache(opts)
} else {
sort.Slice(entries, func(i, j int) bool { return entries[i].Target() < entries[j].Target() })
}
for _, entry := range entries {
e.add(entry.Target())
}
}
if len(e.targets) == before {
hint := ""
if opts.Cluster != "" && e.kind == "" {
hint = " (only devices by default; try --kind vm or --kind all)"
}
return fmt.Errorf("%s matches no hosts%s", selector, hint)
}
return nil
}
func (e *expander) fromCache(opts netbox.SearchOptions) []netbox.HostEntry {
var out []netbox.HostEntry
for _, entry := range e.cache.All() {
if entry.Static || opts.Kind != "" && entry.Kind != opts.Kind {
continue
}
if opts.Tag != "" && !hasTag(entry.Tags, opts.Tag) || opts.Cluster != "" && !strings.EqualFold(entry.Cluster, opts.Cluster) {
continue
}
source, name := netbox.SplitTarget(entry.Name)
out = append(out, netbox.HostEntry{Source: source, Name: name, Kind: entry.Kind})
}
sort.Slice(out, func(i, j int) bool { return out[i].Target() < out[j].Target() })
return out
}
// hasTag compares a tag by name or slug, like ssh.rules.
func hasTag(tags []string, want string) bool {
for _, tag := range tags {
if strings.EqualFold(tag, want) || strings.EqualFold(strings.Join(strings.Fields(strings.ToLower(tag)), "-"), want) {
return true
}
}
return false
}
// multiCompletions offers hosts, @groups, and tag:/cluster: values from the cache.
func multiCompletions(cfg *config.Config, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
c := newCache(cfg)
_ = c.Load()
lower := strings.ToLower(toComplete)
var out []string
switch {
case strings.HasPrefix(lower, "tag:"), strings.HasPrefix(lower, "cluster:"):
prefix, value, _ := strings.Cut(lower, ":")
values := map[string]bool{}
for _, entry := range c.All() {
if prefix == "tag" {
for _, tag := range entry.Tags {
values[strings.ToLower(tag)] = true
}
} else if entry.Cluster != "" {
values[entry.Cluster] = true
}
}
for v := range values {
if strings.HasPrefix(strings.ToLower(v), value) {
out = append(out, prefix+":"+v)
}
}
case strings.HasPrefix(lower, "@"):
for group := range cfg.Groups {
if strings.HasPrefix("@"+group, lower) {
out = append(out, "@"+group)
}
}
default:
out = completeHosts(toComplete)
var prefixes []string
for _, p := range []string{"tag:", "cluster:"} {
if toComplete != "" && strings.HasPrefix(p, lower) {
prefixes = append(prefixes, p)
}
}
if len(out) == 0 && len(prefixes) > 0 {
return prefixes, cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp
}
for group := range cfg.Groups {
if toComplete == "" {
out = append(out, "@"+group)
}
}
}
sort.Strings(out)
return out, cobra.ShellCompDirectiveNoFileComp
}
+92
View File
@@ -0,0 +1,92 @@
package main
import (
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func TestExpandSelectors(t *testing.T) {
cfg := &config.Config{
Hosts: []config.StaticHost{{Name: "box", Address: "10.0.0.1", Tags: []string{"Web Servers"}}},
Groups: map[string][]string{
"all": {"@web", "db1", "box"},
"web": {"web1", "tag:web-servers", "web1"},
"loop": {"@loop"},
},
}
c := cache.New(t.TempDir()+"/hosts.json", 60).WithStatic(cfg.Hosts)
got, _, err := expandSelectors(cfg, c, []string{"@all", "WEB1"}, "")
if err != nil || !reflect.DeepEqual(got, []string{"web1", "box", "db1"}) {
t.Fatalf("got %v %v", got, err)
}
if _, _, err := expandSelectors(cfg, c, []string{"@loop"}, ""); err == nil || !strings.Contains(err.Error(), "contains itself") {
t.Fatalf("cycle: %v", err)
}
if _, _, err := expandSelectors(cfg, c, []string{"@nope"}, ""); err == nil || !strings.Contains(err.Error(), "available: @all, @loop, @web") {
t.Fatalf("unknown group: %v", err)
}
if _, _, err := expandSelectors(cfg, c, []string{"tag:web-servers"}, "device"); err == nil {
t.Fatal("--kind device must exclude static hosts")
}
}
// Without a reachable NetBox, tag: and cluster: fall back to the cache.
func TestExpandSelectorsCacheFallback(t *testing.T) {
cfg := &config.Config{NetBox: config.NetBoxConfig{URL: "http://127.0.0.1:1", Token: "t", TokenVersion: 1}}
c := cache.New(t.TempDir()+"/hosts.json", 60)
c.Upsert(cache.Entry{Name: "node2", Kind: "device", Cluster: "pve"})
c.Upsert(cache.Entry{Name: "node1", Kind: "device", Cluster: "pve", Tags: []string{"pve"}})
c.Upsert(cache.Entry{Name: "vm1", Kind: "vm", Cluster: "pve"})
got, warnings, err := expandSelectors(cfg, c, []string{"cluster:PVE"}, "")
if err != nil || !reflect.DeepEqual(got, []string{"node1", "node2"}) || len(warnings) != 1 {
t.Fatalf("devices: %v %v %v", got, warnings, err)
}
if got, _, _ := expandSelectors(cfg, c, []string{"cluster:pve"}, "all"); len(got) != 3 {
t.Fatalf("all: %v", got)
}
if _, _, err := expandSelectors(cfg, c, []string{"cluster:other"}, ""); err == nil || !strings.Contains(err.Error(), "--kind vm") {
t.Fatalf("empty cluster: %v", err)
}
}
func TestMultiLabelAndPaneArgv(t *testing.T) {
for selectors, want := range map[string]string{"@k8s": "k8s", "cluster:pve-fsn1": "pve-fsn1", "tag:a.b": "a-b", "a b": "multi"} {
if got := multiLabel(strings.Fields(selectors)); got != want {
t.Errorf("%q: got %q", selectors, got)
}
}
t.Setenv("XDG_CONFIG_HOME", "/cfg")
t.Setenv("NETSSH_NETBOX_TOKEN", "secret")
argv := strings.Join(paneArgv("prod/web1", multiFlags{user: "ops", jump: "jh"}), " ")
for _, want := range []string{"NETSSH_NO_REFRESH=1", "XDG_CONFIG_HOME=/cfg", "--jump jh -l ops prod/web1"} {
if !strings.Contains(argv, want) {
t.Errorf("argv lacks %q: %s", want, argv)
}
}
if strings.Contains(argv, "secret") {
t.Fatalf("token leaked into the pane arguments: %s", argv)
}
}
func TestMultiDryRun(t *testing.T) {
prepareConfig(t, "hosts:\n - {name: a, address: 10.0.0.1, tags: [web]}\n - {name: b, address: 10.0.0.2, tags: [web]}\ngroups:\n web: [\"tag:web\"]\n")
out, err := runNetssh(t, "multi", "--dry-run", "--tmux", "--sync", "@web")
if err != nil {
t.Fatalf("%s %v", out, err)
}
for _, want := range []string{"# 2 hosts: a b", "tmux new-session -d -x 240 -y 70 -s netssh-web", "synchronize-panes on", "tmux attach-session -t netssh-web"} {
if !strings.Contains(out, want) {
t.Errorf("missing %q:\n%s", want, out)
}
}
if out, err := runNetssh(t, "multi", "--dry-run", "--zellij", "a", "b"); err != nil || !strings.Contains(out, `pane name="b"`) {
t.Errorf("zellij: %s %v", out, err)
}
if out, err := runNetssh(t, "sync"); err == nil || !strings.Contains(out, "inside tmux or zellij") {
t.Errorf("sync outside: %s %v", out, err)
}
}
+103
View File
@@ -0,0 +1,103 @@
package main
import (
"context"
"fmt"
"io"
"strings"
"time"
"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/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/notes"
"github.com/spf13/cobra"
)
func notesCmd() *cobra.Command {
var remote bool
var kind string
cmd := &cobra.Command{Use: "notes", Short: "Read and write server notes (local by default)"}
cmd.PersistentFlags().BoolVar(&remote, "netbox", false, "Use the NetBox comments field instead of local notes")
cmd.PersistentFlags().StringVar(&kind, "kind", "", "Host kind: device or vm (required for uncached local hosts)")
for _, action := range []string{"show", "set", "append"} {
sub := &cobra.Command{Use: action + " <host> [text]", Short: action + " a server note", Args: cobra.RangeArgs(1, 2)}
if action == "show" {
sub.Args = cobra.ExactArgs(1)
}
sub.RunE = func(cmd *cobra.Command, args []string) error {
if kind != "" && kind != "vm" && kind != "device" {
return fmt.Errorf("invalid kind %q", kind)
}
cfg, err := config.Load()
if err != nil {
return err
}
var client *netbox.Client
if cfg.HasNetBox() {
client = newNetBoxClient(cfg)
}
host := netbox.HostEntry{Name: args[0], Kind: kind}
c := newCache(cfg)
if err := c.Load(); err != nil {
return err
}
var cached []cache.Entry
if !remote {
cached = c.All()
}
query := host.Name
source, rawName := netbox.SplitTarget(query)
var matches []cache.Entry
for _, entry := range cached {
_, entryName := netbox.SplitTarget(entry.Name)
if (kind == "" || kind == entry.Kind) && (strings.EqualFold(entry.Name, query) || (source == "" && strings.EqualFold(entryName, rawName))) {
matches = append(matches, entry)
}
}
if len(matches) > 1 {
return fmt.Errorf("ambiguous hostname %q; use instance/hostname", query)
}
if len(matches) == 1 {
host.Name = matches[0].Name
host.Kind = matches[0].Kind
}
if !remote && host.Kind == "" {
return fmt.Errorf("host is not cached; specify --kind device or --kind vm")
}
ctx, cancel := context.WithTimeout(cmd.Context(), 20*time.Second)
defer cancel()
service := notes.New(cfg.NetBox.URL, client)
note, err := service.Read(ctx, host, remote)
if err != nil {
return err
}
if action == "show" {
_, err := fmt.Fprint(cmd.OutOrStdout(), note.Text)
return err
}
var text string
if len(args) == 2 {
text = args[1]
} else {
data, err := io.ReadAll(io.LimitReader(cmd.InOrStdin(), 1024*1024+1))
if err != nil {
return err
}
if len(data) > 1024*1024 {
return fmt.Errorf("note exceeds 1 MiB")
}
text = string(data)
}
if action == "append" && note.Text != "" {
note.Text = strings.TrimRight(note.Text, "\n") + "\n" + text
} else {
note.Text = text
}
return service.Write(ctx, note, remote)
}
cmd.AddCommand(sub)
}
return cmd
}
+76
View File
@@ -0,0 +1,76 @@
package main
import (
"bytes"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
"os"
"path/filepath"
"strings"
"testing"
)
func TestLocalNotesCLI(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("NETSSH_CACHE_PATH", filepath.Join(t.TempDir(), "hosts.json"))
run := func(args []string, input string) (string, error) {
root := rootCmd()
var out bytes.Buffer
root.SetOut(&out)
root.SetErr(&out)
root.SetIn(strings.NewReader(input))
root.SetArgs(args)
err := root.Execute()
return out.String(), err
}
if _, err := run([]string{"notes", "set", "web01", "--kind", "vm"}, "First\nSecond"); err != nil {
t.Fatal(err)
}
if _, err := run([]string{"notes", "append", "web01", "Third", "--kind", "vm"}, ""); err != nil {
t.Fatal(err)
}
out, err := run([]string{"notes", "show", "web01", "--kind", "vm"}, "")
if err != nil || out != "First\nSecond\nThird" {
t.Fatalf("show: %q, %v", out, err)
}
if _, err := run([]string{"notes", "set", "web01", "", "--kind", "vm"}, ""); err != nil {
t.Fatal(err)
}
out, err = run([]string{"notes", "show", "web01", "--kind", "vm"}, "")
if err != nil || out != "" {
t.Fatalf("clear: %q, %v", out, err)
}
}
func TestShellInitUpdatesAndRemovesCommandAliasWithoutHosts(t *testing.T) {
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("XDG_CACHE_HOME", t.TempDir())
t.Setenv("NETSSH_CACHE_PATH", filepath.Join(t.TempDir(), "hosts.json"))
t.Setenv("NETSSH_NETBOX_URL", "")
t.Setenv("NETSSH_SHELL_ALIAS", "j")
run := func() {
t.Helper()
root := rootCmd()
root.SetArgs([]string{"shell-init"})
if err := root.Execute(); err != nil {
t.Fatal(err)
}
}
run()
data, err := os.ReadFile(hook.AliasesPath())
if err != nil || !strings.Contains(string(data), "alias j='netssh'") {
t.Fatalf("alias missing: %s, %v", data, err)
}
t.Setenv("NETSSH_SHELL_ALIAS", "k")
run()
data, _ = os.ReadFile(hook.AliasesPath())
if strings.Contains(string(data), "alias j=") || !strings.Contains(string(data), "alias k='netssh'") {
t.Fatalf("alias change: %s", data)
}
t.Setenv("NETSSH_SHELL_ALIAS", "")
run()
data, _ = os.ReadFile(hook.AliasesPath())
if strings.Contains(string(data), "alias k=") {
t.Fatalf("stale alias: %s", data)
}
}
+54
View File
@@ -0,0 +1,54 @@
package main
import (
"fmt"
"io"
"os"
"os/exec"
"strings"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
// preConnectRunner runs the hook; tests replace it to avoid spawning a shell.
var preConnectRunner = runPreConnectCommand
// preConnectEnv describes the host to the hook through environment variables.
func preConnectEnv(host resolvedHost, clientName string) []string {
instance, name := netbox.SplitTarget(host.Name)
return []string{
"NETSSH_HOST=" + name,
"NETSSH_TARGET=" + host.Name,
"NETSSH_INSTANCE=" + instance,
"NETSSH_IP=" + host.IP,
"NETSSH_KIND=" + host.Kind,
"NETSSH_TAGS=" + strings.Join(host.Tags, ","),
"NETSSH_CLIENT=" + clientName,
}
}
// runPreConnect runs the configured pre_connect hook for host. Its output goes
// to stderr so it never mixes with the output of a remote command or scp.
// A failing hook returns an error and the connection must not be opened.
func runPreConnect(command string, host resolvedHost, clientName string, dryRun bool) error {
if command == "" {
return nil
}
if dryRun {
fmt.Fprintf(os.Stderr, "# pre_connect (skipped in --dry-run): %s\n", command)
return nil
}
if err := preConnectRunner(command, preConnectEnv(host, clientName), os.Stdin, os.Stderr); err != nil {
return fmt.Errorf("pre_connect hook for %s failed: %w", host.Name, err)
}
return nil
}
func runPreConnectCommand(command string, env []string, stdin io.Reader, out io.Writer) error {
cmd := exec.Command("sh", "-c", command)
cmd.Env = append(os.Environ(), env...)
cmd.Stdin = stdin
cmd.Stdout = out
cmd.Stderr = out
return cmd.Run()
}
+112
View File
@@ -0,0 +1,112 @@
package main
import (
"bytes"
"errors"
"io"
"os"
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
func TestRunPreConnectPassesHostAndStopsOnFailure(t *testing.T) {
host := resolvedHost{Name: "prod/web01", Kind: "vm", IP: "10.0.0.5", Tags: []string{"dmz", "web"}}
var gotCommand string
var gotEnv []string
fail := false
preConnectRunner = func(command string, env []string, _ io.Reader, _ io.Writer) error {
gotCommand, gotEnv = command, env
if fail {
return errors.New("exit status 1")
}
return nil
}
t.Cleanup(func() { preConnectRunner = runPreConnectCommand })
if err := runPreConnect("vpn-check", host, "sftp", false); err != nil {
t.Fatal(err)
}
want := []string{"NETSSH_HOST=web01", "NETSSH_TARGET=prod/web01", "NETSSH_INSTANCE=prod", "NETSSH_IP=10.0.0.5", "NETSSH_KIND=vm", "NETSSH_TAGS=dmz,web", "NETSSH_CLIENT=sftp"}
if gotCommand != "vpn-check" || !reflect.DeepEqual(gotEnv, want) {
t.Fatalf("got %q %v", gotCommand, gotEnv)
}
fail = true
if err := runPreConnect("vpn-check", host, "ssh", false); err == nil || !strings.Contains(err.Error(), "prod/web01") {
t.Fatalf("failure not reported: %v", err)
}
gotCommand = ""
if err := runPreConnect("vpn-check", host, "ssh", true); err != nil || gotCommand != "" {
t.Fatalf("dry-run ran the hook: %v %q", err, gotCommand)
}
if err := runPreConnect("", host, "ssh", false); err != nil || gotCommand != "" {
t.Fatalf("empty hook ran: %v %q", err, gotCommand)
}
}
func TestRunPreConnectCommandUsesShell(t *testing.T) {
var out bytes.Buffer
err := runPreConnectCommand(`echo "$NETSSH_HOST via $NETSSH_CLIENT"`, []string{"NETSSH_HOST=web01", "NETSSH_CLIENT=ssh"}, strings.NewReader(""), &out)
if err != nil || out.String() != "web01 via ssh\n" {
t.Fatalf("got %q, %v", out.String(), err)
}
if err := runPreConnectCommand("exit 3", nil, strings.NewReader(""), io.Discard); err == nil {
t.Fatal("non-zero exit not reported")
}
}
// --dry-run only prints the ssh command: it must not run the hook, which may
// have side effects (bringing up a VPN, logging).
func TestConnectHostDryRunSkipsPreConnect(t *testing.T) {
ran := 0
preConnectRunner = func(string, []string, io.Reader, io.Writer) error { ran++; return nil }
t.Cleanup(func() { preConnectRunner = runPreConnectCommand })
cfg := &config.Config{SSH: config.SSHConfig{SSHOptions: config.SSHOptions{PreConnect: "hook"}}}
stdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
connectHost(cfg, internalssh.SSH, internalssh.WrapperFlags{DryRun: true}, resolvedHost{Name: "web01", IP: "10.0.0.1"}, []int{0}, []string{"web01"})
w.Close()
os.Stdout = stdout
printed, _ := io.ReadAll(r)
if ran != 0 || !strings.Contains(string(printed), "10.0.0.1") {
t.Fatalf("dry-run: ran=%d printed=%q", ran, printed)
}
}
func TestShortcutAliasesOnlyWhenShortened(t *testing.T) {
cfg := config.Config{Shell: config.ShellConfig{Alias: "j"}, Shortcuts: fsnRewrite}
entries := []cache.Entry{{Name: "fsn1-bx1.hoster.de"}, {Name: "web01.other.de"}, {Name: "db01.hoster.de"}}
got := shortcutAliases(entries, cfg)
want := map[string]string{"fsn1-bx1.hoster.de": "fsnbx1", "db01.hoster.de": "db01"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
if got := shortcutAliases(entries, config.Config{}); len(got) != 0 {
t.Fatalf("aliases without shortcuts: %v", got)
}
}
func TestHostCompletionsShowShortcutsForMatchingNames(t *testing.T) {
entries := []cache.Entry{{Name: "fsn1-bx1.hoster.de"}, {Name: "fsn1-db1.hoster.de"}}
if got := hostCompletions(entries, "fsn", fsnRewrite); !reflect.DeepEqual(got, []string{"fsn1-bx1.hoster.de", "fsn1-db1.hoster.de"}) {
t.Fatalf("without show: %v", got)
}
show := fsnRewrite
show.Show = true
want := []string{"fsn1-bx1.hoster.de", "fsn1-db1.hoster.de", "fsnbx1", "fsndb1"}
if got := hostCompletions(entries, "fsn", show); !reflect.DeepEqual(got, want) {
t.Fatalf("with show: got %v, want %v", got, want)
}
// A shortcut equal to an offered name is not repeated.
plain := []cache.Entry{{Name: "web01"}}
if got := hostCompletions(plain, "web", show); !reflect.DeepEqual(got, []string{"web01"}) {
t.Fatalf("duplicate: %v", got)
}
}
+83
View File
@@ -0,0 +1,83 @@
package main
import (
"fmt"
"os"
"os/exec"
"sort"
"strings"
"syscall"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"github.com/spf13/cobra"
)
// expandHostCommand substitutes each argument once, without shell evaluation.
func expandHostCommand(command config.HostCommand, host resolvedHost, extra []string) []string {
_, name := netbox.SplitTarget(host.Name)
replace := strings.NewReplacer("{host}", name, "{address}", host.IP, "{target}", host.Name)
argv := make([]string, 0, len(command.Args)+len(extra))
for _, arg := range command.Args {
argv = append(argv, replace.Replace(arg))
}
return append(argv, extra...)
}
func runCmd() *cobra.Command {
var dryRun bool
cmd := &cobra.Command{
Use: "run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]",
Short: "Run a configured local command for a NetBox or static host",
Args: cobra.MinimumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
command, ok := cfg.Commands[args[0]]
if !ok {
return fmt.Errorf("unknown configured command %q", args[0])
}
host := resolveTarget(cfg, args[1])
argv := expandHostCommand(command, host, args[2:])
if dryRun {
for i, arg := range argv {
if i > 0 {
fmt.Fprint(cmd.OutOrStdout(), " ")
}
fmt.Fprintf(cmd.OutOrStdout(), "%q", arg)
}
fmt.Fprintln(cmd.OutOrStdout())
return nil
}
path, err := exec.LookPath(argv[0])
if err != nil {
return fmt.Errorf("%s not found in PATH: %w", argv[0], err)
}
return syscall.Exec(path, argv, os.Environ())
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, prefix string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
cfg, err := config.Load()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
var names []string
for name := range cfg.Commands {
if strings.HasPrefix(name, prefix) {
names = append(names, name)
}
}
sort.Strings(names)
return names, cobra.ShellCompDirectiveNoFileComp
}
if len(args) == 1 {
return completeHosts(prefix), cobra.ShellCompDirectiveNoFileComp
}
return nil, cobra.ShellCompDirectiveNoFileComp
},
}
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the command without running it")
return cmd
}
+130
View File
@@ -0,0 +1,130 @@
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func TestExpandHostCommand(t *testing.T) {
command := config.HostCommand{Args: []string{"mtr", "--target={address}", "{host}", "{target}", "$(literal)"}}
host := resolvedHost{Name: "office/xzi-groß1", IP: "2001:db8::1"}
got := expandHostCommand(command, host, []string{"--report", "two words"})
want := []string{"mtr", "--target=2001:db8::1", "xzi-groß1", "office/xzi-groß1", "$(literal)", "--report", "two words"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("%q, want %q", got, want)
}
}
func TestRunConfiguredHostCommand(t *testing.T) {
prepareTransferTest(t)
f, err := os.OpenFile(config.Path(), os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
_, err = f.WriteString(`
commands:
trace:
alias_prefix: m
args: [mtr, "{address}", "{host}", "{target}"]
literal:
args: [printf, "%s|%s|%s", "{address}", "{host}", "$(touch should-not-exist)"]
`)
if closeErr := f.Close(); err != nil || closeErr != nil {
t.Fatalf("write config: %v %v", err, closeErr)
}
for _, tc := range []struct {
args []string
want string
}{
{[]string{"run", "--dry-run", "trace", "fsnbx1", "--", "--report"}, `"mtr" "10.0.0.9" "fsn1-bx1.hoster.de" "fsn1-bx1.hoster.de" "--report"`},
{[]string{"run", "--dry-run", "trace", "--", "fsnbx1", "--help"}, `"mtr" "10.0.0.9" "fsn1-bx1.hoster.de" "fsn1-bx1.hoster.de" "--help"`},
{[]string{"run", "literal", "fsnbx1"}, "10.0.0.9|fsn1-bx1.hoster.de|$(touch should-not-exist)"},
} {
out, err := runNetssh(t, tc.args...)
if err != nil || out != tc.want {
t.Fatalf("%v: %q (%v), want %q", tc.args, out, err, tc.want)
}
}
out, err := runNetssh(t, "run", "missing", "fsnbx1")
if err == nil || !strings.Contains(out, "unknown configured command") {
t.Fatalf("%q %v", out, err)
}
}
func TestRunCommandAcceptsResolvedHostname(t *testing.T) {
prepareTransferTest(t)
data := `netbox:
url: http://127.0.0.1:1
token: t
hosts:
- name: router
address: router.example.com
commands:
trace:
args: [mtr, "{address}"]
`
if err := os.WriteFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml"), []byte(data), 0600); err != nil {
t.Fatal(err)
}
out, err := runNetssh(t, "run", "--dry-run", "trace", "router")
if err != nil || out != `"mtr" "router.example.com"` {
t.Fatalf("%q %v", out, err)
}
}
func TestRunOwnScripts(t *testing.T) {
for _, mode := range []string{"executable", "bash", "python3"} {
t.Run(mode, func(t *testing.T) {
if mode != "executable" {
if _, err := exec.LookPath(mode); err != nil {
t.Skip("interpreter not installed")
}
}
prepareTransferTest(t)
script := filepath.Join(t.TempDir(), "my host check")
body := "#!/bin/sh\nprintf '<%s>\\n' \"$@\"\nexit 7\n"
permissions := os.FileMode(0700)
argv := []string{script}
if mode != "executable" {
permissions = 0600
argv = []string{mode, script}
}
if mode == "python3" {
body = "import sys\nfor arg in sys.argv[1:]:\n print('<' + arg + '>')\nsys.exit(7)\n"
}
if err := os.WriteFile(script, []byte(body), permissions); err != nil {
t.Fatal(err)
}
argv = append(argv, "{address}", "{host}", "{target}")
var yaml strings.Builder
yaml.WriteString("\ncommands:\n check:\n alias_prefix: c\n args:\n")
for _, arg := range argv {
fmt.Fprintf(&yaml, " - %q\n", arg)
}
f, err := os.OpenFile(config.Path(), os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
_, err = f.WriteString(yaml.String())
if closeErr := f.Close(); err != nil || closeErr != nil {
t.Fatalf("config write: %v %v", err, closeErr)
}
out, err := runNetssh(t, "run", "check", "fsnbx1", "--", "--report", "two words", "$(literal)")
want := "<10.0.0.9>\n<fsn1-bx1.hoster.de>\n<fsn1-bx1.hoster.de>\n<--report>\n<two words>\n<$(literal)>"
if out != want {
t.Fatalf("script args: %q, want %q", out, want)
}
exit, ok := err.(*exec.ExitError)
if !ok || exit.ExitCode() != 7 {
t.Fatalf("script exit status lost: %v", err)
}
})
}
}
+198
View File
@@ -0,0 +1,198 @@
package main
import (
"sort"
"strings"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
func sftpCmd() *cobra.Command {
return transferCmd(internalssh.SFTP, "sftp [--dry-run] [--jump HOST|--no-jump] [sftp options] HOST[:PATH]",
"Open an SFTP session to a NetBox host",
`Resolve HOST like netssh does for ssh (cache, shortcuts, instance/host,
SSH options and rules, jump host) and run sftp. sftp options are passed
through; note that sftp uses -P for the port.
netssh sftp fsnbx1
netssh sftp -P 2222 prod/web01:/var/log`)
}
func scpCmd() *cobra.Command {
return transferCmd(internalssh.SCP, "scp [--dry-run] [--jump HOST|--no-jump] [scp options] SOURCE... TARGET",
"Copy files to or from a NetBox host",
`Resolve the host in HOST:PATH operands like netssh does for ssh and run scp.
All remote operands must name the same host.
netssh scp ./app.tar fsnbx1:/tmp/
netssh scp -r prod/web01:/etc/nginx ./nginx`)
}
func transferCmd(client internalssh.Client, use, short, long string) *cobra.Command {
return &cobra.Command{
Use: use,
Short: short,
Long: long,
DisableFlagParsing: true,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 || args[0] == "--help" || args[0] == "-h" {
_ = cmd.Help()
return
}
flags, args, err := client.ExtractWrapperFlags(args)
if err != nil {
fatalf("%v", err)
}
if len(flags.Forwards) > 0 {
fatalf("--forward is only available for ssh and netssh tunnel")
}
runClient(client, flags, args)
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
if client.Name == internalssh.SFTP.Name && client.Parse(args) != nil {
return nil, cobra.ShellCompDirectiveNoFileComp
}
if strings.HasPrefix(toComplete, "-") {
return nil, cobra.ShellCompDirectiveNoFileComp
}
if client.Name == internalssh.SCP.Name {
if strings.Contains(toComplete, ":") {
return nil, cobra.ShellCompDirectiveNoFileComp // remote paths are not completed
}
// HOST: for remote operands; without a matching host, local files.
hosts := completeHosts(toComplete)
if len(hosts) == 0 {
return nil, cobra.ShellCompDirectiveDefault
}
for i := range hosts {
hosts[i] += ":"
}
return hosts, cobra.ShellCompDirectiveNoSpace | cobra.ShellCompDirectiveNoFileComp
}
return completeHosts(toComplete), cobra.ShellCompDirectiveNoFileComp
},
}
}
func tunnelCmd() *cobra.Command {
return &cobra.Command{
Use: "tunnel [--dry-run] [--jump HOST|--no-jump] [ssh options] HOST FORWARD...",
Short: "Open port forwards to a NetBox host without a shell",
Long: `Run ssh -N with the named forwards configured under ssh.forwards (globally,
per NetBox instance, or per rule). A FORWARD that is no configured name but a
port spec such as 8080:localhost:80 is used as a local forward (-L).
netssh tunnel fsnbx1 web socks
netssh tunnel prod/db01 5432:localhost:5432`,
DisableFlagParsing: true,
Run: func(cmd *cobra.Command, args []string) {
if len(args) == 0 || args[0] == "--help" || args[0] == "-h" {
_ = cmd.Help()
return
}
flags, args, err := internalssh.SSH.ExtractWrapperFlags(args)
if err != nil {
fatalf("%v", err)
}
parsed := internalssh.SSH.Parse(args)
if parsed == nil {
fatalf("usage: netssh tunnel HOST FORWARD...")
}
// Everything after the host names forwards instead of a remote command.
flags.Forwards = append(flags.Forwards, args[parsed.DestIdx+1:]...)
flags.Tunnel = true
runClient(internalssh.SSH, flags, args[:parsed.DestIdx+1])
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
parsed := internalssh.SSH.Parse(args)
if parsed == nil {
return completeHosts(toComplete), cobra.ShellCompDirectiveNoFileComp
}
cfg, err := config.Load()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
var names []string
if entry, ok := cachedHost(cfg, parsed.Host); ok {
names = forwardNames(hostOptions(cfg, resolvedHost{Name: entry.Name, Kind: entry.Kind, Tags: entry.Tags}))
} else {
names = allForwardNames(cfg)
}
return filterPrefix(names, toComplete, args[parsed.DestIdx+1:]), cobra.ShellCompDirectiveNoFileComp
},
}
}
// completeHosts returns the cached hosts for a completion request.
func completeHosts(toComplete string) []string {
cfg, err := config.Load()
if err != nil {
return nil
}
c := newCache(cfg)
_ = c.Load()
hosts := hostCompletions(c.All(), toComplete, cfg.Shortcuts)
if limit := cfg.Completion.MaxResults; limit > 0 && len(hosts) > limit {
hosts = hosts[:limit]
}
return hosts
}
// cachedHost finds a host for completion by name or shortcut, without NetBox.
func cachedHost(cfg *config.Config, host string) (cache.Entry, bool) {
c := newCache(cfg)
if err := c.Load(); err != nil {
return cache.Entry{}, false
}
if entry, _ := c.Get(host); entry.Name != "" {
return entry, true
}
if !cfg.Shortcuts.Enabled() {
return cache.Entry{}, false
}
entry, found, _, err := c.GetByShortcut(host, normalizeTarget(cfg.Shortcuts, strings.Contains(host, "/")))
return entry, found && err == nil
}
// allForwardNames lists every configured forward name, for when the host is unknown.
func allForwardNames(cfg *config.Config) []string {
seen := map[string]bool{}
add := func(o config.SSHOptions) {
for name := range o.Forwards {
seen[strings.ToLower(name)] = true
}
}
add(cfg.SSH.SSHOptions)
add(cfg.NetBox.SSH)
for _, source := range cfg.NetBoxes {
add(source.SSH)
}
for _, rule := range cfg.SSH.Rules {
add(rule.SSHOptions)
}
names := make([]string, 0, len(seen))
for name := range seen {
names = append(names, name)
}
sort.Strings(names)
return names
}
// filterPrefix keeps the names starting with prefix that were not given yet.
func filterPrefix(names []string, prefix string, given []string) []string {
used := map[string]bool{}
for _, name := range given {
used[strings.ToLower(name)] = true
}
var out []string
for _, name := range names {
if strings.HasPrefix(name, strings.ToLower(prefix)) && !used[name] {
out = append(out, name)
}
}
return out
}
+130
View File
@@ -0,0 +1,130 @@
package main
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"
)
// TestNetsshHelper runs main() with the arguments in NETSSH_TEST_ARGS.
func TestNetsshHelper(t *testing.T) {
if args := os.Getenv("NETSSH_TEST_ARGS"); args != "" {
os.Args = append([]string{"netssh"}, strings.Split(args, "\x1f")...)
main()
os.Exit(0)
}
}
// prepareTransferTest writes a config whose only host is cached; NetBox is
// unreachable, so every result must come from cache, shortcuts, and options.
func prepareTransferTest(t *testing.T) {
t.Helper()
dir := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", dir)
t.Setenv("XDG_CACHE_HOME", t.TempDir())
t.Setenv("NETSSH_NETBOX_URL", "")
t.Setenv("NETSSH_NETBOX_TOKEN", "")
t.Setenv("NETSSH_CACHE_PATH", filepath.Join(t.TempDir(), "hosts.json"))
t.Setenv("NETSSH_SHELL_ALIAS", "")
data := `netbox:
url: http://127.0.0.1:1
token: t
ssh:
default_user: ops
default_port: 2222
extra_args: ["-A"]
forwards:
web: {local: "8080:localhost:80"}
rules:
- match: {tag: dmz}
proxy_jump: jh.example.com
forwards:
socks: {dynamic: "1080"}
shortcuts:
domains: [.hoster.de]
rewrites:
- pattern: '^([a-z]+)[0-9]+-'
replace: '$1'
`
if err := os.WriteFile(filepath.Join(dir, "netssh.yaml"), []byte(data), 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: "fsn1-bx1.hoster.de", IP: "10.0.0.9", Kind: "device", Tags: []string{"dmz"}})
if err := c.Save(); err != nil {
t.Fatal(err)
}
}
func runNetssh(t *testing.T, args ...string) (string, error) {
t.Helper()
cmd := exec.Command(os.Args[0], "-test.run=^TestNetsshHelper$")
cmd.Env = append(os.Environ(), "NETSSH_TEST_ARGS="+strings.Join(args, "\x1f"))
out, err := cmd.CombinedOutput()
return strings.TrimSpace(string(out)), err
}
func TestTransferAndTunnelCommands(t *testing.T) {
prepareTransferTest(t)
for _, tc := range []struct {
args []string
want string
}{
// sftp: -P and -o User, rule jump host, path kept, no ssh-only extra_args.
{[]string{"sftp", "--dry-run", "fsnbx1:/var/log"}, "sftp -P 2222 -o User=ops -J jh.example.com 10.0.0.9:/var/log"},
{[]string{"sftp", "--dry-run", "-P", "22", "root@fsnbx1"}, "sftp -P 22 -J jh.example.com root@10.0.0.9"},
{[]string{"scp", "--dry-run", "-r", "a.txt", "fsn1-bx1.hoster.de:/tmp/"}, "scp -P 2222 -o User=ops -r -J jh.example.com a.txt 10.0.0.9:/tmp/"},
{[]string{"scp", "--dry-run", "--no-jump", "fsnbx1:/etc/hosts", "."}, "scp -P 2222 -o User=ops -o ProxyJump=none 10.0.0.9:/etc/hosts ."},
// Forwards come from the global options and the matching rule.
{[]string{"tunnel", "--dry-run", "fsnbx1", "web", "socks", "5432:db:5432"}, "ssh -A -p 2222 -l ops -J jh.example.com -L 8080:localhost:80 -D 1080 -L 5432:db:5432 -o ExitOnForwardFailure=yes -N 10.0.0.9"},
{[]string{"--dry-run", "--forward", "web", "fsnbx1"}, "ssh -A -p 2222 -l ops -J jh.example.com -L 8080:localhost:80 10.0.0.9"},
} {
out, err := runNetssh(t, tc.args...)
if err != nil || out != tc.want {
t.Errorf("%v:\n got %s (%v)\n want %s", tc.args, out, err, tc.want)
}
}
for _, tc := range []struct {
args []string
want string
}{
{[]string{"tunnel", "--dry-run", "fsnbx1"}, "forwards for fsn1-bx1.hoster.de: socks, web"},
{[]string{"tunnel", "--dry-run", "fsnbx1", "db"}, `unknown forward "db"; available: socks, web`},
{[]string{"sftp", "--forward", "web", "fsnbx1"}, "only available for ssh"},
{[]string{"scp", "fsnbx1:a", "other:b"}, "not supported"},
} {
out, err := runNetssh(t, tc.args...)
if err == nil || !strings.Contains(out, tc.want) {
t.Errorf("%v: got %s (%v), want error containing %q", tc.args, out, err, tc.want)
}
}
}
func TestTransferCompletion(t *testing.T) {
prepareTransferTest(t)
for _, tc := range []struct {
args []string
want string
}{
{[]string{"__complete", "sftp", "fsnb"}, "fsnbx1\n"},
{[]string{"__complete", "scp", "a.txt", "fsnb"}, "fsnbx1:\n"},
{[]string{"__complete", "tunnel", "fsnbx1", ""}, "socks\nweb\n"},
{[]string{"__complete", "tunnel", "fsnbx1", "web", ""}, "socks\n"},
{[]string{"__complete", "--forward", ""}, "socks\nweb\n"},
} {
out, err := runNetssh(t, tc.args...)
if err != nil || !strings.HasPrefix(out+"\n", tc.want) {
t.Errorf("%v: got %q (%v), want prefix %q", tc.args, out, err, tc.want)
}
}
}
+251
View File
@@ -0,0 +1,251 @@
package main
import (
"bufio"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path/filepath"
"strings"
"time"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
)
// uninstallPlan lists everything netssh has written to this machine.
type uninstallPlan struct {
Profiles []string // shell profiles with a netssh block or legacy lines
Paths []string // files and directories to delete
Config string // config file to back up and delete; empty when kept
Binaries []string
}
func buildUninstallPlan(cfg *config.Config, keepConfig bool) uninstallPlan {
var plan uninstallPlan
seen := make(map[string]bool)
addPath := func(path string) {
if path == "" || seen[path] {
return
}
if _, err := os.Lstat(path); err == nil {
seen[path] = true
plan.Paths = append(plan.Paths, path)
}
}
for _, profile := range hook.ProfileCandidates() {
target, err := filepath.EvalSymlinks(profile)
if err != nil || seen[target] {
continue
}
seen[target] = true
if hook.HasEntries(profile) {
plan.Profiles = append(plan.Profiles, profile)
}
}
aliases := []string{hook.CompletionAliasState()}
if cfg != nil {
aliases = append(aliases, cfg.Shell.Alias)
}
for _, path := range hook.CompletionFiles(aliases...) {
if hook.IsGenerated(path) {
addPath(path)
}
}
// The cache directory holds hosts, aliases, refresh stamps, and instance caches.
cacheDir := filepath.Dir(hook.AliasesPath())
addPath(cacheDir)
if cfg != nil {
for _, path := range []string{cfg.Cache.Path, cfg.CachePath()} {
if path == "" || strings.HasPrefix(path, cacheDir+string(filepath.Separator)) {
continue
}
addPath(path)
addPath(path + ".lock")
addPath(filepath.Join(filepath.Dir(path), "last_refresh"))
addPath(filepath.Join(filepath.Dir(path), "refresh_attempt"))
if strings.HasPrefix(filepath.Base(filepath.Dir(path)), "instances-") {
addPath(filepath.Dir(path))
}
}
}
if !keepConfig {
if _, err := os.Stat(config.Path()); err == nil {
plan.Config = config.Path()
}
// Local server notes live next to the config file.
addPath(filepath.Join(filepath.Dir(config.Path()), "netssh"))
}
plan.Binaries = installedBinaries()
return plan
}
// installedBinaries finds the running binary and any other netssh in PATH.
func installedBinaries() []string {
var out []string
seen := make(map[string]bool)
add := func(path string) {
real, err := filepath.EvalSymlinks(path)
if err != nil || seen[real] {
return
}
if info, err := os.Stat(real); err != nil || info.IsDir() || filepath.Base(real) != "netssh" {
return
}
seen[real] = true
out = append(out, real)
}
if self, err := os.Executable(); err == nil {
add(self)
}
for _, dir := range filepath.SplitList(os.Getenv("PATH")) {
if dir != "" {
add(filepath.Join(dir, "netssh"))
}
}
return out
}
func (p uninstallPlan) empty() bool {
return len(p.Profiles) == 0 && len(p.Paths) == 0 && p.Config == "" && len(p.Binaries) == 0
}
func (p uninstallPlan) print(w io.Writer) {
for _, profile := range p.Profiles {
fmt.Fprintf(w, " edit %s (remove netssh entries)\n", profile)
}
for _, path := range p.Paths {
fmt.Fprintf(w, " delete %s\n", path)
}
if p.Config != "" {
fmt.Fprintf(w, " delete %s (a backup is kept)\n", p.Config)
}
for _, binary := range p.Binaries {
fmt.Fprintf(w, " delete %s\n", binary)
}
}
// execute applies the plan. It continues after errors so that one protected
// file does not leave the rest behind, and returns commands that need sudo.
func (p uninstallPlan) execute(w io.Writer) (manual []string, err error) {
var errs []error
for _, profile := range p.Profiles {
if _, err := hook.Uninstall(profile); err != nil {
errs = append(errs, err)
continue
}
fmt.Fprintf(w, "cleaned %s\n", profile)
}
for _, path := range p.Paths {
if err := os.RemoveAll(path); err != nil {
errs = append(errs, err)
continue
}
fmt.Fprintf(w, "removed %s\n", path)
}
if p.Config != "" {
backup, err := backupConfig(p.Config)
if err != nil {
errs = append(errs, fmt.Errorf("config not removed: %w", err))
} else if err := os.Remove(p.Config); err != nil {
errs = append(errs, err)
} else {
fmt.Fprintf(w, "removed %s (backup: %s)\n", p.Config, backup)
}
}
for _, binary := range p.Binaries {
if err := os.Remove(binary); err != nil {
if errors.Is(err, fs.ErrPermission) {
manual = append(manual, "sudo rm -f "+shellQuote(binary))
continue
}
errs = append(errs, err)
continue
}
fmt.Fprintf(w, "removed %s\n", binary)
}
return manual, errors.Join(errs...)
}
// backupConfig keeps a private copy, because the config holds API tokens.
func backupConfig(path string) (string, error) {
data, err := os.ReadFile(path)
if err != nil {
return "", err
}
backup := path + ".backup-" + time.Now().Format("20060102-150405")
if err := storage.WriteFile(backup, data, 0o600); err != nil {
return "", err
}
return backup, nil
}
func shellQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
func uninstallCmd() *cobra.Command {
var keepConfig, yes, dryRun bool
cmd := &cobra.Command{
Use: "uninstall",
Short: "Remove netssh, its shell integration, cache, and config",
Long: `Removes everything netssh and install.sh have set up:
- netssh blocks and unmarked entries of older versions in bash, zsh, and fish profiles
- shell completion files (bash, zsh, fish, oh-my-zsh cache, command alias)
- the cache directory with hosts, aliases, and per-instance caches
- the config file (a private backup is kept) and local server notes
- the netssh binary
Use --keep-config to keep the config file and notes for a reinstall.`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
// A broken config must not block the uninstall.
fmt.Fprintf(os.Stderr, "warning: %v\n", err)
cfg = nil
}
plan := buildUninstallPlan(cfg, keepConfig)
out := cmd.OutOrStdout()
if plan.empty() {
fmt.Fprintln(out, "Nothing to remove.")
return nil
}
fmt.Fprintln(out, "netssh uninstall will:")
plan.print(out)
if dryRun {
return nil
}
if !yes {
fmt.Fprint(out, "Proceed? [y/N] ")
answer, _ := bufio.NewReader(cmd.InOrStdin()).ReadString('\n')
if a := strings.ToLower(strings.TrimSpace(answer)); a != "y" && a != "yes" {
return fmt.Errorf("aborted")
}
}
manual, err := plan.execute(out)
for _, command := range manual {
fmt.Fprintf(out, "Permission denied. Run: %s\n", command)
}
if len(plan.Profiles) > 0 {
fmt.Fprintln(out, "Open a new terminal. For zsh, also run: rm -f ~/.zcompdump*")
}
return err
},
}
cmd.Flags().BoolVar(&keepConfig, "keep-config", false, "Keep the config file and local notes")
cmd.Flags().BoolVarP(&yes, "yes", "y", false, "Do not ask for confirmation")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Only show what would be removed")
return cmd
}
+119
View File
@@ -0,0 +1,119 @@
package main
import (
"os"
"path/filepath"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
)
func uninstallFixture(t *testing.T) (home string) {
t.Helper()
home = t.TempDir()
t.Setenv("HOME", home)
t.Setenv("ZDOTDIR", home)
t.Setenv("XDG_CONFIG_HOME", filepath.Join(home, ".config"))
t.Setenv("XDG_CACHE_HOME", filepath.Join(home, ".cache"))
t.Setenv("ZSH", "")
t.Setenv("ZSH_CACHE_DIR", "")
t.Setenv("NETSSH_SHELL_ALIAS", "")
t.Setenv("NETSSH_CACHE_PATH", "")
t.Setenv("PATH", filepath.Join(home, "nobin"))
files := map[string]string{
".bashrc": "export KEEP=1\n# >>> netssh >>>\nnetssh shell-init\n# <<< netssh <<<\n",
".zshrc": "plugins=(git)\nnetssh shell-init # netssh cache auto-refresh\nsource ~/.cache/netssh/aliases.sh 2>/dev/null # netssh aliases\n",
".profile": "export UNRELATED=1\n",
".config/netssh.yaml": "netbox:\n url: \"https://netbox.example.com\"\n token: \"secret\"\nshell:\n alias: \"j\"\n",
".config/netssh/notes/abc.txt": "note",
".cache/netssh/hosts.json": "{}",
".cache/netssh/instances-0011/hosts.json": "{}",
".local/share/bash-completion/completions/netssh": "# bash completion for netssh",
".zfunc/_netssh": hook.ZshCompletionScript,
".zfunc/_j": "#compdef j\n# netssh command alias completion — generated automatically\n",
".zfunc/_other": "#compdef other\n",
}
for name, content := range files {
path := filepath.Join(home, name)
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
t.Fatal(err)
}
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
}
return home
}
func runUninstall(t *testing.T, args ...string) string {
t.Helper()
cmd := rootCmd()
var out strings.Builder
cmd.SetOut(&out)
cmd.SetArgs(append([]string{"uninstall"}, args...))
if err := cmd.Execute(); err != nil {
t.Fatalf("uninstall: %v\n%s", err, out.String())
}
return out.String()
}
func TestUninstallRemovesEverythingAndBacksUpConfig(t *testing.T) {
home := uninstallFixture(t)
if out := runUninstall(t, "--dry-run"); !strings.Contains(out, ".zshrc") || strings.Contains(out, ".profile") {
t.Fatalf("plan:\n%s", out)
}
if _, err := os.Stat(filepath.Join(home, ".cache", "netssh")); err != nil {
t.Fatal("dry run removed files")
}
runUninstall(t, "--yes")
for name, want := range map[string]string{".bashrc": "export KEEP=1\n", ".zshrc": "plugins=(git)\n", ".profile": "export UNRELATED=1\n"} {
data, _ := os.ReadFile(filepath.Join(home, name))
if string(data) != want {
t.Errorf("%s: %q", name, data)
}
}
for _, gone := range []string{".cache/netssh", ".config/netssh.yaml", ".config/netssh", ".zfunc/_netssh", ".zfunc/_j", ".local/share/bash-completion/completions/netssh"} {
if _, err := os.Stat(filepath.Join(home, gone)); !os.IsNotExist(err) {
t.Errorf("%s not removed: %v", gone, err)
}
}
if _, err := os.Stat(filepath.Join(home, ".zfunc", "_other")); err != nil {
t.Error("unrelated completion removed")
}
backups, _ := filepath.Glob(filepath.Join(home, ".config", "netssh.yaml.backup-*"))
if len(backups) != 1 {
t.Fatalf("backups: %v", backups)
}
if info, _ := os.Stat(backups[0]); info.Mode().Perm() != 0o600 {
t.Error("backup with token is not private")
}
}
func TestUninstallKeepConfig(t *testing.T) {
home := uninstallFixture(t)
runUninstall(t, "--yes", "--keep-config")
for _, kept := range []string{".config/netssh.yaml", ".config/netssh/notes/abc.txt"} {
if _, err := os.Stat(filepath.Join(home, kept)); err != nil {
t.Errorf("%s removed", kept)
}
}
if _, err := os.Stat(filepath.Join(home, ".cache", "netssh")); !os.IsNotExist(err) {
t.Error("cache kept")
}
}
func TestUninstallAbortsWithoutConfirmation(t *testing.T) {
home := uninstallFixture(t)
cmd := rootCmd()
cmd.SetOut(&strings.Builder{})
cmd.SetIn(strings.NewReader("n\n"))
cmd.SetArgs([]string{"uninstall"})
if err := cmd.Execute(); err == nil {
t.Fatal("no confirmation required")
}
if _, err := os.Stat(filepath.Join(home, ".config", "netssh.yaml")); err != nil {
t.Fatal("config removed without confirmation")
}
}
+33
View File
@@ -0,0 +1,33 @@
package main
import (
"fmt"
"runtime/debug"
"github.com/spf13/cobra"
)
// version is set at build time: -ldflags "-X main.version=v1.2.3".
var version = ""
// buildVersion falls back to the module version for `go install` builds.
func buildVersion() string {
if version != "" {
return version
}
if info, ok := debug.ReadBuildInfo(); ok && info.Main.Version != "" && info.Main.Version != "(devel)" {
return info.Main.Version
}
return "dev"
}
func versionCmd() *cobra.Command {
return &cobra.Command{
Use: "version",
Short: "Print the netssh version",
Args: cobra.NoArgs,
Run: func(cmd *cobra.Command, args []string) {
fmt.Fprintf(cmd.OutOrStdout(), "netssh %s\n", buildVersion())
},
}
}