Compare commits
15
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bda57375bd | ||
|
|
c502dd0a2a | ||
|
|
9f6a2b5c19 | ||
|
|
1cc2935115 | ||
|
|
86e53e4c41 | ||
|
|
dd427681b6 | ||
|
|
172258960e | ||
|
|
080e52b437 | ||
|
|
e905a39068 | ||
|
|
793f095e80 | ||
|
|
5c41a5eb6f | ||
|
|
c408d529a0 | ||
|
|
04523569ab | ||
|
|
fde4298f50 | ||
|
|
e01f86f2db |
No files matched your search
@@ -1,5 +1,17 @@
|
||||
# Changelog
|
||||
|
||||
## v1.3.1
|
||||
|
||||
- Update dependencies: charm.land/bubbletea/v2 v2.1.2, github.com/zalando/go-keyring v0.2.8 (no longer needs al.essio.dev/pkg/shellescape), github.com/danieljoos/wincred v1.2.3, github.com/godbus/dbus/v5 v5.2.4.
|
||||
|
||||
## 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.
|
||||
|
||||
@@ -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 `<Tab>`). 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:
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+6
-2
@@ -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()
|
||||
|
||||
+20
-5
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
+7
-3
@@ -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()
|
||||
|
||||
@@ -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]
|
||||
}
|
||||
|
||||
@@ -4,19 +4,18 @@ go 1.27.4
|
||||
|
||||
require (
|
||||
charm.land/bubbles/v2 v2.2.1
|
||||
charm.land/bubbletea/v2 v2.1.1
|
||||
charm.land/bubbletea/v2 v2.1.2
|
||||
charm.land/huh/v2 v2.0.3
|
||||
charm.land/lipgloss/v2 v2.1.1
|
||||
github.com/charmbracelet/x/term v0.2.2
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/spf13/viper v1.21.0
|
||||
github.com/zalando/go-keyring v0.2.6
|
||||
github.com/zalando/go-keyring v0.2.8
|
||||
go.yaml.in/yaml/v3 v3.0.6
|
||||
golang.org/x/sys v0.50.0
|
||||
)
|
||||
|
||||
require (
|
||||
al.essio.dev/pkg/shellescape v1.5.1 // indirect
|
||||
github.com/atotto/clipboard v0.1.4 // indirect
|
||||
github.com/catppuccin/go v0.3.0 // indirect
|
||||
github.com/charmbracelet/colorprofile v0.4.3 // indirect
|
||||
@@ -30,11 +29,11 @@ require (
|
||||
github.com/charmbracelet/x/xpty v0.1.4 // indirect
|
||||
github.com/clipperhouse/displaywidth v0.11.0 // indirect
|
||||
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
|
||||
github.com/danieljoos/wincred v1.2.2 // indirect
|
||||
github.com/danieljoos/wincred v1.2.3 // indirect
|
||||
github.com/dustin/go-humanize v1.1.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.10.1 // indirect
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
|
||||
github.com/godbus/dbus/v5 v5.1.0 // indirect
|
||||
github.com/godbus/dbus/v5 v5.2.4 // indirect
|
||||
github.com/google/go-cmp v0.7.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
|
||||
|
||||
@@ -1,9 +1,7 @@
|
||||
al.essio.dev/pkg/shellescape v1.5.1 h1:86HrALUujYS/h+GtqoB26SBEdkWfmMI6FubjXlsXyho=
|
||||
al.essio.dev/pkg/shellescape v1.5.1/go.mod h1:6sIqp7X2P6mThCQ7twERpZTuigpr6KbZWtls1U8I890=
|
||||
charm.land/bubbles/v2 v2.2.1 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU=
|
||||
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc=
|
||||
charm.land/bubbletea/v2 v2.1.1 h1:S1S9l37pCZGrj1JexBcr9x4Nr3MVeM42InqCYM/tDpU=
|
||||
charm.land/bubbletea/v2 v2.1.1/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
|
||||
charm.land/bubbletea/v2 v2.1.2 h1:vB3XAcHhLB2gR3HOHpwO3lHB3nbvaowIgL3e5x/DUZo=
|
||||
charm.land/bubbletea/v2 v2.1.2/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
|
||||
charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=
|
||||
charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=
|
||||
charm.land/lipgloss/v2 v2.1.1 h1:F+vKWis9Kz3MFRsbICSDFtT1ZwVL+8f+36Dtg+OpKwc=
|
||||
@@ -45,8 +43,8 @@ github.com/clipperhouse/uax29/v2 v2.7.0/go.mod h1:EFJ2TJMRUaplDxHKj1qAEhCtQPW2tJ
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/creack/pty v1.1.24 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
|
||||
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE=
|
||||
github.com/danieljoos/wincred v1.2.2 h1:774zMFJrqaeYCK2W57BgAem/MLi6mtSE47MB6BOJ0i0=
|
||||
github.com/danieljoos/wincred v1.2.2/go.mod h1:w7w4Utbrz8lqeMbDAK0lkNJUv5sAOkFi7nd/ogr0Uh8=
|
||||
github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMFLdQ=
|
||||
github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs=
|
||||
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
@@ -55,12 +53,10 @@ github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx5
|
||||
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/godbus/dbus/v5 v5.1.0 h1:4KLkAxT3aOY8Li4FRJe/KvhoNFFxo0m6fNuFUO8QJUk=
|
||||
github.com/godbus/dbus/v5 v5.1.0/go.mod h1:xhWf0FNVPg57R7Z0UbKHbJfkEywrmjJnf7w5xrFpKfA=
|
||||
github.com/godbus/dbus/v5 v5.2.4 h1:F2gUCy++NMIxGmo9J+z5le/+ZC8W1OgeR51P4i9ZB/U=
|
||||
github.com/godbus/dbus/v5 v5.2.4/go.mod h1:3AAv2+hPq5rdnr5txxxRwiGjPXamgoIHgz9FPBfOp3c=
|
||||
github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8=
|
||||
github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU=
|
||||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 h1:El6M4kTTCOh6aBiKaUGG7oYTSPP8MxqL4YI3kZKwcP4=
|
||||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510/go.mod h1:pupxD2MaaD3pAXIBCelhxNneeOaAeabZDe5s4K6zSpQ=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
@@ -107,8 +103,8 @@ github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/xo/terminfo v1.3.1 h1:4ZwPCuu4PEFw0PkNp3Hv/x3gqvgLCzYhurszsj101cM=
|
||||
github.com/xo/terminfo v1.3.1/go.mod h1:lGzkSo8Fe7IRh/w+Gqz7n5mDog4FVXCj3gy/DYTBqio=
|
||||
github.com/zalando/go-keyring v0.2.6 h1:r7Yc3+H+Ux0+M72zacZoItR3UDxeWfKTcabvkI8ua9s=
|
||||
github.com/zalando/go-keyring v0.2.6/go.mod h1:2TCrxYrbUNYfNS/Kgy/LSrkSQzZ5UPVH85RwfczwvcI=
|
||||
github.com/zalando/go-keyring v0.2.8 h1:6sD/Ucpl7jNq10rM2pgqTs0sZ9V3qMrqfIIy5YPccHs=
|
||||
github.com/zalando/go-keyring v0.2.8/go.mod h1:tsMo+VpRq5NGyKfxoBVjCuMrG47yj8cmakZDO5QGii0=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
go.yaml.in/yaml/v3 v3.0.6 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
|
||||
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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 {
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
+112
-4
@@ -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
|
||||
}
|
||||
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user