v1
This commit is contained in:
commit
8d4915543e
132 files changed
+20628
No files matched your search
@@ -0,0 +1,54 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// HostCommand defines a local command and the prefix of its generated host aliases.
|
||||
type HostCommand struct {
|
||||
AliasPrefix string `mapstructure:"alias_prefix" yaml:"alias_prefix"`
|
||||
Args []string `mapstructure:"args" yaml:"args"`
|
||||
}
|
||||
|
||||
func (c *Config) ValidateCommands() error {
|
||||
prefixes := make(map[string]bool)
|
||||
for name, command := range c.Commands {
|
||||
if name == "" || ValidateCommandAlias(name) != nil {
|
||||
return fmt.Errorf("commands.%s: name must be a non-reserved shell identifier", name)
|
||||
}
|
||||
if command.AliasPrefix != "" {
|
||||
if !regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`).MatchString(command.AliasPrefix) {
|
||||
return fmt.Errorf("commands.%s.alias_prefix must be a shell identifier", name)
|
||||
}
|
||||
if prefixes[command.AliasPrefix] {
|
||||
return fmt.Errorf("commands.%s: duplicate alias_prefix %q", name, command.AliasPrefix)
|
||||
}
|
||||
prefixes[command.AliasPrefix] = true
|
||||
}
|
||||
if len(command.Args) == 0 || strings.TrimSpace(command.Args[0]) == "" {
|
||||
return fmt.Errorf("commands.%s.args requires an executable", name)
|
||||
}
|
||||
target := false
|
||||
for i, arg := range command.Args {
|
||||
if strings.ContainsRune(arg, 0) {
|
||||
return fmt.Errorf("commands.%s.args cannot contain NUL", name)
|
||||
}
|
||||
if i == 0 && strings.ContainsAny(arg, "{}") {
|
||||
return fmt.Errorf("commands.%s: executable cannot contain placeholders", name)
|
||||
}
|
||||
if strings.Contains(arg, "{host}") || strings.Contains(arg, "{address}") || strings.Contains(arg, "{target}") {
|
||||
target = true
|
||||
}
|
||||
rest := strings.NewReplacer("{host}", "", "{address}", "", "{target}", "").Replace(arg)
|
||||
if strings.ContainsAny(rest, "{}") {
|
||||
return fmt.Errorf("commands.%s: supported placeholders are {host}, {address}, {target}", name)
|
||||
}
|
||||
}
|
||||
if !target {
|
||||
return fmt.Errorf("commands.%s.args requires {host}, {address}, or {target}", name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package config
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidateCommands(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
command HostCommand
|
||||
valid bool
|
||||
}{
|
||||
{"mtr", HostCommand{AliasPrefix: "m", Args: []string{"mtr", "{address}"}}, true},
|
||||
{"ping", HostCommand{Args: []string{"ping", "-c", "3", "{host}"}}, true},
|
||||
{"inspect", HostCommand{Args: []string{"echo", "{target}"}}, true},
|
||||
{"", HostCommand{Args: []string{"echo", "{host}"}}, false},
|
||||
{"bad name", HostCommand{Args: []string{"echo", "{host}"}}, false},
|
||||
{"netssh", HostCommand{Args: []string{"echo", "{host}"}}, false},
|
||||
{"bad", HostCommand{AliasPrefix: "m;", Args: []string{"mtr", "{address}"}}, false},
|
||||
{"bad", HostCommand{}, false},
|
||||
{"bad", HostCommand{Args: []string{"", "{host}"}}, false},
|
||||
{"bad", HostCommand{Args: []string{"{host}", "{address}"}}, false},
|
||||
{"bad", HostCommand{Args: []string{"mtr", "{adress}"}}, false},
|
||||
{"bad", HostCommand{Args: []string{"mtr"}}, false},
|
||||
{"bad", HostCommand{Args: []string{"mtr", "{host}\x00"}}, false},
|
||||
} {
|
||||
cfg := Config{Commands: map[string]HostCommand{tc.name: tc.command}}
|
||||
if err := cfg.ValidateCommands(); (err == nil) != tc.valid {
|
||||
t.Errorf("%+v: %v", tc, err)
|
||||
}
|
||||
}
|
||||
cfg := Config{Commands: map[string]HostCommand{
|
||||
"mtr": {AliasPrefix: "m", Args: []string{"mtr", "{address}"}},
|
||||
"ping": {AliasPrefix: "m", Args: []string{"ping", "{address}"}},
|
||||
}}
|
||||
if cfg.ValidateCommands() == nil {
|
||||
t.Fatal("duplicate prefixes accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
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"`
|
||||
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 {
|
||||
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"`
|
||||
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
|
||||
}
|
||||
|
||||
// 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)
|
||||
|
||||
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.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
|
||||
}
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
// 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 != "" {
|
||||
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.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 != "" {
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func writeConfig(t *testing.T, content string) string {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
path := filepath.Join(dir, "netssh.yaml")
|
||||
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return dir
|
||||
}
|
||||
|
||||
func loadFromDir(t *testing.T, dir string) *Config {
|
||||
t.Helper()
|
||||
// Override UserConfigDir by pointing viper at our temp dir via env isn't
|
||||
// straightforward, so we exercise Load() by temporarily changing XDG_CONFIG_HOME.
|
||||
orig := os.Getenv("XDG_CONFIG_HOME")
|
||||
os.Setenv("XDG_CONFIG_HOME", dir)
|
||||
t.Cleanup(func() { os.Setenv("XDG_CONFIG_HOME", orig) })
|
||||
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
return cfg
|
||||
}
|
||||
|
||||
func TestLoad_V2TokenVersion_Preserved(t *testing.T) {
|
||||
dir := writeConfig(t, `
|
||||
netbox:
|
||||
url: "https://netbox.example.com"
|
||||
token: "nbt_abc123"
|
||||
token_version: 2
|
||||
`)
|
||||
cfg := loadFromDir(t, dir)
|
||||
if cfg.NetBox.TokenVersion != 2 {
|
||||
t.Errorf("TokenVersion: got %d, want 2", cfg.NetBox.TokenVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_V1TokenVersion_Preserved(t *testing.T) {
|
||||
dir := writeConfig(t, `
|
||||
netbox:
|
||||
url: "https://netbox.example.com"
|
||||
token: "legacyhex123"
|
||||
token_version: 1
|
||||
`)
|
||||
cfg := loadFromDir(t, dir)
|
||||
if cfg.NetBox.TokenVersion != 1 {
|
||||
t.Errorf("TokenVersion: got %d, want 1", cfg.NetBox.TokenVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_AutoDetectsV2_WhenFieldMissing(t *testing.T) {
|
||||
dir := writeConfig(t, `
|
||||
netbox:
|
||||
url: "https://netbox.example.com"
|
||||
token: "nbt_mytoken"
|
||||
`)
|
||||
cfg := loadFromDir(t, dir)
|
||||
if cfg.NetBox.TokenVersion != 2 {
|
||||
t.Errorf("TokenVersion: got %d, want 2 (auto-detected from nbt_ prefix)", cfg.NetBox.TokenVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_AutoDetectsV1_WhenFieldMissing(t *testing.T) {
|
||||
dir := writeConfig(t, `
|
||||
netbox:
|
||||
url: "https://netbox.example.com"
|
||||
token: "abc123def456"
|
||||
`)
|
||||
cfg := loadFromDir(t, dir)
|
||||
if cfg.NetBox.TokenVersion != 1 {
|
||||
t.Errorf("TokenVersion: got %d, want 1 (auto-detected from plain token)", cfg.NetBox.TokenVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_TokenVersionZero_WhenNoToken(t *testing.T) {
|
||||
dir := writeConfig(t, `
|
||||
netbox:
|
||||
url: "https://netbox.example.com"
|
||||
`)
|
||||
cfg := loadFromDir(t, dir)
|
||||
if cfg.NetBox.TokenVersion != 0 {
|
||||
t.Errorf("TokenVersion: got %d, want 0 (no token present)", cfg.NetBox.TokenVersion)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_Defaults(t *testing.T) {
|
||||
dir := writeConfig(t, `
|
||||
netbox:
|
||||
url: "https://netbox.example.com"
|
||||
token: "nbt_x"
|
||||
`)
|
||||
cfg := loadFromDir(t, dir)
|
||||
|
||||
if cfg.Cache.TTL != 3600 {
|
||||
t.Errorf("default cache.ttl: got %d, want 3600", cfg.Cache.TTL)
|
||||
}
|
||||
if cfg.Cache.Path == "" {
|
||||
t.Error("cache.path should be auto-set when empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_MissingFile_ReturnsEmptyConfig(t *testing.T) {
|
||||
orig := os.Getenv("XDG_CONFIG_HOME")
|
||||
os.Setenv("XDG_CONFIG_HOME", t.TempDir()) // dir exists but no netssh.yaml
|
||||
defer os.Setenv("XDG_CONFIG_HOME", orig)
|
||||
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load on missing file should not error: %v", err)
|
||||
}
|
||||
if cfg.NetBox.URL != "" {
|
||||
t.Errorf("expected empty URL, got %q", cfg.NetBox.URL)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_InvalidYAML_ReturnsError(t *testing.T) {
|
||||
dir := writeConfig(t, "not: valid: yaml: [[[")
|
||||
orig := os.Getenv("XDG_CONFIG_HOME")
|
||||
os.Setenv("XDG_CONFIG_HOME", dir)
|
||||
defer os.Setenv("XDG_CONFIG_HOME", orig)
|
||||
|
||||
_, err := Load()
|
||||
if err == nil {
|
||||
t.Error("invalid YAML should return an error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPath_ReturnsNonEmpty(t *testing.T) {
|
||||
p := Path()
|
||||
if p == "" {
|
||||
t.Error("Path() should return a non-empty string")
|
||||
}
|
||||
if filepath.Base(p) != "netssh.yaml" {
|
||||
t.Errorf("Path() base: got %q, want netssh.yaml", filepath.Base(p))
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnvironmentOverridesWithoutConfigKeys(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("NETSSH_NETBOX_URL", "https://env.example")
|
||||
t.Setenv("NETSSH_NETBOX_TOKEN", "nbt_env")
|
||||
t.Setenv("NETSSH_SSH_DEFAULT_PORT", "2222")
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.NetBox.URL != "https://env.example" || cfg.NetBox.Token != "nbt_env" || cfg.NetBox.TokenVersion != 2 || cfg.SSH.DefaultPort != 2222 {
|
||||
t.Fatalf("env ignored: %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCommandAliasEnvironmentAndValidation(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("NETSSH_SHELL_ALIAS", "j")
|
||||
cfg, err := Load()
|
||||
if err != nil || cfg.Shell.Alias != "j" {
|
||||
t.Fatalf("alias env: %+v, %v", cfg, err)
|
||||
}
|
||||
for _, name := range []string{"netssh", "if", "alias", "j;touch /tmp/bad", "a b", "1bad"} {
|
||||
t.Setenv("NETSSH_SHELL_ALIAS", name)
|
||||
if _, err := Load(); err == nil {
|
||||
t.Errorf("unsafe alias accepted: %q", name)
|
||||
}
|
||||
}
|
||||
for _, name := range []string{"", "j", "jump_server", "goSSH"} {
|
||||
if err := ValidateCommandAlias(name); err != nil {
|
||||
t.Errorf("valid alias rejected: %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_ShortcutRewrites(t *testing.T) {
|
||||
dir := writeConfig(t, "shortcuts:\n rewrites:\n - pattern: '^([a-z]+)[0-9]+-'\n replace: '$1'\n")
|
||||
cfg := loadFromDir(t, dir)
|
||||
want := []ShortcutRewrite{{Pattern: `^([a-z]+)[0-9]+-`, Replace: "$1"}}
|
||||
if len(cfg.Shortcuts.Rewrites) != 1 || cfg.Shortcuts.Rewrites[0] != want[0] || !cfg.Shortcuts.Enabled() {
|
||||
t.Fatalf("rewrites: %+v", cfg.Shortcuts)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_InvalidShortcutRewrite(t *testing.T) {
|
||||
for _, rule := range []string{"pattern: '[a-'", "replace: x"} {
|
||||
t.Setenv("XDG_CONFIG_HOME", writeConfig(t, "shortcuts:\n rewrites:\n - "+rule+"\n"))
|
||||
if _, err := Load(); err == nil || !strings.Contains(err.Error(), "shortcuts.rewrites[0]") {
|
||||
t.Errorf("%s: got %v", rule, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A netssh.yaml in the working directory (e.g. of a cloned repository) must
|
||||
// not be loaded: it could inject ssh options such as ProxyCommand.
|
||||
func TestLoad_IgnoresConfigInWorkingDirectory(t *testing.T) {
|
||||
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
|
||||
t.Setenv("NETSSH_NETBOX_URL", "")
|
||||
t.Chdir(writeConfig(t, "hosts:\n - name: evil\n address: 10.0.0.1\nssh:\n options:\n ProxyCommand: touch /tmp/pwned\n"))
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatalf("Load: %v", err)
|
||||
}
|
||||
if len(cfg.Hosts) != 0 || len(cfg.SSH.Options) != 0 {
|
||||
t.Errorf("config from the working directory was loaded: %+v", cfg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoad_RejectsInvalidLegacyNetBoxURL(t *testing.T) {
|
||||
for _, bad := range []string{"netbox.example.com", "ftp://netbox.example.com", "https://netbox.example.com/?x=1"} {
|
||||
t.Setenv("XDG_CONFIG_HOME", writeConfig(t, "netbox:\n url: \""+bad+"\"\n token: t\n"))
|
||||
if _, err := Load(); err == nil || !strings.Contains(err.Error(), "netbox.url") {
|
||||
t.Errorf("%s: got %v, want a netbox.url error", bad, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// StaticKind is the kind of hosts defined under hosts: instead of NetBox.
|
||||
const StaticKind = "static"
|
||||
|
||||
// StaticHost is a host that is not in NetBox, defined in the config.
|
||||
type StaticHost struct {
|
||||
Name string `mapstructure:"name"`
|
||||
Address string `mapstructure:"address"` // IP address or DNS name
|
||||
User string `mapstructure:"user"`
|
||||
Port int `mapstructure:"port"`
|
||||
Tags []string `mapstructure:"tags"`
|
||||
SSH SSHOptions `mapstructure:"ssh"`
|
||||
}
|
||||
|
||||
var staticHostName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
|
||||
|
||||
// ValidateHosts keeps static host names usable as selectors and addresses
|
||||
// safe to pass to ssh.
|
||||
func (c *Config) ValidateHosts() error {
|
||||
seen := make(map[string]bool)
|
||||
for i, host := range c.Hosts {
|
||||
scope := fmt.Sprintf("hosts[%d]", i)
|
||||
if !staticHostName.MatchString(host.Name) {
|
||||
return fmt.Errorf("%s: name %q must start with a letter or digit and contain only letters, digits, dots, underscores, or hyphens", scope, host.Name)
|
||||
}
|
||||
name := strings.ToLower(host.Name)
|
||||
if seen[name] {
|
||||
return fmt.Errorf("%s: duplicate host name %q", scope, host.Name)
|
||||
}
|
||||
seen[name] = true
|
||||
if host.Address == "" || strings.HasPrefix(host.Address, "-") || strings.ContainsAny(host.Address, " \t\n\r/@") {
|
||||
return fmt.Errorf("%s: address %q must be an IP address or hostname", scope, host.Address)
|
||||
}
|
||||
if host.Port < 0 || host.Port > 65535 {
|
||||
return fmt.Errorf("%s: port must be between 1 and 65535", scope)
|
||||
}
|
||||
if strings.HasPrefix(host.User, "-") || strings.ContainsAny(host.User, " \t\n\r@") {
|
||||
return fmt.Errorf("%s: invalid user %q", scope, host.User)
|
||||
}
|
||||
if err := host.SSH.Validate(scope + ".ssh"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// StaticHost returns the static host with the given name, or nil.
|
||||
func (c *Config) StaticHost(name string) *StaticHost {
|
||||
for i := range c.Hosts {
|
||||
if strings.EqualFold(c.Hosts[i].Name, name) {
|
||||
return &c.Hosts[i]
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
var instanceName = regexp.MustCompile(`^[a-zA-Z0-9][a-zA-Z0-9_-]*$`)
|
||||
|
||||
// ValidateNetBoxes keeps source names usable as instance/hostname selectors.
|
||||
func (c *Config) ValidateNetBoxes() error {
|
||||
if len(c.NetBoxes) > 0 && c.NetBox.URL != "" {
|
||||
return fmt.Errorf("configure either netbox or netboxes, not both")
|
||||
}
|
||||
if c.NetBox.URL != "" && !validNetBoxURL(c.NetBox.URL) {
|
||||
return fmt.Errorf("netbox.url %q must be an HTTP(S) URL without query or fragment", c.NetBox.URL)
|
||||
}
|
||||
seen := make(map[string]bool)
|
||||
for _, source := range c.NetBoxes {
|
||||
if !instanceName.MatchString(source.Name) {
|
||||
return fmt.Errorf("netboxes.name %q must contain only letters, digits, underscores, or hyphens", source.Name)
|
||||
}
|
||||
name := strings.ToLower(source.Name)
|
||||
if seen[name] {
|
||||
return fmt.Errorf("duplicate NetBox instance name %q", source.Name)
|
||||
}
|
||||
seen[name] = true
|
||||
if !validNetBoxURL(source.URL) {
|
||||
return fmt.Errorf("NetBox %q requires an HTTP(S) URL without query or fragment", source.Name)
|
||||
}
|
||||
if source.TokenVersion < 0 || source.TokenVersion > 2 {
|
||||
return fmt.Errorf("NetBox %q: token_version must be 0, 1, or 2", source.Name)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validNetBoxURL accepts base URLs that API paths can be appended to.
|
||||
func validNetBoxURL(raw string) bool {
|
||||
u, err := url.Parse(raw)
|
||||
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != "" && u.RawQuery == "" && u.Fragment == ""
|
||||
}
|
||||
|
||||
func (c *Config) HasNetBox() bool { return c.NetBox.URL != "" || len(c.NetBoxes) > 0 }
|
||||
|
||||
// HasHosts reports whether netssh has anything to connect to: NetBox or static hosts.
|
||||
func (c *Config) HasHosts() bool { return c.HasNetBox() || len(c.Hosts) > 0 }
|
||||
|
||||
// CachePath isolates named sources from legacy caches and from changed endpoints.
|
||||
// Rotating a token or reordering the sources does not discard usage history.
|
||||
func (c *Config) CachePath() string {
|
||||
if len(c.NetBoxes) == 0 {
|
||||
return c.Cache.Path
|
||||
}
|
||||
var identities []string
|
||||
for _, source := range c.NetBoxes {
|
||||
identities = append(identities, strings.ToLower(source.Name)+"\x00"+strings.TrimRight(source.URL, "/"))
|
||||
}
|
||||
sort.Strings(identities)
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadNamedNetBoxes(t *testing.T) {
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_CONFIG_HOME", dir)
|
||||
t.Setenv("NETSSH_NETBOX_URL", "https://legacy-env.example")
|
||||
t.Setenv("NETSSH_NETBOX_TOKEN", "legacy-env-token")
|
||||
data := `netboxes:
|
||||
- name: Office
|
||||
url: https://office.example/netbox
|
||||
token: nbt_office
|
||||
disable_prefix: true
|
||||
- name: lab
|
||||
url: https://lab.example
|
||||
token: legacy-token
|
||||
cache:
|
||||
path: /tmp/netssh-tests/hosts.json
|
||||
`
|
||||
if err := os.WriteFile(filepath.Join(dir, "netssh.yaml"), []byte(data), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
cfg, err := Load()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !cfg.HasNetBox() || len(cfg.NetBoxes) != 2 || cfg.NetBoxes[0].Name != "office" || cfg.NetBoxes[0].TokenVersion != 2 || cfg.NetBoxes[1].TokenVersion != 1 {
|
||||
t.Fatalf("bad instances: %+v", cfg.NetBoxes)
|
||||
}
|
||||
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")
|
||||
}
|
||||
cfg.NetBoxes[0], cfg.NetBoxes[1] = cfg.NetBoxes[1], cfg.NetBoxes[0]
|
||||
cfg.NetBoxes[0].Token = "rotated"
|
||||
if cfg.CachePath() != first {
|
||||
t.Fatal("reordering/rotating credentials discarded cache")
|
||||
}
|
||||
cfg.NetBoxes[0].URL = "https://other.example"
|
||||
if cfg.CachePath() == first {
|
||||
t.Fatal("changed endpoint reuses old hosts")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateNetBoxes(t *testing.T) {
|
||||
good := NetBoxConfig{Name: "office", URL: "https://office.example"}
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
cfg Config
|
||||
}{
|
||||
{"duplicate", Config{NetBoxes: []NetBoxConfig{good, {Name: "OFFICE", URL: "https://other.example"}}}},
|
||||
{"empty name", Config{NetBoxes: []NetBoxConfig{{URL: "https://office.example"}}}},
|
||||
{"invalid name", Config{NetBoxes: []NetBoxConfig{{Name: "a/b", URL: "https://office.example"}}}},
|
||||
{"missing URL", Config{NetBoxes: []NetBoxConfig{{Name: "office"}}}},
|
||||
{"invalid URL", Config{NetBoxes: []NetBoxConfig{{Name: "office", URL: "file:///tmp/netbox"}}}},
|
||||
{"conflicting config", Config{NetBox: good, NetBoxes: []NetBoxConfig{good}}},
|
||||
{"invalid token version", Config{NetBoxes: []NetBoxConfig{{Name: "office", URL: good.URL, TokenVersion: 3}}}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if err := tc.cfg.ValidateNetBoxes(); err == nil {
|
||||
t.Fatal("invalid configuration accepted")
|
||||
}
|
||||
})
|
||||
}
|
||||
legacy := Config{NetBox: good, Cache: CacheConfig{Path: "hosts.json"}}
|
||||
if err := legacy.ValidateNetBoxes(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !legacy.HasNetBox() || legacy.CachePath() != "hosts.json" {
|
||||
t.Fatal("legacy behavior changed")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"sort"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// MultiConfig controls netssh multi.
|
||||
type MultiConfig struct {
|
||||
// Multiplexer is auto, tmux, or zellij; empty means auto.
|
||||
Multiplexer string `mapstructure:"multiplexer"`
|
||||
// PanesPerWindow splits larger host lists into more windows or tabs; 0 = 9.
|
||||
PanesPerWindow int `mapstructure:"panes_per_window"`
|
||||
// SyncKey and SoloKey are tmux prefix keys for broadcast to all panes and
|
||||
// for excluding the current pane; empty = default (S, e), "none" = off.
|
||||
SyncKey string `mapstructure:"sync_key"`
|
||||
SoloKey string `mapstructure:"solo_key"`
|
||||
}
|
||||
|
||||
// Default tmux keys: unbound in a stock tmux (E would be "spread evenly").
|
||||
const (
|
||||
DefaultSyncKey = "S"
|
||||
DefaultSoloKey = "e"
|
||||
)
|
||||
|
||||
// Keys returns the tmux keys to bind; "" for a disabled one.
|
||||
func (m MultiConfig) Keys() (sync, solo string) {
|
||||
pick := func(key, fallback string) string {
|
||||
switch key {
|
||||
case "":
|
||||
return fallback
|
||||
case "none":
|
||||
return ""
|
||||
}
|
||||
return key
|
||||
}
|
||||
return pick(m.SyncKey, DefaultSyncKey), pick(m.SoloKey, DefaultSoloKey)
|
||||
}
|
||||
|
||||
var tmuxKey = regexp.MustCompile(`^([CMS]-)*([A-Za-z0-9]|F[0-9]{1,2}|[-_=+!@#$%^&*,./?<>\[\]]|Tab|Space|Enter|BSpace|Up|Down|Left|Right|Home|End|PPage|NPage)$`)
|
||||
|
||||
// DefaultPanesPerWindow keeps panes readable on a normal screen (3×3).
|
||||
const DefaultPanesPerWindow = 9
|
||||
|
||||
// ValidateMulti checks groups and the multi settings.
|
||||
func (c *Config) ValidateMulti() error {
|
||||
switch c.Multi.Multiplexer {
|
||||
case "", "auto", "tmux", "zellij":
|
||||
default:
|
||||
return fmt.Errorf("multi.multiplexer must be auto, tmux, or zellij")
|
||||
}
|
||||
if c.Multi.PanesPerWindow < 0 || c.Multi.PanesPerWindow > 64 {
|
||||
return fmt.Errorf("multi.panes_per_window must be between 1 and 64")
|
||||
}
|
||||
for name, key := range map[string]string{"sync_key": c.Multi.SyncKey, "solo_key": c.Multi.SoloKey} {
|
||||
if key != "" && key != "none" && !tmuxKey.MatchString(key) {
|
||||
return fmt.Errorf("multi.%s %q is not a tmux key (e.g. S, e, C-s, F5) or none", name, key)
|
||||
}
|
||||
}
|
||||
if sync, solo := c.Multi.Keys(); sync != "" && sync == solo {
|
||||
return fmt.Errorf("multi.sync_key and multi.solo_key must differ")
|
||||
}
|
||||
names := make([]string, 0, len(c.Groups))
|
||||
for name := range c.Groups {
|
||||
names = append(names, name)
|
||||
}
|
||||
sort.Strings(names)
|
||||
for _, name := range names {
|
||||
if !instanceName.MatchString(name) {
|
||||
return fmt.Errorf("groups: name %q must contain only letters, digits, underscores, or hyphens", name)
|
||||
}
|
||||
if len(c.Groups[name]) == 0 {
|
||||
return fmt.Errorf("groups.%s: needs at least one host or selector", name)
|
||||
}
|
||||
for _, selector := range c.Groups[name] {
|
||||
if strings.TrimSpace(selector) == "" || strings.ContainsAny(selector, " \t\n") || strings.HasPrefix(selector, "-") {
|
||||
return fmt.Errorf("groups.%s: invalid entry %q", name, selector)
|
||||
}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PanesPerWindowOrDefault returns the configured value or the default.
|
||||
func (m MultiConfig) PanesPerWindowOrDefault() int {
|
||||
if m.PanesPerWindow > 0 {
|
||||
return m.PanesPerWindow
|
||||
}
|
||||
return DefaultPanesPerWindow
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"path"
|
||||
"regexp"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// SSHOptions are connection settings that can be set globally, per NetBox
|
||||
// instance, and per rule. More specific layers override less specific ones.
|
||||
type SSHOptions struct {
|
||||
// ProxyJump is passed as -J; "none" disables a jump host set by a broader layer.
|
||||
ProxyJump string `mapstructure:"proxy_jump"`
|
||||
// HostKeyChecking is strict, accept-new, or off. Empty keeps ssh's own setting.
|
||||
HostKeyChecking string `mapstructure:"host_key_checking"`
|
||||
// Target selects the ssh destination: ip (default), name, or hostname.
|
||||
Target string `mapstructure:"target"`
|
||||
// AddressFamily is any, inet, or inet6.
|
||||
AddressFamily string `mapstructure:"address_family"`
|
||||
// ExtraArgs are inserted verbatim before the destination.
|
||||
ExtraArgs []string `mapstructure:"extra_args"`
|
||||
// Options are passed as -o Key=Value.
|
||||
Options map[string]string `mapstructure:"options"`
|
||||
// Forwards are named port forwards, selected with --forward or netssh tunnel.
|
||||
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"`
|
||||
}
|
||||
|
||||
// PreConnectNone disables an inherited pre_connect hook.
|
||||
const PreConnectNone = "none"
|
||||
|
||||
// PreConnectCommand returns the hook to run, or "" when none is configured.
|
||||
func (o SSHOptions) PreConnectCommand() string {
|
||||
command := strings.TrimSpace(o.PreConnect)
|
||||
if strings.EqualFold(command, PreConnectNone) {
|
||||
return ""
|
||||
}
|
||||
return command
|
||||
}
|
||||
|
||||
// Forward is one port forward; exactly one of the fields is set.
|
||||
type Forward struct {
|
||||
Local string `mapstructure:"local"` // -L [bind:]port:host:hostport
|
||||
Remote string `mapstructure:"remote"` // -R [bind:]port:host:hostport
|
||||
Dynamic string `mapstructure:"dynamic"` // -D [bind:]port (SOCKS proxy)
|
||||
}
|
||||
|
||||
// Flag returns the ssh arguments for the forward, e.g. -L 8080:localhost:80.
|
||||
func (f Forward) Flag() []string {
|
||||
switch {
|
||||
case f.Local != "":
|
||||
return []string{"-L", f.Local}
|
||||
case f.Remote != "":
|
||||
return []string{"-R", f.Remote}
|
||||
case f.Dynamic != "":
|
||||
return []string{"-D", f.Dynamic}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// String renders the forward as its ssh flag, e.g. "-L 8080:localhost:80".
|
||||
func (f Forward) String() string { return strings.Join(f.Flag(), " ") }
|
||||
|
||||
func (f Forward) validate() error {
|
||||
set := 0
|
||||
for _, spec := range []string{f.Local, f.Remote, f.Dynamic} {
|
||||
if spec == "" {
|
||||
continue
|
||||
}
|
||||
set++
|
||||
if strings.HasPrefix(spec, "-") || strings.ContainsAny(spec, " \t\n\r") {
|
||||
return fmt.Errorf("invalid forward %q", spec)
|
||||
}
|
||||
}
|
||||
if set != 1 {
|
||||
return fmt.Errorf("set exactly one of local, remote, dynamic")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SSHRule applies SSH options to hosts that match every non-empty field.
|
||||
type SSHRule struct {
|
||||
Match SSHMatch `mapstructure:"match"`
|
||||
SSHOptions `mapstructure:",squash"`
|
||||
}
|
||||
|
||||
// SSHMatch selects hosts by NetBox attributes available in the cache.
|
||||
type SSHMatch struct {
|
||||
Tag string `mapstructure:"tag"`
|
||||
Instance string `mapstructure:"instance"`
|
||||
Kind string `mapstructure:"kind"`
|
||||
Name string `mapstructure:"name"` // shell-style glob, e.g. "*.dmz.example.com"
|
||||
}
|
||||
|
||||
// SSHHost identifies the resolved host that SSH options are computed for.
|
||||
type SSHHost struct {
|
||||
Instance string
|
||||
Name string // NetBox name without the instance prefix
|
||||
Kind string
|
||||
Tags []string
|
||||
}
|
||||
|
||||
var sshOptionKey = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`)
|
||||
|
||||
// ValidateSSH rejects values that would be passed to ssh in an unexpected form.
|
||||
func (c *Config) ValidateSSH() error {
|
||||
if err := c.SSH.SSHOptions.Validate("ssh"); err != nil {
|
||||
return err
|
||||
}
|
||||
for i, rule := range c.SSH.Rules {
|
||||
if err := rule.Validate(fmt.Sprintf("ssh.rules[%d]", i)); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if err := c.NetBox.SSH.Validate("netbox.ssh"); err != nil {
|
||||
return err
|
||||
}
|
||||
for _, source := range c.NetBoxes {
|
||||
if err := source.SSH.Validate("netboxes." + source.Name + ".ssh"); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Validate checks the match and options of a single rule.
|
||||
func (r SSHRule) Validate(scope string) error {
|
||||
if err := r.SSHOptions.Validate(scope); err != nil {
|
||||
return err
|
||||
}
|
||||
return r.Match.Validate(scope)
|
||||
}
|
||||
|
||||
// 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)
|
||||
}
|
||||
if _, err := path.Match(m.Name, ""); err != nil {
|
||||
return fmt.Errorf("%s: invalid name pattern %q", scope, m.Name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Validate rejects values that ssh would not accept or would misinterpret.
|
||||
func (o SSHOptions) Validate(scope string) error {
|
||||
switch o.HostKeyChecking {
|
||||
case "", "strict", "accept-new", "off":
|
||||
default:
|
||||
return fmt.Errorf("%s.host_key_checking must be strict, accept-new, or off", scope)
|
||||
}
|
||||
switch o.Target {
|
||||
case "", "ip", "name", "hostname":
|
||||
default:
|
||||
return fmt.Errorf("%s.target must be ip, name, or hostname", scope)
|
||||
}
|
||||
switch o.AddressFamily {
|
||||
case "", "any", "inet", "inet6":
|
||||
default:
|
||||
return fmt.Errorf("%s.address_family must be any, inet, or inet6", scope)
|
||||
}
|
||||
if strings.HasPrefix(o.ProxyJump, "-") || strings.ContainsAny(o.ProxyJump, " \t\n") {
|
||||
return fmt.Errorf("%s.proxy_jump %q is not a valid jump host", scope, o.ProxyJump)
|
||||
}
|
||||
for key, value := range o.Options {
|
||||
if !sshOptionKey.MatchString(key) || strings.ContainsAny(value, "\n\r") {
|
||||
return fmt.Errorf("%s.options: invalid option %q", scope, key)
|
||||
}
|
||||
}
|
||||
if strings.ContainsRune(o.PreConnect, 0) {
|
||||
return fmt.Errorf("%s.pre_connect must not contain NUL bytes", scope)
|
||||
}
|
||||
for name, forward := range o.Forwards {
|
||||
if !instanceName.MatchString(name) {
|
||||
return fmt.Errorf("%s.forwards: name %q must contain only letters, digits, underscores, or hyphens", scope, name)
|
||||
}
|
||||
if err := forward.validate(); err != nil {
|
||||
return fmt.Errorf("%s.forwards.%s: %v", scope, name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// SSHOptionsFor merges global, instance, and matching rule options for host.
|
||||
func (c *Config) SSHOptionsFor(host SSHHost) SSHOptions {
|
||||
merged := c.SSH.SSHOptions.merge(SSHOptions{})
|
||||
if host.Kind == StaticKind {
|
||||
if static := c.StaticHost(host.Name); static != nil {
|
||||
merged = merged.merge(static.SSH)
|
||||
}
|
||||
} else if host.Instance == "" {
|
||||
merged = merged.merge(c.NetBox.SSH)
|
||||
}
|
||||
for _, source := range c.NetBoxes {
|
||||
if strings.EqualFold(source.Name, host.Instance) {
|
||||
merged = merged.merge(source.SSH)
|
||||
}
|
||||
}
|
||||
for _, rule := range c.SSH.Rules {
|
||||
if rule.Match.matches(host) {
|
||||
merged = merged.merge(rule.SSHOptions)
|
||||
}
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
// merge returns o overridden by the non-empty fields of override.
|
||||
// Extra arguments accumulate; options override per key.
|
||||
func (o SSHOptions) merge(override SSHOptions) SSHOptions {
|
||||
out := o
|
||||
out.ExtraArgs = append(append([]string(nil), o.ExtraArgs...), override.ExtraArgs...)
|
||||
out.Options = make(map[string]string, len(o.Options)+len(override.Options))
|
||||
for key, value := range o.Options {
|
||||
out.Options[strings.ToLower(key)] = value
|
||||
}
|
||||
for key, value := range override.Options {
|
||||
out.Options[strings.ToLower(key)] = value
|
||||
}
|
||||
// Forwards override per name, so a rule can redefine a global "web" forward.
|
||||
out.Forwards = make(map[string]Forward, len(o.Forwards)+len(override.Forwards))
|
||||
for name, forward := range o.Forwards {
|
||||
out.Forwards[strings.ToLower(name)] = forward
|
||||
}
|
||||
for name, forward := range override.Forwards {
|
||||
out.Forwards[strings.ToLower(name)] = forward
|
||||
}
|
||||
if override.ProxyJump != "" {
|
||||
out.ProxyJump = override.ProxyJump
|
||||
}
|
||||
if override.HostKeyChecking != "" {
|
||||
out.HostKeyChecking = override.HostKeyChecking
|
||||
}
|
||||
if override.Target != "" {
|
||||
out.Target = override.Target
|
||||
}
|
||||
if override.AddressFamily != "" {
|
||||
out.AddressFamily = override.AddressFamily
|
||||
}
|
||||
if strings.TrimSpace(override.PreConnect) != "" {
|
||||
out.PreConnect = override.PreConnect
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (m SSHMatch) matches(host SSHHost) bool {
|
||||
if m.Instance != "" && !strings.EqualFold(m.Instance, host.Instance) {
|
||||
return false
|
||||
}
|
||||
if m.Kind != "" && !strings.EqualFold(m.Kind, host.Kind) {
|
||||
return false
|
||||
}
|
||||
if m.Name != "" {
|
||||
if ok, _ := path.Match(strings.ToLower(m.Name), strings.ToLower(host.Name)); !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
if m.Tag != "" {
|
||||
found := false
|
||||
for _, tag := range host.Tags {
|
||||
if strings.EqualFold(tag, m.Tag) || strings.EqualFold(tagSlug(tag), m.Tag) {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// tagSlug approximates NetBox's slug so rules may use either the tag name or slug.
|
||||
func tagSlug(name string) string {
|
||||
return strings.Join(strings.Fields(strings.ToLower(name)), "-")
|
||||
}
|
||||
@@ -0,0 +1,259 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"path/filepath"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func loadYAML(t *testing.T, data string) (*Config, error) {
|
||||
t.Helper()
|
||||
dir := t.TempDir()
|
||||
t.Setenv("XDG_CONFIG_HOME", dir)
|
||||
t.Setenv("HOME", t.TempDir())
|
||||
if err := os.WriteFile(filepath.Join(dir, "netssh.yaml"), []byte(data), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return Load()
|
||||
}
|
||||
|
||||
func TestSSHOptionsLayering(t *testing.T) {
|
||||
cfg, err := loadYAML(t, `
|
||||
netboxes:
|
||||
- name: prod
|
||||
url: https://prod.example.com
|
||||
ssh:
|
||||
proxy_jump: jh-prod.example.com
|
||||
host_key_checking: strict
|
||||
- name: staging
|
||||
url: https://staging.example.com
|
||||
ssh:
|
||||
host_key_checking: off
|
||||
ssh:
|
||||
proxy_jump: jh.example.com
|
||||
extra_args: ["-4"]
|
||||
options:
|
||||
ServerAliveInterval: 60
|
||||
ServerAliveCountMax: 5
|
||||
rules:
|
||||
- match: {tag: dmz}
|
||||
proxy_jump: jh-dmz.example.com
|
||||
options: {ServerAliveInterval: 10}
|
||||
- match: {instance: prod, name: "db*"}
|
||||
proxy_jump: none
|
||||
completion:
|
||||
max_results: 200
|
||||
`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.Completion.MaxResults != 200 {
|
||||
t.Fatalf("max_results: %d", cfg.Completion.MaxResults)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
host SSHHost
|
||||
jump, keys, alive string
|
||||
}{
|
||||
{SSHHost{Name: "web"}, "jh.example.com", "", "60"},
|
||||
{SSHHost{Instance: "prod", Name: "web"}, "jh-prod.example.com", "strict", "60"},
|
||||
{SSHHost{Instance: "staging", Name: "web", Tags: []string{"DMZ"}}, "jh-dmz.example.com", "off", "10"},
|
||||
{SSHHost{Instance: "prod", Name: "db01", Tags: []string{"dmz"}}, "none", "strict", "10"},
|
||||
} {
|
||||
got := cfg.SSHOptionsFor(tc.host)
|
||||
if got.ProxyJump != tc.jump || got.HostKeyChecking != tc.keys || got.Options["serveraliveinterval"] != tc.alive || got.Options["serveralivecountmax"] != "5" {
|
||||
t.Errorf("%+v: got %+v", tc.host, got)
|
||||
}
|
||||
if !reflect.DeepEqual(got.ExtraArgs, []string{"-4"}) {
|
||||
t.Errorf("extra args: %v", got.ExtraArgs)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSSHOptionsValidation(t *testing.T) {
|
||||
for _, data := range []string{
|
||||
"ssh:\n host_key_checking: maybe\n",
|
||||
"ssh:\n target: dns\n",
|
||||
"ssh:\n address_family: ipx\n",
|
||||
"ssh:\n proxy_jump: \"-oProxyCommand=x\"\n",
|
||||
"ssh:\n options:\n \"bad key\": 1\n",
|
||||
"ssh:\n rules:\n - proxy_jump: jh\n",
|
||||
"netboxes:\n - name: a\n url: https://a.example\n ssh:\n target: nope\n",
|
||||
} {
|
||||
if _, err := loadYAML(t, data); err == nil {
|
||||
t.Errorf("accepted invalid config:\n%s", data)
|
||||
} else if !strings.Contains(err.Error(), "ssh") {
|
||||
t.Errorf("unclear error %v", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardsLayering(t *testing.T) {
|
||||
cfg, err := loadYAML(t, `
|
||||
netboxes:
|
||||
- name: prod
|
||||
url: https://prod.example
|
||||
token: t
|
||||
ssh:
|
||||
forwards:
|
||||
db: {local: "5432:localhost:5432"}
|
||||
ssh:
|
||||
forwards:
|
||||
web: {local: "8080:localhost:80"}
|
||||
socks: {dynamic: "1080"}
|
||||
rules:
|
||||
- match: {tag: dmz}
|
||||
forwards:
|
||||
web: {local: "8443:localhost:443"}
|
||||
`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := cfg.SSHOptionsFor(SSHHost{Instance: "prod", Name: "web01", Tags: []string{"dmz"}}).Forwards
|
||||
want := map[string]Forward{"web": {Local: "8443:localhost:443"}, "socks": {Dynamic: "1080"}, "db": {Local: "5432:localhost:5432"}}
|
||||
if !reflect.DeepEqual(got, want) {
|
||||
t.Fatalf("got %+v", got)
|
||||
}
|
||||
if got := cfg.SSHOptionsFor(SSHHost{Instance: "other", Name: "web01"}).Forwards; len(got) != 2 || got["web"].Local != "8080:localhost:80" {
|
||||
t.Fatalf("other instance: %+v", got)
|
||||
}
|
||||
if f := (Forward{Remote: "9000:localhost:9000"}); f.String() != "-R 9000:localhost:9000" {
|
||||
t.Fatal(f.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestForwardsValidation(t *testing.T) {
|
||||
for _, forwards := range []string{
|
||||
`web: {local: "8080:a:80", dynamic: "1080"}`,
|
||||
`web: {local: "-oProxyCommand=x"}`,
|
||||
`web: {local: "8080 a:80"}`,
|
||||
`"bad name": {local: "8080:a:80"}`,
|
||||
} {
|
||||
if _, err := loadYAML(t, "ssh:\n forwards:\n "+forwards+"\n"); err == nil || !strings.Contains(err.Error(), "forwards") {
|
||||
t.Errorf("%s: got %v", forwards, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaticHosts(t *testing.T) {
|
||||
cfg, err := loadYAML(t, `
|
||||
resolver:
|
||||
hostname_domain: example.com
|
||||
ssh:
|
||||
proxy_jump: jh
|
||||
rules:
|
||||
- match: {kind: static, tag: home}
|
||||
host_key_checking: off
|
||||
hosts:
|
||||
- name: Router
|
||||
address: 192.168.1.1
|
||||
user: admin
|
||||
port: 2222
|
||||
tags: [home]
|
||||
ssh:
|
||||
proxy_jump: none
|
||||
`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !cfg.HasHosts() || cfg.HasNetBox() || cfg.Resolver.HostnameDomain != "example.com" {
|
||||
t.Fatalf("got %+v", cfg)
|
||||
}
|
||||
host := cfg.StaticHost("router")
|
||||
if host == nil || host.Address != "192.168.1.1" || host.User != "admin" || host.Port != 2222 {
|
||||
t.Fatalf("host: %+v", host)
|
||||
}
|
||||
opts := cfg.SSHOptionsFor(SSHHost{Name: "Router", Kind: StaticKind, Tags: []string{"home"}})
|
||||
if opts.ProxyJump != "none" || opts.HostKeyChecking != "off" {
|
||||
t.Fatalf("static host options: %+v", opts)
|
||||
}
|
||||
// A NetBox host of the same name does not get the static host's options.
|
||||
if got := cfg.SSHOptionsFor(SSHHost{Name: "Router", Kind: "device"}); got.ProxyJump != "jh" {
|
||||
t.Fatalf("netbox host: %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStaticHostsValidation(t *testing.T) {
|
||||
for _, hosts := range []string{
|
||||
"- {name: a, address: 10.0.0.1}\n - {name: A, address: 10.0.0.2}",
|
||||
"- {name: 'bad name', address: 10.0.0.1}",
|
||||
"- {name: prod/a, address: 10.0.0.1}",
|
||||
"- {name: a}",
|
||||
"- {name: a, address: '-oProxyCommand=x'}",
|
||||
"- {name: a, address: 10.0.0.1, port: 70000}",
|
||||
"- {name: a, address: 10.0.0.1, user: 'a b'}",
|
||||
"- {name: a, address: 10.0.0.1, ssh: {target: nope}}",
|
||||
} {
|
||||
if _, err := loadYAML(t, "hosts:\n "+hosts+"\n"); err == nil || !strings.Contains(err.Error(), "hosts[") {
|
||||
t.Errorf("%s: got %v", hosts, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMultiConfig(t *testing.T) {
|
||||
cfg, err := loadYAML(t, "groups:\n K8s: [master1, \"tag:worker\"]\nmulti:\n multiplexer: zellij\n")
|
||||
if err != nil || len(cfg.Groups["k8s"]) != 2 || cfg.Multi.Multiplexer != "zellij" || cfg.Multi.PanesPerWindowOrDefault() != 9 {
|
||||
t.Fatalf("%+v %v", cfg, err)
|
||||
}
|
||||
if sync, solo := cfg.Multi.Keys(); sync != "S" || solo != "e" {
|
||||
t.Fatalf("default keys %q %q", sync, solo)
|
||||
}
|
||||
custom, err := loadYAML(t, "multi: {sync_key: C-s, solo_key: none}\n")
|
||||
if sync, solo := custom.Multi.Keys(); err != nil || sync != "C-s" || solo != "" {
|
||||
t.Fatalf("custom keys %q %q %v", sync, solo, err)
|
||||
}
|
||||
for _, bad := range []string{"multi: {multiplexer: screen}", "multi: {panes_per_window: 100}", "groups: {web: []}", "groups: {web: [\"a b\"]}",
|
||||
"multi: {sync_key: \"x y\"}", "multi: {sync_key: \"{\"}", "multi: {sync_key: e}"} {
|
||||
if _, err := loadYAML(t, bad+"\n"); err == nil {
|
||||
t.Errorf("%s accepted", bad)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreConnectLayeringAndNone(t *testing.T) {
|
||||
cfg, err := loadYAML(t, `
|
||||
netboxes:
|
||||
- name: prod
|
||||
url: https://prod.example.com
|
||||
ssh:
|
||||
pre_connect: vpn-up prod
|
||||
- name: lab
|
||||
url: https://lab.example.com
|
||||
ssh:
|
||||
pre_connect: check-vpn
|
||||
rules:
|
||||
- match: {tag: dmz}
|
||||
pre_connect: none
|
||||
`)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, tc := range []struct {
|
||||
host SSHHost
|
||||
want string
|
||||
}{
|
||||
{SSHHost{Instance: "lab", Name: "web01"}, "check-vpn"},
|
||||
{SSHHost{Instance: "prod", Name: "web01"}, "vpn-up prod"},
|
||||
{SSHHost{Instance: "prod", Name: "gw", Tags: []string{"dmz"}}, ""},
|
||||
} {
|
||||
if got := cfg.SSHOptionsFor(tc.host).PreConnectCommand(); got != tc.want {
|
||||
t.Errorf("%+v: got %q, want %q", tc.host, got, tc.want)
|
||||
}
|
||||
}
|
||||
if err := (SSHOptions{PreConnect: "a\x00b"}).Validate("ssh"); err == nil {
|
||||
t.Error("NUL byte in pre_connect accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPreConnectFromEnvironment(t *testing.T) {
|
||||
t.Setenv("NETSSH_SSH_PRE_CONNECT", "true")
|
||||
t.Setenv("NETSSH_SHORTCUTS_SHOW", "true")
|
||||
cfg, err := loadYAML(t, "")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if cfg.SSH.PreConnect != "true" || !cfg.Shortcuts.Show {
|
||||
t.Fatalf("env not applied: pre_connect=%q show=%v", cfg.SSH.PreConnect, cfg.Shortcuts.Show)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user