vaultapi

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 11, 2019 License: MIT Imports: 14 Imported by: 0

README

vaultapi

A Go vault client for the rest of us.

Go Report Card Build Status GoDoc License

About

vaultapi is a vault client library for Go programs, targeted at the "99% use case". What this means is that while an official Go client provided by Hashicorp exists and exposes the complete functionality of vault, it is often difficult to use and is extremely inconvenient to work with in test cases. This vault library for Go aims to be easily mockable while providing interfaces that are easy to work with.

Install

Like any Go library, just use go get to install. If the Go team ever officially blesses a package manager, this library will incorporate that.

go get github.com/shoenig/vaultapi

Usage

Creating a vault Client is very simple, just call New with the desired ClientOptions.

tracer := log.New(os.Stdout, "vaultapi-", log.LstdFlags)
options := vaultapi.ClientOptions{
    Servers: []string{"https://localhost:8200"},
    HTTPTimeout: 10 * time.Second, // default
    SkipTLSVerification: false, // default
    Logger: tracer,
}

tokener := vaultapi.NewStaticToken("abcdefgh-abcd-abcd-abcdefgh")
client, err := vaultapi.New(options, tokener)
// client implements the vaultapi.Client interface

leader, err := client.Leader()
// etc ...

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	// ErrNoServers indicates that a Client was created with
	// no URIs of vault servers to communicate with.
	ErrNoServers = errors.New("no servers were provided")

	// ErrInvalidHTTPTimeout indicates that a negative time.Duration
	// was provided as a value for client HTTP timeouts.
	ErrInvalidHTTPTimeout = errors.New("invalid HTTP timeout")

	// ErrPathNotFound indicates the requested path did not exist.
	ErrPathNotFound = errors.New("requested path not found")
)
View Source
var (
	// ErrNoValue indicates that no value exists for a requested path.
	ErrNoValue = errors.New("no value defined for given path")
)

Functions

This section is empty.

Types

type Auth

type Auth interface {
	CreateToken(opts TokenOptions) (CreatedToken, error)
	LookupToken(id string) (LookedUpToken, error)
	LookupSelfToken() (LookedUpToken, error)
	RenewToken(id string, increment time.Duration) (RenewedToken, error)
	RenewSelfToken(increment time.Duration) (RenewedToken, error)
	ListTokenRoles() ([]string, error)
	CreateTokenRole(data TokenRoleOptions) error
	LookupTokenRole(name string) (LookedUpTokenRole, error)
	DeleteTokenRole(name string) error
}

Auth provides a way to manage what may be authenticated to vault.

For now, this API supports only the token authentication mechanism that is built into vault. Support for additional types of authentication may be added in future releases.

More information about managing tokens via the auth backend can be found here: https://www.vaultproject.io/docs/auth/token.html

type Client

type Client interface {
	Auth
	KV
	Sys
}

A Client is used to communicate with vault. The interface is composed of other interfaces, which reflect the different categories of API supported by the vault server.

func New

func New(opts ClientOptions, tokener Tokener) (Client, error)

New creates a new Client that will connect to one or more vault servers as specified by opts.Servers. The tokener is used to aquire the token to be used to authenticate with vault. If opts.Logger is not nil, trace output will be emitted to it which can be helpful for debugging an application using the Client.

type ClientOptions

type ClientOptions struct {
	// Servers should be populated with complete URI including transport
	// and port number of each of the vault servers that are running.
	// An example URI: https://127.0.0.1:8200.
	Servers []string

	// HTTPTimeout configures how long underlying HTTP requests should
	// wait before giving up and returning a timeout error. By default,
	// this value is 10 seconds.
	HTTPTimeout time.Duration

	// SkipTLSVerification configures the underlying HTTP client
	// to ignore any TLS certificate validation errors. This is a
	// hacky option that can be used to work around environments that
	// are using self-signed certificates. For best security practices
	// do not use this option in production environments.
	SkipTLSVerification bool

	// Logger may be optionally configured as an output for trace
	// level logging produced by the Client. This can be helpful
	// for debugging logic errors in client code.
	Logger *log.Logger
}

