Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding timeout vault option and better error handling #5

Merged
merged 3 commits into from
Mar 27, 2019
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 18 additions & 7 deletions pkg/vault/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import (
"syscall"
)

// This is the main Login function
// Login gets a Vault token if there isn't one
func (v *Vault) Login() error {
v.tokenHelper = token.InternalTokenHelper{}

Expand Down Expand Up @@ -48,7 +48,7 @@ func (v *Vault) Login() error {
v.Debug("Got permission denied. Trying to login.")
loginToVault = true
} else {
return err
return v.parseError(err)
}
}
defer resp.Body.Close()
Expand All @@ -61,6 +61,17 @@ func (v *Vault) Login() error {
return nil
}

// GetToken returns the raw token
func (v *Vault) GetToken() (string, error) {
v.tokenHelper = token.InternalTokenHelper{}
token, err := v.tokenHelper.Get()
if err != nil {
return "", v.parseError(err)
}

return token, nil
}

func (v *Vault) isCurrentTokenValid() {

}
Expand Down Expand Up @@ -93,20 +104,20 @@ func (v *Vault) userLogin() error {
})
if err != nil {
v.Debug("Do you have a bad username or password?")
return err
return v.parseError(err)
}
v.client.SetToken(secret.Auth.ClientToken)

// Write token to user's dot file
err = v.tokenHelper.Store(secret.Auth.ClientToken)
if err != nil {
return err
return v.parseError(err)
}

