Merge pull request 'feat: add pre_connect hook and optional shortcut alias display' (#43) from feat/pre-connect-hook-alias-display into main

This commit is contained in:
Sebi committed 2026-11-17 11:11:26 +00:00
commit 47f46929ba
15 files changed
+507 -23

No files matched your search

+5
View File
@@ -1,5 +1,10 @@
# Changelog # Changelog
## 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 ## 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: `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.
+70 -6
View File
@@ -21,7 +21,7 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int
- [Installation](#installation) - [Installation](#installation)
- [Quick start](#quick-start) - [Quick start](#quick-start)
- [Configuration](#configuration) — [wizard](#interactive-wizard), [manual config](#manual-config), [reference](#configuration-reference), [environment variables](#environment-variables), [files](#files-and-directories), [multiple instances](#multiple-netbox-instances) - [Configuration](#configuration) — [wizard](#interactive-wizard), [manual config](#manual-config), [reference](#configuration-reference), [environment variables](#environment-variables), [files](#files-and-directories), [multiple instances](#multiple-netbox-instances)
- [Usage](#usage) — [command overview](#command-overview), [SSH options](#ssh-options), [SFTP & SCP](#sftp-and-scp), [port forwarding](#port-forwarding), [static hosts](#static-hosts), [multiple servers](#multiple-servers-in-one-window), [shortcuts](#host-shortcuts), [TUI](#interactive-tui), [notes](#server-notes), [cache](#cache-management) - [Usage](#usage) — [command overview](#command-overview), [SSH options](#ssh-options), [pre-connect hook](#pre-connect-hook), [SFTP & SCP](#sftp-and-scp), [port forwarding](#port-forwarding), [static hosts](#static-hosts), [multiple servers](#multiple-servers-in-one-window), [shortcuts](#host-shortcuts), [TUI](#interactive-tui), [notes](#server-notes), [cache](#cache-management)
- [Hotkey cheat sheet](#hotkey-cheat-sheet) — search, editors, tmux and zellij - [Hotkey cheat sheet](#hotkey-cheat-sheet) — search, editors, tmux and zellij
- [Recipes](#recipes) - [Recipes](#recipes)
- [IP Resolution Strategies](#ip-resolution-strategies) - [IP Resolution Strategies](#ip-resolution-strategies)
@@ -148,12 +148,12 @@ A menu then gives access to every other setting; open only the sections you want
| Section | Settings | | Section | Settings |
|---|---| |---|---|
| SSH defaults | `ssh.default_user`, `ssh.default_port` | | SSH defaults | `ssh.default_user`, `ssh.default_port` |
| SSH options | `proxy_jump`, `host_key_checking`, `target`, `address_family`, `extra_args` (one per line), `options` (`Key=Value` per line), `forwards` (`NAME L\|R\|D SPEC` per line) | | SSH options | `proxy_jump`, `host_key_checking`, `target`, `address_family`, `extra_args` (one per line), `options` (`Key=Value` per line), `forwards` (`NAME L\|R\|D SPEC` per line), `pre_connect` |
| SSH rules | add, edit, remove `ssh.rules` — match by tag, instance, kind, name pattern, each with its own SSH options | | SSH rules | add, edit, remove `ssh.rules` — match by tag, instance, kind, name pattern, each with its own SSH options |
| Static hosts | add, edit, remove hosts that are not in NetBox, each with user, port, tags, and SSH options | | Static hosts | add, edit, remove hosts that are not in NetBox, each with user, port, tags, and SSH options |
| Multi-session | multiplexer (auto, tmux, zellij), panes per window, tmux keys for broadcast and excluding a pane, groups (`NAME: sel1, sel2` per line) | | Multi-session | multiplexer (auto, tmux, zellij), panes per window, tmux keys for broadcast and excluding a pane, groups (`NAME: sel1, sel2` per line) |
| Resolver & cache | strategies, management subnets, interface name, hostname domain, cache TTL, cache file | | Resolver & cache | strategies, management subnets, interface name, hostname domain, cache TTL, cache file |
| Shortcuts & command alias | domain suffixes, hyphen stripping, rewrite rules (`REGEX => REPLACEMENT` per line), `shell.alias` | | Shortcuts & command alias | domain suffixes, hyphen stripping, rewrite rules (`REGEX => REPLACEMENT` per line), show shortcuts (`shortcuts.show`), `shell.alias` |
| Completion | `completion.max_results` | | Completion | `completion.max_results` |
The result is validated and saved to `~/.config/netssh.yaml`; Ctrl+C cancels without writing. The result is validated and saved to `~/.config/netssh.yaml`; Ctrl+C cancels without writing.
@@ -228,10 +228,12 @@ Every key, its default, and the section that explains it. Keys marked *layered*
| `ssh.extra_args` | list | `[]` | *Layered.* Extra ssh arguments; accumulate across layers; ssh only. | | `ssh.extra_args` | list | `[]` | *Layered.* Extra ssh arguments; accumulate across layers; ssh only. |
| `ssh.options` | map | `{}` | *Layered.* `-o Key=Value`; per key, the more specific layer wins. | | `ssh.options` | map | `{}` | *Layered.* `-o Key=Value`; per key, the more specific layer wins. |
| `ssh.forwards` | map | `{}` | *Layered.* Named port forwards (`local`, `remote`, `dynamic`) — see [Port forwarding](#port-forwarding). | | `ssh.forwards` | map | `{}` | *Layered.* Named port forwards (`local`, `remote`, `dynamic`) — see [Port forwarding](#port-forwarding). |
| `ssh.pre_connect` | string | — | *Layered.* Shell command run locally before connecting; a non-zero exit aborts; `none` disables an inherited one — see [Pre-connect hook](#pre-connect-hook). |
| `ssh.rules[]` | list | `[]` | `match` (`tag`, `instance`, `kind`, `name`) plus any layered key. | | `ssh.rules[]` | list | `[]` | `match` (`tag`, `instance`, `kind`, `name`) plus any layered key. |
| `shortcuts.domains` | list | `[]` | Suffixes stripped for shortcuts and tried when expanding a short name. | | `shortcuts.domains` | list | `[]` | Suffixes stripped for shortcuts and tried when expanding a short name. |
| `shortcuts.strip_hyphens` | bool | `false` | Ignore hyphens when matching shortcuts. | | `shortcuts.strip_hyphens` | bool | `false` | Ignore hyphens when matching shortcuts. |
| `shortcuts.rewrites[]` | list | `[]` | `pattern` (Go regex) and `replace` — see [Host shortcuts](#host-shortcuts). | | `shortcuts.rewrites[]` | list | `[]` | `pattern` (Go regex) and `replace` — see [Host shortcuts](#host-shortcuts). |
| `shortcuts.show` | bool | `false` | Show each host's shortcut alias in the TUI, `netssh cache list` and `netssh hosts list`, and offer shortcuts in Tab completion even when the full name matches — see [Showing shortcuts](#showing-shortcuts). |
| `completion.max_results` | int | `0` | Hostnames offered per `<Tab>`; `0` = unlimited. | | `completion.max_results` | int | `0` | Hostnames offered per `<Tab>`; `0` = unlimited. |
| `shell.alias` | string | — | Short command name for netssh, e.g. `j` — see [Short command alias](#short-command-alias). | | `shell.alias` | string | — | Short command name for netssh, e.g. `j` — see [Short command alias](#short-command-alias). |
| `hosts[]` | list | `[]` | Static hosts with `name`, `address`, `user`, `port`, `tags`, `ssh` — see [Static hosts](#static-hosts). | | `hosts[]` | list | `[]` | Static hosts with `name`, `address`, `user`, `port`, `tags`, `ssh` — see [Static hosts](#static-hosts). |
@@ -250,8 +252,8 @@ These variables override the file. Lists are comma-separated (`NETSSH_SHORTCUTS_
| `NETSSH_RESOLVER_STRATEGIES`, `NETSSH_RESOLVER_MANAGEMENT_SUBNETS`, `NETSSH_RESOLVER_INTERFACE_NAME`, `NETSSH_RESOLVER_HOSTNAME_DOMAIN` | `resolver.*` | | `NETSSH_RESOLVER_STRATEGIES`, `NETSSH_RESOLVER_MANAGEMENT_SUBNETS`, `NETSSH_RESOLVER_INTERFACE_NAME`, `NETSSH_RESOLVER_HOSTNAME_DOMAIN` | `resolver.*` |
| `NETSSH_CACHE_TTL`, `NETSSH_CACHE_PATH` | `cache.*` | | `NETSSH_CACHE_TTL`, `NETSSH_CACHE_PATH` | `cache.*` |
| `NETSSH_SSH_DEFAULT_USER`, `NETSSH_SSH_DEFAULT_PORT` | `ssh.default_*` | | `NETSSH_SSH_DEFAULT_USER`, `NETSSH_SSH_DEFAULT_PORT` | `ssh.default_*` |
| `NETSSH_SSH_PROXY_JUMP`, `NETSSH_SSH_HOST_KEY_CHECKING`, `NETSSH_SSH_TARGET`, `NETSSH_SSH_ADDRESS_FAMILY` | global `ssh.*` options | | `NETSSH_SSH_PROXY_JUMP`, `NETSSH_SSH_HOST_KEY_CHECKING`, `NETSSH_SSH_TARGET`, `NETSSH_SSH_ADDRESS_FAMILY`, `NETSSH_SSH_PRE_CONNECT` | global `ssh.*` options |
| `NETSSH_SHORTCUTS_DOMAINS`, `NETSSH_SHORTCUTS_STRIP_HYPHENS` | `shortcuts.*` | | `NETSSH_SHORTCUTS_DOMAINS`, `NETSSH_SHORTCUTS_STRIP_HYPHENS`, `NETSSH_SHORTCUTS_SHOW` | `shortcuts.*` |
| `NETSSH_COMPLETION_MAX_RESULTS` | `completion.max_results` | | `NETSSH_COMPLETION_MAX_RESULTS` | `completion.max_results` |
| `NETSSH_MULTI_MULTIPLEXER`, `NETSSH_MULTI_PANES_PER_WINDOW` | `multi.*` | | `NETSSH_MULTI_MULTIPLEXER`, `NETSSH_MULTI_PANES_PER_WINDOW` | `multi.*` |
| `NETSSH_SHELL_ALIAS` | `shell.alias` | | `NETSSH_SHELL_ALIAS` | `shell.alias` |
@@ -508,7 +510,7 @@ Tags and kind are taken from the cache or the NetBox answer, so rules work offli
**How layers combine.** netssh merges global → instance (or the static host's own `ssh`) → matching rules: **How layers combine.** netssh merges global → instance (or the static host's own `ssh`) → matching rules:
- single values (`proxy_jump`, `host_key_checking`, `target`, `address_family`) — the most specific non-empty value wins; - single values (`proxy_jump`, `host_key_checking`, `target`, `address_family`, `pre_connect`) — the most specific non-empty value wins;
- `options` and `forwards` — merged per key or name, the more specific layer wins; - `options` and `forwards` — merged per key or name, the more specific layer wins;
- `extra_args` — collected from all layers. - `extra_args` — collected from all layers.
@@ -519,6 +521,46 @@ $ netssh --dry-run fw01.dmz.example.com
ssh -A -l admin -J dmz-jump.example.com -o StrictHostKeyChecking=accept-new -o serveraliveinterval=60 192.0.2.10 ssh -A -l admin -J dmz-jump.example.com -o StrictHostKeyChecking=accept-new -o serveraliveinterval=60 192.0.2.10
``` ```
### Pre-connect hook
`pre_connect` runs a shell command (`sh -c`) on your machine right before netssh
starts ssh, sftp, scp, or a tunnel — for example to check or bring up a VPN, or
to log connections. If the command exits non-zero, netssh prints an error and
does not connect.
```yaml
ssh:
pre_connect: 'wg show wg0 >/dev/null 2>&1 || { echo "VPN wg0 is down" >&2; exit 1; }'
rules:
- match: {tag: public}
pre_connect: none # no VPN needed for these hosts
netboxes:
- name: lab
url: "https://netbox-lab.example.com"
ssh:
pre_connect: 'lab-vpn up' # this instance needs its own VPN
```
It is a layered setting like `proxy_jump`: global → instance or static host →
matching rules, the most specific non-empty value wins, and `none` disables an
inherited hook. The hook gets the target in environment variables:
| Variable | Value |
|---|---|
| `NETSSH_HOST` | Hostname without instance prefix (`web01.example.com`) |
| `NETSSH_TARGET` | Name with instance prefix if any (`prod/web01.example.com`) |
| `NETSSH_INSTANCE` | NetBox instance, empty for a single NetBox or static hosts |
| `NETSSH_IP` | Resolved address netssh connects to |
| `NETSSH_KIND` | `device`, `vm`, or `static` |
| `NETSSH_TAGS` | Comma-separated tags |
| `NETSSH_CLIENT` | `ssh`, `sftp`, or `scp` |
The hook's output goes to stderr, so it never mixes with the output of a remote
command or an scp transfer; it can read from the terminal (e.g. a VPN password
prompt). `--dry-run` prints the hook without running it. `netssh multi` runs it
once per pane. It runs only for connections made through netssh, not for a plain
`ssh` call.
### SFTP and SCP ### SFTP and SCP
`netssh sftp` and `netssh scp` look up the host exactly like a connection does: cache, shortcuts and rewrite rules, `instance/host`, default user and port, SSH options and rules, `--jump`/`--no-jump`, and `--dry-run`. `netssh sftp` and `netssh scp` look up the host exactly like a connection does: cache, shortcuts and rewrite rules, `instance/host`, default user and port, SSH options and rules, `--jump`/`--no-jump`, and `--dry-run`.
@@ -708,6 +750,27 @@ Domains may be configured with or without a leading dot. If several cached hosts
| `fsn1web01` | `domains: [.example.com]`, `strip_hyphens: true` | `fsn1-web01.example.com` (cache only) | | `fsn1web01` | `domains: [.example.com]`, `strip_hyphens: true` | `fsn1-web01.example.com` (cache only) |
| `fsnbx1` | `domains: [.hoster.de]`, rewrite `^([a-z]+)[0-9]+-` → `$1` | `fsn1-bx1.hoster.de` (cache only) | | `fsnbx1` | `domains: [.hoster.de]`, rewrite `^([a-z]+)[0-9]+-` → `$1` | `fsn1-bx1.hoster.de` (cache only) |
#### Showing shortcuts
By default shortcuts work but stay out of sight. Set `shortcuts.show: true`
(or **Show shortcuts** in `netssh configure`, or `NETSSH_SHORTCUTS_SHOW=true`)
to see them:
- **TUI** — each host shows its alias next to the name: `fsn1-bx1.hoster.de → fsnbx1 10.0.0.5`.
- **Lists** — `netssh cache list` and `netssh hosts list` get an `ALIAS` column. Without the setting, `--aliases` shows it for one call.
- **Tab completion** — shortcuts are offered even when the full name matches what you typed: `fsn<Tab>` lists `fsn1-bx1.hoster.de` and `fsnbx1`.
The alias shown is the shell alias netssh generates for the host (see [Shell
aliases](#shell-aliases)), so you can type it directly. Hosts whose alias would
only replace dots (`web01_example_com`) show none.
```sh
$ netssh cache list --aliases
NAME ALIAS IP KIND CACHED AT
fsn1-bx1.hoster.de fsnbx1 10.0.0.5 device 2026-11-17T07:30:00+01:00
web01.other.de - 10.0.0.9 vm 2026-11-17T07:30:00+01:00
```
### Shell aliases ### Shell aliases
Generate shell aliases for all cached hosts based on the shortcut settings: Generate shell aliases for all cached hosts based on the shortcut settings:
@@ -808,6 +871,7 @@ See the [NetBox REST API documentation](https://netbox.readthedocs.io/en/stable/
```sh ```sh
netssh cache list # show all cached entries netssh cache list # show all cached entries
netssh cache list --aliases # … with each host's shortcut alias
netssh cache refresh # re-fetch ALL hosts from NetBox (paginated) netssh cache refresh # re-fetch ALL hosts from NetBox (paginated)
netssh cache refresh --tag prod # only hosts with the "prod" tag netssh cache refresh --tag prod # only hosts with the "prod" tag
netssh cache refresh --kind vm # only virtual machines netssh cache refresh --kind vm # only virtual machines
+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()
+40 -1
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"
) )
@@ -29,6 +30,28 @@ func newNetBoxClient(cfg *config.Config) *netbox.Client {
return netbox.NewClient(cfg.NetBox.URL, cfg.NetBox.Token, cfg.NetBox.TokenVersion) return netbox.NewClient(cfg.NetBox.URL, cfg.NetBox.Token, cfg.NetBox.TokenVersion)
} }
// 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 == "" {
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 {
return func(target string) string { return func(target string) string {
source, name := netbox.SplitTarget(target) source, name := netbox.SplitTarget(target)
@@ -48,6 +71,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 +101,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
+29 -3
View File
@@ -348,6 +348,9 @@ 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 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) execClient(client, client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags), flags)
} }
@@ -387,6 +390,10 @@ 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.SetHostLabel(cfg.HostLabel)
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, resolvedHost{Name: name, Kind: kind, Tags: tags}))
@@ -669,7 +676,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 {
@@ -685,13 +693,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 {
+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)
}
}
+4 -1
View File
@@ -67,6 +67,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
@@ -122,7 +125,7 @@ func Load() (*Config, error) {
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.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window"} {
if err := v.BindEnv(key); err != nil { if err := v.BindEnv(key); err != nil {
return nil, err return nil, err
} }
+21
View File
@@ -24,6 +24,21 @@ 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"`
}
// 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.
@@ -155,6 +170,9 @@ 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.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 +239,9 @@ 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.PreConnect) != "" {
out.PreConnect = override.PreConnect
}
return out return out
} }
+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)
}
}
+10
View File
@@ -23,6 +23,7 @@ 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
err := huh.NewForm(huh.NewGroup( err := huh.NewForm(huh.NewGroup(
huh.NewInput(). huh.NewInput().
@@ -69,6 +70,14 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
_, err := parseForwards(s) _, err := parseForwards(s)
return err return err
}), }),
huh.NewInput().
Title("Pre-connect hook").
Description("Shell command run locally before connecting, e.g. vpn-check.sh \"$NETSSH_HOST\".\n"+
"A non-zero exit aborts. Leave empty to inherit; 'none' disables a hook set elsewhere.").
Value(&preConnect).
Validate(func(s string) error {
return config.SSHOptions{PreConnect: s}.Validate("ssh")
}),
).Title(title)).Run() ).Title(title)).Run()
if err != nil { if err != nil {
return o, err return o, err
@@ -84,6 +93,7 @@ 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),
}, nil }, nil
} }
+13 -3
View File
@@ -226,6 +226,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 +248,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 +272,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
} }
@@ -504,7 +511,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")
@@ -521,6 +528,9 @@ 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 cfg.Shell.Alias != "" { if cfg.Shell.Alias != "" {
@@ -536,12 +546,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 == ""
} }
// 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}} {
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])
} }
+27 -1
View File
@@ -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,28 @@ 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)
}
}
}
+27
View File
@@ -166,3 +166,30 @@ func TestHiddenPrefixDuplicateLabels(t *testing.T) {
} }
} }
} }
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)
}
}
+22 -3
View File
@@ -64,6 +64,7 @@ type searchResultMsg struct {
type hostItem struct { type hostItem struct {
label string // display only; name remains the canonical target label string // display only; name remains the canonical target
alias string // shortcut alias shown next to the name (shortcuts.show)
name string name string
id int id int
ip string ip string
@@ -97,7 +98,11 @@ 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.Title(), lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip)) title := h.Title()
if h.alias != "" {
title += " " + lipgloss.NewStyle().Foreground(lipgloss.Color("109")).Render("→ "+h.alias)
}
line := fmt.Sprintf(" %s%s %s", mark, title, lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip))
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, " "))
} }
@@ -188,7 +193,8 @@ type Model struct {
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
hostLabel func(string) string hostLabel func(string) string
markOrder []string // targets in the order they were marked aliasFor func(string) string // shortcut alias per target, "" for none
markOrder []string // targets in the order they were marked
} }
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 {
@@ -705,7 +711,14 @@ func (m *Model) updateListItems(entries []netbox.HostEntry) {
if label != e.Target() && (counts[strings.ToLower(label)] > 1 || canonical[strings.ToLower(label)]) { if label != e.Target() && (counts[strings.ToLower(label)] > 1 || canonical[strings.ToLower(label)]) {
label = e.Target() label = e.Target()
} }
items[i] = hostItem{label: label, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags} alias := ""
if m.aliasFor != nil {
alias = m.aliasFor(e.Target())
if strings.EqualFold(alias, label) {
alias = ""
}
}
items[i] = hostItem{label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags}
} }
m.list.SetItems(items) m.list.SetItems(items)
m.resizeList() m.resizeList()
@@ -847,3 +860,9 @@ func parseForwards(input string, available []string) ([]string, error) {
func (m *Model) SetHostLabel(format func(string) string) { func (m *Model) SetHostLabel(format func(string) string) {
m.hostLabel = format 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
}