ClientOptions are used to configure options of a Client upon creation.

type CreatedToken

type CreatedToken struct {
	ID            string            `json:"client_token"`
	Policies      []string          `json:"policies"`
	Metadata      map[string]string `json:"metadata"`
	LeaseDuration int               `json:"lease_duration"`
	Renewable     bool              `json:"renewable"`
}

A CreatedToken represents information returned from vault after creating a token. The ID attribute is the token itself; this is the value used to authenticate with vault later on.

type Health

type Health struct {
	Initialized   bool   `json:"initialized"`
	Sealed        bool   `json:"sealed"`
	Standby       bool   `json:"standby"`
	ServerTimeUTC int    `json:"server_time_utc"`
	Version       string `json:"version"`
	ClusterName   string `json:"cluster_name"`
	ClusterID     string `json:"cluster_id"`
}

A Health is returned upon requesting health status from vault and contains some metadata about the vault configuartion.

type KV

type KV interface {
	// Get will return the value defined at path.
	Get(path string) (string, error)
	// Put will set value at path.
	Put(path, value string) error
	// Delete will remove the value at path.
	Delete(path string) error
	// Keys will list all of the subpaths under path in asciibetical
	// order. The returned paths may be terminal (ie, the value is
	// stored content) or they may traversable like a directory.
	Keys(path string) ([]string, error)
}

A KV represents the key-value store built into vault.

Although vault supports arbitrary bytes as keys and values, this library assumes all keys and values are strings. This helps simplify code for clients, the 99% use case for which is writing secret passwords and other stringy information into vault for safe keeping.

type Leader

type Leader struct {
	HAEnabled     bool   `json:"ha_enabled"`
	IsSelf        bool   `json:"is_self"`
	LeaderAddress string `json:"leader_address"`
}

A Leader is returned upon requesting the leader from vault.

type Lease

type Lease struct {
	ID              string `json:"id"`
	IssueTime       string `json:"issue_time"`
	ExpireTime      string `json:"expire_time"`
	LastRenewalTime string `json:"last_renewal_time"`
	Renewable       bool   `json:"renewable"`
	TTL             int    `json:"ttl"`
}

A Lease is a piece of meta data around something in vault which may be designed to expire at some time. A common example is that every non-root token is associated with a lease which indicates a TTL. Once the lease expires, that token is no longer valid and cannot be used to authenticate with vault.

type LookedUpToken

type LookedUpToken struct {
	ID           string   `json:"id"`
	Accessor     string   `json:"accessor"`
	CreationTime int      `json:"creation_time"`
	CreationTTL  int      `json:"creation_ttl"`
	DisplayName  string   `json:"display_name"`
	MaxTTL       int      `json:"explicit_max_ttl"`
	NumUses      int      `json:"num_uses"`
	Orphan       bool     `json:"orphan"`
	Path         string   `json:"path"`
	Policies     []string `json:"policies"`
	TTL          int      `json:"ttl"`
}

A LookedUpToken represents information returned from vault after making a request for information about a particular token.

type LookedUpTokenRole

type LookedUpTokenRole struct {
	AllowedPolicies    []string `json:"allowed_policies"`
	DisallowedPolicies []string `json:"disallowed_policies"`
	ExplicitMaxTTL     int      `json:"explicit_max_ttl"`
	Name               string   `json:"name"`
	Orphan             bool     `json:"orphan"`
	PathSuffix         string   `json:"path_suffix"`
	Period             int      `json:"period"`
	Renewable          bool     `json:"renewable"`
}

type Mounts

type Mounts map[string]struct {
	Type        string `json:"type"`
	Description string `json:"description"`
	Config      struct {
		DefaultLeaseTTL int  `json:"default_lease_ttl"`
		MaxLeaseTTL     int  `json:"max_lease_ttl"`
		ForceNoCache    bool `json:"force_no_cache"`
	} `json:"config"`
}

