feat: search multiple NetBox instances with isolated host identities
Release / release (push) Successful in 5m16s
Release / release (push) Successful in 5m16s
This commit is contained in:
1 parent
a2a6dd7591
commit
7f53b90266
26 files changed
+1299
-115
No files matched your search
@@ -13,6 +13,7 @@ import (
|
||||
type Config struct {
|
||||
Shell ShellConfig `mapstructure:"shell"`
|
||||
NetBox NetBoxConfig `mapstructure:"netbox"`
|
||||
NetBoxes []NetBoxConfig `mapstructure:"netboxes"`
|
||||
Resolver ResolverConfig `mapstructure:"resolver"`
|
||||
Cache CacheConfig `mapstructure:"cache"`
|
||||
SSH SSHConfig `mapstructure:"ssh"`
|
||||
@@ -24,6 +25,7 @@ type ShellConfig struct {
|
||||
}
|
||||
|
||||
type NetBoxConfig struct {
|
||||
Name string `mapstructure:"name"`
|
||||
URL string `mapstructure:"url"`
|
||||
Token string `mapstructure:"token"`
|
||||
TokenVersion int `mapstructure:"token_version"`
|
||||
@@ -93,6 +95,11 @@ func Load() (*Config, error) {
|
||||
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
|
||||
@@ -106,6 +113,20 @@ func Load() (*Config, error) {
|
||||
}
|
||||
}
|
||||
|
||||
if err := cfg.ValidateNetBoxes(); 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 {
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
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")
|
||||
}
|
||||
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
|
||||
u, err := url.Parse(source.URL)
|
||||
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.RawQuery != "" || u.Fragment != "" {
|
||||
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
|
||||
}
|
||||
|
||||
func (c *Config) HasNetBox() bool { return c.NetBox.URL != "" || len(c.NetBoxes) > 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))
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
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
|
||||
- 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")
|
||||
}
|
||||
first := cfg.CachePath()
|
||||
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")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user