Files
ssh-netbox-wrapper/internal/config/config.go
T
Sebastian UnterschützandClaude Opus 5.5 5c41a5eb6f feat(config): add links and dns settings
- links: short names mapped to host selectors, validated against chains
  and static host names
- dns.suggest / dns.save_link: ask, always or never
- dns.domains: domain rules per name pattern (mx* -> easysahre.de)
- the wizard edits the dns settings under Resolver & cache and keeps links;
  setup.SaveTo reports to a chosen writer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 13:07:08 +01:00

298 lines
10 KiB
Go

package config
import (
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/spf13/viper"
)
type Config struct {
TUI TUIConfig `mapstructure:"tui"`
Activity ActivityConfig `mapstructure:"activity"`
Commands map[string]HostCommand `mapstructure:"commands"`
Shell ShellConfig `mapstructure:"shell"`
NetBox NetBoxConfig `mapstructure:"netbox"`
NetBoxes []NetBoxConfig `mapstructure:"netboxes"`
Resolver ResolverConfig `mapstructure:"resolver"`
Cache CacheConfig `mapstructure:"cache"`
SSH SSHConfig `mapstructure:"ssh"`
Shortcuts ShortcutsConfig `mapstructure:"shortcuts"`
Completion CompletionConfig `mapstructure:"completion"`
Hosts []StaticHost `mapstructure:"hosts"`
// Groups name lists of hosts and selectors for netssh multi (@name).
Groups map[string][]string `mapstructure:"groups"`
// Links map a short name to a host selector: netssh NAME connects to it,
// and the shell gets an alias NAME. Created after a DNS suggestion or
// with netssh link add.
Links map[string]string `mapstructure:"links"`
DNS DNSConfig `mapstructure:"dns"`
Multi MultiConfig `mapstructure:"multi"`
}
type ShellConfig struct {
Alias string `mapstructure:"alias"`
}
type NetBoxConfig struct {
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 {
// 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"`
// HostnameDomain is appended by the hostname strategy to names without a dot.
HostnameDomain string `mapstructure:"hostname_domain"`
}
type CacheConfig struct {
TTL int `mapstructure:"ttl"`
Path string `mapstructure:"path"`
}
type SSHConfig struct {
DefaultUser string `mapstructure:"default_user"`
DefaultPort int `mapstructure:"default_port"`
// 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 {
// MaxResults limits the number of hostnames offered per completion; 0 = unlimited.
MaxResults int `mapstructure:"max_results"`
}
type ShortcutsConfig struct {
Domains []string `mapstructure:"domains"`
StripHyphens bool `mapstructure:"strip_hyphens"`
Rewrites []ShortcutRewrite `mapstructure:"rewrites"`
// Show displays each host's shortcut alias in the TUI and in host lists, and
// offers shortcuts in Tab completion even when the full name matches.
Show bool `mapstructure:"show"`
}
// ShortcutRewrite replaces every match of Pattern (Go regexp syntax) with
// Replace, which may reference groups as $1. Applied after domain stripping.
type ShortcutRewrite struct {
Pattern string `mapstructure:"pattern"`
Replace string `mapstructure:"replace"`
}
// Enabled reports whether any shortcut normalization is configured.
func (s ShortcutsConfig) Enabled() bool {
return len(s.Domains) > 0 || s.StripHyphens || len(s.Rewrites) > 0
}
// Validate rejects rewrite rules that cannot be compiled.
func (s ShortcutsConfig) Validate() error {
for i, rewrite := range s.Rewrites {
if rewrite.Pattern == "" {
return fmt.Errorf("shortcuts.rewrites[%d]: pattern is required", i)
}
if _, err := regexp.Compile(rewrite.Pattern); err != nil {
return fmt.Errorf("shortcuts.rewrites[%d]: invalid pattern %q: %v", i, rewrite.Pattern, err)
}
}
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()
if err != nil {
configDir = filepath.Join(os.Getenv("HOME"), ".config")
}
return filepath.Join(configDir, "netssh.yaml")
}
func Load() (*Config, error) {
v := viper.New()
v.SetDefault("resolver.strategies", []string{"management_subnet", "primary_ip"})
v.SetDefault("resolver.management_subnets", []string{})
v.SetDefault("cache.ttl", 3600)
v.SetDefault("tui.history_limit", 10)
v.SetDefault("activity.retention_days", 30)
v.SetDefault("activity.max_entries", 1000)
configDir, err := os.UserConfigDir()
if err == nil {
v.SetConfigName("netssh")
v.SetConfigType("yaml")
// Only the user's own directory: a netssh.yaml in the working directory
// (e.g. of a cloned repository) could inject ssh options and a NetBox URL.
v.AddConfigPath(configDir)
}
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", "ssh.warn_status", "tui.columns", "tui.reachability_timeout", "resolver.fallback", "resolver.fallback_timeout", "dns.suggest", "dns.save_link"} {
if err := v.BindEnv(key); err != nil {
return nil, err
}
}
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); !ok {
return nil, fmt.Errorf("reading config: %w", err)
}
}
var cfg Config
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") {
cfg.NetBox = NetBoxConfig{}
}
if err := ValidateCommandAlias(cfg.Shell.Alias); err != nil {
return nil, err
}
if cfg.NetBox.TokenVersion == 0 && cfg.NetBox.Token != "" && !IsKeyringToken(cfg.NetBox.Token) {
if strings.HasPrefix(cfg.NetBox.Token, "nbt_") {
cfg.NetBox.TokenVersion = 2
} else {
cfg.NetBox.TokenVersion = 1
}
}
if err := cfg.ValidateNetBoxes(); err != nil {
return nil, err
}
if err := cfg.ValidateSSH(); err != nil {
return nil, err
}
if err := cfg.Shortcuts.Validate(); err != nil {
return nil, err
}
if err := cfg.ValidateHosts(); err != nil {
return nil, err
}
if err := cfg.ValidateLinks(); err != nil {
return nil, err
}
if err := cfg.ValidateDNS(); err != nil {
return nil, err
}
if err := cfg.ValidateOperations(); err != nil {
return nil, err
}
if err := cfg.ValidateCommands(); err != nil {
return nil, err
}
if err := cfg.ValidateMulti(); err != nil {
return nil, err
}
for i := range cfg.NetBoxes {
source := &cfg.NetBoxes[i]
source.Name = strings.ToLower(source.Name)
if source.TokenVersion == 0 && source.Token != "" && !IsKeyringToken(source.Token) {
source.TokenVersion = 1
if strings.HasPrefix(source.Token, "nbt_") {
source.TokenVersion = 2
}
}
}
if cfg.Cache.Path == "" {
cacheDir, err := os.UserCacheDir()
if err != nil {
cacheDir = filepath.Join(os.Getenv("HOME"), ".cache")
}
cfg.Cache.Path = filepath.Join(cacheDir, "netssh", "hosts.json")
}
return &cfg, nil
}
// ValidateCommandAlias restricts aliases to portable shell identifiers.
func ValidateCommandAlias(name string) error {
if name == "" {
return nil
}
if !regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`).MatchString(name) {
return fmt.Errorf("shell.alias must be a shell identifier (e.g. j)")
}
switch name {
case "netssh", "alias", "unalias", "source", "eval", "exec", "command", "builtin", "if", "then", "else", "elif", "fi", "for", "while", "until", "do", "done", "case", "esac", "in", "function", "select", "time", "coproc", "end", "begin", "switch", "set", "export", "return", "break", "continue", "not", "and", "or":
return fmt.Errorf("shell.alias %q is reserved; choose another name", name)
}
return nil
}