Mounts contains information about the mounts currently configured with vault. Generally, users of the vaultapi client library are likely only concerned with the default backends that come with vault, and will not need to be concerned with this API.

More information can be found here: https://www.vaultproject.io/docs/internals/architecture.html

type RenewedToken

type RenewedToken struct {
	ClientToken   string   `json:"client_token"`
	Accessor      string   `json:"accessor"`
	Policies      []string `json:"policies"`
	LeaseDuration int      `json:"lease_duration"`
	Renewable     bool     `json:"renewable"`
}

A RenewedToken represents information returned from vault after making a request to renew a periodic token.

type SealStatus

type SealStatus struct {
	Sealed      bool   `json:"sealed"`
	Threshold   int    `json:"t"`
	Shares      int    `json:"n"`
	Progress    int    `json:"progress"`
	Version     string `json:"version"`
	ClusterName string `json:"cluster_name"`
	ClusterID   string `json:"cluster_id"`
}

A SealStatus is returned upon requesting the sealed status from vault.

More information about the vault seal mechanism can be found here: https://www.vaultproject.io/docs/concepts/seal.html.

type Sys

type Sys interface {
	// Capabilities
	AccessorCapabilities(path, accessor string) ([]string, error)
	TokenCapabilities(path, token string) ([]string, error)
	SelfCapabilities(path string) ([]string, error)

	// Leases
	LookupLease(id string) (Lease, error)

	// Policies
	ListPolicies() ([]string, error)
	GetPolicy(name string) (string, error)
	SetPolicy(name, content string) error
	DeletePolicy(name string) error

	// Vault Status
	Health() (Health, error)
	Leader() (Leader, error)
	StepDown() error
	SealStatus() (SealStatus, error)
	ListMounts() (Mounts, error)
}

A Sys represents the vault system interface.

For more information about the system backend, visit: https://www.vaultproject.io/api/system/index.html.

type TokenOptions

type TokenOptions struct {
	Policies        []string      `json:"policies,omitempty"`
	NoDefaultPolicy bool          `json:"no_default_policy,omitempty"`
	Orphan          bool          `json:"no_parent,omitempty"`
	Renewable       bool          `json:"renewable,omitempty"`
	DisplayName     string        `json:"display_name,omitempty"`
	MaxUses         int           `json:"num_uses,omitempty"`
	TTL             time.Duration `json:"ttl,omitempty"`
	MaxTTL          time.Duration `json:"explicit_max_ttl,omitempty"`
	Period          time.Duration `json:"period,omitmempty"`
}

TokenOptions are used to define properties of a token being created. More information about the different options can be found in the token documentation at: https://www.vaultproject.io/docs/concepts/tokens.html

type TokenRoleOptions

type TokenRoleOptions struct {
	Name               string   `json:"role_name"`
	AllowedPolicies    string   `json:"allowed_policies"`
	DisallowedPolicies string   `json:"disallowed_policies"`
	Orphan             bool     `json:"orphan"`
	Period             string   `json:"period"`
	Renewable          bool     `json:"renewable"`
	ExplicitMaxTTL     int      `json:"explicit_max_ttl"`
	PathSuffix         string   `json:"path_suffix"`
	BoundCIDRs         []string `json:"bound_cidrs"`
}

type Tokener

type Tokener interface {
	Token() (string, error)
}

A Tokener provides a token that can be used to authenticate with vault.

func NewFileToken

func NewFileToken(filename string) Tokener

NewFileToken will create a Tokener that will always reload the token value from the specified file.

func NewStaticToken

func NewStaticToken(token string) Tokener

NewStaticToken creates a Tokener that will only ever return the one provided value for token.

Directories

Path Synopsis
Package vaultapitest contains autogenerated mocks.
Package vaultapitest contains autogenerated mocks.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL