diff --git a/CHANGELOG.md b/CHANGELOG.md index 39a11ea..ff7b0cd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,13 @@ # Changelog +## v1.3.0 + +- Unknown names are resolved through DNS, and the hosts owning the address in NetBox or the cache are suggested, together with a direct connection to the DNS name. Without a terminal the suggestions are part of the error. `netssh info`, `open` and `whois` use it too. +- Add `dns.domains`: domain rules per name pattern for short names (`mx*` → `easysahre.de`, `ah*` → `jhfduwia.de`), independent of `shortcuts.domains`. +- Add `dns.suggest` and `dns.save_link` (`ask`, `always`, `never`) to always accept or always decline the host suggestion and the shortcut offer; `always` also works in scripts. Both are in `netssh configure`. +- Add links (`links:` in the config, `netssh link add|list|remove`): `netssh mx123` and the shell alias `mx123` connect to the linked host. netssh offers to save a link after a DNS suggestion. +- Generated command aliases honour command restrictions on site, role, platform, tenant and status. + ## v1.2.0 - Add `netssh info HOST` and `Ctrl+L` in the TUI: site, rack/U, role, platform, tenant, device type, serial, VM resources and all IP addresses per interface from NetBox; `--json` for scripts. diff --git a/README.md b/README.md index 87c6dbf..7ac3c57 100644 --- a/README.md +++ b/README.md @@ -58,6 +58,7 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int - **Port forwarding** — named forwards in the config (`netssh tunnel host web`, `netssh --forward web host`), ad hoc specs, and `Ctrl+T` in the TUI - **Dry run** — `netssh --dry-run host` prints the final `ssh` command instead of connecting - **Host details** — `netssh info host` (and `Ctrl+L` in the TUI) shows site, the nested locations down to rack and rack units, role, platform, tenant, status and all IP addresses per interface; `netssh open host` (`Ctrl+G`) opens the NetBox page +- **DNS names and links** — `netssh mx123.webseite.de` (or `netssh mx123`) for a name that is only in DNS: netssh finds the host owning the address in NetBox, suggests it, and can save `mx123` as a link — `netssh mx123` and the shell alias `mx123` then connect directly - **Reverse lookup** — `netssh whois 10.1.2.3` names the device or VM, interface, DNS name and prefixes of an address - **Status warning** — asks before connecting to hosts that are `offline`, `planned`, `decommissioning` …; TUI badge and `status:` filter - **Configurable TUI** — choose what is shown next to each host (`tui.columns`: IP, source, status, site, location path, role, platform, tenant, cluster, tags, kind, alias); the optional `reachability` column marks hosts ✓/✗ after a quick TCP check of their SSH port; `resolver.fallback` connects to another known address when the chosen one does not answer @@ -258,6 +259,10 @@ Every key, its default, and the section that explains it. Keys marked *layered* | `hosts[]` | list | `[]` | Static hosts with `name`, `address`, `user`, `port`, `tags`, `ssh` — see [Static hosts](#static-hosts). | | `commands` | map | `{}` | Local command rules with `alias_prefix` and argument list `args`; see [Custom host commands](#custom-host-commands). | | `groups` | map of lists | `{}` | Named host lists for `netssh multi @NAME`; entries are hosts or selectors. | +| `dns.suggest` | `ask` \| `always` \| `never` | `ask` | Unknown names: suggest the host owning the DNS address (`ask`), take the first suggestion without asking, also in scripts (`always`), or do no DNS lookup (`never`) — see [DNS names and links](#dns-names-and-links). | +| `dns.save_link` | `ask` \| `always` \| `never` | `ask` | Save a link after a suggestion: ask, always, or never. | +| `dns.domains[]` | list | `[]` | `match` (glob on the typed name, e.g. `mx*`; empty = all) and `domain` appended to names without a dot. | +| `links` | map | `{}` | Short names for hosts, `mx123: prod/web07`: `netssh mx123` and the shell alias `mx123` connect to the host — see [DNS names and links](#dns-names-and-links). | | `multi.multiplexer` | `auto` \| `tmux` \| `zellij` | `auto` | Which multiplexer `netssh multi` uses. | | `multi.panes_per_window` | int | `9` | More hosts open in further tmux windows or zellij tabs. | | `multi.sync_key`, `multi.solo_key` | tmux key \| `none` | `S`, `e` | Keys after the tmux prefix: broadcast to all panes, exclude/include the current pane. | @@ -280,6 +285,7 @@ These variables override the file. Lists are comma-separated (`NETSSH_SHORTCUTS_ | `NETSSH_COMPLETION_MAX_RESULTS` | `completion.max_results` | | `NETSSH_MULTI_MULTIPLEXER`, `NETSSH_MULTI_PANES_PER_WINDOW` | `multi.*` | | `NETSSH_SHELL_ALIAS` | `shell.alias` | +| `NETSSH_DNS_SUGGEST`, `NETSSH_DNS_SAVE_LINK` | `dns.suggest`, `dns.save_link` | netssh also respects `XDG_CONFIG_HOME`, `XDG_CACHE_HOME`, `ZDOTDIR`, and `SHELL` (for `hook install`, `completion install`, and `alias` without `--shell`). @@ -429,6 +435,7 @@ To keep tokens out of the config file, store them in the system keyring with | `netssh scp [netssh flags] [scp options] SOURCE... TARGET` | Copy files — see [SFTP and SCP](#sftp-and-scp). | | `netssh doctor [--online]` / `netssh explain HOST` | Diagnose configuration and explain effective settings. | | `netssh info [--json] HOST` / `netssh open [--print] HOST` | Show NetBox details of a host / open its NetBox page — see [Host details](#host-details-and-netbox-page). | +| `netssh link list \| add NAME HOST \| remove NAME` | Short names for hosts — see [DNS names and links](#dns-names-and-links). | | `netssh whois [--json] ADDRESS\|HOSTNAME` | Find the host, interface and prefix of an address — see [Reverse lookup](#reverse-lookup). | | `netssh copy-id [-i KEY] [-l U] [--dry-run] HOST\|tag:T\|cluster:C\|@GROUP...` | Install your public key with ssh-copy-id — see [ssh-copy-id](#ssh-copy-id). | | `netssh known-hosts reset [--yes] [--dry-run] HOST...` | Remove stored host keys of re-deployed hosts — see [known_hosts cleanup](#known_hosts-cleanup). | @@ -1401,6 +1408,75 @@ All NetBox instances are queried; prefixes are listed from the widest to the most specific. The exit code is 1 when nothing is found. A failing instance is reported as a warning without hiding the answers of the others. +### DNS names and links + +Customers and colleagues often know a host by a DNS name such as +`mx123.webseite.de` that is not the device or VM name in NetBox. When netssh +finds a name neither in NetBox nor in the cache, it resolves it through DNS, +looks the addresses up in NetBox (and the cache) and suggests the hosts that +own them: + +``` +$ netssh mx123.webseite.de +netssh: "mx123.webseite.de" is not in NetBox or the cache. DNS: mx123.webseite.de → 203.0.113.5 + 1) prod/web07 203.0.113.5 on eth0 (NetBox) + 2) connect directly to mx123.webseite.de +Choose [1-2, Enter = 1, q = cancel]: +Save shortcut "mx123" → prod/web07 (netssh mx123, shell alias mx123)? [y/N or another name]: y +``` + +- Short names get their domain from `dns.domains` (see below), so `netssh mx123` + looks up `mx123.easysahre.de`. `shortcuts.domains` are not used here. +- Choosing a host connects with all of its settings (user, port, jump host, + rules). "Directly" connects to the DNS name with the global settings. +- The shortcut offer saves a **link** under `links:` in the config: from then on + `netssh mx123` connects to `prod/web07` without asking, and new shells get + the alias `mx123` (it also completes with ``). Answer with another name + to choose it, or `n` to skip. +- Without a terminal (scripts) netssh does not choose, unless `dns.suggest: + always`: the error lists the suggestions, e.g. + `netssh prod/web07 # 203.0.113.5 on eth0 (NetBox)`. +- `netssh info` and `netssh open` use the same suggestion, and `netssh whois mx123` + also uses `dns.domains`. + +```yaml +dns: + suggest: ask # ask | always (first suggestion, also in scripts) | never (no DNS lookup) + save_link: ask # ask | always (save the shortcut without asking) | never + domains: # tried in order for names without a dot + - match: "mx*" # shell glob on the typed name + domain: easysahre.de + - match: "ah*" + domain: jhfduwia.de + # - domain: example.com # without match: every name +``` + +A name without a dot gets the domain of every matching rule (`mx123` → +`mx123.easysahre.de`); only when no rule matches is the bare name looked up, +using the system resolver's search domains. A name with a dot is looked up as +typed. With `suggest: always` netssh connects to the first suggestion (NetBox +hosts first), or directly to the DNS name when no host owns the address. All +three settings are also in `netssh configure` → **Resolver & cache**. + +Manage links directly: + +```sh +netssh link add mx123 prod/web07 # or: netssh link add mx123 mx123.webseite.de +netssh link list +netssh link remove mx123 +``` + +```yaml +links: + mx123: "prod/web07" + shop: "lab/web1" +``` + +A link points to a host netssh knows (NetBox or static host), not to another +link; its name must not be a static host. Links take precedence over NetBox +names. The target is fixed: if the DNS name later points elsewhere, update the +link. + ### Status warning Connecting to a host whose NetBox status is listed in `ssh.warn_status` asks first: diff --git a/cmd/netssh/dns_suggest.go b/cmd/netssh/dns_suggest.go new file mode 100644 index 0000000..249ace0 --- /dev/null +++ b/cmd/netssh/dns_suggest.go @@ -0,0 +1,301 @@ +package main + +import ( + "bufio" + "context" + "errors" + "fmt" + "io" + "os" + "sort" + "strconv" + "strings" + "time" + + "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" + "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox" + internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh" +) + +// dnsSuggestion is a host that owns an address the queried name resolves to. +type dnsSuggestion struct { + target string // host selector, e.g. prod/web07 + reason string // e.g. "203.0.113.5 on eth0 (NetBox)" +} + +// dnsMatch is what a DNS lookup of an unknown name found. +type dnsMatch struct { + name string // the DNS name that resolved, e.g. mx123.webseite.de + addresses []string // its addresses + suggestions []dnsSuggestion +} + +// offerLinkFunc is offerLink; link add replaces it to avoid a second question. +// The first argument is dns.save_link. +var offerLinkFunc = offerLink + +// promptInput is replaced in tests. +var promptInput io.Reader = os.Stdin + +// promptReader buffers promptInput once, so that consecutive questions do +// not lose answers that a previous reader had already buffered. +var ( + promptReader *bufio.Reader + promptSource io.Reader +) + +func readAnswer() (string, error) { + if promptReader == nil || promptSource != promptInput { + promptReader, promptSource = bufio.NewReader(promptInput), promptInput + } + line, err := promptReader.ReadString('\n') + if err != nil && err != io.EOF { + return "", err + } + return strings.TrimSpace(line), nil +} + +// dnsNames lists the DNS names to try for query, following dns.domains. +func dnsNames(cfg *config.Config, query string) []string { + if !plainName(query) { + return nil + } + return cfg.DNS.Names(query) +} + +// lookupDNS resolves the first of names that has addresses. +func lookupDNS(ctx context.Context, names []string) (string, []string) { + for _, name := range names { + addresses, err := lookupHost(ctx, name) + if err == nil && len(addresses) > 0 { + return name, addresses + } + } + return "", nil +} + +// findDNSMatch resolves query through DNS and finds the hosts in NetBox and +// the cache that own the addresses. It returns nil when DNS knows no address. +func findDNSMatch(ctx context.Context, cfg *config.Config, query string) *dnsMatch { + if source, _ := netbox.SplitTarget(query); source != "" { + return nil + } + name, addresses := lookupDNS(ctx, dnsNames(cfg, query)) + if name == "" { + return nil + } + match := &dnsMatch{name: name, addresses: addresses} + seen := map[string]bool{} + add := func(target, reason string) { + if target != "" && !seen[strings.ToLower(target)] { + seen[strings.ToLower(target)] = true + match.suggestions = append(match.suggestions, dnsSuggestion{target: target, reason: reason}) + } + } + if cfg.HasNetBox() { + client := newNetBoxClient(cfg) + for _, address := range addresses { + owners, err := client.LookupIP(ctx, address) + if err != nil { + fmt.Fprintf(os.Stderr, "netssh: warning: %v\n", err) + } + for _, owner := range owners { + reason := address + if owner.Interface != "" { + reason += " on " + owner.Interface + } + add(owner.Target(), reason+" (NetBox)") + } + } + } + c := newCache(cfg) + _ = c.Load() + entries := c.All() + sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name }) + for _, address := range addresses { + for _, e := range entries { + if e.IP == address { + source := "cache" + if e.Static { + source = "static host" + } + add(e.Name, address+" ("+source+")") + } + } + } + return match +} + +// resolveOrSuggest resolves host like resolveTargetE. When neither NetBox nor +// the cache know it, the name is resolved through DNS and the hosts owning +// its address are offered, in a terminal, together with a direct connection +// to the DNS name. Without a terminal the suggestion is part of the error. +func resolveOrSuggest(cfg *config.Config, host string, record bool) (resolvedHost, error) { + resolved, err := resolveTargetE(cfg, host, record) + if err == nil || !errors.Is(err, netbox.ErrHostNotFound) || cfg.DNS.SuggestMode() == config.DNSNever { + return resolved, err + } + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + match := findDNSMatch(ctx, cfg, host) + if match == nil { + return resolved, err + } + var ( + choice string + ok bool + promptErr error + ) + switch { + case cfg.DNS.SuggestMode() == config.DNSAlways: + choice, ok = match.first(host) + case !stdinIsTerminal(): + return resolved, fmt.Errorf("%w\n%s", err, match.describe()) + default: + choice, ok, promptErr = chooseDNSSuggestion(host, match) + } + if promptErr != nil { + return resolved, promptErr + } + if !ok { + return resolved, errors.New("cancelled") + } + if choice == "" { + if !internalssh.ValidAddress(match.name) { + return resolved, fmt.Errorf("refusing DNS name %q", match.name) + } + return resolvedHost{Name: host, Kind: "dns", IP: match.name, Origin: "dns"}, nil + } + resolved, err = resolveTargetE(cfg, choice, record) + if err != nil { + return resolved, err + } + offerLinkFunc(cfg.DNS.SaveLinkMode(), host, resolved.Name) + return resolved, nil +} + +// first takes the first suggestion for dns.suggest: always, or the DNS name +// itself when no host owns the address. +func (m *dnsMatch) first(query string) (string, bool) { + if len(m.suggestions) == 0 { + fmt.Fprintf(os.Stderr, "netssh: %s → %s (%s), no host owns it; connecting directly (dns.suggest: always)\n", query, m.name, strings.Join(m.addresses, ", ")) + return "", true + } + s := m.suggestions[0] + fmt.Fprintf(os.Stderr, "netssh: %s → %s, %s: connecting to %s (dns.suggest: always)\n", query, m.name, s.reason, s.target) + return s.target, true +} + +// describe renders the DNS result and the owning hosts for an error message. +func (m *dnsMatch) describe() string { + var b strings.Builder + fmt.Fprintf(&b, "DNS: %s → %s", m.name, strings.Join(m.addresses, ", ")) + if len(m.suggestions) == 0 { + fmt.Fprintf(&b, "; no host in NetBox or the cache has this address") + return b.String() + } + for _, s := range m.suggestions { + fmt.Fprintf(&b, "\n netssh %s # %s", s.target, s.reason) + } + return b.String() +} + +// chooseDNSSuggestion asks which host to connect to. It returns the chosen +// target, "" for a direct connection to the DNS name, and false on cancel. +func chooseDNSSuggestion(query string, m *dnsMatch) (string, bool, error) { + fmt.Fprintf(os.Stderr, "netssh: %q is not in NetBox or the cache. DNS: %s → %s\n", query, m.name, strings.Join(m.addresses, ", ")) + if len(m.suggestions) == 0 { + fmt.Fprintln(os.Stderr, "No host in NetBox or the cache has this address.") + } + for i, s := range m.suggestions { + fmt.Fprintf(os.Stderr, " %d) %s %s\n", i+1, s.target, s.reason) + } + direct := len(m.suggestions) + 1 + fmt.Fprintf(os.Stderr, " %d) connect directly to %s\n", direct, m.name) + fmt.Fprintf(os.Stderr, "Choose [1-%d, Enter = 1, q = cancel]: ", direct) + answer, err := readAnswer() + if err != nil { + return "", false, err + } + switch { + case answer == "": + answer = "1" + case strings.EqualFold(answer, "q"): + return "", false, nil + } + n, convErr := strconv.Atoi(answer) + if convErr != nil || n < 1 || n > direct { + return "", false, fmt.Errorf("invalid choice %q", answer) + } + if n == direct { + return "", true, nil + } + return m.suggestions[n-1].target, true, nil +} + +// linkName proposes a link name for what the user typed: the first label of +// a DNS name ("mx123" for mx123.webseite.de), else the input. +func linkName(query string) string { + if first, _, ok := strings.Cut(query, "."); ok && first != "" { + return strings.ToLower(first) + } + return strings.ToLower(query) +} + +// offerLink asks whether to save query as a link to target, so that the next +// netssh NAME (and the shell alias NAME) connects without asking. +func offerLink(mode, query, target string) { + name := linkName(query) + if strings.EqualFold(name, target) || mode == config.DNSNever { + return + } + if mode == config.DNSAlways { + if err := saveLink(name, target); err != nil { + fmt.Fprintf(os.Stderr, "netssh: shortcut not saved: %v\n", err) + return + } + fmt.Fprintf(os.Stderr, "netssh: saved shortcut %s → %s (dns.save_link: always)\n", name, target) + return + } + if !stdinIsTerminal() { + return + } + fmt.Fprintf(os.Stderr, "Save shortcut %q → %s (netssh %s, shell alias %s)? [y/N or another name]: ", name, target, name, name) + answer, err := readAnswer() + if err != nil { + return + } + switch strings.ToLower(answer) { + case "", "n", "no": + return + case "y", "yes", "j", "ja": + default: + name = strings.ToLower(answer) + } + if err := saveLink(name, target); err != nil { + fmt.Fprintf(os.Stderr, "netssh: shortcut not saved: %v\n", err) + return + } + fmt.Fprintf(os.Stderr, "netssh: saved; netssh %s now connects to %s (new shells also get the alias %s).\n", name, target, name) +} + +// saveLink adds a link to the config file and regenerates the shell aliases. +var saveLink = func(name, target string) error { + cfg, err := config.Load() + if err != nil { + return err + } + if cfg.Links == nil { + cfg.Links = map[string]string{} + } + for key := range cfg.Links { + if strings.EqualFold(key, name) { + delete(cfg.Links, key) + } + } + cfg.Links[name] = target + if err := cfg.ValidateLinks(); err != nil { + return err + } + return saveHostsTo(cfg, os.Stderr) +} diff --git a/cmd/netssh/dns_suggest_test.go b/cmd/netssh/dns_suggest_test.go new file mode 100644 index 0000000..13af199 --- /dev/null +++ b/cmd/netssh/dns_suggest_test.go @@ -0,0 +1,199 @@ +package main + +import ( + "context" + "errors" + "fmt" + "net/http" + "net/http/httptest" + "strings" + "testing" + + "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache" + "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" +) + +// dnsEnv: NetBox "prod" knows web07 (203.0.113.5 on eth0) but not mx123; +// DNS resolves mx123.webseite.de to 203.0.113.5. +func dnsEnv(t *testing.T, extra string) { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + switch r.URL.Path { + case "/api/ipam/ip-addresses/": + if r.URL.Query().Get("address") == "203.0.113.5" { + fmt.Fprint(w, `{"count":1,"results":[{"address":"203.0.113.5/24","assigned_object":{"name":"eth0","virtual_machine":{"id":7,"name":"web07"}}}]}`) + return + } + fmt.Fprint(w, `{"count":0,"results":[]}`) + case "/api/dcim/devices/", "/api/virtualization/virtual-machines/": + fmt.Fprint(w, `{"count":0,"results":[]}`) + default: + http.NotFound(w, r) + } + })) + t.Cleanup(srv.Close) + insightEnv(t, fmt.Sprintf("netboxes:\n - name: prod\n url: %s\n token: t\nshortcuts:\n domains: [shortcut.example]\ndns:\n domains:\n - match: \"mx*\"\n domain: webseite.de\n - match: \"ah*\"\n domain: other.example\n%s", srv.URL, extra)) + cfg, err := config.Load() + if err != nil { + t.Fatal(err) + } + c := cache.New(cfg.CachePath(), 3600) + c.Upsert(cache.Entry{Name: "prod/web07", IP: "203.0.113.5", Kind: "vm", ID: 7}) + if err := c.Save(); err != nil { + t.Fatal(err) + } + old := lookupHost + lookupHost = func(_ context.Context, name string) ([]string, error) { + if name == "mx123.webseite.de" { + return []string{"203.0.113.5"}, nil + } + if strings.HasSuffix(name, ".shortcut.example") { + t.Errorf("shortcut domain looked up: %s", name) + } + return nil, errors.New("no such host") + } + t.Cleanup(func() { lookupHost = old }) +} + +func answer(t *testing.T, input string) { + t.Helper() + old := promptInput + promptInput = strings.NewReader(input) + t.Cleanup(func() { promptInput = old }) +} + +func TestDNSNames(t *testing.T) { + cfg := &config.Config{ + Shortcuts: config.ShortcutsConfig{Domains: []string{"shortcut.example"}}, + DNS: config.DNSConfig{Domains: []config.DNSDomain{ + {Match: "mx*", Domain: "easysahre.de"}, {Match: "ah*", Domain: ".jhfduwia.de."}, {Match: "MX1*", Domain: "backup.de"}, + }}, + } + for query, want := range map[string]string{ + "mx123": "mx123.easysahre.de mx123.backup.de", + "ah123": "ah123.jhfduwia.de", + "web01": "web01", + "mx123.webseite.de": "mx123.webseite.de", + } { + if got := strings.Join(dnsNames(cfg, query), " "); got != want { + t.Errorf("%s: got %q, want %q", query, got, want) + } + } + cfg.DNS.Domains = append(cfg.DNS.Domains, config.DNSDomain{Domain: "fallback.de"}) + if got := strings.Join(dnsNames(cfg, "web01"), " "); got != "web01.fallback.de" { + t.Fatalf("rule without match: %q", got) + } + if dnsNames(cfg, "-oProxyCommand=x") != nil { + t.Fatal("option-like name looked up") + } +} + +func TestDNSSuggestionWithoutTerminalExplains(t *testing.T) { + dnsEnv(t, "") + stubTerminal(t, false) + cfg, _ := config.Load() + _, err := resolveOrSuggest(cfg, "mx123", false) + if err == nil { + t.Fatal("must not connect without asking") + } + for _, want := range []string{"host not found", "DNS: mx123.webseite.de → 203.0.113.5", "netssh prod/web07", "203.0.113.5 on eth0 (NetBox)"} { + if !strings.Contains(err.Error(), want) { + t.Errorf("missing %q in %v", want, err) + } + } +} + +func TestDNSSuggestionChooseHostAndSaveLink(t *testing.T) { + dnsEnv(t, "") + stubTerminal(t, true) + var saved [2]string + old := saveLink + saveLink = func(name, target string) error { saved = [2]string{name, target}; return nil } + t.Cleanup(func() { saveLink = old }) + answer(t, "\ny\n") + + cfg, _ := config.Load() + h, err := resolveOrSuggest(cfg, "mx123.webseite.de", false) + if err != nil { + t.Fatal(err) + } + if h.Name != "prod/web07" || h.IP != "203.0.113.5" { + t.Fatalf("resolved %+v", h) + } + if saved != [2]string{"mx123", "prod/web07"} { + t.Fatalf("link %v", saved) + } +} + +func TestDNSSuggestionDirectAndCancel(t *testing.T) { + dnsEnv(t, "") + stubTerminal(t, true) + cfg, _ := config.Load() + answer(t, "2\n") + h, err := resolveOrSuggest(cfg, "mx123", false) + if err != nil || h.Kind != "dns" || h.IP != "mx123.webseite.de" || h.Name != "mx123" { + t.Fatalf("direct: %+v %v", h, err) + } + answer(t, "q\n") + if _, err := resolveOrSuggest(cfg, "mx123", false); err == nil || err.Error() != "cancelled" { + t.Fatalf("cancel: %v", err) + } + answer(t, "7\n") + if _, err := resolveOrSuggest(cfg, "mx123", false); err == nil || !strings.Contains(err.Error(), "invalid choice") { + t.Fatalf("invalid: %v", err) + } + // Names DNS does not know keep the plain not-found error. + if _, err := resolveOrSuggest(cfg, "nothere", false); err == nil || strings.Contains(err.Error(), "DNS") { + t.Fatalf("unknown: %v", err) + } +} + +func stubSaveLink(t *testing.T) *[][2]string { + t.Helper() + var saved [][2]string + old := saveLink + saveLink = func(name, target string) error { saved = append(saved, [2]string{name, target}); return nil } + t.Cleanup(func() { saveLink = old }) + return &saved +} + +func TestDNSSuggestAlwaysWorksWithoutTerminal(t *testing.T) { + dnsEnv(t, " suggest: always\n save_link: always\n") + stubTerminal(t, false) + saved := stubSaveLink(t) + cfg, _ := config.Load() + h, err := resolveOrSuggest(cfg, "mx123", true) + if err != nil || h.Name != "prod/web07" { + t.Fatalf("always: %+v %v", h, err) + } + if len(*saved) != 1 || (*saved)[0] != [2]string{"mx123", "prod/web07"} { + t.Fatalf("save_link always: %v", *saved) + } +} + +func TestDNSSaveLinkNeverAndAskWithoutTerminal(t *testing.T) { + dnsEnv(t, " suggest: always\n save_link: never\n") + stubTerminal(t, false) + saved := stubSaveLink(t) + cfg, _ := config.Load() + if _, err := resolveOrSuggest(cfg, "mx123", false); err != nil || len(*saved) != 0 { + t.Fatalf("never: %v %v", *saved, err) + } + cfg.DNS.SaveLink = "" + if _, err := resolveOrSuggest(cfg, "mx123", false); err != nil || len(*saved) != 0 { + t.Fatalf("ask without terminal must not save: %v %v", *saved, err) + } +} + +func TestDNSSuggestNeverSkipsLookup(t *testing.T) { + dnsEnv(t, " suggest: never\n") + stubTerminal(t, true) + looked := false + old := lookupHost + lookupHost = func(context.Context, string) ([]string, error) { looked = true; return []string{"203.0.113.5"}, nil } + t.Cleanup(func() { lookupHost = old }) + cfg, _ := config.Load() + if _, err := resolveOrSuggest(cfg, "mx123", false); err == nil || looked { + t.Fatalf("never: looked=%v err=%v", looked, err) + } +} diff --git a/cmd/netssh/hosts.go b/cmd/netssh/hosts.go index 94b5e26..dfe70b7 100644 --- a/cmd/netssh/hosts.go +++ b/cmd/netssh/hosts.go @@ -2,6 +2,7 @@ package main import ( "fmt" + "io" "os" "strings" "text/tabwriter" @@ -146,8 +147,11 @@ func hostsRemoveCmd() *cobra.Command { } // saveHosts writes the config and regenerates the shell aliases. -func saveHosts(cfg *config.Config) error { - if err := setup.Save(*cfg); err != nil { +func saveHosts(cfg *config.Config) error { return saveHostsTo(cfg, os.Stdout) } + +// saveHostsTo writes the config, reporting to w, and regenerates the aliases. +func saveHostsTo(cfg *config.Config, w io.Writer) error { + if err := setup.SaveTo(*cfg, w); err != nil { return err } loaded, err := config.Load() diff --git a/cmd/netssh/insights.go b/cmd/netssh/insights.go index 6fc1e69..72fd23e 100644 --- a/cmd/netssh/insights.go +++ b/cmd/netssh/insights.go @@ -29,12 +29,15 @@ func hostCompletion(cmd *cobra.Command, args []string, toComplete string) ([]cob // netboxHost finds the NetBox record of a host given like on the command line // (shortcut, instance/host). The cache supplies the ID when it has one. func netboxHost(ctx context.Context, cfg *config.Config, target string) (netbox.HostEntry, *netbox.Client, resolvedHost, error) { - h, err := resolveTargetE(cfg, target, false) + h, err := resolveOrSuggest(cfg, target, false) if err != nil { return netbox.HostEntry{}, nil, h, err } - if h.Kind == config.StaticKind { + switch h.Kind { + case config.StaticKind: return netbox.HostEntry{}, nil, h, fmt.Errorf("%s is a static host (hosts:) and has no NetBox record", h.Name) + case "dns": + return netbox.HostEntry{}, nil, h, fmt.Errorf("%s (%s) is not in NetBox", h.Name, h.IP) } client := newNetBoxClient(cfg) if client == nil { @@ -122,12 +125,12 @@ func infoCmd() *cobra.Command { if err != nil { return err } - h, err := resolveTargetE(cfg, args[0], false) + h, err := resolveOrSuggest(cfg, args[0], false) if err != nil { return err } out := cmd.OutOrStdout() - if h.Kind == config.StaticKind { + if h.Kind == config.StaticKind || h.Kind == "dns" { return printStaticInfo(out, cfg, h, asJSON) } client := newNetBoxClient(cfg) @@ -164,7 +167,11 @@ func printStaticInfo(w io.Writer, cfg *config.Config, h resolvedHost, asJSON boo return json.NewEncoder(w).Encode(map[string]any{"host": map[string]any{"name": h.Name, "kind": h.Kind, "address": h.IP, "user": user, "port": port, "tags": h.Tags}}) } tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0) - fmt.Fprintf(tw, "%s\t(static host from hosts:)\n", h.Name) + origin := "(static host from hosts:)" + if h.Kind == "dns" { + origin = "(DNS name, not in NetBox)" + } + fmt.Fprintf(tw, "%s\t%s\n", h.Name, origin) row(tw, "Address", h.IP) row(tw, "User", user) if port > 0 { @@ -290,6 +297,14 @@ prefixes containing it. A hostname is resolved through DNS first.`, ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) defer cancel() addresses, err := whoisAddresses(ctx, args[0]) + if err != nil { + // A short name like mx123 may resolve with a shortcut domain. + if names := dnsNames(cfg, args[0]); len(names) > 0 && names[0] != args[0] { + if _, found := lookupDNS(ctx, names); len(found) > 0 { + addresses, err = found, nil + } + } + } if err != nil { return err } diff --git a/cmd/netssh/link.go b/cmd/netssh/link.go new file mode 100644 index 0000000..351b414 --- /dev/null +++ b/cmd/netssh/link.go @@ -0,0 +1,140 @@ +package main + +import ( + "fmt" + "sort" + "strings" + "text/tabwriter" + + "github.com/spf13/cobra" + + "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" +) + +func linkCmd() *cobra.Command { + cmd := &cobra.Command{ + Use: "link", + Short: "Short names for hosts: netssh NAME and shell alias NAME", + Long: `Links give a host a name of your own, for example mx123 for the server that +mx123.webseite.de points to. netssh NAME then connects to the host, and new +shells get the alias NAME. netssh offers to create a link after a DNS +suggestion; links are stored under links: in the config.`, + } + cmd.AddCommand(linkListCmd(), linkAddCmd(), linkRemoveCmd()) + return cmd +} + +func linkListCmd() *cobra.Command { + return &cobra.Command{ + Use: "list", + Short: "List links", + Args: cobra.NoArgs, + RunE: func(cmd *cobra.Command, args []string) error { + cfg, err := config.Load() + if err != nil { + return err + } + if len(cfg.Links) == 0 { + fmt.Fprintln(cmd.OutOrStdout(), "No links. Add one with: netssh link add NAME HOST") + return nil + } + names := make([]string, 0, len(cfg.Links)) + for name := range cfg.Links { + names = append(names, name) + } + sort.Strings(names) + w := tabwriter.NewWriter(cmd.OutOrStdout(), 0, 0, 2, ' ', 0) + fmt.Fprintln(w, "NAME\tHOST") + for _, name := range names { + fmt.Fprintf(w, "%s\t%s\n", name, cfg.Links[name]) + } + return w.Flush() + }, + } +} + +func linkAddCmd() *cobra.Command { + return &cobra.Command{ + Use: "add NAME HOST", + Short: "Create or replace a link", + Example: " netssh link add mx123 prod/web07\n netssh link add mx123 mx123.webseite.de # asks which host owns the address", + Args: cobra.ExactArgs(2), + ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { + if len(args) == 1 { + return hostCompletion(cmd, args, toComplete) + } + return nil, cobra.ShellCompDirectiveNoFileComp + }, + RunE: func(cmd *cobra.Command, args []string) error { + cfg, err := config.Load() + if err != nil { + return err + } + name := strings.ToLower(args[0]) + if _, isLink := cfg.Link(args[1]); isLink { + return fmt.Errorf("%q is a link itself; link to a host", args[1]) + } + // Resolve now, so a typo fails here and the link stores the canonical target. + h, err := resolveOrSuggestQuiet(cfg, args[1]) + if err != nil { + return err + } + if h.Kind == "dns" { + return fmt.Errorf("%s is not a NetBox or static host; links point to hosts netssh knows", args[1]) + } + if err := saveLink(name, h.Name); err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "netssh %s → %s (open a new shell for the alias %s)\n", name, h.Name, name) + return nil + }, + } +} + +// resolveOrSuggestQuiet resolves for link add without offering another link. +func resolveOrSuggestQuiet(cfg *config.Config, host string) (resolvedHost, error) { + old := offerLinkFunc + offerLinkFunc = func(string, string, string) {} + defer func() { offerLinkFunc = old }() + return resolveOrSuggest(cfg, host, false) +} + +func linkRemoveCmd() *cobra.Command { + return &cobra.Command{ + Use: "remove NAME", + Short: "Remove a link", + Args: cobra.ExactArgs(1), + ValidArgsFunction: func(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) { + cfg, err := config.Load() + if err != nil { + return nil, cobra.ShellCompDirectiveError + } + var names []string + for name := range cfg.Links { + names = append(names, name) + } + return filterPrefix(names, toComplete, nil), cobra.ShellCompDirectiveNoFileComp + }, + RunE: func(cmd *cobra.Command, args []string) error { + cfg, err := config.Load() + if err != nil { + return err + } + removed := false + for key := range cfg.Links { + if strings.EqualFold(key, args[0]) { + delete(cfg.Links, key) + removed = true + } + } + if !removed { + return fmt.Errorf("no link %q", args[0]) + } + if err := saveHosts(cfg); err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "Link %s removed.\n", args[0]) + return nil + }, + } +} diff --git a/cmd/netssh/link_test.go b/cmd/netssh/link_test.go new file mode 100644 index 0000000..900e5b7 --- /dev/null +++ b/cmd/netssh/link_test.go @@ -0,0 +1,85 @@ +package main + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" + "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook" +) + +func TestLinksResolveAndBecomeAliases(t *testing.T) { + dnsEnv(t, "links:\n mx123: prod/web07\n") + cfg, err := config.Load() + if err != nil { + t.Fatal(err) + } + h, err := resolveTargetE(cfg, "MX123", false) + if err != nil || h.Name != "prod/web07" { + t.Fatalf("link not followed: %+v %v", h, err) + } + var found bool + for _, a := range hook.BuildAliasEntries(nil, *cfg) { + if a.Name == "mx123" && a.Host == "mx123" { + found = true + } + } + if !found { + t.Fatal("link has no shell alias") + } + if got := completeHosts("mx"); len(got) == 0 || got[0] != "mx123" { + t.Fatalf("completion: %v", got) + } +} + +func TestLinkAddListRemove(t *testing.T) { + dnsEnv(t, "") + stubTerminal(t, false) + run := func(args ...string) (string, error) { + var out strings.Builder + cmd := rootCmd() + cmd.SetOut(&out) + cmd.SetArgs(args) + err := cmd.Execute() + return out.String(), err + } + if _, err := run("link", "add", "mx123", "prod/web07"); err != nil { + t.Fatal(err) + } + data, _ := os.ReadFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml")) + if !strings.Contains(string(data), "links:\n mx123: \"prod/web07\"") { + t.Fatalf("link not written:\n%s", data) + } + if out, _ := run("link", "list"); !strings.Contains(out, "mx123 prod/web07") { + t.Fatalf("list: %q", out) + } + if _, err := run("link", "add", "x", "missing-host"); err == nil { + t.Fatal("link to unknown host accepted") + } + if _, err := run("link", "remove", "mx123"); err != nil { + t.Fatal(err) + } + cfg, _ := config.Load() + if len(cfg.Links) != 0 { + t.Fatalf("not removed: %v", cfg.Links) + } +} + +func TestValidateLinks(t *testing.T) { + for _, tc := range []struct { + cfg config.Config + ok bool + }{ + {config.Config{Links: map[string]string{"mx123": "prod/web07"}}, true}, + {config.Config{Links: map[string]string{"bad name": "web"}}, false}, + {config.Config{Links: map[string]string{"a": "-oProxyCommand=x"}}, false}, + {config.Config{Links: map[string]string{"a": "b", "b": "web"}}, false}, + {config.Config{Links: map[string]string{"router": "web"}, Hosts: []config.StaticHost{{Name: "router", Address: "1.2.3.4"}}}, false}, + } { + if err := tc.cfg.ValidateLinks(); (err == nil) != tc.ok { + t.Errorf("%v: %v", tc.cfg.Links, err) + } + } +} diff --git a/cmd/netssh/main.go b/cmd/netssh/main.go index 7c763e8..2a1341c 100644 --- a/cmd/netssh/main.go +++ b/cmd/netssh/main.go @@ -58,6 +58,7 @@ var managedSubcommands = map[string]bool{ "export": true, "token": true, "known-hosts": true, + "link": true, } func main() { @@ -276,13 +277,16 @@ func upsertResolved(c *cache.Cache, entry cache.Entry) (previous string) { // resolveTarget finds host in the cache (also by shortcut) or NetBox and // resolves its address. It exits on failure. func resolveTarget(cfg *config.Config, host string) resolvedHost { - result, err := resolveTargetE(cfg, host, true) + result, err := resolveOrSuggest(cfg, host, true) if err != nil { fatalf("%v", err) } return result } func resolveTargetE(cfg *config.Config, host string, record bool) (resolvedHost, error) { + if target, ok := cfg.Link(host); ok { + host = target + } c := newCache(cfg) _ = c.Load() if record { @@ -343,7 +347,7 @@ func resolveTargetE(cfg *config.Config, host string, record bool) (resolvedHost, } if !cfg.HasNetBox() { - return resolvedHost{}, fmt.Errorf("host %q is not in hosts: and no NetBox is configured (netssh configure)", host) + return resolvedHost{}, fmt.Errorf("host %q is not in hosts: and no NetBox is configured (netssh configure): %w", host, netbox.ErrHostNotFound) } nbClient := newNetBoxClient(cfg) @@ -706,7 +710,7 @@ func rootCmd() *cobra.Command { } root.AddCommand(doctorCmd(), explainCmd(), favoritesCmd(), historyCmd(), batchCmd(), configCmd(), runCmd(), notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd(), - openCmd(), infoCmd(), whoisCmd(), copyIDCmd(), exportCmd(), tokenCmd(), knownHostsCmd()) + openCmd(), infoCmd(), whoisCmd(), copyIDCmd(), exportCmd(), tokenCmd(), knownHostsCmd(), linkCmd()) // cobra builds the "completion" command lazily; force init so we can extend it. root.InitDefaultCompletionCmd() diff --git a/cmd/netssh/transfer.go b/cmd/netssh/transfer.go index 1a291ad..39fc5dd 100644 --- a/cmd/netssh/transfer.go +++ b/cmd/netssh/transfer.go @@ -136,6 +136,12 @@ func completeHosts(toComplete string) []string { c := newCache(cfg) _ = c.Load() hosts := hostCompletions(c.All(), toComplete, cfg.Shortcuts) + for name := range cfg.Links { + if strings.HasPrefix(strings.ToLower(name), strings.ToLower(toComplete)) { + hosts = append(hosts, strings.ToLower(name)) + } + } + sort.Strings(hosts) if limit := cfg.Completion.MaxResults; limit > 0 && len(hosts) > limit { hosts = hosts[:limit] } diff --git a/internal/config/config.go b/internal/config/config.go index f5c8da9..9314840 100644 --- a/internal/config/config.go +++ b/internal/config/config.go @@ -26,7 +26,12 @@ type Config struct { 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"` + // Links map a short name to a host selector: netssh NAME connects to it, + // and the shell gets an alias NAME. Created after a DNS suggestion or + // with netssh link add. + Links map[string]string `mapstructure:"links"` + DNS DNSConfig `mapstructure:"dns"` + Multi MultiConfig `mapstructure:"multi"` } type ShellConfig struct { @@ -185,7 +190,7 @@ func Load() (*Config, error) { v.SetEnvPrefix("NETSSH") v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) v.AutomaticEnv() - for _, key := range []string{"netbox.url", "netbox.token", "netbox.token_version", "resolver.strategies", "resolver.management_subnets", "resolver.interface_name", "resolver.hostname_domain", "cache.ttl", "cache.path", "ssh.default_user", "ssh.default_port", "shortcuts.domains", "shortcuts.strip_hyphens", "shortcuts.show", "shell.alias", "ssh.proxy_jump", "ssh.pre_connect", "ssh.post_disconnect", "tui.history_limit", "activity.enabled", "activity.retention_days", "activity.max_entries", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window", "ssh.warn_status", "tui.columns", "tui.reachability_timeout", "resolver.fallback", "resolver.fallback_timeout"} { + for _, key := range []string{"netbox.url", "netbox.token", "netbox.token_version", "resolver.strategies", "resolver.management_subnets", "resolver.interface_name", "resolver.hostname_domain", "cache.ttl", "cache.path", "ssh.default_user", "ssh.default_port", "shortcuts.domains", "shortcuts.strip_hyphens", "shortcuts.show", "shell.alias", "ssh.proxy_jump", "ssh.pre_connect", "ssh.post_disconnect", "tui.history_limit", "activity.enabled", "activity.retention_days", "activity.max_entries", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window", "ssh.warn_status", "tui.columns", "tui.reachability_timeout", "resolver.fallback", "resolver.fallback_timeout", "dns.suggest", "dns.save_link"} { if err := v.BindEnv(key); err != nil { return nil, err } @@ -239,6 +244,12 @@ func Load() (*Config, error) { if err := cfg.ValidateHosts(); err != nil { return nil, err } + if err := cfg.ValidateLinks(); err != nil { + return nil, err + } + if err := cfg.ValidateDNS(); err != nil { + return nil, err + } if err := cfg.ValidateOperations(); err != nil { return nil, err } diff --git a/internal/config/dns.go b/internal/config/dns.go new file mode 100644 index 0000000..b289631 --- /dev/null +++ b/internal/config/dns.go @@ -0,0 +1,96 @@ +package config + +import ( + "fmt" + "path" + "strings" +) + +// DNSConfig controls what netssh does with names that are neither in NetBox +// nor in the cache: resolve them through DNS and suggest the owning host. +type DNSConfig struct { + // Suggest is ask (default), always (take the first suggestion without + // asking, also in scripts) or never (no DNS lookup, plain "not found"). + Suggest string `mapstructure:"suggest"` + // SaveLink is ask (default), always (save the shortcut without asking) + // or never, for the link offered after a suggestion. + SaveLink string `mapstructure:"save_link"` + // Domains are appended to names without a dot that match the rule. + Domains []DNSDomain `mapstructure:"domains"` +} + +// DNSDomain appends Domain to names matching Match (a shell glob such as +// "mx*"; empty matches every name). +type DNSDomain struct { + Match string `mapstructure:"match"` + Domain string `mapstructure:"domain"` +} + +// DNS modes for dns.suggest and dns.save_link. +const ( + DNSAsk = "ask" + DNSAlways = "always" + DNSNever = "never" +) + +// SuggestMode returns dns.suggest, ask by default. +func (d DNSConfig) SuggestMode() string { return dnsMode(d.Suggest) } + +// SaveLinkMode returns dns.save_link, ask by default. +func (d DNSConfig) SaveLinkMode() string { return dnsMode(d.SaveLink) } + +func dnsMode(mode string) string { + if mode == "" { + return DNSAsk + } + return strings.ToLower(mode) +} + +// Names lists the DNS names to try for what the user typed. A name with a +// dot is used as is. A name without a dot gets the domain of every rule it +// matches, in order; only when no rule matches is the bare name looked up. +func (d DNSConfig) Names(query string) []string { + if strings.Contains(query, ".") { + return []string{query} + } + var names []string + seen := map[string]bool{} + lower := strings.ToLower(query) + for _, rule := range d.Domains { + if rule.Match != "" { + if ok, _ := path.Match(strings.ToLower(rule.Match), lower); !ok { + continue + } + } + name := query + "." + strings.Trim(strings.TrimSpace(rule.Domain), ".") + if !seen[strings.ToLower(name)] { + seen[strings.ToLower(name)] = true + names = append(names, name) + } + } + if len(names) == 0 { + return []string{query} + } + return names +} + +// ValidateDNS rejects unknown modes, broken patterns and empty domains. +func (c *Config) ValidateDNS() error { + for key, mode := range map[string]string{"dns.suggest": c.DNS.Suggest, "dns.save_link": c.DNS.SaveLink} { + switch dnsMode(mode) { + case DNSAsk, DNSAlways, DNSNever: + default: + return fmt.Errorf("%s must be ask, always, or never", key) + } + } + for i, rule := range c.DNS.Domains { + if _, err := path.Match(rule.Match, ""); err != nil { + return fmt.Errorf("dns.domains[%d]: invalid match pattern %q", i, rule.Match) + } + domain := strings.Trim(strings.TrimSpace(rule.Domain), ".") + if domain == "" || strings.ContainsAny(domain, " \t/@*?") || strings.HasPrefix(domain, "-") { + return fmt.Errorf("dns.domains[%d]: invalid domain %q", i, rule.Domain) + } + } + return nil +} diff --git a/internal/config/hosts.go b/internal/config/hosts.go index 4adaff3..07484e1 100644 --- a/internal/config/hosts.go +++ b/internal/config/hosts.go @@ -60,3 +60,34 @@ func (c *Config) StaticHost(name string) *StaticHost { } return nil } + +// Link returns the target of the link named name (case-insensitive). +func (c *Config) Link(name string) (string, bool) { + for key, target := range c.Links { + if strings.EqualFold(key, name) { + return target, true + } + } + return "", false +} + +// ValidateLinks keeps link names usable as selectors and shell aliases and +// rejects chains, which could loop. +func (c *Config) ValidateLinks() error { + for name, target := range c.Links { + if !staticHostName.MatchString(name) || strings.Contains(name, "/") { + return fmt.Errorf("links: name %q must start with a letter or digit and contain only letters, digits, dots, underscores, or hyphens", name) + } + if c.StaticHost(name) != nil { + return fmt.Errorf("links: %q is also a static host", name) + } + target = strings.TrimSpace(target) + if target == "" || strings.HasPrefix(target, "-") || strings.ContainsAny(target, " \t\n\r@") { + return fmt.Errorf("links.%s: invalid target %q", name, target) + } + if _, chained := c.Link(target); chained { + return fmt.Errorf("links.%s: target %q is another link", name, target) + } + } + return nil +} diff --git a/internal/config/insights_test.go b/internal/config/insights_test.go index 541c6a9..74da99f 100644 --- a/internal/config/insights_test.go +++ b/internal/config/insights_test.go @@ -106,3 +106,15 @@ func TestTUIColumnsValidation(t *testing.T) { } } } + +func TestDNSConfigValidation(t *testing.T) { + cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\ndns:\n suggest: Always\n domains:\n - match: \"mx*\"\n domain: easysahre.de\n")) + if cfg.DNS.SuggestMode() != DNSAlways || cfg.DNS.SaveLinkMode() != DNSAsk || len(cfg.DNS.Domains) != 1 { + t.Fatalf("dns: %+v", cfg.DNS) + } + for _, bad := range []DNSConfig{{Suggest: "sometimes"}, {SaveLink: "yes"}, {Domains: []DNSDomain{{Match: "[", Domain: "a.de"}}}, {Domains: []DNSDomain{{Domain: " "}}}, {Domains: []DNSDomain{{Domain: "a b.de"}}}} { + if err := (&Config{DNS: bad}).ValidateDNS(); err == nil { + t.Errorf("%+v accepted", bad) + } + } +} diff --git a/internal/hook/aliases.go b/internal/hook/aliases.go index 9984147..9e8fa3f 100644 --- a/internal/hook/aliases.go +++ b/internal/hook/aliases.go @@ -129,6 +129,20 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry { out = append(out, AliasEntry{Name: cfg.Shell.Alias}) } + // Links are names the user chose explicitly: they come before host aliases. + validLink := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`) + links := make([]string, 0, len(cfg.Links)) + for name := range cfg.Links { + links = append(links, strings.ToLower(name)) + } + sort.Strings(links) + for _, name := range links { + if !seen[name] && validLink.MatchString(name) { + seen[name] = true + out = append(out, AliasEntry{Name: name, Host: name}) + } + } + withoutPrefix := make(map[string]bool, len(cfg.NetBoxes)) for _, source := range cfg.NetBoxes { withoutPrefix[strings.ToLower(source.Name)] = source.DisablePrefix @@ -172,7 +186,8 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry { hostname = instance instance = "" } - hostMetadata[e.Name] = config.SSHHost{Instance: instance, Name: hostname, Kind: e.Kind, Tags: e.Tags} + hostMetadata[e.Name] = config.SSHHost{Instance: instance, Name: hostname, Kind: e.Kind, Tags: e.Tags, Status: e.Status, + Site: cache.RefOf(e.Site), Role: cache.RefOf(e.Role), Platform: cache.RefOf(e.Platform), Tenant: cache.RefOf(e.Tenant)} } var commands []string for name := range cfg.Commands { diff --git a/internal/hook/aliases_test.go b/internal/hook/aliases_test.go index 5a17f9a..c21a5f4 100644 --- a/internal/hook/aliases_test.go +++ b/internal/hook/aliases_test.go @@ -416,3 +416,22 @@ func TestCustomAliasShellArgumentQuoting(t *testing.T) { }) } } + +func TestCommandAliasesHonourNetBoxAttributes(t *testing.T) { + cfg := config.Config{Commands: map[string]config.HostCommand{ + "cli": {AliasPrefix: "c", Args: []string{"cli", "{address}"}, Match: config.SSHMatch{Platform: "junos"}}, + }} + entries := []cache.Entry{ + {Name: "sw1", Kind: "device", Platform: &config.Ref{Name: "Junos", Slug: "junos"}}, + {Name: "web1", Kind: "vm", Platform: &config.Ref{Slug: "ubuntu"}}, + } + var got []string + for _, a := range hook.BuildAliasEntries(entries, cfg) { + if a.Command == "cli" { + got = append(got, a.Name) + } + } + if len(got) != 1 || got[0] != "csw1" { + t.Fatalf("command aliases %v", got) + } +} diff --git a/internal/setup/wizard.go b/internal/setup/wizard.go index 69232db..42587ce 100644 --- a/internal/setup/wizard.go +++ b/internal/setup/wizard.go @@ -3,6 +3,7 @@ package setup import ( "errors" "fmt" + "io" "os" "path/filepath" "sort" @@ -181,6 +182,11 @@ func editResolverCache(cfg *config.Config) error { hostnameDomain := cfg.Resolver.HostnameDomain cacheTTL := strconv.Itoa(cfg.Cache.TTL) cachePath := cfg.Cache.Path + dnsSuggest, dnsSaveLink := cfg.DNS.SuggestMode(), cfg.DNS.SaveLinkMode() + dnsDomains := formatDNSDomains(cfg.DNS.Domains) + modes := func(ask, always, never string) []huh.Option[string] { + return []huh.Option[string]{huh.NewOption(ask, config.DNSAsk), huh.NewOption(always, config.DNSAlways), huh.NewOption(never, config.DNSNever)} + } err := huh.NewForm(huh.NewGroup( huh.NewInput(). Title("Resolver strategies"). @@ -214,7 +220,25 @@ func editResolverCache(cfg *config.Config) error { Title("Cache file"). Description("Where resolved hosts are stored. Leave empty for the default location."). Value(&cachePath), - ).Title("Resolver & cache")).Run() + ).Title("Resolver & cache"), huh.NewGroup( + huh.NewSelect[string](). + Title("Unknown names: suggest the host behind the DNS address?"). + Options(modes("ask", "always take the first suggestion (also in scripts)", "never (no DNS lookup)")...). + Value(&dnsSuggest), + huh.NewSelect[string](). + Title("Save a shortcut (link) after a suggestion?"). + Options(modes("ask", "always", "never")...). + Value(&dnsSaveLink), + huh.NewText(). + Title("DNS domains for short names"). + Description("One rule per line: PATTERN = DOMAIN, e.g.\nmx* = easysahre.de\nah* = jhfduwia.de\nA line with only a domain applies to every name."). + Lines(5). + Value(&dnsDomains). + Validate(func(s string) error { + _, err := parseDNSDomains(s) + return err + }), + ).Title("DNS names")).Run() if err != nil { return err } @@ -224,9 +248,49 @@ func editResolverCache(cfg *config.Config) error { cfg.Resolver.HostnameDomain = strings.Trim(strings.TrimSpace(hostnameDomain), ".") cfg.Cache.TTL, _ = strconv.Atoi(cacheTTL) cfg.Cache.Path = strings.TrimSpace(cachePath) + cfg.DNS.Domains, _ = parseDNSDomains(dnsDomains) + cfg.DNS.Suggest, cfg.DNS.SaveLink = keepDefault(dnsSuggest), keepDefault(dnsSaveLink) return nil } +// keepDefault stores "ask" as unset, so the config only lists changes. +func keepDefault(mode string) string { + if mode == config.DNSAsk { + return "" + } + return mode +} + +func formatDNSDomains(rules []config.DNSDomain) string { + lines := make([]string, 0, len(rules)) + for _, rule := range rules { + if rule.Match == "" { + lines = append(lines, rule.Domain) + } else { + lines = append(lines, rule.Match+" = "+rule.Domain) + } + } + return strings.Join(lines, "\n") +} + +// parseDNSDomains reads "PATTERN = DOMAIN" lines; a bare domain matches all names. +func parseDNSDomains(text string) ([]config.DNSDomain, error) { + var rules []config.DNSDomain + for _, line := range strings.Split(text, "\n") { + line = strings.TrimSpace(line) + if line == "" { + continue + } + rule := config.DNSDomain{Domain: line} + if match, domain, ok := strings.Cut(line, "="); ok { + rule = config.DNSDomain{Match: strings.TrimSpace(match), Domain: strings.TrimSpace(domain)} + } + rules = append(rules, rule) + } + err := (&config.Config{DNS: config.DNSConfig{Domains: rules}}).ValidateDNS() + return rules, err +} + func editShortcuts(cfg *config.Config) error { shortcutDomains := strings.Join(cfg.Shortcuts.Domains, ", ") stripHyphens := cfg.Shortcuts.StripHyphens @@ -367,9 +431,15 @@ func validateStrategies(s string) error { 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 { return SaveTo(cfg, os.Stdout) } -func save(cfg config.Config) error { +// SaveTo is Save with the confirmation written to w; callers that run +// before a connection pass os.Stderr to keep stdout clean. +func SaveTo(cfg config.Config, w io.Writer) error { return saveTo(cfg, w) } + +func save(cfg config.Config) error { return saveTo(cfg, os.Stdout) } + +func saveTo(cfg config.Config, w io.Writer) error { if err := config.ValidateCommandAlias(cfg.Shell.Alias); err != nil { return err } @@ -385,6 +455,12 @@ func save(cfg config.Config) error { if err := cfg.ValidateHosts(); err != nil { return err } + if err := cfg.ValidateLinks(); err != nil { + return err + } + if err := cfg.ValidateDNS(); err != nil { + return err + } if err := cfg.ValidateOperations(); err != nil { return err } @@ -502,6 +578,38 @@ func save(cfg config.Config) error { } } + if cfg.DNS.Suggest != "" || cfg.DNS.SaveLink != "" || len(cfg.DNS.Domains) > 0 { + b.WriteString("\ndns:\n") + if cfg.DNS.Suggest != "" { + fmt.Fprintf(&b, " suggest: %s\n", cfg.DNS.SuggestMode()) + } + if cfg.DNS.SaveLink != "" { + fmt.Fprintf(&b, " save_link: %s\n", cfg.DNS.SaveLinkMode()) + } + if len(cfg.DNS.Domains) > 0 { + b.WriteString(" domains:\n") + for _, rule := range cfg.DNS.Domains { + if rule.Match != "" { + fmt.Fprintf(&b, " - match: %q\n domain: %q\n", rule.Match, rule.Domain) + } else { + fmt.Fprintf(&b, " - domain: %q\n", rule.Domain) + } + } + } + } + + if len(cfg.Links) > 0 { + b.WriteString("\nlinks:\n") + names := make([]string, 0, len(cfg.Links)) + for name := range cfg.Links { + names = append(names, name) + } + sort.Strings(names) + for _, name := range names { + fmt.Fprintf(&b, " %s: %q\n", strings.ToLower(name), cfg.Links[name]) + } + } + if len(cfg.Groups) > 0 { b.WriteString("\ngroups:\n") names := make([]string, 0, len(cfg.Groups)) @@ -599,7 +707,7 @@ func save(cfg config.Config) error { return fmt.Errorf("writing config: %w", err) } - fmt.Printf("\nConfig saved → %s\n", path) + fmt.Fprintf(w, "\nConfig saved → %s\n", path) return nil } diff --git a/internal/setup/wizard_test.go b/internal/setup/wizard_test.go index c63e2e4..27bf5d8 100644 --- a/internal/setup/wizard_test.go +++ b/internal/setup/wizard_test.go @@ -771,3 +771,29 @@ func TestSaveRoundtripNetBoxInsightSettings(t *testing.T) { } } } + +func TestDNSDomainsTextAndSave(t *testing.T) { + rules, err := parseDNSDomains("mx* = easysahre.de\n\nah* = jhfduwia.de\nfallback.de\n") + if err != nil || len(rules) != 3 || rules[0] != (config.DNSDomain{Match: "mx*", Domain: "easysahre.de"}) || rules[2].Match != "" { + t.Fatalf("parsed %+v, %v", rules, err) + } + if formatDNSDomains(rules) != "mx* = easysahre.de\nah* = jhfduwia.de\nfallback.de" { + t.Fatalf("format: %q", formatDNSDomains(rules)) + } + if _, err := parseDNSDomains("mx* = "); err == nil { + t.Fatal("empty domain accepted") + } + t.Setenv("XDG_CONFIG_HOME", t.TempDir()) + cfg := config.Config{NetBox: config.NetBoxConfig{URL: "https://nb.example"}, Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}}, + DNS: config.DNSConfig{Suggest: "never", SaveLink: "always", Domains: rules}, Links: map[string]string{"mx123": "prod/web07"}} + if err := Save(cfg); err != nil { + t.Fatal(err) + } + loaded, err := config.Load() + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(loaded.DNS, cfg.DNS) || loaded.Links["mx123"] != "prod/web07" { + t.Fatalf("lost: %+v %v", loaded.DNS, loaded.Links) + } +}