feat: add host actions, lifecycle hooks and operational tools
Test / test (push) Successful in 4m4s
Release / release (push) Successful in 7m39s

This commit is contained in:
Sebastian Unterschütz committed 2026-11-18 10:41:36 +01:00
1 parent 8d4915543e
commit e5bde9c61f
32 files changed
+2083 -64

No files matched your search

+19
View File
@@ -4,10 +4,15 @@ import (
"fmt"
"regexp"
"strings"
"time"
)
// HostCommand defines a local command and the prefix of its generated host aliases.
type HostCommand struct {
PostRun string `mapstructure:"post_run"`
Match SSHMatch `mapstructure:"match"`
Confirm bool `mapstructure:"confirm"`
Timeout string `mapstructure:"timeout"`
AliasPrefix string `mapstructure:"alias_prefix" yaml:"alias_prefix"`
Args []string `mapstructure:"args" yaml:"args"`
}
@@ -15,6 +20,20 @@ type HostCommand struct {
func (c *Config) ValidateCommands() error {
prefixes := make(map[string]bool)
for name, command := range c.Commands {
if strings.ContainsRune(command.PostRun, 0) {
return fmt.Errorf("commands.%s.post_run contains NUL", name)
}
if command.Match != (SSHMatch{}) {
if err := command.Match.Validate("commands." + name); err != nil {
return err
}
}
if command.Timeout != "" {
d, err := time.ParseDuration(command.Timeout)
if err != nil || d <= 0 {
return fmt.Errorf("commands.%s.timeout requires a positive duration", name)
}
}
if name == "" || ValidateCommandAlias(name) != nil {
return fmt.Errorf("commands.%s: name must be a non-reserved shell identifier", name)
}
+9 -1
View File
@@ -11,6 +11,8 @@ import (
)
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"`
@@ -113,6 +115,9 @@ func Load() (*Config, error) {
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 {
@@ -126,7 +131,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.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"} {
if err := v.BindEnv(key); err != nil {
return nil, err
}
@@ -172,6 +177,9 @@ func Load() (*Config, error) {
if err := cfg.ValidateHosts(); err != nil {
return nil, err
}
if err := cfg.ValidateOperations(); err != nil {
return nil, err
}
if err := cfg.ValidateCommands(); err != nil {
return nil, err
}
+34
View File
@@ -0,0 +1,34 @@
package config
import (
"fmt"
"strings"
)
type TUIConfig struct {
HistoryLimit int `mapstructure:"history_limit"`
}
type ActivityConfig struct {
Enabled bool `mapstructure:"enabled"`
RetentionDays int `mapstructure:"retention_days"`
MaxEntries int `mapstructure:"max_entries"`
}
func (c *Config) ValidateOperations() error {
if c.TUI.HistoryLimit < 0 {
return fmt.Errorf("tui.history_limit must be >= 0 (0 = all)")
}
if c.Activity.RetentionDays < 0 || c.Activity.MaxEntries < 0 {
return fmt.Errorf("activity retention_days and max_entries must be >= 0")
}
return nil
}
func (m SSHMatch) Matches(host SSHHost) bool { return m == (SSHMatch{}) || m.matches(host) }
func (c HostCommand) Allowed(host SSHHost) bool { return c.Match.Matches(host) }
func HookCommand(s string) string {
s = strings.TrimSpace(s)
if strings.EqualFold(s, "none") {
return ""
}
return s
}
+55
View File
@@ -0,0 +1,55 @@
package config
import (
"os"
"path/filepath"
"testing"
)
func TestOperationsDefaultsEnvironmentAndValidation(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := os.WriteFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml"), []byte("hosts:\n - name: router\n address: 192.0.2.1\n"), 0600); err != nil {
t.Fatal(err)
}
cfg, err := Load()
if err != nil {
t.Fatal(err)
}
if cfg.TUI.HistoryLimit != 10 || cfg.Activity.Enabled || cfg.Activity.RetentionDays != 30 || cfg.Activity.MaxEntries != 1000 {
t.Fatalf("%+v %+v", cfg.TUI, cfg.Activity)
}
t.Setenv("NETSSH_TUI_HISTORY_LIMIT", "25")
t.Setenv("NETSSH_SSH_POST_DISCONNECT", "echo done")
cfg, err = Load()
if err != nil || cfg.TUI.HistoryLimit != 25 || cfg.SSH.PostDisconnect != "echo done" {
t.Fatalf("%+v %v", cfg, err)
}
cfg.TUI.HistoryLimit = -1
if cfg.ValidateOperations() == nil {
t.Fatal("negative history accepted")
}
for _, timeout := range []string{"-1s", "0s", "invalid"} {
cfg.Commands = map[string]HostCommand{"check": {Args: []string{"echo", "{host}"}, Timeout: timeout}}
if cfg.ValidateCommands() == nil {
t.Fatalf("accepted %q", timeout)
}
}
}
func TestPostDisconnectLayering(t *testing.T) {
cfg := Config{
SSH: SSHConfig{SSHOptions: SSHOptions{PostDisconnect: "global"}, Rules: []SSHRule{{Match: SSHMatch{Tag: "lab"}, SSHOptions: SSHOptions{PostDisconnect: "none"}}}},
NetBoxes: []NetBoxConfig{{Name: "prod", SSH: SSHOptions{PostDisconnect: "instance"}}},
}
for _, tc := range []struct {
host SSHHost
want string
}{
{SSHHost{Name: "web"}, "global"},
{SSHHost{Name: "web", Instance: "prod"}, "instance"},
{SSHHost{Name: "web", Instance: "prod", Tags: []string{"lab"}}, ""},
} {
if got := HookCommand(cfg.SSHOptionsFor(tc.host).PostDisconnect); got != tc.want {
t.Fatalf("%q want %q", got, tc.want)
}
}
}
+8 -1
View File
@@ -26,7 +26,8 @@ type SSHOptions struct {
Forwards map[string]Forward `mapstructure:"forwards"`
// PreConnect is a shell command run locally before connecting; a non-zero
// exit aborts the connection. "none" disables a hook set by a broader layer.
PreConnect string `mapstructure:"pre_connect"`
PreConnect string `mapstructure:"pre_connect"`
PostDisconnect string `mapstructure:"post_disconnect"`
}
// PreConnectNone disables an inherited pre_connect hook.
@@ -170,6 +171,9 @@ func (o SSHOptions) Validate(scope string) error {
return fmt.Errorf("%s.options: invalid option %q", scope, key)
}
}
if strings.ContainsRune(o.PostDisconnect, 0) {
return fmt.Errorf("%s.post_disconnect must not contain NUL bytes", scope)
}
if strings.ContainsRune(o.PreConnect, 0) {
return fmt.Errorf("%s.pre_connect must not contain NUL bytes", scope)
}
@@ -239,6 +243,9 @@ func (o SSHOptions) merge(override SSHOptions) SSHOptions {
if override.AddressFamily != "" {
out.AddressFamily = override.AddressFamily
}
if strings.TrimSpace(override.PostDisconnect) != "" {
out.PostDisconnect = override.PostDisconnect
}
if strings.TrimSpace(override.PreConnect) != "" {
out.PreConnect = override.PreConnect
}