feat: NetBox insights, host tools and configurable TUI
Test / test (pull_request) Successful in 4m15s

- info/open/whois: NetBox details (site, nested locations, rack units,
  role, platform, tenant, IPs per interface), web page, reverse IP lookup
- cache status, site, role, platform, tenant, location chain and rack;
  ask before connecting to hosts in ssh.warn_status (--force skips)
- ssh rules and command restrictions match site/role/platform/tenant/status
- tui.columns selects what the TUI shows; optional TCP reachability column;
  detail view (Ctrl+L), NetBox page (Ctrl+G), status/location filters
- resolver.fallback tries other strategies' addresses when unreachable
- copy-id, known-hosts reset and address-change notices
- export ansible (YAML/INI) and export ssh-config
- token: keyring stores NetBox tokens in the system keyring
- fix stale menu number in testenv configure test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-18 12:33:59 +01:00
1 parent e5bde9c61f
commit 1660bb3098
39 files changed
+4868 -96

No files matched your search

+67 -5
View File
@@ -6,6 +6,7 @@ import (
"path/filepath"
"regexp"
"strings"
"time"
"github.com/spf13/viper"
)
@@ -42,6 +43,11 @@ type NetBoxConfig struct {
}
type ResolverConfig struct {
// Fallback tries the addresses of the other strategies when the chosen
// address does not accept TCP connections on the SSH port.
Fallback bool `mapstructure:"fallback"`
// FallbackTimeout is the per-address connect timeout in milliseconds; 0 = 1000.
FallbackTimeout int `mapstructure:"fallback_timeout"`
Strategies []string `mapstructure:"strategies"`
ManagementSubnets []string `mapstructure:"management_subnets"`
InterfaceName string `mapstructure:"interface_name"`
@@ -57,8 +63,11 @@ type CacheConfig struct {
type SSHConfig struct {
DefaultUser string `mapstructure:"default_user"`
DefaultPort int `mapstructure:"default_port"`
SSHOptions `mapstructure:",squash"`
Rules []SSHRule `mapstructure:"rules"`
// WarnStatus lists NetBox status values that ask before connecting;
// nil means DefaultWarnStatus, an empty list disables the question.
WarnStatus []string `mapstructure:"warn_status"`
SSHOptions `mapstructure:",squash"`
Rules []SSHRule `mapstructure:"rules"`
}
type CompletionConfig struct {
@@ -100,6 +109,51 @@ func (s ShortcutsConfig) Validate() error {
return nil
}
// DefaultWarnStatus are the NetBox status values that ask before connecting.
var DefaultWarnStatus = []string{"offline", "planned", "staged", "failed", "inventory", "decommissioning"}
// KeyringToken as a token value reads the token from the system keyring.
const KeyringToken = "keyring"
// IsKeyringToken reports whether token refers to the system keyring.
func IsKeyringToken(token string) bool {
return strings.EqualFold(strings.TrimSpace(token), KeyringToken)
}
// KeyringAccount is the keyring entry of a NetBox instance; the unnamed
// single-instance configuration uses "default".
func (n NetBoxConfig) KeyringAccount() string {
if n.Name == "" {
return "default"
}
return strings.ToLower(n.Name)
}
// WarnsStatus reports whether status is configured to ask before connecting.
func (s SSHConfig) WarnsStatus(status string) bool {
if status == "" {
return false
}
list := s.WarnStatus
if list == nil {
list = DefaultWarnStatus
}
for _, warn := range list {
if strings.EqualFold(strings.TrimSpace(warn), status) {
return true
}
}
return false
}
// FallbackTimeoutDuration returns resolver.fallback_timeout, 1s by default.
func (r ResolverConfig) FallbackTimeoutDuration() time.Duration {
if r.FallbackTimeout <= 0 {
return time.Second
}
return time.Duration(r.FallbackTimeout) * time.Millisecond
}
// Path returns the canonical config file path.
func Path() string {
configDir, err := os.UserConfigDir()
@@ -131,7 +185,7 @@ func Load() (*Config, error) {
v.SetEnvPrefix("NETSSH")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
for _, key := range []string{"netbox.url", "netbox.token", "netbox.token_version", "resolver.strategies", "resolver.management_subnets", "resolver.interface_name", "resolver.hostname_domain", "cache.ttl", "cache.path", "ssh.default_user", "ssh.default_port", "shortcuts.domains", "shortcuts.strip_hyphens", "shortcuts.show", "shell.alias", "ssh.proxy_jump", "ssh.pre_connect", "ssh.post_disconnect", "tui.history_limit", "activity.enabled", "activity.retention_days", "activity.max_entries", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window"} {
for _, key := range []string{"netbox.url", "netbox.token", "netbox.token_version", "resolver.strategies", "resolver.management_subnets", "resolver.interface_name", "resolver.hostname_domain", "cache.ttl", "cache.path", "ssh.default_user", "ssh.default_port", "shortcuts.domains", "shortcuts.strip_hyphens", "shortcuts.show", "shell.alias", "ssh.proxy_jump", "ssh.pre_connect", "ssh.post_disconnect", "tui.history_limit", "activity.enabled", "activity.retention_days", "activity.max_entries", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window", "ssh.warn_status", "tui.columns", "tui.reachability_timeout", "resolver.fallback", "resolver.fallback_timeout"} {
if err := v.BindEnv(key); err != nil {
return nil, err
}
@@ -147,6 +201,14 @@ func Load() (*Config, error) {
if err := v.Unmarshal(&cfg); err != nil {
return nil, fmt.Errorf("parsing config: %w", err)
}
// "columns: []" shows only the hostname; only a missing key means the default.
if cfg.TUI.Columns == nil && v.IsSet("tui.columns") {
cfg.TUI.Columns = []string{}
}
// "warn_status: []" disables the question; only a missing key means the default.
if cfg.SSH.WarnStatus == nil && v.IsSet("ssh.warn_status") {
cfg.SSH.WarnStatus = []string{}
}
// Legacy environment variables must not invent an additional unnamed source
// when a file explicitly configures named instances (including wizard migration).
if len(cfg.NetBoxes) > 0 && !v.InConfig("netbox.url") {
@@ -157,7 +219,7 @@ func Load() (*Config, error) {
return nil, err
}
if cfg.NetBox.TokenVersion == 0 && cfg.NetBox.Token != "" {
if cfg.NetBox.TokenVersion == 0 && cfg.NetBox.Token != "" && !IsKeyringToken(cfg.NetBox.Token) {
if strings.HasPrefix(cfg.NetBox.Token, "nbt_") {
cfg.NetBox.TokenVersion = 2
} else {
@@ -189,7 +251,7 @@ func Load() (*Config, error) {
for i := range cfg.NetBoxes {
source := &cfg.NetBoxes[i]
source.Name = strings.ToLower(source.Name)
if source.TokenVersion == 0 && source.Token != "" {
if source.TokenVersion == 0 && source.Token != "" && !IsKeyringToken(source.Token) {
source.TokenVersion = 1
if strings.HasPrefix(source.Token, "nbt_") {
source.TokenVersion = 2
+108
View File
@@ -0,0 +1,108 @@
package config
import (
"os"
"strings"
"testing"
)
func TestSSHRuleMatchesNetBoxAttributes(t *testing.T) {
host := SSHHost{Name: "sw1", Kind: "device", Status: "active",
Site: Ref{Name: "Falkenstein 1", Slug: "fsn1"}, Role: Ref{Name: "Core Switch", Slug: "core-switch"},
Platform: Ref{Name: "Juniper Junos", Slug: "junos"}, Tenant: Ref{Name: "ACME"}}
for _, tc := range []struct {
match SSHMatch
want bool
}{
{SSHMatch{Platform: "junos"}, true},
{SSHMatch{Platform: "juniper junos"}, true},
{SSHMatch{Platform: "eos"}, false},
{SSHMatch{Site: "fsn1", Role: "core-switch"}, true},
{SSHMatch{Role: "Core Switch"}, true},
{SSHMatch{Site: "falkenstein-1"}, true},
{SSHMatch{Tenant: "acme"}, true},
{SSHMatch{Status: "ACTIVE"}, true},
{SSHMatch{Status: "offline"}, false},
{SSHMatch{Platform: "junos", Kind: "vm"}, false},
} {
if got := tc.match.matches(host); got != tc.want {
t.Errorf("%+v: got %v, want %v", tc.match, got, tc.want)
}
}
if err := (SSHMatch{Platform: "junos"}).Validate("rule"); err != nil {
t.Fatalf("platform-only match rejected: %v", err)
}
}
func TestSSHOptionsForPlatformRule(t *testing.T) {
cfg := &Config{SSH: SSHConfig{Rules: []SSHRule{{Match: SSHMatch{Platform: "junos"}, SSHOptions: SSHOptions{Options: map[string]string{"KexAlgorithms": "+diffie-hellman-group14-sha1"}}}}}}
opts := cfg.SSHOptionsFor(SSHHost{Name: "sw1", Kind: "device", Platform: Ref{Slug: "junos"}})
if opts.Options["kexalgorithms"] != "+diffie-hellman-group14-sha1" {
t.Fatalf("platform rule not applied: %+v", opts.Options)
}
if opts := cfg.SSHOptionsFor(SSHHost{Name: "web", Kind: "vm"}); len(opts.Options) != 0 {
t.Fatalf("rule applied to other platform: %+v", opts.Options)
}
}
func TestWarnStatusDefaultsAndOverrides(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\n"))
if cfg.SSH.WarnStatus != nil || !cfg.SSH.WarnsStatus("offline") || cfg.SSH.WarnsStatus("active") || cfg.SSH.WarnsStatus("") {
t.Fatalf("default warn_status wrong: %#v", cfg.SSH.WarnStatus)
}
cfg = loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\nssh:\n warn_status: []\n"))
if cfg.SSH.WarnStatus == nil || cfg.SSH.WarnsStatus("offline") {
t.Fatalf("empty warn_status should disable the question: %#v", cfg.SSH.WarnStatus)
}
cfg = loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\nssh:\n warn_status: [planned]\n"))
if !cfg.SSH.WarnsStatus("Planned") || cfg.SSH.WarnsStatus("offline") {
t.Fatalf("custom warn_status wrong: %#v", cfg.SSH.WarnStatus)
}
}
func TestReachabilityAndFallbackDefaults(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\n"))
if cfg.TUI.ReachabilityEnabled() || cfg.TUI.ReachabilityTimeoutDuration().Milliseconds() != 300 {
t.Fatalf("reachability must be opt-in: %+v", cfg.TUI)
}
if strings.Join(cfg.TUI.EffectiveColumns(), ",") != "alias,ip,source,status" {
t.Fatalf("default columns: %v", cfg.TUI.EffectiveColumns())
}
if cfg.Resolver.Fallback || cfg.Resolver.FallbackTimeoutDuration().Milliseconds() != 1000 {
t.Fatalf("fallback defaults wrong: %+v", cfg.Resolver)
}
cfg = loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\ntui:\n columns: [Reachability, ip, platform]\n reachability_timeout: 800\nresolver:\n fallback: true\n fallback_timeout: 250\n"))
if !cfg.TUI.ReachabilityEnabled() || cfg.TUI.ReachabilityTimeoutDuration().Milliseconds() != 800 || strings.Join(cfg.TUI.Columns, ",") != "reachability,ip,platform" {
t.Fatalf("reachability settings ignored: %+v", cfg.TUI)
}
if !cfg.Resolver.Fallback || cfg.Resolver.FallbackTimeoutDuration().Milliseconds() != 250 {
t.Fatalf("fallback settings ignored: %+v", cfg.Resolver)
}
}
func TestKeyringTokenKeepsVersionUndetected(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\n token: keyring\nnetboxes: []\n"))
if !IsKeyringToken(cfg.NetBox.Token) || cfg.NetBox.TokenVersion != 0 {
t.Fatalf("keyring token treated as literal: %+v", cfg.NetBox)
}
if cfg.NetBox.KeyringAccount() != "default" || (NetBoxConfig{Name: "Prod"}).KeyringAccount() != "prod" {
t.Fatal("unexpected keyring account names")
}
}
func TestTUIColumnsValidation(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\ntui:\n columns: []\n"))
if cfg.TUI.Columns == nil || len(cfg.TUI.EffectiveColumns()) != 0 {
t.Fatalf("empty columns should show only the hostname: %#v", cfg.TUI.Columns)
}
for _, bad := range []string{"[ip, colour]", "[ip, ip]"} {
dir := writeConfig(t, "netbox:\n url: https://nb\ntui:\n columns: "+bad+"\n")
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
_, err := Load()
os.Setenv("XDG_CONFIG_HOME", orig)
if err == nil || !strings.Contains(err.Error(), "tui.columns") {
t.Errorf("%s accepted: %v", bad, err)
}
}
}
+67
View File
@@ -3,11 +3,51 @@ package config
import (
"fmt"
"strings"
"time"
)
type TUIConfig struct {
HistoryLimit int `mapstructure:"history_limit"`
// Columns selects what the TUI shows next to each hostname, in order;
// nil means DefaultTUIColumns. "reachability" enables the TCP check.
Columns []string `mapstructure:"columns"`
// ReachabilityTimeout is the probe timeout in milliseconds; 0 = 300.
ReachabilityTimeout int `mapstructure:"reachability_timeout"`
}
// TUIColumns are the values tui.columns accepts.
var TUIColumns = []string{"alias", "ip", "kind", "source", "status", "site", "location", "role", "platform", "tenant", "cluster", "tags", "reachability"}
// DefaultTUIColumns is the layout without tui.columns. The TCP reachability
// check is opt-in, since it opens connections to every listed host.
var DefaultTUIColumns = []string{"alias", "ip", "source", "status"}
// EffectiveColumns returns tui.columns, or the default layout.
func (t TUIConfig) EffectiveColumns() []string {
if t.Columns == nil {
return DefaultTUIColumns
}
return t.Columns
}
// ReachabilityEnabled reports whether the TUI probes listed hosts.
func (t TUIConfig) ReachabilityEnabled() bool {
for _, column := range t.EffectiveColumns() {
if column == "reachability" {
return true
}
}
return false
}
// ReachabilityTimeoutDuration returns tui.reachability_timeout, 300ms by default.
func (t TUIConfig) ReachabilityTimeoutDuration() time.Duration {
if t.ReachabilityTimeout <= 0 {
return 300 * time.Millisecond
}
return time.Duration(t.ReachabilityTimeout) * time.Millisecond
}
type ActivityConfig struct {
Enabled bool `mapstructure:"enabled"`
RetentionDays int `mapstructure:"retention_days"`
@@ -21,6 +61,33 @@ func (c *Config) ValidateOperations() error {
if c.Activity.RetentionDays < 0 || c.Activity.MaxEntries < 0 {
return fmt.Errorf("activity retention_days and max_entries must be >= 0")
}
seen := map[string]bool{}
for i, column := range c.TUI.Columns {
column = strings.ToLower(strings.TrimSpace(column))
c.TUI.Columns[i] = column
known := false
for _, valid := range TUIColumns {
known = known || column == valid
}
if !known {
return fmt.Errorf("tui.columns: unknown column %q; use %s", column, strings.Join(TUIColumns, ", "))
}
if seen[column] {
return fmt.Errorf("tui.columns: %q is listed twice", column)
}
seen[column] = true
}
if c.TUI.ReachabilityTimeout < 0 || c.TUI.ReachabilityTimeout > 10000 {
return fmt.Errorf("tui.reachability_timeout must be between 0 and 10000 milliseconds")
}
if c.Resolver.FallbackTimeout < 0 || c.Resolver.FallbackTimeout > 30000 {
return fmt.Errorf("resolver.fallback_timeout must be between 0 and 30000 milliseconds")
}
for _, status := range c.SSH.WarnStatus {
if strings.TrimSpace(status) == "" || strings.ContainsAny(status, " \t\n") {
return fmt.Errorf("ssh.warn_status: invalid status %q", status)
}
}
return nil
}
func (m SSHMatch) Matches(host SSHHost) bool { return m == (SSHMatch{}) || m.matches(host) }
+68 -1
View File
@@ -94,6 +94,57 @@ type SSHMatch struct {
Instance string `mapstructure:"instance"`
Kind string `mapstructure:"kind"`
Name string `mapstructure:"name"` // shell-style glob, e.g. "*.dmz.example.com"
// Site, Role, Platform and Tenant match the NetBox name or slug.
Site string `mapstructure:"site"`
Role string `mapstructure:"role"`
Platform string `mapstructure:"platform"`
Tenant string `mapstructure:"tenant"`
// Status matches the NetBox status value, e.g. active or offline.
Status string `mapstructure:"status"`
}
// Ref is a NetBox object referenced by a host, such as its site or platform.
type Ref struct {
Name string `json:"name,omitempty"`
Slug string `json:"slug,omitempty"`
}
// Matches compares want with the name or slug, ignoring case.
func (r Ref) Matches(want string) bool {
return want != "" && (strings.EqualFold(r.Name, want) || strings.EqualFold(r.Slug, want) || strings.EqualFold(tagSlug(r.Name), want))
}
// Key returns the slug, or the name when NetBox sent no slug.
func (r Ref) Key() string {
if r.Slug != "" {
return r.Slug
}
return r.Name
}
// LocationPath renders a host's place as "site › location › … › rack › U20",
// leaving out levels that are not set.
func LocationPath(site Ref, locations []Ref, rack, position string) string {
var parts []string
if site.Name != "" {
parts = append(parts, site.Name)
} else if site.Slug != "" {
parts = append(parts, site.Slug)
}
for _, location := range locations {
if location.Name != "" {
parts = append(parts, location.Name)
} else if location.Slug != "" {
parts = append(parts, location.Slug)
}
}
if rack != "" {
parts = append(parts, rack)
}
if position != "" {
parts = append(parts, "U"+position)
}
return strings.Join(parts, " › ")
}
// SSHHost identifies the resolved host that SSH options are computed for.
@@ -102,6 +153,11 @@ type SSHHost struct {
Name string // NetBox name without the instance prefix
Kind string
Tags []string
Status string
Site Ref
Role Ref
Platform Ref
Tenant Ref
}
var sshOptionKey = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`)
@@ -138,7 +194,7 @@ func (r SSHRule) Validate(scope string) error {
// Validate requires at least one selector and a well-formed name pattern.
func (m SSHMatch) Validate(scope string) error {
if m == (SSHMatch{}) {
return fmt.Errorf("%s: match must set at least one of tag, instance, kind, name", scope)
return fmt.Errorf("%s: match must set at least one of tag, instance, kind, name, site, role, platform, tenant, status", scope)
}
if _, err := path.Match(m.Name, ""); err != nil {
return fmt.Errorf("%s: invalid name pattern %q", scope, m.Name)
@@ -264,6 +320,17 @@ func (m SSHMatch) matches(host SSHHost) bool {
return false
}
}
for _, ref := range []struct {
want string
have Ref
}{{m.Site, host.Site}, {m.Role, host.Role}, {m.Platform, host.Platform}, {m.Tenant, host.Tenant}} {
if ref.want != "" && !ref.have.Matches(ref.want) {
return false
}
}
if m.Status != "" && !strings.EqualFold(m.Status, host.Status) {
return false
}
if m.Tag != "" {
found := false
for _, tag := range host.Tags {