v1
Test / test (push) Successful in 3m36s
Release / release (push) Successful in 7m31s

This commit is contained in:
Sebastian Unterschütz committed 2026-11-17 19:00:44 +01:00
commit 8d4915543e
132 files changed
+20628

No files matched your search

+87
View File
@@ -0,0 +1,87 @@
package setup
import (
"fmt"
"sort"
"strings"
"charm.land/huh/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func editCommands(cfg *config.Config) error {
for {
var names []string
for name := range cfg.Commands {
names = append(names, name)
}
sort.Strings(names)
var options []huh.Option[string]
for _, name := range names {
options = append(options, huh.NewOption("Edit "+name, "edit:"+name), huh.NewOption("Remove "+name, "remove:"+name))
}
options = append(options, huh.NewOption("Add command", "add"), huh.NewOption("Done", "done"))
action := "done"
if err := huh.NewSelect[string]().Title("Custom host commands").Options(options...).Value(&action).Run(); err != nil {
return err
}
if action == "done" {
return nil
}
if name, ok := strings.CutPrefix(action, "remove:"); ok {
remove := false
if err := huh.NewConfirm().Title("Remove " + name + "?").Value(&remove).Run(); err != nil {
return err
}
if remove {
delete(cfg.Commands, name)
}
continue
}
original, _ := strings.CutPrefix(action, "edit:")
if action == "add" {
original = ""
}
name := original
command := cfg.Commands[original]
binary, arguments := "", ""
if len(command.Args) > 0 {
binary = command.Args[0]
arguments = strings.Join(command.Args[1:], "\n")
}
err := huh.NewForm(huh.NewGroup(
huh.NewInput().Title("Command name").Placeholder("mtr").Value(&name).Validate(func(s string) error {
if s == "" {
return fmt.Errorf("required")
}
if s != original {
if _, exists := cfg.Commands[s]; exists {
return fmt.Errorf("name already exists")
}
}
return config.ValidateCommandAlias(s)
}),
huh.NewInput().Title("Alias prefix").Description("m + host shortcut xg1 = mxg1. Empty disables automatic aliases.").Value(&command.AliasPrefix),
huh.NewInput().Title("Program or executable script").Description("Use an absolute script path, or bash/python3 with the script path as the first argument.").Placeholder("mtr or /home/user/bin/check-host").Value(&binary),
huh.NewText().Title("Arguments, one per line").Description("Use {address} for the resolved address, {host} for the hostname, {target} for instance/hostname. No shell quoting needed.").Lines(5).Value(&arguments),
).Title("Local command")).Run()
if err != nil {
return err
}
command.Args = []string{binary}
if arguments != "" {
command.Args = append(command.Args, strings.Split(arguments, "\n")...)
}
candidate := config.Config{Commands: make(map[string]config.HostCommand)}
for k, v := range cfg.Commands {
if k != original {
candidate.Commands[k] = v
}
}
candidate.Commands[name] = command
if err := candidate.ValidateCommands(); err != nil {
return err
}
cfg.Commands = candidate.Commands
}
}
+140
View File
@@ -0,0 +1,140 @@
package setup
import (
"fmt"
"strconv"
"strings"
"charm.land/huh/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
// configureHosts edits a copy of the static hosts; the caller decides whether to keep it.
func configureHosts(hosts []config.StaticHost) ([]config.StaticHost, error) {
hosts = append([]config.StaticHost(nil), hosts...)
for {
action := "done"
var options []huh.Option[string]
for i, host := range hosts {
index := strconv.Itoa(i)
options = append(options,
huh.NewOption("Edit "+host.Name+" ("+host.Address+")", "edit:"+index),
huh.NewOption("SSH options for "+host.Name, "ssh:"+index),
huh.NewOption("Remove "+host.Name, "remove:"+index))
}
options = append(options, huh.NewOption("Add host", "add"), huh.NewOption("Back", "done"))
err := huh.NewForm(huh.NewGroup(huh.NewSelect[string]().
Title("Static hosts").
Description("Hosts that are not in NetBox. They are found before NetBox and work offline.").
Options(options...).
Value(&action))).Run()
if err != nil {
return nil, err
}
if action == "done" {
return hosts, nil
}
if action == "add" {
host, err := editHost(config.StaticHost{}, hosts, -1)
if err != nil {
return nil, err
}
hosts = append(hosts, host)
continue
}
verb, index, _ := strings.Cut(action, ":")
i, _ := strconv.Atoi(index)
switch verb {
case "edit":
host, err := editHost(hosts[i], hosts, i)
if err != nil {
return nil, err
}
hosts[i] = host
case "ssh":
options, err := editSSHOptions("SSH options for "+hosts[i].Name, hosts[i].SSH)
if err != nil {
return nil, err
}
hosts[i].SSH = options
case "remove":
remove := false
if err := huh.NewConfirm().Title("Remove " + hosts[i].Name + "?").Value(&remove).Run(); err != nil {
return nil, err
}
if remove {
hosts = append(hosts[:i], hosts[i+1:]...)
}
}
}
}
func editHost(host config.StaticHost, hosts []config.StaticHost, index int) (config.StaticHost, error) {
name, address, user := host.Name, host.Address, host.User
port := ""
if host.Port > 0 {
port = strconv.Itoa(host.Port)
}
tags := strings.Join(host.Tags, ", ")
candidate := func() config.StaticHost {
out := host
out.Name = strings.TrimSpace(name)
out.Address = strings.TrimSpace(address)
out.User = strings.TrimSpace(user)
out.Port, _ = strconv.Atoi(strings.TrimSpace(port))
out.Tags = splitList(tags)
return out
}
// huh validates the typed value before storing it, so each validator
// checks the host with its own field taken from the argument.
validate := func(set func(*config.StaticHost, string)) func(string) error {
return func(value string) error {
h := candidate()
set(&h, strings.TrimSpace(value))
return validateHostIn(h, hosts, index)
}
}
err := huh.NewForm(huh.NewGroup(
huh.NewInput().Title("Name").Description("What you type: netssh NAME. Letters, digits, dots, hyphens.").Value(&name).
Validate(validate(func(h *config.StaticHost, v string) { h.Name = v })),
huh.NewInput().Title("Address").Description("IP address or DNS name to connect to.").Value(&address).
Validate(validate(func(h *config.StaticHost, v string) {
h.Address = v
if v == "" {
h.Address = "-" // required: reported as invalid address
}
})),
huh.NewInput().Title("User").Description("Leave empty for ssh.default_user.").Value(&user).
Validate(validate(func(h *config.StaticHost, v string) { h.User = v })),
huh.NewInput().Title("Port").Description("Leave empty for ssh.default_port or 22.").Value(&port).Validate(func(s string) error {
if s = strings.TrimSpace(s); s == "" {
return nil
}
if n, err := strconv.Atoi(s); err != nil || n < 1 || n > 65535 {
return fmt.Errorf("must be a port number between 1 and 65535")
}
return nil
}),
huh.NewInput().Title("Tags").Description("Comma-separated, for ssh.rules match: {tag: …}.").Value(&tags),
).Title("Static host")).Run()
if err != nil {
return host, err
}
return candidate(), nil
}
// validateHostIn checks host as entry index of hosts (-1 for a new host).
func validateHostIn(host config.StaticHost, hosts []config.StaticHost, index int) error {
others := make([]config.StaticHost, 0, len(hosts)+1)
for i, other := range hosts {
if i != index {
others = append(others, other)
}
}
if host.Address == "" {
host.Address = "placeholder" // reported once the address field is filled
}
return (&config.Config{Hosts: append(others, host)}).ValidateHosts()
}
+135
View File
@@ -0,0 +1,135 @@
package setup
import (
"fmt"
"os"
"strings"
"charm.land/huh/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
// configureInstances edits a copy; nothing is written until the whole wizard succeeds.
func configureInstances(cfg *config.Config) ([]config.NetBoxConfig, error) {
sources := append([]config.NetBoxConfig(nil), cfg.NetBoxes...)
if len(sources) == 0 && cfg.NetBox.URL != "" {
source := cfg.NetBox
source.Name = "default"
sources = append(sources, source)
}
for {
if len(sources) == 0 {
choice := "add"
err := huh.NewForm(huh.NewGroup(huh.NewSelect[string]().
Title("NetBox").
Description("netssh looks up hosts in NetBox. Without NetBox, only static hosts (configured next) are available.").
Options(huh.NewOption("Add a NetBox instance", "add"), huh.NewOption("Continue without NetBox (static hosts only)", "none")).
Value(&choice))).Run()
if err != nil {
return nil, err
}
if choice == "none" {
return nil, nil
}
source, err := editInstance(config.NetBoxConfig{Name: "default"}, sources, "")
if err != nil {
return nil, err
}
sources = append(sources, source)
}
action := "done"
var options []huh.Option[string]
for _, source := range sources {
options = append(options, huh.NewOption("Edit "+source.Name+" ("+source.URL+")", "edit:"+source.Name))
options = append(options, huh.NewOption("SSH options for "+source.Name, "ssh:"+source.Name))
options = append(options, huh.NewOption("Remove "+source.Name, "remove:"+source.Name))
}
options = append(options, huh.NewOption("Add another NetBox", "add"), huh.NewOption("Continue with these instances", "done"))
err := huh.NewForm(huh.NewGroup(huh.NewSelect[string]().Title("NetBox instances").Description("All configured instances are searched together.").Options(options...).Value(&action))).Run()
if err != nil {
return nil, err
}
if action == "done" {
return sources, nil
}
if action == "add" {
source, err := editInstance(config.NetBoxConfig{}, sources, "")
if err != nil {
return nil, err
}
sources = append(sources, source)
continue
}
verb, name, _ := strings.Cut(action, ":")
for i, source := range sources {
if source.Name != name {
continue
}
switch verb {
case "edit":
edited, err := editInstance(source, sources, name)
if err != nil {
return nil, err
}
sources[i] = edited
case "ssh":
options, err := editSSHOptions("SSH options for "+name, source.SSH)
if err != nil {
return nil, err
}
sources[i].SSH = options
default:
remove := false
if err := huh.NewConfirm().Title("Remove " + name + "?").Value(&remove).Run(); err != nil {
return nil, err
}
if remove {
sources = append(sources[:i], sources[i+1:]...)
}
}
break
}
}
}
func editInstance(source config.NetBoxConfig, sources []config.NetBoxConfig, original string) (config.NetBoxConfig, error) {
err := huh.NewForm(huh.NewGroup(
huh.NewInput().Title("Instance name").Description("Used in selectors such as office/web01.").Value(&source.Name).Validate(func(name string) error {
name = strings.ToLower(strings.TrimSpace(name))
candidate := config.Config{NetBoxes: []config.NetBoxConfig{{Name: name, URL: "https://example.invalid"}}}
if err := candidate.ValidateNetBoxes(); err != nil {
return err
}
for _, existing := range sources {
if strings.EqualFold(existing.Name, name) && !strings.EqualFold(existing.Name, original) {
return fmt.Errorf("instance name %q is already used", name)
}
}
return nil
}),
huh.NewConfirm().Title("Hide instance prefix in aliases and TUI?").
Description("Shorter shell aliases and TUI host names. Conflicting names keep their prefix.").
Value(&source.DisablePrefix),
huh.NewInput().Title("NetBox URL").Placeholder("https://netbox.example.com").Value(&source.URL).Validate(func(value string) error {
return (&config.Config{NetBoxes: []config.NetBoxConfig{{Name: "instance", URL: strings.TrimSpace(value)}}}).ValidateNetBoxes()
}),
huh.NewInput().Title("NetBox API token").EchoMode(huh.EchoModePassword).Value(&source.Token).Validate(func(value string) error {
if strings.TrimSpace(value) == "" {
return fmt.Errorf("required")
}
return nil
}),
).Title("NetBox connection")).Run()
if err != nil {
return source, err
}
source.Name = strings.ToLower(strings.TrimSpace(source.Name))
source.URL = strings.TrimRight(strings.TrimSpace(source.URL), "/")
source.Token = strings.TrimSpace(source.Token)
source.TokenVersion = netbox.TokenVersion(source.Token)
if source.TokenVersion == 1 {
fmt.Fprintf(os.Stderr, "Note: NetBox %s uses a legacy v1 token. A v2 token starts with nbt_.\n", source.Name)
}
return source, nil
}
+128
View File
@@ -0,0 +1,128 @@
package setup
import (
"errors"
"fmt"
"sort"
"strconv"
"strings"
"charm.land/huh/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func editMulti(cfg *config.Config) error {
multiplexer := cfg.Multi.Multiplexer
if multiplexer == "" {
multiplexer = "auto"
}
perWindow := ""
if cfg.Multi.PanesPerWindow > 0 {
perWindow = strconv.Itoa(cfg.Multi.PanesPerWindow)
}
groups := formatGroups(cfg.Groups)
syncKey, soloKey := cfg.Multi.SyncKey, cfg.Multi.SoloKey
validKey := func(field string) func(string) error {
return func(s string) error {
candidate := config.Config{Multi: cfg.Multi}
if field == "sync" {
candidate.Multi.SyncKey = strings.TrimSpace(s)
} else {
candidate.Multi.SoloKey = strings.TrimSpace(s)
}
return candidate.ValidateMulti()
}
}
err := huh.NewForm(huh.NewGroup(
huh.NewSelect[string]().
Title("Multiplexer").
Description("netssh multi opens hosts side by side. auto uses the one you are in, else tmux, else zellij.").
Options(huh.NewOption("auto", "auto"), huh.NewOption("tmux", "tmux"), huh.NewOption("zellij", "zellij")).
Value(&multiplexer),
huh.NewInput().
Title("Panes per window").
Description(fmt.Sprintf("More hosts open in further windows or tabs. Leave empty for %d.", config.DefaultPanesPerWindow)).
Value(&perWindow).
Validate(func(s string) error {
if s = strings.TrimSpace(s); s == "" {
return nil
}
if n, err := strconv.Atoi(s); err != nil || n < 1 || n > 64 {
return errors.New("must be a number between 1 and 64")
}
return nil
}),
huh.NewInput().
Title("tmux key: broadcast to all panes").
Description(fmt.Sprintf("Pressed after the tmux prefix. Empty = %s, none = no key.", config.DefaultSyncKey)).
Placeholder(config.DefaultSyncKey).
Value(&syncKey).
Validate(validKey("sync")),
huh.NewInput().
Title("tmux key: exclude/include this pane").
Description(fmt.Sprintf("Pressed after the tmux prefix. Empty = %s, none = no key.", config.DefaultSoloKey)).
Placeholder(config.DefaultSoloKey).
Value(&soloKey).
Validate(validKey("solo")),
huh.NewText().
Title("Groups").
Description("One per line: NAME: host, tag:TAG, cluster:NAME, @other — open with netssh multi @NAME.").
Lines(4).
Value(&groups).
Validate(func(s string) error {
_, err := parseGroups(s)
return err
}),
).Title("Multi-session")).Run()
if err != nil {
return err
}
cfg.Multi.Multiplexer = multiplexer
if multiplexer == "auto" {
cfg.Multi.Multiplexer = ""
}
cfg.Multi.PanesPerWindow, _ = strconv.Atoi(strings.TrimSpace(perWindow))
cfg.Multi.SyncKey = strings.TrimSpace(syncKey)
cfg.Multi.SoloKey = strings.TrimSpace(soloKey)
cfg.Groups, _ = parseGroups(groups)
return nil
}
// parseGroups reads "NAME: sel1, sel2" lines into groups:.
func parseGroups(s string) (map[string][]string, error) {
var out map[string][]string
for _, line := range parseLines(s) {
name, members, ok := strings.Cut(line, ":")
name = strings.ToLower(strings.TrimSpace(name))
// "tag:x" alone has no group name before the first colon worth keeping.
if !ok || name == "" || name == "tag" || name == "cluster" {
return nil, fmt.Errorf("%q: expected NAME: host, tag:TAG, …", line)
}
var selectors []string
for _, field := range strings.FieldsFunc(members, func(r rune) bool { return r == ',' || r == ' ' || r == '\t' }) {
selectors = append(selectors, field)
}
if out == nil {
out = make(map[string][]string)
}
out[name] = append(out[name], selectors...)
}
if err := (&config.Config{Groups: out}).ValidateMulti(); err != nil {
return nil, err
}
return out, nil
}
func formatGroups(groups map[string][]string) string {
names := make([]string, 0, len(groups))
for name := range groups {
names = append(names, name)
}
sort.Strings(names)
lines := make([]string, 0, len(names))
for _, name := range names {
lines = append(lines, name+": "+strings.Join(groups[name], ", "))
}
return strings.Join(lines, "\n")
}
+294
View File
@@ -0,0 +1,294 @@
package setup
import (
"fmt"
"sort"
"strconv"
"strings"
"charm.land/huh/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
// inheritOption leaves a setting empty so a broader layer (or ssh itself) decides.
func inheritOption() huh.Option[string] { return huh.NewOption("(inherit)", "") }
// editSSHOptions edits one SSH option layer: global, per instance, or per rule.
func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error) {
proxyJump := o.ProxyJump
hostKeyChecking := o.HostKeyChecking
target := o.Target
addressFamily := o.AddressFamily
extraArgs := strings.Join(o.ExtraArgs, "\n")
options := formatOptions(o.Options)
forwards := formatForwards(o.Forwards)
preConnect := o.PreConnect
err := huh.NewForm(huh.NewGroup(
huh.NewInput().
Title("Jump host").
Description("Passed as -J, e.g. admin@bastion.example.com.\nLeave empty to inherit; 'none' disables a jump host set elsewhere.").
Value(&proxyJump).
Validate(func(s string) error {
return config.SSHOptions{ProxyJump: strings.TrimSpace(s)}.Validate("ssh")
}),
huh.NewSelect[string]().
Title("Host key checking").
Options(inheritOption(), huh.NewOption("strict", "strict"), huh.NewOption("accept-new", "accept-new"), huh.NewOption("off", "off")).
Value(&hostKeyChecking),
huh.NewSelect[string]().
Title("Connection target").
Description("What is passed to ssh as destination.").
Options(inheritOption(), huh.NewOption("ip — resolved address", "ip"), huh.NewOption("name — NetBox name", "name"), huh.NewOption("hostname — name as typed", "hostname")).
Value(&target),
huh.NewSelect[string]().
Title("Address family").
Options(inheritOption(), huh.NewOption("any", "any"), huh.NewOption("inet (IPv4)", "inet"), huh.NewOption("inet6 (IPv6)", "inet6")).
Value(&addressFamily),
huh.NewText().
Title("Extra arguments").
Description("One argument per line, inserted before the destination, e.g. -A").
Lines(3).
Value(&extraArgs),
huh.NewText().
Title("SSH options").
Description("One Key=Value per line, passed as -o, e.g. ServerAliveInterval=60").
Lines(4).
Value(&options).
Validate(func(s string) error {
_, err := parseOptions(s)
return err
}),
huh.NewText().
Title("Port forwards").
Description("One per line: NAME L|R|D SPEC, e.g. web L 8080:localhost:80 or socks D 1080.\n"+
"Use with netssh tunnel HOST NAME or netssh --forward NAME HOST.").
Lines(3).
Value(&forwards).
Validate(func(s string) error {
_, err := parseForwards(s)
return err
}),
huh.NewInput().
Title("Pre-connect hook").
Description("Shell command run locally before connecting, e.g. vpn-check.sh \"$NETSSH_HOST\".\n"+
"A non-zero exit aborts. Leave empty to inherit; 'none' disables a hook set elsewhere.").
Value(&preConnect).
Validate(func(s string) error {
return config.SSHOptions{PreConnect: s}.Validate("ssh")
}),
).Title(title)).Run()
if err != nil {
return o, err
}
parsed, _ := parseOptions(options)
parsedForwards, _ := parseForwards(forwards)
return config.SSHOptions{
Forwards: parsedForwards,
ProxyJump: strings.TrimSpace(proxyJump),
HostKeyChecking: hostKeyChecking,
Target: target,
AddressFamily: addressFamily,
ExtraArgs: parseLines(extraArgs),
Options: parsed,
PreConnect: strings.TrimSpace(preConnect),
}, nil
}
// parseLines returns the non-empty, trimmed lines of s.
func parseLines(s string) []string {
var out []string
for _, line := range strings.Split(s, "\n") {
if line = strings.TrimSpace(line); line != "" {
out = append(out, line)
}
}
return out
}
// parseOptions reads Key=Value lines into the map stored under ssh.options.
func parseOptions(s string) (map[string]string, error) {
var out map[string]string
for _, line := range parseLines(s) {
key, value, ok := strings.Cut(line, "=")
key = strings.TrimSpace(key)
if !ok || key == "" {
return nil, fmt.Errorf("%q: expected Key=Value", line)
}
if out == nil {
out = make(map[string]string)
}
out[key] = strings.TrimSpace(value)
}
if err := (config.SSHOptions{Options: out}).Validate("ssh"); err != nil {
return nil, err
}
return out, nil
}
// forwardKinds maps the letters used in the form to the ssh flags.
var forwardKinds = map[string]func(spec string) config.Forward{
"L": func(spec string) config.Forward { return config.Forward{Local: spec} },
"R": func(spec string) config.Forward { return config.Forward{Remote: spec} },
"D": func(spec string) config.Forward { return config.Forward{Dynamic: spec} },
}
// parseForwards reads "NAME L|R|D SPEC" lines into ssh.forwards.
func parseForwards(s string) (map[string]config.Forward, error) {
var out map[string]config.Forward
for _, line := range parseLines(s) {
fields := strings.Fields(line)
if len(fields) != 3 || forwardKinds[strings.ToUpper(fields[1])] == nil {
return nil, fmt.Errorf("%q: expected NAME L|R|D SPEC", line)
}
if out == nil {
out = make(map[string]config.Forward)
}
out[strings.ToLower(fields[0])] = forwardKinds[strings.ToUpper(fields[1])](fields[2])
}
if err := (config.SSHOptions{Forwards: out}).Validate("ssh"); err != nil {
return nil, err
}
return out, nil
}
func formatForwards(forwards map[string]config.Forward) string {
names := make([]string, 0, len(forwards))
for name := range forwards {
names = append(names, name)
}
sort.Strings(names)
lines := make([]string, 0, len(names))
for _, name := range names {
flag := forwards[name].Flag()
if len(flag) == 2 {
lines = append(lines, name+" "+strings.TrimPrefix(flag[0], "-")+" "+flag[1])
}
}
return strings.Join(lines, "\n")
}
func formatOptions(options map[string]string) string {
keys := make([]string, 0, len(options))
for key := range options {
keys = append(keys, key)
}
sort.Strings(keys)
lines := make([]string, 0, len(keys))
for _, key := range keys {
lines = append(lines, key+"="+options[key])
}
return strings.Join(lines, "\n")
}
// configureRules edits a copy of the rules; the caller decides whether to keep it.
func configureRules(rules []config.SSHRule, sources []config.NetBoxConfig) ([]config.SSHRule, error) {
rules = append([]config.SSHRule(nil), rules...)
for {
action := "done"
var options []huh.Option[string]
for i, rule := range rules {
index := strconv.Itoa(i)
options = append(options, huh.NewOption("Edit rule "+describeMatch(rule.Match), "edit:"+index))
options = append(options, huh.NewOption("Remove rule "+describeMatch(rule.Match), "remove:"+index))
}
options = append(options, huh.NewOption("Add rule", "add"), huh.NewOption("Back", "done"))
err := huh.NewForm(huh.NewGroup(huh.NewSelect[string]().
Title("SSH rules").
Description("Rules apply SSH options to hosts matching every set field. Later rules win.").
Options(options...).
Value(&action))).Run()
if err != nil {
return nil, err
}
if action == "done" {
return rules, nil
}
if action == "add" {
rule, err := editRule(config.SSHRule{}, sources)
if err != nil {
return nil, err
}
rules = append(rules, rule)
continue
}
verb, index, _ := strings.Cut(action, ":")
i, _ := strconv.Atoi(index)
if verb == "edit" {
rule, err := editRule(rules[i], sources)
if err != nil {
return nil, err
}
rules[i] = rule
continue
}
remove := false
if err := huh.NewConfirm().Title("Remove rule " + describeMatch(rules[i].Match) + "?").Value(&remove).Run(); err != nil {
return nil, err
}
if remove {
rules = append(rules[:i], rules[i+1:]...)
}
}
}
func editRule(rule config.SSHRule, sources []config.NetBoxConfig) (config.SSHRule, error) {
match := rule.Match
instances := []huh.Option[string]{huh.NewOption("(any)", "")}
known := false
for _, source := range sources {
instances = append(instances, huh.NewOption(source.Name, source.Name))
known = known || strings.EqualFold(source.Name, match.Instance)
}
if match.Instance != "" && !known {
instances = append(instances, huh.NewOption(match.Instance+" (not configured)", match.Instance))
}
err := huh.NewForm(huh.NewGroup(
huh.NewInput().
Title("Tag").
Description("NetBox tag name or slug, e.g. dmz").
Value(&match.Tag),
huh.NewSelect[string]().
Title("Instance").
Options(instances...).
Value(&match.Instance),
huh.NewSelect[string]().
Title("Kind").
Options(huh.NewOption("(any)", ""), huh.NewOption("device", "device"), huh.NewOption("vm", "vm")).
Value(&match.Kind),
huh.NewInput().
Title("Name pattern").
Description("Shell-style glob without instance prefix, e.g. *.dmz.example.com").
Value(&match.Name).
Validate(func(s string) error {
candidate := match
candidate.Tag = strings.TrimSpace(candidate.Tag)
candidate.Name = strings.TrimSpace(s)
return candidate.Validate("rule")
}),
).Title("Rule match")).Run()
if err != nil {
return rule, err
}
match.Tag = strings.TrimSpace(match.Tag)
match.Name = strings.TrimSpace(match.Name)
options, err := editSSHOptions("SSH options for rule "+describeMatch(match), rule.SSHOptions)
if err != nil {
return rule, err
}
return config.SSHRule{Match: match, SSHOptions: options}, nil
}
func describeMatch(m config.SSHMatch) string {
var parts []string
for _, field := range [][2]string{{"tag", m.Tag}, {"instance", m.Instance}, {"kind", m.Kind}, {"name", m.Name}} {
if field[1] != "" {
parts = append(parts, field[0]+"="+field[1])
}
}
return "[" + strings.Join(parts, " ") + "]"
}
+92
View File
@@ -0,0 +1,92 @@
package setup
import (
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func TestParseLines(t *testing.T) {
got := parseLines(" -A \n\n\t-C\n \n")
if want := []string{"-A", "-C"}; !reflect.DeepEqual(got, want) {
t.Fatalf("got %q, want %q", got, want)
}
if got := parseLines(" \n "); got != nil {
t.Fatalf("blank input: got %q, want nil", got)
}
}
func TestParseOptionsRoundtrip(t *testing.T) {
text := "ServerAliveInterval = 60\n\nForwardAgent=yes\nLocalCommand=echo a=b\n"
got, err := parseOptions(text)
if err != nil {
t.Fatal(err)
}
want := map[string]string{"ServerAliveInterval": "60", "ForwardAgent": "yes", "LocalCommand": "echo a=b"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
again, err := parseOptions(formatOptions(got))
if err != nil || !reflect.DeepEqual(again, want) {
t.Fatalf("roundtrip: got %v (%v)", again, err)
}
if formatOptions(got) != "ForwardAgent=yes\nLocalCommand=echo a=b\nServerAliveInterval=60" {
t.Fatalf("formatOptions not sorted: %q", formatOptions(got))
}
}
func TestParseOptionsEmpty(t *testing.T) {
got, err := parseOptions("\n \n")
if err != nil || got != nil {
t.Fatalf("got %v, %v; want nil, nil", got, err)
}
}
func TestParseOptionsInvalid(t *testing.T) {
for _, text := range []string{"ServerAliveInterval", "=60", "Bad-Key=1", "1Key=1"} {
if _, err := parseOptions(text); err == nil {
t.Errorf("%q: expected error", text)
}
}
}
func TestDescribeMatch(t *testing.T) {
got := describeMatch(config.SSHMatch{Tag: "dmz", Name: "*.dmz"})
if got != "[tag=dmz name=*.dmz]" {
t.Fatalf("got %q", got)
}
}
func TestRuleValidation(t *testing.T) {
if err := (config.SSHMatch{}).Validate("rule"); err == nil || !strings.Contains(err.Error(), "at least one") {
t.Fatalf("empty match: got %v", err)
}
if err := (config.SSHMatch{Name: "[web"}).Validate("rule"); err == nil {
t.Fatal("invalid glob accepted")
}
if err := (config.SSHMatch{Kind: "vm"}).Validate("rule"); err != nil {
t.Fatalf("valid match rejected: %v", err)
}
}
func TestParseForwardsRoundtrip(t *testing.T) {
text := "Web L 8080:localhost:80\n\nsocks d 1080\nback R 9000:localhost:9000\n"
got, err := parseForwards(text)
if err != nil {
t.Fatal(err)
}
want := map[string]config.Forward{"web": {Local: "8080:localhost:80"}, "socks": {Dynamic: "1080"}, "back": {Remote: "9000:localhost:9000"}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %+v", got)
}
if formatForwards(got) != "back R 9000:localhost:9000\nsocks D 1080\nweb L 8080:localhost:80" {
t.Fatalf("format: %q", formatForwards(got))
}
for _, bad := range []string{"web 8080:localhost:80", "web X 8080", "web L -oFoo", "bad/name L 1:a:2"} {
if _, err := parseForwards(bad); err == nil {
t.Errorf("%q accepted", bad)
}
}
}
+614
View File
@@ -0,0 +1,614 @@
package setup
import (
"errors"
"fmt"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"charm.land/huh/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
)
// RunWizard runs the interactive configurator, pre-filled with any existing cfg values.
// It saves the result to the config file on success.
func RunWizard(cfg *config.Config) error {
sources, err := configureInstances(cfg)
if err != nil {
return cancelled(err)
}
work := prepare(*cfg, sources)
if err := runMenu(&work); err != nil {
return cancelled(err)
}
if err := save(work); err != nil {
return err
}
loaded, err := config.Load()
if err != nil {
return err
}
c := cache.New(loaded.CachePath(), loaded.Cache.TTL).WithStatic(loaded.Hosts)
if err := c.Load(); err != nil {
return fmt.Errorf("updating aliases: %w", err)
}
if err := hook.WriteAliasFiles(hook.BuildAliasEntries(c.All(), *loaded)); err != nil {
return err
}
if loaded.Shell.Alias != "" {
shell := filepath.Base(os.Getenv("SHELL"))
profile, err := hook.ProfilePath(shell)
if err != nil {
fmt.Fprintf(os.Stderr, "Run 'netssh hook install --shell bash|zsh|fish' to activate your alias.\n")
return nil
}
if _, err := hook.Install(profile, shell); err != nil {
return err
}
fmt.Fprintln(os.Stderr, hook.ReloadNote(profile))
}
return nil
}
func cancelled(err error) error {
if errors.Is(err, huh.ErrUserAborted) {
fmt.Fprintln(os.Stderr, "Setup cancelled.")
os.Exit(0)
}
return err
}
// prepare starts from the loaded config so settings without a menu entry survive
// a rewrite, migrates a legacy single instance, and fills in usable defaults.
func prepare(cfg config.Config, sources []config.NetBoxConfig) config.Config {
cfg.NetBox = config.NetBoxConfig{}
cfg.NetBoxes = sources
if len(cfg.Resolver.Strategies) == 0 {
cfg.Resolver.Strategies = []string{"primary_ip"}
}
if cfg.Cache.TTL == 0 {
cfg.Cache.TTL = 3600
}
return cfg
}
func runMenu(cfg *config.Config) error {
for {
action := "save"
err := huh.NewForm(huh.NewGroup(huh.NewSelect[string]().
Title("netssh configuration").
Description("Choose a section to edit, then save.").
Options(
huh.NewOption("SSH defaults — user, port", "defaults"),
huh.NewOption("SSH options — jump host, host keys, target, -o, forwards", "ssh"),
huh.NewOption(fmt.Sprintf("SSH rules — per tag, instance, kind, name (%d)", len(cfg.SSH.Rules)), "rules"),
huh.NewOption(fmt.Sprintf("Static hosts — hosts not in NetBox (%d)", len(cfg.Hosts)), "hosts"),
huh.NewOption(fmt.Sprintf("Multi-session — groups, tmux/zellij (%d groups)", len(cfg.Groups)), "multi"),
huh.NewOption("Resolver & cache", "resolver"),
huh.NewOption("Shortcuts & command alias", "shortcuts"),
huh.NewOption("Custom commands — mtr, ping, scripts", "commands"),
huh.NewOption("Completion", "completion"),
huh.NewOption("Save and exit", "save"),
).
Value(&action))).Run()
if err != nil {
return err
}
switch action {
case "defaults":
err = editSSHDefaults(cfg)
case "ssh":
cfg.SSH.SSHOptions, err = editSSHOptions("SSH options (all hosts)", cfg.SSH.SSHOptions)
case "rules":
var rules []config.SSHRule
if rules, err = configureRules(cfg.SSH.Rules, cfg.NetBoxes); err == nil {
cfg.SSH.Rules = rules
}
case "hosts":
var hosts []config.StaticHost
if hosts, err = configureHosts(cfg.Hosts); err == nil {
cfg.Hosts = hosts
}
case "multi":
err = editMulti(cfg)
case "resolver":
err = editResolverCache(cfg)
case "shortcuts":
err = editShortcuts(cfg)
case "commands":
err = editCommands(cfg)
case "completion":
err = editCompletion(cfg)
case "save":
return nil
}
if err != nil {
return err
}
}
}
func editSSHDefaults(cfg *config.Config) error {
defaultUser := cfg.SSH.DefaultUser
defaultPort := ""
if cfg.SSH.DefaultPort > 0 {
defaultPort = strconv.Itoa(cfg.SSH.DefaultPort)
}
err := huh.NewForm(huh.NewGroup(
huh.NewInput().
Title("Default SSH user").
Description("Leave empty to use your system user ($USER).").
Value(&defaultUser),
huh.NewInput().
Title("Default SSH port").
Description("Leave empty to use the standard port (22).").
Placeholder("22").
Value(&defaultPort).
Validate(func(s string) error {
if strings.TrimSpace(s) == "" {
return nil
}
n, err := strconv.Atoi(strings.TrimSpace(s))
if err != nil || n < 1 || n > 65535 {
return errors.New("must be a port number between 1 and 65535")
}
return nil
}),
).Title("SSH defaults")).Run()
if err != nil {
return err
}
cfg.SSH.DefaultUser = strings.TrimSpace(defaultUser)
cfg.SSH.DefaultPort, _ = strconv.Atoi(strings.TrimSpace(defaultPort))
return nil
}
func editResolverCache(cfg *config.Config) error {
strategiesRaw := strings.Join(cfg.Resolver.Strategies, ", ")
subnets := strings.Join(cfg.Resolver.ManagementSubnets, ", ")
interfaceName := cfg.Resolver.InterfaceName
hostnameDomain := cfg.Resolver.HostnameDomain
cacheTTL := strconv.Itoa(cfg.Cache.TTL)
cachePath := cfg.Cache.Path
err := huh.NewForm(huh.NewGroup(
huh.NewInput().
Title("Resolver strategies").
Description("Comma-separated, in priority order. First match wins.\nAvailable: primary_ip, management_subnet, interface_name, hostname").
Placeholder("primary_ip, management_subnet").
Value(&strategiesRaw).
Validate(validateStrategies),
huh.NewInput().
Title("Management subnets").
Description("Comma-separated CIDRs, e.g. 10.0.0.0/8, 192.168.0.0/16\nOnly used when management_subnet strategy is active.").
Value(&subnets),
huh.NewInput().
Title("Interface name").
Description("Only used when interface_name strategy is active.").
Placeholder("eth0").
Value(&interfaceName),
huh.NewInput().
Title("Hostname domain").
Description("Only used by the hostname strategy: appended to NetBox names without a dot,\ne.g. example.com turns web01 into web01.example.com.").
Value(&hostnameDomain),
huh.NewInput().
Title("Cache TTL (seconds)").
Value(&cacheTTL).
Validate(func(s string) error {
if _, err := strconv.Atoi(s); err != nil {
return errors.New("must be a number")
}
return nil
}),
huh.NewInput().
Title("Cache file").
Description("Where resolved hosts are stored. Leave empty for the default location.").
Value(&cachePath),
).Title("Resolver & cache")).Run()
if err != nil {
return err
}
cfg.Resolver.Strategies = parseStrategies(strategiesRaw)
cfg.Resolver.ManagementSubnets = splitList(subnets)
cfg.Resolver.InterfaceName = strings.TrimSpace(interfaceName)
cfg.Resolver.HostnameDomain = strings.Trim(strings.TrimSpace(hostnameDomain), ".")
cfg.Cache.TTL, _ = strconv.Atoi(cacheTTL)
cfg.Cache.Path = strings.TrimSpace(cachePath)
return nil
}
func editShortcuts(cfg *config.Config) error {
shortcutDomains := strings.Join(cfg.Shortcuts.Domains, ", ")
stripHyphens := cfg.Shortcuts.StripHyphens
rewrites := formatRewrites(cfg.Shortcuts.Rewrites)
commandAlias := cfg.Shell.Alias
showShortcuts := cfg.Shortcuts.Show
err := huh.NewForm(huh.NewGroup(
huh.NewInput().
Title("Domain suffixes").
Description("Comma-separated suffixes stripped for shortcuts, e.g. .example.com, .example.de\nAllows typing 'web01' instead of 'web01.example.com'.").
Placeholder(".example.com").
Value(&shortcutDomains),
huh.NewConfirm().
Title("Strip hyphens").
Description("When enabled, fsn1-web01.example.com can be accessed as fsn1web01.\nOnly works for hosts already in the cache.").
Value(&stripHyphens),
huh.NewText().
Title("Rewrite rules").
Description("One rule per line: REGEX => REPLACEMENT, applied after the domain suffix is removed.\n"+
"Example: ^([a-z]+)[0-9]+- => $1 turns fsn1-bx1.example.com into fsnbx1.\n"+
"Check rules with: netssh alias --test HOSTNAME").
Lines(3).
Value(&rewrites).
Validate(func(s string) error {
_, err := parseRewrites(s)
return err
}),
huh.NewConfirm().
Title("Show shortcuts").
Description("Show each host's shortcut alias in the TUI, netssh cache list and netssh hosts list,\n"+
"and offer shortcuts in Tab completion even when the full name matches.").
Value(&showShortcuts),
huh.NewInput().
Title("Command alias").
Description("Optional alias for netssh itself, e.g. j. Leave empty to disable.").
Placeholder("j").
Value(&commandAlias).
Validate(func(s string) error { return config.ValidateCommandAlias(strings.TrimSpace(s)) }),
).Title("Shortcuts")).Run()
if err != nil {
return err
}
cfg.Shortcuts.Domains = nil
for _, s := range splitList(shortcutDomains) {
if !strings.HasPrefix(s, ".") {
s = "." + s
}
cfg.Shortcuts.Domains = append(cfg.Shortcuts.Domains, s)
}
cfg.Shortcuts.StripHyphens = stripHyphens
cfg.Shortcuts.Rewrites, _ = parseRewrites(rewrites)
cfg.Shortcuts.Show = showShortcuts
cfg.Shell.Alias = strings.TrimSpace(commandAlias)
return nil
}
func editCompletion(cfg *config.Config) error {
maxResults := ""
if cfg.Completion.MaxResults > 0 {
maxResults = strconv.Itoa(cfg.Completion.MaxResults)
}
err := huh.NewForm(huh.NewGroup(
huh.NewInput().
Title("Maximum completion results").
Description("Limits the hostnames offered per Tab completion. Leave empty for unlimited.").
Value(&maxResults).
Validate(func(s string) error {
if strings.TrimSpace(s) == "" {
return nil
}
if n, err := strconv.Atoi(strings.TrimSpace(s)); err != nil || n < 0 {
return errors.New("must be a non-negative number")
}
return nil
}),
).Title("Completion")).Run()
if err != nil {
return err
}
cfg.Completion.MaxResults, _ = strconv.Atoi(strings.TrimSpace(maxResults))
return nil
}
// parseRewrites reads "REGEX => REPLACEMENT" lines; the replacement may be empty.
func parseRewrites(s string) ([]config.ShortcutRewrite, error) {
var out []config.ShortcutRewrite
for _, line := range parseLines(s) {
pattern, replace, ok := strings.Cut(line, "=>")
if !ok {
return nil, fmt.Errorf("%q: expected REGEX => REPLACEMENT", line)
}
out = append(out, config.ShortcutRewrite{Pattern: strings.TrimSpace(pattern), Replace: strings.TrimSpace(replace)})
}
if err := (config.ShortcutsConfig{Rewrites: out}).Validate(); err != nil {
return nil, err
}
return out, nil
}
func formatRewrites(rewrites []config.ShortcutRewrite) string {
lines := make([]string, 0, len(rewrites))
for _, r := range rewrites {
lines = append(lines, r.Pattern+" => "+r.Replace)
}
return strings.Join(lines, "\n")
}
// splitList returns the non-empty, trimmed entries of a comma-separated list.
func splitList(s string) []string {
var out []string
for _, part := range strings.Split(s, ",") {
if part = strings.TrimSpace(part); part != "" {
out = append(out, part)
}
}
return out
}
var knownStrategies = map[string]bool{
"primary_ip": true,
"management_subnet": true,
"interface_name": true,
"hostname": true,
}
func validateStrategies(s string) error {
if strings.TrimSpace(s) == "" {
return errors.New("at least one strategy is required")
}
for _, name := range parseStrategies(s) {
if !knownStrategies[name] {
return fmt.Errorf("unknown strategy %q — available: primary_ip, management_subnet, interface_name, hostname", name)
}
}
return nil
}
func parseStrategies(s string) []string { return splitList(s) }
// Save validates cfg and writes it to the config file, replacing the old file.
func Save(cfg config.Config) error { return save(cfg) }
func save(cfg config.Config) error {
if err := config.ValidateCommandAlias(cfg.Shell.Alias); err != nil {
return err
}
if err := cfg.ValidateNetBoxes(); err != nil {
return err
}
if err := cfg.ValidateSSH(); err != nil {
return err
}
if err := cfg.Shortcuts.Validate(); err != nil {
return err
}
if err := cfg.ValidateHosts(); err != nil {
return err
}
if err := cfg.ValidateCommands(); err != nil {
return err
}
if err := cfg.ValidateMulti(); err != nil {
return err
}
path := config.Path()
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return fmt.Errorf("creating config dir: %w", err)
}
var b strings.Builder
if len(cfg.NetBoxes) > 0 {
b.WriteString("netboxes:\n")
for _, source := range cfg.NetBoxes {
fmt.Fprintf(&b, " - name: %q\n url: %q\n token: %q\n token_version: %d\n", source.Name, source.URL, source.Token, source.TokenVersion)
if source.DisablePrefix {
b.WriteString(" disable_prefix: true\n")
}
if !sshOptionsEmpty(source.SSH) {
b.WriteString(" ssh:\n")
writeSSHOptions(&b, " ", source.SSH)
}
}
} else if cfg.NetBox.URL != "" || len(cfg.Hosts) == 0 {
b.WriteString("netbox:\n")
fmt.Fprintf(&b, " url: %q\n token: %q\n token_version: %d\n", cfg.NetBox.URL, cfg.NetBox.Token, cfg.NetBox.TokenVersion)
if !sshOptionsEmpty(cfg.NetBox.SSH) {
b.WriteString(" ssh:\n")
writeSSHOptions(&b, " ", cfg.NetBox.SSH)
}
}
b.WriteString("\nresolver:\n")
b.WriteString(" strategies:\n")
for _, s := range cfg.Resolver.Strategies {
fmt.Fprintf(&b, " - %s\n", s)
}
if len(cfg.Resolver.ManagementSubnets) > 0 {
b.WriteString(" management_subnets:\n")
for _, s := range cfg.Resolver.ManagementSubnets {
fmt.Fprintf(&b, " - %s\n", s)
}
}
if cfg.Resolver.InterfaceName != "" {
fmt.Fprintf(&b, " interface_name: %q\n", cfg.Resolver.InterfaceName)
}
if cfg.Resolver.HostnameDomain != "" {
fmt.Fprintf(&b, " hostname_domain: %q\n", cfg.Resolver.HostnameDomain)
}
b.WriteString("\ncache:\n")
fmt.Fprintf(&b, " ttl: %d\n", cfg.Cache.TTL)
if cfg.Cache.Path != "" {
fmt.Fprintf(&b, " path: %q\n", cfg.Cache.Path)
}
b.WriteString("\nssh:\n")
if cfg.SSH.DefaultUser != "" {
fmt.Fprintf(&b, " default_user: %q\n", cfg.SSH.DefaultUser)
}
if cfg.SSH.DefaultPort > 0 {
fmt.Fprintf(&b, " default_port: %d\n", cfg.SSH.DefaultPort)
}
writeSSHOptions(&b, " ", cfg.SSH.SSHOptions)
if len(cfg.SSH.Rules) > 0 {
b.WriteString(" rules:\n")
for _, rule := range cfg.SSH.Rules {
b.WriteString(" - match:\n")
for _, field := range [][2]string{{"tag", rule.Match.Tag}, {"instance", rule.Match.Instance}, {"kind", rule.Match.Kind}, {"name", rule.Match.Name}} {
if field[1] != "" {
fmt.Fprintf(&b, " %s: %q\n", field[0], field[1])
}
}
writeSSHOptions(&b, " ", rule.SSHOptions)
}
}
if len(cfg.Hosts) > 0 {
b.WriteString("\nhosts:\n")
for _, host := range cfg.Hosts {
fmt.Fprintf(&b, " - name: %q\n address: %q\n", host.Name, host.Address)
if host.User != "" {
fmt.Fprintf(&b, " user: %q\n", host.User)
}
if host.Port > 0 {
fmt.Fprintf(&b, " port: %d\n", host.Port)
}
if len(host.Tags) > 0 {
b.WriteString(" tags:\n")
for _, tag := range host.Tags {
fmt.Fprintf(&b, " - %q\n", tag)
}
}
if !sshOptionsEmpty(host.SSH) {
b.WriteString(" ssh:\n")
writeSSHOptions(&b, " ", host.SSH)
}
}
}
if len(cfg.Groups) > 0 {
b.WriteString("\ngroups:\n")
names := make([]string, 0, len(cfg.Groups))
for name := range cfg.Groups {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
quoted := make([]string, 0, len(cfg.Groups[name]))
for _, selector := range cfg.Groups[name] {
quoted = append(quoted, strconv.Quote(selector))
}
fmt.Fprintf(&b, " %s: [%s]\n", name, strings.Join(quoted, ", "))
}
}
if cfg.Multi != (config.MultiConfig{}) {
b.WriteString("\nmulti:\n")
if cfg.Multi.Multiplexer != "" {
fmt.Fprintf(&b, " multiplexer: %s\n", cfg.Multi.Multiplexer)
}
if cfg.Multi.PanesPerWindow > 0 {
fmt.Fprintf(&b, " panes_per_window: %d\n", cfg.Multi.PanesPerWindow)
}
for _, key := range [][2]string{{"sync_key", cfg.Multi.SyncKey}, {"solo_key", cfg.Multi.SoloKey}} {
if key[1] != "" {
fmt.Fprintf(&b, " %s: %q\n", key[0], key[1])
}
}
}
if cfg.Completion.MaxResults > 0 {
fmt.Fprintf(&b, "\ncompletion:\n max_results: %d\n", cfg.Completion.MaxResults)
}
if cfg.Shortcuts.Enabled() || cfg.Shortcuts.Show {
b.WriteString("\nshortcuts:\n")
if len(cfg.Shortcuts.Domains) > 0 {
b.WriteString(" domains:\n")
for _, d := range cfg.Shortcuts.Domains {
fmt.Fprintf(&b, " - %s\n", d)
}
}
if cfg.Shortcuts.StripHyphens {
b.WriteString(" strip_hyphens: true\n")
}
if len(cfg.Shortcuts.Rewrites) > 0 {
b.WriteString(" rewrites:\n")
for _, r := range cfg.Shortcuts.Rewrites {
fmt.Fprintf(&b, " - pattern: %q\n replace: %q\n", r.Pattern, r.Replace)
}
}
if cfg.Shortcuts.Show {
b.WriteString(" show: true\n")
}
}
if len(cfg.Commands) > 0 {
b.WriteString("\ncommands:\n")
var names []string
for name := range cfg.Commands {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
command := cfg.Commands[name]
fmt.Fprintf(&b, " %s:\n alias_prefix: %q\n args:\n", name, command.AliasPrefix)
for _, arg := range command.Args {
fmt.Fprintf(&b, " - %q\n", arg)
}
}
}
if cfg.Shell.Alias != "" {
fmt.Fprintf(&b, "\nshell:\n alias: %q\n", cfg.Shell.Alias)
}
if err := storage.WriteFile(path, []byte(strings.TrimLeft(b.String(), "\n")), 0o600); err != nil {
return fmt.Errorf("writing config: %w", err)
}
fmt.Printf("\nConfig saved → %s\n", path)
return nil
}
func sshOptionsEmpty(o config.SSHOptions) bool {
return o.ProxyJump == "" && o.HostKeyChecking == "" && o.Target == "" && o.AddressFamily == "" && len(o.ExtraArgs) == 0 && len(o.Options) == 0 && len(o.Forwards) == 0 && o.PreConnect == ""
}
// writeSSHOptions keeps settings the wizard does not ask for when it rewrites the config.
func writeSSHOptions(b *strings.Builder, indent string, o config.SSHOptions) {
for _, field := range [][2]string{{"proxy_jump", o.ProxyJump}, {"host_key_checking", o.HostKeyChecking}, {"target", o.Target}, {"address_family", o.AddressFamily}, {"pre_connect", o.PreConnect}} {
if field[1] != "" {
fmt.Fprintf(b, "%s%s: %q\n", indent, field[0], field[1])
}
}
if len(o.ExtraArgs) > 0 {
fmt.Fprintf(b, "%sextra_args:\n", indent)
for _, arg := range o.ExtraArgs {
fmt.Fprintf(b, "%s - %q\n", indent, arg)
}
}
if len(o.Options) > 0 {
keys := make([]string, 0, len(o.Options))
for key := range o.Options {
keys = append(keys, key)
}
sort.Strings(keys)
fmt.Fprintf(b, "%soptions:\n", indent)
for _, key := range keys {
fmt.Fprintf(b, "%s %s: %q\n", indent, key, o.Options[key])
}
}
if len(o.Forwards) > 0 {
names := make([]string, 0, len(o.Forwards))
for name := range o.Forwards {
names = append(names, name)
}
sort.Strings(names)
fmt.Fprintf(b, "%sforwards:\n", indent)
for _, name := range names {
f := o.Forwards[name]
for _, field := range [][2]string{{"local", f.Local}, {"remote", f.Remote}, {"dynamic", f.Dynamic}} {
if field[1] != "" {
fmt.Fprintf(b, "%s %s:\n%s %s: %q\n", indent, name, indent, field[0], field[1])
}
}
}
}
}
+700
View File
@@ -0,0 +1,700 @@
package setup
import (
"os"
"path/filepath"
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func TestSave_WritesFile(t *testing.T) {
dir := t.TempDir()
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
defer os.Setenv("XDG_CONFIG_HOME", orig)
cfg := config.Config{
NetBox: config.NetBoxConfig{
URL: "https://netbox.example.com",
Token: "nbt_abc123",
TokenVersion: 2,
},
SSH: config.SSHConfig{DefaultUser: "admin"},
Resolver: config.ResolverConfig{
Strategies: []string{"primary_ip", "management_subnet"},
ManagementSubnets: []string{"10.0.0.0/8"},
},
Cache: config.CacheConfig{TTL: 3600},
}
if err := save(cfg); err != nil {
t.Fatalf("save: %v", err)
}
data, err := os.ReadFile(filepath.Join(dir, "netssh.yaml"))
if err != nil {
t.Fatalf("reading saved file: %v", err)
}
content := string(data)
for _, want := range []string{
`"https://netbox.example.com"`,
`"nbt_abc123"`,
`token_version: 2`,
`- primary_ip`,
`- management_subnet`,
`- 10.0.0.0/8`,
`ttl: 3600`,
`"admin"`,
} {
if !strings.Contains(content, want) {
t.Errorf("saved config missing %q\nfull content:\n%s", want, content)
}
}
}
func TestSave_FilePermissions(t *testing.T) {
dir := t.TempDir()
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
defer os.Setenv("XDG_CONFIG_HOME", orig)
if err := save(config.Config{
NetBox: config.NetBoxConfig{URL: "http://x", Token: "t", TokenVersion: 1},
Cache: config.CacheConfig{TTL: 60},
}); err != nil {
t.Fatalf("save: %v", err)
}
info, err := os.Stat(filepath.Join(dir, "netssh.yaml"))
if err != nil {
t.Fatalf("stat: %v", err)
}
if perm := info.Mode().Perm(); perm != 0o600 {
t.Errorf("file permissions: got %o, want 600", perm)
}
}
func TestSave_OmitsEmptyOptionalFields(t *testing.T) {
dir := t.TempDir()
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
defer os.Setenv("XDG_CONFIG_HOME", orig)
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "http://x", Token: "t", TokenVersion: 1},
Cache: config.CacheConfig{TTL: 60},
// No DefaultUser, no ManagementSubnets, no InterfaceName
}
if err := save(cfg); err != nil {
t.Fatalf("save: %v", err)
}
data, _ := os.ReadFile(filepath.Join(dir, "netssh.yaml"))
content := string(data)
for _, absent := range []string{"default_user", "management_subnets", "interface_name"} {
if strings.Contains(content, absent) {
t.Errorf("config should not contain %q when field is empty\nfull content:\n%s", absent, content)
}
}
}
func TestSave_CreatesConfigDir(t *testing.T) {
dir := filepath.Join(t.TempDir(), "does", "not", "exist")
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
defer os.Setenv("XDG_CONFIG_HOME", orig)
if err := save(config.Config{
NetBox: config.NetBoxConfig{URL: "http://x", Token: "t", TokenVersion: 1},
Cache: config.CacheConfig{TTL: 60},
}); err != nil {
t.Fatalf("save should create missing directories: %v", err)
}
}
func TestSave_DefaultPort(t *testing.T) {
dir := t.TempDir()
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
defer os.Setenv("XDG_CONFIG_HOME", orig)
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "http://x", Token: "t", TokenVersion: 1},
Cache: config.CacheConfig{TTL: 60},
SSH: config.SSHConfig{DefaultPort: 2222},
}
if err := save(cfg); err != nil {
t.Fatalf("save: %v", err)
}
data, _ := os.ReadFile(filepath.Join(dir, "netssh.yaml"))
if !strings.Contains(string(data), "default_port: 2222") {
t.Errorf("expected default_port: 2222 in config, got:\n%s", string(data))
}
}
func TestSave_Shortcuts_WritesSection(t *testing.T) {
dir := t.TempDir()
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
defer os.Setenv("XDG_CONFIG_HOME", orig)
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "http://x", Token: "t", TokenVersion: 1},
Cache: config.CacheConfig{TTL: 60},
Shortcuts: config.ShortcutsConfig{
Domains: []string{".example.com"},
StripHyphens: true,
},
}
if err := save(cfg); err != nil {
t.Fatalf("save: %v", err)
}
data, _ := os.ReadFile(filepath.Join(dir, "netssh.yaml"))
content := string(data)
for _, want := range []string{"shortcuts:", "domains:", ".example.com", "strip_hyphens: true"} {
if !strings.Contains(content, want) {
t.Errorf("expected %q in config, got:\n%s", want, content)
}
}
}
func TestSave_OmitsDefaultPortWhenZero(t *testing.T) {
dir := t.TempDir()
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
defer os.Setenv("XDG_CONFIG_HOME", orig)
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "http://x", Token: "t", TokenVersion: 1},
Cache: config.CacheConfig{TTL: 60},
SSH: config.SSHConfig{DefaultPort: 0},
}
if err := save(cfg); err != nil {
t.Fatalf("save: %v", err)
}
data, _ := os.ReadFile(filepath.Join(dir, "netssh.yaml"))
if strings.Contains(string(data), "default_port") {
t.Errorf("default_port should be omitted when zero, got:\n%s", string(data))
}
}
func TestSave_OmitsShortcutsWhenEmpty(t *testing.T) {
dir := t.TempDir()
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
defer os.Setenv("XDG_CONFIG_HOME", orig)
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "http://x", Token: "t", TokenVersion: 1},
Cache: config.CacheConfig{TTL: 60},
Shortcuts: config.ShortcutsConfig{}, // empty
}
if err := save(cfg); err != nil {
t.Fatalf("save: %v", err)
}
data, _ := os.ReadFile(filepath.Join(dir, "netssh.yaml"))
if strings.Contains(string(data), "shortcuts:") {
t.Errorf("shortcuts section should be omitted when empty, got:\n%s", string(data))
}
}
func TestSave_Roundtrip_WithNewFields(t *testing.T) {
dir := t.TempDir()
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
defer os.Setenv("XDG_CONFIG_HOME", orig)
original := config.Config{
NetBox: config.NetBoxConfig{
URL: "https://netbox.example.com",
Token: "nbt_test",
TokenVersion: 2,
},
SSH: config.SSHConfig{
DefaultUser: "admin",
DefaultPort: 2222,
},
Resolver: config.ResolverConfig{
Strategies: []string{"primary_ip"},
},
Cache: config.CacheConfig{TTL: 3600},
Shortcuts: config.ShortcutsConfig{
Domains: []string{".example.com", ".example.de"},
StripHyphens: true,
},
}
if err := save(original); err != nil {
t.Fatalf("save: %v", err)
}
loaded, err := config.Load()
if err != nil {
t.Fatalf("Load after save: %v", err)
}
if loaded.SSH.DefaultPort != original.SSH.DefaultPort {
t.Errorf("DefaultPort: got %d, want %d", loaded.SSH.DefaultPort, original.SSH.DefaultPort)
}
if len(loaded.Shortcuts.Domains) != len(original.Shortcuts.Domains) {
t.Errorf("Shortcuts.Domains length: got %d, want %d", len(loaded.Shortcuts.Domains), len(original.Shortcuts.Domains))
} else {
for i, d := range original.Shortcuts.Domains {
if loaded.Shortcuts.Domains[i] != d {
t.Errorf("Shortcuts.Domains[%d]: got %q, want %q", i, loaded.Shortcuts.Domains[i], d)
}
}
}
if loaded.Shortcuts.StripHyphens != original.Shortcuts.StripHyphens {
t.Errorf("StripHyphens: got %v, want %v", loaded.Shortcuts.StripHyphens, original.Shortcuts.StripHyphens)
}
}
func TestParseStrategies(t *testing.T) {
tests := []struct {
in string
want []string
}{
{"primary_ip", []string{"primary_ip"}},
{"management_subnet, primary_ip", []string{"management_subnet", "primary_ip"}},
{"primary_ip,management_subnet,interface_name", []string{"primary_ip", "management_subnet", "interface_name"}},
{" primary_ip , management_subnet ", []string{"primary_ip", "management_subnet"}},
{"", nil},
{" , ", nil},
}
for _, tt := range tests {
got := parseStrategies(tt.in)
if len(got) != len(tt.want) {
t.Errorf("parseStrategies(%q): got %v, want %v", tt.in, got, tt.want)
continue
}
for i := range got {
if got[i] != tt.want[i] {
t.Errorf("parseStrategies(%q)[%d]: got %q, want %q", tt.in, i, got[i], tt.want[i])
}
}
}
}
func TestParseStrategies_PreservesOrder(t *testing.T) {
got := parseStrategies("interface_name, management_subnet, primary_ip")
want := []string{"interface_name", "management_subnet", "primary_ip"}
for i, s := range got {
if s != want[i] {
t.Errorf("order not preserved at [%d]: got %q, want %q", i, s, want[i])
}
}
}
func TestValidateStrategiesHostname(t *testing.T) {
if err := validateStrategies("primary_ip, hostname"); err != nil {
t.Fatal(err)
}
}
func TestValidateStrategies_Valid(t *testing.T) {
cases := []string{
"primary_ip",
"management_subnet, primary_ip",
"interface_name, management_subnet, primary_ip",
}
for _, c := range cases {
if err := validateStrategies(c); err != nil {
t.Errorf("validateStrategies(%q) should be valid, got: %v", c, err)
}
}
}
func TestValidateStrategies_Invalid(t *testing.T) {
cases := []string{
"",
"unknown_strategy",
"primary_ip, typo",
}
for _, c := range cases {
if err := validateStrategies(c); err == nil {
t.Errorf("validateStrategies(%q) should return an error", c)
}
}
}
func TestSave_RoundtripViaLoad(t *testing.T) {
dir := t.TempDir()
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
defer os.Setenv("XDG_CONFIG_HOME", orig)
original := config.Config{
NetBox: config.NetBoxConfig{
URL: "https://netbox.zb-server.de",
Token: "nbt_supersecret",
TokenVersion: 2,
},
SSH: config.SSHConfig{DefaultUser: "root"},
Resolver: config.ResolverConfig{
Strategies: []string{"primary_ip"},
ManagementSubnets: []string{"192.168.0.0/16"},
InterfaceName: "eth0",
},
Cache: config.CacheConfig{TTL: 7200},
}
if err := save(original); err != nil {
t.Fatalf("save: %v", err)
}
loaded, err := config.Load()
if err != nil {
t.Fatalf("Load after save: %v", err)
}
if loaded.NetBox.URL != original.NetBox.URL {
t.Errorf("URL: got %q, want %q", loaded.NetBox.URL, original.NetBox.URL)
}
if loaded.NetBox.Token != original.NetBox.Token {
t.Errorf("Token: got %q, want %q", loaded.NetBox.Token, original.NetBox.Token)
}
if loaded.NetBox.TokenVersion != original.NetBox.TokenVersion {
t.Errorf("TokenVersion: got %d, want %d", loaded.NetBox.TokenVersion, original.NetBox.TokenVersion)
}
if loaded.SSH.DefaultUser != original.SSH.DefaultUser {
t.Errorf("DefaultUser: got %q, want %q", loaded.SSH.DefaultUser, original.SSH.DefaultUser)
}
if loaded.Cache.TTL != original.Cache.TTL {
t.Errorf("TTL: got %d, want %d", loaded.Cache.TTL, original.Cache.TTL)
}
}
func TestSaveCommandAliasRoundtripAndDisable(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{Shell: config.ShellConfig{Alias: "j"}, Cache: config.CacheConfig{Path: filepath.Join(t.TempDir(), "hosts.json")}}
if err := save(cfg); err != nil {
t.Fatal(err)
}
loaded, err := config.Load()
if err != nil || loaded.Shell.Alias != "j" || loaded.Cache.Path != cfg.Cache.Path {
t.Fatalf("roundtrip: %+v, %v", loaded, err)
}
cfg.Shell.Alias = ""
if err := save(cfg); err != nil {
t.Fatal(err)
}
loaded, err = config.Load()
if err != nil || loaded.Shell.Alias != "" {
t.Fatalf("disable: %+v, %v", loaded, err)
}
}
func TestSaveMultipleNetBoxesRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{
{Name: "office", URL: "https://office.example/netbox", Token: "nbt_secret: office", TokenVersion: 2, DisablePrefix: true},
{Name: "lab", URL: "https://lab.example", Token: "legacy#token", TokenVersion: 1},
},
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
Cache: config.CacheConfig{TTL: 3600},
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
loaded, err := config.Load()
if err != nil {
t.Fatal(err)
}
if len(loaded.NetBoxes) != 2 || loaded.NetBox.URL != "" {
t.Fatalf("instances lost during save: %+v", loaded)
}
for i, want := range cfg.NetBoxes {
if !reflect.DeepEqual(loaded.NetBoxes[i], want) {
t.Fatalf("instance changed: %+v, want %+v", loaded.NetBoxes[i], want)
}
}
info, err := os.Stat(config.Path())
if err != nil {
t.Fatal(err)
}
if info.Mode().Perm() != 0o600 {
t.Fatal("credentials are not private")
}
}
func TestSaveKeepsSSHOptions(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("HOME", t.TempDir())
opts := config.SSHOptions{
ProxyJump: "jh.example.com",
HostKeyChecking: "accept-new",
Target: "name",
AddressFamily: "inet",
ExtraArgs: []string{"-A"},
Options: map[string]string{"serveraliveinterval": "60"},
PreConnect: `vpn-check "$NETSSH_HOST" && echo 'ok'`,
}
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://prod.example", Token: "t", TokenVersion: 1, SSH: config.SSHOptions{HostKeyChecking: "off", PreConnect: "none"}}},
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
Cache: config.CacheConfig{TTL: 3600},
SSH: config.SSHConfig{
DefaultUser: "root",
SSHOptions: opts,
Rules: []config.SSHRule{{Match: config.SSHMatch{Tag: "dmz", Name: "*.dmz"}, SSHOptions: config.SSHOptions{ProxyJump: "none"}}},
},
Completion: config.CompletionConfig{MaxResults: 100},
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
loaded, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(loaded.SSH, cfg.SSH) || !reflect.DeepEqual(loaded.NetBoxes[0].SSH, cfg.NetBoxes[0].SSH) || loaded.Completion != cfg.Completion {
t.Fatalf("ssh settings lost:\n%+v\n%+v", loaded.SSH, loaded.NetBoxes[0].SSH)
}
}
// Re-running the configurator must keep settings that have no form field of
// their own or were not touched in the menu.
func TestPrepareKeepsUnmanagedSettings(t *testing.T) {
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "https://legacy.example", Token: "t"},
SSH: config.SSHConfig{
DefaultUser: "root",
SSHOptions: config.SSHOptions{ProxyJump: "jh.example.com", Options: map[string]string{"forwardagent": "yes"}},
Rules: []config.SSHRule{{Match: config.SSHMatch{Tag: "dmz"}, SSHOptions: config.SSHOptions{ProxyJump: "none"}}},
},
Completion: config.CompletionConfig{MaxResults: 50},
Cache: config.CacheConfig{Path: "/var/cache/netssh/hosts.json"},
}
sources := []config.NetBoxConfig{{Name: "default", URL: "https://legacy.example", Token: "t"}}
got := prepare(cfg, sources)
if !reflect.DeepEqual(got.SSH, cfg.SSH) || got.Completion != cfg.Completion || got.Cache.Path != cfg.Cache.Path {
t.Fatalf("settings lost: %+v", got)
}
if got.NetBox.URL != "" || !reflect.DeepEqual(got.NetBoxes, sources) {
t.Fatalf("legacy instance not migrated: %+v / %+v", got.NetBox, got.NetBoxes)
}
if !reflect.DeepEqual(got.Resolver.Strategies, []string{"primary_ip"}) || got.Cache.TTL != 3600 {
t.Fatalf("defaults missing: %+v %+v", got.Resolver, got.Cache)
}
}
func TestSaveRejectsInvalidSSHOptions(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("HOME", t.TempDir())
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://prod.example", Token: "t"}},
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
SSH: config.SSHConfig{Rules: []config.SSHRule{{SSHOptions: config.SSHOptions{ProxyJump: "none"}}}},
}
if err := save(cfg); err == nil {
t.Fatal("rule without match was saved")
}
if _, err := os.Stat(config.Path()); !os.IsNotExist(err) {
t.Fatalf("config file written despite error: %v", err)
}
}
func TestParseRewrites(t *testing.T) {
text := `^([a-z]+)[0-9]+- => $1
\.lab$ =>
`
got, err := parseRewrites(text)
if err != nil {
t.Fatal(err)
}
want := []config.ShortcutRewrite{{Pattern: `^([a-z]+)[0-9]+-`, Replace: "$1"}, {Pattern: `\.lab$`, Replace: ""}}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %+v", got)
}
if again, _ := parseRewrites(formatRewrites(got)); !reflect.DeepEqual(again, want) {
t.Fatalf("roundtrip: %+v", again)
}
for _, bad := range []string{"no arrow", "[a- => x", " => x"} {
if _, err := parseRewrites(bad); err == nil {
t.Errorf("%q accepted", bad)
}
}
}
func TestSaveShortcutRewritesRoundtrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("HOME", t.TempDir())
rewrites := []config.ShortcutRewrite{{Pattern: `^([a-z]+)[0-9]+-`, Replace: "$1"}, {Pattern: `\.lab\.example\.com$`, Replace: `"q"`}}
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://prod.example", Token: "t"}},
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
Shortcuts: config.ShortcutsConfig{Rewrites: rewrites},
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
loaded, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(loaded.Shortcuts.Rewrites, rewrites) {
t.Fatalf("got %+v", loaded.Shortcuts.Rewrites)
}
}
func TestSaveForwardsRoundtrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("HOME", t.TempDir())
global := map[string]config.Forward{"web": {Local: "8080:localhost:80"}, "socks": {Dynamic: "1080"}}
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://prod.example", Token: "t", SSH: config.SSHOptions{Forwards: map[string]config.Forward{"db": {Local: "5432:localhost:5432"}}}}},
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
SSH: config.SSHConfig{
SSHOptions: config.SSHOptions{Forwards: global},
Rules: []config.SSHRule{{Match: config.SSHMatch{Tag: "dmz"}, SSHOptions: config.SSHOptions{Forwards: map[string]config.Forward{"back": {Remote: "9000:localhost:9000"}}}}},
},
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
loaded, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(loaded.SSH.Forwards, global) ||
!reflect.DeepEqual(loaded.NetBoxes[0].SSH.Forwards, cfg.NetBoxes[0].SSH.Forwards) ||
!reflect.DeepEqual(loaded.SSH.Rules[0].Forwards, cfg.SSH.Rules[0].Forwards) {
t.Fatalf("forwards lost: %+v / %+v / %+v", loaded.SSH.Forwards, loaded.NetBoxes[0].SSH.Forwards, loaded.SSH.Rules)
}
}
func TestSaveStaticHostsRoundtrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("HOME", t.TempDir())
hosts := []config.StaticHost{
{Name: "router", Address: "192.168.1.1", User: "admin", Port: 2222, Tags: []string{"home"}, SSH: config.SSHOptions{ProxyJump: "none"}},
{Name: "nas", Address: "nas.example.org"},
}
cfg := config.Config{
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip", "hostname"}, HostnameDomain: "example.com"},
Hosts: hosts,
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(config.Path())
if strings.Contains(string(data), "netbox:") {
t.Fatalf("static-only config got an empty netbox section:\n%s", data)
}
loaded, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(loaded.Hosts, hosts) || loaded.Resolver.HostnameDomain != "example.com" || loaded.HasNetBox() {
t.Fatalf("got %+v / %+v", loaded.Hosts, loaded.Resolver)
}
}
func TestValidateHostIn(t *testing.T) {
hosts := []config.StaticHost{{Name: "router", Address: "10.0.0.1"}, {Name: "nas", Address: "10.0.0.2"}}
if err := validateHostIn(config.StaticHost{Name: "Router", Address: "10.0.0.9"}, hosts, -1); err == nil {
t.Fatal("duplicate name accepted")
}
if err := validateHostIn(config.StaticHost{Name: "router", Address: "10.0.0.9"}, hosts, 0); err != nil {
t.Fatalf("editing a host in place rejected: %v", err)
}
if err := validateHostIn(config.StaticHost{Name: "new"}, hosts, -1); err != nil {
t.Fatalf("empty address while typing rejected: %v", err)
}
if err := validateHostIn(config.StaticHost{Name: "new", Address: "a b"}, hosts, -1); err == nil {
t.Fatal("invalid address accepted")
}
}
func TestParseGroupsAndSaveMulti(t *testing.T) {
groups, err := parseGroups("K8s: master1, tag:k8s-worker\npve: cluster:pve-fsn1 @k8s\n")
want := map[string][]string{"k8s": {"master1", "tag:k8s-worker"}, "pve": {"cluster:pve-fsn1", "@k8s"}}
if err != nil || !reflect.DeepEqual(groups, want) {
t.Fatalf("got %v %v", groups, err)
}
if again, _ := parseGroups(formatGroups(groups)); !reflect.DeepEqual(again, want) {
t.Fatalf("roundtrip: %v", again)
}
for _, bad := range []string{"no colon", "tag:x", "bad name: a", "empty:"} {
if _, err := parseGroups(bad); err == nil {
t.Errorf("%q accepted", bad)
}
}
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("HOME", t.TempDir())
cfg := config.Config{
Hosts: []config.StaticHost{{Name: "a", Address: "10.0.0.1"}},
Groups: groups,
Multi: config.MultiConfig{Multiplexer: "zellij", PanesPerWindow: 4},
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
loaded, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(loaded.Groups, want) || loaded.Multi != cfg.Multi {
t.Fatalf("got %v %+v", loaded.Groups, loaded.Multi)
}
}
func TestSaveKeepsShortcutsShow(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("HOME", t.TempDir())
for _, sc := range []config.ShortcutsConfig{
{Domains: []string{".example.com"}, Show: true},
{Show: true}, // no shortcut rules yet: the switch alone must survive
} {
cfg := config.Config{
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
Cache: config.CacheConfig{TTL: 3600},
Shortcuts: sc,
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
loaded, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !loaded.Shortcuts.Show || !reflect.DeepEqual(loaded.Shortcuts.Domains, sc.Domains) {
t.Fatalf("shortcuts lost: %+v", loaded.Shortcuts)
}
}
}
func TestSaveCommandsRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "https://netbox.example", Token: "test"},
Commands: map[string]config.HostCommand{
"mtr": {AliasPrefix: "m", Args: []string{"mtr", "--report", "{address}"}},
"ping": {AliasPrefix: "p", Args: []string{"ping", "-c", "3", "{address}"}},
},
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
got, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got.Commands, cfg.Commands) {
t.Fatalf("commands lost: %+v", got.Commands)
}
}