Compare commits

...
47 Commits
Author SHA1 Message Date
Sebi 835b6b48cd Merge pull request 'feat: add pre_connect hook and optional shortcut alias display' (#43) from feat/pre-connect-hook-alias-display into main
Test / test (push) Successful in 3m51s
Release / release (push) Successful in 7m46s
2026-11-17 11:11:26 +00:00
Sebastian UnterschützandClaude Opus 5.5 796925b1a2 feat: add pre_connect hook and optional shortcut alias display
Test / test (pull_request) Successful in 4m27s
- ssh.pre_connect: local shell command run before every connection,
  layered like proxy_jump (global, instance/static host, rules; "none"
  disables). Host details are passed as NETSSH_* env vars, a non-zero
  exit aborts the connection, --dry-run only prints it.
- shortcuts.show: show shortcut aliases in the TUI host list, an ALIAS
  column in `cache list` / `hosts list` (also via --aliases) and in Tab
  completion.
- Both editable in `netssh configure`; README and CHANGELOG updated.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_017GpWAuVpPncumMViLLc8N4
2026-11-17 12:00:27 +01:00
Sebastian Unterschütz 20d7a40543 feat(instances): allow disabling prefixes in aliases and TUI
Test / test (push) Successful in 3m19s
Release / release (push) Successful in 8m31s
2026-11-16 22:13:05 +01:00
Sebi 1f46d9d9e5 Merge pull request 'v0.0.25: security and robustness fixes from the project review' (#42) from fix/project-review-findings into main
Test / test (push) Successful in 3m42s
Release / release (push) Successful in 6m2s
Reviewed-on: #42
2026-11-16 20:15:59 +00:00
Sebi 10eadaa13c Merge pull request 'chore(deps): update netboxcommunity/netbox docker tag to v4.7.5' (#38) from renovate/netboxcommunity-netbox-4.x into main 2026-11-16 20:14:07 +00:00
Sebi ffaa0a9c3c Merge pull request 'chore(deps): update alpine docker tag to v3.24' (#39) from renovate/alpine-3.x into main 2026-11-16 20:13:47 +00:00
Sebi 42bf21a79d Merge pull request 'fix(deps): update module charm.land/lipgloss/v2 to v2.1.1' (#41) from renovate/charm.land-lipgloss-v2-2.x into main 2026-11-16 20:13:24 +00:00
Sebastian Unterschütz 81b8715331 Merge remote-tracking branch 'origin/main' into renovate/netboxcommunity-netbox-4.x 2026-11-16 21:08:28 +01:00
Sebastian Unterschütz 41e488bce8 Merge remote-tracking branch 'origin/main' into renovate/alpine-3.x 2026-11-16 21:07:34 +01:00
Sebastian Unterschütz 9f281e9ce6 Merge main into Renovate lipgloss update and resolve conflicts 2026-11-16 21:07:30 +01:00
Sebi c46c95e04b chore(deps): update alpine docker tag to v3.24 2026-11-16 18:45:59 +00:00
Sebi 314dabf1f7 chore(deps): update netboxcommunity/netbox docker tag to v4.7.5 2026-11-16 18:45:54 +00:00
Sebastian UnterschützandClaude Fable 5.2 3e0a8ff67a fix: harden config loading and ssh addresses, stop resolver on API errors
Test / test (pull_request) Successful in 6m7s
Release / release (push) Successful in 5m14s
- read netssh.yaml from the user config directory only, not from the
  working directory
- refuse addresses from NetBox or the cache that are neither an IP
  address nor a hostname (ssh read "-oProxyCommand=…" as an option)
- resolver chain stops at an API failure; only "no address" falls
  through to the next strategy
- netssh --help and -h show netssh's help
- start at most one background cache refresh per 5 minutes
- validate the legacy netbox.url
- page through all IP addresses of a host
- CI: run format check, vet, and tests on pull requests and main
- changelog for v0.0.25

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-15 23:25:28 +01:00
Sebi a23a9bb125 fix(deps): update module charm.land/lipgloss/v2 to v2.1.1 2026-11-15 07:12:29 +00:00
Sebi 6e80b733dc Merge pull request 'v0.0.24' (#40) from release/v0.0.24 into main
Release / release (push) Successful in 6m20s
2026-11-14 12:56:51 +00:00
Sebastian UnterschützandClaude Opus 5.5 d3e7f137c3 docs: changelog for v0.0.24
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:56:13 +01:00
Sebi 6493e7c41e Merge pull request 'netssh multi: mehrere Server in einem Fenster (tmux/zellij)' (#37) from feat/multi into main 2026-11-14 12:36:50 +00:00
Sebi a8bf2b4141 Merge pull request 'Docker-Testumgebung + 3 Bugfixes' (#36) from test/docker-env into main 2026-11-14 12:35:36 +00:00
Sebastian UnterschützandClaude Opus 5.5 396d489187 feat(multi): tmux keys to toggle broadcast and exclude single panes
In windows opened by netssh multi, prefix S toggles broadcast for all
panes and prefix e excludes the current pane (a pane-level
synchronize-panes off, shown as [SOLO] in the border) or includes it
again. netssh sync --pane does the same from a shell.

S and e are unbound in a default tmux (E would be "spread evenly").
netssh writes the bindings to a small tmux config and sources it, binds
a key only if the user's tmux.conf does not use it (netssh's own earlier
binding is refreshed), and the bindings act only in windows marked
@netssh. multi.sync_key and multi.solo_key change the keys or turn them
off (none); also in the configurator. zellij syncs whole tabs only, so
excluding a pane is tmux-only.

testenv: the render test presses the keys through the xterm client
(send-keys -K) and checks [SOLO], that broadcast skips the excluded
pane, that S toggles, and that other windows are unaffected. The client
gets GNU grep: BusyBox grep -oF counted only one match per line.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:32:32 +01:00
Sebastian UnterschützandClaude Opus 5.5 699b9469b6 test: check what a real terminal renders for multi, zellij, and the TUI
tests/16-render.sh runs tmux, zellij, and the TUI in xterm on Xvfb,
takes screenshots, and reads them back with tesseract: remote prompts
in all panes, borders and titles with the hosts, [SYNC] appearing and
disappearing, panes side by side, broadcast output in every pane and
input in one pane only without it, windows split by panes_per_window,
the status bar, and TUI marks. Screenshots stay in testenv/.artifacts.

OCR reads three preprocessing variants (plain, stretched for dim gray,
brightest channel for colored text) and normalizes characters that
DejaVu Sans Mono makes ambiguous (1/l, C/().

The screenshots showed tmux cutting the session name in the status bar
to "[netssh-pv"; netssh multi now widens status-left-length for its
own session.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 13:14:34 +01:00
Sebastian UnterschützandClaude Opus 5.5 a31aab4110 feat: netssh multi — several hosts side by side in tmux or zellij
netssh multi opens one pane per host in a tmux window or zellij tab.
Hosts come from names, tag:TAG (NetBox and static hosts), cluster:NAME
(NetBox virtualization clusters; devices by default, --kind vm|all),
and groups from the config (@name, nested, with cycle detection).
Every pane runs netssh HOST, so lookup, rules, and jump hosts apply.

- tmux: a new window inside tmux, else a new session that is attached;
  tiled layout, pane borders with the host and a [SYNC] marker.
- zellij: a generated grid layout; a new tab inside zellij, else a new
  session.
- --sync broadcasts typing to all panes; netssh sync toggles it in the
  current tmux window or zellij tab.
- TUI: Space marks hosts, Ctrl+A marks all, Enter opens them together.
- Configurator: multiplexer, panes per window, groups.

NetBox SearchAll gains a cluster filter (name to cluster IDs per
instance), and cache entries keep the host's cluster for completion
and an offline fallback. Panes skip the 24-hour background refresh
(checked once by multi) and get HOME/XDG paths but no NETSSH_* values,
which would expose tokens in the process list.

testenv/tests/15-multi.sh checks real tmux and zellij sessions,
including a broadcast command arriving on all three cluster nodes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:45:05 +01:00
Sebastian UnterschützandClaude Opus 5.5 dbb99bdded test: add a local Docker test environment for all features
testenv/ starts two real NetBox 4.7 instances (v2 and v1 token), SSH
targets on public, mgmt, and prod networks, a jump host, an IPv6-only
host, a static host, and a client with ssh, sftp, scp, tmux, zellij,
bash, zsh, and fish. A seed script fills NetBox through the REST API.

141 end-to-end checks cover cache and refresh filters, connecting,
all resolver strategies, multiple instances, shortcuts and rewrites,
SSH options and rules, static hosts, sftp/scp incl. IPv6 and jump
hosts, tunnels, local notes and NetBox comments, completion and shell
hooks, the TUI (driven through tmux), the configurator, and uninstall.

Local only: testenv/up.sh, test.sh, shell.sh, down.sh. Not part of
CI/CD.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:30:24 +01:00
Sebastian UnterschützandClaude Opus 5.5 55e7a5106b fix: interface_name strategy, instance hosts in sftp/scp, alias rewrites
Found by the new Docker test environment against a real NetBox 4.7:

- The interface_name strategy filtered IP addresses with interface_name
  and vminterface_name, which NetBox ignores, so it returned the first
  address of the host instead of the named interface's. Use the real
  filters interface and vminterface; a missing interface (HTTP 400)
  falls through to the next strategy.
- sftp and scp took instance-qualified hosts (prod/web01:/path) for
  local paths, because a "/" comes before the ":". Such arguments are
  remote when the prefix is a configured NetBox instance.
- Shell aliases of instance-qualified hosts ran the shortcut rules on
  "instance/host", so anchored rewrite rules never matched.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-14 12:30:24 +01:00
Sebi 3c9e54b254 Merge pull request 'Hostname-Strategie und statische Hosts' (#35) from feat/hostname-static-hosts into main
Release / release (push) Successful in 4m31s
2026-11-13 22:49:14 +00:00
Sebastian UnterschützandClaude Opus 5.5 a950a82552 feat: hostname resolver strategy and static hosts
Add the hostname resolver strategy. It connects by the NetBox name
instead of an IP, with resolver.hostname_domain appended to names
without a dot. Its position in the chain decides whether it is always
used or only as a fallback (e.g. [primary_ip, hostname]); names that
are not valid DNS hostnames fall through to the next strategy.

Add static hosts under hosts: for machines that are not in NetBox,
with address, user, port, tags, and their own SSH options. They are
checked before NetBox (by name or shortcut), never expire, survive
cache refresh and clear, and work without any NetBox configured. The
cache overlays them after every load and stores only their last use,
so they appear in completion, aliases, the TUI and its recent list.
SSH options merge global, static host, then rules; rules can match
kind: static. Manage them with netssh hosts list|add|remove and in
netssh configure, which can now also continue without NetBox.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 23:46:13 +01:00
Sebi 5821dfbebd Merge pull request 'docs: README ausführlicher' (#34) from docs/readme-details into main 2026-11-13 22:31:12 +00:00
Sebastian UnterschützandClaude Opus 5.5 2be9f19cc2 docs: expand README with reference, recipes, and troubleshooting
Add a table of contents, a quick start, a full configuration reference
with defaults, the environment variables, a table of files and
directories, a command overview, details on rule matching and how
option layers combine (with real --dry-run output), recipes, a
troubleshooting table, and the project layout. Update How it works for
sftp, scp, tunnel, and forwards.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 23:30:23 +01:00
Sebi c71cc0ae3b Merge pull request 'chore(renovate): keine Major-Updates indirekter Go-Module' (#33) from chore/renovate-no-indirect-major into main 2026-11-13 22:25:28 +00:00
Sebastian UnterschützandClaude Opus 5.5 2cadea30c7 chore(renovate): skip major updates of indirect Go modules
A new major version of a Go module is a separate module path. For an
indirect dependency nothing imports it, so Renovate only adds an unused
requirement, as in #24 (go.yaml.in/yaml/v3 to v4). Minor and patch
updates of indirect modules stay enabled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 23:24:31 +01:00
Sebi 25c03fff9d Merge pull request 'chore(deps): update module go.yaml.in/yaml/v3 to v3.0.6' (#23) from renovate/go.yaml.in-yaml-v3-3.x into main 2026-11-13 22:22:23 +00:00
Sebastian Unterschütz 8e4417a6ea Merge remote-tracking branch 'origin/main' into work-23
# Conflicts:
#	go.mod
#	go.sum
2026-11-13 23:21:53 +01:00
Sebi 2fafa0b119 Merge pull request 'chore(deps): update module github.com/xo/terminfo to v1.3.1' (#22) from renovate/github.com-xo-terminfo-1.x into main 2026-11-13 22:21:34 +00:00
Sebastian Unterschütz b009863c37 Merge remote-tracking branch 'origin/main' into work-22 2026-11-13 23:21:03 +01:00
Sebi a1c9210f3c Merge pull request 'chore(deps): update module github.com/spf13/pflag to v1.1.0' (#25) from renovate/github.com-spf13-pflag-1.x into main 2026-11-13 22:20:26 +00:00
Sebastian Unterschütz 15fb57c0ea Merge remote-tracking branch 'origin/main' into work-25 2026-11-13 23:19:44 +01:00
Sebi c55aae520f Merge pull request 'chore(deps): update module golang.org/x/text to v0.44.0' (#29) from renovate/golang.org-x-text-0.x into main 2026-11-13 22:18:52 +00:00
Sebastian Unterschütz 88af34a64b Merge remote-tracking branch 'origin/main' into work-29
# Conflicts:
#	go.sum
2026-11-13 23:18:04 +01:00
Sebi 314905c538 Merge pull request 'fix(deps): update module golang.org/x/sys to v0.50.0' (#27) from renovate/golang.org-x-sys-0.x into main 2026-11-13 22:17:44 +00:00
Sebastian Unterschütz ad3f14186d Merge remote-tracking branch 'origin/main' into work-27 2026-11-13 23:17:15 +01:00
Sebi 4f08a1c92a Merge pull request 'fix(deps): update module charm.land/lipgloss/v2 to v2.1.0' (#28) from renovate/charm.land-lipgloss-v2-2.x into main 2026-11-13 22:16:38 +00:00
Sebastian Unterschütz 45a2abce90 Merge remote-tracking branch 'origin/main' into work-28 2026-11-13 23:16:05 +01:00
Sebi f7fc1b2a37 Merge pull request 'fix(deps): update module charm.land/bubbletea/v2 to v2.1.1' (#21) from renovate/charm.land-bubbletea-v2-2.x into main 2026-11-13 22:15:25 +00:00
Sebastian Unterschütz c45ad9f0d1 Merge remote-tracking branch 'origin/main' into work-21 2026-11-13 23:14:56 +01:00
Sebi 97fc8f5458 Merge pull request 'chore(deps): update go module directive to v1.27.4' (#30) from renovate/go-1.x into main 2026-11-13 22:13:41 +00:00
Sebastian Unterschütz d24870e4c0 Merge remote-tracking branch 'origin/main' into work-30 2026-11-13 23:13:04 +01:00
Sebi 053db984be Merge pull request 'SFTP, SCP und benannte Port-Forwards' (#32) from feat/sftp-forwarding into main 2026-11-13 22:08:48 +00:00
Sebi 6419fbb00d Merge pull request 'v0.0.23: Configurator für alle Optionen, Regex-Kurznamen' (#31) from feat/configure-all-options into main 2026-11-13 22:07:45 +00:00
39 changed files with 1125 additions and 75 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 ./...
+16
View File
@@ -1,5 +1,21 @@
# 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
- 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
- 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.
+107 -9
View File
@@ -21,7 +21,7 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int
- [Installation](#installation)
- [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)
- [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
- [Recipes](#recipes)
- [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 |
|---|---|
| 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 |
| 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) |
| 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` |
The result is validated and saved to `~/.config/netssh.yaml`; Ctrl+C cancels without writing.
@@ -201,7 +201,7 @@ shortcuts:
Single-instance and shared settings can be overridden with environment variables (`NETSSH_NETBOX_URL`, `NETSSH_NETBOX_TOKEN`, etc.; see [Environment variables](#environment-variables)).
netssh reads `netssh.yaml` from the user config directory and, if none exists there, from the current working directory. Unknown keys are ignored; invalid values (an unknown strategy, a bad regex, an invalid SSH option) stop netssh with an error that names the key.
netssh reads `netssh.yaml` from the user config directory only; a file of that name in the working directory is ignored. Unknown keys are ignored; invalid values (an unknown strategy, a bad regex, an invalid SSH option) stop netssh with an error that names the key.
### Configuration reference
@@ -212,7 +212,7 @@ Every key, its default, and the section that explains it. Keys marked *layered*
| `netbox.url` | string | — | NetBox base URL (single instance). Use either `netbox` or `netboxes`. |
| `netbox.token` | string | — | API token; `nbt_…` is v2, anything else v1. |
| `netbox.token_version` | 1 \| 2 | auto | Detected from the token prefix. |
| `netboxes[]` | list | — | Named instances with `name`, `url`, `token`, `token_version`, `ssh` — see [Multiple NetBox instances](#multiple-netbox-instances). |
| `netboxes[]` | list | — | Named instances with `name`, `url`, `token`, `token_version`, `disable_prefix`, `ssh` — see [Multiple NetBox instances](#multiple-netbox-instances). |
| `resolver.strategies` | list | `[management_subnet, primary_ip]` | Tried in order, first IP wins — see [IP Resolution Strategies](#ip-resolution-strategies). The wizard suggests `primary_ip`. |
| `resolver.management_subnets` | list of CIDR | `[]` | Used by `management_subnet`. |
| `resolver.interface_name` | string | — | Used by `interface_name`, e.g. `mgmt0`. |
@@ -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.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.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. |
| `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.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. |
| `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). |
@@ -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_CACHE_TTL`, `NETSSH_CACHE_PATH` | `cache.*` |
| `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_SHORTCUTS_DOMAINS`, `NETSSH_SHORTCUTS_STRIP_HYPHENS` | `shortcuts.*` |
| `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`, `NETSSH_SHORTCUTS_SHOW` | `shortcuts.*` |
| `NETSSH_COMPLETION_MAX_RESULTS` | `completion.max_results` |
| `NETSSH_MULTI_MULTIPLEXER`, `NETSSH_MULTI_PANES_PER_WINDOW` | `multi.*` |
| `NETSSH_SHELL_ALIAS` | `shell.alias` |
@@ -306,7 +308,41 @@ netssh notes show lab/web01 --netbox --kind device
For direct connections without an instance prefix, every instance must be reachable to verify uniqueness. A qualified target queries only its own instance and can use a fresh cached IP while other instances are offline. Qualified shortcuts such as `office/web01` also support configured domain suffixes and hyphen folding.
Cache entries and generated aliases retain the instance name (`office_web01` and `lab_web01`). Named-instance caches live in a configuration-specific subdirectory beneath the configured cache path, so changing an endpoint cannot reuse another server's cached IPs. Run `netssh cache refresh` after adding or changing instances. A failed full refresh leaves the cache and its refresh timestamp unchanged; a per-instance refresh preserves the other instances and does not mark the whole cache as refreshed.
Cache entries retain the instance name. Generated aliases include it by default (`office_web01` and `lab_web01`). Named-instance caches live in a configuration-specific subdirectory beneath the configured cache path, so changing an endpoint cannot reuse another server's cached IPs. Run `netssh cache refresh` after adding or changing instances. A failed full refresh leaves the cache and its refresh timestamp unchanged; a per-instance refresh preserves the other instances and does not mark the whole cache as refreshed.
**Aliases and TUI names without an instance prefix.** Set `disable_prefix: true`
on individual instances, or enable **Hide instance prefix in aliases and TUI?**
when editing an instance in `netssh configure`:
```yaml
netboxes:
- name: office
url: https://netbox.office.example
token: nbt_office-token
disable_prefix: true
- name: lab
url: https://netbox.lab.example
token: nbt_lab-token
```
With the appropriate domain shortcut, this generates `web01` for
`office/web01.example.com` and `lab_web01` for the lab host. The default is
`false`. The alias command still contains the full `instance/hostname`, so it
connects to the selected instance even when another instance has the same host
name. Domain stripping, rewrites and hyphen folding still apply.
If a bare alias conflicts with another generated alias, a reserved qualified
alias, `netssh`, or your configured command alias, the instance prefix is kept.
It is also kept if the bare name is not a valid shell alias (e.g. starts with a digit).
The TUI result list also hides the prefix for this instance; duplicate visible
names keep their prefixes to remain distinguishable. Selection, autocomplete,
connection editors, notes and cache identities still use the full target.
Completion already offers unique hostnames
without an instance prefix.
Open a new shell with the installed netssh hook to regenerate and load aliases.
No cache refresh is needed for this setting. Existing aliases in an already open
shell remain until removed or the shell is replaced.
Local notes remain keyed by the NetBox URL, host kind, and canonical hostname. Migrating a single instance or renaming it preserves its notes. Use `instance/hostname` and `--kind` for uncached local notes; these operations work offline. NetBox comments and interface/IP lookups always use the selected instance's credentials.
@@ -474,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:
- 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;
- `extra_args` — collected from all layers.
@@ -485,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
```
### 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
`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`.
@@ -674,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) |
| `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
Generate shell aliases for all cached hosts based on the shortcut settings:
@@ -774,6 +871,7 @@ See the [NetBox REST API documentation](https://netbox.readthedocs.io/en/stable/
```sh
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 --tag prod # only hosts with the "prod" tag
netssh cache refresh --kind vm # only virtual machines
+26 -5
View File
@@ -14,27 +14,32 @@ import (
)
func hostsCmd() *cobra.Command {
var showAliases bool
cmd := &cobra.Command{
Use: "hosts",
Short: "Manage static hosts that are not in NetBox",
Long: `Static hosts are defined under hosts: in the config. They are found before
NetBox, work offline, and support shortcuts, rules (kind: static), aliases,
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.Flags().BoolVar(&showAliases, "aliases", false, "Show each host's shortcut alias (always on with shortcuts.show)")
return cmd
}
func hostsListCmd() *cobra.Command {
return &cobra.Command{
var showAliases bool
cmd := &cobra.Command{
Use: "list",
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()
if err != nil {
return err
@@ -43,13 +48,29 @@ func listHosts() error {
fmt.Println("No static hosts. Add one with: netssh hosts add NAME ADDRESS")
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)
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 {
port := ""
if host.Port > 0 {
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, ","))
}
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/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/shortcuts"
)
@@ -29,6 +30,28 @@ func newNetBoxClient(cfg *config.Config) *netbox.Client {
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 {
return func(target string) string {
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").
// Hosts whose full name does not match are offered by their configured
// 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 {
prefix := strings.ToLower(toComplete)
qualifiedInput := strings.Contains(prefix, "/")
@@ -75,7 +101,20 @@ func hostCompletions(entries []cache.Entry, toComplete string, sc config.Shortcu
}
}
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)
return names
+49 -4
View File
@@ -62,6 +62,16 @@ func main() {
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 err := rootCmd().Execute(); err != nil {
os.Exit(1)
@@ -320,6 +330,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.
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)
if len(flags.Forwards) > 0 {
forwardArgs, err := internalssh.ForwardArgs(flags.Forwards, opts.Forwards)
@@ -335,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)
}
if err := runPreConnect(opts.PreConnectCommand(), host, client.Name, flags.DryRun); err != nil {
fatalf("%v", err)
}
_, name := netbox.SplitTarget(host.Name)
execClient(client, client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags), flags)
}
@@ -373,6 +389,11 @@ func runTUI() {
}
m := tui.New(nbClient, c, cfg.SSH.DefaultUser, cfg.SSH.DefaultPort)
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.SetForwards(func(name, kind string, tags []string) []string {
return forwardNames(hostOptions(cfg, resolvedHost{Name: name, Kind: kind, Tags: tags}))
@@ -655,7 +676,8 @@ func cacheCmd() *cobra.Command {
}
func cacheListCmd() *cobra.Command {
return &cobra.Command{
var showAliases bool
cmd := &cobra.Command{
Use: "list",
Short: "Show all cached entries",
RunE: func(cmd *cobra.Command, args []string) error {
@@ -671,13 +693,31 @@ func cacheListCmd() *cobra.Command {
sort.Slice(entries, func(i, j int) bool { return entries[i].Name < entries[j].Name })
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 {
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()
},
}
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 {
@@ -1000,6 +1040,9 @@ func hookUninstallCmd() *cobra.Command {
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
// has not been fully refreshed within the last 24 hours.
func maybeBackgroundRefresh(cfg *config.Config, c *cache.Cache) {
@@ -1007,7 +1050,9 @@ func maybeBackgroundRefresh(cfg *config.Config, c *cache.Cache) {
if !cfg.HasNetBox() || os.Getenv("NETSSH_NO_REFRESH") != "" {
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
}
self, err := os.Executable()
+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)
}
}
+1
View File
@@ -71,6 +71,7 @@ func buildUninstallPlan(cfg *config.Config, keepConfig bool) uninstallPlan {
addPath(path)
addPath(path + ".lock")
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-") {
addPath(filepath.Dir(path))
}
+1 -1
View File
@@ -6,7 +6,7 @@ require (
charm.land/bubbles/v2 v2.2.1
charm.land/bubbletea/v2 v2.1.1
charm.land/huh/v2 v2.0.3
charm.land/lipgloss/v2 v2.1.0
charm.land/lipgloss/v2 v2.1.1
github.com/spf13/cobra v1.10.2
github.com/spf13/viper v1.21.0
golang.org/x/sys v0.50.0
+2 -2
View File
@@ -4,8 +4,8 @@ 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/huh/v2 v2.0.3 h1:2cJsMqEPwSywGHvdlKsJyQKPtSJLVnFKyFbsYZTlLkU=
charm.land/huh/v2 v2.0.3/go.mod h1:93eEveeeqn47MwiC3tf+2atZ2l7Is88rAtmZNZ8x9Wc=
charm.land/lipgloss/v2 v2.1.0 h1:RLCNLhSQST+NPOmvUSbRWZ3UFOXsf3ZXFmJ5E/2tHEU=
charm.land/lipgloss/v2 v2.1.0/go.mod h1:wwfOgrNqUA9yjL8nmG6BIO0qQnmkEgJ8ISptbme83gI=
charm.land/lipgloss/v2 v2.1.1 h1:F+vKWis9Kz3MFRsbICSDFtT1ZwVL+8f+36Dtg+OpKwc=
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/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4=
+20
View File
@@ -83,6 +83,26 @@ func (c *Cache) NeedsRefresh(d time.Duration) bool {
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.
func (c *Cache) SetRefreshed() error {
if c.refreshStamp == "" {
+20
View File
@@ -557,3 +557,23 @@ func TestStaticHosts(t *testing.T) {
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")
}
}
+13 -8
View File
@@ -30,11 +30,12 @@ type ShellConfig struct {
}
type NetBoxConfig struct {
Name string `mapstructure:"name"`
URL string `mapstructure:"url"`
Token string `mapstructure:"token"`
TokenVersion int `mapstructure:"token_version"`
SSH SSHOptions `mapstructure:"ssh"`
DisablePrefix bool `mapstructure:"disable_prefix"`
Name string `mapstructure:"name"`
URL string `mapstructure:"url"`
Token string `mapstructure:"token"`
TokenVersion int `mapstructure:"token_version"`
SSH SSHOptions `mapstructure:"ssh"`
}
type ResolverConfig struct {
@@ -66,6 +67,9 @@ type ShortcutsConfig struct {
Domains []string `mapstructure:"domains"`
StripHyphens bool `mapstructure:"strip_hyphens"`
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
@@ -113,14 +117,15 @@ func Load() (*Config, error) {
if err == nil {
v.SetConfigName("netssh")
v.SetConfigType("yaml")
v.AddConfigPath(filepath.Join(configDir))
v.AddConfigPath(".")
// Only the user's own directory: a netssh.yaml in the working directory
// (e.g. of a cloned repository) could inject ssh options and a NetBox URL.
v.AddConfigPath(configDir)
}
v.SetEnvPrefix("NETSSH")
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
v.AutomaticEnv()
for _, key := range []string{"netbox.url", "netbox.token", "netbox.token_version", "resolver.strategies", "resolver.management_subnets", "resolver.interface_name", "resolver.hostname_domain", "cache.ttl", "cache.path", "ssh.default_user", "ssh.default_port", "shortcuts.domains", "shortcuts.strip_hyphens", "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 {
return nil, err
}
+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)
}
}
}
+24 -2
View File
@@ -17,6 +17,9 @@ func (c *Config) ValidateNetBoxes() error {
if len(c.NetBoxes) > 0 && c.NetBox.URL != "" {
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)
for _, source := range c.NetBoxes {
if !instanceName.MatchString(source.Name) {
@@ -27,8 +30,7 @@ func (c *Config) ValidateNetBoxes() error {
return fmt.Errorf("duplicate NetBox instance name %q", source.Name)
}
seen[name] = true
u, err := url.Parse(source.URL)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") || u.Host == "" || u.RawQuery != "" || u.Fragment != "" {
if !validNetBoxURL(source.URL) {
return fmt.Errorf("NetBox %q requires an HTTP(S) URL without query or fragment", source.Name)
}
if source.TokenVersion < 0 || source.TokenVersion > 2 {
@@ -38,6 +40,12 @@ func (c *Config) ValidateNetBoxes() error {
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 }
// 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")))
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
url: https://office.example/netbox
token: nbt_office
disable_prefix: true
- name: lab
url: https://lab.example
token: legacy-token
@@ -34,7 +35,14 @@ cache:
if cfg.NetBox.URL != "" {
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()
cfg.NetBoxes[0].DisablePrefix = false
if cfg.CachePath() != first {
t.Fatal("alias prefix setting discarded cache")
}
if first == cfg.Cache.Path {
t.Fatal("named sources reuse legacy cache")
}
+21
View File
@@ -24,6 +24,21 @@ type SSHOptions struct {
Options map[string]string `mapstructure:"options"`
// Forwards are named port forwards, selected with --forward or netssh tunnel.
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.
@@ -155,6 +170,9 @@ func (o SSHOptions) Validate(scope string) error {
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 {
if !instanceName.MatchString(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 != "" {
out.AddressFamily = override.AddressFamily
}
if strings.TrimSpace(override.PreConnect) != "" {
out.PreConnect = override.PreConnect
}
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)
}
}
+27 -2
View File
@@ -124,9 +124,34 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
seen[cfg.Shell.Alias] = true
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)
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
}
seen[name] = true
+75
View File
@@ -253,3 +253,78 @@ func TestAliasesUseRewriteRules(t *testing.T) {
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)
}
}
})
}
}
+33 -24
View File
@@ -176,24 +176,32 @@ func (c *Client) GetIPs(ctx context.Context, entry HostEntry) ([]string, error)
}
return source.GetIPs(ctx, host)
}
var apiURL string
switch entry.Kind {
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":
apiURL = fmt.Sprintf("%s/api/ipam/ip-addresses/?virtual_machine_id=%d&limit=100", c.baseURL, entry.ID)
default:
return nil, fmt.Errorf("unknown host kind: %q", entry.Kind)
return c.fetchAllIPs(ctx, fmt.Sprintf("virtual_machine_id=%d", entry.ID))
}
return nil, fmt.Errorf("unknown host kind: %q", entry.Kind)
}
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))
// fetchAllIPs pages through the IP addresses matching filterParams, so hosts
// with more addresses than one page do not lose their management address.
func (c *Client) fetchAllIPs(ctx context.Context, filterParams string) ([]string, error) {
const pageSize = 100
var ips []string
for offset := 0; ; offset += pageSize {
apiURL := fmt.Sprintf("%s/api/ipam/ip-addresses/?%s&limit=%d&offset=%d", c.baseURL, filterParams, pageSize, offset)
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
}
@@ -203,16 +211,7 @@ func (c *Client) GetIPsWithFilter(ctx context.Context, filterParams string) ([]s
if c.sources != nil {
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)
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
return c.fetchAllIPs(ctx, filterParams)
}
func (c *Client) searchDevices(ctx context.Context, query, tag string) ([]HostEntry, error) {
@@ -348,7 +347,7 @@ func (c *Client) request(ctx context.Context, method, apiURL string, body io.Rea
}
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 {
@@ -399,6 +398,16 @@ func stripPrefix(cidr string) string {
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.
var ErrHostNotFound = errors.New("host not found")
+45
View File
@@ -3,8 +3,11 @@ package netbox
import (
"context"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
)
@@ -499,3 +502,45 @@ func TestCommentConflictIsReported(t *testing.T) {
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)
}
}
+7
View File
@@ -2,6 +2,7 @@ package resolver
import (
"context"
"errors"
"fmt"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
@@ -32,6 +33,12 @@ func (c *Chain) Resolve(ctx context.Context, entry *netbox.HostEntry, client *ne
if err == nil {
return ip, 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)
}
+14
View File
@@ -153,3 +153,17 @@ func TestNew_MultipleStrategies(t *testing.T) {
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 (
"context"
"errors"
"fmt"
"net/http"
"net/url"
"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)
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 {
return "", fmt.Errorf("fetching IPs for interface %q: %w", s.name, err)
}
+14
View File
@@ -2,6 +2,7 @@ package resolver
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"net/url"
@@ -54,3 +55,16 @@ func urlQuery(s string) (string, error) {
q, err := url.ParseQuery(s)
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)
}
}
+3
View File
@@ -108,6 +108,9 @@ func editInstance(source config.NetBoxConfig, sources []config.NetBoxConfig, ori
}
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 {
return (&config.Config{NetBoxes: []config.NetBoxConfig{{Name: "instance", URL: strings.TrimSpace(value)}}}).ValidateNetBoxes()
}),
+10
View File
@@ -23,6 +23,7 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
extraArgs := strings.Join(o.ExtraArgs, "\n")
options := formatOptions(o.Options)
forwards := formatForwards(o.Forwards)
preConnect := o.PreConnect
err := huh.NewForm(huh.NewGroup(
huh.NewInput().
@@ -69,6 +70,14 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
_, err := parseForwards(s)
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()
if err != nil {
return o, err
@@ -84,6 +93,7 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
AddressFamily: addressFamily,
ExtraArgs: parseLines(extraArgs),
Options: parsed,
PreConnect: strings.TrimSpace(preConnect),
}, nil
}
+16 -3
View File
@@ -226,6 +226,7 @@ func editShortcuts(cfg *config.Config) error {
stripHyphens := cfg.Shortcuts.StripHyphens
rewrites := formatRewrites(cfg.Shortcuts.Rewrites)
commandAlias := cfg.Shell.Alias
showShortcuts := cfg.Shortcuts.Show
err := huh.NewForm(huh.NewGroup(
huh.NewInput().
Title("Domain suffixes").
@@ -247,6 +248,11 @@ func editShortcuts(cfg *config.Config) error {
_, err := parseRewrites(s)
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().
Title("Command alias").
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.Rewrites, _ = parseRewrites(rewrites)
cfg.Shortcuts.Show = showShortcuts
cfg.Shell.Alias = strings.TrimSpace(commandAlias)
return nil
}
@@ -385,6 +392,9 @@ func save(cfg config.Config) error {
b.WriteString("netboxes:\n")
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)
if source.DisablePrefix {
b.WriteString(" disable_prefix: true\n")
}
if !sshOptionsEmpty(source.SSH) {
b.WriteString(" ssh:\n")
writeSSHOptions(&b, " ", source.SSH)
@@ -501,7 +511,7 @@ func save(cfg config.Config) error {
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")
if len(cfg.Shortcuts.Domains) > 0 {
b.WriteString(" domains:\n")
@@ -518,6 +528,9 @@ func save(cfg config.Config) error {
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 != "" {
@@ -533,12 +546,12 @@ func save(cfg config.Config) error {
}
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.
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] != "" {
fmt.Fprintf(b, "%s%s: %q\n", indent, field[0], field[1])
}
+28 -2
View File
@@ -398,7 +398,7 @@ func TestSaveMultipleNetBoxesRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{
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},
},
Resolver: config.ResolverConfig{Strategies: []string{"primary_ip"}},
@@ -438,9 +438,10 @@ func TestSaveKeepsSSHOptions(t *testing.T) {
AddressFamily: "inet",
ExtraArgs: []string{"-A"},
Options: map[string]string{"serveraliveinterval": "60"},
PreConnect: `vpn-check "$NETSSH_HOST" && echo 'ok'`,
}
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"}},
Cache: config.CacheConfig{TTL: 3600},
SSH: config.SSHConfig{
@@ -651,3 +652,28 @@ func TestParseGroupsAndSaveMulti(t *testing.T) {
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)
}
}
}
+13
View File
@@ -2,6 +2,7 @@ package ssh
import (
"fmt"
"net/netip"
"regexp"
"sort"
"strings"
@@ -142,6 +143,18 @@ type Result struct {
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])?$`)
// 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)
}
}
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)
}
}
+114
View File
@@ -9,6 +9,7 @@ import (
tea "charm.land/bubbletea/v2"
"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"
)
@@ -79,3 +80,116 @@ func TestPartialOutageKeepsLiveAndCachedResultsVisible(t *testing.T) {
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)
}
}
+56 -9
View File
@@ -63,14 +63,21 @@ type searchResultMsg struct {
// --- list item ---
type hostItem struct {
name string
id int
ip string
kind string
tags []string
label string // display only; name remains the canonical target
alias string // shortcut alias shown next to the name (shortcuts.show)
name string
id int
ip string
kind string
tags []string
}
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) FilterValue() string { return h.name }
@@ -91,7 +98,11 @@ func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list.
if d.marked[h.key()] {
mark = "● "
}
line := fmt.Sprintf(" %s%s %s", mark, h.name, 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() {
line = lipgloss.NewStyle().Bold(true).Foreground(lipgloss.Color("86")).Render("> " + strings.TrimPrefix(line, " "))
}
@@ -181,7 +192,9 @@ type Model struct {
editMode bool // Ctrl+E on the selected item
forwardMode bool // Ctrl+T on the selected item
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
}
func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts ...int) *Model {
@@ -678,12 +691,34 @@ func (m *Model) updateListItems(entries []netbox.HostEntry) {
f := parseFilter(m.filterInput.Value())
filtered := applyFilter(entries, f)
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 {
ip := e.PrimaryIP4
if ip == "" {
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 = ""
}
}
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.resizeList()
@@ -819,3 +854,15 @@ func parseForwards(input string, available []string) ([]string, error) {
}
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
}
+1 -1
View File
@@ -10,7 +10,7 @@ COPY cmd ./cmd
COPY internal ./internal
RUN CGO_ENABLED=0 go build -o /out/netssh ./cmd/netssh
FROM alpine:3.23
FROM alpine:3.24
# xvfb/xterm/imagemagick/tesseract: render panes in a real terminal emulator,
# take screenshots, and read them back with OCR (tests/16-render.sh).
RUN apk add --no-cache openssh-client-default tmux zellij bash zsh fish bash-completion \
+1 -1
View File
@@ -6,7 +6,7 @@
name: netssh-test
x-netbox: &netbox
image: netboxcommunity/netbox:v4.7.4-5.1.1
image: netboxcommunity/netbox:v4.7.5-5.1.1
depends_on:
postgres: {condition: service_healthy}
redis: {condition: service_healthy}
+1 -1
View File
@@ -1,6 +1,6 @@
# SSH target for the netssh test environment: every NetBox host, the bastion,
# and the static host run this image with a different hostname.
FROM alpine:3.23
FROM alpine:3.24
# Alpine locks new accounts with "!"; sshd refuses key logins for locked
# accounts, so the password field is set to "*" (no password, not locked).