1 Commits
Author SHA1 Message Date
Sebastian Unterschütz e5bde9c61f feat: add host actions, lifecycle hooks and operational tools
Test / test (push) Successful in 4m4s
Release / release (push) Successful in 7m39s
2026-11-18 10:41:36 +01:00
32 changed files with 2083 additions and 64 deletions

No files matched your search

+8
View File
@@ -1,5 +1,13 @@
# Changelog # Changelog
## v1.1.0
- Add local post-disconnect/post-command scripts, execution timeouts, cancellation, per-command confirmation and host restrictions.
- Add configurable recent-host count, persistent favorites/pins, a TUI command menu and cache/live/stale indicators.
- Add doctor/explain diagnostics, parallel batch commands with failed-host retry, and optional bounded local action history.
- Add configuration export/import that excludes credentials and executable settings while preserving matching local credentials.
- Preserve terminal behavior and process exit status during supervised execution; test Bash/Python scripts, process cancellation, concurrency and batch retries.
## v1.0.0 ## v1.0.0
- Consolidate the complete project into the initial v1 commit. - Consolidate the complete project into the initial v1 commit.
+196 -2
View File
@@ -22,6 +22,7 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int
- [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), [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) - [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)
- [Operations](#operations) — post scripts, favorites, history, diagnostics, batch commands, configuration sharing
- [Custom host commands](#custom-host-commands) — automatic aliases for mtr, ping, and other programs - [Custom host commands](#custom-host-commands) — automatic aliases for mtr, ping, and other programs
- [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)
@@ -36,7 +37,7 @@ The same lookup drives `netssh sftp`, `netssh scp`, and `netssh tunnel`, the int
- **Flexible IP resolution** — configurable chain of strategies: management subnet, primary IP, named interface, or the hostname itself - **Flexible IP resolution** — configurable chain of strategies: management subnet, primary IP, named interface, or the hostname itself
- **Static hosts** — add hosts that are not in NetBox (`netssh hosts add router 192.168.1.1`); they work everywhere, also without any NetBox - **Static hosts** — add hosts that are not in NetBox (`netssh hosts add router 192.168.1.1`); they work everywhere, also without any NetBox
- **Interactive TUI** — fuzzy search with live NetBox queries and 300 ms debouncing (start with `netssh`, no arguments) - **Interactive TUI** — fuzzy search with live NetBox queries and 300 ms debouncing (start with `netssh`, no arguments)
- **Recently-used list** — TUI opens with your 10 most-recently-connected hosts, no typing needed - **Recently-used list** — TUI opens with your most-recently-connected hosts (10 by default, configurable with `tui.history_limit`), no typing needed
- **Tag/kind filter** — press `Ctrl+F` in the TUI to filter by `tag:prod` or `kind:vm` - **Tag/kind filter** — press `Ctrl+F` in the TUI to filter by `tag:prod` or `kind:vm`
- **User/port override** — press `Ctrl+E` in the TUI to override the SSH user or port before connecting - **User/port override** — press `Ctrl+E` in the TUI to override the SSH user or port before connecting
- **Server notes** — multiline local notes or optional NetBox comments, available in the TUI and CLI - **Server notes** — multiline local notes or optional NetBox comments, available in the TUI and CLI
@@ -229,6 +230,10 @@ 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.post_disconnect` | string | — | *Layered.* Local shell command after the client exits; `none` disables inheritance. |
| `tui.history_limit` | integer | `10` | Recent hosts shown; `0` means all, favorites are additional. |
| `activity.enabled` | boolean | `false` | Enable local execution metadata history. |
| `activity.retention_days` / `activity.max_entries` | integer | `30` / `1000` | History retention limits; `0` disables the respective limit. |
| `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.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. |
@@ -403,6 +408,10 @@ A hint is shown during `netssh configure` if a legacy v1 token is entered.
| `netssh [--dry-run] [--jump HOST\|--no-jump] [--forward NAME]... [ssh options] HOST [command]` | Connect with ssh. | | `netssh [--dry-run] [--jump HOST\|--no-jump] [--forward NAME]... [ssh options] HOST [command]` | Connect with ssh. |
| `netssh sftp [netssh flags] [sftp options] HOST[:PATH]` | SFTP session — see [SFTP and SCP](#sftp-and-scp). | | `netssh sftp [netssh flags] [sftp options] HOST[:PATH]` | SFTP session — see [SFTP and SCP](#sftp-and-scp). |
| `netssh scp [netssh flags] [scp options] SOURCE... TARGET` | Copy files — see [SFTP and SCP](#sftp-and-scp). | | `netssh scp [netssh flags] [scp options] SOURCE... TARGET` | Copy files — see [SFTP and SCP](#sftp-and-scp). |
| `netssh doctor [--online]` / `netssh explain HOST` | Diagnose configuration and explain effective settings. |
| `netssh favorites` / `netssh history` | Manage saved hosts and optional action records. |
| `netssh batch COMMAND HOST...` | Run a configured command with bounded parallelism and retry. |
| `netssh config export\|import FILE` | Share host configuration without secrets or executable settings. |
| `netssh run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]` | Run a [custom host command](#custom-host-commands), e.g. mtr or ping, using the configured resolver. | | `netssh run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]` | Run a [custom host command](#custom-host-commands), e.g. mtr or ping, using the configured resolver. |
| `netssh tunnel [netssh flags] [ssh options] HOST FORWARD...` | Port forwards without a shell — see [Port forwarding](#port-forwarding). | | `netssh tunnel [netssh flags] [ssh options] HOST FORWARD...` | Port forwards without a shell — see [Port forwarding](#port-forwarding). |
| `netssh hosts [list] \| add NAME ADDRESS [--user U] [--port P] [--tag T]... [--replace] \| remove NAME` | Manage static hosts — see [Static hosts](#static-hosts). | | `netssh hosts [list] \| add NAME ADDRESS [--user U] [--port P] [--tag T]... [--replace] \| remove NAME` | Manage static hosts — see [Static hosts](#static-hosts). |
@@ -927,7 +936,7 @@ Run without arguments to open the interactive search:
netssh netssh
``` ```
The TUI opens with your 10 most-recently-connected hosts. Start typing to search all cached hosts or query NetBox live. The TUI opens with your most-recently-connected hosts (10 by default, configurable with `tui.history_limit`). Start typing to search all cached hosts or query NetBox live.
See the [hotkey cheat sheet](#hotkey-cheat-sheet) for all search and editor keys. See the [hotkey cheat sheet](#hotkey-cheat-sheet) for all search and editor keys.
@@ -1038,6 +1047,9 @@ in the search, while tmux uses `Ctrl+b` as its default prefix.
| `Enter` | connect to selected host | | `Enter` | connect to selected host |
| `Space` | mark/unmark the host; with marks, `Enter` opens them side by side (`netssh multi`) | | `Space` | mark/unmark the host; with marks, `Enter` opens them side by side (`netssh multi`) |
| `Ctrl+A` | mark all listed hosts (again: unmark all) | | `Ctrl+A` | mark all listed hosts (again: unmark all) |
| `Ctrl+R` | choose SSH or a configured command; marked hosts run the command as a batch |
| `Ctrl+D` | toggle favorite for the selected host |
| `Ctrl+P` | toggle pin; pinning also adds the host to favorites |
| `Ctrl+O` | open an SFTP session to the selected host | | `Ctrl+O` | open an SFTP session to the selected host |
| `Ctrl+T` | start a tunnel: enter forward names or specs (`web, 8080:localhost:80`) | | `Ctrl+T` | start a tunnel: enter forward names or specs (`web, 8080:localhost:80`) |
| `Ctrl+E` | open inline editor to override user/port before connecting | | `Ctrl+E` | open inline editor to override user/port before connecting |
@@ -1113,6 +1125,188 @@ the whole tab. When starting a new zellij session, enable broadcast manually
with `Ctrl+t` then `s`; `--sync` is applied automatically only inside an with `Ctrl+t` then `s`; `--sync` is applied automatically only inside an
existing zellij session. existing zellij session.
## Operations
### Post scripts
`ssh.post_disconnect` runs a local shell command after the SSH, SFTP, SCP or
tunnel process exits. Configure it globally, per NetBox instance, per static host
or in an SSH rule. More specific values override broader ones; `none` disables
an inherited hook.
```yaml
ssh:
post_disconnect: /home/user/scripts/after-ssh.sh
rules:
- match: {tag: lab}
post_disconnect: none
commands:
maintenance:
alias_prefix: maint
args: [bash, /home/user/scripts/maintenance.sh, "{address}"]
post_run: /home/user/scripts/after-maintenance.sh
match: {instance: prod, tag: router, name: "router*"}
confirm: true
timeout: 5m
```
Post scripts receive the existing `NETSSH_HOST`, `NETSSH_TARGET`,
`NETSSH_INSTANCE`, `NETSSH_IP`, `NETSSH_KIND`, `NETSSH_TAGS` and
`NETSSH_CLIENT` variables, plus `NETSSH_COMMAND` and `NETSSH_EXIT_CODE`.
They run after a started process succeeds, fails or is cancelled, but not after
a failed pre-connect hook, failed process start, or a dry run. Output goes to
stderr, stdin is closed, and post scripts have a 30-second timeout.
A failing main process retains its exit code. If only the post script fails,
its exit code is returned. Hooks cannot run after the wrapper is forcibly killed
with SIGKILL. In multi-mode each connection runs its own post script.
Without a post hook or activity logging, SSH still replaces netssh directly.
With either enabled, netssh waits for the client while preserving terminal I/O.
### Favorites, pins and recent hosts
```yaml
tui:
history_limit: 25 # default 10; 0 = all used hosts
```
Favorites remain on the TUI's opening screen independently of the recent-host
limit. Pins appear first, followed by favorites and recent hosts. `Ctrl+D`
toggles a favorite; `Ctrl+P` toggles a pin. Removing a favorite also unpins it.
A saved host missing from the cache is still shown and resolved when selected.
```sh
netssh favorites
netssh favorites add prod/web01
netssh favorites pin prod/router01
netssh favorites unpin prod/router01
netssh favorites remove prod/web01
```
Favorites use canonical targets such as `prod/web01`, so identical hostnames in
different instances stay independent. Change the recent-host limit in
`netssh configure` → **History & activity logging**.
The TUI labels results as `live`, `static` or `cache AGE`; expired cache entries
also show `stale`. A partial NetBox outage keeps available and cached results
visible and identifies failed instances in the warning. Cached results are not
proof of current reachability; normal resolution rules still apply on connect.
### TUI actions, restrictions and confirmations
Press `Ctrl+R` on a host to choose SSH or one of your configured commands,
including MTR, Ping and scripts. With marked hosts, SSH opens the existing
multi-session layout; custom commands run through `netssh batch`.
A command's `match` uses the same `instance`, `tag`, `kind` and hostname
glob `name` selectors as SSH rules. All supplied selectors must match.
Restrictions apply to generated aliases, the TUI menu and execution itself.
The chosen command is checked again for every batch target.
`confirm: true` asks before execution. Non-interactive callers must explicitly
pass `--yes`; a batch asks once for the entire selected set. For example:
```sh
netssh run --yes maintenance prod/router01
netssh run --status maintenance prod/router01
```
The terminal shows elapsed runtime for custom commands; `--status` also
enables these messages when output is redirected. `timeout` accepts durations
such as `30s` or `5m`; no value means no timeout. Timeout exits with 124.
Ctrl+C cancels foreground commands. Background batch commands run in isolated
process groups; cancellation terminates their descendants, with a two-second
grace period before forced termination. Interactive programs retain foreground
terminal behavior.
### Diagnostics
```sh
netssh doctor # validate configuration, resolver, cache and programs
netssh doctor --online # additionally query each NetBox instance
netssh explain prod/web01 # resolve and print effective settings, without connecting
```
`explain` reports the chosen instance, address, cache/static/live source,
resolver order and recorded winning strategy, matching SSH rule numbers,
effective SSH options and hooks, and username/port defaults. It does not execute
hooks, mark the host as used or modify the cache. It can query NetBox if resolution
requires it. Older cache entries may lack the winning strategy; this is reported
explicitly. A cache refresh records that information for future explanations.
### Batch commands and retry
```sh
netssh batch --parallel 4 mtr prod/router01 prod/router02 -- --report
netssh batch --yes maintenance prod/router01 prod/router02
netssh batch --dry-run maintenance prod/router01 prod/router02
netssh batch --retry-failed --parallel 2 --yes
```
Batch mode accepts explicit host names and shortcuts. All targets are resolved
and checked before launching commands; duplicates are removed. Parallelism is
bounded (default 4, range 1–64). Output is grouped by host, with each exit code
and a final success/failure count. Batch commands receive no interactive stdin.
The last non-dry-run batch saves its command name, extra arguments and failed
canonical targets in `~/.config/netssh/last-failed.json` with mode `0600`.
Retry uses only that failed subset and rechecks the current configuration and
confirmation requirement. A successful batch clears the retry targets.
Concurrent batches each run independently; the last one to finish owns the
retry file. Command output is held in temporary private files and removed at
completion.
### Optional action history
```yaml
activity:
enabled: true # default false
retention_days: 30 # 0 = unlimited age
max_entries: 1000 # 0 = unlimited count
```
```sh
netssh history
netssh history clear
```
History records host, command name, start time, total duration and final exit
code for custom commands and managed SSH/SFTP/SCP/tunnel sessions. It does not
record arguments, environment variables, API tokens or command output.
Retention is applied when writing records or showing history.
Favorites, pins and action records live in `~/.config/netssh/activity.json`
(mode `0600`), with locking and atomic writes for simultaneous sessions.
`history clear` preserves favorites. `XDG_CONFIG_HOME` applies to both state
files. Configure logging and retention in **History & activity logging**.
### Export and import without secrets
```sh
netssh config export team.json
netssh config import team.json --dry-run
netssh config import team.json --yes
```
Export uses an allowlist: instance names/URLs, static hosts, groups, resolver
settings, shortcuts, completion, recent-host limit and SSH user/port defaults.
It excludes API tokens, credentials embedded in URLs, custom command definitions,
hooks, arbitrary SSH options/rules, local history, favorites and cache contents.
The output is JSON, which is also valid YAML.
Import accepts JSON or YAML and strips credentials and executable settings even
if the supplied file contains them. It preserves local commands and global SSH
rules/options. Existing credentials and per-instance SSH options are retained
only when the instance name and URL match; static-host SSH options are retained
only for the same name/address. New instances require a local token afterward.
Import validates before writing, requires confirmation (or `--yes`), and saves
the previous configuration as `netssh.yaml.before-import` with mode `0600`.
The preview does not modify files. Export/import is intended for shared host
configuration, not a complete backup of local executable settings or secrets.
## Recipes ## Recipes
**Everything through a bastion, except the bastion itself** **Everything through a bastion, except the bastion itself**
+191
View File
@@ -0,0 +1,191 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"sync"
"syscall"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/runner"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"github.com/spf13/cobra"
)
type batchRetry struct {
Command string
Hosts []string
Extra []string
}
type batchResult struct {
Host string
Code int
}
var batchExecutable = os.Executable
func batchPath() string {
return filepath.Join(filepath.Dir(config.Path()), "netssh", "last-failed.json")
}
func batchCmd() *cobra.Command {
var parallel int
var retry, yes, dry bool
cmd := &cobra.Command{Use: "batch COMMAND HOST... [-- EXTRA_ARGS...]", Short: "Run a configured command on hosts with bounded parallelism", RunE: func(cmd *cobra.Command, args []string) error {
if parallel < 1 || parallel > 64 {
return fmt.Errorf("parallel must be between 1 and 64")
}
cfg, err := config.Load()
if err != nil {
return err
}
work := batchRetry{}
if retry {
if len(args) > 0 {
return fmt.Errorf("--retry-failed takes no positional arguments")
}
data, err := os.ReadFile(batchPath())
if err != nil {
return err
}
if err = json.Unmarshal(data, &work); err != nil {
return err
}
} else {
split := cmd.ArgsLenAtDash()
if split >= 0 {
work.Extra = args[split:]
args = args[:split]
}
if len(args) < 2 {
return fmt.Errorf("specify COMMAND and at least one HOST")
}
work.Command, work.Hosts = args[0], args[1:]
}
command, ok := cfg.Commands[work.Command]
if !ok {
return fmt.Errorf("unknown command %q", work.Command)
}
if len(work.Hosts) == 0 {
fmt.Fprintln(cmd.OutOrStdout(), "No failed hosts to retry.")
return nil
}
// Resolve and validate the entire list before launching any action.
var targets []string
seen := map[string]bool{}
for _, target := range work.Hosts {
h, err := resolveTargetE(cfg, target, false)
if err != nil {
return err
}
if !command.Allowed(commandHost(h)) {
return fmt.Errorf("%s is not allowed on %s", work.Command, h.Name)
}
if !seen[h.Name] {
targets = append(targets, h.Name)
seen[h.Name] = true
}
}
if command.Confirm && !dry {
if err := confirmAction(fmt.Sprintf("Run %s on %d hosts", work.Command, len(targets)), yes); err != nil {
return err
}
}
executable, err := batchExecutable()
if err != nil {
return err
}
// Temporary output files bound memory even for very verbose commands.
dir, err := os.MkdirTemp("", "netssh-batch-")
if err != nil {
return err
}
defer os.RemoveAll(dir)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer cancel()
jobs := make(chan int)
results := make(chan batchResult, len(targets))
var wg sync.WaitGroup
var output sync.Mutex
for n := 0; n < parallel; n++ {
wg.Add(1)
go func() {
defer wg.Done()
for i := range jobs {
host := targets[i]
if ctx.Err() != nil {
results <- batchResult{host, 130}
continue
}
output.Lock()
fmt.Fprintf(cmd.OutOrStdout(), "[%s] starting\n", host)
output.Unlock()
f, err := os.CreateTemp(dir, "output-")
if err != nil {
results <- batchResult{host, 1}
continue
}
argv := []string{executable, "run", "--yes"}
if dry {
argv = append(argv, "--dry-run")
}
argv = append(argv, work.Command, "--", host)
argv = append(argv, work.Extra...)
r := runner.Run(ctx, argv, runner.Options{Stdout: f, Stderr: f})
f.Close()
output.Lock()
fmt.Fprintf(cmd.OutOrStdout(), "[%s] exit=%d duration=%s\n", host, r.Code, r.Duration.Round(time.Millisecond))
read, err := os.Open(f.Name())
if err == nil {
_, _ = io.Copy(cmd.OutOrStdout(), read)
read.Close()
}
output.Unlock()
results <- batchResult{host, r.Code}
}
}()
}
for i := range targets {
jobs <- i
}
close(jobs)
wg.Wait()
close(results)
failed := map[string]bool{}
for r := range results {
if r.Code != 0 {
failed[r.Host] = true
}
}
work.Hosts = nil
for _, host := range targets {
if failed[host] {
work.Hosts = append(work.Hosts, host)
}
}
if !dry {
data, _ := json.Marshal(work)
if err := os.MkdirAll(filepath.Dir(batchPath()), 0700); err != nil {
return err
}
if err := storage.WriteFile(batchPath(), data, 0600); err != nil {
return err
}
}
fmt.Fprintf(cmd.OutOrStdout(), "%d succeeded, %d failed\n", len(targets)-len(failed), len(failed))
if len(failed) > 0 {
return fmt.Errorf("batch failed; retry with netssh batch --retry-failed")
}
return nil
}}
cmd.Flags().IntVar(&parallel, "parallel", 4, "Maximum simultaneous hosts (1-64)")
cmd.Flags().BoolVar(&retry, "retry-failed", false, "Repeat failed targets from the last batch")
cmd.Flags().BoolVar(&yes, "yes", false, "Confirm the batch action")
cmd.Flags().BoolVar(&dry, "dry-run", false, "Resolve and print commands without running")
return cmd
}
+1 -1
View File
@@ -41,7 +41,7 @@ func shortcutAliases(entries []cache.Entry, cfg config.Config) map[string]string
} }
plain := strings.NewReplacer(".", "_", "/", "_") plain := strings.NewReplacer(".", "_", "/", "_")
for _, alias := range hook.BuildAliasEntries(append([]cache.Entry(nil), entries...), cfg) { for _, alias := range hook.BuildAliasEntries(append([]cache.Entry(nil), entries...), cfg) {
if alias.Host == "" { if alias.Host == "" || alias.Command != "" {
continue // the command alias for netssh itself continue // the command alias for netssh itself
} }
if alias.Name == plain.Replace(strings.ToLower(cfg.HostLabel(alias.Host))) { if alias.Name == plain.Replace(strings.ToLower(cfg.HostLabel(alias.Host))) {
+131 -28
View File
@@ -17,6 +17,7 @@ import (
tea "charm.land/bubbletea/v2" tea "charm.land/bubbletea/v2"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/hook"
@@ -30,6 +31,7 @@ import (
// managedSubcommands are dispatched to cobra; everything else is treated as SSH wrapper mode. // managedSubcommands are dispatched to cobra; everything else is treated as SSH wrapper mode.
var managedSubcommands = map[string]bool{ var managedSubcommands = map[string]bool{
"doctor": true, "explain": true, "favorites": true, "history": true, "batch": true, "config": true,
"configure": true, "configure": true,
"notes": true, "notes": true,
"search": true, "search": true,
@@ -75,6 +77,10 @@ func main() {
if managedSubcommands[args[0]] { if managedSubcommands[args[0]] {
if err := rootCmd().Execute(); err != nil { if err := rootCmd().Execute(); err != nil {
var exit *commandExit
if errors.As(err, &exit) {
os.Exit(exit.code)
}
os.Exit(1) os.Exit(1)
} }
return return
@@ -208,25 +214,43 @@ func prependArgs(extra, args []string, dests []int) []string {
// resolvedHost is a NetBox host with the address to connect to. // resolvedHost is a NetBox host with the address to connect to.
type resolvedHost struct { type resolvedHost struct {
Name string // cache/selector name, may carry an instance prefix Origin string
Kind string Resolver string
IP string CachedAt time.Time
Tags []string Name string // cache/selector name, may carry an instance prefix
Kind string
IP string
Tags []string
} }
// resolveTarget finds host in the cache (also by shortcut) or NetBox and // resolveTarget finds host in the cache (also by shortcut) or NetBox and
// resolves its address. It exits on failure. // resolves its address. It exits on failure.
func resolveTarget(cfg *config.Config, host string) resolvedHost { func resolveTarget(cfg *config.Config, host string) resolvedHost {
result, err := resolveTargetE(cfg, host, true)
if err != nil {
fatalf("%v", err)
}
return result
}
func resolveTargetE(cfg *config.Config, host string, record bool) (resolvedHost, error) {
c := newCache(cfg) c := newCache(cfg)
_ = c.Load() _ = c.Load()
maybeBackgroundRefresh(cfg, c) if record {
maybeBackgroundRefresh(cfg, c)
}
source, _ := netbox.SplitTarget(host) source, _ := netbox.SplitTarget(host)
useCache := len(cfg.NetBoxes) == 0 || source != "" useCache := len(cfg.NetBoxes) == 0 || source != ""
used := func(entry cache.Entry) resolvedHost { used := func(entry cache.Entry) resolvedHost {
c.MarkUsed(entry.Name) if record {
_ = c.Save() c.MarkUsed(entry.Name)
return resolvedHost{Name: entry.Name, Kind: entry.Kind, IP: entry.IP, Tags: entry.Tags} _ = c.Save()
}
origin := "cache"
if entry.Static {
origin = "static"
}
return resolvedHost{Name: entry.Name, Kind: entry.Kind, IP: entry.IP, Tags: entry.Tags, Origin: origin, Resolver: entry.Resolver, CachedAt: entry.CachedAt}
} }
// Static hosts from the config win and need no NetBox. // Static hosts from the config win and need no NetBox.
@@ -237,16 +261,16 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
} }
entry, found, err := c.GetStatic(host, normalize) entry, found, err := c.GetStatic(host, normalize)
if err != nil { if err != nil {
fatalf("%v", err) return resolvedHost{}, err
} }
if found { if found {
return used(entry) return used(entry), nil
} }
} }
// Cache hit with a fresh TTL — connect directly without querying NetBox. // Cache hit with a fresh TTL — connect directly without querying NetBox.
if entry, fresh := c.Get(host); fresh && useCache { if entry, fresh := c.Get(host); fresh && useCache {
return used(entry) return used(entry), nil
} }
// Shortcut cache lookup: scan entries whose normalized name matches the input. // Shortcut cache lookup: scan entries whose normalized name matches the input.
@@ -257,11 +281,11 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
normalize := normalizeTarget(cfg.Shortcuts, source != "") normalize := normalizeTarget(cfg.Shortcuts, source != "")
entry, found, fresh, err := c.GetByShortcut(lookupHost, normalize) entry, found, fresh, err := c.GetByShortcut(lookupHost, normalize)
if err != nil { if err != nil {
fatalf("%v", err) return resolvedHost{}, err
} }
if found { if found {
if fresh { if fresh {
return used(entry) return used(entry), nil
} }
// Stale shortcut match — use canonical name for NetBox re-fetch. // Stale shortcut match — use canonical name for NetBox re-fetch.
lookupHost = entry.Name lookupHost = entry.Name
@@ -269,7 +293,7 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
} }
if !cfg.HasNetBox() { if !cfg.HasNetBox() {
fatalf("host %q is not in hosts: and no NetBox is configured (netssh configure)", host) return resolvedHost{}, fmt.Errorf("host %q is not in hosts: and no NetBox is configured (netssh configure)", host)
} }
nbClient := newNetBoxClient(cfg) nbClient := newNetBoxClient(cfg)
@@ -280,33 +304,35 @@ func resolveTarget(cfg *config.Config, host string) resolvedHost {
if errors.Is(err, netbox.ErrHostNotFound) && !useCache && shortcutsEnabled { if errors.Is(err, netbox.ErrHostNotFound) && !useCache && shortcutsEnabled {
entry, found, _, cacheErr := c.GetByShortcut(host, normalizeTarget(cfg.Shortcuts, false)) entry, found, _, cacheErr := c.GetByShortcut(host, normalizeTarget(cfg.Shortcuts, false))
if cacheErr != nil { if cacheErr != nil {
fatalf("%v", cacheErr) return resolvedHost{}, cacheErr
} }
if found { if found {
target, err = findSSHHost(ctx, nbClient, entry.Name, cfg.Shortcuts.Domains) target, err = findSSHHost(ctx, nbClient, entry.Name, cfg.Shortcuts.Domains)
} }
} }
if err != nil { if err != nil {
fatalf("NetBox: %v", err) return resolvedHost{}, fmt.Errorf("NetBox: %w", err)
} }
if cached, fresh := c.Get(target.Target()); fresh && cached.Kind == target.Kind { if cached, fresh := c.Get(target.Target()); fresh && cached.Kind == target.Kind {
return used(cached) return used(cached), nil
} }
chain, err := resolver.New(cfg.Resolver) chain, err := resolver.New(cfg.Resolver)
if err != nil { if err != nil {
fatalf("resolver: %v", err) return resolvedHost{}, err
} }
ip, err := chain.Resolve(ctx, &target, nbClient) ip, strategy, err := chain.ResolveWithStrategy(ctx, &target, nbClient)
if err != nil { if err != nil {
fatalf("IP resolution for %q: %v", host, err) return resolvedHost{}, fmt.Errorf("IP resolution for %q: %w", host, err)
} }
entry := cache.Entry{Name: target.Target(), IP: ip, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster} entry := cache.Entry{Name: target.Target(), IP: ip, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster, Resolver: strategy}
c.Upsert(entry) c.Upsert(entry)
return used(entry) result := used(entry)
result.Origin = "live"
return result, nil
} }
// findSSHHost uses the paginated, ambiguity-checking lookup for connection // findSSHHost uses the paginated, ambiguity-checking lookup for connection
@@ -353,7 +379,24 @@ func connectHost(cfg *config.Config, client internalssh.Client, flags internalss
fatalf("%v", err) fatalf("%v", err)
} }
_, name := netbox.SplitTarget(host.Name) _, name := netbox.SplitTarget(host.Name)
execClient(client, client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags), flags) result := client.Apply(args, dests, internalssh.Host{Name: name, IP: host.IP}, opts, flags)
post := config.HookCommand(opts.PostDisconnect)
if flags.DryRun {
if post != "" {
fmt.Fprintf(os.Stderr, "# post_disconnect (skipped in --dry-run): %s\n", post)
}
}
if !flags.DryRun && (post != "" || cfg.Activity.Enabled) {
if result.Notice != "" {
fmt.Fprintln(os.Stderr, result.Notice)
}
code := supervise(cfg, host, client.Name, append([]string{client.Name}, result.Args...), post, 0, false, os.Stdin, os.Stdout, os.Stderr)
if code != 0 {
os.Exit(code)
}
return
}
execClient(client, result, flags)
} }
// hostOptions merges the global, instance, and rule SSH options for host. // hostOptions merges the global, instance, and rule SSH options for host.
@@ -391,6 +434,49 @@ 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)
m.SetHistoryLimit(cfg.TUI.HistoryLimit)
state, stateErr := activity.Read()
if stateErr != nil {
fmt.Fprintf(os.Stderr, "favorites: %v\n", stateErr)
}
m.SetPreferences(state.Favorites, state.Pinned, func(favorites, pinned map[string]bool) error {
err := activity.Update(func(s *activity.State) {
merge := func(dst, previous, next map[string]bool) {
for name, value := range next {
if previous[name] != value {
if value {
dst[name] = true
} else {
delete(dst, name)
}
}
}
for name, value := range previous {
if value && !next[name] {
delete(dst, name)
}
}
}
merge(s.Favorites, state.Favorites, favorites)
merge(s.Pinned, state.Pinned, pinned)
})
if err == nil {
state.Favorites = favorites
state.Pinned = pinned
}
return err
})
m.SetCommands(func(name, kind string, tags []string) []string {
var names []string
h := commandHost(resolvedHost{Name: name, Kind: kind, Tags: tags})
for name, c := range cfg.Commands {
if c.Allowed(h) {
names = append(names, name)
}
}
sort.Strings(names)
return names
})
if cfg.Shortcuts.Show { if cfg.Shortcuts.Show {
aliases := shortcutAliases(c.All(), *cfg) aliases := shortcutAliases(c.All(), *cfg)
m.SetAliases(func(target string) string { return aliases[strings.ToLower(target)] }) m.SetAliases(func(target string) string { return aliases[strings.ToLower(target)] })
@@ -413,6 +499,22 @@ func runTUI() {
if host == nil { if host == nil {
return return
} }
if host.Command != "" {
args := []string{"run", host.Command, "--", host.Name}
if len(host.Targets) > 0 {
args = append([]string{"batch", host.Command}, host.Targets...)
}
root := rootCmd()
root.SetArgs(args)
if err := root.Execute(); err != nil {
var exit *commandExit
if errors.As(err, &exit) {
os.Exit(exit.code)
}
fatalf("%v", err)
}
return
}
if host.Action == tui.ActionMulti { if host.Action == tui.ActionMulti {
if err := runMulti(cfg, host.Targets, multiFlags{}); err != nil { if err := runMulti(cfg, host.Targets, multiFlags{}); err != nil {
fatalf("%v", err) fatalf("%v", err)
@@ -439,11 +541,12 @@ func runTUI() {
if err != nil { if err != nil {
fatalf("resolver: %v", err) fatalf("resolver: %v", err)
} }
host.IP, err = chain.Resolve(ctx, &target, nbClient) var strategy string
host.IP, strategy, err = chain.ResolveWithStrategy(ctx, &target, nbClient)
if err != nil { if err != nil {
fatalf("IP resolution: %v", err) fatalf("IP resolution: %v", err)
} }
c.Upsert(cache.Entry{Name: target.Target(), IP: host.IP, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster}) c.Upsert(cache.Entry{Name: target.Target(), IP: host.IP, Kind: target.Kind, Tags: target.Tags, Cluster: target.Cluster, Resolver: strategy})
tags = target.Tags tags = target.Tags
} }
fmt.Fprintf(os.Stderr, "Connecting to %s (%s)…\n", host.Name, host.IP) fmt.Fprintf(os.Stderr, "Connecting to %s (%s)…\n", host.Name, host.IP)
@@ -529,7 +632,7 @@ func rootCmd() *cobra.Command {
}, },
} }
root.AddCommand(runCmd(), notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd()) root.AddCommand(doctorCmd(), explainCmd(), favoritesCmd(), historyCmd(), batchCmd(), configCmd(), runCmd(), notesCmd(), configureCmd(), searchCmd(), cacheCmd(), aliasCmd(), hookCmd(), shellInitCmd(), versionCmd(), uninstallCmd(), sftpCmd(), scpCmd(), tunnelCmd(), hostsCmd(), multiCmd(), syncCmd())
// cobra builds the "completion" command lazily; force init so we can extend it. // cobra builds the "completion" command lazily; force init so we can extend it.
root.InitDefaultCompletionCmd() root.InitDefaultCompletionCmd()
@@ -792,7 +895,7 @@ func cacheRefreshCmd() *cobra.Command {
continue continue
} }
ip, err := chain.Resolve(ctx, e, nbClient) ip, strategy, err := chain.ResolveWithStrategy(ctx, e, nbClient)
if err != nil { if err != nil {
// Do not turn a failed configured strategy into a fresh // Do not turn a failed configured strategy into a fresh
// primary-IP cache hit that bypasses the resolver. // primary-IP cache hit that bypasses the resolver.
@@ -803,7 +906,7 @@ func cacheRefreshCmd() *cobra.Command {
fmt.Fprintf(os.Stderr, "warning: skipping %s: %v\n", e.Name, err) fmt.Fprintf(os.Stderr, "warning: skipping %s: %v\n", e.Name, err)
continue continue
} }
c.Upsert(cache.Entry{Name: e.Target(), IP: ip, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster}) c.Upsert(cache.Entry{Name: e.Target(), IP: ip, Kind: e.Kind, Tags: e.Tags, Cluster: e.Cluster, Resolver: strategy})
written++ written++
} }
+193
View File
@@ -0,0 +1,193 @@
package main
import (
"context"
"encoding/json"
"fmt"
"os"
"os/exec"
"sort"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/resolver"
"github.com/spf13/cobra"
)
func doctorCmd() *cobra.Command {
var online bool
cmd := &cobra.Command{Use: "doctor", Short: "Check configuration, programs, cache and optional NetBox connectivity", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
failed := false
report := func(label string, err error) {
if err != nil {
failed = true
fmt.Fprintf(cmd.OutOrStdout(), "FAIL %s: %v\n", label, err)
} else {
fmt.Fprintf(cmd.OutOrStdout(), "OK %s\n", label)
}
}
report("configuration", nil)
_, err = resolver.New(cfg.Resolver)
report("resolver", err)
programs := map[string]bool{"ssh": true, "sftp": true, "scp": true}
for name, c := range cfg.Commands {
programs[c.Args[0]] = true
if len(c.Args) > 1 && !strings.HasPrefix(c.Args[1], "-") {
switch c.Args[0] {
case "bash", "sh", "python", "python3":
f, err := os.Open(c.Args[1])
if err == nil {
f.Close()
}
report("script "+name, err)
}
}
}
var names []string
for p := range programs {
names = append(names, p)
}
sort.Strings(names)
for _, p := range names {
_, err := exec.LookPath(p)
report("program "+p, err)
}
report("cache", newCache(cfg).Load())
if online {
sources := cfg.NetBoxes
if len(sources) == 0 && cfg.NetBox.URL != "" {
sources = []config.NetBoxConfig{cfg.NetBox}
}
for _, s := range sources {
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
_, err := netbox.NewClient(s.URL, s.Token, s.TokenVersion).Search(ctx, "", netbox.SearchOptions{})
cancel()
report("NetBox "+s.Name, err)
}
}
if failed {
return fmt.Errorf("doctor found problems")
}
return nil
}}
cmd.Flags().BoolVar(&online, "online", false, "Also query every NetBox instance")
return cmd
}
func explainCmd() *cobra.Command {
return &cobra.Command{Use: "explain HOST", Short: "Explain actual host resolution and effective SSH settings without connecting", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
h, err := resolveTargetE(cfg, args[0], false)
if err != nil {
return err
}
selectors := commandHost(h)
user, port := hostDefaults(cfg, h)
opts := hostOptions(cfg, h)
var rules []int
for i, r := range cfg.SSH.Rules {
if r.Match.Matches(selectors) {
rules = append(rules, i+1)
}
}
strategy := h.Resolver
if strategy == "" {
if h.Origin == "static" {
strategy = "static address"
} else {
strategy = "not recorded in this cache entry"
}
}
return json.NewEncoder(cmd.OutOrStdout()).Encode(map[string]any{
"target": h.Name, "instance": selectors.Instance, "address": h.IP, "source": h.Origin, "cached_at": h.CachedAt,
"resolver_order": cfg.Resolver.Strategies, "resolver_used": strategy, "matching_rules": rules, "user": user, "port": port, "ssh": opts,
})
}}
}
func favoritesCmd() *cobra.Command {
cmd := &cobra.Command{Use: "favorites", Short: "List or change favorite and pinned hosts", RunE: func(cmd *cobra.Command, _ []string) error {
s, err := activity.Read()
if err != nil {
return err
}
var names []string
for n := range s.Favorites {
if s.Favorites[n] {
names = append(names, n)
}
}
sort.Strings(names)
for _, n := range names {
marker := "favorite"
if s.Pinned[n] {
marker = "pinned"
}
fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\n", n, marker)
}
return nil
}}
for _, action := range []string{"add", "remove", "pin", "unpin"} {
cmd.AddCommand(&cobra.Command{Use: action + " HOST", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
target := args[0]
if action == "add" || action == "pin" {
cfg, err := config.Load()
if err != nil {
return err
}
h, err := resolveTargetE(cfg, target, false)
if err != nil {
return err
}
target = h.Name
}
return activity.Update(func(s *activity.State) {
switch action {
case "add":
s.Favorites[target] = true
case "pin":
s.Favorites[target] = true
s.Pinned[target] = true
case "unpin":
delete(s.Pinned, target)
case "remove":
delete(s.Favorites, target)
delete(s.Pinned, target)
}
})
}})
}
return cmd
}
func historyCmd() *cobra.Command {
cmd := &cobra.Command{Use: "history", Short: "Show optional local action history", RunE: func(cmd *cobra.Command, _ []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
if err := activity.Update(func(s *activity.State) { activity.Prune(s, cfg.Activity) }); err != nil {
return err
}
s, err := activity.Read()
if err != nil {
return err
}
for i := len(s.Records) - 1; i >= 0; i-- {
r := s.Records[i]
fmt.Fprintf(cmd.OutOrStdout(), "%s\t%s\t%s\texit=%d\t%s\n", r.Time.Format(time.RFC3339), r.Host, r.Command, r.Code, r.Duration.Round(time.Millisecond))
}
return nil
}}
cmd.AddCommand(&cobra.Command{Use: "clear", Short: "Delete recorded actions, preserving favorites", Args: cobra.NoArgs, RunE: func(_ *cobra.Command, _ []string) error {
return activity.Update(func(s *activity.State) { s.Records = nil })
}})
return cmd
}
+258
View File
@@ -0,0 +1,258 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"reflect"
"strings"
"testing"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func writeOperationsConfig(t *testing.T, extra string) {
t.Helper()
prepareTransferTest(t)
data := `hosts:
- name: router
address: 192.0.2.1
tags: [router]
- name: fail
address: 192.0.2.2
- name: okay
address: 192.0.2.3
resolver:
strategies: [primary_ip]
` + extra
if err := os.WriteFile(config.Path(), []byte(data), 0600); err != nil {
t.Fatal(err)
}
}
func TestPostHooksFiltersAndConfirmation(t *testing.T) {
dir := t.TempDir()
marker := filepath.Join(dir, "post")
writeOperationsConfig(t, fmt.Sprintf(`
commands:
success:
args: [sh, -c, "exit 0", "{host}"]
post_run: 'printf "%%s:%%s" "$NETSSH_HOST" "$NETSSH_EXIT_CODE" > %s'
failure:
args: [sh, -c, "exit 7", "{host}"]
post_run: 'printf "%%s" "$NETSSH_EXIT_CODE" > %s; exit 9'
postfail:
args: [sh, -c, "exit 0", "{host}"]
post_run: exit 9
protected:
args: [sh, -c, "exit 0", "{host}"]
confirm: true
match: {tag: router, kind: static, name: "rou*"}
timeout:
args: [sh, -c, "sleep 20", "{host}"]
timeout: 50ms
activity:
enabled: true
retention_days: 30
max_entries: 50
`, marker, marker))
if out, err := runNetssh(t, "run", "--dry-run", "success", "router"); err != nil {
t.Fatalf("%s %v", out, err)
}
if _, err := os.Stat(marker); !os.IsNotExist(err) {
t.Fatal("dry-run executed post hook")
}
if out, err := runNetssh(t, "run", "success", "router"); err != nil {
t.Fatalf("%s %v", out, err)
}
data, _ := os.ReadFile(marker)
if string(data) != "router:0" {
t.Fatal(string(data))
}
for _, tc := range []struct {
name string
code int
}{{"failure", 7}, {"postfail", 9}, {"timeout", 124}} {
_, err := runNetssh(t, "run", tc.name, "router")
exit, ok := err.(*exec.ExitError)
if !ok || exit.ExitCode() != tc.code {
t.Fatalf("%s: %v", tc.name, err)
}
}
data, _ = os.ReadFile(marker)
if string(data) != "7" {
t.Fatal(string(data))
}
if out, err := runNetssh(t, "run", "protected", "router"); err == nil || !strings.Contains(out, "--yes") {
t.Fatalf("%q %v", out, err)
}
if out, err := runNetssh(t, "run", "--yes", "protected", "router"); err != nil {
t.Fatalf("%q %v", out, err)
}
if out, err := runNetssh(t, "run", "--yes", "protected", "okay"); err == nil || !strings.Contains(out, "not allowed") {
t.Fatalf("%q %v", out, err)
}
state, err := activity.Read()
if err != nil || len(state.Records) != 5 {
t.Fatalf("%+v %v", state, err)
}
}
func TestSSHPostDisconnect(t *testing.T) {
dir := t.TempDir()
marker := filepath.Join(dir, "after")
writeOperationsConfig(t, fmt.Sprintf("ssh:\n post_disconnect: 'printf \"%%s\" \"$NETSSH_EXIT_CODE\" > %s'\n", marker))
if err := os.WriteFile(filepath.Join(dir, "ssh"), []byte("#!/bin/sh\nexit 6\n"), 0700); err != nil {
t.Fatal(err)
}
t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
_, err := runNetssh(t, "router")
exit, ok := err.(*exec.ExitError)
if !ok || exit.ExitCode() != 6 {
t.Fatal(err)
}
data, _ := os.ReadFile(marker)
if string(data) != "6" {
t.Fatalf("post: %s", data)
}
}
func TestExplainAndFavorites(t *testing.T) {
writeOperationsConfig(t, "tui:\n history_limit: 25\nssh:\n rules:\n - match: {tag: router}\n post_disconnect: echo done\n")
out, err := runNetssh(t, "explain", "router")
if err != nil {
t.Fatalf("%s %v", out, err)
}
var result map[string]any
if err := json.Unmarshal([]byte(out), &result); err != nil {
t.Fatal(err)
}
if result["source"] != "static" || result["address"] != "192.0.2.1" {
t.Fatal(result)
}
for _, args := range [][]string{{"favorites", "pin", "router"}, {"favorites", "add", "okay"}} {
if out, err := runNetssh(t, args...); err != nil {
t.Fatalf("%s %v", out, err)
}
}
state, err := activity.Read()
if err != nil || !state.Pinned["router"] || !state.Favorites["okay"] {
t.Fatalf("%+v %v", state, err)
}
if out, err := runNetssh(t, "favorites", "remove", "router"); err != nil {
t.Fatalf("%s %v", out, err)
}
state, _ = activity.Read()
if state.Pinned["router"] || state.Favorites["router"] {
t.Fatal(state)
}
}
func TestPortableConfigOmitsAllExecutableSecrets(t *testing.T) {
c := config.Config{
NetBoxes: []config.NetBoxConfig{{Name: "prod", URL: "https://user:URLSECRET@netbox.example", Token: "TOKEN", SSH: config.SSHOptions{PreConnect: "HOOKSECRET"}}},
SSH: config.SSHConfig{SSHOptions: config.SSHOptions{Options: map[string]string{"ProxyCommand": "OPTIONSECRET"}, PostDisconnect: "POSTSECRET"}},
Commands: map[string]config.HostCommand{"check": {Args: []string{"echo", "COMMANDSECRET", "{host}"}}},
Hosts: []config.StaticHost{{Name: "router", Address: "192.0.2.1", SSH: config.SSHOptions{PreConnect: "STATICSECRET"}}},
TUI: config.TUIConfig{HistoryLimit: 25},
}
data, err := json.Marshal(portableConfig(c))
if err != nil {
t.Fatal(err)
}
for _, secret := range []string{"URLSECRET", "TOKEN", "HOOKSECRET", "OPTIONSECRET", "POSTSECRET", "COMMANDSECRET", "STATICSECRET"} {
if bytes.Contains(data, []byte(secret)) {
t.Fatalf("export leaked %s", secret)
}
}
parsed, err := decodePortable(data)
if err != nil {
t.Fatal(err)
}
if parsed.TUI.HistoryLimit != 25 || len(parsed.NetBoxes) != 1 || parsed.NetBoxes[0].URL != "https://netbox.example" {
t.Fatalf("%+v", parsed)
}
hostile := []byte("netbox:\n url: https://netbox.example\n token: bad\nssh:\n pre_connect: touch /tmp/never\ncommands:\n check:\n args: [sh, -c, evil]\n")
parsed, err = decodePortable(hostile)
if err != nil || parsed.NetBox.Token != "" || parsed.SSH.PreConnect != "" || len(parsed.Commands) != 0 {
t.Fatalf("%+v %v", parsed, err)
}
}
func TestBatchRetryFailedOnly(t *testing.T) {
bin := filepath.Join(t.TempDir(), "netssh")
build := exec.Command("go", "build", "-o", bin, ".")
if out, err := build.CombinedOutput(); err != nil {
t.Fatalf("build: %s %v", out, err)
}
old := batchExecutable
batchExecutable = func() (string, error) { return bin, nil }
t.Cleanup(func() { batchExecutable = old })
dir := t.TempDir()
script := filepath.Join(dir, "check.sh")
ready := filepath.Join(dir, "ready")
if err := os.WriteFile(script, []byte(fmt.Sprintf("#!/bin/sh\nif [ \"$1\" = fail ] && [ ! -f %q ]; then exit 3; fi\nprintf 'ran %%s\\n' \"$1\"\n", ready)), 0700); err != nil {
t.Fatal(err)
}
writeOperationsConfig(t, fmt.Sprintf("commands:\n check:\n args: [%q, \"{host}\"]\n", script))
run := func(args ...string) (string, error) {
cmd := batchCmd()
cmd.SetArgs(args)
var out bytes.Buffer
cmd.SetOut(&out)
cmd.SetErr(&out)
err := cmd.Execute()
return out.String(), err
}
out, err := run("--parallel", "2", "check", "router", "fail", "okay")
if err == nil || !strings.Contains(out, "2 succeeded, 1 failed") {
t.Fatalf("%s %v", out, err)
}
data, _ := os.ReadFile(batchPath())
var retry batchRetry
if err := json.Unmarshal(data, &retry); err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(retry.Hosts, []string{"fail"}) {
t.Fatalf("%+v", retry)
}
if err := os.WriteFile(ready, nil, 0600); err != nil {
t.Fatal(err)
}
out, err = run("--retry-failed")
if err != nil || !strings.Contains(out, "1 succeeded, 0 failed") || strings.Contains(out, "ran router") {
t.Fatalf("%s %v", out, err)
}
}
func TestImportPreservesOnlyMatchingCredentials(t *testing.T) {
writeOperationsConfig(t, "")
original := []byte("netboxes:\n - name: prod\n url: https://prod.example\n token: LOCALPROD\n - name: lab\n url: https://lab.example\n token: LOCALLAB\ncommands:\n local:\n args: [echo, \"{host}\"]\n")
if err := os.WriteFile(config.Path(), original, 0600); err != nil {
t.Fatal(err)
}
shared := filepath.Join(t.TempDir(), "shared.yaml")
if err := os.WriteFile(shared, []byte("netboxes:\n - name: prod\n url: https://prod.example\n token: UNTRUSTED\n - name: lab\n url: https://other.example\ntui:\n history_limit: 25\nssh:\n pre_connect: evil\n"), 0600); err != nil {
t.Fatal(err)
}
if out, err := runNetssh(t, "config", "import", shared, "--dry-run"); err != nil {
t.Fatalf("%s %v", out, err)
}
after, _ := os.ReadFile(config.Path())
if !bytes.Equal(original, after) {
t.Fatal("preview changed config")
}
if out, err := runNetssh(t, "config", "import", shared, "--yes"); err != nil {
t.Fatalf("%s %v", out, err)
}
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
if cfg.NetBoxes[0].Token != "LOCALPROD" || cfg.NetBoxes[1].Token != "" || cfg.SSH.PreConnect != "" || len(cfg.Commands) != 1 || cfg.TUI.HistoryLimit != 25 {
t.Fatalf("incorrect imported settings: names=%d tui=%d", len(cfg.NetBoxes), cfg.TUI.HistoryLimit)
}
backup, _ := os.ReadFile(config.Path() + ".before-import")
if !bytes.Equal(backup, original) {
t.Fatal("backup differs")
}
}
+164
View File
@@ -0,0 +1,164 @@
package main
import (
"bytes"
"encoding/json"
"fmt"
"net/url"
"os"
"strings"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/setup"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
// Portable config deliberately omits arbitrary command/hook/SSH option strings:
// secrets may be embedded there, and cannot reliably be detected by key name.
func portableConfig(c config.Config) map[string]any {
cleanURL := func(raw string) string {
u, err := url.Parse(raw)
if err != nil {
return ""
}
u.User = nil
u.RawQuery = ""
u.Fragment = ""
return u.String()
}
sources := []map[string]any{}
for _, s := range c.NetBoxes {
sources = append(sources, map[string]any{"name": s.Name, "url": cleanURL(s.URL), "disable_prefix": s.DisablePrefix})
}
hosts := []map[string]any{}
for _, h := range c.Hosts {
hosts = append(hosts, map[string]any{"name": h.Name, "address": h.Address, "user": h.User, "port": h.Port, "tags": h.Tags})
}
rewrites := []map[string]string{}
for _, r := range c.Shortcuts.Rewrites {
rewrites = append(rewrites, map[string]string{"pattern": r.Pattern, "replace": r.Replace})
}
out := map[string]any{
"hosts": hosts, "groups": c.Groups,
"ssh": map[string]any{"default_user": c.SSH.DefaultUser, "default_port": c.SSH.DefaultPort},
"resolver": map[string]any{"strategies": c.Resolver.Strategies, "management_subnets": c.Resolver.ManagementSubnets, "interface_name": c.Resolver.InterfaceName, "hostname_domain": c.Resolver.HostnameDomain},
"shortcuts": map[string]any{"domains": c.Shortcuts.Domains, "rewrites": rewrites, "strip_hyphens": c.Shortcuts.StripHyphens, "show": c.Shortcuts.Show},
"completion": map[string]any{"max_results": c.Completion.MaxResults},
"tui": map[string]any{"history_limit": c.TUI.HistoryLimit},
}
if len(sources) > 0 {
out["netboxes"] = sources
} else if c.NetBox.URL != "" {
out["netbox"] = map[string]string{"url": cleanURL(c.NetBox.URL)}
}
return out
}
func decodePortable(data []byte) (config.Config, error) {
v := viper.New()
v.SetConfigType("yaml")
v.SetDefault("tui.history_limit", 10)
var c config.Config
if err := v.ReadConfig(bytes.NewReader(data)); err != nil {
return c, err
}
if err := v.Unmarshal(&c); err != nil {
return c, err
}
// Strip executable settings and credentials even from externally edited files.
safe, _ := json.Marshal(portableConfig(c))
v = viper.New()
v.SetConfigType("json")
if err := v.ReadConfig(bytes.NewReader(safe)); err != nil {
return c, err
}
c = config.Config{}
err := v.Unmarshal(&c)
return c, err
}
func configCmd() *cobra.Command {
cmd := &cobra.Command{Use: "config", Short: "Share configuration without credentials or executable settings"}
export := &cobra.Command{Use: "export [FILE]", Short: "Export a secret-free JSON configuration (also valid YAML)", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load()
if err != nil {
return err
}
data, err := json.MarshalIndent(portableConfig(*cfg), "", " ")
if err != nil {
return err
}
if len(args) == 0 {
fmt.Fprintln(cmd.OutOrStdout(), string(data))
return nil
}
return storage.WriteFile(args[0], append(data, '\n'), 0600)
}}
var yes, dry bool
imp := &cobra.Command{Use: "import FILE", Short: "Import shared host settings; preserve matching local credentials and commands", Args: cobra.ExactArgs(1), RunE: func(cmd *cobra.Command, args []string) error {
data, err := os.ReadFile(args[0])
if err != nil {
return err
}
incoming, err := decodePortable(data)
if err != nil {
return err
}
current, err := config.Load()
if err != nil {
return err
}
same := func(a, b string) bool { return strings.TrimRight(a, "/") == strings.TrimRight(b, "/") }
for i := range incoming.NetBoxes {
for _, old := range current.NetBoxes {
s := &incoming.NetBoxes[i]
if strings.EqualFold(s.Name, old.Name) && same(s.URL, old.URL) {
s.Token = old.Token
s.TokenVersion = old.TokenVersion
s.SSH = old.SSH
}
}
}
if incoming.NetBox.URL != "" && same(incoming.NetBox.URL, current.NetBox.URL) {
incoming.NetBox.Token = current.NetBox.Token
incoming.NetBox.TokenVersion = current.NetBox.TokenVersion
incoming.NetBox.SSH = current.NetBox.SSH
}
incoming.Commands = current.Commands
incoming.Activity = current.Activity
incoming.Cache = current.Cache
incoming.Multi = current.Multi
incoming.Shell = current.Shell
incoming.SSH.SSHOptions = current.SSH.SSHOptions
incoming.SSH.Rules = current.SSH.Rules
for i := range incoming.Hosts {
for _, old := range current.Hosts {
if incoming.Hosts[i].Name == old.Name && incoming.Hosts[i].Address == old.Address {
incoming.Hosts[i].SSH = old.SSH
}
}
}
for _, validate := range []func() error{incoming.ValidateNetBoxes, incoming.ValidateHosts, incoming.ValidateSSH, incoming.ValidateCommands, incoming.ValidateOperations, incoming.Shortcuts.Validate, incoming.ValidateMulti} {
if err := validate(); err != nil {
return err
}
}
fmt.Fprintf(cmd.OutOrStdout(), "Import: %d named instances, %d static hosts. Local commands and matching credentials are retained.\n", len(incoming.NetBoxes), len(incoming.Hosts))
if dry {
return nil
}
if err := confirmAction("Replace shared configuration settings", yes); err != nil {
return err
}
if existing, err := os.ReadFile(config.Path()); err == nil {
if err := storage.WriteFile(config.Path()+".before-import", existing, 0600); err != nil {
return err
}
}
return setup.Save(incoming)
}}
imp.Flags().BoolVar(&yes, "yes", false, "Approve replacing shared configuration settings")
imp.Flags().BoolVar(&dry, "dry-run", false, "Validate and preview without writing")
cmd.AddCommand(export, imp)
return cmd
}
+31 -8
View File
@@ -3,13 +3,13 @@ package main
import ( import (
"fmt" "fmt"
"os" "os"
"os/exec"
"sort" "sort"
"strings" "strings"
"syscall" "time"
"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/netbox" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"github.com/charmbracelet/x/term"
"github.com/spf13/cobra" "github.com/spf13/cobra"
) )
@@ -25,7 +25,7 @@ func expandHostCommand(command config.HostCommand, host resolvedHost, extra []st
} }
func runCmd() *cobra.Command { func runCmd() *cobra.Command {
var dryRun bool var dryRun, yes, status bool
cmd := &cobra.Command{ cmd := &cobra.Command{
Use: "run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]", Use: "run [--dry-run] COMMAND HOST [-- EXTRA_ARGS...]",
Short: "Run a configured local command for a NetBox or static host", Short: "Run a configured local command for a NetBox or static host",
@@ -39,9 +39,18 @@ func runCmd() *cobra.Command {
if !ok { if !ok {
return fmt.Errorf("unknown configured command %q", args[0]) return fmt.Errorf("unknown configured command %q", args[0])
} }
host := resolveTarget(cfg, args[1]) host, err := resolveTargetE(cfg, args[1], !dryRun)
if err != nil {
return err
}
if !command.Allowed(commandHost(host)) {
return fmt.Errorf("command %q is not allowed for %s", args[0], host.Name)
}
argv := expandHostCommand(command, host, args[2:]) argv := expandHostCommand(command, host, args[2:])
if dryRun { if dryRun {
if post := config.HookCommand(command.PostRun); post != "" {
fmt.Fprintf(cmd.ErrOrStderr(), "# post_run (skipped in --dry-run): %s\n", post)
}
for i, arg := range argv { for i, arg := range argv {
if i > 0 { if i > 0 {
fmt.Fprint(cmd.OutOrStdout(), " ") fmt.Fprint(cmd.OutOrStdout(), " ")
@@ -51,11 +60,19 @@ func runCmd() *cobra.Command {
fmt.Fprintln(cmd.OutOrStdout()) fmt.Fprintln(cmd.OutOrStdout())
return nil return nil
} }
path, err := exec.LookPath(argv[0]) if command.Confirm {
if err != nil { if err := confirmAction("Run "+args[0]+" on "+host.Name, yes); err != nil {
return fmt.Errorf("%s not found in PATH: %w", argv[0], err) return err
}
} }
return syscall.Exec(path, argv, os.Environ()) timeout, _ := time.ParseDuration(command.Timeout)
code := supervise(cfg, host, args[0], argv, command.PostRun, timeout, status || term.IsTerminal(os.Stderr.Fd()), os.Stdin, cmd.OutOrStdout(), cmd.ErrOrStderr())
if code != 0 {
cmd.SilenceErrors = true
cmd.SilenceUsage = true
return &commandExit{code}
}
return nil
}, },
ValidArgsFunction: func(cmd *cobra.Command, args []string, prefix string) ([]string, cobra.ShellCompDirective) { ValidArgsFunction: func(cmd *cobra.Command, args []string, prefix string) ([]string, cobra.ShellCompDirective) {
if len(args) == 0 { if len(args) == 0 {
@@ -78,6 +95,12 @@ func runCmd() *cobra.Command {
return nil, cobra.ShellCompDirectiveNoFileComp return nil, cobra.ShellCompDirectiveNoFileComp
}, },
} }
cmd.Flags().BoolVar(&yes, "yes", false, "Approve an action requiring confirmation")
cmd.Flags().BoolVar(&status, "status", false, "Show elapsed runtime")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the command without running it") cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Print the command without running it")
return cmd return cmd
} }
type commandExit struct{ code int }
func (e *commandExit) Error() string { return fmt.Sprintf("command exited with status %d", e.code) }
+59
View File
@@ -0,0 +1,59 @@
package main
import (
"bufio"
"context"
"fmt"
"io"
"os"
"strconv"
"strings"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/activity"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/runner"
"github.com/charmbracelet/x/term"
)
func commandHost(h resolvedHost) config.SSHHost {
instance, name := netbox.SplitTarget(h.Name)
return config.SSHHost{Instance: instance, Name: name, Kind: h.Kind, Tags: h.Tags}
}
func confirmAction(message string, yes bool) error {
if yes {
return nil
}
if !term.IsTerminal(os.Stdin.Fd()) {
return fmt.Errorf("%s requires confirmation; use --yes for unattended execution", message)
}
fmt.Fprintf(os.Stderr, "%s? [y/N] ", message)
answer, err := bufio.NewReader(os.Stdin).ReadString('\n')
if err != nil {
return err
}
if strings.EqualFold(strings.TrimSpace(answer), "y") || strings.EqualFold(strings.TrimSpace(answer), "yes") {
return nil
}
return fmt.Errorf("cancelled")
}
func supervise(cfg *config.Config, h resolvedHost, name string, argv []string, post string, timeout time.Duration, status bool, stdin io.Reader, stdout, stderr io.Writer) int {
start := time.Now()
env := append(preConnectEnv(h, name), "NETSSH_COMMAND="+name)
result := runner.Run(context.Background(), argv, runner.Options{Stdin: stdin, Stdout: stdout, Stderr: stderr, Env: env, Timeout: timeout, Status: status, Label: name + " " + h.Name})
code := result.Code
if result.Started && config.HookCommand(post) != "" {
hook := runner.Run(context.Background(), []string{"sh", "-c", post}, runner.Options{Stdin: nil, Stdout: stderr, Stderr: stderr, Env: append(env, "NETSSH_EXIT_CODE="+strconv.Itoa(code)), Timeout: 30 * time.Second})
if hook.Code != 0 {
fmt.Fprintf(stderr, "post hook failed (exit %d)\n", hook.Code)
if code == 0 {
code = hook.Code
}
}
}
if err := activity.Append(cfg.Activity, activity.Record{Time: start, Host: h.Name, Command: name, Code: code, Duration: time.Since(start)}); err != nil {
fmt.Fprintf(stderr, "activity: %v\n", err)
}
return code
}
+14
View File
@@ -0,0 +1,14 @@
package main
import (
"os"
"testing"
)
// Integration helpers run this test binary as netssh. An automatic refresh
// would otherwise launch the test binary again with "cache refresh", rerunning
// the entire suite. Explicit cache-refresh tests still exercise the real command.
func TestMain(m *testing.M) {
_ = os.Setenv("NETSSH_NO_REFRESH", "1")
os.Exit(m.Run())
}
+3 -3
View File
@@ -204,10 +204,10 @@ func uninstallCmd() *cobra.Command {
- netssh blocks and unmarked entries of older versions in bash, zsh, and fish profiles - netssh blocks and unmarked entries of older versions in bash, zsh, and fish profiles
- shell completion files (bash, zsh, fish, oh-my-zsh cache, command alias) - shell completion files (bash, zsh, fish, oh-my-zsh cache, command alias)
- the cache directory with hosts, aliases, and per-instance caches - the cache directory with hosts, aliases, and per-instance caches
- the config file (a private backup is kept) and local server notes - the config file (a private backup is kept) and local notes, favorites, action history and batch retry state
- the netssh binary - the netssh binary
Use --keep-config to keep the config file and notes for a reinstall.`, Use --keep-config to keep the config file and local state for a reinstall.`,
Args: cobra.NoArgs, Args: cobra.NoArgs,
RunE: func(cmd *cobra.Command, args []string) error { RunE: func(cmd *cobra.Command, args []string) error {
cfg, err := config.Load() cfg, err := config.Load()
@@ -244,7 +244,7 @@ Use --keep-config to keep the config file and notes for a reinstall.`,
return err return err
}, },
} }
cmd.Flags().BoolVar(&keepConfig, "keep-config", false, "Keep the config file and local notes") cmd.Flags().BoolVar(&keepConfig, "keep-config", false, "Keep the config file and local state")
cmd.Flags().BoolVarP(&yes, "yes", "y", false, "Do not ask for confirmation") cmd.Flags().BoolVarP(&yes, "yes", "y", false, "Do not ask for confirmation")
cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Only show what would be removed") cmd.Flags().BoolVar(&dryRun, "dry-run", false, "Only show what would be removed")
return cmd return cmd
+94
View File
@@ -0,0 +1,94 @@
// Package activity stores local preferences and optional execution metadata.
// No command arguments, environment variables, tokens or command output are logged.
package activity
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"sort"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/storage"
"golang.org/x/sys/unix"
)
type Record struct {
Time time.Time `json:"time"`
Host string `json:"host"`
Command string `json:"command"`
Code int `json:"exit_code"`
Duration time.Duration `json:"duration_ns"`
}
type State struct {
Favorites map[string]bool `json:"favorites,omitempty"`
Pinned map[string]bool `json:"pinned,omitempty"`
Records []Record `json:"records,omitempty"`
}
func Path() string { return filepath.Join(filepath.Dir(config.Path()), "netssh", "activity.json") }
func Read() (State, error) {
var s State
data, err := os.ReadFile(Path())
if os.IsNotExist(err) {
err = nil
} else if err == nil {
err = json.Unmarshal(data, &s)
}
if s.Favorites == nil {
s.Favorites = map[string]bool{}
}
if s.Pinned == nil {
s.Pinned = map[string]bool{}
}
return s, err
}
func Update(change func(*State)) error {
p := Path()
if err := os.MkdirAll(filepath.Dir(p), 0700); err != nil {
return err
}
f, err := os.OpenFile(p+".lock", os.O_CREATE|os.O_RDWR, 0600)
if err != nil {
return err
}
defer f.Close()
if err = unix.Flock(int(f.Fd()), unix.LOCK_EX); err != nil {
return err
}
defer unix.Flock(int(f.Fd()), unix.LOCK_UN)
s, err := Read()
if err != nil {
return fmt.Errorf("local state: %w", err)
}
change(&s)
data, err := json.MarshalIndent(s, "", " ")
if err != nil {
return err
}
return storage.WriteFile(p, data, 0600)
}
func Prune(s *State, c config.ActivityConfig) {
if c.RetentionDays > 0 {
cutoff := time.Now().Add(-time.Duration(c.RetentionDays) * 24 * time.Hour)
keep := s.Records[:0]
for _, r := range s.Records {
if !r.Time.Before(cutoff) {
keep = append(keep, r)
}
}
s.Records = keep
}
sort.SliceStable(s.Records, func(i, j int) bool { return s.Records[i].Time.Before(s.Records[j].Time) })
if c.MaxEntries > 0 && len(s.Records) > c.MaxEntries {
s.Records = s.Records[len(s.Records)-c.MaxEntries:]
}
}
func Append(c config.ActivityConfig, r Record) error {
if !c.Enabled {
return nil
}
return Update(func(s *State) { s.Records = append(s.Records, r); Prune(s, c) })
}
+59
View File
@@ -0,0 +1,59 @@
package activity
import (
"fmt"
"os"
"sync"
"testing"
"time"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func TestConcurrentActivityAndRetention(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.ActivityConfig{Enabled: true, RetentionDays: 1, MaxEntries: 10}
if err := Update(func(s *State) {
s.Favorites["prod/web"] = true
s.Pinned["prod/web"] = true
s.Records = []Record{{Time: time.Now().Add(-48 * time.Hour), Host: "old"}}
}); err != nil {
t.Fatal(err)
}
var wg sync.WaitGroup
for i := 0; i < 20; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if err := Append(cfg, Record{Time: time.Now(), Host: fmt.Sprint(i), Command: "test"}); err != nil {
t.Error(err)
}
}()
}
wg.Wait()
s, err := Read()
if err != nil {
t.Fatal(err)
}
if len(s.Records) != 10 || !s.Favorites["prod/web"] || !s.Pinned["prod/web"] {
t.Fatalf("%+v", s)
}
for _, r := range s.Records {
if r.Host == "old" {
t.Fatal("expired record retained")
}
}
info, _ := os.Stat(Path())
if info.Mode().Perm() != 0600 {
t.Fatal(info.Mode())
}
}
func TestDisabledHistoryDoesNotWrite(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := Append(config.ActivityConfig{}, Record{}); err != nil {
t.Fatal(err)
}
if _, err := os.Stat(Path()); !os.IsNotExist(err) {
t.Fatal("disabled history wrote data")
}
}
+1
View File
@@ -17,6 +17,7 @@ import (
) )
type Entry struct { type Entry struct {
Resolver string `json:"resolver,omitempty"`
Name string `json:"name"` Name string `json:"name"`
IP string `json:"ip"` IP string `json:"ip"`
Kind string `json:"kind"` Kind string `json:"kind"`
+19
View File
@@ -4,10 +4,15 @@ import (
"fmt" "fmt"
"regexp" "regexp"
"strings" "strings"
"time"
) )
// HostCommand defines a local command and the prefix of its generated host aliases. // HostCommand defines a local command and the prefix of its generated host aliases.
type HostCommand struct { type HostCommand struct {
PostRun string `mapstructure:"post_run"`
Match SSHMatch `mapstructure:"match"`
Confirm bool `mapstructure:"confirm"`
Timeout string `mapstructure:"timeout"`
AliasPrefix string `mapstructure:"alias_prefix" yaml:"alias_prefix"` AliasPrefix string `mapstructure:"alias_prefix" yaml:"alias_prefix"`
Args []string `mapstructure:"args" yaml:"args"` Args []string `mapstructure:"args" yaml:"args"`
} }
@@ -15,6 +20,20 @@ type HostCommand struct {
func (c *Config) ValidateCommands() error { func (c *Config) ValidateCommands() error {
prefixes := make(map[string]bool) prefixes := make(map[string]bool)
for name, command := range c.Commands { for name, command := range c.Commands {
if strings.ContainsRune(command.PostRun, 0) {
return fmt.Errorf("commands.%s.post_run contains NUL", name)
}
if command.Match != (SSHMatch{}) {
if err := command.Match.Validate("commands." + name); err != nil {
return err
}
}
if command.Timeout != "" {
d, err := time.ParseDuration(command.Timeout)
if err != nil || d <= 0 {
return fmt.Errorf("commands.%s.timeout requires a positive duration", name)
}
}
if name == "" || ValidateCommandAlias(name) != nil { if name == "" || ValidateCommandAlias(name) != nil {
return fmt.Errorf("commands.%s: name must be a non-reserved shell identifier", name) return fmt.Errorf("commands.%s: name must be a non-reserved shell identifier", name)
} }
+9 -1
View File
@@ -11,6 +11,8 @@ import (
) )
type Config struct { type Config struct {
TUI TUIConfig `mapstructure:"tui"`
Activity ActivityConfig `mapstructure:"activity"`
Commands map[string]HostCommand `mapstructure:"commands"` Commands map[string]HostCommand `mapstructure:"commands"`
Shell ShellConfig `mapstructure:"shell"` Shell ShellConfig `mapstructure:"shell"`
NetBox NetBoxConfig `mapstructure:"netbox"` NetBox NetBoxConfig `mapstructure:"netbox"`
@@ -113,6 +115,9 @@ func Load() (*Config, error) {
v.SetDefault("resolver.strategies", []string{"management_subnet", "primary_ip"}) v.SetDefault("resolver.strategies", []string{"management_subnet", "primary_ip"})
v.SetDefault("resolver.management_subnets", []string{}) v.SetDefault("resolver.management_subnets", []string{})
v.SetDefault("cache.ttl", 3600) v.SetDefault("cache.ttl", 3600)
v.SetDefault("tui.history_limit", 10)
v.SetDefault("activity.retention_days", 30)
v.SetDefault("activity.max_entries", 1000)
configDir, err := os.UserConfigDir() configDir, err := os.UserConfigDir()
if err == nil { if err == nil {
@@ -126,7 +131,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", "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"} { for _, key := range []string{"netbox.url", "netbox.token", "netbox.token_version", "resolver.strategies", "resolver.management_subnets", "resolver.interface_name", "resolver.hostname_domain", "cache.ttl", "cache.path", "ssh.default_user", "ssh.default_port", "shortcuts.domains", "shortcuts.strip_hyphens", "shortcuts.show", "shell.alias", "ssh.proxy_jump", "ssh.pre_connect", "ssh.post_disconnect", "tui.history_limit", "activity.enabled", "activity.retention_days", "activity.max_entries", "ssh.host_key_checking", "ssh.target", "ssh.address_family", "completion.max_results", "multi.multiplexer", "multi.panes_per_window"} {
if err := v.BindEnv(key); err != nil { if err := v.BindEnv(key); err != nil {
return nil, err return nil, err
} }
@@ -172,6 +177,9 @@ func Load() (*Config, error) {
if err := cfg.ValidateHosts(); err != nil { if err := cfg.ValidateHosts(); err != nil {
return nil, err return nil, err
} }
if err := cfg.ValidateOperations(); err != nil {
return nil, err
}
if err := cfg.ValidateCommands(); err != nil { if err := cfg.ValidateCommands(); err != nil {
return nil, err return nil, err
} }
+34
View File
@@ -0,0 +1,34 @@
package config
import (
"fmt"
"strings"
)
type TUIConfig struct {
HistoryLimit int `mapstructure:"history_limit"`
}
type ActivityConfig struct {
Enabled bool `mapstructure:"enabled"`
RetentionDays int `mapstructure:"retention_days"`
MaxEntries int `mapstructure:"max_entries"`
}
func (c *Config) ValidateOperations() error {
if c.TUI.HistoryLimit < 0 {
return fmt.Errorf("tui.history_limit must be >= 0 (0 = all)")
}
if c.Activity.RetentionDays < 0 || c.Activity.MaxEntries < 0 {
return fmt.Errorf("activity retention_days and max_entries must be >= 0")
}
return nil
}
func (m SSHMatch) Matches(host SSHHost) bool { return m == (SSHMatch{}) || m.matches(host) }
func (c HostCommand) Allowed(host SSHHost) bool { return c.Match.Matches(host) }
func HookCommand(s string) string {
s = strings.TrimSpace(s)
if strings.EqualFold(s, "none") {
return ""
}
return s
}
+55
View File
@@ -0,0 +1,55 @@
package config
import (
"os"
"path/filepath"
"testing"
)
func TestOperationsDefaultsEnvironmentAndValidation(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
if err := os.WriteFile(filepath.Join(os.Getenv("XDG_CONFIG_HOME"), "netssh.yaml"), []byte("hosts:\n - name: router\n address: 192.0.2.1\n"), 0600); err != nil {
t.Fatal(err)
}
cfg, err := Load()
if err != nil {
t.Fatal(err)
}
if cfg.TUI.HistoryLimit != 10 || cfg.Activity.Enabled || cfg.Activity.RetentionDays != 30 || cfg.Activity.MaxEntries != 1000 {
t.Fatalf("%+v %+v", cfg.TUI, cfg.Activity)
}
t.Setenv("NETSSH_TUI_HISTORY_LIMIT", "25")
t.Setenv("NETSSH_SSH_POST_DISCONNECT", "echo done")
cfg, err = Load()
if err != nil || cfg.TUI.HistoryLimit != 25 || cfg.SSH.PostDisconnect != "echo done" {
t.Fatalf("%+v %v", cfg, err)
}
cfg.TUI.HistoryLimit = -1
if cfg.ValidateOperations() == nil {
t.Fatal("negative history accepted")
}
for _, timeout := range []string{"-1s", "0s", "invalid"} {
cfg.Commands = map[string]HostCommand{"check": {Args: []string{"echo", "{host}"}, Timeout: timeout}}
if cfg.ValidateCommands() == nil {
t.Fatalf("accepted %q", timeout)
}
}
}
func TestPostDisconnectLayering(t *testing.T) {
cfg := Config{
SSH: SSHConfig{SSHOptions: SSHOptions{PostDisconnect: "global"}, Rules: []SSHRule{{Match: SSHMatch{Tag: "lab"}, SSHOptions: SSHOptions{PostDisconnect: "none"}}}},
NetBoxes: []NetBoxConfig{{Name: "prod", SSH: SSHOptions{PostDisconnect: "instance"}}},
}
for _, tc := range []struct {
host SSHHost
want string
}{
{SSHHost{Name: "web"}, "global"},
{SSHHost{Name: "web", Instance: "prod"}, "instance"},
{SSHHost{Name: "web", Instance: "prod", Tags: []string{"lab"}}, ""},
} {
if got := HookCommand(cfg.SSHOptionsFor(tc.host).PostDisconnect); got != tc.want {
t.Fatalf("%q want %q", got, tc.want)
}
}
}
+8 -1
View File
@@ -26,7 +26,8 @@ type SSHOptions struct {
Forwards map[string]Forward `mapstructure:"forwards"` Forwards map[string]Forward `mapstructure:"forwards"`
// PreConnect is a shell command run locally before connecting; a non-zero // 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. // exit aborts the connection. "none" disables a hook set by a broader layer.
PreConnect string `mapstructure:"pre_connect"` PreConnect string `mapstructure:"pre_connect"`
PostDisconnect string `mapstructure:"post_disconnect"`
} }
// PreConnectNone disables an inherited pre_connect hook. // PreConnectNone disables an inherited pre_connect hook.
@@ -170,6 +171,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.PostDisconnect, 0) {
return fmt.Errorf("%s.post_disconnect must not contain NUL bytes", scope)
}
if strings.ContainsRune(o.PreConnect, 0) { if strings.ContainsRune(o.PreConnect, 0) {
return fmt.Errorf("%s.pre_connect must not contain NUL bytes", scope) return fmt.Errorf("%s.pre_connect must not contain NUL bytes", scope)
} }
@@ -239,6 +243,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.PostDisconnect) != "" {
out.PostDisconnect = override.PostDisconnect
}
if strings.TrimSpace(override.PreConnect) != "" { if strings.TrimSpace(override.PreConnect) != "" {
out.PreConnect = override.PreConnect out.PreConnect = override.PreConnect
} }
+12
View File
@@ -165,6 +165,15 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
// Build from the final SSH aliases, preserving per-instance prefix and // Build from the final SSH aliases, preserving per-instance prefix and
// collision handling. Never replace an existing SSH or command alias. // collision handling. Never replace an existing SSH or command alias.
hostAliases := append([]AliasEntry(nil), out...) hostAliases := append([]AliasEntry(nil), out...)
hostMetadata := map[string]config.SSHHost{}
for _, e := range entries {
instance, hostname, ok := strings.Cut(e.Name, "/")
if !ok {
hostname = instance
instance = ""
}
hostMetadata[e.Name] = config.SSHHost{Instance: instance, Name: hostname, Kind: e.Kind, Tags: e.Tags}
}
var commands []string var commands []string
for name := range cfg.Commands { for name := range cfg.Commands {
commands = append(commands, name) commands = append(commands, name)
@@ -181,6 +190,9 @@ func BuildAliasEntries(entries []cache.Entry, cfg config.Config) []AliasEntry {
if host.Host == "" { if host.Host == "" {
continue continue
} }
if !cfg.Commands[name].Allowed(hostMetadata[host.Host]) {
continue
}
alias := prefix + host.Name alias := prefix + host.Name
commandCounts[alias]++ commandCounts[alias]++
candidatesForCommands = append(candidatesForCommands, AliasEntry{Name: alias, Host: host.Host, Command: name}) candidatesForCommands = append(candidatesForCommands, AliasEntry{Name: alias, Host: host.Host, Command: name})
+7 -1
View File
@@ -1,6 +1,9 @@
package netbox package netbox
import "strings" import (
"strings"
"time"
)
// SearchOptions filters a Search or SearchAll query. // SearchOptions filters a Search or SearchAll query.
// Zero value means no filtering (return all kinds, no tag filter). // Zero value means no filtering (return all kinds, no tag filter).
@@ -13,6 +16,9 @@ type SearchOptions struct {
// HostEntry is a unified model for both devices and virtual machines from NetBox. // HostEntry is a unified model for both devices and virtual machines from NetBox.
type HostEntry struct { type HostEntry struct {
Cached bool
CachedAt time.Time
Static bool
Source string // named NetBox instance; empty for the legacy single-instance config Source string // named NetBox instance; empty for the legacy single-instance config
ID int ID int
Name string Name string
+8 -3
View File
@@ -28,19 +28,24 @@ func New(cfg config.ResolverConfig) (*Chain, error) {
} }
func (c *Chain) Resolve(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, error) { func (c *Chain) Resolve(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, error) {
address, _, err := c.ResolveWithStrategy(ctx, entry, client)
return address, err
}
func (c *Chain) ResolveWithStrategy(ctx context.Context, entry *netbox.HostEntry, client *netbox.Client) (string, string, error) {
for _, s := range c.strategies { for _, s := range c.strategies {
ip, err := s.Resolve(ctx, entry, client) ip, err := s.Resolve(ctx, entry, client)
if err == nil { if err == nil {
return ip, nil return ip, s.Name(), nil
} }
// Only "this strategy has no address" moves on. After an API failure // Only "this strategy has no address" moves on. After an API failure
// the next strategy would connect to (and cache) a different address // the next strategy would connect to (and cache) a different address
// than the configured order asks for. // than the configured order asks for.
if !errors.Is(err, ErrNoIP) { if !errors.Is(err, ErrNoIP) {
return "", fmt.Errorf("resolver strategy %q for %q: %w", s.Name(), entry.Name, err) return "", "", fmt.Errorf("resolver strategy %q for %q: %w", s.Name(), entry.Name, err)
} }
} }
return "", fmt.Errorf("no strategy resolved an IP for %q", entry.Name) return "", "", fmt.Errorf("no strategy resolved an IP for %q", entry.Name)
} }
func newStrategy(name string, cfg config.ResolverConfig) (Strategy, error) { func newStrategy(name string, cfg config.ResolverConfig) (Strategy, error) {
+146
View File
@@ -0,0 +1,146 @@
// Package runner supervises local commands while retaining terminal I/O.
package runner
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"os/signal"
"syscall"
"time"
"github.com/charmbracelet/x/term"
)
type Options struct {
Stdin io.Reader
Stdout, Stderr io.Writer
Env []string
Timeout time.Duration
Status bool
Label string
}
type Result struct {
Code int
Started bool
Duration time.Duration
}
func Run(ctx context.Context, argv []string, o Options) Result {
if o.Stderr == nil {
o.Stderr = io.Discard
}
if o.Stdout == nil {
o.Stdout = io.Discard
}
start := time.Now()
result := Result{Code: 1}
if ctx.Err() != nil {
result.Code = 130
return result
}
if len(argv) == 0 {
return result
}
cmd := exec.Command(argv[0], argv[1:]...)
cmd.Stdin, cmd.Stdout, cmd.Stderr = o.Stdin, o.Stdout, o.Stderr
cmd.Env = append(os.Environ(), o.Env...)
interactive := false
if f, ok := o.Stdin.(*os.File); ok {
interactive = term.IsTerminal(f.Fd())
}
// Interactive SSH must share the foreground terminal process group.
// Background jobs get an isolated group so cancellation reaches descendants.
cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: !interactive}
if err := cmd.Start(); err != nil {
fmt.Fprintf(o.Stderr, "%s: %v\n", argv[0], err)
return result
}
result.Started = true
done := make(chan error, 1)
go func() { done <- cmd.Wait() }()
sigs := make(chan os.Signal, 4)
signal.Notify(sigs, os.Interrupt, syscall.SIGTERM, syscall.SIGHUP, syscall.SIGQUIT)
defer signal.Stop(sigs)
var timeout <-chan time.Time
if o.Timeout > 0 {
timer := time.NewTimer(o.Timeout)
defer timer.Stop()
timeout = timer.C
}
ticker := time.NewTicker(time.Second)
defer ticker.Stop()
var killTimer *time.Timer
var kill <-chan time.Time
defer func() {
if killTimer != nil {
killTimer.Stop()
}
}()
send := func(sig syscall.Signal) {
if interactive {
_ = cmd.Process.Signal(sig)
} else {
_ = syscall.Kill(-cmd.Process.Pid, sig)
}
}
forced := 0
cancelCh := ctx.Done()
stop := func(code int, sig syscall.Signal) {
if forced != 0 {
return
}
forced = code
send(sig)
killTimer = time.NewTimer(2 * time.Second)
kill = killTimer.C
}
for {
select {
case err := <-done:
result.Duration = time.Since(start)
result.Code = 0
if err != nil {
result.Code = 1
if e, ok := err.(*exec.ExitError); ok {
result.Code = e.ExitCode()
if s, ok := e.Sys().(syscall.WaitStatus); ok && s.Signaled() {
result.Code = 128 + int(s.Signal())
}
}
}
if forced != 0 {
result.Code = forced
}
// Kill descendants left behind after cancellation even if the parent exited.
if forced != 0 && !interactive {
send(syscall.SIGKILL)
}
if o.Status {
fmt.Fprintf(o.Stderr, "[%s] finished in %s (exit %d)\n", o.Label, result.Duration.Round(time.Millisecond), result.Code)
}
return result
case sig := <-sigs:
s := sig.(syscall.Signal)
if interactive && (s == syscall.SIGINT || s == syscall.SIGQUIT) {
continue
} // terminal delivered it to child too
stop(128+int(s), s)
case <-cancelCh:
cancelCh = nil
stop(130, syscall.SIGTERM)
case <-timeout:
timeout = nil
stop(124, syscall.SIGTERM)
case <-kill:
kill = nil
send(syscall.SIGKILL)
case <-ticker.C:
if o.Status {
fmt.Fprintf(o.Stderr, "[%s] running %s (Ctrl+C cancels)\n", o.Label, time.Since(start).Round(time.Second))
}
}
}
}
+43
View File
@@ -0,0 +1,43 @@
package runner
import (
"bytes"
"context"
"io"
"strings"
"testing"
"time"
)
func TestExitAndTimeout(t *testing.T) {
var out bytes.Buffer
r := Run(context.Background(), []string{"sh", "-c", "printf result; exit 7"}, Options{Stdout: &out, Stderr: io.Discard})
if !r.Started || r.Code != 7 || out.String() != "result" {
t.Fatalf("%+v %q", r, out.String())
}
start := time.Now()
r = Run(context.Background(), []string{"sh", "-c", "trap '' TERM; sleep 30 & wait"}, Options{Stdout: io.Discard, Stderr: io.Discard, Timeout: 50 * time.Millisecond})
if r.Code != 124 || time.Since(start) > 4*time.Second {
t.Fatalf("timeout: %+v", r)
}
}
func TestCancellationAndNoStart(t *testing.T) {
ctx, cancel := context.WithCancel(context.Background())
cancel()
r := Run(ctx, []string{"sh", "-c", "exit 0"}, Options{Stderr: io.Discard})
if r.Started || r.Code != 130 {
t.Fatalf("%+v", r)
}
var errOut bytes.Buffer
r = Run(context.Background(), []string{"/no/such/netssh-test-executable"}, Options{Stderr: &errOut})
if r.Started || r.Code == 0 || !strings.Contains(errOut.String(), "no such") {
t.Fatalf("%+v %s", r, errOut.String())
}
ctx, cancel = context.WithCancel(context.Background())
defer cancel()
time.AfterFunc(50*time.Millisecond, cancel)
r = Run(ctx, []string{"sh", "-c", "sleep 30"}, Options{Stdout: io.Discard, Stderr: io.Discard})
if r.Code != 130 {
t.Fatalf("%+v", r)
}
}
+7
View File
@@ -64,6 +64,13 @@ func editCommands(cfg *config.Config) error {
huh.NewInput().Title("Alias prefix").Description("m + host shortcut xg1 = mxg1. Empty disables automatic aliases.").Value(&command.AliasPrefix), huh.NewInput().Title("Alias prefix").Description("m + host shortcut xg1 = mxg1. Empty disables automatic aliases.").Value(&command.AliasPrefix),
huh.NewInput().Title("Program or executable script").Description("Use an absolute script path, or bash/python3 with the script path as the first argument.").Placeholder("mtr or /home/user/bin/check-host").Value(&binary), huh.NewInput().Title("Program or executable script").Description("Use an absolute script path, or bash/python3 with the script path as the first argument.").Placeholder("mtr or /home/user/bin/check-host").Value(&binary),
huh.NewText().Title("Arguments, one per line").Description("Use {address} for the resolved address, {host} for the hostname, {target} for instance/hostname. No shell quoting needed.").Lines(5).Value(&arguments), huh.NewText().Title("Arguments, one per line").Description("Use {address} for the resolved address, {host} for the hostname, {target} for instance/hostname. No shell quoting needed.").Lines(5).Value(&arguments),
huh.NewConfirm().Title("Confirm before running?").Value(&command.Confirm),
huh.NewInput().Title("Timeout").Description("Optional positive duration, e.g. 30s or 5m.").Value(&command.Timeout),
huh.NewInput().Title("Post-run script").Description("Local command after completion; receives NETSSH_EXIT_CODE.").Value(&command.PostRun),
huh.NewInput().Title("Only for tag").Value(&command.Match.Tag),
huh.NewInput().Title("Only for instance").Value(&command.Match.Instance),
huh.NewInput().Title("Only for kind").Description("device, vm or static; empty means all.").Value(&command.Match.Kind),
huh.NewInput().Title("Only for hostname pattern").Description("For example router*; all specified filters must match.").Value(&command.Match.Name),
).Title("Local command")).Run() ).Title("Local command")).Run()
if err != nil { if err != nil {
return err return err
+35
View File
@@ -0,0 +1,35 @@
package setup
import (
"fmt"
"strconv"
"charm.land/huh/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config"
)
func editOperations(cfg *config.Config) error {
history, days, entries := strconv.Itoa(cfg.TUI.HistoryLimit), strconv.Itoa(cfg.Activity.RetentionDays), strconv.Itoa(cfg.Activity.MaxEntries)
enabled := cfg.Activity.Enabled
valid := func(s string) error {
n, err := strconv.Atoi(s)
if err != nil || n < 0 {
return fmt.Errorf("enter a non-negative number")
}
return nil
}
err := huh.NewForm(huh.NewGroup(
huh.NewInput().Title("Recent hosts shown").Description("10 by default; 0 shows all. Favorites are additional.").Value(&history).Validate(valid),
huh.NewConfirm().Title("Record local action history?").Description("Stores host, command name, duration and exit code; no arguments or output.").Value(&enabled),
huh.NewInput().Title("Retention in days").Description("0 = no age limit").Value(&days).Validate(valid),
huh.NewInput().Title("Maximum recorded actions").Description("0 = no count limit").Value(&entries).Validate(valid),
).Title("History & activity")).Run()
if err != nil {
return err
}
cfg.TUI.HistoryLimit, _ = strconv.Atoi(history)
cfg.Activity.RetentionDays, _ = strconv.Atoi(days)
cfg.Activity.MaxEntries, _ = strconv.Atoi(entries)
cfg.Activity.Enabled = enabled
return nil
}
+3
View File
@@ -24,6 +24,7 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
options := formatOptions(o.Options) options := formatOptions(o.Options)
forwards := formatForwards(o.Forwards) forwards := formatForwards(o.Forwards)
preConnect := o.PreConnect preConnect := o.PreConnect
postDisconnect := o.PostDisconnect
err := huh.NewForm(huh.NewGroup( err := huh.NewForm(huh.NewGroup(
huh.NewInput(). huh.NewInput().
@@ -70,6 +71,7 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
_, err := parseForwards(s) _, err := parseForwards(s)
return err return err
}), }),
huh.NewInput().Title("Post-disconnect script").Description("Local command after the client exits; none disables inheritance.").Value(&postDisconnect),
huh.NewInput(). huh.NewInput().
Title("Pre-connect hook"). Title("Pre-connect hook").
Description("Shell command run locally before connecting, e.g. vpn-check.sh \"$NETSSH_HOST\".\n"+ Description("Shell command run locally before connecting, e.g. vpn-check.sh \"$NETSSH_HOST\".\n"+
@@ -94,6 +96,7 @@ func editSSHOptions(title string, o config.SSHOptions) (config.SSHOptions, error
ExtraArgs: parseLines(extraArgs), ExtraArgs: parseLines(extraArgs),
Options: parsed, Options: parsed,
PreConnect: strings.TrimSpace(preConnect), PreConnect: strings.TrimSpace(preConnect),
PostDisconnect: strings.TrimSpace(postDisconnect),
}, nil }, nil
} }
+18 -2
View File
@@ -95,6 +95,7 @@ func runMenu(cfg *config.Config) error {
huh.NewOption("Resolver & cache", "resolver"), huh.NewOption("Resolver & cache", "resolver"),
huh.NewOption("Shortcuts & command alias", "shortcuts"), huh.NewOption("Shortcuts & command alias", "shortcuts"),
huh.NewOption("Custom commands — mtr, ping, scripts", "commands"), huh.NewOption("Custom commands — mtr, ping, scripts", "commands"),
huh.NewOption("History & activity logging", "operations"),
huh.NewOption("Completion", "completion"), huh.NewOption("Completion", "completion"),
huh.NewOption("Save and exit", "save"), huh.NewOption("Save and exit", "save"),
). ).
@@ -125,6 +126,8 @@ func runMenu(cfg *config.Config) error {
err = editShortcuts(cfg) err = editShortcuts(cfg)
case "commands": case "commands":
err = editCommands(cfg) err = editCommands(cfg)
case "operations":
err = editOperations(cfg)
case "completion": case "completion":
err = editCompletion(cfg) err = editCompletion(cfg)
case "save": case "save":
@@ -382,6 +385,9 @@ func save(cfg config.Config) error {
if err := cfg.ValidateHosts(); err != nil { if err := cfg.ValidateHosts(); err != nil {
return err return err
} }
if err := cfg.ValidateOperations(); err != nil {
return err
}
if err := cfg.ValidateCommands(); err != nil { if err := cfg.ValidateCommands(); err != nil {
return err return err
} }
@@ -552,9 +558,19 @@ func save(cfg config.Config) error {
for _, arg := range command.Args { for _, arg := range command.Args {
fmt.Fprintf(&b, " - %q\n", arg) fmt.Fprintf(&b, " - %q\n", arg)
} }
fmt.Fprintf(&b, " confirm: %t\n timeout: %q\n post_run: %q\n", command.Confirm, command.Timeout, command.PostRun)
if command.Match != (config.SSHMatch{}) {
b.WriteString(" match:\n")
for _, pair := range [][2]string{{"tag", command.Match.Tag}, {"instance", command.Match.Instance}, {"kind", command.Match.Kind}, {"name", command.Match.Name}} {
if pair[1] != "" {
fmt.Fprintf(&b, " %s: %q\n", pair[0], pair[1])
}
}
}
} }
} }
fmt.Fprintf(&b, "\ntui:\n history_limit: %d\nactivity:\n enabled: %t\n retention_days: %d\n max_entries: %d\n", cfg.TUI.HistoryLimit, cfg.Activity.Enabled, cfg.Activity.RetentionDays, cfg.Activity.MaxEntries)
if cfg.Shell.Alias != "" { if cfg.Shell.Alias != "" {
fmt.Fprintf(&b, "\nshell:\n alias: %q\n", cfg.Shell.Alias) fmt.Fprintf(&b, "\nshell:\n alias: %q\n", cfg.Shell.Alias)
} }
@@ -568,12 +584,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 && o.PreConnect == "" return o.ProxyJump == "" && o.HostKeyChecking == "" && o.Target == "" && o.AddressFamily == "" && len(o.ExtraArgs) == 0 && len(o.Options) == 0 && len(o.Forwards) == 0 && o.PreConnect == "" && o.PostDisconnect == ""
} }
// writeSSHOptions keeps settings the wizard does not ask for when it rewrites the config. // writeSSHOptions keeps settings the wizard does not ask for when it rewrites the config.
func writeSSHOptions(b *strings.Builder, indent string, o config.SSHOptions) { func writeSSHOptions(b *strings.Builder, indent string, o config.SSHOptions) {
for _, field := range [][2]string{{"proxy_jump", o.ProxyJump}, {"host_key_checking", o.HostKeyChecking}, {"target", o.Target}, {"address_family", o.AddressFamily}, {"pre_connect", o.PreConnect}} { for _, field := range [][2]string{{"proxy_jump", o.ProxyJump}, {"host_key_checking", o.HostKeyChecking}, {"target", o.Target}, {"address_family", o.AddressFamily}, {"pre_connect", o.PreConnect}, {"post_disconnect", o.PostDisconnect}} {
if field[1] != "" { if field[1] != "" {
fmt.Fprintf(b, "%s%s: %q\n", indent, field[0], field[1]) fmt.Fprintf(b, "%s%s: %q\n", indent, field[0], field[1])
} }
+21
View File
@@ -698,3 +698,24 @@ func TestSaveCommandsRoundTrip(t *testing.T) {
t.Fatalf("commands lost: %+v", got.Commands) t.Fatalf("commands lost: %+v", got.Commands)
} }
} }
func TestOperationsRoundTrip(t *testing.T) {
t.Setenv("XDG_CONFIG_HOME", t.TempDir())
cfg := config.Config{
NetBox: config.NetBoxConfig{URL: "https://netbox.example", Token: "token"},
TUI: config.TUIConfig{HistoryLimit: 25},
Activity: config.ActivityConfig{Enabled: true, RetentionDays: 7, MaxEntries: 50},
SSH: config.SSHConfig{SSHOptions: config.SSHOptions{PostDisconnect: "echo done"}, Rules: []config.SSHRule{{Match: config.SSHMatch{Tag: "lab"}, SSHOptions: config.SSHOptions{PostDisconnect: "none"}}}},
Commands: map[string]config.HostCommand{"mtr": {Args: []string{"mtr", "{address}"}, AliasPrefix: "m", Timeout: "10s", Confirm: true, PostRun: "echo done", Match: config.SSHMatch{Tag: "router", Instance: "prod"}}},
}
if err := save(cfg); err != nil {
t.Fatal(err)
}
got, err := config.Load()
if err != nil {
t.Fatal(err)
}
if got.TUI != cfg.TUI || got.Activity != cfg.Activity || !reflect.DeepEqual(got.Commands, cfg.Commands) || !reflect.DeepEqual(got.SSH, cfg.SSH) {
t.Fatalf("round trip lost operations: %+v", got)
}
}
+188 -14
View File
@@ -22,6 +22,7 @@ import (
// SelectedHost is returned when the user confirms a host in the TUI. // SelectedHost is returned when the user confirms a host in the TUI.
type SelectedHost struct { type SelectedHost struct {
Command string
Kind string Kind string
Name string Name string
IP string IP string
@@ -63,13 +64,15 @@ type searchResultMsg struct {
// --- list item --- // --- list item ---
type hostItem struct { type hostItem struct {
label string // display only; name remains the canonical target provenance string
alias string // shortcut alias shown next to the name (shortcuts.show) favorite, pinned bool
name string label string // display only; name remains the canonical target
id int alias string // shortcut alias shown next to the name (shortcuts.show)
ip string name string
kind string id int
tags []string ip string
kind string
tags []string
} }
func (h hostItem) Title() string { func (h hostItem) Title() string {
@@ -102,7 +105,16 @@ func (d compactDelegate) Render(w io.Writer, m list.Model, index int, item list.
if h.alias != "" { if h.alias != "" {
title += " " + lipgloss.NewStyle().Foreground(lipgloss.Color("109")).Render("→ "+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)) badge := ""
if h.pinned {
badge = "◆ "
} else if h.favorite {
badge = "★ "
}
line := fmt.Sprintf(" %s%s %s", mark+badge, title, lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(h.ip))
if h.provenance != "" {
line += " [" + h.provenance + "]"
}
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, " "))
} }
@@ -161,6 +173,14 @@ func applyFilter(entries []netbox.HostEntry, f filterOpts) []netbox.HostEntry {
// --- Model --- // --- Model ---
type Model struct { type Model struct {
historyLimit int
favorites, pinned map[string]bool
savePreferences func(map[string]bool, map[string]bool) error
commandsFor func(string, string, []string) []string
actionHost *hostItem
actionNames []string
actionIndex int
noteErr error noteErr error
editHost *hostItem editHost *hostItem
noteInput textarea.Model noteInput textarea.Model
@@ -229,6 +249,7 @@ func New(client *netbox.Client, c *cache.Cache, defaultUser string, defaultPorts
ni.CharLimit = 0 ni.CharLimit = 0
ni.SetHeight(10) ni.SetHeight(10)
return &Model{ return &Model{
historyLimit: 10, favorites: map[string]bool{}, pinned: map[string]bool{},
noteInput: ni, noteInput: ni,
defaultPort: port, defaultPort: port,
input: ti, input: ti,
@@ -250,14 +271,40 @@ func (m *Model) Init() tea.Cmd {
// loadRecent returns a Cmd that immediately resolves to the recently-used host list. // loadRecent returns a Cmd that immediately resolves to the recently-used host list.
func (m *Model) loadRecent() tea.Cmd { func (m *Model) loadRecent() tea.Cmd {
favoriteNames, pinned, limit := copyBools(m.favorites), copyBools(m.pinned), m.historyLimit
return func() tea.Msg { return func() tea.Msg {
if m.cache == nil { if m.cache == nil {
return searchResultMsg{query: "", entries: nil, recent: true} return searchResultMsg{query: "", entries: nil, recent: true}
} }
recent := m.cache.RecentlyUsed(10) recent := m.cache.RecentlyUsed(limit)
seen := map[string]bool{}
var favorites []cache.Entry
for name, enabled := range favoriteNames {
if !enabled {
continue
}
e, _ := m.cache.Get(name)
if e.Name == "" {
e.Name = name
}
favorites = append(favorites, e)
seen[name] = true
}
sort.Slice(favorites, func(i, j int) bool {
if pinned[favorites[i].Name] != pinned[favorites[j].Name] {
return pinned[favorites[i].Name]
}
return favorites[i].Name < favorites[j].Name
})
for _, e := range recent {
if !seen[e.Name] {
favorites = append(favorites, e)
}
}
recent = favorites
entries := make([]netbox.HostEntry, len(recent)) entries := make([]netbox.HostEntry, len(recent))
for i, e := range recent { for i, e := range recent {
entries[i] = netbox.HostEntry{Name: e.Name, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags} entries[i] = netbox.HostEntry{Name: e.Name, PrimaryIP4: e.IP, Kind: e.Kind, Tags: e.Tags, Cached: true, CachedAt: e.CachedAt, Static: e.Static}
} }
return searchResultMsg{query: "", entries: entries, recent: true} return searchResultMsg{query: "", entries: entries, recent: true}
} }
@@ -294,6 +341,34 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
if msg.String() == "ctrl+c" { if msg.String() == "ctrl+c" {
return m, tea.Quit return m, tea.Quit
} }
if m.actionHost != nil {
switch msg.String() {
case "esc":
m.actionHost = nil
case "up":
if m.actionIndex > 0 {
m.actionIndex--
}
case "down":
if m.actionIndex+1 < len(m.actionNames) {
m.actionIndex++
}
case "enter":
h := m.actionHost
if m.actionIndex == 0 {
if len(m.markOrder) > 0 {
m.selected = &SelectedHost{Action: ActionMulti, Targets: append([]string(nil), m.markOrder...)}
} else {
m.selected = &SelectedHost{Name: h.name, Kind: h.kind, IP: h.ip}
}
} else {
m.selected = &SelectedHost{Name: h.name, Kind: h.kind, IP: h.ip, Command: m.actionNames[m.actionIndex], Targets: append([]string(nil), m.markOrder...)}
}
return m, tea.Quit
}
return m, nil
}
if m.noteMode { if m.noteMode {
if m.noteBusy { if m.noteBusy {
return m, nil return m, nil
@@ -403,6 +478,43 @@ func (m *Model) Update(msg tea.Msg) (tea.Model, tea.Cmd) {
case "ctrl+c", "esc": case "ctrl+c", "esc":
return m, tea.Quit return m, tea.Quit
case "ctrl+r":
if h, ok := m.list.SelectedItem().(hostItem); ok {
m.actionHost = &h
m.actionIndex = 0
m.actionNames = []string{"SSH"}
if m.commandsFor != nil {
m.actionNames = append(m.actionNames, m.commandsFor(h.name, h.kind, h.tags)...)
}
}
return m, nil
case "ctrl+d", "ctrl+p":
if h, ok := m.list.SelectedItem().(hostItem); ok {
favorites, pinned := copyBools(m.favorites), copyBools(m.pinned)
if msg.String() == "ctrl+p" {
pinned[h.name] = !pinned[h.name]
if pinned[h.name] {
favorites[h.name] = true
}
} else {
favorites[h.name] = !favorites[h.name]
if !favorites[h.name] {
delete(pinned, h.name)
}
}
if m.savePreferences != nil {
if err := m.savePreferences(favorites, pinned); err != nil {
m.err = err
return m, nil
}
}
m.favorites, m.pinned = favorites, pinned
m.updateListItems(m.lastResults)
if m.recentMode && m.input.Value() == "" {
return m, m.loadRecent()
}
}
return m, nil
case "ctrl+f": case "ctrl+f":
m.filterOpen = true m.filterOpen = true
m.input.Blur() m.input.Blur()
@@ -563,6 +675,24 @@ func (m *Model) View() tea.View {
} }
func (m *Model) viewContent() string { func (m *Model) viewContent() string {
if m.actionHost != nil {
var out strings.Builder
fmt.Fprintf(&out, "Action for %s", m.actionHost.Title())
if len(m.markOrder) > 0 {
fmt.Fprintf(&out, " (%d marked hosts)", len(m.markOrder))
}
out.WriteString("\n\n")
for i, n := range m.actionNames {
marker := " "
if i == m.actionIndex {
marker = "> "
}
fmt.Fprintf(&out, "%s%s\n", marker, n)
}
out.WriteString("\n↑/↓ select enter run esc cancel\n")
return out.String()
}
if m.noteMode { if m.noteMode {
target := "local" target := "local"
if m.noteRemote { if m.noteRemote {
@@ -623,7 +753,7 @@ func (m *Model) viewContent() string {
sb.WriteString(m.editInput.View() + "\n") sb.WriteString(m.editInput.View() + "\n")
sb.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(" enter connect esc cancel") + "\n") sb.WriteString(lipgloss.NewStyle().Foreground(lipgloss.Color("240")).Render(" enter connect esc cancel") + "\n")
} else { } else {
hint := "ctrl+c quit enter connect space mark ctrl+o sftp ctrl+t forward ctrl+e edit ctrl+f filter ctrl+n notes ctrl+b NetBox" hint := "ctrl+r actions ctrl+d favorite ctrl+p pin ctrl+c quit enter connect space mark ctrl+o sftp ctrl+t forward ctrl+e edit ctrl+f filter ctrl+n notes ctrl+b NetBox"
if n := len(m.markOrder); n > 0 { if n := len(m.markOrder); n > 0 {
hint = fmt.Sprintf("%d marked — enter open side by side space unmark ctrl+a all esc quit", n) hint = fmt.Sprintf("%d marked — enter open side by side space unmark ctrl+a all esc quit", n)
} }
@@ -652,7 +782,7 @@ func (m *Model) doSearch(query string, seq int) tea.Cmd {
if m.cache != nil { if m.cache != nil {
for _, entry := range m.cache.Search(query) { for _, entry := range m.cache.Search(query) {
source, name := netbox.SplitTarget(entry.Name) source, name := netbox.SplitTarget(entry.Name)
cached = append(cached, netbox.HostEntry{Source: source, Name: name, PrimaryIP4: entry.IP, Kind: entry.Kind, Tags: entry.Tags}) cached = append(cached, netbox.HostEntry{Source: source, Name: name, PrimaryIP4: entry.IP, Kind: entry.Kind, Tags: entry.Tags, Cached: true, CachedAt: entry.CachedAt, Static: entry.Static})
} }
} }
if m.client == nil || (len(cached) > 0 && !m.client.MultipleSources()) { if m.client == nil || (len(cached) > 0 && !m.client.MultipleSources()) {
@@ -689,7 +819,19 @@ func (m *Model) netboxSearchOpts() netbox.SearchOptions {
// updateListItems applies the active filter and sets the list items. // updateListItems applies the active filter and sets the list items.
func (m *Model) updateListItems(entries []netbox.HostEntry) { func (m *Model) updateListItems(entries []netbox.HostEntry) {
f := parseFilter(m.filterInput.Value()) f := parseFilter(m.filterInput.Value())
filtered := applyFilter(entries, f) filtered := append([]netbox.HostEntry(nil), applyFilter(entries, f)...)
sort.SliceStable(filtered, func(i, j int) bool {
rank := func(e netbox.HostEntry) int {
if m.pinned[e.Target()] {
return 2
}
if m.favorites[e.Target()] {
return 1
}
return 0
}
return rank(filtered[i]) > rank(filtered[j])
})
items := make([]list.Item, len(filtered)) items := make([]list.Item, len(filtered))
labels := make([]string, len(filtered)) labels := make([]string, len(filtered))
counts := make(map[string]int, len(filtered)) counts := make(map[string]int, len(filtered))
@@ -718,7 +860,23 @@ func (m *Model) updateListItems(entries []netbox.HostEntry) {
alias = "" alias = ""
} }
} }
items[i] = hostItem{label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags} provenance := "live"
if e.Static {
provenance = "static"
} else if e.Cached {
if e.CachedAt.IsZero() {
provenance = "saved host; resolve on connect"
} else {
age := max(time.Duration(0), time.Since(e.CachedAt)).Round(time.Second)
provenance = "cache " + age.String()
if m.cache != nil {
if _, fresh := m.cache.Get(e.Target()); !fresh {
provenance += ", stale"
}
}
}
}
items[i] = hostItem{provenance: provenance, favorite: m.favorites[e.Target()], pinned: m.pinned[e.Target()], label: label, alias: alias, id: e.ID, name: e.Target(), ip: ip, kind: e.Kind, tags: e.Tags}
} }
m.list.SetItems(items) m.list.SetItems(items)
m.resizeList() m.resizeList()
@@ -866,3 +1024,19 @@ func (m *Model) SetHostLabel(format func(string) string) {
func (m *Model) SetAliases(aliasFor func(target string) string) { func (m *Model) SetAliases(aliasFor func(target string) string) {
m.aliasFor = aliasFor m.aliasFor = aliasFor
} }
func copyBools(in map[string]bool) map[string]bool {
out := map[string]bool{}
for k, v := range in {
out[k] = v
}
return out
}
func (m *Model) SetHistoryLimit(limit int) { m.historyLimit = limit }
func (m *Model) SetPreferences(favorites, pinned map[string]bool, save func(map[string]bool, map[string]bool) error) {
m.favorites, m.pinned = copyBools(favorites), copyBools(pinned)
m.savePreferences = save
}
func (m *Model) SetCommands(commands func(string, string, []string) []string) {
m.commandsFor = commands
}
+67
View File
@@ -0,0 +1,67 @@
package tui
import (
"strings"
"testing"
"time"
tea "charm.land/bubbletea/v2"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/cache"
"git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox"
)
func TestFavoritesHistoryAndActions(t *testing.T) {
c := cache.New("", 3600)
for _, name := range []string{"a", "b", "pinned"} {
c.Upsert(cache.Entry{Name: name, IP: "10.0.0.1", Kind: "device"})
c.MarkUsed(name)
}
m := New(nil, c, "")
m.SetHistoryLimit(1)
m.SetPreferences(map[string]bool{"pinned": true, "offline/missing": true}, map[string]bool{"pinned": true}, nil)
msg := m.loadRecent()().(searchResultMsg)
if len(msg.entries) < 2 || msg.entries[0].Target() != "pinned" {
t.Fatalf("%+v", msg.entries)
}
m.Update(msg)
m.Update(tea.WindowSizeMsg{Width: 160, Height: 30})
if !strings.Contains(m.View().Content, "◆") || !strings.Contains(m.View().Content, "cache") {
t.Fatal(m.View().Content)
}
m.SetCommands(func(name, kind string, tags []string) []string { return []string{"mtr"} })
m.Update(tea.KeyPressMsg{Code: 'r', Mod: tea.ModCtrl})
m.Update(tea.KeyPressMsg{Code: tea.KeyDown})
m.Update(tea.KeyPressMsg{Code: tea.KeyEnter})
if m.Selected() == nil || m.Selected().Command != "mtr" || m.Selected().Name != "pinned" {
t.Fatalf("%+v", m.Selected())
}
}
func TestHistoryLimitAndPreferencePersistence(t *testing.T) {
c := cache.New("", 3600)
for _, n := range []string{"a", "b", "c"} {
c.Upsert(cache.Entry{Name: n})
c.MarkUsed(n)
}
m := New(nil, c, "")
m.SetHistoryLimit(2)
if got := len(m.loadRecent()().(searchResultMsg).entries); got != 2 {
t.Fatal(got)
}
m.SetHistoryLimit(0)
if got := len(m.loadRecent()().(searchResultMsg).entries); got != 3 {
t.Fatal(got)
}
saved := false
m.SetPreferences(nil, nil, func(f, p map[string]bool) error { saved = f["prod/web"] && p["prod/web"]; return nil })
entries := []netbox.HostEntry{{Name: "web", Source: "prod", Cached: true, CachedAt: time.Now().Add(-2 * time.Hour)}}
m.lastResults = entries
m.updateListItems(entries)
m.Update(tea.KeyPressMsg{Code: 'p', Mod: tea.ModCtrl})
if !saved {
t.Fatal("pin not persisted")
}
item := m.list.Items()[0].(hostItem)
if !strings.Contains(item.provenance, "stale") {
t.Fatal(item.provenance)
}
}