package main import ( "bufio" "errors" "fmt" "io" "os" "strings" "sync" "text/tabwriter" "github.com/charmbracelet/x/term" "github.com/spf13/cobra" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/config" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/netbox" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/secret" "git.zb-server.de/Sebi/ssh-netbox-wrapper/internal/setup" ) var ( tokenMu sync.Mutex tokenCache = map[string]string{} ) // resolveToken returns the API token of an instance: the configured value, // or the keyring entry when the value is "keyring". Lookups are cached per // process, since each one can be a D-Bus round trip. func resolveToken(n config.NetBoxConfig) (string, error) { if !config.IsKeyringToken(n.Token) { return n.Token, nil } account := n.KeyringAccount() tokenMu.Lock() defer tokenMu.Unlock() if token, ok := tokenCache[account]; ok { return token, nil } token, err := secret.Get(account) if err != nil { return "", err } tokenCache[account] = token return token, nil } // clientToken resolves a token for a client; a failure is reported once and // leaves the token empty, so NetBox answers with a clear authentication error. func clientToken(n config.NetBoxConfig) (string, int) { token, err := resolveToken(n) if err != nil { label := n.Name if label == "" { label = "netbox" } fmt.Fprintf(os.Stderr, "netssh: %s: %v\n", label, err) return "", n.TokenVersion } version := n.TokenVersion if config.IsKeyringToken(n.Token) { version = netbox.TokenVersion(token) } return token, version } // instanceConfigs returns the configured NetBox instances, including the // legacy unnamed one. func instanceConfigs(cfg *config.Config) []*config.NetBoxConfig { var out []*config.NetBoxConfig for i := range cfg.NetBoxes { out = append(out, &cfg.NetBoxes[i]) } if len(out) == 0 && cfg.NetBox.URL != "" { out = append(out, &cfg.NetBox) } return out } // selectInstance finds the instance named in args, or the only one. func selectInstance(cfg *config.Config, args []string) (*config.NetBoxConfig, error) { instances := instanceConfigs(cfg) if len(instances) == 0 { return nil, errors.New("no NetBox is configured (netssh configure)") } if len(args) == 0 { if len(instances) == 1 { return instances[0], nil } return nil, fmt.Errorf("name the NetBox instance: %s", strings.Join(instanceNames(cfg), ", ")) } for _, instance := range instances { if strings.EqualFold(instance.Name, args[0]) || (instance.Name == "" && strings.EqualFold(args[0], "default")) { return instance, nil } } return nil, fmt.Errorf("unknown NetBox instance %q", args[0]) } // readToken reads a token without echo from a terminal, or a line from stdin. func readToken(label string, stdin io.Reader) (string, error) { if f, ok := stdin.(*os.File); ok && term.IsTerminal(f.Fd()) { fmt.Fprintf(os.Stderr, "NetBox API token for %s: ", label) data, err := term.ReadPassword(f.Fd()) fmt.Fprintln(os.Stderr) if err != nil { return "", err } return strings.TrimSpace(string(data)), nil } line, err := bufio.NewReader(stdin).ReadString('\n') if err != nil && err != io.EOF { return "", err } return strings.TrimSpace(line), nil } // saveConfig is replaced in tests. var saveConfig = setup.Save func tokenCmd() *cobra.Command { cmd := &cobra.Command{ Use: "token", Short: "Keep NetBox API tokens in the system keyring", Long: `Store NetBox API tokens in the system keyring (Secret Service / GNOME Keyring / KWallet on Linux, Keychain on macOS) instead of the config file. The config then contains token: keyring, and netssh reads the token from the keyring. NETSSH_NETBOX_TOKEN still overrides the token of the unnamed instance.`, } cmd.AddCommand(tokenSetCmd(), tokenMigrateCmd(), tokenDeleteCmd(), tokenStatusCmd()) return cmd } func tokenSetCmd() *cobra.Command { return &cobra.Command{ Use: "set [INSTANCE]", Short: "Store a token in the keyring and switch the config to token: keyring", Long: "Read the token without echo (or from stdin) and store it in the keyring.\nExample for scripts: echo \"$TOKEN\" | netssh token set prod", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { cfg, err := config.Load() if err != nil { return err } instance, err := selectInstance(cfg, args) if err != nil { return err } token, err := readToken(instance.KeyringAccount(), cmd.InOrStdin()) if err != nil { return err } if token == "" || config.IsKeyringToken(token) { return errors.New("no token given") } if err := secret.Set(instance.KeyringAccount(), token); err != nil { return err } instance.Token, instance.TokenVersion = config.KeyringToken, netbox.TokenVersion(token) if err := saveConfig(*cfg); err != nil { return err } fmt.Fprintf(cmd.OutOrStdout(), "Token for %s stored in the system keyring.\n", instance.KeyringAccount()) return nil }, } } func tokenMigrateCmd() *cobra.Command { return &cobra.Command{ Use: "migrate", Short: "Move all tokens from the config file into the keyring", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { cfg, err := config.Load() if err != nil { return err } moved := 0 for _, instance := range instanceConfigs(cfg) { if instance.Token == "" || config.IsKeyringToken(instance.Token) { continue } if err := secret.Set(instance.KeyringAccount(), instance.Token); err != nil { return err } instance.TokenVersion = netbox.TokenVersion(instance.Token) instance.Token = config.KeyringToken moved++ fmt.Fprintf(cmd.OutOrStdout(), "%s: moved to the keyring\n", instance.KeyringAccount()) } if moved == 0 { fmt.Fprintln(cmd.OutOrStdout(), "No tokens in the config file.") return nil } return saveConfig(*cfg) }, } } func tokenDeleteCmd() *cobra.Command { return &cobra.Command{ Use: "delete [INSTANCE]", Short: "Remove a token from the keyring", Args: cobra.MaximumNArgs(1), RunE: func(cmd *cobra.Command, args []string) error { cfg, err := config.Load() if err != nil { return err } instance, err := selectInstance(cfg, args) if err != nil { return err } if err := secret.Delete(instance.KeyringAccount()); err != nil { return err } fmt.Fprintf(cmd.OutOrStdout(), "Token for %s removed from the keyring.\n", instance.KeyringAccount()) if config.IsKeyringToken(instance.Token) { fmt.Fprintln(cmd.OutOrStdout(), "The config still says token: keyring; store a new one with netssh token set.") } return nil }, } } func tokenStatusCmd() *cobra.Command { return &cobra.Command{ Use: "status", Short: "Show where each instance's token comes from", Args: cobra.NoArgs, RunE: func(cmd *cobra.Command, args []string) error { cfg, err := config.Load() if err != nil { return err } w := tabwriter.NewWriter(cmd.OutOrStdout(), 0, 0, 2, ' ', 0) fmt.Fprintln(w, "INSTANCE\tTOKEN") for _, instance := range instanceConfigs(cfg) { fmt.Fprintf(w, "%s\t%s\n", instance.KeyringAccount(), tokenSource(*instance)) } return w.Flush() }, } } func tokenSource(n config.NetBoxConfig) string { switch { case n.Token == "": return "missing" case config.IsKeyringToken(n.Token): if _, err := resolveToken(n); err != nil { return "keyring (not readable: " + err.Error() + ")" } return "keyring" default: return "config file (plain text; move it with netssh token migrate)" } }