From 20d7a405436403c024b9fbfa3f88652a852f8163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Sebastian=20Untersch=C3=BCtz?= Date: Mon, 16 Nov 2026 22:13:05 +0100 Subject: [PATCH] feat(instances): allow disabling prefixes in aliases and TUI --- README.md | 38 +++++++++++++- cmd/netssh/main.go | 1 + internal/config/config.go | 11 ++-- internal/config/instances.go | 14 +++++ internal/config/instances_test.go | 8 +++ internal/hook/aliases.go | 29 ++++++++++- internal/hook/aliases_test.go | 75 ++++++++++++++++++++++++++ internal/setup/instances.go | 3 ++ internal/setup/wizard.go | 3 ++ internal/setup/wizard_test.go | 2 +- internal/tui/instances_test.go | 87 +++++++++++++++++++++++++++++++ internal/tui/model.go | 46 ++++++++++++---- 12 files changed, 298 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 45d23e5..b361feb 100644 --- a/README.md +++ b/README.md @@ -212,7 +212,7 @@ Every key, its default, and the section that explains it. Keys marked *layered* | `netbox.url` | string | — | NetBox base URL (single instance). Use either `netbox` or `netboxes`. | | `netbox.token` | string | — | API token; `nbt_…` is v2, anything else v1. | | `netbox.token_version` | 1 \| 2 | auto | Detected from the token prefix. | -| `netboxes[]` | list | — | Named instances with `name`, `url`, `token`, `token_version`, `ssh` — see [Multiple NetBox instances](#multiple-netbox-instances). | +| `netboxes[]` | list | — | Named instances with `name`, `url`, `token`, `token_version`, `disable_prefix`, `ssh` — see [Multiple NetBox instances](#multiple-netbox-instances). | | `resolver.strategies` | list | `[management_subnet, primary_ip]` | Tried in order, first IP wins — see [IP Resolution Strategies](#ip-resolution-strategies). The wizard suggests `primary_ip`. | | `resolver.management_subnets` | list of CIDR | `[]` | Used by `management_subnet`. | | `resolver.interface_name` | string | — | Used by `interface_name`, e.g. `mgmt0`. | @@ -306,7 +306,41 @@ netssh notes show lab/web01 --netbox --kind device For direct connections without an instance prefix, every instance must be reachable to verify uniqueness. A qualified target queries only its own instance and can use a fresh cached IP while other instances are offline. Qualified shortcuts such as `office/web01` also support configured domain suffixes and hyphen folding. -Cache entries and generated aliases retain the instance name (`office_web01` and `lab_web01`). Named-instance caches live in a configuration-specific subdirectory beneath the configured cache path, so changing an endpoint cannot reuse another server's cached IPs. Run `netssh cache refresh` after adding or changing instances. A failed full refresh leaves the cache and its refresh timestamp unchanged; a per-instance refresh preserves the other instances and does not mark the whole cache as refreshed. +Cache entries retain the instance name. Generated aliases include it by default (`office_web01` and `lab_web01`). Named-instance caches live in a configuration-specific subdirectory beneath the configured cache path, so changing an endpoint cannot reuse another server's cached IPs. Run `netssh cache refresh` after adding or changing instances. A failed full refresh leaves the cache and its refresh timestamp unchanged; a per-instance refresh preserves the other instances and does not mark the whole cache as refreshed. + +**Aliases and TUI names without an instance prefix.** Set `disable_prefix: true` +on individual instances, or enable **Hide instance prefix in aliases and TUI?** +when editing an instance in `netssh configure`: + +```yaml +netboxes: + - name: office + url: https://netbox.office.example + token: nbt_office-token + disable_prefix: true + - name: lab + url: https://netbox.lab.example + token: nbt_lab-token +``` + +With the appropriate domain shortcut, this generates `web01` for +`office/web01.example.com` and `lab_web01` for the lab host. The default is +`false`. The alias command still contains the full `instance/hostname`, so it +connects to the selected instance even when another instance has the same host +name. Domain stripping, rewrites and hyphen folding still apply. + +If a bare alias conflicts with another generated alias, a reserved qualified +alias, `netssh`, or your configured command alias, the instance prefix is kept. +It is also kept if the bare name is not a valid shell alias (e.g. starts with a digit). +The TUI result list also hides the prefix for this instance; duplicate visible +names keep their prefixes to remain distinguishable. Selection, autocomplete, +connection editors, notes and cache identities still use the full target. +Completion already offers unique hostnames +without an instance prefix. + +Open a new shell with the installed netssh hook to regenerate and load aliases. +No cache refresh is needed for this setting. Existing aliases in an already open +shell remain until removed or the shell is replaced. Local notes remain keyed by the NetBox URL, host kind, and canonical hostname. Migrating a single instance or renaming it preserves its notes. Use `instance/hostname` and `--kind` for uncached local notes; these operations work offline. NetBox comments and interface/IP lookups always use the selected instance's credentials. diff --git a/cmd/netssh/main.go b/cmd/netssh/main.go index dda5228..7840256 100644 --- a/cmd/netssh/main.go +++ b/cmd/netssh/main.go @@ -386,6 +386,7 @@ func runTUI() { } m := tui.New(nbClient, c, cfg.SSH.DefaultUser, cfg.SSH.DefaultPort) + m.SetHostLabel(cfg.HostLabel) m.SetNotes(notes.New(cfg.NetBox.URL, nbClient)) m.SetForwards(func(name, kind string, tags []string) []string { return forwardNames(hostOptions(cfg, resolvedHost{Name: name, Kind: kind, Tags: tags})) diff --git a/internal/config/config.go b/internal/config/config.go index 1a401c4..c6ad865 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -30,11 +30,12 @@ type ShellConfig struct { } type NetBoxConfig struct { - Name string `mapstructure:"name"` - URL string `mapstructure:"url"` - Token string `mapstructure:"token"` - TokenVersion int `mapstructure:"token_version"` - SSH SSHOptions `mapstructure:"ssh"` + DisablePrefix bool `mapstructure:"disable_prefix"` + Name string `mapstructure:"name"` + URL string `mapstructure:"url"` + Token string `mapstructure:"token"` + TokenVersion int `mapstructure:"token_version"` + SSH SSHOptions `mapstructure:"ssh"` } type ResolverConfig struct { diff --git a/internal/config/instances.go b/internal/config/instances.go index 74a704e..9e2eeeb 100644 --- a/internal/config/instances.go +++ b/internal/config/instances.go @@ -65,3 +65,17 @@ func (c *Config) CachePath() string { sum := sha256.Sum256([]byte(strings.Join(identities, "\x00"))) return filepath.Join(filepath.Dir(c.Cache.Path), fmt.Sprintf("instances-%x", sum[:8]), filepath.Base(c.Cache.Path)) } + +// HostLabel omits the configured instance prefix for display only. Callers +// must retain the canonical target for connections and handle label collisions. +func (c *Config) HostLabel(target string) string { + source, host, qualified := strings.Cut(target, "/") + if qualified { + for _, instance := range c.NetBoxes { + if instance.DisablePrefix && strings.EqualFold(instance.Name, source) { + return host + } + } + } + return target +} diff --git a/internal/config/instances_test.go b/internal/config/instances_test.go index 4adf6d4..5a37890 100644 --- a/internal/config/instances_test.go +++ b/internal/config/instances_test.go @@ -15,6 +15,7 @@ func TestLoadNamedNetBoxes(t *testing.T) { - name: Office url: https://office.example/netbox token: nbt_office + disable_prefix: true - name: lab url: https://lab.example token: legacy-token @@ -34,7 +35,14 @@ cache: if cfg.NetBox.URL != "" { t.Fatal("legacy environment variables added an unnamed instance") } + if !cfg.NetBoxes[0].DisablePrefix || cfg.NetBoxes[1].DisablePrefix { + t.Fatal("per-instance alias prefix setting was not loaded") + } first := cfg.CachePath() + cfg.NetBoxes[0].DisablePrefix = false + if cfg.CachePath() != first { + t.Fatal("alias prefix setting discarded cache") + } if first == cfg.Cache.Path { t.Fatal("named sources reuse legacy cache") } diff --git a/internal/hook/aliases.go b/internal/hook/aliases.go index 738c007..2992291 100644 --- a/internal/hook/aliases.go +++ b/internal/hook/aliases.go @@ -124,9 +124,34 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry { seen[cfg.Shell.Alias] = true out = append(out, AliasEntry{Name: cfg.Shell.Alias}) } - for _, e := range entries { + + withoutPrefix := make(map[string]bool, len(cfg.NetBoxes)) + for _, source := range cfg.NetBoxes { + withoutPrefix[strings.ToLower(source.Name)] = source.DisablePrefix + } + // Reserve canonical aliases as well as requested bare aliases before + // generating any output, so cache ordering cannot redirect a collision. + canonical := make(map[string]bool, len(entries)) + counts := make(map[string]int, len(entries)) + candidates := make([]string, len(entries)) + for i, e := range entries { name := shortcuts.AliasName(e.Name, cfg.Shortcuts) - if seen[name] || name == "" || !regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`).MatchString(name) { + canonical[name] = true + source, host, qualified := strings.Cut(e.Name, "/") + if qualified && withoutPrefix[strings.ToLower(source)] { + name = shortcuts.AliasName(host, cfg.Shortcuts) + } + candidates[i] = name + counts[name]++ + } + validAlias := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`) + for i, e := range entries { + name := candidates[i] + full := shortcuts.AliasName(e.Name, cfg.Shortcuts) + if name != full && (counts[name] > 1 || canonical[name] || seen[name] || !validAlias.MatchString(name)) { + name = full + } + if seen[name] || name == "" || !validAlias.MatchString(name) { continue } seen[name] = true diff --git a/internal/hook/aliases_test.go b/internal/hook/aliases_test.go index e7f4b3c..386d12f 100644 --- a/internal/hook/aliases_test.go +++ b/internal/hook/aliases_test.go @@ -253,3 +253,78 @@ func TestAliasesUseRewriteRules(t *testing.T) { t.Fatalf("entries: %+v", entries) } } + +func TestAliasesOptionalInstancePrefix(t *testing.T) { + cfg := config.Config{ + NetBoxes: []config.NetBoxConfig{ + {Name: "OFFICE", DisablePrefix: true}, + {Name: "lab"}, + }, + Shortcuts: config.ShortcutsConfig{ + Domains: []string{".example.com"}, + Rewrites: []config.ShortcutRewrite{{Pattern: "^web-", Replace: "app"}}, + }, + } + entries := hook.BuildAliasEntries([]cache.Entry{ + {Name: "office/web-01.example.com"}, + {Name: "lab/web-01.example.com"}, + }, cfg) + got := map[string]string{} + for _, e := range entries { + got[e.Name] = e.Host + // Both output formats must keep the fully qualified destination. + for _, shell := range []string{"bash", "zsh", "fish"} { + if !strings.Contains(e.Definition(shell), e.Host) { + t.Fatalf("%s alias lost its target: %s", shell, e.Definition(shell)) + } + } + } + if len(got) != 2 || got["app01"] != "office/web-01.example.com" || got["lab_app01"] != "lab/web-01.example.com" { + t.Fatalf("unexpected aliases: %+v", entries) + } +} + +func TestAliasesWithoutPrefixCollisions(t *testing.T) { + cfg := config.Config{ + NetBoxes: []config.NetBoxConfig{ + {Name: "office", DisablePrefix: true}, + {Name: "lab", DisablePrefix: true}, + }, + Shell: config.ShellConfig{Alias: "j"}, + Shortcuts: config.ShortcutsConfig{Domains: []string{".example.com"}}, + } + for _, tc := range []struct { + name string + hosts []string + want map[string]string + }{ + {"two instances", []string{"office/web.example.com", "lab/web.example.com"}, + map[string]string{"j": "", "office_web": "office/web.example.com", "lab_web": "lab/web.example.com"}}, + {"static host", []string{"office/web.example.com", "web"}, + map[string]string{"j": "", "office_web": "office/web.example.com", "web": "web"}}, + {"command aliases", []string{"office/j", "office/netssh"}, + map[string]string{"j": "", "office_j": "office/j", "office_netssh": "office/netssh"}}, + {"reserved qualified alias", []string{"office/lab_web", "lab/web"}, + map[string]string{"j": "", "office_lab_web": "office/lab_web", "web": "lab/web"}}, + {"invalid bare alias", []string{"office/123.example.com"}, + map[string]string{"j": "", "office_123": "office/123.example.com"}}, + {"normalized names", []string{"office/web.example.com", "office/web"}, + map[string]string{"j": "", "office_web": "office/web"}}, + } { + t.Run(tc.name, func(t *testing.T) { + var input []cache.Entry + for _, host := range tc.hosts { + input = append(input, cache.Entry{Name: host}) + } + entries := hook.BuildAliasEntries(input, cfg) + if len(entries) != len(tc.want) { + t.Fatalf("aliases: %+v, want %+v", entries, tc.want) + } + for _, e := range entries { + if host, ok := tc.want[e.Name]; !ok || host != e.Host { + t.Fatalf("unexpected alias: %+v", e) + } + } + }) + } +} diff --git a/internal/setup/instances.go b/internal/setup/instances.go index bc46962..cf90802 100644 --- a/internal/setup/instances.go +++ b/internal/setup/instances.go @@ -108,6 +108,9 @@ func editInstance(source config.NetBoxConfig, sources []config.NetBoxConfig, ori } return nil }), + huh.NewConfirm().Title("Hide instance prefix in aliases and TUI?"). + Description("Shorter shell aliases and TUI host names. Conflicting names keep their prefix."). + Value(&source.DisablePrefix), huh.NewInput().Title("NetBox URL").Placeholder("https://netbox.example.com").Value(&source.URL).Validate(func(value string) error { return (&config.Config{NetBoxes: []config.NetBoxConfig{{Name: "instance", URL: strings.TrimSpace(value)}}}).ValidateNetBoxes() }), diff --git a/internal/setup/wizard.go b/internal/setup/wizard.go index 408efd9..f4e08e6 100644 --- a/internal/setup/wizard.go +++ b/internal/setup/wizard.go @@ -385,6 +385,9 @@ func save(cfg config.Config) error { b.WriteString("netboxes:\n") for _, source := range cfg.NetBoxes { fmt.Fprintf(&b, " - name: %q\n url: %q\n token: %q\n token_version: %d\n", source.Name, source.URL, source.Token, source.TokenVersion) + if source.DisablePrefix { + b.WriteString(" disable_prefix: true\n") + } if !sshOptionsEmpty(source.SSH) { b.WriteString(" ssh:\n") writeSSHOptions(&b, " ", source.SSH) diff --git a/internal/setup/wizard_test.go b/internal/setup/wizard_test.go index ae17f9c..50aaad9 100644 --- a/internal/setup/wizard_test.go +++ b/internal/setup/wizard_test.go @@ -398,7 +398,7 @@ func TestSaveMultipleNetBoxesRoundTrip(t *testing.T) { t.Setenv("XDG_CONFIG_HOME", t.TempDir()) cfg := config.Config{ NetBoxes: []config.NetBoxConfig{ - {Name: "office", URL: "https://office.example/netbox", Token: "nbt_secret: office", TokenVersion: 2}, + {Name: "office", URL: "https://office.example/netbox", Token: "nbt_secret: office", TokenVersion: 2, DisablePrefix: true}, {Name: "lab", URL: "https://lab.example", Token: "legacy#token", TokenVersion: 1}, }, Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}}, diff --git a/internal/tui/instances_test.go b/internal/tui/instances_test.go index e3982e1..333af63 100644 --- a/internal/tui/instances_test.go +++ b/internal/tui/instances_test.go @@ -9,6 +9,7 @@ import ( tea "charm.land/bubbletea/v2" "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" ) @@ -79,3 +80,89 @@ func TestPartialOutageKeepsLiveAndCachedResultsVisible(t *testing.T) { t.Fatalf("outage warning overflowed view: %d", rows) } } + +func TestHiddenPrefixKeepsCanonicalTargets(t *testing.T) { + cfg := config.Config{NetBoxes: []config.NetBoxConfig{ + {Name: "OFFICE", DisablePrefix: true}, {Name: "lab"}, + }} + for _, cached := range []bool{false, true} { + for _, action := range []string{"ssh", "sftp", "multi", "autocomplete", "edit", "tunnel"} { + t.Run(fmt.Sprintf("cached=%v/%s", cached, action), func(t *testing.T) { + m := New(nil, nil, "") + m.SetHostLabel(cfg.HostLabel) + m.Update(tea.WindowSizeMsg{Width: 100, Height: 24}) + entries := []netbox.HostEntry{ + {Source: "office", Name: "web01", PrimaryIP4: "10.0.0.1"}, + {Source: "lab", Name: "web01", PrimaryIP4: "10.0.0.2"}, + } + if cached { + for i := range entries { + entries[i].Name = entries[i].Target() + entries[i].Source = "" + } + } + m.updateListItems(entries) + item := m.list.Items()[0].(hostItem) + if item.Title() != "web01" || item.name != "office/web01" { + t.Fatalf("display changed identity: %+v", item) + } + view := m.View().Content + if strings.Contains(view, "office/web01") || !strings.Contains(view, "lab/web01") { + t.Fatalf("wrong rendered prefixes: %s", view) + } + switch action { + case "ssh", "sftp": + key := tea.KeyPressMsg{Code: tea.KeyEnter} + if action == "sftp" { + key = tea.KeyPressMsg{Code: 'o', Mod: tea.ModCtrl} + } + m.Update(key) + if m.selected == nil || m.selected.Name != "office/web01" { + t.Fatalf("lost instance: %+v", m.selected) + } + case "multi": + m.Update(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "}) + m.Update(tea.KeyPressMsg{Code: tea.KeyEnter}) + if m.selected == nil || len(m.selected.Targets) != 1 || m.selected.Targets[0] != "office/web01" { + t.Fatalf("multi lost instance: %+v", m.selected) + } + case "autocomplete": + m.Update(tea.KeyPressMsg{Code: tea.KeyTab}) + if m.input.Value() != "office/web01" { + t.Fatal("autocomplete lost instance") + } + case "edit": + m.Update(tea.KeyPressMsg{Code: 'e', Mod: tea.ModCtrl}) + if m.editHost == nil || m.editHost.name != "office/web01" { + t.Fatal("editor lost instance") + } + case "tunnel": + m.Update(tea.KeyPressMsg{Code: 't', Mod: tea.ModCtrl}) + if m.forwardHost == nil || m.forwardHost.name != "office/web01" { + t.Fatal("tunnel lost instance") + } + } + }) + } + } +} + +func TestHiddenPrefixDuplicateLabels(t *testing.T) { + cfg := config.Config{NetBoxes: []config.NetBoxConfig{ + {Name: "office", DisablePrefix: true}, {Name: "lab", DisablePrefix: true}, + }} + for _, other := range []netbox.HostEntry{ + {Source: "lab", Name: "WEB"}, + {Name: "web", Kind: "static"}, + } { + m := New(nil, nil, "") + m.SetHostLabel(cfg.HostLabel) + m.updateListItems([]netbox.HostEntry{{Source: "office", Name: "web"}, other}) + for _, entry := range m.list.Items() { + item := entry.(hostItem) + if item.Title() != item.name { + t.Fatalf("ambiguous label: %+v", item) + } + } + } +} diff --git a/internal/tui/model.go b/internal/tui/model.go index 0220bd2..ac387e2 100644 --- a/internal/tui/model.go +++ b/internal/tui/model.go @@ -63,14 +63,20 @@ type searchResultMsg struct { // --- list item --- type hostItem struct { - name string - id int - ip string - kind string - tags []string + label string // display only; name remains the canonical target + name string + id int + ip string + kind string + tags []string } -func (h hostItem) Title() string { return h.name } +func (h hostItem) Title() string { + if h.label != "" { + return h.label + } + return h.name +} func (h hostItem) Description() string { return fmt.Sprintf("%s [%s]", h.ip, h.kind) } func (h hostItem) FilterValue() string { return h.name } @@ -91,7 +97,7 @@ func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list. if d.marked[h.key()] { mark = "● " } - line := fmt.Sprintf(" %s%s %s", mark, h.name, lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip)) + line := fmt.Sprintf(" %s%s %s", mark, h.Title(), lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip)) if index == m.Index() { line = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("> " + strings.TrimPrefix(line, " ")) } @@ -181,7 +187,8 @@ type Model struct { editMode bool // Ctrl+E on the selected item forwardMode bool // Ctrl+T on the selected item marked map[string]bool // hostItem.key() of hosts marked with space - markOrder []string // targets in the order they were marked + hostLabel func(string) string + markOrder []string // targets in the order they were marked } func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts ...int) *Model { @@ -678,12 +685,27 @@ func (m *Model) updateListItems(entries []netbox.HostEntry) { f := parseFilter(m.filterInput.Value()) filtered := applyFilter(entries, f) items := make([]list.Item, len(filtered)) + labels := make([]string, len(filtered)) + counts := make(map[string]int, len(filtered)) + canonical := make(map[string]bool, len(filtered)) + for i, e := range filtered { + labels[i] = e.Target() + canonical[strings.ToLower(e.Target())] = true + if m.hostLabel != nil { + labels[i] = m.hostLabel(e.Target()) + } + counts[strings.ToLower(labels[i])]++ + } for i, e := range filtered { ip := e.PrimaryIP4 if ip == "" { ip = e.PrimaryIP6 } - items[i] = hostItem{id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags} + label := labels[i] + if label != e.Target() && (counts[strings.ToLower(label)] > 1 || canonical[strings.ToLower(label)]) { + label = e.Target() + } + items[i] = hostItem{label: label, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags} } m.list.SetItems(items) m.resizeList() @@ -819,3 +841,9 @@ func parseForwards(input string, available []string) ([]string, error) { } return fields, nil } + +// SetHostLabel sets the display name formatter without changing host identity. +// Configure it before the program starts, just like SetNotes and SetForwards. +func (m *Model) SetHostLabel(format func(string) string) { + m.hostLabel = format +}