feat: suggest the host behind unknown DNS names

A name neither in NetBox nor in the cache is resolved through DNS, using
dns.domains for short names. The hosts owning the address in NetBox or the
cache are offered together with a direct connection; without a terminal the
suggestions are part of the error. Afterwards netssh offers to save the name
as a link. info, open and whois use the same lookup.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Sebastian UnterschützandClaude Opus 5.5 committed 2026-11-18 13:07:08 +01:00
1 parent 5c41a5eb6f
commit 793f095e80
5 files changed
+531 -9

No files matched your search

+199
View File
@@ -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)
}
}