4 Commits
Author SHA1 Message Date
Sebi c87c2623ec Merge pull request 'feat: NetBox insights, host tools and configurable TUI' (#45) from feat/netbox-insights into main
Test / test (push) Successful in 4m14s
Release / release (push) Successful in 8m0s
2026-11-18 11:39:44 +00:00
Sebastian UnterschützandClaude Opus 5.5 1660bb3098 feat: NetBox insights, host tools and configurable TUI
Test / test (pull_request) Successful in 4m15s
- info/open/whois: NetBox details (site, nested locations, rack units,
  role, platform, tenant, IPs per interface), web page, reverse IP lookup
- cache status, site, role, platform, tenant, location chain and rack;
  ask before connecting to hosts in ssh.warn_status (--force skips)
- ssh rules and command restrictions match site/role/platform/tenant/status
- tui.columns selects what the TUI shows; optional TCP reachability column;
  detail view (Ctrl+L), NetBox page (Ctrl+G), status/location filters
- resolver.fallback tries other strategies' addresses when unreachable
- copy-id, known-hosts reset and address-change notices
- export ansible (YAML/INI) and export ssh-config
- token: keyring stores NetBox tokens in the system keyring
- fix stale menu number in testenv configure test

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-18 12:33:59 +01:00
Sebastian Unterschütz e5bde9c61f feat: add host actions, lifecycle hooks and operational tools
Test / test (push) Successful in 4m4s
Release / release (push) Successful in 7m39s
2026-11-18 10:41:36 +01:00
Sebastian Unterschütz 8d4915543e v1
Test / test (push) Successful in 3m36s
Release / release (push) Successful in 7m31s
2026-11-17 19:00:44 +01:00
76 changed files with 8881 additions and 216 deletions

No files matched your search

+33
View File
@@ -0,0 +1,33 @@
name: Test
on:
pull_request:
push:
branches:
- main
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-go@v7
with:
go-version-file: go.mod
cache: true
- name: Check formatting
run: |
unformatted=$(gofmt -l .)
if [ -n "$unformatted" ]; then
echo "gofmt needed for:"
echo "$unformatted"
exit 1
fi
- name: Vet
run: go vet ./...
- name: Run tests
run: go test -race ./...
+48
View File
@@ -1,5 +1,53 @@
# Changelog # Changelog
## 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.
- Add `netssh open HOST` and `Ctrl+G` in the TUI to open the host's NetBox page (`--print` prints the URL).
- Add `netssh whois ADDRESS|HOSTNAME`: the device or VM, interface, DNS name and containing prefixes of an address across all NetBox instances, plus matching cached hosts.
- Cache NetBox ID, status, site, role, platform and tenant. Ask before connecting to hosts whose status is in `ssh.warn_status` (default: offline, planned, staged, failed, inventory, decommissioning); `--force` skips the question, non-interactive callers get a warning. The TUI shows a status badge and filters by `status:`, `site:`, `role:`, `platform:` and `tenant:`.
- `ssh.rules` and command restrictions match `site`, `role`, `platform`, `tenant` and `status` (name or slug), e.g. legacy key exchange for `platform: junos`. The wizard edits the new selectors.
- Show where a device is: site › all nested NetBox locations › rack › rack unit. `netssh info` and the TUI detail view add `Location`, `Rack` (units, height, face) and `Path`; the TUI gets a `location` column and `location:`/`rack:` filters; Ansible exports add `netbox_location`, `netbox_rack`, `netbox_position` and `--group-by location,rack`. Each location is fetched once per run.
- Add `tui.columns` to choose what the TUI shows next to each host and in which order: `alias`, `ip`, `kind`, `source`, `status`, `site`, `location`, `role`, `platform`, `tenant`, `cluster`, `tags`, `reachability` (default `[alias, ip, source, status]`). Also in `netssh configure`.
- Optional TUI reachability check (`reachability` column, off by default): listed hosts are probed on their SSH port and marked ✓/✗ (`tui.reachability_timeout`); hosts behind a jump host are skipped.
- Add `resolver.fallback`: when the chosen address does not answer, connect to the first answering address of the other strategies (or the other primary IP) for this connection.
- Add `netssh copy-id` to run ssh-copy-id with netssh's address, user, port, jump host and options, for single hosts, `tag:`, `cluster:` and `@group`.
- Report changed host addresses on connect and in `netssh cache refresh`, offer to remove the old known_hosts entry, and add `netssh known-hosts reset HOST...`.
- Add `netssh export ansible` (YAML or INI inventory with groups by tag/site/role/platform/… and `netbox_*` host variables) and `netssh export ssh-config`.
- Add keyring token storage: `token: keyring` reads the NetBox token from the system keyring; `netssh token set|migrate|delete|status` manage it, `netssh doctor` checks it.
## v1.1.0
- Add local post-disconnect/post-command scripts, execution timeouts, cancellation, per-command confirmation and host restrictions.
- Add configurable recent-host count, persistent favorites/pins, a TUI command menu and cache/live/stale indicators.
- Add doctor/explain diagnostics, parallel batch commands with failed-host retry, and optional bounded local action history.
- Add configuration export/import that excludes credentials and executable settings while preserving matching local credentials.
- Preserve terminal behavior and process exit status during supervised execution; test Bash/Python scripts, process cancellation, concurrency and batch retries.
## v1.0.0
- Consolidate the complete project into the initial v1 commit.
- Add configurable local host commands and automatically generated aliases, such as `mxg1` for `mtr` on host shortcut `xg1`. Commands resolve the destination at invocation using the configured resolver strategy.
- Support executable scripts and interpreter-based scripts, host/address placeholders, extra arguments, dry runs, and configuration through `netssh configure`.
- Include all previous SSH, SFTP/SCP, forwarding, multi-session, NetBox instance, shortcut, and security improvements.
## v0.0.29
- Add `ssh.pre_connect`: a shell command run locally before every connection (ssh, sftp, scp, tunnel), e.g. to check a VPN. A non-zero exit aborts the connection. Layered like `proxy_jump` (global → instance or static host → rules, `none` disables an inherited hook); the host is passed as `NETSSH_HOST`, `NETSSH_TARGET`, `NETSSH_INSTANCE`, `NETSSH_IP`, `NETSSH_KIND`, `NETSSH_TAGS`, `NETSSH_CLIENT`. Editable in `netssh configure`, also `NETSSH_SSH_PRE_CONNECT`. `--dry-run` shows it without running it.
- Add `shortcuts.show`: shows each host's shortcut alias (e.g. `fsnbx1` for `fsn1-bx1.hoster.de`) in the TUI and as an `ALIAS` column in `netssh cache list` and `netssh hosts list`, and offers shortcuts in Tab completion even when the full name matches. `--aliases` shows the column for a single call. Editable in `netssh configure`, also `NETSSH_SHORTCUTS_SHOW`.
## v0.0.25
- Security: `netssh.yaml` is read from the user config directory only. A file of that name in the working directory (e.g. of a cloned repository) was loaded when no user config existed, and could set ssh options such as `ProxyCommand` or a NetBox URL.
- Security: an address from NetBox or the cache that is neither an IP address nor a hostname is refused. A value such as `-oProxyCommand=…` was passed to ssh as an option.
- The resolver chain stops at an API failure instead of trying the next strategy. Before, a NetBox error in `management_subnet` or `interface_name` connected to the primary IP and cached it. A strategy that finds no address (including a missing interface) still falls through. Note: a token without permission to read IP addresses now gives an error instead of silently using `primary_ip`.
- `netssh --help` and `netssh -h` show netssh's help instead of `unknown option --help` and ssh's usage.
- Background cache refreshes are started at most every 5 minutes. While NetBox was unreachable, every command and every new shell started another one.
- `netbox.url` is validated like the URLs of named instances (HTTP or HTTPS, no query or fragment).
- Hosts with more than 100 IP addresses: all pages are read, so `management_subnet` no longer misses addresses.
- CI: tests, `go vet`, and a format check run on pull requests and pushes to `main`.
## v0.0.24 ## v0.0.24
- Fix the `interface_name` resolver strategy: it sent filter names that NetBox ignores and therefore returned the host's first IP address instead of the named interface's. It now uses NetBox's `interface` and `vminterface` filters; a missing interface falls through to the next strategy. - Fix the `interface_name` resolver strategy: it sent filter names that NetBox ignores and therefore returned the host's first IP address instead of the named interface's. It now uses NetBox's `interface` and `vminterface` filters; a missing interface falls through to the next strategy.
+846 -33
View File
File diff suppressed because it is too large. Load diff
+191
View File
@@ -0,0 +1,191 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/runner"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"github.com/spf13/cobra"
)
type batchRetry struct {
Command string
Hosts []string
Extra []string
}
type batchResult struct {
Host string
Code int
}
var batchExecutable = os.Executable
func batchPath() string {
return filepath.Join(filepath.Dir(config.Path()), "netssh", "last-failed.json")
}
func batchCmd() *cobra.Command {
var parallel int
var retry, yes, dry bool
cmd := &cobra.Command{Use: "batch COMMAND HOST... [-- EXTRA_ARGS...]", Short: "Run a configured command on hosts with bounded parallelism", RunE: func(cmd *cobra.Command, args []string) error {
if parallel < 1 || parallel > 64 {
return fmt.Errorf("parallel must be between 1 and 64")
}
cfg, err := config.Load()
if err != nil {
return err
}
work := batchRetry{}
if retry {
if len(args) > 0 {
return fmt.Errorf("--retry-failed takes no positional arguments")
}
data, err := os.ReadFile(batchPath())
if err != nil {
return err
}
if err = json.Unmarshal(data, &work); err != nil {
return err
}
} else {
split := cmd.ArgsLenAtDash()
if split >= 0 {
work.Extra = args[split:]
args = args[:split]
}
if len(args) < 2 {
return fmt.Errorf("specify COMMAND and at least one HOST")
}
work.Command, work.Hosts = args[0], args[1:]
}
command, ok := cfg.Commands[work.Command]
if !ok {
return fmt.Errorf("unknown command %q", work.Command)
}
if len(work.Hosts) == 0 {
fmt.Fprintln(cmd.OutOrStdout(), "No failed hosts to retry.")
return nil
}
// Resolve and validate the entire list before launching any action.
var targets []string
seen := map[string]bool{}
for _, target := range work.Hosts {
h, err := resolveTargetE(cfg, target, false)
if err != nil {
return err
}
if !command.Allowed(commandHost(h)) {
return fmt.Errorf("%s is not allowed on %s", work.Command, h.Name)
}
if !seen[h.Name] {
targets = append(targets, h.Name)
seen[h.Name] = true
}
}
if command.Confirm && !dry {
if err := confirmAction(fmt.Sprintf("Run %s on %d hosts", work.Command, len(targets)), yes); err != nil {
return err
}
}
executable, err := batchExecutable()
if err != nil {
return err
}
// Temporary output files bound memory even for very verbose commands.
dir, err := os.MkdirTemp("", "netssh-batch-")
if err != nil {
return err
}
defer os.RemoveAll(dir)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
jobs := make(chan int)
results := make(chan batchResult, len(targets))
var wg sync.WaitGroup
var output sync.Mutex
for n := 0; n < parallel; n++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
host := targets[i]
if ctx.Err() != nil {
results <- batchResult{host, 130}
continue
}
output.Lock()
fmt.Fprintf(cmd.OutOrStdout(), "[%s] starting\n", host)
output.Unlock()
f, err := os.CreateTemp(dir, "output-")
if err != nil {
results <- batchResult{host, 1}
continue
}
argv := []string{executable, "run", "--yes"}
if dry {
argv = append(argv, "--dry-run")
}
argv = append(argv, work.Command, "--", host)
argv = append(argv, work.Extra...)
r := runner.Run(ctx, argv, runner.Options{Stdout: f, Stderr: f})
f.Close()
output.Lock()
fmt.Fprintf(cmd.OutOrStdout(), "[%s] exit=%d duration=%s\n", host, r.Code, r.Duration.Round(time.Millisecond))
read, err := os.Open(f.Name())
if err == nil {
_, _ = io.Copy(cmd.OutOrStdout(), read)
read.Close()
}
output.Unlock()
results <- batchResult{host, r.Code}
}
}()
}
for i := range targets {
jobs <- i
}
close(jobs)
wg.Wait()
close(results)
failed := map[string]bool{}
for r := range results {
if r.Code != 0 {
failed[r.Host] = true
}
}
work.Hosts = nil
for _, host := range targets {
if failed[host] {
work.Hosts = append(work.Hosts, host)
}
}
if !dry {
data, _ := json.Marshal(work)
if err := os.MkdirAll(filepath.Dir(batchPath()), 0700); err != nil {
return err
}
if err := storage.WriteFile(batchPath(), data, 0600); err != nil {
return err
}
}
fmt.Fprintf(cmd.OutOrStdout(), "%d succeeded, %d failed\n", len(targets)-len(failed), len(failed))
if len(failed) > 0 {
return fmt.Errorf("batch failed; retry with netssh batch --retry-failed")
}
return nil
}}
cmd.Flags().IntVar(&parallel, "parallel", 4, "Maximum simultaneous hosts (1-64)")
cmd.Flags().BoolVar(&retry, "retry-failed", false, "Repeat failed targets from the last batch")
cmd.Flags().BoolVar(&yes, "yes", false, "Confirm the batch action")
cmd.Flags().BoolVar(&dry, "dry-run", false, "Resolve and print commands without running")
return cmd
}
+217
View File
@@ -0,0 +1,217 @@
package main
import (
"context"
"fmt"
"net"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/charmbracelet/x/term"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/resolver"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
// stdinIsTerminal is replaced in tests.
var stdinIsTerminal = func() bool { return term.IsTerminal(os.Stdin.Fd()) }
// confirmStatus asks before connecting to a host whose NetBox status is listed
// in ssh.warn_status. Without a terminal it only warns, so scripts keep working.
func confirmStatus(cfg *config.Config, host resolvedHost, force bool) error {
if force || !cfg.SSH.WarnsStatus(host.Status) {
return nil
}
message := fmt.Sprintf("%s has NetBox status %q", host.Name, host.Status)
if !stdinIsTerminal() {
fmt.Fprintf(os.Stderr, "netssh: warning: %s\n", message)
return nil
}
if err := confirmAction(message+" — connect anyway", false); err != nil {
return fmt.Errorf("%s: %w (skip this question with --force)", host.Name, err)
}
return nil
}
// connectPort returns the port given in args (-p for ssh, -P for sftp and scp,
// or -o Port=), else 22. The default port is already in args at this point.
func connectPort(client internalssh.Client, args []string, dests []int) int {
end := len(args)
if len(dests) > 0 && dests[0] <= len(args) {
end = dests[0]
}
flag := client.PortArgs("")[0]
for i := 0; i < end; i++ {
arg := args[i]
value := ""
switch {
case arg == flag && i+1 < end:
value = args[i+1]
case strings.HasPrefix(arg, flag) && len(arg) > len(flag):
value = arg[len(flag):]
case arg == "-o" && i+1 < end:
if key, v, ok := strings.Cut(args[i+1], "="); ok && strings.EqualFold(strings.TrimSpace(key), "port") {
value = v
}
}
if port, err := strconv.Atoi(strings.TrimSpace(value)); err == nil && port > 0 && port <= 65535 {
return port
}
}
return 22
}
// reachable reports whether address accepts TCP connections on port.
func reachable(address string, port int, timeout time.Duration) bool {
conn, err := net.DialTimeout("tcp", net.JoinHostPort(address, strconv.Itoa(port)), timeout)
if err != nil {
return false
}
_ = conn.Close()
return true
}
// usesJumpHost reports whether the connection goes through a jump host, so
// the target address cannot be probed from this machine.
func usesJumpHost(opts config.SSHOptions, flags internalssh.WrapperFlags) bool {
if flags.NoJump {
return false
}
return flags.Jump != "" || (opts.ProxyJump != "" && !strings.EqualFold(opts.ProxyJump, "none")) || opts.Options["proxycommand"] != ""
}
// fallbackProbe and fallbackCandidates are replaced in tests.
var (
fallbackProbe = reachable
fallbackCandidates = netboxCandidates
)
// applyFallback keeps host.IP when it answers on the SSH port. Otherwise it
// tries the addresses the other resolver strategies find and connects to the
// first one that answers, with resolver.fallback enabled.
func applyFallback(cfg *config.Config, host resolvedHost, opts config.SSHOptions, flags internalssh.WrapperFlags, port int) resolvedHost {
if !cfg.Resolver.Fallback || host.Kind == config.StaticKind || usesJumpHost(opts, flags) {
return host
}
timeout := cfg.Resolver.FallbackTimeoutDuration()
if fallbackProbe(host.IP, port, timeout) {
return host
}
candidates, err := fallbackCandidates(cfg, host)
if err != nil {
fmt.Fprintf(os.Stderr, "netssh: %s does not answer on port %d and no other address is known: %v\n", host.IP, port, err)
return host
}
for _, candidate := range candidates {
if candidate.Address == host.IP || !internalssh.ValidAddress(candidate.Address) {
continue
}
if fallbackProbe(candidate.Address, port, timeout) {
fmt.Fprintf(os.Stderr, "netssh: %s does not answer on port %d, using %s (%s)\n", host.IP, port, candidate.Address, candidate.Strategy)
host.IP = candidate.Address
return host
}
}
fmt.Fprintf(os.Stderr, "netssh: no address of %s answers on port %d; trying %s anyway\n", host.Name, port, host.IP)
return host
}
// netboxCandidates looks the host up again and lists every strategy's address.
func netboxCandidates(cfg *config.Config, host resolvedHost) ([]resolver.Candidate, error) {
if !cfg.HasNetBox() {
return nil, fmt.Errorf("no NetBox configured")
}
client := newNetBoxClient(cfg)
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
target, err := client.FindHost(ctx, host.Name, host.Kind)
if err != nil {
return nil, err
}
chain, err := resolver.New(cfg.Resolver)
if err != nil {
return nil, err
}
return chain.Candidates(ctx, &target, client)
}
// knownHostsKeys lists the known_hosts names ssh may have stored for a host.
func knownHostsKeys(name string, addresses []string, port int) []string {
seen := map[string]bool{}
var keys []string
add := func(key string) {
if key == "" || seen[strings.ToLower(key)] {
return
}
seen[strings.ToLower(key)] = true
keys = append(keys, key)
if port != 22 {
keys = append(keys, "["+key+"]:"+strconv.Itoa(port))
}
}
_, bare := netbox.SplitTarget(name)
add(bare)
for _, address := range addresses {
add(address)
}
return keys
}
// knownHostsFile returns the first UserKnownHostsFile configured for the
// host, or "" for ssh-keygen's default (~/.ssh/known_hosts).
func knownHostsFile(opts config.SSHOptions) string {
fields := strings.Fields(opts.Options["userknownhostsfile"])
if len(fields) == 0 || fields[0] == "/dev/null" {
return ""
}
file := fields[0]
if rest, ok := strings.CutPrefix(file, "~/"); ok {
if home, err := os.UserHomeDir(); err == nil {
file = filepath.Join(home, rest)
}
}
return file
}
// removeKnownHosts runs ssh-keygen -R for every key. ssh-keygen keeps a
// known_hosts.old backup of the previous file.
var removeKnownHosts = func(keys []string, file string) error {
for _, key := range keys {
args := []string{"-R", key}
if file != "" {
args = append(args, "-f", file)
}
cmd := exec.Command("ssh-keygen", args...)
cmd.Stdout, cmd.Stderr = os.Stderr, os.Stderr
if err := cmd.Run(); err != nil {
return fmt.Errorf("ssh-keygen -R %s: %w", key, err)
}
}
return nil
}
// offerKnownHostsCleanup reports a changed NetBox address and, in a terminal,
// offers to remove the host key stored for the old address.
func offerKnownHostsCleanup(opts config.SSHOptions, host resolvedHost, port int) {
fmt.Fprintf(os.Stderr, "netssh: address of %s changed from %s to %s\n", host.Name, host.PreviousIP, host.IP)
if opts.HostKeyChecking == "off" {
return
}
keys := knownHostsKeys("", []string{host.PreviousIP}, port)
if !stdinIsTerminal() {
fmt.Fprintf(os.Stderr, "netssh: remove the old host key with: netssh known-hosts reset %s\n", host.Name)
return
}
if confirmAction("Remove the known_hosts entry of the old address "+host.PreviousIP, false) != nil {
return
}
if err := removeKnownHosts(keys, knownHostsFile(opts)); err != nil {
fmt.Fprintf(os.Stderr, "netssh: %v\n", err)
}
}
+186
View File
@@ -0,0 +1,186 @@
package main
import (
"errors"
"fmt"
"os"
"os/exec"
"strconv"
"strings"
"github.com/spf13/cobra"
"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"
)
type copyIDFlags struct {
identity, user, kind, jump string
force, check, dryRun, yes bool
noJump, ignoreStatus bool
}
func copyIDCmd() *cobra.Command {
var f copyIDFlags
cmd := &cobra.Command{
Use: "copy-id [flags] HOST|tag:TAG|cluster:NAME|@GROUP...",
Short: "Install your public key on hosts with ssh-copy-id",
Long: `Run ssh-copy-id for each host with the address, user, port, jump host and
SSH options netssh would use to connect. Hosts are given like for netssh multi:
names, tag:TAG, cluster:NAME (devices; --kind vm|all for VMs) or @GROUP.
Hosts run one after another, so password prompts stay readable. A failing
host does not stop the others; the exit code is 1 if any host failed.`,
Example: ` netssh copy-id web01
netssh copy-id -i ~/.ssh/id_ed25519.pub tag:lab
netssh copy-id --dry-run @k8s`,
Args: cobra.MinimumNArgs(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
}
return multiCompletions(cfg, toComplete)
},
RunE: func(cmd *cobra.Command, args []string) error {
return runCopyID(loadConfigOrSetup(), args, f)
},
}
cmd.Flags().StringVarP(&f.identity, "identity", "i", "", "Public key file to install (ssh-copy-id -i)")
cmd.Flags().StringVarP(&f.user, "user", "l", "", "Login user for every host")
cmd.Flags().StringVar(&f.kind, "kind", "", "Host kind for tag: and cluster: — device, vm, or all")
cmd.Flags().StringVar(&f.jump, "jump", "", "Jump host for every host")
cmd.Flags().BoolVar(&f.noJump, "no-jump", false, "Disable jump hosts")
cmd.Flags().BoolVarP(&f.force, "force", "f", false, "Install the key even if it seems present (ssh-copy-id -f)")
cmd.Flags().BoolVarP(&f.check, "check", "n", false, "Only show which keys would be installed (ssh-copy-id -n)")
cmd.Flags().BoolVar(&f.dryRun, "dry-run", false, "Print the ssh-copy-id commands without running them")
cmd.Flags().BoolVarP(&f.yes, "yes", "y", false, fmt.Sprintf("Run for more than %d hosts without asking", maxHostsWithoutConfirm))
cmd.Flags().BoolVar(&f.ignoreStatus, "ignore-status", false, "Do not ask about hosts with a NetBox status in ssh.warn_status")
_ = cmd.RegisterFlagCompletionFunc("kind", cobra.FixedCompletions([]cobra.Completion{"device", "vm", "all"}, cobra.ShellCompDirectiveNoFileComp))
return cmd
}
func runCopyID(cfg *config.Config, selectors []string, f copyIDFlags) error {
if f.jump != "" && f.noJump {
return errors.New("--jump and --no-jump are mutually exclusive")
}
switch f.kind {
case "", "device", "vm", "all":
default:
return fmt.Errorf("--kind must be device, vm, or all")
}
if strings.HasPrefix(f.user, "-") || strings.ContainsAny(f.user, " \t\n@") {
return fmt.Errorf("invalid user %q", f.user)
}
if strings.HasPrefix(f.jump, "-") {
return fmt.Errorf("--jump: invalid host %q", f.jump)
}
c := newCache(cfg)
_ = c.Load()
targets, warnings, err := expandSelectors(cfg, c, selectors, f.kind)
for _, warning := range warnings {
fmt.Fprintln(os.Stderr, "netssh: warning: "+warning)
}
if err != nil {
return err
}
if len(targets) > maxHostsWithoutConfirm && !f.yes && !f.dryRun {
if err := confirmAction(fmt.Sprintf("Run ssh-copy-id for %d hosts", len(targets)), false); err != nil {
return err
}
}
var failed []string
for _, target := range targets {
h, err := resolveTargetE(cfg, target, false)
if err != nil {
fmt.Fprintf(os.Stderr, "netssh: %s: %v\n", target, err)
failed = append(failed, target)
continue
}
if !f.dryRun {
if err := confirmStatus(cfg, h, f.ignoreStatus); err != nil {
fmt.Fprintf(os.Stderr, "netssh: skipping %v\n", err)
failed = append(failed, target)
continue
}
}
argv, err := copyIDArgv(cfg, h, f)
if err != nil {
fmt.Fprintf(os.Stderr, "netssh: %s: %v\n", target, err)
failed = append(failed, target)
continue
}
if f.dryRun {
fmt.Println(internalssh.Quote(argv))
continue
}
fmt.Fprintf(os.Stderr, "==> %s (%s)\n", h.Name, h.IP)
if err := runCopyIDCommand(argv); err != nil {
fmt.Fprintf(os.Stderr, "netssh: %s: %v\n", h.Name, err)
failed = append(failed, h.Name)
}
}
if len(failed) > 0 {
return fmt.Errorf("ssh-copy-id failed for %d of %d hosts: %s", len(failed), len(targets), strings.Join(failed, " "))
}
return nil
}
// runCopyIDCommand is replaced in tests.
var runCopyIDCommand = func(argv []string) error {
path, err := exec.LookPath(argv[0])
if err != nil {
return fmt.Errorf("%s not found in PATH (it ships with OpenSSH): %w", argv[0], err)
}
cmd := exec.Command(path, argv[1:]...)
cmd.Stdin, cmd.Stdout, cmd.Stderr = os.Stdin, os.Stdout, os.Stderr
return cmd.Run()
}
// copyIDArgv builds the ssh-copy-id command for a resolved host. The
// connection options come from the same code that builds ssh commands, so
// the key lands where netssh HOST connects to. ssh-copy-id passes -o and -p
// on to ssh but has no -J, so a jump host becomes -o ProxyJump=.
func copyIDArgv(cfg *config.Config, h resolvedHost, f copyIDFlags) ([]string, error) {
if !internalssh.ValidAddress(h.IP) {
return nil, fmt.Errorf("refusing address %q", h.IP)
}
user, port := hostDefaults(cfg, h)
if f.user != "" {
user = f.user
}
_, name := netbox.SplitTarget(h.Name)
dest := name
if user != "" {
dest = user + "@" + name
}
var args []string
if port > 0 && port != 22 {
args = append(args, "-p", strconv.Itoa(port))
}
args = append(args, dest)
opts := hostOptions(cfg, h)
opts.ExtraArgs, opts.Forwards = nil, nil
result := internalssh.SSH.Apply(args, []int{len(args) - 1}, internalssh.Host{Name: name, IP: h.IP}, opts, internalssh.WrapperFlags{Jump: f.jump, NoJump: f.noJump})
argv := []string{"ssh-copy-id"}
if f.identity != "" {
argv = append(argv, "-i", f.identity)
}
if f.force {
argv = append(argv, "-f")
}
if f.check {
argv = append(argv, "-n")
}
for i := 0; i < len(result.Args); i++ {
if result.Args[i] == "-J" && i+1 < len(result.Args) {
argv = append(argv, "-o", "ProxyJump="+result.Args[i+1])
i++
continue
}
argv = append(argv, result.Args[i])
}
return argv, nil
}
+523
View File
@@ -0,0 +1,523 @@
package main
import (
"fmt"
"io"
"os"
"regexp"
"sort"
"strconv"
"strings"
"time"
"github.com/spf13/cobra"
"go.yaml.in/yaml/v3"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
)
// exportFilter selects the cached hosts to export.
type exportFilter struct {
tag, kind, instance, status string
noStatic bool
output string
}
func (f *exportFilter) register(cmd *cobra.Command) {
cmd.Flags().StringVar(&f.tag, "tag", "", "Only hosts with this tag")
cmd.Flags().StringVar(&f.kind, "kind", "", "Only this kind: device, vm, or static")
cmd.Flags().StringVar(&f.instance, "instance", "", "Only hosts of this NetBox instance")
cmd.Flags().StringVar(&f.status, "status", "", "Only hosts with this NetBox status, e.g. active")
cmd.Flags().BoolVar(&f.noStatic, "no-static", false, "Leave out static hosts (hosts:)")
cmd.Flags().StringVarP(&f.output, "output", "o", "", "Write to this file instead of stdout")
_ = cmd.RegisterFlagCompletionFunc("kind", cobra.FixedCompletions([]cobra.Completion{"device", "vm", "static"}, cobra.ShellCompDirectiveNoFileComp))
}
func (f exportFilter) matches(e cache.Entry) bool {
instance, _ := netbox.SplitTarget(e.Name)
switch {
case f.noStatic && e.Static,
f.kind != "" && !strings.EqualFold(e.Kind, f.kind),
f.instance != "" && !strings.EqualFold(instance, f.instance),
f.status != "" && !strings.EqualFold(e.Status, f.status),
f.tag != "" && !hasTag(e.Tags, f.tag):
return false
}
return true
}
// exportHost is one host with the connection settings netssh would use.
type exportHost struct {
entry cache.Entry
name string // unique inventory / Host name
address string
user string
port int
opts config.SSHOptions
}
// exportHosts loads the filtered cache entries. Hostnames that exist in
// several instances get the instance as prefix ("prod-web01"), others stay bare.
func exportHosts(cfg *config.Config, f exportFilter) ([]exportHost, error) {
c := newCache(cfg)
if err := c.Load(); err != nil {
return nil, err
}
var entries []cache.Entry
counts := map[string]int{}
for _, e := range c.All() {
if !f.matches(e) {
continue
}
entries = append(entries, e)
_, name := netbox.SplitTarget(e.Name)
counts[strings.ToLower(name)]++
}
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
out := make([]exportHost, 0, len(entries))
for _, e := range entries {
instance, name := netbox.SplitTarget(e.Name)
if counts[strings.ToLower(name)] > 1 && instance != "" {
name = instance + "-" + name
}
h := hostFromEntry(e, "cache")
user, port := hostDefaults(cfg, h)
out = append(out, exportHost{entry: e, name: name, address: e.IP, user: user, port: port, opts: hostOptions(cfg, h)})
}
if len(out) == 0 {
return nil, fmt.Errorf("no cached hosts match; run netssh cache refresh first")
}
return out, nil
}
// writeExport writes data to the --output file, or stdout.
func writeExport(f exportFilter, data []byte) error {
if f.output == "" || f.output == "-" {
_, err := os.Stdout.Write(data)
return err
}
if err := storage.WriteFile(f.output, data, 0o600); err != nil {
return err
}
fmt.Fprintf(os.Stderr, "Written → %s\n", f.output)
return nil
}
func exportCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "export",
Short: "Export cached hosts as Ansible inventory or ssh_config",
}
cmd.AddCommand(exportAnsibleCmd(), exportSSHConfigCmd())
return cmd
}
// ansibleGroupKeys are the attributes --group-by accepts.
var ansibleGroupKeys = []string{"tag", "site", "location", "rack", "role", "platform", "tenant", "kind", "instance", "cluster", "status"}
func exportAnsibleCmd() *cobra.Command {
var f exportFilter
var format, groupBy string
var noVars bool
cmd := &cobra.Command{
Use: "ansible",
Short: "Print an Ansible inventory (YAML or INI) of the cached hosts",
Long: `Print an Ansible inventory of the cached hosts. Every host gets ansible_host
(the address netssh connects to), ansible_user, ansible_port and, with a jump
host, ansible_ssh_common_args. NetBox attributes are added as netbox_* host
variables (disable with --no-vars).
Groups are formed from host attributes, named like tag_prod, site_fsn1,
role_router or platform_junos. Choose them with --group-by (comma-separated:
` + strings.Join(ansibleGroupKeys, ", ") + `, or none).`,
Example: ` netssh export ansible > inventory.yml
netssh export ansible --format ini --group-by site,role -o hosts.ini
netssh export ansible --tag prod --status active`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
keys, err := parseGroupBy(groupBy)
if err != nil {
return err
}
hosts, err := exportHosts(cfg, f)
if err != nil {
return err
}
inv := buildInventory(hosts, keys, !noVars)
var data []byte
switch strings.ToLower(format) {
case "yaml", "yml":
data, err = inv.yaml()
case "ini":
data = inv.ini()
default:
return fmt.Errorf("--format must be yaml or ini")
}
if err != nil {
return err
}
return writeExport(f, data)
},
}
f.register(cmd)
cmd.Flags().StringVar(&format, "format", "yaml", "Inventory format: yaml or ini")
cmd.Flags().StringVar(&groupBy, "group-by", "tag,site,role,platform,kind", "Attributes to group hosts by, or none")
cmd.Flags().BoolVar(&noVars, "no-vars", false, "Leave out the netbox_* host variables")
_ = cmd.RegisterFlagCompletionFunc("format", cobra.FixedCompletions([]cobra.Completion{"yaml", "ini"}, cobra.ShellCompDirectiveNoFileComp))
return cmd
}
func parseGroupBy(value string) ([]string, error) {
if strings.EqualFold(strings.TrimSpace(value), "none") || strings.TrimSpace(value) == "" {
return nil, nil
}
var keys []string
for _, key := range strings.Split(value, ",") {
key = strings.ToLower(strings.TrimSpace(key))
valid := false
for _, known := range ansibleGroupKeys {
valid = valid || key == known
}
if !valid {
return nil, fmt.Errorf("--group-by: unknown attribute %q; use %s, or none", key, strings.Join(ansibleGroupKeys, ", "))
}
keys = append(keys, key)
}
return keys, nil
}
// inventoryVar is a host variable; list values stay lists in YAML.
type inventoryVar struct {
key string
value any // string, int, or []string
}
type inventory struct {
hosts []string
vars map[string][]inventoryVar
groups map[string][]string
}
var groupInvalid = regexp.MustCompile(`[^a-z0-9_]+`)
// groupName builds a valid Ansible group name such as site_fsn1.
func groupName(prefix, value string) string {
name := strings.Trim(groupInvalid.ReplaceAllString(strings.ToLower(value), "_"), "_")
if name == "" {
return ""
}
return prefix + "_" + name
}
func buildInventory(hosts []exportHost, groupBy []string, netboxVars bool) inventory {
inv := inventory{vars: map[string][]inventoryVar{}, groups: map[string][]string{}}
for _, h := range hosts {
e := h.entry
inv.hosts = append(inv.hosts, h.name)
vars := []inventoryVar{{"ansible_host", h.address}}
if h.user != "" {
vars = append(vars, inventoryVar{"ansible_user", h.user})
}
if h.port > 0 && h.port != 22 {
vars = append(vars, inventoryVar{"ansible_port", h.port})
}
if jump := h.opts.ProxyJump; jump != "" && !strings.EqualFold(jump, "none") {
vars = append(vars, inventoryVar{"ansible_ssh_common_args", "-o ProxyJump=" + jump})
}
instance, _ := netbox.SplitTarget(e.Name)
if netboxVars && !e.Static {
for _, pair := range [][2]string{
{"netbox_instance", instance}, {"netbox_kind", e.Kind}, {"netbox_status", e.Status},
{"netbox_site", cache.RefOf(e.Site).Name}, {"netbox_role", cache.RefOf(e.Role).Name},
{"netbox_platform", cache.RefOf(e.Platform).Name}, {"netbox_tenant", cache.RefOf(e.Tenant).Name},
{"netbox_cluster", e.Cluster}, {"netbox_location", locationNames(e.Location)},
{"netbox_rack", e.Rack}, {"netbox_position", e.Position},
} {
if pair[1] != "" {
vars = append(vars, inventoryVar{pair[0], pair[1]})
}
}
if e.ID > 0 {
vars = append(vars, inventoryVar{"netbox_id", e.ID})
}
if len(e.Tags) > 0 {
vars = append(vars, inventoryVar{"netbox_tags", append([]string(nil), e.Tags...)})
}
}
inv.vars[h.name] = vars
for _, key := range groupBy {
var values []string
switch key {
case "tag":
values = e.Tags
case "site":
values = []string{cache.RefOf(e.Site).Key()}
case "location":
// Every level, so a play can target a building or a single room.
for _, location := range e.Location {
values = append(values, location.Key())
}
case "rack":
values = []string{e.Rack}
case "role":
values = []string{cache.RefOf(e.Role).Key()}
case "platform":
values = []string{cache.RefOf(e.Platform).Key()}
case "tenant":
values = []string{cache.RefOf(e.Tenant).Key()}
case "kind":
values = []string{e.Kind}
case "instance":
values = []string{instance}
case "cluster":
values = []string{e.Cluster}
case "status":
values = []string{e.Status}
}
for _, value := range values {
if group := groupName(key, value); group != "" {
inv.groups[group] = append(inv.groups[group], h.name)
}
}
}
}
return inv
}
func (inv inventory) groupNames() []string {
names := make([]string, 0, len(inv.groups))
for name := range inv.groups {
names = append(names, name)
}
sort.Strings(names)
return names
}
func exportHeader(comment string) string {
return fmt.Sprintf("%s Generated by netssh export on %s — changes are overwritten on the next export.\n", comment, time.Now().Format(time.RFC3339))
}
// yaml renders the inventory with host variables under all.hosts and the
// groups as children of all, listing their member hosts.
func (inv inventory) yaml() ([]byte, error) {
node := func(kind yaml.Kind, value string) *yaml.Node {
n := &yaml.Node{Kind: kind, Value: value}
if kind == yaml.ScalarNode {
n.Tag = "!!str"
}
return n
}
mapping := func() *yaml.Node { return &yaml.Node{Kind: yaml.MappingNode} }
add := func(m *yaml.Node, key string, value *yaml.Node) {
m.Content = append(m.Content, node(yaml.ScalarNode, key), value)
}
hosts := mapping()
for _, name := range inv.hosts {
vars := mapping()
for _, v := range inv.vars[name] {
var value *yaml.Node
switch typed := v.value.(type) {
case int:
value = &yaml.Node{Kind: yaml.ScalarNode, Tag: "!!int", Value: strconv.Itoa(typed)}
case []string:
value = &yaml.Node{Kind: yaml.SequenceNode}
for _, item := range typed {
value.Content = append(value.Content, node(yaml.ScalarNode, item))
}
default:
value = node(yaml.ScalarNode, fmt.Sprint(typed))
}
add(vars, v.key, value)
}
add(hosts, name, vars)
}
all := mapping()
add(all, "hosts", hosts)
if len(inv.groups) > 0 {
children := mapping()
for _, group := range inv.groupNames() {
members := mapping()
for _, host := range inv.groups[group] {
add(members, host, &yaml.Node{Kind: yaml.MappingNode, Style: yaml.FlowStyle})
}
g := mapping()
add(g, "hosts", members)
add(children, group, g)
}
add(all, "children", children)
}
root := mapping()
add(root, "all", all)
var b strings.Builder
b.WriteString(exportHeader("#"))
enc := yaml.NewEncoder(&b)
enc.SetIndent(2)
if err := enc.Encode(&yaml.Node{Kind: yaml.DocumentNode, Content: []*yaml.Node{root}}); err != nil {
return nil, err
}
if err := enc.Close(); err != nil {
return nil, err
}
return []byte(b.String()), nil
}
// ini renders host variables in [all] and one section per group. Lists such
// as netbox_tags become comma-separated strings, since INI has no lists.
func (inv inventory) ini() []byte {
var b strings.Builder
b.WriteString(exportHeader(";"))
b.WriteString("[all]\n")
for _, name := range inv.hosts {
b.WriteString(name)
for _, v := range inv.vars[name] {
value := fmt.Sprint(v.value)
if list, ok := v.value.([]string); ok {
value = strings.Join(list, ",")
}
fmt.Fprintf(&b, " %s=%s", v.key, iniQuote(value))
}
b.WriteString("\n")
}
for _, group := range inv.groupNames() {
fmt.Fprintf(&b, "\n[%s]\n", group)
for _, host := range inv.groups[group] {
b.WriteString(host + "\n")
}
}
return []byte(b.String())
}
// iniQuote quotes values that Ansible's INI parser (shlex) would split.
func iniQuote(value string) string {
if value != "" && !strings.ContainsAny(value, " \t\"'\\#;=") {
return value
}
return `"` + strings.NewReplacer(`\`, `\\`, `"`, `\"`).Replace(value) + `"`
}
func exportSSHConfigCmd() *cobra.Command {
var f exportFilter
var noAliases bool
cmd := &cobra.Command{
Use: "ssh-config",
Short: "Print ssh_config Host blocks for the cached hosts",
Long: `Print one ssh_config Host block per cached host with the address, user, port,
jump host and SSH options netssh would use. Tools that run ssh themselves
(VS Code Remote, rsync, git, Ansible) can then reach the hosts by name.
Include the file from ~/.ssh/config:
netssh export ssh-config -o ~/.ssh/netssh.conf
echo 'Include ~/.ssh/netssh.conf' >> ~/.ssh/config # once
Shortcut aliases are added as extra Host names (disable with --no-aliases).
extra_args, forwards and hooks have no ssh_config equivalent and are skipped.`,
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
hosts, err := exportHosts(cfg, f)
if err != nil {
return err
}
aliases := map[string]string{}
if !noAliases {
c := newCache(cfg)
_ = c.Load()
aliases = shortcutAliases(c.All(), *cfg)
}
var b strings.Builder
writeSSHConfig(&b, hosts, aliases)
return writeExport(f, []byte(b.String()))
},
}
f.register(cmd)
cmd.Flags().BoolVar(&noAliases, "no-aliases", false, "Do not add shortcut aliases as Host names")
return cmd
}
var sshConfigUnsafe = regexp.MustCompile(`[\s"#*?!,]`)
func writeSSHConfig(w io.Writer, hosts []exportHost, aliases map[string]string) {
fmt.Fprint(w, exportHeader("#"))
used := map[string]bool{}
for _, h := range hosts {
used[strings.ToLower(h.name)] = true
}
for _, h := range hosts {
if sshConfigUnsafe.MatchString(h.name) {
fmt.Fprintf(w, "\n# skipped %q: not usable as a Host name\n", h.name)
continue
}
names := []string{h.name}
if alias := aliases[strings.ToLower(h.entry.Name)]; alias != "" && !used[strings.ToLower(alias)] && !sshConfigUnsafe.MatchString(alias) {
used[strings.ToLower(alias)] = true
names = append(names, alias)
}
fmt.Fprintf(w, "\nHost %s\n", strings.Join(names, " "))
_, bare := netbox.SplitTarget(h.entry.Name)
hostName := h.address
if h.opts.Target == "hostname" && plainName(bare) {
hostName = bare
}
line := func(key, value string) {
if value != "" {
fmt.Fprintf(w, " %s %s\n", key, value)
}
}
line("HostName", hostName)
if h.opts.Target == "name" && plainName(bare) {
line("HostKeyAlias", bare)
}
line("User", h.user)
if h.port > 0 && h.port != 22 {
line("Port", strconv.Itoa(h.port))
}
if jump := h.opts.ProxyJump; jump != "" {
line("ProxyJump", jump)
}
switch h.opts.HostKeyChecking {
case "strict":
line("StrictHostKeyChecking", "yes")
case "accept-new":
line("StrictHostKeyChecking", "accept-new")
case "off":
line("StrictHostKeyChecking", "no")
line("UserKnownHostsFile", "/dev/null")
}
line("AddressFamily", h.opts.AddressFamily)
keys := make([]string, 0, len(h.opts.Options))
for key := range h.opts.Options {
keys = append(keys, key)
}
sort.Strings(keys)
for _, key := range keys {
line(key, h.opts.Options[key])
}
if len(h.opts.ExtraArgs) > 0 {
fmt.Fprintf(w, " # extra_args not exported: %s\n", strings.Join(h.opts.ExtraArgs, " "))
}
}
}
var plainNamePattern = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$`)
func plainName(name string) bool { return plainNamePattern.MatchString(name) }
// locationNames joins a location chain as "Building A/Room 2.04".
func locationNames(chain []config.Ref) string {
names := make([]string, 0, len(chain))
for _, location := range chain {
names = append(names, location.Name)
}
return strings.Join(names, "/")
}
+26 -5
View File
@@ -14,27 +14,32 @@ import (
) )
func hostsCmd() *cobra.Command { func hostsCmd() *cobra.Command {
var showAliases bool
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "hosts", Use: "hosts",
Short: "Manage static hosts that are not in NetBox", Short: "Manage static hosts that are not in NetBox",
Long: `Static hosts are defined under hosts: in the config. They are found before Long: `Static hosts are defined under hosts: in the config. They are found before
NetBox, work offline, and support shortcuts, rules (kind: static), aliases, NetBox, work offline, and support shortcuts, rules (kind: static), aliases,
completion, sftp, scp, and tunnels like NetBox hosts.`, completion, sftp, scp, and tunnels like NetBox hosts.`,
RunE: func(cmd *cobra.Command, args []string) error { return listHosts() }, RunE: func(cmd *cobra.Command, args []string) error { return listHosts(showAliases) },
} }
cmd.AddCommand(hostsListCmd(), hostsAddCmd(), hostsRemoveCmd()) cmd.AddCommand(hostsListCmd(), hostsAddCmd(), hostsRemoveCmd())
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
return cmd return cmd
} }
func hostsListCmd() *cobra.Command { func hostsListCmd() *cobra.Command {
return &cobra.Command{ var showAliases bool
cmd := &cobra.Command{
Use: "list", Use: "list",
Short: "List static hosts", Short: "List static hosts",
RunE: func(cmd *cobra.Command, args []string) error { return listHosts() }, RunE: func(cmd *cobra.Command, args []string) error { return listHosts(showAliases) },
} }
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
return cmd
} }
func listHosts() error { func listHosts(showAliases bool) error {
cfg, err := config.Load() cfg, err := config.Load()
if err != nil { if err != nil {
return err return err
@@ -43,13 +48,29 @@ func listHosts() error {
fmt.Println("No static hosts. Add one with: netssh hosts add NAME ADDRESS") fmt.Println("No static hosts. Add one with: netssh hosts add NAME ADDRESS")
return nil return nil
} }
withAliases := showAliases || cfg.Shortcuts.Show
var aliases map[string]string
if withAliases {
// Aliases are unique across all hosts, so compute them with the cache.
c := newCache(cfg)
_ = c.Load()
aliases = shortcutAliases(c.All(), *cfg)
}
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "NAME\tADDRESS\tUSER\tPORT\tTAGS") if withAliases {
fmt.Fprintln(w, "NAME\tALIAS\tADDRESS\tUSER\tPORT\tTAGS")
} else {
fmt.Fprintln(w, "NAME\tADDRESS\tUSER\tPORT\tTAGS")
}
for _, host := range cfg.Hosts { for _, host := range cfg.Hosts {
port := "" port := ""
if host.Port > 0 { if host.Port > 0 {
port = fmt.Sprint(host.Port) port = fmt.Sprint(host.Port)
} }
if withAliases {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\t%s\n", host.Name, orDash(aliases[strings.ToLower(host.Name)]), host.Address, host.User, port, strings.Join(host.Tags, ","))
continue
}
fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", host.Name, host.Address, host.User, port, strings.Join(host.Tags, ",")) fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", host.Name, host.Address, host.User, port, strings.Join(host.Tags, ","))
} }
return w.Flush() return w.Flush()
+422
View File
@@ -0,0 +1,422 @@
package main
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"os"
"os/exec"
"runtime"
"sort"
"strings"
"text/tabwriter"
"time"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
// hostCompletion completes cached hostnames for commands taking hosts.
func hostCompletion(cmd *cobra.Command, args []string, toComplete string) ([]cobra.Completion, cobra.ShellCompDirective) {
return completeHosts(toComplete), cobra.ShellCompDirectiveNoFileComp
}
// 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)
if err != nil {
return netbox.HostEntry{}, nil, h, err
}
if h.Kind == config.StaticKind {
return netbox.HostEntry{}, nil, h, fmt.Errorf("%s is a static host (hosts:) and has no NetBox record", h.Name)
}
client := newNetBoxClient(cfg)
if client == nil {
return netbox.HostEntry{}, nil, h, fmt.Errorf("no NetBox is configured (netssh configure)")
}
return netboxEntry(ctx, client, h.Name, h.Kind, h.ID, h)
}
// netboxEntry completes a cached host with its NetBox ID, looking it up if needed.
func netboxEntry(ctx context.Context, client *netbox.Client, name, kind string, id int, h resolvedHost) (netbox.HostEntry, *netbox.Client, resolvedHost, error) {
source, bare := netbox.SplitTarget(name)
entry := netbox.HostEntry{Source: source, Name: bare, Kind: kind, ID: id}
if id <= 0 {
found, err := client.FindHost(ctx, name, kind)
if err != nil {
return entry, client, h, fmt.Errorf("NetBox: %w", err)
}
entry = found
}
return entry, client, h, nil
}
// openBrowser opens url with $BROWSER, open (macOS), or xdg-open.
var openBrowser = func(url string) error {
var cmd *exec.Cmd
switch browser := os.Getenv("BROWSER"); {
case browser != "":
cmd = exec.Command(browser, url)
case runtime.GOOS == "darwin":
cmd = exec.Command("open", url)
default:
cmd = exec.Command("xdg-open", url)
}
cmd.Stdout, cmd.Stderr = nil, nil
if err := cmd.Start(); err != nil {
return fmt.Errorf("opening browser: %w (print the URL with --print)", err)
}
return cmd.Process.Release()
}
func openCmd() *cobra.Command {
var printOnly bool
cmd := &cobra.Command{
Use: "open HOST",
Short: "Open the NetBox page of a host in the web browser",
Long: "Open the device or virtual machine page in the NetBox web interface.\nThe browser is $BROWSER, else open (macOS) or xdg-open.",
Args: cobra.ExactArgs(1),
ValidArgsFunction: hostCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
entry, client, _, err := netboxHost(ctx, cfg, args[0])
if err != nil {
return err
}
url, err := client.WebURL(entry)
if err != nil {
return err
}
if printOnly {
fmt.Fprintln(cmd.OutOrStdout(), url)
return nil
}
fmt.Fprintf(os.Stderr, "Opening %s\n", url)
return openBrowser(url)
},
}
cmd.Flags().BoolVar(&printOnly, "print", false, "Print the URL instead of opening it")
return cmd
}
func infoCmd() *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "info HOST",
Short: "Show site, rack, role, platform, status and IP addresses of a host",
Args: cobra.ExactArgs(1),
ValidArgsFunction: hostCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
h, err := resolveTargetE(cfg, args[0], false)
if err != nil {
return err
}
out := cmd.OutOrStdout()
if h.Kind == config.StaticKind {
return printStaticInfo(out, cfg, h, asJSON)
}
client := newNetBoxClient(cfg)
if client == nil {
return fmt.Errorf("no NetBox is configured (netssh configure)")
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
entry, _, _, err := netboxEntry(ctx, client, h.Name, h.Kind, h.ID, h)
if err != nil {
return err
}
details, err := client.GetDetails(ctx, entry)
if err != nil && details.Name == "" {
return fmt.Errorf("NetBox: %w", err)
}
if asJSON {
return json.NewEncoder(out).Encode(map[string]any{"host": details, "connect": map[string]any{"address": h.IP, "source": h.Origin, "resolver": h.Resolver}})
}
writeDetails(out, details, h)
if err != nil {
fmt.Fprintf(os.Stderr, "warning: %v\n", err)
}
return nil
},
}
cmd.Flags().BoolVar(&asJSON, "json", false, "Print JSON")
return cmd
}
func printStaticInfo(w io.Writer, cfg *config.Config, h resolvedHost, asJSON bool) error {
user, port := hostDefaults(cfg, h)
if asJSON {
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)
row(tw, "Address", h.IP)
row(tw, "User", user)
if port > 0 {
row(tw, "Port", fmt.Sprint(port))
}
row(tw, "Tags", strings.Join(h.Tags, ", "))
return tw.Flush()
}
func row(w io.Writer, label, value string) {
if strings.TrimSpace(value) != "" {
fmt.Fprintf(w, " %s\t%s\n", label, value)
}
}
// formatDetails renders netssh info output; the TUI detail view uses it too.
func formatDetails(d netbox.HostDetails, h resolvedHost) string {
var b strings.Builder
writeDetails(&b, d, h)
return b.String()
}
func writeDetails(w io.Writer, d netbox.HostDetails, h resolvedHost) {
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
header := d.Target() + "\t(" + d.Kind
if d.Source != "" {
header += ", NetBox " + d.Source
}
fmt.Fprintln(tw, header+")")
status := d.StatusLabel
if status == "" {
status = d.Status
}
row(tw, "Status", status)
row(tw, "Site", d.Site.Name)
var locations []string
for _, location := range d.Location {
locations = append(locations, location.Name)
}
row(tw, "Location", strings.Join(locations, " › "))
row(tw, "Rack", strings.TrimSpace(d.Rack+" "+d.RackUnits()))
if len(d.Location) > 0 || d.Rack != "" {
row(tw, "Path", d.LocationPath())
}
row(tw, "Role", d.Role.Name)
row(tw, "Platform", d.Platform.Name)
row(tw, "Tenant", d.Tenant.Name)
row(tw, "Type", d.DeviceType)
row(tw, "Serial", d.Serial)
row(tw, "Asset tag", d.AssetTag)
row(tw, "Cluster", d.Cluster)
var resources []string
if d.VCPUs != "" {
resources = append(resources, d.VCPUs+" vCPU")
}
if d.MemoryMB > 0 {
resources = append(resources, fmt.Sprintf("%d MB RAM", d.MemoryMB))
}
if d.DiskGB > 0 {
resources = append(resources, fmt.Sprintf("%d GB disk", d.DiskGB))
}
row(tw, "Resources", strings.Join(resources, ", "))
row(tw, "Tags", strings.Join(d.Tags, ", "))
if h.IP != "" {
via := h.Resolver
if h.Origin != "" {
via = strings.Trim(via+", "+h.Origin, ", ")
}
connect := h.IP
if via != "" {
connect += " (" + via + ")"
}
row(tw, "Connect", connect)
}
row(tw, "URL", d.URL)
row(tw, "Description", d.Description)
_ = tw.Flush()
if len(d.IPs) == 0 {
return
}
fmt.Fprintln(w, "\nIP addresses")
tw = tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
for _, ip := range d.IPs {
mark := " "
if ip.Primary {
mark = "*"
}
extra := ip.Status
if ip.Role != "" {
extra = strings.Trim(extra+", "+ip.Role, ", ")
}
if ip.VRF != "" {
extra = strings.Trim(extra+", vrf "+ip.VRF, ", ")
}
fmt.Fprintf(tw, " %s %s\t%s\t%s\t%s\n", mark, ip.Address, orDash(ip.Interface), ip.DNSName, extra)
}
_ = tw.Flush()
}
// whoisResult is what netssh whois found for one address.
type whoisResult struct {
Address string `json:"address"`
NetBox []netbox.IPOwner `json:"netbox"`
Prefixes []netbox.PrefixInfo `json:"prefixes"`
Cached []string `json:"cached_hosts"`
}
func whoisCmd() *cobra.Command {
var asJSON bool
cmd := &cobra.Command{
Use: "whois ADDRESS|HOSTNAME",
Short: "Find the host, interface and prefix an IP address belongs to",
Long: `Look an IP address up in every NetBox instance and in the local cache:
the device or VM and interface it is assigned to, its DNS name, and the
prefixes containing it. A hostname is resolved through DNS first.`,
Example: " netssh whois 10.20.0.15\n netssh whois mail.example.com",
Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
addresses, err := whoisAddresses(ctx, args[0])
if err != nil {
return err
}
c := newCache(cfg)
_ = c.Load()
var client *netbox.Client
if cfg.HasNetBox() {
client = newNetBoxClient(cfg)
}
var results []whoisResult
var warnings []error
found := false
for _, address := range addresses {
r := whoisResult{Address: address}
for _, e := range c.All() {
if e.IP == address {
r.Cached = append(r.Cached, e.Name)
}
}
sort.Strings(r.Cached)
if client != nil {
owners, err := client.LookupIP(ctx, address)
if err != nil {
warnings = append(warnings, err)
}
r.NetBox = owners
prefixes, err := client.PrefixesContaining(ctx, address)
if err != nil {
warnings = append(warnings, err)
}
r.Prefixes = prefixes
}
found = found || len(r.NetBox) > 0 || len(r.Cached) > 0 || len(r.Prefixes) > 0
results = append(results, r)
}
for _, warning := range warnings {
fmt.Fprintf(os.Stderr, "warning: %v\n", warning)
}
out := cmd.OutOrStdout()
if asJSON {
return json.NewEncoder(out).Encode(results)
}
writeWhois(out, results)
if !found {
cmd.SilenceErrors, cmd.SilenceUsage = true, true
return &commandExit{code: 1}
}
return nil
},
}
cmd.Flags().BoolVar(&asJSON, "json", false, "Print JSON")
return cmd
}
// lookupHost is replaced in tests.
var lookupHost = net.DefaultResolver.LookupHost
func whoisAddresses(ctx context.Context, query string) ([]string, error) {
query = strings.TrimSpace(query)
if ip := net.ParseIP(query); ip != nil {
return []string{ip.String()}, nil
}
if _, network, err := net.ParseCIDR(query); err == nil {
return []string{network.IP.String()}, nil
}
addresses, err := lookupHost(ctx, query)
if err != nil {
return nil, fmt.Errorf("%q is no IP address and cannot be resolved: %w", query, err)
}
if len(addresses) == 0 {
return nil, errors.New("no addresses found")
}
return addresses, nil
}
func writeWhois(w io.Writer, results []whoisResult) {
for i, r := range results {
if i > 0 {
fmt.Fprintln(w)
}
fmt.Fprintln(w, r.Address)
tw := tabwriter.NewWriter(w, 0, 0, 2, ' ', 0)
if len(r.NetBox) == 0 && len(r.Cached) == 0 && len(r.Prefixes) == 0 {
fmt.Fprintln(tw, " not found in NetBox or the cache")
}
for _, o := range r.NetBox {
owner := "unassigned"
if o.Target() != "" {
owner = o.Target() + " (" + o.HostKind + ")"
if o.Interface != "" {
owner += " " + o.Interface
}
}
var extra []string
if o.Status != "" {
extra = append(extra, o.Status)
}
if o.VRF != "" {
extra = append(extra, "vrf "+o.VRF)
}
if o.DNSName != "" {
extra = append(extra, "dns "+o.DNSName)
}
if o.Description != "" {
extra = append(extra, fmt.Sprintf("%q", o.Description))
}
fmt.Fprintf(tw, " IP\t%s\t%s\t%s\n", o.Address, owner, strings.Join(extra, " "))
}
for _, p := range r.Prefixes {
var extra []string
for _, pair := range [][2]string{{"", p.Status}, {"site ", p.Site}, {"role ", p.Role}, {"vlan ", p.VLAN}, {"vrf ", p.VRF}} {
if pair[1] != "" {
extra = append(extra, pair[0]+pair[1])
}
}
if p.Description != "" {
extra = append(extra, fmt.Sprintf("%q", p.Description))
}
prefix := p.Prefix
if p.Source != "" {
prefix += " (" + p.Source + ")"
}
fmt.Fprintf(tw, " Prefix\t%s\t%s\n", prefix, strings.Join(extra, " "))
}
for _, name := range r.Cached {
fmt.Fprintf(tw, " Cache\t%s\n", name)
}
_ = tw.Flush()
}
}
+559
View File
@@ -0,0 +1,559 @@
package main
import (
"bytes"
"context"
"errors"
"fmt"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
"testing"
"time"
"go.yaml.in/yaml/v3"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/resolver"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/secret"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
// insightEnv writes a config and a cache with two NetBox hosts and a static host.
func insightEnv(t *testing.T, yamlConfig string) string {
t.Helper()
configDir := t.TempDir()
t.Setenv("HOME", t.TempDir())
t.Setenv("XDG_CONFIG_HOME", configDir)
t.Setenv("XDG_CACHE_HOME", t.TempDir())
path := filepath.Join(t.TempDir(), "hosts.json")
t.Setenv("NETSSH_CACHE_PATH", path)
t.Setenv("NETSSH_SHELL_ALIAS", "")
if err := os.WriteFile(filepath.Join(configDir, "netssh.yaml"), []byte(yamlConfig), 0o600); err != nil {
t.Fatal(err)
}
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
c := cache.New(cfg.CachePath(), 3600)
c.Upsert(cache.Entry{Name: "prod/web01", IP: "10.0.0.1", Kind: "vm", Tags: []string{"prod", "Web Server"}, ID: 11, Status: "active",
Site: &config.Ref{Name: "FSN 1", Slug: "fsn1"}, Role: &config.Ref{Name: "Web", Slug: "web"}, Platform: &config.Ref{Name: "Ubuntu 24.04", Slug: "ubuntu-24-04"}})
c.Upsert(cache.Entry{Name: "lab/web01", IP: "10.9.0.1", Kind: "vm", ID: 12, Status: "planned"})
c.Upsert(cache.Entry{Name: "prod/sw1", IP: "10.0.0.2", Kind: "device", ID: 13, Status: "active", Platform: &config.Ref{Name: "Junos", Slug: "junos"},
Location: []config.Ref{{Name: "Building A", Slug: "building-a"}, {Name: "Room 2.04", Slug: "room-2-04"}}, Rack: "R12", Position: "20"})
if err := c.Save(); err != nil {
t.Fatal(err)
}
return path
}
const insightConfig = `netboxes:
- name: prod
url: https://nb.example
token: t
- name: lab
url: https://lab.example
token: t
ssh:
default_user: admin
rules:
- match: {platform: junos}
proxy_jump: jump.example
options: {KexAlgorithms: +diffie-hellman-group14-sha1}
hosts:
- name: router
address: 192.168.1.1
port: 2222
tags: [home]
`
func TestExportAnsibleYAML(t *testing.T) {
insightEnv(t, insightConfig)
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
keys, _ := parseGroupBy("tag,site,platform,status")
hosts, err := exportHosts(cfg, exportFilter{})
if err != nil {
t.Fatal(err)
}
data, err := buildInventory(hosts, keys, true).yaml()
if err != nil {
t.Fatal(err)
}
var inv struct {
All struct {
Hosts map[string]map[string]any `yaml:"hosts"`
Children map[string]struct {
Hosts map[string]any `yaml:"hosts"`
} `yaml:"children"`
} `yaml:"all"`
}
if err := yaml.Unmarshal(data, &inv); err != nil {
t.Fatalf("invalid YAML: %v\n%s", err, data)
}
web := inv.All.Hosts["prod-web01"]
if web["ansible_host"] != "10.0.0.1" || web["ansible_user"] != "admin" || web["netbox_site"] != "FSN 1" || web["netbox_id"] != 11 {
t.Fatalf("prod-web01 vars wrong: %+v\n%s", web, data)
}
if tags, _ := web["netbox_tags"].([]any); len(tags) != 2 {
t.Fatalf("tags should stay a list: %#v", web["netbox_tags"])
}
if _, ok := inv.All.Hosts["lab-web01"]; !ok {
t.Fatalf("duplicate hostnames must be qualified: %v", inv.All.Hosts)
}
sw := inv.All.Hosts["sw1"]
if sw["ansible_ssh_common_args"] != "-o ProxyJump=jump.example" {
t.Fatalf("jump host missing for platform rule: %+v", sw)
}
router := inv.All.Hosts["router"]
if router["ansible_port"] != 2222 || router["ansible_host"] != "192.168.1.1" {
t.Fatalf("static host wrong: %+v", router)
}
for _, group := range []string{"tag_prod", "tag_web_server", "site_fsn1", "platform_junos", "status_planned", "tag_home"} {
if _, ok := inv.All.Children[group]; !ok {
t.Errorf("group %s missing in\n%s", group, data)
}
}
if _, ok := inv.All.Children["platform_junos"].Hosts["sw1"]; !ok {
t.Fatal("sw1 not in platform_junos")
}
}
func TestExportAnsibleINI(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
hosts, err := exportHosts(cfg, exportFilter{instance: "prod"})
if err != nil {
t.Fatal(err)
}
keys, _ := parseGroupBy("tag,role")
out := string(buildInventory(hosts, keys, true).ini())
for _, want := range []string{
"[all]\nsw1 ansible_host=10.0.0.2 ansible_user=admin ansible_ssh_common_args=\"-o ProxyJump=jump.example\"",
`web01 ansible_host=10.0.0.1`,
`netbox_site="FSN 1"`,
`netbox_tags="prod,Web Server"`,
"\n[role_web]\nweb01\n",
"\n[tag_prod]\nweb01\n",
} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in\n%s", want, out)
}
}
if strings.Contains(out, "lab") || strings.Contains(out, "router") {
t.Fatalf("--instance prod not applied:\n%s", out)
}
}
func TestExportFiltersAndGroupByValidation(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
hosts, err := exportHosts(cfg, exportFilter{status: "active", noStatic: true})
if err != nil {
t.Fatal(err)
}
if len(hosts) != 2 {
t.Fatalf("status filter: %+v", hosts)
}
if _, err := parseGroupBy("site,color"); err == nil {
t.Fatal("unknown group-by accepted")
}
if keys, err := parseGroupBy("none"); err != nil || keys != nil {
t.Fatal("none should disable groups")
}
if _, err := exportHosts(cfg, exportFilter{tag: "missing"}); err == nil {
t.Fatal("empty export should fail")
}
}
func TestExportSSHConfig(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
hosts, err := exportHosts(cfg, exportFilter{})
if err != nil {
t.Fatal(err)
}
var b bytes.Buffer
writeSSHConfig(&b, hosts, map[string]string{"prod/sw1": "sw"})
out := b.String()
for _, want := range []string{
"\nHost sw1 sw\n HostName 10.0.0.2\n User admin\n ProxyJump jump.example\n kexalgorithms +diffie-hellman-group14-sha1\n",
"\nHost router\n HostName 192.168.1.1\n User admin\n Port 2222\n",
"\nHost prod-web01\n HostName 10.0.0.1\n",
} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in\n%s", want, out)
}
}
}
func TestCopyIDArgv(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
h, err := resolveTargetE(cfg, "prod/sw1", false)
if err != nil {
t.Fatal(err)
}
argv, err := copyIDArgv(cfg, h, copyIDFlags{identity: "/k.pub"})
if err != nil {
t.Fatal(err)
}
got := internalssh.Quote(argv)
for _, want := range []string{"ssh-copy-id -i /k.pub", "-o ProxyJump=jump.example", "-o kexalgorithms=+diffie-hellman-group14-sha1", "admin@10.0.0.2"} {
if !strings.Contains(got, want) {
t.Errorf("missing %q in %s", want, got)
}
}
if strings.Contains(got, " -J ") {
t.Fatalf("ssh-copy-id has no -J: %s", got)
}
router, _ := resolveTargetE(cfg, "router", false)
argv, _ = copyIDArgv(cfg, router, copyIDFlags{user: "root", noJump: true, check: true})
if got := internalssh.Quote(argv); !strings.Contains(got, "-n") || !strings.Contains(got, "-p 2222") || !strings.HasSuffix(got, "root@192.168.1.1") {
t.Fatalf("static host argv wrong: %s", got)
}
}
func TestRunCopyIDContinuesAfterFailure(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
var ran []string
old := runCopyIDCommand
runCopyIDCommand = func(argv []string) error {
ran = append(ran, argv[len(argv)-1])
if strings.Contains(argv[len(argv)-1], "10.0.0.2") {
return errors.New("permission denied")
}
return nil
}
t.Cleanup(func() { runCopyIDCommand = old })
stubTerminal(t, false)
err := runCopyID(cfg, []string{"prod/sw1", "router"}, copyIDFlags{})
if err == nil || !strings.Contains(err.Error(), "1 of 2 hosts") || len(ran) != 2 {
t.Fatalf("err %v, ran %v", err, ran)
}
}
func stubTerminal(t *testing.T, tty bool) {
t.Helper()
old := stdinIsTerminal
stdinIsTerminal = func() bool { return tty }
t.Cleanup(func() { stdinIsTerminal = old })
}
func TestConfirmStatusWarnsWithoutTerminal(t *testing.T) {
stubTerminal(t, false)
cfg := &config.Config{}
if err := confirmStatus(cfg, resolvedHost{Name: "web", Status: "offline"}, false); err != nil {
t.Fatalf("non-interactive status check must not fail: %v", err)
}
if err := confirmStatus(cfg, resolvedHost{Name: "web", Status: "active"}, false); err != nil {
t.Fatal(err)
}
}
func TestKnownHostsKeysAndFile(t *testing.T) {
keys := knownHostsKeys("prod/web01", []string{"10.0.0.1", "10.0.0.1", "10.0.0.9"}, 2222)
want := []string{"web01", "[web01]:2222", "10.0.0.1", "[10.0.0.1]:2222", "10.0.0.9", "[10.0.0.9]:2222"}
if strings.Join(keys, " ") != strings.Join(want, " ") {
t.Fatalf("got %v", keys)
}
if keys := knownHostsKeys("web", []string{"10.0.0.1"}, 22); strings.Join(keys, " ") != "web 10.0.0.1" {
t.Fatalf("got %v", keys)
}
t.Setenv("HOME", "/home/u")
if f := knownHostsFile(config.SSHOptions{Options: map[string]string{"userknownhostsfile": "~/.ssh/lab_hosts ~/.ssh/other"}}); f != "/home/u/.ssh/lab_hosts" {
t.Fatalf("file %q", f)
}
if f := knownHostsFile(config.SSHOptions{Options: map[string]string{"userknownhostsfile": "/dev/null"}}); f != "" {
t.Fatalf("file %q", f)
}
}
func TestKnownHostsResetRemovesNameAndAddresses(t *testing.T) {
insightEnv(t, insightConfig)
var removed []string
old := removeKnownHosts
removeKnownHosts = func(keys []string, file string) error { removed = append(removed, keys...); return nil }
t.Cleanup(func() { removeKnownHosts = old })
cmd := rootCmd()
cmd.SetArgs([]string{"known-hosts", "reset", "--yes", "router"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if strings.Join(removed, " ") != "router [router]:2222 192.168.1.1 [192.168.1.1]:2222" {
t.Fatalf("removed %v", removed)
}
}
func TestConnectPort(t *testing.T) {
for _, tc := range []struct {
client internalssh.Client
args []string
want int
}{
{internalssh.SSH, []string{"-p", "2222", "web"}, 2222},
{internalssh.SSH, []string{"-p2200", "web"}, 2200},
{internalssh.SSH, []string{"-o", "Port=2022", "web"}, 2022},
{internalssh.SFTP, []string{"-P", "23", "web"}, 23},
{internalssh.SSH, []string{"web", "-p", "1"}, 22},
} {
dest := 0
for i, a := range tc.args {
if a == "web" {
dest = i
}
}
if got := connectPort(tc.client, tc.args, []int{dest}); got != tc.want {
t.Errorf("%v: got %d, want %d", tc.args, got, tc.want)
}
}
}
func TestApplyFallback(t *testing.T) {
up := map[string]bool{"10.0.0.2": true}
oldProbe, oldCandidates := fallbackProbe, fallbackCandidates
fallbackProbe = func(address string, port int, _ time.Duration) bool { return up[address] && port == 22 }
fallbackCandidates = func(*config.Config, resolvedHost) ([]resolver.Candidate, error) {
return []resolver.Candidate{{Address: "10.0.0.1", Strategy: "management_subnet"}, {Address: "10.0.0.2", Strategy: "primary_ip"}}, nil
}
t.Cleanup(func() { fallbackProbe, fallbackCandidates = oldProbe, oldCandidates })
host := resolvedHost{Name: "web", Kind: "vm", IP: "10.0.0.1"}
cfg := &config.Config{}
if got := applyFallback(cfg, host, config.SSHOptions{}, internalssh.WrapperFlags{}, 22); got.IP != "10.0.0.1" {
t.Fatal("fallback ran while disabled")
}
cfg.Resolver.Fallback = true
if got := applyFallback(cfg, host, config.SSHOptions{}, internalssh.WrapperFlags{}, 22); got.IP != "10.0.0.2" {
t.Fatalf("fallback did not switch: %s", got.IP)
}
if got := applyFallback(cfg, host, config.SSHOptions{ProxyJump: "jump"}, internalssh.WrapperFlags{}, 22); got.IP != "10.0.0.1" {
t.Fatal("hosts behind a jump host must not be probed")
}
if got := applyFallback(cfg, host, config.SSHOptions{ProxyJump: "jump"}, internalssh.WrapperFlags{NoJump: true}, 22); got.IP != "10.0.0.2" {
t.Fatal("--no-jump should allow the fallback")
}
up = map[string]bool{}
if got := applyFallback(cfg, host, config.SSHOptions{}, internalssh.WrapperFlags{}, 22); got.IP != "10.0.0.1" {
t.Fatal("must keep the chosen address when nothing answers")
}
}
func TestReachableProbe(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Skip(err)
}
port := ln.Addr().(*net.TCPAddr).Port
if !reachable("127.0.0.1", port, time.Second) {
t.Fatal("listening port reported unreachable")
}
ln.Close()
if reachable("127.0.0.1", port, 200*time.Millisecond) {
t.Fatal("closed port reported reachable")
}
}
func TestWhoisAddresses(t *testing.T) {
old := lookupHost
lookupHost = func(_ context.Context, host string) ([]string, error) {
if host == "mail.example.com" {
return []string{"192.0.2.25"}, nil
}
return nil, errors.New("no such host")
}
t.Cleanup(func() { lookupHost = old })
for in, want := range map[string]string{"10.0.0.1": "10.0.0.1", "10.0.0.0/24": "10.0.0.0", "mail.example.com": "192.0.2.25"} {
got, err := whoisAddresses(context.Background(), in)
if err != nil || len(got) != 1 || got[0] != want {
t.Errorf("%s: %v %v", in, got, err)
}
}
if _, err := whoisAddresses(context.Background(), "nope.invalid"); err == nil {
t.Fatal("unresolvable name accepted")
}
}
func TestWhoisCommandUsesNetBoxAndCache(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/ipam/ip-addresses/":
fmt.Fprint(w, `{"count":1,"results":[{"address":"10.0.0.1/24","dns_name":"web01.example.com","assigned_object":{"name":"eth0","virtual_machine":{"id":11,"name":"web01"}}}]}`)
case "/api/ipam/prefixes/":
fmt.Fprint(w, `{"count":1,"results":[{"prefix":"10.0.0.0/24","description":"servers"}]}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
insightEnv(t, fmt.Sprintf("netboxes:\n - name: prod\n url: %s\n token: t\n", srv.URL))
var out bytes.Buffer
cmd := rootCmd()
cmd.SetOut(&out)
cmd.SetArgs([]string{"whois", "10.0.0.1"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
for _, want := range []string{"prod/web01 (vm) eth0", "dns web01.example.com", "10.0.0.0/24 (prod)", `"servers"`, "Cache prod/web01"} {
if !strings.Contains(out.String(), want) {
t.Errorf("missing %q in\n%s", want, out.String())
}
}
}
func TestOpenPrintsNetBoxURL(t *testing.T) {
insightEnv(t, insightConfig)
var out bytes.Buffer
cmd := rootCmd()
cmd.SetOut(&out)
cmd.SetArgs([]string{"open", "--print", "prod/sw1"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if strings.TrimSpace(out.String()) != "https://nb.example/dcim/devices/13/" {
t.Fatalf("got %q", out.String())
}
cmd = rootCmd()
cmd.SetArgs([]string{"open", "--print", "router"})
if err := cmd.Execute(); err == nil || !strings.Contains(err.Error(), "static host") {
t.Fatalf("static host: %v", err)
}
}
func TestTokenMigrateAndResolve(t *testing.T) {
secret.MockInit()
insightEnv(t, insightConfig)
var saved config.Config
old := saveConfig
saveConfig = func(cfg config.Config) error { saved = cfg; return nil }
t.Cleanup(func() { saveConfig = old })
tokenMu.Lock()
tokenCache = map[string]string{}
tokenMu.Unlock()
var out bytes.Buffer
cmd := rootCmd()
cmd.SetOut(&out)
cmd.SetArgs([]string{"token", "migrate"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
if len(saved.NetBoxes) != 2 || !config.IsKeyringToken(saved.NetBoxes[0].Token) || !config.IsKeyringToken(saved.NetBoxes[1].Token) {
t.Fatalf("tokens not replaced: %+v", saved.NetBoxes)
}
token, err := resolveToken(saved.NetBoxes[0])
if err != nil || token != "t" {
t.Fatalf("token %q, %v", token, err)
}
cmd = rootCmd()
cmd.SetIn(strings.NewReader("nbt_secret\n"))
cmd.SetOut(&out)
cmd.SetArgs([]string{"token", "set", "lab"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
stored, err := secret.Get("lab")
if err != nil || stored != "nbt_secret" {
t.Fatalf("stored %q, %v", stored, err)
}
for _, n := range saved.NetBoxes {
if n.Name == "lab" && n.TokenVersion != 2 {
t.Fatalf("token version not detected: %+v", n)
}
}
cmd = rootCmd()
cmd.SetArgs([]string{"token", "set"})
if err := cmd.Execute(); err == nil {
t.Fatal("ambiguous instance accepted")
}
}
func TestCacheRefreshStoresAttributesAndReportsChangedAddresses(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch r.URL.Path {
case "/api/dcim/devices/":
fmt.Fprint(w, `{"count":1,"results":[{"id":5,"name":"sw1","primary_ip4":{"address":"192.0.2.5/24"},
"status":{"value":"offline"},"site":{"name":"FSN1","slug":"fsn1"},"role":{"name":"Switch","slug":"switch"},"platform":{"name":"Junos","slug":"junos"}}]}`)
case "/api/virtualization/virtual-machines/", "/api/ipam/ip-addresses/":
fmt.Fprint(w, `{"count":0,"results":[]}`)
default:
http.NotFound(w, r)
}
}))
defer srv.Close()
path := prepareRefreshTest(t, srv.URL, "[primary_ip]")
c := cache.New(path, 3600)
c.Upsert(cache.Entry{Name: "sw1", IP: "192.0.2.99", Kind: "device"})
if err := c.Save(); err != nil {
t.Fatal(err)
}
stdout := captureStdout(t, func() {
cmd := rootCmd()
cmd.SetArgs([]string{"cache", "refresh"})
if err := cmd.Execute(); err != nil {
t.Fatal(err)
}
})
if !strings.Contains(stdout, "sw1: 192.0.2.99 → 192.0.2.5") || !strings.Contains(stdout, "known-hosts reset") {
t.Fatalf("address change not reported:\n%s", stdout)
}
if err := c.Load(); err != nil {
t.Fatal(err)
}
got, _ := c.Get("sw1")
if got.ID != 5 || got.Status != "offline" || cache.RefOf(got.Site).Slug != "fsn1" || cache.RefOf(got.Platform).Slug != "junos" || cache.RefOf(got.Role).Name != "Switch" {
t.Fatalf("attributes not cached: %+v", got)
}
cfg, _ := config.Load()
h, _ := resolveTargetE(cfg, "sw1", false)
if h.Status != "offline" || h.Platform.Slug != "junos" || h.ID != 5 {
t.Fatalf("resolved host lacks attributes: %+v", h)
}
}
func captureStdout(t *testing.T, fn func()) string {
t.Helper()
r, w, err := os.Pipe()
if err != nil {
t.Fatal(err)
}
old := os.Stdout
os.Stdout = w
done := make(chan string)
go func() {
var b bytes.Buffer
_, _ = b.ReadFrom(r)
done <- b.String()
}()
defer func() { os.Stdout = old }()
fn()
w.Close()
os.Stdout = old
return <-done
}
func TestExportLocationVarsAndGroups(t *testing.T) {
insightEnv(t, insightConfig)
cfg, _ := config.Load()
hosts, err := exportHosts(cfg, exportFilter{instance: "prod", kind: "device"})
if err != nil {
t.Fatal(err)
}
keys, _ := parseGroupBy("location,rack")
out := string(buildInventory(hosts, keys, true).ini())
for _, want := range []string{`netbox_location="Building A/Room 2.04"`, "netbox_rack=R12", "netbox_position=20",
"\n[location_building_a]\nsw1\n", "\n[location_room_2_04]\nsw1\n", "\n[rack_r12]\nsw1\n"} {
if !strings.Contains(out, want) {
t.Errorf("missing %q in\n%s", want, out)
}
}
}
+44 -3
View File
@@ -6,6 +6,7 @@ import (
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/shortcuts" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/shortcuts"
) )
@@ -19,14 +20,38 @@ func newNetBoxClient(cfg *config.Config) *netbox.Client {
if len(cfg.NetBoxes) > 0 { if len(cfg.NetBoxes) > 0 {
sources := make([]netbox.Source, 0, len(cfg.NetBoxes)) sources := make([]netbox.Source, 0, len(cfg.NetBoxes))
for _, source := range cfg.NetBoxes { for _, source := range cfg.NetBoxes {
sources = append(sources, netbox.Source{Name: source.Name, URL: source.URL, Token: source.Token, TokenVersion: source.TokenVersion}) token, version := clientToken(source)
sources = append(sources, netbox.Source{Name: source.Name, URL: source.URL, Token: token, TokenVersion: version})
} }
return netbox.NewMultiClient(sources) return netbox.NewMultiClient(sources)
} }
if cfg.NetBox.URL == "" { if cfg.NetBox.URL == "" {
return nil return nil
} }
return netbox.NewClient(cfg.NetBox.URL, cfg.NetBox.Token, cfg.NetBox.TokenVersion) token, version := clientToken(cfg.NetBox)
return netbox.NewClient(cfg.NetBox.URL, token, version)
}
// shortcutAliases maps each target (lowercased) to the shell alias generated for
// it, but only where shortcuts actually shorten the displayed name: an alias that
// merely replaces dots with underscores ("web01_example_com") adds nothing.
// The aliases are the same ones netssh alias and the shell hook define.
func shortcutAliases(entries []cache.Entry, cfg config.Config) map[string]string {
out := make(map[string]string)
if !cfg.Shortcuts.Enabled() {
return out
}
plain := strings.NewReplacer(".", "_", "/", "_")
for _, alias := range hook.BuildAliasEntries(append([]cache.Entry(nil), entries...), cfg) {
if alias.Host == "" || alias.Command != "" {
continue // the command alias for netssh itself
}
if alias.Name == plain.Replace(strings.ToLower(cfg.HostLabel(alias.Host))) {
continue
}
out[strings.ToLower(alias.Host)] = alias.Name
}
return out
} }
func normalizeTarget(cfg config.ShortcutsConfig, qualified bool) func(string) string { func normalizeTarget(cfg config.ShortcutsConfig, qualified bool) func(string) string {
@@ -48,6 +73,9 @@ func normalizeTarget(cfg config.ShortcutsConfig, qualified bool) func(string) st
// Names present in several instances stay qualified ("prod/web01"). // Names present in several instances stay qualified ("prod/web01").
// Hosts whose full name does not match are offered by their configured // Hosts whose full name does not match are offered by their configured
// shortcut instead ("fsnb" → "fsnbx1" for fsn1-bx1.example.com). // shortcut instead ("fsnb" → "fsnbx1" for fsn1-bx1.example.com).
//
// With shortcuts.show, shortcuts are also offered for hosts whose full name
// matches, so "fsn" lists both fsn1-bx1.example.com and fsnbx1.
func hostCompletions(entries []cache.Entry, toComplete string, sc config.ShortcutsConfig) []string { func hostCompletions(entries []cache.Entry, toComplete string, sc config.ShortcutsConfig) []string {
prefix := strings.ToLower(toComplete) prefix := strings.ToLower(toComplete)
qualifiedInput := strings.Contains(prefix, "/") qualifiedInput := strings.Contains(prefix, "/")
@@ -75,7 +103,20 @@ func hostCompletions(entries []cache.Entry, toComplete string, sc config.Shortcu
} }
} }
if sc.Enabled() { if sc.Enabled() {
names = append(names, shortcutCompletions(entries, unmatched, prefix, sc)...) candidates := unmatched
if sc.Show {
candidates = entries
}
offered := make(map[string]bool, len(names))
for _, name := range names {
offered[strings.ToLower(name)] = true
}
for _, name := range shortcutCompletions(entries, candidates, prefix, sc) {
if !offered[name] {
offered[name] = true
names = append(names, name)
}
}
} }
sort.Strings(names) sort.Strings(names)
return names return names
+98
View File
@@ -0,0 +1,98 @@
package main
import (
"fmt"
"os"
"strings"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
func knownHostsCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "known-hosts",
Short: "Clean up host keys of re-deployed hosts",
}
cmd.AddCommand(knownHostsResetCmd())
return cmd
}
func knownHostsResetCmd() *cobra.Command {
var yes, dryRun bool
cmd := &cobra.Command{
Use: "reset HOST...",
Short: "Remove the known_hosts entries of hosts (name, current and previous address)",
Long: `Remove the stored host keys of hosts with ssh-keygen -R, after a host was
re-installed or got a new address. Removed are the hostname, the address
netssh connects to, the previously cached address if NetBox changed it, and
[name]:port / [address]:port for a non-standard port. ssh-keygen keeps the
previous file as known_hosts.old.`,
Example: " netssh known-hosts reset web01\n netssh known-hosts reset --dry-run web01 web02",
Args: cobra.MinimumNArgs(1),
ValidArgsFunction: hostCompletion,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
c := newCache(cfg)
_ = c.Load()
type plan struct {
keys []string
file string
}
var plans []plan
var all []string
for _, target := range args {
previous, _ := c.Get(target)
h, err := resolveTargetE(cfg, target, false)
if err != nil {
return err
}
addresses := []string{h.IP}
if h.PreviousIP != "" {
addresses = append(addresses, h.PreviousIP)
}
if previous.IP != "" && previous.IP != h.IP {
addresses = append(addresses, previous.IP)
}
_, port := hostDefaults(cfg, h)
if port <= 0 {
port = 22
}
opts := hostOptions(cfg, h)
p := plan{keys: knownHostsKeys(h.Name, addresses, port), file: knownHostsFile(opts)}
plans = append(plans, p)
all = append(all, p.keys...)
}
if dryRun {
for _, p := range plans {
for _, key := range p.keys {
argv := []string{"ssh-keygen", "-R", key}
if p.file != "" {
argv = append(argv, "-f", p.file)
}
fmt.Fprintln(cmd.OutOrStdout(), internalssh.Quote(argv))
}
}
return nil
}
if err := confirmAction("Remove known_hosts entries for "+strings.Join(all, ", "), yes); err != nil {
return err
}
for _, p := range plans {
if err := removeKnownHosts(p.keys, p.file); err != nil {
return err
}
}
fmt.Fprintln(os.Stderr, "Done. The next connection asks to confirm the new host key.")
return nil
},
}
cmd.Flags().BoolVarP(&yes, "yes", "y", false, "Do not ask for confirmation")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the ssh-keygen commands without running them")
return cmd
}
+293 -59
View File
@@ -17,6 +17,7 @@ import (
tea "charm.land/bubbletea/v2" tea "charm.land/bubbletea/v2"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
@@ -30,24 +31,33 @@ import (
// managedSubcommands are dispatched to cobra; everything else is treated as SSH wrapper mode. // managedSubcommands are dispatched to cobra; everything else is treated as SSH wrapper mode.
var managedSubcommands = map[string]bool{ var managedSubcommands = map[string]bool{
"configure": true, "doctor": true, "explain": true, "favorites": true, "history": true, "batch": true, "config": true,
"notes": true, "configure": true,
"search": true, "notes": true,
"cache": true, "search": true,
"alias": true, "cache": true,
"hook": true, "alias": true,
"shell-init": true, "hook": true,
"completion": true, "shell-init": true,
"__complete": true, "completion": true,
"help": true, "__complete": true,
"version": true, "help": true,
"uninstall": true, "version": true,
"sftp": true, "uninstall": true,
"scp": true, "sftp": true,
"tunnel": true, "scp": true,
"hosts": true, "tunnel": true,
"multi": true, "hosts": true,
"sync": true, "multi": true,
"sync": true,
"run": true,
"open": true,
"info": true,
"whois": true,
"copy-id": true,
"export": true,
"token": true,
"known-hosts": true,
} }
func main() { func main() {
@@ -62,8 +72,22 @@ func main() {
return return
} }
// ssh has neither option, so both can only mean netssh's own help.
if args[0] == "--help" || args[0] == "-h" {
root := rootCmd()
root.SetArgs([]string{"help"})
if err := root.Execute(); err != nil {
os.Exit(1)
}
return
}
if managedSubcommands[args[0]] { if managedSubcommands[args[0]] {
if err := rootCmd().Execute(); err != nil { if err := rootCmd().Execute(); err != nil {
var exit *commandExit
if errors.As(err, &exit) {
os.Exit(exit.code)
}
os.Exit(1) os.Exit(1)
} }
return return
@@ -197,25 +221,86 @@ func prependArgs(extra, args []string, dests []int) []string {
// resolvedHost is a NetBox host with the address to connect to. // resolvedHost is a NetBox host with the address to connect to.
type resolvedHost struct { type resolvedHost struct {
Name string // cache/selector name, may carry an instance prefix Origin string
Kind string Resolver string
IP string CachedAt time.Time
Tags []string Name string // cache/selector name, may carry an instance prefix
Kind string
IP string
Tags []string
ID int // NetBox ID; 0 for static hosts and old cache entries
Status string
Site config.Ref
Role config.Ref
Platform config.Ref
Tenant config.Ref
Location []config.Ref
Rack string
Position string
// PreviousIP is the cached address a live lookup replaced, if it differs.
PreviousIP string
}
// hostFromEntry converts a cache entry into a resolved host.
func hostFromEntry(entry cache.Entry, origin string) resolvedHost {
return resolvedHost{
Name: entry.Name, Kind: entry.Kind, IP: entry.IP, Tags: entry.Tags, Origin: origin, Resolver: entry.Resolver, CachedAt: entry.CachedAt,
ID: entry.ID, Status: entry.Status, Site: cache.RefOf(entry.Site), Role: cache.RefOf(entry.Role), Platform: cache.RefOf(entry.Platform), Tenant: cache.RefOf(entry.Tenant),
Location: entry.Location, Rack: entry.Rack, Position: entry.Position,
}
}
// LocationPath renders site › locations › rack › U position.
func (h resolvedHost) LocationPath() string {
return config.LocationPath(h.Site, h.Location, h.Rack, h.Position)
}
// cacheEntry records a NetBox host and its resolved address in the cache.
func cacheEntry(target netbox.HostEntry, ip, strategy string) cache.Entry {
return cache.Entry{
Name: target.Target(), IP: ip, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster, Resolver: strategy,
ID: target.ID, Status: target.Status, Site: cache.RefPtr(target.Site), Role: cache.RefPtr(target.Role), Platform: cache.RefPtr(target.Platform), Tenant: cache.RefPtr(target.Tenant),
Location: target.Location, Rack: target.Rack, Position: target.Position,
}
}
// upsertResolved caches a live result and reports the address it replaced.
func upsertResolved(c *cache.Cache, entry cache.Entry) (previous string) {
if old, _ := c.Get(entry.Name); old.Name != "" && !old.Static && old.IP != "" && old.IP != entry.IP {
previous = old.IP
}
c.Upsert(entry)
return previous
} }
// resolveTarget finds host in the cache (also by shortcut) or NetBox and // resolveTarget finds host in the cache (also by shortcut) or NetBox and
// resolves its address. It exits on failure. // resolves its address. It exits on failure.
func resolveTarget(cfg *config.Config, host string) resolvedHost { func resolveTarget(cfg *config.Config, host string) resolvedHost {
result, err := resolveTargetE(cfg, host, true)
if err != nil {
fatalf("%v", err)
}
return result
}
func resolveTargetE(cfg *config.Config, host string, record bool) (resolvedHost, error) {
c := newCache(cfg) c := newCache(cfg)
_ = c.Load() _ = c.Load()
maybeBackgroundRefresh(cfg, c) if record {
maybeBackgroundRefresh(cfg, c)
}
source, _ := netbox.SplitTarget(host) source, _ := netbox.SplitTarget(host)
useCache := len(cfg.NetBoxes) == 0 || source != "" useCache := len(cfg.NetBoxes) == 0 || source != ""
used := func(entry cache.Entry) resolvedHost { used := func(entry cache.Entry) resolvedHost {
c.MarkUsed(entry.Name) if record {
_ = c.Save() c.MarkUsed(entry.Name)
return resolvedHost{Name: entry.Name, Kind: entry.Kind, IP: entry.IP, Tags: entry.Tags} _ = c.Save()
}
origin := "cache"
if entry.Static {
origin = "static"
}
return hostFromEntry(entry, origin)
} }
// Static hosts from the config win and need no NetBox. // Static hosts from the config win and need no NetBox.
@@ -226,16 +311,16 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
} }
entry, found, err := c.GetStatic(host, normalize) entry, found, err := c.GetStatic(host, normalize)
if err != nil { if err != nil {
fatalf("%v", err) return resolvedHost{}, err
} }
if found { if found {
return used(entry) return used(entry), nil
} }
} }
// Cache hit with a fresh TTL — connect directly without querying NetBox. // Cache hit with a fresh TTL — connect directly without querying NetBox.
if entry, fresh := c.Get(host); fresh && useCache { if entry, fresh := c.Get(host); fresh && useCache {
return used(entry) return used(entry), nil
} }
// Shortcut cache lookup: scan entries whose normalized name matches the input. // Shortcut cache lookup: scan entries whose normalized name matches the input.
@@ -246,11 +331,11 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
normalize := normalizeTarget(cfg.Shortcuts, source != "") normalize := normalizeTarget(cfg.Shortcuts, source != "")
entry, found, fresh, err := c.GetByShortcut(lookupHost, normalize) entry, found, fresh, err := c.GetByShortcut(lookupHost, normalize)
if err != nil { if err != nil {
fatalf("%v", err) return resolvedHost{}, err
} }
if found { if found {
if fresh { if fresh {
return used(entry) return used(entry), nil
} }
// Stale shortcut match — use canonical name for NetBox re-fetch. // Stale shortcut match — use canonical name for NetBox re-fetch.
lookupHost = entry.Name lookupHost = entry.Name
@@ -258,7 +343,7 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
} }
if !cfg.HasNetBox() { if !cfg.HasNetBox() {
fatalf("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)", host)
} }
nbClient := newNetBoxClient(cfg) nbClient := newNetBoxClient(cfg)
@@ -269,33 +354,36 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
if errors.Is(err, netbox.ErrHostNotFound) && !useCache && shortcutsEnabled { if errors.Is(err, netbox.ErrHostNotFound) && !useCache && shortcutsEnabled {
entry, found, _, cacheErr := c.GetByShortcut(host, normalizeTarget(cfg.Shortcuts, false)) entry, found, _, cacheErr := c.GetByShortcut(host, normalizeTarget(cfg.Shortcuts, false))
if cacheErr != nil { if cacheErr != nil {
fatalf("%v", cacheErr) return resolvedHost{}, cacheErr
} }
if found { if found {
target, err = findSSHHost(ctx, nbClient, entry.Name, cfg.Shortcuts.Domains) target, err = findSSHHost(ctx, nbClient, entry.Name, cfg.Shortcuts.Domains)
} }
} }
if err != nil { if err != nil {
fatalf("NetBox: %v", err) return resolvedHost{}, fmt.Errorf("NetBox: %w", err)
} }
if cached, fresh := c.Get(target.Target()); fresh && cached.Kind == target.Kind { if cached, fresh := c.Get(target.Target()); fresh && cached.Kind == target.Kind {
return used(cached) return used(cached), nil
} }
chain, err := resolver.New(cfg.Resolver) chain, err := resolver.New(cfg.Resolver)
if err != nil { if err != nil {
fatalf("resolver: %v", err) return resolvedHost{}, err
} }
ip, err := chain.Resolve(ctx, &target, nbClient) ip, strategy, err := chain.ResolveWithStrategy(ctx, &target, nbClient)
if err != nil { if err != nil {
fatalf("IP resolution for %q: %v", host, err) return resolvedHost{}, fmt.Errorf("IP resolution for %q: %w", host, err)
} }
entry := cache.Entry{Name: target.Target(), IP: ip, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster} entry := cacheEntry(target, ip, strategy)
c.Upsert(entry) previous := upsertResolved(c, entry)
return used(entry) result := used(entry)
result.Origin = "live"
result.PreviousIP = previous
return result, nil
} }
// findSSHHost uses the paginated, ambiguity-checking lookup for connection // findSSHHost uses the paginated, ambiguity-checking lookup for connection
@@ -320,6 +408,9 @@ func findSSHHost(ctx context.Context, client *netbox.Client, name string, domain
// connectHost applies the SSH options configured for the host and execs the client. // connectHost applies the SSH options configured for the host and execs the client.
func connectHost(cfg *config.Config, client internalssh.Client, flags internalssh.WrapperFlags, host resolvedHost, dests []int, args []string) { func connectHost(cfg *config.Config, client internalssh.Client, flags internalssh.WrapperFlags, host resolvedHost, dests []int, args []string) {
if !internalssh.ValidAddress(host.IP) {
fatalf("refusing address %q for %s: not an IP address or hostname (check NetBox, or run netssh cache clear)", host.IP, host.Name)
}
opts := hostOptions(cfg, host) opts := hostOptions(cfg, host)
if len(flags.Forwards) > 0 { if len(flags.Forwards) > 0 {
forwardArgs, err := internalssh.ForwardArgs(flags.Forwards, opts.Forwards) forwardArgs, err := internalssh.ForwardArgs(flags.Forwards, opts.Forwards)
@@ -335,14 +426,47 @@ func connectHost(cfg *config.Config, client internalssh.Client, flags internalss
} }
fatalf("name a forward or a spec such as 8080:localhost:80; forwards for %s: %s", host.Name, available) fatalf("name a forward or a spec such as 8080:localhost:80; forwards for %s: %s", host.Name, available)
} }
if flags.DryRun {
if cfg.SSH.WarnsStatus(host.Status) {
fmt.Fprintf(os.Stderr, "# warning: %s has NetBox status %q\n", host.Name, host.Status)
}
} else {
if err := confirmStatus(cfg, host, flags.Force); err != nil {
fatalf("%v", err)
}
port := connectPort(client, args, dests)
host = applyFallback(cfg, host, opts, flags, port)
if host.PreviousIP != "" {
offerKnownHostsCleanup(opts, host, port)
}
}
if err := runPreConnect(opts.PreConnectCommand(), host, client.Name, flags.DryRun); err != nil {
fatalf("%v", err)
}
_, name := netbox.SplitTarget(host.Name) _, name := netbox.SplitTarget(host.Name)
execClient(client, client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags), flags) result := client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags)
post := config.HookCommand(opts.PostDisconnect)
if flags.DryRun {
if post != "" {
fmt.Fprintf(os.Stderr, "# post_disconnect (skipped in --dry-run): %s\n", post)
}
}
if !flags.DryRun && (post != "" || cfg.Activity.Enabled) {
if result.Notice != "" {
fmt.Fprintln(os.Stderr, result.Notice)
}
code := supervise(cfg, host, client.Name, append([]string{client.Name}, result.Args...), post, 0, false, os.Stdin, os.Stdout, os.Stderr)
if code != 0 {
os.Exit(code)
}
return
}
execClient(client, result, flags)
} }
// hostOptions merges the global, instance, and rule SSH options for host. // hostOptions merges the global, instance, and rule SSH options for host.
func hostOptions(cfg *config.Config, host resolvedHost) config.SSHOptions { func hostOptions(cfg *config.Config, host resolvedHost) config.SSHOptions {
instance, name := netbox.SplitTarget(host.Name) return cfg.SSHOptionsFor(commandHost(host))
return cfg.SSHOptionsFor(config.SSHHost{Instance: instance, Name: name, Kind: host.Kind, Tags: host.Tags})
} }
// execClient replaces the process with the client, or prints the command for --dry-run. // execClient replaces the process with the client, or prints the command for --dry-run.
@@ -373,10 +497,65 @@ func runTUI() {
} }
m := tui.New(nbClient, c, cfg.SSH.DefaultUser, cfg.SSH.DefaultPort) m := tui.New(nbClient, c, cfg.SSH.DefaultUser, cfg.SSH.DefaultPort)
m.SetHostLabel(cfg.HostLabel)
m.SetHistoryLimit(cfg.TUI.HistoryLimit)
state, stateErr := activity.Read()
if stateErr != nil {
fmt.Fprintf(os.Stderr, "favorites: %v\n", stateErr)
}
m.SetPreferences(state.Favorites, state.Pinned, func(favorites, pinned map[string]bool) error {
err := activity.Update(func(s *activity.State) {
merge := func(dst, previous, next map[string]bool) {
for name, value := range next {
if previous[name] != value {
if value {
dst[name] = true
} else {
delete(dst, name)
}
}
}
for name, value := range previous {
if value && !next[name] {
delete(dst, name)
}
}
}
merge(s.Favorites, state.Favorites, favorites)
merge(s.Pinned, state.Pinned, pinned)
})
if err == nil {
state.Favorites = favorites
state.Pinned = pinned
}
return err
})
known := func(name, kind string, tags []string) resolvedHost {
if e, _ := c.Get(name); e.Name != "" && e.Kind == kind {
return hostFromEntry(e, "cache")
}
return resolvedHost{Name: name, Kind: kind, Tags: tags}
}
m.SetCommands(func(name, kind string, tags []string) []string {
var names []string
h := commandHost(known(name, kind, tags))
for name, c := range cfg.Commands {
if c.Allowed(h) {
names = append(names, name)
}
}
sort.Strings(names)
return names
})
if cfg.Shortcuts.Show {
aliases := shortcutAliases(c.All(), *cfg)
m.SetAliases(func(target string) string { return aliases[strings.ToLower(target)] })
}
m.SetNotes(notes.New(cfg.NetBox.URL, nbClient)) m.SetNotes(notes.New(cfg.NetBox.URL, nbClient))
m.SetForwards(func(name, kind string, tags []string) []string { m.SetForwards(func(name, kind string, tags []string) []string {
return forwardNames(hostOptions(cfg, resolvedHost{Name: name, Kind: kind, Tags: tags})) return forwardNames(hostOptions(cfg, known(name, kind, tags)))
}) })
configureTUIExtras(m, cfg, nbClient, known)
p := tea.NewProgram(m) p := tea.NewProgram(m)
final, err := p.Run() final, err := p.Run()
if err != nil { if err != nil {
@@ -391,6 +570,22 @@ func runTUI() {
if host == nil { if host == nil {
return return
} }
if host.Command != "" {
args := []string{"run", host.Command, "--", host.Name}
if len(host.Targets) > 0 {
args = append([]string{"batch", host.Command}, host.Targets...)
}
root := rootCmd()
root.SetArgs(args)
if err := root.Execute(); err != nil {
var exit *commandExit
if errors.As(err, &exit) {
os.Exit(exit.code)
}
fatalf("%v", err)
}
return
}
if host.Action == tui.ActionMulti { if host.Action == tui.ActionMulti {
if err := runMulti(cfg, host.Targets, multiFlags{}); err != nil { if err := runMulti(cfg, host.Targets, multiFlags{}); err != nil {
fatalf("%v", err) fatalf("%v", err)
@@ -399,10 +594,9 @@ func runTUI() {
} }
// Revalidate stale or live TUI results through the configured resolver chain. // Revalidate stale or live TUI results through the configured resolver chain.
var tags []string var resolved resolvedHost
if cached, fresh := c.Get(host.Name); fresh && cached.Kind == host.Kind { if cached, fresh := c.Get(host.Name); fresh && cached.Kind == host.Kind {
host.IP = cached.IP resolved = hostFromEntry(cached, "cache")
tags = cached.Tags
} else { } else {
if nbClient == nil { if nbClient == nil {
fatalf("cannot resolve %q: NetBox is not configured", host.Name) fatalf("cannot resolve %q: NetBox is not configured", host.Name)
@@ -417,20 +611,24 @@ func runTUI() {
if err != nil { if err != nil {
fatalf("resolver: %v", err) fatalf("resolver: %v", err)
} }
host.IP, err = chain.Resolve(ctx, &target, nbClient) var strategy string
host.IP, strategy, err = chain.ResolveWithStrategy(ctx, &target, nbClient)
if err != nil { if err != nil {
fatalf("IP resolution: %v", err) fatalf("IP resolution: %v", err)
} }
c.Upsert(cache.Entry{Name: target.Target(), IP: host.IP, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster}) entry := cacheEntry(target, host.IP, strategy)
tags = target.Tags previous := upsertResolved(c, entry)
resolved = hostFromEntry(entry, "live")
resolved.PreviousIP = previous
} }
host.IP = resolved.IP
fmt.Fprintf(os.Stderr, "Connecting to %s (%s)…\n", host.Name, host.IP) fmt.Fprintf(os.Stderr, "Connecting to %s (%s)…\n", host.Name, host.IP)
c.MarkUsed(host.Name) c.MarkUsed(host.Name)
_ = c.Save() _ = c.Save()
client, flags, args := tuiCommand(cfg, host) client, flags, args := tuiCommand(cfg, host)
connectHost(cfg, client, flags, resolvedHost{Name: host.Name, Kind: host.Kind, IP: host.IP, Tags: tags}, []int{len(args) - 1}, args) connectHost(cfg, client, flags, resolved, []int{len(args) - 1}, args)
} }
// tuiCommand builds the client and arguments for the action chosen in the TUI. // tuiCommand builds the client and arguments for the action chosen in the TUI.
@@ -507,7 +705,8 @@ func rootCmd() *cobra.Command {
}, },
} }
root.AddCommand(notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd()) 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())
// cobra builds the "completion" command lazily; force init so we can extend it. // cobra builds the "completion" command lazily; force init so we can extend it.
root.InitDefaultCompletionCmd() root.InitDefaultCompletionCmd()
@@ -655,7 +854,8 @@ func cacheCmd() *cobra.Command {
} }
func cacheListCmd() *cobra.Command { func cacheListCmd() *cobra.Command {
return &cobra.Command{ var showAliases bool
cmd := &cobra.Command{
Use: "list", Use: "list",
Short: "Show all cached entries", Short: "Show all cached entries",
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
@@ -671,13 +871,31 @@ func cacheListCmd() *cobra.Command {
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name }) sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0) w := tabwriter.NewWriter(os.Stdout, 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "NAME\tIP\tKIND\tCACHED AT") if !showAliases && !cfg.Shortcuts.Show {
fmt.Fprintln(w, "NAME\tIP\tKIND\tCACHED AT")
for _, e := range entries {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", e.Name, e.IP, e.Kind, e.CachedAt.Format(time.RFC3339))
}
return w.Flush()
}
aliases := shortcutAliases(entries, *cfg)
fmt.Fprintln(w, "NAME\tALIAS\tIP\tKIND\tCACHED AT")
for _, e := range entries { for _, e := range entries {
fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", e.Name, e.IP, e.Kind, e.CachedAt.Format(time.RFC3339)) fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", e.Name, orDash(aliases[strings.ToLower(e.Name)]), e.IP, e.Kind, e.CachedAt.Format(time.RFC3339))
} }
return w.Flush() return w.Flush()
}, },
} }
cmd.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
return cmd
}
// orDash keeps empty table cells visible.
func orDash(s string) string {
if s == "" {
return "-"
}
return s
} }
func cacheClearCmd() *cobra.Command { func cacheClearCmd() *cobra.Command {
@@ -739,6 +957,7 @@ func cacheRefreshCmd() *cobra.Command {
return fmt.Errorf("resolver: %w", err) return fmt.Errorf("resolver: %w", err)
} }
written := 0 written := 0
var changed []string
nameCounts := make(map[string]int) nameCounts := make(map[string]int)
for _, e := range entries { for _, e := range entries {
nameCounts[strings.ToLower(e.Target())]++ nameCounts[strings.ToLower(e.Target())]++
@@ -751,7 +970,7 @@ func cacheRefreshCmd() *cobra.Command {
continue continue
} }
ip, err := chain.Resolve(ctx, e, nbClient) ip, strategy, err := chain.ResolveWithStrategy(ctx, e, nbClient)
if err != nil { if err != nil {
// Do not turn a failed configured strategy into a fresh // Do not turn a failed configured strategy into a fresh
// primary-IP cache hit that bypasses the resolver. // primary-IP cache hit that bypasses the resolver.
@@ -762,7 +981,9 @@ func cacheRefreshCmd() *cobra.Command {
fmt.Fprintf(os.Stderr, "warning: skipping %s: %v\n", e.Name, err) fmt.Fprintf(os.Stderr, "warning: skipping %s: %v\n", e.Name, err)
continue continue
} }
c.Upsert(cache.Entry{Name: e.Target(), IP: ip, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster}) if previous := upsertResolved(c, cacheEntry(*e, ip, strategy)); previous != "" {
changed = append(changed, fmt.Sprintf("%s: %s → %s", e.Target(), previous, ip))
}
written++ written++
} }
@@ -780,6 +1001,14 @@ func cacheRefreshCmd() *cobra.Command {
} }
} }
fmt.Printf("%d entries written to cache.\n", written) fmt.Printf("%d entries written to cache.\n", written)
if len(changed) > 0 {
sort.Strings(changed)
fmt.Printf("%d hosts changed their address:\n", len(changed))
for _, line := range changed {
fmt.Printf(" %s\n", line)
}
fmt.Println("Remove outdated host keys with: netssh known-hosts reset HOST")
}
return nil return nil
}, },
} }
@@ -1000,6 +1229,9 @@ func hookUninstallCmd() *cobra.Command {
return cmd return cmd
} }
// refreshRetryInterval is the pause between background refresh attempts.
const refreshRetryInterval = 5 * time.Minute
// maybeBackgroundRefresh starts a background `netssh cache refresh` if the cache // maybeBackgroundRefresh starts a background `netssh cache refresh` if the cache
// has not been fully refreshed within the last 24 hours. // has not been fully refreshed within the last 24 hours.
func maybeBackgroundRefresh(cfg *config.Config, c *cache.Cache) { func maybeBackgroundRefresh(cfg *config.Config, c *cache.Cache) {
@@ -1007,7 +1239,9 @@ func maybeBackgroundRefresh(cfg *config.Config, c *cache.Cache) {
if !cfg.HasNetBox() || os.Getenv("NETSSH_NO_REFRESH") != "" { if !cfg.HasNetBox() || os.Getenv("NETSSH_NO_REFRESH") != "" {
return return
} }
if !c.NeedsRefresh(24 * time.Hour) { // While NetBox is unreachable the cache stays stale; without the retry
// interval every command and every new shell would start another refresh.
if !c.ClaimRefresh(24*time.Hour, refreshRetryInterval) {
return return
} }
self, err := os.Executable() self, err := os.Executable()
+201
View File
@@ -0,0 +1,201 @@
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"sort"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/resolver"
"github.com/spf13/cobra"
)
func doctorCmd() *cobra.Command {
var online bool
cmd := &cobra.Command{Use: "doctor", Short: "Check configuration, programs, cache and optional NetBox connectivity", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
failed := false
report := func(label string, err error) {
if err != nil {
failed = true
fmt.Fprintf(cmd.OutOrStdout(), "FAIL %s: %v\n", label, err)
} else {
fmt.Fprintf(cmd.OutOrStdout(), "OK %s\n", label)
}
}
report("configuration", nil)
_, err = resolver.New(cfg.Resolver)
report("resolver", err)
programs := map[string]bool{"ssh": true, "sftp": true, "scp": true}
for name, c := range cfg.Commands {
programs[c.Args[0]] = true
if len(c.Args) > 1 && !strings.HasPrefix(c.Args[1], "-") {
switch c.Args[0] {
case "bash", "sh", "python", "python3":
f, err := os.Open(c.Args[1])
if err == nil {
f.Close()
}
report("script "+name, err)
}
}
}
var names []string
for p := range programs {
names = append(names, p)
}
sort.Strings(names)
for _, p := range names {
_, err := exec.LookPath(p)
report("program "+p, err)
}
report("cache", newCache(cfg).Load())
for _, instance := range instanceConfigs(cfg) {
if config.IsKeyringToken(instance.Token) {
_, err := resolveToken(*instance)
report("keyring token "+instance.KeyringAccount(), err)
}
}
if online {
sources := cfg.NetBoxes
if len(sources) == 0 && cfg.NetBox.URL != "" {
sources = []config.NetBoxConfig{cfg.NetBox}
}
for _, s := range sources {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
token, version := clientToken(s)
_, err := netbox.NewClient(s.URL, token, version).Search(ctx, "", netbox.SearchOptions{})
cancel()
report("NetBox "+s.Name, err)
}
}
if failed {
return fmt.Errorf("doctor found problems")
}
return nil
}}
cmd.Flags().BoolVar(&online, "online", false, "Also query every NetBox instance")
return cmd
}
func explainCmd() *cobra.Command {
return &cobra.Command{Use: "explain HOST", Short: "Explain actual host resolution and effective SSH settings without connecting", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
h, err := resolveTargetE(cfg, args[0], false)
if err != nil {
return err
}
selectors := commandHost(h)
user, port := hostDefaults(cfg, h)
opts := hostOptions(cfg, h)
var rules []int
for i, r := range cfg.SSH.Rules {
if r.Match.Matches(selectors) {
rules = append(rules, i+1)
}
}
strategy := h.Resolver
if strategy == "" {
if h.Origin == "static" {
strategy = "static address"
} else {
strategy = "not recorded in this cache entry"
}
}
return json.NewEncoder(cmd.OutOrStdout()).Encode(map[string]any{
"target": h.Name, "instance": selectors.Instance, "address": h.IP, "source": h.Origin, "cached_at": h.CachedAt,
"status": h.Status, "site": h.Site.Name, "role": h.Role.Name, "platform": h.Platform.Name, "tenant": h.Tenant.Name, "netbox_id": h.ID, "location": h.LocationPath(),
"resolver_order": cfg.Resolver.Strategies, "resolver_used": strategy, "matching_rules": rules, "user": user, "port": port, "ssh": opts,
})
}}
}
func favoritesCmd() *cobra.Command {
cmd := &cobra.Command{Use: "favorites", Short: "List or change favorite and pinned hosts", RunE: func(cmd *cobra.Command, _ []string) error {
s, err := activity.Read()
if err != nil {
return err
}
var names []string
for n := range s.Favorites {
if s.Favorites[n] {
names = append(names, n)
}
}
sort.Strings(names)
for _, n := range names {
marker := "favorite"
if s.Pinned[n] {
marker = "pinned"
}
fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\n", n, marker)
}
return nil
}}
for _, action := range []string{"add", "remove", "pin", "unpin"} {
cmd.AddCommand(&cobra.Command{Use: action + " HOST", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
target := args[0]
if action == "add" || action == "pin" {
cfg, err := config.Load()
if err != nil {
return err
}
h, err := resolveTargetE(cfg, target, false)
if err != nil {
return err
}
target = h.Name
}
return activity.Update(func(s *activity.State) {
switch action {
case "add":
s.Favorites[target] = true
case "pin":
s.Favorites[target] = true
s.Pinned[target] = true
case "unpin":
delete(s.Pinned, target)
case "remove":
delete(s.Favorites, target)
delete(s.Pinned, target)
}
})
}})
}
return cmd
}
func historyCmd() *cobra.Command {
cmd := &cobra.Command{Use: "history", Short: "Show optional local action history", RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
if err := activity.Update(func(s *activity.State) { activity.Prune(s, cfg.Activity) }); err != nil {
return err
}
s, err := activity.Read()
if err != nil {
return err
}
for i := len(s.Records) - 1; i >= 0; i-- {
r := s.Records[i]
fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\texit=%d\t%s\n", r.Time.Format(time.RFC3339), r.Host, r.Command, r.Code, r.Duration.Round(time.Millisecond))
}
return nil
}}
cmd.AddCommand(&cobra.Command{Use: "clear", Short: "Delete recorded actions, preserving favorites", Args: cobra.NoArgs, RunE: func(_ *cobra.Command, _ []string) error {
return activity.Update(func(s *activity.State) { s.Records = nil })
}})
return cmd
}
+258
View File
@@ -0,0 +1,258 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func writeOperationsConfig(t *testing.T, extra string) {
t.Helper()
prepareTransferTest(t)
data := `hosts:
- name: router
address: 192.0.2.1
tags: [router]
- name: fail
address: 192.0.2.2
- name: okay
address: 192.0.2.3
resolver:
strategies: [primary_ip]
` + extra
if err := os.WriteFile(config.Path(), []byte(data), 0600); err != nil {
t.Fatal(err)
}
}
func TestPostHooksFiltersAndConfirmation(t *testing.T) {
dir := t.TempDir()
marker := filepath.Join(dir, "post")
writeOperationsConfig(t, fmt.Sprintf(`
commands:
success:
args: [sh, -c, "exit 0", "{host}"]
post_run: 'printf "%%s:%%s" "$NETSSH_HOST" "$NETSSH_EXIT_CODE" > %s'
failure:
args: [sh, -c, "exit 7", "{host}"]
post_run: 'printf "%%s" "$NETSSH_EXIT_CODE" > %s; exit 9'
postfail:
args: [sh, -c, "exit 0", "{host}"]
post_run: exit 9
protected:
args: [sh, -c, "exit 0", "{host}"]
confirm: true
match: {tag: router, kind: static, name: "rou*"}
timeout:
args: [sh, -c, "sleep 20", "{host}"]
timeout: 50ms
activity:
enabled: true
retention_days: 30
max_entries: 50
`, marker, marker))
if out, err := runNetssh(t, "run", "--dry-run", "success", "router"); err != nil {
t.Fatalf("%s %v", out, err)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatal("dry-run executed post hook")
}
if out, err := runNetssh(t, "run", "success", "router"); err != nil {
t.Fatalf("%s %v", out, err)
}
data, _ := os.ReadFile(marker)
if string(data) != "router:0" {
t.Fatal(string(data))
}
for _, tc := range []struct {
name string
code int
}{{"failure", 7}, {"postfail", 9}, {"timeout", 124}} {
_, err := runNetssh(t, "run", tc.name, "router")
exit, ok := err.(*exec.ExitError)
if !ok || exit.ExitCode() != tc.code {
t.Fatalf("%s: %v", tc.name, err)
}
}
data, _ = os.ReadFile(marker)
if string(data) != "7" {
t.Fatal(string(data))
}
if out, err := runNetssh(t, "run", "protected", "router"); err == nil || !strings.Contains(out, "--yes") {
t.Fatalf("%q %v", out, err)
}
if out, err := runNetssh(t, "run", "--yes", "protected", "router"); err != nil {
t.Fatalf("%q %v", out, err)
}
if out, err := runNetssh(t, "run", "--yes", "protected", "okay"); err == nil || !strings.Contains(out, "not allowed") {
t.Fatalf("%q %v", out, err)
}
state, err := activity.Read()
if err != nil || len(state.Records) != 5 {
t.Fatalf("%+v %v", state, err)
}
}
func TestSSHPostDisconnect(t *testing.T) {
dir := t.TempDir()
marker := filepath.Join(dir, "after")
writeOperationsConfig(t, fmt.Sprintf("ssh:\n post_disconnect: 'printf \"%%s\" \"$NETSSH_EXIT_CODE\" > %s'\n", marker))
if err := os.WriteFile(filepath.Join(dir, "ssh"), []byte("#!/bin/sh\nexit 6\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
_, err := runNetssh(t, "router")
exit, ok := err.(*exec.ExitError)
if !ok || exit.ExitCode() != 6 {
t.Fatal(err)
}
data, _ := os.ReadFile(marker)
if string(data) != "6" {
t.Fatalf("post: %s", data)
}
}
func TestExplainAndFavorites(t *testing.T) {
writeOperationsConfig(t, "tui:\n history_limit: 25\nssh:\n rules:\n - match: {tag: router}\n post_disconnect: echo done\n")
out, err := runNetssh(t, "explain", "router")
if err != nil {
t.Fatalf("%s %v", out, err)
}
var result map[string]any
if err := json.Unmarshal([]byte(out), &result); err != nil {
t.Fatal(err)
}
if result["source"] != "static" || result["address"] != "192.0.2.1" {
t.Fatal(result)
}
for _, args := range [][]string{{"favorites", "pin", "router"}, {"favorites", "add", "okay"}} {
if out, err := runNetssh(t, args...); err != nil {
t.Fatalf("%s %v", out, err)
}
}
state, err := activity.Read()
if err != nil || !state.Pinned["router"] || !state.Favorites["okay"] {
t.Fatalf("%+v %v", state, err)
}
if out, err := runNetssh(t, "favorites", "remove", "router"); err != nil {
t.Fatalf("%s %v", out, err)
}
state, _ = activity.Read()
if state.Pinned["router"] || state.Favorites["router"] {
t.Fatal(state)
}
}
func TestPortableConfigOmitsAllExecutableSecrets(t *testing.T) {
c := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://user:URLSECRET@netbox.example", Token: "TOKEN", SSH: config.SSHOptions{PreConnect: "HOOKSECRET"}}},
SSH: config.SSHConfig{SSHOptions: config.SSHOptions{Options: map[string]string{"ProxyCommand": "OPTIONSECRET"}, PostDisconnect: "POSTSECRET"}},
Commands: map[string]config.HostCommand{"check": {Args: []string{"echo", "COMMANDSECRET", "{host}"}}},
Hosts: []config.StaticHost{{Name: "router", Address: "192.0.2.1", SSH: config.SSHOptions{PreConnect: "STATICSECRET"}}},
TUI: config.TUIConfig{HistoryLimit: 25},
}
data, err := json.Marshal(portableConfig(c))
if err != nil {
t.Fatal(err)
}
for _, secret := range []string{"URLSECRET", "TOKEN", "HOOKSECRET", "OPTIONSECRET", "POSTSECRET", "COMMANDSECRET", "STATICSECRET"} {
if bytes.Contains(data, []byte(secret)) {
t.Fatalf("export leaked %s", secret)
}
}
parsed, err := decodePortable(data)
if err != nil {
t.Fatal(err)
}
if parsed.TUI.HistoryLimit != 25 || len(parsed.NetBoxes) != 1 || parsed.NetBoxes[0].URL != "https://netbox.example" {
t.Fatalf("%+v", parsed)
}
hostile := []byte("netbox:\n url: https://netbox.example\n token: bad\nssh:\n pre_connect: touch /tmp/never\ncommands:\n check:\n args: [sh, -c, evil]\n")
parsed, err = decodePortable(hostile)
if err != nil || parsed.NetBox.Token != "" || parsed.SSH.PreConnect != "" || len(parsed.Commands) != 0 {
t.Fatalf("%+v %v", parsed, err)
}
}
func TestBatchRetryFailedOnly(t *testing.T) {
bin := filepath.Join(t.TempDir(), "netssh")
build := exec.Command("go", "build", "-o", bin, ".")
if out, err := build.CombinedOutput(); err != nil {
t.Fatalf("build: %s %v", out, err)
}
old := batchExecutable
batchExecutable = func() (string, error) { return bin, nil }
t.Cleanup(func() { batchExecutable = old })
dir := t.TempDir()
script := filepath.Join(dir, "check.sh")
ready := filepath.Join(dir, "ready")
if err := os.WriteFile(script, []byte(fmt.Sprintf("#!/bin/sh\nif [ \"$1\" = fail ] && [ ! -f %q ]; then exit 3; fi\nprintf 'ran %%s\\n' \"$1\"\n", ready)), 0700); err != nil {
t.Fatal(err)
}
writeOperationsConfig(t, fmt.Sprintf("commands:\n check:\n args: [%q, \"{host}\"]\n", script))
run := func(args ...string) (string, error) {
cmd := batchCmd()
cmd.SetArgs(args)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
err := cmd.Execute()
return out.String(), err
}
out, err := run("--parallel", "2", "check", "router", "fail", "okay")
if err == nil || !strings.Contains(out, "2 succeeded, 1 failed") {
t.Fatalf("%s %v", out, err)
}
data, _ := os.ReadFile(batchPath())
var retry batchRetry
if err := json.Unmarshal(data, &retry); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(retry.Hosts, []string{"fail"}) {
t.Fatalf("%+v", retry)
}
if err := os.WriteFile(ready, nil, 0600); err != nil {
t.Fatal(err)
}
out, err = run("--retry-failed")
if err != nil || !strings.Contains(out, "1 succeeded, 0 failed") || strings.Contains(out, "ran router") {
t.Fatalf("%s %v", out, err)
}
}
func TestImportPreservesOnlyMatchingCredentials(t *testing.T) {
writeOperationsConfig(t, "")
original := []byte("netboxes:\n - name: prod\n url: https://prod.example\n token: LOCALPROD\n - name: lab\n url: https://lab.example\n token: LOCALLAB\ncommands:\n local:\n args: [echo, \"{host}\"]\n")
if err := os.WriteFile(config.Path(), original, 0600); err != nil {
t.Fatal(err)
}
shared := filepath.Join(t.TempDir(), "shared.yaml")
if err := os.WriteFile(shared, []byte("netboxes:\n - name: prod\n url: https://prod.example\n token: UNTRUSTED\n - name: lab\n url: https://other.example\ntui:\n history_limit: 25\nssh:\n pre_connect: evil\n"), 0600); err != nil {
t.Fatal(err)
}
if out, err := runNetssh(t, "config", "import", shared, "--dry-run"); err != nil {
t.Fatalf("%s %v", out, err)
}
after, _ := os.ReadFile(config.Path())
if !bytes.Equal(original, after) {
t.Fatal("preview changed config")
}
if out, err := runNetssh(t, "config", "import", shared, "--yes"); err != nil {
t.Fatalf("%s %v", out, err)
}
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
if cfg.NetBoxes[0].Token != "LOCALPROD" || cfg.NetBoxes[1].Token != "" || cfg.SSH.PreConnect != "" || len(cfg.Commands) != 1 || cfg.TUI.HistoryLimit != 25 {
t.Fatalf("incorrect imported settings: names=%d tui=%d", len(cfg.NetBoxes), cfg.TUI.HistoryLimit)
}
backup, _ := os.ReadFile(config.Path() + ".before-import")
if !bytes.Equal(backup, original) {
t.Fatal("backup differs")
}
}
+164
View File
@@ -0,0 +1,164 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"os"
"strings"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/setup"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// Portable config deliberately omits arbitrary command/hook/SSH option strings:
// secrets may be embedded there, and cannot reliably be detected by key name.
func portableConfig(c config.Config) map[string]any {
cleanURL := func(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return ""
}
u.User = nil
u.RawQuery = ""
u.Fragment = ""
return u.String()
}
sources := []map[string]any{}
for _, s := range c.NetBoxes {
sources = append(sources, map[string]any{"name": s.Name, "url": cleanURL(s.URL), "disable_prefix": s.DisablePrefix})
}
hosts := []map[string]any{}
for _, h := range c.Hosts {
hosts = append(hosts, map[string]any{"name": h.Name, "address": h.Address, "user": h.User, "port": h.Port, "tags": h.Tags})
}
rewrites := []map[string]string{}
for _, r := range c.Shortcuts.Rewrites {
rewrites = append(rewrites, map[string]string{"pattern": r.Pattern, "replace": r.Replace})
}
out := map[string]any{
"hosts": hosts, "groups": c.Groups,
"ssh": map[string]any{"default_user": c.SSH.DefaultUser, "default_port": c.SSH.DefaultPort},
"resolver": map[string]any{"strategies": c.Resolver.Strategies, "management_subnets": c.Resolver.ManagementSubnets, "interface_name": c.Resolver.InterfaceName, "hostname_domain": c.Resolver.HostnameDomain},
"shortcuts": map[string]any{"domains": c.Shortcuts.Domains, "rewrites": rewrites, "strip_hyphens": c.Shortcuts.StripHyphens, "show": c.Shortcuts.Show},
"completion": map[string]any{"max_results": c.Completion.MaxResults},
"tui": map[string]any{"history_limit": c.TUI.HistoryLimit},
}
if len(sources) > 0 {
out["netboxes"] = sources
} else if c.NetBox.URL != "" {
out["netbox"] = map[string]string{"url": cleanURL(c.NetBox.URL)}
}
return out
}
func decodePortable(data []byte) (config.Config, error) {
v := viper.New()
v.SetConfigType("yaml")
v.SetDefault("tui.history_limit", 10)
var c config.Config
if err := v.ReadConfig(bytes.NewReader(data)); err != nil {
return c, err
}
if err := v.Unmarshal(&c); err != nil {
return c, err
}
// Strip executable settings and credentials even from externally edited files.
safe, _ := json.Marshal(portableConfig(c))
v = viper.New()
v.SetConfigType("json")
if err := v.ReadConfig(bytes.NewReader(safe)); err != nil {
return c, err
}
c = config.Config{}
err := v.Unmarshal(&c)
return c, err
}
func configCmd() *cobra.Command {
cmd := &cobra.Command{Use: "config", Short: "Share configuration without credentials or executable settings"}
export := &cobra.Command{Use: "export [FILE]", Short: "Export a secret-free JSON configuration (also valid YAML)", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
data, err := json.MarshalIndent(portableConfig(*cfg), "", " ")
if err != nil {
return err
}
if len(args) == 0 {
fmt.Fprintln(cmd.OutOrStdout(), string(data))
return nil
}
return storage.WriteFile(args[0], append(data, '\n'), 0600)
}}
var yes, dry bool
imp := &cobra.Command{Use: "import FILE", Short: "Import shared host settings; preserve matching local credentials and commands", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
data, err := os.ReadFile(args[0])
if err != nil {
return err
}
incoming, err := decodePortable(data)
if err != nil {
return err
}
current, err := config.Load()
if err != nil {
return err
}
same := func(a, b string) bool { return strings.TrimRight(a, "/") == strings.TrimRight(b, "/") }
for i := range incoming.NetBoxes {
for _, old := range current.NetBoxes {
s := &incoming.NetBoxes[i]
if strings.EqualFold(s.Name, old.Name) && same(s.URL, old.URL) {
s.Token = old.Token
s.TokenVersion = old.TokenVersion
s.SSH = old.SSH
}
}
}
if incoming.NetBox.URL != "" && same(incoming.NetBox.URL, current.NetBox.URL) {
incoming.NetBox.Token = current.NetBox.Token
incoming.NetBox.TokenVersion = current.NetBox.TokenVersion
incoming.NetBox.SSH = current.NetBox.SSH
}
incoming.Commands = current.Commands
incoming.Activity = current.Activity
incoming.Cache = current.Cache
incoming.Multi = current.Multi
incoming.Shell = current.Shell
incoming.SSH.SSHOptions = current.SSH.SSHOptions
incoming.SSH.Rules = current.SSH.Rules
for i := range incoming.Hosts {
for _, old := range current.Hosts {
if incoming.Hosts[i].Name == old.Name && incoming.Hosts[i].Address == old.Address {
incoming.Hosts[i].SSH = old.SSH
}
}
}
for _, validate := range []func() error{incoming.ValidateNetBoxes, incoming.ValidateHosts, incoming.ValidateSSH, incoming.ValidateCommands, incoming.ValidateOperations, incoming.Shortcuts.Validate, incoming.ValidateMulti} {
if err := validate(); err != nil {
return err
}
}
fmt.Fprintf(cmd.OutOrStdout(), "Import: %d named instances, %d static hosts. Local commands and matching credentials are retained.\n", len(incoming.NetBoxes), len(incoming.Hosts))
if dry {
return nil
}
if err := confirmAction("Replace shared configuration settings", yes); err != nil {
return err
}
if existing, err := os.ReadFile(config.Path()); err == nil {
if err := storage.WriteFile(config.Path()+".before-import", existing, 0600); err != nil {
return err
}
}
return setup.Save(incoming)
}}
imp.Flags().BoolVar(&yes, "yes", false, "Approve replacing shared configuration settings")
imp.Flags().BoolVar(&dry, "dry-run", false, "Validate and preview without writing")
cmd.AddCommand(export, imp)
return cmd
}
+54
View File
@@ -0,0 +1,54 @@
package main
import (
"fmt"
"io"
"os"
"os/exec"
"strings"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
// preConnectRunner runs the hook; tests replace it to avoid spawning a shell.
var preConnectRunner = runPreConnectCommand
// preConnectEnv describes the host to the hook through environment variables.
func preConnectEnv(host resolvedHost, clientName string) []string {
instance, name := netbox.SplitTarget(host.Name)
return []string{
"NETSSH_HOST=" + name,
"NETSSH_TARGET=" + host.Name,
"NETSSH_INSTANCE=" + instance,
"NETSSH_IP=" + host.IP,
"NETSSH_KIND=" + host.Kind,
"NETSSH_TAGS=" + strings.Join(host.Tags, ","),
"NETSSH_CLIENT=" + clientName,
}
}
// runPreConnect runs the configured pre_connect hook for host. Its output goes
// to stderr so it never mixes with the output of a remote command or scp.
// A failing hook returns an error and the connection must not be opened.
func runPreConnect(command string, host resolvedHost, clientName string, dryRun bool) error {
if command == "" {
return nil
}
if dryRun {
fmt.Fprintf(os.Stderr, "# pre_connect (skipped in --dry-run): %s\n", command)
return nil
}
if err := preConnectRunner(command, preConnectEnv(host, clientName), os.Stdin, os.Stderr); err != nil {
return fmt.Errorf("pre_connect hook for %s failed: %w", host.Name, err)
}
return nil
}
func runPreConnectCommand(command string, env []string, stdin io.Reader, out io.Writer) error {
cmd := exec.Command("sh", "-c", command)
cmd.Env = append(os.Environ(), env...)
cmd.Stdin = stdin
cmd.Stdout = out
cmd.Stderr = out
return cmd.Run()
}
+112
View File
@@ -0,0 +1,112 @@
package main
import (
"bytes"
"errors"
"io"
"os"
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
internalssh "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/ssh"
)
func TestRunPreConnectPassesHostAndStopsOnFailure(t *testing.T) {
host := resolvedHost{Name: "prod/web01", Kind: "vm", IP: "10.0.0.5", Tags: []string{"dmz", "web"}}
var gotCommand string
var gotEnv []string
fail := false
preConnectRunner = func(command string, env []string, _ io.Reader, _ io.Writer) error {
gotCommand, gotEnv = command, env
if fail {
return errors.New("exit status 1")
}
return nil
}
t.Cleanup(func() { preConnectRunner = runPreConnectCommand })
if err := runPreConnect("vpn-check", host, "sftp", false); err != nil {
t.Fatal(err)
}
want := []string{"NETSSH_HOST=web01", "NETSSH_TARGET=prod/web01", "NETSSH_INSTANCE=prod", "NETSSH_IP=10.0.0.5", "NETSSH_KIND=vm", "NETSSH_TAGS=dmz,web", "NETSSH_CLIENT=sftp"}
if gotCommand != "vpn-check" || !reflect.DeepEqual(gotEnv, want) {
t.Fatalf("got %q %v", gotCommand, gotEnv)
}
fail = true
if err := runPreConnect("vpn-check", host, "ssh", false); err == nil || !strings.Contains(err.Error(), "prod/web01") {
t.Fatalf("failure not reported: %v", err)
}
gotCommand = ""
if err := runPreConnect("vpn-check", host, "ssh", true); err != nil || gotCommand != "" {
t.Fatalf("dry-run ran the hook: %v %q", err, gotCommand)
}
if err := runPreConnect("", host, "ssh", false); err != nil || gotCommand != "" {
t.Fatalf("empty hook ran: %v %q", err, gotCommand)
}
}
func TestRunPreConnectCommandUsesShell(t *testing.T) {
var out bytes.Buffer
err := runPreConnectCommand(`echo "$NETSSH_HOST via $NETSSH_CLIENT"`, []string{"NETSSH_HOST=web01", "NETSSH_CLIENT=ssh"}, strings.NewReader(""), &out)
if err != nil || out.String() != "web01 via ssh\n" {
t.Fatalf("got %q, %v", out.String(), err)
}
if err := runPreConnectCommand("exit 3", nil, strings.NewReader(""), io.Discard); err == nil {
t.Fatal("non-zero exit not reported")
}
}
// --dry-run only prints the ssh command: it must not run the hook, which may
// have side effects (bringing up a VPN, logging).
func TestConnectHostDryRunSkipsPreConnect(t *testing.T) {
ran := 0
preConnectRunner = func(string, []string, io.Reader, io.Writer) error { ran++; return nil }
t.Cleanup(func() { preConnectRunner = runPreConnectCommand })
cfg := &config.Config{SSH: config.SSHConfig{SSHOptions: config.SSHOptions{PreConnect: "hook"}}}
stdout := os.Stdout
r, w, _ := os.Pipe()
os.Stdout = w
connectHost(cfg, internalssh.SSH, internalssh.WrapperFlags{DryRun: true}, resolvedHost{Name: "web01", IP: "10.0.0.1"}, []int{0}, []string{"web01"})
w.Close()
os.Stdout = stdout
printed, _ := io.ReadAll(r)
if ran != 0 || !strings.Contains(string(printed), "10.0.0.1") {
t.Fatalf("dry-run: ran=%d printed=%q", ran, printed)
}
}
func TestShortcutAliasesOnlyWhenShortened(t *testing.T) {
cfg := config.Config{Shell: config.ShellConfig{Alias: "j"}, Shortcuts: fsnRewrite}
entries := []cache.Entry{{Name: "fsn1-bx1.hoster.de"}, {Name: "web01.other.de"}, {Name: "db01.hoster.de"}}
got := shortcutAliases(entries, cfg)
want := map[string]string{"fsn1-bx1.hoster.de": "fsnbx1", "db01.hoster.de": "db01"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("got %v, want %v", got, want)
}
if got := shortcutAliases(entries, config.Config{}); len(got) != 0 {
t.Fatalf("aliases without shortcuts: %v", got)
}
}
func TestHostCompletionsShowShortcutsForMatchingNames(t *testing.T) {
entries := []cache.Entry{{Name: "fsn1-bx1.hoster.de"}, {Name: "fsn1-db1.hoster.de"}}
if got := hostCompletions(entries, "fsn", fsnRewrite); !reflect.DeepEqual(got, []string{"fsn1-bx1.hoster.de", "fsn1-db1.hoster.de"}) {
t.Fatalf("without show: %v", got)
}
show := fsnRewrite
show.Show = true
want := []string{"fsn1-bx1.hoster.de", "fsn1-db1.hoster.de", "fsnbx1", "fsndb1"}
if got := hostCompletions(entries, "fsn", show); !reflect.DeepEqual(got, want) {
t.Fatalf("with show: got %v, want %v", got, want)
}
// A shortcut equal to an offered name is not repeated.
plain := []cache.Entry{{Name: "web01"}}
if got := hostCompletions(plain, "web", show); !reflect.DeepEqual(got, []string{"web01"}) {
t.Fatalf("duplicate: %v", got)
}
}
+106
View File
@@ -0,0 +1,106 @@
package main
import (
"fmt"
"os"
"sort"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"github.com/charmbracelet/x/term"
"github.com/spf13/cobra"
)
// expandHostCommand substitutes each argument once, without shell evaluation.
func expandHostCommand(command config.HostCommand, host resolvedHost, extra []string) []string {
_, name := netbox.SplitTarget(host.Name)
replace := strings.NewReplacer("{host}", name, "{address}", host.IP, "{target}", host.Name)
argv := make([]string, 0, len(command.Args)+len(extra))
for _, arg := range command.Args {
argv = append(argv, replace.Replace(arg))
}
return append(argv, extra...)
}
func runCmd() *cobra.Command {
var dryRun, yes, status bool
cmd := &cobra.Command{
Use: "run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]",
Short: "Run a configured local command for a NetBox or static host",
Args: cobra.MinimumNArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
command, ok := cfg.Commands[args[0]]
if !ok {
return fmt.Errorf("unknown configured command %q", args[0])
}
host, err := resolveTargetE(cfg, args[1], !dryRun)
if err != nil {
return err
}
if !command.Allowed(commandHost(host)) {
return fmt.Errorf("command %q is not allowed for %s", args[0], host.Name)
}
argv := expandHostCommand(command, host, args[2:])
if dryRun {
if post := config.HookCommand(command.PostRun); post != "" {
fmt.Fprintf(cmd.ErrOrStderr(), "# post_run (skipped in --dry-run): %s\n", post)
}
for i, arg := range argv {
if i > 0 {
fmt.Fprint(cmd.OutOrStdout(), " ")
}
fmt.Fprintf(cmd.OutOrStdout(), "%q", arg)
}
fmt.Fprintln(cmd.OutOrStdout())
return nil
}
if command.Confirm {
if err := confirmAction("Run "+args[0]+" on "+host.Name, yes); err != nil {
return err
}
}
timeout, _ := time.ParseDuration(command.Timeout)
code := supervise(cfg, host, args[0], argv, command.PostRun, timeout, status || term.IsTerminal(os.Stderr.Fd()), os.Stdin, cmd.OutOrStdout(), cmd.ErrOrStderr())
if code != 0 {
cmd.SilenceErrors = true
cmd.SilenceUsage = true
return &commandExit{code}
}
return nil
},
ValidArgsFunction: func(cmd *cobra.Command, args []string, prefix string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 {
cfg, err := config.Load()
if err != nil {
return nil, cobra.ShellCompDirectiveError
}
var names []string
for name := range cfg.Commands {
if strings.HasPrefix(name, prefix) {
names = append(names, name)
}
}
sort.Strings(names)
return names, cobra.ShellCompDirectiveNoFileComp
}
if len(args) == 1 {
return completeHosts(prefix), cobra.ShellCompDirectiveNoFileComp
}
return nil, cobra.ShellCompDirectiveNoFileComp
},
}
cmd.Flags().BoolVar(&yes, "yes", false, "Approve an action requiring confirmation")
cmd.Flags().BoolVar(&status, "status", false, "Show elapsed runtime")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the command without running it")
return cmd
}
type commandExit struct{ code int }
func (e *commandExit) Error() string { return fmt.Sprintf("command exited with status %d", e.code) }
+130
View File
@@ -0,0 +1,130 @@
package main
import (
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func TestExpandHostCommand(t *testing.T) {
command := config.HostCommand{Args: []string{"mtr", "--target={address}", "{host}", "{target}", "$(literal)"}}
host := resolvedHost{Name: "office/xzi-groß1", IP: "2001:db8::1"}
got := expandHostCommand(command, host, []string{"--report", "two words"})
want := []string{"mtr", "--target=2001:db8::1", "xzi-groß1", "office/xzi-groß1", "$(literal)", "--report", "two words"}
if !reflect.DeepEqual(got, want) {
t.Fatalf("%q, want %q", got, want)
}
}
func TestRunConfiguredHostCommand(t *testing.T) {
prepareTransferTest(t)
f, err := os.OpenFile(config.Path(), os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
_, err = f.WriteString(`
commands:
trace:
alias_prefix: m
args: [mtr, "{address}", "{host}", "{target}"]
literal:
args: [printf, "%s|%s|%s", "{address}", "{host}", "$(touch should-not-exist)"]
`)
if closeErr := f.Close(); err != nil || closeErr != nil {
t.Fatalf("write config: %v %v", err, closeErr)
}
for _, tc := range []struct {
args []string
want string
}{
{[]string{"run", "--dry-run", "trace", "fsnbx1", "--", "--report"}, `"mtr" "10.0.0.9" "fsn1-bx1.hoster.de" "fsn1-bx1.hoster.de" "--report"`},
{[]string{"run", "--dry-run", "trace", "--", "fsnbx1", "--help"}, `"mtr" "10.0.0.9" "fsn1-bx1.hoster.de" "fsn1-bx1.hoster.de" "--help"`},
{[]string{"run", "literal", "fsnbx1"}, "10.0.0.9|fsn1-bx1.hoster.de|$(touch should-not-exist)"},
} {
out, err := runNetssh(t, tc.args...)
if err != nil || out != tc.want {
t.Fatalf("%v: %q (%v), want %q", tc.args, out, err, tc.want)
}
}
out, err := runNetssh(t, "run", "missing", "fsnbx1")
if err == nil || !strings.Contains(out, "unknown configured command") {
t.Fatalf("%q %v", out, err)
}
}
func TestRunCommandAcceptsResolvedHostname(t *testing.T) {
prepareTransferTest(t)
data := `netbox:
url: http://127.0.0.1:1
token: t
hosts:
- name: router
address: router.example.com
commands:
trace:
args: [mtr, "{address}"]
`
if err := os.WriteFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml"), []byte(data), 0600); err != nil {
t.Fatal(err)
}
out, err := runNetssh(t, "run", "--dry-run", "trace", "router")
if err != nil || out != `"mtr" "router.example.com"` {
t.Fatalf("%q %v", out, err)
}
}
func TestRunOwnScripts(t *testing.T) {
for _, mode := range []string{"executable", "bash", "python3"} {
t.Run(mode, func(t *testing.T) {
if mode != "executable" {
if _, err := exec.LookPath(mode); err != nil {
t.Skip("interpreter not installed")
}
}
prepareTransferTest(t)
script := filepath.Join(t.TempDir(), "my host check")
body := "#!/bin/sh\nprintf '<%s>\\n' \"$@\"\nexit 7\n"
permissions := os.FileMode(0700)
argv := []string{script}
if mode != "executable" {
permissions = 0600
argv = []string{mode, script}
}
if mode == "python3" {
body = "import sys\nfor arg in sys.argv[1:]:\n print('<' + arg + '>')\nsys.exit(7)\n"
}
if err := os.WriteFile(script, []byte(body), permissions); err != nil {
t.Fatal(err)
}
argv = append(argv, "{address}", "{host}", "{target}")
var yaml strings.Builder
yaml.WriteString("\ncommands:\n check:\n alias_prefix: c\n args:\n")
for _, arg := range argv {
fmt.Fprintf(&yaml, " - %q\n", arg)
}
f, err := os.OpenFile(config.Path(), os.O_APPEND|os.O_WRONLY, 0)
if err != nil {
t.Fatal(err)
}
_, err = f.WriteString(yaml.String())
if closeErr := f.Close(); err != nil || closeErr != nil {
t.Fatalf("config write: %v %v", err, closeErr)
}
out, err := runNetssh(t, "run", "check", "fsnbx1", "--", "--report", "two words", "$(literal)")
want := "<10.0.0.9>\n<fsn1-bx1.hoster.de>\n<fsn1-bx1.hoster.de>\n<--report>\n<two words>\n<$(literal)>"
if out != want {
t.Fatalf("script args: %q, want %q", out, want)
}
exit, ok := err.(*exec.ExitError)
if !ok || exit.ExitCode() != 7 {
t.Fatalf("script exit status lost: %v", err)
}
})
}
}
+59
View File
@@ -0,0 +1,59 @@
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"strconv"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/runner"
"github.com/charmbracelet/x/term"
)
func commandHost(h resolvedHost) config.SSHHost {
instance, name := netbox.SplitTarget(h.Name)
return config.SSHHost{Instance: instance, Name: name, Kind: h.Kind, Tags: h.Tags, Status: h.Status, Site: h.Site, Role: h.Role, Platform: h.Platform, Tenant: h.Tenant}
}
func confirmAction(message string, yes bool) error {
if yes {
return nil
}
if !term.IsTerminal(os.Stdin.Fd()) {
return fmt.Errorf("%s requires confirmation; use --yes for unattended execution", message)
}
fmt.Fprintf(os.Stderr, "%s? [y/N] ", message)
answer, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return err
}
if strings.EqualFold(strings.TrimSpace(answer), "y") || strings.EqualFold(strings.TrimSpace(answer), "yes") {
return nil
}
return fmt.Errorf("cancelled")
}
func supervise(cfg *config.Config, h resolvedHost, name string, argv []string, post string, timeout time.Duration, status bool, stdin io.Reader, stdout, stderr io.Writer) int {
start := time.Now()
env := append(preConnectEnv(h, name), "NETSSH_COMMAND="+name)
result := runner.Run(context.Background(), argv, runner.Options{Stdin: stdin, Stdout: stdout, Stderr: stderr, Env: env, Timeout: timeout, Status: status, Label: name + " " + h.Name})
code := result.Code
if result.Started && config.HookCommand(post) != "" {
hook := runner.Run(context.Background(), []string{"sh", "-c", post}, runner.Options{Stdin: nil, Stdout: stderr, Stderr: stderr, Env: append(env, "NETSSH_EXIT_CODE="+strconv.Itoa(code)), Timeout: 30 * time.Second})
if hook.Code != 0 {
fmt.Fprintf(stderr, "post hook failed (exit %d)\n", hook.Code)
if code == 0 {
code = hook.Code
}
}
}
if err := activity.Append(cfg.Activity, activity.Record{Time: start, Host: h.Name, Command: name, Code: code, Duration: time.Since(start)}); err != nil {
fmt.Fprintf(stderr, "activity: %v\n", err)
}
return code
}
+14
View File
@@ -0,0 +1,14 @@
package main
import (
"os"
"testing"
)
// Integration helpers run this test binary as netssh. An automatic refresh
// would otherwise launch the test binary again with "cache refresh", rerunning
// the entire suite. Explicit cache-refresh tests still exercise the real command.
func TestMain(m *testing.M) {
_ = os.Setenv("NETSSH_NO_REFRESH", "1")
os.Exit(m.Run())
}
+260
View File
@@ -0,0 +1,260 @@
package main
import (
"bufio"
"errors"
"fmt"
"io"
"os"
"strings"
"sync"
"text/tabwriter"
"github.com/charmbracelet/x/term"
"github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/secret"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/setup"
)
var (
tokenMu sync.Mutex
tokenCache = map[string]string{}
)
// resolveToken returns the API token of an instance: the configured value,
// or the keyring entry when the value is "keyring". Lookups are cached per
// process, since each one can be a D-Bus round trip.
func resolveToken(n config.NetBoxConfig) (string, error) {
if !config.IsKeyringToken(n.Token) {
return n.Token, nil
}
account := n.KeyringAccount()
tokenMu.Lock()
defer tokenMu.Unlock()
if token, ok := tokenCache[account]; ok {
return token, nil
}
token, err := secret.Get(account)
if err != nil {
return "", err
}
tokenCache[account] = token
return token, nil
}
// clientToken resolves a token for a client; a failure is reported once and
// leaves the token empty, so NetBox answers with a clear authentication error.
func clientToken(n config.NetBoxConfig) (string, int) {
token, err := resolveToken(n)
if err != nil {
label := n.Name
if label == "" {
label = "netbox"
}
fmt.Fprintf(os.Stderr, "netssh: %s: %v\n", label, err)
return "", n.TokenVersion
}
version := n.TokenVersion
if config.IsKeyringToken(n.Token) {
version = netbox.TokenVersion(token)
}
return token, version
}
// instanceConfigs returns the configured NetBox instances, including the
// legacy unnamed one.
func instanceConfigs(cfg *config.Config) []*config.NetBoxConfig {
var out []*config.NetBoxConfig
for i := range cfg.NetBoxes {
out = append(out, &cfg.NetBoxes[i])
}
if len(out) == 0 && cfg.NetBox.URL != "" {
out = append(out, &cfg.NetBox)
}
return out
}
// selectInstance finds the instance named in args, or the only one.
func selectInstance(cfg *config.Config, args []string) (*config.NetBoxConfig, error) {
instances := instanceConfigs(cfg)
if len(instances) == 0 {
return nil, errors.New("no NetBox is configured (netssh configure)")
}
if len(args) == 0 {
if len(instances) == 1 {
return instances[0], nil
}
return nil, fmt.Errorf("name the NetBox instance: %s", strings.Join(instanceNames(cfg), ", "))
}
for _, instance := range instances {
if strings.EqualFold(instance.Name, args[0]) || (instance.Name == "" && strings.EqualFold(args[0], "default")) {
return instance, nil
}
}
return nil, fmt.Errorf("unknown NetBox instance %q", args[0])
}
// readToken reads a token without echo from a terminal, or a line from stdin.
func readToken(label string, stdin io.Reader) (string, error) {
if f, ok := stdin.(*os.File); ok && term.IsTerminal(f.Fd()) {
fmt.Fprintf(os.Stderr, "NetBox API token for %s: ", label)
data, err := term.ReadPassword(f.Fd())
fmt.Fprintln(os.Stderr)
if err != nil {
return "", err
}
return strings.TrimSpace(string(data)), nil
}
line, err := bufio.NewReader(stdin).ReadString('\n')
if err != nil && err != io.EOF {
return "", err
}
return strings.TrimSpace(line), nil
}
// saveConfig is replaced in tests.
var saveConfig = setup.Save
func tokenCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "token",
Short: "Keep NetBox API tokens in the system keyring",
Long: `Store NetBox API tokens in the system keyring (Secret Service / GNOME Keyring /
KWallet on Linux, Keychain on macOS) instead of the config file. The config
then contains token: keyring, and netssh reads the token from the keyring.
NETSSH_NETBOX_TOKEN still overrides the token of the unnamed instance.`,
}
cmd.AddCommand(tokenSetCmd(), tokenMigrateCmd(), tokenDeleteCmd(), tokenStatusCmd())
return cmd
}
func tokenSetCmd() *cobra.Command {
return &cobra.Command{
Use: "set [INSTANCE]",
Short: "Store a token in the keyring and switch the config to token: keyring",
Long: "Read the token without echo (or from stdin) and store it in the keyring.\nExample for scripts: echo \"$TOKEN\" | netssh token set prod",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
instance, err := selectInstance(cfg, args)
if err != nil {
return err
}
token, err := readToken(instance.KeyringAccount(), cmd.InOrStdin())
if err != nil {
return err
}
if token == "" || config.IsKeyringToken(token) {
return errors.New("no token given")
}
if err := secret.Set(instance.KeyringAccount(), token); err != nil {
return err
}
instance.Token, instance.TokenVersion = config.KeyringToken, netbox.TokenVersion(token)
if err := saveConfig(*cfg); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "Token for %s stored in the system keyring.\n", instance.KeyringAccount())
return nil
},
}
}
func tokenMigrateCmd() *cobra.Command {
return &cobra.Command{
Use: "migrate",
Short: "Move all tokens from the config file into the keyring",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
moved := 0
for _, instance := range instanceConfigs(cfg) {
if instance.Token == "" || config.IsKeyringToken(instance.Token) {
continue
}
if err := secret.Set(instance.KeyringAccount(), instance.Token); err != nil {
return err
}
instance.TokenVersion = netbox.TokenVersion(instance.Token)
instance.Token = config.KeyringToken
moved++
fmt.Fprintf(cmd.OutOrStdout(), "%s: moved to the keyring\n", instance.KeyringAccount())
}
if moved == 0 {
fmt.Fprintln(cmd.OutOrStdout(), "No tokens in the config file.")
return nil
}
return saveConfig(*cfg)
},
}
}
func tokenDeleteCmd() *cobra.Command {
return &cobra.Command{
Use: "delete [INSTANCE]",
Short: "Remove a token from the keyring",
Args: cobra.MaximumNArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
instance, err := selectInstance(cfg, args)
if err != nil {
return err
}
if err := secret.Delete(instance.KeyringAccount()); err != nil {
return err
}
fmt.Fprintf(cmd.OutOrStdout(), "Token for %s removed from the keyring.\n", instance.KeyringAccount())
if config.IsKeyringToken(instance.Token) {
fmt.Fprintln(cmd.OutOrStdout(), "The config still says token: keyring; store a new one with netssh token set.")
}
return nil
},
}
}
func tokenStatusCmd() *cobra.Command {
return &cobra.Command{
Use: "status",
Short: "Show where each instance's token comes from",
Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
w := tabwriter.NewWriter(cmd.OutOrStdout(), 0, 0, 2, ' ', 0)
fmt.Fprintln(w, "INSTANCE\tTOKEN")
for _, instance := range instanceConfigs(cfg) {
fmt.Fprintf(w, "%s\t%s\n", instance.KeyringAccount(), tokenSource(*instance))
}
return w.Flush()
},
}
}
func tokenSource(n config.NetBoxConfig) string {
switch {
case n.Token == "":
return "missing"
case config.IsKeyringToken(n.Token):
if _, err := resolveToken(n); err != nil {
return "keyring (not readable: " + err.Error() + ")"
}
return "keyring"
default:
return "config file (plain text; move it with netssh token migrate)"
}
}
+87
View File
@@ -0,0 +1,87 @@
package main
import (
"context"
"fmt"
"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"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/tui"
)
// configureTUIExtras wires reachability, the detail view and opening NetBox
// pages into the TUI. known enriches a listed host from the cache.
func configureTUIExtras(m *tui.Model, cfg *config.Config, client *netbox.Client, known func(name, kind string, tags []string) resolvedHost) {
m.SetColumns(cfg.TUI.EffectiveColumns())
if cfg.TUI.ReachabilityEnabled() {
m.SetReachability(cfg.TUI.ReachabilityTimeoutDuration(), func(name, kind string, tags []string) (int, bool) {
h := known(name, kind, tags)
if usesJumpHost(hostOptions(cfg, h), internalssh.WrapperFlags{}) {
return 0, false
}
_, port := hostDefaults(cfg, h)
if port <= 0 {
port = 22
}
return port, true
})
}
lookup := func(ctx context.Context, name, kind string, id int) (netbox.HostEntry, resolvedHost, error) {
h := known(name, kind, nil)
if kind == config.StaticKind {
return netbox.HostEntry{}, h, fmt.Errorf("%s is a static host and has no NetBox record", name)
}
if client == nil {
return netbox.HostEntry{}, h, fmt.Errorf("no NetBox is configured")
}
if id <= 0 {
id = h.ID
}
entry, _, h, err := netboxEntry(ctx, client, name, kind, id, h)
return entry, h, err
}
m.SetOpener(func(name, kind string, id int) error {
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
entry, _, err := lookup(ctx, name, kind, id)
if err != nil {
return err
}
url, err := client.WebURL(entry)
if err != nil {
return err
}
return openBrowser(url)
})
m.SetDetails(func(name, kind string, id int) (string, error) {
if kind == config.StaticKind {
h := known(name, kind, nil)
user, port := hostDefaults(cfg, h)
text := fmt.Sprintf("%s (static host from hosts:)\n Address %s\n", name, h.IP)
if user != "" {
text += " User " + user + "\n"
}
if port > 0 {
text += fmt.Sprintf(" Port %d\n", port)
}
return text, nil
}
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
defer cancel()
entry, h, err := lookup(ctx, name, kind, id)
if err != nil {
return "", err
}
details, err := client.GetDetails(ctx, entry)
if err != nil && details.Name == "" {
return "", err
}
text := formatDetails(details, h)
if err != nil {
text += "\nwarning: " + err.Error() + "\n"
}
return text, nil
})
}
+4 -3
View File
@@ -71,6 +71,7 @@ func buildUninstallPlan(cfg *config.Config, keepConfig bool) uninstallPlan {
addPath(path) addPath(path)
addPath(path + ".lock") addPath(path + ".lock")
addPath(filepath.Join(filepath.Dir(path), "last_refresh")) addPath(filepath.Join(filepath.Dir(path), "last_refresh"))
addPath(filepath.Join(filepath.Dir(path), "refresh_attempt"))
if strings.HasPrefix(filepath.Base(filepath.Dir(path)), "instances-") { if strings.HasPrefix(filepath.Base(filepath.Dir(path)), "instances-") {
addPath(filepath.Dir(path)) addPath(filepath.Dir(path))
} }
@@ -203,10 +204,10 @@ func uninstallCmd() *cobra.Command {
- netssh blocks and unmarked entries of older versions in bash, zsh, and fish profiles - netssh blocks and unmarked entries of older versions in bash, zsh, and fish profiles
- shell completion files (bash, zsh, fish, oh-my-zsh cache, command alias) - shell completion files (bash, zsh, fish, oh-my-zsh cache, command alias)
- the cache directory with hosts, aliases, and per-instance caches - the cache directory with hosts, aliases, and per-instance caches
- the config file (a private backup is kept) and local server notes - the config file (a private backup is kept) and local notes, favorites, action history and batch retry state
- the netssh binary - the netssh binary
Use --keep-config to keep the config file and notes for a reinstall.`, Use --keep-config to keep the config file and local state for a reinstall.`,
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load() cfg, err := config.Load()
@@ -243,7 +244,7 @@ Use --keep-config to keep the config file and notes for a reinstall.`,
return err return err
}, },
} }
cmd.Flags().BoolVar(&keepConfig, "keep-config", false, "Keep the config file and local notes") cmd.Flags().BoolVar(&keepConfig, "keep-config", false, "Keep the config file and local state")
cmd.Flags().BoolVarP(&yes, "yes", "y", false, "Do not ask for confirmation") cmd.Flags().BoolVarP(&yes, "yes", "y", false, "Do not ask for confirmation")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Only show what would be removed") cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Only show what would be removed")
return cmd return cmd
+7 -3
View File
@@ -6,13 +6,17 @@ require (
charm.land/bubbles/v2 v2.2.1 charm.land/bubbles/v2 v2.2.1
charm.land/bubbletea/v2 v2.1.1 charm.land/bubbletea/v2 v2.1.1
charm.land/huh/v2 v2.0.3 charm.land/huh/v2 v2.0.3
charm.land/lipgloss/v2 v2.1.0 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/cobra v1.10.2
github.com/spf13/viper v1.21.0 github.com/spf13/viper v1.21.0
github.com/zalando/go-keyring v0.2.6
go.yaml.in/yaml/v3 v3.0.6
golang.org/x/sys v0.50.0 golang.org/x/sys v0.50.0
) )
require ( require (
al.essio.dev/pkg/shellescape v1.5.1 // indirect
github.com/atotto/clipboard v0.1.4 // indirect github.com/atotto/clipboard v0.1.4 // indirect
github.com/catppuccin/go v0.3.0 // indirect github.com/catppuccin/go v0.3.0 // indirect
github.com/charmbracelet/colorprofile v0.4.3 // indirect github.com/charmbracelet/colorprofile v0.4.3 // indirect
@@ -21,15 +25,16 @@ require (
github.com/charmbracelet/x/exp/golden v0.1.0 // indirect github.com/charmbracelet/x/exp/golden v0.1.0 // indirect
github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect github.com/charmbracelet/x/exp/ordered v0.1.0 // indirect
github.com/charmbracelet/x/exp/strings v0.1.0 // indirect github.com/charmbracelet/x/exp/strings v0.1.0 // indirect
github.com/charmbracelet/x/term v0.2.2 // indirect
github.com/charmbracelet/x/termios v0.1.1 // indirect github.com/charmbracelet/x/termios v0.1.1 // indirect
github.com/charmbracelet/x/windows v0.2.2 // indirect github.com/charmbracelet/x/windows v0.2.2 // indirect
github.com/charmbracelet/x/xpty v0.1.4 // indirect github.com/charmbracelet/x/xpty v0.1.4 // indirect
github.com/clipperhouse/displaywidth v0.11.0 // indirect github.com/clipperhouse/displaywidth v0.11.0 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
github.com/danieljoos/wincred v1.2.2 // indirect
github.com/dustin/go-humanize v1.1.0 // indirect github.com/dustin/go-humanize v1.1.0 // indirect
github.com/fsnotify/fsnotify v1.10.1 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect
github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect
github.com/godbus/dbus/v5 v5.1.0 // indirect
github.com/google/go-cmp v0.7.0 // indirect github.com/google/go-cmp v0.7.0 // indirect
github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect
github.com/lucasb-eyer/go-colorful v1.4.1 // indirect github.com/lucasb-eyer/go-colorful v1.4.1 // indirect
@@ -47,7 +52,6 @@ require (
github.com/stretchr/testify v1.12.1 // indirect github.com/stretchr/testify v1.12.1 // indirect
github.com/subosito/gotenv v1.6.0 // indirect github.com/subosito/gotenv v1.6.0 // indirect
github.com/xo/terminfo v1.3.1 // indirect github.com/xo/terminfo v1.3.1 // indirect
go.yaml.in/yaml/v3 v3.0.6 // indirect
golang.org/x/sync v0.25.0 // indirect golang.org/x/sync v0.25.0 // indirect
golang.org/x/text v0.44.0 // indirect golang.org/x/text v0.44.0 // indirect
) )
+14 -2
View File
@@ -1,11 +1,13 @@
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 h1:Fq1+qm5hV6GkvzLQDhCBpXXE5tLgvh1PRriCLwSvIQU=
charm.land/bubbles/v2 v2.2.1/go.mod h1:wdMgn+sje1KNXdwFizIWjbf328fIUBxqEmJ/vYPo8yc= 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 h1:S1S9l37pCZGrj1JexBcr9x4Nr3MVeM42InqCYM/tDpU=
charm.land/bubbletea/v2 v2.1.1/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU= charm.land/bubbletea/v2 v2.1.1/go.mod h1:xWHeyxIX9/wiFU2kgPW04ojOZyTzrWf+8lGjUCaftiU=
charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU= charm.land/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=
charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc= charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=
charm.land/lipgloss/v2 v2.1.0 h1:RLCNLhSQST+NPOmvUSbRWZ3UFOXsf3ZXFmJ5E/2tHEU= charm.land/lipgloss/v2 v2.1.1 h1:F+vKWis9Kz3MFRsbICSDFtT1ZwVL+8f+36Dtg+OpKwc=
charm.land/lipgloss/v2 v2.1.0/go.mod h1:wwfOgrNqUA9yjL8nmG6BIO0qQnmkEgJ8ISptbme83gI= charm.land/lipgloss/v2 v2.1.1/go.mod h1:k79y/56yThpkJvbwyrcHr8MyZF42e84Q5fW9Ibu6LFc=
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ= github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
@@ -43,6 +45,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/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 h1:bJrF4RRfyJnbTJqzRLHzcGaZK1NeM5kTC9jGgovnR1s=
github.com/creack/pty v1.1.24/go.mod h1:08sCNb52WyoAwi2QDyzUCTgcvVFhUzewun7wtTfvcwE= 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/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg= 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/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8= github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
@@ -51,8 +55,12 @@ github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx5
github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= 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 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM= 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/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= 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/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 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
@@ -91,12 +99,16 @@ github.com/spf13/pflag v1.1.0 h1:6W6MbVUrnMb8PEhjkqwsVLY7ryuzRfFHF4mQd7L94ag=
github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.1.0/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU= github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY= github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4=
github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0=
github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE=
github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg=
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= 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 h1:4ZwPCuu4PEFw0PkNp3Hv/x3gqvgLCzYhurszsj101cM=
github.com/xo/terminfo v1.3.1/go.mod h1:lGzkSo8Fe7IRh/w+Gqz7n5mDog4FVXCj3gy/DYTBqio= 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=
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg= 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 h1:zcDfvjXEqTQmpjniUBLc91xYJMB2c4QOFxEF/LCEckM=
go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= go.yaml.in/yaml/v3 v3.0.6/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
+94
View File
@@ -0,0 +1,94 @@
// Package activity stores local preferences and optional execution metadata.
// No command arguments, environment variables, tokens or command output are logged.
package activity
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"golang.org/x/sys/unix"
)
type Record struct {
Time time.Time `json:"time"`
Host string `json:"host"`
Command string `json:"command"`
Code int `json:"exit_code"`
Duration time.Duration `json:"duration_ns"`
}
type State struct {
Favorites map[string]bool `json:"favorites,omitempty"`
Pinned map[string]bool `json:"pinned,omitempty"`
Records []Record `json:"records,omitempty"`
}
func Path() string { return filepath.Join(filepath.Dir(config.Path()), "netssh", "activity.json") }
func Read() (State, error) {
var s State
data, err := os.ReadFile(Path())
if os.IsNotExist(err) {
err = nil
} else if err == nil {
err = json.Unmarshal(data, &s)
}
if s.Favorites == nil {
s.Favorites = map[string]bool{}
}
if s.Pinned == nil {
s.Pinned = map[string]bool{}
}
return s, err
}
func Update(change func(*State)) error {
p := Path()
if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {
return err
}
f, err := os.OpenFile(p+".lock", os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return err
}
defer f.Close()
if err = unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil {
return err
}
defer unix.Flock(int(f.Fd()), unix.LOCK_UN)
s, err := Read()
if err != nil {
return fmt.Errorf("local state: %w", err)
}
change(&s)
data, err := json.MarshalIndent(s, "", " ")
if err != nil {
return err
}
return storage.WriteFile(p, data, 0600)
}
func Prune(s *State, c config.ActivityConfig) {
if c.RetentionDays > 0 {
cutoff := time.Now().Add(-time.Duration(c.RetentionDays) * 24 * time.Hour)
keep := s.Records[:0]
for _, r := range s.Records {
if !r.Time.Before(cutoff) {
keep = append(keep, r)
}
}
s.Records = keep
}
sort.SliceStable(s.Records, func(i, j int) bool { return s.Records[i].Time.Before(s.Records[j].Time) })
if c.MaxEntries > 0 && len(s.Records) > c.MaxEntries {
s.Records = s.Records[len(s.Records)-c.MaxEntries:]
}
}
func Append(c config.ActivityConfig, r Record) error {
if !c.Enabled {
return nil
}
return Update(func(s *State) { s.Records = append(s.Records, r); Prune(s, c) })
}
+59
View File
@@ -0,0 +1,59 @@
package activity
import (
"fmt"
"os"
"sync"
"testing"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func TestConcurrentActivityAndRetention(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.ActivityConfig{Enabled: true, RetentionDays: 1, MaxEntries: 10}
if err := Update(func(s *State) {
s.Favorites["prod/web"] = true
s.Pinned["prod/web"] = true
s.Records = []Record{{Time: time.Now().Add(-48 * time.Hour), Host: "old"}}
}); err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if err := Append(cfg, Record{Time: time.Now(), Host: fmt.Sprint(i), Command: "test"}); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
s, err := Read()
if err != nil {
t.Fatal(err)
}
if len(s.Records) != 10 || !s.Favorites["prod/web"] || !s.Pinned["prod/web"] {
t.Fatalf("%+v", s)
}
for _, r := range s.Records {
if r.Host == "old" {
t.Fatal("expired record retained")
}
}
info, _ := os.Stat(Path())
if info.Mode().Perm() != 0600 {
t.Fatal(info.Mode())
}
}
func TestDisabledHistoryDoesNotWrite(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := Append(config.ActivityConfig{}, Record{}); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(Path()); !os.IsNotExist(err) {
t.Fatal("disabled history wrote data")
}
}
+56 -7
View File
@@ -17,13 +17,26 @@ import (
) )
type Entry struct { type Entry struct {
Name string `json:"name"` Resolver string `json:"resolver,omitempty"`
IP string `json:"ip"` Name string `json:"name"`
Kind string `json:"kind"` IP string `json:"ip"`
Tags []string `json:"tags,omitempty"` Kind string `json:"kind"`
Cluster string `json:"cluster,omitempty"` Tags []string `json:"tags,omitempty"`
CachedAt time.Time `json:"cached_at"` Cluster string `json:"cluster,omitempty"`
LastUsed time.Time `json:"last_used,omitempty"` // ID, Status, Site, Role, Platform and Tenant come from NetBox; entries
// written by older versions lack them until the next refresh.
ID int `json:"id,omitempty"`
Status string `json:"status,omitempty"`
Site *config.Ref `json:"site,omitempty"`
Role *config.Ref `json:"role,omitempty"`
Platform *config.Ref `json:"platform,omitempty"`
Tenant *config.Ref `json:"tenant,omitempty"`
// Location is the chain of nested locations below the site, outermost first.
Location []config.Ref `json:"location,omitempty"`
Rack string `json:"rack,omitempty"`
Position string `json:"position,omitempty"`
CachedAt time.Time `json:"cached_at"`
LastUsed time.Time `json:"last_used,omitempty"`
// Static marks a host from the config's hosts: list. It never expires; // Static marks a host from the config's hosts: list. It never expires;
// it is stored only to remember LastUsed for the recently-used list. // it is stored only to remember LastUsed for the recently-used list.
Static bool `json:"static,omitempty"` Static bool `json:"static,omitempty"`
@@ -83,6 +96,26 @@ func (c *Cache) NeedsRefresh(d time.Duration) bool {
return time.Since(t) >= d return time.Since(t) >= d
} }
// ClaimRefresh reports whether a background refresh should start now: the last
// full refresh is older than d and no attempt was claimed within retry. It
// records the attempt, so parallel shells and repeated commands start one
// refresh per retry interval instead of one each.
func (c *Cache) ClaimRefresh(d, retry time.Duration) bool {
if !c.NeedsRefresh(d) {
return false
}
attempt := filepath.Join(filepath.Dir(c.refreshStamp), "refresh_attempt")
if info, err := os.Stat(attempt); err == nil && time.Since(info.ModTime()) < retry {
return false
}
if err := os.MkdirAll(filepath.Dir(attempt), 0o755); err != nil {
return true // cannot record the attempt; refreshing is still right
}
// Best effort: two processes racing here may both refresh once.
_ = os.WriteFile(attempt, nil, 0o600)
return true
}
// SetRefreshed records the current time as the last successful full refresh. // SetRefreshed records the current time as the last successful full refresh.
func (c *Cache) SetRefreshed() error { func (c *Cache) SetRefreshed() error {
if c.refreshStamp == "" { if c.refreshStamp == "" {
@@ -406,3 +439,19 @@ func (c *Cache) All() []Entry {
} }
return out return out
} }
// RefPtr returns nil for an empty reference, keeping the cache file small.
func RefPtr(r config.Ref) *config.Ref {
if r == (config.Ref{}) {
return nil
}
return &r
}
// RefOf returns the referenced value, or an empty Ref.
func RefOf(r *config.Ref) config.Ref {
if r == nil {
return config.Ref{}
}
return *r
}
+20
View File
@@ -557,3 +557,23 @@ func TestStaticHosts(t *testing.T) {
t.Fatalf("removed static host still on disk:\n%s", data) t.Fatalf("removed static host still on disk:\n%s", data)
} }
} }
func TestClaimRefreshThrottlesAttempts(t *testing.T) {
c := New(filepath.Join(t.TempDir(), "netssh", "hosts.json"), 60)
if !c.ClaimRefresh(24*time.Hour, time.Minute) {
t.Fatal("a never refreshed cache must claim a refresh")
}
// NetBox is down: the stamp stays stale, but the attempt is remembered.
if c.ClaimRefresh(24*time.Hour, time.Minute) {
t.Error("a second refresh within the retry interval must not start")
}
if !c.ClaimRefresh(24*time.Hour, 0) {
t.Error("after the retry interval a refresh must start again")
}
if err := c.SetRefreshed(); err != nil {
t.Fatal(err)
}
if c.ClaimRefresh(24*time.Hour, 0) {
t.Error("a freshly refreshed cache must not claim a refresh")
}
}
+73
View File
@@ -0,0 +1,73 @@
package config
import (
"fmt"
"regexp"
"strings"
"time"
)
// HostCommand defines a local command and the prefix of its generated host aliases.
type HostCommand struct {
PostRun string `mapstructure:"post_run"`
Match SSHMatch `mapstructure:"match"`
Confirm bool `mapstructure:"confirm"`
Timeout string `mapstructure:"timeout"`
AliasPrefix string `mapstructure:"alias_prefix" yaml:"alias_prefix"`
Args []string `mapstructure:"args" yaml:"args"`
}
func (c *Config) ValidateCommands() error {
prefixes := make(map[string]bool)
for name, command := range c.Commands {
if strings.ContainsRune(command.PostRun, 0) {
return fmt.Errorf("commands.%s.post_run contains NUL", name)
}
if command.Match != (SSHMatch{}) {
if err := command.Match.Validate("commands." + name); err != nil {
return err
}
}
if command.Timeout != "" {
d, err := time.ParseDuration(command.Timeout)
if err != nil || d <= 0 {
return fmt.Errorf("commands.%s.timeout requires a positive duration", name)
}
}
if name == "" || ValidateCommandAlias(name) != nil {
return fmt.Errorf("commands.%s: name must be a non-reserved shell identifier", name)
}
if command.AliasPrefix != "" {
if !regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_]*$`).MatchString(command.AliasPrefix) {
return fmt.Errorf("commands.%s.alias_prefix must be a shell identifier", name)
}
if prefixes[command.AliasPrefix] {
return fmt.Errorf("commands.%s: duplicate alias_prefix %q", name, command.AliasPrefix)
}
prefixes[command.AliasPrefix] = true
}
if len(command.Args) == 0 || strings.TrimSpace(command.Args[0]) == "" {
return fmt.Errorf("commands.%s.args requires an executable", name)
}
target := false
for i, arg := range command.Args {
if strings.ContainsRune(arg, 0) {
return fmt.Errorf("commands.%s.args cannot contain NUL", name)
}
if i == 0 && strings.ContainsAny(arg, "{}") {
return fmt.Errorf("commands.%s: executable cannot contain placeholders", name)
}
if strings.Contains(arg, "{host}") || strings.Contains(arg, "{address}") || strings.Contains(arg, "{target}") {
target = true
}
rest := strings.NewReplacer("{host}", "", "{address}", "", "{target}", "").Replace(arg)
if strings.ContainsAny(rest, "{}") {
return fmt.Errorf("commands.%s: supported placeholders are {host}, {address}, {target}", name)
}
}
if !target {
return fmt.Errorf("commands.%s.args requires {host}, {address}, or {target}", name)
}
}
return nil
}
+37
View File
@@ -0,0 +1,37 @@
package config
import "testing"
func TestValidateCommands(t *testing.T) {
for _, tc := range []struct {
name string
command HostCommand
valid bool
}{
{"mtr", HostCommand{AliasPrefix: "m", Args: []string{"mtr", "{address}"}}, true},
{"ping", HostCommand{Args: []string{"ping", "-c", "3", "{host}"}}, true},
{"inspect", HostCommand{Args: []string{"echo", "{target}"}}, true},
{"", HostCommand{Args: []string{"echo", "{host}"}}, false},
{"bad name", HostCommand{Args: []string{"echo", "{host}"}}, false},
{"netssh", HostCommand{Args: []string{"echo", "{host}"}}, false},
{"bad", HostCommand{AliasPrefix: "m;", Args: []string{"mtr", "{address}"}}, false},
{"bad", HostCommand{}, false},
{"bad", HostCommand{Args: []string{"", "{host}"}}, false},
{"bad", HostCommand{Args: []string{"{host}", "{address}"}}, false},
{"bad", HostCommand{Args: []string{"mtr", "{adress}"}}, false},
{"bad", HostCommand{Args: []string{"mtr"}}, false},
{"bad", HostCommand{Args: []string{"mtr", "{host}\x00"}}, false},
} {
cfg := Config{Commands: map[string]HostCommand{tc.name: tc.command}}
if err := cfg.ValidateCommands(); (err == nil) != tc.valid {
t.Errorf("%+v: %v", tc, err)
}
}
cfg := Config{Commands: map[string]HostCommand{
"mtr": {AliasPrefix: "m", Args: []string{"mtr", "{address}"}},
"ping": {AliasPrefix: "m", Args: []string{"ping", "{address}"}},
}}
if cfg.ValidateCommands() == nil {
t.Fatal("duplicate prefixes accepted")
}
}
+100 -21
View File
@@ -6,20 +6,24 @@ import (
"path/filepath" "path/filepath"
"regexp" "regexp"
"strings" "strings"
"time"
"github.com/spf13/viper" "github.com/spf13/viper"
) )
type Config struct { type Config struct {
Shell ShellConfig `mapstructure:"shell"` TUI TUIConfig `mapstructure:"tui"`
NetBox NetBoxConfig `mapstructure:"netbox"` Activity ActivityConfig `mapstructure:"activity"`
NetBoxes []NetBoxConfig `mapstructure:"netboxes"` Commands map[string]HostCommand `mapstructure:"commands"`
Resolver ResolverConfig `mapstructure:"resolver"` Shell ShellConfig `mapstructure:"shell"`
Cache CacheConfig `mapstructure:"cache"` NetBox NetBoxConfig `mapstructure:"netbox"`
SSH SSHConfig `mapstructure:"ssh"` NetBoxes []NetBoxConfig `mapstructure:"netboxes"`
Shortcuts ShortcutsConfig `mapstructure:"shortcuts"` Resolver ResolverConfig `mapstructure:"resolver"`
Completion CompletionConfig `mapstructure:"completion"` Cache CacheConfig `mapstructure:"cache"`
Hosts []StaticHost `mapstructure:"hosts"` SSH SSHConfig `mapstructure:"ssh"`
Shortcuts ShortcutsConfig `mapstructure:"shortcuts"`
Completion CompletionConfig `mapstructure:"completion"`
Hosts []StaticHost `mapstructure:"hosts"`
// Groups name lists of hosts and selectors for netssh multi (@name). // Groups name lists of hosts and selectors for netssh multi (@name).
Groups map[string][]string `mapstructure:"groups"` Groups map[string][]string `mapstructure:"groups"`
Multi MultiConfig `mapstructure:"multi"` Multi MultiConfig `mapstructure:"multi"`
@@ -30,14 +34,20 @@ type ShellConfig struct {
} }
type NetBoxConfig struct { type NetBoxConfig struct {
Name string `mapstructure:"name"` DisablePrefix bool `mapstructure:"disable_prefix"`
URL string `mapstructure:"url"` Name string `mapstructure:"name"`
Token string `mapstructure:"token"` URL string `mapstructure:"url"`
TokenVersion int `mapstructure:"token_version"` Token string `mapstructure:"token"`
SSH SSHOptions `mapstructure:"ssh"` TokenVersion int `mapstructure:"token_version"`
SSH SSHOptions `mapstructure:"ssh"`
} }
type ResolverConfig struct { type ResolverConfig struct {
// Fallback tries the addresses of the other strategies when the chosen
// address does not accept TCP connections on the SSH port.
Fallback bool `mapstructure:"fallback"`
// FallbackTimeout is the per-address connect timeout in milliseconds; 0 = 1000.
FallbackTimeout int `mapstructure:"fallback_timeout"`
Strategies []string `mapstructure:"strategies"` Strategies []string `mapstructure:"strategies"`
ManagementSubnets []string `mapstructure:"management_subnets"` ManagementSubnets []string `mapstructure:"management_subnets"`
InterfaceName string `mapstructure:"interface_name"` InterfaceName string `mapstructure:"interface_name"`
@@ -53,8 +63,11 @@ type CacheConfig struct {
type SSHConfig struct { type SSHConfig struct {
DefaultUser string `mapstructure:"default_user"` DefaultUser string `mapstructure:"default_user"`
DefaultPort int `mapstructure:"default_port"` DefaultPort int `mapstructure:"default_port"`
SSHOptions `mapstructure:",squash"` // WarnStatus lists NetBox status values that ask before connecting;
Rules []SSHRule `mapstructure:"rules"` // nil means DefaultWarnStatus, an empty list disables the question.
WarnStatus []string `mapstructure:"warn_status"`
SSHOptions `mapstructure:",squash"`
Rules []SSHRule `mapstructure:"rules"`
} }
type CompletionConfig struct { type CompletionConfig struct {
@@ -66,6 +79,9 @@ type ShortcutsConfig struct {
Domains []string `mapstructure:"domains"` Domains []string `mapstructure:"domains"`
StripHyphens bool `mapstructure:"strip_hyphens"` StripHyphens bool `mapstructure:"strip_hyphens"`
Rewrites []ShortcutRewrite `mapstructure:"rewrites"` Rewrites []ShortcutRewrite `mapstructure:"rewrites"`
// Show displays each host's shortcut alias in the TUI and in host lists, and
// offers shortcuts in Tab completion even when the full name matches.
Show bool `mapstructure:"show"`
} }
// ShortcutRewrite replaces every match of Pattern (Go regexp syntax) with // ShortcutRewrite replaces every match of Pattern (Go regexp syntax) with
@@ -93,6 +109,51 @@ func (s ShortcutsConfig) Validate() error {
return nil return nil
} }
// DefaultWarnStatus are the NetBox status values that ask before connecting.
var DefaultWarnStatus = []string{"offline", "planned", "staged", "failed", "inventory", "decommissioning"}
// KeyringToken as a token value reads the token from the system keyring.
const KeyringToken = "keyring"
// IsKeyringToken reports whether token refers to the system keyring.
func IsKeyringToken(token string) bool {
return strings.EqualFold(strings.TrimSpace(token), KeyringToken)
}
// KeyringAccount is the keyring entry of a NetBox instance; the unnamed
// single-instance configuration uses "default".
func (n NetBoxConfig) KeyringAccount() string {
if n.Name == "" {
return "default"
}
return strings.ToLower(n.Name)
}
// WarnsStatus reports whether status is configured to ask before connecting.
func (s SSHConfig) WarnsStatus(status string) bool {
if status == "" {
return false
}
list := s.WarnStatus
if list == nil {
list = DefaultWarnStatus
}
for _, warn := range list {
if strings.EqualFold(strings.TrimSpace(warn), status) {
return true
}
}
return false
}
// FallbackTimeoutDuration returns resolver.fallback_timeout, 1s by default.
func (r ResolverConfig) FallbackTimeoutDuration() time.Duration {
if r.FallbackTimeout <= 0 {
return time.Second
}
return time.Duration(r.FallbackTimeout) * time.Millisecond
}
// Path returns the canonical config file path. // Path returns the canonical config file path.
func Path() string { func Path() string {
configDir, err := os.UserConfigDir() configDir, err := os.UserConfigDir()
@@ -108,19 +169,23 @@ func Load() (*Config, error) {
v.SetDefault("resolver.strategies", []string{"management_subnet", "primary_ip"}) v.SetDefault("resolver.strategies", []string{"management_subnet", "primary_ip"})
v.SetDefault("resolver.management_subnets", []string{}) v.SetDefault("resolver.management_subnets", []string{})
v.SetDefault("cache.ttl", 3600) v.SetDefault("cache.ttl", 3600)
v.SetDefault("tui.history_limit", 10)
v.SetDefault("activity.retention_days", 30)
v.SetDefault("activity.max_entries", 1000)
configDir, err := os.UserConfigDir() configDir, err := os.UserConfigDir()
if err == nil { if err == nil {
v.SetConfigName("netssh") v.SetConfigName("netssh")
v.SetConfigType("yaml") v.SetConfigType("yaml")
v.AddConfigPath(filepath.Join(configDir)) // Only the user's own directory: a netssh.yaml in the working directory
v.AddConfigPath(".") // (e.g. of a cloned repository) could inject ssh options and a NetBox URL.
v.AddConfigPath(configDir)
} }
v.SetEnvPrefix("NETSSH") v.SetEnvPrefix("NETSSH")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_")) v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv() 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", "shell.alias", "ssh.proxy_jump", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window"} { 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"} {
if err := v.BindEnv(key); err != nil { if err := v.BindEnv(key); err != nil {
return nil, err return nil, err
} }
@@ -136,6 +201,14 @@ func Load() (*Config, error) {
if err := v.Unmarshal(&cfg); err != nil { if err := v.Unmarshal(&cfg); err != nil {
return nil, fmt.Errorf("parsing config: %w", err) return nil, fmt.Errorf("parsing config: %w", err)
} }
// "columns: []" shows only the hostname; only a missing key means the default.
if cfg.TUI.Columns == nil && v.IsSet("tui.columns") {
cfg.TUI.Columns = []string{}
}
// "warn_status: []" disables the question; only a missing key means the default.
if cfg.SSH.WarnStatus == nil && v.IsSet("ssh.warn_status") {
cfg.SSH.WarnStatus = []string{}
}
// Legacy environment variables must not invent an additional unnamed source // Legacy environment variables must not invent an additional unnamed source
// when a file explicitly configures named instances (including wizard migration). // when a file explicitly configures named instances (including wizard migration).
if len(cfg.NetBoxes) > 0 && !v.InConfig("netbox.url") { if len(cfg.NetBoxes) > 0 && !v.InConfig("netbox.url") {
@@ -146,7 +219,7 @@ func Load() (*Config, error) {
return nil, err return nil, err
} }
if cfg.NetBox.TokenVersion == 0 && cfg.NetBox.Token != "" { if cfg.NetBox.TokenVersion == 0 && cfg.NetBox.Token != "" && !IsKeyringToken(cfg.NetBox.Token) {
if strings.HasPrefix(cfg.NetBox.Token, "nbt_") { if strings.HasPrefix(cfg.NetBox.Token, "nbt_") {
cfg.NetBox.TokenVersion = 2 cfg.NetBox.TokenVersion = 2
} else { } else {
@@ -166,13 +239,19 @@ func Load() (*Config, error) {
if err := cfg.ValidateHosts(); err != nil { if err := cfg.ValidateHosts(); err != nil {
return nil, err return nil, err
} }
if err := cfg.ValidateOperations(); err != nil {
return nil, err
}
if err := cfg.ValidateCommands(); err != nil {
return nil, err
}
if err := cfg.ValidateMulti(); err != nil { if err := cfg.ValidateMulti(); err != nil {
return nil, err return nil, err
} }
for i := range cfg.NetBoxes { for i := range cfg.NetBoxes {
source := &cfg.NetBoxes[i] source := &cfg.NetBoxes[i]
source.Name = strings.ToLower(source.Name) source.Name = strings.ToLower(source.Name)
if source.TokenVersion == 0 && source.Token != "" { if source.TokenVersion == 0 && source.Token != "" && !IsKeyringToken(source.Token) {
source.TokenVersion = 1 source.TokenVersion = 1
if strings.HasPrefix(source.Token, "nbt_") { if strings.HasPrefix(source.Token, "nbt_") {
source.TokenVersion = 2 source.TokenVersion = 2
+24
View File
@@ -196,3 +196,27 @@ func TestLoad_InvalidShortcutRewrite(t *testing.T) {
} }
} }
} }
// A netssh.yaml in the working directory (e.g. of a cloned repository) must
// not be loaded: it could inject ssh options such as ProxyCommand.
func TestLoad_IgnoresConfigInWorkingDirectory(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("NETSSH_NETBOX_URL", "")
t.Chdir(writeConfig(t, "hosts:\n - name: evil\n address: 10.0.0.1\nssh:\n options:\n ProxyCommand: touch /tmp/pwned\n"))
cfg, err := Load()
if err != nil {
t.Fatalf("Load: %v", err)
}
if len(cfg.Hosts) != 0 || len(cfg.SSH.Options) != 0 {
t.Errorf("config from the working directory was loaded: %+v", cfg)
}
}
func TestLoad_RejectsInvalidLegacyNetBoxURL(t *testing.T) {
for _, bad := range []string{"netbox.example.com", "ftp://netbox.example.com", "https://netbox.example.com/?x=1"} {
t.Setenv("XDG_CONFIG_HOME", writeConfig(t, "netbox:\n url: \""+bad+"\"\n token: t\n"))
if _, err := Load(); err == nil || !strings.Contains(err.Error(), "netbox.url") {
t.Errorf("%s: got %v, want a netbox.url error", bad, err)
}
}
}
+108
View File
@@ -0,0 +1,108 @@
package config
import (
"os"
"strings"
"testing"
)
func TestSSHRuleMatchesNetBoxAttributes(t *testing.T) {
host := SSHHost{Name: "sw1", Kind: "device", Status: "active",
Site: Ref{Name: "Falkenstein 1", Slug: "fsn1"}, Role: Ref{Name: "Core Switch", Slug: "core-switch"},
Platform: Ref{Name: "Juniper Junos", Slug: "junos"}, Tenant: Ref{Name: "ACME"}}
for _, tc := range []struct {
match SSHMatch
want bool
}{
{SSHMatch{Platform: "junos"}, true},
{SSHMatch{Platform: "juniper junos"}, true},
{SSHMatch{Platform: "eos"}, false},
{SSHMatch{Site: "fsn1", Role: "core-switch"}, true},
{SSHMatch{Role: "Core Switch"}, true},
{SSHMatch{Site: "falkenstein-1"}, true},
{SSHMatch{Tenant: "acme"}, true},
{SSHMatch{Status: "ACTIVE"}, true},
{SSHMatch{Status: "offline"}, false},
{SSHMatch{Platform: "junos", Kind: "vm"}, false},
} {
if got := tc.match.matches(host); got != tc.want {
t.Errorf("%+v: got %v, want %v", tc.match, got, tc.want)
}
}
if err := (SSHMatch{Platform: "junos"}).Validate("rule"); err != nil {
t.Fatalf("platform-only match rejected: %v", err)
}
}
func TestSSHOptionsForPlatformRule(t *testing.T) {
cfg := &Config{SSH: SSHConfig{Rules: []SSHRule{{Match: SSHMatch{Platform: "junos"}, SSHOptions: SSHOptions{Options: map[string]string{"KexAlgorithms": "+diffie-hellman-group14-sha1"}}}}}}
opts := cfg.SSHOptionsFor(SSHHost{Name: "sw1", Kind: "device", Platform: Ref{Slug: "junos"}})
if opts.Options["kexalgorithms"] != "+diffie-hellman-group14-sha1" {
t.Fatalf("platform rule not applied: %+v", opts.Options)
}
if opts := cfg.SSHOptionsFor(SSHHost{Name: "web", Kind: "vm"}); len(opts.Options) != 0 {
t.Fatalf("rule applied to other platform: %+v", opts.Options)
}
}
func TestWarnStatusDefaultsAndOverrides(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\n"))
if cfg.SSH.WarnStatus != nil || !cfg.SSH.WarnsStatus("offline") || cfg.SSH.WarnsStatus("active") || cfg.SSH.WarnsStatus("") {
t.Fatalf("default warn_status wrong: %#v", cfg.SSH.WarnStatus)
}
cfg = loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\nssh:\n warn_status: []\n"))
if cfg.SSH.WarnStatus == nil || cfg.SSH.WarnsStatus("offline") {
t.Fatalf("empty warn_status should disable the question: %#v", cfg.SSH.WarnStatus)
}
cfg = loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\nssh:\n warn_status: [planned]\n"))
if !cfg.SSH.WarnsStatus("Planned") || cfg.SSH.WarnsStatus("offline") {
t.Fatalf("custom warn_status wrong: %#v", cfg.SSH.WarnStatus)
}
}
func TestReachabilityAndFallbackDefaults(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\n"))
if cfg.TUI.ReachabilityEnabled() || cfg.TUI.ReachabilityTimeoutDuration().Milliseconds() != 300 {
t.Fatalf("reachability must be opt-in: %+v", cfg.TUI)
}
if strings.Join(cfg.TUI.EffectiveColumns(), ",") != "alias,ip,source,status" {
t.Fatalf("default columns: %v", cfg.TUI.EffectiveColumns())
}
if cfg.Resolver.Fallback || cfg.Resolver.FallbackTimeoutDuration().Milliseconds() != 1000 {
t.Fatalf("fallback defaults wrong: %+v", cfg.Resolver)
}
cfg = loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\ntui:\n columns: [Reachability, ip, platform]\n reachability_timeout: 800\nresolver:\n fallback: true\n fallback_timeout: 250\n"))
if !cfg.TUI.ReachabilityEnabled() || cfg.TUI.ReachabilityTimeoutDuration().Milliseconds() != 800 || strings.Join(cfg.TUI.Columns, ",") != "reachability,ip,platform" {
t.Fatalf("reachability settings ignored: %+v", cfg.TUI)
}
if !cfg.Resolver.Fallback || cfg.Resolver.FallbackTimeoutDuration().Milliseconds() != 250 {
t.Fatalf("fallback settings ignored: %+v", cfg.Resolver)
}
}
func TestKeyringTokenKeepsVersionUndetected(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\n token: keyring\nnetboxes: []\n"))
if !IsKeyringToken(cfg.NetBox.Token) || cfg.NetBox.TokenVersion != 0 {
t.Fatalf("keyring token treated as literal: %+v", cfg.NetBox)
}
if cfg.NetBox.KeyringAccount() != "default" || (NetBoxConfig{Name: "Prod"}).KeyringAccount() != "prod" {
t.Fatal("unexpected keyring account names")
}
}
func TestTUIColumnsValidation(t *testing.T) {
cfg := loadFromDir(t, writeConfig(t, "netbox:\n url: https://nb\ntui:\n columns: []\n"))
if cfg.TUI.Columns == nil || len(cfg.TUI.EffectiveColumns()) != 0 {
t.Fatalf("empty columns should show only the hostname: %#v", cfg.TUI.Columns)
}
for _, bad := range []string{"[ip, colour]", "[ip, ip]"} {
dir := writeConfig(t, "netbox:\n url: https://nb\ntui:\n columns: "+bad+"\n")
orig := os.Getenv("XDG_CONFIG_HOME")
os.Setenv("XDG_CONFIG_HOME", dir)
_, err := Load()
os.Setenv("XDG_CONFIG_HOME", orig)
if err == nil || !strings.Contains(err.Error(), "tui.columns") {
t.Errorf("%s accepted: %v", bad, err)
}
}
}
+24 -2
View File
@@ -17,6 +17,9 @@ func (c *Config) ValidateNetBoxes() error {
if len(c.NetBoxes) > 0 && c.NetBox.URL != "" { if len(c.NetBoxes) > 0 && c.NetBox.URL != "" {
return fmt.Errorf("configure either netbox or netboxes, not both") return fmt.Errorf("configure either netbox or netboxes, not both")
} }
if c.NetBox.URL != "" && !validNetBoxURL(c.NetBox.URL) {
return fmt.Errorf("netbox.url %q must be an HTTP(S) URL without query or fragment", c.NetBox.URL)
}
seen := make(map[string]bool) seen := make(map[string]bool)
for _, source := range c.NetBoxes { for _, source := range c.NetBoxes {
if !instanceName.MatchString(source.Name) { if !instanceName.MatchString(source.Name) {
@@ -27,8 +30,7 @@ func (c *Config) ValidateNetBoxes() error {
return fmt.Errorf("duplicate NetBox instance name %q", source.Name) return fmt.Errorf("duplicate NetBox instance name %q", source.Name)
} }
seen[name] = true seen[name] = true
u, err := url.Parse(source.URL) if !validNetBoxURL(source.URL) {
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.RawQuery != "" || u.Fragment != "" {
return fmt.Errorf("NetBox %q requires an HTTP(S) URL without query or fragment", source.Name) return fmt.Errorf("NetBox %q requires an HTTP(S) URL without query or fragment", source.Name)
} }
if source.TokenVersion < 0 || source.TokenVersion > 2 { if source.TokenVersion < 0 || source.TokenVersion > 2 {
@@ -38,6 +40,12 @@ func (c *Config) ValidateNetBoxes() error {
return nil return nil
} }
// validNetBoxURL accepts base URLs that API paths can be appended to.
func validNetBoxURL(raw string) bool {
u, err := url.Parse(raw)
return err == nil && (u.Scheme == "http" || u.Scheme == "https") && u.Host != "" && u.RawQuery == "" && u.Fragment == ""
}
func (c *Config) HasNetBox() bool { return c.NetBox.URL != "" || len(c.NetBoxes) > 0 } func (c *Config) HasNetBox() bool { return c.NetBox.URL != "" || len(c.NetBoxes) > 0 }
// HasHosts reports whether netssh has anything to connect to: NetBox or static hosts. // HasHosts reports whether netssh has anything to connect to: NetBox or static hosts.
@@ -57,3 +65,17 @@ func (c *Config) CachePath() string {
sum := sha256.Sum256([]byte(strings.Join(identities, "\x00"))) sum := sha256.Sum256([]byte(strings.Join(identities, "\x00")))
return filepath.Join(filepath.Dir(c.Cache.Path), fmt.Sprintf("instances-%x", sum[:8]), filepath.Base(c.Cache.Path)) return filepath.Join(filepath.Dir(c.Cache.Path), fmt.Sprintf("instances-%x", sum[:8]), filepath.Base(c.Cache.Path))
} }
// HostLabel omits the configured instance prefix for display only. Callers
// must retain the canonical target for connections and handle label collisions.
func (c *Config) HostLabel(target string) string {
source, host, qualified := strings.Cut(target, "/")
if qualified {
for _, instance := range c.NetBoxes {
if instance.DisablePrefix && strings.EqualFold(instance.Name, source) {
return host
}
}
}
return target
}
+8
View File
@@ -15,6 +15,7 @@ func TestLoadNamedNetBoxes(t *testing.T) {
- name: Office - name: Office
url: https://office.example/netbox url: https://office.example/netbox
token: nbt_office token: nbt_office
disable_prefix: true
- name: lab - name: lab
url: https://lab.example url: https://lab.example
token: legacy-token token: legacy-token
@@ -34,7 +35,14 @@ cache:
if cfg.NetBox.URL != "" { if cfg.NetBox.URL != "" {
t.Fatal("legacy environment variables added an unnamed instance") t.Fatal("legacy environment variables added an unnamed instance")
} }
if !cfg.NetBoxes[0].DisablePrefix || cfg.NetBoxes[1].DisablePrefix {
t.Fatal("per-instance alias prefix setting was not loaded")
}
first := cfg.CachePath() first := cfg.CachePath()
cfg.NetBoxes[0].DisablePrefix = false
if cfg.CachePath() != first {
t.Fatal("alias prefix setting discarded cache")
}
if first == cfg.Cache.Path { if first == cfg.Cache.Path {
t.Fatal("named sources reuse legacy cache") t.Fatal("named sources reuse legacy cache")
} }
+101
View File
@@ -0,0 +1,101 @@
package config
import (
"fmt"
"strings"
"time"
)
type TUIConfig struct {
HistoryLimit int `mapstructure:"history_limit"`
// Columns selects what the TUI shows next to each hostname, in order;
// nil means DefaultTUIColumns. "reachability" enables the TCP check.
Columns []string `mapstructure:"columns"`
// ReachabilityTimeout is the probe timeout in milliseconds; 0 = 300.
ReachabilityTimeout int `mapstructure:"reachability_timeout"`
}
// TUIColumns are the values tui.columns accepts.
var TUIColumns = []string{"alias", "ip", "kind", "source", "status", "site", "location", "role", "platform", "tenant", "cluster", "tags", "reachability"}
// DefaultTUIColumns is the layout without tui.columns. The TCP reachability
// check is opt-in, since it opens connections to every listed host.
var DefaultTUIColumns = []string{"alias", "ip", "source", "status"}
// EffectiveColumns returns tui.columns, or the default layout.
func (t TUIConfig) EffectiveColumns() []string {
if t.Columns == nil {
return DefaultTUIColumns
}
return t.Columns
}
// ReachabilityEnabled reports whether the TUI probes listed hosts.
func (t TUIConfig) ReachabilityEnabled() bool {
for _, column := range t.EffectiveColumns() {
if column == "reachability" {
return true
}
}
return false
}
// ReachabilityTimeoutDuration returns tui.reachability_timeout, 300ms by default.
func (t TUIConfig) ReachabilityTimeoutDuration() time.Duration {
if t.ReachabilityTimeout <= 0 {
return 300 * time.Millisecond
}
return time.Duration(t.ReachabilityTimeout) * time.Millisecond
}
type ActivityConfig struct {
Enabled bool `mapstructure:"enabled"`
RetentionDays int `mapstructure:"retention_days"`
MaxEntries int `mapstructure:"max_entries"`
}
func (c *Config) ValidateOperations() error {
if c.TUI.HistoryLimit < 0 {
return fmt.Errorf("tui.history_limit must be >= 0 (0 = all)")
}
if c.Activity.RetentionDays < 0 || c.Activity.MaxEntries < 0 {
return fmt.Errorf("activity retention_days and max_entries must be >= 0")
}
seen := map[string]bool{}
for i, column := range c.TUI.Columns {
column = strings.ToLower(strings.TrimSpace(column))
c.TUI.Columns[i] = column
known := false
for _, valid := range TUIColumns {
known = known || column == valid
}
if !known {
return fmt.Errorf("tui.columns: unknown column %q; use %s", column, strings.Join(TUIColumns, ", "))
}
if seen[column] {
return fmt.Errorf("tui.columns: %q is listed twice", column)
}
seen[column] = true
}
if c.TUI.ReachabilityTimeout < 0 || c.TUI.ReachabilityTimeout > 10000 {
return fmt.Errorf("tui.reachability_timeout must be between 0 and 10000 milliseconds")
}
if c.Resolver.FallbackTimeout < 0 || c.Resolver.FallbackTimeout > 30000 {
return fmt.Errorf("resolver.fallback_timeout must be between 0 and 30000 milliseconds")
}
for _, status := range c.SSH.WarnStatus {
if strings.TrimSpace(status) == "" || strings.ContainsAny(status, " \t\n") {
return fmt.Errorf("ssh.warn_status: invalid status %q", status)
}
}
return nil
}
func (m SSHMatch) Matches(host SSHHost) bool { return m == (SSHMatch{}) || m.matches(host) }
func (c HostCommand) Allowed(host SSHHost) bool { return c.Match.Matches(host) }
func HookCommand(s string) string {
s = strings.TrimSpace(s)
if strings.EqualFold(s, "none") {
return ""
}
return s
}
+55
View File
@@ -0,0 +1,55 @@
package config
import (
"os"
"path/filepath"
"testing"
)
func TestOperationsDefaultsEnvironmentAndValidation(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := os.WriteFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml"), []byte("hosts:\n - name: router\n address: 192.0.2.1\n"), 0600); err != nil {
t.Fatal(err)
}
cfg, err := Load()
if err != nil {
t.Fatal(err)
}
if cfg.TUI.HistoryLimit != 10 || cfg.Activity.Enabled || cfg.Activity.RetentionDays != 30 || cfg.Activity.MaxEntries != 1000 {
t.Fatalf("%+v %+v", cfg.TUI, cfg.Activity)
}
t.Setenv("NETSSH_TUI_HISTORY_LIMIT", "25")
t.Setenv("NETSSH_SSH_POST_DISCONNECT", "echo done")
cfg, err = Load()
if err != nil || cfg.TUI.HistoryLimit != 25 || cfg.SSH.PostDisconnect != "echo done" {
t.Fatalf("%+v %v", cfg, err)
}
cfg.TUI.HistoryLimit = -1
if cfg.ValidateOperations() == nil {
t.Fatal("negative history accepted")
}
for _, timeout := range []string{"-1s", "0s", "invalid"} {
cfg.Commands = map[string]HostCommand{"check": {Args: []string{"echo", "{host}"}, Timeout: timeout}}
if cfg.ValidateCommands() == nil {
t.Fatalf("accepted %q", timeout)
}
}
}
func TestPostDisconnectLayering(t *testing.T) {
cfg := Config{
SSH: SSHConfig{SSHOptions: SSHOptions{PostDisconnect: "global"}, Rules: []SSHRule{{Match: SSHMatch{Tag: "lab"}, SSHOptions: SSHOptions{PostDisconnect: "none"}}}},
NetBoxes: []NetBoxConfig{{Name: "prod", SSH: SSHOptions{PostDisconnect: "instance"}}},
}
for _, tc := range []struct {
host SSHHost
want string
}{
{SSHHost{Name: "web"}, "global"},
{SSHHost{Name: "web", Instance: "prod"}, "instance"},
{SSHHost{Name: "web", Instance: "prod", Tags: []string{"lab"}}, ""},
} {
if got := HookCommand(cfg.SSHOptionsFor(tc.host).PostDisconnect); got != tc.want {
t.Fatalf("%q want %q", got, tc.want)
}
}
}
+96 -1
View File
@@ -24,6 +24,22 @@ type SSHOptions struct {
Options map[string]string `mapstructure:"options"` Options map[string]string `mapstructure:"options"`
// Forwards are named port forwards, selected with --forward or netssh tunnel. // Forwards are named port forwards, selected with --forward or netssh tunnel.
Forwards map[string]Forward `mapstructure:"forwards"` Forwards map[string]Forward `mapstructure:"forwards"`
// PreConnect is a shell command run locally before connecting; a non-zero
// exit aborts the connection. "none" disables a hook set by a broader layer.
PreConnect string `mapstructure:"pre_connect"`
PostDisconnect string `mapstructure:"post_disconnect"`
}
// PreConnectNone disables an inherited pre_connect hook.
const PreConnectNone = "none"
// PreConnectCommand returns the hook to run, or "" when none is configured.
func (o SSHOptions) PreConnectCommand() string {
command := strings.TrimSpace(o.PreConnect)
if strings.EqualFold(command, PreConnectNone) {
return ""
}
return command
} }
// Forward is one port forward; exactly one of the fields is set. // Forward is one port forward; exactly one of the fields is set.
@@ -78,6 +94,57 @@ type SSHMatch struct {
Instance string `mapstructure:"instance"` Instance string `mapstructure:"instance"`
Kind string `mapstructure:"kind"` Kind string `mapstructure:"kind"`
Name string `mapstructure:"name"` // shell-style glob, e.g. "*.dmz.example.com" Name string `mapstructure:"name"` // shell-style glob, e.g. "*.dmz.example.com"
// Site, Role, Platform and Tenant match the NetBox name or slug.
Site string `mapstructure:"site"`
Role string `mapstructure:"role"`
Platform string `mapstructure:"platform"`
Tenant string `mapstructure:"tenant"`
// Status matches the NetBox status value, e.g. active or offline.
Status string `mapstructure:"status"`
}
// Ref is a NetBox object referenced by a host, such as its site or platform.
type Ref struct {
Name string `json:"name,omitempty"`
Slug string `json:"slug,omitempty"`
}
// Matches compares want with the name or slug, ignoring case.
func (r Ref) Matches(want string) bool {
return want != "" && (strings.EqualFold(r.Name, want) || strings.EqualFold(r.Slug, want) || strings.EqualFold(tagSlug(r.Name), want))
}
// Key returns the slug, or the name when NetBox sent no slug.
func (r Ref) Key() string {
if r.Slug != "" {
return r.Slug
}
return r.Name
}
// LocationPath renders a host's place as "site › location › … › rack › U20",
// leaving out levels that are not set.
func LocationPath(site Ref, locations []Ref, rack, position string) string {
var parts []string
if site.Name != "" {
parts = append(parts, site.Name)
} else if site.Slug != "" {
parts = append(parts, site.Slug)
}
for _, location := range locations {
if location.Name != "" {
parts = append(parts, location.Name)
} else if location.Slug != "" {
parts = append(parts, location.Slug)
}
}
if rack != "" {
parts = append(parts, rack)
}
if position != "" {
parts = append(parts, "U"+position)
}
return strings.Join(parts, " › ")
} }
// SSHHost identifies the resolved host that SSH options are computed for. // SSHHost identifies the resolved host that SSH options are computed for.
@@ -86,6 +153,11 @@ type SSHHost struct {
Name string // NetBox name without the instance prefix Name string // NetBox name without the instance prefix
Kind string Kind string
Tags []string Tags []string
Status string
Site Ref
Role Ref
Platform Ref
Tenant Ref
} }
var sshOptionKey = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`) var sshOptionKey = regexp.MustCompile(`^[A-Za-z][A-Za-z0-9]*$`)
@@ -122,7 +194,7 @@ func (r SSHRule) Validate(scope string) error {
// Validate requires at least one selector and a well-formed name pattern. // Validate requires at least one selector and a well-formed name pattern.
func (m SSHMatch) Validate(scope string) error { func (m SSHMatch) Validate(scope string) error {
if m == (SSHMatch{}) { if m == (SSHMatch{}) {
return fmt.Errorf("%s: match must set at least one of tag, instance, kind, name", scope) return fmt.Errorf("%s: match must set at least one of tag, instance, kind, name, site, role, platform, tenant, status", scope)
} }
if _, err := path.Match(m.Name, ""); err != nil { if _, err := path.Match(m.Name, ""); err != nil {
return fmt.Errorf("%s: invalid name pattern %q", scope, m.Name) return fmt.Errorf("%s: invalid name pattern %q", scope, m.Name)
@@ -155,6 +227,12 @@ func (o SSHOptions) Validate(scope string) error {
return fmt.Errorf("%s.options: invalid option %q", scope, key) return fmt.Errorf("%s.options: invalid option %q", scope, key)
} }
} }
if strings.ContainsRune(o.PostDisconnect, 0) {
return fmt.Errorf("%s.post_disconnect must not contain NUL bytes", scope)
}
if strings.ContainsRune(o.PreConnect, 0) {
return fmt.Errorf("%s.pre_connect must not contain NUL bytes", scope)
}
for name, forward := range o.Forwards { for name, forward := range o.Forwards {
if !instanceName.MatchString(name) { if !instanceName.MatchString(name) {
return fmt.Errorf("%s.forwards: name %q must contain only letters, digits, underscores, or hyphens", scope, name) return fmt.Errorf("%s.forwards: name %q must contain only letters, digits, underscores, or hyphens", scope, name)
@@ -221,6 +299,12 @@ func (o SSHOptions) merge(override SSHOptions) SSHOptions {
if override.AddressFamily != "" { if override.AddressFamily != "" {
out.AddressFamily = override.AddressFamily out.AddressFamily = override.AddressFamily
} }
if strings.TrimSpace(override.PostDisconnect) != "" {
out.PostDisconnect = override.PostDisconnect
}
if strings.TrimSpace(override.PreConnect) != "" {
out.PreConnect = override.PreConnect
}
return out return out
} }
@@ -236,6 +320,17 @@ func (m SSHMatch) matches(host SSHHost) bool {
return false return false
} }
} }
for _, ref := range []struct {
want string
have Ref
}{{m.Site, host.Site}, {m.Role, host.Role}, {m.Platform, host.Platform}, {m.Tenant, host.Tenant}} {
if ref.want != "" && !ref.have.Matches(ref.want) {
return false
}
}
if m.Status != "" && !strings.EqualFold(m.Status, host.Status) {
return false
}
if m.Tag != "" { if m.Tag != "" {
found := false found := false
for _, tag := range host.Tags { for _, tag := range host.Tags {
+47
View File
@@ -210,3 +210,50 @@ func TestMultiConfig(t *testing.T) {
} }
} }
} }
func TestPreConnectLayeringAndNone(t *testing.T) {
cfg, err := loadYAML(t, `
netboxes:
- name: prod
url: https://prod.example.com
ssh:
pre_connect: vpn-up prod
- name: lab
url: https://lab.example.com
ssh:
pre_connect: check-vpn
rules:
- match: {tag: dmz}
pre_connect: none
`)
if err != nil {
t.Fatal(err)
}
for _, tc := range []struct {
host SSHHost
want string
}{
{SSHHost{Instance: "lab", Name: "web01"}, "check-vpn"},
{SSHHost{Instance: "prod", Name: "web01"}, "vpn-up prod"},
{SSHHost{Instance: "prod", Name: "gw", Tags: []string{"dmz"}}, ""},
} {
if got := cfg.SSHOptionsFor(tc.host).PreConnectCommand(); got != tc.want {
t.Errorf("%+v: got %q, want %q", tc.host, got, tc.want)
}
}
if err := (SSHOptions{PreConnect: "a\x00b"}).Validate("ssh"); err == nil {
t.Error("NUL byte in pre_connect accepted")
}
}
func TestPreConnectFromEnvironment(t *testing.T) {
t.Setenv("NETSSH_SSH_PRE_CONNECT", "true")
t.Setenv("NETSSH_SHORTCUTS_SHOW", "true")
cfg, err := loadYAML(t, "")
if err != nil {
t.Fatal(err)
}
if cfg.SSH.PreConnect != "true" || !cfg.Shortcuts.Show {
t.Fatalf("env not applied: pre_connect=%q show=%v", cfg.SSH.PreConnect, cfg.Shortcuts.Show)
}
}
+78 -5
View File
@@ -16,8 +16,9 @@ import (
// AliasEntry holds a single shell alias mapping. // AliasEntry holds a single shell alias mapping.
type AliasEntry struct { type AliasEntry struct {
Name string // short alias name (e.g. "web01") Command string // configured host command; empty means the default SSH alias
Host string // canonical NetBox hostname (e.g. "web01.example.com") Name string // short alias name (e.g. "web01")
Host string // canonical NetBox hostname (e.g. "web01.example.com")
} }
// AliasesPath returns the path for the bash/zsh aliases file. // AliasesPath returns the path for the bash/zsh aliases file.
@@ -51,7 +52,7 @@ func WriteAliasFiles(entries []AliasEntry) error {
writeFishAliasFile(entries) // best-effort — never blocks the caller on failure writeFishAliasFile(entries) // best-effort — never blocks the caller on failure
alias := "" alias := ""
for _, entry := range entries { for _, entry := range entries {
if entry.Host == "" { if entry.Host == "" && entry.Command == "" {
alias = entry.Name alias = entry.Name
break break
} }
@@ -94,6 +95,9 @@ func writeFishAliasFile(entries []AliasEntry) {
// Empty Host represents an alias for the netssh command itself. // Empty Host represents an alias for the netssh command itself.
func (e AliasEntry) Definition(shell string) string { func (e AliasEntry) Definition(shell string) string {
command := "netssh" command := "netssh"
if e.Command != "" {
command += " run " + shellQuote(e.Command, shell) + " --"
}
if e.Host != "" { if e.Host != "" {
host := e.Host host := e.Host
if !regexp.MustCompile(`^[a-zA-Z0-9_.:-]+$`).MatchString(host) { if !regexp.MustCompile(`^[a-zA-Z0-9_.:-]+$`).MatchString(host) {
@@ -124,14 +128,83 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
seen[cfg.Shell.Alias] = true seen[cfg.Shell.Alias] = true
out = append(out, AliasEntry{Name: cfg.Shell.Alias}) out = append(out, AliasEntry{Name: cfg.Shell.Alias})
} }
for _, e := range entries {
withoutPrefix := make(map[string]bool, len(cfg.NetBoxes))
for _, source := range cfg.NetBoxes {
withoutPrefix[strings.ToLower(source.Name)] = source.DisablePrefix
}
// Reserve canonical aliases as well as requested bare aliases before
// generating any output, so cache ordering cannot redirect a collision.
canonical := make(map[string]bool, len(entries))
counts := make(map[string]int, len(entries))
candidates := make([]string, len(entries))
for i, e := range entries {
name := shortcuts.AliasName(e.Name, cfg.Shortcuts) name := shortcuts.AliasName(e.Name, cfg.Shortcuts)
if seen[name] || name == "" || !regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`).MatchString(name) { canonical[name] = true
source, host, qualified := strings.Cut(e.Name, "/")
if qualified && withoutPrefix[strings.ToLower(source)] {
name = shortcuts.AliasName(host, cfg.Shortcuts)
}
candidates[i] = name
counts[name]++
}
validAlias := regexp.MustCompile(`^[a-zA-Z_][a-zA-Z0-9_-]*$`)
for i, e := range entries {
name := candidates[i]
full := shortcuts.AliasName(e.Name, cfg.Shortcuts)
if name != full && (counts[name] > 1 || canonical[name] || seen[name] || !validAlias.MatchString(name)) {
name = full
}
if seen[name] || name == "" || !validAlias.MatchString(name) {
continue continue
} }
seen[name] = true seen[name] = true
out = append(out, AliasEntry{Name: name, Host: e.Name}) out = append(out, AliasEntry{Name: name, Host: e.Name})
} }
// Build from the final SSH aliases, preserving per-instance prefix and
// collision handling. Never replace an existing SSH or command alias.
hostAliases := append([]AliasEntry(nil), out...)
hostMetadata := map[string]config.SSHHost{}
for _, e := range entries {
instance, hostname, ok := strings.Cut(e.Name, "/")
if !ok {
hostname = instance
instance = ""
}
hostMetadata[e.Name] = config.SSHHost{Instance: instance, Name: hostname, Kind: e.Kind, Tags: e.Tags}
}
var commands []string
for name := range cfg.Commands {
commands = append(commands, name)
}
sort.Strings(commands)
var candidatesForCommands []AliasEntry
commandCounts := make(map[string]int)
for _, name := range commands {
prefix := cfg.Commands[name].AliasPrefix
if prefix == "" {
continue
}
for _, host := range hostAliases {
if host.Host == "" {
continue
}
if !cfg.Commands[name].Allowed(hostMetadata[host.Host]) {
continue
}
alias := prefix + host.Name
commandCounts[alias]++
candidatesForCommands = append(candidatesForCommands, AliasEntry{Name: alias, Host: host.Host, Command: name})
}
}
for _, c := range candidatesForCommands {
if seen[c.Name] || commandCounts[c.Name] != 1 {
continue
}
seen[c.Name] = true
out = append(out, c)
}
return out return out
} }
+163
View File
@@ -2,6 +2,7 @@ package hook_test
import ( import (
"os" "os"
"os/exec"
"path/filepath" "path/filepath"
"strings" "strings"
"testing" "testing"
@@ -253,3 +254,165 @@ func TestAliasesUseRewriteRules(t *testing.T) {
t.Fatalf("entries: %+v", entries) t.Fatalf("entries: %+v", entries)
} }
} }
func TestAliasesOptionalInstancePrefix(t *testing.T) {
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{
{Name: "OFFICE", DisablePrefix: true},
{Name: "lab"},
},
Shortcuts: config.ShortcutsConfig{
Domains: []string{".example.com"},
Rewrites: []config.ShortcutRewrite{{Pattern: "^web-", Replace: "app"}},
},
}
entries := hook.BuildAliasEntries([]cache.Entry{
{Name: "office/web-01.example.com"},
{Name: "lab/web-01.example.com"},
}, cfg)
got := map[string]string{}
for _, e := range entries {
got[e.Name] = e.Host
// Both output formats must keep the fully qualified destination.
for _, shell := range []string{"bash", "zsh", "fish"} {
if !strings.Contains(e.Definition(shell), e.Host) {
t.Fatalf("%s alias lost its target: %s", shell, e.Definition(shell))
}
}
}
if len(got) != 2 || got["app01"] != "office/web-01.example.com" || got["lab_app01"] != "lab/web-01.example.com" {
t.Fatalf("unexpected aliases: %+v", entries)
}
}
func TestAliasesWithoutPrefixCollisions(t *testing.T) {
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{
{Name: "office", DisablePrefix: true},
{Name: "lab", DisablePrefix: true},
},
Shell: config.ShellConfig{Alias: "j"},
Shortcuts: config.ShortcutsConfig{Domains: []string{".example.com"}},
}
for _, tc := range []struct {
name string
hosts []string
want map[string]string
}{
{"two instances", []string{"office/web.example.com", "lab/web.example.com"},
map[string]string{"j": "", "office_web": "office/web.example.com", "lab_web": "lab/web.example.com"}},
{"static host", []string{"office/web.example.com", "web"},
map[string]string{"j": "", "office_web": "office/web.example.com", "web": "web"}},
{"command aliases", []string{"office/j", "office/netssh"},
map[string]string{"j": "", "office_j": "office/j", "office_netssh": "office/netssh"}},
{"reserved qualified alias", []string{"office/lab_web", "lab/web"},
map[string]string{"j": "", "office_lab_web": "office/lab_web", "web": "lab/web"}},
{"invalid bare alias", []string{"office/123.example.com"},
map[string]string{"j": "", "office_123": "office/123.example.com"}},
{"normalized names", []string{"office/web.example.com", "office/web"},
map[string]string{"j": "", "office_web": "office/web"}},
} {
t.Run(tc.name, func(t *testing.T) {
var input []cache.Entry
for _, host := range tc.hosts {
input = append(input, cache.Entry{Name: host})
}
entries := hook.BuildAliasEntries(input, cfg)
if len(entries) != len(tc.want) {
t.Fatalf("aliases: %+v, want %+v", entries, tc.want)
}
for _, e := range entries {
if host, ok := tc.want[e.Name]; !ok || host != e.Host {
t.Fatalf("unexpected alias: %+v", e)
}
}
})
}
}
func TestCustomCommandAliases(t *testing.T) {
cfg := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "office", DisablePrefix: true}},
Shortcuts: config.ShortcutsConfig{Rewrites: []config.ShortcutRewrite{{Pattern: "^xzi-groß", Replace: "xg"}}},
Commands: map[string]config.HostCommand{
"mtr": {AliasPrefix: "m", Args: []string{"mtr", "{address}"}},
"ping": {AliasPrefix: "p", Args: []string{"ping", "{address}"}},
"manual": {Args: []string{"echo", "{host}"}},
},
}
entries := hook.BuildAliasEntries([]cache.Entry{{Name: "office/xzi-groß1", IP: "10.0.0.1"}}, cfg)
got := map[string]hook.AliasEntry{}
for _, e := range entries {
got[e.Name] = e
}
if len(entries) != 3 || got["mxg1"].Command != "mtr" || got["pxg1"].Command != "ping" {
t.Fatalf("unexpected aliases: %+v", entries)
}
if got["mxg1"].Host != "office/xzi-groß1" {
t.Fatal("instance lost")
}
for _, shell := range []string{"bash", "zsh", "fish"} {
def := got["mxg1"].Definition(shell)
if !strings.Contains(def, "netssh run") || !strings.Contains(def, "office/xzi-groß1") || strings.Contains(def, "10.0.0.1") {
t.Fatalf("%s alias must resolve at invocation: %s", shell, def)
}
}
}
func TestCustomCommandAliasesPreserveExistingNames(t *testing.T) {
cfg := config.Config{
Shell: config.ShellConfig{Alias: "mfoo"},
Commands: map[string]config.HostCommand{
"mtr": {AliasPrefix: "m", Args: []string{"mtr", "{address}"}},
"ping": {AliasPrefix: "mp", Args: []string{"ping", "{address}"}},
},
}
entries := hook.BuildAliasEntries([]cache.Entry{
{Name: "foo"}, {Name: "web"}, {Name: "mweb"}, {Name: "x"}, {Name: "px"},
}, cfg)
for _, e := range entries {
if e.Name == "mfoo" && (e.Host != "" || e.Command != "") {
t.Fatal("command alias overwritten")
}
if e.Name == "mweb" && (e.Host != "mweb" || e.Command != "") {
t.Fatal("SSH alias overwritten")
}
if e.Name == "mpx" {
t.Fatal("ambiguous custom alias generated")
}
}
}
func TestCustomAliasShellArgumentQuoting(t *testing.T) {
dir := t.TempDir()
if err := os.WriteFile(filepath.Join(dir, "netssh"), []byte("#!/bin/sh\nprintf '%s\\n' \"$@\"\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
entry := hook.AliasEntry{Name: "mxg1", Host: "office/xzi-groß1'$(oops)", Command: "mtr"}
for _, shell := range []string{"bash", "zsh", "fish"} {
t.Run(shell, func(t *testing.T) {
path, err := exec.LookPath(shell)
if err != nil {
t.Skip("shell not installed")
}
// A separate parse models invoking an alias after sourcing the file.
script := entry.Definition(shell) + "\neval 'mxg1 --report'\n"
args := []string{"-c", script}
if shell == "bash" {
args = []string{"--noprofile", "--norc", "-O", "expand_aliases", "-c", script}
}
if shell == "zsh" {
args = []string{"-f", "-c", script}
}
if shell == "fish" {
args = []string{"--no-config", "-c", script}
}
out, err := exec.Command(path, args...).CombinedOutput()
want := "run\nmtr\n--\n" + entry.Host + "\n--report\n"
if err != nil || string(out) != want {
t.Fatalf("%q (%v), want %q", out, err, want)
}
})
}
}
+37 -1
View File
@@ -18,6 +18,7 @@ type fake struct {
syncState string syncState string
keys map[string]string // existing prefix bindings by key keys map[string]string // existing prefix bindings by key
solo string solo string
prefix string
n int n int
} }
@@ -33,6 +34,8 @@ func (f *fake) Output(argv ...string) (string, error) {
f.calls = append(f.calls, strings.Join(argv, " ")) f.calls = append(f.calls, strings.Join(argv, " "))
f.n++ f.n++
switch argv[1] { switch argv[1] {
case "show-options":
return f.prefix, nil
case "new-window", "new-session": case "new-window", "new-session":
return fmt.Sprintf("@%d %%%d", f.n, f.n), nil return fmt.Sprintf("@%d %%%d", f.n, f.n), nil
case "split-window": case "split-window":
@@ -121,6 +124,8 @@ func TestTmuxInside(t *testing.T) {
"tmux list-keys -T prefix S", "tmux list-keys -T prefix S",
"tmux list-keys -T prefix e", "tmux list-keys -T prefix e",
"tmux source-file /tmp/l/netssh-multi.tmux.conf", "tmux source-file /tmp/l/netssh-multi.tmux.conf",
"tmux set-window-option -t @1 @netssh_keys keys: Ctrl+b then S: sync on/off | Ctrl+b then e: solo on/off",
"tmux set-window-option -t @1 pane-border-format #{@netssh_host}#{?pane_synchronized, [SYNC],#{?@netssh_solo, [SOLO],}} #{?pane_active, | #{@netssh_keys},} ",
"tmux select-window -t @1", "tmux select-window -t @1",
} }
if strings.Join(f.calls, "\n") != strings.Join(want, "\n") { if strings.Join(f.calls, "\n") != strings.Join(want, "\n") {
@@ -234,7 +239,7 @@ func TestTmuxKeyBindings(t *testing.T) {
t.Errorf("conf lacks %q:\n%s", want, conf) t.Errorf("conf lacks %q:\n%s", want, conf)
} }
} }
if hint != "keys: C-b S broadcast to all panes, C-b e exclude/include this pane" { if hint != "keys: Ctrl+b then S: sync on/off | Ctrl+b then e: solo on/off" {
t.Errorf("hint %q", hint) t.Errorf("hint %q", hint)
} }
@@ -279,3 +284,34 @@ func TestToggleSyncPane(t *testing.T) {
t.Fatalf("zellij: %v", err) t.Fatalf("zellij: %v", err)
} }
} }
func TestTmuxPersistentHints(t *testing.T) {
for _, tc := range []struct {
name string
keys map[string]string
want string
}{
{"custom prefix", nil, "keys: Ctrl+a then Ctrl+s: sync on/off | Ctrl+a then e: solo on/off"},
{"occupied key", map[string]string{"C-s": "bind-key -T prefix C-s display-time"}, "keys: Ctrl+a then e: solo on/off; C-a C-s kept your own binding (use netssh sync)"},
} {
t.Run(tc.name, func(t *testing.T) {
f := newFake(nil, "tmux")
f.prefix, f.keys = "C-a", tc.keys
if err := Open(Tmux, panes("a", "b"), Options{PerWindow: 1, SyncKey: "C-s", SoloKey: "e"}, f); err != nil {
t.Fatal(err)
}
n := 0
for _, call := range f.calls {
if strings.Contains(call, " @netssh_keys ") {
n++
if !strings.HasSuffix(call, " @netssh_keys "+tc.want) {
t.Fatalf("wrong persistent hint: %s", call)
}
}
}
if n != 2 {
t.Fatalf("hints installed in %d windows, want 2", n)
}
})
}
}
+23 -4
View File
@@ -27,6 +27,7 @@ func openTmux(panes []Pane, opts Options, r Runner) error {
} }
groups := chunks(panes, opts.PerWindow) groups := chunks(panes, opts.PerWindow)
first := "" first := ""
var windows []string
for i, group := range groups { for i, group := range groups {
name := windowLabel(opts.Label, i, len(groups)) name := windowLabel(opts.Label, i, len(groups))
format := []string{"-P", "-F", "#{window_id} #{pane_id}", "-n", name} format := []string{"-P", "-F", "#{window_id} #{pane_id}", "-n", name}
@@ -52,6 +53,7 @@ func openTmux(panes []Pane, opts Options, r Runner) error {
} }
} }
window, pane, _ := strings.Cut(out, " ") window, pane, _ := strings.Cut(out, " ")
windows = append(windows, window)
if first == "" { if first == "" {
first = window first = window
} }
@@ -91,6 +93,17 @@ func openTmux(panes []Pane, opts Options, r Runner) error {
} }
if keys != "" { if keys != "" {
opts.Hint(keys) opts.Hint(keys)
// Window-local hints remain visible after attaching, including in an
// existing session. Keep other windows and the user's status bar intact.
for _, window := range windows {
if _, err := r.Output("tmux", "set-window-option", "-t", window, "@netssh_keys", keys); err != nil {
return err
}
if _, err := r.Output("tmux", "set-window-option", "-t", window, "pane-border-format",
" #{@netssh_host}#{?pane_synchronized, [SYNC],#{?@netssh_solo, [SOLO],}} #{?pane_active, | #{@netssh_keys},} "); err != nil {
return err
}
}
} }
if inside { if inside {
_, err := r.Output("tmux", "select-window", "-t", first) _, err := r.Output("tmux", "select-window", "-t", first)
@@ -149,8 +162,8 @@ func bindKeys(r Runner, opts Options) (string, error) {
var conf strings.Builder var conf strings.Builder
var hints, taken []string var hints, taken []string
for _, key := range []struct{ key, binding, what string }{ for _, key := range []struct{ key, binding, what string }{
{opts.SyncKey, syncBinding, "broadcast to all panes"}, {opts.SyncKey, syncBinding, "sync on/off"},
{opts.SoloKey, soloBinding, "exclude/include this pane"}, {opts.SoloKey, soloBinding, "solo on/off"},
} { } {
if key.key == "" { if key.key == "" {
continue continue
@@ -161,7 +174,7 @@ func bindKeys(r Runner, opts Options) (string, error) {
continue continue
} }
fmt.Fprintf(&conf, key.binding, key.key) fmt.Fprintf(&conf, key.binding, key.key)
hints = append(hints, prefix+" "+key.key+" "+key.what) hints = append(hints, displayKey(prefix)+" then "+displayKey(key.key)+": "+key.what)
} }
if conf.Len() > 0 { if conf.Len() > 0 {
path := filepath.Join(opts.LayoutDir, "netssh-multi.tmux.conf") path := filepath.Join(opts.LayoutDir, "netssh-multi.tmux.conf")
@@ -172,7 +185,7 @@ func bindKeys(r Runner, opts Options) (string, error) {
return "", err return "", err
} }
} }
hint := "keys: " + strings.Join(hints, ", ") hint := "keys: " + strings.Join(hints, " | ")
if len(hints) == 0 { if len(hints) == 0 {
hint = "toggle broadcast with: netssh sync, netssh sync --pane" hint = "toggle broadcast with: netssh sync, netssh sync --pane"
} }
@@ -192,3 +205,9 @@ func freeSession(r Runner, name string) string {
candidate = name + "-" + strconv.Itoa(n) candidate = name + "-" + strconv.Itoa(n)
} }
} }
// displayKey expands tmux's modifier notation for the on-screen legend.
func displayKey(key string) string {
key = strings.ReplaceAll(key, "C-", "Ctrl+")
return strings.ReplaceAll(key, "M-", "Alt+")
}
+68 -24
View File
@@ -12,6 +12,8 @@ import (
"strings" "strings"
"sync" "sync"
"time" "time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
) )
type Client struct { type Client struct {
@@ -20,6 +22,9 @@ type Client struct {
token string token string
tokenVersion int tokenVersion int
httpClient *http.Client httpClient *http.Client
locMu sync.Mutex
locations map[int]locationNode // location ID → name and parent, per client
} }
// NewClient creates a NetBox API client. Pass tokenVersion=0 to auto-detect // NewClient creates a NetBox API client. Pass tokenVersion=0 to auto-detect
@@ -176,24 +181,32 @@ func (c *Client) GetIPs(ctx context.Context, entry HostEntry) ([]string, error)
} }
return source.GetIPs(ctx, host) return source.GetIPs(ctx, host)
} }
var apiURL string
switch entry.Kind { switch entry.Kind {
case "device": case "device":
apiURL = fmt.Sprintf("%s/api/ipam/ip-addresses/?device_id=%d&limit=100", c.baseURL, entry.ID) return c.fetchAllIPs(ctx, fmt.Sprintf("device_id=%d", entry.ID))
case "vm": case "vm":
apiURL = fmt.Sprintf("%s/api/ipam/ip-addresses/?virtual_machine_id=%d&limit=100", c.baseURL, entry.ID) return c.fetchAllIPs(ctx, fmt.Sprintf("virtual_machine_id=%d", entry.ID))
default:
return nil, fmt.Errorf("unknown host kind: %q", entry.Kind)
} }
return nil, fmt.Errorf("unknown host kind: %q", entry.Kind)
}
var resp netboxIPListResponse // fetchAllIPs pages through the IP addresses matching filterParams, so hosts
if err := c.get(ctx, apiURL, &resp); err != nil { // with more addresses than one page do not lose their management address.
return nil, err func (c *Client) fetchAllIPs(ctx context.Context, filterParams string) ([]string, error) {
} const pageSize = 100
var ips []string
ips := make([]string, 0, len(resp.Results)) for offset := 0; ; offset += pageSize {
for _, r := range resp.Results { apiURL := fmt.Sprintf("%s/api/ipam/ip-addresses/?%s&limit=%d&offset=%d", c.baseURL, filterParams, pageSize, offset)
ips = append(ips, stripPrefix(r.Address)) var resp netboxIPListResponse
if err := c.get(ctx, apiURL, &resp); err != nil {
return nil, err
}
for _, r := range resp.Results {
ips = append(ips, stripPrefix(r.Address))
}
if len(resp.Results) < pageSize || len(ips) >= resp.Count {
break
}
} }
return ips, nil return ips, nil
} }
@@ -203,16 +216,7 @@ func (c *Client) GetIPsWithFilter(ctx context.Context, filterParams string) ([]s
if c.sources != nil { if c.sources != nil {
return nil, fmt.Errorf("IP filters require a host instance; use GetIPsWithFilterForHost") return nil, fmt.Errorf("IP filters require a host instance; use GetIPsWithFilterForHost")
} }
apiURL := fmt.Sprintf("%s/api/ipam/ip-addresses/?%s&limit=100", c.baseURL, filterParams) return c.fetchAllIPs(ctx, filterParams)
var resp netboxIPListResponse
if err := c.get(ctx, apiURL, &resp); err != nil {
return nil, err
}
ips := make([]string, 0, len(resp.Results))
for _, r := range resp.Results {
ips = append(ips, stripPrefix(r.Address))
}
return ips, nil
} }
func (c *Client) searchDevices(ctx context.Context, query, tag string) ([]HostEntry, error) { func (c *Client) searchDevices(ctx context.Context, query, tag string) ([]HostEntry, error) {
@@ -228,6 +232,7 @@ func (c *Client) searchDevices(ctx context.Context, query, tag string) ([]HostEn
for _, d := range resp.Results { for _, d := range resp.Results {
entries = append(entries, deviceToEntry(d)) entries = append(entries, deviceToEntry(d))
} }
c.fillLocations(ctx, entries)
return entries, nil return entries, nil
} }
@@ -279,6 +284,7 @@ func (c *Client) fetchAllDevices(ctx context.Context, query, filters string) ([]
break break
} }
} }
c.fillLocations(ctx, all)
return all, nil return all, nil
} }
@@ -348,7 +354,7 @@ func (c *Client) request(ctx context.Context, method, apiURL string, body io.Rea
} }
if resp.StatusCode != http.StatusOK { if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("netbox returned %d for %s", resp.StatusCode, apiURL) return "", &StatusError{Code: resp.StatusCode, URL: apiURL}
} }
if err := json.NewDecoder(resp.Body).Decode(out); err != nil { if err := json.NewDecoder(resp.Body).Decode(out); err != nil {
@@ -371,6 +377,20 @@ func deviceToEntry(d netboxDevice) HostEntry {
if d.Cluster != nil { if d.Cluster != nil {
e.Cluster = d.Cluster.Name e.Cluster = d.Cluster.Name
} }
e.Status = d.Status.value()
e.Site, e.Platform, e.Tenant = d.Site.ref(), d.Platform.ref(), d.Tenant.ref()
e.Role = d.Role.ref()
if d.Role == nil {
e.Role = d.DeviceRole.ref()
}
if d.Location != nil {
e.locationID = d.Location.ID
e.Location = []config.Ref{{Name: d.Location.Name, Slug: d.Location.Slug}}
}
if d.Rack != nil {
e.Rack = d.Rack.Name
}
e.Position = rackUnit(d.Position)
return e return e
} }
@@ -388,6 +408,20 @@ func vmToEntry(v netboxVM) HostEntry {
if v.Cluster != nil { if v.Cluster != nil {
e.Cluster = v.Cluster.Name e.Cluster = v.Cluster.Name
} }
e.Status = v.Status.value()
e.Site, e.Platform, e.Tenant = v.Site.ref(), v.Platform.ref(), v.Tenant.ref()
e.Role = v.Role.ref()
if v.Role == nil {
e.Role = v.DeviceRole.ref()
}
if v.Location != nil {
e.locationID = v.Location.ID
e.Location = []config.Ref{{Name: v.Location.Name, Slug: v.Location.Slug}}
}
if v.Rack != nil {
e.Rack = v.Rack.Name
}
e.Position = rackUnit(v.Position)
return e return e
} }
@@ -399,6 +433,16 @@ func stripPrefix(cidr string) string {
return cidr return cidr
} }
// StatusError is an unexpected HTTP status from NetBox.
type StatusError struct {
Code int
URL string
}
func (e *StatusError) Error() string {
return fmt.Sprintf("netbox returned %d for %s", e.Code, e.URL)
}
// ErrHostNotFound distinguishes a missing exact match from API failures or ambiguity. // ErrHostNotFound distinguishes a missing exact match from API failures or ambiguity.
var ErrHostNotFound = errors.New("host not found") var ErrHostNotFound = errors.New("host not found")
+45
View File
@@ -3,8 +3,11 @@ package netbox
import ( import (
"context" "context"
"encoding/json" "encoding/json"
"errors"
"fmt"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"strconv"
"strings" "strings"
"testing" "testing"
) )
@@ -499,3 +502,45 @@ func TestCommentConflictIsReported(t *testing.T) {
t.Fatal("conflict ignored") t.Fatal("conflict ignored")
} }
} }
// Hosts with more addresses than one page must not lose the later ones.
func TestGetIPs_Paginates(t *testing.T) {
const total = 230
var offsets []string
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
offsets = append(offsets, r.URL.Query().Get("offset"))
offset, _ := strconv.Atoi(r.URL.Query().Get("offset"))
limit, _ := strconv.Atoi(r.URL.Query().Get("limit"))
var addrs []string
for i := offset; i < offset+limit && i < total; i++ {
addrs = append(addrs, fmt.Sprintf("10.0.%d.%d/24", i/250, i%250+1))
}
resp := ipListResponse(addrs...)
resp.Count = total
json.NewEncoder(w).Encode(resp)
}))
defer srv.Close()
ips, err := NewClient(srv.URL, "token", 0).GetIPs(context.Background(), HostEntry{ID: 1, Kind: "device"})
if err != nil {
t.Fatalf("GetIPs: %v", err)
}
if len(ips) != total || ips[total-1] != "10.0.0.230" {
t.Errorf("got %d IPs (last %q), want %d", len(ips), ips[len(ips)-1], total)
}
if strings.Join(offsets, ",") != "0,100,200" {
t.Errorf("offsets %v, want 0,100,200", offsets)
}
}
func TestRequest_StatusErrorCarriesCode(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
}))
defer srv.Close()
_, err := NewClient(srv.URL, "token", 0).GetIPsWithFilter(context.Background(), "device_id=1&interface=nope")
var status *StatusError
if !errors.As(err, &status) || status.Code != http.StatusBadRequest {
t.Fatalf("got %v, want a StatusError with code 400", err)
}
}
+365
View File
@@ -0,0 +1,365 @@
package netbox
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/url"
"sort"
"strconv"
"strings"
)
// HostDetails is everything netssh info shows about a device or VM.
type HostDetails struct {
HostEntry
URL string `json:"url"`
StatusLabel string `json:"status_label,omitempty"`
HeightU string `json:"height_u,omitempty"` // rack units the device occupies
Face string `json:"face,omitempty"` // front | rear
DeviceType string `json:"device_type,omitempty"`
Serial string `json:"serial,omitempty"`
AssetTag string `json:"asset_tag,omitempty"`
Description string `json:"description,omitempty"`
VCPUs string `json:"vcpus,omitempty"`
MemoryMB int `json:"memory_mb,omitempty"`
DiskGB int `json:"disk_gb,omitempty"`
IPs []IPAssignment `json:"ips"`
}
// IPAssignment is one IP address of a host with the interface it is on.
type IPAssignment struct {
Address string `json:"address"` // CIDR notation
Interface string `json:"interface,omitempty"`
DNSName string `json:"dns_name,omitempty"`
Status string `json:"status,omitempty"`
Role string `json:"role,omitempty"`
VRF string `json:"vrf,omitempty"`
Primary bool `json:"primary,omitempty"`
}
// IPOwner is a NetBox IP address found by LookupIP, with the host and
// interface it is assigned to.
type IPOwner struct {
Source string `json:"instance,omitempty"`
Address string `json:"address"`
Status string `json:"status,omitempty"`
DNSName string `json:"dns_name,omitempty"`
Description string `json:"description,omitempty"`
VRF string `json:"vrf,omitempty"`
Interface string `json:"interface,omitempty"`
HostKind string `json:"kind,omitempty"` // device | vm; empty when unassigned
HostName string `json:"host,omitempty"`
HostID int `json:"host_id,omitempty"`
}
// Target returns the selector of the owning host, or "" when unassigned.
func (o IPOwner) Target() string {
if o.HostName == "" {
return ""
}
return HostEntry{Source: o.Source, Name: o.HostName}.Target()
}
// PrefixInfo is a NetBox prefix that contains an address.
type PrefixInfo struct {
Source string `json:"instance,omitempty"`
Prefix string `json:"prefix"`
Status string `json:"status,omitempty"`
Role string `json:"role,omitempty"`
Site string `json:"site,omitempty"`
VLAN string `json:"vlan,omitempty"`
VRF string `json:"vrf,omitempty"`
Description string `json:"description,omitempty"`
}
type netboxHostDetail struct {
netboxDevice
Face *netboxStatus `json:"face"`
Serial string `json:"serial"`
AssetTag *string `json:"asset_tag"`
DeviceType *struct {
ID int `json:"id"`
Model string `json:"model"`
Manufacturer *netboxRef `json:"manufacturer"`
} `json:"device_type"`
Description string `json:"description"`
VCPUs json.Number `json:"vcpus"`
Memory *int `json:"memory"`
Disk *int `json:"disk"`
}
type netboxIPAddress struct {
Address string `json:"address"`
Status *netboxStatus `json:"status"`
Role *netboxStatus `json:"role"`
DNSName string `json:"dns_name"`
Description string `json:"description"`
VRF *netboxRef `json:"vrf"`
ObjectType string `json:"assigned_object_type"`
Object *struct {
Name string `json:"name"`
Device *struct {
ID int `json:"id"`
Name string `json:"name"`
} `json:"device"`
VirtualMachine *struct {
ID int `json:"id"`
Name string `json:"name"`
} `json:"virtual_machine"`
} `json:"assigned_object"`
}
type netboxPrefix struct {
Prefix string `json:"prefix"`
Status *netboxStatus `json:"status"`
Role *netboxRef `json:"role"`
Site *netboxRef `json:"site"`
Scope *netboxRef `json:"scope"`
VRF *netboxRef `json:"vrf"`
Description string `json:"description"`
VLAN *struct {
VID int `json:"vid"`
Name string `json:"name"`
} `json:"vlan"`
}
func hostPath(kind string) (string, error) {
switch kind {
case "device":
return "dcim/devices", nil
case "vm":
return "virtualization/virtual-machines", nil
}
return "", fmt.Errorf("invalid host kind %q", kind)
}
// WebURL returns the page of a host in the NetBox web interface.
func (c *Client) WebURL(host HostEntry) (string, error) {
source, host, err := c.sourceForHost(host)
if err != nil {
return "", err
}
path, err := hostPath(host.Kind)
if err != nil {
return "", err
}
if host.ID <= 0 {
return "", fmt.Errorf("NetBox ID of %s is unknown", host.Target())
}
return fmt.Sprintf("%s/%s/%d/", source.baseURL, path, host.ID), nil
}
// GetDetails fetches the full record and all IP addresses of a host.
func (c *Client) GetDetails(ctx context.Context, host HostEntry) (HostDetails, error) {
source, host, err := c.sourceForHost(host)
if err != nil {
return HostDetails{}, err
}
apiURL, err := source.hostURL(host)
if err != nil {
return HostDetails{}, err
}
var raw netboxHostDetail
if err := source.get(ctx, apiURL, &raw); err != nil {
return HostDetails{}, err
}
entry := deviceToEntry(raw.netboxDevice)
entry.Kind, entry.Source = host.Kind, host.Source
entries := []HostEntry{entry}
source.fillLocations(ctx, entries)
entry = entries[0]
d := HostDetails{HostEntry: entry, Serial: raw.Serial, Description: raw.Description}
d.URL, _ = c.WebURL(entry)
if raw.Status != nil {
d.StatusLabel = raw.Status.Label
}
if raw.Face != nil {
d.Face = raw.Face.Value
}
if raw.AssetTag != nil {
d.AssetTag = *raw.AssetTag
}
if raw.DeviceType != nil && entry.Position != "" && raw.DeviceType.ID > 0 {
var deviceType struct {
UHeight json.Number `json:"u_height"`
}
if err := source.get(ctx, fmt.Sprintf("%s/api/dcim/device-types/%d/", source.baseURL, raw.DeviceType.ID), &deviceType); err == nil {
d.HeightU = rackUnit(deviceType.UHeight)
}
}
if raw.DeviceType != nil {
d.DeviceType = raw.DeviceType.Model
if raw.DeviceType.Manufacturer != nil && raw.DeviceType.Manufacturer.Name != "" {
d.DeviceType = raw.DeviceType.Manufacturer.Name + " " + d.DeviceType
}
}
if raw.VCPUs != "" {
d.VCPUs = strings.TrimSuffix(strings.TrimSuffix(raw.VCPUs.String(), ".00"), ".0")
}
if raw.Memory != nil {
d.MemoryMB = *raw.Memory
}
if raw.Disk != nil {
d.DiskGB = *raw.Disk
}
filter := fmt.Sprintf("device_id=%d", host.ID)
if host.Kind == "vm" {
filter = fmt.Sprintf("virtual_machine_id=%d", host.ID)
}
addresses, err := source.fetchIPAddresses(ctx, filter)
if err != nil {
return d, fmt.Errorf("IP addresses: %w", err)
}
for _, a := range addresses {
ip := IPAssignment{Address: a.Address, DNSName: a.DNSName, Status: a.Status.value(), Role: a.Role.value()}
if a.VRF != nil {
ip.VRF = a.VRF.Name
}
if a.Object != nil {
ip.Interface = a.Object.Name
}
addr := stripPrefix(a.Address)
ip.Primary = addr == entry.PrimaryIP4 || addr == entry.PrimaryIP6
d.IPs = append(d.IPs, ip)
}
sort.SliceStable(d.IPs, func(i, j int) bool {
if d.IPs[i].Primary != d.IPs[j].Primary {
return d.IPs[i].Primary
}
return d.IPs[i].Interface < d.IPs[j].Interface
})
return d, nil
}
func (c *Client) fetchIPAddresses(ctx context.Context, filter string) ([]netboxIPAddress, error) {
const pageSize = 100
var out []netboxIPAddress
for offset := 0; ; offset += pageSize {
apiURL := fmt.Sprintf("%s/api/ipam/ip-addresses/?%s&limit=%d&offset=%d", c.baseURL, filter, pageSize, offset)
var resp netboxListResponse[netboxIPAddress]
if err := c.get(ctx, apiURL, &resp); err != nil {
return nil, err
}
out = append(out, resp.Results...)
if len(resp.Results) < pageSize || len(out) >= resp.Count {
return out, nil
}
}
}
// eachSource runs fn for every configured instance in name order, or once
// for a single-instance client. It keeps going after an error, so one
// unreachable instance does not hide answers from the others.
func (c *Client) eachSource(fn func(name string, source *Client) error) error {
if c.sources == nil {
return fn("", c)
}
names := make([]string, 0, len(c.sources))
for name := range c.sources {
names = append(names, name)
}
sort.Strings(names)
var errs []error
for _, name := range names {
if err := fn(name, c.sources[name]); err != nil {
errs = append(errs, fmt.Errorf("NetBox %s: %w", name, err))
}
}
return errors.Join(errs...)
}
// LookupIP finds the NetBox IP address records of ip in every instance.
func (c *Client) LookupIP(ctx context.Context, ip string) ([]IPOwner, error) {
var out []IPOwner
err := c.eachSource(func(name string, source *Client) error {
found, err := source.fetchIPAddresses(ctx, "address="+url.QueryEscape(ip))
if err != nil {
return err
}
for _, a := range found {
owner := IPOwner{Source: name, Address: a.Address, Status: a.Status.value(), DNSName: a.DNSName, Description: a.Description}
if a.VRF != nil {
owner.VRF = a.VRF.Name
}
if a.Object != nil {
owner.Interface = a.Object.Name
switch {
case a.Object.Device != nil:
owner.HostKind, owner.HostName, owner.HostID = "device", a.Object.Device.Name, a.Object.Device.ID
case a.Object.VirtualMachine != nil:
owner.HostKind, owner.HostName, owner.HostID = "vm", a.Object.VirtualMachine.Name, a.Object.VirtualMachine.ID
}
}
out = append(out, owner)
}
return nil
})
return out, err
}
// PrefixesContaining returns the prefixes containing ip, most specific last.
func (c *Client) PrefixesContaining(ctx context.Context, ip string) ([]PrefixInfo, error) {
var out []PrefixInfo
err := c.eachSource(func(name string, source *Client) error {
apiURL := fmt.Sprintf("%s/api/ipam/prefixes/?contains=%s&limit=100", source.baseURL, url.QueryEscape(ip))
var resp netboxListResponse[netboxPrefix]
if err := source.get(ctx, apiURL, &resp); err != nil {
return err
}
for _, p := range resp.Results {
info := PrefixInfo{Source: name, Prefix: p.Prefix, Status: p.Status.value(), Description: p.Description}
if p.Role != nil {
info.Role = p.Role.Name
}
if p.Site != nil {
info.Site = p.Site.Name
} else if p.Scope != nil {
info.Site = p.Scope.Name
}
if p.VRF != nil {
info.VRF = p.VRF.Name
}
if p.VLAN != nil {
info.VLAN = strconv.Itoa(p.VLAN.VID)
if p.VLAN.Name != "" {
info.VLAN += " (" + p.VLAN.Name + ")"
}
}
out = append(out, info)
}
return nil
})
sort.SliceStable(out, func(i, j int) bool { return prefixLen(out[i].Prefix) < prefixLen(out[j].Prefix) })
return out, err
}
func prefixLen(prefix string) int {
_, bits, _ := strings.Cut(prefix, "/")
n, _ := strconv.Atoi(bits)
return n
}
// RackUnits renders the occupied units, e.g. "U20-21 (2U, front)".
func (d HostDetails) RackUnits() string {
if d.Position == "" {
return ""
}
units := "U" + d.Position
var extra []string
if height, err := strconv.ParseFloat(d.HeightU, 64); err == nil && height > 0 {
if start, err := strconv.ParseFloat(d.Position, 64); err == nil && height > 1 {
units += "-" + strconv.FormatFloat(start+height-1, 'f', -1, 64)
}
extra = append(extra, d.HeightU+"U")
}
if d.Face != "" {
extra = append(extra, d.Face)
}
if len(extra) > 0 {
units += " (" + strings.Join(extra, ", ") + ")"
}
return units
}
+101
View File
@@ -0,0 +1,101 @@
package netbox
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
func detailServer(t *testing.T) *httptest.Server {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
switch {
case r.URL.Path == "/api/dcim/devices/7/":
fmt.Fprint(w, `{"id":7,"name":"sw1","status":{"value":"offline","label":"Offline"},
"site":{"name":"Falkenstein 1","slug":"fsn1"},"rack":{"name":"R12"},"position":20.0,
"device_role":{"name":"Core Switch","slug":"core-switch"},"platform":{"name":"Junos","slug":"junos"},
"tenant":null,"serial":"ABC","asset_tag":null,"device_type":{"model":"QFX5120","manufacturer":{"name":"Juniper"}},
"primary_ip4":{"address":"10.0.0.7/24"},"tags":[{"name":"core"}]}`)
case r.URL.Path == "/api/ipam/ip-addresses/" && r.URL.Query().Get("device_id") == "7":
fmt.Fprint(w, `{"count":2,"results":[
{"address":"192.0.2.7/24","assigned_object":{"name":"xe-0/0/1"},"status":{"value":"active"}},
{"address":"10.0.0.7/24","assigned_object":{"name":"em0"},"dns_name":"sw1.example.com","status":{"value":"active"}}]}`)
case r.URL.Path == "/api/ipam/ip-addresses/" && r.URL.Query().Get("address") != "":
fmt.Fprint(w, `{"count":1,"results":[{"address":"10.0.0.7/24","status":{"value":"active"},
"assigned_object_type":"dcim.interface","assigned_object":{"name":"em0","device":{"id":7,"name":"sw1"}}}]}`)
case r.URL.Path == "/api/ipam/prefixes/":
if r.URL.Query().Get("contains") != "10.0.0.7" {
t.Errorf("unexpected contains %q", r.URL.Query().Get("contains"))
}
fmt.Fprint(w, `{"count":2,"results":[
{"prefix":"10.0.0.0/24","status":{"value":"active"},"vlan":{"vid":100,"name":"mgmt"},"site":{"name":"FSN1"}},
{"prefix":"10.0.0.0/8","description":"internal"}]}`)
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return srv
}
func TestDeviceAttributesAndDetails(t *testing.T) {
srv := detailServer(t)
c := NewClient(srv.URL, "token", 0)
d, err := c.GetDetails(context.Background(), HostEntry{ID: 7, Name: "sw1", Kind: "device"})
if err != nil {
t.Fatal(err)
}
if d.Status != "offline" || d.StatusLabel != "Offline" || d.Site.Slug != "fsn1" || d.Role.Slug != "core-switch" || d.Platform.Slug != "junos" {
t.Fatalf("attributes not parsed: %+v", d.HostEntry)
}
if d.Rack != "R12" || d.Position != "20" || d.DeviceType != "Juniper QFX5120" || d.Serial != "ABC" {
t.Fatalf("details not parsed: %+v", d)
}
if d.URL != srv.URL+"/dcim/devices/7/" {
t.Fatalf("web URL %q", d.URL)
}
if len(d.IPs) != 2 || !d.IPs[0].Primary || d.IPs[0].Interface != "em0" || d.IPs[0].DNSName != "sw1.example.com" {
t.Fatalf("IPs not sorted primary first: %+v", d.IPs)
}
}
func TestWebURLForInstances(t *testing.T) {
c := NewMultiClient([]Source{{Name: "prod", URL: "https://nb.example/", Token: "t"}})
got, err := c.WebURL(HostEntry{Source: "prod", Name: "web", Kind: "vm", ID: 3})
if err != nil || got != "https://nb.example/virtualization/virtual-machines/3/" {
t.Fatalf("got %q, %v", got, err)
}
if _, err := c.WebURL(HostEntry{Source: "prod", Name: "web", Kind: "vm"}); err == nil {
t.Fatal("missing ID accepted")
}
}
func TestLookupIPAndPrefixes(t *testing.T) {
srv := detailServer(t)
c := NewMultiClient([]Source{{Name: "prod", URL: srv.URL, Token: "t"}})
owners, err := c.LookupIP(context.Background(), "10.0.0.7")
if err != nil || len(owners) != 1 || owners[0].Target() != "prod/sw1" || owners[0].Interface != "em0" || owners[0].HostKind != "device" {
t.Fatalf("owners %+v, %v", owners, err)
}
prefixes, err := c.PrefixesContaining(context.Background(), "10.0.0.7")
if err != nil || len(prefixes) != 2 || prefixes[0].Prefix != "10.0.0.0/8" || prefixes[1].VLAN != "100 (mgmt)" || prefixes[1].Source != "prod" {
t.Fatalf("prefixes %+v, %v", prefixes, err)
}
}
func TestLookupIPReportsFailingInstanceButKeepsOthers(t *testing.T) {
good := detailServer(t)
bad := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
http.Error(w, "down", http.StatusBadGateway)
}))
defer bad.Close()
c := NewMultiClient([]Source{{Name: "a", URL: bad.URL, Token: "t"}, {Name: "b", URL: good.URL, Token: "t"}})
owners, err := c.LookupIP(context.Background(), "10.0.0.7")
if err == nil || !strings.Contains(err.Error(), "NetBox a") || len(owners) != 1 {
t.Fatalf("owners %+v, err %v", owners, err)
}
}
+92
View File
@@ -0,0 +1,92 @@
package netbox
import (
"context"
"encoding/json"
"fmt"
"strings"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
// maxLocationDepth stops walking up a broken (cyclic) location tree.
const maxLocationDepth = 16
type locationNode struct {
ref config.Ref
parent int
}
type netboxLocation struct {
ID int `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
Parent *struct {
ID int `json:"id"`
} `json:"parent"`
}
// rackUnit formats a NetBox rack position (a decimal such as 20.0 or 20.5).
func rackUnit(n json.Number) string {
if n == "" {
return ""
}
s := n.String()
if strings.Contains(s, ".") {
s = strings.TrimRight(strings.TrimRight(s, "0"), ".")
}
return s
}
// locationChain returns the locations from the outermost to id. NetBox nests
// locations through "parent"; each location is fetched once per client.
func (c *Client) locationChain(ctx context.Context, id int) ([]config.Ref, error) {
var chain []config.Ref
for depth := 0; id > 0 && depth < maxLocationDepth; depth++ {
node, err := c.location(ctx, id)
if err != nil {
return nil, err
}
chain = append([]config.Ref{node.ref}, chain...)
id = node.parent
}
return chain, nil
}
func (c *Client) location(ctx context.Context, id int) (locationNode, error) {
c.locMu.Lock()
node, ok := c.locations[id]
c.locMu.Unlock()
if ok {
return node, nil
}
var raw netboxLocation
if err := c.get(ctx, fmt.Sprintf("%s/api/dcim/locations/%d/", c.baseURL, id), &raw); err != nil {
return locationNode{}, err
}
node = locationNode{ref: config.Ref{Name: raw.Name, Slug: raw.Slug}}
if raw.Parent != nil {
node.parent = raw.Parent.ID
}
c.locMu.Lock()
if c.locations == nil {
c.locations = map[int]locationNode{}
}
c.locations[id] = node
c.locMu.Unlock()
return node, nil
}
// fillLocations replaces each device's own location with the full chain of
// parent locations. A failed lookup keeps the device's own location: the
// location is informational and must not break a search or a connection.
func (c *Client) fillLocations(ctx context.Context, entries []HostEntry) {
for i := range entries {
if entries[i].locationID <= 0 {
continue
}
if chain, err := c.locationChain(ctx, entries[i].locationID); err == nil && len(chain) > 0 {
entries[i].Location = chain
}
}
}
+101
View File
@@ -0,0 +1,101 @@
package netbox
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
)
// locationServer serves a site with Building A › Floor 2 › Room 2.04 and two
// racked devices in Room 2.04, plus a location loop 90 ↔ 91.
func locationServer(t *testing.T, calls *int32) *httptest.Server {
t.Helper()
locations := map[string]string{
"1": `{"id":1,"name":"Building A","slug":"building-a","parent":null}`,
"2": `{"id":2,"name":"Floor 2","slug":"floor-2","parent":{"id":1}}`,
"3": `{"id":3,"name":"Room 2.04","slug":"room-2-04","parent":{"id":2}}`,
"90": `{"id":90,"name":"Loop A","slug":"loop-a","parent":{"id":91}}`,
"91": `{"id":91,"name":"Loop B","slug":"loop-b","parent":{"id":90}}`,
}
device := func(id int, name string, location int, position string) string {
return fmt.Sprintf(`{"id":%d,"name":%q,"site":{"name":"FSN1","slug":"fsn1"},"location":{"id":%d,"name":"x","slug":"x"},
"rack":{"name":"R12"},"position":%s,"face":{"value":"front"},"device_type":{"id":9,"model":"R640"}}`, id, name, location, position)
}
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch {
case strings.HasPrefix(r.URL.Path, "/api/dcim/locations/"):
atomic.AddInt32(calls, 1)
id := strings.Trim(strings.TrimPrefix(r.URL.Path, "/api/dcim/locations/"), "/")
if body, ok := locations[id]; ok {
fmt.Fprint(w, body)
return
}
http.NotFound(w, r)
case r.URL.Path == "/api/dcim/devices/":
fmt.Fprintf(w, `{"count":3,"results":[%s,%s,%s]}`, device(1, "srv1", 3, "20.0"), device(2, "srv2", 3, "22"), device(3, "loopy", 90, "null"))
case r.URL.Path == "/api/dcim/devices/1/":
fmt.Fprint(w, device(1, "srv1", 3, "20.0"))
case r.URL.Path == "/api/dcim/device-types/9/":
fmt.Fprint(w, `{"id":9,"u_height":2.0}`)
case r.URL.Path == "/api/virtualization/virtual-machines/", r.URL.Path == "/api/ipam/ip-addresses/":
fmt.Fprint(w, `{"count":0,"results":[]}`)
default:
http.NotFound(w, r)
}
}))
t.Cleanup(srv.Close)
return srv
}
func TestSearchAllResolvesNestedLocations(t *testing.T) {
var calls int32
srv := locationServer(t, &calls)
entries, err := NewClient(srv.URL, "t", 0).SearchAll(context.Background(), "", SearchOptions{Kind: "device"})
if err != nil {
t.Fatal(err)
}
byName := map[string]HostEntry{}
for _, e := range entries {
byName[e.Name] = e
}
srv1 := byName["srv1"]
if got := srv1.LocationPath(); got != "FSN1 › Building A › Floor 2 › Room 2.04 › R12 › U20" {
t.Fatalf("path %q", got)
}
if srv1.Location[0].Slug != "building-a" || srv1.Location[2].Slug != "room-2-04" {
t.Fatalf("chain order: %+v", srv1.Location)
}
// Room, floor and building are fetched once for both devices, the loop
// stops at the depth limit instead of hanging.
if n := atomic.LoadInt32(&calls); n != 5 {
t.Fatalf("location requests: %d", n)
}
if len(byName["loopy"].Location) != maxLocationDepth || byName["loopy"].Position != "" {
t.Fatalf("loop not bounded: %d", len(byName["loopy"].Location))
}
}
func TestDetailsShowRackUnits(t *testing.T) {
var calls int32
srv := locationServer(t, &calls)
d, err := NewClient(srv.URL, "t", 0).GetDetails(context.Background(), HostEntry{ID: 1, Name: "srv1", Kind: "device"})
if err != nil {
t.Fatal(err)
}
if d.Rack != "R12" || d.Position != "20" || d.HeightU != "2" || d.RackUnits() != "U20-21 (2U, front)" {
t.Fatalf("rack: %q %q %q %q", d.Rack, d.Position, d.HeightU, d.RackUnits())
}
if len(d.Location) != 3 {
t.Fatalf("details lack location chain: %+v", d.Location)
}
if (HostDetails{HostEntry: HostEntry{Position: "7"}, HeightU: "1"}).RackUnits() != "U7 (1U)" {
t.Fatal("single unit")
}
if (HostDetails{}).RackUnits() != "" {
t.Fatal("unracked device should have no units")
}
}
+83 -1
View File
@@ -1,6 +1,12 @@
package netbox package netbox
import "strings" import (
"encoding/json"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
// SearchOptions filters a Search or SearchAll query. // SearchOptions filters a Search or SearchAll query.
// Zero value means no filtering (return all kinds, no tag filter). // Zero value means no filtering (return all kinds, no tag filter).
@@ -13,6 +19,9 @@ type SearchOptions struct {
// HostEntry is a unified model for both devices and virtual machines from NetBox. // HostEntry is a unified model for both devices and virtual machines from NetBox.
type HostEntry struct { type HostEntry struct {
Cached bool
CachedAt time.Time
Static bool
Source string // named NetBox instance; empty for the legacy single-instance config Source string // named NetBox instance; empty for the legacy single-instance config
ID int ID int
Name string Name string
@@ -21,6 +30,49 @@ type HostEntry struct {
PrimaryIP6 string PrimaryIP6 string
Tags []string Tags []string
Cluster string // virtualization cluster name, if assigned Cluster string // virtualization cluster name, if assigned
Status string // NetBox status value, e.g. "active"
Site config.Ref
Role config.Ref
Platform config.Ref
Tenant config.Ref
// Location is the chain of nested NetBox locations from the outermost
// (directly below the site) to the device's own location.
Location []config.Ref
Rack string
Position string // lowest rack unit, e.g. "20"; empty when not racked
locationID int // the device's own location, before the chain is resolved
}
// LocationPath renders site › locations › rack › U position.
func (h HostEntry) LocationPath() string {
return config.LocationPath(h.Site, h.Location, h.Rack, h.Position)
}
// netboxRef is a nested NetBox object with a name and slug.
type netboxRef struct {
Name string `json:"name"`
Slug string `json:"slug"`
}
func (r *netboxRef) ref() config.Ref {
if r == nil {
return config.Ref{}
}
return config.Ref{Name: r.Name, Slug: r.Slug}
}
// netboxStatus is a NetBox choice field such as status.
type netboxStatus struct {
Value string `json:"value"`
Label string `json:"label"`
}
func (s *netboxStatus) value() string {
if s == nil {
return ""
}
return s.Value
} }
// netboxCluster is the nested cluster of a device or virtual machine. // netboxCluster is the nested cluster of a device or virtual machine.
@@ -44,6 +96,21 @@ type netboxDevice struct {
PrimaryIP4 *netboxIP `json:"primary_ip4"` PrimaryIP4 *netboxIP `json:"primary_ip4"`
PrimaryIP6 *netboxIP `json:"primary_ip6"` PrimaryIP6 *netboxIP `json:"primary_ip6"`
Cluster *netboxCluster `json:"cluster"` Cluster *netboxCluster `json:"cluster"`
Status *netboxStatus `json:"status"`
Site *netboxRef `json:"site"`
Role *netboxRef `json:"role"`
DeviceRole *netboxRef `json:"device_role"` // NetBox < 3.6
Platform *netboxRef `json:"platform"`
Tenant *netboxRef `json:"tenant"`
Location *struct {
ID int `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
} `json:"location"`
Rack *struct {
Name string `json:"name"`
} `json:"rack"`
Position json.Number `json:"position"`
} }
// netboxVM matches the relevant fields of the NetBox /virtualization/virtual-machines/ response. // netboxVM matches the relevant fields of the NetBox /virtualization/virtual-machines/ response.
@@ -56,6 +123,21 @@ type netboxVM struct {
PrimaryIP4 *netboxIP `json:"primary_ip4"` PrimaryIP4 *netboxIP `json:"primary_ip4"`
PrimaryIP6 *netboxIP `json:"primary_ip6"` PrimaryIP6 *netboxIP `json:"primary_ip6"`
Cluster *netboxCluster `json:"cluster"` Cluster *netboxCluster `json:"cluster"`
Status *netboxStatus `json:"status"`
Site *netboxRef `json:"site"`
Role *netboxRef `json:"role"`
DeviceRole *netboxRef `json:"device_role"` // NetBox < 3.6
Platform *netboxRef `json:"platform"`
Tenant *netboxRef `json:"tenant"`
Location *struct {
ID int `json:"id"`
Name string `json:"name"`
Slug string `json:"slug"`
} `json:"location"`
Rack *struct {
Name string `json:"name"`
} `json:"rack"`
Position json.Number `json:"position"`
} }
type netboxListResponse[T any] struct { type netboxListResponse[T any] struct {
+30
View File
@@ -0,0 +1,30 @@
package resolver
import (
"context"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
func TestCandidatesListsEveryStrategyOnce(t *testing.T) {
chain, err := New(config.ResolverConfig{Strategies: []string{"primary_ip", "hostname"}, HostnameDomain: "example.com"})
if err != nil {
t.Fatal(err)
}
entry := &netbox.HostEntry{Name: "web", Kind: "vm", PrimaryIP4: "10.0.0.1", PrimaryIP6: "2001:db8::1"}
got, err := chain.Candidates(context.Background(), entry, nil)
if err != nil {
t.Fatal(err)
}
want := []Candidate{{"10.0.0.1", "primary_ip"}, {"web.example.com", "hostname"}, {"2001:db8::1", "primary_ip"}}
if len(got) != len(want) {
t.Fatalf("got %+v", got)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("got %+v, want %+v", got, want)
}
}
}
+54 -2
View File
@@ -2,6 +2,7 @@ package resolver
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
@@ -27,13 +28,24 @@ func New(cfg config.ResolverConfig) (*Chain, error) {
} }
func (c *Chain) Resolve(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, error) { func (c *Chain) Resolve(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, error) {
address, _, err := c.ResolveWithStrategy(ctx, entry, client)
return address, err
}
func (c *Chain) ResolveWithStrategy(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, string, error) {
for _, s := range c.strategies { for _, s := range c.strategies {
ip, err := s.Resolve(ctx, entry, client) ip, err := s.Resolve(ctx, entry, client)
if err == nil { if err == nil {
return ip, nil return ip, s.Name(), nil
}
// Only "this strategy has no address" moves on. After an API failure
// the next strategy would connect to (and cache) a different address
// than the configured order asks for.
if !errors.Is(err, ErrNoIP) {
return "", "", fmt.Errorf("resolver strategy %q for %q: %w", s.Name(), entry.Name, err)
} }
} }
return "", fmt.Errorf("no strategy resolved an IP for %q", entry.Name) return "", "", fmt.Errorf("no strategy resolved an IP for %q", entry.Name)
} }
func newStrategy(name string, cfg config.ResolverConfig) (Strategy, error) { func newStrategy(name string, cfg config.ResolverConfig) (Strategy, error) {
@@ -57,3 +69,43 @@ func newStrategy(name string, cfg config.ResolverConfig) (Strategy, error) {
return nil, fmt.Errorf("unknown strategy %q", name) return nil, fmt.Errorf("unknown strategy %q", name)
} }
} }
// Candidate is an address one strategy resolved for a host.
type Candidate struct {
Address string
Strategy string
}
// Candidates runs every strategy and returns their distinct addresses in the
// configured order. Unlike Resolve, an API failure of one strategy does not
// stop the others: candidates are only used as fallbacks for an address that
// was already chosen by Resolve and turned out to be unreachable.
func (c *Chain) Candidates(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) ([]Candidate, error) {
var out []Candidate
var errs []error
seen := map[string]bool{}
for _, s := range c.strategies {
ip, err := s.Resolve(ctx, entry, client)
if err != nil {
if !errors.Is(err, ErrNoIP) {
errs = append(errs, fmt.Errorf("%s: %w", s.Name(), err))
}
continue
}
if !seen[ip] {
seen[ip] = true
out = append(out, Candidate{Address: ip, Strategy: s.Name()})
}
}
// Both addresses of a dual-stack host are worth trying.
for _, ip := range []string{entry.PrimaryIP4, entry.PrimaryIP6} {
if ip != "" && !seen[ip] {
seen[ip] = true
out = append(out, Candidate{Address: ip, Strategy: "primary_ip"})
}
}
if len(out) == 0 {
return nil, errors.Join(errs...)
}
return out, nil
}
+14
View File
@@ -153,3 +153,17 @@ func TestNew_MultipleStrategies(t *testing.T) {
t.Errorf("got %d strategies, want 2", len(c.strategies)) t.Errorf("got %d strategies, want 2", len(c.strategies))
} }
} }
// An API failure must not fall through: the next strategy would connect to
// and cache a different address than the configured order asks for.
func TestChain_APIErrorStopsTheChain(t *testing.T) {
apiErr := errors.New("connection refused")
c := &Chain{strategies: []Strategy{
&stubStrategy{name: "management_subnet", err: apiErr},
&stubStrategy{name: "primary_ip", ip: "10.0.0.2"},
}}
ip, err := c.Resolve(context.Background(), &netbox.HostEntry{Name: "host"}, nil)
if !errors.Is(err, apiErr) || ip != "" {
t.Fatalf("got %q, %v; want the API error and no address", ip, err)
}
}
+6
View File
@@ -2,7 +2,9 @@ package resolver
import ( import (
"context" "context"
"errors"
"fmt" "fmt"
"net/http"
"net/url" "net/url"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
@@ -31,6 +33,10 @@ func (s *InterfaceNameStrategy) Resolve(ctx context.Context, entry *netbox.HostE
} }
ips, err := client.GetIPsWithFilterForHost(ctx, *entry, filterParam) ips, err := client.GetIPsWithFilterForHost(ctx, *entry, filterParam)
var status *netbox.StatusError
if errors.As(err, &status) && status.Code == http.StatusBadRequest {
return "", ErrNoIP // the host has no interface of this name
}
if err != nil { if err != nil {
return "", fmt.Errorf("fetching IPs for interface %q: %w", s.name, err) return "", fmt.Errorf("fetching IPs for interface %q: %w", s.name, err)
} }
+14
View File
@@ -2,6 +2,7 @@ package resolver
import ( import (
"context" "context"
"errors"
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"net/url" "net/url"
@@ -54,3 +55,16 @@ func urlQuery(s string) (string, error) {
q, err := url.ParseQuery(s) q, err := url.ParseQuery(s)
return q.Encode(), err return q.Encode(), err
} }
// Only the HTTP 400 of a missing interface means "no address here"; a server
// error must stop the chain instead of silently using the next strategy.
func TestInterfaceNameStrategyServerErrorIsNotNoIP(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadGateway)
}))
defer srv.Close()
_, err := (&InterfaceNameStrategy{name: "mgmt0"}).Resolve(context.Background(), &netbox.HostEntry{ID: 7, Kind: "device"}, netbox.NewClient(srv.URL, "t", 1))
if err == nil || errors.Is(err, ErrNoIP) {
t.Fatalf("got %v, want an API error", err)
}
}
+146
View File
@@ -0,0 +1,146 @@
// Package runner supervises local commands while retaining terminal I/O.
package runner
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
"github.com/charmbracelet/x/term"
)
type Options struct {
Stdin io.Reader
Stdout, Stderr io.Writer
Env []string
Timeout time.Duration
Status bool
Label string
}
type Result struct {
Code int
Started bool
Duration time.Duration
}
func Run(ctx context.Context, argv []string, o Options) Result {
if o.Stderr == nil {
o.Stderr = io.Discard
}
if o.Stdout == nil {
o.Stdout = io.Discard
}
start := time.Now()
result := Result{Code: 1}
if ctx.Err() != nil {
result.Code = 130
return result
}
if len(argv) == 0 {
return result
}
cmd := exec.Command(argv[0], argv[1:]...)
cmd.Stdin, cmd.Stdout, cmd.Stderr = o.Stdin, o.Stdout, o.Stderr
cmd.Env = append(os.Environ(), o.Env...)
interactive := false
if f, ok := o.Stdin.(*os.File); ok {
interactive = term.IsTerminal(f.Fd())
}
// Interactive SSH must share the foreground terminal process group.
// Background jobs get an isolated group so cancellation reaches descendants.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: !interactive}
if err := cmd.Start(); err != nil {
fmt.Fprintf(o.Stderr, "%s: %v\n", argv[0], err)
return result
}
result.Started = true
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
sigs := make(chan os.Signal, 4)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT)
defer signal.Stop(sigs)
var timeout <-chan time.Time
if o.Timeout > 0 {
timer := time.NewTimer(o.Timeout)
defer timer.Stop()
timeout = timer.C
}
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
var killTimer *time.Timer
var kill <-chan time.Time
defer func() {
if killTimer != nil {
killTimer.Stop()
}
}()
send := func(sig syscall.Signal) {
if interactive {
_ = cmd.Process.Signal(sig)
} else {
_ = syscall.Kill(-cmd.Process.Pid, sig)
}
}
forced := 0
cancelCh := ctx.Done()
stop := func(code int, sig syscall.Signal) {
if forced != 0 {
return
}
forced = code
send(sig)
killTimer = time.NewTimer(2 * time.Second)
kill = killTimer.C
}
for {
select {
case err := <-done:
result.Duration = time.Since(start)
result.Code = 0
if err != nil {
result.Code = 1
if e, ok := err.(*exec.ExitError); ok {
result.Code = e.ExitCode()
if s, ok := e.Sys().(syscall.WaitStatus); ok && s.Signaled() {
result.Code = 128 + int(s.Signal())
}
}
}
if forced != 0 {
result.Code = forced
}
// Kill descendants left behind after cancellation even if the parent exited.
if forced != 0 && !interactive {
send(syscall.SIGKILL)
}
if o.Status {
fmt.Fprintf(o.Stderr, "[%s] finished in %s (exit %d)\n", o.Label, result.Duration.Round(time.Millisecond), result.Code)
}
return result
case sig := <-sigs:
s := sig.(syscall.Signal)
if interactive && (s == syscall.SIGINT || s == syscall.SIGQUIT) {
continue
} // terminal delivered it to child too
stop(128+int(s), s)
case <-cancelCh:
cancelCh = nil
stop(130, syscall.SIGTERM)
case <-timeout:
timeout = nil
stop(124, syscall.SIGTERM)
case <-kill:
kill = nil
send(syscall.SIGKILL)
case <-ticker.C:
if o.Status {
fmt.Fprintf(o.Stderr, "[%s] running %s (Ctrl+C cancels)\n", o.Label, time.Since(start).Round(time.Second))
}
}
}
}
+43
View File
@@ -0,0 +1,43 @@
package runner
import (
"bytes"
"context"
"io"
"strings"
"testing"
"time"
)
func TestExitAndTimeout(t *testing.T) {
var out bytes.Buffer
r := Run(context.Background(), []string{"sh", "-c", "printf result; exit 7"}, Options{Stdout: &out, Stderr: io.Discard})
if !r.Started || r.Code != 7 || out.String() != "result" {
t.Fatalf("%+v %q", r, out.String())
}
start := time.Now()
r = Run(context.Background(), []string{"sh", "-c", "trap '' TERM; sleep 30 & wait"}, Options{Stdout: io.Discard, Stderr: io.Discard, Timeout: 50 * time.Millisecond})
if r.Code != 124 || time.Since(start) > 4*time.Second {
t.Fatalf("timeout: %+v", r)
}
}
func TestCancellationAndNoStart(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
r := Run(ctx, []string{"sh", "-c", "exit 0"}, Options{Stderr: io.Discard})
if r.Started || r.Code != 130 {
t.Fatalf("%+v", r)
}
var errOut bytes.Buffer
r = Run(context.Background(), []string{"/no/such/netssh-test-executable"}, Options{Stderr: &errOut})
if r.Started || r.Code == 0 || !strings.Contains(errOut.String(), "no such") {
t.Fatalf("%+v %s", r, errOut.String())
}
ctx, cancel = context.WithCancel(context.Background())
defer cancel()
time.AfterFunc(50*time.Millisecond, cancel)
r = Run(ctx, []string{"sh", "-c", "sleep 30"}, Options{Stdout: io.Discard, Stderr: io.Discard})
if r.Code != 130 {
t.Fatalf("%+v", r)
}
}
+48
View File
@@ -0,0 +1,48 @@
// Package secret keeps NetBox API tokens in the operating system's keyring
// (Secret Service on Linux, Keychain on macOS) instead of the config file.
package secret
import (
"errors"
"fmt"
"github.com/zalando/go-keyring"
)
// Service is the keyring service name of all netssh entries.
const Service = "netssh"
// ErrNotFound means the keyring has no token for the account.
var ErrNotFound = errors.New("no token in the system keyring")
// Get returns the token stored for account.
func Get(account string) (string, error) {
token, err := keyring.Get(Service, account)
if errors.Is(err, keyring.ErrNotFound) {
return "", fmt.Errorf("%w for %q (store one with: netssh token set %s)", ErrNotFound, account, account)
}
if err != nil {
return "", fmt.Errorf("system keyring: %w", err)
}
return token, nil
}
// Set stores token for account, replacing an existing one.
func Set(account, token string) error {
if err := keyring.Set(Service, account, token); err != nil {
return fmt.Errorf("system keyring: %w", err)
}
return nil
}
// Delete removes the token of account; a missing entry is not an error.
func Delete(account string) error {
err := keyring.Delete(Service, account)
if err != nil && !errors.Is(err, keyring.ErrNotFound) {
return fmt.Errorf("system keyring: %w", err)
}
return nil
}
// MockInit replaces the system keyring with an in-memory one, for tests.
func MockInit() { keyring.MockInit() }
+99
View File
@@ -0,0 +1,99 @@
package setup
import (
"fmt"
"sort"
"strings"
"charm.land/huh/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func editCommands(cfg *config.Config) error {
for {
var names []string
for name := range cfg.Commands {
names = append(names, name)
}
sort.Strings(names)
var options []huh.Option[string]
for _, name := range names {
options = append(options, huh.NewOption("Edit "+name, "edit:"+name), huh.NewOption("Remove "+name, "remove:"+name))
}
options = append(options, huh.NewOption("Add command", "add"), huh.NewOption("Done", "done"))
action := "done"
if err := huh.NewSelect[string]().Title("Custom host commands").Options(options...).Value(&action).Run(); err != nil {
return err
}
if action == "done" {
return nil
}
if name, ok := strings.CutPrefix(action, "remove:"); ok {
remove := false
if err := huh.NewConfirm().Title("Remove " + name + "?").Value(&remove).Run(); err != nil {
return err
}
if remove {
delete(cfg.Commands, name)
}
continue
}
original, _ := strings.CutPrefix(action, "edit:")
if action == "add" {
original = ""
}
name := original
command := cfg.Commands[original]
binary, arguments := "", ""
if len(command.Args) > 0 {
binary = command.Args[0]
arguments = strings.Join(command.Args[1:], "\n")
}
err := huh.NewForm(huh.NewGroup(
huh.NewInput().Title("Command name").Placeholder("mtr").Value(&name).Validate(func(s string) error {
if s == "" {
return fmt.Errorf("required")
}
if s != original {
if _, exists := cfg.Commands[s]; exists {
return fmt.Errorf("name already exists")
}
}
return config.ValidateCommandAlias(s)
}),
huh.NewInput().Title("Alias prefix").Description("m + host shortcut xg1 = mxg1. Empty disables automatic aliases.").Value(&command.AliasPrefix),
huh.NewInput().Title("Program or executable script").Description("Use an absolute script path, or bash/python3 with the script path as the first argument.").Placeholder("mtr or /home/user/bin/check-host").Value(&binary),
huh.NewText().Title("Arguments, one per line").Description("Use {address} for the resolved address, {host} for the hostname, {target} for instance/hostname. No shell quoting needed.").Lines(5).Value(&arguments),
huh.NewConfirm().Title("Confirm before running?").Value(&command.Confirm),
huh.NewInput().Title("Timeout").Description("Optional positive duration, e.g. 30s or 5m.").Value(&command.Timeout),
huh.NewInput().Title("Post-run script").Description("Local command after completion; receives NETSSH_EXIT_CODE.").Value(&command.PostRun),
huh.NewInput().Title("Only for tag").Value(&command.Match.Tag),
huh.NewInput().Title("Only for instance").Value(&command.Match.Instance),
huh.NewInput().Title("Only for kind").Description("device, vm or static; empty means all.").Value(&command.Match.Kind),
huh.NewInput().Title("Only for hostname pattern").Description("For example router*; all specified filters must match.").Value(&command.Match.Name),
huh.NewInput().Title("Only for site").Description("NetBox site name or slug.").Value(&command.Match.Site),
huh.NewInput().Title("Only for role").Description("NetBox device/VM role name or slug.").Value(&command.Match.Role),
huh.NewInput().Title("Only for platform").Description("NetBox platform name or slug, e.g. junos.").Value(&command.Match.Platform),
huh.NewInput().Title("Only for status").Description("NetBox status value, e.g. active.").Value(&command.Match.Status),
).Title("Local command")).Run()
if err != nil {
return err
}
command.Match = trimMatch(command.Match)
command.Args = []string{binary}
if arguments != "" {
command.Args = append(command.Args, strings.Split(arguments, "\n")...)
}
candidate := config.Config{Commands: make(map[string]config.HostCommand)}
for k, v := range cfg.Commands {
if k != original {
candidate.Commands[k] = v
}
}
candidate.Commands[name] = command
if err := candidate.ValidateCommands(); err != nil {
return err
}
cfg.Commands = candidate.Commands
}
}
+3
View File
@@ -108,6 +108,9 @@ func editInstance(source config.NetBoxConfig, sources []config.NetBoxConfig, ori
} }
return nil return nil
}), }),
huh.NewConfirm().Title("Hide instance prefix in aliases and TUI?").
Description("Shorter shell aliases and TUI host names. Conflicting names keep their prefix.").
Value(&source.DisablePrefix),
huh.NewInput().Title("NetBox URL").Placeholder("https://netbox.example.com").Value(&source.URL).Validate(func(value string) error { huh.NewInput().Title("NetBox URL").Placeholder("https://netbox.example.com").Value(&source.URL).Validate(func(value string) error {
return (&config.Config{NetBoxes: []config.NetBoxConfig{{Name: "instance", URL: strings.TrimSpace(value)}}}).ValidateNetBoxes() return (&config.Config{NetBoxes: []config.NetBoxConfig{{Name: "instance", URL: strings.TrimSpace(value)}}}).ValidateNetBoxes()
}), }),
+84
View File
@@ -0,0 +1,84 @@
package setup
import (
"fmt"
"strconv"
"charm.land/huh/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func editOperations(cfg *config.Config) error {
history, days, entries := strconv.Itoa(cfg.TUI.HistoryLimit), strconv.Itoa(cfg.Activity.RetentionDays), strconv.Itoa(cfg.Activity.MaxEntries)
enabled := cfg.Activity.Enabled
columns := append([]string(nil), cfg.TUI.EffectiveColumns()...)
timeout := strconv.Itoa(int(cfg.TUI.ReachabilityTimeoutDuration().Milliseconds()))
columnOptions := make([]huh.Option[string], 0, len(config.TUIColumns))
for _, column := range config.TUIColumns {
columnOptions = append(columnOptions, huh.NewOption(columnLabels[column], column).Selected(contains(columns, column)))
}
valid := func(s string) error {
n, err := strconv.Atoi(s)
if err != nil || n < 0 {
return fmt.Errorf("enter a non-negative number")
}
return nil
}
err := huh.NewForm(huh.NewGroup(
huh.NewInput().Title("Recent hosts shown").Description("10 by default; 0 shows all. Favorites are additional.").Value(&history).Validate(valid),
huh.NewConfirm().Title("Record local action history?").Description("Stores host, command name, duration and exit code; no arguments or output.").Value(&enabled),
huh.NewInput().Title("Retention in days").Description("0 = no age limit").Value(&days).Validate(valid),
huh.NewInput().Title("Maximum recorded actions").Description("0 = no count limit").Value(&entries).Validate(valid),
).Title("History & activity"), huh.NewGroup(
huh.NewMultiSelect[string]().Title("Shown in the TUI next to each host").
Description("Reachability opens a TCP connection to every listed host's SSH port.").
Options(columnOptions...).Value(&columns),
huh.NewInput().Title("Reachability timeout (ms)").Description("300 by default").Value(&timeout).Validate(valid),
).Title("TUI display")).Run()
if err != nil {
return err
}
cfg.TUI.Columns = orderColumns(cfg.TUI.EffectiveColumns(), columns)
if ms, _ := strconv.Atoi(timeout); ms != 300 {
cfg.TUI.ReachabilityTimeout = ms
} else {
cfg.TUI.ReachabilityTimeout = 0
}
cfg.TUI.HistoryLimit, _ = strconv.Atoi(history)
cfg.Activity.RetentionDays, _ = strconv.Atoi(days)
cfg.Activity.MaxEntries, _ = strconv.Atoi(entries)
cfg.Activity.Enabled = enabled
return nil
}
var columnLabels = map[string]string{
"alias": "Shortcut alias", "ip": "IP address", "kind": "Kind (device/vm/static)", "source": "Source (live/cache/static)",
"status": "NetBox status (if not active)", "site": "Site", "location": "Location (site › locations › rack › U)", "role": "Role", "platform": "Platform", "tenant": "Tenant",
"cluster": "Cluster", "tags": "Tags", "reachability": "Reachability (TCP check ✓/✗)",
}
func contains(list []string, value string) bool {
for _, item := range list {
if item == value {
return true
}
}
return false
}
// orderColumns keeps an existing custom order and appends new selections in
// the canonical order; the multi-select itself does not preserve order.
func orderColumns(previous, selected []string) []string {
out := []string{}
for _, column := range previous {
if contains(selected, column) {
out = append(out, column)
}
}
for _, column := range config.TUIColumns {
if contains(selected, column) && !contains(out, column) {
out = append(out, column)
}
}
return out
}
+41 -6
View File
@@ -23,6 +23,8 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
extraArgs := strings.Join(o.ExtraArgs, "\n") extraArgs := strings.Join(o.ExtraArgs, "\n")
options := formatOptions(o.Options) options := formatOptions(o.Options)
forwards := formatForwards(o.Forwards) forwards := formatForwards(o.Forwards)
preConnect := o.PreConnect
postDisconnect := o.PostDisconnect
err := huh.NewForm(huh.NewGroup( err := huh.NewForm(huh.NewGroup(
huh.NewInput(). huh.NewInput().
@@ -69,6 +71,15 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
_, err := parseForwards(s) _, err := parseForwards(s)
return err return err
}), }),
huh.NewInput().Title("Post-disconnect script").Description("Local command after the client exits; none disables inheritance.").Value(&postDisconnect),
huh.NewInput().
Title("Pre-connect hook").
Description("Shell command run locally before connecting, e.g. vpn-check.sh \"$NETSSH_HOST\".\n"+
"A non-zero exit aborts. Leave empty to inherit; 'none' disables a hook set elsewhere.").
Value(&preConnect).
Validate(func(s string) error {
return config.SSHOptions{PreConnect: s}.Validate("ssh")
}),
).Title(title)).Run() ).Title(title)).Run()
if err != nil { if err != nil {
return o, err return o, err
@@ -84,6 +95,8 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
AddressFamily: addressFamily, AddressFamily: addressFamily,
ExtraArgs: parseLines(extraArgs), ExtraArgs: parseLines(extraArgs),
Options: parsed, Options: parsed,
PreConnect: strings.TrimSpace(preConnect),
PostDisconnect: strings.TrimSpace(postDisconnect),
}, nil }, nil
} }
@@ -249,22 +262,36 @@ func editRule(rule config.SSHRule, sources []config.NetBoxConfig) (config.SSHRul
Title("Kind"). Title("Kind").
Options(huh.NewOption("(any)", ""), huh.NewOption("device", "device"), huh.NewOption("vm", "vm")). Options(huh.NewOption("(any)", ""), huh.NewOption("device", "device"), huh.NewOption("vm", "vm")).
Value(&match.Kind), Value(&match.Kind),
huh.NewInput().
Title("Site").
Description("NetBox site name or slug, e.g. fsn1").
Value(&match.Site),
huh.NewInput().
Title("Role").
Description("NetBox device/VM role name or slug, e.g. core-switch").
Value(&match.Role),
huh.NewInput().
Title("Platform").
Description("NetBox platform name or slug, e.g. junos").
Value(&match.Platform),
huh.NewInput().
Title("Status").
Description("NetBox status value, e.g. active").
Value(&match.Status),
huh.NewInput(). huh.NewInput().
Title("Name pattern"). Title("Name pattern").
Description("Shell-style glob without instance prefix, e.g. *.dmz.example.com"). Description("Shell-style glob without instance prefix, e.g. *.dmz.example.com").
Value(&match.Name). Value(&match.Name).
Validate(func(s string) error { Validate(func(s string) error {
candidate := match candidate := match
candidate.Tag = strings.TrimSpace(candidate.Tag) candidate.Name = s
candidate.Name = strings.TrimSpace(s) return trimMatch(candidate).Validate("rule")
return candidate.Validate("rule")
}), }),
).Title("Rule match")).Run() ).Title("Rule match")).Run()
if err != nil { if err != nil {
return rule, err return rule, err
} }
match.Tag = strings.TrimSpace(match.Tag) match = trimMatch(match)
match.Name = strings.TrimSpace(match.Name)
options, err := editSSHOptions("SSH options for rule "+describeMatch(match), rule.SSHOptions) options, err := editSSHOptions("SSH options for rule "+describeMatch(match), rule.SSHOptions)
if err != nil { if err != nil {
@@ -275,10 +302,18 @@ func editRule(rule config.SSHRule, sources []config.NetBoxConfig) (config.SSHRul
func describeMatch(m config.SSHMatch) string { func describeMatch(m config.SSHMatch) string {
var parts []string var parts []string
for _, field := range [][2]string{{"tag", m.Tag}, {"instance", m.Instance}, {"kind", m.Kind}, {"name", m.Name}} { for _, field := range matchFields(m) {
if field[1] != "" { if field[1] != "" {
parts = append(parts, field[0]+"="+field[1]) parts = append(parts, field[0]+"="+field[1])
} }
} }
return "[" + strings.Join(parts, " ") + "]" return "[" + strings.Join(parts, " ") + "]"
} }
// trimMatch removes surrounding spaces from every selector.
func trimMatch(m config.SSHMatch) config.SSHMatch {
for _, field := range []*string{&m.Tag, &m.Instance, &m.Kind, &m.Name, &m.Site, &m.Role, &m.Platform, &m.Tenant, &m.Status} {
*field = strings.TrimSpace(*field)
}
return m
}
+93 -4
View File
@@ -94,6 +94,8 @@ func runMenu(cfg *config.Config) error {
huh.NewOption(fmt.Sprintf("Multi-session — groups, tmux/zellij (%d groups)", len(cfg.Groups)), "multi"), huh.NewOption(fmt.Sprintf("Multi-session — groups, tmux/zellij (%d groups)", len(cfg.Groups)), "multi"),
huh.NewOption("Resolver & cache", "resolver"), huh.NewOption("Resolver & cache", "resolver"),
huh.NewOption("Shortcuts & command alias", "shortcuts"), huh.NewOption("Shortcuts & command alias", "shortcuts"),
huh.NewOption("Custom commands — mtr, ping, scripts", "commands"),
huh.NewOption("History & activity logging", "operations"),
huh.NewOption("Completion", "completion"), huh.NewOption("Completion", "completion"),
huh.NewOption("Save and exit", "save"), huh.NewOption("Save and exit", "save"),
). ).
@@ -122,6 +124,10 @@ func runMenu(cfg *config.Config) error {
err = editResolverCache(cfg) err = editResolverCache(cfg)
case "shortcuts": case "shortcuts":
err = editShortcuts(cfg) err = editShortcuts(cfg)
case "commands":
err = editCommands(cfg)
case "operations":
err = editOperations(cfg)
case "completion": case "completion":
err = editCompletion(cfg) err = editCompletion(cfg)
case "save": case "save":
@@ -226,6 +232,7 @@ func editShortcuts(cfg *config.Config) error {
stripHyphens := cfg.Shortcuts.StripHyphens stripHyphens := cfg.Shortcuts.StripHyphens
rewrites := formatRewrites(cfg.Shortcuts.Rewrites) rewrites := formatRewrites(cfg.Shortcuts.Rewrites)
commandAlias := cfg.Shell.Alias commandAlias := cfg.Shell.Alias
showShortcuts := cfg.Shortcuts.Show
err := huh.NewForm(huh.NewGroup( err := huh.NewForm(huh.NewGroup(
huh.NewInput(). huh.NewInput().
Title("Domain suffixes"). Title("Domain suffixes").
@@ -247,6 +254,11 @@ func editShortcuts(cfg *config.Config) error {
_, err := parseRewrites(s) _, err := parseRewrites(s)
return err return err
}), }),
huh.NewConfirm().
Title("Show shortcuts").
Description("Show each host's shortcut alias in the TUI, netssh cache list and netssh hosts list,\n"+
"and offer shortcuts in Tab completion even when the full name matches.").
Value(&showShortcuts),
huh.NewInput(). huh.NewInput().
Title("Command alias"). Title("Command alias").
Description("Optional alias for netssh itself, e.g. j. Leave empty to disable."). Description("Optional alias for netssh itself, e.g. j. Leave empty to disable.").
@@ -266,6 +278,7 @@ func editShortcuts(cfg *config.Config) error {
} }
cfg.Shortcuts.StripHyphens = stripHyphens cfg.Shortcuts.StripHyphens = stripHyphens
cfg.Shortcuts.Rewrites, _ = parseRewrites(rewrites) cfg.Shortcuts.Rewrites, _ = parseRewrites(rewrites)
cfg.Shortcuts.Show = showShortcuts
cfg.Shell.Alias = strings.TrimSpace(commandAlias) cfg.Shell.Alias = strings.TrimSpace(commandAlias)
return nil return nil
} }
@@ -372,6 +385,12 @@ func save(cfg config.Config) error {
if err := cfg.ValidateHosts(); err != nil { if err := cfg.ValidateHosts(); err != nil {
return err return err
} }
if err := cfg.ValidateOperations(); err != nil {
return err
}
if err := cfg.ValidateCommands(); err != nil {
return err
}
if err := cfg.ValidateMulti(); err != nil { if err := cfg.ValidateMulti(); err != nil {
return err return err
} }
@@ -385,6 +404,9 @@ func save(cfg config.Config) error {
b.WriteString("netboxes:\n") b.WriteString("netboxes:\n")
for _, source := range cfg.NetBoxes { for _, source := range cfg.NetBoxes {
fmt.Fprintf(&b, " - name: %q\n url: %q\n token: %q\n token_version: %d\n", source.Name, source.URL, source.Token, source.TokenVersion) fmt.Fprintf(&b, " - name: %q\n url: %q\n token: %q\n token_version: %d\n", source.Name, source.URL, source.Token, source.TokenVersion)
if source.DisablePrefix {
b.WriteString(" disable_prefix: true\n")
}
if !sshOptionsEmpty(source.SSH) { if !sshOptionsEmpty(source.SSH) {
b.WriteString(" ssh:\n") b.WriteString(" ssh:\n")
writeSSHOptions(&b, " ", source.SSH) writeSSHOptions(&b, " ", source.SSH)
@@ -404,6 +426,12 @@ func save(cfg config.Config) error {
for _, s := range cfg.Resolver.Strategies { for _, s := range cfg.Resolver.Strategies {
fmt.Fprintf(&b, " - %s\n", s) fmt.Fprintf(&b, " - %s\n", s)
} }
if cfg.Resolver.Fallback {
b.WriteString(" fallback: true\n")
}
if cfg.Resolver.FallbackTimeout > 0 {
fmt.Fprintf(&b, " fallback_timeout: %d\n", cfg.Resolver.FallbackTimeout)
}
if len(cfg.Resolver.ManagementSubnets) > 0 { if len(cfg.Resolver.ManagementSubnets) > 0 {
b.WriteString(" management_subnets:\n") b.WriteString(" management_subnets:\n")
for _, s := range cfg.Resolver.ManagementSubnets { for _, s := range cfg.Resolver.ManagementSubnets {
@@ -430,12 +458,19 @@ func save(cfg config.Config) error {
if cfg.SSH.DefaultPort > 0 { if cfg.SSH.DefaultPort > 0 {
fmt.Fprintf(&b, " default_port: %d\n", cfg.SSH.DefaultPort) fmt.Fprintf(&b, " default_port: %d\n", cfg.SSH.DefaultPort)
} }
if cfg.SSH.WarnStatus != nil && !sameStrings(cfg.SSH.WarnStatus, config.DefaultWarnStatus) {
quoted := make([]string, 0, len(cfg.SSH.WarnStatus))
for _, status := range cfg.SSH.WarnStatus {
quoted = append(quoted, strconv.Quote(status))
}
fmt.Fprintf(&b, " warn_status: [%s]\n", strings.Join(quoted, ", "))
}
writeSSHOptions(&b, " ", cfg.SSH.SSHOptions) writeSSHOptions(&b, " ", cfg.SSH.SSHOptions)
if len(cfg.SSH.Rules) > 0 { if len(cfg.SSH.Rules) > 0 {
b.WriteString(" rules:\n") b.WriteString(" rules:\n")
for _, rule := range cfg.SSH.Rules { for _, rule := range cfg.SSH.Rules {
b.WriteString(" - match:\n") b.WriteString(" - match:\n")
for _, field := range [][2]string{{"tag", rule.Match.Tag}, {"instance", rule.Match.Instance}, {"kind", rule.Match.Kind}, {"name", rule.Match.Name}} { for _, field := range matchFields(rule.Match) {
if field[1] != "" { if field[1] != "" {
fmt.Fprintf(&b, " %s: %q\n", field[0], field[1]) fmt.Fprintf(&b, " %s: %q\n", field[0], field[1])
} }
@@ -501,7 +536,7 @@ func save(cfg config.Config) error {
fmt.Fprintf(&b, "\ncompletion:\n max_results: %d\n", cfg.Completion.MaxResults) fmt.Fprintf(&b, "\ncompletion:\n max_results: %d\n", cfg.Completion.MaxResults)
} }
if cfg.Shortcuts.Enabled() { if cfg.Shortcuts.Enabled() || cfg.Shortcuts.Show {
b.WriteString("\nshortcuts:\n") b.WriteString("\nshortcuts:\n")
if len(cfg.Shortcuts.Domains) > 0 { if len(cfg.Shortcuts.Domains) > 0 {
b.WriteString(" domains:\n") b.WriteString(" domains:\n")
@@ -518,8 +553,44 @@ func save(cfg config.Config) error {
fmt.Fprintf(&b, " - pattern: %q\n replace: %q\n", r.Pattern, r.Replace) fmt.Fprintf(&b, " - pattern: %q\n replace: %q\n", r.Pattern, r.Replace)
} }
} }
if cfg.Shortcuts.Show {
b.WriteString(" show: true\n")
}
} }
if len(cfg.Commands) > 0 {
b.WriteString("\ncommands:\n")
var names []string
for name := range cfg.Commands {
names = append(names, name)
}
sort.Strings(names)
for _, name := range names {
command := cfg.Commands[name]
fmt.Fprintf(&b, " %s:\n alias_prefix: %q\n args:\n", name, command.AliasPrefix)
for _, arg := range command.Args {
fmt.Fprintf(&b, " - %q\n", arg)
}
fmt.Fprintf(&b, " confirm: %t\n timeout: %q\n post_run: %q\n", command.Confirm, command.Timeout, command.PostRun)
if command.Match != (config.SSHMatch{}) {
b.WriteString(" match:\n")
for _, pair := range matchFields(command.Match) {
if pair[1] != "" {
fmt.Fprintf(&b, " %s: %q\n", pair[0], pair[1])
}
}
}
}
}
fmt.Fprintf(&b, "\ntui:\n history_limit: %d\n", cfg.TUI.HistoryLimit)
if cfg.TUI.Columns != nil && !sameStrings(cfg.TUI.Columns, config.DefaultTUIColumns) {
fmt.Fprintf(&b, " columns: [%s]\n", strings.Join(cfg.TUI.Columns, ", "))
}
if cfg.TUI.ReachabilityTimeout > 0 {
fmt.Fprintf(&b, " reachability_timeout: %d\n", cfg.TUI.ReachabilityTimeout)
}
fmt.Fprintf(&b, "activity:\n enabled: %t\n retention_days: %d\n max_entries: %d\n", cfg.Activity.Enabled, cfg.Activity.RetentionDays, cfg.Activity.MaxEntries)
if cfg.Shell.Alias != "" { if cfg.Shell.Alias != "" {
fmt.Fprintf(&b, "\nshell:\n alias: %q\n", cfg.Shell.Alias) fmt.Fprintf(&b, "\nshell:\n alias: %q\n", cfg.Shell.Alias)
} }
@@ -533,12 +604,12 @@ func save(cfg config.Config) error {
} }
func sshOptionsEmpty(o config.SSHOptions) bool { func sshOptionsEmpty(o config.SSHOptions) bool {
return o.ProxyJump == "" && o.HostKeyChecking == "" && o.Target == "" && o.AddressFamily == "" && len(o.ExtraArgs) == 0 && len(o.Options) == 0 && len(o.Forwards) == 0 return o.ProxyJump == "" && o.HostKeyChecking == "" && o.Target == "" && o.AddressFamily == "" && len(o.ExtraArgs) == 0 && len(o.Options) == 0 && len(o.Forwards) == 0 && o.PreConnect == "" && o.PostDisconnect == ""
} }
// writeSSHOptions keeps settings the wizard does not ask for when it rewrites the config. // writeSSHOptions keeps settings the wizard does not ask for when it rewrites the config.
func writeSSHOptions(b *strings.Builder, indent string, o config.SSHOptions) { func writeSSHOptions(b *strings.Builder, indent string, o config.SSHOptions) {
for _, field := range [][2]string{{"proxy_jump", o.ProxyJump}, {"host_key_checking", o.HostKeyChecking}, {"target", o.Target}, {"address_family", o.AddressFamily}} { for _, field := range [][2]string{{"proxy_jump", o.ProxyJump}, {"host_key_checking", o.HostKeyChecking}, {"target", o.Target}, {"address_family", o.AddressFamily}, {"pre_connect", o.PreConnect}, {"post_disconnect", o.PostDisconnect}} {
if field[1] != "" { if field[1] != "" {
fmt.Fprintf(b, "%s%s: %q\n", indent, field[0], field[1]) fmt.Fprintf(b, "%s%s: %q\n", indent, field[0], field[1])
} }
@@ -577,3 +648,21 @@ func writeSSHOptions(b *strings.Builder, indent string, o config.SSHOptions) {
} }
} }
} }
// matchFields lists the selectors of a rule or command match in config order.
func matchFields(m config.SSHMatch) [][2]string {
return [][2]string{{"tag", m.Tag}, {"instance", m.Instance}, {"kind", m.Kind}, {"name", m.Name},
{"site", m.Site}, {"role", m.Role}, {"platform", m.Platform}, {"tenant", m.Tenant}, {"status", m.Status}}
}
func sameStrings(a, b []string) bool {
if len(a) != len(b) {
return false
}
for i := range a {
if !strings.EqualFold(a[i], b[i]) {
return false
}
}
return true
}
+122 -2
View File
@@ -398,7 +398,7 @@ func TestSaveMultipleNetBoxesRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir()) t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{ cfg := config.Config{
NetBoxes: []config.NetBoxConfig{ NetBoxes: []config.NetBoxConfig{
{Name: "office", URL: "https://office.example/netbox", Token: "nbt_secret: office", TokenVersion: 2}, {Name: "office", URL: "https://office.example/netbox", Token: "nbt_secret: office", TokenVersion: 2, DisablePrefix: true},
{Name: "lab", URL: "https://lab.example", Token: "legacy#token", TokenVersion: 1}, {Name: "lab", URL: "https://lab.example", Token: "legacy#token", TokenVersion: 1},
}, },
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}}, Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
@@ -438,9 +438,10 @@ func TestSaveKeepsSSHOptions(t *testing.T) {
AddressFamily: "inet", AddressFamily: "inet",
ExtraArgs: []string{"-A"}, ExtraArgs: []string{"-A"},
Options: map[string]string{"serveraliveinterval": "60"}, Options: map[string]string{"serveraliveinterval": "60"},
PreConnect: `vpn-check "$NETSSH_HOST" && echo 'ok'`,
} }
cfg := config.Config{ cfg := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://prod.example", Token: "t", TokenVersion: 1, SSH: config.SSHOptions{HostKeyChecking: "off"}}}, NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://prod.example", Token: "t", TokenVersion: 1, SSH: config.SSHOptions{HostKeyChecking: "off", PreConnect: "none"}}},
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}}, Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
Cache: config.CacheConfig{TTL: 3600}, Cache: config.CacheConfig{TTL: 3600},
SSH: config.SSHConfig{ SSH: config.SSHConfig{
@@ -651,3 +652,122 @@ func TestParseGroupsAndSaveMulti(t *testing.T) {
t.Fatalf("got %v %+v", loaded.Groups, loaded.Multi) t.Fatalf("got %v %+v", loaded.Groups, loaded.Multi)
} }
} }
func TestSaveKeepsShortcutsShow(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
t.Setenv("HOME", t.TempDir())
for _, sc := range []config.ShortcutsConfig{
{Domains: []string{".example.com"}, Show: true},
{Show: true}, // no shortcut rules yet: the switch alone must survive
} {
cfg := config.Config{
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
Cache: config.CacheConfig{TTL: 3600},
Shortcuts: sc,
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
loaded, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !loaded.Shortcuts.Show || !reflect.DeepEqual(loaded.Shortcuts.Domains, sc.Domains) {
t.Fatalf("shortcuts lost: %+v", loaded.Shortcuts)
}
}
}
func TestSaveCommandsRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "https://netbox.example", Token: "test"},
Commands: map[string]config.HostCommand{
"mtr": {AliasPrefix: "m", Args: []string{"mtr", "--report", "{address}"}},
"ping": {AliasPrefix: "p", Args: []string{"ping", "-c", "3", "{address}"}},
},
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
got, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got.Commands, cfg.Commands) {
t.Fatalf("commands lost: %+v", got.Commands)
}
}
func TestOperationsRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "https://netbox.example", Token: "token"},
TUI: config.TUIConfig{HistoryLimit: 25},
Activity: config.ActivityConfig{Enabled: true, RetentionDays: 7, MaxEntries: 50},
SSH: config.SSHConfig{SSHOptions: config.SSHOptions{PostDisconnect: "echo done"}, Rules: []config.SSHRule{{Match: config.SSHMatch{Tag: "lab"}, SSHOptions: config.SSHOptions{PostDisconnect: "none"}}}},
Commands: map[string]config.HostCommand{"mtr": {Args: []string{"mtr", "{address}"}, AliasPrefix: "m", Timeout: "10s", Confirm: true, PostRun: "echo done", Match: config.SSHMatch{Tag: "router", Instance: "prod"}}},
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
got, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(got.TUI, cfg.TUI) || got.Activity != cfg.Activity || !reflect.DeepEqual(got.Commands, cfg.Commands) || !reflect.DeepEqual(got.SSH, cfg.SSH) {
t.Fatalf("round trip lost operations: %+v", got)
}
}
func TestSaveRoundtripNetBoxInsightSettings(t *testing.T) {
dir := t.TempDir()
t.Setenv("XDG_CONFIG_HOME", dir)
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "https://nb.example", Token: "keyring"},
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}, Fallback: true, FallbackTimeout: 400},
TUI: config.TUIConfig{HistoryLimit: 10, Columns: []string{"ip", "platform", "reachability"}, ReachabilityTimeout: 900},
SSH: config.SSHConfig{WarnStatus: []string{"planned"}, Rules: []config.SSHRule{{
Match: config.SSHMatch{Platform: "junos", Site: "fsn1", Role: "core", Tenant: "acme", Status: "active"},
SSHOptions: config.SSHOptions{ProxyJump: "jump"},
}}},
Commands: map[string]config.HostCommand{"cli": {Args: []string{"cli", "{address}"}, Match: config.SSHMatch{Platform: "eos"}}},
}
if err := Save(cfg); err != nil {
t.Fatal(err)
}
loaded, err := config.Load()
if err != nil {
t.Fatal(err)
}
if !loaded.Resolver.Fallback || loaded.Resolver.FallbackTimeout != 400 {
t.Fatalf("resolver lost: %+v", loaded.Resolver)
}
if !reflect.DeepEqual(loaded.TUI.Columns, []string{"ip", "platform", "reachability"}) || !loaded.TUI.ReachabilityEnabled() || loaded.TUI.ReachabilityTimeout != 900 {
t.Fatalf("tui lost: %+v", loaded.TUI)
}
if !loaded.SSH.WarnsStatus("planned") || loaded.SSH.WarnsStatus("offline") {
t.Fatalf("warn_status lost: %v", loaded.SSH.WarnStatus)
}
if got := loaded.SSH.Rules[0].Match; got != cfg.SSH.Rules[0].Match {
t.Fatalf("rule match lost: %+v", got)
}
if loaded.Commands["cli"].Match.Platform != "eos" {
t.Fatalf("command match lost: %+v", loaded.Commands["cli"].Match)
}
if !config.IsKeyringToken(loaded.NetBox.Token) || loaded.NetBox.TokenVersion != 0 {
t.Fatalf("keyring token changed: %+v", loaded.NetBox)
}
// Defaults stay implicit, so later default changes reach existing configs.
cfg = config.Config{NetBox: config.NetBoxConfig{URL: "https://nb.example"}, Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}}}
if err := Save(cfg); err != nil {
t.Fatal(err)
}
data, _ := os.ReadFile(filepath.Join(dir, "netssh.yaml"))
for _, key := range []string{"warn_status", "columns", "reachability", "fallback"} {
if strings.Contains(string(data), key) {
t.Errorf("default %s written:\n%s", key, data)
}
}
}
+17
View File
@@ -2,6 +2,7 @@ package ssh
import ( import (
"fmt" "fmt"
"net/netip"
"regexp" "regexp"
"sort" "sort"
"strings" "strings"
@@ -20,6 +21,8 @@ type WrapperFlags struct {
ForwardArgs []string ForwardArgs []string
// Tunnel runs ssh without a remote command (-N), for netssh tunnel. // Tunnel runs ssh without a remote command (-N), for netssh tunnel.
Tunnel bool Tunnel bool
// Force connects without asking about a NetBox status in ssh.warn_status.
Force bool
} }
// ExtractWrapperFlags removes netssh's long options that appear before the // ExtractWrapperFlags removes netssh's long options that appear before the
@@ -39,6 +42,8 @@ func (c Client) ExtractWrapperFlags(args []string) (WrapperFlags, []string, erro
flags.DryRun = true flags.DryRun = true
case arg == "--no-jump": case arg == "--no-jump":
flags.NoJump = true flags.NoJump = true
case arg == "--force":
flags.Force = true
case arg == "--jump": case arg == "--jump":
if i+1 >= len(args) { if i+1 >= len(args) {
return flags, nil, fmt.Errorf("--jump requires a host") return flags, nil, fmt.Errorf("--jump requires a host")
@@ -142,6 +147,18 @@ type Result struct {
Notice string Notice string
} }
var destinationName = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]*$`)
// ValidAddress reports whether addr is an IP address or a hostname. Addresses
// come from NetBox and the cache file; one such as "-oProxyCommand=…" would be
// read by ssh as an option and run a command.
func ValidAddress(addr string) bool {
if _, err := netip.ParseAddr(addr); err == nil {
return !strings.ContainsAny(addr, " \t\r\n")
}
return destinationName.MatchString(addr)
}
var plainHostname = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$`) var plainHostname = regexp.MustCompile(`^[A-Za-z0-9]([A-Za-z0-9._-]*[A-Za-z0-9])?$`)
// Apply replaces the destination at destIdx and inserts the configured -o // Apply replaces the destination at destIdx and inserts the configured -o
+14
View File
@@ -128,3 +128,17 @@ func TestQuote(t *testing.T) {
t.Fatalf("got %s", got) t.Fatalf("got %s", got)
} }
} }
func TestValidAddress(t *testing.T) {
for _, addr := range []string{"10.0.0.1", "fd00:30::60", "fe80::1%eth0", "web01", "web01.example.com", "db_1.lan"} {
if !ValidAddress(addr) {
t.Errorf("ValidAddress(%q) = false, want true", addr)
}
}
// ssh would read the first as an option and run the command.
for _, addr := range []string{"-oProxyCommand=touch /tmp/pwned", "-J", "", "a b", "host;id", "user@host", "host/path", "fe80::1%eth0 x", "$(id)"} {
if ValidAddress(addr) {
t.Errorf("ValidAddress(%q) = true, want false", addr)
}
}
}
+29
View File
@@ -0,0 +1,29 @@
package storage
import (
"os"
"path/filepath"
"testing"
)
func TestWriteFileReplacesAtomically(t *testing.T) {
dir := filepath.Join(t.TempDir(), "new", "dir")
path := filepath.Join(dir, "file")
for _, content := range []string{"first", "second"} {
if err := WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
got, err := os.ReadFile(path)
if err != nil || string(got) != content {
t.Fatalf("got %q, %v; want %q", got, err, content)
}
}
info, err := os.Stat(path)
if err != nil || info.Mode().Perm() != 0o600 {
t.Errorf("mode %v, %v; want 0600", info.Mode().Perm(), err)
}
entries, _ := os.ReadDir(dir)
if len(entries) != 1 {
t.Errorf("temporary files left behind: %v", entries)
}
}
+233
View File
@@ -0,0 +1,233 @@
package tui
import (
"errors"
"net"
"strconv"
"strings"
"testing"
"time"
tea "charm.land/bubbletea/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
func TestFilterByNetBoxAttributes(t *testing.T) {
entries := []netbox.HostEntry{
{Name: "sw1", Kind: "device", Status: "active", Site: config.Ref{Name: "FSN 1", Slug: "fsn1"}, Platform: config.Ref{Slug: "junos"}, Role: config.Ref{Slug: "core"}},
{Name: "sw2", Kind: "device", Status: "offline", Site: config.Ref{Slug: "nbg1"}, Platform: config.Ref{Slug: "junos"}},
{Name: "web", Kind: "vm", Status: "active", Site: config.Ref{Slug: "fsn1"}, Tenant: config.Ref{Name: "ACME"}},
}
for filter, want := range map[string]string{
"status:active": "sw1 web",
"site:fsn1": "sw1 web",
"site:FSN-1": "sw1",
"platform:junos status:active": "sw1",
"role:core": "sw1",
"tenant:acme kind:vm": "web",
"bogus": "sw1 sw2 web",
} {
var names []string
for _, e := range applyFilter(entries, parseFilter(filter)) {
names = append(names, e.Name)
}
if got := strings.Join(names, " "); got != want {
t.Errorf("%q: got %q, want %q", filter, got, want)
}
}
}
func TestStatusBadgeShownForInactiveHosts(t *testing.T) {
m := New(nil, nil, "")
m.updateListItems([]netbox.HostEntry{{Name: "a", Status: "active"}, {Name: "b", Status: "offline"}})
var out strings.Builder
for i, it := range m.list.Items() {
compactDelegate{marked: map[string]bool{}}.Render(&out, m.list, i, it)
out.WriteString("\n")
}
if strings.Contains(out.String(), "[active]") || !strings.Contains(out.String(), "[offline]") {
t.Fatalf("unexpected badges:\n%s", out.String())
}
}
func TestReachabilityProbesListedHosts(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Skip(err)
}
defer ln.Close()
port := ln.Addr().(*net.TCPAddr).Port
m := New(nil, nil, "")
m.SetReachability(time.Second, func(name, kind string, tags []string) (int, bool) {
return port, name != "behind-jump"
})
_, cmd := m.Update(searchResultMsg{query: "", recent: true, entries: []netbox.HostEntry{
{Name: "up", PrimaryIP4: "127.0.0.1"},
{Name: "behind-jump", PrimaryIP4: "127.0.0.1"},
}})
if cmd == nil {
t.Fatal("no probe started")
}
for _, msg := range runBatch(cmd) {
m.Update(msg)
}
up := hostItem{name: "up"}.key()
skipped := hostItem{name: "behind-jump"}.key()
if m.reach[up] != reachUp || m.reach[skipped] != reachSkipped {
t.Fatalf("states: %v", m.reach)
}
var out strings.Builder
m.list.Select(0)
compactDelegate{marked: m.marked, reach: m.reach}.Render(&out, m.list, 0, m.list.Items()[0])
if !strings.Contains(out.String(), "✓") {
t.Fatalf("reachable mark missing: %q", out.String())
}
// A second result list does not probe hosts that already have a state.
_, cmd = m.Update(searchResultMsg{query: "", recent: true, entries: []netbox.HostEntry{{Name: "up", PrimaryIP4: "127.0.0.1"}}})
if len(runBatch(cmd)) != 0 {
t.Fatal("host probed twice")
}
}
func TestUnreachableHostMarked(t *testing.T) {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
t.Skip(err)
}
port := ln.Addr().(*net.TCPAddr).Port
ln.Close()
m := New(nil, nil, "")
m.SetReachability(200*time.Millisecond, func(string, string, []string) (int, bool) { return port, true })
_, cmd := m.Update(searchResultMsg{recent: true, entries: []netbox.HostEntry{{Name: "down", PrimaryIP4: "127.0.0.1"}}})
for _, msg := range runBatch(cmd) {
m.Update(msg)
}
if m.reach[hostItem{name: "down"}.key()] != reachDown {
t.Fatalf("states: %v", m.reach)
}
}
// runBatch executes a command and the commands of a batch it returns.
func runBatch(cmd tea.Cmd) []tea.Msg {
if cmd == nil {
return nil
}
msg := cmd()
if batch, ok := msg.(tea.BatchMsg); ok {
var out []tea.Msg
for _, c := range batch {
out = append(out, runBatch(c)...)
}
return out
}
if msg == nil {
return nil
}
return []tea.Msg{msg}
}
func TestDetailViewLoadsAndConnects(t *testing.T) {
m := New(nil, nil, "")
var asked string
m.SetDetails(func(name, kind string, id int) (string, error) {
asked = name + "/" + strconv.Itoa(id)
return "sw1 (device)\n Site FSN1\n", nil
})
m.updateListItems([]netbox.HostEntry{{Name: "sw1", ID: 7, Kind: "device", PrimaryIP4: "10.0.0.7"}})
_, cmd := m.Update(tea.KeyPressMsg{Code: 'l', Mod: tea.ModCtrl})
if m.detailHost == nil || !strings.Contains(m.viewContent(), "Loading") {
t.Fatal("detail view not opened")
}
m.Update(cmd())
if asked != "sw1/7" || !strings.Contains(m.viewContent(), "Site FSN1") {
t.Fatalf("details not shown (asked %q):\n%s", asked, m.viewContent())
}
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if m.selected == nil || m.selected.Name != "sw1" {
t.Fatalf("enter in detail view should connect: %+v", m.selected)
}
}
func TestDetailViewShowsErrorAndEscCloses(t *testing.T) {
m := New(nil, nil, "")
m.SetDetails(func(string, string, int) (string, error) { return "", errors.New("boom") })
m.updateListItems([]netbox.HostEntry{{Name: "sw1"}})
_, cmd := m.Update(tea.KeyPressMsg{Code: 'l', Mod: tea.ModCtrl})
m.Update(cmd())
if !strings.Contains(m.viewContent(), "Error: boom") {
t.Fatalf("error not shown:\n%s", m.viewContent())
}
m.Update(tea.KeyPressMsg{Code: tea.KeyEscape})
if m.detailHost != nil || m.selected != nil {
t.Fatal("esc should close the detail view without selecting")
}
}
func TestCtrlGOpensNetBoxPage(t *testing.T) {
m := New(nil, nil, "")
var opened string
m.SetOpener(func(name, kind string, id int) error { opened = name; return nil })
m.updateListItems([]netbox.HostEntry{{Name: "web", Kind: "vm"}})
_, cmd := m.Update(tea.KeyPressMsg{Code: 'g', Mod: tea.ModCtrl})
if cmd == nil || m.selected != nil {
t.Fatal("ctrl+g must not quit the TUI")
}
m.Update(cmd())
if opened != "web" || !strings.Contains(m.viewContent(), "opened web in NetBox") {
t.Fatalf("opened %q:\n%s", opened, m.viewContent())
}
}
func TestConfiguredColumns(t *testing.T) {
m := New(nil, nil, "")
m.SetColumns([]string{"platform", "site", "tags", "kind"})
m.updateListItems([]netbox.HostEntry{{Name: "sw1", Kind: "device", PrimaryIP4: "10.0.0.7", Status: "offline", Tags: []string{"core", "dc"},
Site: config.Ref{Name: "FSN 1", Slug: "fsn1"}, Platform: config.Ref{Slug: "junos"}}})
var out strings.Builder
m.delegate().Render(&out, m.list, 1, m.list.Items()[0])
got := out.String()
for _, want := range []string{"platform:junos", "site:fsn1", "#core #dc", "[device]"} {
if !strings.Contains(got, want) {
t.Errorf("missing %q in %q", want, got)
}
}
if strings.Contains(got, "10.0.0.7") || strings.Contains(got, "[offline]") || strings.Contains(got, "[live]") {
t.Fatalf("columns not configured must be hidden: %q", got)
}
if strings.Index(got, "platform:") > strings.Index(got, "site:") {
t.Fatalf("configured order not kept: %q", got)
}
m.SetColumns(nil)
out.Reset()
m.delegate().Render(&out, m.list, 1, m.list.Items()[0])
if got := out.String(); !strings.HasSuffix(strings.TrimSpace(got), "sw1") {
t.Fatalf("empty column list should show only the name: %q", got)
}
}
func TestLocationColumnAndFilter(t *testing.T) {
entries := []netbox.HostEntry{
{Name: "srv1", Site: config.Ref{Name: "FSN1"}, Location: []config.Ref{{Name: "Building A", Slug: "building-a"}, {Name: "Room 2.04", Slug: "room-2-04"}}, Rack: "R12", Position: "20"},
{Name: "srv2", Site: config.Ref{Name: "NBG1"}, Location: []config.Ref{{Name: "Hall 1", Slug: "hall-1"}}, Rack: "B03"},
}
for filter, want := range map[string]string{"location:building-a": "srv1", "location:room-2-04": "srv1", "rack:b03": "srv2", "location:hall-1": "srv2"} {
var names []string
for _, e := range applyFilter(entries, parseFilter(filter)) {
names = append(names, e.Name)
}
if got := strings.Join(names, " "); got != want {
t.Errorf("%q: got %q, want %q", filter, got, want)
}
}
m := New(nil, nil, "")
m.SetColumns([]string{"location"})
m.updateListItems(entries[:1])
var out strings.Builder
m.delegate().Render(&out, m.list, 1, m.list.Items()[0])
if !strings.Contains(out.String(), "FSN1 › Building A › Room 2.04 › R12 › U20") {
t.Fatalf("location column: %q", out.String())
}
}
+114
View File
@@ -9,6 +9,7 @@ import (
tea "charm.land/bubbletea/v2" tea "charm.land/bubbletea/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
) )
@@ -79,3 +80,116 @@ func TestPartialOutageKeepsLiveAndCachedResultsVisible(t *testing.T) {
t.Fatalf("outage warning overflowed view: %d", rows) t.Fatalf("outage warning overflowed view: %d", rows)
} }
} }
func TestHiddenPrefixKeepsCanonicalTargets(t *testing.T) {
cfg := config.Config{NetBoxes: []config.NetBoxConfig{
{Name: "OFFICE", DisablePrefix: true}, {Name: "lab"},
}}
for _, cached := range []bool{false, true} {
for _, action := range []string{"ssh", "sftp", "multi", "autocomplete", "edit", "tunnel"} {
t.Run(fmt.Sprintf("cached=%v/%s", cached, action), func(t *testing.T) {
m := New(nil, nil, "")
m.SetHostLabel(cfg.HostLabel)
m.Update(tea.WindowSizeMsg{Width: 100, Height: 24})
entries := []netbox.HostEntry{
{Source: "office", Name: "web01", PrimaryIP4: "10.0.0.1"},
{Source: "lab", Name: "web01", PrimaryIP4: "10.0.0.2"},
}
if cached {
for i := range entries {
entries[i].Name = entries[i].Target()
entries[i].Source = ""
}
}
m.updateListItems(entries)
item := m.list.Items()[0].(hostItem)
if item.Title() != "web01" || item.name != "office/web01" {
t.Fatalf("display changed identity: %+v", item)
}
view := m.View().Content
if strings.Contains(view, "office/web01") || !strings.Contains(view, "lab/web01") {
t.Fatalf("wrong rendered prefixes: %s", view)
}
switch action {
case "ssh", "sftp":
key := tea.KeyPressMsg{Code: tea.KeyEnter}
if action == "sftp" {
key = tea.KeyPressMsg{Code: 'o', Mod: tea.ModCtrl}
}
m.Update(key)
if m.selected == nil || m.selected.Name != "office/web01" {
t.Fatalf("lost instance: %+v", m.selected)
}
case "multi":
m.Update(tea.KeyPressMsg{Code: tea.KeySpace, Text: " "})
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if m.selected == nil || len(m.selected.Targets) != 1 || m.selected.Targets[0] != "office/web01" {
t.Fatalf("multi lost instance: %+v", m.selected)
}
case "autocomplete":
m.Update(tea.KeyPressMsg{Code: tea.KeyTab})
if m.input.Value() != "office/web01" {
t.Fatal("autocomplete lost instance")
}
case "edit":
m.Update(tea.KeyPressMsg{Code: 'e', Mod: tea.ModCtrl})
if m.editHost == nil || m.editHost.name != "office/web01" {
t.Fatal("editor lost instance")
}
case "tunnel":
m.Update(tea.KeyPressMsg{Code: 't', Mod: tea.ModCtrl})
if m.forwardHost == nil || m.forwardHost.name != "office/web01" {
t.Fatal("tunnel lost instance")
}
}
})
}
}
}
func TestHiddenPrefixDuplicateLabels(t *testing.T) {
cfg := config.Config{NetBoxes: []config.NetBoxConfig{
{Name: "office", DisablePrefix: true}, {Name: "lab", DisablePrefix: true},
}}
for _, other := range []netbox.HostEntry{
{Source: "lab", Name: "WEB"},
{Name: "web", Kind: "static"},
} {
m := New(nil, nil, "")
m.SetHostLabel(cfg.HostLabel)
m.updateListItems([]netbox.HostEntry{{Source: "office", Name: "web"}, other})
for _, entry := range m.list.Items() {
item := entry.(hostItem)
if item.Title() != item.name {
t.Fatalf("ambiguous label: %+v", item)
}
}
}
}
func TestAliasesShownNextToHostName(t *testing.T) {
m := New(nil, cache.New("", 3600), "")
m.SetAliases(func(target string) string {
return map[string]string{"fsn1-bx1.hoster.de": "fsnbx1", "web01": "web01"}[target]
})
m.updateListItems([]netbox.HostEntry{{Name: "fsn1-bx1.hoster.de", PrimaryIP4: "10.0.0.1"}, {Name: "web01", PrimaryIP4: "10.0.0.2"}})
items := m.list.Items()
if got := items[0].(hostItem).alias; got != "fsnbx1" {
t.Fatalf("alias = %q", got)
}
// An alias equal to the shown name is not repeated.
if got := items[1].(hostItem).alias; got != "" {
t.Fatalf("redundant alias %q", got)
}
var b strings.Builder
compactDelegate{marked: map[string]bool{}}.Render(&b, m.list, 1, items[0])
if !strings.Contains(b.String(), "fsn1-bx1.hoster.de") || !strings.Contains(b.String(), "→ fsnbx1") {
t.Fatalf("row %q", b.String())
}
// Without SetAliases nothing changes.
plain := New(nil, cache.New("", 3600), "")
plain.updateListItems([]netbox.HostEntry{{Name: "fsn1-bx1.hoster.de"}})
if got := plain.list.Items()[0].(hostItem).alias; got != "" {
t.Fatalf("alias without SetAliases: %q", got)
}
}
+594 -26
View File
@@ -4,6 +4,7 @@ import (
"context" "context"
"fmt" "fmt"
"io" "io"
"net"
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
@@ -22,6 +23,7 @@ import (
// SelectedHost is returned when the user confirms a host in the TUI. // SelectedHost is returned when the user confirms a host in the TUI.
type SelectedHost struct { type SelectedHost struct {
Command string
Kind string Kind string
Name string Name string
IP string IP string
@@ -52,6 +54,25 @@ type noteResultMsg struct {
saved bool saved bool
} }
// reachMsg is the result of probing a listed host's SSH port.
type reachMsg struct {
key string
state reachState
}
// detailMsg carries the text of the detail view (ctrl+l).
type detailMsg struct {
key string
text string
err error
}
// flashMsg is a short notice in the footer, e.g. after opening NetBox.
type flashMsg struct {
text string
err error
}
type searchResultMsg struct { type searchResultMsg struct {
query string query string
seq int seq int
@@ -63,21 +84,112 @@ type searchResultMsg struct {
// --- list item --- // --- list item ---
type hostItem struct { type hostItem struct {
name string provenance string
id int favorite, pinned bool
ip string label string // display only; name remains the canonical target
kind string alias string // shortcut alias shown next to the name (shortcuts.show)
tags []string name string
id int
ip string
kind string
tags []string
status string
site, role string
platform, tenant string
cluster string
location string // site › locations › rack › U
} }
func (h hostItem) Title() string { return h.name } func (h hostItem) Title() string {
if h.label != "" {
return h.label
}
return h.name
}
func (h hostItem) Description() string { return fmt.Sprintf("%s [%s]", h.ip, h.kind) } func (h hostItem) Description() string { return fmt.Sprintf("%s [%s]", h.ip, h.kind) }
func (h hostItem) FilterValue() string { return h.name } func (h hostItem) FilterValue() string { return h.name }
// --- compact list delegate --- // --- compact list delegate ---
// reachState is the result of the reachability probe of a host.
type reachState uint8
const (
reachUnknown reachState = iota
reachPending
reachUp
reachDown
reachSkipped // behind a jump host: not probed
)
// compactDelegate shares the model's marks so marked hosts show a dot. // compactDelegate shares the model's marks so marked hosts show a dot.
type compactDelegate struct{ marked map[string]bool } // With reach set, a column shows whether the SSH port answers.
type compactDelegate struct {
marked map[string]bool
reach map[string]reachState
columns []string // nil = defaultColumns
}
// defaultColumns matches config.DefaultTUIColumns.
var defaultColumns = []string{"alias", "ip", "source", "status"}
var (
dimStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("240"))
attrStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("244"))
aliasStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("109"))
statusStyle = lipgloss.NewStyle().Foreground(lipgloss.Color("214"))
)
// column renders one configured column of a host, or "" when it is empty.
func (h hostItem) column(name string) string {
attr := func(key, value string) string {
if value == "" {
return ""
}
return attrStyle.Render(key + ":" + value)
}
switch name {
case "alias":
if h.alias != "" {
return aliasStyle.Render("→ " + h.alias)
}
case "ip":
if h.ip != "" {
return dimStyle.Render(h.ip)
}
case "kind":
if h.kind != "" {
return "[" + h.kind + "]"
}
case "source":
if h.provenance != "" {
return "[" + h.provenance + "]"
}
case "status":
if h.status != "" && !strings.EqualFold(h.status, "active") {
return statusStyle.Render("[" + h.status + "]")
}
case "site":
return attr("site", h.site)
case "location":
if h.location != "" {
return attrStyle.Render("⌂ " + h.location)
}
case "role":
return attr("role", h.role)
case "platform":
return attr("platform", h.platform)
case "tenant":
return attr("tenant", h.tenant)
case "cluster":
return attr("cluster", h.cluster)
case "tags":
if len(h.tags) > 0 {
return attrStyle.Render("#" + strings.Join(h.tags, " #"))
}
}
return ""
}
func (d compactDelegate) Height() int { return 1 } func (d compactDelegate) Height() int { return 1 }
func (d compactDelegate) Spacing() int { return 0 } func (d compactDelegate) Spacing() int { return 0 }
@@ -91,7 +203,36 @@ func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list.
if d.marked[h.key()] { if d.marked[h.key()] {
mark = "● " mark = "● "
} }
line := fmt.Sprintf(" %s%s %s", mark, h.name, lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip)) badge := ""
if h.pinned {
badge = "◆ "
} else if h.favorite {
badge = "★ "
}
columns := d.columns
if columns == nil {
columns = defaultColumns
}
// The reachability mark is a fixed-width prefix so names stay aligned.
reach := ""
if d.reach != nil {
switch d.reach[h.key()] {
case reachUp:
reach = lipgloss.NewStyle().Foreground(lipgloss.Color("2")).Render("✓") + " "
case reachDown:
reach = lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Render("✗") + " "
case reachPending:
reach = dimStyle.Render("·") + " "
default:
reach = " "
}
}
line := " " + mark + reach + badge + h.Title()
for _, name := range columns {
if text := h.column(name); text != "" {
line += " " + text
}
}
if index == m.Index() { if index == m.Index() {
line = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("> " + strings.TrimPrefix(line, " ")) line = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("> " + strings.TrimPrefix(line, " "))
} }
@@ -101,24 +242,47 @@ func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list.
// --- filter --- // --- filter ---
type filterOpts struct { type filterOpts struct {
tags []string tags []string
kind string kind string
status, site, role, platform, tenant string
location string
}
func (f filterOpts) empty() bool {
return len(f.tags) == 0 && f.kind == "" && f.status == "" && f.site == "" && f.role == "" && f.platform == "" && f.tenant == "" && f.location == ""
} }
func parseFilter(s string) filterOpts { func parseFilter(s string) filterOpts {
var f filterOpts var f filterOpts
for _, part := range strings.Fields(s) { for _, part := range strings.Fields(s) {
if after, ok := strings.CutPrefix(part, "tag:"); ok { key, value, ok := strings.Cut(part, ":")
f.tags = append(f.tags, after) if !ok {
} else if after, ok := strings.CutPrefix(part, "kind:"); ok { continue
f.kind = after }
switch strings.ToLower(key) {
case "tag":
f.tags = append(f.tags, value)
case "kind":
f.kind = value
case "status":
f.status = value
case "site":
f.site = value
case "role":
f.role = value
case "platform":
f.platform = value
case "tenant":
f.tenant = value
case "location", "rack":
f.location = value
} }
} }
return f return f
} }
func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry { func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
if len(f.tags) == 0 && f.kind == "" { if f.empty() {
return entries return entries
} }
out := make([]netbox.HostEntry, 0, len(entries)) out := make([]netbox.HostEntry, 0, len(entries))
@@ -126,6 +290,14 @@ func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
if f.kind != "" && e.Kind != f.kind { if f.kind != "" && e.Kind != f.kind {
continue continue
} }
if f.status != "" && !strings.EqualFold(e.Status, f.status) {
continue
}
if f.site != "" && !e.Site.Matches(f.site) || f.role != "" && !e.Role.Matches(f.role) ||
f.platform != "" && !e.Platform.Matches(f.platform) || f.tenant != "" && !e.Tenant.Matches(f.tenant) ||
f.location != "" && !inLocation(e, f.location) {
continue
}
if len(f.tags) > 0 { if len(f.tags) > 0 {
tagSet := make(map[string]bool, len(e.Tags)) tagSet := make(map[string]bool, len(e.Tags))
for _, t := range e.Tags { for _, t := range e.Tags {
@@ -150,6 +322,14 @@ func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
// --- Model --- // --- Model ---
type Model struct { type Model struct {
historyLimit int
favorites, pinned map[string]bool
savePreferences func(map[string]bool, map[string]bool) error
commandsFor func(string, string, []string) []string
actionHost *hostItem
actionNames []string
actionIndex int
noteErr error noteErr error
editHost *hostItem editHost *hostItem
noteInput textarea.Model noteInput textarea.Model
@@ -181,7 +361,20 @@ type Model struct {
editMode bool // Ctrl+E on the selected item editMode bool // Ctrl+E on the selected item
forwardMode bool // Ctrl+T on the selected item forwardMode bool // Ctrl+T on the selected item
marked map[string]bool // hostItem.key() of hosts marked with space marked map[string]bool // hostItem.key() of hosts marked with space
markOrder []string // targets in the order they were marked hostLabel func(string) string
aliasFor func(string) string // shortcut alias per target, "" for none
markOrder []string // targets in the order they were marked
columns []string // nil = defaultColumns
reach map[string]reachState // probe results by hostItem.key()
reachTimeout time.Duration
reachPort func(name, kind string, tags []string) (port int, probe bool)
opener func(name, kind string, id int) error
details func(name, kind string, id int) (string, error)
detailHost *hostItem
detailText string
detailErr error
flash string
} }
func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts ...int) *Model { func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts ...int) *Model {
@@ -190,7 +383,7 @@ func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts
ti.Focus() ti.Focus()
fi := textinput.New() fi := textinput.New()
fi.Placeholder = "tag:prod kind:vm" fi.Placeholder = "tag:prod kind:vm status:active site:fsn1 location:room-2 role:router platform:junos"
fi.Prompt = "Filter: " fi.Prompt = "Filter: "
ei := textinput.New() ei := textinput.New()
@@ -216,6 +409,7 @@ func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts
ni.CharLimit = 0 ni.CharLimit = 0
ni.SetHeight(10) ni.SetHeight(10)
return &Model{ return &Model{
historyLimit: 10, favorites: map[string]bool{}, pinned: map[string]bool{},
noteInput: ni, noteInput: ni,
defaultPort: port, defaultPort: port,
input: ti, input: ti,
@@ -237,14 +431,40 @@ func (m *Model) Init() tea.Cmd {
// loadRecent returns a Cmd that immediately resolves to the recently-used host list. // loadRecent returns a Cmd that immediately resolves to the recently-used host list.
func (m *Model) loadRecent() tea.Cmd { func (m *Model) loadRecent() tea.Cmd {
favoriteNames, pinned, limit := copyBools(m.favorites), copyBools(m.pinned), m.historyLimit
return func() tea.Msg { return func() tea.Msg {
if m.cache == nil { if m.cache == nil {
return searchResultMsg{query: "", entries: nil, recent: true} return searchResultMsg{query: "", entries: nil, recent: true}
} }
recent := m.cache.RecentlyUsed(10) recent := m.cache.RecentlyUsed(limit)
seen := map[string]bool{}
var favorites []cache.Entry
for name, enabled := range favoriteNames {
if !enabled {
continue
}
e, _ := m.cache.Get(name)
if e.Name == "" {
e.Name = name
}
favorites = append(favorites, e)
seen[name] = true
}
sort.Slice(favorites, func(i, j int) bool {
if pinned[favorites[i].Name] != pinned[favorites[j].Name] {
return pinned[favorites[i].Name]
}
return favorites[i].Name < favorites[j].Name
})
for _, e := range recent {
if !seen[e.Name] {
favorites = append(favorites, e)
}
}
recent = favorites
entries := make([]netbox.HostEntry, len(recent)) entries := make([]netbox.HostEntry, len(recent))
for i, e := range recent { for i, e := range recent {
entries[i] = netbox.HostEntry{Name: e.Name, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags} entries[i] = entryFromCache(e, false)
} }
return searchResultMsg{query: "", entries: entries, recent: true} return searchResultMsg{query: "", entries: entries, recent: true}
} }
@@ -268,6 +488,25 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
} }
return m, nil return m, nil
case reachMsg:
if m.reach != nil {
m.reach[msg.key] = msg.state
}
return m, nil
case detailMsg:
if m.detailHost != nil && m.detailHost.key() == msg.key {
m.detailText, m.detailErr = msg.text, msg.err
}
return m, nil
case flashMsg:
m.flash = msg.text
if msg.err != nil {
m.flash = "error: " + msg.err.Error()
}
return m, nil
case tea.WindowSizeMsg: case tea.WindowSizeMsg:
m.width = msg.Width m.width = msg.Width
m.height = msg.Height m.height = msg.Height
@@ -281,6 +520,51 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if msg.String() == "ctrl+c" { if msg.String() == "ctrl+c" {
return m, tea.Quit return m, tea.Quit
} }
if m.flash != "" {
m.flash = ""
}
if m.detailHost != nil {
switch msg.String() {
case "esc", "ctrl+l", "q":
m.detailHost = nil
m.input.Focus()
case "enter":
h := m.detailHost
m.selected = &SelectedHost{Name: h.name, IP: h.ip, Kind: h.kind}
return m, tea.Quit
case "ctrl+g":
return m, m.openCmd(*m.detailHost)
}
return m, nil
}
if m.actionHost != nil {
switch msg.String() {
case "esc":
m.actionHost = nil
case "up":
if m.actionIndex > 0 {
m.actionIndex--
}
case "down":
if m.actionIndex+1 < len(m.actionNames) {
m.actionIndex++
}
case "enter":
h := m.actionHost
if m.actionIndex == 0 {
if len(m.markOrder) > 0 {
m.selected = &SelectedHost{Action: ActionMulti, Targets: append([]string(nil), m.markOrder...)}
} else {
m.selected = &SelectedHost{Name: h.name, Kind: h.kind, IP: h.ip}
}
} else {
m.selected = &SelectedHost{Name: h.name, Kind: h.kind, IP: h.ip, Command: m.actionNames[m.actionIndex], Targets: append([]string(nil), m.markOrder...)}
}
return m, tea.Quit
}
return m, nil
}
if m.noteMode { if m.noteMode {
if m.noteBusy { if m.noteBusy {
return m, nil return m, nil
@@ -390,6 +674,43 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case "ctrl+c", "esc": case "ctrl+c", "esc":
return m, tea.Quit return m, tea.Quit
case "ctrl+r":
if h, ok := m.list.SelectedItem().(hostItem); ok {
m.actionHost = &h
m.actionIndex = 0
m.actionNames = []string{"SSH"}
if m.commandsFor != nil {
m.actionNames = append(m.actionNames, m.commandsFor(h.name, h.kind, h.tags)...)
}
}
return m, nil
case "ctrl+d", "ctrl+p":
if h, ok := m.list.SelectedItem().(hostItem); ok {
favorites, pinned := copyBools(m.favorites), copyBools(m.pinned)
if msg.String() == "ctrl+p" {
pinned[h.name] = !pinned[h.name]
if pinned[h.name] {
favorites[h.name] = true
}
} else {
favorites[h.name] = !favorites[h.name]
if !favorites[h.name] {
delete(pinned, h.name)
}
}
if m.savePreferences != nil {
if err := m.savePreferences(favorites, pinned); err != nil {
m.err = err
return m, nil
}
}
m.favorites, m.pinned = favorites, pinned
m.updateListItems(m.lastResults)
if m.recentMode && m.input.Value() == "" {
return m, m.loadRecent()
}
}
return m, nil
case "ctrl+f": case "ctrl+f":
m.filterOpen = true m.filterOpen = true
m.input.Blur() m.input.Blur()
@@ -429,6 +750,25 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
return m, tea.Quit return m, tea.Quit
} }
case "ctrl+g":
if item, ok := m.list.SelectedItem().(hostItem); ok {
return m, m.openCmd(item)
}
return m, nil
case "ctrl+l":
if item, ok := m.list.SelectedItem().(hostItem); ok && m.details != nil {
m.detailHost = &item
m.detailText, m.detailErr = "", nil
m.input.Blur()
details, key := m.details, item.key()
return m, func() tea.Msg {
text, err := details(item.name, item.kind, item.id)
return detailMsg{key: key, text: text, err: err}
}
}
return m, nil
case "ctrl+t": case "ctrl+t":
if item, ok := m.list.SelectedItem().(hostItem); ok { if item, ok := m.list.SelectedItem().(hostItem); ok {
m.forwardMode = true m.forwardMode = true
@@ -492,7 +832,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.recentMode = true m.recentMode = true
m.lastResults = msg.entries m.lastResults = msg.entries
m.updateListItems(msg.entries) m.updateListItems(msg.entries)
return m, nil return m, m.probeCmd()
} }
if msg.seq != m.seq || msg.query != m.input.Value() { if msg.seq != m.seq || msg.query != m.input.Value() {
return m, nil // discard stale result return m, nil // discard stale result
@@ -501,7 +841,7 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
m.err = msg.err m.err = msg.err
m.lastResults = msg.entries m.lastResults = msg.entries
m.updateListItems(msg.entries) m.updateListItems(msg.entries)
return m, nil return m, m.probeCmd()
} }
if m.noteMode { if m.noteMode {
@@ -550,6 +890,50 @@ func (m *Model) View() tea.View {
} }
func (m *Model) viewContent() string { func (m *Model) viewContent() string {
if m.detailHost != nil {
var out strings.Builder
title := lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("Details — " + m.detailHost.Title())
out.WriteString(title + "\n\n")
switch {
case m.detailErr != nil:
out.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("9")).Render("Error: "+m.detailErr.Error()) + "\n")
case m.detailText == "":
out.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render("Loading…") + "\n")
default:
text := m.detailText
if m.height > 4 {
lines := strings.Split(strings.TrimRight(text, "\n"), "\n")
if len(lines) > m.height-4 {
lines = append(lines[:m.height-5], "…")
}
text = strings.Join(lines, "\n") + "\n"
}
out.WriteString(text)
}
if m.flash != "" {
out.WriteString("\n" + m.flash + "\n")
}
out.WriteString("\n" + lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render("enter connect ctrl+g open in NetBox esc back") + "\n")
return out.String()
}
if m.actionHost != nil {
var out strings.Builder
fmt.Fprintf(&out, "Action for %s", m.actionHost.Title())
if len(m.markOrder) > 0 {
fmt.Fprintf(&out, " (%d marked hosts)", len(m.markOrder))
}
out.WriteString("\n\n")
for i, n := range m.actionNames {
marker := " "
if i == m.actionIndex {
marker = "> "
}
fmt.Fprintf(&out, "%s%s\n", marker, n)
}
out.WriteString("\n↑/↓ select enter run esc cancel\n")
return out.String()
}
if m.noteMode { if m.noteMode {
target := "local" target := "local"
if m.noteRemote { if m.noteRemote {
@@ -610,7 +994,10 @@ func (m *Model) viewContent() string {
sb.WriteString(m.editInput.View() + "\n") sb.WriteString(m.editInput.View() + "\n")
sb.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(" enter connect esc cancel") + "\n") sb.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(" enter connect esc cancel") + "\n")
} else { } else {
hint := "ctrl+c quit enter connect space mark ctrl+o sftp ctrl+t forward ctrl+e edit ctrl+f filter ctrl+n notes ctrl+b NetBox" hint := "ctrl+r actions ctrl+d favorite ctrl+p pin ctrl+c quit enter connect space mark ctrl+o sftp ctrl+t forward ctrl+e edit ctrl+f filter ctrl+n notes ctrl+b NetBox ctrl+l details ctrl+g NetBox page"
if m.flash != "" {
hint = m.flash
}
if n := len(m.markOrder); n > 0 { if n := len(m.markOrder); n > 0 {
hint = fmt.Sprintf("%d marked — enter open side by side space unmark ctrl+a all esc quit", n) hint = fmt.Sprintf("%d marked — enter open side by side space unmark ctrl+a all esc quit", n)
} }
@@ -638,8 +1025,7 @@ func (m *Model) doSearch(query string, seq int) tea.Cmd {
var cached []netbox.HostEntry var cached []netbox.HostEntry
if m.cache != nil { if m.cache != nil {
for _, entry := range m.cache.Search(query) { for _, entry := range m.cache.Search(query) {
source, name := netbox.SplitTarget(entry.Name) cached = append(cached, entryFromCache(entry, true))
cached = append(cached, netbox.HostEntry{Source: source, Name: name, PrimaryIP4: entry.IP, Kind: entry.Kind, Tags: entry.Tags})
} }
} }
if m.client == nil || (len(cached) > 0 && !m.client.MultipleSources()) { if m.client == nil || (len(cached) > 0 && !m.client.MultipleSources()) {
@@ -673,17 +1059,80 @@ func (m *Model) netboxSearchOpts() netbox.SearchOptions {
return netbox.SearchOptions{Tag: tag, Kind: f.kind} return netbox.SearchOptions{Tag: tag, Kind: f.kind}
} }
// entryFromCache converts a cache entry for the list. With split, the
// instance prefix becomes Source, like in live NetBox results.
func entryFromCache(e cache.Entry, split bool) netbox.HostEntry {
h := netbox.HostEntry{Name: e.Name, ID: e.ID, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster, Cached: true, CachedAt: e.CachedAt, Static: e.Static,
Status: e.Status, Site: cache.RefOf(e.Site), Role: cache.RefOf(e.Role), Platform: cache.RefOf(e.Platform), Tenant: cache.RefOf(e.Tenant),
Location: e.Location, Rack: e.Rack, Position: e.Position}
if split {
h.Source, h.Name = netbox.SplitTarget(e.Name)
}
return h
}
// updateListItems applies the active filter and sets the list items. // updateListItems applies the active filter and sets the list items.
func (m *Model) updateListItems(entries []netbox.HostEntry) { func (m *Model) updateListItems(entries []netbox.HostEntry) {
f := parseFilter(m.filterInput.Value()) f := parseFilter(m.filterInput.Value())
filtered := applyFilter(entries, f) filtered := append([]netbox.HostEntry(nil), applyFilter(entries, f)...)
sort.SliceStable(filtered, func(i, j int) bool {
rank := func(e netbox.HostEntry) int {
if m.pinned[e.Target()] {
return 2
}
if m.favorites[e.Target()] {
return 1
}
return 0
}
return rank(filtered[i]) > rank(filtered[j])
})
items := make([]list.Item, len(filtered)) items := make([]list.Item, len(filtered))
labels := make([]string, len(filtered))
counts := make(map[string]int, len(filtered))
canonical := make(map[string]bool, len(filtered))
for i, e := range filtered {
labels[i] = e.Target()
canonical[strings.ToLower(e.Target())] = true
if m.hostLabel != nil {
labels[i] = m.hostLabel(e.Target())
}
counts[strings.ToLower(labels[i])]++
}
for i, e := range filtered { for i, e := range filtered {
ip := e.PrimaryIP4 ip := e.PrimaryIP4
if ip == "" { if ip == "" {
ip = e.PrimaryIP6 ip = e.PrimaryIP6
} }
items[i] = hostItem{id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags} label := labels[i]
if label != e.Target() && (counts[strings.ToLower(label)] > 1 || canonical[strings.ToLower(label)]) {
label = e.Target()
}
alias := ""
if m.aliasFor != nil {
alias = m.aliasFor(e.Target())
if strings.EqualFold(alias, label) {
alias = ""
}
}
provenance := "live"
if e.Static {
provenance = "static"
} else if e.Cached {
if e.CachedAt.IsZero() {
provenance = "saved host; resolve on connect"
} else {
age := max(time.Duration(0), time.Since(e.CachedAt)).Round(time.Second)
provenance = "cache " + age.String()
if m.cache != nil {
if _, fresh := m.cache.Get(e.Target()); !fresh {
provenance += ", stale"
}
}
}
}
items[i] = hostItem{provenance: provenance, favorite: m.favorites[e.Target()], pinned: m.pinned[e.Target()], label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags, status: e.Status,
site: e.Site.Key(), role: e.Role.Key(), platform: e.Platform.Key(), tenant: e.Tenant.Key(), cluster: e.Cluster, location: e.LocationPath()}
} }
m.list.SetItems(items) m.list.SetItems(items)
m.resizeList() m.resizeList()
@@ -819,3 +1268,122 @@ func parseForwards(input string, available []string) ([]string, error) {
} }
return fields, nil return fields, nil
} }
// SetHostLabel sets the display name formatter without changing host identity.
// Configure it before the program starts, just like SetNotes and SetForwards.
func (m *Model) SetHostLabel(format func(string) string) {
m.hostLabel = format
}
// SetAliases shows the shortcut alias returned for each target next to its
// name; return "" for hosts without one. Configure it before the program starts.
func (m *Model) SetAliases(aliasFor func(target string) string) {
m.aliasFor = aliasFor
}
func copyBools(in map[string]bool) map[string]bool {
out := map[string]bool{}
for k, v := range in {
out[k] = v
}
return out
}
func (m *Model) SetHistoryLimit(limit int) { m.historyLimit = limit }
func (m *Model) SetPreferences(favorites, pinned map[string]bool, save func(map[string]bool, map[string]bool) error) {
m.favorites, m.pinned = copyBools(favorites), copyBools(pinned)
m.savePreferences = save
}
func (m *Model) SetCommands(commands func(string, string, []string) []string) {
m.commandsFor = commands
}
// SetReachability enables the reachability column: listed hosts are probed
// with a TCP connect to the port returned by portFor, unless it returns
// probe=false (for hosts behind a jump host). Configure it before the program starts.
func (m *Model) SetReachability(timeout time.Duration, portFor func(name, kind string, tags []string) (port int, probe bool)) {
if timeout <= 0 {
timeout = 300 * time.Millisecond
}
m.reach = map[string]reachState{}
m.reachTimeout = timeout
m.reachPort = portFor
m.list.SetDelegate(m.delegate())
}
// SetColumns selects what is shown next to each hostname, in order (see
// config.TUIColumns). "reachability" is ignored here: SetReachability
// enables the check. Configure it before the program starts.
func (m *Model) SetColumns(columns []string) {
m.columns = append([]string{}, columns...)
m.list.SetDelegate(m.delegate())
}
func (m *Model) delegate() compactDelegate {
return compactDelegate{marked: m.marked, reach: m.reach, columns: m.columns}
}
// probeCmd starts probes for listed hosts that have no result yet.
func (m *Model) probeCmd() tea.Cmd {
if m.reach == nil {
return nil
}
var cmds []tea.Cmd
for _, it := range m.list.Items() {
h, ok := it.(hostItem)
if !ok || m.reach[h.key()] != reachUnknown {
continue
}
key := h.key()
port, probe := 22, true
if m.reachPort != nil {
port, probe = m.reachPort(h.name, h.kind, h.tags)
}
if !probe || h.ip == "" {
m.reach[key] = reachSkipped
continue
}
m.reach[key] = reachPending
address, timeout := h.ip, m.reachTimeout
cmds = append(cmds, func() tea.Msg {
conn, err := net.DialTimeout("tcp", net.JoinHostPort(address, strconv.Itoa(port)), timeout)
if err != nil {
return reachMsg{key: key, state: reachDown}
}
_ = conn.Close()
return reachMsg{key: key, state: reachUp}
})
}
return tea.Batch(cmds...)
}
// SetOpener opens a host's NetBox page (ctrl+g). Configure it before the program starts.
func (m *Model) SetOpener(open func(name, kind string, id int) error) { m.opener = open }
// SetDetails provides the text of the detail view (ctrl+l). Configure it before the program starts.
func (m *Model) SetDetails(details func(name, kind string, id int) (string, error)) {
m.details = details
}
func (m *Model) openCmd(h hostItem) tea.Cmd {
if m.opener == nil {
return nil
}
open := m.opener
return func() tea.Msg {
if err := open(h.name, h.kind, h.id); err != nil {
return flashMsg{err: err}
}
return flashMsg{text: "opened " + h.name + " in NetBox"}
}
}
// inLocation reports whether a host is in the location want at any level of
// its location chain, or in the rack named want.
func inLocation(e netbox.HostEntry, want string) bool {
for _, location := range e.Location {
if location.Matches(want) {
return true
}
}
return want != "" && strings.EqualFold(e.Rack, want)
}
+67
View File
@@ -0,0 +1,67 @@
package tui
import (
"strings"
"testing"
"time"
tea "charm.land/bubbletea/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
func TestFavoritesHistoryAndActions(t *testing.T) {
c := cache.New("", 3600)
for _, name := range []string{"a", "b", "pinned"} {
c.Upsert(cache.Entry{Name: name, IP: "10.0.0.1", Kind: "device"})
c.MarkUsed(name)
}
m := New(nil, c, "")
m.SetHistoryLimit(1)
m.SetPreferences(map[string]bool{"pinned": true, "offline/missing": true}, map[string]bool{"pinned": true}, nil)
msg := m.loadRecent()().(searchResultMsg)
if len(msg.entries) < 2 || msg.entries[0].Target() != "pinned" {
t.Fatalf("%+v", msg.entries)
}
m.Update(msg)
m.Update(tea.WindowSizeMsg{Width: 160, Height: 30})
if !strings.Contains(m.View().Content, "◆") || !strings.Contains(m.View().Content, "cache") {
t.Fatal(m.View().Content)
}
m.SetCommands(func(name, kind string, tags []string) []string { return []string{"mtr"} })
m.Update(tea.KeyPressMsg{Code: 'r', Mod: tea.ModCtrl})
m.Update(tea.KeyPressMsg{Code: tea.KeyDown})
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if m.Selected() == nil || m.Selected().Command != "mtr" || m.Selected().Name != "pinned" {
t.Fatalf("%+v", m.Selected())
}
}
func TestHistoryLimitAndPreferencePersistence(t *testing.T) {
c := cache.New("", 3600)
for _, n := range []string{"a", "b", "c"} {
c.Upsert(cache.Entry{Name: n})
c.MarkUsed(n)
}
m := New(nil, c, "")
m.SetHistoryLimit(2)
if got := len(m.loadRecent()().(searchResultMsg).entries); got != 2 {
t.Fatal(got)
}
m.SetHistoryLimit(0)
if got := len(m.loadRecent()().(searchResultMsg).entries); got != 3 {
t.Fatal(got)
}
saved := false
m.SetPreferences(nil, nil, func(f, p map[string]bool) error { saved = f["prod/web"] && p["prod/web"]; return nil })
entries := []netbox.HostEntry{{Name: "web", Source: "prod", Cached: true, CachedAt: time.Now().Add(-2 * time.Hour)}}
m.lastResults = entries
m.updateListItems(entries)
m.Update(tea.KeyPressMsg{Code: 'p', Mod: tea.ModCtrl})
if !saved {
t.Fatal("pin not persisted")
}
item := m.list.Items()[0].(hostItem)
if !strings.Contains(item.provenance, "stale") {
t.Fatal(item.provenance)
}
}
+1 -1
View File
@@ -6,7 +6,7 @@
name: netssh-test name: netssh-test
x-netbox: &netbox x-netbox: &netbox
image: netboxcommunity/netbox:v4.7.4-5.1.1 image: netboxcommunity/netbox:v4.7.5-5.1.1
depends_on: depends_on:
postgres: {condition: service_healthy} postgres: {condition: service_healthy}
redis: {condition: service_healthy} redis: {condition: service_healthy}
+1 -1
View File
@@ -3,7 +3,7 @@
config_only </dev/null config_only </dev/null
rm -f "$XDG_CONFIG_HOME/netssh.yaml" rm -f "$XDG_CONFIG_HOME/netssh.yaml"
# no NetBox, static hosts, add, name, address, user, port, tags, back, save # no NetBox, static hosts, add, name, address, user, port, tags, back, save
out=$(python3 /tests/drive.py 2 4 1 legacy-box 10.231.0.50 admin "" legacy 5 9) out=$(python3 /tests/drive.py 2 4 1 legacy-box 10.231.0.50 admin "" legacy 5 11)
[[ $out == *"Config saved"* ]] && ok "configure saves" || bad "configure saves" "$out" [[ $out == *"Config saved"* ]] && ok "configure saves" || bad "configure saves" "$out"
expect_out "config has the host" 'address: "10.231.0.50"' cat "$XDG_CONFIG_HOME/netssh.yaml" expect_out "config has the host" 'address: "10.231.0.50"' cat "$XDG_CONFIG_HOME/netssh.yaml"
expect_eq "connect to the configured host" "admin" netssh legacy-box whoami expect_eq "connect to the configured host" "admin" netssh legacy-box whoami