// Lookup the token to get the entity ID
secret, err = v.client.Auth().Token().Lookup(v.client.Token())
if err != nil {
return err
return v.parseError(err)
}
// spew.Dump(secret)
// entityID := secret.Data["entity_id"].(string)
Expand All @@ -130,7 +141,7 @@ func (v *Vault) getCredentials() (string, string, error) {

if len(username) <= 0 { // If user just clicked enter
if v.config.Username == "" { // If there also isn't default
return "", "", errors.New("No username given")
return "", "", v.newError("No username given")
}
username = v.config.Username
} else {
Expand All @@ -140,7 +151,7 @@ func (v *Vault) getCredentials() (string, string, error) {
fmt.Print("Password: ")
bytePassword, err := terminal.ReadPassword(int(syscall.Stdin))
if err != nil {
return "", "", err
return "", "", v.parseError(err)
}
fmt.Println("")
password := string(bytePassword)
Expand Down
60 changes: 60 additions & 0 deletions pkg/vault/error.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
package vault

import (
"context"
"errors"
"fmt"
"net"
"net/url"
"os"
"strings"
"syscall"
)

// Error is the custom error type for this package
type Error struct {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Feel like this should be named something more specific, to easy to confuse error and Error and mismatch them. I would say something like StimError, or even StimVaultError

MessageParts []string
OriginalError error
}

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Might want to add a String() func to this so if someone outputs it in a log things look correct. https://tour.golang.org/methods/17

// Error returns the error string
func (verr Error) Error() string {
return fmt.Sprintf("Vault Error: %s", strings.Join(verr.MessageParts, "; "))
}

// parseError parses known errors into more user-friendly messages
func (v *Vault) parseError(err error) Error {

var verr Error
verr.OriginalError = err

// Catch some known HTTP errors
if uerr, ok := err.(*url.Error); ok {
if oerr, ok := uerr.Err.(*net.OpError); ok {
if addr, ok := oerr.Addr.(*net.TCPAddr); ok {
if addr.IP.String() == "127.0.0.1" {
verr.MessageParts = append(verr.MessageParts, "Vault appears to be connecting to localhost, ensure correct Vault address is set")
}
}

if serr, ok := oerr.Err.(*os.SyscallError); ok {
if serr.Err == syscall.ECONNREFUSED {
verr.MessageParts = append(verr.MessageParts, "Connection Refused")
}
}
}
}

if err == context.DeadlineExceeded {
verr.MessageParts = append(verr.MessageParts, fmt.Sprintf("Timeout connecting after %v seconds. Ensure connectivity to Vault.", v.config.Timeout))
}

verr.MessageParts = append(verr.MessageParts, fmt.Sprintf("%v", err))

return verr
}

// newError returns a new error based on a given string
func (v *Vault) newError(msg string) Error {
return v.parseError(errors.New(msg))
}
2 changes: 1 addition & 1 deletion pkg/vault/mounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ func (v *Vault) GetMounts(mountType string) ([]string, error) {

mounts, err := v.client.Sys().ListMounts()
if err != nil {
return nil, err
return nil, v.parseError(err)
}

var result []string
Expand Down
15 changes: 7 additions & 8 deletions pkg/vault/secrets.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package vault

import (
"errors"
"path/filepath"
)

Expand All @@ -11,17 +10,17 @@ func (v *Vault) GetSecretKey(path string, key string) (string, error) {

secret, err := v.client.Logical().Read(path)
if err != nil {
return "", err
return "", v.parseError(err)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would assume you want to return Error (or whatever we might change it too) so if someone wants to handle it a different way farther down (say another stimpack calling it) they would not have to see if its castable.

}

// If we got back an empty response, fail
if secret == nil {
return "", errors.New("Could not find secret `" + path + "`")
return "", v.newError("Could not find secret `" + path + "`")
}

// If the provided key doesn't exist, fail
if secret.Data[key] == nil {
return "", errors.New("Vault: Could not find key `" + key + "` for secret `" + path + "`")
return "", v.newError("Vault: Could not find key `" + key + "` for secret `" + path + "`")
}

return secret.Data[key].(string), nil
Expand All @@ -33,12 +32,12 @@ func (v *Vault) GetSecretKeys(path string) (map[string]string, error) {

secret, err := v.client.Logical().Read(path)
if err != nil {
return nil, err
return nil, v.parseError(err)
}

// If we got back an empty response, fail
if secret == nil {
return nil, errors.New("Could not find secret `" + path + "`")
return nil, v.newError("Could not find secret `" + path + "`")
}

// Loop through and get all the keys
Expand All @@ -57,12 +56,12 @@ func (v *Vault) ListSecrets(path string) ([]string, error) {

secret, err := v.client.Logical().List(path)
if err != nil {
return nil, err
return nil, v.parseError(err)
}

// If we got back an empty response, fail
if secret == nil {
return nil, errors.New("Could not find secret `" + path + "`")
return nil, v.newError("Could not find secret `" + path + "`")
}

// Loop through and get all the keys
Expand Down
3 changes: 2 additions & 1 deletion pkg/vault/status.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@ import (
)

func (v *Vault) isVaultHealthy() (bool, error) {

result, err := v.client.Sys().Health()
if err != nil {
return false, err
return false, v.parseError(err)
}

v.Debug("Vault server info from (" + v.client.Address() + ")")
Expand Down
23 changes: 9 additions & 14 deletions pkg/vault/vault.go
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
package vault

import (
"fmt"
"github.com/hashicorp/vault/api"
"github.com/hashicorp/vault/command/token"

"errors"
"fmt"
"time"
)

Expand All @@ -19,7 +17,7 @@ type Config struct {
Noprompt bool
Address string
Username string
Timeout time.Duration
Timeout int
Logger
}

Expand All @@ -43,39 +41,36 @@ func (v *Vault) Info(message string) {
}

func New(config *Config) (*Vault, error) {
// Ensure that the Vault address is set
if config.Address == "" {
return nil, errors.New("Vault address not set")
}

v := &Vault{config: config}

if v.config.Timeout == 0 {
v.config.Timeout = time.Second * 10 // No need to wait over a minite from default
// Ensure that the Vault address is set
if config.Address == "" {
return nil, v.newError("Vault address not set")
}

// Configure new Vault Client
apiConfig := api.DefaultConfig()
apiConfig.Address = v.config.Address // Since we read the env we can override
// apiConfig.HttpClient.Timeout = v.config.Timeout
apiConfig.Timeout = time.Duration(v.config.Timeout) * time.Second

// Create our new API client
var err error
v.client, err = api.NewClient(apiConfig)
if err != nil {
return nil, err
return nil, v.parseError(err)
}

// Ensure Vault is up and Healthy
_, err = v.isVaultHealthy()
if err != nil {
return nil, err
return nil, v.parseError(err)
}

// Run Login logic
err = v.Login()
if err != nil {
return nil, err
return nil, v.parseError(err)
}

return v, nil
Expand Down
3 changes: 3 additions & 0 deletions stim/rootcmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,8 @@ func (stim *Stim) rootCommand(viper *viper.Viper) *cobra.Command {
cmd.PersistentFlags().BoolP("noprompt", "x", false, "Do not prompt for input. Will default to true for Jenkin builds.")
viper.BindPFlag("noprompt", cmd.PersistentFlags().Lookup("noprompt"))

// Set some defaults
viper.SetDefault("vault-timeout", 15)

return cmd
}
9 changes: 2 additions & 7 deletions stim/vault.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@ func (stim *Stim) Vault() *vault.Vault {
Noprompt: stim.GetConfigBool("noprompt") == false && stim.IsAutomated(),
Logger: stim.log,
Username: username,
Timeout: stim.config.Get("vault-timeout").(int),
})
if err != nil {
stim.log.Fatal("Stim-Vault: Error Initializaing: ", err)
stim.log.Fatal(err)
}

// Update the username set in local configs to make any new logins friendly
Expand All @@ -44,9 +45,3 @@ func (stim *Stim) Vault() *vault.Vault {

return stim.vault
}

// func (stim *Stim) Vault() error {
//
//
// return nil
// }